3 Linker no longer used - apart from mymalloc().
4 Instead, simply compile and link switchback.c with test_xxx.c, e.g.:
5 ./> (cd .. && make EXTRA_CFLAGS="-m64" libvex_ppc64_linux.a) && gcc -m64 -Wall -O -g -o switchback switchback.c linker.c ../libvex_ppc64_linux.a test_bzip2.c
12 #include <sys/types.h>
22 #include "../pub/libvex_basictypes.h"
25 #define IF_DEBUG(x,y) /* */
26 static int debug_linker = 0;
30 #if defined(__x86_64__)
31 # define x86_64_TARGET_ARCH
32 #elif defined(__i386__)
33 # define i386_TARGET_ARCH
34 #elif defined (__powerpc__)
35 # define ppc32_TARGET_ARCH
37 # error "Unknown arch"
42 #define CALLOC_MAX 10000000
43 static HChar calloc_area[CALLOC_MAX];
44 static UInt calloc_used = 0;
45 static void* calloc_below2G ( Int n, Int m )
49 while ((calloc_used % 16) > 0) calloc_used++;
50 assert(calloc_used + n*m < CALLOC_MAX);
51 p = &calloc_area[calloc_used];
52 for (i = 0; i < n*m; i++)
53 calloc_area[calloc_used+i] = 0;
59 #define MYMALLOC_MAX 50*1000*1000
60 static HChar mymalloc_area[MYMALLOC_MAX];
61 static UInt mymalloc_used = 0;
62 void* mymalloc ( Int n )
65 #if defined(__powerpc64__)
66 while ((ULong)(mymalloc_area+mymalloc_used) & 0xFFF)
68 while ((UInt)(mymalloc_area+mymalloc_used) & 0xFFF)
71 assert(mymalloc_used+n < MYMALLOC_MAX);
72 p = (void*)(&mymalloc_area[mymalloc_used]);
74 // printf("mymalloc(%d) = %p\n", n, p);
78 void myfree ( void* p )
89 ///////////////////////////////////////////////////////////////////
90 ///////////////////////////////////////////////////////////////////
91 ///////////////////////////////////////////////////////////////////
98 typedef enum { OBJECT_LOADED, OBJECT_RESOLVED } OStatus;
101 #define N_FIXUP_PAGES 1
104 /* Indication of section kinds for loaded objects. Needed by
105 the GC for deciding whether or not a pointer on the stack
109 enum { SECTIONKIND_CODE_OR_RODATA,
112 SECTIONKIND_NOINFOAVAIL }
120 struct _Section* next;
125 struct _ProddableBlock {
128 struct _ProddableBlock* next;
132 /* Top-level structure for an object module. One of these is allocated
133 * for each object file in use.
135 typedef struct _ObjectCode {
139 char* formatName; /* eg "ELF32", "DLL", "COFF", etc. */
141 /* An array containing ptrs to all the symbol names copied from
142 this object into the global symbol hash table. This is so that
143 we know which parts of the latter mapping to nuke when this
144 object is removed from the system. */
148 /* ptr to malloc'd lump of memory holding the obj file */
151 /* Fixup area for long-distance jumps. */
156 /* The section-kind entries for this object module. Linked
160 /* A private hash table for local symbols. */
161 /* HashTable* */ void* lochash;
163 /* Allow a chain of these things */
164 struct _ObjectCode * next;
166 /* SANITY CHECK ONLY: a list of the only memory regions which may
167 safely be prodded during relocation. Any attempt to prod
168 outside one of these is an error in the linker. */
169 ProddableBlock* proddables;
174 * Define a set of types which can be used for both ELF32 and ELF64
177 #if VEX_HOST_WORDSIZE == 8
178 #define ELFCLASS ELFCLASS64
179 #define Elf_Addr Elf64_Addr
180 #define Elf_Word Elf64_Word
181 #define Elf_Sword Elf64_Sword
182 #define Elf_Ehdr Elf64_Ehdr
183 #define Elf_Phdr Elf64_Phdr
184 #define Elf_Shdr Elf64_Shdr
185 #define Elf_Sym Elf64_Sym
186 #define Elf_Rel Elf64_Rel
187 #define Elf_Rela Elf64_Rela
188 #define ELF_ST_TYPE ELF64_ST_TYPE
189 #define ELF_ST_BIND ELF64_ST_BIND
190 #define ELF_R_TYPE ELF64_R_TYPE
191 #define ELF_R_SYM ELF64_R_SYM
193 #define ELFCLASS ELFCLASS32
194 #define Elf_Addr Elf32_Addr
195 #define Elf_Word Elf32_Word
196 #define Elf_Sword Elf32_Sword
197 #define Elf_Ehdr Elf32_Ehdr
198 #define Elf_Phdr Elf32_Phdr
199 #define Elf_Shdr Elf32_Shdr
200 #define Elf_Sym Elf32_Sym
201 #define Elf_Rel Elf32_Rel
202 #define Elf_Rela Elf32_Rela
204 #define ELF_ST_TYPE ELF32_ST_TYPE
207 #define ELF_ST_BIND ELF32_ST_BIND
210 #define ELF_R_TYPE ELF32_R_TYPE
213 #define ELF_R_SYM ELF32_R_SYM
220 ///////////////////////////////////////////////////////////////////
221 ///////////////////////////////////////////////////////////////////
222 ///////////////////////////////////////////////////////////////////
226 /* -----------------------------------------------------------------------
227 * Sanity checking. For each ObjectCode, maintain a list of address ranges
228 * which may be prodded during relocation, and abort if we try and write
229 * outside any of these.
231 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
234 = mymalloc(sizeof(ProddableBlock));
236 fprintf(stderr, "aPB oc=%p %p %d (%p .. %p)\n", oc, start, size,
237 start, ((char*)start)+size-1 );
241 pb->next = oc->proddables;
245 static void checkProddableBlock ( ObjectCode* oc, void* addr )
248 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
249 char* s = (char*)(pb->start);
250 char* e = s + pb->size - 1;
251 char* a = (char*)addr;
252 /* Assumes that the biggest fixup involves a 4-byte write. This
253 probably needs to be changed to 8 (ie, +7) on 64-bit
255 if (a >= s && (a+3) <= e) return;
258 "checkProddableBlock: invalid fixup %p in runtime linker\n",
265 ///////////////////////////////////////////////////////////////////
266 ///////////////////////////////////////////////////////////////////
267 ///////////////////////////////////////////////////////////////////
269 // String->Addr mappings
272 struct { char* mp_name; void* mp_addr; }
283 static StringMap* new_StringMap ( void )
285 StringMap* sm = mymalloc(sizeof(StringMap));
288 sm->maplets = mymalloc(10 * sizeof(Maplet));
292 static void delete_StringMap ( StringMap* sm )
294 assert(sm->maplets != NULL);
300 static void ensure_StringMap ( StringMap* sm )
304 assert(sm->maplets != NULL);
305 if (sm->sm_used < sm->sm_size)
308 mp2 = mymalloc(sm->sm_size * sizeof(Maplet));
309 for (i = 0; i < sm->sm_used; i++)
310 mp2[i] = sm->maplets[i];
315 static void* search_StringMap ( StringMap* sm, char* name )
318 for (i = 0; i < sm->sm_used; i++)
319 if (0 == strcmp(name, sm->maplets[i].mp_name))
320 return sm->maplets[i].mp_addr;
324 static void addto_StringMap ( StringMap* sm, char* name, void* addr )
326 ensure_StringMap(sm);
327 sm->maplets[sm->sm_used].mp_name = name;
328 sm->maplets[sm->sm_used].mp_addr = addr;
332 static void paranoid_addto_StringMap ( StringMap* sm, char* name, void* addr )
335 fprintf(stderr, "paranoid_addto_StringMap(%s,%p)\n", name, addr);
336 if (search_StringMap(sm,name) != NULL) {
337 fprintf(stderr, "duplicate: paranoid_addto_StringMap(%s,%p)\n", name, addr);
340 addto_StringMap(sm,name,addr);
344 ///////////////////////////////////////////////////////////////////
345 ///////////////////////////////////////////////////////////////////
346 ///////////////////////////////////////////////////////////////////
348 // Top-level linker control.
350 StringMap* global_symbol_table = NULL;
351 ObjectCode* global_object_list = NULL;
353 static void initLinker ( void )
355 if (global_symbol_table != NULL)
357 global_symbol_table = new_StringMap();
362 ///////////////////////////////////////////////////////////////////
363 ///////////////////////////////////////////////////////////////////
364 ///////////////////////////////////////////////////////////////////
368 /* -----------------------------------------------------------------
369 * lookup a symbol in the global symbol table
372 void * lookupSymbol( char *lbl )
376 assert(global_symbol_table != NULL);
377 val = search_StringMap(global_symbol_table, lbl);
382 ///////////////////////////////////////////////////////////////////
383 ///////////////////////////////////////////////////////////////////
384 ///////////////////////////////////////////////////////////////////
389 * Generic ELF functions
393 findElfSection ( void* objImage, Elf_Word sh_type )
395 char* ehdrC = (char*)objImage;
396 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
397 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
398 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
402 for (i = 0; i < ehdr->e_shnum; i++) {
403 if (shdr[i].sh_type == sh_type
404 /* Ignore the section header's string table. */
405 && i != ehdr->e_shstrndx
406 /* Ignore string tables named .stabstr, as they contain
408 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
410 ptr = ehdrC + shdr[i].sh_offset;
417 #ifdef arm_TARGET_ARCH
419 char* alloc_fixup_bytes ( ObjectCode* oc, int nbytes )
422 assert(nbytes % 4 == 0);
424 res = &(oc->fixup[oc->fixup_used]);
425 oc->fixup_used += nbytes;
426 if (oc->fixup_used >= oc->fixup_size) {
427 fprintf(stderr, "fixup area too small for %s\n", oc->fileName);
435 ///////////////////////////////////////////////////////////////////
436 ///////////////////////////////////////////////////////////////////
437 ///////////////////////////////////////////////////////////////////
442 void* lookup_magic_hacks ( char* sym )
444 if (0==strcmp(sym, "printf")) return (void*)(&printf);
448 #ifdef arm_TARGET_ARCH
450 void arm_notify_new_code ( char* start, int length )
452 __asm __volatile ("mov r1, %0\n\t"
457 : "ir" (start), "ir" (length), "ir" (0) );
462 void gen_armle_goto ( char* fixup, char* dstP )
464 Elf_Word w = (Elf_Word)dstP;
467 3 0000 04F01FE5 ldr pc, value
468 4 0004 44332211 value: .word 0x11223344
470 fprintf(stderr,"at %p generating jump to %p\n", fixup, dstP );
471 fixup[0] = 0x04; fixup[1] = 0xF0; fixup[2] = 0x1F; fixup[3] = 0xE5;
472 fixup[4] = w & 0xFF; w >>= 8;
473 fixup[5] = w & 0xFF; w >>= 8;
474 fixup[6] = w & 0xFF; w >>= 8;
475 fixup[7] = w & 0xFF; w >>= 8;
476 arm_notify_new_code(fixup, 8);
478 #endif /* arm_TARGET_ARCH */
481 #ifdef ppc32_TARGET_ARCH
482 static void invalidate_icache(void *ptr, int nbytes)
484 unsigned long startaddr = (unsigned long) ptr;
485 unsigned long endaddr = startaddr + nbytes;
487 unsigned long cls = 16; //VG_(cache_line_size);
489 startaddr &= ~(cls - 1);
490 for (addr = startaddr; addr < endaddr; addr += cls)
491 asm volatile("dcbst 0,%0" : : "r" (addr));
492 asm volatile("sync");
493 for (addr = startaddr; addr < endaddr; addr += cls)
494 asm volatile("icbi 0,%0" : : "r" (addr));
495 asm volatile("sync; isync");
498 static UInt compute_ppc_HA ( UInt x ) {
499 return 0xFFFF & ( (x >> 16) + ((x & 0x8000) ? 1 : 0) );
501 static UInt compute_ppc_LO ( UInt x ) {
504 static UInt compute_ppc_HI ( UInt x ) {
505 return 0xFFFF & (x >> 16);
507 #endif /* ppc32_TARGET_ARCH */
510 /* Do ELF relocations which lack an explicit addend. All x86-linux
511 relocations appear to be of this form. */
513 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
514 Elf_Shdr* shdr, int shnum,
515 Elf_Sym* stab, char* strtab )
520 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
521 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
522 int target_shndx = shdr[shnum].sh_info;
523 int symtab_shndx = shdr[shnum].sh_link;
525 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
526 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
527 IF_DEBUG(linker,belch( "relocations for section %d using symtab %d",
528 target_shndx, symtab_shndx ));
530 for (j = 0; j < nent; j++) {
531 Elf_Addr offset = rtab[j].r_offset;
532 Elf_Addr info = rtab[j].r_info;
534 Elf_Addr P = ((Elf_Addr)targ) + offset;
535 Elf_Word* pP = (Elf_Word*)P;
540 IF_DEBUG(linker,belch( "Rel entry %3d is raw(%6p %6p)",
541 j, (void*)offset, (void*)info ));
543 IF_DEBUG(linker,belch( " ZERO" ));
546 Elf_Sym sym = stab[ELF_R_SYM(info)];
547 /* First see if it is a local symbol. */
548 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
549 /* Yes, so we can get the address directly from the ELF symbol
551 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
553 (ehdrC + shdr[ sym.st_shndx ].sh_offset
554 + stab[ELF_R_SYM(info)].st_value);
557 /* No, so look up the name in our global table. */
558 symbol = strtab + sym.st_name;
559 S = (Elf_Addr)lookupSymbol( symbol );
562 S = (Elf_Addr)lookup_magic_hacks(symbol);
565 fprintf(stderr,"%s: unknown symbol `%s'\n",
566 oc->fileName, symbol);
570 fprintf(stderr, "\n`%s' resolves to %p\n", symbol, (void*)S );
574 fprintf(stderr, "Reloc: P = %p S = %p A = %p\n",
575 (void*)P, (void*)S, (void*)A );
576 checkProddableBlock ( oc, pP );
580 switch (ELF_R_TYPE(info)) {
581 # ifdef i386_TARGET_ARCH
582 case R_386_32: *pP = value; break;
583 case R_386_PC32: *pP = value - P; break;
585 # ifdef arm_TARGET_ARCH
587 Elf_Word w, delta, deltaTop8;
588 /* Generate a jump sequence into the fixup area
589 and branch to that instead. */
590 char* fixup = alloc_fixup_bytes(oc, 8);
591 /* First of all, figure out where we're really trying to
593 // compensate for pc+8 bias
594 Elf_Word real_dst = (A & 0x00FFFFFF) + 2;
595 // sign-extend 24-to-32 of real_dst
596 if (real_dst & 0x00800000)
597 real_dst |= 0xFF000000;
599 real_dst &= 0x00FFFFFF;
604 gen_armle_goto(fixup, (char*)real_dst);
606 /* Delta is in bytes .. */
607 delta = (((Elf_Word)fixup) - ((Elf_Word)pP) - 8);
608 deltaTop8 = (delta >> 24) & 0xFF;
609 if (deltaTop8 != 0 && deltaTop8 != 0xFF) {
610 fprintf(stderr,"R_ARM_PC24: out of range delta 0x%x for %s\n",
617 w |= (0x00FFFFFF & delta );
627 "%s: unhandled ELF relocation(Rel) type %d\n\n",
628 oc->fileName, (Int)ELF_R_TYPE(info));
636 /* Do ELF relocations for which explicit addends are supplied.
637 sparc-solaris relocations appear to be of this form. */
639 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
640 Elf_Shdr* shdr, int shnum,
641 Elf_Sym* stab, char* strtab )
646 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
647 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
648 int target_shndx = shdr[shnum].sh_info;
649 int symtab_shndx = shdr[shnum].sh_link;
651 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
652 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
653 IF_DEBUG(linker,belch( "relocations for section %d using symtab %d",
654 target_shndx, symtab_shndx ));
656 for (j = 0; j < nent; j++) {
657 #if defined(DEBUG) || defined(sparc_TARGET_ARCH) \
658 || defined(ia64_TARGET_ARCH) \
659 || defined(x86_64_TARGET_ARCH) \
660 || defined(ppc32_TARGET_ARCH)
661 /* This #ifdef only serves to avoid unused-var warnings. */
662 Elf_Addr offset = rtab[j].r_offset;
663 Elf_Addr P = targ + offset;
665 Elf_Addr info = rtab[j].r_info;
666 Elf_Addr A = rtab[j].r_addend;
669 # if defined(sparc_TARGET_ARCH)
670 Elf_Word* pP = (Elf_Word*)P;
673 # if defined(ia64_TARGET_ARCH)
674 Elf64_Xword *pP = (Elf64_Xword *)P;
677 # if defined(x86_64_TARGET_ARCH)
678 ULong* pP = (ULong*)P;
680 # if defined(ppc32_TARGET_ARCH)
682 Elf_Word* pP = (Elf_Word*)P;
685 IF_DEBUG(linker,belch( "Rel entry %3d is raw(%6p %6p %6p) ",
686 j, (void*)offset, (void*)info,
689 IF_DEBUG(linker,belch( " ZERO" ));
692 Elf_Sym sym = stab[ELF_R_SYM(info)];
693 /* First see if it is a local symbol. */
694 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
695 /* Yes, so we can get the address directly from the ELF symbol
697 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
699 (ehdrC + shdr[ sym.st_shndx ].sh_offset
700 + stab[ELF_R_SYM(info)].st_value);
701 #ifdef ELF_FUNCTION_DESC
702 /* Make a function descriptor for this function */
703 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
704 S = allocateFunctionDesc(S + A);
709 /* No, so look up the name in our global table. */
710 symbol = strtab + sym.st_name;
711 S = (Elf_Addr)lookupSymbol( symbol );
713 #ifdef ELF_FUNCTION_DESC
714 /* If a function, already a function descriptor - we would
715 have to copy it to add an offset. */
716 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
717 belch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
721 fprintf(stderr,"%s: unknown symbol `%s'\n", oc->fileName, symbol);
725 fprintf(stderr, "`%s' resolves to %p\n", symbol, (void*)S );
729 fprintf ( stderr, "Reloc: offset = %p P = %p S = %p A = %p\n",
730 (void*)offset, (void*)P, (void*)S, (void*)A );
733 /* checkProddableBlock ( oc, (void*)P ); */
737 switch (ELF_R_TYPE(info)) {
738 # if defined(sparc_TARGET_ARCH)
739 case R_SPARC_WDISP30:
740 w1 = *pP & 0xC0000000;
741 w2 = (Elf_Word)((value - P) >> 2);
742 ASSERT((w2 & 0xC0000000) == 0);
747 w1 = *pP & 0xFFC00000;
748 w2 = (Elf_Word)(value >> 10);
749 ASSERT((w2 & 0xFFC00000) == 0);
755 w2 = (Elf_Word)(value & 0x3FF);
756 ASSERT((w2 & ~0x3FF) == 0);
760 /* According to the Sun documentation:
762 This relocation type resembles R_SPARC_32, except it refers to an
763 unaligned word. That is, the word to be relocated must be treated
764 as four separate bytes with arbitrary alignment, not as a word
765 aligned according to the architecture requirements.
767 (JRS: which means that freeloading on the R_SPARC_32 case
768 is probably wrong, but hey ...)
772 w2 = (Elf_Word)value;
776 # if defined(ia64_TARGET_ARCH)
777 case R_IA64_DIR64LSB:
778 case R_IA64_FPTR64LSB:
781 case R_IA64_PCREL64LSB:
784 case R_IA64_SEGREL64LSB:
785 addr = findElfSegment(ehdrC, value);
789 ia64_reloc_gprel22(P, value);
792 case R_IA64_LTOFF22X:
793 case R_IA64_LTOFF_FPTR22:
794 addr = allocateGOTEntry(value);
795 ia64_reloc_gprel22(P, addr);
797 case R_IA64_PCREL21B:
798 ia64_reloc_pcrel21(P, S, oc);
801 /* This goes with R_IA64_LTOFF22X and points to the load to
802 convert into a move. We don't implement relaxation. */
805 # if defined(x86_64_TARGET_ARCH)
806 case R_X86_64_64: /* 1 *//* Direct 64 bit */
807 *((ULong*)pP) = (ULong)(S + A);
809 case R_X86_64_PC32: /* 2 *//* PC relative 32 bit signed */
810 *((UInt*)pP) = (UInt)(S + A - P);
812 case R_X86_64_32: /* 10 *//* Direct 32 bit zero extended */
813 *((UInt*)pP) = (UInt)(S + A);
815 case R_X86_64_32S: /* 11 *//* Direct 32 bit sign extended */
816 *((UInt*)pP) = (UInt)(S + A);
819 # if defined(ppc32_TARGET_ARCH)
820 case R_PPC_ADDR32: /* 1 *//* 32bit absolute address */
822 invalidate_icache(pP,4);
824 case R_PPC_ADDR16_LO: /* 4 *//* lower 16bit of absolute address */
825 *((UInt*)pP) &= 0x0000FFFF;
826 *((UInt*)pP) |= 0xFFFF0000 & (compute_ppc_LO(S+A) << 16);
827 invalidate_icache(pP,4);
829 case R_PPC_ADDR16_HA: /* 6 *//* adjusted high 16bit */
830 *((UInt*)pP) &= 0x0000FFFF;
831 *((UInt*)pP) |= 0xFFFF0000 & (compute_ppc_HA(S+A) << 16);
832 invalidate_icache(pP,4);
834 case R_PPC_REL24: /* 10 *//* PC relative 26 bit */
837 /* the top 9 bits of sI must be the same (all 0s or
838 all 1s) for this to be valid; else we have to fail. */
839 sI2 = sI >> 23; /* 23 == 32 - 9 */
840 if (sI2 != 0 && sI2 != 0xFFFFFFFF) {
841 fprintf(stderr, "%s: R_PPC_REL24 relocation failed\n", oc->fileName );
844 *((UInt*)pP) &= ~(0x00FFFFFF << 2);
845 *((UInt*)pP) |= (0xFFFFFF & sI) << 2;
846 invalidate_icache(pP,4);
848 case R_PPC_REL32: /* 26 */
849 *((UInt*)pP) = S+A-P;
850 invalidate_icache(pP,4);
855 "%s: unhandled ELF relocation(RelA) type %d\n",
856 oc->fileName, (Int)ELF_R_TYPE(info));
866 ocResolve_ELF ( ObjectCode* oc )
870 Elf_Sym* stab = NULL;
871 char* ehdrC = (char*)(oc->image);
872 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
873 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
874 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
876 /* first find "the" symbol table */
877 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
879 /* also go find the string table */
880 strtab = findElfSection ( ehdrC, SHT_STRTAB );
882 if (stab == NULL || strtab == NULL) {
883 fprintf(stderr,"%s: can't find string or symbol table\n", oc->fileName);
887 /* Process the relocation sections. */
888 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
890 /* Skip sections called ".rel.stab". These appear to contain
891 relocation entries that, when done, make the stabs debugging
892 info point at the right places. We ain't interested in all
894 if (0 == memcmp(".rel.stab", sh_strtab + shdr[shnum].sh_name, 9))
897 if (shdr[shnum].sh_type == SHT_REL ) {
898 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
899 shnum, stab, strtab );
903 if (shdr[shnum].sh_type == SHT_RELA) {
904 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
905 shnum, stab, strtab );
910 /* Free the local symbol table; we won't need it again. */
911 delete_StringMap(oc->lochash);
918 ///////////////////////////////////////////////////////////////////
919 ///////////////////////////////////////////////////////////////////
920 ///////////////////////////////////////////////////////////////////
925 ocVerifyImage_ELF ( ObjectCode* oc )
929 int i, j, nent, nstrtab, nsymtabs;
933 char* ehdrC = (char*)(oc->image);
934 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
936 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
937 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
938 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
939 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
940 fprintf(stderr,"%s: not an ELF object\n", oc->fileName);
944 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
945 fprintf(stderr,"%s: unsupported ELF format\n", oc->fileName);
949 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
951 fprintf(stderr, "Is little-endian\n" );
953 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
955 fprintf(stderr, "Is big-endian\n" );
957 fprintf(stderr,"%s: unknown endiannness\n", oc->fileName);
961 if (ehdr->e_type != ET_REL) {
962 fprintf(stderr,"%s: not a relocatable object (.o) file\n", oc->fileName);
966 fprintf(stderr, "Is a relocatable object (.o) file\n" );
969 fprintf(stderr, "Architecture is " );
970 switch (ehdr->e_machine) {
971 case EM_386: if (debug_linker) fprintf(stderr, "x86\n" ); break;
972 case EM_SPARC: if (debug_linker) fprintf(stderr, "sparc\n" ); break;
973 case EM_ARM: if (debug_linker) fprintf(stderr, "arm\n" ); break;
975 case EM_IA_64: if (debug_linker) fprintf(stderr, "ia64\n" ); break;
977 case EM_X86_64: if (debug_linker) fprintf(stderr, "x86_64\n" ); break;
978 case EM_PPC: if (debug_linker) fprintf(stderr, "ppc\n" ); break;
979 default: if (debug_linker) fprintf(stderr, "unknown\n" );
980 fprintf(stderr,"%s: unknown architecture\n", oc->fileName);
984 if (debug_linker>1) fprintf(stderr,
985 "\nSection header table: start %lld, n_entries %d, ent_size %d\n",
987 ehdr->e_shnum, ehdr->e_shentsize );
989 assert (ehdr->e_shentsize == sizeof(Elf_Shdr));
991 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
993 if (ehdr->e_shstrndx == SHN_UNDEF) {
994 fprintf(stderr,"%s: no section header string table\n", oc->fileName);
998 fprintf(stderr, "Section header string table is section %d\n",
1000 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
1003 for (i = 0; i < ehdr->e_shnum; i++) {
1004 if (debug_linker>1) fprintf(stderr, "%2d: ", i );
1005 if (debug_linker>1) fprintf(stderr, "type=%2d ", (int)shdr[i].sh_type );
1006 if (debug_linker>1) fprintf(stderr, "size=%4d ", (int)shdr[i].sh_size );
1007 if (debug_linker>1) fprintf(stderr, "offs=%4d ", (int)shdr[i].sh_offset );
1008 if (debug_linker>1) fprintf(stderr, " (%p .. %p) ",
1009 ehdrC + shdr[i].sh_offset,
1010 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
1012 if (shdr[i].sh_type == SHT_REL) {
1013 if (debug_linker>1) fprintf(stderr, "Rel " );
1014 } else if (shdr[i].sh_type == SHT_RELA) {
1015 if (debug_linker>1) fprintf(stderr, "RelA " );
1017 if (debug_linker>1) fprintf(stderr," ");
1020 if (debug_linker>1) fprintf(stderr, "sname=%s\n",
1021 sh_strtab + shdr[i].sh_name );
1025 if (debug_linker>1) fprintf(stderr, "\nString tables\n" );
1028 for (i = 0; i < ehdr->e_shnum; i++) {
1029 if (shdr[i].sh_type == SHT_STRTAB
1030 /* Ignore the section header's string table. */
1031 && i != ehdr->e_shstrndx
1032 /* Ignore string tables named .stabstr, as they contain
1034 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
1037 fprintf(stderr," section %d is a normal string table\n", i );
1038 strtab = ehdrC + shdr[i].sh_offset;
1043 fprintf(stderr,"%s: no string tables, or too many\n", oc->fileName);
1048 if (debug_linker>1) fprintf(stderr, "\nSymbol tables\n" );
1049 for (i = 0; i < ehdr->e_shnum; i++) {
1050 if (shdr[i].sh_type != SHT_SYMTAB) continue;
1051 if (debug_linker>1) fprintf(stderr, "section %d is a symbol table\n", i );
1053 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
1054 nent = shdr[i].sh_size / sizeof(Elf_Sym);
1055 if (debug_linker>1) fprintf(stderr,
1056 " number of entries is apparently %d (%lld rem)\n",
1058 (Long)(shdr[i].sh_size % sizeof(Elf_Sym))
1060 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
1061 fprintf(stderr,"%s: non-integral number of symbol table entries\n",
1065 for (j = 0; j < nent; j++) {
1066 if (debug_linker>1) fprintf(stderr, " %2d ", j );
1067 if (debug_linker>1) fprintf(stderr, " sec=%-5d size=%-3d val=%5p ",
1068 (int)stab[j].st_shndx,
1069 (int)stab[j].st_size,
1070 (char*)stab[j].st_value );
1072 if (debug_linker>1) fprintf(stderr, "type=" );
1073 switch (ELF_ST_TYPE(stab[j].st_info)) {
1074 case STT_NOTYPE: if (debug_linker>1) fprintf(stderr, "notype " ); break;
1075 case STT_OBJECT: if (debug_linker>1) fprintf(stderr, "object " ); break;
1076 case STT_FUNC : if (debug_linker>1) fprintf(stderr, "func " ); break;
1077 case STT_SECTION: if (debug_linker>1) fprintf(stderr, "section" ); break;
1078 case STT_FILE: if (debug_linker>1) fprintf(stderr, "file " ); break;
1079 default: if (debug_linker>1) fprintf(stderr, "? " ); break;
1081 if (debug_linker>1) fprintf(stderr, " " );
1083 if (debug_linker>1) fprintf(stderr, "bind=" );
1084 switch (ELF_ST_BIND(stab[j].st_info)) {
1085 case STB_LOCAL : if (debug_linker>1) fprintf(stderr, "local " ); break;
1086 case STB_GLOBAL: if (debug_linker>1) fprintf(stderr, "global" ); break;
1087 case STB_WEAK : if (debug_linker>1) fprintf(stderr, "weak " ); break;
1088 default: if (debug_linker>1) fprintf(stderr, "? " ); break;
1090 if (debug_linker>1) fprintf(stderr, " " );
1092 if (debug_linker>1) fprintf(stderr, "name=%s\n", strtab + stab[j].st_name );
1096 if (nsymtabs == 0) {
1097 fprintf(stderr,"%s: didn't find any symbol tables\n", oc->fileName);
1105 ///////////////////////////////////////////////////////////////////
1106 ///////////////////////////////////////////////////////////////////
1107 ///////////////////////////////////////////////////////////////////
1112 ocGetNames_ELF ( ObjectCode* oc )
1117 char* ehdrC = (char*)(oc->image);
1118 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
1119 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
1120 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
1122 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
1125 assert(global_symbol_table != NULL);
1128 fprintf(stderr,"%s: no strtab\n", oc->fileName);
1133 for (i = 0; i < ehdr->e_shnum; i++) {
1134 /* Figure out what kind of section it is. Logic derived from
1135 Figure 1.14 ("Special Sections") of the ELF document
1136 ("Portable Formats Specification, Version 1.1"). */
1137 Elf_Shdr hdr = shdr[i];
1138 SectionKind kind = SECTIONKIND_OTHER;
1141 if (hdr.sh_type == SHT_PROGBITS
1142 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_EXECINSTR)) {
1143 /* .text-style section */
1144 kind = SECTIONKIND_CODE_OR_RODATA;
1147 if (hdr.sh_type == SHT_PROGBITS
1148 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_WRITE)) {
1149 /* .data-style section */
1150 kind = SECTIONKIND_RWDATA;
1153 if (hdr.sh_type == SHT_PROGBITS
1154 && (hdr.sh_flags & SHF_ALLOC) && !(hdr.sh_flags & SHF_WRITE)) {
1155 /* .rodata-style section */
1156 kind = SECTIONKIND_CODE_OR_RODATA;
1159 if (hdr.sh_type == SHT_NOBITS
1160 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_WRITE)) {
1161 /* .bss-style section */
1162 kind = SECTIONKIND_RWDATA;
1166 if (is_bss && shdr[i].sh_size > 0) {
1167 /* This is a non-empty .bss section. Allocate zeroed space for
1168 it, and set its .sh_offset field such that
1169 ehdrC + .sh_offset == addr_of_zeroed_space. */
1170 char* zspace = calloc(1, shdr[i].sh_size);
1171 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
1173 fprintf(stderr, "BSS section at %p, size %lld\n",
1174 zspace, (Long)shdr[i].sh_size);
1177 /* When loading objects compiled with -g, it seems there are
1178 relocations in various debug-info sections. So we'd better
1179 tell addProddableBlock to allow those bits to be prodded. */
1180 //fprintf(stderr, "ZZZZZZZZZZ %s\n", sh_strtab + hdr.sh_name);
1181 sec_name = sh_strtab + shdr[i].sh_name;
1182 if (kind == SECTIONKIND_OTHER
1183 && (0 == strcmp(".debug_info", sec_name)
1184 || 0 == strcmp(".debug_line", sec_name)
1185 || 0 == strcmp(".debug_pubnames", sec_name)
1186 || 0 == strcmp(".debug_aranges", sec_name)
1187 || 0 == strcmp(".debug_frame", sec_name))) {
1188 kind = SECTIONKIND_CODE_OR_RODATA;
1191 /* fill in the section info */
1192 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
1193 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
1194 //addSection(oc, kind, ehdrC + shdr[i].sh_offset,
1195 // ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
1198 if (shdr[i].sh_type != SHT_SYMTAB) continue;
1200 /* copy stuff into this module's object symbol table */
1201 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
1202 nent = shdr[i].sh_size / sizeof(Elf_Sym);
1204 oc->n_symbols = nent;
1205 oc->symbols = mymalloc(oc->n_symbols * sizeof(char*));
1207 for (j = 0; j < nent; j++) {
1209 char isLocal = FALSE; /* avoids uninit-var warning */
1211 char* nm = strtab + stab[j].st_name;
1212 int secno = stab[j].st_shndx;
1214 /* Figure out if we want to add it; if so, set ad to its
1215 address. Otherwise leave ad == NULL. */
1217 if (secno == SHN_COMMON) {
1219 # if defined(__x86_64__)
1220 ad = calloc_below2G(1, stab[j].st_size);
1222 ad = calloc(1, stab[j].st_size);
1224 // assert( Ptr_to_ULong(ad) < 0xF0000000ULL );
1227 fprintf(stderr, "COMMON symbol, size %lld name %s allocd %p\n",
1228 (Long)stab[j].st_size, nm, ad);
1229 /* Pointless to do addProddableBlock() for this area,
1230 since the linker should never poke around in it. */
1233 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
1234 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
1236 /* and not an undefined symbol */
1237 && stab[j].st_shndx != SHN_UNDEF
1238 /* and not in a "special section" */
1239 && stab[j].st_shndx < SHN_LORESERVE
1241 /* and it's a not a section or string table or anything silly */
1242 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
1243 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
1244 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
1247 /* Section 0 is the undefined section, hence > and not >=. */
1248 assert(secno > 0 && secno < ehdr->e_shnum);
1250 if (shdr[secno].sh_type == SHT_NOBITS) {
1251 fprintf(stderr, " BSS symbol, size %d off %d name %s\n",
1252 stab[j].st_size, stab[j].st_value, nm);
1255 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
1256 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
1259 #ifdef ELF_FUNCTION_DESC
1260 /* dlsym() and the initialisation table both give us function
1261 * descriptors, so to be consistent we store function descriptors
1262 * in the symbol table */
1263 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
1264 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
1266 if (0|| debug_linker)
1267 fprintf(stderr, "addOTabName(GLOB): %10p %s %s\n",
1268 ad, oc->fileName, nm );
1273 /* And the decision is ... */
1277 oc->symbols[j] = nm;
1280 /* Ignore entirely. */
1282 //ghciInsertStrHashTable(oc->fileName, global_symbol_table, nm, ad);
1283 paranoid_addto_StringMap(global_symbol_table, nm, ad);
1287 if (debug_linker>1) fprintf(stderr, "skipping `%s'\n",
1288 strtab + stab[j].st_name );
1291 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
1292 (int)ELF_ST_BIND(stab[j].st_info),
1293 (int)ELF_ST_TYPE(stab[j].st_info),
1294 (int)stab[j].st_shndx,
1295 strtab + stab[j].st_name
1298 oc->symbols[j] = NULL;
1308 ///////////////////////////////////////////////////////////////////
1309 ///////////////////////////////////////////////////////////////////
1310 ///////////////////////////////////////////////////////////////////
1312 // TOP-LEVEL CONTROL OF THE LINKER
1315 /* ---------------------------------------------------------------------
1316 * Load an obj (populate the global symbol table, but don't resolve yet)
1318 * Returns: 1 if ok, 0 on error.
1321 int loadObj( char *path )
1331 fprintf(stderr, "==== loadObj %s ====\n", path );
1333 /* Check that we haven't already loaded this object. */
1337 for (o = global_object_list; o; o = o->next) {
1338 if (0 == strcmp(o->fileName, path))
1344 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1345 "same object file twice:\n"
1352 oc = mymalloc(sizeof(ObjectCode));
1354 oc->formatName = "ELF";
1356 r = stat(path, &st);
1357 if (r == -1) { return 0; }
1359 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1360 oc->fileName = mymalloc( strlen(path)+1 );
1361 strcpy(oc->fileName, path);
1363 oc->fileSize = st.st_size;
1365 oc->sections = NULL;
1366 oc->lochash = new_StringMap();
1367 oc->proddables = NULL;
1372 /* chain it onto the list of objects */
1373 oc->next = global_object_list;
1374 global_object_list = oc;
1376 fd = open(path, O_RDONLY);
1378 fprintf(stderr,"loadObj: can't open `%s'\n", path);
1382 /* Allocate a 1-page area just prior to the image, so we can put
1383 fixup code fragments there. Used for doing R_ARM_PC24
1384 relocations for jump distances > 64M. */
1386 pagesize = getpagesize();
1387 // p = memalign(pagesize, N_FIXUP_PAGES * pagesize
1389 p = mymalloc(N_FIXUP_PAGES * pagesize + oc->fileSize);
1390 if (0) fprintf(stderr,"XXXX p = %p\n", p);
1392 fprintf(stderr,"loadObj: failed to allocate space for `%s'\n", path);
1397 oc->fixup_size = N_FIXUP_PAGES * pagesize;
1399 oc->image = &(p[ oc->fixup_size ]);
1401 r = read(fd, oc->image, oc->fileSize);
1402 if (r != oc->fileSize) {
1403 fprintf(stderr,"loadObj: failed to read `%s'\n", path);
1407 fprintf(stderr, "loaded %s at %p (fixup = %p)\n",
1408 oc->fileName, oc->image, oc->fixup );
1412 /* verify the in-memory image */
1413 r = ocVerifyImage_ELF ( oc );
1414 if (!r) { return r; }
1416 /* build the symbol list for this image */
1417 r = ocGetNames_ELF ( oc );
1418 if (!r) { return r; }
1420 /* loaded, but not resolved yet */
1421 oc->status = OBJECT_LOADED;
1423 #ifdef ppc32_TARGET_ARCH
1424 invalidate_icache(oc->image, oc->fileSize);
1432 /* ---------------------------------------------------------------------------
1433 * resolve all the currently unlinked objects in memory
1435 * Returns: 1 if ok, 0 on error.
1438 int resolveObjs( void )
1445 for (oc = global_object_list; oc; oc = oc->next) {
1446 if (oc->status != OBJECT_RESOLVED) {
1447 r = ocResolve_ELF ( oc );
1448 if (!r) { return r; }
1449 oc->status = OBJECT_RESOLVED;
1456 /* ---------------------------------------------------------------------------
1460 /* Load and link a bunch of .o's, and return the address of
1461 'entry'. Or NULL if something borks.
1463 void* linker_top_level_LINK ( int n_object_names, char** object_names )
1469 for (i = 0; i < n_object_names; i++) {
1470 //fprintf(stderr, "linkloop %d %s\n", i, object_names[i] );
1471 r = loadObj( object_names[i] );
1472 if (r != 1) return NULL;
1475 if (r != 1) return NULL;
1476 mainp = search_StringMap ( global_symbol_table, "entry" );
1477 if (mainp == NULL) return NULL;
1478 printf("switchback: Linker: success!\n");