blob: c0b325d3f70b7af95d3a5483f26d393780a4957b [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'Connor2b0fb8c2013-08-07 23:03:47 -040062BUILD_LOWRAM_END = 0xa0000
Kevin O'Connor6d152642013-02-19 21:35:20 -050063# Space to reserve in f-segment for dynamic allocations
64BUILD_MIN_BIOSTABLE = 2048
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040065
66# Layout the 16bit code. This ensures sections with fixed offset
67# requirements are placed in the correct location. It also places the
68# 16bit code as high as possible in the f-segment.
69def fitSections(sections, fillsections):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040070 # fixedsections = [(addr, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040071 fixedsections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040072 for section in sections:
73 if section.name.startswith('.fixedaddr.'):
74 addr = int(section.name[11:], 16)
Kevin O'Connor46b82622012-05-13 12:10:30 -040075 section.finalloc = addr + BUILD_BIOS_ADDR
76 section.finalsegloc = addr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040077 fixedsections.append((addr, section))
78 if section.align != 1:
Johannes Krampf064fd062014-01-12 11:14:54 -050079 print("Error: Fixed section %s has non-zero alignment (%d)" % (
80 section.name, section.align))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040081 sys.exit(1)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040082 fixedsections.sort()
83 firstfixed = fixedsections[0][0]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040084
85 # Find freespace in fixed address area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040086 # fixedAddr = [(freespace, section), ...]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040087 fixedAddr = []
88 for i in range(len(fixedsections)):
89 fixedsectioninfo = fixedsections[i]
90 addr, section = fixedsectioninfo
91 if i == len(fixedsections) - 1:
92 nextaddr = BUILD_BIOS_SIZE
93 else:
94 nextaddr = fixedsections[i+1][0]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -040095 avail = nextaddr - addr - section.size
96 fixedAddr.append((avail, section))
97 fixedAddr.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -040098
99 # Attempt to fit other sections into fixed area
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400100 canrelocate = [(section.size, section.align, section.name, section)
101 for section in fillsections]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400102 canrelocate.sort()
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400103 canrelocate = [section for size, align, name, section in canrelocate]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400104 totalused = 0
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400105 for freespace, fixedsection in fixedAddr:
Kevin O'Connor46b82622012-05-13 12:10:30 -0400106 addpos = fixedsection.finalsegloc + fixedsection.size
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400107 totalused += fixedsection.size
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400108 nextfixedaddr = addpos + freespace
Johannes Krampf064fd062014-01-12 11:14:54 -0500109# print("Filling section %x uses %d, next=%x, available=%d" % (
110# fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400111 while 1:
112 canfit = None
113 for fitsection in canrelocate:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400114 if addpos + fitsection.size > nextfixedaddr:
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400115 # Can't fit and nothing else will fit.
116 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400117 fitnextaddr = alignpos(addpos, fitsection.align) + fitsection.size
Johannes Krampf064fd062014-01-12 11:14:54 -0500118# print("Test %s - %x vs %x" % (
119# fitsection.name, fitnextaddr, nextfixedaddr))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400120 if fitnextaddr > nextfixedaddr:
121 # This item can't fit.
122 continue
123 canfit = (fitnextaddr, fitsection)
124 if canfit is None:
125 break
126 # Found a section that can fit.
127 fitnextaddr, fitsection = canfit
128 canrelocate.remove(fitsection)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400129 fitsection.finalloc = addpos + BUILD_BIOS_ADDR
130 fitsection.finalsegloc = addpos
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400131 addpos = fitnextaddr
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400132 totalused += fitsection.size
Johannes Krampf064fd062014-01-12 11:14:54 -0500133# print(" Adding %s (size %d align %d) pos=%x avail=%d" % (
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400134# fitsection[2], fitsection[0], fitsection[1]
Johannes Krampf064fd062014-01-12 11:14:54 -0500135# , fitnextaddr, nextfixedaddr - fitnextaddr))
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400136
137 # Report stats
138 total = BUILD_BIOS_SIZE-firstfixed
139 slack = total - totalused
140 print ("Fixed space: 0x%x-0x%x total: %d slack: %d"
141 " Percent slack: %.1f%%" % (
142 firstfixed, BUILD_BIOS_SIZE, total, slack,
143 (float(slack) / total) * 100.0))
144
Kevin O'Connor46b82622012-05-13 12:10:30 -0400145 return firstfixed + BUILD_BIOS_ADDR
146
147# Return the subset of sections with a given category
148def getSectionsCategory(sections, category):
149 return [section for section in sections if section.category == category]
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400150
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400151# Return the subset of sections with a given name prefix
Kevin O'Connor46b82622012-05-13 12:10:30 -0400152def getSectionsPrefix(sections, prefix):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400153 return [section for section in sections
Kevin O'Connor46b82622012-05-13 12:10:30 -0400154 if section.name.startswith(prefix)]
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400155
Kevin O'Connor46b82622012-05-13 12:10:30 -0400156# The sections (and associated information) to be placed in output rom
157class LayoutInfo:
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500158 genreloc = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400159 sections16 = sec16_start = sec16_align = None
160 sections32seg = sec32seg_start = sec32seg_align = None
161 sections32flat = sec32flat_start = sec32flat_align = None
162 sections32init = sec32init_start = sec32init_align = None
163 sections32low = sec32low_start = sec32low_align = None
Kevin O'Connor41953492013-02-18 23:09:01 -0500164 sections32fseg = sec32fseg_start = sec32fseg_align = None
Kevin O'Connor6d152642013-02-19 21:35:20 -0500165 zonefseg_start = zonefseg_end = None
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500166 final_readonly_start = None
Kevin O'Connorc9243442013-02-17 13:58:28 -0500167 zonelow_base = final_sec32low_start = None
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500168 exportsyms = varlowsyms = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400169
170# Determine final memory addresses for sections
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500171def doLayout(sections, config, genreloc):
Kevin O'Connor46b82622012-05-13 12:10:30 -0400172 li = LayoutInfo()
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500173 li.genreloc = genreloc
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400174 # Determine 16bit positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400175 li.sections16 = getSectionsCategory(sections, '16')
176 textsections = getSectionsPrefix(li.sections16, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500177 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400178 getSectionsPrefix(li.sections16, '.rodata.str1.1')
179 + getSectionsPrefix(li.sections16, '.rodata.__func__.')
180 + getSectionsPrefix(li.sections16, '.rodata.__PRETTY_FUNCTION__.'))
181 datasections = getSectionsPrefix(li.sections16, '.data16.')
182 fixedsections = getSectionsPrefix(li.sections16, '.fixedaddr.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400183
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400184 firstfixed = fitSections(fixedsections, textsections)
185 remsections = [s for s in textsections+rodatasections+datasections
186 if s.finalloc is None]
Kevin O'Connor46b82622012-05-13 12:10:30 -0400187 li.sec16_start, li.sec16_align = setSectionsStart(
188 remsections, firstfixed, segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400189
190 # Determine 32seg positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400191 li.sections32seg = getSectionsCategory(sections, '32seg')
192 textsections = getSectionsPrefix(li.sections32seg, '.text.')
Kevin O'Connor805ede22012-02-08 20:23:36 -0500193 rodatasections = (
Kevin O'Connor46b82622012-05-13 12:10:30 -0400194 getSectionsPrefix(li.sections32seg, '.rodata.str1.1')
195 + getSectionsPrefix(li.sections32seg, '.rodata.__func__.')
196 + getSectionsPrefix(li.sections32seg, '.rodata.__PRETTY_FUNCTION__.'))
197 datasections = getSectionsPrefix(li.sections32seg, '.data32seg.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400198
Kevin O'Connor46b82622012-05-13 12:10:30 -0400199 li.sec32seg_start, li.sec32seg_align = setSectionsStart(
200 textsections + rodatasections + datasections, li.sec16_start
201 , segoffset=BUILD_BIOS_ADDR)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400202
Kevin O'Connor41953492013-02-18 23:09:01 -0500203 # Determine "fseg memory" data positions
204 li.sections32fseg = getSectionsCategory(sections, '32fseg')
205
206 li.sec32fseg_start, li.sec32fseg_align = setSectionsStart(
207 li.sections32fseg, li.sec32seg_start, 16
208 , segoffset=BUILD_BIOS_ADDR)
209
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400210 # Determine 32flat runtime positions
Kevin O'Connor46b82622012-05-13 12:10:30 -0400211 li.sections32flat = getSectionsCategory(sections, '32flat')
212 textsections = getSectionsPrefix(li.sections32flat, '.text.')
213 rodatasections = getSectionsPrefix(li.sections32flat, '.rodata')
214 datasections = getSectionsPrefix(li.sections32flat, '.data.')
215 bsssections = getSectionsPrefix(li.sections32flat, '.bss.')
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400216
Kevin O'Connor46b82622012-05-13 12:10:30 -0400217 li.sec32flat_start, li.sec32flat_align = setSectionsStart(
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400218 textsections + rodatasections + datasections + bsssections
Kevin O'Connor41953492013-02-18 23:09:01 -0500219 , li.sec32fseg_start, 16)
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500220
221 # Determine 32flat init positions
222 li.sections32init = getSectionsCategory(sections, '32init')
223 init32_textsections = getSectionsPrefix(li.sections32init, '.text.')
224 init32_rodatasections = getSectionsPrefix(li.sections32init, '.rodata')
225 init32_datasections = getSectionsPrefix(li.sections32init, '.data.')
226 init32_bsssections = getSectionsPrefix(li.sections32init, '.bss.')
227
228 li.sec32init_start, li.sec32init_align = setSectionsStart(
229 init32_textsections + init32_rodatasections
230 + init32_datasections + init32_bsssections
231 , li.sec32flat_start, 16)
232
233 # Determine location of ZoneFSeg memory.
Kevin O'Connor6d152642013-02-19 21:35:20 -0500234 li.zonefseg_end = li.sec32flat_start
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500235 if not genreloc:
236 li.zonefseg_end = li.sec32init_start
Kevin O'Connor6d152642013-02-19 21:35:20 -0500237 li.zonefseg_start = BUILD_BIOS_ADDR
238 if li.zonefseg_start + BUILD_MIN_BIOSTABLE > li.zonefseg_end:
239 # Not enough ZoneFSeg space - force a minimum space.
240 li.zonefseg_end = li.sec32fseg_start
241 li.zonefseg_start = li.zonefseg_end - BUILD_MIN_BIOSTABLE
242 li.sec32flat_start, li.sec32flat_align = setSectionsStart(
243 textsections + rodatasections + datasections + bsssections
244 , li.zonefseg_start, 16)
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500245 li.sec32init_start, li.sec32init_align = setSectionsStart(
246 init32_textsections + init32_rodatasections
247 + init32_datasections + init32_bsssections
248 , li.sec32flat_start, 16)
249 li.final_readonly_start = min(BUILD_BIOS_ADDR, li.sec32flat_start)
250 if not genreloc:
251 li.final_readonly_start = min(BUILD_BIOS_ADDR, li.sec32init_start)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400252
253 # Determine "low memory" data positions
254 li.sections32low = getSectionsCategory(sections, '32low')
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500255 sec32low_end = li.sec32init_start
Kevin O'Connor2b0fb8c2013-08-07 23:03:47 -0400256 if config.get('CONFIG_MALLOC_UPPERMEMORY'):
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500257 final_sec32low_end = li.final_readonly_start
Kevin O'Connor2b0fb8c2013-08-07 23:03:47 -0400258 zonelow_base = final_sec32low_end - 64*1024
259 li.zonelow_base = max(BUILD_ROM_START, alignpos(zonelow_base, 2*1024))
260 else:
261 final_sec32low_end = BUILD_LOWRAM_END
262 li.zonelow_base = final_sec32low_end - 64*1024
Kevin O'Connor3be89a12013-02-23 16:07:00 -0500263 relocdelta = final_sec32low_end - sec32low_end
Kevin O'Connor46b82622012-05-13 12:10:30 -0400264 li.sec32low_start, li.sec32low_align = setSectionsStart(
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500265 li.sections32low, sec32low_end, 16
Kevin O'Connorc9243442013-02-17 13:58:28 -0500266 , segoffset=li.zonelow_base - relocdelta)
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400267 li.final_sec32low_start = li.sec32low_start + relocdelta
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400268
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400269 # Print statistics
Kevin O'Connor46b82622012-05-13 12:10:30 -0400270 size16 = BUILD_BIOS_ADDR + BUILD_BIOS_SIZE - li.sec16_start
271 size32seg = li.sec16_start - li.sec32seg_start
Kevin O'Connor41953492013-02-18 23:09:01 -0500272 size32fseg = li.sec32seg_start - li.sec32fseg_start
273 size32flat = li.sec32fseg_start - li.sec32flat_start
Kevin O'Connor46b82622012-05-13 12:10:30 -0400274 size32init = li.sec32flat_start - li.sec32init_start
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500275 sizelow = sec32low_end - li.sec32low_start
Johannes Krampf064fd062014-01-12 11:14:54 -0500276 print("16bit size: %d" % size16)
277 print("32bit segmented size: %d" % size32seg)
278 print("32bit flat size: %d" % size32flat)
279 print("32bit flat init size: %d" % size32init)
280 print("Lowmem size: %d" % sizelow)
281 print("f-segment var size: %d" % size32fseg)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400282 return li
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400283
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400284
285######################################################################
286# Linker script output
287######################################################################
288
289# Write LD script includes for the given cross references
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500290def outXRefs(sections, useseg=0, exportsyms=[], forcedelta=0):
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500291 xrefs = dict([(symbol.name, symbol) for symbol in exportsyms])
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400292 out = ""
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400293 for section in sections:
294 for reloc in section.relocs:
295 symbol = reloc.symbol
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500296 if (symbol.section is not None
297 and (symbol.section.fileid != section.fileid
298 or symbol.name != reloc.symbolname)):
299 xrefs[reloc.symbolname] = symbol
300 for symbolname, symbol in xrefs.items():
301 loc = symbol.section.finalloc
302 if useseg:
303 loc = symbol.section.finalsegloc
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500304 out += "%s = 0x%x ;\n" % (symbolname, loc + forcedelta + symbol.offset)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400305 return out
306
307# Write LD script includes for the given sections using relative offsets
Kevin O'Connor46b82622012-05-13 12:10:30 -0400308def outRelSections(sections, startsym, useseg=0):
309 sections = [(section.finalloc, section) for section in sections
310 if section.finalloc is not None]
311 sections.sort()
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400312 out = ""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400313 for addr, section in sections:
314 loc = section.finalloc
315 if useseg:
316 loc = section.finalsegloc
317 out += ". = ( 0x%x - %s ) ;\n" % (loc, startsym)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400318 if section.name == '.rodata.str1.1':
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400319 out += "_rodata = . ;\n"
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400320 out += "*(%s)\n" % (section.name,)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400321 return out
322
Kevin O'Connor46b82622012-05-13 12:10:30 -0400323# Build linker script output for a list of relocations.
324def strRelocs(outname, outrel, relocs):
325 relocs.sort()
326 return (" %s_start = ABSOLUTE(.) ;\n" % (outname,)
327 + "".join(["LONG(0x%x - %s)\n" % (pos, outrel)
328 for pos in relocs])
329 + " %s_end = ABSOLUTE(.) ;\n" % (outname,))
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500330
Kevin O'Connor46b82622012-05-13 12:10:30 -0400331# Find all relocations in the given sections with the given attributes
332def getRelocs(sections, type=None, category=None, notcategory=None):
333 out = []
334 for section in sections:
335 for reloc in section.relocs:
336 if reloc.symbol.section is None:
337 continue
338 destcategory = reloc.symbol.section.category
339 if ((type is None or reloc.type == type)
340 and (category is None or destcategory == category)
341 and (notcategory is None or destcategory != notcategory)):
342 out.append(section.finalloc + reloc.offset)
343 return out
344
345# Return the start address and minimum alignment for a set of sections
346def getSectionsStart(sections, defaddr=0):
347 return min([section.finalloc for section in sections
348 if section.finalloc is not None] or [defaddr])
349
350# Output the linker scripts for all required sections.
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500351def writeLinkerScripts(li, out16, out32seg, out32flat):
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400352 # Write 16bit linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400353 out = outXRefs(li.sections16, useseg=1) + """
Kevin O'Connorc9243442013-02-17 13:58:28 -0500354 zonelow_base = 0x%x ;
355 _zonelow_seg = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400356
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400357 code16_start = 0x%x ;
358 .text16 code16_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400359%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400360 }
Kevin O'Connorc9243442013-02-17 13:58:28 -0500361""" % (li.zonelow_base,
362 li.zonelow_base / 16,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400363 li.sec16_start - BUILD_BIOS_ADDR,
364 outRelSections(li.sections16, 'code16_start', useseg=1))
365 outfile = open(out16, 'wb')
366 outfile.write(COMMONHEADER + out + COMMONTRAILER)
367 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500368
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400369 # Write 32seg linker script
Kevin O'Connor46b82622012-05-13 12:10:30 -0400370 out = outXRefs(li.sections32seg, useseg=1) + """
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400371 code32seg_start = 0x%x ;
372 .text32seg code32seg_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400373%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400374 }
Kevin O'Connor46b82622012-05-13 12:10:30 -0400375""" % (li.sec32seg_start - BUILD_BIOS_ADDR,
376 outRelSections(li.sections32seg, 'code32seg_start', useseg=1))
377 outfile = open(out32seg, 'wb')
378 outfile.write(COMMONHEADER + out + COMMONTRAILER)
379 outfile.close()
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500380
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400381 # Write 32flat linker script
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500382 sections32all = (li.sections32flat + li.sections32init + li.sections32fseg)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400383 sec32all_start = li.sec32low_start
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400384 relocstr = ""
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500385 if li.genreloc:
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400386 # Generate relocations
Kevin O'Connor46b82622012-05-13 12:10:30 -0400387 absrelocs = getRelocs(
388 li.sections32init, type='R_386_32', category='32init')
389 relrelocs = getRelocs(
390 li.sections32init, type='R_386_PC32', notcategory='32init')
391 initrelocs = getRelocs(
392 li.sections32flat + li.sections32low + li.sections16
Kevin O'Connor41953492013-02-18 23:09:01 -0500393 + li.sections32seg + li.sections32fseg, category='32init')
Kevin O'Connor46b82622012-05-13 12:10:30 -0400394 relocstr = (strRelocs("_reloc_abs", "code32init_start", absrelocs)
395 + strRelocs("_reloc_rel", "code32init_start", relrelocs)
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500396 + strRelocs("_reloc_init", "code32flat_start", initrelocs))
397 numrelocs = len(absrelocs + relrelocs + initrelocs)
Kevin O'Connor46b82622012-05-13 12:10:30 -0400398 sec32all_start -= numrelocs * 4
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500399 out = outXRefs(li.sections32low, exportsyms=li.varlowsyms
400 , forcedelta=li.final_sec32low_start-li.sec32low_start)
401 out += outXRefs(sections32all, exportsyms=li.exportsyms) + """
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400402 _reloc_min_align = 0x%x ;
Kevin O'Connor6d152642013-02-19 21:35:20 -0500403 zonefseg_start = 0x%x ;
404 zonefseg_end = 0x%x ;
Kevin O'Connorc9243442013-02-17 13:58:28 -0500405 zonelow_base = 0x%x ;
406 final_varlow_start = 0x%x ;
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500407 final_readonly_start = 0x%x ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400408
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400409 code32flat_start = 0x%x ;
410 .text code32flat_start : {
Kevin O'Connor46b82622012-05-13 12:10:30 -0400411%s
Kevin O'Connorc9243442013-02-17 13:58:28 -0500412 varlow_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400413%s
Kevin O'Connorc9243442013-02-17 13:58:28 -0500414 varlow_end = ABSOLUTE(.) ;
Kevin O'Connor402fd9c2010-09-15 00:26:19 -0400415 code32init_start = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400416%s
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400417 code32init_end = ABSOLUTE(.) ;
Kevin O'Connor46b82622012-05-13 12:10:30 -0400418%s
Kevin O'Connor41953492013-02-18 23:09:01 -0500419%s
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400420 . = ( 0x%x - code32flat_start ) ;
421 *(.text32seg)
422 . = ( 0x%x - code32flat_start ) ;
423 *(.text16)
424 code32flat_end = ABSOLUTE(.) ;
425 } :text
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500426""" % (li.sec32init_align,
Kevin O'Connor6d152642013-02-19 21:35:20 -0500427 li.zonefseg_start,
428 li.zonefseg_end,
Kevin O'Connorc9243442013-02-17 13:58:28 -0500429 li.zonelow_base,
Kevin O'Connorc91da7a2012-06-08 21:14:19 -0400430 li.final_sec32low_start,
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500431 li.final_readonly_start,
Kevin O'Connor46b82622012-05-13 12:10:30 -0400432 sec32all_start,
433 relocstr,
434 outRelSections(li.sections32low, 'code32flat_start'),
435 outRelSections(li.sections32init, 'code32flat_start'),
436 outRelSections(li.sections32flat, 'code32flat_start'),
Kevin O'Connor41953492013-02-18 23:09:01 -0500437 outRelSections(li.sections32fseg, 'code32flat_start'),
Kevin O'Connor46b82622012-05-13 12:10:30 -0400438 li.sec32seg_start,
439 li.sec16_start)
440 out = COMMONHEADER + out + COMMONTRAILER + """
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500441ENTRY(entry_elf)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400442PHDRS
443{
444 text PT_LOAD AT ( code32flat_start ) ;
445}
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500446"""
Kevin O'Connor46b82622012-05-13 12:10:30 -0400447 outfile = open(out32flat, 'wb')
448 outfile.write(out)
449 outfile.close()
Kevin O'Connorc0693942009-06-10 21:56:01 -0400450
451
452######################################################################
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400453# Detection of init code
454######################################################################
455
Kevin O'Connor2af52da2013-03-08 19:36:28 -0500456def markRuntime(section, sections, chain=[]):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400457 if (section is None or not section.keep or section.category is not None
458 or '.init.' in section.name or section.fileid != '32flat'):
459 return
Kevin O'Connor2af52da2013-03-08 19:36:28 -0500460 if '.data.varinit.' in section.name:
Johannes Krampf064fd062014-01-12 11:14:54 -0500461 print("ERROR: %s is VARVERIFY32INIT but used from %s" % (
462 section.name, chain))
Kevin O'Connor2af52da2013-03-08 19:36:28 -0500463 sys.exit(1)
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400464 section.category = '32flat'
465 # Recursively mark all sections this section points to
466 for reloc in section.relocs:
Kevin O'Connor2af52da2013-03-08 19:36:28 -0500467 markRuntime(reloc.symbol.section, sections, chain + [section.name])
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400468
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500469def findInit(sections):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400470 # Recursively find and mark all "runtime" sections.
471 for section in sections:
Kevin O'Connor41953492013-02-18 23:09:01 -0500472 if ('.data.varlow.' in section.name or '.data.varfseg.' in section.name
473 or '.runtime.' in section.name or '.export.' in section.name):
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400474 markRuntime(section, sections)
475 for section in sections:
476 if section.category is not None:
477 continue
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500478 if section.fileid == '32flat':
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400479 section.category = '32init'
480 else:
481 section.category = section.fileid
482
483
484######################################################################
Kevin O'Connorc0693942009-06-10 21:56:01 -0400485# Section garbage collection
486######################################################################
487
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500488CFUNCPREFIX = [('_cfunc16_', 0), ('_cfunc32seg_', 1), ('_cfunc32flat_', 2)]
489
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500490# Find and keep the section associated with a symbol (if available).
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500491def keepsymbol(reloc, infos, pos, isxref):
492 symbolname = reloc.symbolname
493 mustbecfunc = 0
494 for symprefix, needpos in CFUNCPREFIX:
495 if symbolname.startswith(symprefix):
496 if needpos != pos:
497 return -1
498 symbolname = symbolname[len(symprefix):]
499 mustbecfunc = 1
500 break
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400501 symbol = infos[pos][1].get(symbolname)
502 if (symbol is None or symbol.section is None
503 or symbol.section.name.startswith('.discard.')):
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500504 return -1
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500505 isdestcfunc = (symbol.section.name.startswith('.text.')
506 and not symbol.section.name.startswith('.text.asm.'))
507 if ((mustbecfunc and not isdestcfunc)
508 or (not mustbecfunc and isdestcfunc and isxref)):
509 return -1
510
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400511 reloc.symbol = symbol
512 keepsection(symbol.section, infos, pos)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500513 return 0
514
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400515# Note required section, and recursively set all referenced sections
516# as required.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400517def keepsection(section, infos, pos=0):
518 if section.keep:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400519 # Already kept - nothing to do.
520 return
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400521 section.keep = 1
Kevin O'Connorc0693942009-06-10 21:56:01 -0400522 # Keep all sections that this section points to
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400523 for reloc in section.relocs:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500524 ret = keepsymbol(reloc, infos, pos, 0)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500525 if not ret:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400526 continue
527 # Not in primary sections - it may be a cross 16/32 reference
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500528 ret = keepsymbol(reloc, infos, (pos+1)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500529 if not ret:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500530 continue
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500531 ret = keepsymbol(reloc, infos, (pos+2)%3, 1)
Kevin O'Connorfdca4182010-01-01 12:46:54 -0500532 if not ret:
533 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400534
Kevin O'Connor5b8f8092009-09-20 19:47:45 -0400535# Determine which sections are actually referenced and need to be
536# placed into the output file.
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500537def gc(info16, info32seg, info32flat):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400538 # infos = ((sections16, symbols16), (sect32seg, sym32seg)
539 # , (sect32flat, sym32flat))
540 infos = (info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400541 # Start by keeping sections that are globally visible.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400542 for section in info16[0]:
543 if section.name.startswith('.fixedaddr.') or '.export.' in section.name:
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500544 keepsection(section, infos)
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400545 return [section for section in info16[0]+info32seg[0]+info32flat[0]
546 if section.keep]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400547
548
549######################################################################
550# Startup and input parsing
551######################################################################
552
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400553class Section:
554 name = size = alignment = fileid = relocs = None
Kevin O'Connor46b82622012-05-13 12:10:30 -0400555 finalloc = finalsegloc = category = keep = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400556class Reloc:
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500557 offset = type = symbolname = symbol = None
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400558class Symbol:
559 name = offset = section = None
560
Kevin O'Connorc0693942009-06-10 21:56:01 -0400561# Read in output from objdump
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400562def parseObjDump(file, fileid):
563 # sections = [section, ...]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400564 sections = []
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400565 sectionmap = {}
566 # symbols[symbolname] = symbol
Kevin O'Connorc0693942009-06-10 21:56:01 -0400567 symbols = {}
Kevin O'Connorc0693942009-06-10 21:56:01 -0400568
569 state = None
570 for line in file.readlines():
571 line = line.rstrip()
572 if line == 'Sections:':
573 state = 'section'
574 continue
575 if line == 'SYMBOL TABLE:':
576 state = 'symbol'
577 continue
Kevin O'Connor6c2e7812010-09-13 18:04:02 -0400578 if line.startswith('RELOCATION RECORDS FOR ['):
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400579 sectionname = line[24:-2]
580 if sectionname.startswith('.debug_'):
581 # Skip debugging sections (to reduce parsing time)
582 state = None
583 continue
Kevin O'Connorc0693942009-06-10 21:56:01 -0400584 state = 'reloc'
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400585 relocsection = sectionmap[sectionname]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400586 continue
587
588 if state == 'section':
589 try:
590 idx, name, size, vma, lma, fileoff, align = line.split()
591 if align[:3] != '2**':
592 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400593 section = Section()
594 section.name = name
595 section.size = int(size, 16)
596 section.align = 2**int(align[3:])
597 section.fileid = fileid
598 section.relocs = []
599 sections.append(section)
600 sectionmap[name] = section
601 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400602 pass
603 continue
604 if state == 'symbol':
605 try:
Kevin O'Connor90ebed42012-06-21 20:54:53 -0400606 parts = line[17:].split()
607 if len(parts) == 3:
608 sectionname, size, name = parts
609 elif len(parts) == 4 and parts[2] == '.hidden':
610 sectionname, size, hidden, name = parts
611 else:
612 continue
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400613 symbol = Symbol()
614 symbol.size = int(size, 16)
615 symbol.offset = int(line[:8], 16)
616 symbol.name = name
617 symbol.section = sectionmap.get(sectionname)
618 symbols[name] = symbol
619 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400620 pass
621 continue
622 if state == 'reloc':
623 try:
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400624 off, type, symbolname = line.split()
625 reloc = Reloc()
626 reloc.offset = int(off, 16)
627 reloc.type = type
Kevin O'Connorf3fe3aa2010-12-05 12:38:33 -0500628 reloc.symbolname = symbolname
Kevin O'Connor67863be2010-12-24 10:23:10 -0500629 reloc.symbol = symbols.get(symbolname)
630 if reloc.symbol is None:
631 # Some binutils (2.20.1) give section name instead
632 # of a symbol - create a dummy symbol.
633 reloc.symbol = symbol = Symbol()
634 symbol.size = 0
635 symbol.offset = 0
636 symbol.name = symbolname
637 symbol.section = sectionmap.get(symbolname)
638 symbols[symbolname] = symbol
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400639 relocsection.relocs.append(reloc)
640 except ValueError:
Kevin O'Connorc0693942009-06-10 21:56:01 -0400641 pass
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400642 return sections, symbols
Kevin O'Connorc0693942009-06-10 21:56:01 -0400643
Kevin O'Connor2b0fb8c2013-08-07 23:03:47 -0400644# Parser for constants in simple C header files.
645def scanconfig(file):
646 f = open(file, 'rb')
647 opts = {}
648 for l in f.readlines():
649 parts = l.split()
650 if len(parts) != 3:
651 continue
652 if parts[0] != '#define':
653 continue
654 value = parts[2]
655 if value.isdigit() or (value.startswith('0x') and value[2:].isdigit()):
656 value = int(value, 0)
657 opts[parts[1]] = value
658 return opts
659
Kevin O'Connorc0693942009-06-10 21:56:01 -0400660def main():
661 # Get output name
Kevin O'Connor2b0fb8c2013-08-07 23:03:47 -0400662 in16, in32seg, in32flat, cfgfile, out16, out32seg, out32flat = sys.argv[1:]
Kevin O'Connorc0693942009-06-10 21:56:01 -0400663
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400664 # Read in the objdump information
Kevin O'Connorc0693942009-06-10 21:56:01 -0400665 infile16 = open(in16, 'rb')
Kevin O'Connor871e0a02009-12-30 12:14:53 -0500666 infile32seg = open(in32seg, 'rb')
667 infile32flat = open(in32flat, 'rb')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400668
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400669 # infoX = (sections, symbols)
670 info16 = parseObjDump(infile16, '16')
671 info32seg = parseObjDump(infile32seg, '32seg')
672 info32flat = parseObjDump(infile32flat, '32flat')
Kevin O'Connorc0693942009-06-10 21:56:01 -0400673
Kevin O'Connor2b0fb8c2013-08-07 23:03:47 -0400674 # Read kconfig config file
675 config = scanconfig(cfgfile)
676
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400677 # Figure out which sections to keep.
Kevin O'Connor1a4885e2010-09-15 21:28:31 -0400678 sections = gc(info16, info32seg, info32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400679
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400680 # Separate 32bit flat into runtime and init parts
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500681 findInit(sections)
Kevin O'Connord1b4f962010-09-15 21:38:16 -0400682
Kevin O'Connor41953492013-02-18 23:09:01 -0500683 # Note "low memory" and "fseg memory" parts
Kevin O'Connorc9243442013-02-17 13:58:28 -0500684 for section in getSectionsPrefix(sections, '.data.varlow.'):
Kevin O'Connor46b82622012-05-13 12:10:30 -0400685 section.category = '32low'
Kevin O'Connor41953492013-02-18 23:09:01 -0500686 for section in getSectionsPrefix(sections, '.data.varfseg.'):
687 section.category = '32fseg'
Kevin O'Connor46b82622012-05-13 12:10:30 -0400688
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400689 # Determine the final memory locations of each kept section.
Kevin O'Connorb94170c2013-12-06 13:52:16 -0500690 genreloc = '_reloc_abs_start' in info32flat[1]
691 li = doLayout(sections, config, genreloc)
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400692
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500693 # Exported symbols
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500694 li.exportsyms = [symbol for symbol in info16[1].values()
695 if (symbol.section is not None
696 and '.export.' in symbol.section.name
697 and symbol.name != symbol.section.name)]
698 li.varlowsyms = [symbol for symbol in info32flat[1].values()
699 if (symbol.section is not None
700 and symbol.section.finalloc is not None
701 and '.data.varlow.' in symbol.section.name
702 and symbol.name != symbol.section.name)]
Kevin O'Connora3c48f52013-02-05 22:36:13 -0500703
Kevin O'Connor9ba1dea2010-05-01 09:50:13 -0400704 # Write out linker script files.
Kevin O'Connor6afc6f82013-02-19 01:02:50 -0500705 writeLinkerScripts(li, out16, out32seg, out32flat)
Kevin O'Connorc0693942009-06-10 21:56:01 -0400706
Kevin O'Connor202024a2009-01-17 10:41:28 -0500707if __name__ == '__main__':
708 main()