blob: 70370e4f4fc772be670c9dd99e2c965e87565dc4 [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*)
Kevin O'Connor90ebed42012-06-21 20:54:53 -040026 *(COMMON) *(.discard*) *(.eh_frame) *(.note*)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040027 }
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:
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500155 genreloc = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400156 sections16 = sec16_start = sec16_align = None
157 sections32seg = sec32seg_start = sec32seg_align = None
158 sections32flat = sec32flat_start = sec32flat_align = None
159 sections32init = sec32init_start = sec32init_align = None
160 sections32low = sec32low_start = sec32low_align = None
Kevin O'Connor41953492013-02-18 23:09:01 -0500161 sections32fseg = sec32fseg_start = sec32fseg_align = None
Kevin O'Connorc9243442013-02-17 13:58:28 -0500162 zonelow_base = final_sec32low_start = None
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500163 exportsyms = varlowsyms = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400164
165# Determine final memory addresses for sections
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500166def doLayout(sections):
Kevin O'Connor46b82622012-05-13 12:10:30 -0400167 li = LayoutInfo()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400168 # Determine 16bit positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400169 li.sections16 = getSectionsCategory(sections, '16')
170 textsections = getSectionsPrefix(li.sections16, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500171 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400172 getSectionsPrefix(li.sections16, '.rodata.str1.1')
173 + getSectionsPrefix(li.sections16, '.rodata.__func__.')
174 + getSectionsPrefix(li.sections16, '.rodata.__PRETTY_FUNCTION__.'))
175 datasections = getSectionsPrefix(li.sections16, '.data16.')
176 fixedsections = getSectionsPrefix(li.sections16, '.fixedaddr.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400177
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400178 firstfixed = fitSections(fixedsections, textsections)
179 remsections = [s for s in textsections+rodatasections+datasections
180 if s.finalloc is None]
Kevin O'Connor46b82622012-05-13 12:10:30 -0400181 li.sec16_start, li.sec16_align = setSectionsStart(
182 remsections, firstfixed, segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400183
184 # Determine 32seg positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400185 li.sections32seg = getSectionsCategory(sections, '32seg')
186 textsections = getSectionsPrefix(li.sections32seg, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500187 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400188 getSectionsPrefix(li.sections32seg, '.rodata.str1.1')
189 + getSectionsPrefix(li.sections32seg, '.rodata.__func__.')
190 + getSectionsPrefix(li.sections32seg, '.rodata.__PRETTY_FUNCTION__.'))
191 datasections = getSectionsPrefix(li.sections32seg, '.data32seg.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400192
Kevin O'Connor46b82622012-05-13 12:10:30 -0400193 li.sec32seg_start, li.sec32seg_align = setSectionsStart(
194 textsections + rodatasections + datasections, li.sec16_start
195 , segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400196
Kevin O'Connor41953492013-02-18 23:09:01 -0500197 # Determine "fseg memory" data positions
198 li.sections32fseg = getSectionsCategory(sections, '32fseg')
199
200 li.sec32fseg_start, li.sec32fseg_align = setSectionsStart(
201 li.sections32fseg, li.sec32seg_start, 16
202 , segoffset=BUILD_BIOS_ADDR)
203
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400204 # Determine 32flat runtime positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400205 li.sections32flat = getSectionsCategory(sections, '32flat')
206 textsections = getSectionsPrefix(li.sections32flat, '.text.')
207 rodatasections = getSectionsPrefix(li.sections32flat, '.rodata')
208 datasections = getSectionsPrefix(li.sections32flat, '.data.')
209 bsssections = getSectionsPrefix(li.sections32flat, '.bss.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400210
Kevin O'Connor46b82622012-05-13 12:10:30 -0400211 li.sec32flat_start, li.sec32flat_align = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400212 textsections + rodatasections + datasections + bsssections
Kevin O'Connor41953492013-02-18 23:09:01 -0500213 , li.sec32fseg_start, 16)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400214
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400215 # Determine 32flat init positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400216 li.sections32init = getSectionsCategory(sections, '32init')
217 textsections = getSectionsPrefix(li.sections32init, '.text.')
218 rodatasections = getSectionsPrefix(li.sections32init, '.rodata')
219 datasections = getSectionsPrefix(li.sections32init, '.data.')
220 bsssections = getSectionsPrefix(li.sections32init, '.bss.')
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400221
Kevin O'Connor46b82622012-05-13 12:10:30 -0400222 li.sec32init_start, li.sec32init_align = setSectionsStart(
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400223 textsections + rodatasections + datasections + bsssections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400224 , li.sec32flat_start, 16)
225
226 # Determine "low memory" data positions
227 li.sections32low = getSectionsCategory(sections, '32low')
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500228 sec32low_end = li.sec32init_start
229 final_sec32low_start = min(BUILD_BIOS_ADDR, li.sec32flat_start)
230 relocdelta = final_sec32low_start - sec32low_end
231 zonelow_base = final_sec32low_start - 64*1024
Kevin O'Connorc9243442013-02-17 13:58:28 -0500232 li.zonelow_base = max(BUILD_ROM_START, alignpos(zonelow_base, 2*1024))
Kevin O'Connor46b82622012-05-13 12:10:30 -0400233 li.sec32low_start, li.sec32low_align = setSectionsStart(
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500234 li.sections32low, sec32low_end, 16
Kevin O'Connorc9243442013-02-17 13:58:28 -0500235 , segoffset=li.zonelow_base - relocdelta)
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400236 li.final_sec32low_start = li.sec32low_start + relocdelta
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400237
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400238 # Print statistics
Kevin O'Connor46b82622012-05-13 12:10:30 -0400239 size16 = BUILD_BIOS_ADDR + BUILD_BIOS_SIZE - li.sec16_start
240 size32seg = li.sec16_start - li.sec32seg_start
Kevin O'Connor41953492013-02-18 23:09:01 -0500241 size32fseg = li.sec32seg_start - li.sec32fseg_start
242 size32flat = li.sec32fseg_start - li.sec32flat_start
Kevin O'Connor46b82622012-05-13 12:10:30 -0400243 size32init = li.sec32flat_start - li.sec32init_start
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500244 sizelow = sec32low_end - li.sec32low_start
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400245 print "16bit size: %d" % size16
246 print "32bit segmented size: %d" % size32seg
247 print "32bit flat size: %d" % size32flat
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400248 print "32bit flat init size: %d" % size32init
Kevin O'Connor46b82622012-05-13 12:10:30 -0400249 print "Lowmem size: %d" % sizelow
Kevin O'Connor41953492013-02-18 23:09:01 -0500250 print "f-segment var size: %d" % size32fseg
Kevin O'Connor46b82622012-05-13 12:10:30 -0400251 return li
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400252
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400253
254######################################################################
255# Linker script output
256######################################################################
257
258# Write LD script includes for the given cross references
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500259def outXRefs(sections, useseg=0, exportsyms=[], forcedelta=0):
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500260 xrefs = dict([(symbol.name, symbol) for symbol in exportsyms])
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400261 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400262 for section in sections:
263 for reloc in section.relocs:
264 symbol = reloc.symbol
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500265 if (symbol.section is not None
266 and (symbol.section.fileid != section.fileid
267 or symbol.name != reloc.symbolname)):
268 xrefs[reloc.symbolname] = symbol
269 for symbolname, symbol in xrefs.items():
270 loc = symbol.section.finalloc
271 if useseg:
272 loc = symbol.section.finalsegloc
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500273 out += "%s = 0x%x ;\n" % (symbolname, loc + forcedelta + symbol.offset)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400274 return out
275
276# Write LD script includes for the given sections using relative offsets
Kevin O'Connor46b82622012-05-13 12:10:30 -0400277def outRelSections(sections, startsym, useseg=0):
278 sections = [(section.finalloc, section) for section in sections
279 if section.finalloc is not None]
280 sections.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400281 out = ""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400282 for addr, section in sections:
283 loc = section.finalloc
284 if useseg:
285 loc = section.finalsegloc
286 out += ". = ( 0x%x - %s ) ;\n" % (loc, startsym)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400287 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400288 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400289 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400290 return out
291
Kevin O'Connor46b82622012-05-13 12:10:30 -0400292# Build linker script output for a list of relocations.
293def strRelocs(outname, outrel, relocs):
294 relocs.sort()
295 return (" %s_start = ABSOLUTE(.) ;\n" % (outname,)
296 + "".join(["LONG(0x%x - %s)\n" % (pos, outrel)
297 for pos in relocs])
298 + " %s_end = ABSOLUTE(.) ;\n" % (outname,))
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500299
Kevin O'Connor46b82622012-05-13 12:10:30 -0400300# Find all relocations in the given sections with the given attributes
301def getRelocs(sections, type=None, category=None, notcategory=None):
302 out = []
303 for section in sections:
304 for reloc in section.relocs:
305 if reloc.symbol.section is None:
306 continue
307 destcategory = reloc.symbol.section.category
308 if ((type is None or reloc.type == type)
309 and (category is None or destcategory == category)
310 and (notcategory is None or destcategory != notcategory)):
311 out.append(section.finalloc + reloc.offset)
312 return out
313
314# Return the start address and minimum alignment for a set of sections
315def getSectionsStart(sections, defaddr=0):
316 return min([section.finalloc for section in sections
317 if section.finalloc is not None] or [defaddr])
318
319# Output the linker scripts for all required sections.
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500320def writeLinkerScripts(li, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400321 # Write 16bit linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400322 out = outXRefs(li.sections16, useseg=1) + """
Kevin O'Connorc9243442013-02-17 13:58:28 -0500323 zonelow_base = 0x%x ;
324 _zonelow_seg = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400325
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400326 code16_start = 0x%x ;
327 .text16 code16_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400328%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400329 }
Kevin O'Connorc9243442013-02-17 13:58:28 -0500330""" % (li.zonelow_base,
331 li.zonelow_base / 16,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400332 li.sec16_start - BUILD_BIOS_ADDR,
333 outRelSections(li.sections16, 'code16_start', useseg=1))
334 outfile = open(out16, 'wb')
335 outfile.write(COMMONHEADER + out + COMMONTRAILER)
336 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500337
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400338 # Write 32seg linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400339 out = outXRefs(li.sections32seg, useseg=1) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400340 code32seg_start = 0x%x ;
341 .text32seg code32seg_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400342%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400343 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400344""" % (li.sec32seg_start - BUILD_BIOS_ADDR,
345 outRelSections(li.sections32seg, 'code32seg_start', useseg=1))
346 outfile = open(out32seg, 'wb')
347 outfile.write(COMMONHEADER + out + COMMONTRAILER)
348 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500349
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400350 # Write 32flat linker script
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500351 sections32all = (li.sections32flat + li.sections32init + li.sections32fseg)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400352 sec32all_start = li.sec32low_start
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400353 relocstr = ""
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500354 if li.genreloc:
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400355 # Generate relocations
Kevin O'Connor46b82622012-05-13 12:10:30 -0400356 absrelocs = getRelocs(
357 li.sections32init, type='R_386_32', category='32init')
358 relrelocs = getRelocs(
359 li.sections32init, type='R_386_PC32', notcategory='32init')
360 initrelocs = getRelocs(
361 li.sections32flat + li.sections32low + li.sections16
Kevin O'Connor41953492013-02-18 23:09:01 -0500362 + li.sections32seg + li.sections32fseg, category='32init')
Kevin O'Connor46b82622012-05-13 12:10:30 -0400363 relocstr = (strRelocs("_reloc_abs", "code32init_start", absrelocs)
364 + strRelocs("_reloc_rel", "code32init_start", relrelocs)
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500365 + strRelocs("_reloc_init", "code32flat_start", initrelocs))
366 numrelocs = len(absrelocs + relrelocs + initrelocs)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400367 sec32all_start -= numrelocs * 4
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500368 out = outXRefs(li.sections32low, exportsyms=li.varlowsyms
369 , forcedelta=li.final_sec32low_start-li.sec32low_start)
370 out += outXRefs(sections32all, exportsyms=li.exportsyms) + """
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400371 _reloc_min_align = 0x%x ;
Kevin O'Connorc9243442013-02-17 13:58:28 -0500372 zonelow_base = 0x%x ;
373 final_varlow_start = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400374
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400375 code32flat_start = 0x%x ;
376 .text code32flat_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400377%s
Kevin O'Connorc9243442013-02-17 13:58:28 -0500378 varlow_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400379%s
Kevin O'Connorc9243442013-02-17 13:58:28 -0500380 varlow_end = ABSOLUTE(.) ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400381 code32init_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400382%s
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400383 code32init_end = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400384%s
Kevin O'Connor41953492013-02-18 23:09:01 -0500385%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400386 . = ( 0x%x - code32flat_start ) ;
387 *(.text32seg)
388 . = ( 0x%x - code32flat_start ) ;
389 *(.text16)
390 code32flat_end = ABSOLUTE(.) ;
391 } :text
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500392""" % (li.sec32init_align,
Kevin O'Connorc9243442013-02-17 13:58:28 -0500393 li.zonelow_base,
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400394 li.final_sec32low_start,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400395 sec32all_start,
396 relocstr,
397 outRelSections(li.sections32low, 'code32flat_start'),
398 outRelSections(li.sections32init, 'code32flat_start'),
399 outRelSections(li.sections32flat, 'code32flat_start'),
Kevin O'Connor41953492013-02-18 23:09:01 -0500400 outRelSections(li.sections32fseg, 'code32flat_start'),
Kevin O'Connor46b82622012-05-13 12:10:30 -0400401 li.sec32seg_start,
402 li.sec16_start)
403 out = COMMONHEADER + out + COMMONTRAILER + """
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500404ENTRY(entry_elf)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400405PHDRS
406{
407 text PT_LOAD AT ( code32flat_start ) ;
408}
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500409"""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400410 outfile = open(out32flat, 'wb')
411 outfile.write(out)
412 outfile.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400413
414
415######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400416# Detection of init code
417######################################################################
418
419def markRuntime(section, sections):
420 if (section is None or not section.keep or section.category is not None
421 or '.init.' in section.name or section.fileid != '32flat'):
422 return
423 section.category = '32flat'
424 # Recursively mark all sections this section points to
425 for reloc in section.relocs:
426 markRuntime(reloc.symbol.section, sections)
427
428def findInit(sections):
429 # Recursively find and mark all "runtime" sections.
430 for section in sections:
Kevin O'Connor41953492013-02-18 23:09:01 -0500431 if ('.data.varlow.' in section.name or '.data.varfseg.' in section.name
432 or '.runtime.' in section.name or '.export.' in section.name):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400433 markRuntime(section, sections)
434 for section in sections:
435 if section.category is not None:
436 continue
437 if section.fileid == '32flat':
438 section.category = '32init'
439 else:
440 section.category = section.fileid
441
442
443######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400444# Section garbage collection
445######################################################################
446
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500447CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
448
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500449# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500450def keepsymbol(reloc, infos, pos, isxref):
451 symbolname = reloc.symbolname
452 mustbecfunc = 0
453 for symprefix, needpos in CFUNCPREFIX:
454 if symbolname.startswith(symprefix):
455 if needpos != pos:
456 return -1
457 symbolname = symbolname[len(symprefix):]
458 mustbecfunc = 1
459 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400460 symbol = infos[pos][1].get(symbolname)
461 if (symbol is None or symbol.section is None
462 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500463 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500464 isdestcfunc = (symbol.section.name.startswith('.text.')
465 and not symbol.section.name.startswith('.text.asm.'))
466 if ((mustbecfunc and not isdestcfunc)
467 or (not mustbecfunc and isdestcfunc and isxref)):
468 return -1
469
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400470 reloc.symbol = symbol
471 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500472 return 0
473
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400474# Note required section, and recursively set all referenced sections
475# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400476def keepsection(section, infos, pos=0):
477 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400478 # Already kept - nothing to do.
479 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400480 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400481 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400482 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500483 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500484 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400485 continue
486 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500487 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500488 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500489 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500490 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500491 if not ret:
492 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400493
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400494# Determine which sections are actually referenced and need to be
495# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500496def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400497 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
498 # , (sect32flat, sym32flat))
499 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400500 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400501 for section in info16[0]:
502 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500503 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400504 return [section for section in info16[0]+info32seg[0]+info32flat[0]
505 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400506
507
508######################################################################
509# Startup and input parsing
510######################################################################
511
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400512class Section:
513 name = size = alignment = fileid = relocs = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400514 finalloc = finalsegloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400515class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500516 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400517class Symbol:
518 name = offset = section = None
519
Kevin O'Connorc0693942009-06-10 21:56:01 -0400520# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400521def parseObjDump(file, fileid):
522 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400523 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400524 sectionmap = {}
525 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400526 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400527
528 state = None
529 for line in file.readlines():
530 line = line.rstrip()
531 if line == 'Sections:':
532 state = 'section'
533 continue
534 if line == 'SYMBOL TABLE:':
535 state = 'symbol'
536 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400537 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400538 sectionname = line[24:-2]
539 if sectionname.startswith('.debug_'):
540 # Skip debugging sections (to reduce parsing time)
541 state = None
542 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400543 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400544 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400545 continue
546
547 if state == 'section':
548 try:
549 idx, name, size, vma, lma, fileoff, align = line.split()
550 if align[:3] != '2**':
551 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400552 section = Section()
553 section.name = name
554 section.size = int(size, 16)
555 section.align = 2**int(align[3:])
556 section.fileid = fileid
557 section.relocs = []
558 sections.append(section)
559 sectionmap[name] = section
560 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400561 pass
562 continue
563 if state == 'symbol':
564 try:
Kevin O'Connor90ebed42012-06-21 20:54:53 -0400565 parts = line[17:].split()
566 if len(parts) == 3:
567 sectionname, size, name = parts
568 elif len(parts) == 4 and parts[2] == '.hidden':
569 sectionname, size, hidden, name = parts
570 else:
571 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400572 symbol = Symbol()
573 symbol.size = int(size, 16)
574 symbol.offset = int(line[:8], 16)
575 symbol.name = name
576 symbol.section = sectionmap.get(sectionname)
577 symbols[name] = symbol
578 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400579 pass
580 continue
581 if state == 'reloc':
582 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400583 off, type, symbolname = line.split()
584 reloc = Reloc()
585 reloc.offset = int(off, 16)
586 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500587 reloc.symbolname = symbolname
Kevin O'Connor67863be2010-12-24 10:23:10 -0500588 reloc.symbol = symbols.get(symbolname)
589 if reloc.symbol is None:
590 # Some binutils (2.20.1) give section name instead
591 # of a symbol - create a dummy symbol.
592 reloc.symbol = symbol = Symbol()
593 symbol.size = 0
594 symbol.offset = 0
595 symbol.name = symbolname
596 symbol.section = sectionmap.get(symbolname)
597 symbols[symbolname] = symbol
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400598 relocsection.relocs.append(reloc)
599 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400600 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400601 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400602
603def main():
604 # Get output name
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500605 in16, in32seg, in32flat, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400606
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400607 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400608 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500609 infile32seg = open(in32seg, 'rb')
610 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400611
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400612 # infoX = (sections, symbols)
613 info16 = parseObjDump(infile16, '16')
614 info32seg = parseObjDump(infile32seg, '32seg')
615 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400616
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400617 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400618 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400619
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400620 # Separate 32bit flat into runtime and init parts
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500621 genreloc = '_reloc_abs_start' in info32flat[1]
622 if genreloc:
623 findInit(sections)
624 else:
625 for section in sections:
626 section.category = section.fileid
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400627
Kevin O'Connor41953492013-02-18 23:09:01 -0500628 # Note "low memory" and "fseg memory" parts
Kevin O'Connorc9243442013-02-17 13:58:28 -0500629 for section in getSectionsPrefix(sections, '.data.varlow.'):
Kevin O'Connor46b82622012-05-13 12:10:30 -0400630 section.category = '32low'
Kevin O'Connor41953492013-02-18 23:09:01 -0500631 for section in getSectionsPrefix(sections, '.data.varfseg.'):
632 section.category = '32fseg'
Kevin O'Connor46b82622012-05-13 12:10:30 -0400633
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400634 # Determine the final memory locations of each kept section.
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500635 li = doLayout(sections)
636 li.genreloc = genreloc
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400637
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500638 # Exported symbols
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500639 li.exportsyms = [symbol for symbol in info16[1].values()
640 if (symbol.section is not None
641 and '.export.' in symbol.section.name
642 and symbol.name != symbol.section.name)]
643 li.varlowsyms = [symbol for symbol in info32flat[1].values()
644 if (symbol.section is not None
645 and symbol.section.finalloc is not None
646 and '.data.varlow.' in symbol.section.name
647 and symbol.name != symbol.section.name)]
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500648
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400649 # Write out linker script files.
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500650 writeLinkerScripts(li, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400651
Kevin O'Connor202024a2009-01-17 10:41:28 -0500652if __name__ == '__main__':
653 main()