blob: 86e1f3351f47019490debd620980feec158c9bec [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.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500150 rodatasections = (
151 getSectionsPrefix(sections, '16', '.rodata.str1.1')
152 + getSectionsPrefix(sections, '16', '.rodata.__func__.')
153 + getSectionsPrefix(sections, '16', '.rodata.__PRETTY_FUNCTION__.'))
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400154 datasections = getSectionsPrefix(sections, '16', '.data16.')
155 fixedsections = getSectionsPrefix(sections, '16', '.fixedaddr.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400156
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400157 firstfixed = fitSections(fixedsections, textsections)
158 remsections = [s for s in textsections+rodatasections+datasections
159 if s.finalloc is None]
160 code16_start = setSectionsStart(remsections, firstfixed)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400161
162 # Determine 32seg positions
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400163 textsections = getSectionsPrefix(sections, '32seg', '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500164 rodatasections = (
165 getSectionsPrefix(sections, '32seg', '.rodata.str1.1')
166 + getSectionsPrefix(sections, '32seg', '.rodata.__func__.')
167 + getSectionsPrefix(sections, '32seg', '.rodata.__PRETTY_FUNCTION__.'))
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400168 datasections = getSectionsPrefix(sections, '32seg', '.data32seg.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400169
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400170 code32seg_start = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400171 textsections + rodatasections + datasections, code16_start)
172
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400173 # Determine 32flat runtime positions
174 textsections = getSectionsPrefix(sections, '32flat', '.text.')
175 rodatasections = getSectionsPrefix(sections, '32flat', '.rodata')
176 datasections = getSectionsPrefix(sections, '32flat', '.data.')
177 bsssections = getSectionsPrefix(sections, '32flat', '.bss.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400178
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400179 code32flat_start = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400180 textsections + rodatasections + datasections + bsssections
181 , code32seg_start + BUILD_BIOS_ADDR, 16)
182
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400183 # Determine 32flat init positions
184 textsections = getSectionsPrefix(sections, '32init', '.text.')
185 rodatasections = getSectionsPrefix(sections, '32init', '.rodata')
186 datasections = getSectionsPrefix(sections, '32init', '.data.')
187 bsssections = getSectionsPrefix(sections, '32init', '.bss.')
188
189 code32init_start = setSectionsStart(
190 textsections + rodatasections + datasections + bsssections
191 , code32flat_start, 16)
192
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400193 # Print statistics
194 size16 = BUILD_BIOS_SIZE - code16_start
195 size32seg = code16_start - code32seg_start
196 size32flat = code32seg_start + BUILD_BIOS_ADDR - code32flat_start
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400197 size32init = code32flat_start - code32init_start
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400198 print "16bit size: %d" % size16
199 print "32bit segmented size: %d" % size32seg
200 print "32bit flat size: %d" % size32flat
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400201 print "32bit flat init size: %d" % size32init
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400202
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400203
204######################################################################
205# Linker script output
206######################################################################
207
208# Write LD script includes for the given cross references
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400209def outXRefs(sections):
210 xrefs = {}
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400211 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400212 for section in sections:
213 for reloc in section.relocs:
214 symbol = reloc.symbol
215 if (symbol.section is None
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500216 or (symbol.section.fileid == section.fileid
217 and symbol.name == reloc.symbolname)
218 or reloc.symbolname in xrefs):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400219 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500220 xrefs[reloc.symbolname] = 1
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400221 addr = symbol.section.finalloc + symbol.offset
222 if (section.fileid == '32flat'
223 and symbol.section.fileid in ('16', '32seg')):
224 addr += BUILD_BIOS_ADDR
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500225 out += "%s = 0x%x ;\n" % (reloc.symbolname, addr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400226 return out
227
228# Write LD script includes for the given sections using relative offsets
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400229def outRelSections(sections, startsym):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400230 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400231 for section in sections:
232 out += ". = ( 0x%x - %s ) ;\n" % (section.finalloc, startsym)
233 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400234 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400235 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400236 return out
237
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400238def getSectionsFile(sections, fileid, defaddr=0):
239 sections = [(section.finalloc, section)
240 for section in sections if section.fileid == fileid]
241 sections.sort()
242 sections = [section for addr, section in sections]
243 pos = defaddr
244 if sections:
245 pos = sections[0].finalloc
246 return sections, pos
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500247
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400248# Layout the 32bit segmented code. This places the code as high as possible.
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400249def writeLinkerScripts(sections, entrysym, genreloc, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400250 # Write 16bit linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400251 sections16, code16_start = getSectionsFile(sections, '16')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400252 output = open(out16, 'wb')
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400253 output.write(COMMONHEADER + outXRefs(sections16) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400254 code16_start = 0x%x ;
255 .text16 code16_start : {
256""" % (code16_start)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400257 + outRelSections(sections16, 'code16_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400258 + """
259 }
260"""
261 + COMMONTRAILER)
262 output.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500263
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400264 # Write 32seg linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400265 sections32seg, code32seg_start = getSectionsFile(
266 sections, '32seg', code16_start)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400267 output = open(out32seg, 'wb')
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400268 output.write(COMMONHEADER + outXRefs(sections32seg) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400269 code32seg_start = 0x%x ;
270 .text32seg code32seg_start : {
271""" % (code32seg_start)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400272 + outRelSections(sections32seg, 'code32seg_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400273 + """
274 }
275"""
276 + COMMONTRAILER)
277 output.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500278
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400279 # Write 32flat linker script
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400280 sections32flat, code32flat_start = getSectionsFile(
281 sections, '32flat', code32seg_start)
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400282 relocstr = ""
283 relocminalign = 0
284 if genreloc:
285 # Generate relocations
286 relocstr, size, relocminalign = genRelocs(sections)
287 code32flat_start -= size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400288 output = open(out32flat, 'wb')
289 output.write(COMMONHEADER
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400290 + outXRefs(sections32flat) + """
291 %s = 0x%x ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400292 _reloc_min_align = 0x%x ;
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400293 code32flat_start = 0x%x ;
294 .text code32flat_start : {
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400295""" % (entrysym.name,
296 entrysym.section.finalloc + entrysym.offset + BUILD_BIOS_ADDR,
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400297 relocminalign, code32flat_start)
298 + relocstr
299 + """
300 code32init_start = ABSOLUTE(.) ;
301"""
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400302 + outRelSections(getSectionsPrefix(sections32flat, '32init', '')
303 , 'code32flat_start')
304 + """
305 code32init_end = ABSOLUTE(.) ;
306"""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400307 + outRelSections(getSectionsPrefix(sections32flat, '32flat', '')
308 , 'code32flat_start')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400309 + """
310 . = ( 0x%x - code32flat_start ) ;
311 *(.text32seg)
312 . = ( 0x%x - code32flat_start ) ;
313 *(.text16)
314 code32flat_end = ABSOLUTE(.) ;
315 } :text
316""" % (code32seg_start + BUILD_BIOS_ADDR, code16_start + BUILD_BIOS_ADDR)
317 + COMMONTRAILER
318 + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400319ENTRY(%s)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400320PHDRS
321{
322 text PT_LOAD AT ( code32flat_start ) ;
323}
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400324""" % (entrysym.name,))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400325 output.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400326
327
328######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400329# Detection of init code
330######################################################################
331
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400332# Determine init section relocations
333def genRelocs(sections):
334 absrelocs = []
335 relrelocs = []
336 initrelocs = []
337 minalign = 16
338 for section in sections:
339 if section.category == '32init' and section.align > minalign:
340 minalign = section.align
341 for reloc in section.relocs:
342 symbol = reloc.symbol
343 if symbol.section is None:
344 continue
345 relocpos = section.finalloc + reloc.offset
346 if (reloc.type == 'R_386_32' and section.category == '32init'
347 and symbol.section.category == '32init'):
348 # Absolute relocation
349 absrelocs.append(relocpos)
350 elif (reloc.type == 'R_386_PC32' and section.category == '32init'
351 and symbol.section.category != '32init'):
352 # Relative relocation
353 relrelocs.append(relocpos)
354 elif (section.category != '32init'
355 and symbol.section.category == '32init'):
356 # Relocation to the init section
357 if section.fileid in ('16', '32seg'):
358 relocpos += BUILD_BIOS_ADDR
359 initrelocs.append(relocpos)
360 absrelocs.sort()
361 relrelocs.sort()
362 initrelocs.sort()
363 out = (" _reloc_abs_start = ABSOLUTE(.) ;\n"
364 + "".join(["LONG(0x%x - code32init_start)\n" % (pos,)
365 for pos in absrelocs])
366 + " _reloc_abs_end = ABSOLUTE(.) ;\n"
367 + " _reloc_rel_start = ABSOLUTE(.) ;\n"
368 + "".join(["LONG(0x%x - code32init_start)\n" % (pos,)
369 for pos in relrelocs])
370 + " _reloc_rel_end = ABSOLUTE(.) ;\n"
371 + " _reloc_init_start = ABSOLUTE(.) ;\n"
372 + "".join(["LONG(0x%x - code32flat_start)\n" % (pos,)
373 for pos in initrelocs])
374 + " _reloc_init_end = ABSOLUTE(.) ;\n")
375 return out, len(absrelocs + relrelocs + initrelocs) * 4, minalign
376
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400377def markRuntime(section, sections):
378 if (section is None or not section.keep or section.category is not None
379 or '.init.' in section.name or section.fileid != '32flat'):
380 return
381 section.category = '32flat'
382 # Recursively mark all sections this section points to
383 for reloc in section.relocs:
384 markRuntime(reloc.symbol.section, sections)
385
386def findInit(sections):
387 # Recursively find and mark all "runtime" sections.
388 for section in sections:
389 if '.runtime.' in section.name or '.export.' in section.name:
390 markRuntime(section, sections)
391 for section in sections:
392 if section.category is not None:
393 continue
394 if section.fileid == '32flat':
395 section.category = '32init'
396 else:
397 section.category = section.fileid
398
399
400######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400401# Section garbage collection
402######################################################################
403
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500404CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
405
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500406# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500407def keepsymbol(reloc, infos, pos, isxref):
408 symbolname = reloc.symbolname
409 mustbecfunc = 0
410 for symprefix, needpos in CFUNCPREFIX:
411 if symbolname.startswith(symprefix):
412 if needpos != pos:
413 return -1
414 symbolname = symbolname[len(symprefix):]
415 mustbecfunc = 1
416 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400417 symbol = infos[pos][1].get(symbolname)
418 if (symbol is None or symbol.section is None
419 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500420 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500421 isdestcfunc = (symbol.section.name.startswith('.text.')
422 and not symbol.section.name.startswith('.text.asm.'))
423 if ((mustbecfunc and not isdestcfunc)
424 or (not mustbecfunc and isdestcfunc and isxref)):
425 return -1
426
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400427 reloc.symbol = symbol
428 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500429 return 0
430
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400431# Note required section, and recursively set all referenced sections
432# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400433def keepsection(section, infos, pos=0):
434 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400435 # Already kept - nothing to do.
436 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400437 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400438 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400439 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500440 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500441 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400442 continue
443 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500444 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500445 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500446 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500447 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500448 if not ret:
449 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400450
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400451# Determine which sections are actually referenced and need to be
452# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500453def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400454 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
455 # , (sect32flat, sym32flat))
456 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400457 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400458 for section in info16[0]:
459 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500460 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400461 return [section for section in info16[0]+info32seg[0]+info32flat[0]
462 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400463
464
465######################################################################
466# Startup and input parsing
467######################################################################
468
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400469class Section:
470 name = size = alignment = fileid = relocs = None
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400471 finalloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400472class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500473 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400474class Symbol:
475 name = offset = section = None
476
Kevin O'Connorc0693942009-06-10 21:56:01 -0400477# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400478def parseObjDump(file, fileid):
479 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400480 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400481 sectionmap = {}
482 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400483 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400484
485 state = None
486 for line in file.readlines():
487 line = line.rstrip()
488 if line == 'Sections:':
489 state = 'section'
490 continue
491 if line == 'SYMBOL TABLE:':
492 state = 'symbol'
493 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400494 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400495 sectionname = line[24:-2]
496 if sectionname.startswith('.debug_'):
497 # Skip debugging sections (to reduce parsing time)
498 state = None
499 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400500 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400501 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400502 continue
503
504 if state == 'section':
505 try:
506 idx, name, size, vma, lma, fileoff, align = line.split()
507 if align[:3] != '2**':
508 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400509 section = Section()
510 section.name = name
511 section.size = int(size, 16)
512 section.align = 2**int(align[3:])
513 section.fileid = fileid
514 section.relocs = []
515 sections.append(section)
516 sectionmap[name] = section
517 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400518 pass
519 continue
520 if state == 'symbol':
521 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400522 sectionname, size, name = line[17:].split()
523 symbol = Symbol()
524 symbol.size = int(size, 16)
525 symbol.offset = int(line[:8], 16)
526 symbol.name = name
527 symbol.section = sectionmap.get(sectionname)
528 symbols[name] = symbol
529 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400530 pass
531 continue
532 if state == 'reloc':
533 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400534 off, type, symbolname = line.split()
535 reloc = Reloc()
536 reloc.offset = int(off, 16)
537 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500538 reloc.symbolname = symbolname
Kevin O'Connor67863be2010-12-24 10:23:10 -0500539 reloc.symbol = symbols.get(symbolname)
540 if reloc.symbol is None:
541 # Some binutils (2.20.1) give section name instead
542 # of a symbol - create a dummy symbol.
543 reloc.symbol = symbol = Symbol()
544 symbol.size = 0
545 symbol.offset = 0
546 symbol.name = symbolname
547 symbol.section = sectionmap.get(symbolname)
548 symbols[symbolname] = symbol
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400549 relocsection.relocs.append(reloc)
550 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400551 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400552 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400553
554def main():
555 # Get output name
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500556 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400557
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400558 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400559 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500560 infile32seg = open(in32seg, 'rb')
561 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400562
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400563 # infoX = (sections, symbols)
564 info16 = parseObjDump(infile16, '16')
565 info32seg = parseObjDump(infile32seg, '32seg')
566 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400567
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400568 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400569 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400570
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400571 # Separate 32bit flat into runtime and init parts
572 findInit(sections)
573
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400574 # Determine the final memory locations of each kept section.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400575 doLayout(sections)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400576
577 # Write out linker script files.
Kevin O'Connor47c8e312011-07-10 22:57:32 -0400578 entrysym = info16[1]['entry_elf']
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400579 genreloc = '_reloc_abs_start' in info32flat[1]
580 writeLinkerScripts(sections, entrysym, genreloc, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400581
Kevin O'Connor202024a2009-01-17 10:41:28 -0500582if __name__ == '__main__':
583 main()