1 /* -----------------------------------------------------------------------------
2 * $Id: Linker.c,v 1.106 2002/10/23 08:52:26 simonmar Exp $
4 * (c) The GHC Team, 2000, 2001
8 * ---------------------------------------------------------------------------*/
11 #include "PosixSource.h"
18 #include "LinkerInternals.h"
20 #include "StoragePriv.h"
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
30 #ifdef HAVE_SYS_STAT_H
34 #if defined(HAVE_FRAMEWORK_HASKELLSUPPORT)
35 #include <HaskellSupport/dlfcn.h>
36 #elif defined(HAVE_DLFCN_H)
40 #if defined(cygwin32_TARGET_OS)
45 #ifdef HAVE_SYS_TIME_H
49 #include <sys/fcntl.h>
50 #include <sys/termios.h>
51 #include <sys/utime.h>
52 #include <sys/utsname.h>
56 #if defined(ia64_TARGET_ARCH)
62 #if defined(linux_TARGET_OS) || defined(solaris2_TARGET_OS) || defined(freebsd_TARGET_OS)
63 # define OBJFORMAT_ELF
64 #elif defined(cygwin32_TARGET_OS) || defined (mingw32_TARGET_OS)
65 # define OBJFORMAT_PEi386
68 #elif defined(darwin_TARGET_OS)
69 # include <mach-o/ppc/reloc.h>
70 # define OBJFORMAT_MACHO
71 # include <mach-o/loader.h>
72 # include <mach-o/nlist.h>
73 # include <mach-o/reloc.h>
76 /* Hash table mapping symbol names to Symbol */
77 static /*Str*/HashTable *symhash;
79 #if defined(OBJFORMAT_ELF)
80 static int ocVerifyImage_ELF ( ObjectCode* oc );
81 static int ocGetNames_ELF ( ObjectCode* oc );
82 static int ocResolve_ELF ( ObjectCode* oc );
83 #elif defined(OBJFORMAT_PEi386)
84 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
85 static int ocGetNames_PEi386 ( ObjectCode* oc );
86 static int ocResolve_PEi386 ( ObjectCode* oc );
87 #elif defined(OBJFORMAT_MACHO)
88 static int ocVerifyImage_MachO ( ObjectCode* oc );
89 static int ocGetNames_MachO ( ObjectCode* oc );
90 static int ocResolve_MachO ( ObjectCode* oc );
93 /* -----------------------------------------------------------------------------
94 * Built-in symbols from the RTS
97 typedef struct _RtsSymbolVal {
104 #define Maybe_ForeignObj SymX(mkForeignObjzh_fast)
106 #define Maybe_Stable_Names SymX(mkWeakzh_fast) \
107 SymX(makeStableNamezh_fast) \
108 SymX(finalizzeWeakzh_fast)
110 /* These are not available in GUM!!! -- HWL */
111 #define Maybe_ForeignObj
112 #define Maybe_Stable_Names
115 #if !defined (mingw32_TARGET_OS)
116 #define RTS_POSIX_ONLY_SYMBOLS \
117 SymX(stg_sig_install) \
121 #if defined (cygwin32_TARGET_OS)
122 #define RTS_MINGW_ONLY_SYMBOLS /**/
123 /* Don't have the ability to read import libs / archives, so
124 * we have to stupidly list a lot of what libcygwin.a
127 #define RTS_CYGWIN_ONLY_SYMBOLS \
209 #elif !defined(mingw32_TARGET_OS)
210 #define RTS_MINGW_ONLY_SYMBOLS /**/
211 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
212 #else /* defined(mingw32_TARGET_OS) */
213 #define RTS_POSIX_ONLY_SYMBOLS /**/
214 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
216 /* These are statically linked from the mingw libraries into the ghc
217 executable, so we have to employ this hack. */
218 #define RTS_MINGW_ONLY_SYMBOLS \
230 SymX(getservbyname) \
231 SymX(getservbyport) \
232 SymX(getprotobynumber) \
233 SymX(getprotobyname) \
234 SymX(gethostbyname) \
235 SymX(gethostbyaddr) \
270 Sym(_imp___timezone) \
286 # define MAIN_CAP_SYM SymX(MainCapability)
288 # define MAIN_CAP_SYM
291 #define RTS_SYMBOLS \
305 Sym(stg_enterStackTop) \
308 SymX(__stg_gc_enter_1) \
309 SymX(stg_gc_enter_2) \
310 SymX(stg_gc_enter_3) \
311 SymX(stg_gc_enter_4) \
312 SymX(stg_gc_enter_5) \
313 SymX(stg_gc_enter_6) \
314 SymX(stg_gc_enter_7) \
315 SymX(stg_gc_enter_8) \
317 SymX(stg_gc_noregs) \
319 SymX(stg_gc_unbx_r1) \
320 SymX(stg_gc_unpt_r1) \
321 SymX(stg_gc_ut_0_1) \
322 SymX(stg_gc_ut_1_0) \
324 SymX(stg_yield_to_interpreter) \
327 SymX(MallocFailHook) \
328 SymX(NoRunnableThreadsHook) \
330 SymX(OutOfHeapHook) \
331 SymX(PatErrorHdrHook) \
332 SymX(PostTraceHook) \
334 SymX(StackOverflowHook) \
335 SymX(__encodeDouble) \
336 SymX(__encodeFloat) \
339 SymX(__gmpz_cmp_si) \
340 SymX(__gmpz_cmp_ui) \
341 SymX(__gmpz_get_si) \
342 SymX(__gmpz_get_ui) \
343 SymX(__int_encodeDouble) \
344 SymX(__int_encodeFloat) \
345 SymX(andIntegerzh_fast) \
346 SymX(blockAsyncExceptionszh_fast) \
349 SymX(complementIntegerzh_fast) \
350 SymX(cmpIntegerzh_fast) \
351 SymX(cmpIntegerIntzh_fast) \
352 SymX(createAdjustor) \
353 SymX(decodeDoublezh_fast) \
354 SymX(decodeFloatzh_fast) \
357 SymX(deRefWeakzh_fast) \
358 SymX(deRefStablePtrzh_fast) \
359 SymX(divExactIntegerzh_fast) \
360 SymX(divModIntegerzh_fast) \
362 SymX(forkProcesszh_fast) \
363 SymX(freeHaskellFunctionPtr) \
364 SymX(freeStablePtr) \
365 SymX(gcdIntegerzh_fast) \
366 SymX(gcdIntegerIntzh_fast) \
367 SymX(gcdIntzh_fast) \
370 SymX(int2Integerzh_fast) \
371 SymX(integer2Intzh_fast) \
372 SymX(integer2Wordzh_fast) \
373 SymX(isDoubleDenormalized) \
374 SymX(isDoubleInfinite) \
376 SymX(isDoubleNegativeZero) \
377 SymX(isEmptyMVarzh_fast) \
378 SymX(isFloatDenormalized) \
379 SymX(isFloatInfinite) \
381 SymX(isFloatNegativeZero) \
382 SymX(killThreadzh_fast) \
383 SymX(makeStablePtrzh_fast) \
384 SymX(minusIntegerzh_fast) \
385 SymX(mkApUpd0zh_fast) \
386 SymX(myThreadIdzh_fast) \
387 SymX(labelThreadzh_fast) \
388 SymX(newArrayzh_fast) \
389 SymX(newBCOzh_fast) \
390 SymX(newByteArrayzh_fast) \
392 SymX(newMVarzh_fast) \
393 SymX(newMutVarzh_fast) \
394 SymX(atomicModifyMutVarzh_fast) \
395 SymX(newPinnedByteArrayzh_fast) \
396 SymX(orIntegerzh_fast) \
398 SymX(plusIntegerzh_fast) \
401 SymX(putMVarzh_fast) \
402 SymX(quotIntegerzh_fast) \
403 SymX(quotRemIntegerzh_fast) \
405 SymX(remIntegerzh_fast) \
406 SymX(resetNonBlockingFd) \
409 SymX(rts_checkSchedStatus) \
412 SymX(rts_evalLazyIO) \
416 SymX(rts_getDouble) \
421 SymX(rts_getStablePtr) \
422 SymX(rts_getThreadId) \
424 SymX(rts_getWord32) \
435 SymX(rts_mkStablePtr) \
444 SymX(shutdownHaskellAndExit) \
445 SymX(stable_ptr_table) \
446 SymX(stackOverflow) \
447 SymX(stg_CAF_BLACKHOLE_info) \
448 SymX(stg_CHARLIKE_closure) \
449 SymX(stg_EMPTY_MVAR_info) \
450 SymX(stg_IND_STATIC_info) \
451 SymX(stg_INTLIKE_closure) \
452 SymX(stg_MUT_ARR_PTRS_FROZEN_info) \
453 SymX(stg_WEAK_info) \
454 SymX(stg_ap_1_upd_info) \
455 SymX(stg_ap_2_upd_info) \
456 SymX(stg_ap_3_upd_info) \
457 SymX(stg_ap_4_upd_info) \
458 SymX(stg_ap_5_upd_info) \
459 SymX(stg_ap_6_upd_info) \
460 SymX(stg_ap_7_upd_info) \
461 SymX(stg_ap_8_upd_info) \
463 SymX(stg_sel_0_upd_info) \
464 SymX(stg_sel_10_upd_info) \
465 SymX(stg_sel_11_upd_info) \
466 SymX(stg_sel_12_upd_info) \
467 SymX(stg_sel_13_upd_info) \
468 SymX(stg_sel_14_upd_info) \
469 SymX(stg_sel_15_upd_info) \
470 SymX(stg_sel_1_upd_info) \
471 SymX(stg_sel_2_upd_info) \
472 SymX(stg_sel_3_upd_info) \
473 SymX(stg_sel_4_upd_info) \
474 SymX(stg_sel_5_upd_info) \
475 SymX(stg_sel_6_upd_info) \
476 SymX(stg_sel_7_upd_info) \
477 SymX(stg_sel_8_upd_info) \
478 SymX(stg_sel_9_upd_info) \
479 SymX(stg_seq_frame_info) \
480 SymX(stg_upd_frame_info) \
481 SymX(__stg_update_PAP) \
482 SymX(suspendThread) \
483 SymX(takeMVarzh_fast) \
484 SymX(timesIntegerzh_fast) \
485 SymX(tryPutMVarzh_fast) \
486 SymX(tryTakeMVarzh_fast) \
487 SymX(unblockAsyncExceptionszh_fast) \
488 SymX(unsafeThawArrayzh_fast) \
489 SymX(waitReadzh_fast) \
490 SymX(waitWritezh_fast) \
491 SymX(word2Integerzh_fast) \
492 SymX(xorIntegerzh_fast) \
495 #ifdef SUPPORT_LONG_LONGS
496 #define RTS_LONG_LONG_SYMS \
497 SymX(int64ToIntegerzh_fast) \
498 SymX(word64ToIntegerzh_fast)
500 #define RTS_LONG_LONG_SYMS /* nothing */
503 #ifdef ia64_TARGET_ARCH
504 /* force these symbols to be present */
505 #define RTS_EXTRA_SYMBOLS \
507 #elif defined(powerpc_TARGET_ARCH)
508 #define RTS_EXTRA_SYMBOLS \
518 #define RTS_EXTRA_SYMBOLS /* nothing */
521 /* entirely bogus claims about types of these symbols */
522 #define Sym(vvv) extern void (vvv);
523 #define SymX(vvv) /**/
527 RTS_POSIX_ONLY_SYMBOLS
528 RTS_MINGW_ONLY_SYMBOLS
529 RTS_CYGWIN_ONLY_SYMBOLS
533 #ifdef LEADING_UNDERSCORE
534 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
536 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
539 #define Sym(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
541 #define SymX(vvv) Sym(vvv)
543 static RtsSymbolVal rtsSyms[] = {
547 RTS_POSIX_ONLY_SYMBOLS
548 RTS_MINGW_ONLY_SYMBOLS
549 RTS_CYGWIN_ONLY_SYMBOLS
550 { 0, 0 } /* sentinel */
553 /* -----------------------------------------------------------------------------
554 * Insert symbols into hash tables, checking for duplicates.
556 static void ghciInsertStrHashTable ( char* obj_name,
562 if (lookupHashTable(table, (StgWord)key) == NULL)
564 insertStrHashTable(table, (StgWord)key, data);
569 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
571 "whilst processing object file\n"
573 "This could be caused by:\n"
574 " * Loading two different object files which export the same symbol\n"
575 " * Specifying the same object file twice on the GHCi command line\n"
576 " * An incorrect `package.conf' entry, causing some object to be\n"
578 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
587 /* -----------------------------------------------------------------------------
588 * initialize the object linker
592 static int linker_init_done = 0 ;
594 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
595 static void *dl_prog_handle;
603 /* Make initLinker idempotent, so we can call it
604 before evey relevant operation; that means we
605 don't need to initialise the linker separately */
606 if (linker_init_done == 1) { return; } else {
607 linker_init_done = 1;
610 symhash = allocStrHashTable();
612 /* populate the symbol table with stuff from the RTS */
613 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
614 ghciInsertStrHashTable("(GHCi built-in symbols)",
615 symhash, sym->lbl, sym->addr);
617 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
618 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
622 /* -----------------------------------------------------------------------------
623 * Loading DLL or .so dynamic libraries
624 * -----------------------------------------------------------------------------
626 * Add a DLL from which symbols may be found. In the ELF case, just
627 * do RTLD_GLOBAL-style add, so no further messing around needs to
628 * happen in order that symbols in the loaded .so are findable --
629 * lookupSymbol() will subsequently see them by dlsym on the program's
630 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
632 * In the PEi386 case, open the DLLs and put handles to them in a
633 * linked list. When looking for a symbol, try all handles in the
634 * list. This means that we need to load even DLLs that are guaranteed
635 * to be in the ghc.exe image already, just so we can get a handle
636 * to give to loadSymbol, so that we can find the symbols. For such
637 * libraries, the LoadLibrary call should be a no-op except for returning
642 #if defined(OBJFORMAT_PEi386)
643 /* A record for storing handles into DLLs. */
648 struct _OpenedDLL* next;
653 /* A list thereof. */
654 static OpenedDLL* opened_dlls = NULL;
658 addDLL( char *dll_name )
660 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
661 /* ------------------- ELF DLL loader ------------------- */
667 hdl= dlopen(dll_name, RTLD_NOW | RTLD_GLOBAL);
669 /* dlopen failed; return a ptr to the error msg. */
671 if (errmsg == NULL) errmsg = "addDLL: unknown error";
678 # elif defined(OBJFORMAT_PEi386)
679 /* ------------------- Win32 DLL loader ------------------- */
687 /* fprintf(stderr, "\naddDLL; dll_name = `%s'\n", dll_name); */
689 /* See if we've already got it, and ignore if so. */
690 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
691 if (0 == strcmp(o_dll->name, dll_name))
695 /* The file name has no suffix (yet) so that we can try
696 both foo.dll and foo.drv
698 The documentation for LoadLibrary says:
699 If no file name extension is specified in the lpFileName
700 parameter, the default library extension .dll is
701 appended. However, the file name string can include a trailing
702 point character (.) to indicate that the module name has no
705 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
706 sprintf(buf, "%s.DLL", dll_name);
707 instance = LoadLibrary(buf);
708 if (instance == NULL) {
709 sprintf(buf, "%s.DRV", dll_name); // KAA: allow loading of drivers (like winspool.drv)
710 instance = LoadLibrary(buf);
711 if (instance == NULL) {
714 /* LoadLibrary failed; return a ptr to the error msg. */
715 return "addDLL: unknown error";
720 /* Add this DLL to the list of DLLs in which to search for symbols. */
721 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
722 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
723 strcpy(o_dll->name, dll_name);
724 o_dll->instance = instance;
725 o_dll->next = opened_dlls;
730 barf("addDLL: not implemented on this platform");
734 /* -----------------------------------------------------------------------------
735 * lookup a symbol in the hash table
738 lookupSymbol( char *lbl )
742 ASSERT(symhash != NULL);
743 val = lookupStrHashTable(symhash, lbl);
746 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
747 return dlsym(dl_prog_handle, lbl);
748 # elif defined(OBJFORMAT_PEi386)
751 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
752 /* fprintf(stderr, "look in %s for %s\n", o_dll->name, lbl); */
754 /* HACK: if the name has an initial underscore, try stripping
755 it off & look that up first. I've yet to verify whether there's
756 a Rule that governs whether an initial '_' *should always* be
757 stripped off when mapping from import lib name to the DLL name.
759 sym = GetProcAddress(o_dll->instance, (lbl+1));
761 /*fprintf(stderr, "found %s in %s\n", lbl+1,o_dll->name); fflush(stderr);*/
765 sym = GetProcAddress(o_dll->instance, lbl);
767 /*fprintf(stderr, "found %s in %s\n", lbl,o_dll->name); fflush(stderr);*/
782 __attribute((unused))
784 lookupLocalSymbol( ObjectCode* oc, char *lbl )
788 val = lookupStrHashTable(oc->lochash, lbl);
798 /* -----------------------------------------------------------------------------
799 * Debugging aid: look in GHCi's object symbol tables for symbols
800 * within DELTA bytes of the specified address, and show their names.
803 void ghci_enquire ( char* addr );
805 void ghci_enquire ( char* addr )
810 const int DELTA = 64;
815 for (oc = objects; oc; oc = oc->next) {
816 for (i = 0; i < oc->n_symbols; i++) {
817 sym = oc->symbols[i];
818 if (sym == NULL) continue;
819 /* fprintf(stderr, "enquire %p %p\n", sym, oc->lochash); */
821 if (oc->lochash != NULL)
822 a = lookupStrHashTable(oc->lochash, sym);
824 a = lookupStrHashTable(symhash, sym);
826 /* fprintf(stderr, "ghci_enquire: can't find %s\n", sym); */
828 else if (addr-DELTA <= a && a <= addr+DELTA) {
829 fprintf(stderr, "%p + %3d == `%s'\n", addr, a - addr, sym);
836 #ifdef ia64_TARGET_ARCH
837 static unsigned int PLTSize(void);
840 /* -----------------------------------------------------------------------------
841 * Load an obj (populate the global symbol table, but don't resolve yet)
843 * Returns: 1 if ok, 0 on error.
846 loadObj( char *path )
860 /* fprintf(stderr, "loadObj %s\n", path ); */
862 /* Check that we haven't already loaded this object. Don't give up
863 at this stage; ocGetNames_* will barf later. */
867 for (o = objects; o; o = o->next) {
868 if (0 == strcmp(o->fileName, path))
874 "GHCi runtime linker: warning: looks like you're trying to load the\n"
875 "same object file twice:\n"
877 "GHCi will continue, but a duplicate-symbol error may shortly follow.\n"
883 oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
885 # if defined(OBJFORMAT_ELF)
886 oc->formatName = "ELF";
887 # elif defined(OBJFORMAT_PEi386)
888 oc->formatName = "PEi386";
889 # elif defined(OBJFORMAT_MACHO)
890 oc->formatName = "Mach-O";
893 barf("loadObj: not implemented on this platform");
897 if (r == -1) { return 0; }
899 /* sigh, strdup() isn't a POSIX function, so do it the long way */
900 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
901 strcpy(oc->fileName, path);
903 oc->fileSize = st.st_size;
906 oc->lochash = allocStrHashTable();
907 oc->proddables = NULL;
909 /* chain it onto the list of objects */
914 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
916 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
918 fd = open(path, O_RDONLY);
920 barf("loadObj: can't open `%s'", path);
922 pagesize = getpagesize();
924 #ifdef ia64_TARGET_ARCH
925 /* The PLT needs to be right before the object */
926 n = ROUND_UP(PLTSize(), pagesize);
927 oc->plt = mmap(NULL, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
928 if (oc->plt == MAP_FAILED)
929 barf("loadObj: can't allocate PLT");
932 map_addr = oc->plt + n;
935 n = ROUND_UP(oc->fileSize, pagesize);
936 oc->image = mmap(map_addr, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
937 if (oc->image == MAP_FAILED)
938 barf("loadObj: can't map `%s'", path);
942 #else /* !USE_MMAP */
944 oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
946 /* load the image into memory */
947 f = fopen(path, "rb");
949 barf("loadObj: can't read `%s'", path);
951 n = fread ( oc->image, 1, oc->fileSize, f );
952 if (n != oc->fileSize)
953 barf("loadObj: error whilst reading `%s'", path);
957 #endif /* USE_MMAP */
959 /* verify the in-memory image */
960 # if defined(OBJFORMAT_ELF)
961 r = ocVerifyImage_ELF ( oc );
962 # elif defined(OBJFORMAT_PEi386)
963 r = ocVerifyImage_PEi386 ( oc );
964 # elif defined(OBJFORMAT_MACHO)
965 r = ocVerifyImage_MachO ( oc );
967 barf("loadObj: no verify method");
969 if (!r) { return r; }
971 /* build the symbol list for this image */
972 # if defined(OBJFORMAT_ELF)
973 r = ocGetNames_ELF ( oc );
974 # elif defined(OBJFORMAT_PEi386)
975 r = ocGetNames_PEi386 ( oc );
976 # elif defined(OBJFORMAT_MACHO)
977 r = ocGetNames_MachO ( oc );
979 barf("loadObj: no getNames method");
981 if (!r) { return r; }
983 /* loaded, but not resolved yet */
984 oc->status = OBJECT_LOADED;
989 /* -----------------------------------------------------------------------------
990 * resolve all the currently unlinked objects in memory
992 * Returns: 1 if ok, 0 on error.
1002 for (oc = objects; oc; oc = oc->next) {
1003 if (oc->status != OBJECT_RESOLVED) {
1004 # if defined(OBJFORMAT_ELF)
1005 r = ocResolve_ELF ( oc );
1006 # elif defined(OBJFORMAT_PEi386)
1007 r = ocResolve_PEi386 ( oc );
1008 # elif defined(OBJFORMAT_MACHO)
1009 r = ocResolve_MachO ( oc );
1011 barf("resolveObjs: not implemented on this platform");
1013 if (!r) { return r; }
1014 oc->status = OBJECT_RESOLVED;
1020 /* -----------------------------------------------------------------------------
1021 * delete an object from the pool
1024 unloadObj( char *path )
1026 ObjectCode *oc, *prev;
1028 ASSERT(symhash != NULL);
1029 ASSERT(objects != NULL);
1034 for (oc = objects; oc; prev = oc, oc = oc->next) {
1035 if (!strcmp(oc->fileName,path)) {
1037 /* Remove all the mappings for the symbols within this
1042 for (i = 0; i < oc->n_symbols; i++) {
1043 if (oc->symbols[i] != NULL) {
1044 removeStrHashTable(symhash, oc->symbols[i], NULL);
1052 prev->next = oc->next;
1055 /* We're going to leave this in place, in case there are
1056 any pointers from the heap into it: */
1057 /* free(oc->image); */
1061 /* The local hash table should have been freed at the end
1062 of the ocResolve_ call on it. */
1063 ASSERT(oc->lochash == NULL);
1069 belch("unloadObj: can't find `%s' to unload", path);
1073 /* -----------------------------------------------------------------------------
1074 * Sanity checking. For each ObjectCode, maintain a list of address ranges
1075 * which may be prodded during relocation, and abort if we try and write
1076 * outside any of these.
1078 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1081 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1082 /* fprintf(stderr, "aPB %p %p %d\n", oc, start, size); */
1086 pb->next = oc->proddables;
1087 oc->proddables = pb;
1090 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1093 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1094 char* s = (char*)(pb->start);
1095 char* e = s + pb->size - 1;
1096 char* a = (char*)addr;
1097 /* Assumes that the biggest fixup involves a 4-byte write. This
1098 probably needs to be changed to 8 (ie, +7) on 64-bit
1100 if (a >= s && (a+3) <= e) return;
1102 barf("checkProddableBlock: invalid fixup in runtime linker");
1105 /* -----------------------------------------------------------------------------
1106 * Section management.
1108 static void addSection ( ObjectCode* oc, SectionKind kind,
1109 void* start, void* end )
1111 Section* s = stgMallocBytes(sizeof(Section), "addSection");
1115 s->next = oc->sections;
1118 fprintf(stderr, "addSection: %p-%p (size %d), kind %d\n",
1119 start, ((char*)end)-1, end - start + 1, kind );
1125 /* --------------------------------------------------------------------------
1126 * PEi386 specifics (Win32 targets)
1127 * ------------------------------------------------------------------------*/
1129 /* The information for this linker comes from
1130 Microsoft Portable Executable
1131 and Common Object File Format Specification
1132 revision 5.1 January 1998
1133 which SimonM says comes from the MS Developer Network CDs.
1135 It can be found there (on older CDs), but can also be found
1138 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
1140 (this is Rev 6.0 from February 1999).
1142 Things move, so if that fails, try searching for it via
1144 http://www.google.com/search?q=PE+COFF+specification
1146 The ultimate reference for the PE format is the Winnt.h
1147 header file that comes with the Platform SDKs; as always,
1148 implementations will drift wrt their documentation.
1150 A good background article on the PE format is Matt Pietrek's
1151 March 1994 article in Microsoft System Journal (MSJ)
1152 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
1153 Win32 Portable Executable File Format." The info in there
1154 has recently been updated in a two part article in
1155 MSDN magazine, issues Feb and March 2002,
1156 "Inside Windows: An In-Depth Look into the Win32 Portable
1157 Executable File Format"
1159 John Levine's book "Linkers and Loaders" contains useful
1164 #if defined(OBJFORMAT_PEi386)
1168 typedef unsigned char UChar;
1169 typedef unsigned short UInt16;
1170 typedef unsigned int UInt32;
1177 UInt16 NumberOfSections;
1178 UInt32 TimeDateStamp;
1179 UInt32 PointerToSymbolTable;
1180 UInt32 NumberOfSymbols;
1181 UInt16 SizeOfOptionalHeader;
1182 UInt16 Characteristics;
1186 #define sizeof_COFF_header 20
1193 UInt32 VirtualAddress;
1194 UInt32 SizeOfRawData;
1195 UInt32 PointerToRawData;
1196 UInt32 PointerToRelocations;
1197 UInt32 PointerToLinenumbers;
1198 UInt16 NumberOfRelocations;
1199 UInt16 NumberOfLineNumbers;
1200 UInt32 Characteristics;
1204 #define sizeof_COFF_section 40
1211 UInt16 SectionNumber;
1214 UChar NumberOfAuxSymbols;
1218 #define sizeof_COFF_symbol 18
1223 UInt32 VirtualAddress;
1224 UInt32 SymbolTableIndex;
1229 #define sizeof_COFF_reloc 10
1232 /* From PE spec doc, section 3.3.2 */
1233 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
1234 windows.h -- for the same purpose, but I want to know what I'm
1236 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
1237 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
1238 #define MYIMAGE_FILE_DLL 0x2000
1239 #define MYIMAGE_FILE_SYSTEM 0x1000
1240 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
1241 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
1242 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
1244 /* From PE spec doc, section 5.4.2 and 5.4.4 */
1245 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
1246 #define MYIMAGE_SYM_CLASS_STATIC 3
1247 #define MYIMAGE_SYM_UNDEFINED 0
1249 /* From PE spec doc, section 4.1 */
1250 #define MYIMAGE_SCN_CNT_CODE 0x00000020
1251 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
1252 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
1254 /* From PE spec doc, section 5.2.1 */
1255 #define MYIMAGE_REL_I386_DIR32 0x0006
1256 #define MYIMAGE_REL_I386_REL32 0x0014
1259 /* We use myindex to calculate array addresses, rather than
1260 simply doing the normal subscript thing. That's because
1261 some of the above structs have sizes which are not
1262 a whole number of words. GCC rounds their sizes up to a
1263 whole number of words, which means that the address calcs
1264 arising from using normal C indexing or pointer arithmetic
1265 are just plain wrong. Sigh.
1268 myindex ( int scale, void* base, int index )
1271 ((UChar*)base) + scale * index;
1276 printName ( UChar* name, UChar* strtab )
1278 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1279 UInt32 strtab_offset = * (UInt32*)(name+4);
1280 fprintf ( stderr, "%s", strtab + strtab_offset );
1283 for (i = 0; i < 8; i++) {
1284 if (name[i] == 0) break;
1285 fprintf ( stderr, "%c", name[i] );
1292 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
1294 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1295 UInt32 strtab_offset = * (UInt32*)(name+4);
1296 strncpy ( dst, strtab+strtab_offset, dstSize );
1302 if (name[i] == 0) break;
1312 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
1315 /* If the string is longer than 8 bytes, look in the
1316 string table for it -- this will be correctly zero terminated.
1318 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1319 UInt32 strtab_offset = * (UInt32*)(name+4);
1320 return ((UChar*)strtab) + strtab_offset;
1322 /* Otherwise, if shorter than 8 bytes, return the original,
1323 which by defn is correctly terminated.
1325 if (name[7]==0) return name;
1326 /* The annoying case: 8 bytes. Copy into a temporary
1327 (which is never freed ...)
1329 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
1331 strncpy(newstr,name,8);
1337 /* Just compares the short names (first 8 chars) */
1338 static COFF_section *
1339 findPEi386SectionCalled ( ObjectCode* oc, char* name )
1343 = (COFF_header*)(oc->image);
1344 COFF_section* sectab
1346 ((UChar*)(oc->image))
1347 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1349 for (i = 0; i < hdr->NumberOfSections; i++) {
1352 COFF_section* section_i
1354 myindex ( sizeof_COFF_section, sectab, i );
1355 n1 = (UChar*) &(section_i->Name);
1357 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
1358 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
1359 n1[6]==n2[6] && n1[7]==n2[7])
1368 zapTrailingAtSign ( UChar* sym )
1370 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
1372 if (sym[0] == 0) return;
1374 while (sym[i] != 0) i++;
1377 while (j > 0 && my_isdigit(sym[j])) j--;
1378 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
1384 ocVerifyImage_PEi386 ( ObjectCode* oc )
1389 COFF_section* sectab;
1390 COFF_symbol* symtab;
1392 /* fprintf(stderr, "\nLOADING %s\n", oc->fileName); */
1393 hdr = (COFF_header*)(oc->image);
1394 sectab = (COFF_section*) (
1395 ((UChar*)(oc->image))
1396 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1398 symtab = (COFF_symbol*) (
1399 ((UChar*)(oc->image))
1400 + hdr->PointerToSymbolTable
1402 strtab = ((UChar*)symtab)
1403 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1405 if (hdr->Machine != 0x14c) {
1406 belch("Not x86 PEi386");
1409 if (hdr->SizeOfOptionalHeader != 0) {
1410 belch("PEi386 with nonempty optional header");
1413 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
1414 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
1415 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
1416 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
1417 belch("Not a PEi386 object file");
1420 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
1421 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
1422 belch("Invalid PEi386 word size or endiannness: %d",
1423 (int)(hdr->Characteristics));
1426 /* If the string table size is way crazy, this might indicate that
1427 there are more than 64k relocations, despite claims to the
1428 contrary. Hence this test. */
1429 /* fprintf(stderr, "strtab size %d\n", * (UInt32*)strtab); */
1431 if ( (*(UInt32*)strtab) > 600000 ) {
1432 /* Note that 600k has no special significance other than being
1433 big enough to handle the almost-2MB-sized lumps that
1434 constitute HSwin32*.o. */
1435 belch("PEi386 object has suspiciously large string table; > 64k relocs?");
1440 /* No further verification after this point; only debug printing. */
1442 IF_DEBUG(linker, i=1);
1443 if (i == 0) return 1;
1446 "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
1448 "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
1450 "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
1452 fprintf ( stderr, "\n" );
1454 "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
1456 "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
1458 "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
1460 "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
1462 "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
1464 "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
1466 "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
1468 /* Print the section table. */
1469 fprintf ( stderr, "\n" );
1470 for (i = 0; i < hdr->NumberOfSections; i++) {
1472 COFF_section* sectab_i
1474 myindex ( sizeof_COFF_section, sectab, i );
1481 printName ( sectab_i->Name, strtab );
1491 sectab_i->VirtualSize,
1492 sectab_i->VirtualAddress,
1493 sectab_i->SizeOfRawData,
1494 sectab_i->PointerToRawData,
1495 sectab_i->NumberOfRelocations,
1496 sectab_i->PointerToRelocations,
1497 sectab_i->PointerToRawData
1499 reltab = (COFF_reloc*) (
1500 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
1503 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
1504 /* If the relocation field (a short) has overflowed, the
1505 * real count can be found in the first reloc entry.
1507 * See Section 4.1 (last para) of the PE spec (rev6.0).
1509 COFF_reloc* rel = (COFF_reloc*)
1510 myindex ( sizeof_COFF_reloc, reltab, 0 );
1511 noRelocs = rel->VirtualAddress;
1514 noRelocs = sectab_i->NumberOfRelocations;
1518 for (; j < noRelocs; j++) {
1520 COFF_reloc* rel = (COFF_reloc*)
1521 myindex ( sizeof_COFF_reloc, reltab, j );
1523 " type 0x%-4x vaddr 0x%-8x name `",
1525 rel->VirtualAddress );
1526 sym = (COFF_symbol*)
1527 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
1528 /* Hmm..mysterious looking offset - what's it for? SOF */
1529 printName ( sym->Name, strtab -10 );
1530 fprintf ( stderr, "'\n" );
1533 fprintf ( stderr, "\n" );
1535 fprintf ( stderr, "\n" );
1536 fprintf ( stderr, "string table has size 0x%x\n", * (UInt32*)strtab );
1537 fprintf ( stderr, "---START of string table---\n");
1538 for (i = 4; i < *(Int32*)strtab; i++) {
1540 fprintf ( stderr, "\n"); else
1541 fprintf( stderr, "%c", strtab[i] );
1543 fprintf ( stderr, "--- END of string table---\n");
1545 fprintf ( stderr, "\n" );
1548 COFF_symbol* symtab_i;
1549 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1550 symtab_i = (COFF_symbol*)
1551 myindex ( sizeof_COFF_symbol, symtab, i );
1557 printName ( symtab_i->Name, strtab );
1566 (Int32)(symtab_i->SectionNumber),
1567 (UInt32)symtab_i->Type,
1568 (UInt32)symtab_i->StorageClass,
1569 (UInt32)symtab_i->NumberOfAuxSymbols
1571 i += symtab_i->NumberOfAuxSymbols;
1575 fprintf ( stderr, "\n" );
1581 ocGetNames_PEi386 ( ObjectCode* oc )
1584 COFF_section* sectab;
1585 COFF_symbol* symtab;
1592 hdr = (COFF_header*)(oc->image);
1593 sectab = (COFF_section*) (
1594 ((UChar*)(oc->image))
1595 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1597 symtab = (COFF_symbol*) (
1598 ((UChar*)(oc->image))
1599 + hdr->PointerToSymbolTable
1601 strtab = ((UChar*)(oc->image))
1602 + hdr->PointerToSymbolTable
1603 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1605 /* Allocate space for any (local, anonymous) .bss sections. */
1607 for (i = 0; i < hdr->NumberOfSections; i++) {
1609 COFF_section* sectab_i
1611 myindex ( sizeof_COFF_section, sectab, i );
1612 if (0 != strcmp(sectab_i->Name, ".bss")) continue;
1613 if (sectab_i->VirtualSize == 0) continue;
1614 /* This is a non-empty .bss section. Allocate zeroed space for
1615 it, and set its PointerToRawData field such that oc->image +
1616 PointerToRawData == addr_of_zeroed_space. */
1617 zspace = stgCallocBytes(1, sectab_i->VirtualSize,
1618 "ocGetNames_PEi386(anonymous bss)");
1619 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
1620 addProddableBlock(oc, zspace, sectab_i->VirtualSize);
1621 /* fprintf(stderr, "BSS anon section at 0x%x\n", zspace); */
1624 /* Copy section information into the ObjectCode. */
1626 for (i = 0; i < hdr->NumberOfSections; i++) {
1632 = SECTIONKIND_OTHER;
1633 COFF_section* sectab_i
1635 myindex ( sizeof_COFF_section, sectab, i );
1636 IF_DEBUG(linker, belch("section name = %s\n", sectab_i->Name ));
1639 /* I'm sure this is the Right Way to do it. However, the
1640 alternative of testing the sectab_i->Name field seems to
1641 work ok with Cygwin.
1643 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
1644 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
1645 kind = SECTIONKIND_CODE_OR_RODATA;
1648 if (0==strcmp(".text",sectab_i->Name) ||
1649 0==strcmp(".rodata",sectab_i->Name))
1650 kind = SECTIONKIND_CODE_OR_RODATA;
1651 if (0==strcmp(".data",sectab_i->Name) ||
1652 0==strcmp(".bss",sectab_i->Name))
1653 kind = SECTIONKIND_RWDATA;
1655 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
1656 sz = sectab_i->SizeOfRawData;
1657 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
1659 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
1660 end = start + sz - 1;
1662 if (kind == SECTIONKIND_OTHER
1663 /* Ignore sections called which contain stabs debugging
1665 && 0 != strcmp(".stab", sectab_i->Name)
1666 && 0 != strcmp(".stabstr", sectab_i->Name)
1668 belch("Unknown PEi386 section name `%s'", sectab_i->Name);
1672 if (kind != SECTIONKIND_OTHER && end >= start) {
1673 addSection(oc, kind, start, end);
1674 addProddableBlock(oc, start, end - start + 1);
1678 /* Copy exported symbols into the ObjectCode. */
1680 oc->n_symbols = hdr->NumberOfSymbols;
1681 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
1682 "ocGetNames_PEi386(oc->symbols)");
1683 /* Call me paranoid; I don't care. */
1684 for (i = 0; i < oc->n_symbols; i++)
1685 oc->symbols[i] = NULL;
1689 COFF_symbol* symtab_i;
1690 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1691 symtab_i = (COFF_symbol*)
1692 myindex ( sizeof_COFF_symbol, symtab, i );
1696 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
1697 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
1698 /* This symbol is global and defined, viz, exported */
1699 /* for MYIMAGE_SYMCLASS_EXTERNAL
1700 && !MYIMAGE_SYM_UNDEFINED,
1701 the address of the symbol is:
1702 address of relevant section + offset in section
1704 COFF_section* sectabent
1705 = (COFF_section*) myindex ( sizeof_COFF_section,
1707 symtab_i->SectionNumber-1 );
1708 addr = ((UChar*)(oc->image))
1709 + (sectabent->PointerToRawData
1713 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
1714 && symtab_i->Value > 0) {
1715 /* This symbol isn't in any section at all, ie, global bss.
1716 Allocate zeroed space for it. */
1717 addr = stgCallocBytes(1, symtab_i->Value,
1718 "ocGetNames_PEi386(non-anonymous bss)");
1719 addSection(oc, SECTIONKIND_RWDATA, addr,
1720 ((UChar*)addr) + symtab_i->Value - 1);
1721 addProddableBlock(oc, addr, symtab_i->Value);
1722 /* fprintf(stderr, "BSS section at 0x%x\n", addr); */
1725 if (addr != NULL ) {
1726 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
1727 /* fprintf(stderr,"addSymbol %p `%s \n", addr,sname); */
1728 IF_DEBUG(linker, belch("addSymbol %p `%s'\n", addr,sname);)
1729 ASSERT(i >= 0 && i < oc->n_symbols);
1730 /* cstring_from_COFF_symbol_name always succeeds. */
1731 oc->symbols[i] = sname;
1732 ghciInsertStrHashTable(oc->fileName, symhash, sname, addr);
1736 "IGNORING symbol %d\n"
1740 printName ( symtab_i->Name, strtab );
1749 (Int32)(symtab_i->SectionNumber),
1750 (UInt32)symtab_i->Type,
1751 (UInt32)symtab_i->StorageClass,
1752 (UInt32)symtab_i->NumberOfAuxSymbols
1757 i += symtab_i->NumberOfAuxSymbols;
1766 ocResolve_PEi386 ( ObjectCode* oc )
1769 COFF_section* sectab;
1770 COFF_symbol* symtab;
1780 /* ToDo: should be variable-sized? But is at least safe in the
1781 sense of buffer-overrun-proof. */
1783 /* fprintf(stderr, "resolving for %s\n", oc->fileName); */
1785 hdr = (COFF_header*)(oc->image);
1786 sectab = (COFF_section*) (
1787 ((UChar*)(oc->image))
1788 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1790 symtab = (COFF_symbol*) (
1791 ((UChar*)(oc->image))
1792 + hdr->PointerToSymbolTable
1794 strtab = ((UChar*)(oc->image))
1795 + hdr->PointerToSymbolTable
1796 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1798 for (i = 0; i < hdr->NumberOfSections; i++) {
1799 COFF_section* sectab_i
1801 myindex ( sizeof_COFF_section, sectab, i );
1804 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
1807 /* Ignore sections called which contain stabs debugging
1809 if (0 == strcmp(".stab", sectab_i->Name)
1810 || 0 == strcmp(".stabstr", sectab_i->Name))
1813 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
1814 /* If the relocation field (a short) has overflowed, the
1815 * real count can be found in the first reloc entry.
1817 * See Section 4.1 (last para) of the PE spec (rev6.0).
1819 COFF_reloc* rel = (COFF_reloc*)
1820 myindex ( sizeof_COFF_reloc, reltab, 0 );
1821 noRelocs = rel->VirtualAddress;
1822 fprintf(stderr, "Overflown relocs: %u\n", noRelocs);
1825 noRelocs = sectab_i->NumberOfRelocations;
1830 for (; j < noRelocs; j++) {
1832 COFF_reloc* reltab_j
1834 myindex ( sizeof_COFF_reloc, reltab, j );
1836 /* the location to patch */
1838 ((UChar*)(oc->image))
1839 + (sectab_i->PointerToRawData
1840 + reltab_j->VirtualAddress
1841 - sectab_i->VirtualAddress )
1843 /* the existing contents of pP */
1845 /* the symbol to connect to */
1846 sym = (COFF_symbol*)
1847 myindex ( sizeof_COFF_symbol,
1848 symtab, reltab_j->SymbolTableIndex );
1851 "reloc sec %2d num %3d: type 0x%-4x "
1852 "vaddr 0x%-8x name `",
1854 (UInt32)reltab_j->Type,
1855 reltab_j->VirtualAddress );
1856 printName ( sym->Name, strtab );
1857 fprintf ( stderr, "'\n" ));
1859 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
1860 COFF_section* section_sym
1861 = findPEi386SectionCalled ( oc, sym->Name );
1863 belch("%s: can't find section `%s'", oc->fileName, sym->Name);
1866 S = ((UInt32)(oc->image))
1867 + (section_sym->PointerToRawData
1870 copyName ( sym->Name, strtab, symbol, 1000-1 );
1871 (void*)S = lookupLocalSymbol( oc, symbol );
1872 if ((void*)S != NULL) goto foundit;
1873 (void*)S = lookupSymbol( symbol );
1874 if ((void*)S != NULL) goto foundit;
1875 zapTrailingAtSign ( symbol );
1876 (void*)S = lookupLocalSymbol( oc, symbol );
1877 if ((void*)S != NULL) goto foundit;
1878 (void*)S = lookupSymbol( symbol );
1879 if ((void*)S != NULL) goto foundit;
1880 /* Newline first because the interactive linker has printed "linking..." */
1881 belch("\n%s: unknown symbol `%s'", oc->fileName, symbol);
1885 checkProddableBlock(oc, pP);
1886 switch (reltab_j->Type) {
1887 case MYIMAGE_REL_I386_DIR32:
1890 case MYIMAGE_REL_I386_REL32:
1891 /* Tricky. We have to insert a displacement at
1892 pP which, when added to the PC for the _next_
1893 insn, gives the address of the target (S).
1894 Problem is to know the address of the next insn
1895 when we only know pP. We assume that this
1896 literal field is always the last in the insn,
1897 so that the address of the next insn is pP+4
1898 -- hence the constant 4.
1899 Also I don't know if A should be added, but so
1900 far it has always been zero.
1903 *pP = S - ((UInt32)pP) - 4;
1906 belch("%s: unhandled PEi386 relocation type %d",
1907 oc->fileName, reltab_j->Type);
1914 IF_DEBUG(linker, belch("completed %s", oc->fileName));
1918 #endif /* defined(OBJFORMAT_PEi386) */
1921 /* --------------------------------------------------------------------------
1923 * ------------------------------------------------------------------------*/
1925 #if defined(OBJFORMAT_ELF)
1930 #if defined(sparc_TARGET_ARCH)
1931 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
1932 #elif defined(i386_TARGET_ARCH)
1933 # define ELF_TARGET_386 /* Used inside <elf.h> */
1934 #elif defined (ia64_TARGET_ARCH)
1935 # define ELF_TARGET_IA64 /* Used inside <elf.h> */
1937 # define ELF_FUNCTION_DESC /* calling convention uses function descriptors */
1938 # define ELF_NEED_GOT /* needs Global Offset Table */
1939 # define ELF_NEED_PLT /* needs Procedure Linkage Tables */
1945 * Define a set of types which can be used for both ELF32 and ELF64
1949 #define ELFCLASS ELFCLASS64
1950 #define Elf_Addr Elf64_Addr
1951 #define Elf_Word Elf64_Word
1952 #define Elf_Sword Elf64_Sword
1953 #define Elf_Ehdr Elf64_Ehdr
1954 #define Elf_Phdr Elf64_Phdr
1955 #define Elf_Shdr Elf64_Shdr
1956 #define Elf_Sym Elf64_Sym
1957 #define Elf_Rel Elf64_Rel
1958 #define Elf_Rela Elf64_Rela
1959 #define ELF_ST_TYPE ELF64_ST_TYPE
1960 #define ELF_ST_BIND ELF64_ST_BIND
1961 #define ELF_R_TYPE ELF64_R_TYPE
1962 #define ELF_R_SYM ELF64_R_SYM
1964 #define ELFCLASS ELFCLASS32
1965 #define Elf_Addr Elf32_Addr
1966 #define Elf_Word Elf32_Word
1967 #define Elf_Sword Elf32_Sword
1968 #define Elf_Ehdr Elf32_Ehdr
1969 #define Elf_Phdr Elf32_Phdr
1970 #define Elf_Shdr Elf32_Shdr
1971 #define Elf_Sym Elf32_Sym
1972 #define Elf_Rel Elf32_Rel
1973 #define Elf_Rela Elf32_Rela
1974 #define ELF_ST_TYPE ELF32_ST_TYPE
1975 #define ELF_ST_BIND ELF32_ST_BIND
1976 #define ELF_R_TYPE ELF32_R_TYPE
1977 #define ELF_R_SYM ELF32_R_SYM
1982 * Functions to allocate entries in dynamic sections. Currently we simply
1983 * preallocate a large number, and we don't check if a entry for the given
1984 * target already exists (a linear search is too slow). Ideally these
1985 * entries would be associated with symbols.
1988 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
1989 #define GOT_SIZE 0x20000
1990 #define FUNCTION_TABLE_SIZE 0x10000
1991 #define PLT_SIZE 0x08000
1994 static Elf_Addr got[GOT_SIZE];
1995 static unsigned int gotIndex;
1996 static Elf_Addr gp_val = (Elf_Addr)got;
1999 allocateGOTEntry(Elf_Addr target)
2003 if (gotIndex >= GOT_SIZE)
2004 barf("Global offset table overflow");
2006 entry = &got[gotIndex++];
2008 return (Elf_Addr)entry;
2012 #ifdef ELF_FUNCTION_DESC
2018 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
2019 static unsigned int functionTableIndex;
2022 allocateFunctionDesc(Elf_Addr target)
2024 FunctionDesc *entry;
2026 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
2027 barf("Function table overflow");
2029 entry = &functionTable[functionTableIndex++];
2031 entry->gp = (Elf_Addr)gp_val;
2032 return (Elf_Addr)entry;
2036 copyFunctionDesc(Elf_Addr target)
2038 FunctionDesc *olddesc = (FunctionDesc *)target;
2039 FunctionDesc *newdesc;
2041 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
2042 newdesc->gp = olddesc->gp;
2043 return (Elf_Addr)newdesc;
2048 #ifdef ia64_TARGET_ARCH
2049 static void ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value);
2050 static void ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc);
2052 static unsigned char plt_code[] =
2054 /* taken from binutils bfd/elfxx-ia64.c */
2055 0x0b, 0x78, 0x00, 0x02, 0x00, 0x24, /* [MMI] addl r15=0,r1;; */
2056 0x00, 0x41, 0x3c, 0x30, 0x28, 0xc0, /* ld8 r16=[r15],8 */
2057 0x01, 0x08, 0x00, 0x84, /* mov r14=r1;; */
2058 0x11, 0x08, 0x00, 0x1e, 0x18, 0x10, /* [MIB] ld8 r1=[r15] */
2059 0x60, 0x80, 0x04, 0x80, 0x03, 0x00, /* mov b6=r16 */
2060 0x60, 0x00, 0x80, 0x00 /* br.few b6;; */
2063 /* If we can't get to the function descriptor via gp, take a local copy of it */
2064 #define PLT_RELOC(code, target) { \
2065 Elf64_Sxword rel_value = target - gp_val; \
2066 if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff)) \
2067 ia64_reloc_gprel22((Elf_Addr)code, copyFunctionDesc(target)); \
2069 ia64_reloc_gprel22((Elf_Addr)code, target); \
2074 unsigned char code[sizeof(plt_code)];
2078 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
2080 PLTEntry *plt = (PLTEntry *)oc->plt;
2083 if (oc->pltIndex >= PLT_SIZE)
2084 barf("Procedure table overflow");
2086 entry = &plt[oc->pltIndex++];
2087 memcpy(entry->code, plt_code, sizeof(entry->code));
2088 PLT_RELOC(entry->code, target);
2089 return (Elf_Addr)entry;
2095 return (PLT_SIZE * sizeof(PLTEntry));
2101 * Generic ELF functions
2105 findElfSection ( void* objImage, Elf_Word sh_type )
2107 char* ehdrC = (char*)objImage;
2108 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2109 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
2110 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2114 for (i = 0; i < ehdr->e_shnum; i++) {
2115 if (shdr[i].sh_type == sh_type
2116 /* Ignore the section header's string table. */
2117 && i != ehdr->e_shstrndx
2118 /* Ignore string tables named .stabstr, as they contain
2120 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2122 ptr = ehdrC + shdr[i].sh_offset;
2129 #if defined(ia64_TARGET_ARCH)
2131 findElfSegment ( void* objImage, Elf_Addr vaddr )
2133 char* ehdrC = (char*)objImage;
2134 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2135 Elf_Phdr* phdr = (Elf_Phdr*)(ehdrC + ehdr->e_phoff);
2136 Elf_Addr segaddr = 0;
2139 for (i = 0; i < ehdr->e_phnum; i++) {
2140 segaddr = phdr[i].p_vaddr;
2141 if ((vaddr >= segaddr) && (vaddr < segaddr + phdr[i].p_memsz))
2149 ocVerifyImage_ELF ( ObjectCode* oc )
2153 int i, j, nent, nstrtab, nsymtabs;
2157 char* ehdrC = (char*)(oc->image);
2158 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2160 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
2161 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
2162 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
2163 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
2164 belch("%s: not an ELF object", oc->fileName);
2168 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
2169 belch("%s: unsupported ELF format", oc->fileName);
2173 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
2174 IF_DEBUG(linker,belch( "Is little-endian" ));
2176 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
2177 IF_DEBUG(linker,belch( "Is big-endian" ));
2179 belch("%s: unknown endiannness", oc->fileName);
2183 if (ehdr->e_type != ET_REL) {
2184 belch("%s: not a relocatable object (.o) file", oc->fileName);
2187 IF_DEBUG(linker, belch( "Is a relocatable object (.o) file" ));
2189 IF_DEBUG(linker,belch( "Architecture is " ));
2190 switch (ehdr->e_machine) {
2191 case EM_386: IF_DEBUG(linker,belch( "x86" )); break;
2192 case EM_SPARC: IF_DEBUG(linker,belch( "sparc" )); break;
2194 case EM_IA_64: IF_DEBUG(linker,belch( "ia64" )); break;
2196 default: IF_DEBUG(linker,belch( "unknown" ));
2197 belch("%s: unknown architecture", oc->fileName);
2201 IF_DEBUG(linker,belch(
2202 "\nSection header table: start %d, n_entries %d, ent_size %d",
2203 ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
2205 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
2207 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2209 if (ehdr->e_shstrndx == SHN_UNDEF) {
2210 belch("%s: no section header string table", oc->fileName);
2213 IF_DEBUG(linker,belch( "Section header string table is section %d",
2215 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2218 for (i = 0; i < ehdr->e_shnum; i++) {
2219 IF_DEBUG(linker,fprintf(stderr, "%2d: ", i ));
2220 IF_DEBUG(linker,fprintf(stderr, "type=%2d ", (int)shdr[i].sh_type ));
2221 IF_DEBUG(linker,fprintf(stderr, "size=%4d ", (int)shdr[i].sh_size ));
2222 IF_DEBUG(linker,fprintf(stderr, "offs=%4d ", (int)shdr[i].sh_offset ));
2223 IF_DEBUG(linker,fprintf(stderr, " (%p .. %p) ",
2224 ehdrC + shdr[i].sh_offset,
2225 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
2227 if (shdr[i].sh_type == SHT_REL) {
2228 IF_DEBUG(linker,fprintf(stderr, "Rel " ));
2229 } else if (shdr[i].sh_type == SHT_RELA) {
2230 IF_DEBUG(linker,fprintf(stderr, "RelA " ));
2232 IF_DEBUG(linker,fprintf(stderr," "));
2235 IF_DEBUG(linker,fprintf(stderr, "sname=%s\n", sh_strtab + shdr[i].sh_name ));
2239 IF_DEBUG(linker,belch( "\nString tables" ));
2242 for (i = 0; i < ehdr->e_shnum; i++) {
2243 if (shdr[i].sh_type == SHT_STRTAB
2244 /* Ignore the section header's string table. */
2245 && i != ehdr->e_shstrndx
2246 /* Ignore string tables named .stabstr, as they contain
2248 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2250 IF_DEBUG(linker,belch(" section %d is a normal string table", i ));
2251 strtab = ehdrC + shdr[i].sh_offset;
2256 belch("%s: no string tables, or too many", oc->fileName);
2261 IF_DEBUG(linker,belch( "\nSymbol tables" ));
2262 for (i = 0; i < ehdr->e_shnum; i++) {
2263 if (shdr[i].sh_type != SHT_SYMTAB) continue;
2264 IF_DEBUG(linker,belch( "section %d is a symbol table", i ));
2266 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2267 nent = shdr[i].sh_size / sizeof(Elf_Sym);
2268 IF_DEBUG(linker,belch( " number of entries is apparently %d (%d rem)",
2270 shdr[i].sh_size % sizeof(Elf_Sym)
2272 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
2273 belch("%s: non-integral number of symbol table entries", oc->fileName);
2276 for (j = 0; j < nent; j++) {
2277 IF_DEBUG(linker,fprintf(stderr, " %2d ", j ));
2278 IF_DEBUG(linker,fprintf(stderr, " sec=%-5d size=%-3d val=%5p ",
2279 (int)stab[j].st_shndx,
2280 (int)stab[j].st_size,
2281 (char*)stab[j].st_value ));
2283 IF_DEBUG(linker,fprintf(stderr, "type=" ));
2284 switch (ELF_ST_TYPE(stab[j].st_info)) {
2285 case STT_NOTYPE: IF_DEBUG(linker,fprintf(stderr, "notype " )); break;
2286 case STT_OBJECT: IF_DEBUG(linker,fprintf(stderr, "object " )); break;
2287 case STT_FUNC : IF_DEBUG(linker,fprintf(stderr, "func " )); break;
2288 case STT_SECTION: IF_DEBUG(linker,fprintf(stderr, "section" )); break;
2289 case STT_FILE: IF_DEBUG(linker,fprintf(stderr, "file " )); break;
2290 default: IF_DEBUG(linker,fprintf(stderr, "? " )); break;
2292 IF_DEBUG(linker,fprintf(stderr, " " ));
2294 IF_DEBUG(linker,fprintf(stderr, "bind=" ));
2295 switch (ELF_ST_BIND(stab[j].st_info)) {
2296 case STB_LOCAL : IF_DEBUG(linker,fprintf(stderr, "local " )); break;
2297 case STB_GLOBAL: IF_DEBUG(linker,fprintf(stderr, "global" )); break;
2298 case STB_WEAK : IF_DEBUG(linker,fprintf(stderr, "weak " )); break;
2299 default: IF_DEBUG(linker,fprintf(stderr, "? " )); break;
2301 IF_DEBUG(linker,fprintf(stderr, " " ));
2303 IF_DEBUG(linker,fprintf(stderr, "name=%s\n", strtab + stab[j].st_name ));
2307 if (nsymtabs == 0) {
2308 belch("%s: didn't find any symbol tables", oc->fileName);
2317 ocGetNames_ELF ( ObjectCode* oc )
2322 char* ehdrC = (char*)(oc->image);
2323 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2324 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
2325 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2327 ASSERT(symhash != NULL);
2330 belch("%s: no strtab", oc->fileName);
2335 for (i = 0; i < ehdr->e_shnum; i++) {
2336 /* Figure out what kind of section it is. Logic derived from
2337 Figure 1.14 ("Special Sections") of the ELF document
2338 ("Portable Formats Specification, Version 1.1"). */
2339 Elf_Shdr hdr = shdr[i];
2340 SectionKind kind = SECTIONKIND_OTHER;
2343 if (hdr.sh_type == SHT_PROGBITS
2344 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_EXECINSTR)) {
2345 /* .text-style section */
2346 kind = SECTIONKIND_CODE_OR_RODATA;
2349 if (hdr.sh_type == SHT_PROGBITS
2350 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_WRITE)) {
2351 /* .data-style section */
2352 kind = SECTIONKIND_RWDATA;
2355 if (hdr.sh_type == SHT_PROGBITS
2356 && (hdr.sh_flags & SHF_ALLOC) && !(hdr.sh_flags & SHF_WRITE)) {
2357 /* .rodata-style section */
2358 kind = SECTIONKIND_CODE_OR_RODATA;
2361 if (hdr.sh_type == SHT_NOBITS
2362 && (hdr.sh_flags & SHF_ALLOC) && (hdr.sh_flags & SHF_WRITE)) {
2363 /* .bss-style section */
2364 kind = SECTIONKIND_RWDATA;
2368 if (is_bss && shdr[i].sh_size > 0) {
2369 /* This is a non-empty .bss section. Allocate zeroed space for
2370 it, and set its .sh_offset field such that
2371 ehdrC + .sh_offset == addr_of_zeroed_space. */
2372 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
2373 "ocGetNames_ELF(BSS)");
2374 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
2376 fprintf(stderr, "BSS section at 0x%x, size %d\n",
2377 zspace, shdr[i].sh_size);
2381 /* fill in the section info */
2382 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
2383 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
2384 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
2385 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
2388 if (shdr[i].sh_type != SHT_SYMTAB) continue;
2390 /* copy stuff into this module's object symbol table */
2391 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2392 nent = shdr[i].sh_size / sizeof(Elf_Sym);
2394 oc->n_symbols = nent;
2395 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2396 "ocGetNames_ELF(oc->symbols)");
2398 for (j = 0; j < nent; j++) {
2400 char isLocal = FALSE; /* avoids uninit-var warning */
2402 char* nm = strtab + stab[j].st_name;
2403 int secno = stab[j].st_shndx;
2405 /* Figure out if we want to add it; if so, set ad to its
2406 address. Otherwise leave ad == NULL. */
2408 if (secno == SHN_COMMON) {
2410 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
2412 fprintf(stderr, "COMMON symbol, size %d name %s\n",
2413 stab[j].st_size, nm);
2415 /* Pointless to do addProddableBlock() for this area,
2416 since the linker should never poke around in it. */
2419 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
2420 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
2422 /* and not an undefined symbol */
2423 && stab[j].st_shndx != SHN_UNDEF
2424 /* and not in a "special section" */
2425 && stab[j].st_shndx < SHN_LORESERVE
2427 /* and it's a not a section or string table or anything silly */
2428 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
2429 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
2430 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
2433 /* Section 0 is the undefined section, hence > and not >=. */
2434 ASSERT(secno > 0 && secno < ehdr->e_shnum);
2436 if (shdr[secno].sh_type == SHT_NOBITS) {
2437 fprintf(stderr, " BSS symbol, size %d off %d name %s\n",
2438 stab[j].st_size, stab[j].st_value, nm);
2441 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
2442 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
2445 #ifdef ELF_FUNCTION_DESC
2446 /* dlsym() and the initialisation table both give us function
2447 * descriptors, so to be consistent we store function descriptors
2448 * in the symbol table */
2449 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
2450 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
2452 IF_DEBUG(linker,belch( "addOTabName(GLOB): %10p %s %s",
2453 ad, oc->fileName, nm ));
2458 /* And the decision is ... */
2462 oc->symbols[j] = nm;
2465 /* Ignore entirely. */
2467 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
2471 IF_DEBUG(linker,belch( "skipping `%s'",
2472 strtab + stab[j].st_name ));
2475 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
2476 (int)ELF_ST_BIND(stab[j].st_info),
2477 (int)ELF_ST_TYPE(stab[j].st_info),
2478 (int)stab[j].st_shndx,
2479 strtab + stab[j].st_name
2482 oc->symbols[j] = NULL;
2491 /* Do ELF relocations which lack an explicit addend. All x86-linux
2492 relocations appear to be of this form. */
2494 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
2495 Elf_Shdr* shdr, int shnum,
2496 Elf_Sym* stab, char* strtab )
2501 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
2502 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
2503 int target_shndx = shdr[shnum].sh_info;
2504 int symtab_shndx = shdr[shnum].sh_link;
2506 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2507 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
2508 IF_DEBUG(linker,belch( "relocations for section %d using symtab %d",
2509 target_shndx, symtab_shndx ));
2511 for (j = 0; j < nent; j++) {
2512 Elf_Addr offset = rtab[j].r_offset;
2513 Elf_Addr info = rtab[j].r_info;
2515 Elf_Addr P = ((Elf_Addr)targ) + offset;
2516 Elf_Word* pP = (Elf_Word*)P;
2521 IF_DEBUG(linker,belch( "Rel entry %3d is raw(%6p %6p)",
2522 j, (void*)offset, (void*)info ));
2524 IF_DEBUG(linker,belch( " ZERO" ));
2527 Elf_Sym sym = stab[ELF_R_SYM(info)];
2528 /* First see if it is a local symbol. */
2529 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
2530 /* Yes, so we can get the address directly from the ELF symbol
2532 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
2534 (ehdrC + shdr[ sym.st_shndx ].sh_offset
2535 + stab[ELF_R_SYM(info)].st_value);
2538 /* No, so look up the name in our global table. */
2539 symbol = strtab + sym.st_name;
2540 (void*)S = lookupSymbol( symbol );
2543 belch("%s: unknown symbol `%s'", oc->fileName, symbol);
2546 IF_DEBUG(linker,belch( "`%s' resolves to %p", symbol, (void*)S ));
2549 IF_DEBUG(linker,belch( "Reloc: P = %p S = %p A = %p",
2550 (void*)P, (void*)S, (void*)A ));
2551 checkProddableBlock ( oc, pP );
2555 switch (ELF_R_TYPE(info)) {
2556 # ifdef i386_TARGET_ARCH
2557 case R_386_32: *pP = value; break;
2558 case R_386_PC32: *pP = value - P; break;
2561 belch("%s: unhandled ELF relocation(Rel) type %d\n",
2562 oc->fileName, ELF_R_TYPE(info));
2570 /* Do ELF relocations for which explicit addends are supplied.
2571 sparc-solaris relocations appear to be of this form. */
2573 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
2574 Elf_Shdr* shdr, int shnum,
2575 Elf_Sym* stab, char* strtab )
2580 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
2581 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
2582 int target_shndx = shdr[shnum].sh_info;
2583 int symtab_shndx = shdr[shnum].sh_link;
2585 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2586 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
2587 IF_DEBUG(linker,belch( "relocations for section %d using symtab %d",
2588 target_shndx, symtab_shndx ));
2590 for (j = 0; j < nent; j++) {
2591 #if defined(DEBUG) || defined(sparc_TARGET_ARCH) || defined(ia64_TARGET_ARCH)
2592 /* This #ifdef only serves to avoid unused-var warnings. */
2593 Elf_Addr offset = rtab[j].r_offset;
2594 Elf_Addr P = targ + offset;
2596 Elf_Addr info = rtab[j].r_info;
2597 Elf_Addr A = rtab[j].r_addend;
2600 # if defined(sparc_TARGET_ARCH)
2601 Elf_Word* pP = (Elf_Word*)P;
2603 # elif defined(ia64_TARGET_ARCH)
2604 Elf64_Xword *pP = (Elf64_Xword *)P;
2608 IF_DEBUG(linker,belch( "Rel entry %3d is raw(%6p %6p %6p) ",
2609 j, (void*)offset, (void*)info,
2612 IF_DEBUG(linker,belch( " ZERO" ));
2615 Elf_Sym sym = stab[ELF_R_SYM(info)];
2616 /* First see if it is a local symbol. */
2617 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
2618 /* Yes, so we can get the address directly from the ELF symbol
2620 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
2622 (ehdrC + shdr[ sym.st_shndx ].sh_offset
2623 + stab[ELF_R_SYM(info)].st_value);
2624 #ifdef ELF_FUNCTION_DESC
2625 /* Make a function descriptor for this function */
2626 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
2627 S = allocateFunctionDesc(S + A);
2632 /* No, so look up the name in our global table. */
2633 symbol = strtab + sym.st_name;
2634 (void*)S = lookupSymbol( symbol );
2636 #ifdef ELF_FUNCTION_DESC
2637 /* If a function, already a function descriptor - we would
2638 have to copy it to add an offset. */
2639 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC)
2644 belch("%s: unknown symbol `%s'", oc->fileName, symbol);
2647 IF_DEBUG(linker,belch( "`%s' resolves to %p", symbol, (void*)S ));
2650 IF_DEBUG(linker,fprintf ( stderr, "Reloc: P = %p S = %p A = %p\n",
2651 (void*)P, (void*)S, (void*)A ));
2652 /* checkProddableBlock ( oc, (void*)P ); */
2656 switch (ELF_R_TYPE(info)) {
2657 # if defined(sparc_TARGET_ARCH)
2658 case R_SPARC_WDISP30:
2659 w1 = *pP & 0xC0000000;
2660 w2 = (Elf_Word)((value - P) >> 2);
2661 ASSERT((w2 & 0xC0000000) == 0);
2666 w1 = *pP & 0xFFC00000;
2667 w2 = (Elf_Word)(value >> 10);
2668 ASSERT((w2 & 0xFFC00000) == 0);
2674 w2 = (Elf_Word)(value & 0x3FF);
2675 ASSERT((w2 & ~0x3FF) == 0);
2679 /* According to the Sun documentation:
2681 This relocation type resembles R_SPARC_32, except it refers to an
2682 unaligned word. That is, the word to be relocated must be treated
2683 as four separate bytes with arbitrary alignment, not as a word
2684 aligned according to the architecture requirements.
2686 (JRS: which means that freeloading on the R_SPARC_32 case
2687 is probably wrong, but hey ...)
2691 w2 = (Elf_Word)value;
2694 # elif defined(ia64_TARGET_ARCH)
2695 case R_IA64_DIR64LSB:
2696 case R_IA64_FPTR64LSB:
2699 case R_IA64_SEGREL64LSB:
2700 addr = findElfSegment(ehdrC, value);
2703 case R_IA64_GPREL22:
2704 ia64_reloc_gprel22(P, value);
2706 case R_IA64_LTOFF22:
2707 case R_IA64_LTOFF_FPTR22:
2708 addr = allocateGOTEntry(value);
2709 ia64_reloc_gprel22(P, addr);
2711 case R_IA64_PCREL21B:
2712 ia64_reloc_pcrel21(P, S, oc);
2716 belch("%s: unhandled ELF relocation(RelA) type %d\n",
2717 oc->fileName, ELF_R_TYPE(info));
2726 ocResolve_ELF ( ObjectCode* oc )
2730 Elf_Sym* stab = NULL;
2731 char* ehdrC = (char*)(oc->image);
2732 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
2733 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2734 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2736 /* first find "the" symbol table */
2737 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
2739 /* also go find the string table */
2740 strtab = findElfSection ( ehdrC, SHT_STRTAB );
2742 if (stab == NULL || strtab == NULL) {
2743 belch("%s: can't find string or symbol table", oc->fileName);
2747 /* Process the relocation sections. */
2748 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
2750 /* Skip sections called ".rel.stab". These appear to contain
2751 relocation entries that, when done, make the stabs debugging
2752 info point at the right places. We ain't interested in all
2754 if (0 == memcmp(".rel.stab", sh_strtab + shdr[shnum].sh_name, 9))
2757 if (shdr[shnum].sh_type == SHT_REL ) {
2758 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
2759 shnum, stab, strtab );
2763 if (shdr[shnum].sh_type == SHT_RELA) {
2764 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
2765 shnum, stab, strtab );
2770 /* Free the local symbol table; we won't need it again. */
2771 freeHashTable(oc->lochash, NULL);
2779 * Instructions are 41 bits long, packed into 128 bit bundles with a 5-bit template
2780 * at the front. The following utility functions pack and unpack instructions, and
2781 * take care of the most common relocations.
2784 #ifdef ia64_TARGET_ARCH
2787 ia64_extract_instruction(Elf64_Xword *target)
2790 int slot = (Elf_Addr)target & 3;
2791 (Elf_Addr)target &= ~3;
2799 return ((w1 >> 5) & 0x1ffffffffff);
2801 return (w1 >> 46) | ((w2 & 0x7fffff) << 18);
2805 barf("ia64_extract_instruction: invalid slot %p", target);
2810 ia64_deposit_instruction(Elf64_Xword *target, Elf64_Xword value)
2812 int slot = (Elf_Addr)target & 3;
2813 (Elf_Addr)target &= ~3;
2818 *target |= value << 5;
2821 *target |= value << 46;
2822 *(target+1) |= value >> 18;
2825 *(target+1) |= value << 23;
2831 ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value)
2833 Elf64_Xword instruction;
2834 Elf64_Sxword rel_value;
2836 rel_value = value - gp_val;
2837 if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff))
2838 barf("GP-relative data out of range (address = 0x%lx, gp = 0x%lx)", value, gp_val);
2840 instruction = ia64_extract_instruction((Elf64_Xword *)target);
2841 instruction |= (((rel_value >> 0) & 0x07f) << 13) /* imm7b */
2842 | (((rel_value >> 7) & 0x1ff) << 27) /* imm9d */
2843 | (((rel_value >> 16) & 0x01f) << 22) /* imm5c */
2844 | ((Elf64_Xword)(rel_value < 0) << 36); /* s */
2845 ia64_deposit_instruction((Elf64_Xword *)target, instruction);
2849 ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc)
2851 Elf64_Xword instruction;
2852 Elf64_Sxword rel_value;
2855 entry = allocatePLTEntry(value, oc);
2857 rel_value = (entry >> 4) - (target >> 4);
2858 if ((rel_value > 0xfffff) || (rel_value < -0xfffff))
2859 barf("PLT entry too far away (entry = 0x%lx, target = 0x%lx)", entry, target);
2861 instruction = ia64_extract_instruction((Elf64_Xword *)target);
2862 instruction |= ((rel_value & 0xfffff) << 13) /* imm20b */
2863 | ((Elf64_Xword)(rel_value < 0) << 36); /* s */
2864 ia64_deposit_instruction((Elf64_Xword *)target, instruction);
2871 /* --------------------------------------------------------------------------
2873 * ------------------------------------------------------------------------*/
2875 #if defined(OBJFORMAT_MACHO)
2878 Initial support for MachO linking on Darwin/MacOS X on PowerPC chips
2879 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
2881 I hereby formally apologize for the hackish nature of this code.
2882 Things that need to be done:
2883 *) get common symbols and .bss sections to work properly.
2884 Haskell modules seem to work, but C modules can cause problems
2885 *) implement ocVerifyImage_MachO
2886 *) add more sanity checks. The current code just has to segfault if there's a
2890 static int ocVerifyImage_MachO(ObjectCode* oc)
2892 // FIXME: do some verifying here
2896 static void resolveImports(
2899 struct symtab_command *symLC,
2900 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
2901 unsigned long *indirectSyms,
2902 struct nlist *nlist)
2906 for(i=0;i*4<sect->size;i++)
2908 // according to otool, reserved1 contains the first index into the indirect symbol table
2909 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
2910 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
2913 if((symbol->n_type & N_TYPE) == N_UNDF
2914 && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
2915 addr = (void*) (symbol->n_value);
2916 else if((addr = lookupLocalSymbol(oc,nm)) != NULL)
2919 addr = lookupSymbol(nm);
2922 fprintf(stderr, "not found: %s\n", nm);
2926 ((void**)(image + sect->offset))[i] = addr;
2930 static void relocateSection(char *image,
2931 struct symtab_command *symLC, struct nlist *nlist,
2932 struct section* sections, struct section *sect)
2934 struct relocation_info *relocs;
2937 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
2939 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
2943 relocs = (struct relocation_info*) (image + sect->reloff);
2947 if(relocs[i].r_address & R_SCATTERED)
2949 struct scattered_relocation_info *scat =
2950 (struct scattered_relocation_info*) &relocs[i];
2954 if(scat->r_length == 2 && scat->r_type == GENERIC_RELOC_VANILLA)
2956 unsigned long* word = (unsigned long*) (image + sect->offset + scat->r_address);
2958 *word = scat->r_value + sect->offset + ((long) image);
2962 continue; // FIXME: I hope it's OK to ignore all the others.
2966 struct relocation_info *reloc = &relocs[i];
2967 if(reloc->r_pcrel && !reloc->r_extern)
2970 if(!reloc->r_pcrel && reloc->r_length == 2)
2974 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
2976 if(reloc->r_type == GENERIC_RELOC_VANILLA)
2980 else if(reloc->r_type == PPC_RELOC_LO16)
2982 word = ((unsigned short*) wordPtr)[1];
2983 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
2985 else if(reloc->r_type == PPC_RELOC_HI16)
2987 word = ((unsigned short*) wordPtr)[1] << 16;
2988 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
2990 else if(reloc->r_type == PPC_RELOC_HA16)
2992 word = ((unsigned short*) wordPtr)[1] << 16;
2993 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
2996 if(!reloc->r_extern)
2999 sections[reloc->r_symbolnum-1].offset
3000 - sections[reloc->r_symbolnum-1].addr
3007 struct nlist *symbol = &nlist[reloc->r_symbolnum];
3008 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3009 word = (unsigned long) (lookupSymbol(nm));
3013 if(reloc->r_type == GENERIC_RELOC_VANILLA)
3018 else if(reloc->r_type == PPC_RELOC_LO16)
3020 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
3023 else if(reloc->r_type == PPC_RELOC_HI16)
3025 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
3028 else if(reloc->r_type == PPC_RELOC_HA16)
3030 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
3031 + ((word & (1<<15)) ? 1 : 0);
3036 fprintf(stderr, "unknown reloc\n");
3043 static int ocGetNames_MachO(ObjectCode* oc)
3045 char *image = (char*) oc->image;
3046 struct mach_header *header = (struct mach_header*) image;
3047 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3048 unsigned i,curSymbol;
3049 struct segment_command *segLC = NULL;
3050 struct section *sections, *la_ptrs = NULL, *nl_ptrs = NULL;
3051 struct symtab_command *symLC = NULL;
3052 struct dysymtab_command *dsymLC = NULL;
3053 struct nlist *nlist;
3054 unsigned long commonSize = 0;
3055 char *commonStorage = NULL;
3056 unsigned long commonCounter;
3058 for(i=0;i<header->ncmds;i++)
3060 if(lc->cmd == LC_SEGMENT)
3061 segLC = (struct segment_command*) lc;
3062 else if(lc->cmd == LC_SYMTAB)
3063 symLC = (struct symtab_command*) lc;
3064 else if(lc->cmd == LC_DYSYMTAB)
3065 dsymLC = (struct dysymtab_command*) lc;
3066 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3069 sections = (struct section*) (segLC+1);
3070 nlist = (struct nlist*) (image + symLC->symoff);
3072 for(i=0;i<segLC->nsects;i++)
3074 if(!strcmp(sections[i].sectname,"__la_symbol_ptr"))
3075 la_ptrs = §ions[i];
3076 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr"))
3077 nl_ptrs = §ions[i];
3079 // for now, only add __text and __const to the sections table
3080 else if(!strcmp(sections[i].sectname,"__text"))
3081 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
3082 (void*) (image + sections[i].offset),
3083 (void*) (image + sections[i].offset + sections[i].size));
3084 else if(!strcmp(sections[i].sectname,"__const"))
3085 addSection(oc, SECTIONKIND_RWDATA,
3086 (void*) (image + sections[i].offset),
3087 (void*) (image + sections[i].offset + sections[i].size));
3088 else if(!strcmp(sections[i].sectname,"__data"))
3089 addSection(oc, SECTIONKIND_RWDATA,
3090 (void*) (image + sections[i].offset),
3091 (void*) (image + sections[i].offset + sections[i].size));
3094 // count external symbols defined here
3096 for(i=dsymLC->iextdefsym;i<dsymLC->iextdefsym+dsymLC->nextdefsym;i++)
3098 if((nlist[i].n_type & N_TYPE) == N_SECT)
3101 for(i=0;i<symLC->nsyms;i++)
3103 if((nlist[i].n_type & N_TYPE) == N_UNDF
3104 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
3106 commonSize += nlist[i].n_value;
3110 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3111 "ocGetNames_MachO(oc->symbols)");
3113 // insert symbols into hash table
3114 for(i=dsymLC->iextdefsym,curSymbol=0;i<dsymLC->iextdefsym+dsymLC->nextdefsym;i++)
3116 if((nlist[i].n_type & N_TYPE) == N_SECT)
3118 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3119 ghciInsertStrHashTable(oc->fileName, symhash, nm, image +
3120 sections[nlist[i].n_sect-1].offset
3121 - sections[nlist[i].n_sect-1].addr
3122 + nlist[i].n_value);
3123 oc->symbols[curSymbol++] = nm;
3127 // insert local symbols into lochash
3128 for(i=dsymLC->ilocalsym;i<dsymLC->ilocalsym+dsymLC->nlocalsym;i++)
3130 if((nlist[i].n_type & N_TYPE) == N_SECT)
3132 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3133 ghciInsertStrHashTable(oc->fileName, oc->lochash, nm, image +
3134 sections[nlist[i].n_sect-1].offset
3135 - sections[nlist[i].n_sect-1].addr
3136 + nlist[i].n_value);
3141 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
3142 commonCounter = (unsigned long)commonStorage;
3143 for(i=0;i<symLC->nsyms;i++)
3145 if((nlist[i].n_type & N_TYPE) == N_UNDF
3146 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
3148 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3149 unsigned long sz = nlist[i].n_value;
3151 nlist[i].n_value = commonCounter;
3153 ghciInsertStrHashTable(oc->fileName, symhash, nm, (void*)commonCounter);
3154 oc->symbols[curSymbol++] = nm;
3156 commonCounter += sz;
3162 static int ocResolve_MachO(ObjectCode* oc)
3164 char *image = (char*) oc->image;
3165 struct mach_header *header = (struct mach_header*) image;
3166 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3168 struct segment_command *segLC = NULL;
3169 struct section *sections, *la_ptrs = NULL, *nl_ptrs = NULL;
3170 struct symtab_command *symLC = NULL;
3171 struct dysymtab_command *dsymLC = NULL;
3172 struct nlist *nlist;
3173 unsigned long *indirectSyms;
3175 for(i=0;i<header->ncmds;i++)
3177 if(lc->cmd == LC_SEGMENT)
3178 segLC = (struct segment_command*) lc;
3179 else if(lc->cmd == LC_SYMTAB)
3180 symLC = (struct symtab_command*) lc;
3181 else if(lc->cmd == LC_DYSYMTAB)
3182 dsymLC = (struct dysymtab_command*) lc;
3183 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3186 sections = (struct section*) (segLC+1);
3187 nlist = (struct nlist*) (image + symLC->symoff);
3189 for(i=0;i<segLC->nsects;i++)
3191 if(!strcmp(sections[i].sectname,"__la_symbol_ptr"))
3192 la_ptrs = §ions[i];
3193 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr"))
3194 nl_ptrs = §ions[i];
3197 indirectSyms = (unsigned long*) (image + dsymLC->indirectsymoff);
3200 resolveImports(oc,image,symLC,la_ptrs,indirectSyms,nlist);
3202 resolveImports(oc,image,symLC,nl_ptrs,indirectSyms,nlist);
3204 for(i=0;i<segLC->nsects;i++)
3206 relocateSection(image,symLC,nlist,sections,§ions[i]);
3209 /* Free the local symbol table; we won't need it again. */
3210 freeHashTable(oc->lochash, NULL);