]> git.alrj.org Git - bold.git/blob - Bold/linker.py
Correct a "oh so stupid" bug.
[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.content = BinArray("")
133     fo.shdrs.append(bss_shdr)
134     fo.sections['.bss'] = bss_shdr
135
136     if with_jump:
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
141       if align_jump:
142         fmt = '\xff\x25\x00\x00\x00\x00\x00\x00' # ff 25 = jmp [rel label]
143         jmp_size = 8
144       else:
145         fmt = '\xff\x25\x00\x00\x00\x00'
146         jmp_size = 6
147       text_shdr.content = BinArray(fmt * len(symbols))
148       fo.shdrs.append(text_shdr)
149       fo.sections['.text'] = text_shdr
150
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)
157
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
165
166     bss_shdr.sh_size = bss_common_offset
167
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
172
173       if with_jump:
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.
177         p = "_bold__%s" % i
178         fo.global_symbols[p] = (bss_shdr, n * 8)
179
180       else:
181         # The symbol is in .bss, must be called indirectly
182         fo.global_symbols[i] = (bss_shdr, n * 8)
183
184     if with_jump:
185       # Add relocation entries for the jumps
186       # Relocation will be done for the .text, for every jmp instruction.
187       class dummy: pass
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
195
196       for n, i in enumerate(symbols):
197         # Create a relocation entry for each symbol
198         reloc = dummy()
199         reloc.r_offset = (n * jmp_size) + 2   # Beginning of the cell to update
200         reloc.r_addend = -4
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
208
209     # Ok, let's add this fake object
210     self.objs.append(fo)
211
212
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)
217     if not fullname:
218       raise LibNotFound(libname)
219     self.shlibs.append(fullname)
220
221
222   def check_external(self):
223     """Verify that all globally undefined symbols are present in shared
224     libraries."""
225     libs = []
226     for libname in self.shlibs:
227       libs.append(CDLL(libname))
228
229     for symbol in self.undefined_symbols:
230       # Hackish ! Eek!
231       if symbol.startswith('_bold__'):
232         continue
233       found = False
234       for lib in libs:
235         if hasattr(lib, symbol):
236           found = True
237           break
238       if not found:
239         raise UndefinedSymbol(symbol)
240
241
242   def link(self):
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)
250
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)
257
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)
265
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)
272
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)
278
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)
284
285     # We have all the needed program headers, update ELF header
286     self.output.header.ph_num = len(self.output.phdrs)
287
288     # Create the actual content for the interpreter section
289     interp = Interpreter()
290     self.text_segment.add_content(interp)
291
292     # Then the Dynamic section
293     dynamic = Dynamic()
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
300     dynamic.add_debug()
301
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)
306
307     # We can now add the interesting sections to the corresponding segments
308     for i in self.objs:
309       for sh in i.shdrs:
310         # Only ALLOC sections are worth it.
311         # This might require change in the future
312         if not (sh.sh_flags & SHF_ALLOC):
313           continue
314
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)
320           else:
321             self.data_segment.add_content(sh.content)
322
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)
326
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)
333
334     # All parts are at their final address, find out the symbols' addresses
335     for i in self.objs:
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]
340         else:
341           addr = i.global_symbols[s][0].content.virt_addr
342           addr += i.global_symbols[s][1]
343
344         self.global_symbols[s] = addr
345
346     # Resolve the few useful symbols
347     self.global_symbols["_dt_debug"] = dynamic.dt_debug_address
348     self.global_symbols["_DYNAMIC"] = dynamic.virt_addr
349
350     # We can now do the actual relocation
351     for i in self.objs:
352       i.apply_relocation(self.global_symbols)
353
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]
358
359     # DONE !
360
361
362   def toBinArray(self):
363     return self.output.toBinArray()
364
365
366   def tofile(self, file_object):
367     return self.output.toBinArray().tofile(file_object)
368