Use str.startswith() in python scripts.
[seabios.git] / tools / layoutrom.py
1 #!/usr/bin/env python
2 # Script to analyze code and arrange ld sections.
3 #
4 # Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
5 #
6 # This file may be distributed under the terms of the GNU GPLv3 license.
7
8 import sys
9
10 # LD script headers/trailers
11 COMMONHEADER = """
12 /* DO NOT EDIT!  This is an autogenerated file.  See tools/layoutrom.py. */
13 OUTPUT_FORMAT("elf32-i386")
14 OUTPUT_ARCH("i386")
15 SECTIONS
16 {
17 """
18 COMMONTRAILER = """
19
20         /* Discard regular data sections to force a link error if
21          * code attempts to access data not marked with VAR16 (or other
22          * appropriate macro)
23          */
24         /DISCARD/ : {
25                 *(.text*) *(.data*) *(.bss*) *(.rodata*)
26                 *(COMMON) *(.discard*) *(.eh_frame)
27                 }
28 }
29 """
30
31
32 ######################################################################
33 # Determine section locations
34 ######################################################################
35
36 # Align 'pos' to 'alignbytes' offset
37 def alignpos(pos, alignbytes):
38     mask = alignbytes - 1
39     return (pos + mask) & ~mask
40
41 # Determine the final addresses for a list of sections that end at an
42 # address.
43 def getSectionsStart(sections, endaddr, minalign=1):
44     totspace = 0
45     for size, align, name in sections:
46         if align > minalign:
47             minalign = align
48         totspace = alignpos(totspace, align) + size
49     startaddr = (endaddr - totspace) / minalign * minalign
50     curaddr = startaddr
51     # out = [(addr, sectioninfo), ...]
52     out = []
53     for sectioninfo in sections:
54         size, align, name = sectioninfo
55         curaddr = alignpos(curaddr, align)
56         out.append((curaddr, sectioninfo))
57         curaddr += size
58     return out, startaddr
59
60 # Return the subset of sections with a given name prefix
61 def getSectionsPrefix(sections, prefix):
62     out = []
63     for size, align, name in sections:
64         if name.startswith(prefix):
65             out.append((size, align, name))
66     return out
67
68 # The 16bit code can't exceed 64K of space.
69 BUILD_BIOS_ADDR = 0xf0000
70 BUILD_BIOS_SIZE = 0x10000
71
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), ...]
78     fixedsections = []
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))
84             if align != 1:
85                 print "Error: Fixed section %s has non-zero alignment (%d)" % (
86                     name, align)
87                 sys.exit(1)
88
89     # Find freespace in fixed address area
90     fixedsections.sort()
91     # fixedAddr = [(freespace, sectioninfo), ...]
92     fixedAddr = []
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
98         else:
99             nextaddr = fixedsections[i+1][0]
100         avail = nextaddr - addr - section[0]
101         fixedAddr.append((avail, fixedsectioninfo))
102
103     # Attempt to fit other sections into fixed area
104     extrasections = []
105     fixedAddr.sort()
106     canrelocate.sort()
107     totalused = 0
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)
115         while 1:
116             canfit = None
117             for fitsection in canrelocate:
118                 fitsize, fitalign, fitname = fitsection
119                 if addpos + fitsize > nextfixedaddr:
120                     # Can't fit and nothing else will fit.
121                     break
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.
127                     continue
128                 canfit = (fitnextaddr, fitsection)
129             if canfit is None:
130                 break
131             # Found a section that can fit.
132             fitnextaddr, fitsection = canfit
133             canrelocate.remove(fitsection)
134             extrasections.append((addpos, fitsection))
135             addpos = fitnextaddr
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]
141
142     # Report stats
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))
149
150     return fixedsections + extrasections, firstfixed
151
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.')
159
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
166     locs16.sort()
167
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.')
173
174     locs32seg, code32seg_start = getSectionsStart(
175         textsections + rodatasections + datasections, code16_start)
176
177     # Determine 32flat positions
178     textsections = getSectionsPrefix(sections32flat, '.text.')
179     rodatasections = getSectionsPrefix(sections32flat, '.rodata')
180     datasections = getSectionsPrefix(sections32flat, '.data.')
181     bsssections = getSectionsPrefix(sections32flat, '.bss.')
182
183     locs32flat, code32flat_start = getSectionsStart(
184         textsections + rodatasections + datasections + bsssections
185         , code32seg_start + BUILD_BIOS_ADDR, 16)
186
187     # Print statistics
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
194
195     return locs16, locs32seg, locs32flat
196
197
198 ######################################################################
199 # Linker script output
200 ######################################################################
201
202 # Write LD script includes for the given cross references
203 def outXRefs(xrefs, finallocs, delta=0):
204     out = ""
205     for symbol, (fileid, section, addr) in xrefs.items():
206         if fileid < 2:
207             addr += delta
208         out += "%s = 0x%x ;\n" % (symbol, finallocs[(fileid, section)] + addr)
209     return out
210
211 # Write LD script includes for the given sections using relative offsets
212 def outRelSections(locs, startsym):
213     out = ""
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,)
220     return out
221
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
228     finallocs = {}
229     for fileid, locs in ((0, locs16), (1, locs32seg), (2, locs32flat)):
230         for addr, sectioninfo in locs:
231             finallocs[(fileid, sectioninfo[2])] = addr
232
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 : {
239 """ % (code16_start)
240                  + outRelSections(locs16, 'code16_start')
241                  + """
242     }
243 """
244                  + COMMONTRAILER)
245     output.close()
246
247     # Write 32seg linker script
248     code32seg_start = code16_start
249     if locs32seg:
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')
257                  + """
258     }
259 """
260                  + COMMONTRAILER)
261     output.close()
262
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')
271                  + """
272         . = ( 0x%x - code32flat_start ) ;
273         *(.text32seg)
274         . = ( 0x%x - code32flat_start ) ;
275         *(.text16)
276         code32flat_end = ABSOLUTE(.) ;
277     } :text
278 """ % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
279                  + COMMONTRAILER
280                  + """
281 ENTRY(post32)
282 PHDRS
283 {
284         text PT_LOAD AT ( code32flat_start ) ;
285 }
286 """)
287     output.close()
288
289
290 ######################################################################
291 # Section garbage collection
292 ######################################################################
293
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.'):
298         return -1
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)
304     return 0
305
306 # Note required section, and recursively set all referenced sections
307 # as required.
308 def keepsection(name, infos, pos=0):
309     if name in infos[pos][3]:
310         # Already kept - nothing to do.
311         return
312     infos[pos][3].append(name)
313     relocs = infos[pos][2].get(name)
314     if relocs is None:
315         return
316     # Keep all sections that this section points to
317     for symbol in relocs:
318         ret = keepsymbol(symbol, infos, pos)
319         if not ret:
320             continue
321         # Not in primary sections - it may be a cross 16/32 reference
322         ret = keepsymbol(symbol, infos, (pos+1)%3, pos)
323         if not ret:
324             continue
325         ret = keepsymbol(symbol, infos, (pos+2)%3, pos)
326         if not ret:
327             continue
328
329 # Return a list of kept sections.
330 def getSectionsList(sections, names):
331     return [i for i in sections if i[2] in names]
332
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
350
351
352 ######################################################################
353 # Startup and input parsing
354 ######################################################################
355
356 # Read in output from objdump
357 def parseObjDump(file):
358     # sections = [(size, align, section), ...]
359     sections = []
360     # symbols[symbol] = (addr, section)
361     symbols = {}
362     # relocs[section] = [symbol, ...]
363     relocs = {}
364
365     state = None
366     for line in file.readlines():
367         line = line.rstrip()
368         if line == 'Sections:':
369             state = 'section'
370             continue
371         if line == 'SYMBOL TABLE:':
372             state = 'symbol'
373             continue
374         if line.startswith('RELOCATION RECORDS FOR ['):
375             state = 'reloc'
376             relocsection = line[24:-2]
377             continue
378
379         if state == 'section':
380             try:
381                 idx, name, size, vma, lma, fileoff, align = line.split()
382                 if align[:3] != '2**':
383                     continue
384                 sections.append((int(size, 16), 2**int(align[3:]), name))
385             except:
386                 pass
387             continue
388         if state == 'symbol':
389             try:
390                 section, size, symbol = line[17:].split()
391                 size = int(size, 16)
392                 addr = int(line[:8], 16)
393                 symbols[symbol] = addr, section
394             except:
395                 pass
396             continue
397         if state == 'reloc':
398             try:
399                 off, type, symbol = line.split()
400                 off = int(off, 16)
401                 relocs.setdefault(relocsection, []).append(symbol)
402             except:
403                 pass
404     return sections, symbols, relocs
405
406 def main():
407     # Get output name
408     in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
409
410     # Read in the objdump information
411     infile16 = open(in16, 'rb')
412     infile32seg = open(in32seg, 'rb')
413     infile32flat = open(in32flat, 'rb')
414
415     # infoX = (sections, symbols, relocs)
416     info16 = parseObjDump(infile16)
417     info32seg = parseObjDump(infile32seg)
418     info32flat = parseObjDump(infile32flat)
419
420     # Figure out which sections to keep.
421     # keepX = (sections, xrefs)
422     keep16, keep32seg, keep32flat = gc(info16, info32seg, info32flat)
423
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])
428
429     # Write out linker script files.
430     writeLinkerScripts(locs16, locs32seg, locs32flat
431                        , keep16[1], keep32seg[1], keep32flat[1]
432                        , out16, out32seg, out32flat)
433
434 if __name__ == '__main__':
435     main()