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 # LD script headers/trailers
12 /* DO NOT EDIT! This is an autogenerated file. See tools/layoutrom.py. */
13 OUTPUT_FORMAT("elf32-i386")
20 /* Discard regular data sections to force a link error if
21 * code attempts to access data not marked with VAR16 (or other
25 *(.text*) *(.data*) *(.bss*) *(.rodata*)
26 *(COMMON) *(.discard*) *(.eh_frame)
32 ######################################################################
33 # Determine section locations
34 ######################################################################
36 # Align 'pos' to 'alignbytes' offset
37 def alignpos(pos, alignbytes):
39 return (pos + mask) & ~mask
41 # Determine the final addresses for a list of sections that end at an
43 def getSectionsStart(sections, endaddr, minalign=1):
45 for size, align, name in sections:
48 totspace = alignpos(totspace, align) + size
49 startaddr = (endaddr - totspace) / minalign * minalign
51 # out = [(addr, sectioninfo), ...]
53 for sectioninfo in sections:
54 size, align, name = sectioninfo
55 curaddr = alignpos(curaddr, align)
56 out.append((curaddr, sectioninfo))
60 # Return the subset of sections with a given name prefix
61 def getSectionsPrefix(sections, prefix):
63 for size, align, name in sections:
64 if name.startswith(prefix):
65 out.append((size, align, name))
68 # The 16bit code can't exceed 64K of space.
69 BUILD_BIOS_ADDR = 0xf0000
70 BUILD_BIOS_SIZE = 0x10000
72 # Layout the 16bit code. This ensures sections with fixed offset
73 # requirements are placed in the correct location. It also places the
74 # 16bit code as high as possible in the f-segment.
75 def fitSections(sections, fillsections):
76 canrelocate = list(fillsections)
77 # fixedsections = [(addr, sectioninfo), ...]
79 for sectioninfo in sections:
80 size, align, name = sectioninfo
81 if name.startswith('.fixedaddr.'):
82 addr = int(name[11:], 16)
83 fixedsections.append((addr, sectioninfo))
85 print "Error: Fixed section %s has non-zero alignment (%d)" % (
89 # Find freespace in fixed address area
91 # fixedAddr = [(freespace, sectioninfo), ...]
93 for i in range(len(fixedsections)):
94 fixedsectioninfo = fixedsections[i]
95 addr, section = fixedsectioninfo
96 if i == len(fixedsections) - 1:
97 nextaddr = BUILD_BIOS_SIZE
99 nextaddr = fixedsections[i+1][0]
100 avail = nextaddr - addr - section[0]
101 fixedAddr.append((avail, fixedsectioninfo))
103 # Attempt to fit other sections into fixed area
108 for freespace, fixedsectioninfo in fixedAddr:
109 fixedaddr, fixedsection = fixedsectioninfo
110 addpos = fixedaddr + fixedsection[0]
111 totalused += fixedsection[0]
112 nextfixedaddr = addpos + freespace
113 # print "Filling section %x uses %d, next=%x, available=%d" % (
114 # fixedaddr, fixedsection[0], nextfixedaddr, freespace)
117 for fitsection in canrelocate:
118 fitsize, fitalign, fitname = fitsection
119 if addpos + fitsize > nextfixedaddr:
120 # Can't fit and nothing else will fit.
122 fitnextaddr = alignpos(addpos, fitalign) + fitsize
123 # print "Test %s - %x vs %x" % (
124 # fitname, fitnextaddr, nextfixedaddr)
125 if fitnextaddr > nextfixedaddr:
126 # This item can't fit.
128 canfit = (fitnextaddr, fitsection)
131 # Found a section that can fit.
132 fitnextaddr, fitsection = canfit
133 canrelocate.remove(fitsection)
134 extrasections.append((addpos, fitsection))
136 totalused += fitsection[0]
137 # print " Adding %s (size %d align %d) pos=%x avail=%d" % (
138 # fitsection[2], fitsection[0], fitsection[1]
139 # , fitnextaddr, nextfixedaddr - fitnextaddr)
140 firstfixed = fixedsections[0][0]
143 total = BUILD_BIOS_SIZE-firstfixed
144 slack = total - totalused
145 print ("Fixed space: 0x%x-0x%x total: %d slack: %d"
146 " Percent slack: %.1f%%" % (
147 firstfixed, BUILD_BIOS_SIZE, total, slack,
148 (float(slack) / total) * 100.0))
150 return fixedsections + extrasections, firstfixed
152 def doLayout(sections16, sections32seg, sections32flat):
153 # Determine 16bit positions
154 textsections = getSectionsPrefix(sections16, '.text.')
155 rodatasections = (getSectionsPrefix(sections16, '.rodata.str1.1')
156 + getSectionsPrefix(sections16, '.rodata.__func__.'))
157 datasections = getSectionsPrefix(sections16, '.data16.')
158 fixedsections = getSectionsPrefix(sections16, '.fixedaddr.')
160 locs16fixed, firstfixed = fitSections(fixedsections, textsections)
161 prunesections = [i[1] for i in locs16fixed]
162 remsections = [i for i in textsections+rodatasections+datasections
163 if i not in prunesections]
164 locs16, code16_start = getSectionsStart(remsections, firstfixed)
165 locs16 = locs16 + locs16fixed
168 # Determine 32seg positions
169 textsections = getSectionsPrefix(sections32seg, '.text.')
170 rodatasections = (getSectionsPrefix(sections32seg, '.rodata.str1.1')
171 + getSectionsPrefix(sections32seg, '.rodata.__func__.'))
172 datasections = getSectionsPrefix(sections32seg, '.data32seg.')
174 locs32seg, code32seg_start = getSectionsStart(
175 textsections + rodatasections + datasections, code16_start)
177 # Determine 32flat positions
178 textsections = getSectionsPrefix(sections32flat, '.text.')
179 rodatasections = getSectionsPrefix(sections32flat, '.rodata')
180 datasections = getSectionsPrefix(sections32flat, '.data.')
181 bsssections = getSectionsPrefix(sections32flat, '.bss.')
183 locs32flat, code32flat_start = getSectionsStart(
184 textsections + rodatasections + datasections + bsssections
185 , code32seg_start + BUILD_BIOS_ADDR, 16)
188 size16 = BUILD_BIOS_SIZE - code16_start
189 size32seg = code16_start - code32seg_start
190 size32flat = code32seg_start + BUILD_BIOS_ADDR - code32flat_start
191 print "16bit size: %d" % size16
192 print "32bit segmented size: %d" % size32seg
193 print "32bit flat size: %d" % size32flat
195 return locs16, locs32seg, locs32flat
198 ######################################################################
199 # Linker script output
200 ######################################################################
202 # Write LD script includes for the given cross references
203 def outXRefs(xrefs, finallocs, delta=0):
205 for symbol, (fileid, section, addr) in xrefs.items():
208 out += "%s = 0x%x ;\n" % (symbol, finallocs[(fileid, section)] + addr)
211 # Write LD script includes for the given sections using relative offsets
212 def outRelSections(locs, startsym):
214 for addr, sectioninfo in locs:
215 size, align, name = sectioninfo
216 out += ". = ( 0x%x - %s ) ;\n" % (addr, startsym)
217 if name == '.rodata.str1.1':
218 out += "_rodata = . ;\n"
219 out += "*(%s)\n" % (name,)
222 # Layout the 32bit segmented code. This places the code as high as possible.
223 def writeLinkerScripts(locs16, locs32seg, locs32flat
224 , xref16, xref32seg, xref32flat
225 , out16, out32seg, out32flat):
226 # Index to final location for each section
227 # finallocs[(fileid, section)] = addr
229 for fileid, locs in ((0, locs16), (1, locs32seg), (2, locs32flat)):
230 for addr, sectioninfo in locs:
231 finallocs[(fileid, sectioninfo[2])] = addr
233 # Write 16bit linker script
234 code16_start = locs16[0][0]
235 output = open(out16, 'wb')
236 output.write(COMMONHEADER + outXRefs(xref16, finallocs) + """
237 code16_start = 0x%x ;
238 .text16 code16_start : {
240 + outRelSections(locs16, 'code16_start')
247 # Write 32seg linker script
248 code32seg_start = code16_start
250 code32seg_start = locs32seg[0][0]
251 output = open(out32seg, 'wb')
252 output.write(COMMONHEADER + outXRefs(xref32seg, finallocs) + """
253 code32seg_start = 0x%x ;
254 .text32seg code32seg_start : {
255 """ % (code32seg_start)
256 + outRelSections(locs32seg, 'code32seg_start')
263 # Write 32flat linker script
264 output = open(out32flat, 'wb')
265 output.write(COMMONHEADER
266 + outXRefs(xref32flat, finallocs, BUILD_BIOS_ADDR) + """
267 code32flat_start = 0x%x ;
268 .text code32flat_start : {
269 """ % (locs32flat[0][0])
270 + outRelSections(locs32flat, 'code32flat_start')
272 . = ( 0x%x - code32flat_start ) ;
274 . = ( 0x%x - code32flat_start ) ;
276 code32flat_end = ABSOLUTE(.) ;
278 """ % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
284 text PT_LOAD AT ( code32flat_start ) ;
290 ######################################################################
291 # Section garbage collection
292 ######################################################################
294 # Find and keep the section associated with a symbol (if available).
295 def keepsymbol(symbol, infos, pos, callerpos=None):
296 addr, section = infos[pos][1].get(symbol, (None, None))
297 if section is None or '*' in section or section.startswith('.discard.'):
299 if callerpos is not None and symbol not in infos[callerpos][4]:
300 # This symbol reference is a cross section reference (an xref).
301 # xref[symbol] = (fileid, section, addr)
302 infos[callerpos][4][symbol] = (pos, section, addr)
303 keepsection(section, infos, pos)
306 # Note required section, and recursively set all referenced sections
308 def keepsection(name, infos, pos=0):
309 if name in infos[pos][3]:
310 # Already kept - nothing to do.
312 infos[pos][3].append(name)
313 relocs = infos[pos][2].get(name)
316 # Keep all sections that this section points to
317 for symbol in relocs:
318 ret = keepsymbol(symbol, infos, pos)
321 # Not in primary sections - it may be a cross 16/32 reference
322 ret = keepsymbol(symbol, infos, (pos+1)%3, pos)
325 ret = keepsymbol(symbol, infos, (pos+2)%3, pos)
329 # Return a list of kept sections.
330 def getSectionsList(sections, names):
331 return [i for i in sections if i[2] in names]
333 # Determine which sections are actually referenced and need to be
334 # placed into the output file.
335 def gc(info16, info32seg, info32flat):
336 # infos = ((sections, symbols, relocs, keep sections, xrefs), ...)
337 infos = ((info16[0], info16[1], info16[2], [], {}),
338 (info32seg[0], info32seg[1], info32seg[2], [], {}),
339 (info32flat[0], info32flat[1], info32flat[2], [], {}))
340 # Start by keeping sections that are globally visible.
341 for size, align, section in info16[0]:
342 if section.startswith('.fixedaddr.') or '.export.' in section:
343 keepsection(section, infos)
344 keepsymbol('post32', infos, 0, 2)
345 # Return sections found.
346 keep16 = getSectionsList(info16[0], infos[0][3]), infos[0][4]
347 keep32seg = getSectionsList(info32seg[0], infos[1][3]), infos[1][4]
348 keep32flat = getSectionsList(info32flat[0], infos[2][3]), infos[2][4]
349 return keep16, keep32seg, keep32flat
352 ######################################################################
353 # Startup and input parsing
354 ######################################################################
356 # Read in output from objdump
357 def parseObjDump(file):
358 # sections = [(size, align, section), ...]
360 # symbols[symbol] = (addr, section)
362 # relocs[section] = [symbol, ...]
366 for line in file.readlines():
368 if line == 'Sections:':
371 if line == 'SYMBOL TABLE:':
374 if line.startswith('RELOCATION RECORDS FOR ['):
376 relocsection = line[24:-2]
379 if state == 'section':
381 idx, name, size, vma, lma, fileoff, align = line.split()
382 if align[:3] != '2**':
384 sections.append((int(size, 16), 2**int(align[3:]), name))
388 if state == 'symbol':
390 section, size, symbol = line[17:].split()
392 addr = int(line[:8], 16)
393 symbols[symbol] = addr, section
399 off, type, symbol = line.split()
401 relocs.setdefault(relocsection, []).append(symbol)
404 return sections, symbols, relocs
408 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
410 # Read in the objdump information
411 infile16 = open(in16, 'rb')
412 infile32seg = open(in32seg, 'rb')
413 infile32flat = open(in32flat, 'rb')
415 # infoX = (sections, symbols, relocs)
416 info16 = parseObjDump(infile16)
417 info32seg = parseObjDump(infile32seg)
418 info32flat = parseObjDump(infile32flat)
420 # Figure out which sections to keep.
421 # keepX = (sections, xrefs)
422 keep16, keep32seg, keep32flat = gc(info16, info32seg, info32flat)
424 # Determine the final memory locations of each kept section.
425 # locsX = [(addr, sectioninfo), ...]
426 locs16, locs32seg, locs32flat = doLayout(
427 keep16[0], keep32seg[0], keep32flat[0])
429 # Write out linker script files.
430 writeLinkerScripts(locs16, locs32seg, locs32flat
431 , keep16[1], keep32seg[1], keep32flat[1]
432 , out16, out32seg, out32flat)
434 if __name__ == '__main__':