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