blob: 74b410f4663aec799332f8d7d0d6c6f3432cdd7f [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'Connor46b82622012-05-13 12:10:30 -040043def setSectionsStart(sections, endaddr, minalign=1, segoffset=0):
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
Kevin O'Connor46b82622012-05-13 12:10:30 -040056 section.finalsegloc = curaddr - segoffset
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040057 curaddr += section.size
Kevin O'Connor46b82622012-05-13 12:10:30 -040058 return startaddr, minalign
Kevin O'Connorc0693942009-06-10 21:56:01 -040059
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040060# The 16bit code can't exceed 64K of space.
61BUILD_BIOS_ADDR = 0xf0000
62BUILD_BIOS_SIZE = 0x10000
Kevin O'Connor46b82622012-05-13 12:10:30 -040063BUILD_ROM_START = 0xc0000
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040064
65# Layout the 16bit code. This ensures sections with fixed offset
66# requirements are placed in the correct location. It also places the
67# 16bit code as high as possible in the f-segment.
68def fitSections(sections, fillsections):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040069 # fixedsections = [(addr, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040070 fixedsections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040071 for section in sections:
72 if section.name.startswith('.fixedaddr.'):
73 addr = int(section.name[11:], 16)
Kevin O'Connor46b82622012-05-13 12:10:30 -040074 section.finalloc = addr + BUILD_BIOS_ADDR
75 section.finalsegloc = addr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040076 fixedsections.append((addr, section))
77 if section.align != 1:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040078 print "Error: Fixed section %s has non-zero alignment (%d)" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040079 section.name, section.align)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040080 sys.exit(1)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040081 fixedsections.sort()
82 firstfixed = fixedsections[0][0]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040083
84 # Find freespace in fixed address area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040085 # fixedAddr = [(freespace, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040086 fixedAddr = []
87 for i in range(len(fixedsections)):
88 fixedsectioninfo = fixedsections[i]
89 addr, section = fixedsectioninfo
90 if i == len(fixedsections) - 1:
91 nextaddr = BUILD_BIOS_SIZE
92 else:
93 nextaddr = fixedsections[i+1][0]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040094 avail = nextaddr - addr - section.size
95 fixedAddr.append((avail, section))
96 fixedAddr.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040097
98 # Attempt to fit other sections into fixed area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040099 canrelocate = [(section.size, section.align, section.name, section)
100 for section in fillsections]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400101 canrelocate.sort()
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400102 canrelocate = [section for size, align, name, section in canrelocate]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400103 totalused = 0
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400104 for freespace, fixedsection in fixedAddr:
Kevin O'Connor46b82622012-05-13 12:10:30 -0400105 addpos = fixedsection.finalsegloc + fixedsection.size
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400106 totalused += fixedsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400107 nextfixedaddr = addpos + freespace
108# print "Filling section %x uses %d, next=%x, available=%d" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400109# fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400110 while 1:
111 canfit = None
112 for fitsection in canrelocate:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400113 if addpos + fitsection.size > nextfixedaddr:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400114 # Can't fit and nothing else will fit.
115 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400116 fitnextaddr = alignpos(addpos, fitsection.align) + fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400117# print "Test %s - %x vs %x" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400118# fitsection.name, fitnextaddr, nextfixedaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400119 if fitnextaddr > nextfixedaddr:
120 # This item can't fit.
121 continue
122 canfit = (fitnextaddr, fitsection)
123 if canfit is None:
124 break
125 # Found a section that can fit.
126 fitnextaddr, fitsection = canfit
127 canrelocate.remove(fitsection)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400128 fitsection.finalloc = addpos + BUILD_BIOS_ADDR
129 fitsection.finalsegloc = addpos
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400130 addpos = fitnextaddr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400131 totalused += fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400132# print " Adding %s (size %d align %d) pos=%x avail=%d" % (
133# fitsection[2], fitsection[0], fitsection[1]
134# , fitnextaddr, nextfixedaddr - fitnextaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400135
136 # Report stats
137 total = BUILD_BIOS_SIZE-firstfixed
138 slack = total - totalused
139 print ("Fixed space: 0x%x-0x%x total: %d slack: %d"
140 " Percent slack: %.1f%%" % (
141 firstfixed, BUILD_BIOS_SIZE, total, slack,
142 (float(slack) / total) * 100.0))
143
Kevin O'Connor46b82622012-05-13 12:10:30 -0400144 return firstfixed + BUILD_BIOS_ADDR
145
146# Return the subset of sections with a given category
147def getSectionsCategory(sections, category):
148 return [section for section in sections if section.category == category]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400149
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400150# Return the subset of sections with a given name prefix
Kevin O'Connor46b82622012-05-13 12:10:30 -0400151def getSectionsPrefix(sections, prefix):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400152 return [section for section in sections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400153 if section.name.startswith(prefix)]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400154
Kevin O'Connor46b82622012-05-13 12:10:30 -0400155# The sections (and associated information) to be placed in output rom
156class LayoutInfo:
157 sections16 = sec16_start = sec16_align = None
158 sections32seg = sec32seg_start = sec32seg_align = None
159 sections32flat = sec32flat_start = sec32flat_align = None
160 sections32init = sec32init_start = sec32init_align = None
161 sections32low = sec32low_start = sec32low_align = None
162 datalow_base = None
163
164# Determine final memory addresses for sections
165def doLayout(sections, genreloc):
166 li = LayoutInfo()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400167 # Determine 16bit positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400168 li.sections16 = getSectionsCategory(sections, '16')
169 textsections = getSectionsPrefix(li.sections16, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500170 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400171 getSectionsPrefix(li.sections16, '.rodata.str1.1')
172 + getSectionsPrefix(li.sections16, '.rodata.__func__.')
173 + getSectionsPrefix(li.sections16, '.rodata.__PRETTY_FUNCTION__.'))
174 datasections = getSectionsPrefix(li.sections16, '.data16.')
175 fixedsections = getSectionsPrefix(li.sections16, '.fixedaddr.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400176
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400177 firstfixed = fitSections(fixedsections, textsections)
178 remsections = [s for s in textsections+rodatasections+datasections
179 if s.finalloc is None]
Kevin O'Connor46b82622012-05-13 12:10:30 -0400180 li.sec16_start, li.sec16_align = setSectionsStart(
181 remsections, firstfixed, segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400182
183 # Determine 32seg positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400184 li.sections32seg = getSectionsCategory(sections, '32seg')
185 textsections = getSectionsPrefix(li.sections32seg, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500186 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400187 getSectionsPrefix(li.sections32seg, '.rodata.str1.1')
188 + getSectionsPrefix(li.sections32seg, '.rodata.__func__.')
189 + getSectionsPrefix(li.sections32seg, '.rodata.__PRETTY_FUNCTION__.'))
190 datasections = getSectionsPrefix(li.sections32seg, '.data32seg.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400191
Kevin O'Connor46b82622012-05-13 12:10:30 -0400192 li.sec32seg_start, li.sec32seg_align = setSectionsStart(
193 textsections + rodatasections + datasections, li.sec16_start
194 , segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400195
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400196 # Determine 32flat runtime positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400197 li.sections32flat = getSectionsCategory(sections, '32flat')
198 textsections = getSectionsPrefix(li.sections32flat, '.text.')
199 rodatasections = getSectionsPrefix(li.sections32flat, '.rodata')
200 datasections = getSectionsPrefix(li.sections32flat, '.data.')
201 bsssections = getSectionsPrefix(li.sections32flat, '.bss.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400202
Kevin O'Connor46b82622012-05-13 12:10:30 -0400203 li.sec32flat_start, li.sec32flat_align = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400204 textsections + rodatasections + datasections + bsssections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400205 , li.sec32seg_start, 16)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400206
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400207 # Determine 32flat init positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400208 li.sections32init = getSectionsCategory(sections, '32init')
209 textsections = getSectionsPrefix(li.sections32init, '.text.')
210 rodatasections = getSectionsPrefix(li.sections32init, '.rodata')
211 datasections = getSectionsPrefix(li.sections32init, '.data.')
212 bsssections = getSectionsPrefix(li.sections32init, '.bss.')
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400213
Kevin O'Connor46b82622012-05-13 12:10:30 -0400214 li.sec32init_start, li.sec32init_align = setSectionsStart(
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400215 textsections + rodatasections + datasections + bsssections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400216 , li.sec32flat_start, 16)
217
218 # Determine "low memory" data positions
219 li.sections32low = getSectionsCategory(sections, '32low')
220 if genreloc:
221 sec32low_top = li.sec32init_start
222 datalow_base = min(BUILD_BIOS_ADDR, li.sec32flat_start) - 64*1024
223 else:
224 sec32low_top = min(BUILD_BIOS_ADDR, li.sec32init_start)
225 datalow_base = sec32low_top - 64*1024
226 li.datalow_base = max(BUILD_ROM_START, alignpos(datalow_base, 2*1024))
227 li.sec32low_start, li.sec32low_align = setSectionsStart(
228 li.sections32low, sec32low_top, 16, segoffset=li.datalow_base)
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400229
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400230 # Print statistics
Kevin O'Connor46b82622012-05-13 12:10:30 -0400231 size16 = BUILD_BIOS_ADDR + BUILD_BIOS_SIZE - li.sec16_start
232 size32seg = li.sec16_start - li.sec32seg_start
233 size32flat = li.sec32seg_start - li.sec32flat_start
234 size32init = li.sec32flat_start - li.sec32init_start
235 sizelow = sec32low_top - li.sec32low_start
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400236 print "16bit size: %d" % size16
237 print "32bit segmented size: %d" % size32seg
238 print "32bit flat size: %d" % size32flat
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400239 print "32bit flat init size: %d" % size32init
Kevin O'Connor46b82622012-05-13 12:10:30 -0400240 print "Lowmem size: %d" % sizelow
241 return li
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400242
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400243
244######################################################################
245# Linker script output
246######################################################################
247
248# Write LD script includes for the given cross references
Kevin O'Connor46b82622012-05-13 12:10:30 -0400249def outXRefs(sections, useseg=0):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400250 xrefs = {}
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400251 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400252 for section in sections:
253 for reloc in section.relocs:
254 symbol = reloc.symbol
255 if (symbol.section is None
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500256 or (symbol.section.fileid == section.fileid
257 and symbol.name == reloc.symbolname)
258 or reloc.symbolname in xrefs):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400259 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500260 xrefs[reloc.symbolname] = 1
Kevin O'Connor46b82622012-05-13 12:10:30 -0400261 loc = symbol.section.finalloc
262 if useseg:
263 loc = symbol.section.finalsegloc
264 out += "%s = 0x%x ;\n" % (reloc.symbolname, loc + symbol.offset)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400265 return out
266
267# Write LD script includes for the given sections using relative offsets
Kevin O'Connor46b82622012-05-13 12:10:30 -0400268def outRelSections(sections, startsym, useseg=0):
269 sections = [(section.finalloc, section) for section in sections
270 if section.finalloc is not None]
271 sections.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400272 out = ""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400273 for addr, section in sections:
274 loc = section.finalloc
275 if useseg:
276 loc = section.finalsegloc
277 out += ". = ( 0x%x - %s ) ;\n" % (loc, startsym)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400278 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400279 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400280 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400281 return out
282
Kevin O'Connor46b82622012-05-13 12:10:30 -0400283# Build linker script output for a list of relocations.
284def strRelocs(outname, outrel, relocs):
285 relocs.sort()
286 return (" %s_start = ABSOLUTE(.) ;\n" % (outname,)
287 + "".join(["LONG(0x%x - %s)\n" % (pos, outrel)
288 for pos in relocs])
289 + " %s_end = ABSOLUTE(.) ;\n" % (outname,))
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500290
Kevin O'Connor46b82622012-05-13 12:10:30 -0400291# Find all relocations in the given sections with the given attributes
292def getRelocs(sections, type=None, category=None, notcategory=None):
293 out = []
294 for section in sections:
295 for reloc in section.relocs:
296 if reloc.symbol.section is None:
297 continue
298 destcategory = reloc.symbol.section.category
299 if ((type is None or reloc.type == type)
300 and (category is None or destcategory == category)
301 and (notcategory is None or destcategory != notcategory)):
302 out.append(section.finalloc + reloc.offset)
303 return out
304
305# Return the start address and minimum alignment for a set of sections
306def getSectionsStart(sections, defaddr=0):
307 return min([section.finalloc for section in sections
308 if section.finalloc is not None] or [defaddr])
309
310# Output the linker scripts for all required sections.
311def writeLinkerScripts(li, entrysym, genreloc, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400312 # Write 16bit linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400313 out = outXRefs(li.sections16, useseg=1) + """
314 _datalow_base = 0x%x ;
315 _datalow_seg = 0x%x ;
316
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400317 code16_start = 0x%x ;
318 .text16 code16_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400319%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400320 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400321""" % (li.datalow_base,
322 li.datalow_base / 16,
323 li.sec16_start - BUILD_BIOS_ADDR,
324 outRelSections(li.sections16, 'code16_start', useseg=1))
325 outfile = open(out16, 'wb')
326 outfile.write(COMMONHEADER + out + COMMONTRAILER)
327 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500328
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400329 # Write 32seg linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400330 out = outXRefs(li.sections32seg, useseg=1) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400331 code32seg_start = 0x%x ;
332 .text32seg code32seg_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400333%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400334 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400335""" % (li.sec32seg_start - BUILD_BIOS_ADDR,
336 outRelSections(li.sections32seg, 'code32seg_start', useseg=1))
337 outfile = open(out32seg, 'wb')
338 outfile.write(COMMONHEADER + out + COMMONTRAILER)
339 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500340
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400341 # Write 32flat linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400342 sections32all = li.sections32flat + li.sections32init + li.sections32low
343 sec32all_start = li.sec32low_start
344 entrysympos = entrysym.section.finalloc + entrysym.offset
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400345 relocstr = ""
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400346 if genreloc:
347 # Generate relocations
Kevin O'Connor46b82622012-05-13 12:10:30 -0400348 absrelocs = getRelocs(
349 li.sections32init, type='R_386_32', category='32init')
350 relrelocs = getRelocs(
351 li.sections32init, type='R_386_PC32', notcategory='32init')
352 initrelocs = getRelocs(
353 li.sections32flat + li.sections32low + li.sections16
354 + li.sections32seg, category='32init')
355 lowrelocs = getRelocs(
356 li.sections16 + li.sections32seg + sections32all, category='32low')
357 relocstr = (strRelocs("_reloc_abs", "code32init_start", absrelocs)
358 + strRelocs("_reloc_rel", "code32init_start", relrelocs)
359 + strRelocs("_reloc_init", "code32flat_start", initrelocs)
360 + strRelocs("_reloc_datalow", "code32flat_start", lowrelocs))
361 numrelocs = len(absrelocs + relrelocs + initrelocs + lowrelocs)
362 sec32all_start -= numrelocs * 4
363 out = outXRefs(sections32all) + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400364 %s = 0x%x ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400365 _reloc_min_align = 0x%x ;
Kevin O'Connor5e019082012-05-20 21:11:43 -0400366 _datalow_base = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400367 _datalow_min_align = 0x%x ;
368
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400369 code32flat_start = 0x%x ;
370 .text code32flat_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400371%s
372 datalow_start = ABSOLUTE(.) ;
373%s
374 datalow_end = ABSOLUTE(.) ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400375 code32init_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400376%s
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400377 code32init_end = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400378%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400379 . = ( 0x%x - code32flat_start ) ;
380 *(.text32seg)
381 . = ( 0x%x - code32flat_start ) ;
382 *(.text16)
383 code32flat_end = ABSOLUTE(.) ;
384 } :text
Kevin O'Connor46b82622012-05-13 12:10:30 -0400385""" % (entrysym.name, entrysympos,
386 li.sec32init_align,
Kevin O'Connor5e019082012-05-20 21:11:43 -0400387 li.datalow_base,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400388 li.sec32low_align,
389 sec32all_start,
390 relocstr,
391 outRelSections(li.sections32low, 'code32flat_start'),
392 outRelSections(li.sections32init, 'code32flat_start'),
393 outRelSections(li.sections32flat, 'code32flat_start'),
394 li.sec32seg_start,
395 li.sec16_start)
396 out = COMMONHEADER + out + COMMONTRAILER + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400397ENTRY(%s)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400398PHDRS
399{
400 text PT_LOAD AT ( code32flat_start ) ;
401}
Kevin O'Connor46b82622012-05-13 12:10:30 -0400402""" % (entrysym.name,)
403 outfile = open(out32flat, 'wb')
404 outfile.write(out)
405 outfile.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400406
407
408######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400409# Detection of init code
410######################################################################
411
412def markRuntime(section, sections):
413 if (section is None or not section.keep or section.category is not None
414 or '.init.' in section.name or section.fileid != '32flat'):
415 return
416 section.category = '32flat'
417 # Recursively mark all sections this section points to
418 for reloc in section.relocs:
419 markRuntime(reloc.symbol.section, sections)
420
421def findInit(sections):
422 # Recursively find and mark all "runtime" sections.
423 for section in sections:
Kevin O'Connor46b82622012-05-13 12:10:30 -0400424 if ('.datalow.' in section.name or '.runtime.' in section.name
425 or '.export.' in section.name):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400426 markRuntime(section, sections)
427 for section in sections:
428 if section.category is not None:
429 continue
430 if section.fileid == '32flat':
431 section.category = '32init'
432 else:
433 section.category = section.fileid
434
435
436######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400437# Section garbage collection
438######################################################################
439
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500440CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
441
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500442# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500443def keepsymbol(reloc, infos, pos, isxref):
444 symbolname = reloc.symbolname
445 mustbecfunc = 0
446 for symprefix, needpos in CFUNCPREFIX:
447 if symbolname.startswith(symprefix):
448 if needpos != pos:
449 return -1
450 symbolname = symbolname[len(symprefix):]
451 mustbecfunc = 1
452 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400453 symbol = infos[pos][1].get(symbolname)
454 if (symbol is None or symbol.section is None
455 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500456 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500457 isdestcfunc = (symbol.section.name.startswith('.text.')
458 and not symbol.section.name.startswith('.text.asm.'))
459 if ((mustbecfunc and not isdestcfunc)
460 or (not mustbecfunc and isdestcfunc and isxref)):
461 return -1
462
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400463 reloc.symbol = symbol
464 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500465 return 0
466
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400467# Note required section, and recursively set all referenced sections
468# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400469def keepsection(section, infos, pos=0):
470 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400471 # Already kept - nothing to do.
472 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400473 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400474 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400475 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500476 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500477 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400478 continue
479 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500480 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500481 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500482 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500483 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500484 if not ret:
485 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400486
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400487# Determine which sections are actually referenced and need to be
488# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500489def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400490 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
491 # , (sect32flat, sym32flat))
492 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400493 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400494 for section in info16[0]:
495 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500496 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400497 return [section for section in info16[0]+info32seg[0]+info32flat[0]
498 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400499
500
501######################################################################
502# Startup and input parsing
503######################################################################
504
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400505class Section:
506 name = size = alignment = fileid = relocs = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400507 finalloc = finalsegloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400508class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500509 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400510class Symbol:
511 name = offset = section = None
512
Kevin O'Connorc0693942009-06-10 21:56:01 -0400513# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400514def parseObjDump(file, fileid):
515 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400516 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400517 sectionmap = {}
518 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400519 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400520
521 state = None
522 for line in file.readlines():
523 line = line.rstrip()
524 if line == 'Sections:':
525 state = 'section'
526 continue
527 if line == 'SYMBOL TABLE:':
528 state = 'symbol'
529 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400530 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400531 sectionname = line[24:-2]
532 if sectionname.startswith('.debug_'):
533 # Skip debugging sections (to reduce parsing time)
534 state = None
535 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400536 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400537 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400538 continue
539
540 if state == 'section':
541 try:
542 idx, name, size, vma, lma, fileoff, align = line.split()
543 if align[:3] != '2**':
544 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400545 section = Section()
546 section.name = name
547 section.size = int(size, 16)
548 section.align = 2**int(align[3:])
549 section.fileid = fileid
550 section.relocs = []
551 sections.append(section)
552 sectionmap[name] = section
553 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400554 pass
555 continue
556 if state == 'symbol':
557 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400558 sectionname, size, name = line[17:].split()
559 symbol = Symbol()
560 symbol.size = int(size, 16)
561 symbol.offset = int(line[:8], 16)
562 symbol.name = name
563 symbol.section = sectionmap.get(sectionname)
564 symbols[name] = symbol
565 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400566 pass
567 continue
568 if state == 'reloc':
569 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400570 off, type, symbolname = line.split()
571 reloc = Reloc()
572 reloc.offset = int(off, 16)
573 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500574 reloc.symbolname = symbolname
Kevin O'Connor67863be2010-12-24 10:23:10 -0500575 reloc.symbol = symbols.get(symbolname)
576 if reloc.symbol is None:
577 # Some binutils (2.20.1) give section name instead
578 # of a symbol - create a dummy symbol.
579 reloc.symbol = symbol = Symbol()
580 symbol.size = 0
581 symbol.offset = 0
582 symbol.name = symbolname
583 symbol.section = sectionmap.get(symbolname)
584 symbols[symbolname] = symbol
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400585 relocsection.relocs.append(reloc)
586 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400587 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400588 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400589
590def main():
591 # Get output name
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500592 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400593
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400594 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400595 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500596 infile32seg = open(in32seg, 'rb')
597 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400598
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400599 # infoX = (sections, symbols)
600 info16 = parseObjDump(infile16, '16')
601 info32seg = parseObjDump(infile32seg, '32seg')
602 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400603
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400604 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400605 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400606
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400607 # Separate 32bit flat into runtime and init parts
608 findInit(sections)
609
Kevin O'Connor46b82622012-05-13 12:10:30 -0400610 # Note "low memory" parts
611 for section in getSectionsPrefix(sections, '.datalow.'):
612 section.category = '32low'
613
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400614 # Determine the final memory locations of each kept section.
Kevin O'Connor46b82622012-05-13 12:10:30 -0400615 genreloc = '_reloc_abs_start' in info32flat[1]
616 li = doLayout(sections, genreloc)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400617
618 # Write out linker script files.
Kevin O'Connor47c8e312011-07-10 22:57:32 -0400619 entrysym = info16[1]['entry_elf']
Kevin O'Connor46b82622012-05-13 12:10:30 -0400620 writeLinkerScripts(li, entrysym, genreloc, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400621
Kevin O'Connor202024a2009-01-17 10:41:28 -0500622if __name__ == '__main__':
623 main()