]> git.alrj.org Git - bold.git/blob - Bold/linker.py
First support for .gnu.hash/DT_GNU_HASH.
[bold.git] / Bold / linker.py
1 # -*- coding: utf-8 -*-
2 # kate: space-indent on; indent-width 2; mixedindent off; indent-mode python;
3
4 # Copyright (C) 2009 Amand 'alrj' Tihon <amand.tihon@alrj.org>
5 #
6 # This file is part of bold, the Byte Optimized Linker.
7 #
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.
11
12 """
13 Main entry point for the bold linker.
14 """
15
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
20 from errors import *
21 from ctypes import CDLL
22 from ctypes.util import find_library
23 import struct
24
25
26 def hash_name(name):
27   """Caculate the hash of the function name.
28   @param name: the string to hash
29   @return: 32 bits hash value.
30   """
31   h = 0
32   for c in name:
33     h = ((h * 0x21) ^ ord(c)) & 0xffffffff
34   return h
35
36
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.
40   """
41
42   def __init__(self):
43     object.__init__(self)
44
45     self.objs = []
46     self.shlibs = []
47     self.entry_point = "_start"
48     self.output = Elf64()
49     self.global_symbols = {}
50     self.undefined_symbols = set()
51     self.common_symbols = set()
52
53
54   def add_object(self, filename):
55     """Add a relocatable file as input.
56     @param filename: path to relocatable object file to add
57     """
58     obj = Elf64(filename)
59     obj.resolve_names()
60     obj.find_symbols()
61     self.objs.append(obj)
62
63
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."""
67
68     # Gather the "extern" and common symbols from each input files.
69     for i in self.objs:
70       self.undefined_symbols.update(i.undefined_symbols)
71       self.common_symbols.update(i.common_symbols)
72
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.
77     for i in self.objs:
78       for s in i.global_symbols:
79         if s in self.global_symbols:
80           raise RedefinedSymbol(s)
81         self.global_symbols[s] = None
82
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
86
87     # Find out which symbols aren't really defined anywhere
88     self.undefined_symbols.difference_update(self.global_symbols)
89
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
92     # global_symbols.
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)
97
98
99   def build_external(self, with_jump=False, align_jump=False):
100     """
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.
104     """
105
106     # Find out all the undefined symbols. They're the one we'll need to resolve
107     # dynamically.
108     symbols = sorted(list(self.undefined_symbols))
109
110     # Those three will soon be known...
111     if '_bold__functions_count' in symbols:
112       symbols.remove('_bold__functions_count')
113     if '_bold__functions_hash' in symbols:
114       symbols.remove('_bold__functions_hash')
115     if '_bold__functions_pointers' in symbols:
116       symbols.remove('_bold__functions_pointers')
117
118     # Create the fake ELF object.
119     fo = Elf64() # Don't care about most parts of ELF header (?)
120     fo.filename = "Internal dynamic linker"
121
122     # We need a .data section, a .bss section and a possibly a .text section
123     data_shdr = Elf64_Shdr()
124     data_shdr.sh_type = SHT_PROGBITS
125     data_shdr.sh_flags = (SHF_WRITE | SHF_ALLOC)
126     data_shdr.sh_size = len(symbols) * 4
127     fmt = "<" + "I" * len(symbols)
128     data_shdr.content = BinArray(struct.pack(fmt, *[hash_name(s) for s in symbols]))
129     fo.shdrs.append(data_shdr)
130     fo.sections['.data'] = data_shdr
131
132     bss_shdr = Elf64_Shdr()
133     bss_shdr.sh_type = SHT_NOBITS
134     bss_shdr.sh_flags = (SHF_WRITE | SHF_ALLOC)
135     bss_shdr.content = BinArray("")
136     fo.shdrs.append(bss_shdr)
137     fo.sections['.bss'] = bss_shdr
138
139     if with_jump:
140       text_shdr = Elf64_Shdr()
141       text_shdr.sh_type = SHT_PROGBITS
142       text_shdr.sh_flags = (SHF_ALLOC | SHF_EXECINSTR)
143       text_shdr.sh_size = len(symbols) * 8
144       if align_jump:
145         fmt = '\xff\x25\x00\x00\x00\x00\x00\x00' # ff 25 = jmp [rel label]
146         jmp_size = 8
147       else:
148         fmt = '\xff\x25\x00\x00\x00\x00'
149         jmp_size = 6
150       text_shdr.content = BinArray(fmt * len(symbols))
151       fo.shdrs.append(text_shdr)
152       fo.sections['.text'] = text_shdr
153
154     # Cheating here. All symbols declared as global so we don't need to create
155     # a symtab from scratch.
156     fo.global_symbols = {}
157     fo.global_symbols['_bold__functions_count'] = (SHN_ABS, len(symbols))
158     fo.global_symbols['_bold__functions_hash'] = (data_shdr, 0)
159     fo.global_symbols['_bold__functions_pointers'] = (bss_shdr, 0)
160
161     # The COMMON symbols. Assign an offset in .bss, declare as global.
162     bss_common_offset = len(symbols) * 8
163     for s_name, s_size, s_alignment in self.common_symbols:
164       padding = (s_alignment - (bss_common_offset % s_alignment)) % s_alignment
165       bss_common_offset += padding
166       fo.global_symbols[s_name] = (bss_shdr, bss_common_offset)
167       bss_common_offset += s_size
168
169     bss_shdr.sh_size = bss_common_offset
170
171     for n, i in enumerate(symbols):
172       # The hash is always in .data
173       h = "_bold__hash_%s" % i
174       fo.global_symbols[h] = (data_shdr, n * 4) # Section, offset
175
176       if with_jump:
177         # the symbol is in .text, can be called directly
178         fo.global_symbols[i] = (text_shdr, n * jmp_size)
179         # another symbol can be used to reference the pointer, just in case.
180         p = "_bold__%s" % i
181         fo.global_symbols[p] = (bss_shdr, n * 8)
182
183       else:
184         # The symbol is in .bss, must be called indirectly
185         fo.global_symbols[i] = (bss_shdr, n * 8)
186
187     if with_jump:
188       # Add relocation entries for the jumps
189       # Relocation will be done for the .text, for every jmp instruction.
190       class dummy: pass
191       rela_shdr = Elf64_Shdr()
192       rela_shdr.sh_type = SHT_RELA
193       rela_shdr.target = text_shdr
194       rela_shdr.sh_flags = 0
195       rela_shdr._content = dummy() # We only need a container for relatab...
196       relatab = []                      # Prepare a relatab
197       rela_shdr.content.relatab = relatab
198
199       for n, i in enumerate(symbols):
200         # Create a relocation entry for each symbol
201         reloc = dummy()
202         reloc.r_offset = (n * jmp_size) + 2   # Beginning of the cell to update
203         reloc.r_addend = -4
204         reloc.r_type = R_X86_64_PC32
205         reloc.symbol = dummy()
206         reloc.symbol.st_shndx = SHN_UNDEF
207         reloc.symbol.name = "_bold__%s" % i
208         relatab.append(reloc)
209       fo.shdrs.append(rela_shdr)
210       fo.sections['.rela.text'] = rela_shdr
211
212     # Ok, let's add this fake object
213     self.objs.append(fo)
214
215
216   def add_shlib(self, libname):
217     """Add a shared library to link against."""
218     # Note : we use ctypes' find_library to find the real name
219     fullname = find_library(libname)
220     if not fullname:
221       raise LibNotFound(libname)
222     self.shlibs.append(fullname)
223
224
225   def check_external(self):
226     """Verify that all globally undefined symbols are present in shared
227     libraries."""
228     libs = []
229     for libname in self.shlibs:
230       libs.append(CDLL(libname))
231
232     for symbol in self.undefined_symbols:
233       # Hackish ! Eek!
234       if symbol.startswith('_bold__'):
235         continue
236       found = False
237       for lib in libs:
238         if hasattr(lib, symbol):
239           found = True
240           break
241       if not found:
242         raise UndefinedSymbol(symbol)
243
244
245   def link(self):
246     """Do the actual linking."""
247     # Prepare two segments. One for .text, the other for .data + .bss
248     self.text_segment = TextSegment()
249     # .data will be mapped 0x100000 bytes further
250     self.data_segment = DataSegment(align=0x100000)
251     self.output.add_segment(self.text_segment)
252     self.output.add_segment(self.data_segment)
253
254     # Adjust the ELF header
255     self.output.header.e_ident.make_default_amd64()
256     self.output.header.e_phoff = self.output.header.size
257     self.output.header.e_type = ET_EXEC
258     # Elf header lies inside .text
259     self.text_segment.add_content(self.output.header)
260
261     # Create the four Program Headers. They'll be inside .text
262     # The first Program Header defines .text
263     ph_text = Elf64_Phdr()
264     ph_text.p_type = PT_LOAD
265     ph_text.p_align = 0x100000
266     self.output.add_phdr(ph_text)
267     self.text_segment.add_content(ph_text)
268
269     # Second one defines .data + .bss
270     ph_data = Elf64_Phdr()
271     ph_data.p_type = PT_LOAD
272     ph_data.p_align = 0x100000
273     self.output.add_phdr(ph_data)
274     self.text_segment.add_content(ph_data)
275
276     # Third one is only there to define the DYNAMIC section
277     ph_dynamic = Elf64_Phdr()
278     ph_dynamic.p_type = PT_DYNAMIC
279     self.output.add_phdr(ph_dynamic)
280     self.text_segment.add_content(ph_dynamic)
281
282     # Fourth one is for interp
283     ph_interp = Elf64_Phdr()
284     ph_interp.p_type = PT_INTERP
285     self.output.add_phdr(ph_interp)
286     self.text_segment.add_content(ph_interp)
287
288     # We have all the needed program headers, update ELF header
289     self.output.header.ph_num = len(self.output.phdrs)
290
291     # Create the actual content for the interpreter section
292     interp = Interpreter()
293     self.text_segment.add_content(interp)
294
295     # Then the Dynamic section
296     dynamic = Dynamic()
297     # for all the requested libs, add a reference in the Dynamic table
298     for lib in self.shlibs:
299       dynamic.add_shlib(lib)
300     # Add an empty symtab, symbol resolution is not done.
301     dynamic.add_symtab(0)
302     # And we need a DT_DEBUG
303     dynamic.add_debug()
304
305     # This belongs to .data
306     self.data_segment.add_content(dynamic)
307     # The dynamic table links to a string table for the libs' names.
308     self.text_segment.add_content(dynamic.strtab)
309
310     # We can now add the interesting sections to the corresponding segments
311     for i in self.objs:
312       for sh in i.shdrs:
313         # Only ALLOC sections are worth it.
314         # This might require change in the future
315         if not (sh.sh_flags & SHF_ALLOC):
316           continue
317
318         if (sh.sh_flags & SHF_EXECINSTR):
319           self.text_segment.add_content(sh.content)
320         else: # No exec, it's for .data or .bss
321           if (sh.sh_type == SHT_NOBITS):
322             self.data_segment.add_nobits(sh.content)
323           else:
324             self.data_segment.add_content(sh.content)
325
326     # Now, everything is at its place.
327     # Knowing the base address, we can determine where everyone will fall
328     self.output.layout(base_vaddr=0x400000)
329
330     # Knowing the addresses of all the parts, Program Headers can be filled
331     # This will put the correct p_offset, p_vaddr, p_filesz and p_memsz
332     ph_text.update_from_content(self.text_segment)
333     ph_data.update_from_content(self.data_segment)
334     ph_interp.update_from_content(interp)
335     ph_dynamic.update_from_content(dynamic)
336
337     # All parts are at their final address, find out the symbols' addresses
338     for i in self.objs:
339       for s in i.global_symbols:
340         # Final address is the section's base address + the symbol's offset
341         if i.global_symbols[s][0] == SHN_ABS:
342           addr = i.global_symbols[s][1]
343         else:
344           addr = i.global_symbols[s][0].content.virt_addr
345           addr += i.global_symbols[s][1]
346
347         self.global_symbols[s] = addr
348
349     # Resolve the few useful symbols
350     self.global_symbols["_dt_debug"] = dynamic.dt_debug_address
351     self.global_symbols["_DYNAMIC"] = dynamic.virt_addr
352
353     # We can now do the actual relocation
354     for i in self.objs:
355       i.apply_relocation(self.global_symbols)
356
357     # And update the ELF header with the entry point
358     if not self.entry_point in self.global_symbols:
359       raise UndefinedSymbol(self.entry_point)
360     self.output.header.e_entry = self.global_symbols[self.entry_point]
361
362     # DONE !
363
364
365   def toBinArray(self):
366     return self.output.toBinArray()
367
368
369   def tofile(self, file_object):
370     return self.output.toBinArray().tofile(file_object)
371