Usermode/ld-acess - Overhaul cleanup of ELF loader
authorJohn Hodge (sonata) <[email protected]>
Mon, 3 Nov 2014 04:41:33 +0000 (12:41 +0800)
committerJohn Hodge (sonata) <[email protected]>
Mon, 3 Nov 2014 04:41:33 +0000 (12:41 +0800)
KernelLand/Kernel/bin/elf.c
Usermode/Libraries/ld-acess.so_src/Makefile
Usermode/Libraries/ld-acess.so_src/elf.c
Usermode/Libraries/ld-acess.so_src/elf32.h
Usermode/Libraries/ld-acess.so_src/elf64.h
Usermode/Libraries/ld-acess.so_src/elf_impl.c [new file with mode: 0644]
Usermode/Libraries/ld-acess.so_src/loadlib.c

index 7998d86..37172cf 100644 (file)
@@ -205,15 +205,14 @@ tBinary *Elf_Load32(int FD, Elf32_Ehdr *Header)
 {\r
        tBinary *ret;\r
        Elf32_Phdr      *phtab;\r
-        int    i, j;\r
-        int    iLoadCount;\r
+        int    j;\r
 \r
        ENTER("xFD", FD);\r
 \r
        // Check architecture with current CPU\r
        // - TODO: Support kernel level emulation\r
        #if ARCH_IS_x86\r
-       if( Header->machine != EM_386 )\r
+       if( Header->e_machine != EM_386 )\r
        {\r
                Log_Warning("ELF", "Unknown architecure on ELF-32");\r
                LEAVE_RET('n');\r
@@ -222,7 +221,7 @@ tBinary *Elf_Load32(int FD, Elf32_Ehdr *Header)
        #endif\r
 \r
        // Check for a program header\r
-       if(Header->phoff == 0) {\r
+       if(Header->e_phoff == 0) {\r
                #if DEBUG_WARN\r
                Log_Warning("ELF", "File does not contain a program header (phoff == 0)");\r
                #endif\r
@@ -231,25 +230,25 @@ tBinary *Elf_Load32(int FD, Elf32_Ehdr *Header)
        }\r
        \r
        // Read Program Header Table\r
-       phtab = malloc( sizeof(Elf32_Phdr) * Header->phentcount );\r
+       phtab = malloc( sizeof(Elf32_Phdr) * Header->e_phnum );\r
        if( !phtab ) {\r
                LEAVE('n');\r
                return NULL;\r
        }\r
-       LOG("hdr.phoff = 0x%08x", Header->phoff);\r
-       VFS_Seek(FD, Header->phoff, SEEK_SET);\r
-       VFS_Read(FD, sizeof(Elf32_Phdr)*Header->phentcount, phtab);\r
+       LOG("hdr.phoff = 0x%08x", Header->e_phoff);\r
+       VFS_Seek(FD, Header->e_phoff, SEEK_SET);\r
+       VFS_Read(FD, sizeof(Elf32_Phdr)*Header->e_phnum, phtab);\r
        \r
        // Count Pages\r
-       iLoadCount = 0;\r
-       LOG("Header->phentcount = %i", Header->phentcount);\r
-       for( i = 0; i < Header->phentcount; i++ )\r
+       unsigned iLoadCount = 0;\r
+       LOG("Header->phentcount = %i", Header->e_phnum);\r
+       for( int i = 0; i < Header->e_phnum; i++ )\r
        {\r
                // Ignore Non-LOAD types\r
-               if(phtab[i].Type != PT_LOAD)\r
+               if(phtab[i].p_type != PT_LOAD)\r
                        continue;\r
                iLoadCount ++;\r
-               LOG("phtab[%i] = {VAddr:0x%x, MemSize:0x%x}", i, phtab[i].VAddr, phtab[i].MemSize);\r
+               LOG("phtab[%i] = {VAddr:0x%x, MemSize:0x%x}", i, phtab[i].p_vaddr, phtab[i].p_memsz);\r
        }\r
        \r
        LOG("iLoadCount = %i", iLoadCount);\r
@@ -257,56 +256,55 @@ tBinary *Elf_Load32(int FD, Elf32_Ehdr *Header)
        // Allocate Information Structure\r
        ret = malloc( sizeof(tBinary) + sizeof(tBinarySection)*iLoadCount );\r
        // Fill Info Struct\r
-       ret->Entry = Header->entrypoint;\r
+       ret->Entry = Header->e_entry;\r
        ret->Base = -1;         // Set Base to maximum value\r
        ret->NumSections = iLoadCount;\r
        ret->Interpreter = NULL;\r
        \r
        // Load Pages\r
        j = 0;\r
-       for( i = 0; i < Header->phentcount; i++ )\r
+       for( int i = 0; i < Header->e_phnum; i++ )\r
        {\r
                //LOG("phtab[%i].Type = 0x%x", i, phtab[i].Type);\r
                LOG("phtab[%i] = {", i);\r
-               LOG(" .Type = 0x%08x", phtab[i].Type);\r
-               LOG(" .Offset = 0x%08x", phtab[i].Offset);\r
-               LOG(" .VAddr = 0x%08x", phtab[i].VAddr);\r
-               LOG(" .PAddr = 0x%08x", phtab[i].PAddr);\r
-               LOG(" .FileSize = 0x%08x", phtab[i].FileSize);\r
-               LOG(" .MemSize = 0x%08x", phtab[i].MemSize);\r
-               LOG(" .Flags = 0x%08x", phtab[i].Flags);\r
-               LOG(" .Align = 0x%08x", phtab[i].Align);\r
+               LOG(" .Type = 0x%08x",   phtab[i].p_type);\r
+               LOG(" .Offset = 0x%08x", phtab[i].p_offset);\r
+               LOG(" .VAddr = 0x%08x",  phtab[i].p_vaddr);\r
+               LOG(" .PAddr = 0x%08x",  phtab[i].p_paddr);\r
+               LOG(" .FileSize = 0x%08x", phtab[i].p_filesz);\r
+               LOG(" .MemSize = 0x%08x", phtab[i].p_memsz);\r
+               LOG(" .Flags = 0x%08x",  phtab[i].p_flags);\r
+               LOG(" .Align = 0x%08x",  phtab[i].p_align);\r
                LOG(" }");\r
                // Get Interpreter Name\r
-               if( phtab[i].Type == PT_INTERP )\r
+               if( phtab[i].p_type == PT_INTERP )\r
                {\r
-                       char *tmp;\r
                        if(ret->Interpreter)    continue;\r
-                       tmp = malloc(phtab[i].FileSize);\r
-                       VFS_Seek(FD, phtab[i].Offset, 1);\r
-                       VFS_Read(FD, phtab[i].FileSize, tmp);\r
+                       char* tmp = malloc(phtab[i].p_filesz);\r
+                       VFS_Seek(FD, phtab[i].p_offset, 1);\r
+                       VFS_Read(FD, phtab[i].p_filesz, tmp);\r
                        ret->Interpreter = Binary_RegInterp(tmp);\r
                        LOG("Interpreter '%s'", tmp);\r
                        free(tmp);\r
                        continue;\r
                }\r
                // Ignore non-LOAD types\r
-               if(phtab[i].Type != PT_LOAD)    continue;\r
+               if(phtab[i].p_type != PT_LOAD)  continue;\r
                \r
                // Find Base\r
-               if(phtab[i].VAddr < ret->Base)  ret->Base = phtab[i].VAddr;\r
+               if(phtab[i].p_vaddr < ret->Base)        ret->Base = phtab[i].p_vaddr;\r
                \r
                LOG("phtab[%i] = {VAddr:0x%x,Offset:0x%x,FileSize:0x%x}",\r
-                       i, phtab[i].VAddr, phtab[i].Offset, phtab[i].FileSize);\r
+                       i, phtab[i].p_vaddr, phtab[i].p_offset, phtab[i].p_filesz);\r
                \r
-               ret->LoadSections[j].Offset = phtab[i].Offset;\r
-               ret->LoadSections[j].FileSize = phtab[i].FileSize;\r
-               ret->LoadSections[j].Virtual = phtab[i].VAddr;\r
-               ret->LoadSections[j].MemSize = phtab[i].MemSize;\r
+               ret->LoadSections[j].Offset   = phtab[i].p_offset;\r
+               ret->LoadSections[j].FileSize = phtab[i].p_filesz;\r
+               ret->LoadSections[j].Virtual  = phtab[i].p_vaddr;\r
+               ret->LoadSections[j].MemSize  = phtab[i].p_memsz;\r
                ret->LoadSections[j].Flags = 0;\r
-               if( !(phtab[i].Flags & PF_W) )\r
+               if( !(phtab[i].p_flags & PF_W) )\r
                        ret->LoadSections[j].Flags |= BIN_SECTFLAG_RO;\r
-               if( phtab[i].Flags & PF_X )\r
+               if( phtab[i].p_flags & PF_X )\r
                        ret->LoadSections[j].Flags |= BIN_SECTFLAG_EXEC;\r
                j ++;\r
        }\r
index a588f75..78aac4b 100644 (file)
@@ -11,6 +11,7 @@ EXTRABIN := libld-acess.so
 EXTRACLEAN = $(_OBJPREFIX)_stublib.o
 INCFILES := sys/sys.h
 
+#CPPFLAGS += -D DISABLE_ELF64
 CFLAGS   = -g -Wall -fno-builtin -fno-stack-protector -fPIC -std=c99 -ffreestanding
 # -fno-leading-underscore
 CFLAGS  += $(CPPFLAGS)
index 1e31f77..fa2e3f4 100644 (file)
@@ -17,6 +17,7 @@
 
 #include "common.h"
 #include <stdint.h>
+#include <stdbool.h>
 #ifndef assert
 # include <assert.h>
 #endif
 # define SUPPORT_ELF64
 #endif
 
-typedef struct
-{
-       void    *Base;
-       intptr_t        iBaseDiff;
-       const char      *strtab;
-       Elf32_Sym       *symtab;
-} tElfRelocInfo;
-
-typedef int tElf32RelocFcn(tElfRelocInfo *Info, uint32_t t_info, uint32_t *ptr, Elf32_Addr addend, int bRela);
-
 // === CONSTANTS ===
 #if DEBUG
 //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"};
 //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"};
 #endif
 
+#ifdef SUPPORT_ELF64
+#endif
+
 // === PROTOTYPES ===
 void   *ElfRelocate(void *Base, char **envp, const char *Filename);
  int   ElfGetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
-void   *Elf32Relocate(void *Base, char **envp, const char *Filename);
- int   Elf32GetSymbolVars(void *Base, Elf32_Sym** symtab, Elf32_Word** pBuckets, const char **dynstrtab, uintptr_t* piBaseDiff);
- int   Elf32GetSymbolInfo(void *Base, const char *Name, void **Addr, size_t *Size, int* Section, int *Binding, int *Type);
- int   Elf32GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
-tElf32RelocFcn elf_doRelocate_386;
-tElf32RelocFcn elf_doRelocate_arm;
-tElf32RelocFcn elf_doRelocate_unk;
+void   *Elf32_Relocate(void *Base, char **envp, const char *Filename);
+ int   Elf32_GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
 #ifdef SUPPORT_ELF64
-int    _Elf64DoReloc_X86_64(void *Base, const char *strtab, Elf64_Sym *symtab, Elf64_Xword r_info, void *ptr, Elf64_Sxword addend);
-void   *Elf64Relocate(void *Base, char **envp, const char *Filename);
- int   Elf64GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
+void   *Elf64_Relocate(void *Base, char **envp, const char *Filename);
+ int   Elf64_GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size);
 #endif
- int   Elf32GetSymbolReloc(tElfRelocInfo *Info, const Elf32_Sym *Symbol, void **Ret, size_t *Size);
 uint32_t       ElfHashString(const char *name);
 
 // === CODE ===
@@ -84,10 +71,10 @@ void *ElfRelocate(void *Base, char **envp, const char *Filename)
        switch(hdr->e_ident[4])
        {
        case ELFCLASS32:
-               return Elf32Relocate(Base, envp, Filename);
+               return Elf32_Relocate(Base, envp, Filename);
 #ifdef SUPPORT_ELF64
        case ELFCLASS64:
-               return Elf64Relocate(Base, envp, Filename);
+               return Elf64_Relocate(Base, envp, Filename);
 #endif
        default:
                SysDebug("ld-acess - ElfRelocate: Unknown file class %i", hdr->e_ident[4]);
@@ -105,10 +92,10 @@ int ElfGetSymbol(void *Base, const char *Name, void **ret, size_t *Size)
        switch(hdr->e_ident[4])
        {
        case ELFCLASS32:
-               return Elf32GetSymbol(Base, Name, ret, Size);
+               return Elf32_GetSymbol(Base, Name, ret, Size);
 #ifdef SUPPORT_ELF64
        case ELFCLASS64:
-               return Elf64GetSymbol(Base, Name, ret, Size);
+               return Elf64_GetSymbol(Base, Name, ret, Size);
 #endif
        default:
                SysDebug("ld-acess - ElfRelocate: Unknown file class %i", hdr->e_ident[4]);
@@ -116,7 +103,17 @@ int ElfGetSymbol(void *Base, const char *Name, void **ret, size_t *Size)
        }
 }
 
-int elf_doRelocate_386(tElfRelocInfo *Info, uint32_t r_info, uint32_t *ptr, Elf32_Addr addend, int bRela)
+// --------------------------------------------------------------------
+// Elf32 support
+// --------------------------------------------------------------------
+#define ELFTYPE        Elf32
+#include "elf_impl.c"
+#undef ELFTYPE
+
+Elf32_RelocFcn elf_doRelocate_386;
+Elf32_RelocFcn elf_doRelocate_arm;
+
+int elf_doRelocate_386(const Elf32_RelocInfo *Info, Elf32_Word r_info, Elf32_Word* ptr, Elf32_Addr addend, bool bRela)
 {
        const Elf32_Sym *sym = &Info->symtab[ ELF32_R_SYM(r_info) ];
        void    *symval = (void*)(intptr_t)sym->st_value;
@@ -180,7 +177,7 @@ int elf_doRelocate_386(tElfRelocInfo *Info, uint32_t r_info, uint32_t *ptr, Elf3
        return 0;
 }
 
-int elf_doRelocate_arm(tElfRelocInfo *Info, uint32_t r_info, uint32_t *ptr, Elf32_Addr addend, int bRela)
+int elf_doRelocate_arm(const Elf32_RelocInfo *Info, Elf32_Word r_info, Elf32_Word* ptr, Elf32_Addr addend, bool bRela)
 {
        const Elf32_Sym *sym = &Info->symtab[ ELF32_R_SYM(r_info) ];
        void    *symval = (void*)(intptr_t)sym->st_value;
@@ -227,490 +224,98 @@ int elf_doRelocate_arm(tElfRelocInfo *Info, uint32_t r_info, uint32_t *ptr, Elf3
        return 0;
 }
 
-int elf_doRelocate_unk(tElfRelocInfo *Info, uint32_t r_info, uint32_t *ptr, Elf32_Addr addend, int bRela)
-{
-       return 1;
-}
-
-void *Elf32Relocate(void *Base, char **envp, const char *Filename)
+Elf32_RelocFcn*        Elf32_GetRelocFcn(unsigned Machine)
 {
-       const Elf32_Ehdr        *hdr = Base;
-       char    *libPath;
-       intptr_t        iRealBase = -1;
-       Elf32_Rel       *rel = NULL;
-       Elf32_Rela      *rela = NULL;
-       void    *plt = NULL;
-        int    relSz=0, relEntSz=8;
-        int    relaSz=0, relaEntSz=8;
-        int    pltSz=0, pltType=0;
-       Elf32_Dyn       *dynamicTab = NULL;     // Dynamic Table Pointer
-       
-       TRACE("(Base=0x%x)", Base);
-       
-       // Check magic header
-       
-       
-       // Parse Program Header to get Dynamic Table
-       // - Determine the linked base of the executable
-       const Elf32_Phdr        *phtab = (void*)( (uintptr_t)Base + hdr->phoff );
-       const int iSegmentCount = hdr->phentcount;
-       for(int i = 0; i < iSegmentCount; i ++)
+       switch(Machine)
        {
-               switch(phtab[i].Type)
-               {
-               case PT_LOAD:
-                       // Determine linked base address
-                       if( iRealBase > phtab[i].VAddr)
-                               iRealBase = phtab[i].VAddr;
-                       break;
-               case PT_DYNAMIC:
-                       // Find Dynamic Section
-                       if(!dynamicTab) {
-                               dynamicTab = (void *) (intptr_t) phtab[i].VAddr;
-                       }
-                       else {
-                               WARNING("elf_relocate: Multiple PT_DYNAMIC segments");
-                       }
-                       break;
-               }
-       }
-       
-       // Page Align real base
-       iRealBase &= ~0xFFF;
-       
-       // Adjust "Real" Base
-       const intptr_t  iBaseDiff = (intptr_t)Base - iRealBase;
-
-       TRACE("True Base = 0x%x, Compiled Base = 0x%x, Difference = 0x%x", Base, iRealBase, iBaseDiff);
-
-       // Check if a PT_DYNAMIC segement was found
-       if(!dynamicTab) {
-               SysDebug(" elf_relocate: No PT_DYNAMIC segment in image %p, returning", Base);
-               return (void *)(intptr_t)(hdr->entrypoint + iBaseDiff);
-       }
-
-       // Allow writing to read-only segments, just in case they need to be relocated
-       // - Will be reversed at the end of the function
-       for( int i = 0; i < iSegmentCount; i ++ )
-       {
-               if(phtab[i].Type == PT_LOAD && !(phtab[i].Flags & PF_W) ) {
-                       uintptr_t       addr = phtab[i].VAddr + iBaseDiff;
-                       uintptr_t       end = addr + phtab[i].MemSize;
-                       for( ; addr < end; addr += PAGE_SIZE )
-                               _SysSetMemFlags(addr, 0, 1);    // Unset RO
-               }
-       }
-
-       // Adjust Dynamic Table
-       dynamicTab = (void *)( (intptr_t)dynamicTab + iBaseDiff );
-       
-       // === Get Symbol table and String Table ===
-       char    *dynstrtab = NULL;      // .dynamic String Table
-       Elf32_Sym       *dynsymtab = NULL;
-       Elf32_Word      *hashtable = NULL;
-        int    iSymCount = 0;
-       for( int j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
-       {
-               const Elf32_Dyn *dt = &dynamicTab[j];
-               switch(dt->d_tag)
-               {
-               // --- Symbol Table ---
-               case DT_SYMTAB:
-                       TRACE("DYNAMIC Symbol Table 0x%x (0x%x)", dt->d_val, dt->d_val + iBaseDiff);
-                       dynsymtab = (void*)((intptr_t)dt->d_val + iBaseDiff);
-                       break;
-               // --- String Table ---
-               case DT_STRTAB:
-                       TRACE("DYNAMIC String Table 0x%x (0x%x)", dt->d_val, dt->d_val + iBaseDiff);
-                       dynstrtab = (void*)((intptr_t)dt->d_val + iBaseDiff);
-                       break;
-               // --- Hash Table --
-               case DT_HASH:
-                       TRACE("DYNAMIC Hash table %p (%p)", dt->d_val, dt->d_val + iBaseDiff);
-                       hashtable = (void*)((intptr_t)dt->d_val + iBaseDiff);
-                       iSymCount = hashtable[1];
-                       break;
-               }
+       case EM_386:    return elf_doRelocate_386;
+       case EM_ARM:    return elf_doRelocate_arm;
+       default:        return NULL;
        }
+}
 
-       if(dynsymtab == NULL) {
-               SysDebug("ld-acess.so - WARNING: No Dynamic Symbol table in %p, returning", hdr);
-               return (void *)(intptr_t) (hdr->entrypoint + iBaseDiff);
-       }
-       
-       // Apply base offset to locally defined symbols
-       // - #0 is defined as ("" SHN_UNDEF), so skip it
-       for( int i = 1; i < iSymCount; i ++ )
-       {
-               Elf32_Sym       *sym = &dynsymtab[i];
-               const char *name = dynstrtab + sym->st_name;
-               (void)name;
-               if( sym->st_shndx == SHN_UNDEF )
-               {
-                       TRACE("Sym %i'%s' deferred (SHN_UNDEF)", i, name);
-               }
-               else if( sym->st_shndx == SHN_ABS )
-               {
-                       // Leave as is
-                       SysDebug("Sym %i'%s' untouched", i, name);
-               }
-               else
-               {
-                       void *newval;
-                       size_t  newsize;
-                       if( ELF32_ST_BIND(sym->st_info) != STB_WEAK )
-                       {
-                               TRACE("Sym %i'%s' = %p (local)", i, name, sym->st_value + iBaseDiff);
-                               sym->st_value += iBaseDiff;
-                       }
-                       // If GetSymbol doesn't return a strong/global symbol value
-                       else if( GetSymbol(name, &newval, &newsize, Base) != 1 )
-                       {
-                               TRACE("Sym %i'%s' = %p (Local weak)", i, name, sym->st_value + iBaseDiff);
-                               sym->st_value += iBaseDiff;
-                       }
-                       else
-                       {
-                               TRACE("Sym %i'%s' = %p+0x%x (Extern weak)", i, name, newval, newsize);
-                               sym->st_value = (uintptr_t)newval;
-                               sym->st_size = newsize;
-                       }
-               }
-       }
 
-       // === Add to loaded list (can be imported now) ===
-       AddLoaded( Filename, Base );
+// --------------------------------------------------------------------
+// Elf64 support
+// --------------------------------------------------------------------
+#ifdef SUPPORT_ELF64
 
-       // === Parse Relocation Data ===
-       TRACE("dynamicTab = 0x%x", dynamicTab);
-       for( int j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
-       {
-               const Elf32_Dyn *dt = &dynamicTab[j];
-               switch(dt->d_tag)
-               {
-               // --- Shared Library Name ---
-               case DT_SONAME:
-                       TRACE(".so Name '%s'", dynstrtab + dt->d_val);
-                       break;
-               // --- Needed Library ---
-               case DT_NEEDED:
-                       //assert(dt->d_val <= sizeof_dynstrtab);
-                       libPath = dynstrtab + dt->d_val;
-                       TRACE(" Required Library '%s'", libPath);
-                       if(LoadLibrary(libPath, NULL, envp) == 0) {
-                               SysDebug("Unable to load required library '%s'", libPath);
-                               return 0;
-                       }
-                       TRACE(" Lib loaded");
-                       break;
-               // --- PLT/GOT ---
-//             case DT_PLTGOT: pltgot = (void*)(iBaseDiff + dt->d_val);        break;
-               case DT_JMPREL: plt = (void*)(iBaseDiff + dt->d_val);   break;
-               case DT_PLTREL: pltType = dt->d_val;    break;
-               case DT_PLTRELSZ:       pltSz = dt->d_val;      break;
-               
-               // --- Relocation ---
-               case DT_REL:    rel = (void*)(iBaseDiff + dt->d_val);   break;
-               case DT_RELSZ:  relSz = dt->d_val;      break;
-               case DT_RELENT: relEntSz = dt->d_val;   break;
-               case DT_RELA:   rela = (void*)(iBaseDiff + dt->d_val);  break;
-               case DT_RELASZ: relaSz = dt->d_val;     break;
-               case DT_RELAENT:        relaEntSz = dt->d_val;  break;
-               
-               // --- Symbol Table ---
-               case DT_SYMTAB:
-               // --- Hash Table ---
-               case DT_HASH:
-               // --- String Table ---
-               case DT_STRTAB:
-                       break;
-               
-               // --- Unknown ---
-               default:
-                       if(dt->d_tag > DT_JMPREL)       continue;
-                       //DEBUGS(" elf_relocate: %i-%i = %s,0x%x",
-                       //      i,j, csaDT_NAMES[dynamicTab[j].d_tag],dynamicTab[j].d_val);
-                       break;
-               }
-       }
-       
-       // Resolve symbols (second pass)
-       // - #0 is defined as ("" SHN_UNDEF), so skip it
-        int    fail = 0;
-       for( int i = 1; i < iSymCount; i ++ )
-       {
-               Elf32_Sym       *sym = &dynsymtab[i];
-               const char *name = dynstrtab + sym->st_name;
-               if( sym->st_shndx == SHN_UNDEF )
-               {
-                       void *newval;
-                       size_t  newsize;
-                       if( !GetSymbol(name, &newval, &newsize, Base) ) {
-                               if( ELF32_ST_BIND(sym->st_info) != STB_WEAK ) {
-                                       // Not a weak binding, set fail and move on
-                                       WARNING("Elf32Relocate: Can't find required symbol '%s' for '%s'",
-                                               name, Filename);
-                                       fail = 1;
-                                       continue ;
-                               }
-                               // Leave the symbol value as-is
-                       }
-                       else {
-                               TRACE("Sym %i'%s' bound to %p+0x%x", i, name, newval, newsize);
-                               sym->st_value = (intptr_t)newval;
-                               sym->st_size = newsize;
-                       }
-               }
-               else if( sym->st_shndx == SHN_ABS )
-               {
-                       // Leave as is
-               }
-               else
-               {
-                       // Handled previously
-                       // TODO: What about weak locally-defined symbols?
-                       //assert( ELF32_ST_BIND(sym->st_info) != STB_WEAK );
-               }
-       }
-       if( fail ) {
-               WARNING("Relocation of '%s' failed", Filename);
-               return NULL;
-       }
-       
-       TRACE("Beginning Relocation on '%s'", Filename);
+#define ELFTYPE        Elf64
+#include "elf_impl.c"
+#undef ELFTYPE
 
+Elf64_RelocFcn elf_doRelocate_x86_64;
 
-       tElf32RelocFcn  *do_relocate;
-       switch(hdr->machine)
+int elf_doRelocate_x86_64(const Elf64_RelocInfo *Info, Elf64_Xword r_info, Elf64_Xword* ptr, Elf64_Addr addend, bool bRela)
+{
+       const Elf64_Sym *sym = &Info->symtab[ ELF64_R_SYM(r_info) ];
+       void    *symval = (void*)(intptr_t)sym->st_value;
+       size_t  size = sym->st_size;
+       TRACE("%i '%s'", ELF64_R_TYPE(r_info), Info->strtab + sym->st_name);
+       switch( ELF64_R_TYPE(r_info) )
        {
-       case EM_386:
-               do_relocate = elf_doRelocate_386;
+       case R_X86_64_NONE:
                break;
-       case EM_ARM:
-               do_relocate = elf_doRelocate_arm;
+       case R_X86_64_64:
+               TRACE("R_X86_64_64 *0x%x = %p + 0x%x", ptr, symval, addend);
+               *ptr = (intptr_t)symval + addend;
                break;
-       default:
-               SysDebug("Elf32Relocate: Unknown machine type %i", hdr->machine);
-               do_relocate = elf_doRelocate_unk;
-               fail = 1;
+       // Absolute Value of a symbol (S)
+       case R_X86_64_GLOB_DAT:
+               TRACE("R_X86_64_GLOB_DAT *0x%x = %p", ptr, symval);     if(0)
+       case R_X86_64_JUMP_SLOT:
+               TRACE("R_X86_64_JUMP_SLOT *0x%x = %p", ptr, symval);
+               *ptr = (intptr_t)symval;
                break;
-       }
-       
-       TRACE("do_relocate = %p (%p or %p)", do_relocate, &elf_doRelocate_386, &elf_doRelocate_arm);
 
-       #define _doRelocate(r_info, ptr, bRela, addend) \
-               do_relocate(&reloc_info, r_info, ptr, addend, bRela);
-
-       tElfRelocInfo   reloc_info = {
-               .Base = Base,
-               .iBaseDiff = iBaseDiff,
-               .strtab = dynstrtab,
-               .symtab = dynsymtab
-       };
+       // Base Address (B+A)
+       case R_X86_64_RELATIVE:
+               TRACE("R_X86_64_RELATIVE *0x%x = 0x%x + 0x%x", ptr, Info->iBaseDiff, addend);
+               *ptr = Info->iBaseDiff + addend;
+               break;
 
-       // Parse Relocation Entries
-       if(rel && relSz)
-       {
-               Elf32_Word      *ptr;
-               TRACE("rel=0x%x, relSz=0x%x, relEntSz=0x%x", rel, relSz, relEntSz);
-               int max = relSz / relEntSz;
-               for( int i = 0; i < max; i++ )
-               {
-                       ptr = (void*)(iBaseDiff + rel[i].r_offset);
-                       fail |= _doRelocate(rel[i].r_info, ptr, 0, *ptr);
-               }
-       }
-       // Parse Relocation Entries
-       if(rela && relaSz)
-       {
-               Elf32_Word      *ptr;
-               TRACE("rela=0x%x, relaSz=0x%x, relaEntSz=0x%x", rela, relaSz, relaEntSz);
-               int count = relaSz / relaEntSz;
-               for( int i = 0; i < count; i++ )
-               {
-                       ptr = (void*)(iBaseDiff + rela[i].r_offset);
-                       fail |= _doRelocate(rel[i].r_info, ptr, 1, rela[i].r_addend);
-               }
-       }
-       
-       // === Process PLT (Procedure Linkage Table) ===
-       if(plt && pltSz)
-       {
-               Elf32_Word      *ptr;
-               TRACE("Relocate PLT, plt=0x%x", plt);
-               if(pltType == DT_REL)
+       case R_X86_64_COPY: {
+               void *old_symval = symval;
+               GetSymbol(Info->strtab + sym->st_name, &symval, &size, Info->Base);
+               if( symval == old_symval )
                {
-                       Elf32_Rel       *pltRel = plt;
-                       int count = pltSz / sizeof(Elf32_Rel);
-                       TRACE("PLT Reloc Type = Rel, %i entries", count);
-                       for(int i = 0; i < count; i ++)
+                       if( ELF64_ST_BIND(sym->st_info) != STB_WEAK )
                        {
-                               ptr = (void*)(iBaseDiff + pltRel[i].r_offset);
-                               fail |= _doRelocate(pltRel[i].r_info, ptr, 0, *ptr);
+                               WARNING("sym={val:%p,size:0x%x,info:0x%x,other:0x%x,shndx:%i}",
+                                       sym->st_value, sym->st_size, sym->st_info, sym->st_other, sym->st_shndx);
+                               WARNING("Can't find required external symbol '%s' for R_X86_64_COPY", Info->strtab + sym->st_name);
+                               return 1;
                        }
+                       // Don't bother doing the memcpy
+                       TRACE("R_X86_64_COPY (%p, %p, %i)", ptr, symval, size);
                }
                else
                {
-                       Elf32_Rela      *pltRela = plt;
-                       int count = pltSz / sizeof(Elf32_Rela);
-                       TRACE("PLT Reloc Type = Rela, %i entries", count);
-                       for(int i=0;i<count;i++)
-                       {
-                               ptr = (void*)(iRealBase + pltRela[i].r_offset);
-                               fail |= _doRelocate(pltRela[i].r_info, ptr, 1, pltRela[i].r_addend);
-                       }
-               }
-       }
-
-       // Re-set readonly
-       for( int i = 0; i < iSegmentCount; i ++ )
-       {
-               // If load and not writable
-               if(phtab[i].Type == PT_LOAD && !(phtab[i].Flags & PF_W) ) {
-                       uintptr_t       addr = phtab[i].VAddr + iBaseDiff;
-                       uintptr_t       end = addr + phtab[i].MemSize;
-                       for( ; addr < end; addr += PAGE_SIZE )
-                               _SysSetMemFlags(addr, 1, 1);    // Unset RO
+                       TRACE("R_X86_64_COPY (%p, %p, %i)", ptr, symval, size);
+                       memcpy(ptr, symval, size);
                }
+               break; }
+       default:
+               WARNING("Unknown Relocation, %i", ELF64_R_TYPE(r_info));
+               return 2;
        }
-
-       if( fail ) {
-               TRACE("ElfRelocate: Failure");
-               return NULL;
-       }       
-
-       #undef _doRelocate
-
-       TRACE("RETURN 0x%x to %p", hdr->entrypoint + iBaseDiff, __builtin_return_address(0));
-       return (void*)(intptr_t)( hdr->entrypoint + iBaseDiff );
+       return 0;
 }
 
-int Elf32GetSymbolVars(void *Base, Elf32_Sym** symtab, Elf32_Word** pBuckets, const char **dynstrtab, uintptr_t* piBaseDiff)
+Elf64_RelocFcn* Elf64_GetRelocFcn(unsigned Machine)
 {
-       Elf32_Dyn       *dynTab = NULL;
-       uintptr_t       iBaseDiff = -1;
-       Elf32_Ehdr *hdr = Base;
-       Elf32_Phdr *phtab = (void*)( (uintptr_t)Base + hdr->phoff );
-       for( int i = 0; i < hdr->phentcount; i ++ )
-       {
-               if(phtab[i].Type == PT_LOAD && iBaseDiff > phtab[i].VAddr)
-                       iBaseDiff = phtab[i].VAddr;
-               if( phtab[i].Type == PT_DYNAMIC ) {
-                       dynTab = (void*)(intptr_t)phtab[i].VAddr;
-               }
-       }
-       if( !dynTab ) {
-               SysDebug("ERROR - Unable to find DYNAMIC segment in %p", Base);
-               return 1;
-       }
-       iBaseDiff = (intptr_t)Base - iBaseDiff; // Make iBaseDiff actually the diff
-       dynTab = (void*)( (intptr_t)dynTab + iBaseDiff );
-       for( int i = 0; dynTab[i].d_tag != DT_NULL; i++)
-       {
-               switch(dynTab[i].d_tag)
-               {
-               // --- Symbol Table ---
-               case DT_SYMTAB:
-                       *symtab = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);       // Rebased in Relocate
-                       break;
-               case DT_STRTAB:
-                       *dynstrtab = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);
-                       break;
-               // --- Hash Table --
-               case DT_HASH:
-                       *pBuckets = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);
-                       break;
-               }
-       }
-       
-       if( !*symtab ) {
-               SysDebug("ERRO - No DT_SYMTAB in %p", Base);
-               return 1;
-       }
-       if( !*pBuckets ) {
-               SysDebug("ERRO - No DT_HASH in %p", Base);
-               return 1;
-       }
-       if( !*dynstrtab ) {
-               SysDebug("ERRO - No DT_STRTAB in %p", Base);
-               return 1;
-       }
-
-       // ... ok... maybe they haven't been relocated
-       if( (uintptr_t)*symtab < (uintptr_t)Base )
+       switch(Machine)
        {
-               SysDebug("Executable not yet relocated (symtab,pBuckets,dynstrtab = %p,%p,%p + 0x%x)",
-                       *symtab,*pBuckets,*dynstrtab, iBaseDiff);
-               *symtab    = (void*)( (uintptr_t)*symtab    + iBaseDiff );
-               *pBuckets  = (void*)( (uintptr_t)*pBuckets  + iBaseDiff );
-               *dynstrtab = (void*)( (uintptr_t)*dynstrtab + iBaseDiff );
+       case EM_X86_64: return elf_doRelocate_x86_64;
+       default:        return NULL;
        }
-       *piBaseDiff = iBaseDiff;
-       return 0;
 }
 
-int Elf32GetSymbolInfo(void *Base, const char *Name, void **Addr, size_t *Size, int* Section, int *Binding, int *Type)
-{
-       // Locate the tables
-       uintptr_t       iBaseDiff = -1;
-       Elf32_Sym       *symtab = NULL;
-       Elf32_Word      *pBuckets = NULL;
-       const char      *dynstrtab = NULL;
-       if( Elf32GetSymbolVars(Base, &symtab, &pBuckets, &dynstrtab, &iBaseDiff) )
-               return 1;
-
-       int nbuckets = pBuckets[0];
-//     int iSymCount = pBuckets[1];
-       pBuckets = &pBuckets[2];
-       Elf32_Word* pChains = &pBuckets[ nbuckets ];
-       assert(pChains);
-
-       // Get hash
-       int iNameHash = ElfHashString(Name);
-       iNameHash %= nbuckets;
-
-       // Walk Chain
-       int idx = pBuckets[ iNameHash ];
-       do {
-               const Elf32_Sym *sym = &symtab[idx];
-               assert(sym);
-               if( strcmp(dynstrtab + sym->st_name, Name) == 0 )
-               {
-                       TRACE("*sym = {value:0x%x,size:0x%x,info:0x%x,other:0x%x,shndx:%i}",
-                               sym->st_value, sym->st_size, sym->st_info,
-                               sym->st_other, sym->st_shndx);
-                       if(Addr)        *Addr = (void*)(intptr_t)( sym->st_value );
-                       if(Size)        *Size = sym->st_size;
-                       if(Binding)     *Binding = ELF32_ST_BIND(sym->st_info);
-                       if(Type)        *Type = ELF32_ST_TYPE(sym->st_info);
-                       if(Section)     *Section = sym->st_shndx;
-                       return 0;
-               }
-       } while( (idx = pChains[idx]) != STN_UNDEF && idx != pBuckets[iNameHash] );
-       
-       TRACE("No symbol");
-       return 1;
-}
+#endif // SUPPORT_ELF64
 
-int Elf32GetSymbol(void *Base, const char *Name, void **ret, size_t *Size)
-{
-        int    section, binding;
-       TRACE("Elf32GetSymbol(%p,%s,...)", Base, Name);
-       if( Elf32GetSymbolInfo(Base, Name, ret, Size, &section, &binding, NULL) )
-               return 0;
-       if( section == SHN_UNDEF ) {
-               TRACE("Elf32GetSymbol: Undefined %p", *ret, (Size?*Size:0), section);
-               return 0;
-       }
-       if( binding == STB_WEAK ) {
-               TRACE("Elf32GetSymbol: Weak, return %p+0x%x,section=%i", *ret, (Size?*Size:0), section);
-               return 2;
-       }
-       TRACE("Elf32GetSymbol: Found %p+0x%x,section=%i", *ret, (Size?*Size:0), section);
-       return 1;
-}
 
 #ifdef SUPPORT_ELF64
+#if 0
 typedef int (*t_elf64_doreloc)(void *Base, const char *strtab, Elf64_Sym *symtab, Elf64_Xword r_info, void *ptr, Elf64_Sxword addend);
 
 int _Elf64DoReloc_X86_64(void *Base, const char *strtab, Elf64_Sym *symtab, Elf64_Xword r_info, void *ptr, Elf64_Sxword addend)
@@ -1046,6 +651,7 @@ int Elf64GetSymbol(void *Base, const char *Name, void **Ret, size_t *Size)
        return 0;
 }
 #endif
+#endif
 
 uint32_t ElfHashString(const char *name)
 {
index bb15f82..40c801c 100644 (file)
@@ -12,6 +12,7 @@ typedef uint16_t      Elf32_Half;
 typedef uint32_t       Elf32_Addr;
 typedef uint32_t       Elf32_Off;
 typedef uint32_t       Elf32_Word;
+typedef uint32_t       Elf32_Xword;    // < not strictly correct... but meh
 typedef int32_t        Elf32_Sword;
 
 #define ELFCLASS32     1
@@ -26,19 +27,19 @@ typedef int32_t     Elf32_Sword;
 */
 struct sElf32_Ehdr {
        uint8_t e_ident[16];    //!< Identifier Bytes
-       Elf32_Half      filetype;       //!< File Type
-       Elf32_Half      machine;        //!< Machine / Arch
-       Elf32_Word      version;        //!< Version (File?)
-       Elf32_Addr      entrypoint;     //!< Entry Point
-       Elf32_Off       phoff;  //!< Program Header Offset
-       Elf32_Word      shoff;  //!< Section Header Offset
-       Elf32_Word      flags;  //!< Flags
-       Elf32_Half      headersize;     //!< Header Size
-       Elf32_Half      phentsize;      //!< Program Header Entry Size
-       Elf32_Half      phentcount;     //!< Program Header Entry Count
-       Elf32_Half      shentsize;      //!< Section Header Entry Size
-       Elf32_Half      shentcount;     //!< Section Header Entry Count
-       Elf32_Half      shstrindex;     //!< Section Header String Table Index
+       Elf32_Half      e_filetype;     //!< File Type
+       Elf32_Half      e_machine;      //!< Machine / Arch
+       Elf32_Word      e_version;      //!< Version (File?)
+       Elf32_Addr      e_entry;        //!< Entry Point
+       Elf32_Off       e_phoff;        //!< Program Header Offset
+       Elf32_Word      e_shoff;        //!< Section Header Offset
+       Elf32_Word      e_flags;        //!< Flags
+       Elf32_Half      e_headersize;   //!< Header Size
+       Elf32_Half      e_phentsize;    //!< Program Header Entry Size
+       Elf32_Half      e_phnum;        //!< Program Header Entry Count
+       Elf32_Half      e_shentsize;    //!< Section Header Entry Size
+       Elf32_Half      e_shentcount;   //!< Section Header Entry Count
+       Elf32_Half      e_shstrindex;   //!< Section Header String Table Index
 };
 
 /**
@@ -147,14 +148,14 @@ enum {
 #define PF_R   4
 
 struct sElf32_Phdr {
-       Elf32_Word      Type;
-       Elf32_Off       Offset;
-       Elf32_Addr      VAddr;
-       Elf32_Addr      PAddr;
-       Elf32_Word      FileSize;
-       Elf32_Word      MemSize;
-       Elf32_Word      Flags;
-       Elf32_Word      Align;
+       Elf32_Word      p_type;
+       Elf32_Off       p_offset;
+       Elf32_Addr      p_vaddr;
+       Elf32_Addr      p_paddr;
+       Elf32_Word      p_filesz;
+       Elf32_Word      p_memsz;
+       Elf32_Word      p_flags;
+       Elf32_Word      p_align;
 };
 
 struct elf32_rel_s {
index fb39782..9d04e8a 100644 (file)
@@ -69,7 +69,7 @@ typedef struct
        union {
                Elf64_Xword     d_val;
                Elf64_Addr      d_ptr;
-       } d_un;
+       };// d_un;
 } Elf64_Dyn;
 
 typedef struct
@@ -97,6 +97,8 @@ typedef struct
 
 #define ELF64_R_SYM(info)      ((info) >> 32)
 #define ELF64_R_TYPE(info)     ((info) & 0xFFFFFFFF)
+#define ELF64_ST_BIND(i)       ((i)>>4)
+#define ELF64_ST_TYPE(i)       ((i)&0xF)
 
 enum eElf64_RelocTypes_x86_64
 {
diff --git a/Usermode/Libraries/ld-acess.so_src/elf_impl.c b/Usermode/Libraries/ld-acess.so_src/elf_impl.c
new file mode 100644 (file)
index 0000000..a89a26f
--- /dev/null
@@ -0,0 +1,506 @@
+
+#ifndef ELFTYPE
+# error "ELFTYPE must be defined to either ELf32 or Elf64 to use this file"
+#endif
+
+#define __PREF(t,s)    t##_##s
+#define _PREF(t,s)     __PREF(t,s)
+#define PREF(sym)      _PREF(ELFTYPE,sym)
+
+typedef struct
+{
+       void    *Base;
+       intptr_t        iBaseDiff;
+       const char      *strtab;
+       const PREF(Sym) *symtab;
+} PREF(RelocInfo);
+
+typedef int PREF(RelocFcn)(const PREF(RelocInfo)* Info, PREF(Xword) t_info, PREF(Xword)* ptr, PREF(Addr) addend, bool bRela);
+
+// - Extern
+static PREF(RelocFcn)* PREF(GetRelocFcn)(unsigned Machine);
+// - Local
+static PREF(RelocFcn) PREF(doRelocate_unk);
+static void PREF(int_GetBaseDyntab)(void* Base, const PREF(Phdr)* phtab, unsigned phentcount, intptr_t* iBaseDiff_p, PREF(Dyn)** dynamicTab_p);
+static int PREF(GetSymbolVars)(void *Base, const PREF(Sym)** symtab, const PREF(Word)** pBuckets, const char **dynstrtab, uintptr_t* piBaseDiff);
+static int PREF(GetSymbolInfo)(void *Base, const char *Name, void **Addr, size_t *Size, int* Section, int *Binding, int *Type);
+
+// - Relocate
+void *PREF(Relocate)(void *Base, char **envp, const char *Filename)
+{
+       TRACE("(Base=0x%x)", Base);
+       const PREF(Ehdr)        *hdr = Base;
+       
+       // Check magic header
+       // TODO: Validate header?
+       
+       
+       // Parse Program Header to get Dynamic Table
+       // - Determine the linked base of the executable
+       const PREF(Phdr)        *phtab = (void*)( (uintptr_t)Base + hdr->e_phoff );
+       
+       intptr_t        iBaseDiff = 0;
+       PREF(Dyn)*      dynamicTab = NULL;
+       
+       PREF(int_GetBaseDyntab)(Base, phtab, hdr->e_phnum, &iBaseDiff, &dynamicTab);
+       
+       // Check if a PT_DYNAMIC segement was found
+       if(!dynamicTab)
+       {
+               SysDebug(" elf_relocate: No PT_DYNAMIC segment in image %p, returning", Base);
+               return (void *)(intptr_t)(hdr->e_entry + iBaseDiff);
+       }
+
+       // Allow writing to read-only segments, just in case they need to be relocated
+       // - Will be reversed at the end of the function
+       for( unsigned i = 0; i < hdr->e_phnum; i ++ )
+       {
+               if(phtab[i].p_type == PT_LOAD && !(phtab[i].p_flags & PF_W) )
+               {
+                       uintptr_t       addr = phtab[i].p_vaddr + iBaseDiff;
+                       uintptr_t       end = addr + phtab[i].p_memsz;
+                       for( ; addr < end; addr += PAGE_SIZE )
+                               _SysSetMemFlags(addr, 0, 1);    // Unset RO
+               }
+       }
+       
+       // === Get Symbol table and String Table ===
+       char    *dynstrtab = NULL;      // .dynamic String Table
+       PREF(Sym)       *dynsymtab = NULL;
+       PREF(Word)      *hashtable = NULL;
+       unsigned        iSymCount = 0;
+       for( unsigned j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
+       {
+               const PREF(Dyn) *dt = &dynamicTab[j];
+               switch(dt->d_tag)
+               {
+               // --- Symbol Table ---
+               case DT_SYMTAB:
+                       TRACE("DYNAMIC Symbol Table 0x%x (0x%x)", dt->d_val, dt->d_val + iBaseDiff);
+                       dynsymtab = (void*)((intptr_t)dt->d_val + iBaseDiff);
+                       break;
+               // --- String Table ---
+               case DT_STRTAB:
+                       TRACE("DYNAMIC String Table 0x%x (0x%x)", dt->d_val, dt->d_val + iBaseDiff);
+                       dynstrtab = (void*)((intptr_t)dt->d_val + iBaseDiff);
+                       break;
+               // --- Hash Table --
+               case DT_HASH:
+                       TRACE("DYNAMIC Hash table %p (%p)", dt->d_val, dt->d_val + iBaseDiff);
+                       hashtable = (void*)((intptr_t)dt->d_val + iBaseDiff);
+                       iSymCount = hashtable[1];
+                       break;
+               }
+       }
+
+       if(dynsymtab == NULL) {
+               SysDebug("ld-acess.so - WARNING: No Dynamic Symbol table in %p, returning", hdr);
+               return (void *)(intptr_t) (hdr->e_entry + iBaseDiff);
+       }
+       
+       // Apply base offset to locally defined symbols
+       // - #0 is defined as ("" SHN_UNDEF), so skip it
+       for( unsigned i = 1; i < iSymCount; i ++ )
+       {
+               PREF(Sym)       *sym = &dynsymtab[i];
+               const char *name = dynstrtab + sym->st_name;
+               (void)name;
+               if( sym->st_shndx == SHN_UNDEF )
+               {
+                       TRACE("Sym %i'%s' deferred (SHN_UNDEF)", i, name);
+               }
+               else if( sym->st_shndx == SHN_ABS )
+               {
+                       // Leave as is
+                       TRACE("Sym %i'%s' untouched", i, name);
+               }
+               else
+               {
+                       void *newval;
+                       size_t  newsize;
+                       if( ELF32_ST_BIND(sym->st_info) != STB_WEAK )
+                       {
+                               TRACE("Sym %i'%s' = %p (local)", i, name, sym->st_value + iBaseDiff);
+                               sym->st_value += iBaseDiff;
+                       }
+                       // If GetSymbol doesn't return a strong/global symbol value
+                       else if( GetSymbol(name, &newval, &newsize, Base) != 1 )
+                       {
+                               TRACE("Sym %i'%s' = %p (Local weak)", i, name, sym->st_value + iBaseDiff);
+                               sym->st_value += iBaseDiff;
+                       }
+                       else
+                       {
+                               TRACE("Sym %i'%s' = %p+0x%x (Extern weak)", i, name, newval, newsize);
+                               sym->st_value = (uintptr_t)newval;
+                               sym->st_size = newsize;
+                       }
+               }
+       }
+
+       // === Add to loaded list (can be imported now) ===
+       AddLoaded( Filename, Base );
+
+       // === Parse Relocation Data ===
+       PREF(Rel)       *rel = NULL;
+       PREF(Rela)      *rela = NULL;
+       void    *plt = NULL;
+        int    relSz=0, relEntSz=8;
+        int    relaSz=0, relaEntSz=8;
+        int    pltSz=0, pltType=0;
+       TRACE("dynamicTab = 0x%x", dynamicTab);
+       for( int j = 0; dynamicTab[j].d_tag != DT_NULL; j++)
+       {
+               const PREF(Dyn) *dt = &dynamicTab[j];
+               switch(dt->d_tag)
+               {
+               // --- Shared Library Name ---
+               case DT_SONAME:
+                       TRACE(".so Name '%s'", dynstrtab + dt->d_val);
+                       break;
+               // --- Needed Library ---
+               case DT_NEEDED: {
+                       //assert(dt->d_val < sizeof_dynstrtab); // Disabled, no sizeof_dynstrtab
+                       const char      *libPath = dynstrtab + dt->d_val;
+                       TRACE(" Required Library '%s'", libPath);
+                       if(LoadLibrary(libPath, NULL, envp) == 0) {
+                               SysDebug("Unable to load required library '%s'", libPath);
+                               return 0;
+                       }
+                       TRACE(" Lib loaded");
+                       break; }
+               // --- PLT/GOT ---
+//             case DT_PLTGOT: pltgot = (void*)(iBaseDiff + dt->d_val);        break;
+               case DT_JMPREL: plt = (void*)(iBaseDiff + dt->d_val);   break;
+               case DT_PLTREL: pltType = dt->d_val;    break;
+               case DT_PLTRELSZ:       pltSz = dt->d_val;      break;
+               
+               // --- Relocation ---
+               case DT_REL:    rel = (void*)(iBaseDiff + dt->d_val);   break;
+               case DT_RELSZ:  relSz = dt->d_val;      break;
+               case DT_RELENT: relEntSz = dt->d_val;   break;
+               case DT_RELA:   rela = (void*)(iBaseDiff + dt->d_val);  break;
+               case DT_RELASZ: relaSz = dt->d_val;     break;
+               case DT_RELAENT:        relaEntSz = dt->d_val;  break;
+               
+               // --- Symbol Table ---
+               case DT_SYMTAB:
+               // --- Hash Table ---
+               case DT_HASH:
+               // --- String Table ---
+               case DT_STRTAB:
+                       break;
+               
+               // --- Unknown ---
+               default:
+                       if(dt->d_tag > DT_JMPREL)       continue;
+                       //DEBUGS(" elf_relocate: %i-%i = %s,0x%x",
+                       //      i,j, csaDT_NAMES[dynamicTab[j].d_tag],dynamicTab[j].d_val);
+                       break;
+               }
+       }
+       
+       // Resolve symbols (second pass)
+       // - #0 is defined as ("" SHN_UNDEF), so skip it
+        int    fail = 0;
+       for( int i = 1; i < iSymCount; i ++ )
+       {
+               PREF(Sym)       *sym = &dynsymtab[i];
+               const char *name = dynstrtab + sym->st_name;
+               if( sym->st_shndx == SHN_UNDEF )
+               {
+                       void *newval;
+                       size_t  newsize;
+                       if( !GetSymbol(name, &newval, &newsize, Base) ) {
+                               if( ELF32_ST_BIND(sym->st_info) != STB_WEAK ) {
+                                       // Not a weak binding, set fail and move on
+                                       WARNING("%s: Can't find required symbol '%s' for '%s'", __func__, name, Filename);
+                                       fail = 1;
+                                       continue ;
+                               }
+                               // Leave the symbol value as-is
+                       }
+                       else {
+                               TRACE("Sym %i'%s' bound to %p+0x%x", i, name, newval, newsize);
+                               sym->st_value = (intptr_t)newval;
+                               sym->st_size = newsize;
+                       }
+               }
+               else if( sym->st_shndx == SHN_ABS )
+               {
+                       // Leave as is
+               }
+               else
+               {
+                       // Handled previously
+                       // TODO: What about weak locally-defined symbols?
+                       //assert( ELF32_ST_BIND(sym->st_info) != STB_WEAK );
+               }
+       }
+       if( fail ) {
+               WARNING("Relocation of '%s' failed", Filename);
+               return NULL;
+       }
+       
+       TRACE("Beginning Relocation on '%s'", Filename);
+
+
+       PREF(RelocFcn)* do_relocate = PREF(GetRelocFcn)(hdr->e_machine);
+       if( do_relocate == 0 )
+       {
+               SysDebug("%s: Unknown machine type %i", __func__, hdr->e_machine);
+               do_relocate = PREF(doRelocate_unk);
+               fail = 1;
+       }
+       
+       TRACE("do_relocate = %p", do_relocate);
+
+       #define _doRelocate(r_info, ptr, bRela, addend) \
+               do_relocate(&reloc_info, r_info, ptr, addend, bRela);
+
+       PREF(RelocInfo) reloc_info = {
+               .Base = Base,
+               .iBaseDiff = iBaseDiff,
+               .strtab = dynstrtab,
+               .symtab = dynsymtab
+       };
+
+       // Parse Relocation Entries
+       if(rel && relSz)
+       {
+               TRACE("rel=0x%x, relSz=0x%x, relEntSz=0x%x", rel, relSz, relEntSz);
+               int max = relSz / relEntSz;
+               for( int i = 0; i < max; i++ )
+               {
+                       PREF(Xword) *ptr = (void*)(iBaseDiff + rel[i].r_offset);
+                       fail |= _doRelocate(rel[i].r_info, ptr, 0, *ptr);
+               }
+       }
+       // Parse Relocation Entries
+       if(rela && relaSz)
+       {
+               TRACE("rela=0x%x, relaSz=0x%x, relaEntSz=0x%x", rela, relaSz, relaEntSz);
+               int count = relaSz / relaEntSz;
+               for( int i = 0; i < count; i++ )
+               {
+                       void *ptr = (void*)(iBaseDiff + rela[i].r_offset);
+                       fail |= _doRelocate(rela[i].r_info, ptr, 1, rela[i].r_addend);
+               }
+       }
+       
+       // === Process PLT (Procedure Linkage Table) ===
+       if(plt && pltSz)
+       {
+               TRACE("Relocate PLT, plt=0x%x", plt);
+               if(pltType == DT_REL)
+               {
+                       PREF(Rel)       *pltRel = plt;
+                       int count = pltSz / sizeof(*pltRel);
+                       TRACE("PLT Reloc Type = Rel, %i entries", count);
+                       for(int i = 0; i < count; i ++)
+                       {
+                               PREF(Xword) *ptr = (void*)(iBaseDiff + pltRel[i].r_offset);
+                               fail |= _doRelocate(pltRel[i].r_info, ptr, 0, *ptr);
+                       }
+               }
+               else
+               {
+                       PREF(Rela)      *pltRela = plt;
+                       int count = pltSz / sizeof(*pltRela);
+                       TRACE("PLT Reloc Type = Rela, %i entries", count);
+                       for(int i=0;i<count;i++)
+                       {
+                               void *ptr = (void*)(iBaseDiff + pltRela[i].r_offset);
+                               fail |= _doRelocate(pltRela[i].r_info, ptr, 1, pltRela[i].r_addend);
+                       }
+               }
+       }
+
+       // Re-set readonly
+       for( int i = 0; i < hdr->e_phnum; i ++ )
+       {
+               // If load and not writable
+               if(phtab[i].p_type == PT_LOAD && !(phtab[i].p_flags & PF_W) )
+               {
+                       uintptr_t       addr = phtab[i].p_vaddr + iBaseDiff;
+                       uintptr_t       end = addr + phtab[i].p_memsz;
+                       for( ; addr < end; addr += PAGE_SIZE )
+                               _SysSetMemFlags(addr, 1, 1);    // Unset RO
+               }
+       }
+
+       if( fail ) {
+               TRACE("ElfRelocate: Failure");
+               return NULL;
+       }       
+
+       #undef _doRelocate
+
+       TRACE("RETURN 0x%x to %p", hdr->e_entry + iBaseDiff, __builtin_return_address(0));
+       return (void*)(intptr_t)( hdr->e_entry + iBaseDiff );
+}
+
+void PREF(int_GetBaseDyntab)(void* Base, const PREF(Phdr)* phtab, unsigned phentcount, intptr_t* iBaseDiff_p, PREF(Dyn)** dynamicTab_p)
+{
+       uintptr_t       iRealBase = UINTPTR_MAX;
+       assert(dynamicTab_p);
+       
+       for(unsigned i = 0; i < phentcount; i ++)
+       {
+               switch(phtab[i].p_type)
+               {
+               case PT_LOAD:
+                       // Determine linked base address
+                       if( iRealBase > phtab[i].p_vaddr)
+                               iRealBase = phtab[i].p_vaddr;
+                       break;
+               case PT_DYNAMIC:
+                       // Find Dynamic Section
+                       if(!*dynamicTab_p) {
+                               *dynamicTab_p = (void *) (intptr_t) phtab[i].p_vaddr;
+                       }
+                       else {
+                               WARNING("elf_relocate: Multiple PT_DYNAMIC segments");
+                       }
+                       break;
+               }
+       }
+       
+       // Page Align real base
+       iRealBase &= ~0xFFF;
+       
+       // Adjust "Real" Base
+       const intptr_t  iBaseDiff = (intptr_t)Base - iRealBase;
+       *iBaseDiff_p = iBaseDiff;
+
+       // Adjust Dynamic Table
+       if( *dynamicTab_p )
+       {
+               *dynamicTab_p = (void *)( (intptr_t)*dynamicTab_p + iBaseDiff );
+       }
+
+       TRACE("True Base = 0x%x, Compiled Base = 0x%x, Difference = 0x%x", Base, iRealBase, *iBaseDiff_p);
+}
+
+int PREF(doRelocate_unk)(const PREF(RelocInfo)* Info, PREF(Xword) r_info, PREF(Xword)* ptr, PREF(Addr) addend, bool bRela)
+{
+       return 1;
+}
+
+int PREF(GetSymbolVars)(void *Base, const PREF(Sym)** symtab, const PREF(Word)** pBuckets, const char **dynstrtab, uintptr_t* piBaseDiff)
+{
+       const PREF(Ehdr)*       hdr = Base;
+       PREF(Dyn)*      dynTab = NULL;
+       intptr_t        iBaseDiff = -1;
+       
+       PREF(int_GetBaseDyntab)(Base, (void*)( (uintptr_t)Base + hdr->e_phoff ), hdr->e_phnum, &iBaseDiff, &dynTab);
+       if( !dynTab ) {
+               SysDebug("ERROR - Unable to find DYNAMIC segment in %p", Base);
+               return 1;
+       }
+       
+       for( int i = 0; dynTab[i].d_tag != DT_NULL; i++)
+       {
+               switch(dynTab[i].d_tag)
+               {
+               // --- Symbol Table ---
+               case DT_SYMTAB:
+                       *symtab = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);       // Rebased in Relocate
+                       break;
+               case DT_STRTAB:
+                       *dynstrtab = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);
+                       break;
+               // --- Hash Table --
+               case DT_HASH:
+                       *pBuckets = (void*)((intptr_t)dynTab[i].d_val + iBaseDiff);
+                       break;
+               }
+       }
+       
+       if( !*symtab ) {
+               SysDebug("ERRO - No DT_SYMTAB in %p", Base);
+               return 1;
+       }
+       if( !*pBuckets ) {
+               SysDebug("ERRO - No DT_HASH in %p", Base);
+               return 1;
+       }
+       if( !*dynstrtab ) {
+               SysDebug("ERRO - No DT_STRTAB in %p", Base);
+               return 1;
+       }
+
+       // ... ok... maybe they haven't been relocated
+       if( (uintptr_t)*symtab < (uintptr_t)Base )
+       {
+               SysDebug("Executable not yet relocated (symtab,pBuckets,dynstrtab = %p,%p,%p + 0x%x)",
+                       *symtab,*pBuckets,*dynstrtab, iBaseDiff);
+               *symtab    = (void*)( (uintptr_t)*symtab    + iBaseDiff );
+               *pBuckets  = (void*)( (uintptr_t)*pBuckets  + iBaseDiff );
+               *dynstrtab = (void*)( (uintptr_t)*dynstrtab + iBaseDiff );
+       }
+       *piBaseDiff = iBaseDiff;
+       return 0;
+}
+
+int PREF(GetSymbolInfo)(void *Base, const char *Name, void **Addr, size_t *Size, int* Section, int *Binding, int *Type)
+{
+       // Locate the tables
+       uintptr_t       iBaseDiff = -1;
+       const PREF(Sym)*        symtab = NULL;
+       const PREF(Word)*       pBuckets = NULL;
+       const char      *dynstrtab = NULL;
+       if( PREF(GetSymbolVars)(Base, &symtab, &pBuckets, &dynstrtab, &iBaseDiff) )
+               return 1;
+
+       unsigned nbuckets = pBuckets[0];
+//     int iSymCount = pBuckets[1];
+       pBuckets = &pBuckets[2];
+       
+       const PREF(Word)*       pChains = &pBuckets[ nbuckets ];
+       assert(pChains);
+
+       // Get hash
+       unsigned iNameHash = ElfHashString(Name);
+       iNameHash %= nbuckets;
+
+       // Walk Chain
+       unsigned idx = pBuckets[ iNameHash ];
+       do {
+               const PREF(Sym)*        sym = &symtab[idx];
+               assert(sym);
+               if( strcmp(dynstrtab + sym->st_name, Name) == 0 )
+               {
+                       TRACE("*sym = {value:0x%x,size:0x%x,info:0x%x,other:0x%x,shndx:%i}",
+                               sym->st_value, sym->st_size, sym->st_info,
+                               sym->st_other, sym->st_shndx);
+                       if(Addr)        *Addr = (void*)(intptr_t)( sym->st_value );
+                       if(Size)        *Size = sym->st_size;
+                       if(Binding)     *Binding = ELF32_ST_BIND(sym->st_info);
+                       if(Type)        *Type = ELF32_ST_TYPE(sym->st_info);
+                       if(Section)     *Section = sym->st_shndx;
+                       return 0;
+               }
+       } while( (idx = pChains[idx]) != STN_UNDEF && idx != pBuckets[iNameHash] );
+       
+       TRACE("No symbol");
+       return 1;
+}
+
+int PREF(GetSymbol)(void *Base, const char *Name, void **ret, size_t *Size)
+{
+        int    section, binding;
+       TRACE("%s(%p,%s,...)", __func__, Base, Name);
+       if( PREF(GetSymbolInfo)(Base, Name, ret, Size, &section, &binding, NULL) )
+               return 0;
+       if( section == SHN_UNDEF ) {
+               TRACE("%s: Undefined %p", __func__, *ret, (Size?*Size:0), section);
+               return 0;
+       }
+       if( binding == STB_WEAK ) {
+               TRACE("%s: Weak, return %p+0x%x,section=%i", __func__, *ret, (Size?*Size:0), section);
+               return 2;
+       }
+       TRACE("%s: Found %p+0x%x,section=%i", __func__, *ret, (Size?*Size:0), section);
+       return 1;
+}
index 1c750a8..31dcbd8 100644 (file)
@@ -65,7 +65,7 @@ void CallQueuedEntrypoints(char **EnvP)
        {
                giNumQueuedEntrypoints --;
                const struct sQueuedEntry       *qe = &gaQueuedEntrypoints[giNumQueuedEntrypoints];
-               //_SysDebug("Calling EP for %p", qe->Base);
+               DEBUGS("Calling EP %p for %p", qe->Entry, qe->Base);
                qe->Entry(qe->Base, 0, NULL, EnvP);
        }
 }

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