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

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