]> git.alrj.org Git - bold.git/blob - Bold/linker.py
9c4b51e748613206e72ebb536428f66bc35d282b
[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     symbols.remove('_bold__functions_count')
112     symbols.remove('_bold__functions_hash')
113     symbols.remove('_bold__functions_pointers')
114
115     # Create the fake ELF object.
116     fo = Elf64() # Don't care about most parts of ELF header (?)
117     fo.filename = "Internal dynamic linker"
118
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
128
129     bss_shdr = Elf64_Shdr()
130     bss_shdr.sh_type = SHT_NOBITS
131     bss_shdr.sh_flags = (SHF_WRITE | SHF_ALLOC)
132     bss_shdr.sh_size = bss_size
133     bss_shdr.content = BinArray("")
134     fo.shdrs.append(bss_shdr)
135     fo.sections['.bss'] = bss_shdr
136
137     if with_jump:
138       text_shdr = Elf64_Shdr()
139       text_shdr.sh_type = SHT_PROGBITS
140       text_shdr.sh_flags = (SHF_ALLOC | SHF_EXECINSTR)
141       text_shdr.sh_size = len(symbols) * 8
142       if align_jump:
143         fmt = '\xff\x25\x00\x00\x00\x00\x00\x00' # ff 25 = jmp [rel label]
144         jmp_size = 8
145       else:
146         fmt = '\xff\x25\x00\x00\x00\x00'
147         jmp_size = 6
148       text_shdr.content = BinArray(fmt * len(symbols))
149       fo.shdrs.append(text_shdr)
150       fo.sections['.text'] = text_shdr
151
152     # Cheating here. All symbols declared as global so we don't need to create
153     # a symtab from scratch.
154     fo.global_symbols = {}
155     fo.global_symbols['_bold__functions_count'] = (SHN_ABS, len(symbols))
156     fo.global_symbols['_bold__functions_hash'] = (data_shdr, 0)
157     fo.global_symbols['_bold__functions_pointers'] = (bss_shdr, 0)
158
159     # The COMMON symbols. Assign an offset in .bss, declare as global.
160     bss_common_offset = len(symbols) * 8
161     for s_name, s_size, s_alignment in self.common_symbols:
162       padding = (s_alignment - (bss_common_offset % s_alignment)) % s_alignment
163       bss_common_offset += padding
164       fo.global_symbols[s_name] = (bss_shdr, bss_common_offset)
165       bss_common_offset += s_size
166
167     bss_shdr.sh_size = bss_common_offset
168
169     for n, i in enumerate(symbols):
170       # The hash is always in .data
171       h = "_bold__hash_%s" % i
172       fo.global_symbols[h] = (data_shdr, n * 4) # Section, offset
173
174       if with_jump:
175         # the symbol is in .text, can be called directly
176         fo.global_symbols[i] = (text_shdr, n * jmp_size)
177         # another symbol can be used to reference the pointer, just in case.
178         p = "_bold__%s" % i
179         fo.global_symbols[p] = (bss_shdr, n * 8)
180
181       else:
182         # The symbol is in .bss, must be called indirectly
183         fo.global_symbols[i] = (bss_shdr, n * 8)
184
185     if with_jump:
186       # Add relocation entries for the jumps
187       # Relocation will be done for the .text, for every jmp instruction.
188       class dummy: pass
189       rela_shdr = Elf64_Shdr()
190       rela_shdr.sh_type = SHT_RELA
191       rela_shdr.target = text_shdr
192       rela_shdr.sh_flags = 0
193       rela_shdr._content = dummy() # We only need a container for relatab...
194       relatab = []                      # Prepare a relatab
195       rela_shdr.content.relatab = relatab
196
197       for n, i in enumerate(symbols):
198         # Create a relocation entry for each symbol
199         reloc = dummy()
200         reloc.r_offset = (n * jmp_size) + 2   # Beginning of the cell to update
201         reloc.r_addend = -4
202         reloc.r_type = R_X86_64_PC32
203         reloc.symbol = dummy()
204         reloc.symbol.st_shndx = SHN_UNDEF
205         reloc.symbol.name = "_bold__%s" % i
206         relatab.append(reloc)
207       fo.shdrs.append(rela_shdr)
208       fo.sections['.rela.text'] = rela_shdr
209
210     # Ok, let's add this fake object
211     self.objs.append(fo)
212
213
214   def add_shlib(self, libname):
215     """Add a shared library to link against."""
216     # Note : we use ctypes' find_library to find the real name
217     fullname = find_library(libname)
218     if not fullname:
219       raise LibNotFound(libname)
220     self.shlibs.append(fullname)
221
222
223   def check_external(self):
224     """Verify that all globally undefined symbols are present in shared
225     libraries."""
226     libs = []
227     for libname in self.shlibs:
228       libs.append(CDLL(libname))
229
230     for symbol in self.undefined_symbols:
231       # Hackish ! Eek!
232       if symbol.startswith('_bold__'):
233         continue
234       found = False
235       for lib in libs:
236         if hasattr(lib, symbol):
237           found = True
238           break
239       if not found:
240         raise UndefinedSymbol(symbol)
241
242
243   def link(self):
244     """Do the actual linking."""
245     # Prepare two segments. One for .text, the other for .data + .bss
246     self.text_segment = TextSegment()
247     # .data will be mapped 0x100000 bytes further
248     self.data_segment = DataSegment(align=0x100000)
249     self.output.add_segment(self.text_segment)
250     self.output.add_segment(self.data_segment)
251
252     # Adjust the ELF header
253     self.output.header.e_ident.make_default_amd64()
254     self.output.header.e_phoff = self.output.header.size
255     self.output.header.e_type = ET_EXEC
256     # Elf header lies inside .text
257     self.text_segment.add_content(self.output.header)
258
259     # Create the four Program Headers. They'll be inside .text
260     # The first Program Header defines .text
261     ph_text = Elf64_Phdr()
262     ph_text.p_type = PT_LOAD
263     ph_text.p_align = 0x100000
264     self.output.add_phdr(ph_text)
265     self.text_segment.add_content(ph_text)
266
267     # Second one defines .data + .bss
268     ph_data = Elf64_Phdr()
269     ph_data.p_type = PT_LOAD
270     ph_data.p_align = 0x100000
271     self.output.add_phdr(ph_data)
272     self.text_segment.add_content(ph_data)
273
274     # Third one is only there to define the DYNAMIC section
275     ph_dynamic = Elf64_Phdr()
276     ph_dynamic.p_type = PT_DYNAMIC
277     self.output.add_phdr(ph_dynamic)
278     self.text_segment.add_content(ph_dynamic)
279
280     # Fourth one is for interp
281     ph_interp = Elf64_Phdr()
282     ph_interp.p_type = PT_INTERP
283     self.output.add_phdr(ph_interp)
284     self.text_segment.add_content(ph_interp)
285
286     # We have all the needed program headers, update ELF header
287     self.output.header.ph_num = len(self.output.phdrs)
288
289     # Create the actual content for the interpreter section
290     interp = Interpreter()
291     self.text_segment.add_content(interp)
292
293     # Then the Dynamic section
294     dynamic = Dynamic()
295     # for all the requested libs, add a reference in the Dynamic table
296     for lib in self.shlibs:
297       dynamic.add_shlib(lib)
298     # Add an empty symtab, symbol resolution is not done.
299     dynamic.add_symtab(0)
300     # And we need a DT_DEBUG
301     dynamic.add_debug()
302
303     # This belongs to .data
304     self.data_segment.add_content(dynamic)
305     # The dynamic table links to a string table for the libs' names.
306     self.text_segment.add_content(dynamic.strtab)
307
308     # We can now add the interesting sections to the corresponding segments
309     for i in self.objs:
310       for sh in i.shdrs:
311         # Only ALLOC sections are worth it.
312         # This might require change in the future
313         if not (sh.sh_flags & SHF_ALLOC):
314           continue
315
316         if (sh.sh_flags & SHF_EXECINSTR):
317           self.text_segment.add_content(sh.content)
318         else: # No exec, it's for .data or .bss
319           if (sh.sh_type == SHT_NOBITS):
320             self.data_segment.add_nobits(sh.content)
321           else:
322             self.data_segment.add_content(sh.content)
323
324     # Now, everything is at its place.
325     # Knowing the base address, we can determine where everyone will fall
326     self.output.layout(base_vaddr=0x400000)
327
328     # Knowing the addresses of all the parts, Program Headers can be filled
329     # This will put the correct p_offset, p_vaddr, p_filesz and p_memsz
330     ph_text.update_from_content(self.text_segment)
331     ph_data.update_from_content(self.data_segment)
332     ph_interp.update_from_content(interp)
333     ph_dynamic.update_from_content(dynamic)
334
335     # All parts are at their final address, find out the symbols' addresses
336     for i in self.objs:
337       for s in i.global_symbols:
338         # Final address is the section's base address + the symbol's offset
339         if i.global_symbols[s][0] == SHN_ABS:
340           addr = i.global_symbols[s][1]
341         else:
342           addr = i.global_symbols[s][0].content.virt_addr
343           addr += i.global_symbols[s][1]
344
345         self.global_symbols[s] = addr
346
347     # Resolve the few useful symbols
348     self.global_symbols["_dt_debug"] = dynamic.dt_debug_address
349     self.global_symbols["_DYNAMIC"] = dynamic.virt_addr
350
351     # We can now do the actual relocation
352     for i in self.objs:
353       i.apply_relocation(self.global_symbols)
354
355     # And update the ELF header with the entry point
356     if not self.entry_point in self.global_symbols:
357       raise UndefinedSymbol(self.entry_point)
358     self.output.header.e_entry = self.global_symbols[self.entry_point]
359
360     # DONE !
361
362
363   def toBinArray(self):
364     return self.output.toBinArray()
365
366
367   def tofile(self, file_object):
368     return self.output.toBinArray().tofile(file_object)
369