1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2004
7 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
13 /* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and
14 MREMAP_MAYMOVE from <sys/mman.h>.
25 #include "LinkerInternals.h"
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
37 #ifdef HAVE_SYS_STAT_H
41 #if defined(HAVE_FRAMEWORK_HASKELLSUPPORT)
42 #include <HaskellSupport/dlfcn.h>
43 #elif defined(HAVE_DLFCN_H)
47 #if defined(cygwin32_HOST_OS)
52 #ifdef HAVE_SYS_TIME_H
56 #include <sys/fcntl.h>
57 #include <sys/termios.h>
58 #include <sys/utime.h>
59 #include <sys/utsname.h>
63 #if defined(ia64_HOST_ARCH) || defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
68 #if defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
76 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
77 # define OBJFORMAT_ELF
78 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
79 # define OBJFORMAT_PEi386
82 #elif defined(darwin_HOST_OS)
83 # include <mach-o/ppc/reloc.h>
84 # define OBJFORMAT_MACHO
85 # include <mach-o/loader.h>
86 # include <mach-o/nlist.h>
87 # include <mach-o/reloc.h>
88 # include <mach-o/dyld.h>
91 /* Hash table mapping symbol names to Symbol */
92 static /*Str*/HashTable *symhash;
94 /* List of currently loaded objects */
95 ObjectCode *objects = NULL; /* initially empty */
97 #if defined(OBJFORMAT_ELF)
98 static int ocVerifyImage_ELF ( ObjectCode* oc );
99 static int ocGetNames_ELF ( ObjectCode* oc );
100 static int ocResolve_ELF ( ObjectCode* oc );
101 #if defined(powerpc_HOST_ARCH)
102 static int ocAllocateJumpIslands_ELF ( ObjectCode* oc );
104 #elif defined(OBJFORMAT_PEi386)
105 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
106 static int ocGetNames_PEi386 ( ObjectCode* oc );
107 static int ocResolve_PEi386 ( ObjectCode* oc );
108 #elif defined(OBJFORMAT_MACHO)
109 static int ocAllocateJumpIslands_MachO ( ObjectCode* oc );
110 static int ocVerifyImage_MachO ( ObjectCode* oc );
111 static int ocGetNames_MachO ( ObjectCode* oc );
112 static int ocResolve_MachO ( ObjectCode* oc );
114 static void machoInitSymbolsWithoutUnderscore( void );
117 /* -----------------------------------------------------------------------------
118 * Built-in symbols from the RTS
121 typedef struct _RtsSymbolVal {
128 #define Maybe_ForeignObj SymX(mkForeignObjzh_fast)
130 #define Maybe_Stable_Names SymX(mkWeakzh_fast) \
131 SymX(makeStableNamezh_fast) \
132 SymX(finalizzeWeakzh_fast)
134 /* These are not available in GUM!!! -- HWL */
135 #define Maybe_ForeignObj
136 #define Maybe_Stable_Names
139 #if !defined (mingw32_HOST_OS)
140 #define RTS_POSIX_ONLY_SYMBOLS \
141 SymX(stg_sig_install) \
145 #if defined (cygwin32_HOST_OS)
146 #define RTS_MINGW_ONLY_SYMBOLS /**/
147 /* Don't have the ability to read import libs / archives, so
148 * we have to stupidly list a lot of what libcygwin.a
151 #define RTS_CYGWIN_ONLY_SYMBOLS \
229 #elif !defined(mingw32_HOST_OS)
230 #define RTS_MINGW_ONLY_SYMBOLS /**/
231 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
232 #else /* defined(mingw32_HOST_OS) */
233 #define RTS_POSIX_ONLY_SYMBOLS /**/
234 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
236 /* Extra syms gen'ed by mingw-2's gcc-3.2: */
238 #define RTS_MINGW_EXTRA_SYMS \
239 Sym(_imp____mb_cur_max) \
242 #define RTS_MINGW_EXTRA_SYMS
245 /* These are statically linked from the mingw libraries into the ghc
246 executable, so we have to employ this hack. */
247 #define RTS_MINGW_ONLY_SYMBOLS \
248 SymX(asyncReadzh_fast) \
249 SymX(asyncWritezh_fast) \
250 SymX(asyncDoProczh_fast) \
262 SymX(getservbyname) \
263 SymX(getservbyport) \
264 SymX(getprotobynumber) \
265 SymX(getprotobyname) \
266 SymX(gethostbyname) \
267 SymX(gethostbyaddr) \
301 SymX(stg_InstallConsoleEvent) \
303 Sym(_imp___timezone) \
311 RTS_MINGW_EXTRA_SYMS \
316 # define MAIN_CAP_SYM SymX(MainCapability)
318 # define MAIN_CAP_SYM
321 #ifdef TABLES_NEXT_TO_CODE
322 #define RTS_RET_SYMBOLS /* nothing */
324 #define RTS_RET_SYMBOLS \
325 SymX(stg_enter_ret) \
326 SymX(stg_gc_fun_ret) \
334 SymX(stg_ap_pv_ret) \
335 SymX(stg_ap_pp_ret) \
336 SymX(stg_ap_ppv_ret) \
337 SymX(stg_ap_ppp_ret) \
338 SymX(stg_ap_pppv_ret) \
339 SymX(stg_ap_pppp_ret) \
340 SymX(stg_ap_ppppp_ret) \
341 SymX(stg_ap_pppppp_ret)
344 #define RTS_SYMBOLS \
348 SymX(stg_enter_info) \
349 SymX(stg_gc_void_info) \
350 SymX(__stg_gc_enter_1) \
351 SymX(stg_gc_noregs) \
352 SymX(stg_gc_unpt_r1_info) \
353 SymX(stg_gc_unpt_r1) \
354 SymX(stg_gc_unbx_r1_info) \
355 SymX(stg_gc_unbx_r1) \
356 SymX(stg_gc_f1_info) \
358 SymX(stg_gc_d1_info) \
360 SymX(stg_gc_l1_info) \
363 SymX(stg_gc_fun_info) \
365 SymX(stg_gc_gen_info) \
366 SymX(stg_gc_gen_hp) \
368 SymX(stg_gen_yield) \
369 SymX(stg_yield_noregs) \
370 SymX(stg_yield_to_interpreter) \
371 SymX(stg_gen_block) \
372 SymX(stg_block_noregs) \
374 SymX(stg_block_takemvar) \
375 SymX(stg_block_putmvar) \
376 SymX(stg_seq_frame_info) \
378 SymX(MallocFailHook) \
380 SymX(OutOfHeapHook) \
381 SymX(StackOverflowHook) \
382 SymX(__encodeDouble) \
383 SymX(__encodeFloat) \
387 SymX(__gmpz_cmp_si) \
388 SymX(__gmpz_cmp_ui) \
389 SymX(__gmpz_get_si) \
390 SymX(__gmpz_get_ui) \
391 SymX(__int_encodeDouble) \
392 SymX(__int_encodeFloat) \
393 SymX(andIntegerzh_fast) \
394 SymX(atomicallyzh_fast) \
398 SymX(blockAsyncExceptionszh_fast) \
400 SymX(catchRetryzh_fast) \
401 SymX(catchSTMzh_fast) \
402 SymX(closure_flags) \
404 SymX(cmpIntegerzh_fast) \
405 SymX(cmpIntegerIntzh_fast) \
406 SymX(complementIntegerzh_fast) \
407 SymX(createAdjustor) \
408 SymX(decodeDoublezh_fast) \
409 SymX(decodeFloatzh_fast) \
412 SymX(deRefWeakzh_fast) \
413 SymX(deRefStablePtrzh_fast) \
414 SymX(divExactIntegerzh_fast) \
415 SymX(divModIntegerzh_fast) \
418 SymX(forkOS_createThread) \
419 SymX(freeHaskellFunctionPtr) \
420 SymX(freeStablePtr) \
421 SymX(gcdIntegerzh_fast) \
422 SymX(gcdIntegerIntzh_fast) \
423 SymX(gcdIntzh_fast) \
429 SymX(int2Integerzh_fast) \
430 SymX(integer2Intzh_fast) \
431 SymX(integer2Wordzh_fast) \
432 SymX(isCurrentThreadBoundzh_fast) \
433 SymX(isDoubleDenormalized) \
434 SymX(isDoubleInfinite) \
436 SymX(isDoubleNegativeZero) \
437 SymX(isEmptyMVarzh_fast) \
438 SymX(isFloatDenormalized) \
439 SymX(isFloatInfinite) \
441 SymX(isFloatNegativeZero) \
442 SymX(killThreadzh_fast) \
445 SymX(makeStablePtrzh_fast) \
446 SymX(minusIntegerzh_fast) \
447 SymX(mkApUpd0zh_fast) \
448 SymX(myThreadIdzh_fast) \
449 SymX(labelThreadzh_fast) \
450 SymX(newArrayzh_fast) \
451 SymX(newBCOzh_fast) \
452 SymX(newByteArrayzh_fast) \
453 SymX_redirect(newCAF, newDynCAF) \
454 SymX(newMVarzh_fast) \
455 SymX(newMutVarzh_fast) \
456 SymX(newTVarzh_fast) \
457 SymX(atomicModifyMutVarzh_fast) \
458 SymX(newPinnedByteArrayzh_fast) \
459 SymX(orIntegerzh_fast) \
461 SymX(performMajorGC) \
462 SymX(plusIntegerzh_fast) \
465 SymX(putMVarzh_fast) \
466 SymX(quotIntegerzh_fast) \
467 SymX(quotRemIntegerzh_fast) \
469 SymX(raiseIOzh_fast) \
470 SymX(readTVarzh_fast) \
471 SymX(remIntegerzh_fast) \
472 SymX(resetNonBlockingFd) \
477 SymX(rts_checkSchedStatus) \
480 SymX(rts_evalLazyIO) \
481 SymX(rts_evalStableIO) \
485 SymX(rts_getDouble) \
490 SymX(rts_getFunPtr) \
491 SymX(rts_getStablePtr) \
492 SymX(rts_getThreadId) \
494 SymX(rts_getWord32) \
507 SymX(rts_mkStablePtr) \
515 SymX(rtsSupportsBoundThreads) \
517 SymX(__hscore_get_saved_termios) \
518 SymX(__hscore_set_saved_termios) \
520 SymX(startupHaskell) \
521 SymX(shutdownHaskell) \
522 SymX(shutdownHaskellAndExit) \
523 SymX(stable_ptr_table) \
524 SymX(stackOverflow) \
525 SymX(stg_CAF_BLACKHOLE_info) \
526 SymX(stg_BLACKHOLE_BQ_info) \
527 SymX(awakenBlockedQueue) \
528 SymX(stg_CHARLIKE_closure) \
529 SymX(stg_EMPTY_MVAR_info) \
530 SymX(stg_IND_STATIC_info) \
531 SymX(stg_INTLIKE_closure) \
532 SymX(stg_MUT_ARR_PTRS_FROZEN_info) \
533 SymX(stg_MUT_ARR_PTRS_FROZEN0_info) \
534 SymX(stg_WEAK_info) \
535 SymX(stg_ap_0_info) \
536 SymX(stg_ap_v_info) \
537 SymX(stg_ap_f_info) \
538 SymX(stg_ap_d_info) \
539 SymX(stg_ap_l_info) \
540 SymX(stg_ap_n_info) \
541 SymX(stg_ap_p_info) \
542 SymX(stg_ap_pv_info) \
543 SymX(stg_ap_pp_info) \
544 SymX(stg_ap_ppv_info) \
545 SymX(stg_ap_ppp_info) \
546 SymX(stg_ap_pppv_info) \
547 SymX(stg_ap_pppp_info) \
548 SymX(stg_ap_ppppp_info) \
549 SymX(stg_ap_pppppp_info) \
550 SymX(stg_ap_1_upd_info) \
551 SymX(stg_ap_2_upd_info) \
552 SymX(stg_ap_3_upd_info) \
553 SymX(stg_ap_4_upd_info) \
554 SymX(stg_ap_5_upd_info) \
555 SymX(stg_ap_6_upd_info) \
556 SymX(stg_ap_7_upd_info) \
558 SymX(stg_sel_0_upd_info) \
559 SymX(stg_sel_10_upd_info) \
560 SymX(stg_sel_11_upd_info) \
561 SymX(stg_sel_12_upd_info) \
562 SymX(stg_sel_13_upd_info) \
563 SymX(stg_sel_14_upd_info) \
564 SymX(stg_sel_15_upd_info) \
565 SymX(stg_sel_1_upd_info) \
566 SymX(stg_sel_2_upd_info) \
567 SymX(stg_sel_3_upd_info) \
568 SymX(stg_sel_4_upd_info) \
569 SymX(stg_sel_5_upd_info) \
570 SymX(stg_sel_6_upd_info) \
571 SymX(stg_sel_7_upd_info) \
572 SymX(stg_sel_8_upd_info) \
573 SymX(stg_sel_9_upd_info) \
574 SymX(stg_upd_frame_info) \
575 SymX(suspendThread) \
576 SymX(takeMVarzh_fast) \
577 SymX(timesIntegerzh_fast) \
578 SymX(tryPutMVarzh_fast) \
579 SymX(tryTakeMVarzh_fast) \
580 SymX(unblockAsyncExceptionszh_fast) \
582 SymX(unsafeThawArrayzh_fast) \
583 SymX(waitReadzh_fast) \
584 SymX(waitWritezh_fast) \
585 SymX(word2Integerzh_fast) \
586 SymX(writeTVarzh_fast) \
587 SymX(xorIntegerzh_fast) \
590 #ifdef SUPPORT_LONG_LONGS
591 #define RTS_LONG_LONG_SYMS \
592 SymX(int64ToIntegerzh_fast) \
593 SymX(word64ToIntegerzh_fast)
595 #define RTS_LONG_LONG_SYMS /* nothing */
598 // 64-bit support functions in libgcc.a
599 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
600 #define RTS_LIBGCC_SYMBOLS \
610 #elif defined(ia64_HOST_ARCH)
611 #define RTS_LIBGCC_SYMBOLS \
619 #define RTS_LIBGCC_SYMBOLS
622 #ifdef darwin_HOST_OS
623 // Symbols that don't have a leading underscore
624 // on Mac OS X. They have to receive special treatment,
625 // see machoInitSymbolsWithoutUnderscore()
626 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
631 /* entirely bogus claims about types of these symbols */
632 #define Sym(vvv) extern void vvv(void);
633 #define SymX(vvv) /**/
634 #define SymX_redirect(vvv,xxx) /**/
638 RTS_POSIX_ONLY_SYMBOLS
639 RTS_MINGW_ONLY_SYMBOLS
640 RTS_CYGWIN_ONLY_SYMBOLS
646 #ifdef LEADING_UNDERSCORE
647 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
649 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
652 #define Sym(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
654 #define SymX(vvv) Sym(vvv)
656 // SymX_redirect allows us to redirect references to one symbol to
657 // another symbol. See newCAF/newDynCAF for an example.
658 #define SymX_redirect(vvv,xxx) \
659 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
662 static RtsSymbolVal rtsSyms[] = {
666 RTS_POSIX_ONLY_SYMBOLS
667 RTS_MINGW_ONLY_SYMBOLS
668 RTS_CYGWIN_ONLY_SYMBOLS
670 { 0, 0 } /* sentinel */
673 /* -----------------------------------------------------------------------------
674 * Insert symbols into hash tables, checking for duplicates.
676 static void ghciInsertStrHashTable ( char* obj_name,
682 if (lookupHashTable(table, (StgWord)key) == NULL)
684 insertStrHashTable(table, (StgWord)key, data);
689 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
691 "whilst processing object file\n"
693 "This could be caused by:\n"
694 " * Loading two different object files which export the same symbol\n"
695 " * Specifying the same object file twice on the GHCi command line\n"
696 " * An incorrect `package.conf' entry, causing some object to be\n"
698 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
707 /* -----------------------------------------------------------------------------
708 * initialize the object linker
712 static int linker_init_done = 0 ;
714 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
715 static void *dl_prog_handle;
718 /* dlopen(NULL,..) doesn't work so we grab libc explicitly */
719 #if defined(openbsd_HOST_OS)
720 static void *dl_libc_handle;
728 /* Make initLinker idempotent, so we can call it
729 before evey relevant operation; that means we
730 don't need to initialise the linker separately */
731 if (linker_init_done == 1) { return; } else {
732 linker_init_done = 1;
735 symhash = allocStrHashTable();
737 /* populate the symbol table with stuff from the RTS */
738 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
739 ghciInsertStrHashTable("(GHCi built-in symbols)",
740 symhash, sym->lbl, sym->addr);
742 # if defined(OBJFORMAT_MACHO)
743 machoInitSymbolsWithoutUnderscore();
746 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
747 # if defined(RTLD_DEFAULT)
748 dl_prog_handle = RTLD_DEFAULT;
750 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
751 # if defined(openbsd_HOST_OS)
752 dl_libc_handle = dlopen("libc.so", RTLD_LAZY);
754 # endif // RTLD_DEFAULT
758 /* -----------------------------------------------------------------------------
759 * Loading DLL or .so dynamic libraries
760 * -----------------------------------------------------------------------------
762 * Add a DLL from which symbols may be found. In the ELF case, just
763 * do RTLD_GLOBAL-style add, so no further messing around needs to
764 * happen in order that symbols in the loaded .so are findable --
765 * lookupSymbol() will subsequently see them by dlsym on the program's
766 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
768 * In the PEi386 case, open the DLLs and put handles to them in a
769 * linked list. When looking for a symbol, try all handles in the
770 * list. This means that we need to load even DLLs that are guaranteed
771 * to be in the ghc.exe image already, just so we can get a handle
772 * to give to loadSymbol, so that we can find the symbols. For such
773 * libraries, the LoadLibrary call should be a no-op except for returning
778 #if defined(OBJFORMAT_PEi386)
779 /* A record for storing handles into DLLs. */
784 struct _OpenedDLL* next;
789 /* A list thereof. */
790 static OpenedDLL* opened_dlls = NULL;
794 addDLL( char *dll_name )
796 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
797 /* ------------------- ELF DLL loader ------------------- */
803 hdl= dlopen(dll_name, RTLD_NOW | RTLD_GLOBAL);
806 /* dlopen failed; return a ptr to the error msg. */
808 if (errmsg == NULL) errmsg = "addDLL: unknown error";
815 # elif defined(OBJFORMAT_PEi386)
816 /* ------------------- Win32 DLL loader ------------------- */
824 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
826 /* See if we've already got it, and ignore if so. */
827 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
828 if (0 == strcmp(o_dll->name, dll_name))
832 /* The file name has no suffix (yet) so that we can try
833 both foo.dll and foo.drv
835 The documentation for LoadLibrary says:
836 If no file name extension is specified in the lpFileName
837 parameter, the default library extension .dll is
838 appended. However, the file name string can include a trailing
839 point character (.) to indicate that the module name has no
842 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
843 sprintf(buf, "%s.DLL", dll_name);
844 instance = LoadLibrary(buf);
845 if (instance == NULL) {
846 sprintf(buf, "%s.DRV", dll_name); // KAA: allow loading of drivers (like winspool.drv)
847 instance = LoadLibrary(buf);
848 if (instance == NULL) {
851 /* LoadLibrary failed; return a ptr to the error msg. */
852 return "addDLL: unknown error";
857 /* Add this DLL to the list of DLLs in which to search for symbols. */
858 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
859 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
860 strcpy(o_dll->name, dll_name);
861 o_dll->instance = instance;
862 o_dll->next = opened_dlls;
867 barf("addDLL: not implemented on this platform");
871 /* -----------------------------------------------------------------------------
872 * lookup a symbol in the hash table
875 lookupSymbol( char *lbl )
879 ASSERT(symhash != NULL);
880 val = lookupStrHashTable(symhash, lbl);
883 # if defined(OBJFORMAT_ELF)
884 # if defined(openbsd_HOST_OS)
885 val = dlsym(dl_prog_handle, lbl);
886 return (val != NULL) ? val : dlsym(dl_libc_handle,lbl);
887 # else /* not openbsd */
888 return dlsym(dl_prog_handle, lbl);
890 # elif defined(OBJFORMAT_MACHO)
891 if(NSIsSymbolNameDefined(lbl)) {
892 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
893 return NSAddressOfSymbol(symbol);
897 # elif defined(OBJFORMAT_PEi386)
900 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
901 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
903 /* HACK: if the name has an initial underscore, try stripping
904 it off & look that up first. I've yet to verify whether there's
905 a Rule that governs whether an initial '_' *should always* be
906 stripped off when mapping from import lib name to the DLL name.
908 sym = GetProcAddress(o_dll->instance, (lbl+1));
910 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
914 sym = GetProcAddress(o_dll->instance, lbl);
916 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
931 __attribute((unused))
933 lookupLocalSymbol( ObjectCode* oc, char *lbl )
937 val = lookupStrHashTable(oc->lochash, lbl);
947 /* -----------------------------------------------------------------------------
948 * Debugging aid: look in GHCi's object symbol tables for symbols
949 * within DELTA bytes of the specified address, and show their names.
952 void ghci_enquire ( char* addr );
954 void ghci_enquire ( char* addr )
959 const int DELTA = 64;
964 for (oc = objects; oc; oc = oc->next) {
965 for (i = 0; i < oc->n_symbols; i++) {
966 sym = oc->symbols[i];
967 if (sym == NULL) continue;
968 // debugBelch("enquire %p %p\n", sym, oc->lochash);
970 if (oc->lochash != NULL) {
971 a = lookupStrHashTable(oc->lochash, sym);
974 a = lookupStrHashTable(symhash, sym);
977 // debugBelch("ghci_enquire: can't find %s\n", sym);
979 else if (addr-DELTA <= a && a <= addr+DELTA) {
980 debugBelch("%p + %3d == `%s'\n", addr, a - addr, sym);
987 #ifdef ia64_HOST_ARCH
988 static unsigned int PLTSize(void);
991 /* -----------------------------------------------------------------------------
992 * Load an obj (populate the global symbol table, but don't resolve yet)
994 * Returns: 1 if ok, 0 on error.
997 loadObj( char *path )
1004 void *map_addr = NULL;
1011 /* debugBelch("loadObj %s\n", path ); */
1013 /* Check that we haven't already loaded this object.
1014 Ignore requests to load multiple times */
1018 for (o = objects; o; o = o->next) {
1019 if (0 == strcmp(o->fileName, path)) {
1021 break; /* don't need to search further */
1025 IF_DEBUG(linker, debugBelch(
1026 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1027 "same object file twice:\n"
1029 "GHCi will ignore this, but be warned.\n"
1031 return 1; /* success */
1035 oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
1037 # if defined(OBJFORMAT_ELF)
1038 oc->formatName = "ELF";
1039 # elif defined(OBJFORMAT_PEi386)
1040 oc->formatName = "PEi386";
1041 # elif defined(OBJFORMAT_MACHO)
1042 oc->formatName = "Mach-O";
1045 barf("loadObj: not implemented on this platform");
1048 r = stat(path, &st);
1049 if (r == -1) { return 0; }
1051 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1052 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1053 strcpy(oc->fileName, path);
1055 oc->fileSize = st.st_size;
1057 oc->sections = NULL;
1058 oc->lochash = allocStrHashTable();
1059 oc->proddables = NULL;
1061 /* chain it onto the list of objects */
1066 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1068 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
1070 #if defined(openbsd_HOST_OS)
1071 fd = open(path, O_RDONLY, S_IRUSR);
1073 fd = open(path, O_RDONLY);
1076 barf("loadObj: can't open `%s'", path);
1078 pagesize = getpagesize();
1080 #ifdef ia64_HOST_ARCH
1081 /* The PLT needs to be right before the object */
1082 n = ROUND_UP(PLTSize(), pagesize);
1083 oc->plt = mmap(NULL, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
1084 if (oc->plt == MAP_FAILED)
1085 barf("loadObj: can't allocate PLT");
1088 map_addr = oc->plt + n;
1091 n = ROUND_UP(oc->fileSize, pagesize);
1092 oc->image = mmap(map_addr, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
1093 if (oc->image == MAP_FAILED)
1094 barf("loadObj: can't map `%s'", path);
1098 #else /* !USE_MMAP */
1100 oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
1102 /* load the image into memory */
1103 f = fopen(path, "rb");
1105 barf("loadObj: can't read `%s'", path);
1107 n = fread ( oc->image, 1, oc->fileSize, f );
1108 if (n != oc->fileSize)
1109 barf("loadObj: error whilst reading `%s'", path);
1113 #endif /* USE_MMAP */
1115 # if defined(OBJFORMAT_MACHO)
1116 r = ocAllocateJumpIslands_MachO ( oc );
1117 if (!r) { return r; }
1118 # elif defined(OBJFORMAT_ELF) && defined(powerpc_HOST_ARCH)
1119 r = ocAllocateJumpIslands_ELF ( oc );
1120 if (!r) { return r; }
1123 /* verify the in-memory image */
1124 # if defined(OBJFORMAT_ELF)
1125 r = ocVerifyImage_ELF ( oc );
1126 # elif defined(OBJFORMAT_PEi386)
1127 r = ocVerifyImage_PEi386 ( oc );
1128 # elif defined(OBJFORMAT_MACHO)
1129 r = ocVerifyImage_MachO ( oc );
1131 barf("loadObj: no verify method");
1133 if (!r) { return r; }
1135 /* build the symbol list for this image */
1136 # if defined(OBJFORMAT_ELF)
1137 r = ocGetNames_ELF ( oc );
1138 # elif defined(OBJFORMAT_PEi386)
1139 r = ocGetNames_PEi386 ( oc );
1140 # elif defined(OBJFORMAT_MACHO)
1141 r = ocGetNames_MachO ( oc );
1143 barf("loadObj: no getNames method");
1145 if (!r) { return r; }
1147 /* loaded, but not resolved yet */
1148 oc->status = OBJECT_LOADED;
1153 /* -----------------------------------------------------------------------------
1154 * resolve all the currently unlinked objects in memory
1156 * Returns: 1 if ok, 0 on error.
1166 for (oc = objects; oc; oc = oc->next) {
1167 if (oc->status != OBJECT_RESOLVED) {
1168 # if defined(OBJFORMAT_ELF)
1169 r = ocResolve_ELF ( oc );
1170 # elif defined(OBJFORMAT_PEi386)
1171 r = ocResolve_PEi386 ( oc );
1172 # elif defined(OBJFORMAT_MACHO)
1173 r = ocResolve_MachO ( oc );
1175 barf("resolveObjs: not implemented on this platform");
1177 if (!r) { return r; }
1178 oc->status = OBJECT_RESOLVED;
1184 /* -----------------------------------------------------------------------------
1185 * delete an object from the pool
1188 unloadObj( char *path )
1190 ObjectCode *oc, *prev;
1192 ASSERT(symhash != NULL);
1193 ASSERT(objects != NULL);
1198 for (oc = objects; oc; prev = oc, oc = oc->next) {
1199 if (!strcmp(oc->fileName,path)) {
1201 /* Remove all the mappings for the symbols within this
1206 for (i = 0; i < oc->n_symbols; i++) {
1207 if (oc->symbols[i] != NULL) {
1208 removeStrHashTable(symhash, oc->symbols[i], NULL);
1216 prev->next = oc->next;
1219 /* We're going to leave this in place, in case there are
1220 any pointers from the heap into it: */
1221 /* stgFree(oc->image); */
1222 stgFree(oc->fileName);
1223 stgFree(oc->symbols);
1224 stgFree(oc->sections);
1225 /* The local hash table should have been freed at the end
1226 of the ocResolve_ call on it. */
1227 ASSERT(oc->lochash == NULL);
1233 errorBelch("unloadObj: can't find `%s' to unload", path);
1237 /* -----------------------------------------------------------------------------
1238 * Sanity checking. For each ObjectCode, maintain a list of address ranges
1239 * which may be prodded during relocation, and abort if we try and write
1240 * outside any of these.
1242 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1245 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1246 /* debugBelch("aPB %p %p %d\n", oc, start, size); */
1250 pb->next = oc->proddables;
1251 oc->proddables = pb;
1254 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1257 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1258 char* s = (char*)(pb->start);
1259 char* e = s + pb->size - 1;
1260 char* a = (char*)addr;
1261 /* Assumes that the biggest fixup involves a 4-byte write. This
1262 probably needs to be changed to 8 (ie, +7) on 64-bit
1264 if (a >= s && (a+3) <= e) return;
1266 barf("checkProddableBlock: invalid fixup in runtime linker");
1269 /* -----------------------------------------------------------------------------
1270 * Section management.
1272 static void addSection ( ObjectCode* oc, SectionKind kind,
1273 void* start, void* end )
1275 Section* s = stgMallocBytes(sizeof(Section), "addSection");
1279 s->next = oc->sections;
1282 debugBelch("addSection: %p-%p (size %d), kind %d\n",
1283 start, ((char*)end)-1, end - start + 1, kind );
1288 /* --------------------------------------------------------------------------
1289 * PowerPC specifics (jump islands)
1290 * ------------------------------------------------------------------------*/
1292 #if defined(powerpc_HOST_ARCH)
1295 ocAllocateJumpIslands
1297 Allocate additional space at the end of the object file image to make room
1300 PowerPC relative branch instructions have a 24 bit displacement field.
1301 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
1302 If a particular imported symbol is outside this range, we have to redirect
1303 the jump to a short piece of new code that just loads the 32bit absolute
1304 address and jumps there.
1305 This function just allocates space for one 16 byte ppcJumpIsland for every
1306 undefined symbol in the object file. The code for the islands is filled in by
1307 makeJumpIsland below.
1310 static int ocAllocateJumpIslands( ObjectCode* oc, int count, int first )
1319 // round up to the nearest 4
1320 aligned = (oc->fileSize + 3) & ~3;
1323 #ifndef linux_HOST_OS /* mremap is a linux extension */
1324 #error ocAllocateJumpIslands doesnt want USE_MMAP to be defined
1327 pagesize = getpagesize();
1328 n = ROUND_UP( oc->fileSize, pagesize );
1329 m = ROUND_UP( aligned + sizeof (ppcJumpIsland) * count, pagesize );
1331 /* The effect of this mremap() call is only the ensure that we have
1332 * a sufficient number of virtually contiguous pages. As returned from
1333 * mremap, the pages past the end of the file are not backed. We give
1334 * them a backing by using MAP_FIXED to map in anonymous pages.
1336 if( (oc->image = mremap( oc->image, n, m, MREMAP_MAYMOVE )) == MAP_FAILED )
1338 errorBelch( "Unable to mremap for Jump Islands\n" );
1342 if( mmap( oc->image + n, m - n, PROT_READ | PROT_WRITE | PROT_EXEC,
1343 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 0, 0 ) == MAP_FAILED )
1345 errorBelch( "Unable to mmap( MAP_FIXED ) for Jump Islands\n" );
1350 oc->image = stgReallocBytes( oc->image,
1351 aligned + sizeof (ppcJumpIsland) * count,
1352 "ocAllocateJumpIslands" );
1353 #endif /* USE_MMAP */
1355 oc->jump_islands = (ppcJumpIsland *) (oc->image + aligned);
1356 memset( oc->jump_islands, 0, sizeof (ppcJumpIsland) * count );
1359 oc->jump_islands = NULL;
1361 oc->island_start_symbol = first;
1362 oc->n_islands = count;
1367 static unsigned long makeJumpIsland( ObjectCode* oc,
1368 unsigned long symbolNumber,
1369 unsigned long target )
1371 ppcJumpIsland *island;
1373 if( symbolNumber < oc->island_start_symbol ||
1374 symbolNumber - oc->island_start_symbol > oc->n_islands)
1377 island = &oc->jump_islands[symbolNumber - oc->island_start_symbol];
1379 // lis r12, hi16(target)
1380 island->lis_r12 = 0x3d80;
1381 island->hi_addr = target >> 16;
1383 // ori r12, r12, lo16(target)
1384 island->ori_r12_r12 = 0x618c;
1385 island->lo_addr = target & 0xffff;
1388 island->mtctr_r12 = 0x7d8903a6;
1391 island->bctr = 0x4e800420;
1393 return (unsigned long) island;
1397 ocFlushInstructionCache
1399 Flush the data & instruction caches.
1400 Because the PPC has split data/instruction caches, we have to
1401 do that whenever we modify code at runtime.
1404 static void ocFlushInstructionCache( ObjectCode *oc )
1406 int n = (oc->fileSize + sizeof( ppcJumpIsland ) * oc->n_islands + 3) / 4;
1407 unsigned long *p = (unsigned long *) oc->image;
1411 __asm__ volatile ( "dcbf 0,%0\n\t"
1419 __asm__ volatile ( "sync\n\t"
1425 /* --------------------------------------------------------------------------
1426 * PEi386 specifics (Win32 targets)
1427 * ------------------------------------------------------------------------*/
1429 /* The information for this linker comes from
1430 Microsoft Portable Executable
1431 and Common Object File Format Specification
1432 revision 5.1 January 1998
1433 which SimonM says comes from the MS Developer Network CDs.
1435 It can be found there (on older CDs), but can also be found
1438 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
1440 (this is Rev 6.0 from February 1999).
1442 Things move, so if that fails, try searching for it via
1444 http://www.google.com/search?q=PE+COFF+specification
1446 The ultimate reference for the PE format is the Winnt.h
1447 header file that comes with the Platform SDKs; as always,
1448 implementations will drift wrt their documentation.
1450 A good background article on the PE format is Matt Pietrek's
1451 March 1994 article in Microsoft System Journal (MSJ)
1452 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
1453 Win32 Portable Executable File Format." The info in there
1454 has recently been updated in a two part article in
1455 MSDN magazine, issues Feb and March 2002,
1456 "Inside Windows: An In-Depth Look into the Win32 Portable
1457 Executable File Format"
1459 John Levine's book "Linkers and Loaders" contains useful
1464 #if defined(OBJFORMAT_PEi386)
1468 typedef unsigned char UChar;
1469 typedef unsigned short UInt16;
1470 typedef unsigned int UInt32;
1477 UInt16 NumberOfSections;
1478 UInt32 TimeDateStamp;
1479 UInt32 PointerToSymbolTable;
1480 UInt32 NumberOfSymbols;
1481 UInt16 SizeOfOptionalHeader;
1482 UInt16 Characteristics;
1486 #define sizeof_COFF_header 20
1493 UInt32 VirtualAddress;
1494 UInt32 SizeOfRawData;
1495 UInt32 PointerToRawData;
1496 UInt32 PointerToRelocations;
1497 UInt32 PointerToLinenumbers;
1498 UInt16 NumberOfRelocations;
1499 UInt16 NumberOfLineNumbers;
1500 UInt32 Characteristics;
1504 #define sizeof_COFF_section 40
1511 UInt16 SectionNumber;
1514 UChar NumberOfAuxSymbols;
1518 #define sizeof_COFF_symbol 18
1523 UInt32 VirtualAddress;
1524 UInt32 SymbolTableIndex;
1529 #define sizeof_COFF_reloc 10
1532 /* From PE spec doc, section 3.3.2 */
1533 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
1534 windows.h -- for the same purpose, but I want to know what I'm
1536 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
1537 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
1538 #define MYIMAGE_FILE_DLL 0x2000
1539 #define MYIMAGE_FILE_SYSTEM 0x1000
1540 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
1541 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
1542 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
1544 /* From PE spec doc, section 5.4.2 and 5.4.4 */
1545 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
1546 #define MYIMAGE_SYM_CLASS_STATIC 3
1547 #define MYIMAGE_SYM_UNDEFINED 0
1549 /* From PE spec doc, section 4.1 */
1550 #define MYIMAGE_SCN_CNT_CODE 0x00000020
1551 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
1552 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
1554 /* From PE spec doc, section 5.2.1 */
1555 #define MYIMAGE_REL_I386_DIR32 0x0006
1556 #define MYIMAGE_REL_I386_REL32 0x0014
1559 /* We use myindex to calculate array addresses, rather than
1560 simply doing the normal subscript thing. That's because
1561 some of the above structs have sizes which are not
1562 a whole number of words. GCC rounds their sizes up to a
1563 whole number of words, which means that the address calcs
1564 arising from using normal C indexing or pointer arithmetic
1565 are just plain wrong. Sigh.
1568 myindex ( int scale, void* base, int index )
1571 ((UChar*)base) + scale * index;
1576 printName ( UChar* name, UChar* strtab )
1578 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1579 UInt32 strtab_offset = * (UInt32*)(name+4);
1580 debugBelch("%s", strtab + strtab_offset );
1583 for (i = 0; i < 8; i++) {
1584 if (name[i] == 0) break;
1585 debugBelch("%c", name[i] );
1592 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
1594 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1595 UInt32 strtab_offset = * (UInt32*)(name+4);
1596 strncpy ( dst, strtab+strtab_offset, dstSize );
1602 if (name[i] == 0) break;
1612 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
1615 /* If the string is longer than 8 bytes, look in the
1616 string table for it -- this will be correctly zero terminated.
1618 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1619 UInt32 strtab_offset = * (UInt32*)(name+4);
1620 return ((UChar*)strtab) + strtab_offset;
1622 /* Otherwise, if shorter than 8 bytes, return the original,
1623 which by defn is correctly terminated.
1625 if (name[7]==0) return name;
1626 /* The annoying case: 8 bytes. Copy into a temporary
1627 (which is never freed ...)
1629 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
1631 strncpy(newstr,name,8);
1637 /* Just compares the short names (first 8 chars) */
1638 static COFF_section *
1639 findPEi386SectionCalled ( ObjectCode* oc, char* name )
1643 = (COFF_header*)(oc->image);
1644 COFF_section* sectab
1646 ((UChar*)(oc->image))
1647 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1649 for (i = 0; i < hdr->NumberOfSections; i++) {
1652 COFF_section* section_i
1654 myindex ( sizeof_COFF_section, sectab, i );
1655 n1 = (UChar*) &(section_i->Name);
1657 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
1658 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
1659 n1[6]==n2[6] && n1[7]==n2[7])
1668 zapTrailingAtSign ( UChar* sym )
1670 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
1672 if (sym[0] == 0) return;
1674 while (sym[i] != 0) i++;
1677 while (j > 0 && my_isdigit(sym[j])) j--;
1678 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
1684 ocVerifyImage_PEi386 ( ObjectCode* oc )
1689 COFF_section* sectab;
1690 COFF_symbol* symtab;
1692 /* debugBelch("\nLOADING %s\n", oc->fileName); */
1693 hdr = (COFF_header*)(oc->image);
1694 sectab = (COFF_section*) (
1695 ((UChar*)(oc->image))
1696 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1698 symtab = (COFF_symbol*) (
1699 ((UChar*)(oc->image))
1700 + hdr->PointerToSymbolTable
1702 strtab = ((UChar*)symtab)
1703 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1705 if (hdr->Machine != 0x14c) {
1706 errorBelch("Not x86 PEi386");
1709 if (hdr->SizeOfOptionalHeader != 0) {
1710 errorBelch("PEi386 with nonempty optional header");
1713 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
1714 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
1715 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
1716 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
1717 errorBelch("Not a PEi386 object file");
1720 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
1721 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
1722 errorBelch("Invalid PEi386 word size or endiannness: %d",
1723 (int)(hdr->Characteristics));
1726 /* If the string table size is way crazy, this might indicate that
1727 there are more than 64k relocations, despite claims to the
1728 contrary. Hence this test. */
1729 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
1731 if ( (*(UInt32*)strtab) > 600000 ) {
1732 /* Note that 600k has no special significance other than being
1733 big enough to handle the almost-2MB-sized lumps that
1734 constitute HSwin32*.o. */
1735 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
1740 /* No further verification after this point; only debug printing. */
1742 IF_DEBUG(linker, i=1);
1743 if (i == 0) return 1;
1745 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
1746 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
1747 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
1750 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
1751 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
1752 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
1753 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
1754 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
1755 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
1756 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
1758 /* Print the section table. */
1760 for (i = 0; i < hdr->NumberOfSections; i++) {
1762 COFF_section* sectab_i
1764 myindex ( sizeof_COFF_section, sectab, i );
1771 printName ( sectab_i->Name, strtab );
1781 sectab_i->VirtualSize,
1782 sectab_i->VirtualAddress,
1783 sectab_i->SizeOfRawData,
1784 sectab_i->PointerToRawData,
1785 sectab_i->NumberOfRelocations,
1786 sectab_i->PointerToRelocations,
1787 sectab_i->PointerToRawData
1789 reltab = (COFF_reloc*) (
1790 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
1793 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
1794 /* If the relocation field (a short) has overflowed, the
1795 * real count can be found in the first reloc entry.
1797 * See Section 4.1 (last para) of the PE spec (rev6.0).
1799 COFF_reloc* rel = (COFF_reloc*)
1800 myindex ( sizeof_COFF_reloc, reltab, 0 );
1801 noRelocs = rel->VirtualAddress;
1804 noRelocs = sectab_i->NumberOfRelocations;
1808 for (; j < noRelocs; j++) {
1810 COFF_reloc* rel = (COFF_reloc*)
1811 myindex ( sizeof_COFF_reloc, reltab, j );
1813 " type 0x%-4x vaddr 0x%-8x name `",
1815 rel->VirtualAddress );
1816 sym = (COFF_symbol*)
1817 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
1818 /* Hmm..mysterious looking offset - what's it for? SOF */
1819 printName ( sym->Name, strtab -10 );
1826 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
1827 debugBelch("---START of string table---\n");
1828 for (i = 4; i < *(Int32*)strtab; i++) {
1830 debugBelch("\n"); else
1831 debugBelch("%c", strtab[i] );
1833 debugBelch("--- END of string table---\n");
1838 COFF_symbol* symtab_i;
1839 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1840 symtab_i = (COFF_symbol*)
1841 myindex ( sizeof_COFF_symbol, symtab, i );
1847 printName ( symtab_i->Name, strtab );
1856 (Int32)(symtab_i->SectionNumber),
1857 (UInt32)symtab_i->Type,
1858 (UInt32)symtab_i->StorageClass,
1859 (UInt32)symtab_i->NumberOfAuxSymbols
1861 i += symtab_i->NumberOfAuxSymbols;
1871 ocGetNames_PEi386 ( ObjectCode* oc )
1874 COFF_section* sectab;
1875 COFF_symbol* symtab;
1882 hdr = (COFF_header*)(oc->image);
1883 sectab = (COFF_section*) (
1884 ((UChar*)(oc->image))
1885 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1887 symtab = (COFF_symbol*) (
1888 ((UChar*)(oc->image))
1889 + hdr->PointerToSymbolTable
1891 strtab = ((UChar*)(oc->image))
1892 + hdr->PointerToSymbolTable
1893 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1895 /* Allocate space for any (local, anonymous) .bss sections. */
1897 for (i = 0; i < hdr->NumberOfSections; i++) {
1899 COFF_section* sectab_i
1901 myindex ( sizeof_COFF_section, sectab, i );
1902 if (0 != strcmp(sectab_i->Name, ".bss")) continue;
1903 if (sectab_i->VirtualSize == 0) continue;
1904 /* This is a non-empty .bss section. Allocate zeroed space for
1905 it, and set its PointerToRawData field such that oc->image +
1906 PointerToRawData == addr_of_zeroed_space. */
1907 zspace = stgCallocBytes(1, sectab_i->VirtualSize,
1908 "ocGetNames_PEi386(anonymous bss)");
1909 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
1910 addProddableBlock(oc, zspace, sectab_i->VirtualSize);
1911 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
1914 /* Copy section information into the ObjectCode. */
1916 for (i = 0; i < hdr->NumberOfSections; i++) {
1922 = SECTIONKIND_OTHER;
1923 COFF_section* sectab_i
1925 myindex ( sizeof_COFF_section, sectab, i );
1926 IF_DEBUG(linker, debugBelch("section name = %s\n", sectab_i->Name ));
1929 /* I'm sure this is the Right Way to do it. However, the
1930 alternative of testing the sectab_i->Name field seems to
1931 work ok with Cygwin.
1933 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
1934 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
1935 kind = SECTIONKIND_CODE_OR_RODATA;
1938 if (0==strcmp(".text",sectab_i->Name) ||
1939 0==strcmp(".rodata",sectab_i->Name))
1940 kind = SECTIONKIND_CODE_OR_RODATA;
1941 if (0==strcmp(".data",sectab_i->Name) ||
1942 0==strcmp(".bss",sectab_i->Name))
1943 kind = SECTIONKIND_RWDATA;
1945 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
1946 sz = sectab_i->SizeOfRawData;
1947 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
1949 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
1950 end = start + sz - 1;
1952 if (kind == SECTIONKIND_OTHER
1953 /* Ignore sections called which contain stabs debugging
1955 && 0 != strcmp(".stab", sectab_i->Name)
1956 && 0 != strcmp(".stabstr", sectab_i->Name)
1958 errorBelch("Unknown PEi386 section name `%s'", sectab_i->Name);
1962 if (kind != SECTIONKIND_OTHER && end >= start) {
1963 addSection(oc, kind, start, end);
1964 addProddableBlock(oc, start, end - start + 1);
1968 /* Copy exported symbols into the ObjectCode. */
1970 oc->n_symbols = hdr->NumberOfSymbols;
1971 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
1972 "ocGetNames_PEi386(oc->symbols)");
1973 /* Call me paranoid; I don't care. */
1974 for (i = 0; i < oc->n_symbols; i++)
1975 oc->symbols[i] = NULL;
1979 COFF_symbol* symtab_i;
1980 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1981 symtab_i = (COFF_symbol*)
1982 myindex ( sizeof_COFF_symbol, symtab, i );
1986 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
1987 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
1988 /* This symbol is global and defined, viz, exported */
1989 /* for MYIMAGE_SYMCLASS_EXTERNAL
1990 && !MYIMAGE_SYM_UNDEFINED,
1991 the address of the symbol is:
1992 address of relevant section + offset in section
1994 COFF_section* sectabent
1995 = (COFF_section*) myindex ( sizeof_COFF_section,
1997 symtab_i->SectionNumber-1 );
1998 addr = ((UChar*)(oc->image))
1999 + (sectabent->PointerToRawData
2003 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
2004 && symtab_i->Value > 0) {
2005 /* This symbol isn't in any section at all, ie, global bss.
2006 Allocate zeroed space for it. */
2007 addr = stgCallocBytes(1, symtab_i->Value,
2008 "ocGetNames_PEi386(non-anonymous bss)");
2009 addSection(oc, SECTIONKIND_RWDATA, addr,
2010 ((UChar*)addr) + symtab_i->Value - 1);
2011 addProddableBlock(oc, addr, symtab_i->Value);
2012 /* debugBelch("BSS section at 0x%x\n", addr); */
2015 if (addr != NULL ) {
2016 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
2017 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
2018 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
2019 ASSERT(i >= 0 && i < oc->n_symbols);
2020 /* cstring_from_COFF_symbol_name always succeeds. */
2021 oc->symbols[i] = sname;
2022 ghciInsertStrHashTable(oc->fileName, symhash, sname, addr);
2026 "IGNORING symbol %d\n"
2030 printName ( symtab_i->Name, strtab );
2039 (Int32)(symtab_i->SectionNumber),
2040 (UInt32)symtab_i->Type,
2041 (UInt32)symtab_i->StorageClass,
2042 (UInt32)symtab_i->NumberOfAuxSymbols
2047 i += symtab_i->NumberOfAuxSymbols;
2056 ocResolve_PEi386 ( ObjectCode* oc )
2059 COFF_section* sectab;
2060 COFF_symbol* symtab;
2070 /* ToDo: should be variable-sized? But is at least safe in the
2071 sense of buffer-overrun-proof. */
2073 /* debugBelch("resolving for %s\n", oc->fileName); */
2075 hdr = (COFF_header*)(oc->image);
2076 sectab = (COFF_section*) (
2077 ((UChar*)(oc->image))
2078 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2080 symtab = (COFF_symbol*) (
2081 ((UChar*)(oc->image))
2082 + hdr->PointerToSymbolTable
2084 strtab = ((UChar*)(oc->image))
2085 + hdr->PointerToSymbolTable
2086 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2088 for (i = 0; i < hdr->NumberOfSections; i++) {
2089 COFF_section* sectab_i
2091 myindex ( sizeof_COFF_section, sectab, i );
2094 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2097 /* Ignore sections called which contain stabs debugging
2099 if (0 == strcmp(".stab", sectab_i->Name)
2100 || 0 == strcmp(".stabstr", sectab_i->Name))
2103 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2104 /* If the relocation field (a short) has overflowed, the
2105 * real count can be found in the first reloc entry.
2107 * See Section 4.1 (last para) of the PE spec (rev6.0).
2109 * Nov2003 update: the GNU linker still doesn't correctly
2110 * handle the generation of relocatable object files with
2111 * overflown relocations. Hence the output to warn of potential
2114 COFF_reloc* rel = (COFF_reloc*)
2115 myindex ( sizeof_COFF_reloc, reltab, 0 );
2116 noRelocs = rel->VirtualAddress;
2117 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
2121 noRelocs = sectab_i->NumberOfRelocations;
2126 for (; j < noRelocs; j++) {
2128 COFF_reloc* reltab_j
2130 myindex ( sizeof_COFF_reloc, reltab, j );
2132 /* the location to patch */
2134 ((UChar*)(oc->image))
2135 + (sectab_i->PointerToRawData
2136 + reltab_j->VirtualAddress
2137 - sectab_i->VirtualAddress )
2139 /* the existing contents of pP */
2141 /* the symbol to connect to */
2142 sym = (COFF_symbol*)
2143 myindex ( sizeof_COFF_symbol,
2144 symtab, reltab_j->SymbolTableIndex );
2147 "reloc sec %2d num %3d: type 0x%-4x "
2148 "vaddr 0x%-8x name `",
2150 (UInt32)reltab_j->Type,
2151 reltab_j->VirtualAddress );
2152 printName ( sym->Name, strtab );
2153 debugBelch("'\n" ));
2155 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
2156 COFF_section* section_sym
2157 = findPEi386SectionCalled ( oc, sym->Name );
2159 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
2162 S = ((UInt32)(oc->image))
2163 + (section_sym->PointerToRawData
2166 copyName ( sym->Name, strtab, symbol, 1000-1 );
2167 (void*)S = lookupLocalSymbol( oc, symbol );
2168 if ((void*)S != NULL) goto foundit;
2169 (void*)S = lookupSymbol( symbol );
2170 if ((void*)S != NULL) goto foundit;
2171 zapTrailingAtSign ( symbol );
2172 (void*)S = lookupLocalSymbol( oc, symbol );
2173 if ((void*)S != NULL) goto foundit;
2174 (void*)S = lookupSymbol( symbol );
2175 if ((void*)S != NULL) goto foundit;
2176 /* Newline first because the interactive linker has printed "linking..." */
2177 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, symbol);
2181 checkProddableBlock(oc, pP);
2182 switch (reltab_j->Type) {
2183 case MYIMAGE_REL_I386_DIR32:
2186 case MYIMAGE_REL_I386_REL32:
2187 /* Tricky. We have to insert a displacement at
2188 pP which, when added to the PC for the _next_
2189 insn, gives the address of the target (S).
2190 Problem is to know the address of the next insn
2191 when we only know pP. We assume that this
2192 literal field is always the last in the insn,
2193 so that the address of the next insn is pP+4
2194 -- hence the constant 4.
2195 Also I don't know if A should be added, but so
2196 far it has always been zero.
2199 *pP = S - ((UInt32)pP) - 4;
2202 debugBelch("%s: unhandled PEi386 relocation type %d",
2203 oc->fileName, reltab_j->Type);
2210 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
2214 #endif /* defined(OBJFORMAT_PEi386) */
2217 /* --------------------------------------------------------------------------
2219 * ------------------------------------------------------------------------*/
2221 #if defined(OBJFORMAT_ELF)
2226 #if defined(sparc_HOST_ARCH)
2227 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
2228 #elif defined(i386_HOST_ARCH)
2229 # define ELF_TARGET_386 /* Used inside <elf.h> */
2230 #elif defined(x86_64_HOST_ARCH)
2231 # define ELF_TARGET_X64_64
2233 #elif defined (ia64_HOST_ARCH)
2234 # define ELF_TARGET_IA64 /* Used inside <elf.h> */
2236 # define ELF_FUNCTION_DESC /* calling convention uses function descriptors */
2237 # define ELF_NEED_GOT /* needs Global Offset Table */
2238 # define ELF_NEED_PLT /* needs Procedure Linkage Tables */
2241 #if !defined(openbsd_HOST_OS)
2244 /* openbsd elf has things in different places, with diff names */
2245 #include <elf_abi.h>
2246 #include <machine/reloc.h>
2247 #define R_386_32 RELOC_32
2248 #define R_386_PC32 RELOC_PC32
2252 * Define a set of types which can be used for both ELF32 and ELF64
2256 #define ELFCLASS ELFCLASS64
2257 #define Elf_Addr Elf64_Addr
2258 #define Elf_Word Elf64_Word
2259 #define Elf_Sword Elf64_Sword
2260 #define Elf_Ehdr Elf64_Ehdr
2261 #define Elf_Phdr Elf64_Phdr
2262 #define Elf_Shdr Elf64_Shdr
2263 #define Elf_Sym Elf64_Sym
2264 #define Elf_Rel Elf64_Rel
2265 #define Elf_Rela Elf64_Rela
2266 #define ELF_ST_TYPE ELF64_ST_TYPE
2267 #define ELF_ST_BIND ELF64_ST_BIND
2268 #define ELF_R_TYPE ELF64_R_TYPE
2269 #define ELF_R_SYM ELF64_R_SYM
2271 #define ELFCLASS ELFCLASS32
2272 #define Elf_Addr Elf32_Addr
2273 #define Elf_Word Elf32_Word
2274 #define Elf_Sword Elf32_Sword
2275 #define Elf_Ehdr Elf32_Ehdr
2276 #define Elf_Phdr Elf32_Phdr
2277 #define Elf_Shdr Elf32_Shdr
2278 #define Elf_Sym Elf32_Sym
2279 #define Elf_Rel Elf32_Rel
2280 #define Elf_Rela Elf32_Rela
2282 #define ELF_ST_TYPE ELF32_ST_TYPE
2285 #define ELF_ST_BIND ELF32_ST_BIND
2288 #define ELF_R_TYPE ELF32_R_TYPE
2291 #define ELF_R_SYM ELF32_R_SYM
2297 * Functions to allocate entries in dynamic sections. Currently we simply
2298 * preallocate a large number, and we don't check if a entry for the given
2299 * target already exists (a linear search is too slow). Ideally these
2300 * entries would be associated with symbols.
2303 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
2304 #define GOT_SIZE 0x20000
2305 #define FUNCTION_TABLE_SIZE 0x10000
2306 #define PLT_SIZE 0x08000
2309 static Elf_Addr got[GOT_SIZE];
2310 static unsigned int gotIndex;
2311 static Elf_Addr gp_val = (Elf_Addr)got;
2314 allocateGOTEntry(Elf_Addr target)
2318 if (gotIndex >= GOT_SIZE)
2319 barf("Global offset table overflow");
2321 entry = &got[gotIndex++];
2323 return (Elf_Addr)entry;
2327 #ifdef ELF_FUNCTION_DESC
2333 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
2334 static unsigned int functionTableIndex;
2337 allocateFunctionDesc(Elf_Addr target)
2339 FunctionDesc *entry;
2341 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
2342 barf("Function table overflow");
2344 entry = &functionTable[functionTableIndex++];
2346 entry->gp = (Elf_Addr)gp_val;
2347 return (Elf_Addr)entry;
2351 copyFunctionDesc(Elf_Addr target)
2353 FunctionDesc *olddesc = (FunctionDesc *)target;
2354 FunctionDesc *newdesc;
2356 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
2357 newdesc->gp = olddesc->gp;
2358 return (Elf_Addr)newdesc;
2363 #ifdef ia64_HOST_ARCH
2364 static void ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value);
2365 static void ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc);
2367 static unsigned char plt_code[] =
2369 /* taken from binutils bfd/elfxx-ia64.c */
2370 0x0b, 0x78, 0x00, 0x02, 0x00, 0x24, /* [MMI] addl r15=0,r1;; */
2371 0x00, 0x41, 0x3c, 0x30, 0x28, 0xc0, /* ld8 r16=[r15],8 */
2372 0x01, 0x08, 0x00, 0x84, /* mov r14=r1;; */
2373 0x11, 0x08, 0x00, 0x1e, 0x18, 0x10, /* [MIB] ld8 r1=[r15] */
2374 0x60, 0x80, 0x04, 0x80, 0x03, 0x00, /* mov b6=r16 */
2375 0x60, 0x00, 0x80, 0x00 /* br.few b6;; */
2378 /* If we can't get to the function descriptor via gp, take a local copy of it */
2379 #define PLT_RELOC(code, target) { \
2380 Elf64_Sxword rel_value = target - gp_val; \
2381 if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff)) \
2382 ia64_reloc_gprel22((Elf_Addr)code, copyFunctionDesc(target)); \
2384 ia64_reloc_gprel22((Elf_Addr)code, target); \
2389 unsigned char code[sizeof(plt_code)];
2393 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
2395 PLTEntry *plt = (PLTEntry *)oc->plt;
2398 if (oc->pltIndex >= PLT_SIZE)
2399 barf("Procedure table overflow");
2401 entry = &plt[oc->pltIndex++];
2402 memcpy(entry->code, plt_code, sizeof(entry->code));
2403 PLT_RELOC(entry->code, target);
2404 return (Elf_Addr)entry;
2410 return (PLT_SIZE * sizeof(PLTEntry));
2416 * Generic ELF functions
2420 findElfSection ( void* objImage, Elf_Word sh_type )
2422 char* ehdrC = (char*)objImage;
2423 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2424 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
2425 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2429 for (i = 0; i < ehdr->e_shnum; i++) {
2430 if (shdr[i].sh_type == sh_type
2431 /* Ignore the section header's string table. */
2432 && i != ehdr->e_shstrndx
2433 /* Ignore string tables named .stabstr, as they contain
2435 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2437 ptr = ehdrC + shdr[i].sh_offset;
2445 findElfSectionIndexByName( ObjectCode *oc, const char *sh_name,
2446 Elf_Word expected_type, Elf_Word expected_entsize )
2448 Elf_Ehdr *ehdr = (Elf_Ehdr *) oc->image;
2449 Elf_Shdr *shdr = (Elf_Shdr *) (oc->image + ehdr->e_shoff);
2450 char *sectnames = oc->image + shdr[ehdr->e_shstrndx].sh_offset;
2453 for( i = 0; i < ehdr->e_shnum; i++ )
2454 if( !strcmp( sectnames + shdr[i].sh_name, sh_name ) )
2456 if( shdr[i].sh_type != expected_type )
2458 errorBelch( "The entry type (%d) of the '%s' section isn't %d\n",
2459 shdr[i].sh_type, sh_name, expected_type );
2463 if( shdr[i].sh_entsize != expected_entsize )
2465 errorBelch( "The entry size (%d) of the '%s' section isn't %d\n",
2466 shdr[i].sh_entsize, sh_name, expected_entsize );
2474 errorBelch( "This ELF file contains no '%s' section", sh_name );
2479 findElfSectionByName( ObjectCode *oc, const char *sh_name,
2480 Elf_Word expected_type, int expected_entsize,
2483 Elf_Ehdr *ehdr = (Elf_Ehdr *) oc->image;
2484 Elf_Shdr *shdr = (Elf_Shdr *) (oc->image + ehdr->e_shoff);
2487 section = findElfSectionIndexByName( oc, sh_name, expected_type,
2493 /* allow for meaningful results in num_entries even when entsize is 0 */
2494 if( expected_entsize == 0 )
2495 expected_entsize = 1;
2498 *num_entries = shdr[section].sh_size / expected_entsize;
2500 return oc->image + shdr[section].sh_offset;
2503 #if defined(ia64_HOST_ARCH)
2505 findElfSegment ( void* objImage, Elf_Addr vaddr )
2507 char* ehdrC = (char*)objImage;
2508 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2509 Elf_Phdr* phdr = (Elf_Phdr*)(ehdrC + ehdr->e_phoff);
2510 Elf_Addr segaddr = 0;
2513 for (i = 0; i < ehdr->e_phnum; i++) {
2514 segaddr = phdr[i].p_vaddr;
2515 if ((vaddr >= segaddr) && (vaddr < segaddr + phdr[i].p_memsz))
2523 ocVerifyImage_ELF ( ObjectCode* oc )
2527 int i, j, nent, nstrtab, nsymtabs;
2531 char* ehdrC = (char*)(oc->image);
2532 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2534 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
2535 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
2536 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
2537 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
2538 errorBelch("%s: not an ELF object", oc->fileName);
2542 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
2543 errorBelch("%s: unsupported ELF format", oc->fileName);
2547 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
2548 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
2550 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
2551 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
2553 errorBelch("%s: unknown endiannness", oc->fileName);
2557 if (ehdr->e_type != ET_REL) {
2558 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
2561 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
2563 IF_DEBUG(linker,debugBelch( "Architecture is " ));
2564 switch (ehdr->e_machine) {
2565 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
2566 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
2568 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
2570 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
2571 default: IF_DEBUG(linker,debugBelch( "unknown" ));
2572 errorBelch("%s: unknown architecture", oc->fileName);
2576 IF_DEBUG(linker,debugBelch(
2577 "\nSection header table: start %d, n_entries %d, ent_size %d\n",
2578 ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
2580 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
2582 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2584 if (ehdr->e_shstrndx == SHN_UNDEF) {
2585 errorBelch("%s: no section header string table", oc->fileName);
2588 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
2590 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2593 for (i = 0; i < ehdr->e_shnum; i++) {
2594 IF_DEBUG(linker,debugBelch("%2d: ", i ));
2595 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
2596 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
2597 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
2598 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
2599 ehdrC + shdr[i].sh_offset,
2600 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
2602 if (shdr[i].sh_type == SHT_REL) {
2603 IF_DEBUG(linker,debugBelch("Rel " ));
2604 } else if (shdr[i].sh_type == SHT_RELA) {
2605 IF_DEBUG(linker,debugBelch("RelA " ));
2607 IF_DEBUG(linker,debugBelch(" "));
2610 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
2614 IF_DEBUG(linker,debugBelch( "\nString tables" ));
2617 for (i = 0; i < ehdr->e_shnum; i++) {
2618 if (shdr[i].sh_type == SHT_STRTAB
2619 /* Ignore the section header's string table. */
2620 && i != ehdr->e_shstrndx
2621 /* Ignore string tables named .stabstr, as they contain
2623 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2625 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
2626 strtab = ehdrC + shdr[i].sh_offset;
2631 errorBelch("%s: no string tables, or too many", oc->fileName);
2636 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
2637 for (i = 0; i < ehdr->e_shnum; i++) {
2638 if (shdr[i].sh_type != SHT_SYMTAB) continue;
2639 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
2641 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2642 nent = shdr[i].sh_size / sizeof(Elf_Sym);
2643 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%d rem)\n",
2645 shdr[i].sh_size % sizeof(Elf_Sym)
2647 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
2648 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
2651 for (j = 0; j < nent; j++) {
2652 IF_DEBUG(linker,debugBelch(" %2d ", j ));
2653 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
2654 (int)stab[j].st_shndx,
2655 (int)stab[j].st_size,
2656 (char*)stab[j].st_value ));
2658 IF_DEBUG(linker,debugBelch("type=" ));
2659 switch (ELF_ST_TYPE(stab[j].st_info)) {
2660 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
2661 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
2662 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
2663 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
2664 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
2665 default: IF_DEBUG(linker,debugBelch("? " )); break;
2667 IF_DEBUG(linker,debugBelch(" " ));
2669 IF_DEBUG(linker,debugBelch("bind=" ));
2670 switch (ELF_ST_BIND(stab[j].st_info)) {
2671 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
2672 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
2673 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
2674 default: IF_DEBUG(linker,debugBelch("? " )); break;
2676 IF_DEBUG(linker,debugBelch(" " ));
2678 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
2682 if (nsymtabs == 0) {
2683 errorBelch("%s: didn't find any symbol tables", oc->fileName);
2690 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
2694 if (hdr->sh_type == SHT_PROGBITS
2695 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
2696 /* .text-style section */
2697 return SECTIONKIND_CODE_OR_RODATA;
2700 if (hdr->sh_type == SHT_PROGBITS
2701 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
2702 /* .data-style section */
2703 return SECTIONKIND_RWDATA;
2706 if (hdr->sh_type == SHT_PROGBITS
2707 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
2708 /* .rodata-style section */
2709 return SECTIONKIND_CODE_OR_RODATA;
2712 if (hdr->sh_type == SHT_NOBITS
2713 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
2714 /* .bss-style section */
2716 return SECTIONKIND_RWDATA;
2719 return SECTIONKIND_OTHER;
2724 ocGetNames_ELF ( ObjectCode* oc )
2729 char* ehdrC = (char*)(oc->image);
2730 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2731 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
2732 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2734 ASSERT(symhash != NULL);
2737 errorBelch("%s: no strtab", oc->fileName);
2742 for (i = 0; i < ehdr->e_shnum; i++) {
2743 /* Figure out what kind of section it is. Logic derived from
2744 Figure 1.14 ("Special Sections") of the ELF document
2745 ("Portable Formats Specification, Version 1.1"). */
2747 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
2749 if (is_bss && shdr[i].sh_size > 0) {
2750 /* This is a non-empty .bss section. Allocate zeroed space for
2751 it, and set its .sh_offset field such that
2752 ehdrC + .sh_offset == addr_of_zeroed_space. */
2753 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
2754 "ocGetNames_ELF(BSS)");
2755 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
2757 debugBelch("BSS section at 0x%x, size %d\n",
2758 zspace, shdr[i].sh_size);
2762 /* fill in the section info */
2763 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
2764 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
2765 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
2766 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
2769 if (shdr[i].sh_type != SHT_SYMTAB) continue;
2771 /* copy stuff into this module's object symbol table */
2772 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2773 nent = shdr[i].sh_size / sizeof(Elf_Sym);
2775 oc->n_symbols = nent;
2776 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2777 "ocGetNames_ELF(oc->symbols)");
2779 for (j = 0; j < nent; j++) {
2781 char isLocal = FALSE; /* avoids uninit-var warning */
2783 char* nm = strtab + stab[j].st_name;
2784 int secno = stab[j].st_shndx;
2786 /* Figure out if we want to add it; if so, set ad to its
2787 address. Otherwise leave ad == NULL. */
2789 if (secno == SHN_COMMON) {
2791 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
2793 debugBelch("COMMON symbol, size %d name %s\n",
2794 stab[j].st_size, nm);
2796 /* Pointless to do addProddableBlock() for this area,
2797 since the linker should never poke around in it. */
2800 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
2801 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
2803 /* and not an undefined symbol */
2804 && stab[j].st_shndx != SHN_UNDEF
2805 /* and not in a "special section" */
2806 && stab[j].st_shndx < SHN_LORESERVE
2808 /* and it's a not a section or string table or anything silly */
2809 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
2810 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
2811 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
2814 /* Section 0 is the undefined section, hence > and not >=. */
2815 ASSERT(secno > 0 && secno < ehdr->e_shnum);
2817 if (shdr[secno].sh_type == SHT_NOBITS) {
2818 debugBelch(" BSS symbol, size %d off %d name %s\n",
2819 stab[j].st_size, stab[j].st_value, nm);
2822 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
2823 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
2826 #ifdef ELF_FUNCTION_DESC
2827 /* dlsym() and the initialisation table both give us function
2828 * descriptors, so to be consistent we store function descriptors
2829 * in the symbol table */
2830 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
2831 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
2833 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s",
2834 ad, oc->fileName, nm ));
2839 /* And the decision is ... */
2843 oc->symbols[j] = nm;
2846 /* Ignore entirely. */
2848 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
2852 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
2853 strtab + stab[j].st_name ));
2856 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
2857 (int)ELF_ST_BIND(stab[j].st_info),
2858 (int)ELF_ST_TYPE(stab[j].st_info),
2859 (int)stab[j].st_shndx,
2860 strtab + stab[j].st_name
2863 oc->symbols[j] = NULL;
2872 /* Do ELF relocations which lack an explicit addend. All x86-linux
2873 relocations appear to be of this form. */
2875 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
2876 Elf_Shdr* shdr, int shnum,
2877 Elf_Sym* stab, char* strtab )
2882 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
2883 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
2884 int target_shndx = shdr[shnum].sh_info;
2885 int symtab_shndx = shdr[shnum].sh_link;
2887 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2888 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
2889 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
2890 target_shndx, symtab_shndx ));
2892 /* Skip sections that we're not interested in. */
2895 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
2896 if (kind == SECTIONKIND_OTHER) {
2897 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
2902 for (j = 0; j < nent; j++) {
2903 Elf_Addr offset = rtab[j].r_offset;
2904 Elf_Addr info = rtab[j].r_info;
2906 Elf_Addr P = ((Elf_Addr)targ) + offset;
2907 Elf_Word* pP = (Elf_Word*)P;
2913 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
2914 j, (void*)offset, (void*)info ));
2916 IF_DEBUG(linker,debugBelch( " ZERO" ));
2919 Elf_Sym sym = stab[ELF_R_SYM(info)];
2920 /* First see if it is a local symbol. */
2921 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
2922 /* Yes, so we can get the address directly from the ELF symbol
2924 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
2926 (ehdrC + shdr[ sym.st_shndx ].sh_offset
2927 + stab[ELF_R_SYM(info)].st_value);
2930 /* No, so look up the name in our global table. */
2931 symbol = strtab + sym.st_name;
2932 S_tmp = lookupSymbol( symbol );
2933 S = (Elf_Addr)S_tmp;
2936 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
2939 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
2942 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
2943 (void*)P, (void*)S, (void*)A ));
2944 checkProddableBlock ( oc, pP );
2948 switch (ELF_R_TYPE(info)) {
2949 # ifdef i386_HOST_ARCH
2950 case R_386_32: *pP = value; break;
2951 case R_386_PC32: *pP = value - P; break;
2954 errorBelch("%s: unhandled ELF relocation(Rel) type %d\n",
2955 oc->fileName, ELF_R_TYPE(info));
2963 /* Do ELF relocations for which explicit addends are supplied.
2964 sparc-solaris relocations appear to be of this form. */
2966 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
2967 Elf_Shdr* shdr, int shnum,
2968 Elf_Sym* stab, char* strtab )
2973 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
2974 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
2975 int target_shndx = shdr[shnum].sh_info;
2976 int symtab_shndx = shdr[shnum].sh_link;
2978 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2979 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
2980 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
2981 target_shndx, symtab_shndx ));
2983 for (j = 0; j < nent; j++) {
2984 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH)
2985 /* This #ifdef only serves to avoid unused-var warnings. */
2986 Elf_Addr offset = rtab[j].r_offset;
2987 Elf_Addr P = targ + offset;
2989 Elf_Addr info = rtab[j].r_info;
2990 Elf_Addr A = rtab[j].r_addend;
2994 # if defined(sparc_HOST_ARCH)
2995 Elf_Word* pP = (Elf_Word*)P;
2997 # elif defined(ia64_HOST_ARCH)
2998 Elf64_Xword *pP = (Elf64_Xword *)P;
3000 # elif defined(powerpc_HOST_ARCH)
3004 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
3005 j, (void*)offset, (void*)info,
3008 IF_DEBUG(linker,debugBelch( " ZERO" ));
3011 Elf_Sym sym = stab[ELF_R_SYM(info)];
3012 /* First see if it is a local symbol. */
3013 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3014 /* Yes, so we can get the address directly from the ELF symbol
3016 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3018 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3019 + stab[ELF_R_SYM(info)].st_value);
3020 #ifdef ELF_FUNCTION_DESC
3021 /* Make a function descriptor for this function */
3022 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
3023 S = allocateFunctionDesc(S + A);
3028 /* No, so look up the name in our global table. */
3029 symbol = strtab + sym.st_name;
3030 S_tmp = lookupSymbol( symbol );
3031 S = (Elf_Addr)S_tmp;
3033 #ifdef ELF_FUNCTION_DESC
3034 /* If a function, already a function descriptor - we would
3035 have to copy it to add an offset. */
3036 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
3037 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
3041 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3044 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
3047 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
3048 (void*)P, (void*)S, (void*)A ));
3049 /* checkProddableBlock ( oc, (void*)P ); */
3053 switch (ELF_R_TYPE(info)) {
3054 # if defined(sparc_HOST_ARCH)
3055 case R_SPARC_WDISP30:
3056 w1 = *pP & 0xC0000000;
3057 w2 = (Elf_Word)((value - P) >> 2);
3058 ASSERT((w2 & 0xC0000000) == 0);
3063 w1 = *pP & 0xFFC00000;
3064 w2 = (Elf_Word)(value >> 10);
3065 ASSERT((w2 & 0xFFC00000) == 0);
3071 w2 = (Elf_Word)(value & 0x3FF);
3072 ASSERT((w2 & ~0x3FF) == 0);
3076 /* According to the Sun documentation:
3078 This relocation type resembles R_SPARC_32, except it refers to an
3079 unaligned word. That is, the word to be relocated must be treated
3080 as four separate bytes with arbitrary alignment, not as a word
3081 aligned according to the architecture requirements.
3083 (JRS: which means that freeloading on the R_SPARC_32 case
3084 is probably wrong, but hey ...)
3088 w2 = (Elf_Word)value;
3091 # elif defined(ia64_HOST_ARCH)
3092 case R_IA64_DIR64LSB:
3093 case R_IA64_FPTR64LSB:
3096 case R_IA64_PCREL64LSB:
3099 case R_IA64_SEGREL64LSB:
3100 addr = findElfSegment(ehdrC, value);
3103 case R_IA64_GPREL22:
3104 ia64_reloc_gprel22(P, value);
3106 case R_IA64_LTOFF22:
3107 case R_IA64_LTOFF22X:
3108 case R_IA64_LTOFF_FPTR22:
3109 addr = allocateGOTEntry(value);
3110 ia64_reloc_gprel22(P, addr);
3112 case R_IA64_PCREL21B:
3113 ia64_reloc_pcrel21(P, S, oc);
3116 /* This goes with R_IA64_LTOFF22X and points to the load to
3117 * convert into a move. We don't implement relaxation. */
3119 # elif defined(powerpc_HOST_ARCH)
3120 case R_PPC_ADDR16_LO:
3121 *(Elf32_Half*) P = value;
3124 case R_PPC_ADDR16_HI:
3125 *(Elf32_Half*) P = value >> 16;
3128 case R_PPC_ADDR16_HA:
3129 *(Elf32_Half*) P = (value + 0x8000) >> 16;
3133 *(Elf32_Word *) P = value;
3137 *(Elf32_Word *) P = value - P;
3143 if( delta << 6 >> 6 != delta )
3145 value = makeJumpIsland( oc, ELF_R_SYM(info), value );
3148 if( value == 0 || delta << 6 >> 6 != delta )
3150 barf( "Unable to make ppcJumpIsland for #%d",
3156 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
3157 | (delta & 0x3fffffc);
3161 errorBelch("%s: unhandled ELF relocation(RelA) type %d\n",
3162 oc->fileName, ELF_R_TYPE(info));
3171 ocResolve_ELF ( ObjectCode* oc )
3175 Elf_Sym* stab = NULL;
3176 char* ehdrC = (char*)(oc->image);
3177 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
3178 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3180 /* first find "the" symbol table */
3181 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
3183 /* also go find the string table */
3184 strtab = findElfSection ( ehdrC, SHT_STRTAB );
3186 if (stab == NULL || strtab == NULL) {
3187 errorBelch("%s: can't find string or symbol table", oc->fileName);
3191 /* Process the relocation sections. */
3192 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
3193 if (shdr[shnum].sh_type == SHT_REL) {
3194 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
3195 shnum, stab, strtab );
3199 if (shdr[shnum].sh_type == SHT_RELA) {
3200 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
3201 shnum, stab, strtab );
3206 /* Free the local symbol table; we won't need it again. */
3207 freeHashTable(oc->lochash, NULL);
3210 #if defined(powerpc_HOST_ARCH)
3211 ocFlushInstructionCache( oc );
3219 * Instructions are 41 bits long, packed into 128 bit bundles with a 5-bit template
3220 * at the front. The following utility functions pack and unpack instructions, and
3221 * take care of the most common relocations.
3224 #ifdef ia64_HOST_ARCH
3227 ia64_extract_instruction(Elf64_Xword *target)
3230 int slot = (Elf_Addr)target & 3;
3231 (Elf_Addr)target &= ~3;
3239 return ((w1 >> 5) & 0x1ffffffffff);
3241 return (w1 >> 46) | ((w2 & 0x7fffff) << 18);
3245 barf("ia64_extract_instruction: invalid slot %p", target);
3250 ia64_deposit_instruction(Elf64_Xword *target, Elf64_Xword value)
3252 int slot = (Elf_Addr)target & 3;
3253 (Elf_Addr)target &= ~3;
3258 *target |= value << 5;
3261 *target |= value << 46;
3262 *(target+1) |= value >> 18;
3265 *(target+1) |= value << 23;
3271 ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value)
3273 Elf64_Xword instruction;
3274 Elf64_Sxword rel_value;
3276 rel_value = value - gp_val;
3277 if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff))
3278 barf("GP-relative data out of range (address = 0x%lx, gp = 0x%lx)", value, gp_val);
3280 instruction = ia64_extract_instruction((Elf64_Xword *)target);
3281 instruction |= (((rel_value >> 0) & 0x07f) << 13) /* imm7b */
3282 | (((rel_value >> 7) & 0x1ff) << 27) /* imm9d */
3283 | (((rel_value >> 16) & 0x01f) << 22) /* imm5c */
3284 | ((Elf64_Xword)(rel_value < 0) << 36); /* s */
3285 ia64_deposit_instruction((Elf64_Xword *)target, instruction);
3289 ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc)
3291 Elf64_Xword instruction;
3292 Elf64_Sxword rel_value;
3295 entry = allocatePLTEntry(value, oc);
3297 rel_value = (entry >> 4) - (target >> 4);
3298 if ((rel_value > 0xfffff) || (rel_value < -0xfffff))
3299 barf("PLT entry too far away (entry = 0x%lx, target = 0x%lx)", entry, target);
3301 instruction = ia64_extract_instruction((Elf64_Xword *)target);
3302 instruction |= ((rel_value & 0xfffff) << 13) /* imm20b */
3303 | ((Elf64_Xword)(rel_value < 0) << 36); /* s */
3304 ia64_deposit_instruction((Elf64_Xword *)target, instruction);
3310 * PowerPC ELF specifics
3313 #ifdef powerpc_HOST_ARCH
3315 static int ocAllocateJumpIslands_ELF( ObjectCode *oc )
3321 ehdr = (Elf_Ehdr *) oc->image;
3322 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
3324 for( i = 0; i < ehdr->e_shnum; i++ )
3325 if( shdr[i].sh_type == SHT_SYMTAB )
3328 if( i == ehdr->e_shnum )
3330 errorBelch( "This ELF file contains no symtab" );
3334 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
3336 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
3337 shdr[i].sh_entsize, sizeof( Elf_Sym ) );
3342 return ocAllocateJumpIslands( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
3345 #endif /* powerpc */
3349 /* --------------------------------------------------------------------------
3351 * ------------------------------------------------------------------------*/
3353 #if defined(OBJFORMAT_MACHO)
3356 Support for MachO linking on Darwin/MacOS X on PowerPC chips
3357 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
3359 I hereby formally apologize for the hackish nature of this code.
3360 Things that need to be done:
3361 *) implement ocVerifyImage_MachO
3362 *) add still more sanity checks.
3365 static int ocAllocateJumpIslands_MachO(ObjectCode* oc)
3367 struct mach_header *header = (struct mach_header *) oc->image;
3368 struct load_command *lc = (struct load_command *) (header + 1);
3371 for( i = 0; i < header->ncmds; i++ )
3373 if( lc->cmd == LC_SYMTAB )
3375 // Find out the first and last undefined external
3376 // symbol, so we don't have to allocate too many
3378 struct symtab_command *symLC = (struct symtab_command *) lc;
3379 int min = symLC->nsyms, max = 0;
3380 struct nlist *nlist =
3381 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
3383 for(i=0;i<symLC->nsyms;i++)
3385 if(nlist[i].n_type & N_STAB)
3387 else if(nlist[i].n_type & N_EXT)
3389 if((nlist[i].n_type & N_TYPE) == N_UNDF
3390 && (nlist[i].n_value == 0))
3400 return ocAllocateJumpIslands(oc, max - min + 1, min);
3405 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3407 return ocAllocateJumpIslands(oc,0,0);
3410 static int ocVerifyImage_MachO(ObjectCode* oc)
3412 // FIXME: do some verifying here
3416 static int resolveImports(
3419 struct symtab_command *symLC,
3420 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
3421 unsigned long *indirectSyms,
3422 struct nlist *nlist)
3426 for(i=0;i*4<sect->size;i++)
3428 // according to otool, reserved1 contains the first index into the indirect symbol table
3429 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
3430 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3433 if((symbol->n_type & N_TYPE) == N_UNDF
3434 && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
3435 addr = (void*) (symbol->n_value);
3436 else if((addr = lookupLocalSymbol(oc,nm)) != NULL)
3439 addr = lookupSymbol(nm);
3442 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
3446 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
3447 ((void**)(image + sect->offset))[i] = addr;
3453 static char* relocateAddress(
3456 struct section* sections,
3457 unsigned long address)
3460 for(i = 0; i < nSections; i++)
3462 if(sections[i].addr <= address
3463 && address < sections[i].addr + sections[i].size)
3465 return oc->image + sections[i].offset + address - sections[i].addr;
3468 barf("Invalid Mach-O file:"
3469 "Address out of bounds while relocating object file");
3473 static int relocateSection(
3476 struct symtab_command *symLC, struct nlist *nlist,
3477 int nSections, struct section* sections, struct section *sect)
3479 struct relocation_info *relocs;
3482 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
3484 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
3488 relocs = (struct relocation_info*) (image + sect->reloff);
3492 if(relocs[i].r_address & R_SCATTERED)
3494 struct scattered_relocation_info *scat =
3495 (struct scattered_relocation_info*) &relocs[i];
3499 if(scat->r_length == 2)
3501 unsigned long word = 0;
3502 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
3503 checkProddableBlock(oc,wordPtr);
3505 // Step 1: Figure out what the relocated value should be
3506 if(scat->r_type == GENERIC_RELOC_VANILLA)
3508 word = *wordPtr + (unsigned long) relocateAddress(
3515 else if(scat->r_type == PPC_RELOC_SECTDIFF
3516 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
3517 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
3518 || scat->r_type == PPC_RELOC_HA16_SECTDIFF)
3520 struct scattered_relocation_info *pair =
3521 (struct scattered_relocation_info*) &relocs[i+1];
3523 if(!pair->r_scattered || pair->r_type != PPC_RELOC_PAIR)
3524 barf("Invalid Mach-O file: "
3525 "PPC_RELOC_*_SECTDIFF not followed by PPC_RELOC_PAIR");
3527 word = (unsigned long)
3528 (relocateAddress(oc, nSections, sections, scat->r_value)
3529 - relocateAddress(oc, nSections, sections, pair->r_value));
3532 else if(scat->r_type == PPC_RELOC_HI16
3533 || scat->r_type == PPC_RELOC_LO16
3534 || scat->r_type == PPC_RELOC_HA16
3535 || scat->r_type == PPC_RELOC_LO14)
3536 { // these are generated by label+offset things
3537 struct relocation_info *pair = &relocs[i+1];
3538 if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
3539 barf("Invalid Mach-O file: "
3540 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
3542 if(scat->r_type == PPC_RELOC_LO16)
3544 word = ((unsigned short*) wordPtr)[1];
3545 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3547 else if(scat->r_type == PPC_RELOC_LO14)
3549 barf("Unsupported Relocation: PPC_RELOC_LO14");
3550 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
3551 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3553 else if(scat->r_type == PPC_RELOC_HI16)
3555 word = ((unsigned short*) wordPtr)[1] << 16;
3556 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
3558 else if(scat->r_type == PPC_RELOC_HA16)
3560 word = ((unsigned short*) wordPtr)[1] << 16;
3561 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
3565 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
3571 continue; // ignore the others
3573 if(scat->r_type == GENERIC_RELOC_VANILLA
3574 || scat->r_type == PPC_RELOC_SECTDIFF)
3578 else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
3580 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
3582 else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
3584 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
3586 else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
3588 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
3589 + ((word & (1<<15)) ? 1 : 0);
3594 continue; // FIXME: I hope it's OK to ignore all the others.
3598 struct relocation_info *reloc = &relocs[i];
3599 if(reloc->r_pcrel && !reloc->r_extern)
3602 if(reloc->r_length == 2)
3604 unsigned long word = 0;
3605 unsigned long jumpIsland = 0;
3606 long offsetToJumpIsland;
3608 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
3609 checkProddableBlock(oc,wordPtr);
3611 if(reloc->r_type == GENERIC_RELOC_VANILLA)
3615 else if(reloc->r_type == PPC_RELOC_LO16)
3617 word = ((unsigned short*) wordPtr)[1];
3618 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3620 else if(reloc->r_type == PPC_RELOC_HI16)
3622 word = ((unsigned short*) wordPtr)[1] << 16;
3623 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
3625 else if(reloc->r_type == PPC_RELOC_HA16)
3627 word = ((unsigned short*) wordPtr)[1] << 16;
3628 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
3630 else if(reloc->r_type == PPC_RELOC_BR24)
3633 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
3637 if(!reloc->r_extern)
3640 sections[reloc->r_symbolnum-1].offset
3641 - sections[reloc->r_symbolnum-1].addr
3648 struct nlist *symbol = &nlist[reloc->r_symbolnum];
3649 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3650 unsigned long symbolAddress = (unsigned long) (lookupSymbol(nm));
3653 errorBelch("\nunknown symbol `%s'", nm);
3659 // In the .o file, this should be a relative jump to NULL
3660 // and we'll change it to a jump to a relative jump to the symbol
3661 ASSERT(-word == reloc->r_address);
3662 word = symbolAddress;
3663 jumpIsland = makeJumpIsland(oc,reloc->r_symbolnum,word);
3664 word -= ((long)image) + sect->offset + reloc->r_address;
3667 offsetToJumpIsland = jumpIsland
3668 - (((long)image) + sect->offset + reloc->r_address);
3673 word += symbolAddress;
3677 if(reloc->r_type == GENERIC_RELOC_VANILLA)
3682 else if(reloc->r_type == PPC_RELOC_LO16)
3684 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
3687 else if(reloc->r_type == PPC_RELOC_HI16)
3689 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
3692 else if(reloc->r_type == PPC_RELOC_HA16)
3694 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
3695 + ((word & (1<<15)) ? 1 : 0);
3698 else if(reloc->r_type == PPC_RELOC_BR24)
3700 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
3702 // The branch offset is too large.
3703 // Therefore, we try to use a jump island.
3706 barf("unconditional relative branch out of range: "
3707 "no jump island available");
3710 word = offsetToJumpIsland;
3711 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
3712 barf("unconditional relative branch out of range: "
3713 "jump island out of range");
3715 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
3719 barf("\nunknown relocation %d",reloc->r_type);
3726 static int ocGetNames_MachO(ObjectCode* oc)
3728 char *image = (char*) oc->image;
3729 struct mach_header *header = (struct mach_header*) image;
3730 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3731 unsigned i,curSymbol;
3732 struct segment_command *segLC = NULL;
3733 struct section *sections;
3734 struct symtab_command *symLC = NULL;
3735 struct nlist *nlist;
3736 unsigned long commonSize = 0;
3737 char *commonStorage = NULL;
3738 unsigned long commonCounter;
3740 for(i=0;i<header->ncmds;i++)
3742 if(lc->cmd == LC_SEGMENT)
3743 segLC = (struct segment_command*) lc;
3744 else if(lc->cmd == LC_SYMTAB)
3745 symLC = (struct symtab_command*) lc;
3746 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3749 sections = (struct section*) (segLC+1);
3750 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
3753 for(i=0;i<segLC->nsects;i++)
3755 if(sections[i].size == 0)
3758 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
3760 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
3761 "ocGetNames_MachO(common symbols)");
3762 sections[i].offset = zeroFillArea - image;
3765 if(!strcmp(sections[i].sectname,"__text"))
3766 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
3767 (void*) (image + sections[i].offset),
3768 (void*) (image + sections[i].offset + sections[i].size));
3769 else if(!strcmp(sections[i].sectname,"__const"))
3770 addSection(oc, SECTIONKIND_RWDATA,
3771 (void*) (image + sections[i].offset),
3772 (void*) (image + sections[i].offset + sections[i].size));
3773 else if(!strcmp(sections[i].sectname,"__data"))
3774 addSection(oc, SECTIONKIND_RWDATA,
3775 (void*) (image + sections[i].offset),
3776 (void*) (image + sections[i].offset + sections[i].size));
3777 else if(!strcmp(sections[i].sectname,"__bss")
3778 || !strcmp(sections[i].sectname,"__common"))
3779 addSection(oc, SECTIONKIND_RWDATA,
3780 (void*) (image + sections[i].offset),
3781 (void*) (image + sections[i].offset + sections[i].size));
3783 addProddableBlock(oc, (void*) (image + sections[i].offset),
3787 // count external symbols defined here
3791 for(i=0;i<symLC->nsyms;i++)
3793 if(nlist[i].n_type & N_STAB)
3795 else if(nlist[i].n_type & N_EXT)
3797 if((nlist[i].n_type & N_TYPE) == N_UNDF
3798 && (nlist[i].n_value != 0))
3800 commonSize += nlist[i].n_value;
3803 else if((nlist[i].n_type & N_TYPE) == N_SECT)
3808 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3809 "ocGetNames_MachO(oc->symbols)");
3814 for(i=0;i<symLC->nsyms;i++)
3816 if(nlist[i].n_type & N_STAB)
3818 else if((nlist[i].n_type & N_TYPE) == N_SECT)
3820 if(nlist[i].n_type & N_EXT)
3822 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3823 ghciInsertStrHashTable(oc->fileName, symhash, nm,
3825 + sections[nlist[i].n_sect-1].offset
3826 - sections[nlist[i].n_sect-1].addr
3827 + nlist[i].n_value);
3828 oc->symbols[curSymbol++] = nm;
3832 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3833 ghciInsertStrHashTable(oc->fileName, oc->lochash, nm,
3835 + sections[nlist[i].n_sect-1].offset
3836 - sections[nlist[i].n_sect-1].addr
3837 + nlist[i].n_value);
3843 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
3844 commonCounter = (unsigned long)commonStorage;
3847 for(i=0;i<symLC->nsyms;i++)
3849 if((nlist[i].n_type & N_TYPE) == N_UNDF
3850 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
3852 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3853 unsigned long sz = nlist[i].n_value;
3855 nlist[i].n_value = commonCounter;
3857 ghciInsertStrHashTable(oc->fileName, symhash, nm,
3858 (void*)commonCounter);
3859 oc->symbols[curSymbol++] = nm;
3861 commonCounter += sz;
3868 static int ocResolve_MachO(ObjectCode* oc)
3870 char *image = (char*) oc->image;
3871 struct mach_header *header = (struct mach_header*) image;
3872 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3874 struct segment_command *segLC = NULL;
3875 struct section *sections, *la_ptrs = NULL, *nl_ptrs = NULL;
3876 struct symtab_command *symLC = NULL;
3877 struct dysymtab_command *dsymLC = NULL;
3878 struct nlist *nlist;
3880 for(i=0;i<header->ncmds;i++)
3882 if(lc->cmd == LC_SEGMENT)
3883 segLC = (struct segment_command*) lc;
3884 else if(lc->cmd == LC_SYMTAB)
3885 symLC = (struct symtab_command*) lc;
3886 else if(lc->cmd == LC_DYSYMTAB)
3887 dsymLC = (struct dysymtab_command*) lc;
3888 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3891 sections = (struct section*) (segLC+1);
3892 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
3895 for(i=0;i<segLC->nsects;i++)
3897 if(!strcmp(sections[i].sectname,"__la_symbol_ptr"))
3898 la_ptrs = §ions[i];
3899 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr"))
3900 nl_ptrs = §ions[i];
3905 unsigned long *indirectSyms
3906 = (unsigned long*) (image + dsymLC->indirectsymoff);
3909 if(!resolveImports(oc,image,symLC,la_ptrs,indirectSyms,nlist))
3912 if(!resolveImports(oc,image,symLC,nl_ptrs,indirectSyms,nlist))
3916 for(i=0;i<segLC->nsects;i++)
3918 if(!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
3922 /* Free the local symbol table; we won't need it again. */
3923 freeHashTable(oc->lochash, NULL);
3926 #if defined (powerpc_HOST_ARCH)
3927 ocFlushInstructionCache( oc );
3934 * The Mach-O object format uses leading underscores. But not everywhere.
3935 * There is a small number of runtime support functions defined in
3936 * libcc_dynamic.a whose name does not have a leading underscore.
3937 * As a consequence, we can't get their address from C code.
3938 * We have to use inline assembler just to take the address of a function.
3942 static void machoInitSymbolsWithoutUnderscore()
3944 extern void* symbolsWithoutUnderscore[];
3945 void **p = symbolsWithoutUnderscore;
3946 __asm__ volatile(".data\n_symbolsWithoutUnderscore:");
3950 __asm__ volatile(".long " # x);
3952 RTS_MACHO_NOUNDERLINE_SYMBOLS
3954 __asm__ volatile(".text");
3958 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
3960 RTS_MACHO_NOUNDERLINE_SYMBOLS