2 # Script to analyze code and arrange ld sections.
4 # Copyright (C) 2008 Kevin O'Connor <kevin@koconnor.net>
6 # This file may be distributed under the terms of the GNU GPLv3 license.
10 # Align 'pos' to 'alignbytes' offset
11 def alignpos(pos, alignbytes):
13 return (pos + mask) & ~mask
15 # LD script headers/trailers
17 /* DO NOT EDIT! This is an autogenerated file. See tools/layoutrom.py. */
18 OUTPUT_FORMAT("elf32-i386")
28 ######################################################################
29 # 16bit fixed address section fitting
30 ######################################################################
32 # Get the maximum start position for a list of sections that end at an
34 def getSectionsStart(sections, endaddr, minalign=1):
36 for size, align, name in sections:
39 totspace = alignpos(totspace, align) + size
40 return (endaddr - totspace) / minalign * minalign
42 # Write LD script includes for the given sections
43 def outSections(file, sections):
44 for size, align, name in sections:
45 file.write("*(%s)\n" % (name,))
47 # The 16bit code can't exceed 64K of space.
50 # Layout the 16bit code. This ensures sections with fixed offset
51 # requirements are placed in the correct location. It also places the
52 # 16bit code as high as possible in the f-segment.
53 def doLayout16(sections, outname):
57 # fixedsections = [(addr, sectioninfo, extasectionslist), ...]
59 # canrelocate = [(sectioninfo, list), ...]
62 # Find desired sections.
63 for section in sections:
64 size, align, name = section
65 if name[:11] == '.fixedaddr.':
66 addr = int(name[11:], 16)
67 fixedsections.append((addr, section, []))
69 print "Error: Fixed section %s has non-zero alignment (%d)" % (
72 if name[:6] == '.text.':
73 textsections.append(section)
74 canrelocate.append((section, textsections))
75 if name[:17] == '.rodata.__func__.' or name == '.rodata.str1.1':
76 rodatasections.append(section)
77 #canrelocate.append((section, rodatasections))
78 if name[:8] == '.data16.':
79 datasections.append(section)
80 #canrelocate.append((section, datasections))
82 # Find freespace in fixed address area
84 # fixedAddr = [(freespace, sectioninfo), ...]
86 for i in range(len(fixedsections)):
87 fixedsectioninfo = fixedsections[i]
88 addr, section, extrasectionslist = fixedsectioninfo
89 if i == len(fixedsections) - 1:
92 nextaddr = fixedsections[i+1][0]
93 avail = nextaddr - addr - section[0]
94 fixedAddr.append((avail, fixedsectioninfo))
96 # Attempt to fit other sections into fixed area
100 for freespace, fixedsectioninfo in fixedAddr:
101 fixedaddr, fixedsection, extrasections = fixedsectioninfo
102 addpos = fixedaddr + fixedsection[0]
103 totalused += fixedsection[0]
104 nextfixedaddr = addpos + freespace
105 # print "Filling section %x uses %d, next=%x, available=%d" % (
106 # fixedaddr, fixedsection[0], nextfixedaddr, freespace)
109 for fixedaddrinfo in canrelocate:
110 fitsection, inlist = fixedaddrinfo
111 fitsize, fitalign, fitname = fitsection
112 if addpos + fitsize > nextfixedaddr:
113 # Can't fit and nothing else will fit.
115 fitnextaddr = alignpos(addpos, fitalign) + fitsize
116 # print "Test %s - %x vs %x" % (
117 # fitname, fitnextaddr, nextfixedaddr)
118 if fitnextaddr > nextfixedaddr:
119 # This item can't fit.
121 canfit = (fitnextaddr, fixedaddrinfo)
124 # Found a section that can fit.
125 fitnextaddr, fixedaddrinfo = canfit
126 canrelocate.remove(fixedaddrinfo)
127 fitsection, inlist = fixedaddrinfo
128 inlist.remove(fitsection)
129 extrasections.append(fitsection)
131 totalused += fitsection[0]
132 # print " Adding %s (size %d align %d) pos=%x avail=%d" % (
133 # fitsection[2], fitsection[0], fitsection[1]
134 # , fitnextaddr, nextfixedaddr - fitnextaddr)
135 firstfixed = fixedsections[0][0]
138 total = MAXPOS-firstfixed
139 slack = total - totalused
140 print ("Fixed space: 0x%x-0x%x total: %d slack: %d"
141 " Percent slack: %.1f%%" % (
142 firstfixed, MAXPOS, total, slack,
143 (float(slack) / total) * 100.0))
145 # Find start positions
146 text16_start = getSectionsStart(textsections, firstfixed)
147 data16_start = getSectionsStart(rodatasections + datasections, text16_start)
149 # Write header and regular sections
150 output = open(outname, 'wb')
151 output.write(COMMONHEADER + """
152 data16_start = 0x%x ;
153 .data16 data16_start : {
155 outSections(output, datasections)
156 output.write("code16_rodata = . ;\n")
157 outSections(output, rodatasections)
161 text16_start = 0x%x ;
162 .text16 text16_start : {
164 outSections(output, textsections)
166 # Write fixed sections
167 for addr, section, extrasections in fixedsections:
169 output.write(". = ( 0x%x - text16_start ) ;\n" % (addr,))
170 output.write("*(%s)\n" % (name,))
171 for extrasection in extrasections:
172 output.write("*(%s)\n" % (extrasection[2],))
176 text16_end = ABSOLUTE(.) ;
179 /* Discard regular data sections to force a link error if
180 * 16bit code attempts to access data not marked with VAR16
182 /DISCARD/ : { *(.text*) *(.rodata*) *(.data*) *(.bss*) *(COMMON) }
188 ######################################################################
189 # 32bit section outputting
190 ######################################################################
192 # Return the subset of sections with a given name prefix
193 def getSectionsPrefix(sections, prefix):
196 for size, align, name in sections:
197 if name[:lp] == prefix:
198 out.append((size, align, name))
201 # Layout the 32bit segmented code. This places the code as high as possible.
202 def doLayout32seg(sections, outname, endat):
203 # Find sections to output
204 textsections = getSectionsPrefix(sections, '.text.')
205 rodatasections = (getSectionsPrefix(sections, '.rodata.str1.1')
206 + getSectionsPrefix(sections, '.rodata.__func__.'))
207 datasections = getSectionsPrefix(sections, '.data32seg.')
208 startat = getSectionsStart(
209 textsections + rodatasections + datasections, endat)
212 output = open(outname, 'wb')
213 output.write(COMMONHEADER + """
214 code32seg_start = 0x%x ;
215 .text32seg code32seg_start : {
219 outSections(output, textsections)
220 output.write("code32seg_rodata = . ;\n")
221 outSections(output, rodatasections)
222 outSections(output, datasections)
225 code32seg_end = ABSOLUTE(.) ;
227 /DISCARD/ : { *(.text*) *(.rodata*) *(.data*) *(.bss*) *(COMMON) }
231 # Layout the 32bit flat code. This places the code as high as possible.
232 def doLayout32flat(sections, outname, endat):
234 # Find sections to output
235 textsections = getSectionsPrefix(sections, '.text.')
236 rodatasections = getSectionsPrefix(sections, '.rodata')
237 datasections = getSectionsPrefix(sections, '.data.')
238 bsssections = getSectionsPrefix(sections, '.bss.')
239 startat = getSectionsStart(
240 textsections + rodatasections + datasections + bsssections, endat, 512)
243 output = open(outname, 'wb')
244 output.write(COMMONHEADER + """
245 code32flat_start = 0x%x ;
246 .text32flat code32flat_start : {
249 outSections(output, textsections)
250 output.write("code32_rodata = . ;\n")
251 outSections(output, rodatasections)
252 outSections(output, datasections)
253 outSections(output, bsssections)
256 freespace_start = . ;
257 code32flat_end = ABSOLUTE(.) ;
263 ######################################################################
264 # Section garbage collection
265 ######################################################################
267 def getSectionsList(info, names):
270 size, align, section = i
271 if section not in names:
272 # print "gc", section
277 # Note required section, and recursively set all referenced sections
279 def keepsection(name, infos, pos=0):
280 if name in infos[pos][3]:
281 # Already kept - nothing to do.
283 infos[pos][3].append(name)
284 relocs = infos[pos][2].get(name)
287 # Keep all sections that this section points to
288 for symbol in relocs:
289 addr, section = infos[pos][1].get(symbol, (None, None))
290 if (section is not None and '*' not in section
291 and section[:9] != '.discard.'):
292 keepsection(section, infos, pos)
294 # Not in primary sections - it may be a cross 16/32 reference
296 addr, section = infos[newpos][1].get(symbol, (None, None))
297 if section is not None and '*' not in section:
298 keepsection(section, infos, newpos)
301 addr, section = infos[(pos+2)%3][1].get(symbol, (None, None))
302 if section is not None and '*' not in section:
303 keepsection(section, infos, newpos)
305 # Determine which sections are actually referenced and need to be
306 # placed into the output file.
307 def gc(info16, info32seg, info32flat):
308 # infos = ((sections, symbols, relocs, keep sections), ...)
309 infos = ((info16[0], info16[1], info16[2], []),
310 (info32seg[0], info32seg[1], info32seg[2], []),
311 (info32flat[0], info32flat[1], info32flat[2], []))
312 # Start by keeping sections that are globally visible.
313 for size, align, section in info16[0]:
314 if section[:11] == '.fixedaddr.' or '.export.' in section:
315 keepsection(section, infos)
316 # Return sections found.
317 sections16 = getSectionsList(info16, infos[0][3])
318 sections32seg = getSectionsList(info32seg, infos[1][3])
319 sections32flat = getSectionsList(info32flat, infos[2][3])
320 return sections16, sections32seg, sections32flat
323 ######################################################################
324 # Startup and input parsing
325 ######################################################################
327 # Read in output from objdump
328 def parseObjDump(file):
329 # sections = [(size, align, section), ...]
331 # symbols[symbol] = section
333 # relocs[section] = [symbol, ...]
337 for line in file.readlines():
339 if line == 'Sections:':
342 if line == 'SYMBOL TABLE:':
345 if line[:24] == 'RELOCATION RECORDS FOR [':
347 relocsection = line[24:-2]
350 if state == 'section':
352 idx, name, size, vma, lma, fileoff, align = line.split()
353 if align[:3] != '2**':
355 sections.append((int(size, 16), 2**int(align[3:]), name))
359 if state == 'symbol':
361 section, off, symbol = line[17:].split()
363 addr = int(line[:8], 16)
364 symbols[symbol] = addr, section
370 off, type, symbol = line.split()
372 relocs.setdefault(relocsection, []).append(symbol)
375 return sections, symbols, relocs
379 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
381 infile16 = open(in16, 'rb')
382 infile32seg = open(in32seg, 'rb')
383 infile32flat = open(in32flat, 'rb')
385 info16 = parseObjDump(infile16)
386 info32seg = parseObjDump(infile32seg)
387 info32flat = parseObjDump(infile32flat)
389 sections16, sections32seg, sections32flat = gc(info16, info32seg, info32flat)
391 start16 = doLayout16(sections16, out16)
392 start32seg = doLayout32seg(sections32seg, out32seg, start16)
393 doLayout32flat(sections32flat, out32flat, start32seg)
395 if __name__ == '__main__':