Separate out init code from the rest of the 32bit flat code.
[seabios.git] / tools / layoutrom.py
1 #!/usr/bin/env python
2 # Script to analyze code and arrange ld sections.
3 #
4 # Copyright (C) 2008-2010  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 setSectionsStart(sections, endaddr, minalign=1):
44     totspace = 0
45     for section in sections:
46         if section.align > minalign:
47             minalign = section.align
48         totspace = alignpos(totspace, section.align) + section.size
49     startaddr = (endaddr - totspace) / minalign * minalign
50     curaddr = startaddr
51     # out = [(addr, sectioninfo), ...]
52     out = []
53     for section in sections:
54         curaddr = alignpos(curaddr, section.align)
55         section.finalloc = curaddr
56         curaddr += section.size
57     return startaddr
58
59 # The 16bit code can't exceed 64K of space.
60 BUILD_BIOS_ADDR = 0xf0000
61 BUILD_BIOS_SIZE = 0x10000
62
63 # Layout the 16bit code.  This ensures sections with fixed offset
64 # requirements are placed in the correct location.  It also places the
65 # 16bit code as high as possible in the f-segment.
66 def fitSections(sections, fillsections):
67     # fixedsections = [(addr, section), ...]
68     fixedsections = []
69     for section in sections:
70         if section.name.startswith('.fixedaddr.'):
71             addr = int(section.name[11:], 16)
72             section.finalloc = addr
73             fixedsections.append((addr, section))
74             if section.align != 1:
75                 print "Error: Fixed section %s has non-zero alignment (%d)" % (
76                     section.name, section.align)
77                 sys.exit(1)
78     fixedsections.sort()
79     firstfixed = fixedsections[0][0]
80
81     # Find freespace in fixed address area
82     # fixedAddr = [(freespace, section), ...]
83     fixedAddr = []
84     for i in range(len(fixedsections)):
85         fixedsectioninfo = fixedsections[i]
86         addr, section = fixedsectioninfo
87         if i == len(fixedsections) - 1:
88             nextaddr = BUILD_BIOS_SIZE
89         else:
90             nextaddr = fixedsections[i+1][0]
91         avail = nextaddr - addr - section.size
92         fixedAddr.append((avail, section))
93     fixedAddr.sort()
94
95     # Attempt to fit other sections into fixed area
96     canrelocate = [(section.size, section.align, section.name, section)
97                    for section in fillsections]
98     canrelocate.sort()
99     canrelocate = [section for size, align, name, section in canrelocate]
100     totalused = 0
101     for freespace, fixedsection in fixedAddr:
102         addpos = fixedsection.finalloc + fixedsection.size
103         totalused += fixedsection.size
104         nextfixedaddr = addpos + freespace
105 #        print "Filling section %x uses %d, next=%x, available=%d" % (
106 #            fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace)
107         while 1:
108             canfit = None
109             for fitsection in canrelocate:
110                 if addpos + fitsection.size > nextfixedaddr:
111                     # Can't fit and nothing else will fit.
112                     break
113                 fitnextaddr = alignpos(addpos, fitsection.align) + fitsection.size
114 #                print "Test %s - %x vs %x" % (
115 #                    fitsection.name, fitnextaddr, nextfixedaddr)
116                 if fitnextaddr > nextfixedaddr:
117                     # This item can't fit.
118                     continue
119                 canfit = (fitnextaddr, fitsection)
120             if canfit is None:
121                 break
122             # Found a section that can fit.
123             fitnextaddr, fitsection = canfit
124             canrelocate.remove(fitsection)
125             fitsection.finalloc = addpos
126             addpos = fitnextaddr
127             totalused += fitsection.size
128 #            print "    Adding %s (size %d align %d) pos=%x avail=%d" % (
129 #                fitsection[2], fitsection[0], fitsection[1]
130 #                , fitnextaddr, nextfixedaddr - fitnextaddr)
131
132     # Report stats
133     total = BUILD_BIOS_SIZE-firstfixed
134     slack = total - totalused
135     print ("Fixed space: 0x%x-0x%x  total: %d  slack: %d"
136            "  Percent slack: %.1f%%" % (
137             firstfixed, BUILD_BIOS_SIZE, total, slack,
138             (float(slack) / total) * 100.0))
139
140     return firstfixed
141
142 # Return the subset of sections with a given name prefix
143 def getSectionsPrefix(sections, category, prefix):
144     return [section for section in sections
145             if section.category == category and section.name.startswith(prefix)]
146
147 def doLayout(sections):
148     # Determine 16bit positions
149     textsections = getSectionsPrefix(sections, '16', '.text.')
150     rodatasections = (getSectionsPrefix(sections, '16', '.rodata.str1.1')
151                       + getSectionsPrefix(sections, '16', '.rodata.__func__.'))
152     datasections = getSectionsPrefix(sections, '16', '.data16.')
153     fixedsections = getSectionsPrefix(sections, '16', '.fixedaddr.')
154
155     firstfixed = fitSections(fixedsections, textsections)
156     remsections = [s for s in textsections+rodatasections+datasections
157                    if s.finalloc is None]
158     code16_start = setSectionsStart(remsections, firstfixed)
159
160     # Determine 32seg positions
161     textsections = getSectionsPrefix(sections, '32seg', '.text.')
162     rodatasections = (getSectionsPrefix(sections, '32seg', '.rodata.str1.1')
163                       +getSectionsPrefix(sections, '32seg', '.rodata.__func__.'))
164     datasections = getSectionsPrefix(sections, '32seg', '.data32seg.')
165
166     code32seg_start = setSectionsStart(
167         textsections + rodatasections + datasections, code16_start)
168
169     # Determine 32flat runtime positions
170     textsections = getSectionsPrefix(sections, '32flat', '.text.')
171     rodatasections = getSectionsPrefix(sections, '32flat', '.rodata')
172     datasections = getSectionsPrefix(sections, '32flat', '.data.')
173     bsssections = getSectionsPrefix(sections, '32flat', '.bss.')
174
175     code32flat_start = setSectionsStart(
176         textsections + rodatasections + datasections + bsssections
177         , code32seg_start + BUILD_BIOS_ADDR, 16)
178
179     # Determine 32flat init positions
180     textsections = getSectionsPrefix(sections, '32init', '.text.')
181     rodatasections = getSectionsPrefix(sections, '32init', '.rodata')
182     datasections = getSectionsPrefix(sections, '32init', '.data.')
183     bsssections = getSectionsPrefix(sections, '32init', '.bss.')
184
185     code32init_start = setSectionsStart(
186         textsections + rodatasections + datasections + bsssections
187         , code32flat_start, 16)
188
189     # Print statistics
190     size16 = BUILD_BIOS_SIZE - code16_start
191     size32seg = code16_start - code32seg_start
192     size32flat = code32seg_start + BUILD_BIOS_ADDR - code32flat_start
193     size32init = code32flat_start - code32init_start
194     print "16bit size:           %d" % size16
195     print "32bit segmented size: %d" % size32seg
196     print "32bit flat size:      %d" % size32flat
197     print "32bit flat init size: %d" % size32init
198
199
200 ######################################################################
201 # Linker script output
202 ######################################################################
203
204 # Write LD script includes for the given cross references
205 def outXRefs(sections):
206     xrefs = {}
207     out = ""
208     for section in sections:
209         for reloc in section.relocs:
210             symbol = reloc.symbol
211             if (symbol.section is None
212                 or symbol.section.fileid == section.fileid
213                 or symbol.name in xrefs):
214                 continue
215             xrefs[symbol.name] = 1
216             addr = symbol.section.finalloc + symbol.offset
217             if (section.fileid == '32flat'
218                 and symbol.section.fileid in ('16', '32seg')):
219                 addr += BUILD_BIOS_ADDR
220             out += "%s = 0x%x ;\n" % (symbol.name, addr)
221     return out
222
223 # Write LD script includes for the given sections using relative offsets
224 def outRelSections(sections, startsym):
225     out = ""
226     for section in sections:
227         out += ". = ( 0x%x - %s ) ;\n" % (section.finalloc, startsym)
228         if section.name == '.rodata.str1.1':
229             out += "_rodata = . ;\n"
230         out += "*(%s)\n" % (section.name,)
231     return out
232
233 def getSectionsFile(sections, fileid, defaddr=0):
234     sections = [(section.finalloc, section)
235                 for section in sections if section.fileid == fileid]
236     sections.sort()
237     sections = [section for addr, section in sections]
238     pos = defaddr
239     if sections:
240         pos = sections[0].finalloc
241     return sections, pos
242
243 # Layout the 32bit segmented code.  This places the code as high as possible.
244 def writeLinkerScripts(sections, entrysym, out16, out32seg, out32flat):
245     # Write 16bit linker script
246     sections16, code16_start = getSectionsFile(sections, '16')
247     output = open(out16, 'wb')
248     output.write(COMMONHEADER + outXRefs(sections16) + """
249     code16_start = 0x%x ;
250     .text16 code16_start : {
251 """ % (code16_start)
252                  + outRelSections(sections16, 'code16_start')
253                  + """
254     }
255 """
256                  + COMMONTRAILER)
257     output.close()
258
259     # Write 32seg linker script
260     sections32seg, code32seg_start = getSectionsFile(
261         sections, '32seg', code16_start)
262     output = open(out32seg, 'wb')
263     output.write(COMMONHEADER + outXRefs(sections32seg) + """
264     code32seg_start = 0x%x ;
265     .text32seg code32seg_start : {
266 """ % (code32seg_start)
267                  + outRelSections(sections32seg, 'code32seg_start')
268                  + """
269     }
270 """
271                  + COMMONTRAILER)
272     output.close()
273
274     # Write 32flat linker script
275     sections32flat, code32flat_start = getSectionsFile(
276         sections, '32flat', code32seg_start)
277     output = open(out32flat, 'wb')
278     output.write(COMMONHEADER
279                  + outXRefs(sections32flat) + """
280     %s = 0x%x ;
281     code32flat_start = 0x%x ;
282     .text code32flat_start : {
283 """ % (entrysym.name,
284        entrysym.section.finalloc + entrysym.offset + BUILD_BIOS_ADDR,
285        code32flat_start)
286                  + outRelSections(getSectionsPrefix(sections32flat, '32init', '')
287                                   , 'code32flat_start')
288                  + """
289         code32init_end = ABSOLUTE(.) ;
290 """
291                  + outRelSections(getSectionsPrefix(sections32flat, '32flat', '')
292                                   , 'code32flat_start')
293                  + """
294         . = ( 0x%x - code32flat_start ) ;
295         *(.text32seg)
296         . = ( 0x%x - code32flat_start ) ;
297         *(.text16)
298         code32flat_end = ABSOLUTE(.) ;
299     } :text
300 """ % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
301                  + COMMONTRAILER
302                  + """
303 ENTRY(%s)
304 PHDRS
305 {
306         text PT_LOAD AT ( code32flat_start ) ;
307 }
308 """ % (entrysym.name,))
309     output.close()
310
311
312 ######################################################################
313 # Detection of init code
314 ######################################################################
315
316 def markRuntime(section, sections):
317     if (section is None or not section.keep or section.category is not None
318         or '.init.' in section.name or section.fileid != '32flat'):
319         return
320     section.category = '32flat'
321     # Recursively mark all sections this section points to
322     for reloc in section.relocs:
323         markRuntime(reloc.symbol.section, sections)
324
325 def findInit(sections):
326     # Recursively find and mark all "runtime" sections.
327     for section in sections:
328         if '.runtime.' in section.name or '.export.' in section.name:
329             markRuntime(section, sections)
330     for section in sections:
331         if section.category is not None:
332             continue
333         if section.fileid == '32flat':
334             section.category = '32init'
335         else:
336             section.category = section.fileid
337
338
339 ######################################################################
340 # Section garbage collection
341 ######################################################################
342
343 # Find and keep the section associated with a symbol (if available).
344 def keepsymbol(reloc, infos, pos):
345     symbolname = reloc.symbol.name
346     symbol = infos[pos][1].get(symbolname)
347     if (symbol is None or symbol.section is None
348         or symbol.section.name.startswith('.discard.')):
349         return -1
350     reloc.symbol = symbol
351     keepsection(symbol.section, infos, pos)
352     return 0
353
354 # Note required section, and recursively set all referenced sections
355 # as required.
356 def keepsection(section, infos, pos=0):
357     if section.keep:
358         # Already kept - nothing to do.
359         return
360     section.keep = 1
361     # Keep all sections that this section points to
362     for reloc in section.relocs:
363         ret = keepsymbol(reloc, infos, pos)
364         if not ret:
365             continue
366         # Not in primary sections - it may be a cross 16/32 reference
367         ret = keepsymbol(reloc, infos, (pos+1)%3)
368         if not ret:
369             continue
370         ret = keepsymbol(reloc, infos, (pos+2)%3)
371         if not ret:
372             continue
373
374 # Determine which sections are actually referenced and need to be
375 # placed into the output file.
376 def gc(info16, info32seg, info32flat):
377     # infos = ((sections16, symbols16), (sect32seg, sym32seg)
378     #          , (sect32flat, sym32flat))
379     infos = (info16, info32seg, info32flat)
380     # Start by keeping sections that are globally visible.
381     for section in info16[0]:
382         if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
383             keepsection(section, infos)
384     return [section for section in info16[0]+info32seg[0]+info32flat[0]
385             if section.keep]
386
387
388 ######################################################################
389 # Startup and input parsing
390 ######################################################################
391
392 class Section:
393     name = size = alignment = fileid = relocs = None
394     finalloc = category = keep = None
395 class Reloc:
396     offset = type = symbol = None
397 class Symbol:
398     name = offset = section = None
399
400 # Read in output from objdump
401 def parseObjDump(file, fileid):
402     # sections = [section, ...]
403     sections = []
404     sectionmap = {}
405     # symbols[symbolname] = symbol
406     symbols = {}
407
408     state = None
409     for line in file.readlines():
410         line = line.rstrip()
411         if line == 'Sections:':
412             state = 'section'
413             continue
414         if line == 'SYMBOL TABLE:':
415             state = 'symbol'
416             continue
417         if line.startswith('RELOCATION RECORDS FOR ['):
418             sectionname = line[24:-2]
419             if sectionname.startswith('.debug_'):
420                 # Skip debugging sections (to reduce parsing time)
421                 state = None
422                 continue
423             state = 'reloc'
424             relocsection = sectionmap[sectionname]
425             continue
426
427         if state == 'section':
428             try:
429                 idx, name, size, vma, lma, fileoff, align = line.split()
430                 if align[:3] != '2**':
431                     continue
432                 section = Section()
433                 section.name = name
434                 section.size = int(size, 16)
435                 section.align = 2**int(align[3:])
436                 section.fileid = fileid
437                 section.relocs = []
438                 sections.append(section)
439                 sectionmap[name] = section
440             except ValueError:
441                 pass
442             continue
443         if state == 'symbol':
444             try:
445                 sectionname, size, name = line[17:].split()
446                 symbol = Symbol()
447                 symbol.size = int(size, 16)
448                 symbol.offset = int(line[:8], 16)
449                 symbol.name = name
450                 symbol.section = sectionmap.get(sectionname)
451                 symbols[name] = symbol
452             except ValueError:
453                 pass
454             continue
455         if state == 'reloc':
456             try:
457                 off, type, symbolname = line.split()
458                 reloc = Reloc()
459                 reloc.offset = int(off, 16)
460                 reloc.type = type
461                 reloc.symbol = symbols[symbolname]
462                 relocsection.relocs.append(reloc)
463             except ValueError:
464                 pass
465     return sections, symbols
466
467 def main():
468     # Get output name
469     in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
470
471     # Read in the objdump information
472     infile16 = open(in16, 'rb')
473     infile32seg = open(in32seg, 'rb')
474     infile32flat = open(in32flat, 'rb')
475
476     # infoX = (sections, symbols)
477     info16 = parseObjDump(infile16, '16')
478     info32seg = parseObjDump(infile32seg, '32seg')
479     info32flat = parseObjDump(infile32flat, '32flat')
480
481     # Figure out which sections to keep.
482     sections = gc(info16, info32seg, info32flat)
483
484     # Separate 32bit flat into runtime and init parts
485     findInit(sections)
486
487     # Determine the final memory locations of each kept section.
488     # locsX = [(addr, sectioninfo), ...]
489     doLayout(sections)
490
491     # Write out linker script files.
492     entrysym = info16[1]['post32']
493     writeLinkerScripts(sections, entrysym, out16, out32seg, out32flat)
494
495 if __name__ == '__main__':
496     main()