AcessNative - Little fixes to get it running on 64-bit
[tpg/acess2.git] / Usermode / Libraries / ld-acess.so_src / elf.c
1 /*
2  * Acess2 Dynamic Linker
3  * - By John Hodge (thePowersGang)
4  *
5  * elf.c
6  * - ELF32/ELF64 relocation
7  */
8 #define DEBUG   0
9
10 #include "common.h"
11 #include <stdint.h>
12 #include "elf32.h"
13 #include "elf64.h"
14
15 #if DEBUG
16 # define        DEBUGS(v...)    SysDebug("ld-acess - " v)
17 #else
18 # define        DEBUGS(...)     
19 #endif
20
21 //#if BITS > 32
22 # define SUPPORT_ELF64
23 //#endif
24
25 // === CONSTANTS ===
26 #if DEBUG
27 //static const char     *csaDT_NAMES[] = {"DT_NULL", "DT_NEEDED", "DT_PLTRELSZ", "DT_PLTGOT", "DT_HASH", "DT_STRTAB", "DT_SYMTAB", "DT_RELA", "DT_RELASZ", "DT_RELAENT", "DT_STRSZ", "DT_SYMENT", "DT_INIT", "DT_FINI", "DT_SONAME", "DT_RPATH", "DT_SYMBOLIC", "DT_REL", "DT_RELSZ", "DT_RELENT", "DT_PLTREL", "DT_DEBUG", "DT_TEXTREL", "DT_JMPREL"};
28 static const char       *csaR_NAMES[] = {"R_386_NONE", "R_386_32", "R_386_PC32", "R_386_GOT32", "R_386_PLT32", "R_386_COPY", "R_386_GLOB_DAT", "R_386_JMP_SLOT", "R_386_RELATIVE", "R_386_GOTOFF", "R_386_GOTPC", "R_386_LAST"};
29 #endif
30
31 // === PROTOTYPES ===
32 void    *ElfRelocate(void *Base, char **envp, const char *Filename);
33  int    ElfGetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
34 void    *Elf32Relocate(void *Base, char **envp, const char *Filename);
35  int    Elf32GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
36 #ifdef SUPPORT_ELF64
37 void    *Elf64Relocate(void *Base, char **envp, const char *Filename);
38  int    Elf64GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
39 #endif
40 uint32_t        ElfHashString(const char *name);
41
42 // === CODE ===
43 /**
44  * \fn int ElfRelocate(void *Base, char **envp, const char *Filename)
45  * \brief Relocates a loaded ELF Executable
46  */
47 void *ElfRelocate(void *Base, char **envp, const char *Filename)
48 {
49         Elf32_Ehdr      *hdr = Base;
50         
51         switch(hdr->e_ident[4])
52         {
53         case ELFCLASS32:
54                 return Elf32Relocate(Base, envp, Filename);
55 #ifdef SUPPORT_ELF64
56         case ELFCLASS64:
57                 return Elf64Relocate(Base, envp, Filename);
58 #endif
59         default:
60                 SysDebug("ld-acess - ElfRelocate: Unknown file class %i", hdr->e_ident[4]);
61                 return NULL;
62         }
63 }
64
65 /**
66  * \fn int ElfGetSymbol(Uint Base, const char *name, void **ret)
67  */
68 int ElfGetSymbol(void *Base, const char *Name, void **ret, size_t *Size)
69 {
70         Elf32_Ehdr      *hdr = Base;
71
72         switch(hdr->e_ident[4])
73         {
74         case ELFCLASS32:
75                 return Elf32GetSymbol(Base, Name, ret, Size);
76 #ifdef SUPPORT_ELF64
77         case ELFCLASS64:
78                 return Elf64GetSymbol(Base, Name, ret, Size);
79 #endif
80         default:
81                 SysDebug("ld-acess - ElfRelocate: Unknown file class %i", hdr->e_ident[4]);
82                 return 0;
83         }
84 }
85
86 void elf_doRelocate_386(uint32_t r_info, uint32_t *ptr, Elf32_Addr addend, int type, int bRela, const char *Sym, intptr_t iBaseDiff)
87 {
88         intptr_t        val;
89         switch( type )
90         {
91         // Standard 32 Bit Relocation (S+A)
92         case R_386_32:
93                 val = (intptr_t) GetSymbol(Sym, NULL);
94                 DEBUGS(" elf_doRelocate: R_386_32 *0x%x += 0x%x('%s')",
95                                 ptr, val, Sym);
96                 *ptr = val + addend;
97                 break;
98                 
99         // 32 Bit Relocation wrt. Offset (S+A-P)
100         case R_386_PC32:
101                 DEBUGS(" elf_doRelocate: '%s'", Sym);
102                 val = (intptr_t) GetSymbol(Sym, NULL);
103                 DEBUGS(" elf_doRelocate: R_386_PC32 *0x%x = 0x%x + 0x%x - 0x%x",
104                         ptr, *ptr, val, (intptr_t)ptr );
105                 *ptr = val + addend - (intptr_t)ptr;
106                 //*ptr = val + addend - ((Uint)ptr - iBaseDiff);
107                 break;
108
109         // Absolute Value of a symbol (S)
110         case R_386_GLOB_DAT:
111         case R_386_JMP_SLOT:
112                 DEBUGS(" elf_doRelocate: '%s'", Sym);
113                 val = (intptr_t) GetSymbol( Sym, NULL );
114                 DEBUGS(" elf_doRelocate: %s *0x%x = 0x%x", csaR_NAMES[type], ptr, val);
115                 *ptr = val;
116                 break;
117
118         // Base Address (B+A)
119         case R_386_RELATIVE:
120                 DEBUGS(" elf_doRelocate: R_386_RELATIVE *0x%x = 0x%x + 0x%x", ptr, iBaseDiff, addend);
121                 *ptr = iBaseDiff + addend;
122                 break;
123
124         case R_386_COPY: {
125                 size_t  size;
126                 void    *src = GetSymbol(Sym, &size);
127                 DEBUGS(" elf_doRelocate_386: R_386_COPY (%p, %p, %i)", ptr, src, size);
128                 memcpy(ptr, src, size);
129                 break; }
130
131         default:
132                 SysDebug("elf_doRelocate_386: Unknown relocation %i", type);
133                 break;
134         }
135 }
136
137 void elf_doRelocate_arm(uint32_t r_info, uint32_t *ptr, Elf32_Addr addend, int type, int bRela, const char *Sym, intptr_t iBaseDiff)
138 {
139         uint32_t        val;
140         switch(type)
141         {
142         // (S + A) | T
143         case R_ARM_ABS32:
144                 DEBUGS(" elf_doRelocate_arm: R_ARM_ABS32 %p (%s + %x)", ptr, Sym, addend);
145                 val = (intptr_t)GetSymbol(Sym, NULL);
146                 *ptr = val + addend;
147                 break;
148         case R_ARM_GLOB_DAT:
149                 DEBUGS(" elf_doRelocate_arm: R_ARM_GLOB_DAT %p (%s + %x)", ptr, Sym, addend);
150                 val = (intptr_t)GetSymbol(Sym, NULL);
151                 *ptr = val + addend;
152                 break;
153         case R_ARM_JUMP_SLOT:
154                 if(!bRela)      addend = 0;
155                 DEBUGS(" elf_doRelocate_arm: R_ARM_JUMP_SLOT %p (%s + %x)", ptr, Sym, addend);
156                 val = (intptr_t)GetSymbol(Sym, NULL);
157                 *ptr = val + addend;
158                 break;
159         // Copy
160         case R_ARM_COPY: {
161                 size_t  size;
162                 void    *src = GetSymbol(Sym, &size);
163                 DEBUGS(" elf_doRelocate_arm: R_ARM_COPY (%p, %p, %i)", ptr, src, size);
164                 memcpy(ptr, src, size);
165                 break; }
166         // Delta between link and runtime locations + A
167         case R_ARM_RELATIVE:
168                 if(Sym[0] != '\0') {
169                         // TODO: Get delta for a symbol
170                         SysDebug("elf_doRelocate_arm: TODO - Implment R_ARM_RELATIVE for symbols");
171                 }
172                 else {
173                         *ptr = iBaseDiff + addend;
174                 }
175                 break;
176         default:
177                 SysDebug("elf_doRelocate_arm: Unknown Relocation, %i", type);
178                 break;
179         }
180 }
181
182 void *Elf32Relocate(void *Base, char **envp, const char *Filename)
183 {
184         Elf32_Ehdr      *hdr = Base;
185         Elf32_Phdr      *phtab;
186          int    i, j;   // Counters
187         char    *libPath;
188         intptr_t        iRealBase = -1;
189         intptr_t        iBaseDiff;
190          int    iSegmentCount;
191 //       int    iSymCount;
192         Elf32_Rel       *rel = NULL;
193         Elf32_Rela      *rela = NULL;
194         void    *plt = NULL;
195          int    relSz=0, relEntSz=8;
196          int    relaSz=0, relaEntSz=8;
197          int    pltSz=0, pltType=0;
198         Elf32_Dyn       *dynamicTab = NULL;     // Dynamic Table Pointer
199         char    *dynstrtab = NULL;      // .dynamic String Table
200         Elf32_Sym       *dynsymtab;
201         void    (*do_relocate)(uint32_t t_info, uint32_t *ptr, Elf32_Addr addend, int Type, int bRela, const char *Sym, intptr_t iBaseDiff);
202         
203         DEBUGS("ElfRelocate: (Base=0x%x)", Base);
204         
205         // Check magic header
206         
207         
208         // Parse Program Header to get Dynamic Table
209         phtab = Base + hdr->phoff;
210         iSegmentCount = hdr->phentcount;
211         for(i=0;i<iSegmentCount;i++)
212         {
213                 // Determine linked base address
214                 if(phtab[i].Type == PT_LOAD && iRealBase > phtab[i].VAddr)
215                         iRealBase = phtab[i].VAddr;
216                 
217                 // Find Dynamic Section
218                 if(phtab[i].Type == PT_DYNAMIC) {
219                         if(dynamicTab) {
220                                 DEBUGS(" WARNING - elf_relocate: Multiple PT_DYNAMIC segments");
221                                 continue;
222                         }
223                         dynamicTab = (void *) (intptr_t) phtab[i].VAddr;
224                         j = i;  // Save Dynamic Table ID
225                 }
226         }
227         
228         // Page Align real base
229         iRealBase &= ~0xFFF;
230         DEBUGS(" elf_relocate: True Base = 0x%x, Compiled Base = 0x%x", Base, iRealBase);
231         
232         // Adjust "Real" Base
233         iBaseDiff = (intptr_t)Base - iRealBase;
234         
235 //      hdr->entrypoint += iBaseDiff;   // Adjust Entrypoint
236         
237         // Check if a PT_DYNAMIC segement was found
238         if(!dynamicTab) {
239                 SysDebug(" elf_relocate: No PT_DYNAMIC segment in image %p, returning", Base);
240                 return (void *)(intptr_t)(hdr->entrypoint + iBaseDiff);
241         }
242         
243         // Adjust Dynamic Table
244         dynamicTab = (void *)( (intptr_t)dynamicTab + iBaseDiff );
245         
246         // === Get Symbol table and String Table ===
247         for( j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
248         {
249                 switch(dynamicTab[j].d_tag)
250                 {
251                 // --- Symbol Table ---
252                 case DT_SYMTAB:
253                         DEBUGS(" elf_relocate: DYNAMIC Symbol Table 0x%x (0x%x)",
254                                 dynamicTab[j].d_val, dynamicTab[j].d_val + iBaseDiff);
255                         if(iBaseDiff != 0)      dynamicTab[j].d_val += iBaseDiff;
256                         dynsymtab = (void*)(intptr_t)dynamicTab[j].d_val;
257                         break;
258                 // --- String Table ---
259                 case DT_STRTAB:
260                         DEBUGS(" elf_relocate: DYNAMIC String Table 0x%x (0x%x)",
261                                 dynamicTab[j].d_val, dynamicTab[j].d_val + iBaseDiff);
262                         if(iBaseDiff != 0)      dynamicTab[j].d_val += iBaseDiff;
263                         dynstrtab = (void*)(intptr_t)dynamicTab[j].d_val;
264                         break;
265                 // --- Hash Table --
266                 case DT_HASH:
267                         if(iBaseDiff != 0)      dynamicTab[j].d_val += iBaseDiff;
268 //                      iSymCount = ((Elf32_Word*)(intptr_t)dynamicTab[j].d_val)[1];
269                         break;
270                 }
271         }
272
273         if(dynsymtab == NULL) {
274                 SysDebug("ld-acess.so - WARNING: No Dynamic Symbol table in %p, returning", hdr);
275                 return (void *)(intptr_t) (hdr->entrypoint + iBaseDiff);
276         }
277
278         // === Add to loaded list (can be imported now) ===
279         AddLoaded( Filename, Base );
280
281         // === Parse Relocation Data ===
282         DEBUGS(" elf_relocate: dynamicTab = 0x%x", dynamicTab);
283         for( j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
284         {
285                 switch(dynamicTab[j].d_tag)
286                 {
287                 // --- Shared Library Name ---
288                 case DT_SONAME:
289                         DEBUGS(" elf_relocate: .so Name '%s'", dynstrtab+dynamicTab[j].d_val);
290                         break;
291                 // --- Needed Library ---
292                 case DT_NEEDED:
293                         libPath = dynstrtab + dynamicTab[j].d_val;
294                         DEBUGS(" Required Library '%s'", libPath);
295                         if(LoadLibrary(libPath, NULL, envp) == 0) {
296                                 #if DEBUG
297                                 DEBUGS(" elf_relocate: Unable to load '%s'", libPath);
298                                 #else
299                                 SysDebug("Unable to load required library '%s'", libPath);
300                                 #endif
301                                 return 0;
302                         }
303                         DEBUGS(" Lib loaded");
304                         break;
305                 // --- PLT/GOT ---
306 //              case DT_PLTGOT: pltgot = (void*)(iBaseDiff + dynamicTab[j].d_val);      break;
307                 case DT_JMPREL: plt = (void*)(iBaseDiff + dynamicTab[j].d_val); break;
308                 case DT_PLTREL: pltType = dynamicTab[j].d_val;  break;
309                 case DT_PLTRELSZ:       pltSz = dynamicTab[j].d_val;    break;
310                 
311                 // --- Relocation ---
312                 case DT_REL:    rel = (void*)(iBaseDiff + dynamicTab[j].d_val); break;
313                 case DT_RELSZ:  relSz = dynamicTab[j].d_val;    break;
314                 case DT_RELENT: relEntSz = dynamicTab[j].d_val; break;
315                 case DT_RELA:   rela = (void*)(iBaseDiff + dynamicTab[j].d_val);        break;
316                 case DT_RELASZ: relaSz = dynamicTab[j].d_val;   break;
317                 case DT_RELAENT:        relaEntSz = dynamicTab[j].d_val;        break;
318                 
319                 // --- Symbol Table ---
320                 case DT_SYMTAB:
321                 // --- Hash Table ---
322                 case DT_HASH:
323                 // --- String Table ---
324                 case DT_STRTAB:
325                         break;
326                 
327                 // --- Unknown ---
328                 default:
329                         if(dynamicTab[j].d_tag > DT_JMPREL)     continue;
330                         //DEBUGS(" elf_relocate: %i-%i = %s,0x%x",
331                         //      i,j, csaDT_NAMES[dynamicTab[j].d_tag],dynamicTab[j].d_val);
332                         break;
333                 }
334         }
335         
336         DEBUGS(" elf_relocate: Beginning Relocation");
337
338         void _doRelocate(uint32_t r_info, uint32_t *ptr, int bRela, Elf32_Addr addend)
339         {
340                  int    type = ELF32_R_TYPE(r_info);
341                  int    sym = ELF32_R_SYM(r_info);
342                 const char      *symname = dynstrtab + dynsymtab[sym].nameOfs;
343                 do_relocate(r_info, ptr, addend, type, bRela, symname, iBaseDiff);
344         }
345
346         switch(hdr->machine)
347         {
348         case EM_386:
349                 do_relocate = elf_doRelocate_386;
350                 break;
351         case EM_ARM:
352                 do_relocate = elf_doRelocate_arm;
353                 break;
354         default:
355                 SysDebug("Elf32Relocate: Unknown machine type %i", hdr->machine);
356                 break;
357         }
358         
359         DEBUGS("do_relocate = %p (%p or %p)", do_relocate, &elf_doRelocate_386, &elf_doRelocate_arm);
360
361         // Parse Relocation Entries
362         if(rel && relSz)
363         {
364                 Elf32_Word      *ptr;
365                 DEBUGS(" elf_relocate: rel=0x%x, relSz=0x%x, relEntSz=0x%x", rel, relSz, relEntSz);
366                 j = relSz / relEntSz;
367                 for( i = 0; i < j; i++ )
368                 {
369                         //DEBUGS("  Rel %i: 0x%x+0x%x", i, iBaseDiff, rel[i].r_offset);
370                         ptr = (void*)(iBaseDiff + rel[i].r_offset);
371                         _doRelocate(rel[i].r_info, ptr, 0, *ptr);
372                 }
373         }
374         // Parse Relocation Entries
375         if(rela && relaSz)
376         {
377                 Elf32_Word      *ptr;
378                 DEBUGS(" elf_relocate: rela=0x%x, relaSz=0x%x, relaEntSz=0x%x", rela, relaSz, relaEntSz);
379                 j = relaSz / relaEntSz;
380                 for( i = 0; i < j; i++ )
381                 {
382                         ptr = (void*)(iBaseDiff + rela[i].r_offset);
383                         _doRelocate(rel[i].r_info, ptr, 1, rela[i].r_addend);
384                 }
385         }
386         
387         // === Process PLT (Procedure Linkage Table) ===
388         if(plt && pltSz)
389         {
390                 Elf32_Word      *ptr;
391                 DEBUGS(" elf_relocate: Relocate PLT, plt=0x%x", plt);
392                 if(pltType == DT_REL)
393                 {
394                         Elf32_Rel       *pltRel = plt;
395                         j = pltSz / sizeof(Elf32_Rel);
396                         DEBUGS(" elf_relocate: PLT Reloc Type = Rel, %i entries", j);
397                         for(i=0;i<j;i++)
398                         {
399                                 ptr = (void*)(iBaseDiff + pltRel[i].r_offset);
400                                 _doRelocate(pltRel[i].r_info, ptr, 0, *ptr);
401                         }
402                 }
403                 else
404                 {
405                         Elf32_Rela      *pltRela = plt;
406                         j = pltSz / sizeof(Elf32_Rela);
407                         DEBUGS(" elf_relocate: PLT Reloc Type = Rela, %i entries", j);
408                         for(i=0;i<j;i++)
409                         {
410                                 ptr = (void*)(iRealBase + pltRela[i].r_offset);
411                                 _doRelocate(pltRela[i].r_info, ptr, 1, pltRela[i].r_addend);
412                         }
413                 }
414         }
415         
416         DEBUGS("ElfRelocate: RETURN 0x%x to %p", hdr->entrypoint + iBaseDiff, __builtin_return_address(0));
417         return (void*)(intptr_t)( hdr->entrypoint + iBaseDiff );
418 }
419
420 int Elf32GetSymbol(void *Base, const char *Name, void **ret, size_t *Size)
421 {
422         Elf32_Ehdr      *hdr = Base;
423         Elf32_Sym       *symtab;
424          int    nbuckets = 0;
425 //       int    iSymCount = 0;
426          int    i;
427         Elf32_Word      *pBuckets;
428         Elf32_Word      *pChains;
429         uint32_t        iNameHash;
430         const char      *dynstrtab;
431         uintptr_t       iBaseDiff = -1;
432         Elf32_Phdr      *phtab;
433         Elf32_Dyn       *dynTab = NULL;
434
435         // Locate the tables
436         phtab = (void*)( Base + hdr->phoff );
437         for( i = 0; i < hdr->phentcount; i ++ )
438         {
439                 if(phtab[i].Type == PT_LOAD && iBaseDiff > phtab[i].VAddr)
440                         iBaseDiff = phtab[i].VAddr;
441                 if( phtab[i].Type == PT_DYNAMIC ) {
442                         dynTab = (void*)(intptr_t)phtab[i].VAddr;
443                 }
444         }
445         if( !dynTab ) {
446                 SysDebug("ERROR - Unable to find DYNAMIC segment in %p", Base);
447                 return 0;
448         }
449         iBaseDiff = (intptr_t)Base - iBaseDiff; // Make iBaseDiff actually the diff
450         dynTab = (void*)( (intptr_t)dynTab + iBaseDiff );
451         for( i = 0; dynTab[i].d_tag != DT_NULL; i++)
452         {
453                 switch(dynTab[i].d_tag)
454                 {
455                 // --- Symbol Table ---
456                 case DT_SYMTAB:
457                         symtab = (void*)(intptr_t) dynTab[i].d_val;     // Rebased in Relocate
458                         break;
459                 case DT_STRTAB:
460                         dynstrtab = (void*)(intptr_t) dynTab[i].d_val;
461                         break;
462                 // --- Hash Table --
463                 case DT_HASH:
464                         pBuckets = (void*)(intptr_t) dynTab[i].d_val;
465                         break;
466                 }
467         }
468         
469         nbuckets = pBuckets[0];
470 //      iSymCount = pBuckets[1];
471         pBuckets = &pBuckets[2];
472         pChains = &pBuckets[ nbuckets ];
473         
474         // Get hash
475         iNameHash = ElfHashString(Name);
476         iNameHash %= nbuckets;
477
478         // Walk Chain
479         i = pBuckets[ iNameHash ];
480         if(symtab[i].shndx != SHN_UNDEF && strcmp(dynstrtab + symtab[i].nameOfs, Name) == 0) {
481                 *ret = (void*) (intptr_t) symtab[ i ].value + iBaseDiff;
482                 if(Size)        *Size = symtab[i].size;
483                 return 1;
484         }
485         
486         while(pChains[i] != STN_UNDEF)
487         {
488                 i = pChains[i];
489                 if(symtab[i].shndx != SHN_UNDEF && strcmp(dynstrtab + symtab[ i ].nameOfs, Name) == 0) {
490                         *ret = (void*)(intptr_t)symtab[ i ].value + iBaseDiff;
491                         if(Size)        *Size = symtab[i].size;
492                         return 1;
493                 }
494         }
495         
496         return 0;
497 }
498
499 #ifdef SUPPORT_ELF64
500 void *Elf64Relocate(void *Base, char **envp, const char *Filename)
501 {
502          int    i;
503         Elf64_Ehdr      *hdr = Base;
504         Elf64_Phdr      *phtab;
505         Elf64_Dyn       *dyntab;
506         Elf64_Addr      compiledBase = -1, baseDiff;
507         Elf64_Sym       *symtab = NULL;
508         char    *strtab = NULL;
509         Elf64_Word      *hashtab = NULL;
510         Elf64_Rel       *rel = NULL;
511          int    rel_count = 0;
512         Elf64_Rela      *rela = NULL;
513          int    rela_count = 0;
514         void    *pltrel = NULL;
515          int    plt_size = 0, plt_type = 0;
516
517         DEBUGS("Elf64Relocate: hdr = {");
518         DEBUGS("Elf64Relocate:  e_ident = '%.16s'", hdr->e_ident);
519         DEBUGS("Elf64Relocate:  e_type = 0x%x", hdr->e_type);
520         DEBUGS("Elf64Relocate:  e_machine = 0x%x", hdr->e_machine);
521         DEBUGS("Elf64Relocate:  e_version = 0x%x", hdr->e_version);
522         DEBUGS("Elf64Relocate:  e_entry = %p", hdr->e_entry);
523         DEBUGS("Elf64Relocate:  e_phoff = 0x%llx", hdr->e_phoff);
524         DEBUGS("Elf64Relocate:  e_shoff = 0x%llx", hdr->e_shoff);
525         DEBUGS("Elf64Relocate:  e_flags = 0x%x", hdr->e_flags);
526         DEBUGS("Elf64Relocate:  e_ehsize = 0x%x", hdr->e_ehsize);
527         DEBUGS("Elf64Relocate:  e_phentsize = 0x%x", hdr->e_phentsize);
528         DEBUGS("Elf64Relocate:  e_phnum = %i", hdr->e_phnum);
529
530         // Scan for the dynamic table (and find the compiled base)
531         phtab = Base + hdr->e_phoff;
532         for( i = 0; i < hdr->e_phnum; i ++ )
533         {
534                 if(phtab[i].p_type == PT_DYNAMIC)
535                         dyntab = (void *)(intptr_t)phtab[i].p_vaddr;
536                 if(phtab[i].p_type == PT_LOAD && compiledBase > phtab[i].p_vaddr)
537                         compiledBase = phtab[i].p_vaddr;
538         }
539
540         baseDiff = (uintptr_t)Base - compiledBase;
541
542         DEBUGS("baseDiff = %p", baseDiff);
543
544         if(dyntab == NULL) {
545                 SysDebug(" Elf64Relocate: No PT_DYNAMIC segment in image %p, returning", Base);
546                 return (void *)(uintptr_t)(hdr->e_entry + baseDiff);
547         }
548
549         dyntab = (void *)(uintptr_t)((uintptr_t)dyntab + baseDiff);
550
551         // Parse the dynamic table (first pass)
552         // - Search for String, Symbol and Hash tables
553         for(i = 0; dyntab[i].d_tag != DT_NULL; i ++)
554         {
555                 switch(dyntab[i].d_tag)
556                 {
557                 case DT_SYMTAB:
558                         dyntab[i].d_un.d_ptr += baseDiff;
559                         symtab = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
560                         break;
561                 case DT_STRTAB:
562                         dyntab[i].d_un.d_ptr += baseDiff;
563                         strtab = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
564                         break;
565                 case DT_HASH:
566                         dyntab[i].d_un.d_ptr += baseDiff;
567                         hashtab = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
568                         break;
569                 }
570         }
571
572         if( !symtab || !strtab || !hashtab ) {
573                 SysDebug("ld-acess - Elf64Relocate: Missing Symbol, string or hash table");
574                 return NULL;
575         }
576
577         // Ready for symbol use 
578         AddLoaded( Filename, Base );
579
580         // Second pass on dynamic table
581         for(i = 0; dyntab[i].d_tag != DT_NULL; i ++)
582         {
583                 DEBUGS("dyntab[%i].d_tag = %i", i, dyntab[i].d_tag);
584                 switch(dyntab[i].d_tag)
585                 {
586                 case DT_SONAME: break;
587
588                 case DT_NEEDED: {
589                         char *libPath = strtab + dyntab[i].d_un.d_val;
590                         DEBUGS("Elf64Relocate: libPath = '%s'", libPath);
591                         if(LoadLibrary(libPath, NULL, envp) == 0) {
592                                 SysDebug("ld-acess - Elf64Relocate: Unable to load '%s'", libPath);
593                                 return NULL;
594                         }
595                         } break;
596                 
597                 // Relocation entries
598                 case DT_REL:
599                         dyntab[i].d_un.d_ptr += baseDiff;
600                         rel = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
601                         break;
602                 case DT_RELSZ:
603                         rel_count = dyntab[i].d_un.d_val / sizeof(Elf64_Rel);
604                         break;
605                 case DT_RELENT:
606                         if( dyntab[i].d_un.d_val != sizeof(Elf64_Rel) ) {
607                                 SysDebug("ld-acess - Elf64Relocate: DT_RELENT(%i) != sizeof(Elf64_Rel)(%i)",
608                                         dyntab[i].d_un.d_val, sizeof(Elf64_Rel));
609                                 return NULL;
610                         }
611                         break;
612                 case DT_RELA:
613                         dyntab[i].d_un.d_ptr += baseDiff;
614                         rela = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
615                         break;
616                 case DT_RELASZ:
617                         rela_count = dyntab[i].d_un.d_val / sizeof(Elf64_Rela);
618                         break;
619                 case DT_RELAENT:
620                         if( dyntab[i].d_un.d_val != sizeof(Elf64_Rela) ) {
621                                 SysDebug("ld-acess - Elf64Relocate: DT_RELAENT(%i) != sizeof(Elf64_Rela)(%i)",
622                                         dyntab[i].d_un.d_val, sizeof(Elf64_Rela));
623                                 return NULL;
624                         }
625                         break;
626                 case DT_JMPREL:
627                         dyntab[i].d_un.d_ptr += baseDiff;
628                         pltrel = (void *)(uintptr_t)dyntab[i].d_un.d_ptr;
629                         break;
630                 case DT_PLTREL:
631                         plt_type = dyntab[i].d_un.d_val;
632                         break;
633                 case DT_PLTRELSZ:
634                         plt_size = dyntab[i].d_un.d_val;
635                         break;
636                 }
637         }
638
639         // Relocation function
640         void _Elf64DoReloc(Elf64_Xword r_info, void *ptr, Elf64_Sxword addend)
641         {
642                  int    sym = ELF64_R_SYM(r_info);
643                  int    type = ELF64_R_TYPE(r_info);
644                 const char      *symname = strtab + symtab[sym].st_name;
645                 switch( type )
646                 {
647                 case R_X86_64_NONE:
648                         break;
649                 case R_X86_64_64:
650                         *(uint64_t*)ptr = (uintptr_t)GetSymbol(symname, NULL) + addend;
651                         break;
652                 case R_X86_64_COPY: {
653                         size_t  size;
654                         void    *sym = GetSymbol(symname, &size);
655                         memcpy(ptr, sym, size);
656                         } break;
657                 case R_X86_64_GLOB_DAT:
658                         *(uint64_t*)ptr = (uintptr_t)GetSymbol(symname, NULL);
659                         break;
660                 case R_X86_64_JUMP_SLOT:
661                         *(uint64_t*)ptr = (uintptr_t)GetSymbol(symname, NULL);
662                         break;
663                 case R_X86_64_RELATIVE:
664                         *(uint64_t*)ptr = (uintptr_t)Base + addend;
665                         break;
666                 default:
667                         SysDebug("ld-acess - _Elf64DoReloc: Unknown relocation type %i", type);
668                         break;
669                 }
670         }
671
672         if( rel )
673         {
674                 DEBUGS("rel_count = %i", rel_count);
675                 for( i = 0; i < rel_count; i ++ )
676                 {
677                         uint64_t *ptr = (void *)(uintptr_t)( rel[i].r_offset + baseDiff );
678                         _Elf64DoReloc( rel[i].r_info, ptr, *ptr);
679                 }
680         }
681
682         if( rela )
683         {
684                 DEBUGS("rela_count = %i", rela_count);
685                 for( i = 0; i < rela_count; i ++ )
686                 {
687                         uint64_t *ptr = (void *)(uintptr_t)( rela[i].r_offset + baseDiff );
688                         _Elf64DoReloc( rela[i].r_info, ptr, rela[i].r_addend );
689                 }
690         }
691
692         if( pltrel && plt_type )
693         {
694                 if( plt_type == DT_REL ) {
695                         Elf64_Rel       *plt = pltrel;
696                          int    count = plt_size / sizeof(Elf64_Rel);
697                         DEBUGS("plt rel count = %i", count);
698                         for( i = 0; i < count; i ++ )
699                         {
700                                 uint64_t *ptr = (void *)(uintptr_t)( plt[i].r_offset + baseDiff );
701                                 _Elf64DoReloc( plt[i].r_info, ptr, *ptr);
702                         }
703                 }
704                 else {
705                         Elf64_Rela      *plt = pltrel;
706                          int    count = plt_size / sizeof(Elf64_Rela);
707                         DEBUGS("plt rela count = %i", count);
708                         for( i = 0; i < count; i ++ )
709                         {
710                                 uint64_t *ptr = (void *)(uintptr_t)( plt[i].r_offset + baseDiff );
711                                 _Elf64DoReloc( plt[i].r_info, ptr, plt[i].r_addend);
712                         }
713                 }
714         }
715
716         {
717         void *ret = (void *)(uintptr_t)(hdr->e_entry + baseDiff);
718         DEBUGS("Elf64Relocate: Relocations done, return %p", ret);
719         return ret;
720         }
721 }
722
723 int Elf64GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size)
724 {
725         Elf64_Ehdr      *hdr = Base;
726         Elf64_Sym       *symtab;
727          int    nbuckets = 0;
728 //       int    iSymCount = 0;
729          int    i;
730         Elf64_Word      *pBuckets;
731         Elf64_Word      *pChains;
732         uint32_t        iNameHash;
733         const char      *dynstrtab;
734         uintptr_t       iBaseDiff = -1;
735
736         dynstrtab = NULL;
737         pBuckets = NULL;
738         symtab = NULL;
739
740         // Catch the current executable
741         if( !pBuckets )
742         {
743                 Elf64_Phdr      *phtab;
744                 Elf64_Dyn       *dynTab = NULL;
745                  int    j;
746                 
747                 // Locate the tables
748                 phtab = (void*)( Base + hdr->e_phoff );
749                 for( i = 0; i < hdr->e_phnum; i ++ )
750                 {
751                         if(phtab[i].p_type == PT_LOAD && iBaseDiff > phtab[i].p_vaddr)
752                                 iBaseDiff = phtab[i].p_vaddr;
753                         if( phtab[i].p_type == PT_DYNAMIC ) {
754                                 dynTab = (void*)(intptr_t)phtab[i].p_vaddr;
755                         }
756                 }
757                 if( !dynTab ) {
758                         SysDebug("ERROR - Unable to find DYNAMIC segment in %p", Base);
759                         return 0;
760                 }
761                 iBaseDiff = (intptr_t)Base - iBaseDiff; // Make iBaseDiff actually the diff
762                 dynTab = (void*)( (intptr_t)dynTab + iBaseDiff );
763                 
764                 for( j = 0; dynTab[j].d_tag != DT_NULL; j++)
765                 {
766                         switch(dynTab[j].d_tag)
767                         {
768                         // --- Symbol Table ---
769                         case DT_SYMTAB:
770                                 symtab = (void*)(intptr_t) dynTab[j].d_un.d_val;        // Rebased in Relocate
771                                 break;
772                         case DT_STRTAB:
773                                 dynstrtab = (void*)(intptr_t) dynTab[j].d_un.d_val;
774                                 break;
775                         // --- Hash Table --
776                         case DT_HASH:
777                                 pBuckets = (void*)(intptr_t) dynTab[j].d_un.d_val;
778                                 break;
779                         }
780                 }
781         }
782
783         nbuckets = pBuckets[0];
784 //      iSymCount = pBuckets[1];
785         pBuckets = &pBuckets[2];
786         pChains = &pBuckets[ nbuckets ];
787         
788         // Get hash
789         iNameHash = ElfHashString(Name);
790         iNameHash %= nbuckets;
791
792         // Walk Chain
793         i = pBuckets[ iNameHash ];
794         if(symtab[i].st_shndx != SHN_UNDEF && strcmp(dynstrtab + symtab[i].st_name, Name) == 0) {
795                 *Ret = (void*) (intptr_t) symtab[i].st_value + iBaseDiff;
796                 if(Size)        *Size = symtab[i].st_size;
797                 DEBUGS("%s = %p", Name, *Ret);
798                 return 1;
799         }
800         
801         while(pChains[i] != STN_UNDEF)
802         {
803                 i = pChains[i];
804                 if(symtab[i].st_shndx != SHN_UNDEF && strcmp(dynstrtab + symtab[i].st_name, Name) == 0) {
805                         *Ret = (void*)(intptr_t)symtab[i].st_value + iBaseDiff;
806                         if(Size)        *Size = symtab[i].st_size;
807                         DEBUGS("%s = %p", Name, *Ret);
808                         return 1;
809                 }
810         }
811         
812         return 0;
813 }
814 #endif
815
816
817 uint32_t ElfHashString(const char *name)
818 {
819         uint32_t        h = 0, g;
820         while(*name)
821         {
822                 h = (h << 4) + *(uint8_t*)name++;
823                 if( (g = h & 0xf0000000) )
824                         h ^= g >> 24;
825                 h &= ~g;
826         }
827         return h;
828 }
829

UCC git Repository :: git.ucc.asn.au