Modify tools/layoutrom.py to use classes instead of tuples.
[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, fileid, prefix):
144     return [section for section in sections
145             if section.fileid == fileid 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     # Print statistics
180     size16 = BUILD_BIOS_SIZE - code16_start
181     size32seg = code16_start - code32seg_start
182     size32flat = code32seg_start + BUILD_BIOS_ADDR - code32flat_start
183     print "16bit size:           %d" % size16
184     print "32bit segmented size: %d" % size32seg
185     print "32bit flat size:      %d" % size32flat
186
187
188 ######################################################################
189 # Linker script output
190 ######################################################################
191
192 # Write LD script includes for the given cross references
193 def outXRefs(sections):
194     xrefs = {}
195     out = ""
196     for section in sections:
197         for reloc in section.relocs:
198             symbol = reloc.symbol
199             if (symbol.section is None
200                 or symbol.section.fileid == section.fileid
201                 or symbol.name in xrefs):
202                 continue
203             xrefs[symbol.name] = 1
204             addr = symbol.section.finalloc + symbol.offset
205             if (section.fileid == '32flat'
206                 and symbol.section.fileid in ('16', '32seg')):
207                 addr += BUILD_BIOS_ADDR
208             out += "%s = 0x%x ;\n" % (symbol.name, addr)
209     return out
210
211 # Write LD script includes for the given sections using relative offsets
212 def outRelSections(sections, startsym):
213     out = ""
214     for section in sections:
215         out += ". = ( 0x%x - %s ) ;\n" % (section.finalloc, startsym)
216         if section.name == '.rodata.str1.1':
217             out += "_rodata = . ;\n"
218         out += "*(%s)\n" % (section.name,)
219     return out
220
221 def getSectionsFile(sections, fileid, defaddr=0):
222     sections = [(section.finalloc, section)
223                 for section in sections if section.fileid == fileid]
224     sections.sort()
225     sections = [section for addr, section in sections]
226     pos = defaddr
227     if sections:
228         pos = sections[0].finalloc
229     return sections, pos
230
231 # Layout the 32bit segmented code.  This places the code as high as possible.
232 def writeLinkerScripts(sections, entrysym, out16, out32seg, out32flat):
233     # Write 16bit linker script
234     sections16, code16_start = getSectionsFile(sections, '16')
235     output = open(out16, 'wb')
236     output.write(COMMONHEADER + outXRefs(sections16) + """
237     code16_start = 0x%x ;
238     .text16 code16_start : {
239 """ % (code16_start)
240                  + outRelSections(sections16, 'code16_start')
241                  + """
242     }
243 """
244                  + COMMONTRAILER)
245     output.close()
246
247     # Write 32seg linker script
248     sections32seg, code32seg_start = getSectionsFile(
249         sections, '32seg', code16_start)
250     output = open(out32seg, 'wb')
251     output.write(COMMONHEADER + outXRefs(sections32seg) + """
252     code32seg_start = 0x%x ;
253     .text32seg code32seg_start : {
254 """ % (code32seg_start)
255                  + outRelSections(sections32seg, 'code32seg_start')
256                  + """
257     }
258 """
259                  + COMMONTRAILER)
260     output.close()
261
262     # Write 32flat linker script
263     sections32flat, code32flat_start = getSectionsFile(
264         sections, '32flat', code32seg_start)
265     output = open(out32flat, 'wb')
266     output.write(COMMONHEADER
267                  + outXRefs(sections32flat) + """
268     %s = 0x%x ;
269     code32flat_start = 0x%x ;
270     .text code32flat_start : {
271 """ % (entrysym.name,
272        entrysym.section.finalloc + entrysym.offset + BUILD_BIOS_ADDR,
273        code32flat_start)
274                  + outRelSections(getSectionsPrefix(sections32flat, '32flat', '')
275                                   , 'code32flat_start')
276                  + """
277         . = ( 0x%x - code32flat_start ) ;
278         *(.text32seg)
279         . = ( 0x%x - code32flat_start ) ;
280         *(.text16)
281         code32flat_end = ABSOLUTE(.) ;
282     } :text
283 """ % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
284                  + COMMONTRAILER
285                  + """
286 ENTRY(%s)
287 PHDRS
288 {
289         text PT_LOAD AT ( code32flat_start ) ;
290 }
291 """ % (entrysym.name,))
292     output.close()
293
294
295 ######################################################################
296 # Section garbage collection
297 ######################################################################
298
299 # Find and keep the section associated with a symbol (if available).
300 def keepsymbol(reloc, infos, pos):
301     symbolname = reloc.symbol.name
302     symbol = infos[pos][1].get(symbolname)
303     if (symbol is None or symbol.section is None
304         or symbol.section.name.startswith('.discard.')):
305         return -1
306     reloc.symbol = symbol
307     keepsection(symbol.section, infos, pos)
308     return 0
309
310 # Note required section, and recursively set all referenced sections
311 # as required.
312 def keepsection(section, infos, pos=0):
313     if section.keep:
314         # Already kept - nothing to do.
315         return
316     section.keep = 1
317     # Keep all sections that this section points to
318     for reloc in section.relocs:
319         ret = keepsymbol(reloc, infos, pos)
320         if not ret:
321             continue
322         # Not in primary sections - it may be a cross 16/32 reference
323         ret = keepsymbol(reloc, infos, (pos+1)%3)
324         if not ret:
325             continue
326         ret = keepsymbol(reloc, infos, (pos+2)%3)
327         if not ret:
328             continue
329
330 # Determine which sections are actually referenced and need to be
331 # placed into the output file.
332 def gc(info16, info32seg, info32flat):
333     # infos = ((sections16, symbols16), (sect32seg, sym32seg)
334     #          , (sect32flat, sym32flat))
335     infos = (info16, info32seg, info32flat)
336     # Start by keeping sections that are globally visible.
337     for section in info16[0]:
338         if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
339             keepsection(section, infos)
340     return [section for section in info16[0]+info32seg[0]+info32flat[0]
341             if section.keep]
342
343
344 ######################################################################
345 # Startup and input parsing
346 ######################################################################
347
348 class Section:
349     name = size = alignment = fileid = relocs = None
350     finalloc = keep = None
351 class Reloc:
352     offset = type = symbol = None
353 class Symbol:
354     name = offset = section = None
355
356 # Read in output from objdump
357 def parseObjDump(file, fileid):
358     # sections = [section, ...]
359     sections = []
360     sectionmap = {}
361     # symbols[symbolname] = symbol
362     symbols = {}
363
364     state = None
365     for line in file.readlines():
366         line = line.rstrip()
367         if line == 'Sections:':
368             state = 'section'
369             continue
370         if line == 'SYMBOL TABLE:':
371             state = 'symbol'
372             continue
373         if line.startswith('RELOCATION RECORDS FOR ['):
374             sectionname = line[24:-2]
375             if sectionname.startswith('.debug_'):
376                 # Skip debugging sections (to reduce parsing time)
377                 state = None
378                 continue
379             state = 'reloc'
380             relocsection = sectionmap[sectionname]
381             continue
382
383         if state == 'section':
384             try:
385                 idx, name, size, vma, lma, fileoff, align = line.split()
386                 if align[:3] != '2**':
387                     continue
388                 section = Section()
389                 section.name = name
390                 section.size = int(size, 16)
391                 section.align = 2**int(align[3:])
392                 section.fileid = fileid
393                 section.relocs = []
394                 sections.append(section)
395                 sectionmap[name] = section
396             except ValueError:
397                 pass
398             continue
399         if state == 'symbol':
400             try:
401                 sectionname, size, name = line[17:].split()
402                 symbol = Symbol()
403                 symbol.size = int(size, 16)
404                 symbol.offset = int(line[:8], 16)
405                 symbol.name = name
406                 symbol.section = sectionmap.get(sectionname)
407                 symbols[name] = symbol
408             except ValueError:
409                 pass
410             continue
411         if state == 'reloc':
412             try:
413                 off, type, symbolname = line.split()
414                 reloc = Reloc()
415                 reloc.offset = int(off, 16)
416                 reloc.type = type
417                 reloc.symbol = symbols[symbolname]
418                 relocsection.relocs.append(reloc)
419             except ValueError:
420                 pass
421     return sections, symbols
422
423 def main():
424     # Get output name
425     in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
426
427     # Read in the objdump information
428     infile16 = open(in16, 'rb')
429     infile32seg = open(in32seg, 'rb')
430     infile32flat = open(in32flat, 'rb')
431
432     # infoX = (sections, symbols)
433     info16 = parseObjDump(infile16, '16')
434     info32seg = parseObjDump(infile32seg, '32seg')
435     info32flat = parseObjDump(infile32flat, '32flat')
436
437     # Figure out which sections to keep.
438     sections = gc(info16, info32seg, info32flat)
439
440     # Determine the final memory locations of each kept section.
441     # locsX = [(addr, sectioninfo), ...]
442     doLayout(sections)
443
444     # Write out linker script files.
445     entrysym = info16[1]['post32']
446     writeLinkerScripts(sections, entrysym, out16, out32seg, out32flat)
447
448 if __name__ == '__main__':
449     main()