blob: 7a7d08c20a2087a47c2b62e61b9f48e9572b9351 [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
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040051 for section in sections:
52 curaddr = alignpos(curaddr, section.align)
53 section.finalloc = curaddr
Kevin O'Connor46b82622012-05-13 12:10:30 -040054 section.finalsegloc = curaddr - segoffset
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040055 curaddr += section.size
Kevin O'Connor46b82622012-05-13 12:10:30 -040056 return startaddr, minalign
Kevin O'Connorc0693942009-06-10 21:56:01 -040057
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040058# The 16bit code can't exceed 64K of space.
59BUILD_BIOS_ADDR = 0xf0000
60BUILD_BIOS_SIZE = 0x10000
Kevin O'Connor46b82622012-05-13 12:10:30 -040061BUILD_ROM_START = 0xc0000
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040062
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)
Kevin O'Connor46b82622012-05-13 12:10:30 -040072 section.finalloc = addr + BUILD_BIOS_ADDR
73 section.finalsegloc = addr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040074 fixedsections.append((addr, section))
75 if section.align != 1:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040076 print "Error: Fixed section %s has non-zero alignment (%d)" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040077 section.name, section.align)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040078 sys.exit(1)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040079 fixedsections.sort()
80 firstfixed = fixedsections[0][0]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040081
82 # Find freespace in fixed address area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040083 # fixedAddr = [(freespace, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040084 fixedAddr = []
85 for i in range(len(fixedsections)):
86 fixedsectioninfo = fixedsections[i]
87 addr, section = fixedsectioninfo
88 if i == len(fixedsections) - 1:
89 nextaddr = BUILD_BIOS_SIZE
90 else:
91 nextaddr = fixedsections[i+1][0]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040092 avail = nextaddr - addr - section.size
93 fixedAddr.append((avail, section))
94 fixedAddr.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040095
96 # Attempt to fit other sections into fixed area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040097 canrelocate = [(section.size, section.align, section.name, section)
98 for section in fillsections]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040099 canrelocate.sort()
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400100 canrelocate = [section for size, align, name, section in canrelocate]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400101 totalused = 0
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400102 for freespace, fixedsection in fixedAddr:
Kevin O'Connor46b82622012-05-13 12:10:30 -0400103 addpos = fixedsection.finalsegloc + fixedsection.size
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400104 totalused += fixedsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400105 nextfixedaddr = addpos + freespace
106# print "Filling section %x uses %d, next=%x, available=%d" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400107# fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400108 while 1:
109 canfit = None
110 for fitsection in canrelocate:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400111 if addpos + fitsection.size > nextfixedaddr:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400112 # Can't fit and nothing else will fit.
113 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400114 fitnextaddr = alignpos(addpos, fitsection.align) + fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400115# print "Test %s - %x vs %x" % (
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400116# fitsection.name, fitnextaddr, nextfixedaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400117 if fitnextaddr > nextfixedaddr:
118 # This item can't fit.
119 continue
120 canfit = (fitnextaddr, fitsection)
121 if canfit is None:
122 break
123 # Found a section that can fit.
124 fitnextaddr, fitsection = canfit
125 canrelocate.remove(fitsection)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400126 fitsection.finalloc = addpos + BUILD_BIOS_ADDR
127 fitsection.finalsegloc = addpos
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400128 addpos = fitnextaddr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400129 totalused += fitsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400130# print " Adding %s (size %d align %d) pos=%x avail=%d" % (
131# fitsection[2], fitsection[0], fitsection[1]
132# , fitnextaddr, nextfixedaddr - fitnextaddr)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400133
134 # Report stats
135 total = BUILD_BIOS_SIZE-firstfixed
136 slack = total - totalused
137 print ("Fixed space: 0x%x-0x%x total: %d slack: %d"
138 " Percent slack: %.1f%%" % (
139 firstfixed, BUILD_BIOS_SIZE, total, slack,
140 (float(slack) / total) * 100.0))
141
Kevin O'Connor46b82622012-05-13 12:10:30 -0400142 return firstfixed + BUILD_BIOS_ADDR
143
144# Return the subset of sections with a given category
145def getSectionsCategory(sections, category):
146 return [section for section in sections if section.category == category]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400147
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400148# Return the subset of sections with a given name prefix
Kevin O'Connor46b82622012-05-13 12:10:30 -0400149def getSectionsPrefix(sections, prefix):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400150 return [section for section in sections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400151 if section.name.startswith(prefix)]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400152
Kevin O'Connor46b82622012-05-13 12:10:30 -0400153# The sections (and associated information) to be placed in output rom
154class LayoutInfo:
155 sections16 = sec16_start = sec16_align = None
156 sections32seg = sec32seg_start = sec32seg_align = None
157 sections32flat = sec32flat_start = sec32flat_align = None
158 sections32init = sec32init_start = sec32init_align = None
159 sections32low = sec32low_start = sec32low_align = None
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400160 datalow_base = final_sec32low_start = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400161
162# Determine final memory addresses for sections
163def doLayout(sections, genreloc):
164 li = LayoutInfo()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400165 # Determine 16bit positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400166 li.sections16 = getSectionsCategory(sections, '16')
167 textsections = getSectionsPrefix(li.sections16, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500168 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400169 getSectionsPrefix(li.sections16, '.rodata.str1.1')
170 + getSectionsPrefix(li.sections16, '.rodata.__func__.')
171 + getSectionsPrefix(li.sections16, '.rodata.__PRETTY_FUNCTION__.'))
172 datasections = getSectionsPrefix(li.sections16, '.data16.')
173 fixedsections = getSectionsPrefix(li.sections16, '.fixedaddr.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400174
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400175 firstfixed = fitSections(fixedsections, textsections)
176 remsections = [s for s in textsections+rodatasections+datasections
177 if s.finalloc is None]
Kevin O'Connor46b82622012-05-13 12:10:30 -0400178 li.sec16_start, li.sec16_align = setSectionsStart(
179 remsections, firstfixed, segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400180
181 # Determine 32seg positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400182 li.sections32seg = getSectionsCategory(sections, '32seg')
183 textsections = getSectionsPrefix(li.sections32seg, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500184 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400185 getSectionsPrefix(li.sections32seg, '.rodata.str1.1')
186 + getSectionsPrefix(li.sections32seg, '.rodata.__func__.')
187 + getSectionsPrefix(li.sections32seg, '.rodata.__PRETTY_FUNCTION__.'))
188 datasections = getSectionsPrefix(li.sections32seg, '.data32seg.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400189
Kevin O'Connor46b82622012-05-13 12:10:30 -0400190 li.sec32seg_start, li.sec32seg_align = setSectionsStart(
191 textsections + rodatasections + datasections, li.sec16_start
192 , segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400193
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400194 # Determine 32flat runtime positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400195 li.sections32flat = getSectionsCategory(sections, '32flat')
196 textsections = getSectionsPrefix(li.sections32flat, '.text.')
197 rodatasections = getSectionsPrefix(li.sections32flat, '.rodata')
198 datasections = getSectionsPrefix(li.sections32flat, '.data.')
199 bsssections = getSectionsPrefix(li.sections32flat, '.bss.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400200
Kevin O'Connor46b82622012-05-13 12:10:30 -0400201 li.sec32flat_start, li.sec32flat_align = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400202 textsections + rodatasections + datasections + bsssections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400203 , li.sec32seg_start, 16)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400204
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400205 # Determine 32flat init positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400206 li.sections32init = getSectionsCategory(sections, '32init')
207 textsections = getSectionsPrefix(li.sections32init, '.text.')
208 rodatasections = getSectionsPrefix(li.sections32init, '.rodata')
209 datasections = getSectionsPrefix(li.sections32init, '.data.')
210 bsssections = getSectionsPrefix(li.sections32init, '.bss.')
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400211
Kevin O'Connor46b82622012-05-13 12:10:30 -0400212 li.sec32init_start, li.sec32init_align = setSectionsStart(
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400213 textsections + rodatasections + datasections + bsssections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400214 , li.sec32flat_start, 16)
215
216 # Determine "low memory" data positions
217 li.sections32low = getSectionsCategory(sections, '32low')
218 if genreloc:
219 sec32low_top = li.sec32init_start
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400220 final_sec32low_top = min(BUILD_BIOS_ADDR, li.sec32flat_start)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400221 else:
222 sec32low_top = min(BUILD_BIOS_ADDR, li.sec32init_start)
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400223 final_sec32low_top = sec32low_top
224 relocdelta = final_sec32low_top - sec32low_top
225 datalow_base = final_sec32low_top - 64*1024
Kevin O'Connor46b82622012-05-13 12:10:30 -0400226 li.datalow_base = max(BUILD_ROM_START, alignpos(datalow_base, 2*1024))
227 li.sec32low_start, li.sec32low_align = setSectionsStart(
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400228 li.sections32low, sec32low_top, 16
229 , segoffset=li.datalow_base - relocdelta)
230 li.final_sec32low_start = li.sec32low_start + relocdelta
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400231
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400232 # Print statistics
Kevin O'Connor46b82622012-05-13 12:10:30 -0400233 size16 = BUILD_BIOS_ADDR + BUILD_BIOS_SIZE - li.sec16_start
234 size32seg = li.sec16_start - li.sec32seg_start
235 size32flat = li.sec32seg_start - li.sec32flat_start
236 size32init = li.sec32flat_start - li.sec32init_start
237 sizelow = sec32low_top - li.sec32low_start
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400238 print "16bit size: %d" % size16
239 print "32bit segmented size: %d" % size32seg
240 print "32bit flat size: %d" % size32flat
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400241 print "32bit flat init size: %d" % size32init
Kevin O'Connor46b82622012-05-13 12:10:30 -0400242 print "Lowmem size: %d" % sizelow
243 return li
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400244
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400245
246######################################################################
247# Linker script output
248######################################################################
249
250# Write LD script includes for the given cross references
Kevin O'Connor46b82622012-05-13 12:10:30 -0400251def outXRefs(sections, useseg=0):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400252 xrefs = {}
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400253 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400254 for section in sections:
255 for reloc in section.relocs:
256 symbol = reloc.symbol
257 if (symbol.section is None
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500258 or (symbol.section.fileid == section.fileid
259 and symbol.name == reloc.symbolname)
260 or reloc.symbolname in xrefs):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400261 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500262 xrefs[reloc.symbolname] = 1
Kevin O'Connor46b82622012-05-13 12:10:30 -0400263 loc = symbol.section.finalloc
264 if useseg:
265 loc = symbol.section.finalsegloc
266 out += "%s = 0x%x ;\n" % (reloc.symbolname, loc + symbol.offset)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400267 return out
268
269# Write LD script includes for the given sections using relative offsets
Kevin O'Connor46b82622012-05-13 12:10:30 -0400270def outRelSections(sections, startsym, useseg=0):
271 sections = [(section.finalloc, section) for section in sections
272 if section.finalloc is not None]
273 sections.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400274 out = ""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400275 for addr, section in sections:
276 loc = section.finalloc
277 if useseg:
278 loc = section.finalsegloc
279 out += ". = ( 0x%x - %s ) ;\n" % (loc, startsym)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400280 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400281 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400282 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400283 return out
284
Kevin O'Connor46b82622012-05-13 12:10:30 -0400285# Build linker script output for a list of relocations.
286def strRelocs(outname, outrel, relocs):
287 relocs.sort()
288 return (" %s_start = ABSOLUTE(.) ;\n" % (outname,)
289 + "".join(["LONG(0x%x - %s)\n" % (pos, outrel)
290 for pos in relocs])
291 + " %s_end = ABSOLUTE(.) ;\n" % (outname,))
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500292
Kevin O'Connor46b82622012-05-13 12:10:30 -0400293# Find all relocations in the given sections with the given attributes
294def getRelocs(sections, type=None, category=None, notcategory=None):
295 out = []
296 for section in sections:
297 for reloc in section.relocs:
298 if reloc.symbol.section is None:
299 continue
300 destcategory = reloc.symbol.section.category
301 if ((type is None or reloc.type == type)
302 and (category is None or destcategory == category)
303 and (notcategory is None or destcategory != notcategory)):
304 out.append(section.finalloc + reloc.offset)
305 return out
306
307# Return the start address and minimum alignment for a set of sections
308def getSectionsStart(sections, defaddr=0):
309 return min([section.finalloc for section in sections
310 if section.finalloc is not None] or [defaddr])
311
312# Output the linker scripts for all required sections.
313def writeLinkerScripts(li, entrysym, genreloc, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400314 # Write 16bit linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400315 out = outXRefs(li.sections16, useseg=1) + """
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400316 datalow_base = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400317 _datalow_seg = 0x%x ;
318
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400319 code16_start = 0x%x ;
320 .text16 code16_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400321%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400322 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400323""" % (li.datalow_base,
324 li.datalow_base / 16,
325 li.sec16_start - BUILD_BIOS_ADDR,
326 outRelSections(li.sections16, 'code16_start', useseg=1))
327 outfile = open(out16, 'wb')
328 outfile.write(COMMONHEADER + out + COMMONTRAILER)
329 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500330
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400331 # Write 32seg linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400332 out = outXRefs(li.sections32seg, useseg=1) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400333 code32seg_start = 0x%x ;
334 .text32seg code32seg_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400335%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400336 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400337""" % (li.sec32seg_start - BUILD_BIOS_ADDR,
338 outRelSections(li.sections32seg, 'code32seg_start', useseg=1))
339 outfile = open(out32seg, 'wb')
340 outfile.write(COMMONHEADER + out + COMMONTRAILER)
341 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500342
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400343 # Write 32flat linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400344 sections32all = li.sections32flat + li.sections32init + li.sections32low
345 sec32all_start = li.sec32low_start
346 entrysympos = entrysym.section.finalloc + entrysym.offset
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400347 relocstr = ""
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400348 if genreloc:
349 # Generate relocations
Kevin O'Connor46b82622012-05-13 12:10:30 -0400350 absrelocs = getRelocs(
351 li.sections32init, type='R_386_32', category='32init')
352 relrelocs = getRelocs(
353 li.sections32init, type='R_386_PC32', notcategory='32init')
354 initrelocs = getRelocs(
355 li.sections32flat + li.sections32low + li.sections16
356 + li.sections32seg, category='32init')
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400357 lowrelocs = getRelocs(sections32all, category='32low')
Kevin O'Connor46b82622012-05-13 12:10:30 -0400358 relocstr = (strRelocs("_reloc_abs", "code32init_start", absrelocs)
359 + strRelocs("_reloc_rel", "code32init_start", relrelocs)
360 + strRelocs("_reloc_init", "code32flat_start", initrelocs)
361 + strRelocs("_reloc_datalow", "code32flat_start", lowrelocs))
362 numrelocs = len(absrelocs + relrelocs + initrelocs + lowrelocs)
363 sec32all_start -= numrelocs * 4
364 out = outXRefs(sections32all) + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400365 %s = 0x%x ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400366 _reloc_min_align = 0x%x ;
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400367 datalow_base = 0x%x ;
368 final_datalow_start = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400369
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400370 code32flat_start = 0x%x ;
371 .text code32flat_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400372%s
373 datalow_start = ABSOLUTE(.) ;
374%s
375 datalow_end = ABSOLUTE(.) ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400376 code32init_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400377%s
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400378 code32init_end = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400379%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400380 . = ( 0x%x - code32flat_start ) ;
381 *(.text32seg)
382 . = ( 0x%x - code32flat_start ) ;
383 *(.text16)
384 code32flat_end = ABSOLUTE(.) ;
385 } :text
Kevin O'Connor46b82622012-05-13 12:10:30 -0400386""" % (entrysym.name, entrysympos,
387 li.sec32init_align,
Kevin O'Connor5e019082012-05-20 21:11:43 -0400388 li.datalow_base,
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400389 li.final_sec32low_start,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400390 sec32all_start,
391 relocstr,
392 outRelSections(li.sections32low, 'code32flat_start'),
393 outRelSections(li.sections32init, 'code32flat_start'),
394 outRelSections(li.sections32flat, 'code32flat_start'),
395 li.sec32seg_start,
396 li.sec16_start)
397 out = COMMONHEADER + out + COMMONTRAILER + """
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400398ENTRY(%s)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400399PHDRS
400{
401 text PT_LOAD AT ( code32flat_start ) ;
402}
Kevin O'Connor46b82622012-05-13 12:10:30 -0400403""" % (entrysym.name,)
404 outfile = open(out32flat, 'wb')
405 outfile.write(out)
406 outfile.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400407
408
409######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400410# Detection of init code
411######################################################################
412
413def markRuntime(section, sections):
414 if (section is None or not section.keep or section.category is not None
415 or '.init.' in section.name or section.fileid != '32flat'):
416 return
417 section.category = '32flat'
418 # Recursively mark all sections this section points to
419 for reloc in section.relocs:
420 markRuntime(reloc.symbol.section, sections)
421
422def findInit(sections):
423 # Recursively find and mark all "runtime" sections.
424 for section in sections:
Kevin O'Connor46b82622012-05-13 12:10:30 -0400425 if ('.datalow.' in section.name or '.runtime.' in section.name
426 or '.export.' in section.name):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400427 markRuntime(section, sections)
428 for section in sections:
429 if section.category is not None:
430 continue
431 if section.fileid == '32flat':
432 section.category = '32init'
433 else:
434 section.category = section.fileid
435
436
437######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400438# Section garbage collection
439######################################################################
440
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500441CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
442
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500443# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500444def keepsymbol(reloc, infos, pos, isxref):
445 symbolname = reloc.symbolname
446 mustbecfunc = 0
447 for symprefix, needpos in CFUNCPREFIX:
448 if symbolname.startswith(symprefix):
449 if needpos != pos:
450 return -1
451 symbolname = symbolname[len(symprefix):]
452 mustbecfunc = 1
453 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400454 symbol = infos[pos][1].get(symbolname)
455 if (symbol is None or symbol.section is None
456 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500457 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500458 isdestcfunc = (symbol.section.name.startswith('.text.')
459 and not symbol.section.name.startswith('.text.asm.'))
460 if ((mustbecfunc and not isdestcfunc)
461 or (not mustbecfunc and isdestcfunc and isxref)):
462 return -1
463
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400464 reloc.symbol = symbol
465 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500466 return 0
467
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400468# Note required section, and recursively set all referenced sections
469# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400470def keepsection(section, infos, pos=0):
471 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400472 # Already kept - nothing to do.
473 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400474 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400475 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400476 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500477 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500478 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400479 continue
480 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500481 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500482 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500483 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500484 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500485 if not ret:
486 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400487
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400488# Determine which sections are actually referenced and need to be
489# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500490def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400491 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
492 # , (sect32flat, sym32flat))
493 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400494 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400495 for section in info16[0]:
496 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500497 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400498 return [section for section in info16[0]+info32seg[0]+info32flat[0]
499 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400500
501
502######################################################################
503# Startup and input parsing
504######################################################################
505
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400506class Section:
507 name = size = alignment = fileid = relocs = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400508 finalloc = finalsegloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400509class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500510 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400511class Symbol:
512 name = offset = section = None
513
Kevin O'Connorc0693942009-06-10 21:56:01 -0400514# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400515def parseObjDump(file, fileid):
516 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400517 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400518 sectionmap = {}
519 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400520 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400521
522 state = None
523 for line in file.readlines():
524 line = line.rstrip()
525 if line == 'Sections:':
526 state = 'section'
527 continue
528 if line == 'SYMBOL TABLE:':
529 state = 'symbol'
530 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400531 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400532 sectionname = line[24:-2]
533 if sectionname.startswith('.debug_'):
534 # Skip debugging sections (to reduce parsing time)
535 state = None
536 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400537 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400538 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400539 continue
540
541 if state == 'section':
542 try:
543 idx, name, size, vma, lma, fileoff, align = line.split()
544 if align[:3] != '2**':
545 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400546 section = Section()
547 section.name = name
548 section.size = int(size, 16)
549 section.align = 2**int(align[3:])
550 section.fileid = fileid
551 section.relocs = []
552 sections.append(section)
553 sectionmap[name] = section
554 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400555 pass
556 continue
557 if state == 'symbol':
558 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400559 sectionname, size, name = line[17:].split()
560 symbol = Symbol()
561 symbol.size = int(size, 16)
562 symbol.offset = int(line[:8], 16)
563 symbol.name = name
564 symbol.section = sectionmap.get(sectionname)
565 symbols[name] = symbol
566 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400567 pass
568 continue
569 if state == 'reloc':
570 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400571 off, type, symbolname = line.split()
572 reloc = Reloc()
573 reloc.offset = int(off, 16)
574 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500575 reloc.symbolname = symbolname
Kevin O'Connor67863be2010-12-24 10:23:10 -0500576 reloc.symbol = symbols.get(symbolname)
577 if reloc.symbol is None:
578 # Some binutils (2.20.1) give section name instead
579 # of a symbol - create a dummy symbol.
580 reloc.symbol = symbol = Symbol()
581 symbol.size = 0
582 symbol.offset = 0
583 symbol.name = symbolname
584 symbol.section = sectionmap.get(symbolname)
585 symbols[symbolname] = symbol
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400586 relocsection.relocs.append(reloc)
587 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400588 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400589 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400590
591def main():
592 # Get output name
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500593 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400594
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400595 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400596 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500597 infile32seg = open(in32seg, 'rb')
598 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400599
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400600 # infoX = (sections, symbols)
601 info16 = parseObjDump(infile16, '16')
602 info32seg = parseObjDump(infile32seg, '32seg')
603 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400604
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400605 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400606 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400607
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400608 # Separate 32bit flat into runtime and init parts
609 findInit(sections)
610
Kevin O'Connor46b82622012-05-13 12:10:30 -0400611 # Note "low memory" parts
612 for section in getSectionsPrefix(sections, '.datalow.'):
613 section.category = '32low'
614
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400615 # Determine the final memory locations of each kept section.
Kevin O'Connor46b82622012-05-13 12:10:30 -0400616 genreloc = '_reloc_abs_start' in info32flat[1]
617 li = doLayout(sections, genreloc)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400618
619 # Write out linker script files.
Kevin O'Connor47c8e312011-07-10 22:57:32 -0400620 entrysym = info16[1]['entry_elf']
Kevin O'Connor46b82622012-05-13 12:10:30 -0400621 writeLinkerScripts(li, entrysym, genreloc, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400622
Kevin O'Connor202024a2009-01-17 10:41:28 -0500623if __name__ == '__main__':
624 main()