blob: 4109b168509541c3a5bb9db0f75c7af72df1f991 [file] [log] [blame]
Kevin O'Connor202024a2009-01-17 10:41:28 -05001#!/usr/bin/env python
Kevin O'Connor5b8f8092009-09-20 19:47:45 -04002# Script to analyze code and arrange ld sections.
Kevin O'Connor202024a2009-01-17 10:41:28 -05003#
Kevin O'Connor1a4885e2010-09-15 21:28:31 -04004# Copyright (C) 2008-2010 Kevin O'Connor <kevin@koconnor.net>
Kevin O'Connor202024a2009-01-17 10:41:28 -05005#
6# This file may be distributed under the terms of the GNU GPLv3 license.
7
8import sys
9
Kevin O'Connor5b8f8092009-09-20 19:47:45 -040010# LD script headers/trailers
11COMMONHEADER = """
12/* DO NOT EDIT! This is an autogenerated file. See tools/layoutrom.py. */
13OUTPUT_FORMAT("elf32-i386")
14OUTPUT_ARCH("i386")
15SECTIONS
16{
17"""
18COMMONTRAILER = """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040019
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 }
Kevin O'Connor5b8f8092009-09-20 19:47:45 -040028}
29"""
30
Kevin O'Connorc0693942009-06-10 21:56:01 -040031
32######################################################################
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040033# Determine section locations
Kevin O'Connorc0693942009-06-10 21:56:01 -040034######################################################################
35
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040036# Align 'pos' to 'alignbytes' offset
37def 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
Kevin O'Connor5b8f8092009-09-20 19:47:45 -040042# address.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040043def setSectionsStart(sections, endaddr, minalign=1):
Kevin O'Connor5b8f8092009-09-20 19:47:45 -040044 totspace = 0
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040045 for section in sections:
46 if section.align > minalign:
47 minalign = section.align
48 totspace = alignpos(totspace, section.align) + section.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040049 startaddr = (endaddr - totspace) / minalign * minalign
50 curaddr = startaddr
51 # out = [(addr, sectioninfo), ...]
52 out = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040053 for section in sections:
54 curaddr = alignpos(curaddr, section.align)
55 section.finalloc = curaddr
56 curaddr += section.size
57 return startaddr
Kevin O'Connorc0693942009-06-10 21:56:01 -040058
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040059# The 16bit code can't exceed 64K of space.
60BUILD_BIOS_ADDR = 0xf0000
61BUILD_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.
66def fitSections(sections, fillsections):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040067 # fixedsections = [(addr, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040068 fixedsections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040069 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:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040075 print "Error: Fixed section %s has non-zero alignment (%d)" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040076 section.name, section.align)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040077 sys.exit(1)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040078 fixedsections.sort()
79 firstfixed = fixedsections[0][0]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040080
81 # Find freespace in fixed address area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040082 # fixedAddr = [(freespace, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040083 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]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040091 avail = nextaddr - addr - section.size
92 fixedAddr.append((avail, section))
93 fixedAddr.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040094
95 # Attempt to fit other sections into fixed area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040096 canrelocate = [(section.size, section.align, section.name, section)
97 for section in fillsections]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040098 canrelocate.sort()
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040099 canrelocate = [section for size, align, name, section in canrelocate]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400100 totalused = 0
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400101 for freespace, fixedsection in fixedAddr:
102 addpos = fixedsection.finalloc + fixedsection.size
103 totalused += fixedsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400104 nextfixedaddr = addpos + freespace
105# print "Filling section %x uses %d, next=%x, available=%d" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400106# fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400107 while 1:
108 canfit = None
109 for fitsection in canrelocate:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400110 if addpos + fitsection.size > nextfixedaddr:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400111 # Can't fit and nothing else will fit.
112 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400113 fitnextaddr = alignpos(addpos, fitsection.align) + fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400114# print "Test %s - %x vs %x" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400115# fitsection.name, fitnextaddr, nextfixedaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400116 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)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400125 fitsection.finalloc = addpos
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400126 addpos = fitnextaddr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400127 totalused += fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400128# print " Adding %s (size %d align %d) pos=%x avail=%d" % (
129# fitsection[2], fitsection[0], fitsection[1]
130# , fitnextaddr, nextfixedaddr - fitnextaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400131
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
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400140 return firstfixed
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400141
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400142# Return the subset of sections with a given name prefix
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400143def getSectionsPrefix(sections, category, prefix):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400144 return [section for section in sections
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400145 if section.category == category and section.name.startswith(prefix)]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400146
147def doLayout(sections):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400148 # Determine 16bit positions
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400149 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.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400154
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400155 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)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400159
160 # Determine 32seg positions
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400161 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.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400165
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400166 code32seg_start = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400167 textsections + rodatasections + datasections, code16_start)
168
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400169 # 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.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400174
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400175 code32flat_start = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400176 textsections + rodatasections + datasections + bsssections
177 , code32seg_start + BUILD_BIOS_ADDR, 16)
178
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400179 # 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
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400189 # Print statistics
190 size16 = BUILD_BIOS_SIZE - code16_start
191 size32seg = code16_start - code32seg_start
192 size32flat = code32seg_start + BUILD_BIOS_ADDR - code32flat_start
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400193 size32init = code32flat_start - code32init_start
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400194 print "16bit size: %d" % size16
195 print "32bit segmented size: %d" % size32seg
196 print "32bit flat size: %d" % size32flat
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400197 print "32bit flat init size: %d" % size32init
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400198
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400199
200######################################################################
201# Linker script output
202######################################################################
203
204# Write LD script includes for the given cross references
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400205def outXRefs(sections):
206 xrefs = {}
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400207 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400208 for section in sections:
209 for reloc in section.relocs:
210 symbol = reloc.symbol
211 if (symbol.section is None
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500212 or (symbol.section.fileid == section.fileid
213 and symbol.name == reloc.symbolname)
214 or reloc.symbolname in xrefs):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400215 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500216 xrefs[reloc.symbolname] = 1
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400217 addr = symbol.section.finalloc + symbol.offset
218 if (section.fileid == '32flat'
219 and symbol.section.fileid in ('16', '32seg')):
220 addr += BUILD_BIOS_ADDR
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500221 out += "%s = 0x%x ;\n" % (reloc.symbolname, addr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400222 return out
223
224# Write LD script includes for the given sections using relative offsets
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400225def outRelSections(sections, startsym):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400226 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400227 for section in sections:
228 out += ". = ( 0x%x - %s ) ;\n" % (section.finalloc, startsym)
229 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400230 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400231 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400232 return out
233
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400234def getSectionsFile(sections, fileid, defaddr=0):
235 sections = [(section.finalloc, section)
236 for section in sections if section.fileid == fileid]
237 sections.sort()
238 sections = [section for addr, section in sections]
239 pos = defaddr
240 if sections:
241 pos = sections[0].finalloc
242 return sections, pos
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500243
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400244# Layout the 32bit segmented code. This places the code as high as possible.
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400245def writeLinkerScripts(sections, entrysym, genreloc, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400246 # Write 16bit linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400247 sections16, code16_start = getSectionsFile(sections, '16')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400248 output = open(out16, 'wb')
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400249 output.write(COMMONHEADER + outXRefs(sections16) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400250 code16_start = 0x%x ;
251 .text16 code16_start : {
252""" % (code16_start)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400253 + outRelSections(sections16, 'code16_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400254 + """
255 }
256"""
257 + COMMONTRAILER)
258 output.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500259
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400260 # Write 32seg linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400261 sections32seg, code32seg_start = getSectionsFile(
262 sections, '32seg', code16_start)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400263 output = open(out32seg, 'wb')
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400264 output.write(COMMONHEADER + outXRefs(sections32seg) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400265 code32seg_start = 0x%x ;
266 .text32seg code32seg_start : {
267""" % (code32seg_start)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400268 + outRelSections(sections32seg, 'code32seg_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400269 + """
270 }
271"""
272 + COMMONTRAILER)
273 output.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500274
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400275 # Write 32flat linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400276 sections32flat, code32flat_start = getSectionsFile(
277 sections, '32flat', code32seg_start)
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400278 relocstr = ""
279 relocminalign = 0
280 if genreloc:
281 # Generate relocations
282 relocstr, size, relocminalign = genRelocs(sections)
283 code32flat_start -= size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400284 output = open(out32flat, 'wb')
285 output.write(COMMONHEADER
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400286 + outXRefs(sections32flat) + """
287 %s = 0x%x ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400288 _reloc_min_align = 0x%x ;
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400289 code32flat_start = 0x%x ;
290 .text code32flat_start : {
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400291""" % (entrysym.name,
292 entrysym.section.finalloc + entrysym.offset + BUILD_BIOS_ADDR,
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400293 relocminalign, code32flat_start)
294 + relocstr
295 + """
296 code32init_start = ABSOLUTE(.) ;
297"""
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400298 + outRelSections(getSectionsPrefix(sections32flat, '32init', '')
299 , 'code32flat_start')
300 + """
301 code32init_end = ABSOLUTE(.) ;
302"""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400303 + outRelSections(getSectionsPrefix(sections32flat, '32flat', '')
304 , 'code32flat_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400305 + """
306 . = ( 0x%x - code32flat_start ) ;
307 *(.text32seg)
308 . = ( 0x%x - code32flat_start ) ;
309 *(.text16)
310 code32flat_end = ABSOLUTE(.) ;
311 } :text
312""" % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
313 + COMMONTRAILER
314 + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400315ENTRY(%s)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400316PHDRS
317{
318 text PT_LOAD AT ( code32flat_start ) ;
319}
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400320""" % (entrysym.name,))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400321 output.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400322
323
324######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400325# Detection of init code
326######################################################################
327
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400328# Determine init section relocations
329def genRelocs(sections):
330 absrelocs = []
331 relrelocs = []
332 initrelocs = []
333 minalign = 16
334 for section in sections:
335 if section.category == '32init' and section.align > minalign:
336 minalign = section.align
337 for reloc in section.relocs:
338 symbol = reloc.symbol
339 if symbol.section is None:
340 continue
341 relocpos = section.finalloc + reloc.offset
342 if (reloc.type == 'R_386_32' and section.category == '32init'
343 and symbol.section.category == '32init'):
344 # Absolute relocation
345 absrelocs.append(relocpos)
346 elif (reloc.type == 'R_386_PC32' and section.category == '32init'
347 and symbol.section.category != '32init'):
348 # Relative relocation
349 relrelocs.append(relocpos)
350 elif (section.category != '32init'
351 and symbol.section.category == '32init'):
352 # Relocation to the init section
353 if section.fileid in ('16', '32seg'):
354 relocpos += BUILD_BIOS_ADDR
355 initrelocs.append(relocpos)
356 absrelocs.sort()
357 relrelocs.sort()
358 initrelocs.sort()
359 out = (" _reloc_abs_start = ABSOLUTE(.) ;\n"
360 + "".join(["LONG(0x%x - code32init_start)\n" % (pos,)
361 for pos in absrelocs])
362 + " _reloc_abs_end = ABSOLUTE(.) ;\n"
363 + " _reloc_rel_start = ABSOLUTE(.) ;\n"
364 + "".join(["LONG(0x%x - code32init_start)\n" % (pos,)
365 for pos in relrelocs])
366 + " _reloc_rel_end = ABSOLUTE(.) ;\n"
367 + " _reloc_init_start = ABSOLUTE(.) ;\n"
368 + "".join(["LONG(0x%x - code32flat_start)\n" % (pos,)
369 for pos in initrelocs])
370 + " _reloc_init_end = ABSOLUTE(.) ;\n")
371 return out, len(absrelocs + relrelocs + initrelocs) * 4, minalign
372
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400373def markRuntime(section, sections):
374 if (section is None or not section.keep or section.category is not None
375 or '.init.' in section.name or section.fileid != '32flat'):
376 return
377 section.category = '32flat'
378 # Recursively mark all sections this section points to
379 for reloc in section.relocs:
380 markRuntime(reloc.symbol.section, sections)
381
382def findInit(sections):
383 # Recursively find and mark all "runtime" sections.
384 for section in sections:
385 if '.runtime.' in section.name or '.export.' in section.name:
386 markRuntime(section, sections)
387 for section in sections:
388 if section.category is not None:
389 continue
390 if section.fileid == '32flat':
391 section.category = '32init'
392 else:
393 section.category = section.fileid
394
395
396######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400397# Section garbage collection
398######################################################################
399
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500400CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
401
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500402# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500403def keepsymbol(reloc, infos, pos, isxref):
404 symbolname = reloc.symbolname
405 mustbecfunc = 0
406 for symprefix, needpos in CFUNCPREFIX:
407 if symbolname.startswith(symprefix):
408 if needpos != pos:
409 return -1
410 symbolname = symbolname[len(symprefix):]
411 mustbecfunc = 1
412 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400413 symbol = infos[pos][1].get(symbolname)
414 if (symbol is None or symbol.section is None
415 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500416 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500417 isdestcfunc = (symbol.section.name.startswith('.text.')
418 and not symbol.section.name.startswith('.text.asm.'))
419 if ((mustbecfunc and not isdestcfunc)
420 or (not mustbecfunc and isdestcfunc and isxref)):
421 return -1
422
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400423 reloc.symbol = symbol
424 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500425 return 0
426
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400427# Note required section, and recursively set all referenced sections
428# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400429def keepsection(section, infos, pos=0):
430 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400431 # Already kept - nothing to do.
432 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400433 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400434 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400435 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500436 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500437 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400438 continue
439 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500440 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500441 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500442 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500443 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500444 if not ret:
445 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400446
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400447# Determine which sections are actually referenced and need to be
448# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500449def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400450 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
451 # , (sect32flat, sym32flat))
452 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400453 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400454 for section in info16[0]:
455 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500456 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400457 return [section for section in info16[0]+info32seg[0]+info32flat[0]
458 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400459
460
461######################################################################
462# Startup and input parsing
463######################################################################
464
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400465class Section:
466 name = size = alignment = fileid = relocs = None
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400467 finalloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400468class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500469 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400470class Symbol:
471 name = offset = section = None
472
Kevin O'Connorc0693942009-06-10 21:56:01 -0400473# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400474def parseObjDump(file, fileid):
475 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400476 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400477 sectionmap = {}
478 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400479 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400480
481 state = None
482 for line in file.readlines():
483 line = line.rstrip()
484 if line == 'Sections:':
485 state = 'section'
486 continue
487 if line == 'SYMBOL TABLE:':
488 state = 'symbol'
489 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400490 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400491 sectionname = line[24:-2]
492 if sectionname.startswith('.debug_'):
493 # Skip debugging sections (to reduce parsing time)
494 state = None
495 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400496 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400497 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400498 continue
499
500 if state == 'section':
501 try:
502 idx, name, size, vma, lma, fileoff, align = line.split()
503 if align[:3] != '2**':
504 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400505 section = Section()
506 section.name = name
507 section.size = int(size, 16)
508 section.align = 2**int(align[3:])
509 section.fileid = fileid
510 section.relocs = []
511 sections.append(section)
512 sectionmap[name] = section
513 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400514 pass
515 continue
516 if state == 'symbol':
517 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400518 sectionname, size, name = line[17:].split()
519 symbol = Symbol()
520 symbol.size = int(size, 16)
521 symbol.offset = int(line[:8], 16)
522 symbol.name = name
523 symbol.section = sectionmap.get(sectionname)
524 symbols[name] = symbol
525 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400526 pass
527 continue
528 if state == 'reloc':
529 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400530 off, type, symbolname = line.split()
531 reloc = Reloc()
532 reloc.offset = int(off, 16)
533 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500534 reloc.symbolname = symbolname
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400535 reloc.symbol = symbols[symbolname]
536 relocsection.relocs.append(reloc)
537 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400538 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400539 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400540
541def main():
542 # Get output name
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500543 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400544
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400545 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400546 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500547 infile32seg = open(in32seg, 'rb')
548 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400549
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400550 # infoX = (sections, symbols)
551 info16 = parseObjDump(infile16, '16')
552 info32seg = parseObjDump(infile32seg, '32seg')
553 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400554
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400555 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400556 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400557
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400558 # Separate 32bit flat into runtime and init parts
559 findInit(sections)
560
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400561 # Determine the final memory locations of each kept section.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400562 doLayout(sections)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400563
564 # Write out linker script files.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400565 entrysym = info16[1]['post32']
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400566 genreloc = '_reloc_abs_start' in info32flat[1]
567 writeLinkerScripts(sections, entrysym, genreloc, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400568
Kevin O'Connor202024a2009-01-17 10:41:28 -0500569if __name__ == '__main__':
570 main()