a79b591fd1af5f9e4957d5feaf4e4252be3525dc
[tpg/acess2.git] / AcessNative / ld-acess_src / elf.c
1 /*\r
2  * Acess v0.1\r
3  * ELF Executable Loader Code\r
4  */\r
5 #define DEBUG   0\r
6 #include <stdlib.h>\r
7 #include <stdio.h>\r
8 #include <string.h>\r
9 #include <unistd.h>\r
10 #include "common.h"\r
11 #include "elf.h"\r
12 \r
13 #define DEBUG_WARN      1\r
14 \r
15 #define MKPTR(_type,_val)       ((_type*)(uintptr_t)(_val))\r
16 #define PTRMK(_type,_val)       MKPTR(_type,_val)\r
17 #define PTR(_val)       ((void*)(uintptr_t)(_val))\r
18 \r
19 #if DEBUG\r
20 # define ENTER(...)\r
21 # define LOG(s, ...)    printf("%s: " s, __func__, __VA_ARGS__)\r
22 # define LOGS(s)        printf("%s: " s, __func__)\r
23 # define LEAVE(...)\r
24 #else\r
25 # define ENTER(...)\r
26 # define LOG(...)\r
27 # define LOGS(...)\r
28 # define LEAVE(...)\r
29 #endif\r
30 \r
31 // === PROTOTYPES ===\r
32 void    *Elf_Load(FILE *FP);\r
33 uintptr_t       Elf_Relocate(void *Base);\r
34  int    Elf_GetSymbol(void *Base, char *Name, uintptr_t *ret);\r
35  int    Elf_Int_DoRelocate(uint32_t r_info, uint32_t *ptr, uint32_t addend, Elf32_Sym *symtab, void *Base);\r
36 uint32_t        Elf_Int_HashString(char *str);\r
37 \r
38 // === CODE ===\r
39 void *Elf_Load(FILE *FP)\r
40 {\r
41         Elf32_Ehdr      hdr;\r
42         Elf32_Phdr      *phtab;\r
43          int    i, j;\r
44          int    iPageCount;\r
45         uint32_t        max, base;\r
46         uint32_t        addr;\r
47         uint32_t        baseDiff = 0;\r
48         \r
49         ENTER("pFP", FP);\r
50         \r
51         // Read ELF Header\r
52         fread(&hdr, sizeof(hdr), 1, FP);\r
53         \r
54         // Check the file type\r
55         if(hdr.ident[0] != 0x7F || hdr.ident[1] != 'E' || hdr.ident[2] != 'L' || hdr.ident[3] != 'F') {\r
56                 Warning("Non-ELF File was passed to the ELF loader\n");\r
57                 LEAVE('n');\r
58                 return NULL;\r
59         }\r
60         \r
61         // Check for a program header\r
62         if(hdr.phoff == 0) {\r
63                 #if DEBUG_WARN\r
64                 Warning("ELF File does not contain a program header\n");\r
65                 #endif\r
66                 LEAVE('n');\r
67                 return NULL;\r
68         }\r
69         \r
70         // Read Program Header Table\r
71         phtab = malloc( sizeof(Elf32_Phdr) * hdr.phentcount );\r
72         if( !phtab ) {\r
73                 LEAVE('n');\r
74                 return NULL;\r
75         }\r
76         LOG("hdr.phoff = 0x%08x\n", hdr.phoff);\r
77         fseek(FP, hdr.phoff, SEEK_SET);\r
78         fread(phtab, sizeof(Elf32_Phdr), hdr.phentcount, FP);\r
79         \r
80         // Count Pages\r
81         iPageCount = 0;\r
82         LOG("hdr.phentcount = %i\n", hdr.phentcount);\r
83         for( i = 0; i < hdr.phentcount; i++ )\r
84         {\r
85                 // Ignore Non-LOAD types\r
86                 if(phtab[i].Type != PT_LOAD)\r
87                         continue;\r
88                 iPageCount += ((phtab[i].VAddr&0xFFF) + phtab[i].MemSize + 0xFFF) >> 12;\r
89                 LOG("phtab[%i] = {VAddr:0x%x, MemSize:0x%x}\n", i, phtab[i].VAddr, phtab[i].MemSize);\r
90         }\r
91         \r
92         LOG("iPageCount = %i\n", iPageCount);\r
93         \r
94         // Allocate Information Structure\r
95         //ret = malloc( sizeof(tBinary) + sizeof(tBinaryPage)*iPageCount );\r
96         // Fill Info Struct\r
97         //ret->Entry = hdr.entrypoint;\r
98         //ret->Base = -1;               // Set Base to maximum value\r
99         //ret->NumPages = iPageCount;\r
100         //ret->Interpreter = NULL;\r
101 \r
102         // Prescan for base and size\r
103         max = 0;\r
104         base = 0xFFFFFFFF;\r
105         for( i = 0; i < hdr.phentcount; i ++)\r
106         {\r
107                 if( phtab[i].Type != PT_LOAD )\r
108                         continue;\r
109                 if( phtab[i].VAddr < base )\r
110                         base = phtab[i].VAddr;\r
111                 if( phtab[i].VAddr > max )\r
112                         max = phtab[i].VAddr;\r
113         }\r
114 \r
115         LOG("base = %08x, max = %08x\n", base, max);\r
116 \r
117         if( base == 0 ) {\r
118                 // Find a nice space (31 address bits allowed)\r
119                 base = FindFreeRange( max, 31 );\r
120                 LOG("new base = %08x\n", base);\r
121                 if( base == 0 ) return NULL;\r
122                 baseDiff = base;\r
123         }\r
124         \r
125         // Load Pages\r
126         j = 0;\r
127         for( i = 0; i < hdr.phentcount; i++ )\r
128         {\r
129                 //LOG("phtab[%i].Type = 0x%x", i, phtab[i].Type);\r
130                 LOG("phtab[%i] = {\n", i);\r
131                 LOG(" .Type = 0x%08x\n", phtab[i].Type);\r
132                 LOG(" .Offset = 0x%08x\n", phtab[i].Offset);\r
133                 LOG(" .VAddr = 0x%08x\n", phtab[i].VAddr);\r
134                 LOG(" .PAddr = 0x%08x\n", phtab[i].PAddr);\r
135                 LOG(" .FileSize = 0x%08x\n", phtab[i].FileSize);\r
136                 LOG(" .MemSize = 0x%08x\n", phtab[i].MemSize);\r
137                 LOG(" .Flags = 0x%08x\n", phtab[i].Flags);\r
138                 LOG(" .Align = 0x%08x\n", phtab[i].Align);\r
139                 LOGS(" }\n");\r
140                 // Get Interpreter Name\r
141                 if( phtab[i].Type == PT_INTERP )\r
142                 {\r
143                         char *tmp;\r
144                         //if(ret->Interpreter)  continue;\r
145                         tmp = malloc(phtab[i].FileSize);\r
146                         fseek(FP, phtab[i].Offset, SEEK_SET);\r
147                         fread(tmp, phtab[i].FileSize, 1, FP);\r
148                         //ret->Interpreter = Binary_RegInterp(tmp);\r
149                         LOG("Interpreter '%s'\n", tmp);\r
150                         free(tmp);\r
151                         continue;\r
152                 }\r
153                 // Ignore non-LOAD types\r
154                 if(phtab[i].Type != PT_LOAD)    continue;\r
155                 \r
156                 LOG("phtab[%i] = {VAddr:0x%x,Offset:0x%x,FileSize:0x%x}\n",\r
157                         i, phtab[i].VAddr+baseDiff, phtab[i].Offset, phtab[i].FileSize);\r
158                 \r
159                 addr = phtab[i].VAddr + baseDiff;\r
160 \r
161                 if( AllocateMemory( addr, phtab[i].MemSize ) ) {\r
162                         fprintf(stderr, "Elf_Load: Unable to map memory at %x (0x%x bytes)\n",\r
163                                 addr, phtab[i].MemSize);\r
164                         free( phtab );\r
165                         return NULL;\r
166                 }\r
167                 \r
168                 fseek(FP, phtab[i].Offset, SEEK_SET);\r
169                 fread( PTRMK(void, addr), phtab[i].FileSize, 1, FP );\r
170                 memset( PTRMK(char, addr) + phtab[i].FileSize, 0, phtab[i].MemSize - phtab[i].FileSize );\r
171         }\r
172         \r
173         // Clean Up\r
174         free(phtab);\r
175         // Return\r
176         LEAVE('p', base);\r
177         return PTRMK(void, base);\r
178 }\r
179 \r
180 // --- ELF RELOCATION ---\r
181 /**\r
182  * \brief Relocates a loaded ELF Executable\r
183  */\r
184 uintptr_t Elf_Relocate(void *Base)\r
185 {\r
186         Elf32_Ehdr      *hdr = Base;\r
187         Elf32_Phdr      *phtab;\r
188          int    i, j;   // Counters\r
189         char    *libPath;\r
190         uint32_t        iRealBase = -1;\r
191         uintptr_t       iBaseDiff;\r
192          int    iSegmentCount;\r
193          int    iSymCount = 0;\r
194         Elf32_Rel       *rel = NULL;\r
195         Elf32_Rela      *rela = NULL;\r
196         uint32_t        *pltgot = NULL;\r
197         void    *plt = NULL;\r
198         uint32_t        *ptr;\r
199          int    relSz=0, relEntSz=8;\r
200          int    relaSz=0, relaEntSz=8;\r
201          int    pltSz=0, pltType=0;\r
202         Elf32_Dyn       *dynamicTab = NULL;     // Dynamic Table Pointer\r
203         char    *dynstrtab = NULL;      // .dynamic String Table\r
204         Elf32_Sym       *dynsymtab = NULL;\r
205          int    bFailed = 0;\r
206         \r
207         ENTER("pBase", Base);\r
208         LOG("Base = %p\n", Base);\r
209         \r
210         // Parse Program Header to get Dynamic Table\r
211         phtab = Base + hdr->phoff;\r
212         iSegmentCount = hdr->phentcount;\r
213         for(i = 0; i < iSegmentCount; i ++ )\r
214         {\r
215                 // Determine linked base address\r
216                 if(phtab[i].Type == PT_LOAD && iRealBase > phtab[i].VAddr)\r
217                         iRealBase = phtab[i].VAddr;\r
218                 \r
219                 // Find Dynamic Section\r
220                 if(phtab[i].Type == PT_DYNAMIC) {\r
221                         if(dynamicTab) {\r
222                                 Warning("Elf_Relocate - Multiple PT_DYNAMIC segments\n");\r
223                                 continue;\r
224                         }\r
225                         dynamicTab = MKPTR(void, phtab[i].VAddr);\r
226                         j = i;  // Save Dynamic Table ID\r
227                         break;\r
228                 }\r
229         }\r
230         \r
231         // Check if a PT_DYNAMIC segement was found\r
232         if(!dynamicTab) {\r
233                 Warning("Elf_Relocate: No PT_DYNAMIC segment in image, returning\n");\r
234                 LEAVE('x', hdr->entrypoint);\r
235                 return hdr->entrypoint;\r
236         }\r
237         \r
238         // Page Align real base\r
239         iRealBase &= ~0xFFF;\r
240         \r
241         LOG("dynamicTab = %p\n", dynamicTab);\r
242         // Adjust "Real" Base\r
243         iBaseDiff = (uintptr_t)Base - iRealBase;\r
244         LOG("iBaseDiff = %p\n", (void*)iBaseDiff);\r
245         // Adjust Dynamic Table\r
246         dynamicTab = PTR( (uintptr_t)dynamicTab + iBaseDiff);\r
247         LOG("dynamicTab = %p\n", dynamicTab);\r
248 \r
249         hdr->entrypoint += iBaseDiff;\r
250         \r
251         // === Get Symbol table and String Table ===\r
252         for( j = 0; dynamicTab[j].d_tag != DT_NULL; j++)\r
253         {\r
254                 switch(dynamicTab[j].d_tag)\r
255                 {\r
256                 // --- Symbol Table ---\r
257                 case DT_SYMTAB:\r
258                         dynamicTab[j].d_val += iBaseDiff;\r
259                         dynsymtab = PTRMK(void, dynamicTab[j].d_val);\r
260                         hdr->misc.SymTable = dynamicTab[j].d_val;       // Saved in unused bytes of ident\r
261                         break;\r
262                 \r
263                 // --- String Table ---\r
264                 case DT_STRTAB:\r
265                         dynamicTab[j].d_val += iBaseDiff;\r
266                         dynstrtab = PTRMK(void, dynamicTab[j].d_val);\r
267                         break;\r
268                 \r
269                 // --- Hash Table --\r
270                 case DT_HASH:\r
271                         dynamicTab[j].d_val += iBaseDiff;\r
272                         iSymCount = (PTRMK(uint32_t, dynamicTab[j].d_val))[1];\r
273                         hdr->misc.HashTable = dynamicTab[j].d_val;      // Saved in unused bytes of ident\r
274                         break;\r
275                 }\r
276         }\r
277 \r
278 \r
279         // Alter Symbols to true base\r
280         for(i = 0; i < iSymCount; i ++)\r
281         {\r
282                 dynsymtab[i].nameOfs += (uintptr_t)dynstrtab;\r
283                 if( dynsymtab[i].shndx == SHN_UNDEF )\r
284                 {\r
285                         LOG("Sym '%s' = UNDEF\n", MKPTR(char,dynsymtab[i].name));\r
286                 }\r
287                 else\r
288                 {\r
289                         dynsymtab[i].value += iBaseDiff;\r
290                         LOG("Sym '%s' = 0x%x (relocated)\n", MKPTR(char,dynsymtab[i].name), dynsymtab[i].value);\r
291                 }\r
292         }\r
293         \r
294         // === Add to loaded list (can be imported now) ===\r
295         Binary_SetReadyToUse( Base );\r
296 \r
297         // === Parse Relocation Data ===\r
298         for( j = 0; dynamicTab[j].d_tag != DT_NULL; j++)\r
299         {\r
300                 switch(dynamicTab[j].d_tag)\r
301                 {\r
302                 // --- Shared Library Name ---\r
303                 case DT_SONAME:\r
304                         LOG(".so Name '%s'\n", dynstrtab + dynamicTab[j].d_val);\r
305                         break;\r
306                 // --- Needed Library ---\r
307                 case DT_NEEDED:\r
308                         libPath = dynstrtab + dynamicTab[j].d_val;\r
309                         Binary_LoadLibrary(libPath);\r
310                         break;\r
311                 // --- PLT/GOT ---\r
312                 case DT_PLTGOT: pltgot = (void*)(iBaseDiff+dynamicTab[j].d_val);        break;\r
313                 case DT_JMPREL: plt = (void*)(iBaseDiff+dynamicTab[j].d_val);   break;\r
314                 case DT_PLTREL: pltType = dynamicTab[j].d_val;  break;\r
315                 case DT_PLTRELSZ:       pltSz = dynamicTab[j].d_val;    break;\r
316                 \r
317                 // --- Relocation ---\r
318                 case DT_REL:    rel = (void*)(iBaseDiff + dynamicTab[j].d_val); break;\r
319                 case DT_RELSZ:  relSz = dynamicTab[j].d_val;    break;\r
320                 case DT_RELENT: relEntSz = dynamicTab[j].d_val; break;\r
321                 \r
322                 case DT_RELA:   rela = (void*)(iBaseDiff + dynamicTab[j].d_val);        break;\r
323                 case DT_RELASZ: relaSz = dynamicTab[j].d_val;   break;\r
324                 case DT_RELAENT:        relaEntSz = dynamicTab[j].d_val;        break;\r
325                 }\r
326         }\r
327         \r
328         // Parse Relocation Entries\r
329         if(rel && relSz)\r
330         {\r
331                 j = relSz / relEntSz;\r
332                 for( i = 0; i < j; i++ )\r
333                 {\r
334                         ptr = (void*)(iBaseDiff + rel[i].r_offset);\r
335                         if( !Elf_Int_DoRelocate(rel[i].r_info, ptr, *ptr, dynsymtab, Base) ) {\r
336                                 bFailed = 1;\r
337                         }\r
338                 }\r
339         }\r
340         // Parse Relocation Entries\r
341         if(rela && relaSz)\r
342         {\r
343                 j = relaSz / relaEntSz;\r
344                 for( i = 0; i < j; i++ )\r
345                 {\r
346                         ptr = (void*)(iBaseDiff + rela[i].r_offset);\r
347                         if( !Elf_Int_DoRelocate(rel[i].r_info, ptr, rela[i].r_addend, dynsymtab, Base) ) {\r
348                                 bFailed = 1;\r
349                         }\r
350                 }\r
351         }\r
352         \r
353         // === Process PLT (Procedure Linkage Table) ===\r
354         if(plt && pltSz)\r
355         {\r
356                 if(pltType == DT_REL)\r
357                 {\r
358                         Elf32_Rel       *pltRel = plt;\r
359                         j = pltSz / sizeof(Elf32_Rel);\r
360                         LOG("PLT Rel - plt = %p, pltSz = %i (%i ents)\n", plt, pltSz, j);\r
361                         for(i = 0; i < j; i++)\r
362                         {\r
363                                 ptr = (void*)(iBaseDiff + pltRel[i].r_offset);\r
364                                 if( !Elf_Int_DoRelocate(pltRel[i].r_info, ptr, *ptr, dynsymtab, Base) ) {\r
365                                         bFailed = 1;\r
366                                 }\r
367                         }\r
368                 }\r
369                 else\r
370                 {\r
371                         Elf32_Rela      *pltRela = plt;\r
372                         j = pltSz / sizeof(Elf32_Rela);\r
373                         LOG("PLT RelA - plt = %p, pltSz = %i (%i ents)\n", plt, pltSz, j);\r
374                         for(i=0;i<j;i++)\r
375                         {\r
376                                 ptr = (void*)(iBaseDiff + pltRela[i].r_offset);\r
377                                 if( !Elf_Int_DoRelocate(pltRela[i].r_info, ptr, pltRela[i].r_addend, dynsymtab, Base) ) {\r
378                                         bFailed = 1;\r
379                                 }\r
380                         }\r
381                 }\r
382         }\r
383         \r
384         if(bFailed) {\r
385                 LEAVE('i', 0);\r
386                 return 0;\r
387         }\r
388         \r
389         LEAVE('x', hdr->entrypoint);\r
390         return hdr->entrypoint;\r
391 }\r
392 \r
393 /**\r
394  * \fn void Elf_Int_DoRelocate(uint32_t r_info, uint32_t *ptr, uint32_t addend, Elf32_Sym *symtab, void *base)\r
395  * \brief Performs a relocation\r
396  * \param r_info        Field from relocation entry\r
397  * \param ptr   Pointer to location of relocation\r
398  * \param addend        Value to add to symbol\r
399  * \param symtab        Symbol Table\r
400  * \param base  Base of loaded binary\r
401  */\r
402 int Elf_Int_DoRelocate(uint32_t r_info, uint32_t *ptr, uint32_t addend, Elf32_Sym *symtab, void *base)\r
403 {\r
404         uintptr_t       val;\r
405          int    type = ELF32_R_TYPE(r_info);\r
406          int    sym = ELF32_R_SYM(r_info);\r
407         char    *sSymName = PTRMK(char, symtab[sym].name);\r
408         \r
409         //LogF("Elf_Int_DoRelocate: (r_info=0x%x, ptr=0x%x, addend=0x%x, .., base=0x%x)\n",\r
410         //      r_info, ptr, addend, base);\r
411         \r
412         switch( type )\r
413         {\r
414         // Standard 32 Bit Relocation (S+A)\r
415         case R_386_32:\r
416                 if( !Elf_GetSymbol( base, sSymName, &val ) && !Binary_GetSymbol( sSymName, &val ) ) {\r
417                         Warning("Unable to find symbol '%s'", sSymName);\r
418                         return 0;\r
419                 }\r
420                 LOG("%08x R_386_32 *%p += %p('%s')\n", r_info, ptr, (void*)val, sSymName);\r
421                 *ptr = val + addend;\r
422                 break;\r
423                 \r
424         // 32 Bit Relocation wrt. Offset (S+A-P)\r
425         case R_386_PC32:\r
426                 if( !Elf_GetSymbol( base, sSymName, &val ) && !Binary_GetSymbol( sSymName, &val ) ) {\r
427                         Warning("Unable to find symbol '%s'", sSymName);\r
428                         return 0;\r
429                 }\r
430                 LOG("%08x R_386_PC32 *%p = 0x%x + %p('%s') - %p\n", r_info, ptr, *ptr, (void*)val, sSymName, ptr );\r
431                 // TODO: Check if it needs the true value of ptr or the compiled value\r
432                 // NOTE: Testing using true value\r
433                 *ptr = val + addend - (uintptr_t)ptr;\r
434                 break;\r
435 \r
436         // Absolute Value of a symbol (S)\r
437         case R_386_GLOB_DAT:\r
438                 if( !Elf_GetSymbol( base, sSymName, &val ) && !Binary_GetSymbol( sSymName, &val ) ) {\r
439                         Warning("Unable to find symbol '%s'", sSymName);\r
440                         return 0; \r
441                 }\r
442                 LOG("%08x R_386_GLOB_DAT *%p = 0x%x(%s)\n", r_info, ptr, (unsigned int)val, sSymName);\r
443                 *ptr = val;\r
444                 break;\r
445         \r
446         // Absolute Value of a symbol (S)\r
447         case R_386_JMP_SLOT:\r
448                 if( !Elf_GetSymbol( base, sSymName, &val ) && !Binary_GetSymbol( sSymName, &val ) ) {\r
449                         Warning("Unable to find symbol '%s'", sSymName);\r
450                         return 0;\r
451                 }\r
452                 LOG("%08x R_386_JMP_SLOT *%p = 0x%x (%s)\n", r_info, ptr, (unsigned int)val, sSymName);\r
453                 *ptr = val;\r
454                 break;\r
455 \r
456         // Base Address (B+A)\r
457         case R_386_RELATIVE:\r
458                 LOG("%08x R_386_RELATIVE *%p = %p + 0x%x\n", r_info, ptr, base, addend);\r
459                 *ptr = (uintptr_t)base + addend;\r
460                 break;\r
461                 \r
462         default:\r
463                 LOG("Rel %p: 0x%x,%i\n", ptr, sym, type);\r
464                 break;\r
465         }\r
466         return 1;\r
467 }\r
468 \r
469 /**\r
470  * \fn int Elf_GetSymbol(void *Base, char *name, uintptr_t *ret)\r
471  * \brief Get a symbol from the loaded binary\r
472  */\r
473 int Elf_GetSymbol(void *Base, char *Name, uintptr_t *ret)\r
474 {\r
475         Elf32_Ehdr      *hdr = (void*)Base;\r
476         Elf32_Sym       *symtab;\r
477          int    nbuckets = 0;\r
478          int    iSymCount = 0;\r
479          int    i;\r
480         uint32_t        *pBuckets;\r
481         uint32_t        *pChains;\r
482         uint32_t        iNameHash;\r
483 \r
484         if(!Base)       return 0;\r
485 \r
486         pBuckets = PTR(hdr->misc.HashTable);\r
487         symtab = PTR(hdr->misc.SymTable);\r
488         \r
489         nbuckets = pBuckets[0];\r
490         iSymCount = pBuckets[1];\r
491         pBuckets = &pBuckets[2];\r
492         pChains = &pBuckets[ nbuckets ];\r
493         \r
494         // Get hash\r
495         iNameHash = Elf_Int_HashString(Name);\r
496         iNameHash %= nbuckets;\r
497 \r
498         // Check Bucket\r
499         i = pBuckets[ iNameHash ];\r
500         if(symtab[i].shndx != SHN_UNDEF && strcmp(MKPTR(char,symtab[i].name), Name) == 0) {\r
501                 if(ret) *ret = symtab[ i ].value;\r
502                 return 1;\r
503         }\r
504         \r
505         // Walk Chain\r
506         while(pChains[i] != STN_UNDEF)\r
507         {\r
508                 i = pChains[i];\r
509                 if(symtab[i].shndx != SHN_UNDEF && strcmp(MKPTR(char,symtab[i].name), Name) == 0) {\r
510                         if(ret) *ret = symtab[ i ].value;\r
511                         return 1;\r
512                 }\r
513         }\r
514         return 0;\r
515 }\r
516 \r
517 /**\r
518  * \fn uint32_t Elf_Int_HashString(char *str)\r
519  * \brief Hash a string in the ELF format\r
520  * \param str   String to hash\r
521  * \return Hash value\r
522  */\r
523 uint32_t Elf_Int_HashString(char *str)\r
524 {\r
525         uint32_t        h = 0, g;\r
526         while(*str)\r
527         {\r
528                 h = (h << 4) + *str++;\r
529                 if( (g = h & 0xf0000000) )\r
530                         h ^= g >> 24;\r
531                 h &= ~g;\r
532         }\r
533         return h;\r
534 }\r

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