1 # -*- coding: utf-8 -*-
2 # kate: space-indent on; indent-width 2; mixedindent off; indent-mode python;
4 # Copyright (C) 2009 Amand 'alrj' Tihon <amand.tihon@alrj.org>
6 # This file is part of bold, the Byte Optimized Linker.
8 # You can redistribute this file and/or modify it under the terms of the
9 # GNU General Public License as published by the Free Software Foundation,
10 # either version 3 of the License or (at your option) any later version.
13 Main entry point for the bold linker.
16 from constants import *
17 from BinArray import BinArray
18 from elf import Elf64, Elf64_Phdr, Elf64_Shdr, TextSegment, DataSegment
19 from elf import SStrtab, SSymtab, SProgBits, SNobits, Dynamic, Interpreter
21 from ctypes import CDLL
22 from ctypes.util import find_library
27 """Caculate the hash of the function name.
28 @param name: the string to hash
29 @return: 32 bits hash value.
33 h = ((h * 0x21) ^ ord(c)) & 0xffffffff
37 class BoldLinker(object):
38 """A Linker object takes one or more objects files, optional shared libs,
39 and arranges all this in an executable.
47 self.entry_point = "_start"
49 self.global_symbols = {}
50 self.undefined_symbols = set()
51 self.common_symbols = set()
54 def add_object(self, filename):
55 """Add a relocatable file as input.
56 @param filename: path to relocatable object file to add
64 def build_symbols_tables(self):
65 """Find out the globally available symbols, as well as the globally
66 undefined ones (which should be found in external libraries."""
68 # Gather the "extern" and common symbols from each input files.
70 self.undefined_symbols.update(i.undefined_symbols)
71 self.common_symbols.update(i.common_symbols)
73 # Make a dict with all the symbols declared globally.
74 # Key is the symbol name, value will later be set to the final
75 # virtual address. Currently, we're only interrested in the declaration.
76 # The virtual addresses are set to None, they'll be resolved later.
78 for s in i.global_symbols:
79 if s in self.global_symbols:
80 raise RedefinedSymbol(s)
81 self.global_symbols[s] = None
83 # Add a few useful symbols. They'll be resolved ater as well.
84 self.global_symbols["_dt_debug"] = None
85 self.global_symbols["_DYNAMIC"] = None
87 # Find out which symbols aren't really defined anywhere
88 self.undefined_symbols.difference_update(self.global_symbols)
90 # A symbol declared as COMMON in one object may very well have been
91 # defined in another. In this case, it will be present in the
93 # Take a copy because we can't change the set's size inside the loop
94 for i in self.common_symbols.copy():
95 if i[0] in self.global_symbols:
96 self.common_symbols.remove(i)
99 def build_external(self, with_jump=False, align_jump=False):
101 Generate a fake relocatable object, for dynamic linking.
102 This object is then automatically added in the list of ebjects to link.
103 TODO: This part is extremely non-portable.
106 # Find out all the undefined symbols. They're the one we'll need to resolve
108 symbols = sorted(list(self.undefined_symbols))
110 # Those three will soon be known...
111 symbols.remove('_bold__functions_count')
112 symbols.remove('_bold__functions_hash')
113 symbols.remove('_bold__functions_pointers')
115 # Create the fake ELF object.
116 fo = Elf64() # Don't care about most parts of ELF header (?)
117 fo.filename = "Internal dynamic linker"
119 # We need a .data section, a .bss section and a possibly a .text section
120 data_shdr = Elf64_Shdr()
121 data_shdr.sh_type = SHT_PROGBITS
122 data_shdr.sh_flags = (SHF_WRITE | SHF_ALLOC)
123 data_shdr.sh_size = len(symbols) * 4
124 fmt = "<" + "I" * len(symbols)
125 data_shdr.content = BinArray(struct.pack(fmt, *[hash_name(s) for s in symbols]))
126 fo.shdrs.append(data_shdr)
127 fo.sections['.data'] = data_shdr
129 bss_shdr = Elf64_Shdr()
130 bss_shdr.sh_type = SHT_NOBITS
131 bss_shdr.sh_flags = (SHF_WRITE | SHF_ALLOC)
132 bss_shdr.content = BinArray("")
133 fo.shdrs.append(bss_shdr)
134 fo.sections['.bss'] = bss_shdr
137 text_shdr = Elf64_Shdr()
138 text_shdr.sh_type = SHT_PROGBITS
139 text_shdr.sh_flags = (SHF_ALLOC | SHF_EXECINSTR)
140 text_shdr.sh_size = len(symbols) * 8
142 fmt = '\xff\x25\x00\x00\x00\x00\x00\x00' # ff 25 = jmp [rel label]
145 fmt = '\xff\x25\x00\x00\x00\x00'
147 text_shdr.content = BinArray(fmt * len(symbols))
148 fo.shdrs.append(text_shdr)
149 fo.sections['.text'] = text_shdr
151 # Cheating here. All symbols declared as global so we don't need to create
152 # a symtab from scratch.
153 fo.global_symbols = {}
154 fo.global_symbols['_bold__functions_count'] = (SHN_ABS, len(symbols))
155 fo.global_symbols['_bold__functions_hash'] = (data_shdr, 0)
156 fo.global_symbols['_bold__functions_pointers'] = (bss_shdr, 0)
158 # The COMMON symbols. Assign an offset in .bss, declare as global.
159 bss_common_offset = len(symbols) * 8
160 for s_name, s_size, s_alignment in self.common_symbols:
161 padding = (s_alignment - (bss_common_offset % s_alignment)) % s_alignment
162 bss_common_offset += padding
163 fo.global_symbols[s_name] = (bss_shdr, bss_common_offset)
164 bss_common_offset += s_size
166 bss_shdr.sh_size = bss_common_offset
168 for n, i in enumerate(symbols):
169 # The hash is always in .data
170 h = "_bold__hash_%s" % i
171 fo.global_symbols[h] = (data_shdr, n * 4) # Section, offset
174 # the symbol is in .text, can be called directly
175 fo.global_symbols[i] = (text_shdr, n * jmp_size)
176 # another symbol can be used to reference the pointer, just in case.
178 fo.global_symbols[p] = (bss_shdr, n * 8)
181 # The symbol is in .bss, must be called indirectly
182 fo.global_symbols[i] = (bss_shdr, n * 8)
185 # Add relocation entries for the jumps
186 # Relocation will be done for the .text, for every jmp instruction.
188 rela_shdr = Elf64_Shdr()
189 rela_shdr.sh_type = SHT_RELA
190 rela_shdr.target = text_shdr
191 rela_shdr.sh_flags = 0
192 rela_shdr._content = dummy() # We only need a container for relatab...
193 relatab = [] # Prepare a relatab
194 rela_shdr.content.relatab = relatab
196 for n, i in enumerate(symbols):
197 # Create a relocation entry for each symbol
199 reloc.r_offset = (n * jmp_size) + 2 # Beginning of the cell to update
201 reloc.r_type = R_X86_64_PC32
202 reloc.symbol = dummy()
203 reloc.symbol.st_shndx = SHN_UNDEF
204 reloc.symbol.name = "_bold__%s" % i
205 relatab.append(reloc)
206 fo.shdrs.append(rela_shdr)
207 fo.sections['.rela.text'] = rela_shdr
209 # Ok, let's add this fake object
213 def add_shlib(self, libname):
214 """Add a shared library to link against."""
215 # Note : we use ctypes' find_library to find the real name
216 fullname = find_library(libname)
218 raise LibNotFound(libname)
219 self.shlibs.append(fullname)
222 def check_external(self):
223 """Verify that all globally undefined symbols are present in shared
226 for libname in self.shlibs:
227 libs.append(CDLL(libname))
229 for symbol in self.undefined_symbols:
231 if symbol.startswith('_bold__'):
235 if hasattr(lib, symbol):
239 raise UndefinedSymbol(symbol)
243 """Do the actual linking."""
244 # Prepare two segments. One for .text, the other for .data + .bss
245 self.text_segment = TextSegment()
246 # .data will be mapped 0x100000 bytes further
247 self.data_segment = DataSegment(align=0x100000)
248 self.output.add_segment(self.text_segment)
249 self.output.add_segment(self.data_segment)
251 # Adjust the ELF header
252 self.output.header.e_ident.make_default_amd64()
253 self.output.header.e_phoff = self.output.header.size
254 self.output.header.e_type = ET_EXEC
255 # Elf header lies inside .text
256 self.text_segment.add_content(self.output.header)
258 # Create the four Program Headers. They'll be inside .text
259 # The first Program Header defines .text
260 ph_text = Elf64_Phdr()
261 ph_text.p_type = PT_LOAD
262 ph_text.p_align = 0x100000
263 self.output.add_phdr(ph_text)
264 self.text_segment.add_content(ph_text)
266 # Second one defines .data + .bss
267 ph_data = Elf64_Phdr()
268 ph_data.p_type = PT_LOAD
269 ph_data.p_align = 0x100000
270 self.output.add_phdr(ph_data)
271 self.text_segment.add_content(ph_data)
273 # Third one is only there to define the DYNAMIC section
274 ph_dynamic = Elf64_Phdr()
275 ph_dynamic.p_type = PT_DYNAMIC
276 self.output.add_phdr(ph_dynamic)
277 self.text_segment.add_content(ph_dynamic)
279 # Fourth one is for interp
280 ph_interp = Elf64_Phdr()
281 ph_interp.p_type = PT_INTERP
282 self.output.add_phdr(ph_interp)
283 self.text_segment.add_content(ph_interp)
285 # We have all the needed program headers, update ELF header
286 self.output.header.ph_num = len(self.output.phdrs)
288 # Create the actual content for the interpreter section
289 interp = Interpreter()
290 self.text_segment.add_content(interp)
292 # Then the Dynamic section
294 # for all the requested libs, add a reference in the Dynamic table
295 for lib in self.shlibs:
296 dynamic.add_shlib(lib)
297 # Add an empty symtab, symbol resolution is not done.
298 dynamic.add_symtab(0)
299 # And we need a DT_DEBUG
302 # This belongs to .data
303 self.data_segment.add_content(dynamic)
304 # The dynamic table links to a string table for the libs' names.
305 self.text_segment.add_content(dynamic.strtab)
307 # We can now add the interesting sections to the corresponding segments
310 # Only ALLOC sections are worth it.
311 # This might require change in the future
312 if not (sh.sh_flags & SHF_ALLOC):
315 if (sh.sh_flags & SHF_EXECINSTR):
316 self.text_segment.add_content(sh.content)
317 else: # No exec, it's for .data or .bss
318 if (sh.sh_type == SHT_NOBITS):
319 self.data_segment.add_nobits(sh.content)
321 self.data_segment.add_content(sh.content)
323 # Now, everything is at its place.
324 # Knowing the base address, we can determine where everyone will fall
325 self.output.layout(base_vaddr=0x400000)
327 # Knowing the addresses of all the parts, Program Headers can be filled
328 # This will put the correct p_offset, p_vaddr, p_filesz and p_memsz
329 ph_text.update_from_content(self.text_segment)
330 ph_data.update_from_content(self.data_segment)
331 ph_interp.update_from_content(interp)
332 ph_dynamic.update_from_content(dynamic)
334 # All parts are at their final address, find out the symbols' addresses
336 for s in i.global_symbols:
337 # Final address is the section's base address + the symbol's offset
338 if i.global_symbols[s][0] == SHN_ABS:
339 addr = i.global_symbols[s][1]
341 addr = i.global_symbols[s][0].content.virt_addr
342 addr += i.global_symbols[s][1]
344 self.global_symbols[s] = addr
346 # Resolve the few useful symbols
347 self.global_symbols["_dt_debug"] = dynamic.dt_debug_address
348 self.global_symbols["_DYNAMIC"] = dynamic.virt_addr
350 # We can now do the actual relocation
352 i.apply_relocation(self.global_symbols)
354 # And update the ELF header with the entry point
355 if not self.entry_point in self.global_symbols:
356 raise UndefinedSymbol(self.entry_point)
357 self.output.header.e_entry = self.global_symbols[self.entry_point]
362 def toBinArray(self):
363 return self.output.toBinArray()
366 def tofile(self, file_object):
367 return self.output.toBinArray().tofile(file_object)