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>.
16 #if defined(__linux__) || defined(__GLIBC__)
23 #include "sm/Storage.h"
26 #include "LinkerInternals.h"
29 #include "StgPrimFloat.h" // for __int_encodeFloat etc.
32 #if !defined(mingw32_HOST_OS)
33 #include "posix/Signals.h"
36 // get protos for is*()
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
49 #ifdef HAVE_SYS_STAT_H
53 #if defined(HAVE_DLFCN_H)
57 #if defined(cygwin32_HOST_OS)
62 #ifdef HAVE_SYS_TIME_H
66 #include <sys/fcntl.h>
67 #include <sys/termios.h>
68 #include <sys/utime.h>
69 #include <sys/utsname.h>
73 #if defined(linux_HOST_OS ) || defined(freebsd_HOST_OS) || \
74 defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS ) || \
75 defined(openbsd_HOST_OS ) || \
76 ( defined(darwin_HOST_OS ) && !defined(powerpc_HOST_ARCH) ) || \
77 defined(kfreebsdgnu_HOST_OS)
78 /* Don't use mmap on powerpc-apple-darwin as mmap doesn't support
79 * reallocating but we need to allocate jump islands just after each
80 * object images. Otherwise relative branches to jump islands can fail
81 * due to 24-bits displacement overflow.
93 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
94 # define OBJFORMAT_ELF
95 # include <regex.h> // regex is already used by dlopen() so this is OK
96 // to use here without requiring an additional lib
97 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
98 # define OBJFORMAT_PEi386
101 #elif defined(darwin_HOST_OS)
102 # define OBJFORMAT_MACHO
104 # include <mach/machine.h>
105 # include <mach-o/fat.h>
106 # include <mach-o/loader.h>
107 # include <mach-o/nlist.h>
108 # include <mach-o/reloc.h>
109 #if !defined(HAVE_DLFCN_H)
110 # include <mach-o/dyld.h>
112 #if defined(powerpc_HOST_ARCH)
113 # include <mach-o/ppc/reloc.h>
115 #if defined(x86_64_HOST_ARCH)
116 # include <mach-o/x86_64/reloc.h>
120 #if defined(x86_64_HOST_ARCH) && defined(darwin_HOST_OS)
124 /* Hash table mapping symbol names to Symbol */
125 static /*Str*/HashTable *symhash;
127 /* Hash table mapping symbol names to StgStablePtr */
128 static /*Str*/HashTable *stablehash;
130 /* List of currently loaded objects */
131 ObjectCode *objects = NULL; /* initially empty */
133 static HsInt loadOc( ObjectCode* oc );
134 static ObjectCode* mkOc( char *path, char *image, int imageSize,
135 char *archiveMemberName
137 #ifdef darwin_HOST_OS
143 #if defined(OBJFORMAT_ELF)
144 static int ocVerifyImage_ELF ( ObjectCode* oc );
145 static int ocGetNames_ELF ( ObjectCode* oc );
146 static int ocResolve_ELF ( ObjectCode* oc );
147 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
148 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
150 #elif defined(OBJFORMAT_PEi386)
151 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
152 static int ocGetNames_PEi386 ( ObjectCode* oc );
153 static int ocResolve_PEi386 ( ObjectCode* oc );
154 static void *lookupSymbolInDLLs ( unsigned char *lbl );
155 static void zapTrailingAtSign ( unsigned char *sym );
156 #elif defined(OBJFORMAT_MACHO)
157 static int ocVerifyImage_MachO ( ObjectCode* oc );
158 static int ocGetNames_MachO ( ObjectCode* oc );
159 static int ocResolve_MachO ( ObjectCode* oc );
162 static int machoGetMisalignment( FILE * );
164 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
165 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
167 #ifdef powerpc_HOST_ARCH
168 static void machoInitSymbolsWithoutUnderscore( void );
172 /* on x86_64 we have a problem with relocating symbol references in
173 * code that was compiled without -fPIC. By default, the small memory
174 * model is used, which assumes that symbol references can fit in a
175 * 32-bit slot. The system dynamic linker makes this work for
176 * references to shared libraries by either (a) allocating a jump
177 * table slot for code references, or (b) moving the symbol at load
178 * time (and copying its contents, if necessary) for data references.
180 * We unfortunately can't tell whether symbol references are to code
181 * or data. So for now we assume they are code (the vast majority
182 * are), and allocate jump-table slots. Unfortunately this will
183 * SILENTLY generate crashing code for data references. This hack is
184 * enabled by X86_64_ELF_NONPIC_HACK.
186 * One workaround is to use shared Haskell libraries. This is
187 * coming. Another workaround is to keep the static libraries but
188 * compile them with -fPIC, because that will generate PIC references
189 * to data which can be relocated. The PIC code is still too green to
190 * do this systematically, though.
193 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
195 * Naming Scheme for Symbol Macros
197 * SymI_*: symbol is internal to the RTS. It resides in an object
198 * file/library that is statically.
199 * SymE_*: symbol is external to the RTS library. It might be linked
202 * Sym*_HasProto : the symbol prototype is imported in an include file
203 * or defined explicitly
204 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
205 * default proto extern void sym(void);
207 #define X86_64_ELF_NONPIC_HACK 1
209 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
210 * small memory model on this architecture (see gcc docs,
213 * MAP_32BIT not available on OpenBSD/amd64
215 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
216 #define TRY_MAP_32BIT MAP_32BIT
218 #define TRY_MAP_32BIT 0
222 * Due to the small memory model (see above), on x86_64 we have to map
223 * all our non-PIC object files into the low 2Gb of the address space
224 * (why 2Gb and not 4Gb? Because all addresses must be reachable
225 * using a 32-bit signed PC-relative offset). On Linux we can do this
226 * using the MAP_32BIT flag to mmap(), however on other OSs
227 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
228 * can't do this. So on these systems, we have to pick a base address
229 * in the low 2Gb of the address space and try to allocate memory from
232 * We pick a default address based on the OS, but also make this
233 * configurable via an RTS flag (+RTS -xm)
235 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
237 #if defined(MAP_32BIT)
238 // Try to use MAP_32BIT
239 #define MMAP_32BIT_BASE_DEFAULT 0
242 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
245 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
248 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
249 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
250 #define MAP_ANONYMOUS MAP_ANON
253 /* -----------------------------------------------------------------------------
254 * Built-in symbols from the RTS
257 typedef struct _RtsSymbolVal {
262 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
263 SymI_HasProto(stg_mkWeakForeignEnvzh) \
264 SymI_HasProto(stg_makeStableNamezh) \
265 SymI_HasProto(stg_finalizzeWeakzh)
267 #if !defined (mingw32_HOST_OS)
268 #define RTS_POSIX_ONLY_SYMBOLS \
269 SymI_HasProto(__hscore_get_saved_termios) \
270 SymI_HasProto(__hscore_set_saved_termios) \
271 SymI_HasProto(shutdownHaskellAndSignal) \
272 SymI_HasProto(lockFile) \
273 SymI_HasProto(unlockFile) \
274 SymI_HasProto(signal_handlers) \
275 SymI_HasProto(stg_sig_install) \
276 SymI_HasProto(rtsTimerSignal) \
277 SymI_HasProto(atexit) \
278 SymI_NeedsProto(nocldstop)
281 #if defined (cygwin32_HOST_OS)
282 #define RTS_MINGW_ONLY_SYMBOLS /**/
283 /* Don't have the ability to read import libs / archives, so
284 * we have to stupidly list a lot of what libcygwin.a
287 #define RTS_CYGWIN_ONLY_SYMBOLS \
288 SymI_HasProto(regfree) \
289 SymI_HasProto(regexec) \
290 SymI_HasProto(regerror) \
291 SymI_HasProto(regcomp) \
292 SymI_HasProto(__errno) \
293 SymI_HasProto(access) \
294 SymI_HasProto(chmod) \
295 SymI_HasProto(chdir) \
296 SymI_HasProto(close) \
297 SymI_HasProto(creat) \
299 SymI_HasProto(dup2) \
300 SymI_HasProto(fstat) \
301 SymI_HasProto(fcntl) \
302 SymI_HasProto(getcwd) \
303 SymI_HasProto(getenv) \
304 SymI_HasProto(lseek) \
305 SymI_HasProto(open) \
306 SymI_HasProto(fpathconf) \
307 SymI_HasProto(pathconf) \
308 SymI_HasProto(stat) \
310 SymI_HasProto(tanh) \
311 SymI_HasProto(cosh) \
312 SymI_HasProto(sinh) \
313 SymI_HasProto(atan) \
314 SymI_HasProto(acos) \
315 SymI_HasProto(asin) \
321 SymI_HasProto(sqrt) \
322 SymI_HasProto(localtime_r) \
323 SymI_HasProto(gmtime_r) \
324 SymI_HasProto(mktime) \
325 SymI_NeedsProto(_imp___tzname) \
326 SymI_HasProto(gettimeofday) \
327 SymI_HasProto(timezone) \
328 SymI_HasProto(tcgetattr) \
329 SymI_HasProto(tcsetattr) \
330 SymI_HasProto(memcpy) \
331 SymI_HasProto(memmove) \
332 SymI_HasProto(realloc) \
333 SymI_HasProto(malloc) \
334 SymI_HasProto(free) \
335 SymI_HasProto(fork) \
336 SymI_HasProto(lstat) \
337 SymI_HasProto(isatty) \
338 SymI_HasProto(mkdir) \
339 SymI_HasProto(opendir) \
340 SymI_HasProto(readdir) \
341 SymI_HasProto(rewinddir) \
342 SymI_HasProto(closedir) \
343 SymI_HasProto(link) \
344 SymI_HasProto(mkfifo) \
345 SymI_HasProto(pipe) \
346 SymI_HasProto(read) \
347 SymI_HasProto(rename) \
348 SymI_HasProto(rmdir) \
349 SymI_HasProto(select) \
350 SymI_HasProto(system) \
351 SymI_HasProto(write) \
352 SymI_HasProto(strcmp) \
353 SymI_HasProto(strcpy) \
354 SymI_HasProto(strncpy) \
355 SymI_HasProto(strerror) \
356 SymI_HasProto(sigaddset) \
357 SymI_HasProto(sigemptyset) \
358 SymI_HasProto(sigprocmask) \
359 SymI_HasProto(umask) \
360 SymI_HasProto(uname) \
361 SymI_HasProto(unlink) \
362 SymI_HasProto(utime) \
363 SymI_HasProto(waitpid)
365 #elif !defined(mingw32_HOST_OS)
366 #define RTS_MINGW_ONLY_SYMBOLS /**/
367 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
368 #else /* defined(mingw32_HOST_OS) */
369 #define RTS_POSIX_ONLY_SYMBOLS /**/
370 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
372 #if HAVE_GETTIMEOFDAY
373 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
375 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
378 #if HAVE___MINGW_VFPRINTF
379 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
381 #define RTS___MINGW_VFPRINTF_SYM /**/
384 /* These are statically linked from the mingw libraries into the ghc
385 executable, so we have to employ this hack. */
386 #define RTS_MINGW_ONLY_SYMBOLS \
387 SymI_HasProto(stg_asyncReadzh) \
388 SymI_HasProto(stg_asyncWritezh) \
389 SymI_HasProto(stg_asyncDoProczh) \
390 SymI_HasProto(memset) \
391 SymI_HasProto(inet_ntoa) \
392 SymI_HasProto(inet_addr) \
393 SymI_HasProto(htonl) \
394 SymI_HasProto(recvfrom) \
395 SymI_HasProto(listen) \
396 SymI_HasProto(bind) \
397 SymI_HasProto(shutdown) \
398 SymI_HasProto(connect) \
399 SymI_HasProto(htons) \
400 SymI_HasProto(ntohs) \
401 SymI_HasProto(getservbyname) \
402 SymI_HasProto(getservbyport) \
403 SymI_HasProto(getprotobynumber) \
404 SymI_HasProto(getprotobyname) \
405 SymI_HasProto(gethostbyname) \
406 SymI_HasProto(gethostbyaddr) \
407 SymI_HasProto(gethostname) \
408 SymI_HasProto(strcpy) \
409 SymI_HasProto(strncpy) \
410 SymI_HasProto(abort) \
411 SymI_NeedsProto(_alloca) \
412 SymI_HasProto(isxdigit) \
413 SymI_HasProto(isupper) \
414 SymI_HasProto(ispunct) \
415 SymI_HasProto(islower) \
416 SymI_HasProto(isspace) \
417 SymI_HasProto(isprint) \
418 SymI_HasProto(isdigit) \
419 SymI_HasProto(iscntrl) \
420 SymI_HasProto(isalpha) \
421 SymI_HasProto(isalnum) \
422 SymI_HasProto(isascii) \
423 RTS___MINGW_VFPRINTF_SYM \
424 SymI_HasProto(strcmp) \
425 SymI_HasProto(memmove) \
426 SymI_HasProto(realloc) \
427 SymI_HasProto(malloc) \
429 SymI_HasProto(tanh) \
430 SymI_HasProto(cosh) \
431 SymI_HasProto(sinh) \
432 SymI_HasProto(atan) \
433 SymI_HasProto(acos) \
434 SymI_HasProto(asin) \
440 SymI_HasProto(sqrt) \
441 SymI_HasProto(powf) \
442 SymI_HasProto(tanhf) \
443 SymI_HasProto(coshf) \
444 SymI_HasProto(sinhf) \
445 SymI_HasProto(atanf) \
446 SymI_HasProto(acosf) \
447 SymI_HasProto(asinf) \
448 SymI_HasProto(tanf) \
449 SymI_HasProto(cosf) \
450 SymI_HasProto(sinf) \
451 SymI_HasProto(expf) \
452 SymI_HasProto(logf) \
453 SymI_HasProto(sqrtf) \
455 SymI_HasProto(erfc) \
456 SymI_HasProto(erff) \
457 SymI_HasProto(erfcf) \
458 SymI_HasProto(memcpy) \
459 SymI_HasProto(rts_InstallConsoleEvent) \
460 SymI_HasProto(rts_ConsoleHandlerDone) \
461 SymI_NeedsProto(mktime) \
462 SymI_NeedsProto(_imp___timezone) \
463 SymI_NeedsProto(_imp___tzname) \
464 SymI_NeedsProto(_imp__tzname) \
465 SymI_NeedsProto(_imp___iob) \
466 SymI_NeedsProto(_imp___osver) \
467 SymI_NeedsProto(localtime) \
468 SymI_NeedsProto(gmtime) \
469 SymI_NeedsProto(opendir) \
470 SymI_NeedsProto(readdir) \
471 SymI_NeedsProto(rewinddir) \
472 SymI_NeedsProto(_imp____mb_cur_max) \
473 SymI_NeedsProto(_imp___pctype) \
474 SymI_NeedsProto(__chkstk) \
475 RTS_MINGW_GETTIMEOFDAY_SYM \
476 SymI_NeedsProto(closedir)
480 #if defined(darwin_HOST_OS) && HAVE_PRINTF_LDBLSTUB
481 #define RTS_DARWIN_ONLY_SYMBOLS \
482 SymI_NeedsProto(asprintf$LDBLStub) \
483 SymI_NeedsProto(err$LDBLStub) \
484 SymI_NeedsProto(errc$LDBLStub) \
485 SymI_NeedsProto(errx$LDBLStub) \
486 SymI_NeedsProto(fprintf$LDBLStub) \
487 SymI_NeedsProto(fscanf$LDBLStub) \
488 SymI_NeedsProto(fwprintf$LDBLStub) \
489 SymI_NeedsProto(fwscanf$LDBLStub) \
490 SymI_NeedsProto(printf$LDBLStub) \
491 SymI_NeedsProto(scanf$LDBLStub) \
492 SymI_NeedsProto(snprintf$LDBLStub) \
493 SymI_NeedsProto(sprintf$LDBLStub) \
494 SymI_NeedsProto(sscanf$LDBLStub) \
495 SymI_NeedsProto(strtold$LDBLStub) \
496 SymI_NeedsProto(swprintf$LDBLStub) \
497 SymI_NeedsProto(swscanf$LDBLStub) \
498 SymI_NeedsProto(syslog$LDBLStub) \
499 SymI_NeedsProto(vasprintf$LDBLStub) \
500 SymI_NeedsProto(verr$LDBLStub) \
501 SymI_NeedsProto(verrc$LDBLStub) \
502 SymI_NeedsProto(verrx$LDBLStub) \
503 SymI_NeedsProto(vfprintf$LDBLStub) \
504 SymI_NeedsProto(vfscanf$LDBLStub) \
505 SymI_NeedsProto(vfwprintf$LDBLStub) \
506 SymI_NeedsProto(vfwscanf$LDBLStub) \
507 SymI_NeedsProto(vprintf$LDBLStub) \
508 SymI_NeedsProto(vscanf$LDBLStub) \
509 SymI_NeedsProto(vsnprintf$LDBLStub) \
510 SymI_NeedsProto(vsprintf$LDBLStub) \
511 SymI_NeedsProto(vsscanf$LDBLStub) \
512 SymI_NeedsProto(vswprintf$LDBLStub) \
513 SymI_NeedsProto(vswscanf$LDBLStub) \
514 SymI_NeedsProto(vsyslog$LDBLStub) \
515 SymI_NeedsProto(vwarn$LDBLStub) \
516 SymI_NeedsProto(vwarnc$LDBLStub) \
517 SymI_NeedsProto(vwarnx$LDBLStub) \
518 SymI_NeedsProto(vwprintf$LDBLStub) \
519 SymI_NeedsProto(vwscanf$LDBLStub) \
520 SymI_NeedsProto(warn$LDBLStub) \
521 SymI_NeedsProto(warnc$LDBLStub) \
522 SymI_NeedsProto(warnx$LDBLStub) \
523 SymI_NeedsProto(wcstold$LDBLStub) \
524 SymI_NeedsProto(wprintf$LDBLStub) \
525 SymI_NeedsProto(wscanf$LDBLStub)
527 #define RTS_DARWIN_ONLY_SYMBOLS
531 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
533 # define MAIN_CAP_SYM
536 #if !defined(mingw32_HOST_OS)
537 #define RTS_USER_SIGNALS_SYMBOLS \
538 SymI_HasProto(setIOManagerControlFd) \
539 SymI_HasProto(setIOManagerWakeupFd) \
540 SymI_HasProto(ioManagerWakeup) \
541 SymI_HasProto(blockUserSignals) \
542 SymI_HasProto(unblockUserSignals)
544 #define RTS_USER_SIGNALS_SYMBOLS \
545 SymI_HasProto(ioManagerWakeup) \
546 SymI_HasProto(sendIOManagerEvent) \
547 SymI_HasProto(readIOManagerEvent) \
548 SymI_HasProto(getIOManagerEvent) \
549 SymI_HasProto(console_handler)
552 #define RTS_LIBFFI_SYMBOLS \
553 SymE_NeedsProto(ffi_prep_cif) \
554 SymE_NeedsProto(ffi_call) \
555 SymE_NeedsProto(ffi_type_void) \
556 SymE_NeedsProto(ffi_type_float) \
557 SymE_NeedsProto(ffi_type_double) \
558 SymE_NeedsProto(ffi_type_sint64) \
559 SymE_NeedsProto(ffi_type_uint64) \
560 SymE_NeedsProto(ffi_type_sint32) \
561 SymE_NeedsProto(ffi_type_uint32) \
562 SymE_NeedsProto(ffi_type_sint16) \
563 SymE_NeedsProto(ffi_type_uint16) \
564 SymE_NeedsProto(ffi_type_sint8) \
565 SymE_NeedsProto(ffi_type_uint8) \
566 SymE_NeedsProto(ffi_type_pointer)
568 #ifdef TABLES_NEXT_TO_CODE
569 #define RTS_RET_SYMBOLS /* nothing */
571 #define RTS_RET_SYMBOLS \
572 SymI_HasProto(stg_enter_ret) \
573 SymI_HasProto(stg_gc_fun_ret) \
574 SymI_HasProto(stg_ap_v_ret) \
575 SymI_HasProto(stg_ap_f_ret) \
576 SymI_HasProto(stg_ap_d_ret) \
577 SymI_HasProto(stg_ap_l_ret) \
578 SymI_HasProto(stg_ap_n_ret) \
579 SymI_HasProto(stg_ap_p_ret) \
580 SymI_HasProto(stg_ap_pv_ret) \
581 SymI_HasProto(stg_ap_pp_ret) \
582 SymI_HasProto(stg_ap_ppv_ret) \
583 SymI_HasProto(stg_ap_ppp_ret) \
584 SymI_HasProto(stg_ap_pppv_ret) \
585 SymI_HasProto(stg_ap_pppp_ret) \
586 SymI_HasProto(stg_ap_ppppp_ret) \
587 SymI_HasProto(stg_ap_pppppp_ret)
590 /* Modules compiled with -ticky may mention ticky counters */
591 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
592 #define RTS_TICKY_SYMBOLS \
593 SymI_NeedsProto(ticky_entry_ctrs) \
594 SymI_NeedsProto(top_ct) \
596 SymI_HasProto(ENT_VIA_NODE_ctr) \
597 SymI_HasProto(ENT_STATIC_THK_ctr) \
598 SymI_HasProto(ENT_DYN_THK_ctr) \
599 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
600 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
601 SymI_HasProto(ENT_STATIC_CON_ctr) \
602 SymI_HasProto(ENT_DYN_CON_ctr) \
603 SymI_HasProto(ENT_STATIC_IND_ctr) \
604 SymI_HasProto(ENT_DYN_IND_ctr) \
605 SymI_HasProto(ENT_PERM_IND_ctr) \
606 SymI_HasProto(ENT_PAP_ctr) \
607 SymI_HasProto(ENT_AP_ctr) \
608 SymI_HasProto(ENT_AP_STACK_ctr) \
609 SymI_HasProto(ENT_BH_ctr) \
610 SymI_HasProto(UNKNOWN_CALL_ctr) \
611 SymI_HasProto(SLOW_CALL_v_ctr) \
612 SymI_HasProto(SLOW_CALL_f_ctr) \
613 SymI_HasProto(SLOW_CALL_d_ctr) \
614 SymI_HasProto(SLOW_CALL_l_ctr) \
615 SymI_HasProto(SLOW_CALL_n_ctr) \
616 SymI_HasProto(SLOW_CALL_p_ctr) \
617 SymI_HasProto(SLOW_CALL_pv_ctr) \
618 SymI_HasProto(SLOW_CALL_pp_ctr) \
619 SymI_HasProto(SLOW_CALL_ppv_ctr) \
620 SymI_HasProto(SLOW_CALL_ppp_ctr) \
621 SymI_HasProto(SLOW_CALL_pppv_ctr) \
622 SymI_HasProto(SLOW_CALL_pppp_ctr) \
623 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
624 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
625 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
626 SymI_HasProto(ticky_slow_call_unevald) \
627 SymI_HasProto(SLOW_CALL_ctr) \
628 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
629 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
630 SymI_HasProto(KNOWN_CALL_ctr) \
631 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
632 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
633 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
634 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
635 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
636 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
637 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
638 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
639 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
640 SymI_HasProto(UPDF_OMITTED_ctr) \
641 SymI_HasProto(UPDF_PUSHED_ctr) \
642 SymI_HasProto(CATCHF_PUSHED_ctr) \
643 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
644 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
645 SymI_HasProto(UPD_SQUEEZED_ctr) \
646 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
647 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
648 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
649 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
650 SymI_HasProto(ALLOC_HEAP_ctr) \
651 SymI_HasProto(ALLOC_HEAP_tot) \
652 SymI_HasProto(ALLOC_FUN_ctr) \
653 SymI_HasProto(ALLOC_FUN_adm) \
654 SymI_HasProto(ALLOC_FUN_gds) \
655 SymI_HasProto(ALLOC_FUN_slp) \
656 SymI_HasProto(UPD_NEW_IND_ctr) \
657 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
658 SymI_HasProto(UPD_OLD_IND_ctr) \
659 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
660 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
661 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
662 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
663 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
664 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
665 SymI_HasProto(GC_SEL_MINOR_ctr) \
666 SymI_HasProto(GC_SEL_MAJOR_ctr) \
667 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
668 SymI_HasProto(ALLOC_UP_THK_ctr) \
669 SymI_HasProto(ALLOC_SE_THK_ctr) \
670 SymI_HasProto(ALLOC_THK_adm) \
671 SymI_HasProto(ALLOC_THK_gds) \
672 SymI_HasProto(ALLOC_THK_slp) \
673 SymI_HasProto(ALLOC_CON_ctr) \
674 SymI_HasProto(ALLOC_CON_adm) \
675 SymI_HasProto(ALLOC_CON_gds) \
676 SymI_HasProto(ALLOC_CON_slp) \
677 SymI_HasProto(ALLOC_TUP_ctr) \
678 SymI_HasProto(ALLOC_TUP_adm) \
679 SymI_HasProto(ALLOC_TUP_gds) \
680 SymI_HasProto(ALLOC_TUP_slp) \
681 SymI_HasProto(ALLOC_BH_ctr) \
682 SymI_HasProto(ALLOC_BH_adm) \
683 SymI_HasProto(ALLOC_BH_gds) \
684 SymI_HasProto(ALLOC_BH_slp) \
685 SymI_HasProto(ALLOC_PRIM_ctr) \
686 SymI_HasProto(ALLOC_PRIM_adm) \
687 SymI_HasProto(ALLOC_PRIM_gds) \
688 SymI_HasProto(ALLOC_PRIM_slp) \
689 SymI_HasProto(ALLOC_PAP_ctr) \
690 SymI_HasProto(ALLOC_PAP_adm) \
691 SymI_HasProto(ALLOC_PAP_gds) \
692 SymI_HasProto(ALLOC_PAP_slp) \
693 SymI_HasProto(ALLOC_TSO_ctr) \
694 SymI_HasProto(ALLOC_TSO_adm) \
695 SymI_HasProto(ALLOC_TSO_gds) \
696 SymI_HasProto(ALLOC_TSO_slp) \
697 SymI_HasProto(RET_NEW_ctr) \
698 SymI_HasProto(RET_OLD_ctr) \
699 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
700 SymI_HasProto(RET_SEMI_loads_avoided)
703 // On most platforms, the garbage collector rewrites references
704 // to small integer and char objects to a set of common, shared ones.
706 // We don't do this when compiling to Windows DLLs at the moment because
707 // it doesn't support cross package data references well.
709 #if defined(__PIC__) && defined(mingw32_HOST_OS)
710 #define RTS_INTCHAR_SYMBOLS
712 #define RTS_INTCHAR_SYMBOLS \
713 SymI_HasProto(stg_CHARLIKE_closure) \
714 SymI_HasProto(stg_INTLIKE_closure)
718 #define RTS_SYMBOLS \
721 SymI_HasProto(StgReturn) \
722 SymI_HasProto(stg_enter_info) \
723 SymI_HasProto(stg_gc_void_info) \
724 SymI_HasProto(__stg_gc_enter_1) \
725 SymI_HasProto(stg_gc_noregs) \
726 SymI_HasProto(stg_gc_unpt_r1_info) \
727 SymI_HasProto(stg_gc_unpt_r1) \
728 SymI_HasProto(stg_gc_unbx_r1_info) \
729 SymI_HasProto(stg_gc_unbx_r1) \
730 SymI_HasProto(stg_gc_f1_info) \
731 SymI_HasProto(stg_gc_f1) \
732 SymI_HasProto(stg_gc_d1_info) \
733 SymI_HasProto(stg_gc_d1) \
734 SymI_HasProto(stg_gc_l1_info) \
735 SymI_HasProto(stg_gc_l1) \
736 SymI_HasProto(__stg_gc_fun) \
737 SymI_HasProto(stg_gc_fun_info) \
738 SymI_HasProto(stg_gc_gen) \
739 SymI_HasProto(stg_gc_gen_info) \
740 SymI_HasProto(stg_gc_gen_hp) \
741 SymI_HasProto(stg_gc_ut) \
742 SymI_HasProto(stg_gen_yield) \
743 SymI_HasProto(stg_yield_noregs) \
744 SymI_HasProto(stg_yield_to_interpreter) \
745 SymI_HasProto(stg_gen_block) \
746 SymI_HasProto(stg_block_noregs) \
747 SymI_HasProto(stg_block_1) \
748 SymI_HasProto(stg_block_takemvar) \
749 SymI_HasProto(stg_block_putmvar) \
751 SymI_HasProto(MallocFailHook) \
752 SymI_HasProto(OnExitHook) \
753 SymI_HasProto(OutOfHeapHook) \
754 SymI_HasProto(StackOverflowHook) \
755 SymI_HasProto(addDLL) \
756 SymI_HasProto(__int_encodeDouble) \
757 SymI_HasProto(__word_encodeDouble) \
758 SymI_HasProto(__2Int_encodeDouble) \
759 SymI_HasProto(__int_encodeFloat) \
760 SymI_HasProto(__word_encodeFloat) \
761 SymI_HasProto(stg_atomicallyzh) \
762 SymI_HasProto(barf) \
763 SymI_HasProto(debugBelch) \
764 SymI_HasProto(errorBelch) \
765 SymI_HasProto(sysErrorBelch) \
766 SymI_HasProto(stg_getMaskingStatezh) \
767 SymI_HasProto(stg_maskAsyncExceptionszh) \
768 SymI_HasProto(stg_maskUninterruptiblezh) \
769 SymI_HasProto(stg_catchzh) \
770 SymI_HasProto(stg_catchRetryzh) \
771 SymI_HasProto(stg_catchSTMzh) \
772 SymI_HasProto(stg_checkzh) \
773 SymI_HasProto(closure_flags) \
774 SymI_HasProto(cmp_thread) \
775 SymI_HasProto(createAdjustor) \
776 SymI_HasProto(stg_decodeDoublezu2Intzh) \
777 SymI_HasProto(stg_decodeFloatzuIntzh) \
778 SymI_HasProto(defaultsHook) \
779 SymI_HasProto(stg_delayzh) \
780 SymI_HasProto(stg_deRefWeakzh) \
781 SymI_HasProto(stg_deRefStablePtrzh) \
782 SymI_HasProto(dirty_MUT_VAR) \
783 SymI_HasProto(stg_forkzh) \
784 SymI_HasProto(stg_forkOnzh) \
785 SymI_HasProto(forkProcess) \
786 SymI_HasProto(forkOS_createThread) \
787 SymI_HasProto(freeHaskellFunctionPtr) \
788 SymI_HasProto(getOrSetTypeableStore) \
789 SymI_HasProto(getOrSetGHCConcSignalSignalHandlerStore) \
790 SymI_HasProto(getOrSetGHCConcWindowsPendingDelaysStore) \
791 SymI_HasProto(getOrSetGHCConcWindowsIOManagerThreadStore) \
792 SymI_HasProto(getOrSetGHCConcWindowsProddingStore) \
793 SymI_HasProto(getOrSetSystemEventThreadEventManagerStore) \
794 SymI_HasProto(getOrSetSystemEventThreadIOManagerThreadStore) \
795 SymI_HasProto(genSymZh) \
796 SymI_HasProto(genericRaise) \
797 SymI_HasProto(getProgArgv) \
798 SymI_HasProto(getFullProgArgv) \
799 SymI_HasProto(getStablePtr) \
800 SymI_HasProto(hs_init) \
801 SymI_HasProto(hs_exit) \
802 SymI_HasProto(hs_set_argv) \
803 SymI_HasProto(hs_add_root) \
804 SymI_HasProto(hs_perform_gc) \
805 SymI_HasProto(hs_free_stable_ptr) \
806 SymI_HasProto(hs_free_fun_ptr) \
807 SymI_HasProto(hs_hpc_rootModule) \
808 SymI_HasProto(hs_hpc_module) \
809 SymI_HasProto(initLinker) \
810 SymI_HasProto(stg_unpackClosurezh) \
811 SymI_HasProto(stg_getApStackValzh) \
812 SymI_HasProto(stg_getSparkzh) \
813 SymI_HasProto(stg_numSparkszh) \
814 SymI_HasProto(stg_isCurrentThreadBoundzh) \
815 SymI_HasProto(stg_isEmptyMVarzh) \
816 SymI_HasProto(stg_killThreadzh) \
817 SymI_HasProto(loadArchive) \
818 SymI_HasProto(loadObj) \
819 SymI_HasProto(insertStableSymbol) \
820 SymI_HasProto(insertSymbol) \
821 SymI_HasProto(lookupSymbol) \
822 SymI_HasProto(stg_makeStablePtrzh) \
823 SymI_HasProto(stg_mkApUpd0zh) \
824 SymI_HasProto(stg_myThreadIdzh) \
825 SymI_HasProto(stg_labelThreadzh) \
826 SymI_HasProto(stg_newArrayzh) \
827 SymI_HasProto(stg_newBCOzh) \
828 SymI_HasProto(stg_newByteArrayzh) \
829 SymI_HasProto_redirect(newCAF, newDynCAF) \
830 SymI_HasProto(stg_newMVarzh) \
831 SymI_HasProto(stg_newMutVarzh) \
832 SymI_HasProto(stg_newTVarzh) \
833 SymI_HasProto(stg_noDuplicatezh) \
834 SymI_HasProto(stg_atomicModifyMutVarzh) \
835 SymI_HasProto(stg_casMutVarzh) \
836 SymI_HasProto(stg_newPinnedByteArrayzh) \
837 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
838 SymI_HasProto(newSpark) \
839 SymI_HasProto(performGC) \
840 SymI_HasProto(performMajorGC) \
841 SymI_HasProto(prog_argc) \
842 SymI_HasProto(prog_argv) \
843 SymI_HasProto(stg_putMVarzh) \
844 SymI_HasProto(stg_raisezh) \
845 SymI_HasProto(stg_raiseIOzh) \
846 SymI_HasProto(stg_readTVarzh) \
847 SymI_HasProto(stg_readTVarIOzh) \
848 SymI_HasProto(resumeThread) \
849 SymI_HasProto(resolveObjs) \
850 SymI_HasProto(stg_retryzh) \
851 SymI_HasProto(rts_apply) \
852 SymI_HasProto(rts_checkSchedStatus) \
853 SymI_HasProto(rts_eval) \
854 SymI_HasProto(rts_evalIO) \
855 SymI_HasProto(rts_evalLazyIO) \
856 SymI_HasProto(rts_evalStableIO) \
857 SymI_HasProto(rts_eval_) \
858 SymI_HasProto(rts_getBool) \
859 SymI_HasProto(rts_getChar) \
860 SymI_HasProto(rts_getDouble) \
861 SymI_HasProto(rts_getFloat) \
862 SymI_HasProto(rts_getInt) \
863 SymI_HasProto(rts_getInt8) \
864 SymI_HasProto(rts_getInt16) \
865 SymI_HasProto(rts_getInt32) \
866 SymI_HasProto(rts_getInt64) \
867 SymI_HasProto(rts_getPtr) \
868 SymI_HasProto(rts_getFunPtr) \
869 SymI_HasProto(rts_getStablePtr) \
870 SymI_HasProto(rts_getThreadId) \
871 SymI_HasProto(rts_getWord) \
872 SymI_HasProto(rts_getWord8) \
873 SymI_HasProto(rts_getWord16) \
874 SymI_HasProto(rts_getWord32) \
875 SymI_HasProto(rts_getWord64) \
876 SymI_HasProto(rts_lock) \
877 SymI_HasProto(rts_mkBool) \
878 SymI_HasProto(rts_mkChar) \
879 SymI_HasProto(rts_mkDouble) \
880 SymI_HasProto(rts_mkFloat) \
881 SymI_HasProto(rts_mkInt) \
882 SymI_HasProto(rts_mkInt8) \
883 SymI_HasProto(rts_mkInt16) \
884 SymI_HasProto(rts_mkInt32) \
885 SymI_HasProto(rts_mkInt64) \
886 SymI_HasProto(rts_mkPtr) \
887 SymI_HasProto(rts_mkFunPtr) \
888 SymI_HasProto(rts_mkStablePtr) \
889 SymI_HasProto(rts_mkString) \
890 SymI_HasProto(rts_mkWord) \
891 SymI_HasProto(rts_mkWord8) \
892 SymI_HasProto(rts_mkWord16) \
893 SymI_HasProto(rts_mkWord32) \
894 SymI_HasProto(rts_mkWord64) \
895 SymI_HasProto(rts_unlock) \
896 SymI_HasProto(rts_unsafeGetMyCapability) \
897 SymI_HasProto(rtsSupportsBoundThreads) \
898 SymI_HasProto(rts_isProfiled) \
899 SymI_HasProto(setProgArgv) \
900 SymI_HasProto(startupHaskell) \
901 SymI_HasProto(shutdownHaskell) \
902 SymI_HasProto(shutdownHaskellAndExit) \
903 SymI_HasProto(stable_ptr_table) \
904 SymI_HasProto(stackOverflow) \
905 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
906 SymI_HasProto(stg_BLACKHOLE_info) \
907 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
908 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
909 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
910 SymI_HasProto(startTimer) \
911 SymI_HasProto(stg_MVAR_CLEAN_info) \
912 SymI_HasProto(stg_MVAR_DIRTY_info) \
913 SymI_HasProto(stg_IND_STATIC_info) \
914 SymI_HasProto(stg_ARR_WORDS_info) \
915 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
916 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
917 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
918 SymI_HasProto(stg_WEAK_info) \
919 SymI_HasProto(stg_ap_v_info) \
920 SymI_HasProto(stg_ap_f_info) \
921 SymI_HasProto(stg_ap_d_info) \
922 SymI_HasProto(stg_ap_l_info) \
923 SymI_HasProto(stg_ap_n_info) \
924 SymI_HasProto(stg_ap_p_info) \
925 SymI_HasProto(stg_ap_pv_info) \
926 SymI_HasProto(stg_ap_pp_info) \
927 SymI_HasProto(stg_ap_ppv_info) \
928 SymI_HasProto(stg_ap_ppp_info) \
929 SymI_HasProto(stg_ap_pppv_info) \
930 SymI_HasProto(stg_ap_pppp_info) \
931 SymI_HasProto(stg_ap_ppppp_info) \
932 SymI_HasProto(stg_ap_pppppp_info) \
933 SymI_HasProto(stg_ap_0_fast) \
934 SymI_HasProto(stg_ap_v_fast) \
935 SymI_HasProto(stg_ap_f_fast) \
936 SymI_HasProto(stg_ap_d_fast) \
937 SymI_HasProto(stg_ap_l_fast) \
938 SymI_HasProto(stg_ap_n_fast) \
939 SymI_HasProto(stg_ap_p_fast) \
940 SymI_HasProto(stg_ap_pv_fast) \
941 SymI_HasProto(stg_ap_pp_fast) \
942 SymI_HasProto(stg_ap_ppv_fast) \
943 SymI_HasProto(stg_ap_ppp_fast) \
944 SymI_HasProto(stg_ap_pppv_fast) \
945 SymI_HasProto(stg_ap_pppp_fast) \
946 SymI_HasProto(stg_ap_ppppp_fast) \
947 SymI_HasProto(stg_ap_pppppp_fast) \
948 SymI_HasProto(stg_ap_1_upd_info) \
949 SymI_HasProto(stg_ap_2_upd_info) \
950 SymI_HasProto(stg_ap_3_upd_info) \
951 SymI_HasProto(stg_ap_4_upd_info) \
952 SymI_HasProto(stg_ap_5_upd_info) \
953 SymI_HasProto(stg_ap_6_upd_info) \
954 SymI_HasProto(stg_ap_7_upd_info) \
955 SymI_HasProto(stg_exit) \
956 SymI_HasProto(stg_sel_0_upd_info) \
957 SymI_HasProto(stg_sel_10_upd_info) \
958 SymI_HasProto(stg_sel_11_upd_info) \
959 SymI_HasProto(stg_sel_12_upd_info) \
960 SymI_HasProto(stg_sel_13_upd_info) \
961 SymI_HasProto(stg_sel_14_upd_info) \
962 SymI_HasProto(stg_sel_15_upd_info) \
963 SymI_HasProto(stg_sel_1_upd_info) \
964 SymI_HasProto(stg_sel_2_upd_info) \
965 SymI_HasProto(stg_sel_3_upd_info) \
966 SymI_HasProto(stg_sel_4_upd_info) \
967 SymI_HasProto(stg_sel_5_upd_info) \
968 SymI_HasProto(stg_sel_6_upd_info) \
969 SymI_HasProto(stg_sel_7_upd_info) \
970 SymI_HasProto(stg_sel_8_upd_info) \
971 SymI_HasProto(stg_sel_9_upd_info) \
972 SymI_HasProto(stg_upd_frame_info) \
973 SymI_HasProto(stg_bh_upd_frame_info) \
974 SymI_HasProto(suspendThread) \
975 SymI_HasProto(stg_takeMVarzh) \
976 SymI_HasProto(stg_threadStatuszh) \
977 SymI_HasProto(stg_tryPutMVarzh) \
978 SymI_HasProto(stg_tryTakeMVarzh) \
979 SymI_HasProto(stg_unmaskAsyncExceptionszh) \
980 SymI_HasProto(unloadObj) \
981 SymI_HasProto(stg_unsafeThawArrayzh) \
982 SymI_HasProto(stg_waitReadzh) \
983 SymI_HasProto(stg_waitWritezh) \
984 SymI_HasProto(stg_writeTVarzh) \
985 SymI_HasProto(stg_yieldzh) \
986 SymI_NeedsProto(stg_interp_constr_entry) \
987 SymI_HasProto(stg_arg_bitmaps) \
988 SymI_HasProto(large_alloc_lim) \
990 SymI_HasProto(allocate) \
991 SymI_HasProto(allocateExec) \
992 SymI_HasProto(freeExec) \
993 SymI_HasProto(getAllocations) \
994 SymI_HasProto(revertCAFs) \
995 SymI_HasProto(RtsFlags) \
996 SymI_NeedsProto(rts_breakpoint_io_action) \
997 SymI_NeedsProto(rts_stop_next_breakpoint) \
998 SymI_NeedsProto(rts_stop_on_exception) \
999 SymI_HasProto(stopTimer) \
1000 SymI_HasProto(n_capabilities) \
1001 SymI_HasProto(stg_traceCcszh) \
1002 SymI_HasProto(stg_traceEventzh) \
1003 RTS_USER_SIGNALS_SYMBOLS \
1007 // 64-bit support functions in libgcc.a
1008 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
1009 #define RTS_LIBGCC_SYMBOLS \
1010 SymI_NeedsProto(__divdi3) \
1011 SymI_NeedsProto(__udivdi3) \
1012 SymI_NeedsProto(__moddi3) \
1013 SymI_NeedsProto(__umoddi3) \
1014 SymI_NeedsProto(__muldi3) \
1015 SymI_NeedsProto(__ashldi3) \
1016 SymI_NeedsProto(__ashrdi3) \
1017 SymI_NeedsProto(__lshrdi3)
1019 #define RTS_LIBGCC_SYMBOLS
1022 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
1023 // Symbols that don't have a leading underscore
1024 // on Mac OS X. They have to receive special treatment,
1025 // see machoInitSymbolsWithoutUnderscore()
1026 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1027 SymI_NeedsProto(saveFP) \
1028 SymI_NeedsProto(restFP)
1031 /* entirely bogus claims about types of these symbols */
1032 #define SymI_NeedsProto(vvv) extern void vvv(void);
1033 #if defined(__PIC__) && defined(mingw32_HOST_OS)
1034 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1035 #define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1037 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1038 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1040 #define SymI_HasProto(vvv) /**/
1041 #define SymI_HasProto_redirect(vvv,xxx) /**/
1044 RTS_POSIX_ONLY_SYMBOLS
1045 RTS_MINGW_ONLY_SYMBOLS
1046 RTS_CYGWIN_ONLY_SYMBOLS
1047 RTS_DARWIN_ONLY_SYMBOLS
1050 #undef SymI_NeedsProto
1051 #undef SymI_HasProto
1052 #undef SymI_HasProto_redirect
1053 #undef SymE_HasProto
1054 #undef SymE_NeedsProto
1056 #ifdef LEADING_UNDERSCORE
1057 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1059 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1062 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1064 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1065 (void*)DLL_IMPORT_DATA_REF(vvv) },
1067 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1068 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1070 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1071 // another symbol. See newCAF/newDynCAF for an example.
1072 #define SymI_HasProto_redirect(vvv,xxx) \
1073 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1076 static RtsSymbolVal rtsSyms[] = {
1079 RTS_POSIX_ONLY_SYMBOLS
1080 RTS_MINGW_ONLY_SYMBOLS
1081 RTS_CYGWIN_ONLY_SYMBOLS
1082 RTS_DARWIN_ONLY_SYMBOLS
1085 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1086 // dyld stub code contains references to this,
1087 // but it should never be called because we treat
1088 // lazy pointers as nonlazy.
1089 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1091 { 0, 0 } /* sentinel */
1096 /* -----------------------------------------------------------------------------
1097 * Insert symbols into hash tables, checking for duplicates.
1100 static void ghciInsertStrHashTable ( char* obj_name,
1106 if (lookupHashTable(table, (StgWord)key) == NULL)
1108 insertStrHashTable(table, (StgWord)key, data);
1113 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1115 "whilst processing object file\n"
1117 "This could be caused by:\n"
1118 " * Loading two different object files which export the same symbol\n"
1119 " * Specifying the same object file twice on the GHCi command line\n"
1120 " * An incorrect `package.conf' entry, causing some object to be\n"
1122 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1129 /* -----------------------------------------------------------------------------
1130 * initialize the object linker
1134 static int linker_init_done = 0 ;
1136 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1137 static void *dl_prog_handle;
1138 static regex_t re_invalid;
1139 static regex_t re_realso;
1141 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1149 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1153 IF_DEBUG(linker, debugBelch("initLinker: start\n"));
1155 /* Make initLinker idempotent, so we can call it
1156 before evey relevant operation; that means we
1157 don't need to initialise the linker separately */
1158 if (linker_init_done == 1) {
1159 IF_DEBUG(linker, debugBelch("initLinker: idempotent return\n"));
1162 linker_init_done = 1;
1165 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1166 initMutex(&dl_mutex);
1168 stablehash = allocStrHashTable();
1169 symhash = allocStrHashTable();
1171 /* populate the symbol table with stuff from the RTS */
1172 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1173 ghciInsertStrHashTable("(GHCi built-in symbols)",
1174 symhash, sym->lbl, sym->addr);
1175 IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
1177 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1178 machoInitSymbolsWithoutUnderscore();
1181 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1182 # if defined(RTLD_DEFAULT)
1183 dl_prog_handle = RTLD_DEFAULT;
1185 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1186 # endif /* RTLD_DEFAULT */
1188 compileResult = regcomp(&re_invalid,
1189 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*invalid ELF header",
1191 ASSERT( compileResult == 0 );
1192 compileResult = regcomp(&re_realso,
1193 "GROUP *\\( *(([^ )])+)",
1195 ASSERT( compileResult == 0 );
1198 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1199 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1200 // User-override for mmap_32bit_base
1201 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1205 #if defined(mingw32_HOST_OS)
1207 * These two libraries cause problems when added to the static link,
1208 * but are necessary for resolving symbols in GHCi, hence we load
1209 * them manually here.
1215 IF_DEBUG(linker, debugBelch("initLinker: done\n"));
1220 exitLinker( void ) {
1221 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1222 if (linker_init_done == 1) {
1223 regfree(&re_invalid);
1224 regfree(&re_realso);
1226 closeMutex(&dl_mutex);
1232 /* -----------------------------------------------------------------------------
1233 * Loading DLL or .so dynamic libraries
1234 * -----------------------------------------------------------------------------
1236 * Add a DLL from which symbols may be found. In the ELF case, just
1237 * do RTLD_GLOBAL-style add, so no further messing around needs to
1238 * happen in order that symbols in the loaded .so are findable --
1239 * lookupSymbol() will subsequently see them by dlsym on the program's
1240 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1242 * In the PEi386 case, open the DLLs and put handles to them in a
1243 * linked list. When looking for a symbol, try all handles in the
1244 * list. This means that we need to load even DLLs that are guaranteed
1245 * to be in the ghc.exe image already, just so we can get a handle
1246 * to give to loadSymbol, so that we can find the symbols. For such
1247 * libraries, the LoadLibrary call should be a no-op except for returning
1252 #if defined(OBJFORMAT_PEi386)
1253 /* A record for storing handles into DLLs. */
1258 struct _OpenedDLL* next;
1263 /* A list thereof. */
1264 static OpenedDLL* opened_dlls = NULL;
1267 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1270 internal_dlopen(const char *dll_name)
1276 // omitted: RTLD_NOW
1277 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1279 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1281 //-------------- Begin critical section ------------------
1282 // This critical section is necessary because dlerror() is not
1283 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1284 // Also, the error message returned must be copied to preserve it
1287 ACQUIRE_LOCK(&dl_mutex);
1288 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1292 /* dlopen failed; return a ptr to the error msg. */
1294 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1295 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1296 strcpy(errmsg_copy, errmsg);
1297 errmsg = errmsg_copy;
1299 RELEASE_LOCK(&dl_mutex);
1300 //--------------- End critical section -------------------
1307 addDLL( char *dll_name )
1309 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1310 /* ------------------- ELF DLL loader ------------------- */
1313 regmatch_t match[NMATCH];
1316 size_t match_length;
1317 #define MAXLINE 1000
1323 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1324 errmsg = internal_dlopen(dll_name);
1326 if (errmsg == NULL) {
1330 // GHC Trac ticket #2615
1331 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1332 // contain linker scripts rather than ELF-format object code. This
1333 // code handles the situation by recognizing the real object code
1334 // file name given in the linker script.
1336 // If an "invalid ELF header" error occurs, it is assumed that the
1337 // .so file contains a linker script instead of ELF object code.
1338 // In this case, the code looks for the GROUP ( ... ) linker
1339 // directive. If one is found, the first file name inside the
1340 // parentheses is treated as the name of a dynamic library and the
1341 // code attempts to dlopen that file. If this is also unsuccessful,
1342 // an error message is returned.
1344 // see if the error message is due to an invalid ELF header
1345 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1346 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1347 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1349 // success -- try to read the named file as a linker script
1350 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1352 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1353 line[match_length] = '\0'; // make sure string is null-terminated
1354 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1355 if ((fp = fopen(line, "r")) == NULL) {
1356 return errmsg; // return original error if open fails
1358 // try to find a GROUP ( ... ) command
1359 while (fgets(line, MAXLINE, fp) != NULL) {
1360 IF_DEBUG(linker, debugBelch("input line = %s", line));
1361 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1362 // success -- try to dlopen the first named file
1363 IF_DEBUG(linker, debugBelch("match%s\n",""));
1364 line[match[1].rm_eo] = '\0';
1365 errmsg = internal_dlopen(line+match[1].rm_so);
1368 // if control reaches here, no GROUP ( ... ) directive was found
1369 // and the original error message is returned to the caller
1375 # elif defined(OBJFORMAT_PEi386)
1376 /* ------------------- Win32 DLL loader ------------------- */
1384 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1386 /* See if we've already got it, and ignore if so. */
1387 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1388 if (0 == strcmp(o_dll->name, dll_name))
1392 /* The file name has no suffix (yet) so that we can try
1393 both foo.dll and foo.drv
1395 The documentation for LoadLibrary says:
1396 If no file name extension is specified in the lpFileName
1397 parameter, the default library extension .dll is
1398 appended. However, the file name string can include a trailing
1399 point character (.) to indicate that the module name has no
1402 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1403 sprintf(buf, "%s.DLL", dll_name);
1404 instance = LoadLibrary(buf);
1405 if (instance == NULL) {
1406 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1407 // KAA: allow loading of drivers (like winspool.drv)
1408 sprintf(buf, "%s.DRV", dll_name);
1409 instance = LoadLibrary(buf);
1410 if (instance == NULL) {
1411 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1412 // #1883: allow loading of unix-style libfoo.dll DLLs
1413 sprintf(buf, "lib%s.DLL", dll_name);
1414 instance = LoadLibrary(buf);
1415 if (instance == NULL) {
1422 /* Add this DLL to the list of DLLs in which to search for symbols. */
1423 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1424 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
1425 strcpy(o_dll->name, dll_name);
1426 o_dll->instance = instance;
1427 o_dll->next = opened_dlls;
1428 opened_dlls = o_dll;
1434 sysErrorBelch(dll_name);
1436 /* LoadLibrary failed; return a ptr to the error msg. */
1437 return "addDLL: could not load DLL";
1440 barf("addDLL: not implemented on this platform");
1444 /* -----------------------------------------------------------------------------
1445 * insert a stable symbol in the hash table
1449 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1451 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1455 /* -----------------------------------------------------------------------------
1456 * insert a symbol in the hash table
1459 insertSymbol(char* obj_name, char* key, void* data)
1461 ghciInsertStrHashTable(obj_name, symhash, key, data);
1464 /* -----------------------------------------------------------------------------
1465 * lookup a symbol in the hash table
1468 lookupSymbol( char *lbl )
1471 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s\n", lbl));
1473 ASSERT(symhash != NULL);
1474 val = lookupStrHashTable(symhash, lbl);
1477 IF_DEBUG(linker, debugBelch("lookupSymbol: symbol not found\n"));
1478 # if defined(OBJFORMAT_ELF)
1479 return dlsym(dl_prog_handle, lbl);
1480 # elif defined(OBJFORMAT_MACHO)
1482 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1485 HACK: On OS X, global symbols are prefixed with an underscore.
1486 However, dlsym wants us to omit the leading underscore from the
1487 symbol name. For now, we simply strip it off here (and ONLY
1490 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s with dlsym\n", lbl));
1491 ASSERT(lbl[0] == '_');
1492 return dlsym(dl_prog_handle, lbl+1);
1494 if(NSIsSymbolNameDefined(lbl)) {
1495 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1496 return NSAddressOfSymbol(symbol);
1500 # endif /* HAVE_DLFCN_H */
1501 # elif defined(OBJFORMAT_PEi386)
1504 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1505 if (sym != NULL) { return sym; };
1507 // Also try looking up the symbol without the @N suffix. Some
1508 // DLLs have the suffixes on their symbols, some don't.
1509 zapTrailingAtSign ( (unsigned char*)lbl );
1510 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1511 if (sym != NULL) { return sym; };
1519 IF_DEBUG(linker, debugBelch("lookupSymbol: value of %s is %p\n", lbl, val));
1524 /* -----------------------------------------------------------------------------
1525 * Debugging aid: look in GHCi's object symbol tables for symbols
1526 * within DELTA bytes of the specified address, and show their names.
1529 void ghci_enquire ( char* addr );
1531 void ghci_enquire ( char* addr )
1536 const int DELTA = 64;
1541 for (oc = objects; oc; oc = oc->next) {
1542 for (i = 0; i < oc->n_symbols; i++) {
1543 sym = oc->symbols[i];
1544 if (sym == NULL) continue;
1547 a = lookupStrHashTable(symhash, sym);
1550 // debugBelch("ghci_enquire: can't find %s\n", sym);
1552 else if (addr-DELTA <= a && a <= addr+DELTA) {
1553 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1561 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1564 mmapForLinker (size_t bytes, nat flags, int fd)
1566 void *map_addr = NULL;
1569 static nat fixed = 0;
1571 IF_DEBUG(linker, debugBelch("mmapForLinker: start\n"));
1572 pagesize = getpagesize();
1573 size = ROUND_UP(bytes, pagesize);
1575 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1578 if (mmap_32bit_base != 0) {
1579 map_addr = mmap_32bit_base;
1583 IF_DEBUG(linker, debugBelch("mmapForLinker: \tprotection %#0x\n", PROT_EXEC | PROT_READ | PROT_WRITE));
1584 IF_DEBUG(linker, debugBelch("mmapForLinker: \tflags %#0x\n", MAP_PRIVATE | TRY_MAP_32BIT | fixed | flags));
1585 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1586 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1588 if (result == MAP_FAILED) {
1589 sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1590 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1591 stg_exit(EXIT_FAILURE);
1594 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1595 if (mmap_32bit_base != 0) {
1596 if (result == map_addr) {
1597 mmap_32bit_base = (StgWord8*)map_addr + size;
1599 if ((W_)result > 0x80000000) {
1600 // oops, we were given memory over 2Gb
1601 #if defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS)
1602 // Some platforms require MAP_FIXED. This is normally
1603 // a bad idea, because MAP_FIXED will overwrite
1604 // existing mappings.
1605 munmap(result,size);
1609 barf("loadObj: failed to mmap() memory below 2Gb; asked for %lu bytes at %p. Try specifying an address with +RTS -xm<addr> -RTS", size, map_addr, result);
1612 // hmm, we were given memory somewhere else, but it's
1613 // still under 2Gb so we can use it. Next time, ask
1614 // for memory right after the place we just got some
1615 mmap_32bit_base = (StgWord8*)result + size;
1619 if ((W_)result > 0x80000000) {
1620 // oops, we were given memory over 2Gb
1621 // ... try allocating memory somewhere else?;
1622 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1623 munmap(result, size);
1625 // Set a base address and try again... (guess: 1Gb)
1626 mmap_32bit_base = (void*)0x40000000;
1632 IF_DEBUG(linker, debugBelch("mmapForLinker: mapped %lu bytes starting at %p\n", (lnat)size, result));
1633 IF_DEBUG(linker, debugBelch("mmapForLinker: done\n"));
1639 mkOc( char *path, char *image, int imageSize,
1640 char *archiveMemberName
1642 #ifdef darwin_HOST_OS
1649 IF_DEBUG(linker, debugBelch("mkOc: start\n"));
1650 oc = stgMallocBytes(sizeof(ObjectCode), "loadArchive(oc)");
1652 # if defined(OBJFORMAT_ELF)
1653 oc->formatName = "ELF";
1654 # elif defined(OBJFORMAT_PEi386)
1655 oc->formatName = "PEi386";
1656 # elif defined(OBJFORMAT_MACHO)
1657 oc->formatName = "Mach-O";
1660 barf("loadObj: not implemented on this platform");
1664 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1665 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1666 strcpy(oc->fileName, path);
1668 if (archiveMemberName) {
1669 oc->archiveMemberName = stgMallocBytes( strlen(archiveMemberName)+1, "loadObj" );
1670 strcpy(oc->archiveMemberName, archiveMemberName);
1673 oc->archiveMemberName = NULL;
1676 oc->fileSize = imageSize;
1678 oc->sections = NULL;
1679 oc->proddables = NULL;
1682 #ifdef darwin_HOST_OS
1683 oc->misalignment = misalignment;
1687 /* chain it onto the list of objects */
1691 IF_DEBUG(linker, debugBelch("mkOc: done\n"));
1696 loadArchive( char *path )
1703 size_t thisFileNameSize;
1705 size_t fileNameSize;
1706 int isObject, isGnuIndex;
1709 int gnuFileIndexSize;
1710 #if defined(darwin_HOST_OS)
1712 uint32_t nfat_arch, nfat_offset, cputype, cpusubtype;
1713 #if defined(i386_HOST_ARCH)
1714 const uint32_t mycputype = CPU_TYPE_X86;
1715 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_ALL;
1716 #elif defined(x86_64_HOST_ARCH)
1717 const uint32_t mycputype = CPU_TYPE_X86_64;
1718 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_64_ALL;
1719 #elif defined(powerpc_HOST_ARCH)
1720 const uint32_t mycputype = CPU_TYPE_POWERPC;
1721 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
1722 #elif defined(powerpc64_HOST_ARCH)
1723 const uint32_t mycputype = CPU_TYPE_POWERPC64;
1724 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
1726 #error Unknown Darwin architecture
1728 #if !defined(USE_MMAP)
1733 IF_DEBUG(linker, debugBelch("loadArchive: start\n"));
1734 IF_DEBUG(linker, debugBelch("loadArchive: Loading archive `%s'\n", path));
1736 gnuFileIndex = NULL;
1737 gnuFileIndexSize = 0;
1740 fileName = stgMallocBytes(fileNameSize, "loadArchive(fileName)");
1742 f = fopen(path, "rb");
1744 barf("loadObj: can't read `%s'", path);
1746 /* Check if this is an archive by looking for the magic "!<arch>\n"
1747 * string. Usually, if this fails, we barf and quit. On Darwin however,
1748 * we may have a fat archive, which contains archives for more than
1749 * one architecture. Fat archives start with the magic number 0xcafebabe,
1750 * always stored big endian. If we find a fat_header, we scan through
1751 * the fat_arch structs, searching through for one for our host
1752 * architecture. If a matching struct is found, we read the offset
1753 * of our archive data (nfat_offset) and seek forward nfat_offset bytes
1754 * from the start of the file.
1756 * A subtlety is that all of the members of the fat_header and fat_arch
1757 * structs are stored big endian, so we need to call byte order
1758 * conversion functions.
1760 * If we find the appropriate architecture in a fat archive, we gobble
1761 * its magic "!<arch>\n" string and continue processing just as if
1762 * we had a single architecture archive.
1765 n = fread ( tmp, 1, 8, f );
1767 barf("loadArchive: Failed reading header from `%s'", path);
1768 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
1770 #if defined(darwin_HOST_OS)
1771 /* Not a standard archive, look for a fat archive magic number: */
1772 if (ntohl(*(uint32_t *)tmp) == FAT_MAGIC) {
1773 nfat_arch = ntohl(*(uint32_t *)(tmp + 4));
1774 IF_DEBUG(linker, debugBelch("loadArchive: found a fat archive containing %d architectures\n", nfat_arch));
1777 for (i = 0; i < (int)nfat_arch; i++) {
1778 /* search for the right arch */
1779 n = fread( tmp, 1, 20, f );
1781 barf("loadArchive: Failed reading arch from `%s'", path);
1782 cputype = ntohl(*(uint32_t *)tmp);
1783 cpusubtype = ntohl(*(uint32_t *)(tmp + 4));
1785 if (cputype == mycputype && cpusubtype == mycpusubtype) {
1786 IF_DEBUG(linker, debugBelch("loadArchive: found my archive in a fat archive\n"));
1787 nfat_offset = ntohl(*(uint32_t *)(tmp + 8));
1792 if (nfat_offset == 0) {
1793 barf ("loadArchive: searched %d architectures, but no host arch found", (int)nfat_arch);
1796 n = fseek( f, nfat_offset, SEEK_SET );
1798 barf("loadArchive: Failed to seek to arch in `%s'", path);
1799 n = fread ( tmp, 1, 8, f );
1801 barf("loadArchive: Failed reading header from `%s'", path);
1802 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
1803 barf("loadArchive: couldn't find archive in `%s' at offset %d", path, nfat_offset);
1808 barf("loadArchive: Neither an archive, nor a fat archive: `%s'", path);
1812 barf("loadArchive: Not an archive: `%s'", path);
1816 IF_DEBUG(linker, debugBelch("loadArchive: loading archive contents\n"));
1819 n = fread ( fileName, 1, 16, f );
1822 IF_DEBUG(linker, debugBelch("loadArchive: EOF while reading from '%s'\n", path));
1826 barf("loadArchive: Failed reading file name from `%s'", path);
1830 #if defined(darwin_HOST_OS)
1831 if (strncmp(fileName, "!<arch>\n", 8) == 0) {
1832 IF_DEBUG(linker, debugBelch("loadArchive: found the start of another archive, breaking\n"));
1837 n = fread ( tmp, 1, 12, f );
1839 barf("loadArchive: Failed reading mod time from `%s'", path);
1840 n = fread ( tmp, 1, 6, f );
1842 barf("loadArchive: Failed reading owner from `%s'", path);
1843 n = fread ( tmp, 1, 6, f );
1845 barf("loadArchive: Failed reading group from `%s'", path);
1846 n = fread ( tmp, 1, 8, f );
1848 barf("loadArchive: Failed reading mode from `%s'", path);
1849 n = fread ( tmp, 1, 10, f );
1851 barf("loadArchive: Failed reading size from `%s'", path);
1853 for (n = 0; isdigit(tmp[n]); n++);
1855 memberSize = atoi(tmp);
1857 IF_DEBUG(linker, debugBelch("loadArchive: size of this archive member is %d\n", memberSize));
1858 n = fread ( tmp, 1, 2, f );
1860 barf("loadArchive: Failed reading magic from `%s'", path);
1861 if (strncmp(tmp, "\x60\x0A", 2) != 0)
1862 barf("loadArchive: Failed reading magic from `%s' at %ld. Got %c%c",
1863 path, ftell(f), tmp[0], tmp[1]);
1866 /* Check for BSD-variant large filenames */
1867 if (0 == strncmp(fileName, "#1/", 3)) {
1868 fileName[16] = '\0';
1869 if (isdigit(fileName[3])) {
1870 for (n = 4; isdigit(fileName[n]); n++);
1872 thisFileNameSize = atoi(fileName + 3);
1873 memberSize -= thisFileNameSize;
1874 if (thisFileNameSize >= fileNameSize) {
1875 /* Double it to avoid potentially continually
1876 increasing it by 1 */
1877 fileNameSize = thisFileNameSize * 2;
1878 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1880 n = fread ( fileName, 1, thisFileNameSize, f );
1881 if (n != (int)thisFileNameSize) {
1882 barf("loadArchive: Failed reading filename from `%s'",
1885 fileName[thisFileNameSize] = 0;
1887 /* On OS X at least, thisFileNameSize is the size of the
1888 fileName field, not the length of the fileName
1890 thisFileNameSize = strlen(fileName);
1893 barf("loadArchive: BSD-variant filename size not found while reading filename from `%s'", path);
1896 /* Check for GNU file index file */
1897 else if (0 == strncmp(fileName, "//", 2)) {
1899 thisFileNameSize = 0;
1902 /* Check for a file in the GNU file index */
1903 else if (fileName[0] == '/') {
1904 if (isdigit(fileName[1])) {
1907 for (n = 2; isdigit(fileName[n]); n++);
1909 n = atoi(fileName + 1);
1911 if (gnuFileIndex == NULL) {
1912 barf("loadArchive: GNU-variant filename without an index while reading from `%s'", path);
1914 if (n < 0 || n > gnuFileIndexSize) {
1915 barf("loadArchive: GNU-variant filename offset %d out of range [0..%d] while reading filename from `%s'", n, gnuFileIndexSize, path);
1917 if (n != 0 && gnuFileIndex[n - 1] != '\n') {
1918 barf("loadArchive: GNU-variant filename offset %d invalid (range [0..%d]) while reading filename from `%s'", n, gnuFileIndexSize, path);
1920 for (i = n; gnuFileIndex[i] != '/'; i++);
1921 thisFileNameSize = i - n;
1922 if (thisFileNameSize >= fileNameSize) {
1923 /* Double it to avoid potentially continually
1924 increasing it by 1 */
1925 fileNameSize = thisFileNameSize * 2;
1926 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1928 memcpy(fileName, gnuFileIndex + n, thisFileNameSize);
1929 fileName[thisFileNameSize] = '\0';
1931 else if (fileName[1] == ' ') {
1933 thisFileNameSize = 0;
1936 barf("loadArchive: GNU-variant filename offset not found while reading filename from `%s'", path);
1939 /* Finally, the case where the filename field actually contains
1942 /* GNU ar terminates filenames with a '/', this allowing
1943 spaces in filenames. So first look to see if there is a
1945 for (thisFileNameSize = 0;
1946 thisFileNameSize < 16;
1947 thisFileNameSize++) {
1948 if (fileName[thisFileNameSize] == '/') {
1949 fileName[thisFileNameSize] = '\0';
1953 /* If we didn't find a '/', then a space teminates the
1954 filename. Note that if we don't find one, then
1955 thisFileNameSize ends up as 16, and we already have the
1957 if (thisFileNameSize == 16) {
1958 for (thisFileNameSize = 0;
1959 thisFileNameSize < 16;
1960 thisFileNameSize++) {
1961 if (fileName[thisFileNameSize] == ' ') {
1962 fileName[thisFileNameSize] = '\0';
1970 debugBelch("loadArchive: Found member file `%s'\n", fileName));
1972 isObject = thisFileNameSize >= 2
1973 && fileName[thisFileNameSize - 2] == '.'
1974 && fileName[thisFileNameSize - 1] == 'o';
1976 IF_DEBUG(linker, debugBelch("loadArchive: \tthisFileNameSize = %d\n", (int)thisFileNameSize));
1977 IF_DEBUG(linker, debugBelch("loadArchive: \tisObject = %d\n", isObject));
1980 char *archiveMemberName;
1982 IF_DEBUG(linker, debugBelch("loadArchive: Member is an object file...loading...\n"));
1984 /* We can't mmap from the archive directly, as object
1985 files need to be 8-byte aligned but files in .ar
1986 archives are 2-byte aligned. When possible we use mmap
1987 to get some anonymous memory, as on 64-bit platforms if
1988 we use malloc then we can be given memory above 2^32.
1989 In the mmap case we're probably wasting lots of space;
1990 we could do better. */
1991 #if defined(USE_MMAP)
1992 image = mmapForLinker(memberSize, MAP_ANONYMOUS, -1);
1993 #elif defined(darwin_HOST_OS)
1995 misalignment = machoGetMisalignment(f);
1996 image = stgMallocBytes(memberSize + misalignment, "loadArchive(image)");
1997 image += misalignment;
1999 image = stgMallocBytes(memberSize, "loadArchive(image)");
2001 n = fread ( image, 1, memberSize, f );
2002 if (n != memberSize) {
2003 barf("loadArchive: error whilst reading `%s'", path);
2006 archiveMemberName = stgMallocBytes(strlen(path) + thisFileNameSize + 3,
2007 "loadArchive(file)");
2008 sprintf(archiveMemberName, "%s(%.*s)",
2009 path, (int)thisFileNameSize, fileName);
2011 oc = mkOc(path, image, memberSize, archiveMemberName
2013 #ifdef darwin_HOST_OS
2019 stgFree(archiveMemberName);
2021 if (0 == loadOc(oc)) {
2026 else if (isGnuIndex) {
2027 if (gnuFileIndex != NULL) {
2028 barf("loadArchive: GNU-variant index found, but already have an index, while reading filename from `%s'", path);
2030 IF_DEBUG(linker, debugBelch("loadArchive: Found GNU-variant file index\n"));
2032 gnuFileIndex = mmapForLinker(memberSize + 1, MAP_ANONYMOUS, -1);
2034 gnuFileIndex = stgMallocBytes(memberSize + 1, "loadArchive(image)");
2036 n = fread ( gnuFileIndex, 1, memberSize, f );
2037 if (n != memberSize) {
2038 barf("loadArchive: error whilst reading `%s'", path);
2040 gnuFileIndex[memberSize] = '/';
2041 gnuFileIndexSize = memberSize;
2044 IF_DEBUG(linker, debugBelch("loadArchive: '%s' does not appear to be an object file\n", fileName));
2045 n = fseek(f, memberSize, SEEK_CUR);
2047 barf("loadArchive: error whilst seeking by %d in `%s'",
2051 /* .ar files are 2-byte aligned */
2052 if (memberSize % 2) {
2053 IF_DEBUG(linker, debugBelch("loadArchive: trying to read one pad byte\n"));
2054 n = fread ( tmp, 1, 1, f );
2057 IF_DEBUG(linker, debugBelch("loadArchive: found EOF while reading one pad byte\n"));
2061 barf("loadArchive: Failed reading padding from `%s'", path);
2064 IF_DEBUG(linker, debugBelch("loadArchive: successfully read one pad byte\n"));
2066 IF_DEBUG(linker, debugBelch("loadArchive: reached end of archive loading while loop\n"));
2072 if (gnuFileIndex != NULL) {
2074 munmap(gnuFileIndex, gnuFileIndexSize + 1);
2076 stgFree(gnuFileIndex);
2080 IF_DEBUG(linker, debugBelch("loadArchive: done\n"));
2084 /* -----------------------------------------------------------------------------
2085 * Load an obj (populate the global symbol table, but don't resolve yet)
2087 * Returns: 1 if ok, 0 on error.
2090 loadObj( char *path )
2101 # if defined(darwin_HOST_OS)
2105 IF_DEBUG(linker, debugBelch("loadObj %s\n", path));
2109 /* debugBelch("loadObj %s\n", path ); */
2111 /* Check that we haven't already loaded this object.
2112 Ignore requests to load multiple times */
2116 for (o = objects; o; o = o->next) {
2117 if (0 == strcmp(o->fileName, path)) {
2119 break; /* don't need to search further */
2123 IF_DEBUG(linker, debugBelch(
2124 "GHCi runtime linker: warning: looks like you're trying to load the\n"
2125 "same object file twice:\n"
2127 "GHCi will ignore this, but be warned.\n"
2129 return 1; /* success */
2133 r = stat(path, &st);
2135 IF_DEBUG(linker, debugBelch("File doesn't exist\n"));
2139 fileSize = st.st_size;
2142 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
2144 #if defined(openbsd_HOST_OS)
2145 fd = open(path, O_RDONLY, S_IRUSR);
2147 fd = open(path, O_RDONLY);
2150 barf("loadObj: can't open `%s'", path);
2152 image = mmapForLinker(fileSize, 0, fd);
2156 #else /* !USE_MMAP */
2157 /* load the image into memory */
2158 f = fopen(path, "rb");
2160 barf("loadObj: can't read `%s'", path);
2162 # if defined(mingw32_HOST_OS)
2163 // TODO: We would like to use allocateExec here, but allocateExec
2164 // cannot currently allocate blocks large enough.
2165 image = VirtualAlloc(NULL, fileSize, MEM_RESERVE | MEM_COMMIT,
2166 PAGE_EXECUTE_READWRITE);
2167 # elif defined(darwin_HOST_OS)
2168 // In a Mach-O .o file, all sections can and will be misaligned
2169 // if the total size of the headers is not a multiple of the
2170 // desired alignment. This is fine for .o files that only serve
2171 // as input for the static linker, but it's not fine for us,
2172 // as SSE (used by gcc for floating point) and Altivec require
2173 // 16-byte alignment.
2174 // We calculate the correct alignment from the header before
2175 // reading the file, and then we misalign image on purpose so
2176 // that the actual sections end up aligned again.
2177 misalignment = machoGetMisalignment(f);
2178 image = stgMallocBytes(fileSize + misalignment, "loadObj(image)");
2179 image += misalignment;
2181 image = stgMallocBytes(fileSize, "loadObj(image)");
2186 n = fread ( image, 1, fileSize, f );
2188 barf("loadObj: error whilst reading `%s'", path);
2191 #endif /* USE_MMAP */
2193 oc = mkOc(path, image, fileSize, NULL
2195 #ifdef darwin_HOST_OS
2205 loadOc( ObjectCode* oc ) {
2208 IF_DEBUG(linker, debugBelch("loadOc: start\n"));
2210 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2211 r = ocAllocateSymbolExtras_MachO ( oc );
2213 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_MachO failed\n"));
2216 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2217 r = ocAllocateSymbolExtras_ELF ( oc );
2219 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_ELF failed\n"));
2224 /* verify the in-memory image */
2225 # if defined(OBJFORMAT_ELF)
2226 r = ocVerifyImage_ELF ( oc );
2227 # elif defined(OBJFORMAT_PEi386)
2228 r = ocVerifyImage_PEi386 ( oc );
2229 # elif defined(OBJFORMAT_MACHO)
2230 r = ocVerifyImage_MachO ( oc );
2232 barf("loadObj: no verify method");
2235 IF_DEBUG(linker, debugBelch("loadOc: ocVerifyImage_* failed\n"));
2239 /* build the symbol list for this image */
2240 # if defined(OBJFORMAT_ELF)
2241 r = ocGetNames_ELF ( oc );
2242 # elif defined(OBJFORMAT_PEi386)
2243 r = ocGetNames_PEi386 ( oc );
2244 # elif defined(OBJFORMAT_MACHO)
2245 r = ocGetNames_MachO ( oc );
2247 barf("loadObj: no getNames method");
2250 IF_DEBUG(linker, debugBelch("loadOc: ocGetNames_* failed\n"));
2254 /* loaded, but not resolved yet */
2255 oc->status = OBJECT_LOADED;
2256 IF_DEBUG(linker, debugBelch("loadOc: done.\n"));
2261 /* -----------------------------------------------------------------------------
2262 * resolve all the currently unlinked objects in memory
2264 * Returns: 1 if ok, 0 on error.
2272 IF_DEBUG(linker, debugBelch("resolveObjs: start\n"));
2275 for (oc = objects; oc; oc = oc->next) {
2276 if (oc->status != OBJECT_RESOLVED) {
2277 # if defined(OBJFORMAT_ELF)
2278 r = ocResolve_ELF ( oc );
2279 # elif defined(OBJFORMAT_PEi386)
2280 r = ocResolve_PEi386 ( oc );
2281 # elif defined(OBJFORMAT_MACHO)
2282 r = ocResolve_MachO ( oc );
2284 barf("resolveObjs: not implemented on this platform");
2286 if (!r) { return r; }
2287 oc->status = OBJECT_RESOLVED;
2290 IF_DEBUG(linker, debugBelch("resolveObjs: done\n"));
2294 /* -----------------------------------------------------------------------------
2295 * delete an object from the pool
2298 unloadObj( char *path )
2300 ObjectCode *oc, *prev;
2301 HsBool unloadedAnyObj = HS_BOOL_FALSE;
2303 ASSERT(symhash != NULL);
2304 ASSERT(objects != NULL);
2309 for (oc = objects; oc; prev = oc, oc = oc->next) {
2310 if (!strcmp(oc->fileName,path)) {
2312 /* Remove all the mappings for the symbols within this
2317 for (i = 0; i < oc->n_symbols; i++) {
2318 if (oc->symbols[i] != NULL) {
2319 removeStrHashTable(symhash, oc->symbols[i], NULL);
2327 prev->next = oc->next;
2330 // We're going to leave this in place, in case there are
2331 // any pointers from the heap into it:
2332 // #ifdef mingw32_HOST_OS
2333 // VirtualFree(oc->image);
2335 // stgFree(oc->image);
2337 stgFree(oc->fileName);
2338 stgFree(oc->symbols);
2339 stgFree(oc->sections);
2342 /* This could be a member of an archive so continue
2343 * unloading other members. */
2344 unloadedAnyObj = HS_BOOL_TRUE;
2348 if (unloadedAnyObj) {
2352 errorBelch("unloadObj: can't find `%s' to unload", path);
2357 /* -----------------------------------------------------------------------------
2358 * Sanity checking. For each ObjectCode, maintain a list of address ranges
2359 * which may be prodded during relocation, and abort if we try and write
2360 * outside any of these.
2363 addProddableBlock ( ObjectCode* oc, void* start, int size )
2366 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
2368 IF_DEBUG(linker, debugBelch("addProddableBlock: %p %p %d\n", oc, start, size));
2372 pb->next = oc->proddables;
2373 oc->proddables = pb;
2377 checkProddableBlock (ObjectCode *oc, void *addr )
2381 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
2382 char* s = (char*)(pb->start);
2383 char* e = s + pb->size - 1;
2384 char* a = (char*)addr;
2385 /* Assumes that the biggest fixup involves a 4-byte write. This
2386 probably needs to be changed to 8 (ie, +7) on 64-bit
2388 if (a >= s && (a+3) <= e) return;
2390 barf("checkProddableBlock: invalid fixup in runtime linker");
2393 /* -----------------------------------------------------------------------------
2394 * Section management.
2397 addSection ( ObjectCode* oc, SectionKind kind,
2398 void* start, void* end )
2400 Section* s = stgMallocBytes(sizeof(Section), "addSection");
2404 s->next = oc->sections;
2407 IF_DEBUG(linker, debugBelch("addSection: %p-%p (size %ld), kind %d\n",
2408 start, ((char*)end)-1, (long)end - (long)start + 1, kind ));
2412 /* --------------------------------------------------------------------------
2414 * This is about allocating a small chunk of memory for every symbol in the
2415 * object file. We make sure that the SymboLExtras are always "in range" of
2416 * limited-range PC-relative instructions on various platforms by allocating
2417 * them right next to the object code itself.
2420 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2423 ocAllocateSymbolExtras
2425 Allocate additional space at the end of the object file image to make room
2426 for jump islands (powerpc, x86_64) and GOT entries (x86_64).
2428 PowerPC relative branch instructions have a 24 bit displacement field.
2429 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
2430 If a particular imported symbol is outside this range, we have to redirect
2431 the jump to a short piece of new code that just loads the 32bit absolute
2432 address and jumps there.
2433 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
2436 This function just allocates space for one SymbolExtra for every
2437 undefined symbol in the object file. The code for the jump islands is
2438 filled in by makeSymbolExtra below.
2441 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
2448 int misalignment = 0;
2449 #ifdef darwin_HOST_OS
2450 misalignment = oc->misalignment;
2456 // round up to the nearest 4
2457 aligned = (oc->fileSize + 3) & ~3;
2460 pagesize = getpagesize();
2461 n = ROUND_UP( oc->fileSize, pagesize );
2462 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
2464 /* we try to use spare space at the end of the last page of the
2465 * image for the jump islands, but if there isn't enough space
2466 * then we have to map some (anonymously, remembering MAP_32BIT).
2468 if( m > n ) // we need to allocate more pages
2470 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
2475 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2478 oc->image -= misalignment;
2479 oc->image = stgReallocBytes( oc->image,
2481 aligned + sizeof (SymbolExtra) * count,
2482 "ocAllocateSymbolExtras" );
2483 oc->image += misalignment;
2485 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2486 #endif /* USE_MMAP */
2488 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
2491 oc->symbol_extras = NULL;
2493 oc->first_symbol_extra = first;
2494 oc->n_symbol_extras = count;
2499 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
2500 unsigned long symbolNumber,
2501 unsigned long target )
2505 ASSERT( symbolNumber >= oc->first_symbol_extra
2506 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
2508 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
2510 #ifdef powerpc_HOST_ARCH
2511 // lis r12, hi16(target)
2512 extra->jumpIsland.lis_r12 = 0x3d80;
2513 extra->jumpIsland.hi_addr = target >> 16;
2515 // ori r12, r12, lo16(target)
2516 extra->jumpIsland.ori_r12_r12 = 0x618c;
2517 extra->jumpIsland.lo_addr = target & 0xffff;
2520 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2523 extra->jumpIsland.bctr = 0x4e800420;
2525 #ifdef x86_64_HOST_ARCH
2527 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2528 extra->addr = target;
2529 memcpy(extra->jumpIsland, jmp, 6);
2537 /* --------------------------------------------------------------------------
2538 * PowerPC specifics (instruction cache flushing)
2539 * ------------------------------------------------------------------------*/
2541 #ifdef powerpc_HOST_ARCH
2543 ocFlushInstructionCache
2545 Flush the data & instruction caches.
2546 Because the PPC has split data/instruction caches, we have to
2547 do that whenever we modify code at runtime.
2551 ocFlushInstructionCacheFrom(void* begin, size_t length)
2553 size_t n = (length + 3) / 4;
2554 unsigned long* p = begin;
2558 __asm__ volatile ( "dcbf 0,%0\n\t"
2566 __asm__ volatile ( "sync\n\t"
2572 ocFlushInstructionCache( ObjectCode *oc )
2574 /* The main object code */
2575 ocFlushInstructionCacheFrom(oc->image + oc->misalignment, oc->fileSize);
2578 ocFlushInstructionCacheFrom(oc->symbol_extras, sizeof(SymbolExtra) * oc->n_symbol_extras);
2580 #endif /* powerpc_HOST_ARCH */
2583 /* --------------------------------------------------------------------------
2584 * PEi386 specifics (Win32 targets)
2585 * ------------------------------------------------------------------------*/
2587 /* The information for this linker comes from
2588 Microsoft Portable Executable
2589 and Common Object File Format Specification
2590 revision 5.1 January 1998
2591 which SimonM says comes from the MS Developer Network CDs.
2593 It can be found there (on older CDs), but can also be found
2596 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
2598 (this is Rev 6.0 from February 1999).
2600 Things move, so if that fails, try searching for it via
2602 http://www.google.com/search?q=PE+COFF+specification
2604 The ultimate reference for the PE format is the Winnt.h
2605 header file that comes with the Platform SDKs; as always,
2606 implementations will drift wrt their documentation.
2608 A good background article on the PE format is Matt Pietrek's
2609 March 1994 article in Microsoft System Journal (MSJ)
2610 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
2611 Win32 Portable Executable File Format." The info in there
2612 has recently been updated in a two part article in
2613 MSDN magazine, issues Feb and March 2002,
2614 "Inside Windows: An In-Depth Look into the Win32 Portable
2615 Executable File Format"
2617 John Levine's book "Linkers and Loaders" contains useful
2622 #if defined(OBJFORMAT_PEi386)
2626 typedef unsigned char UChar;
2627 typedef unsigned short UInt16;
2628 typedef unsigned int UInt32;
2635 UInt16 NumberOfSections;
2636 UInt32 TimeDateStamp;
2637 UInt32 PointerToSymbolTable;
2638 UInt32 NumberOfSymbols;
2639 UInt16 SizeOfOptionalHeader;
2640 UInt16 Characteristics;
2644 #define sizeof_COFF_header 20
2651 UInt32 VirtualAddress;
2652 UInt32 SizeOfRawData;
2653 UInt32 PointerToRawData;
2654 UInt32 PointerToRelocations;
2655 UInt32 PointerToLinenumbers;
2656 UInt16 NumberOfRelocations;
2657 UInt16 NumberOfLineNumbers;
2658 UInt32 Characteristics;
2662 #define sizeof_COFF_section 40
2669 UInt16 SectionNumber;
2672 UChar NumberOfAuxSymbols;
2676 #define sizeof_COFF_symbol 18
2681 UInt32 VirtualAddress;
2682 UInt32 SymbolTableIndex;
2687 #define sizeof_COFF_reloc 10
2690 /* From PE spec doc, section 3.3.2 */
2691 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
2692 windows.h -- for the same purpose, but I want to know what I'm
2694 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
2695 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
2696 #define MYIMAGE_FILE_DLL 0x2000
2697 #define MYIMAGE_FILE_SYSTEM 0x1000
2698 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
2699 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
2700 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
2702 /* From PE spec doc, section 5.4.2 and 5.4.4 */
2703 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
2704 #define MYIMAGE_SYM_CLASS_STATIC 3
2705 #define MYIMAGE_SYM_UNDEFINED 0
2707 /* From PE spec doc, section 4.1 */
2708 #define MYIMAGE_SCN_CNT_CODE 0x00000020
2709 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
2710 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
2712 /* From PE spec doc, section 5.2.1 */
2713 #define MYIMAGE_REL_I386_DIR32 0x0006
2714 #define MYIMAGE_REL_I386_REL32 0x0014
2717 /* We use myindex to calculate array addresses, rather than
2718 simply doing the normal subscript thing. That's because
2719 some of the above structs have sizes which are not
2720 a whole number of words. GCC rounds their sizes up to a
2721 whole number of words, which means that the address calcs
2722 arising from using normal C indexing or pointer arithmetic
2723 are just plain wrong. Sigh.
2726 myindex ( int scale, void* base, int index )
2729 ((UChar*)base) + scale * index;
2734 printName ( UChar* name, UChar* strtab )
2736 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2737 UInt32 strtab_offset = * (UInt32*)(name+4);
2738 debugBelch("%s", strtab + strtab_offset );
2741 for (i = 0; i < 8; i++) {
2742 if (name[i] == 0) break;
2743 debugBelch("%c", name[i] );
2750 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
2752 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2753 UInt32 strtab_offset = * (UInt32*)(name+4);
2754 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
2760 if (name[i] == 0) break;
2770 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
2773 /* If the string is longer than 8 bytes, look in the
2774 string table for it -- this will be correctly zero terminated.
2776 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2777 UInt32 strtab_offset = * (UInt32*)(name+4);
2778 return ((UChar*)strtab) + strtab_offset;
2780 /* Otherwise, if shorter than 8 bytes, return the original,
2781 which by defn is correctly terminated.
2783 if (name[7]==0) return name;
2784 /* The annoying case: 8 bytes. Copy into a temporary
2785 (XXX which is never freed ...)
2787 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
2789 strncpy((char*)newstr,(char*)name,8);
2794 /* Getting the name of a section is mildly tricky, so we make a
2795 function for it. Sadly, in one case we have to copy the string
2796 (when it is exactly 8 bytes long there's no trailing '\0'), so for
2797 consistency we *always* copy the string; the caller must free it
2800 cstring_from_section_name (UChar* name, UChar* strtab)
2805 int strtab_offset = strtol((char*)name+1,NULL,10);
2806 int len = strlen(((char*)strtab) + strtab_offset);
2808 newstr = stgMallocBytes(len, "cstring_from_section_symbol_name");
2809 strcpy((char*)newstr, (char*)((UChar*)strtab) + strtab_offset);
2814 newstr = stgMallocBytes(9, "cstring_from_section_symbol_name");
2816 strncpy((char*)newstr,(char*)name,8);
2822 /* Just compares the short names (first 8 chars) */
2823 static COFF_section *
2824 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
2828 = (COFF_header*)(oc->image);
2829 COFF_section* sectab
2831 ((UChar*)(oc->image))
2832 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2834 for (i = 0; i < hdr->NumberOfSections; i++) {
2837 COFF_section* section_i
2839 myindex ( sizeof_COFF_section, sectab, i );
2840 n1 = (UChar*) &(section_i->Name);
2842 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2843 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2844 n1[6]==n2[6] && n1[7]==n2[7])
2853 zapTrailingAtSign ( UChar* sym )
2855 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2857 if (sym[0] == 0) return;
2859 while (sym[i] != 0) i++;
2862 while (j > 0 && my_isdigit(sym[j])) j--;
2863 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2868 lookupSymbolInDLLs ( UChar *lbl )
2873 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2874 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2876 if (lbl[0] == '_') {
2877 /* HACK: if the name has an initial underscore, try stripping
2878 it off & look that up first. I've yet to verify whether there's
2879 a Rule that governs whether an initial '_' *should always* be
2880 stripped off when mapping from import lib name to the DLL name.
2882 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
2884 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2888 sym = GetProcAddress(o_dll->instance, (char*)lbl);
2890 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2899 ocVerifyImage_PEi386 ( ObjectCode* oc )
2904 COFF_section* sectab;
2905 COFF_symbol* symtab;
2907 /* debugBelch("\nLOADING %s\n", oc->fileName); */
2908 hdr = (COFF_header*)(oc->image);
2909 sectab = (COFF_section*) (
2910 ((UChar*)(oc->image))
2911 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2913 symtab = (COFF_symbol*) (
2914 ((UChar*)(oc->image))
2915 + hdr->PointerToSymbolTable
2917 strtab = ((UChar*)symtab)
2918 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2920 if (hdr->Machine != 0x14c) {
2921 errorBelch("%s: Not x86 PEi386", oc->fileName);
2924 if (hdr->SizeOfOptionalHeader != 0) {
2925 errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2928 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2929 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2930 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2931 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2932 errorBelch("%s: Not a PEi386 object file", oc->fileName);
2935 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2936 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2937 errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2939 (int)(hdr->Characteristics));
2942 /* If the string table size is way crazy, this might indicate that
2943 there are more than 64k relocations, despite claims to the
2944 contrary. Hence this test. */
2945 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2947 if ( (*(UInt32*)strtab) > 600000 ) {
2948 /* Note that 600k has no special significance other than being
2949 big enough to handle the almost-2MB-sized lumps that
2950 constitute HSwin32*.o. */
2951 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2956 /* No further verification after this point; only debug printing. */
2958 IF_DEBUG(linker, i=1);
2959 if (i == 0) return 1;
2961 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2962 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2963 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2966 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
2967 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
2968 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2969 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
2970 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
2971 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
2972 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
2974 /* Print the section table. */
2976 for (i = 0; i < hdr->NumberOfSections; i++) {
2978 COFF_section* sectab_i
2980 myindex ( sizeof_COFF_section, sectab, i );
2987 printName ( sectab_i->Name, strtab );
2997 sectab_i->VirtualSize,
2998 sectab_i->VirtualAddress,
2999 sectab_i->SizeOfRawData,
3000 sectab_i->PointerToRawData,
3001 sectab_i->NumberOfRelocations,
3002 sectab_i->PointerToRelocations,
3003 sectab_i->PointerToRawData
3005 reltab = (COFF_reloc*) (
3006 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3009 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3010 /* If the relocation field (a short) has overflowed, the
3011 * real count can be found in the first reloc entry.
3013 * See Section 4.1 (last para) of the PE spec (rev6.0).
3015 COFF_reloc* rel = (COFF_reloc*)
3016 myindex ( sizeof_COFF_reloc, reltab, 0 );
3017 noRelocs = rel->VirtualAddress;
3020 noRelocs = sectab_i->NumberOfRelocations;
3024 for (; j < noRelocs; j++) {
3026 COFF_reloc* rel = (COFF_reloc*)
3027 myindex ( sizeof_COFF_reloc, reltab, j );
3029 " type 0x%-4x vaddr 0x%-8x name `",
3031 rel->VirtualAddress );
3032 sym = (COFF_symbol*)
3033 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
3034 /* Hmm..mysterious looking offset - what's it for? SOF */
3035 printName ( sym->Name, strtab -10 );
3042 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
3043 debugBelch("---START of string table---\n");
3044 for (i = 4; i < *(Int32*)strtab; i++) {
3046 debugBelch("\n"); else
3047 debugBelch("%c", strtab[i] );
3049 debugBelch("--- END of string table---\n");
3054 COFF_symbol* symtab_i;
3055 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3056 symtab_i = (COFF_symbol*)
3057 myindex ( sizeof_COFF_symbol, symtab, i );
3063 printName ( symtab_i->Name, strtab );
3072 (Int32)(symtab_i->SectionNumber),
3073 (UInt32)symtab_i->Type,
3074 (UInt32)symtab_i->StorageClass,
3075 (UInt32)symtab_i->NumberOfAuxSymbols
3077 i += symtab_i->NumberOfAuxSymbols;
3087 ocGetNames_PEi386 ( ObjectCode* oc )
3090 COFF_section* sectab;
3091 COFF_symbol* symtab;
3098 hdr = (COFF_header*)(oc->image);
3099 sectab = (COFF_section*) (
3100 ((UChar*)(oc->image))
3101 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3103 symtab = (COFF_symbol*) (
3104 ((UChar*)(oc->image))
3105 + hdr->PointerToSymbolTable
3107 strtab = ((UChar*)(oc->image))
3108 + hdr->PointerToSymbolTable
3109 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3111 /* Allocate space for any (local, anonymous) .bss sections. */
3113 for (i = 0; i < hdr->NumberOfSections; i++) {
3116 COFF_section* sectab_i
3118 myindex ( sizeof_COFF_section, sectab, i );
3120 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3122 if (0 != strcmp(secname, ".bss")) {
3129 /* sof 10/05: the PE spec text isn't too clear regarding what
3130 * the SizeOfRawData field is supposed to hold for object
3131 * file sections containing just uninitialized data -- for executables,
3132 * it is supposed to be zero; unclear what it's supposed to be
3133 * for object files. However, VirtualSize is guaranteed to be
3134 * zero for object files, which definitely suggests that SizeOfRawData
3135 * will be non-zero (where else would the size of this .bss section be
3136 * stored?) Looking at the COFF_section info for incoming object files,
3137 * this certainly appears to be the case.
3139 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
3140 * object files up until now. This turned out to bite us with ghc-6.4.1's use
3141 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
3142 * variable decls into to the .bss section. (The specific function in Q which
3143 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
3145 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
3146 /* This is a non-empty .bss section. Allocate zeroed space for
3147 it, and set its PointerToRawData field such that oc->image +
3148 PointerToRawData == addr_of_zeroed_space. */
3149 bss_sz = sectab_i->VirtualSize;
3150 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
3151 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
3152 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
3153 addProddableBlock(oc, zspace, bss_sz);
3154 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
3157 /* Copy section information into the ObjectCode. */
3159 for (i = 0; i < hdr->NumberOfSections; i++) {
3165 = SECTIONKIND_OTHER;
3166 COFF_section* sectab_i
3168 myindex ( sizeof_COFF_section, sectab, i );
3170 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3172 IF_DEBUG(linker, debugBelch("section name = %s\n", secname ));
3175 /* I'm sure this is the Right Way to do it. However, the
3176 alternative of testing the sectab_i->Name field seems to
3177 work ok with Cygwin.
3179 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
3180 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
3181 kind = SECTIONKIND_CODE_OR_RODATA;
3184 if (0==strcmp(".text",(char*)secname) ||
3185 0==strcmp(".rdata",(char*)secname)||
3186 0==strcmp(".rodata",(char*)secname))
3187 kind = SECTIONKIND_CODE_OR_RODATA;
3188 if (0==strcmp(".data",(char*)secname) ||
3189 0==strcmp(".bss",(char*)secname))
3190 kind = SECTIONKIND_RWDATA;
3192 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
3193 sz = sectab_i->SizeOfRawData;
3194 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
3196 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
3197 end = start + sz - 1;
3199 if (kind == SECTIONKIND_OTHER
3200 /* Ignore sections called which contain stabs debugging
3202 && 0 != strcmp(".stab", (char*)secname)
3203 && 0 != strcmp(".stabstr", (char*)secname)
3204 /* ignore constructor section for now */
3205 && 0 != strcmp(".ctors", (char*)secname)
3206 /* ignore section generated from .ident */
3207 && 0!= strncmp(".debug", (char*)secname, 6)
3208 /* ignore unknown section that appeared in gcc 3.4.5(?) */
3209 && 0!= strcmp(".reloc", (char*)secname)
3210 && 0 != strcmp(".rdata$zzz", (char*)secname)
3212 errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", secname, oc->fileName);
3217 if (kind != SECTIONKIND_OTHER && end >= start) {
3218 addSection(oc, kind, start, end);
3219 addProddableBlock(oc, start, end - start + 1);
3225 /* Copy exported symbols into the ObjectCode. */
3227 oc->n_symbols = hdr->NumberOfSymbols;
3228 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3229 "ocGetNames_PEi386(oc->symbols)");
3230 /* Call me paranoid; I don't care. */
3231 for (i = 0; i < oc->n_symbols; i++)
3232 oc->symbols[i] = NULL;
3236 COFF_symbol* symtab_i;
3237 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3238 symtab_i = (COFF_symbol*)
3239 myindex ( sizeof_COFF_symbol, symtab, i );
3243 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
3244 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
3245 /* This symbol is global and defined, viz, exported */
3246 /* for MYIMAGE_SYMCLASS_EXTERNAL
3247 && !MYIMAGE_SYM_UNDEFINED,
3248 the address of the symbol is:
3249 address of relevant section + offset in section
3251 COFF_section* sectabent
3252 = (COFF_section*) myindex ( sizeof_COFF_section,
3254 symtab_i->SectionNumber-1 );
3255 addr = ((UChar*)(oc->image))
3256 + (sectabent->PointerToRawData
3260 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
3261 && symtab_i->Value > 0) {
3262 /* This symbol isn't in any section at all, ie, global bss.
3263 Allocate zeroed space for it. */
3264 addr = stgCallocBytes(1, symtab_i->Value,
3265 "ocGetNames_PEi386(non-anonymous bss)");
3266 addSection(oc, SECTIONKIND_RWDATA, addr,
3267 ((UChar*)addr) + symtab_i->Value - 1);
3268 addProddableBlock(oc, addr, symtab_i->Value);
3269 /* debugBelch("BSS section at 0x%x\n", addr); */
3272 if (addr != NULL ) {
3273 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
3274 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
3275 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
3276 ASSERT(i >= 0 && i < oc->n_symbols);
3277 /* cstring_from_COFF_symbol_name always succeeds. */
3278 oc->symbols[i] = (char*)sname;
3279 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
3283 "IGNORING symbol %d\n"
3287 printName ( symtab_i->Name, strtab );
3296 (Int32)(symtab_i->SectionNumber),
3297 (UInt32)symtab_i->Type,
3298 (UInt32)symtab_i->StorageClass,
3299 (UInt32)symtab_i->NumberOfAuxSymbols
3304 i += symtab_i->NumberOfAuxSymbols;
3313 ocResolve_PEi386 ( ObjectCode* oc )
3316 COFF_section* sectab;
3317 COFF_symbol* symtab;
3327 /* ToDo: should be variable-sized? But is at least safe in the
3328 sense of buffer-overrun-proof. */
3330 /* debugBelch("resolving for %s\n", oc->fileName); */
3332 hdr = (COFF_header*)(oc->image);
3333 sectab = (COFF_section*) (
3334 ((UChar*)(oc->image))
3335 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3337 symtab = (COFF_symbol*) (
3338 ((UChar*)(oc->image))
3339 + hdr->PointerToSymbolTable
3341 strtab = ((UChar*)(oc->image))
3342 + hdr->PointerToSymbolTable
3343 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3345 for (i = 0; i < hdr->NumberOfSections; i++) {
3346 COFF_section* sectab_i
3348 myindex ( sizeof_COFF_section, sectab, i );
3351 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3354 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3356 /* Ignore sections called which contain stabs debugging
3358 if (0 == strcmp(".stab", (char*)secname)
3359 || 0 == strcmp(".stabstr", (char*)secname)
3360 || 0 == strcmp(".ctors", (char*)secname)
3361 || 0 == strncmp(".debug", (char*)secname, 6)
3362 || 0 == strcmp(".rdata$zzz", (char*)secname)) {
3369 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3370 /* If the relocation field (a short) has overflowed, the
3371 * real count can be found in the first reloc entry.
3373 * See Section 4.1 (last para) of the PE spec (rev6.0).
3375 * Nov2003 update: the GNU linker still doesn't correctly
3376 * handle the generation of relocatable object files with
3377 * overflown relocations. Hence the output to warn of potential
3380 COFF_reloc* rel = (COFF_reloc*)
3381 myindex ( sizeof_COFF_reloc, reltab, 0 );
3382 noRelocs = rel->VirtualAddress;
3384 /* 10/05: we now assume (and check for) a GNU ld that is capable
3385 * of handling object files with (>2^16) of relocs.
3388 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
3393 noRelocs = sectab_i->NumberOfRelocations;
3398 for (; j < noRelocs; j++) {
3400 COFF_reloc* reltab_j
3402 myindex ( sizeof_COFF_reloc, reltab, j );
3404 /* the location to patch */
3406 ((UChar*)(oc->image))
3407 + (sectab_i->PointerToRawData
3408 + reltab_j->VirtualAddress
3409 - sectab_i->VirtualAddress )
3411 /* the existing contents of pP */
3413 /* the symbol to connect to */
3414 sym = (COFF_symbol*)
3415 myindex ( sizeof_COFF_symbol,
3416 symtab, reltab_j->SymbolTableIndex );
3419 "reloc sec %2d num %3d: type 0x%-4x "
3420 "vaddr 0x%-8x name `",
3422 (UInt32)reltab_j->Type,
3423 reltab_j->VirtualAddress );
3424 printName ( sym->Name, strtab );
3425 debugBelch("'\n" ));
3427 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
3428 COFF_section* section_sym
3429 = findPEi386SectionCalled ( oc, sym->Name );
3431 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
3434 S = ((UInt32)(oc->image))
3435 + (section_sym->PointerToRawData
3438 copyName ( sym->Name, strtab, symbol, 1000-1 );
3439 S = (UInt32) lookupSymbol( (char*)symbol );
3440 if ((void*)S != NULL) goto foundit;
3441 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3445 checkProddableBlock(oc, pP);
3446 switch (reltab_j->Type) {
3447 case MYIMAGE_REL_I386_DIR32:
3450 case MYIMAGE_REL_I386_REL32:
3451 /* Tricky. We have to insert a displacement at
3452 pP which, when added to the PC for the _next_
3453 insn, gives the address of the target (S).
3454 Problem is to know the address of the next insn
3455 when we only know pP. We assume that this
3456 literal field is always the last in the insn,
3457 so that the address of the next insn is pP+4
3458 -- hence the constant 4.
3459 Also I don't know if A should be added, but so
3460 far it has always been zero.
3462 SOF 05/2005: 'A' (old contents of *pP) have been observed
3463 to contain values other than zero (the 'wx' object file
3464 that came with wxhaskell-0.9.4; dunno how it was compiled..).
3465 So, add displacement to old value instead of asserting
3466 A to be zero. Fixes wxhaskell-related crashes, and no other
3467 ill effects have been observed.
3469 Update: the reason why we're seeing these more elaborate
3470 relocations is due to a switch in how the NCG compiles SRTs
3471 and offsets to them from info tables. SRTs live in .(ro)data,
3472 while info tables live in .text, causing GAS to emit REL32/DISP32
3473 relocations with non-zero values. Adding the displacement is
3474 the right thing to do.
3476 *pP = S - ((UInt32)pP) - 4 + A;
3479 debugBelch("%s: unhandled PEi386 relocation type %d",
3480 oc->fileName, reltab_j->Type);
3487 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
3491 #endif /* defined(OBJFORMAT_PEi386) */
3494 /* --------------------------------------------------------------------------
3496 * ------------------------------------------------------------------------*/
3498 #if defined(OBJFORMAT_ELF)
3503 #if defined(sparc_HOST_ARCH)
3504 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
3505 #elif defined(i386_HOST_ARCH)
3506 # define ELF_TARGET_386 /* Used inside <elf.h> */
3507 #elif defined(x86_64_HOST_ARCH)
3508 # define ELF_TARGET_X64_64
3512 #if !defined(openbsd_HOST_OS)
3515 /* openbsd elf has things in different places, with diff names */
3516 # include <elf_abi.h>
3517 # include <machine/reloc.h>
3518 # define R_386_32 RELOC_32
3519 # define R_386_PC32 RELOC_PC32
3522 /* If elf.h doesn't define it */
3523 # ifndef R_X86_64_PC64
3524 # define R_X86_64_PC64 24
3528 * Define a set of types which can be used for both ELF32 and ELF64
3532 #define ELFCLASS ELFCLASS64
3533 #define Elf_Addr Elf64_Addr
3534 #define Elf_Word Elf64_Word
3535 #define Elf_Sword Elf64_Sword
3536 #define Elf_Ehdr Elf64_Ehdr
3537 #define Elf_Phdr Elf64_Phdr
3538 #define Elf_Shdr Elf64_Shdr
3539 #define Elf_Sym Elf64_Sym
3540 #define Elf_Rel Elf64_Rel
3541 #define Elf_Rela Elf64_Rela
3543 #define ELF_ST_TYPE ELF64_ST_TYPE
3546 #define ELF_ST_BIND ELF64_ST_BIND
3549 #define ELF_R_TYPE ELF64_R_TYPE
3552 #define ELF_R_SYM ELF64_R_SYM
3555 #define ELFCLASS ELFCLASS32
3556 #define Elf_Addr Elf32_Addr
3557 #define Elf_Word Elf32_Word
3558 #define Elf_Sword Elf32_Sword
3559 #define Elf_Ehdr Elf32_Ehdr
3560 #define Elf_Phdr Elf32_Phdr
3561 #define Elf_Shdr Elf32_Shdr
3562 #define Elf_Sym Elf32_Sym
3563 #define Elf_Rel Elf32_Rel
3564 #define Elf_Rela Elf32_Rela
3566 #define ELF_ST_TYPE ELF32_ST_TYPE
3569 #define ELF_ST_BIND ELF32_ST_BIND
3572 #define ELF_R_TYPE ELF32_R_TYPE
3575 #define ELF_R_SYM ELF32_R_SYM
3581 * Functions to allocate entries in dynamic sections. Currently we simply
3582 * preallocate a large number, and we don't check if a entry for the given
3583 * target already exists (a linear search is too slow). Ideally these
3584 * entries would be associated with symbols.
3587 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
3588 #define GOT_SIZE 0x20000
3589 #define FUNCTION_TABLE_SIZE 0x10000
3590 #define PLT_SIZE 0x08000
3593 static Elf_Addr got[GOT_SIZE];
3594 static unsigned int gotIndex;
3595 static Elf_Addr gp_val = (Elf_Addr)got;
3598 allocateGOTEntry(Elf_Addr target)
3602 if (gotIndex >= GOT_SIZE)
3603 barf("Global offset table overflow");
3605 entry = &got[gotIndex++];
3607 return (Elf_Addr)entry;
3611 #ifdef ELF_FUNCTION_DESC
3617 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
3618 static unsigned int functionTableIndex;
3621 allocateFunctionDesc(Elf_Addr target)
3623 FunctionDesc *entry;
3625 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
3626 barf("Function table overflow");
3628 entry = &functionTable[functionTableIndex++];
3630 entry->gp = (Elf_Addr)gp_val;
3631 return (Elf_Addr)entry;
3635 copyFunctionDesc(Elf_Addr target)
3637 FunctionDesc *olddesc = (FunctionDesc *)target;
3638 FunctionDesc *newdesc;
3640 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
3641 newdesc->gp = olddesc->gp;
3642 return (Elf_Addr)newdesc;
3649 unsigned char code[sizeof(plt_code)];
3653 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
3655 PLTEntry *plt = (PLTEntry *)oc->plt;
3658 if (oc->pltIndex >= PLT_SIZE)
3659 barf("Procedure table overflow");
3661 entry = &plt[oc->pltIndex++];
3662 memcpy(entry->code, plt_code, sizeof(entry->code));
3663 PLT_RELOC(entry->code, target);
3664 return (Elf_Addr)entry;
3670 return (PLT_SIZE * sizeof(PLTEntry));
3676 * Generic ELF functions
3680 findElfSection ( void* objImage, Elf_Word sh_type )
3682 char* ehdrC = (char*)objImage;
3683 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3684 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
3685 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3689 for (i = 0; i < ehdr->e_shnum; i++) {
3690 if (shdr[i].sh_type == sh_type
3691 /* Ignore the section header's string table. */
3692 && i != ehdr->e_shstrndx
3693 /* Ignore string tables named .stabstr, as they contain
3695 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3697 ptr = ehdrC + shdr[i].sh_offset;
3705 ocVerifyImage_ELF ( ObjectCode* oc )
3709 int i, j, nent, nstrtab, nsymtabs;
3713 char* ehdrC = (char*)(oc->image);
3714 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3716 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
3717 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
3718 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
3719 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
3720 errorBelch("%s: not an ELF object", oc->fileName);
3724 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
3725 errorBelch("%s: unsupported ELF format", oc->fileName);
3729 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
3730 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
3732 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
3733 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
3735 errorBelch("%s: unknown endiannness", oc->fileName);
3739 if (ehdr->e_type != ET_REL) {
3740 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
3743 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
3745 IF_DEBUG(linker,debugBelch( "Architecture is " ));
3746 switch (ehdr->e_machine) {
3747 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
3748 #ifdef EM_SPARC32PLUS
3749 case EM_SPARC32PLUS:
3751 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
3753 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
3755 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
3757 case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
3758 #elif defined(EM_AMD64)
3759 case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
3761 default: IF_DEBUG(linker,debugBelch( "unknown" ));
3762 errorBelch("%s: unknown architecture (e_machine == %d)"
3763 , oc->fileName, ehdr->e_machine);
3767 IF_DEBUG(linker,debugBelch(
3768 "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
3769 (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
3771 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
3773 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3775 if (ehdr->e_shstrndx == SHN_UNDEF) {
3776 errorBelch("%s: no section header string table", oc->fileName);
3779 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
3781 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3784 for (i = 0; i < ehdr->e_shnum; i++) {
3785 IF_DEBUG(linker,debugBelch("%2d: ", i ));
3786 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
3787 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
3788 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
3789 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
3790 ehdrC + shdr[i].sh_offset,
3791 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
3793 if (shdr[i].sh_type == SHT_REL) {
3794 IF_DEBUG(linker,debugBelch("Rel " ));
3795 } else if (shdr[i].sh_type == SHT_RELA) {
3796 IF_DEBUG(linker,debugBelch("RelA " ));
3798 IF_DEBUG(linker,debugBelch(" "));
3801 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
3805 IF_DEBUG(linker,debugBelch( "\nString tables" ));
3808 for (i = 0; i < ehdr->e_shnum; i++) {
3809 if (shdr[i].sh_type == SHT_STRTAB
3810 /* Ignore the section header's string table. */
3811 && i != ehdr->e_shstrndx
3812 /* Ignore string tables named .stabstr, as they contain
3814 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3816 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
3817 strtab = ehdrC + shdr[i].sh_offset;
3822 errorBelch("%s: no string tables, or too many", oc->fileName);
3827 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
3828 for (i = 0; i < ehdr->e_shnum; i++) {
3829 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3830 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
3832 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3833 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3834 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%ld rem)\n",
3836 (long)shdr[i].sh_size % sizeof(Elf_Sym)
3838 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
3839 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
3842 for (j = 0; j < nent; j++) {
3843 IF_DEBUG(linker,debugBelch(" %2d ", j ));
3844 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
3845 (int)stab[j].st_shndx,
3846 (int)stab[j].st_size,
3847 (char*)stab[j].st_value ));
3849 IF_DEBUG(linker,debugBelch("type=" ));
3850 switch (ELF_ST_TYPE(stab[j].st_info)) {
3851 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
3852 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
3853 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
3854 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
3855 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
3856 default: IF_DEBUG(linker,debugBelch("? " )); break;
3858 IF_DEBUG(linker,debugBelch(" " ));
3860 IF_DEBUG(linker,debugBelch("bind=" ));
3861 switch (ELF_ST_BIND(stab[j].st_info)) {
3862 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
3863 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
3864 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
3865 default: IF_DEBUG(linker,debugBelch("? " )); break;
3867 IF_DEBUG(linker,debugBelch(" " ));
3869 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3873 if (nsymtabs == 0) {
3874 errorBelch("%s: didn't find any symbol tables", oc->fileName);
3881 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3885 if (hdr->sh_type == SHT_PROGBITS
3886 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3887 /* .text-style section */
3888 return SECTIONKIND_CODE_OR_RODATA;
3891 if (hdr->sh_type == SHT_PROGBITS
3892 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3893 /* .data-style section */
3894 return SECTIONKIND_RWDATA;
3897 if (hdr->sh_type == SHT_PROGBITS
3898 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3899 /* .rodata-style section */
3900 return SECTIONKIND_CODE_OR_RODATA;
3903 if (hdr->sh_type == SHT_NOBITS
3904 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3905 /* .bss-style section */
3907 return SECTIONKIND_RWDATA;
3910 return SECTIONKIND_OTHER;
3915 ocGetNames_ELF ( ObjectCode* oc )
3920 char* ehdrC = (char*)(oc->image);
3921 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3922 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
3923 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3925 ASSERT(symhash != NULL);
3928 errorBelch("%s: no strtab", oc->fileName);
3933 for (i = 0; i < ehdr->e_shnum; i++) {
3934 /* Figure out what kind of section it is. Logic derived from
3935 Figure 1.14 ("Special Sections") of the ELF document
3936 ("Portable Formats Specification, Version 1.1"). */
3938 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
3940 if (is_bss && shdr[i].sh_size > 0) {
3941 /* This is a non-empty .bss section. Allocate zeroed space for
3942 it, and set its .sh_offset field such that
3943 ehdrC + .sh_offset == addr_of_zeroed_space. */
3944 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3945 "ocGetNames_ELF(BSS)");
3946 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3948 debugBelch("BSS section at 0x%x, size %d\n",
3949 zspace, shdr[i].sh_size);
3953 /* fill in the section info */
3954 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3955 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3956 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3957 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3960 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3962 /* copy stuff into this module's object symbol table */
3963 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3964 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3966 oc->n_symbols = nent;
3967 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3968 "ocGetNames_ELF(oc->symbols)");
3970 for (j = 0; j < nent; j++) {
3972 char isLocal = FALSE; /* avoids uninit-var warning */
3974 char* nm = strtab + stab[j].st_name;
3975 int secno = stab[j].st_shndx;
3977 /* Figure out if we want to add it; if so, set ad to its
3978 address. Otherwise leave ad == NULL. */
3980 if (secno == SHN_COMMON) {
3982 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3984 debugBelch("COMMON symbol, size %d name %s\n",
3985 stab[j].st_size, nm);
3987 /* Pointless to do addProddableBlock() for this area,
3988 since the linker should never poke around in it. */
3991 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3992 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3994 /* and not an undefined symbol */
3995 && stab[j].st_shndx != SHN_UNDEF
3996 /* and not in a "special section" */
3997 && stab[j].st_shndx < SHN_LORESERVE
3999 /* and it's a not a section or string table or anything silly */
4000 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
4001 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
4002 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
4005 /* Section 0 is the undefined section, hence > and not >=. */
4006 ASSERT(secno > 0 && secno < ehdr->e_shnum);
4008 if (shdr[secno].sh_type == SHT_NOBITS) {
4009 debugBelch(" BSS symbol, size %d off %d name %s\n",
4010 stab[j].st_size, stab[j].st_value, nm);
4013 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
4014 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
4017 #ifdef ELF_FUNCTION_DESC
4018 /* dlsym() and the initialisation table both give us function
4019 * descriptors, so to be consistent we store function descriptors
4020 * in the symbol table */
4021 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
4022 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
4024 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s\n",
4025 ad, oc->fileName, nm ));
4030 /* And the decision is ... */
4034 oc->symbols[j] = nm;
4037 /* Ignore entirely. */
4039 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
4043 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
4044 strtab + stab[j].st_name ));
4047 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
4048 (int)ELF_ST_BIND(stab[j].st_info),
4049 (int)ELF_ST_TYPE(stab[j].st_info),
4050 (int)stab[j].st_shndx,
4051 strtab + stab[j].st_name
4054 oc->symbols[j] = NULL;
4063 /* Do ELF relocations which lack an explicit addend. All x86-linux
4064 relocations appear to be of this form. */
4066 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
4067 Elf_Shdr* shdr, int shnum,
4068 Elf_Sym* stab, char* strtab )
4073 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
4074 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
4075 int target_shndx = shdr[shnum].sh_info;
4076 int symtab_shndx = shdr[shnum].sh_link;
4078 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
4079 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
4080 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
4081 target_shndx, symtab_shndx ));
4083 /* Skip sections that we're not interested in. */
4086 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
4087 if (kind == SECTIONKIND_OTHER) {
4088 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
4093 for (j = 0; j < nent; j++) {
4094 Elf_Addr offset = rtab[j].r_offset;
4095 Elf_Addr info = rtab[j].r_info;
4097 Elf_Addr P = ((Elf_Addr)targ) + offset;
4098 Elf_Word* pP = (Elf_Word*)P;
4103 StgStablePtr stablePtr;
4106 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
4107 j, (void*)offset, (void*)info ));
4109 IF_DEBUG(linker,debugBelch( " ZERO" ));
4112 Elf_Sym sym = stab[ELF_R_SYM(info)];
4113 /* First see if it is a local symbol. */
4114 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
4115 /* Yes, so we can get the address directly from the ELF symbol
4117 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
4119 (ehdrC + shdr[ sym.st_shndx ].sh_offset
4120 + stab[ELF_R_SYM(info)].st_value);
4123 symbol = strtab + sym.st_name;
4124 stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
4125 if (NULL == stablePtr) {
4126 /* No, so look up the name in our global table. */
4127 S_tmp = lookupSymbol( symbol );
4128 S = (Elf_Addr)S_tmp;
4130 stableVal = deRefStablePtr( stablePtr );
4132 S = (Elf_Addr)S_tmp;
4136 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4139 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
4142 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
4143 (void*)P, (void*)S, (void*)A ));
4144 checkProddableBlock ( oc, pP );
4148 switch (ELF_R_TYPE(info)) {
4149 # ifdef i386_HOST_ARCH
4150 case R_386_32: *pP = value; break;
4151 case R_386_PC32: *pP = value - P; break;
4154 errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
4155 oc->fileName, (lnat)ELF_R_TYPE(info));
4163 /* Do ELF relocations for which explicit addends are supplied.
4164 sparc-solaris relocations appear to be of this form. */
4166 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
4167 Elf_Shdr* shdr, int shnum,
4168 Elf_Sym* stab, char* strtab )
4171 char *symbol = NULL;
4173 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
4174 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
4175 int target_shndx = shdr[shnum].sh_info;
4176 int symtab_shndx = shdr[shnum].sh_link;
4178 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
4179 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
4180 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
4181 target_shndx, symtab_shndx ));
4183 for (j = 0; j < nent; j++) {
4184 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4185 /* This #ifdef only serves to avoid unused-var warnings. */
4186 Elf_Addr offset = rtab[j].r_offset;
4187 Elf_Addr P = targ + offset;
4189 Elf_Addr info = rtab[j].r_info;
4190 Elf_Addr A = rtab[j].r_addend;
4194 # if defined(sparc_HOST_ARCH)
4195 Elf_Word* pP = (Elf_Word*)P;
4197 # elif defined(powerpc_HOST_ARCH)
4201 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
4202 j, (void*)offset, (void*)info,
4205 IF_DEBUG(linker,debugBelch( " ZERO" ));
4208 Elf_Sym sym = stab[ELF_R_SYM(info)];
4209 /* First see if it is a local symbol. */
4210 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
4211 /* Yes, so we can get the address directly from the ELF symbol
4213 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
4215 (ehdrC + shdr[ sym.st_shndx ].sh_offset
4216 + stab[ELF_R_SYM(info)].st_value);
4217 #ifdef ELF_FUNCTION_DESC
4218 /* Make a function descriptor for this function */
4219 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
4220 S = allocateFunctionDesc(S + A);
4225 /* No, so look up the name in our global table. */
4226 symbol = strtab + sym.st_name;
4227 S_tmp = lookupSymbol( symbol );
4228 S = (Elf_Addr)S_tmp;
4230 #ifdef ELF_FUNCTION_DESC
4231 /* If a function, already a function descriptor - we would
4232 have to copy it to add an offset. */
4233 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
4234 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
4238 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4241 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
4244 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
4245 (void*)P, (void*)S, (void*)A ));
4246 /* checkProddableBlock ( oc, (void*)P ); */
4250 switch (ELF_R_TYPE(info)) {
4251 # if defined(sparc_HOST_ARCH)
4252 case R_SPARC_WDISP30:
4253 w1 = *pP & 0xC0000000;
4254 w2 = (Elf_Word)((value - P) >> 2);
4255 ASSERT((w2 & 0xC0000000) == 0);
4260 w1 = *pP & 0xFFC00000;
4261 w2 = (Elf_Word)(value >> 10);
4262 ASSERT((w2 & 0xFFC00000) == 0);
4268 w2 = (Elf_Word)(value & 0x3FF);
4269 ASSERT((w2 & ~0x3FF) == 0);
4274 /* According to the Sun documentation:
4276 This relocation type resembles R_SPARC_32, except it refers to an
4277 unaligned word. That is, the word to be relocated must be treated
4278 as four separate bytes with arbitrary alignment, not as a word
4279 aligned according to the architecture requirements.
4282 w2 = (Elf_Word)value;
4284 // SPARC doesn't do misaligned writes of 32 bit words,
4285 // so we have to do this one byte-at-a-time.
4286 char *pPc = (char*)pP;
4287 pPc[0] = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
4288 pPc[1] = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
4289 pPc[2] = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
4290 pPc[3] = (char) ((Elf_Word)(w2 & 0x000000ff));
4294 w2 = (Elf_Word)value;
4297 # elif defined(powerpc_HOST_ARCH)
4298 case R_PPC_ADDR16_LO:
4299 *(Elf32_Half*) P = value;
4302 case R_PPC_ADDR16_HI:
4303 *(Elf32_Half*) P = value >> 16;
4306 case R_PPC_ADDR16_HA:
4307 *(Elf32_Half*) P = (value + 0x8000) >> 16;
4311 *(Elf32_Word *) P = value;
4315 *(Elf32_Word *) P = value - P;
4321 if( delta << 6 >> 6 != delta )
4323 value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
4327 if( value == 0 || delta << 6 >> 6 != delta )
4329 barf( "Unable to make SymbolExtra for #%d",
4335 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
4336 | (delta & 0x3fffffc);
4340 #if x86_64_HOST_ARCH
4342 *(Elf64_Xword *)P = value;
4347 #if defined(ALWAYS_PIC)
4348 barf("R_X86_64_PC32 relocation, but ALWAYS_PIC.");
4350 StgInt64 off = value - P;
4351 if (off >= 0x7fffffffL || off < -0x80000000L) {
4352 #if X86_64_ELF_NONPIC_HACK
4353 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4355 off = pltAddress + A - P;
4357 barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4358 symbol, off, oc->fileName );
4361 *(Elf64_Word *)P = (Elf64_Word)off;
4368 StgInt64 off = value - P;
4369 *(Elf64_Word *)P = (Elf64_Word)off;
4374 #if defined(ALWAYS_PIC)
4375 barf("R_X86_64_32 relocation, but ALWAYS_PIC.");
4377 if (value >= 0x7fffffffL) {
4378 #if X86_64_ELF_NONPIC_HACK
4379 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4381 value = pltAddress + A;
4383 barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4384 symbol, value, oc->fileName );
4387 *(Elf64_Word *)P = (Elf64_Word)value;
4392 #if defined(ALWAYS_PIC)
4393 barf("R_X86_64_32S relocation, but ALWAYS_PIC.");
4395 if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
4396 #if X86_64_ELF_NONPIC_HACK
4397 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4399 value = pltAddress + A;
4401 barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4402 symbol, value, oc->fileName );
4405 *(Elf64_Sword *)P = (Elf64_Sword)value;
4409 case R_X86_64_GOTPCREL:
4411 StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
4412 StgInt64 off = gotAddress + A - P;
4413 *(Elf64_Word *)P = (Elf64_Word)off;
4417 case R_X86_64_PLT32:
4419 #if defined(ALWAYS_PIC)
4420 barf("R_X86_64_PLT32 relocation, but ALWAYS_PIC.");
4422 StgInt64 off = value - P;
4423 if (off >= 0x7fffffffL || off < -0x80000000L) {
4424 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4426 off = pltAddress + A - P;
4428 *(Elf64_Word *)P = (Elf64_Word)off;
4435 errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
4436 oc->fileName, (lnat)ELF_R_TYPE(info));
4445 ocResolve_ELF ( ObjectCode* oc )
4449 Elf_Sym* stab = NULL;
4450 char* ehdrC = (char*)(oc->image);
4451 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
4452 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
4454 /* first find "the" symbol table */
4455 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
4457 /* also go find the string table */
4458 strtab = findElfSection ( ehdrC, SHT_STRTAB );
4460 if (stab == NULL || strtab == NULL) {
4461 errorBelch("%s: can't find string or symbol table", oc->fileName);
4465 /* Process the relocation sections. */
4466 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
4467 if (shdr[shnum].sh_type == SHT_REL) {
4468 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
4469 shnum, stab, strtab );
4473 if (shdr[shnum].sh_type == SHT_RELA) {
4474 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
4475 shnum, stab, strtab );
4480 #if defined(powerpc_HOST_ARCH)
4481 ocFlushInstructionCache( oc );
4488 * PowerPC & X86_64 ELF specifics
4491 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4493 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
4499 ehdr = (Elf_Ehdr *) oc->image;
4500 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
4502 for( i = 0; i < ehdr->e_shnum; i++ )
4503 if( shdr[i].sh_type == SHT_SYMTAB )
4506 if( i == ehdr->e_shnum )
4508 errorBelch( "This ELF file contains no symtab" );
4512 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
4514 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
4515 (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
4520 return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
4523 #endif /* powerpc */
4527 /* --------------------------------------------------------------------------
4529 * ------------------------------------------------------------------------*/
4531 #if defined(OBJFORMAT_MACHO)
4534 Support for MachO linking on Darwin/MacOS X
4535 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
4537 I hereby formally apologize for the hackish nature of this code.
4538 Things that need to be done:
4539 *) implement ocVerifyImage_MachO
4540 *) add still more sanity checks.
4543 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4544 #define mach_header mach_header_64
4545 #define segment_command segment_command_64
4546 #define section section_64
4547 #define nlist nlist_64
4550 #ifdef powerpc_HOST_ARCH
4552 ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4554 struct mach_header *header = (struct mach_header *) oc->image;
4555 struct load_command *lc = (struct load_command *) (header + 1);
4558 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: start\n"));
4560 for (i = 0; i < header->ncmds; i++) {
4561 if (lc->cmd == LC_SYMTAB) {
4563 // Find out the first and last undefined external
4564 // symbol, so we don't have to allocate too many
4565 // jump islands/GOT entries.
4567 struct symtab_command *symLC = (struct symtab_command *) lc;
4568 unsigned min = symLC->nsyms, max = 0;
4569 struct nlist *nlist =
4570 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
4573 for (i = 0; i < symLC->nsyms; i++) {
4575 if (nlist[i].n_type & N_STAB) {
4577 } else if (nlist[i].n_type & N_EXT) {
4579 if((nlist[i].n_type & N_TYPE) == N_UNDF
4580 && (nlist[i].n_value == 0)) {
4594 return ocAllocateSymbolExtras(oc, max - min + 1, min);
4600 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4603 return ocAllocateSymbolExtras(oc,0,0);
4607 #ifdef x86_64_HOST_ARCH
4609 ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4611 struct mach_header *header = (struct mach_header *) oc->image;
4612 struct load_command *lc = (struct load_command *) (header + 1);
4615 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: start\n"));
4617 for (i = 0; i < header->ncmds; i++) {
4618 if (lc->cmd == LC_SYMTAB) {
4620 // Just allocate one entry for every symbol
4621 struct symtab_command *symLC = (struct symtab_command *) lc;
4623 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: allocate %d symbols\n", symLC->nsyms));
4624 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: done\n"));
4625 return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
4628 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4631 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: allocated no symbols\n"));
4632 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO: done\n"));
4633 return ocAllocateSymbolExtras(oc,0,0);
4638 ocVerifyImage_MachO(ObjectCode * oc)
4640 char *image = (char*) oc->image;
4641 struct mach_header *header = (struct mach_header*) image;
4643 IF_DEBUG(linker, debugBelch("ocVerifyImage_MachO: start\n"));
4645 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4646 if(header->magic != MH_MAGIC_64) {
4647 errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4648 oc->fileName, MH_MAGIC_64, header->magic);
4652 if(header->magic != MH_MAGIC) {
4653 errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4654 oc->fileName, MH_MAGIC, header->magic);
4659 // FIXME: do some more verifying here
4660 IF_DEBUG(linker, debugBelch("ocVerifyImage_MachO: done\n"));
4668 struct symtab_command *symLC,
4669 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
4670 unsigned long *indirectSyms,
4671 struct nlist *nlist)
4674 size_t itemSize = 4;
4676 IF_DEBUG(linker, debugBelch("resolveImports: start\n"));
4679 int isJumpTable = 0;
4681 if (strcmp(sect->sectname,"__jump_table") == 0) {
4684 ASSERT(sect->reserved2 == itemSize);
4689 for(i=0; i*itemSize < sect->size;i++)
4691 // according to otool, reserved1 contains the first index into the indirect symbol table
4692 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
4693 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4696 IF_DEBUG(linker, debugBelch("resolveImports: resolving %s\n", nm));
4698 if ((symbol->n_type & N_TYPE) == N_UNDF
4699 && (symbol->n_type & N_EXT) && (symbol->n_value != 0)) {
4700 addr = (void*) (symbol->n_value);
4701 IF_DEBUG(linker, debugBelch("resolveImports: undefined external %s has value %p\n", nm, addr));
4703 addr = lookupSymbol(nm);
4704 IF_DEBUG(linker, debugBelch("resolveImports: looking up %s, %p\n", nm, addr));
4708 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
4715 checkProddableBlock(oc,image + sect->offset + i*itemSize);
4717 *(image + sect->offset + i * itemSize) = 0xe9; // jmp opcode
4718 *(unsigned*)(image + sect->offset + i*itemSize + 1)
4719 = (char*)addr - (image + sect->offset + i*itemSize + 5);
4724 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
4725 ((void**)(image + sect->offset))[i] = addr;
4729 IF_DEBUG(linker, debugBelch("resolveImports: done\n"));
4733 static unsigned long relocateAddress(
4736 struct section* sections,
4737 unsigned long address)
4740 IF_DEBUG(linker, debugBelch("relocateAddress: start\n"));
4741 for (i = 0; i < nSections; i++)
4743 IF_DEBUG(linker, debugBelch(" relocating address in section %d\n", i));
4744 if (sections[i].addr <= address
4745 && address < sections[i].addr + sections[i].size)
4747 return (unsigned long)oc->image
4748 + sections[i].offset + address - sections[i].addr;
4751 barf("Invalid Mach-O file:"
4752 "Address out of bounds while relocating object file");
4756 static int relocateSection(
4759 struct symtab_command *symLC, struct nlist *nlist,
4760 int nSections, struct section* sections, struct section *sect)
4762 struct relocation_info *relocs;
4765 IF_DEBUG(linker, debugBelch("relocateSection: start\n"));
4767 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
4769 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
4771 else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
4773 else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
4777 IF_DEBUG(linker, debugBelch("relocateSection: number of relocations: %d\n", n));
4779 relocs = (struct relocation_info*) (image + sect->reloff);
4783 #ifdef x86_64_HOST_ARCH
4784 struct relocation_info *reloc = &relocs[i];
4786 char *thingPtr = image + sect->offset + reloc->r_address;
4788 /* We shouldn't need to initialise this, but gcc on OS X 64 bit
4789 complains that it may be used uninitialized if we don't */
4792 int type = reloc->r_type;
4794 checkProddableBlock(oc,thingPtr);
4795 switch(reloc->r_length)
4798 thing = *(uint8_t*)thingPtr;
4799 baseValue = (uint64_t)thingPtr + 1;
4802 thing = *(uint16_t*)thingPtr;
4803 baseValue = (uint64_t)thingPtr + 2;
4806 thing = *(uint32_t*)thingPtr;
4807 baseValue = (uint64_t)thingPtr + 4;
4810 thing = *(uint64_t*)thingPtr;
4811 baseValue = (uint64_t)thingPtr + 8;
4814 barf("Unknown size.");
4818 debugBelch("relocateSection: length = %d, thing = %" PRId64 ", baseValue = %p\n",
4819 reloc->r_length, thing, (char *)baseValue));
4821 if (type == X86_64_RELOC_GOT
4822 || type == X86_64_RELOC_GOT_LOAD)
4824 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4825 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4827 IF_DEBUG(linker, debugBelch("relocateSection: making jump island for %s, extern = %d, X86_64_RELOC_GOT\n", nm, reloc->r_extern));
4828 ASSERT(reloc->r_extern);
4829 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, (unsigned long)lookupSymbol(nm))->addr;
4831 type = X86_64_RELOC_SIGNED;
4833 else if(reloc->r_extern)
4835 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4836 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4838 IF_DEBUG(linker, debugBelch("relocateSection: looking up external symbol %s\n", nm));
4839 IF_DEBUG(linker, debugBelch(" : type = %d\n", symbol->n_type));
4840 IF_DEBUG(linker, debugBelch(" : sect = %d\n", symbol->n_sect));
4841 IF_DEBUG(linker, debugBelch(" : desc = %d\n", symbol->n_desc));
4842 IF_DEBUG(linker, debugBelch(" : value = %p\n", (void *)symbol->n_value));
4843 if ((symbol->n_type & N_TYPE) == N_SECT) {
4844 value = relocateAddress(oc, nSections, sections,
4846 IF_DEBUG(linker, debugBelch("relocateSection, defined external symbol %s, relocated address %p\n", nm, (void *)value));
4849 value = (uint64_t) lookupSymbol(nm);
4850 IF_DEBUG(linker, debugBelch("relocateSection: external symbol %s, address %p\n", nm, (void *)value));
4855 // If the relocation is not through the global offset table
4856 // or external, then set the value to the baseValue. This
4857 // will leave displacements into the __const section
4858 // unchanged (as they ought to be).
4863 IF_DEBUG(linker, debugBelch("relocateSection: value = %p\n", (void *)value));
4865 if (type == X86_64_RELOC_BRANCH)
4867 if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
4869 ASSERT(reloc->r_extern);
4870 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
4873 ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
4874 type = X86_64_RELOC_SIGNED;
4879 case X86_64_RELOC_UNSIGNED:
4880 ASSERT(!reloc->r_pcrel);
4883 case X86_64_RELOC_SIGNED:
4884 case X86_64_RELOC_SIGNED_1:
4885 case X86_64_RELOC_SIGNED_2:
4886 case X86_64_RELOC_SIGNED_4:
4887 ASSERT(reloc->r_pcrel);
4888 thing += value - baseValue;
4890 case X86_64_RELOC_SUBTRACTOR:
4891 ASSERT(!reloc->r_pcrel);
4895 barf("unkown relocation");
4898 switch(reloc->r_length)
4901 *(uint8_t*)thingPtr = thing;
4904 *(uint16_t*)thingPtr = thing;
4907 *(uint32_t*)thingPtr = thing;
4910 *(uint64_t*)thingPtr = thing;
4914 if(relocs[i].r_address & R_SCATTERED)
4916 struct scattered_relocation_info *scat =
4917 (struct scattered_relocation_info*) &relocs[i];
4921 if(scat->r_length == 2)
4923 unsigned long word = 0;
4924 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
4925 checkProddableBlock(oc,wordPtr);
4927 // Note on relocation types:
4928 // i386 uses the GENERIC_RELOC_* types,
4929 // while ppc uses special PPC_RELOC_* types.
4930 // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
4931 // in both cases, all others are different.
4932 // Therefore, we use GENERIC_RELOC_VANILLA
4933 // and GENERIC_RELOC_PAIR instead of the PPC variants,
4934 // and use #ifdefs for the other types.
4936 // Step 1: Figure out what the relocated value should be
4937 if (scat->r_type == GENERIC_RELOC_VANILLA) {
4939 + (unsigned long) relocateAddress(oc,
4945 #ifdef powerpc_HOST_ARCH
4946 else if(scat->r_type == PPC_RELOC_SECTDIFF
4947 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4948 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4949 || scat->r_type == PPC_RELOC_HA16_SECTDIFF
4950 || scat->r_type == PPC_RELOC_LOCAL_SECTDIFF)
4952 else if(scat->r_type == GENERIC_RELOC_SECTDIFF
4953 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4956 struct scattered_relocation_info *pair =
4957 (struct scattered_relocation_info*) &relocs[i+1];
4959 if (!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR) {
4960 barf("Invalid Mach-O file: "
4961 "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4964 word = (unsigned long)
4965 (relocateAddress(oc, nSections, sections, scat->r_value)
4966 - relocateAddress(oc, nSections, sections, pair->r_value));
4969 #ifdef powerpc_HOST_ARCH
4970 else if(scat->r_type == PPC_RELOC_HI16
4971 || scat->r_type == PPC_RELOC_LO16
4972 || scat->r_type == PPC_RELOC_HA16
4973 || scat->r_type == PPC_RELOC_LO14)
4974 { // these are generated by label+offset things
4975 struct relocation_info *pair = &relocs[i+1];
4977 if ((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR) {
4978 barf("Invalid Mach-O file: "
4979 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4982 if(scat->r_type == PPC_RELOC_LO16)
4984 word = ((unsigned short*) wordPtr)[1];
4985 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4987 else if(scat->r_type == PPC_RELOC_LO14)
4989 barf("Unsupported Relocation: PPC_RELOC_LO14");
4990 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4991 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4993 else if(scat->r_type == PPC_RELOC_HI16)
4995 word = ((unsigned short*) wordPtr)[1] << 16;
4996 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4998 else if(scat->r_type == PPC_RELOC_HA16)
5000 word = ((unsigned short*) wordPtr)[1] << 16;
5001 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
5005 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
5012 barf ("Don't know how to handle this Mach-O "
5013 "scattered relocation entry: "
5014 "object file %s; entry type %ld; "
5016 OC_INFORMATIVE_FILENAME(oc),
5022 #ifdef powerpc_HOST_ARCH
5023 if(scat->r_type == GENERIC_RELOC_VANILLA
5024 || scat->r_type == PPC_RELOC_SECTDIFF)
5026 if(scat->r_type == GENERIC_RELOC_VANILLA
5027 || scat->r_type == GENERIC_RELOC_SECTDIFF
5028 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
5033 #ifdef powerpc_HOST_ARCH
5034 else if (scat->r_type == PPC_RELOC_LO16_SECTDIFF
5035 || scat->r_type == PPC_RELOC_LO16)
5037 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
5039 else if (scat->r_type == PPC_RELOC_HI16_SECTDIFF
5040 || scat->r_type == PPC_RELOC_HI16)
5042 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
5044 else if (scat->r_type == PPC_RELOC_HA16_SECTDIFF
5045 || scat->r_type == PPC_RELOC_HA16)
5047 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
5048 + ((word & (1<<15)) ? 1 : 0);
5054 barf("Can't handle Mach-O scattered relocation entry "
5055 "with this r_length tag: "
5056 "object file %s; entry type %ld; "
5057 "r_length tag %ld; address %#lx\n",
5058 OC_INFORMATIVE_FILENAME(oc),
5065 else /* scat->r_pcrel */
5067 barf("Don't know how to handle *PC-relative* Mach-O "
5068 "scattered relocation entry: "
5069 "object file %s; entry type %ld; address %#lx\n",
5070 OC_INFORMATIVE_FILENAME(oc),
5077 else /* !(relocs[i].r_address & R_SCATTERED) */
5079 struct relocation_info *reloc = &relocs[i];
5080 if (reloc->r_pcrel && !reloc->r_extern) {
5081 IF_DEBUG(linker, debugBelch("relocateSection: pc relative but not external, skipping\n"));
5085 if (reloc->r_length == 2) {
5086 unsigned long word = 0;
5087 #ifdef powerpc_HOST_ARCH
5088 unsigned long jumpIsland = 0;
5089 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
5090 // to avoid warning and to catch
5094 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
5095 checkProddableBlock(oc,wordPtr);
5097 if (reloc->r_type == GENERIC_RELOC_VANILLA) {
5100 #ifdef powerpc_HOST_ARCH
5101 else if (reloc->r_type == PPC_RELOC_LO16) {
5102 word = ((unsigned short*) wordPtr)[1];
5103 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
5105 else if (reloc->r_type == PPC_RELOC_HI16) {
5106 word = ((unsigned short*) wordPtr)[1] << 16;
5107 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
5109 else if (reloc->r_type == PPC_RELOC_HA16) {
5110 word = ((unsigned short*) wordPtr)[1] << 16;
5111 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
5113 else if (reloc->r_type == PPC_RELOC_BR24) {
5115 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
5119 barf("Can't handle this Mach-O relocation entry "
5121 "object file %s; entry type %ld; address %#lx\n",
5122 OC_INFORMATIVE_FILENAME(oc),
5128 if (!reloc->r_extern) {
5129 long delta = sections[reloc->r_symbolnum-1].offset
5130 - sections[reloc->r_symbolnum-1].addr
5136 struct nlist *symbol = &nlist[reloc->r_symbolnum];
5137 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
5138 void *symbolAddress = lookupSymbol(nm);
5140 if (!symbolAddress) {
5141 errorBelch("\nunknown symbol `%s'", nm);
5145 if (reloc->r_pcrel) {
5146 #ifdef powerpc_HOST_ARCH
5147 // In the .o file, this should be a relative jump to NULL
5148 // and we'll change it to a relative jump to the symbol
5149 ASSERT(word + reloc->r_address == 0);
5150 jumpIsland = (unsigned long)
5151 &makeSymbolExtra(oc,
5153 (unsigned long) symbolAddress)
5155 if (jumpIsland != 0) {
5156 offsetToJumpIsland = word + jumpIsland
5157 - (((long)image) + sect->offset - sect->addr);
5160 word += (unsigned long) symbolAddress
5161 - (((long)image) + sect->offset - sect->addr);
5164 word += (unsigned long) symbolAddress;
5168 if (reloc->r_type == GENERIC_RELOC_VANILLA) {
5172 #ifdef powerpc_HOST_ARCH
5173 else if(reloc->r_type == PPC_RELOC_LO16)
5175 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
5179 else if(reloc->r_type == PPC_RELOC_HI16)
5181 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
5185 else if(reloc->r_type == PPC_RELOC_HA16)
5187 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
5188 + ((word & (1<<15)) ? 1 : 0);
5192 else if(reloc->r_type == PPC_RELOC_BR24)
5194 if ((word & 0x03) != 0) {
5195 barf("%s: unconditional relative branch with a displacement "
5196 "which isn't a multiple of 4 bytes: %#lx",
5197 OC_INFORMATIVE_FILENAME(oc),
5201 if((word & 0xFE000000) != 0xFE000000 &&
5202 (word & 0xFE000000) != 0x00000000) {
5203 // The branch offset is too large.
5204 // Therefore, we try to use a jump island.
5205 if (jumpIsland == 0) {
5206 barf("%s: unconditional relative branch out of range: "
5207 "no jump island available: %#lx",
5208 OC_INFORMATIVE_FILENAME(oc),
5212 word = offsetToJumpIsland;
5214 if((word & 0xFE000000) != 0xFE000000 &&
5215 (word & 0xFE000000) != 0x00000000) {
5216 barf("%s: unconditional relative branch out of range: "
5217 "jump island out of range: %#lx",
5218 OC_INFORMATIVE_FILENAME(oc),
5222 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
5229 barf("Can't handle Mach-O relocation entry (not scattered) "
5230 "with this r_length tag: "
5231 "object file %s; entry type %ld; "
5232 "r_length tag %ld; address %#lx\n",
5233 OC_INFORMATIVE_FILENAME(oc),
5243 IF_DEBUG(linker, debugBelch("relocateSection: done\n"));
5248 ocGetNames_MachO(ObjectCode* oc)
5250 char *image = (char*) oc->image;
5251 struct mach_header *header = (struct mach_header*) image;
5252 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5253 unsigned i,curSymbol = 0;
5254 struct segment_command *segLC = NULL;
5255 struct section *sections;
5256 struct symtab_command *symLC = NULL;
5257 struct nlist *nlist;
5258 unsigned long commonSize = 0;
5259 char *commonStorage = NULL;
5260 unsigned long commonCounter;
5262 IF_DEBUG(linker,debugBelch("ocGetNames_MachO: start\n"));
5264 for(i=0;i<header->ncmds;i++)
5266 if (lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64) {
5267 segLC = (struct segment_command*) lc;
5269 else if (lc->cmd == LC_SYMTAB) {
5270 symLC = (struct symtab_command*) lc;
5273 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5276 sections = (struct section*) (segLC+1);
5277 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5281 barf("ocGetNames_MachO: no segment load command");
5284 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: will load %d sections\n", segLC->nsects));
5285 for(i=0;i<segLC->nsects;i++)
5287 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: section %d\n", i));
5289 if (sections[i].size == 0) {
5290 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: found a zero length section, skipping\n"));
5294 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
5296 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
5297 "ocGetNames_MachO(common symbols)");
5298 sections[i].offset = zeroFillArea - image;
5301 if (!strcmp(sections[i].sectname,"__text")) {
5303 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: adding __text section\n"));
5304 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
5305 (void*) (image + sections[i].offset),
5306 (void*) (image + sections[i].offset + sections[i].size));
5308 else if (!strcmp(sections[i].sectname,"__const")) {
5310 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: adding __const section\n"));
5311 addSection(oc, SECTIONKIND_RWDATA,
5312 (void*) (image + sections[i].offset),
5313 (void*) (image + sections[i].offset + sections[i].size));
5315 else if (!strcmp(sections[i].sectname,"__data")) {
5317 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: adding __data section\n"));
5318 addSection(oc, SECTIONKIND_RWDATA,
5319 (void*) (image + sections[i].offset),
5320 (void*) (image + sections[i].offset + sections[i].size));
5322 else if(!strcmp(sections[i].sectname,"__bss")
5323 || !strcmp(sections[i].sectname,"__common")) {
5325 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: adding __bss section\n"));
5326 addSection(oc, SECTIONKIND_RWDATA,
5327 (void*) (image + sections[i].offset),
5328 (void*) (image + sections[i].offset + sections[i].size));
5330 addProddableBlock(oc,
5331 (void *) (image + sections[i].offset),
5335 // count external symbols defined here
5338 for (i = 0; i < symLC->nsyms; i++) {
5339 if (nlist[i].n_type & N_STAB) {
5342 else if(nlist[i].n_type & N_EXT)
5344 if((nlist[i].n_type & N_TYPE) == N_UNDF
5345 && (nlist[i].n_value != 0))
5347 commonSize += nlist[i].n_value;
5350 else if((nlist[i].n_type & N_TYPE) == N_SECT)
5355 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: %d external symbols\n", oc->n_symbols));
5356 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
5357 "ocGetNames_MachO(oc->symbols)");
5361 for(i=0;i<symLC->nsyms;i++)
5363 if(nlist[i].n_type & N_STAB)
5365 else if((nlist[i].n_type & N_TYPE) == N_SECT)
5367 if(nlist[i].n_type & N_EXT)
5369 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5370 if ((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm)) {
5371 // weak definition, and we already have a definition
5372 IF_DEBUG(linker, debugBelch(" weak: %s\n", nm));
5376 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting %s\n", nm));
5377 ghciInsertStrHashTable(oc->fileName, symhash, nm,
5379 + sections[nlist[i].n_sect-1].offset
5380 - sections[nlist[i].n_sect-1].addr
5381 + nlist[i].n_value);
5382 oc->symbols[curSymbol++] = nm;
5387 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: \t...not external, skipping\n"));
5392 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: \t...not defined in this section, skipping\n"));
5397 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
5398 commonCounter = (unsigned long)commonStorage;
5401 for (i = 0; i < symLC->nsyms; i++) {
5402 if((nlist[i].n_type & N_TYPE) == N_UNDF
5403 && (nlist[i].n_type & N_EXT)
5404 && (nlist[i].n_value != 0)) {
5406 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5407 unsigned long sz = nlist[i].n_value;
5409 nlist[i].n_value = commonCounter;
5411 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting common symbol: %s\n", nm));
5412 ghciInsertStrHashTable(oc->fileName, symhash, nm,
5413 (void*)commonCounter);
5414 oc->symbols[curSymbol++] = nm;
5416 commonCounter += sz;
5421 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: done\n"));
5426 ocResolve_MachO(ObjectCode* oc)
5428 char *image = (char*) oc->image;
5429 struct mach_header *header = (struct mach_header*) image;
5430 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5432 struct segment_command *segLC = NULL;
5433 struct section *sections;
5434 struct symtab_command *symLC = NULL;
5435 struct dysymtab_command *dsymLC = NULL;
5436 struct nlist *nlist;
5438 IF_DEBUG(linker, debugBelch("ocResolve_MachO: start\n"));
5439 for (i = 0; i < header->ncmds; i++)
5441 if (lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64) {
5442 segLC = (struct segment_command*) lc;
5443 IF_DEBUG(linker, debugBelch("ocResolve_MachO: found a 32 or 64 bit segment load command\n"));
5445 else if (lc->cmd == LC_SYMTAB) {
5446 symLC = (struct symtab_command*) lc;
5447 IF_DEBUG(linker, debugBelch("ocResolve_MachO: found a symbol table load command\n"));
5449 else if (lc->cmd == LC_DYSYMTAB) {
5450 dsymLC = (struct dysymtab_command*) lc;
5451 IF_DEBUG(linker, debugBelch("ocResolve_MachO: found a dynamic symbol table load command\n"));
5454 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5457 sections = (struct section*) (segLC+1);
5458 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5463 unsigned long *indirectSyms
5464 = (unsigned long*) (image + dsymLC->indirectsymoff);
5466 IF_DEBUG(linker, debugBelch("ocResolve_MachO: resolving dsymLC\n"));
5467 for (i = 0; i < segLC->nsects; i++)
5469 if( !strcmp(sections[i].sectname,"__la_symbol_ptr")
5470 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
5471 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
5473 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5476 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
5477 || !strcmp(sections[i].sectname,"__pointers"))
5479 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5482 else if(!strcmp(sections[i].sectname,"__jump_table"))
5484 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5489 IF_DEBUG(linker, debugBelch("ocResolve_MachO: unknown section\n"));
5494 for(i=0;i<segLC->nsects;i++)
5496 IF_DEBUG(linker, debugBelch("ocResolve_MachO: relocating section %d\n", i));
5498 if (!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
5502 #if defined (powerpc_HOST_ARCH)
5503 ocFlushInstructionCache( oc );
5509 #ifdef powerpc_HOST_ARCH
5511 * The Mach-O object format uses leading underscores. But not everywhere.
5512 * There is a small number of runtime support functions defined in
5513 * libcc_dynamic.a whose name does not have a leading underscore.
5514 * As a consequence, we can't get their address from C code.
5515 * We have to use inline assembler just to take the address of a function.
5519 extern void* symbolsWithoutUnderscore[];
5522 machoInitSymbolsWithoutUnderscore(void)
5524 void **p = symbolsWithoutUnderscore;
5525 __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
5527 #undef SymI_NeedsProto
5528 #define SymI_NeedsProto(x) \
5529 __asm__ volatile(".long " # x);
5531 RTS_MACHO_NOUNDERLINE_SYMBOLS
5533 __asm__ volatile(".text");
5535 #undef SymI_NeedsProto
5536 #define SymI_NeedsProto(x) \
5537 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
5539 RTS_MACHO_NOUNDERLINE_SYMBOLS
5541 #undef SymI_NeedsProto
5547 * Figure out by how much to shift the entire Mach-O file in memory
5548 * when loading so that its single segment ends up 16-byte-aligned
5551 machoGetMisalignment( FILE * f )
5553 struct mach_header header;
5557 int n = fread(&header, sizeof(header), 1, f);
5559 barf("machoGetMisalignment: can't read the Mach-O header");
5562 fseek(f, -sizeof(header), SEEK_CUR);
5564 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
5565 if(header.magic != MH_MAGIC_64) {
5566 barf("Bad magic. Expected: %08x, got: %08x.",
5567 MH_MAGIC_64, header.magic);
5570 if(header.magic != MH_MAGIC) {
5571 barf("Bad magic. Expected: %08x, got: %08x.",
5572 MH_MAGIC, header.magic);
5576 misalignment = (header.sizeofcmds + sizeof(header))
5579 return misalignment ? (16 - misalignment) : 0;