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>.
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 #if defined(mingw32_HOST_OS)
37 // get protos for is*()
41 #ifdef HAVE_SYS_TYPES_H
42 #include <sys/types.h>
50 #ifdef HAVE_SYS_STAT_H
54 #if defined(HAVE_DLFCN_H)
58 #if defined(cygwin32_HOST_OS)
63 #ifdef HAVE_SYS_TIME_H
67 #include <sys/fcntl.h>
68 #include <sys/termios.h>
69 #include <sys/utime.h>
70 #include <sys/utsname.h>
74 #if defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS) || defined(darwin_HOST_OS)
85 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
86 # define OBJFORMAT_ELF
87 # include <regex.h> // regex is already used by dlopen() so this is OK
88 // to use here without requiring an additional lib
89 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
90 # define OBJFORMAT_PEi386
93 #elif defined(darwin_HOST_OS)
94 # define OBJFORMAT_MACHO
96 # include <mach-o/loader.h>
97 # include <mach-o/nlist.h>
98 # include <mach-o/reloc.h>
99 #if !defined(HAVE_DLFCN_H)
100 # include <mach-o/dyld.h>
102 #if defined(powerpc_HOST_ARCH)
103 # include <mach-o/ppc/reloc.h>
105 #if defined(x86_64_HOST_ARCH)
106 # include <mach-o/x86_64/reloc.h>
110 /* Hash table mapping symbol names to Symbol */
111 static /*Str*/HashTable *symhash;
113 /* Hash table mapping symbol names to StgStablePtr */
114 static /*Str*/HashTable *stablehash;
116 /* List of currently loaded objects */
117 ObjectCode *objects = NULL; /* initially empty */
119 #if defined(OBJFORMAT_ELF)
120 static int ocVerifyImage_ELF ( ObjectCode* oc );
121 static int ocGetNames_ELF ( ObjectCode* oc );
122 static int ocResolve_ELF ( ObjectCode* oc );
123 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
124 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
126 #elif defined(OBJFORMAT_PEi386)
127 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
128 static int ocGetNames_PEi386 ( ObjectCode* oc );
129 static int ocResolve_PEi386 ( ObjectCode* oc );
130 static void *lookupSymbolInDLLs ( unsigned char *lbl );
131 static void zapTrailingAtSign ( unsigned char *sym );
132 #elif defined(OBJFORMAT_MACHO)
133 static int ocVerifyImage_MachO ( ObjectCode* oc );
134 static int ocGetNames_MachO ( ObjectCode* oc );
135 static int ocResolve_MachO ( ObjectCode* oc );
138 static int machoGetMisalignment( FILE * );
140 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
141 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
143 #ifdef powerpc_HOST_ARCH
144 static void machoInitSymbolsWithoutUnderscore( void );
148 /* on x86_64 we have a problem with relocating symbol references in
149 * code that was compiled without -fPIC. By default, the small memory
150 * model is used, which assumes that symbol references can fit in a
151 * 32-bit slot. The system dynamic linker makes this work for
152 * references to shared libraries by either (a) allocating a jump
153 * table slot for code references, or (b) moving the symbol at load
154 * time (and copying its contents, if necessary) for data references.
156 * We unfortunately can't tell whether symbol references are to code
157 * or data. So for now we assume they are code (the vast majority
158 * are), and allocate jump-table slots. Unfortunately this will
159 * SILENTLY generate crashing code for data references. This hack is
160 * enabled by X86_64_ELF_NONPIC_HACK.
162 * One workaround is to use shared Haskell libraries. This is
163 * coming. Another workaround is to keep the static libraries but
164 * compile them with -fPIC, because that will generate PIC references
165 * to data which can be relocated. The PIC code is still too green to
166 * do this systematically, though.
169 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
171 * Naming Scheme for Symbol Macros
173 * SymI_*: symbol is internal to the RTS. It resides in an object
174 * file/library that is statically.
175 * SymE_*: symbol is external to the RTS library. It might be linked
178 * Sym*_HasProto : the symbol prototype is imported in an include file
179 * or defined explicitly
180 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
181 * default proto extern void sym(void);
183 #define X86_64_ELF_NONPIC_HACK 1
185 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
186 * small memory model on this architecture (see gcc docs,
189 * MAP_32BIT not available on OpenBSD/amd64
191 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
192 #define TRY_MAP_32BIT MAP_32BIT
194 #define TRY_MAP_32BIT 0
198 * Due to the small memory model (see above), on x86_64 we have to map
199 * all our non-PIC object files into the low 2Gb of the address space
200 * (why 2Gb and not 4Gb? Because all addresses must be reachable
201 * using a 32-bit signed PC-relative offset). On Linux we can do this
202 * using the MAP_32BIT flag to mmap(), however on other OSs
203 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
204 * can't do this. So on these systems, we have to pick a base address
205 * in the low 2Gb of the address space and try to allocate memory from
208 * We pick a default address based on the OS, but also make this
209 * configurable via an RTS flag (+RTS -xm)
211 #if defined(x86_64_HOST_ARCH)
213 #if defined(MAP_32BIT)
214 // Try to use MAP_32BIT
215 #define MMAP_32BIT_BASE_DEFAULT 0
218 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
221 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
224 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
225 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
226 #define MAP_ANONYMOUS MAP_ANON
229 /* -----------------------------------------------------------------------------
230 * Built-in symbols from the RTS
233 typedef struct _RtsSymbolVal {
238 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
239 SymI_HasProto(stg_mkWeakForeignEnvzh) \
240 SymI_HasProto(stg_makeStableNamezh) \
241 SymI_HasProto(stg_finalizzeWeakzh)
243 #if !defined (mingw32_HOST_OS)
244 #define RTS_POSIX_ONLY_SYMBOLS \
245 SymI_HasProto(__hscore_get_saved_termios) \
246 SymI_HasProto(__hscore_set_saved_termios) \
247 SymI_HasProto(shutdownHaskellAndSignal) \
248 SymI_HasProto(lockFile) \
249 SymI_HasProto(unlockFile) \
250 SymI_HasProto(signal_handlers) \
251 SymI_HasProto(stg_sig_install) \
252 SymI_NeedsProto(nocldstop)
255 #if defined (cygwin32_HOST_OS)
256 #define RTS_MINGW_ONLY_SYMBOLS /**/
257 /* Don't have the ability to read import libs / archives, so
258 * we have to stupidly list a lot of what libcygwin.a
261 #define RTS_CYGWIN_ONLY_SYMBOLS \
262 SymI_HasProto(regfree) \
263 SymI_HasProto(regexec) \
264 SymI_HasProto(regerror) \
265 SymI_HasProto(regcomp) \
266 SymI_HasProto(__errno) \
267 SymI_HasProto(access) \
268 SymI_HasProto(chmod) \
269 SymI_HasProto(chdir) \
270 SymI_HasProto(close) \
271 SymI_HasProto(creat) \
273 SymI_HasProto(dup2) \
274 SymI_HasProto(fstat) \
275 SymI_HasProto(fcntl) \
276 SymI_HasProto(getcwd) \
277 SymI_HasProto(getenv) \
278 SymI_HasProto(lseek) \
279 SymI_HasProto(open) \
280 SymI_HasProto(fpathconf) \
281 SymI_HasProto(pathconf) \
282 SymI_HasProto(stat) \
284 SymI_HasProto(tanh) \
285 SymI_HasProto(cosh) \
286 SymI_HasProto(sinh) \
287 SymI_HasProto(atan) \
288 SymI_HasProto(acos) \
289 SymI_HasProto(asin) \
295 SymI_HasProto(sqrt) \
296 SymI_HasProto(localtime_r) \
297 SymI_HasProto(gmtime_r) \
298 SymI_HasProto(mktime) \
299 SymI_NeedsProto(_imp___tzname) \
300 SymI_HasProto(gettimeofday) \
301 SymI_HasProto(timezone) \
302 SymI_HasProto(tcgetattr) \
303 SymI_HasProto(tcsetattr) \
304 SymI_HasProto(memcpy) \
305 SymI_HasProto(memmove) \
306 SymI_HasProto(realloc) \
307 SymI_HasProto(malloc) \
308 SymI_HasProto(free) \
309 SymI_HasProto(fork) \
310 SymI_HasProto(lstat) \
311 SymI_HasProto(isatty) \
312 SymI_HasProto(mkdir) \
313 SymI_HasProto(opendir) \
314 SymI_HasProto(readdir) \
315 SymI_HasProto(rewinddir) \
316 SymI_HasProto(closedir) \
317 SymI_HasProto(link) \
318 SymI_HasProto(mkfifo) \
319 SymI_HasProto(pipe) \
320 SymI_HasProto(read) \
321 SymI_HasProto(rename) \
322 SymI_HasProto(rmdir) \
323 SymI_HasProto(select) \
324 SymI_HasProto(system) \
325 SymI_HasProto(write) \
326 SymI_HasProto(strcmp) \
327 SymI_HasProto(strcpy) \
328 SymI_HasProto(strncpy) \
329 SymI_HasProto(strerror) \
330 SymI_HasProto(sigaddset) \
331 SymI_HasProto(sigemptyset) \
332 SymI_HasProto(sigprocmask) \
333 SymI_HasProto(umask) \
334 SymI_HasProto(uname) \
335 SymI_HasProto(unlink) \
336 SymI_HasProto(utime) \
337 SymI_HasProto(waitpid)
339 #elif !defined(mingw32_HOST_OS)
340 #define RTS_MINGW_ONLY_SYMBOLS /**/
341 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
342 #else /* defined(mingw32_HOST_OS) */
343 #define RTS_POSIX_ONLY_SYMBOLS /**/
344 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
346 /* Extra syms gen'ed by mingw-2's gcc-3.2: */
348 #define RTS_MINGW_EXTRA_SYMS \
349 SymI_NeedsProto(_imp____mb_cur_max) \
350 SymI_NeedsProto(_imp___pctype)
352 #define RTS_MINGW_EXTRA_SYMS
355 #if HAVE_GETTIMEOFDAY
356 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
358 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
361 #if HAVE___MINGW_VFPRINTF
362 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
364 #define RTS___MINGW_VFPRINTF_SYM /**/
367 /* These are statically linked from the mingw libraries into the ghc
368 executable, so we have to employ this hack. */
369 #define RTS_MINGW_ONLY_SYMBOLS \
370 SymI_HasProto(stg_asyncReadzh) \
371 SymI_HasProto(stg_asyncWritezh) \
372 SymI_HasProto(stg_asyncDoProczh) \
373 SymI_HasProto(memset) \
374 SymI_HasProto(inet_ntoa) \
375 SymI_HasProto(inet_addr) \
376 SymI_HasProto(htonl) \
377 SymI_HasProto(recvfrom) \
378 SymI_HasProto(listen) \
379 SymI_HasProto(bind) \
380 SymI_HasProto(shutdown) \
381 SymI_HasProto(connect) \
382 SymI_HasProto(htons) \
383 SymI_HasProto(ntohs) \
384 SymI_HasProto(getservbyname) \
385 SymI_HasProto(getservbyport) \
386 SymI_HasProto(getprotobynumber) \
387 SymI_HasProto(getprotobyname) \
388 SymI_HasProto(gethostbyname) \
389 SymI_HasProto(gethostbyaddr) \
390 SymI_HasProto(gethostname) \
391 SymI_HasProto(strcpy) \
392 SymI_HasProto(strncpy) \
393 SymI_HasProto(abort) \
394 SymI_NeedsProto(_alloca) \
395 SymI_HasProto(isxdigit) \
396 SymI_HasProto(isupper) \
397 SymI_HasProto(ispunct) \
398 SymI_HasProto(islower) \
399 SymI_HasProto(isspace) \
400 SymI_HasProto(isprint) \
401 SymI_HasProto(isdigit) \
402 SymI_HasProto(iscntrl) \
403 SymI_HasProto(isalpha) \
404 SymI_HasProto(isalnum) \
405 SymI_HasProto(isascii) \
406 RTS___MINGW_VFPRINTF_SYM \
407 SymI_HasProto(strcmp) \
408 SymI_HasProto(memmove) \
409 SymI_HasProto(realloc) \
410 SymI_HasProto(malloc) \
412 SymI_HasProto(tanh) \
413 SymI_HasProto(cosh) \
414 SymI_HasProto(sinh) \
415 SymI_HasProto(atan) \
416 SymI_HasProto(acos) \
417 SymI_HasProto(asin) \
423 SymI_HasProto(sqrt) \
424 SymI_HasProto(powf) \
425 SymI_HasProto(tanhf) \
426 SymI_HasProto(coshf) \
427 SymI_HasProto(sinhf) \
428 SymI_HasProto(atanf) \
429 SymI_HasProto(acosf) \
430 SymI_HasProto(asinf) \
431 SymI_HasProto(tanf) \
432 SymI_HasProto(cosf) \
433 SymI_HasProto(sinf) \
434 SymI_HasProto(expf) \
435 SymI_HasProto(logf) \
436 SymI_HasProto(sqrtf) \
438 SymI_HasProto(erfc) \
439 SymI_HasProto(erff) \
440 SymI_HasProto(erfcf) \
441 SymI_HasProto(memcpy) \
442 SymI_HasProto(rts_InstallConsoleEvent) \
443 SymI_HasProto(rts_ConsoleHandlerDone) \
444 SymI_NeedsProto(mktime) \
445 SymI_NeedsProto(_imp___timezone) \
446 SymI_NeedsProto(_imp___tzname) \
447 SymI_NeedsProto(_imp__tzname) \
448 SymI_NeedsProto(_imp___iob) \
449 SymI_NeedsProto(_imp___osver) \
450 SymI_NeedsProto(localtime) \
451 SymI_NeedsProto(gmtime) \
452 SymI_NeedsProto(opendir) \
453 SymI_NeedsProto(readdir) \
454 SymI_NeedsProto(rewinddir) \
455 RTS_MINGW_EXTRA_SYMS \
456 RTS_MINGW_GETTIMEOFDAY_SYM \
457 SymI_NeedsProto(closedir)
460 #if defined(darwin_TARGET_OS) && HAVE_PRINTF_LDBLSTUB
461 #define RTS_DARWIN_ONLY_SYMBOLS \
462 SymI_NeedsProto(asprintf$LDBLStub) \
463 SymI_NeedsProto(err$LDBLStub) \
464 SymI_NeedsProto(errc$LDBLStub) \
465 SymI_NeedsProto(errx$LDBLStub) \
466 SymI_NeedsProto(fprintf$LDBLStub) \
467 SymI_NeedsProto(fscanf$LDBLStub) \
468 SymI_NeedsProto(fwprintf$LDBLStub) \
469 SymI_NeedsProto(fwscanf$LDBLStub) \
470 SymI_NeedsProto(printf$LDBLStub) \
471 SymI_NeedsProto(scanf$LDBLStub) \
472 SymI_NeedsProto(snprintf$LDBLStub) \
473 SymI_NeedsProto(sprintf$LDBLStub) \
474 SymI_NeedsProto(sscanf$LDBLStub) \
475 SymI_NeedsProto(strtold$LDBLStub) \
476 SymI_NeedsProto(swprintf$LDBLStub) \
477 SymI_NeedsProto(swscanf$LDBLStub) \
478 SymI_NeedsProto(syslog$LDBLStub) \
479 SymI_NeedsProto(vasprintf$LDBLStub) \
480 SymI_NeedsProto(verr$LDBLStub) \
481 SymI_NeedsProto(verrc$LDBLStub) \
482 SymI_NeedsProto(verrx$LDBLStub) \
483 SymI_NeedsProto(vfprintf$LDBLStub) \
484 SymI_NeedsProto(vfscanf$LDBLStub) \
485 SymI_NeedsProto(vfwprintf$LDBLStub) \
486 SymI_NeedsProto(vfwscanf$LDBLStub) \
487 SymI_NeedsProto(vprintf$LDBLStub) \
488 SymI_NeedsProto(vscanf$LDBLStub) \
489 SymI_NeedsProto(vsnprintf$LDBLStub) \
490 SymI_NeedsProto(vsprintf$LDBLStub) \
491 SymI_NeedsProto(vsscanf$LDBLStub) \
492 SymI_NeedsProto(vswprintf$LDBLStub) \
493 SymI_NeedsProto(vswscanf$LDBLStub) \
494 SymI_NeedsProto(vsyslog$LDBLStub) \
495 SymI_NeedsProto(vwarn$LDBLStub) \
496 SymI_NeedsProto(vwarnc$LDBLStub) \
497 SymI_NeedsProto(vwarnx$LDBLStub) \
498 SymI_NeedsProto(vwprintf$LDBLStub) \
499 SymI_NeedsProto(vwscanf$LDBLStub) \
500 SymI_NeedsProto(warn$LDBLStub) \
501 SymI_NeedsProto(warnc$LDBLStub) \
502 SymI_NeedsProto(warnx$LDBLStub) \
503 SymI_NeedsProto(wcstold$LDBLStub) \
504 SymI_NeedsProto(wprintf$LDBLStub) \
505 SymI_NeedsProto(wscanf$LDBLStub)
507 #define RTS_DARWIN_ONLY_SYMBOLS
511 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
513 # define MAIN_CAP_SYM
516 #if !defined(mingw32_HOST_OS)
517 #define RTS_USER_SIGNALS_SYMBOLS \
518 SymI_HasProto(setIOManagerPipe) \
519 SymI_HasProto(ioManagerWakeup) \
520 SymI_HasProto(ioManagerSync) \
521 SymI_HasProto(blockUserSignals) \
522 SymI_HasProto(unblockUserSignals)
524 #define RTS_USER_SIGNALS_SYMBOLS \
525 SymI_HasProto(ioManagerWakeup) \
526 SymI_HasProto(sendIOManagerEvent) \
527 SymI_HasProto(readIOManagerEvent) \
528 SymI_HasProto(getIOManagerEvent) \
529 SymI_HasProto(console_handler)
532 #define RTS_LIBFFI_SYMBOLS \
533 SymE_NeedsProto(ffi_prep_cif) \
534 SymE_NeedsProto(ffi_call) \
535 SymE_NeedsProto(ffi_type_void) \
536 SymE_NeedsProto(ffi_type_float) \
537 SymE_NeedsProto(ffi_type_double) \
538 SymE_NeedsProto(ffi_type_sint64) \
539 SymE_NeedsProto(ffi_type_uint64) \
540 SymE_NeedsProto(ffi_type_sint32) \
541 SymE_NeedsProto(ffi_type_uint32) \
542 SymE_NeedsProto(ffi_type_sint16) \
543 SymE_NeedsProto(ffi_type_uint16) \
544 SymE_NeedsProto(ffi_type_sint8) \
545 SymE_NeedsProto(ffi_type_uint8) \
546 SymE_NeedsProto(ffi_type_pointer)
548 #ifdef TABLES_NEXT_TO_CODE
549 #define RTS_RET_SYMBOLS /* nothing */
551 #define RTS_RET_SYMBOLS \
552 SymI_HasProto(stg_enter_ret) \
553 SymI_HasProto(stg_gc_fun_ret) \
554 SymI_HasProto(stg_ap_v_ret) \
555 SymI_HasProto(stg_ap_f_ret) \
556 SymI_HasProto(stg_ap_d_ret) \
557 SymI_HasProto(stg_ap_l_ret) \
558 SymI_HasProto(stg_ap_n_ret) \
559 SymI_HasProto(stg_ap_p_ret) \
560 SymI_HasProto(stg_ap_pv_ret) \
561 SymI_HasProto(stg_ap_pp_ret) \
562 SymI_HasProto(stg_ap_ppv_ret) \
563 SymI_HasProto(stg_ap_ppp_ret) \
564 SymI_HasProto(stg_ap_pppv_ret) \
565 SymI_HasProto(stg_ap_pppp_ret) \
566 SymI_HasProto(stg_ap_ppppp_ret) \
567 SymI_HasProto(stg_ap_pppppp_ret)
570 /* Modules compiled with -ticky may mention ticky counters */
571 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
572 #define RTS_TICKY_SYMBOLS \
573 SymI_NeedsProto(ticky_entry_ctrs) \
574 SymI_NeedsProto(top_ct) \
576 SymI_HasProto(ENT_VIA_NODE_ctr) \
577 SymI_HasProto(ENT_STATIC_THK_ctr) \
578 SymI_HasProto(ENT_DYN_THK_ctr) \
579 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
580 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
581 SymI_HasProto(ENT_STATIC_CON_ctr) \
582 SymI_HasProto(ENT_DYN_CON_ctr) \
583 SymI_HasProto(ENT_STATIC_IND_ctr) \
584 SymI_HasProto(ENT_DYN_IND_ctr) \
585 SymI_HasProto(ENT_PERM_IND_ctr) \
586 SymI_HasProto(ENT_PAP_ctr) \
587 SymI_HasProto(ENT_AP_ctr) \
588 SymI_HasProto(ENT_AP_STACK_ctr) \
589 SymI_HasProto(ENT_BH_ctr) \
590 SymI_HasProto(UNKNOWN_CALL_ctr) \
591 SymI_HasProto(SLOW_CALL_v_ctr) \
592 SymI_HasProto(SLOW_CALL_f_ctr) \
593 SymI_HasProto(SLOW_CALL_d_ctr) \
594 SymI_HasProto(SLOW_CALL_l_ctr) \
595 SymI_HasProto(SLOW_CALL_n_ctr) \
596 SymI_HasProto(SLOW_CALL_p_ctr) \
597 SymI_HasProto(SLOW_CALL_pv_ctr) \
598 SymI_HasProto(SLOW_CALL_pp_ctr) \
599 SymI_HasProto(SLOW_CALL_ppv_ctr) \
600 SymI_HasProto(SLOW_CALL_ppp_ctr) \
601 SymI_HasProto(SLOW_CALL_pppv_ctr) \
602 SymI_HasProto(SLOW_CALL_pppp_ctr) \
603 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
604 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
605 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
606 SymI_HasProto(ticky_slow_call_unevald) \
607 SymI_HasProto(SLOW_CALL_ctr) \
608 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
609 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
610 SymI_HasProto(KNOWN_CALL_ctr) \
611 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
612 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
613 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
614 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
615 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
616 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
617 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
618 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
619 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
620 SymI_HasProto(UPDF_OMITTED_ctr) \
621 SymI_HasProto(UPDF_PUSHED_ctr) \
622 SymI_HasProto(CATCHF_PUSHED_ctr) \
623 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
624 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
625 SymI_HasProto(UPD_SQUEEZED_ctr) \
626 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
627 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
628 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
629 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
630 SymI_HasProto(ALLOC_HEAP_ctr) \
631 SymI_HasProto(ALLOC_HEAP_tot) \
632 SymI_HasProto(ALLOC_FUN_ctr) \
633 SymI_HasProto(ALLOC_FUN_adm) \
634 SymI_HasProto(ALLOC_FUN_gds) \
635 SymI_HasProto(ALLOC_FUN_slp) \
636 SymI_HasProto(UPD_NEW_IND_ctr) \
637 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
638 SymI_HasProto(UPD_OLD_IND_ctr) \
639 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
640 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
641 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
642 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
643 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
644 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
645 SymI_HasProto(GC_SEL_MINOR_ctr) \
646 SymI_HasProto(GC_SEL_MAJOR_ctr) \
647 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
648 SymI_HasProto(ALLOC_UP_THK_ctr) \
649 SymI_HasProto(ALLOC_SE_THK_ctr) \
650 SymI_HasProto(ALLOC_THK_adm) \
651 SymI_HasProto(ALLOC_THK_gds) \
652 SymI_HasProto(ALLOC_THK_slp) \
653 SymI_HasProto(ALLOC_CON_ctr) \
654 SymI_HasProto(ALLOC_CON_adm) \
655 SymI_HasProto(ALLOC_CON_gds) \
656 SymI_HasProto(ALLOC_CON_slp) \
657 SymI_HasProto(ALLOC_TUP_ctr) \
658 SymI_HasProto(ALLOC_TUP_adm) \
659 SymI_HasProto(ALLOC_TUP_gds) \
660 SymI_HasProto(ALLOC_TUP_slp) \
661 SymI_HasProto(ALLOC_BH_ctr) \
662 SymI_HasProto(ALLOC_BH_adm) \
663 SymI_HasProto(ALLOC_BH_gds) \
664 SymI_HasProto(ALLOC_BH_slp) \
665 SymI_HasProto(ALLOC_PRIM_ctr) \
666 SymI_HasProto(ALLOC_PRIM_adm) \
667 SymI_HasProto(ALLOC_PRIM_gds) \
668 SymI_HasProto(ALLOC_PRIM_slp) \
669 SymI_HasProto(ALLOC_PAP_ctr) \
670 SymI_HasProto(ALLOC_PAP_adm) \
671 SymI_HasProto(ALLOC_PAP_gds) \
672 SymI_HasProto(ALLOC_PAP_slp) \
673 SymI_HasProto(ALLOC_TSO_ctr) \
674 SymI_HasProto(ALLOC_TSO_adm) \
675 SymI_HasProto(ALLOC_TSO_gds) \
676 SymI_HasProto(ALLOC_TSO_slp) \
677 SymI_HasProto(RET_NEW_ctr) \
678 SymI_HasProto(RET_OLD_ctr) \
679 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
680 SymI_HasProto(RET_SEMI_loads_avoided)
683 // On most platforms, the garbage collector rewrites references
684 // to small integer and char objects to a set of common, shared ones.
686 // We don't do this when compiling to Windows DLLs at the moment because
687 // it doesn't support cross package data references well.
689 #if defined(__PIC__) && defined(mingw32_HOST_OS)
690 #define RTS_INTCHAR_SYMBOLS
692 #define RTS_INTCHAR_SYMBOLS \
693 SymI_HasProto(stg_CHARLIKE_closure) \
694 SymI_HasProto(stg_INTLIKE_closure)
698 #define RTS_SYMBOLS \
701 SymI_HasProto(StgReturn) \
702 SymI_HasProto(stg_enter_info) \
703 SymI_HasProto(stg_gc_void_info) \
704 SymI_HasProto(__stg_gc_enter_1) \
705 SymI_HasProto(stg_gc_noregs) \
706 SymI_HasProto(stg_gc_unpt_r1_info) \
707 SymI_HasProto(stg_gc_unpt_r1) \
708 SymI_HasProto(stg_gc_unbx_r1_info) \
709 SymI_HasProto(stg_gc_unbx_r1) \
710 SymI_HasProto(stg_gc_f1_info) \
711 SymI_HasProto(stg_gc_f1) \
712 SymI_HasProto(stg_gc_d1_info) \
713 SymI_HasProto(stg_gc_d1) \
714 SymI_HasProto(stg_gc_l1_info) \
715 SymI_HasProto(stg_gc_l1) \
716 SymI_HasProto(__stg_gc_fun) \
717 SymI_HasProto(stg_gc_fun_info) \
718 SymI_HasProto(stg_gc_gen) \
719 SymI_HasProto(stg_gc_gen_info) \
720 SymI_HasProto(stg_gc_gen_hp) \
721 SymI_HasProto(stg_gc_ut) \
722 SymI_HasProto(stg_gen_yield) \
723 SymI_HasProto(stg_yield_noregs) \
724 SymI_HasProto(stg_yield_to_interpreter) \
725 SymI_HasProto(stg_gen_block) \
726 SymI_HasProto(stg_block_noregs) \
727 SymI_HasProto(stg_block_1) \
728 SymI_HasProto(stg_block_takemvar) \
729 SymI_HasProto(stg_block_putmvar) \
731 SymI_HasProto(MallocFailHook) \
732 SymI_HasProto(OnExitHook) \
733 SymI_HasProto(OutOfHeapHook) \
734 SymI_HasProto(StackOverflowHook) \
735 SymI_HasProto(addDLL) \
736 SymI_HasProto(__int_encodeDouble) \
737 SymI_HasProto(__word_encodeDouble) \
738 SymI_HasProto(__2Int_encodeDouble) \
739 SymI_HasProto(__int_encodeFloat) \
740 SymI_HasProto(__word_encodeFloat) \
741 SymI_HasProto(stg_atomicallyzh) \
742 SymI_HasProto(barf) \
743 SymI_HasProto(debugBelch) \
744 SymI_HasProto(errorBelch) \
745 SymI_HasProto(sysErrorBelch) \
746 SymI_HasProto(stg_asyncExceptionsBlockedzh) \
747 SymI_HasProto(stg_blockAsyncExceptionszh) \
748 SymI_HasProto(stg_catchzh) \
749 SymI_HasProto(stg_catchRetryzh) \
750 SymI_HasProto(stg_catchSTMzh) \
751 SymI_HasProto(stg_checkzh) \
752 SymI_HasProto(closure_flags) \
753 SymI_HasProto(cmp_thread) \
754 SymI_HasProto(createAdjustor) \
755 SymI_HasProto(stg_decodeDoublezu2Intzh) \
756 SymI_HasProto(stg_decodeFloatzuIntzh) \
757 SymI_HasProto(defaultsHook) \
758 SymI_HasProto(stg_delayzh) \
759 SymI_HasProto(stg_deRefWeakzh) \
760 SymI_HasProto(stg_deRefStablePtrzh) \
761 SymI_HasProto(dirty_MUT_VAR) \
762 SymI_HasProto(stg_forkzh) \
763 SymI_HasProto(stg_forkOnzh) \
764 SymI_HasProto(forkProcess) \
765 SymI_HasProto(forkOS_createThread) \
766 SymI_HasProto(freeHaskellFunctionPtr) \
767 SymI_HasProto(getOrSetTypeableStore) \
768 SymI_HasProto(getOrSetGHCConcSignalHandlerStore) \
769 SymI_HasProto(getOrSetGHCConcPendingEventsStore) \
770 SymI_HasProto(getOrSetGHCConcPendingDelaysStore) \
771 SymI_HasProto(getOrSetGHCConcIOManagerThreadStore) \
772 SymI_HasProto(getOrSetGHCConcProddingStore) \
773 SymI_HasProto(genSymZh) \
774 SymI_HasProto(genericRaise) \
775 SymI_HasProto(getProgArgv) \
776 SymI_HasProto(getFullProgArgv) \
777 SymI_HasProto(getStablePtr) \
778 SymI_HasProto(hs_init) \
779 SymI_HasProto(hs_exit) \
780 SymI_HasProto(hs_set_argv) \
781 SymI_HasProto(hs_add_root) \
782 SymI_HasProto(hs_perform_gc) \
783 SymI_HasProto(hs_free_stable_ptr) \
784 SymI_HasProto(hs_free_fun_ptr) \
785 SymI_HasProto(hs_hpc_rootModule) \
786 SymI_HasProto(hs_hpc_module) \
787 SymI_HasProto(initLinker) \
788 SymI_HasProto(stg_unpackClosurezh) \
789 SymI_HasProto(stg_getApStackValzh) \
790 SymI_HasProto(stg_getSparkzh) \
791 SymI_HasProto(stg_isCurrentThreadBoundzh) \
792 SymI_HasProto(stg_isEmptyMVarzh) \
793 SymI_HasProto(stg_killThreadzh) \
794 SymI_HasProto(loadObj) \
795 SymI_HasProto(insertStableSymbol) \
796 SymI_HasProto(insertSymbol) \
797 SymI_HasProto(lookupSymbol) \
798 SymI_HasProto(stg_makeStablePtrzh) \
799 SymI_HasProto(stg_mkApUpd0zh) \
800 SymI_HasProto(stg_myThreadIdzh) \
801 SymI_HasProto(stg_labelThreadzh) \
802 SymI_HasProto(stg_newArrayzh) \
803 SymI_HasProto(stg_newBCOzh) \
804 SymI_HasProto(stg_newByteArrayzh) \
805 SymI_HasProto_redirect(newCAF, newDynCAF) \
806 SymI_HasProto(stg_newMVarzh) \
807 SymI_HasProto(stg_newMutVarzh) \
808 SymI_HasProto(stg_newTVarzh) \
809 SymI_HasProto(stg_noDuplicatezh) \
810 SymI_HasProto(stg_atomicModifyMutVarzh) \
811 SymI_HasProto(stg_newPinnedByteArrayzh) \
812 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
813 SymI_HasProto(newSpark) \
814 SymI_HasProto(performGC) \
815 SymI_HasProto(performMajorGC) \
816 SymI_HasProto(prog_argc) \
817 SymI_HasProto(prog_argv) \
818 SymI_HasProto(stg_putMVarzh) \
819 SymI_HasProto(stg_raisezh) \
820 SymI_HasProto(stg_raiseIOzh) \
821 SymI_HasProto(stg_readTVarzh) \
822 SymI_HasProto(stg_readTVarIOzh) \
823 SymI_HasProto(resumeThread) \
824 SymI_HasProto(resolveObjs) \
825 SymI_HasProto(stg_retryzh) \
826 SymI_HasProto(rts_apply) \
827 SymI_HasProto(rts_checkSchedStatus) \
828 SymI_HasProto(rts_eval) \
829 SymI_HasProto(rts_evalIO) \
830 SymI_HasProto(rts_evalLazyIO) \
831 SymI_HasProto(rts_evalStableIO) \
832 SymI_HasProto(rts_eval_) \
833 SymI_HasProto(rts_getBool) \
834 SymI_HasProto(rts_getChar) \
835 SymI_HasProto(rts_getDouble) \
836 SymI_HasProto(rts_getFloat) \
837 SymI_HasProto(rts_getInt) \
838 SymI_HasProto(rts_getInt8) \
839 SymI_HasProto(rts_getInt16) \
840 SymI_HasProto(rts_getInt32) \
841 SymI_HasProto(rts_getInt64) \
842 SymI_HasProto(rts_getPtr) \
843 SymI_HasProto(rts_getFunPtr) \
844 SymI_HasProto(rts_getStablePtr) \
845 SymI_HasProto(rts_getThreadId) \
846 SymI_HasProto(rts_getWord) \
847 SymI_HasProto(rts_getWord8) \
848 SymI_HasProto(rts_getWord16) \
849 SymI_HasProto(rts_getWord32) \
850 SymI_HasProto(rts_getWord64) \
851 SymI_HasProto(rts_lock) \
852 SymI_HasProto(rts_mkBool) \
853 SymI_HasProto(rts_mkChar) \
854 SymI_HasProto(rts_mkDouble) \
855 SymI_HasProto(rts_mkFloat) \
856 SymI_HasProto(rts_mkInt) \
857 SymI_HasProto(rts_mkInt8) \
858 SymI_HasProto(rts_mkInt16) \
859 SymI_HasProto(rts_mkInt32) \
860 SymI_HasProto(rts_mkInt64) \
861 SymI_HasProto(rts_mkPtr) \
862 SymI_HasProto(rts_mkFunPtr) \
863 SymI_HasProto(rts_mkStablePtr) \
864 SymI_HasProto(rts_mkString) \
865 SymI_HasProto(rts_mkWord) \
866 SymI_HasProto(rts_mkWord8) \
867 SymI_HasProto(rts_mkWord16) \
868 SymI_HasProto(rts_mkWord32) \
869 SymI_HasProto(rts_mkWord64) \
870 SymI_HasProto(rts_unlock) \
871 SymI_HasProto(rts_unsafeGetMyCapability) \
872 SymI_HasProto(rtsSupportsBoundThreads) \
873 SymI_HasProto(setProgArgv) \
874 SymI_HasProto(startupHaskell) \
875 SymI_HasProto(shutdownHaskell) \
876 SymI_HasProto(shutdownHaskellAndExit) \
877 SymI_HasProto(stable_ptr_table) \
878 SymI_HasProto(stackOverflow) \
879 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
880 SymI_HasProto(stg_BLACKHOLE_info) \
881 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
882 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
883 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
884 SymI_HasProto(startTimer) \
885 SymI_HasProto(stg_MVAR_CLEAN_info) \
886 SymI_HasProto(stg_MVAR_DIRTY_info) \
887 SymI_HasProto(stg_IND_STATIC_info) \
888 SymI_HasProto(stg_ARR_WORDS_info) \
889 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
890 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
891 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
892 SymI_HasProto(stg_WEAK_info) \
893 SymI_HasProto(stg_ap_v_info) \
894 SymI_HasProto(stg_ap_f_info) \
895 SymI_HasProto(stg_ap_d_info) \
896 SymI_HasProto(stg_ap_l_info) \
897 SymI_HasProto(stg_ap_n_info) \
898 SymI_HasProto(stg_ap_p_info) \
899 SymI_HasProto(stg_ap_pv_info) \
900 SymI_HasProto(stg_ap_pp_info) \
901 SymI_HasProto(stg_ap_ppv_info) \
902 SymI_HasProto(stg_ap_ppp_info) \
903 SymI_HasProto(stg_ap_pppv_info) \
904 SymI_HasProto(stg_ap_pppp_info) \
905 SymI_HasProto(stg_ap_ppppp_info) \
906 SymI_HasProto(stg_ap_pppppp_info) \
907 SymI_HasProto(stg_ap_0_fast) \
908 SymI_HasProto(stg_ap_v_fast) \
909 SymI_HasProto(stg_ap_f_fast) \
910 SymI_HasProto(stg_ap_d_fast) \
911 SymI_HasProto(stg_ap_l_fast) \
912 SymI_HasProto(stg_ap_n_fast) \
913 SymI_HasProto(stg_ap_p_fast) \
914 SymI_HasProto(stg_ap_pv_fast) \
915 SymI_HasProto(stg_ap_pp_fast) \
916 SymI_HasProto(stg_ap_ppv_fast) \
917 SymI_HasProto(stg_ap_ppp_fast) \
918 SymI_HasProto(stg_ap_pppv_fast) \
919 SymI_HasProto(stg_ap_pppp_fast) \
920 SymI_HasProto(stg_ap_ppppp_fast) \
921 SymI_HasProto(stg_ap_pppppp_fast) \
922 SymI_HasProto(stg_ap_1_upd_info) \
923 SymI_HasProto(stg_ap_2_upd_info) \
924 SymI_HasProto(stg_ap_3_upd_info) \
925 SymI_HasProto(stg_ap_4_upd_info) \
926 SymI_HasProto(stg_ap_5_upd_info) \
927 SymI_HasProto(stg_ap_6_upd_info) \
928 SymI_HasProto(stg_ap_7_upd_info) \
929 SymI_HasProto(stg_exit) \
930 SymI_HasProto(stg_sel_0_upd_info) \
931 SymI_HasProto(stg_sel_10_upd_info) \
932 SymI_HasProto(stg_sel_11_upd_info) \
933 SymI_HasProto(stg_sel_12_upd_info) \
934 SymI_HasProto(stg_sel_13_upd_info) \
935 SymI_HasProto(stg_sel_14_upd_info) \
936 SymI_HasProto(stg_sel_15_upd_info) \
937 SymI_HasProto(stg_sel_1_upd_info) \
938 SymI_HasProto(stg_sel_2_upd_info) \
939 SymI_HasProto(stg_sel_3_upd_info) \
940 SymI_HasProto(stg_sel_4_upd_info) \
941 SymI_HasProto(stg_sel_5_upd_info) \
942 SymI_HasProto(stg_sel_6_upd_info) \
943 SymI_HasProto(stg_sel_7_upd_info) \
944 SymI_HasProto(stg_sel_8_upd_info) \
945 SymI_HasProto(stg_sel_9_upd_info) \
946 SymI_HasProto(stg_upd_frame_info) \
947 SymI_HasProto(stg_bh_upd_frame_info) \
948 SymI_HasProto(suspendThread) \
949 SymI_HasProto(stg_takeMVarzh) \
950 SymI_HasProto(stg_threadStatuszh) \
951 SymI_HasProto(stg_tryPutMVarzh) \
952 SymI_HasProto(stg_tryTakeMVarzh) \
953 SymI_HasProto(stg_unblockAsyncExceptionszh) \
954 SymI_HasProto(unloadObj) \
955 SymI_HasProto(stg_unsafeThawArrayzh) \
956 SymI_HasProto(stg_waitReadzh) \
957 SymI_HasProto(stg_waitWritezh) \
958 SymI_HasProto(stg_writeTVarzh) \
959 SymI_HasProto(stg_yieldzh) \
960 SymI_NeedsProto(stg_interp_constr_entry) \
961 SymI_HasProto(alloc_blocks_lim) \
963 SymI_HasProto(allocate) \
964 SymI_HasProto(allocateExec) \
965 SymI_HasProto(freeExec) \
966 SymI_HasProto(getAllocations) \
967 SymI_HasProto(revertCAFs) \
968 SymI_HasProto(RtsFlags) \
969 SymI_NeedsProto(rts_breakpoint_io_action) \
970 SymI_NeedsProto(rts_stop_next_breakpoint) \
971 SymI_NeedsProto(rts_stop_on_exception) \
972 SymI_HasProto(stopTimer) \
973 SymI_HasProto(n_capabilities) \
974 SymI_HasProto(stg_traceCcszh) \
975 SymI_HasProto(stg_traceEventzh) \
976 RTS_USER_SIGNALS_SYMBOLS \
980 // 64-bit support functions in libgcc.a
981 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
982 #define RTS_LIBGCC_SYMBOLS \
983 SymI_NeedsProto(__divdi3) \
984 SymI_NeedsProto(__udivdi3) \
985 SymI_NeedsProto(__moddi3) \
986 SymI_NeedsProto(__umoddi3) \
987 SymI_NeedsProto(__muldi3) \
988 SymI_NeedsProto(__ashldi3) \
989 SymI_NeedsProto(__ashrdi3) \
990 SymI_NeedsProto(__lshrdi3)
992 #define RTS_LIBGCC_SYMBOLS
995 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
996 // Symbols that don't have a leading underscore
997 // on Mac OS X. They have to receive special treatment,
998 // see machoInitSymbolsWithoutUnderscore()
999 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1000 SymI_NeedsProto(saveFP) \
1001 SymI_NeedsProto(restFP)
1004 /* entirely bogus claims about types of these symbols */
1005 #define SymI_NeedsProto(vvv) extern void vvv(void);
1006 #if defined(__PIC__) && defined(mingw32_TARGET_OS)
1007 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1008 #define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1010 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1011 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1013 #define SymI_HasProto(vvv) /**/
1014 #define SymI_HasProto_redirect(vvv,xxx) /**/
1017 RTS_POSIX_ONLY_SYMBOLS
1018 RTS_MINGW_ONLY_SYMBOLS
1019 RTS_CYGWIN_ONLY_SYMBOLS
1020 RTS_DARWIN_ONLY_SYMBOLS
1023 #undef SymI_NeedsProto
1024 #undef SymI_HasProto
1025 #undef SymI_HasProto_redirect
1026 #undef SymE_HasProto
1027 #undef SymE_NeedsProto
1029 #ifdef LEADING_UNDERSCORE
1030 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1032 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1035 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1037 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1038 (void*)DLL_IMPORT_DATA_REF(vvv) },
1040 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1041 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1043 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1044 // another symbol. See newCAF/newDynCAF for an example.
1045 #define SymI_HasProto_redirect(vvv,xxx) \
1046 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1049 static RtsSymbolVal rtsSyms[] = {
1052 RTS_POSIX_ONLY_SYMBOLS
1053 RTS_MINGW_ONLY_SYMBOLS
1054 RTS_CYGWIN_ONLY_SYMBOLS
1055 RTS_DARWIN_ONLY_SYMBOLS
1058 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1059 // dyld stub code contains references to this,
1060 // but it should never be called because we treat
1061 // lazy pointers as nonlazy.
1062 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1064 { 0, 0 } /* sentinel */
1069 /* -----------------------------------------------------------------------------
1070 * Insert symbols into hash tables, checking for duplicates.
1073 static void ghciInsertStrHashTable ( char* obj_name,
1079 if (lookupHashTable(table, (StgWord)key) == NULL)
1081 insertStrHashTable(table, (StgWord)key, data);
1086 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1088 "whilst processing object file\n"
1090 "This could be caused by:\n"
1091 " * Loading two different object files which export the same symbol\n"
1092 " * Specifying the same object file twice on the GHCi command line\n"
1093 " * An incorrect `package.conf' entry, causing some object to be\n"
1095 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1102 /* -----------------------------------------------------------------------------
1103 * initialize the object linker
1107 static int linker_init_done = 0 ;
1109 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1110 static void *dl_prog_handle;
1111 static regex_t re_invalid;
1112 static regex_t re_realso;
1114 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1122 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1126 /* Make initLinker idempotent, so we can call it
1127 before evey relevant operation; that means we
1128 don't need to initialise the linker separately */
1129 if (linker_init_done == 1) { return; } else {
1130 linker_init_done = 1;
1133 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1134 initMutex(&dl_mutex);
1136 stablehash = allocStrHashTable();
1137 symhash = allocStrHashTable();
1139 /* populate the symbol table with stuff from the RTS */
1140 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1141 ghciInsertStrHashTable("(GHCi built-in symbols)",
1142 symhash, sym->lbl, sym->addr);
1144 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1145 machoInitSymbolsWithoutUnderscore();
1148 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1149 # if defined(RTLD_DEFAULT)
1150 dl_prog_handle = RTLD_DEFAULT;
1152 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1153 # endif /* RTLD_DEFAULT */
1155 compileResult = regcomp(&re_invalid,
1156 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*invalid ELF header",
1158 ASSERT( compileResult == 0 );
1159 compileResult = regcomp(&re_realso,
1160 "GROUP *\\( *(([^ )])+)",
1162 ASSERT( compileResult == 0 );
1165 #if defined(x86_64_HOST_ARCH)
1166 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1167 // User-override for mmap_32bit_base
1168 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1172 #if defined(mingw32_HOST_OS)
1174 * These two libraries cause problems when added to the static link,
1175 * but are necessary for resolving symbols in GHCi, hence we load
1176 * them manually here.
1184 exitLinker( void ) {
1185 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1186 if (linker_init_done == 1) {
1187 regfree(&re_invalid);
1188 regfree(&re_realso);
1190 closeMutex(&dl_mutex);
1196 /* -----------------------------------------------------------------------------
1197 * Loading DLL or .so dynamic libraries
1198 * -----------------------------------------------------------------------------
1200 * Add a DLL from which symbols may be found. In the ELF case, just
1201 * do RTLD_GLOBAL-style add, so no further messing around needs to
1202 * happen in order that symbols in the loaded .so are findable --
1203 * lookupSymbol() will subsequently see them by dlsym on the program's
1204 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1206 * In the PEi386 case, open the DLLs and put handles to them in a
1207 * linked list. When looking for a symbol, try all handles in the
1208 * list. This means that we need to load even DLLs that are guaranteed
1209 * to be in the ghc.exe image already, just so we can get a handle
1210 * to give to loadSymbol, so that we can find the symbols. For such
1211 * libraries, the LoadLibrary call should be a no-op except for returning
1216 #if defined(OBJFORMAT_PEi386)
1217 /* A record for storing handles into DLLs. */
1222 struct _OpenedDLL* next;
1227 /* A list thereof. */
1228 static OpenedDLL* opened_dlls = NULL;
1231 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1234 internal_dlopen(const char *dll_name)
1240 // omitted: RTLD_NOW
1241 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1243 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1245 //-------------- Begin critical section ------------------
1246 // This critical section is necessary because dlerror() is not
1247 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1248 // Also, the error message returned must be copied to preserve it
1251 ACQUIRE_LOCK(&dl_mutex);
1252 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1256 /* dlopen failed; return a ptr to the error msg. */
1258 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1259 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1260 strcpy(errmsg_copy, errmsg);
1261 errmsg = errmsg_copy;
1263 RELEASE_LOCK(&dl_mutex);
1264 //--------------- End critical section -------------------
1271 addDLL( char *dll_name )
1273 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1274 /* ------------------- ELF DLL loader ------------------- */
1277 regmatch_t match[NMATCH];
1280 size_t match_length;
1281 #define MAXLINE 1000
1287 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1288 errmsg = internal_dlopen(dll_name);
1290 if (errmsg == NULL) {
1294 // GHC Trac ticket #2615
1295 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1296 // contain linker scripts rather than ELF-format object code. This
1297 // code handles the situation by recognizing the real object code
1298 // file name given in the linker script.
1300 // If an "invalid ELF header" error occurs, it is assumed that the
1301 // .so file contains a linker script instead of ELF object code.
1302 // In this case, the code looks for the GROUP ( ... ) linker
1303 // directive. If one is found, the first file name inside the
1304 // parentheses is treated as the name of a dynamic library and the
1305 // code attempts to dlopen that file. If this is also unsuccessful,
1306 // an error message is returned.
1308 // see if the error message is due to an invalid ELF header
1309 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1310 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1311 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1313 // success -- try to read the named file as a linker script
1314 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1316 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1317 line[match_length] = '\0'; // make sure string is null-terminated
1318 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1319 if ((fp = fopen(line, "r")) == NULL) {
1320 return errmsg; // return original error if open fails
1322 // try to find a GROUP ( ... ) command
1323 while (fgets(line, MAXLINE, fp) != NULL) {
1324 IF_DEBUG(linker, debugBelch("input line = %s", line));
1325 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1326 // success -- try to dlopen the first named file
1327 IF_DEBUG(linker, debugBelch("match%s\n",""));
1328 line[match[1].rm_eo] = '\0';
1329 errmsg = internal_dlopen(line+match[1].rm_so);
1332 // if control reaches here, no GROUP ( ... ) directive was found
1333 // and the original error message is returned to the caller
1339 # elif defined(OBJFORMAT_PEi386)
1340 /* ------------------- Win32 DLL loader ------------------- */
1348 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1350 /* See if we've already got it, and ignore if so. */
1351 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1352 if (0 == strcmp(o_dll->name, dll_name))
1356 /* The file name has no suffix (yet) so that we can try
1357 both foo.dll and foo.drv
1359 The documentation for LoadLibrary says:
1360 If no file name extension is specified in the lpFileName
1361 parameter, the default library extension .dll is
1362 appended. However, the file name string can include a trailing
1363 point character (.) to indicate that the module name has no
1366 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1367 sprintf(buf, "%s.DLL", dll_name);
1368 instance = LoadLibrary(buf);
1369 if (instance == NULL) {
1370 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1371 // KAA: allow loading of drivers (like winspool.drv)
1372 sprintf(buf, "%s.DRV", dll_name);
1373 instance = LoadLibrary(buf);
1374 if (instance == NULL) {
1375 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1376 // #1883: allow loading of unix-style libfoo.dll DLLs
1377 sprintf(buf, "lib%s.DLL", dll_name);
1378 instance = LoadLibrary(buf);
1379 if (instance == NULL) {
1386 /* Add this DLL to the list of DLLs in which to search for symbols. */
1387 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1388 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
1389 strcpy(o_dll->name, dll_name);
1390 o_dll->instance = instance;
1391 o_dll->next = opened_dlls;
1392 opened_dlls = o_dll;
1398 sysErrorBelch(dll_name);
1400 /* LoadLibrary failed; return a ptr to the error msg. */
1401 return "addDLL: could not load DLL";
1404 barf("addDLL: not implemented on this platform");
1408 /* -----------------------------------------------------------------------------
1409 * insert a stable symbol in the hash table
1413 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1415 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1419 /* -----------------------------------------------------------------------------
1420 * insert a symbol in the hash table
1423 insertSymbol(char* obj_name, char* key, void* data)
1425 ghciInsertStrHashTable(obj_name, symhash, key, data);
1428 /* -----------------------------------------------------------------------------
1429 * lookup a symbol in the hash table
1432 lookupSymbol( char *lbl )
1436 ASSERT(symhash != NULL);
1437 val = lookupStrHashTable(symhash, lbl);
1440 # if defined(OBJFORMAT_ELF)
1441 return dlsym(dl_prog_handle, lbl);
1442 # elif defined(OBJFORMAT_MACHO)
1444 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1447 HACK: On OS X, global symbols are prefixed with an underscore.
1448 However, dlsym wants us to omit the leading underscore from the
1449 symbol name. For now, we simply strip it off here (and ONLY
1452 ASSERT(lbl[0] == '_');
1453 return dlsym(dl_prog_handle, lbl+1);
1455 if(NSIsSymbolNameDefined(lbl)) {
1456 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1457 return NSAddressOfSymbol(symbol);
1461 # endif /* HAVE_DLFCN_H */
1462 # elif defined(OBJFORMAT_PEi386)
1465 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1466 if (sym != NULL) { return sym; };
1468 // Also try looking up the symbol without the @N suffix. Some
1469 // DLLs have the suffixes on their symbols, some don't.
1470 zapTrailingAtSign ( (unsigned char*)lbl );
1471 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1472 if (sym != NULL) { return sym; };
1484 /* -----------------------------------------------------------------------------
1485 * Debugging aid: look in GHCi's object symbol tables for symbols
1486 * within DELTA bytes of the specified address, and show their names.
1489 void ghci_enquire ( char* addr );
1491 void ghci_enquire ( char* addr )
1496 const int DELTA = 64;
1501 for (oc = objects; oc; oc = oc->next) {
1502 for (i = 0; i < oc->n_symbols; i++) {
1503 sym = oc->symbols[i];
1504 if (sym == NULL) continue;
1507 a = lookupStrHashTable(symhash, sym);
1510 // debugBelch("ghci_enquire: can't find %s\n", sym);
1512 else if (addr-DELTA <= a && a <= addr+DELTA) {
1513 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1521 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1524 mmapForLinker (size_t bytes, nat flags, int fd)
1526 void *map_addr = NULL;
1529 static nat fixed = 0;
1531 pagesize = getpagesize();
1532 size = ROUND_UP(bytes, pagesize);
1534 #if defined(x86_64_HOST_ARCH)
1537 if (mmap_32bit_base != 0) {
1538 map_addr = mmap_32bit_base;
1542 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1543 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1545 if (result == MAP_FAILED) {
1546 sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1547 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1548 stg_exit(EXIT_FAILURE);
1551 #if defined(x86_64_HOST_ARCH)
1552 if (mmap_32bit_base != 0) {
1553 if (result == map_addr) {
1554 mmap_32bit_base = (StgWord8*)map_addr + size;
1556 if ((W_)result > 0x80000000) {
1557 // oops, we were given memory over 2Gb
1558 #if defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS)
1559 // Some platforms require MAP_FIXED. This is normally
1560 // a bad idea, because MAP_FIXED will overwrite
1561 // existing mappings.
1562 munmap(result,size);
1566 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);
1569 // hmm, we were given memory somewhere else, but it's
1570 // still under 2Gb so we can use it. Next time, ask
1571 // for memory right after the place we just got some
1572 mmap_32bit_base = (StgWord8*)result + size;
1576 if ((W_)result > 0x80000000) {
1577 // oops, we were given memory over 2Gb
1578 // ... try allocating memory somewhere else?;
1579 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1580 munmap(result, size);
1582 // Set a base address and try again... (guess: 1Gb)
1583 mmap_32bit_base = (void*)0x40000000;
1593 /* -----------------------------------------------------------------------------
1594 * Load an obj (populate the global symbol table, but don't resolve yet)
1596 * Returns: 1 if ok, 0 on error.
1599 loadObj( char *path )
1611 /* debugBelch("loadObj %s\n", path ); */
1613 /* Check that we haven't already loaded this object.
1614 Ignore requests to load multiple times */
1618 for (o = objects; o; o = o->next) {
1619 if (0 == strcmp(o->fileName, path)) {
1621 break; /* don't need to search further */
1625 IF_DEBUG(linker, debugBelch(
1626 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1627 "same object file twice:\n"
1629 "GHCi will ignore this, but be warned.\n"
1631 return 1; /* success */
1635 oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
1637 # if defined(OBJFORMAT_ELF)
1638 oc->formatName = "ELF";
1639 # elif defined(OBJFORMAT_PEi386)
1640 oc->formatName = "PEi386";
1641 # elif defined(OBJFORMAT_MACHO)
1642 oc->formatName = "Mach-O";
1645 barf("loadObj: not implemented on this platform");
1648 r = stat(path, &st);
1649 if (r == -1) { return 0; }
1651 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1652 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1653 strcpy(oc->fileName, path);
1655 oc->fileSize = st.st_size;
1657 oc->sections = NULL;
1658 oc->proddables = NULL;
1660 /* chain it onto the list of objects */
1665 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
1667 #if defined(openbsd_HOST_OS)
1668 fd = open(path, O_RDONLY, S_IRUSR);
1670 fd = open(path, O_RDONLY);
1673 barf("loadObj: can't open `%s'", path);
1675 oc->image = mmapForLinker(oc->fileSize, 0, fd);
1679 #else /* !USE_MMAP */
1680 /* load the image into memory */
1681 f = fopen(path, "rb");
1683 barf("loadObj: can't read `%s'", path);
1685 # if defined(mingw32_HOST_OS)
1686 // TODO: We would like to use allocateExec here, but allocateExec
1687 // cannot currently allocate blocks large enough.
1688 oc->image = VirtualAlloc(NULL, oc->fileSize, MEM_RESERVE | MEM_COMMIT,
1689 PAGE_EXECUTE_READWRITE);
1690 # elif defined(darwin_HOST_OS)
1691 // In a Mach-O .o file, all sections can and will be misaligned
1692 // if the total size of the headers is not a multiple of the
1693 // desired alignment. This is fine for .o files that only serve
1694 // as input for the static linker, but it's not fine for us,
1695 // as SSE (used by gcc for floating point) and Altivec require
1696 // 16-byte alignment.
1697 // We calculate the correct alignment from the header before
1698 // reading the file, and then we misalign oc->image on purpose so
1699 // that the actual sections end up aligned again.
1700 oc->misalignment = machoGetMisalignment(f);
1701 oc->image = stgMallocBytes(oc->fileSize + oc->misalignment, "loadObj(image)");
1702 oc->image += oc->misalignment;
1704 oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
1709 n = fread ( oc->image, 1, oc->fileSize, f );
1710 if (n != oc->fileSize)
1711 barf("loadObj: error whilst reading `%s'", path);
1714 #endif /* USE_MMAP */
1716 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1717 r = ocAllocateSymbolExtras_MachO ( oc );
1718 if (!r) { return r; }
1719 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1720 r = ocAllocateSymbolExtras_ELF ( oc );
1721 if (!r) { return r; }
1724 /* verify the in-memory image */
1725 # if defined(OBJFORMAT_ELF)
1726 r = ocVerifyImage_ELF ( oc );
1727 # elif defined(OBJFORMAT_PEi386)
1728 r = ocVerifyImage_PEi386 ( oc );
1729 # elif defined(OBJFORMAT_MACHO)
1730 r = ocVerifyImage_MachO ( oc );
1732 barf("loadObj: no verify method");
1734 if (!r) { return r; }
1736 /* build the symbol list for this image */
1737 # if defined(OBJFORMAT_ELF)
1738 r = ocGetNames_ELF ( oc );
1739 # elif defined(OBJFORMAT_PEi386)
1740 r = ocGetNames_PEi386 ( oc );
1741 # elif defined(OBJFORMAT_MACHO)
1742 r = ocGetNames_MachO ( oc );
1744 barf("loadObj: no getNames method");
1746 if (!r) { return r; }
1748 /* loaded, but not resolved yet */
1749 oc->status = OBJECT_LOADED;
1754 /* -----------------------------------------------------------------------------
1755 * resolve all the currently unlinked objects in memory
1757 * Returns: 1 if ok, 0 on error.
1767 for (oc = objects; oc; oc = oc->next) {
1768 if (oc->status != OBJECT_RESOLVED) {
1769 # if defined(OBJFORMAT_ELF)
1770 r = ocResolve_ELF ( oc );
1771 # elif defined(OBJFORMAT_PEi386)
1772 r = ocResolve_PEi386 ( oc );
1773 # elif defined(OBJFORMAT_MACHO)
1774 r = ocResolve_MachO ( oc );
1776 barf("resolveObjs: not implemented on this platform");
1778 if (!r) { return r; }
1779 oc->status = OBJECT_RESOLVED;
1785 /* -----------------------------------------------------------------------------
1786 * delete an object from the pool
1789 unloadObj( char *path )
1791 ObjectCode *oc, *prev;
1793 ASSERT(symhash != NULL);
1794 ASSERT(objects != NULL);
1799 for (oc = objects; oc; prev = oc, oc = oc->next) {
1800 if (!strcmp(oc->fileName,path)) {
1802 /* Remove all the mappings for the symbols within this
1807 for (i = 0; i < oc->n_symbols; i++) {
1808 if (oc->symbols[i] != NULL) {
1809 removeStrHashTable(symhash, oc->symbols[i], NULL);
1817 prev->next = oc->next;
1820 // We're going to leave this in place, in case there are
1821 // any pointers from the heap into it:
1822 // #ifdef mingw32_HOST_OS
1823 // VirtualFree(oc->image);
1825 // stgFree(oc->image);
1827 stgFree(oc->fileName);
1828 stgFree(oc->symbols);
1829 stgFree(oc->sections);
1835 errorBelch("unloadObj: can't find `%s' to unload", path);
1839 /* -----------------------------------------------------------------------------
1840 * Sanity checking. For each ObjectCode, maintain a list of address ranges
1841 * which may be prodded during relocation, and abort if we try and write
1842 * outside any of these.
1844 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1847 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1848 /* debugBelch("aPB %p %p %d\n", oc, start, size); */
1852 pb->next = oc->proddables;
1853 oc->proddables = pb;
1856 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1859 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1860 char* s = (char*)(pb->start);
1861 char* e = s + pb->size - 1;
1862 char* a = (char*)addr;
1863 /* Assumes that the biggest fixup involves a 4-byte write. This
1864 probably needs to be changed to 8 (ie, +7) on 64-bit
1866 if (a >= s && (a+3) <= e) return;
1868 barf("checkProddableBlock: invalid fixup in runtime linker");
1871 /* -----------------------------------------------------------------------------
1872 * Section management.
1874 static void addSection ( ObjectCode* oc, SectionKind kind,
1875 void* start, void* end )
1877 Section* s = stgMallocBytes(sizeof(Section), "addSection");
1881 s->next = oc->sections;
1884 debugBelch("addSection: %p-%p (size %d), kind %d\n",
1885 start, ((char*)end)-1, end - start + 1, kind );
1890 /* --------------------------------------------------------------------------
1892 * This is about allocating a small chunk of memory for every symbol in the
1893 * object file. We make sure that the SymboLExtras are always "in range" of
1894 * limited-range PC-relative instructions on various platforms by allocating
1895 * them right next to the object code itself.
1898 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
1901 ocAllocateSymbolExtras
1903 Allocate additional space at the end of the object file image to make room
1904 for jump islands (powerpc, x86_64) and GOT entries (x86_64).
1906 PowerPC relative branch instructions have a 24 bit displacement field.
1907 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
1908 If a particular imported symbol is outside this range, we have to redirect
1909 the jump to a short piece of new code that just loads the 32bit absolute
1910 address and jumps there.
1911 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
1914 This function just allocates space for one SymbolExtra for every
1915 undefined symbol in the object file. The code for the jump islands is
1916 filled in by makeSymbolExtra below.
1919 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
1926 int misalignment = 0;
1927 #ifdef darwin_HOST_OS
1928 misalignment = oc->misalignment;
1934 // round up to the nearest 4
1935 aligned = (oc->fileSize + 3) & ~3;
1938 pagesize = getpagesize();
1939 n = ROUND_UP( oc->fileSize, pagesize );
1940 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
1942 /* we try to use spare space at the end of the last page of the
1943 * image for the jump islands, but if there isn't enough space
1944 * then we have to map some (anonymously, remembering MAP_32BIT).
1946 if( m > n ) // we need to allocate more pages
1948 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
1953 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1956 oc->image -= misalignment;
1957 oc->image = stgReallocBytes( oc->image,
1959 aligned + sizeof (SymbolExtra) * count,
1960 "ocAllocateSymbolExtras" );
1961 oc->image += misalignment;
1963 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1964 #endif /* USE_MMAP */
1966 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
1969 oc->symbol_extras = NULL;
1971 oc->first_symbol_extra = first;
1972 oc->n_symbol_extras = count;
1977 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
1978 unsigned long symbolNumber,
1979 unsigned long target )
1983 ASSERT( symbolNumber >= oc->first_symbol_extra
1984 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
1986 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
1988 #ifdef powerpc_HOST_ARCH
1989 // lis r12, hi16(target)
1990 extra->jumpIsland.lis_r12 = 0x3d80;
1991 extra->jumpIsland.hi_addr = target >> 16;
1993 // ori r12, r12, lo16(target)
1994 extra->jumpIsland.ori_r12_r12 = 0x618c;
1995 extra->jumpIsland.lo_addr = target & 0xffff;
1998 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2001 extra->jumpIsland.bctr = 0x4e800420;
2003 #ifdef x86_64_HOST_ARCH
2005 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2006 extra->addr = target;
2007 memcpy(extra->jumpIsland, jmp, 6);
2015 /* --------------------------------------------------------------------------
2016 * PowerPC specifics (instruction cache flushing)
2017 * ------------------------------------------------------------------------*/
2019 #ifdef powerpc_TARGET_ARCH
2021 ocFlushInstructionCache
2023 Flush the data & instruction caches.
2024 Because the PPC has split data/instruction caches, we have to
2025 do that whenever we modify code at runtime.
2028 static void ocFlushInstructionCache( ObjectCode *oc )
2030 int n = (oc->fileSize + sizeof( SymbolExtra ) * oc->n_symbol_extras + 3) / 4;
2031 unsigned long *p = (unsigned long *) oc->image;
2035 __asm__ volatile ( "dcbf 0,%0\n\t"
2043 __asm__ volatile ( "sync\n\t"
2049 /* --------------------------------------------------------------------------
2050 * PEi386 specifics (Win32 targets)
2051 * ------------------------------------------------------------------------*/
2053 /* The information for this linker comes from
2054 Microsoft Portable Executable
2055 and Common Object File Format Specification
2056 revision 5.1 January 1998
2057 which SimonM says comes from the MS Developer Network CDs.
2059 It can be found there (on older CDs), but can also be found
2062 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
2064 (this is Rev 6.0 from February 1999).
2066 Things move, so if that fails, try searching for it via
2068 http://www.google.com/search?q=PE+COFF+specification
2070 The ultimate reference for the PE format is the Winnt.h
2071 header file that comes with the Platform SDKs; as always,
2072 implementations will drift wrt their documentation.
2074 A good background article on the PE format is Matt Pietrek's
2075 March 1994 article in Microsoft System Journal (MSJ)
2076 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
2077 Win32 Portable Executable File Format." The info in there
2078 has recently been updated in a two part article in
2079 MSDN magazine, issues Feb and March 2002,
2080 "Inside Windows: An In-Depth Look into the Win32 Portable
2081 Executable File Format"
2083 John Levine's book "Linkers and Loaders" contains useful
2088 #if defined(OBJFORMAT_PEi386)
2092 typedef unsigned char UChar;
2093 typedef unsigned short UInt16;
2094 typedef unsigned int UInt32;
2101 UInt16 NumberOfSections;
2102 UInt32 TimeDateStamp;
2103 UInt32 PointerToSymbolTable;
2104 UInt32 NumberOfSymbols;
2105 UInt16 SizeOfOptionalHeader;
2106 UInt16 Characteristics;
2110 #define sizeof_COFF_header 20
2117 UInt32 VirtualAddress;
2118 UInt32 SizeOfRawData;
2119 UInt32 PointerToRawData;
2120 UInt32 PointerToRelocations;
2121 UInt32 PointerToLinenumbers;
2122 UInt16 NumberOfRelocations;
2123 UInt16 NumberOfLineNumbers;
2124 UInt32 Characteristics;
2128 #define sizeof_COFF_section 40
2135 UInt16 SectionNumber;
2138 UChar NumberOfAuxSymbols;
2142 #define sizeof_COFF_symbol 18
2147 UInt32 VirtualAddress;
2148 UInt32 SymbolTableIndex;
2153 #define sizeof_COFF_reloc 10
2156 /* From PE spec doc, section 3.3.2 */
2157 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
2158 windows.h -- for the same purpose, but I want to know what I'm
2160 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
2161 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
2162 #define MYIMAGE_FILE_DLL 0x2000
2163 #define MYIMAGE_FILE_SYSTEM 0x1000
2164 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
2165 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
2166 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
2168 /* From PE spec doc, section 5.4.2 and 5.4.4 */
2169 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
2170 #define MYIMAGE_SYM_CLASS_STATIC 3
2171 #define MYIMAGE_SYM_UNDEFINED 0
2173 /* From PE spec doc, section 4.1 */
2174 #define MYIMAGE_SCN_CNT_CODE 0x00000020
2175 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
2176 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
2178 /* From PE spec doc, section 5.2.1 */
2179 #define MYIMAGE_REL_I386_DIR32 0x0006
2180 #define MYIMAGE_REL_I386_REL32 0x0014
2183 /* We use myindex to calculate array addresses, rather than
2184 simply doing the normal subscript thing. That's because
2185 some of the above structs have sizes which are not
2186 a whole number of words. GCC rounds their sizes up to a
2187 whole number of words, which means that the address calcs
2188 arising from using normal C indexing or pointer arithmetic
2189 are just plain wrong. Sigh.
2192 myindex ( int scale, void* base, int index )
2195 ((UChar*)base) + scale * index;
2200 printName ( UChar* name, UChar* strtab )
2202 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2203 UInt32 strtab_offset = * (UInt32*)(name+4);
2204 debugBelch("%s", strtab + strtab_offset );
2207 for (i = 0; i < 8; i++) {
2208 if (name[i] == 0) break;
2209 debugBelch("%c", name[i] );
2216 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
2218 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2219 UInt32 strtab_offset = * (UInt32*)(name+4);
2220 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
2226 if (name[i] == 0) break;
2236 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
2239 /* If the string is longer than 8 bytes, look in the
2240 string table for it -- this will be correctly zero terminated.
2242 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2243 UInt32 strtab_offset = * (UInt32*)(name+4);
2244 return ((UChar*)strtab) + strtab_offset;
2246 /* Otherwise, if shorter than 8 bytes, return the original,
2247 which by defn is correctly terminated.
2249 if (name[7]==0) return name;
2250 /* The annoying case: 8 bytes. Copy into a temporary
2251 (which is never freed ...)
2253 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
2255 strncpy((char*)newstr,(char*)name,8);
2261 /* Just compares the short names (first 8 chars) */
2262 static COFF_section *
2263 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
2267 = (COFF_header*)(oc->image);
2268 COFF_section* sectab
2270 ((UChar*)(oc->image))
2271 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2273 for (i = 0; i < hdr->NumberOfSections; i++) {
2276 COFF_section* section_i
2278 myindex ( sizeof_COFF_section, sectab, i );
2279 n1 = (UChar*) &(section_i->Name);
2281 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2282 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2283 n1[6]==n2[6] && n1[7]==n2[7])
2292 zapTrailingAtSign ( UChar* sym )
2294 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2296 if (sym[0] == 0) return;
2298 while (sym[i] != 0) i++;
2301 while (j > 0 && my_isdigit(sym[j])) j--;
2302 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2307 lookupSymbolInDLLs ( UChar *lbl )
2312 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2313 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2315 if (lbl[0] == '_') {
2316 /* HACK: if the name has an initial underscore, try stripping
2317 it off & look that up first. I've yet to verify whether there's
2318 a Rule that governs whether an initial '_' *should always* be
2319 stripped off when mapping from import lib name to the DLL name.
2321 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
2323 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2327 sym = GetProcAddress(o_dll->instance, (char*)lbl);
2329 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2338 ocVerifyImage_PEi386 ( ObjectCode* oc )
2343 COFF_section* sectab;
2344 COFF_symbol* symtab;
2346 /* debugBelch("\nLOADING %s\n", oc->fileName); */
2347 hdr = (COFF_header*)(oc->image);
2348 sectab = (COFF_section*) (
2349 ((UChar*)(oc->image))
2350 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2352 symtab = (COFF_symbol*) (
2353 ((UChar*)(oc->image))
2354 + hdr->PointerToSymbolTable
2356 strtab = ((UChar*)symtab)
2357 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2359 if (hdr->Machine != 0x14c) {
2360 errorBelch("%s: Not x86 PEi386", oc->fileName);
2363 if (hdr->SizeOfOptionalHeader != 0) {
2364 errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2367 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2368 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2369 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2370 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2371 errorBelch("%s: Not a PEi386 object file", oc->fileName);
2374 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2375 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2376 errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2378 (int)(hdr->Characteristics));
2381 /* If the string table size is way crazy, this might indicate that
2382 there are more than 64k relocations, despite claims to the
2383 contrary. Hence this test. */
2384 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2386 if ( (*(UInt32*)strtab) > 600000 ) {
2387 /* Note that 600k has no special significance other than being
2388 big enough to handle the almost-2MB-sized lumps that
2389 constitute HSwin32*.o. */
2390 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2395 /* No further verification after this point; only debug printing. */
2397 IF_DEBUG(linker, i=1);
2398 if (i == 0) return 1;
2400 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2401 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2402 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2405 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
2406 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
2407 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2408 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
2409 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
2410 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
2411 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
2413 /* Print the section table. */
2415 for (i = 0; i < hdr->NumberOfSections; i++) {
2417 COFF_section* sectab_i
2419 myindex ( sizeof_COFF_section, sectab, i );
2426 printName ( sectab_i->Name, strtab );
2436 sectab_i->VirtualSize,
2437 sectab_i->VirtualAddress,
2438 sectab_i->SizeOfRawData,
2439 sectab_i->PointerToRawData,
2440 sectab_i->NumberOfRelocations,
2441 sectab_i->PointerToRelocations,
2442 sectab_i->PointerToRawData
2444 reltab = (COFF_reloc*) (
2445 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2448 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2449 /* If the relocation field (a short) has overflowed, the
2450 * real count can be found in the first reloc entry.
2452 * See Section 4.1 (last para) of the PE spec (rev6.0).
2454 COFF_reloc* rel = (COFF_reloc*)
2455 myindex ( sizeof_COFF_reloc, reltab, 0 );
2456 noRelocs = rel->VirtualAddress;
2459 noRelocs = sectab_i->NumberOfRelocations;
2463 for (; j < noRelocs; j++) {
2465 COFF_reloc* rel = (COFF_reloc*)
2466 myindex ( sizeof_COFF_reloc, reltab, j );
2468 " type 0x%-4x vaddr 0x%-8x name `",
2470 rel->VirtualAddress );
2471 sym = (COFF_symbol*)
2472 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
2473 /* Hmm..mysterious looking offset - what's it for? SOF */
2474 printName ( sym->Name, strtab -10 );
2481 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
2482 debugBelch("---START of string table---\n");
2483 for (i = 4; i < *(Int32*)strtab; i++) {
2485 debugBelch("\n"); else
2486 debugBelch("%c", strtab[i] );
2488 debugBelch("--- END of string table---\n");
2493 COFF_symbol* symtab_i;
2494 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2495 symtab_i = (COFF_symbol*)
2496 myindex ( sizeof_COFF_symbol, symtab, i );
2502 printName ( symtab_i->Name, strtab );
2511 (Int32)(symtab_i->SectionNumber),
2512 (UInt32)symtab_i->Type,
2513 (UInt32)symtab_i->StorageClass,
2514 (UInt32)symtab_i->NumberOfAuxSymbols
2516 i += symtab_i->NumberOfAuxSymbols;
2526 ocGetNames_PEi386 ( ObjectCode* oc )
2529 COFF_section* sectab;
2530 COFF_symbol* symtab;
2537 hdr = (COFF_header*)(oc->image);
2538 sectab = (COFF_section*) (
2539 ((UChar*)(oc->image))
2540 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2542 symtab = (COFF_symbol*) (
2543 ((UChar*)(oc->image))
2544 + hdr->PointerToSymbolTable
2546 strtab = ((UChar*)(oc->image))
2547 + hdr->PointerToSymbolTable
2548 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2550 /* Allocate space for any (local, anonymous) .bss sections. */
2552 for (i = 0; i < hdr->NumberOfSections; i++) {
2555 COFF_section* sectab_i
2557 myindex ( sizeof_COFF_section, sectab, i );
2558 if (0 != strcmp((char*)sectab_i->Name, ".bss")) continue;
2559 /* sof 10/05: the PE spec text isn't too clear regarding what
2560 * the SizeOfRawData field is supposed to hold for object
2561 * file sections containing just uninitialized data -- for executables,
2562 * it is supposed to be zero; unclear what it's supposed to be
2563 * for object files. However, VirtualSize is guaranteed to be
2564 * zero for object files, which definitely suggests that SizeOfRawData
2565 * will be non-zero (where else would the size of this .bss section be
2566 * stored?) Looking at the COFF_section info for incoming object files,
2567 * this certainly appears to be the case.
2569 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
2570 * object files up until now. This turned out to bite us with ghc-6.4.1's use
2571 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
2572 * variable decls into to the .bss section. (The specific function in Q which
2573 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
2575 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
2576 /* This is a non-empty .bss section. Allocate zeroed space for
2577 it, and set its PointerToRawData field such that oc->image +
2578 PointerToRawData == addr_of_zeroed_space. */
2579 bss_sz = sectab_i->VirtualSize;
2580 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
2581 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
2582 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
2583 addProddableBlock(oc, zspace, bss_sz);
2584 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
2587 /* Copy section information into the ObjectCode. */
2589 for (i = 0; i < hdr->NumberOfSections; i++) {
2595 = SECTIONKIND_OTHER;
2596 COFF_section* sectab_i
2598 myindex ( sizeof_COFF_section, sectab, i );
2599 IF_DEBUG(linker, debugBelch("section name = %s\n", sectab_i->Name ));
2602 /* I'm sure this is the Right Way to do it. However, the
2603 alternative of testing the sectab_i->Name field seems to
2604 work ok with Cygwin.
2606 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
2607 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
2608 kind = SECTIONKIND_CODE_OR_RODATA;
2611 if (0==strcmp(".text",(char*)sectab_i->Name) ||
2612 0==strcmp(".rdata",(char*)sectab_i->Name)||
2613 0==strcmp(".rodata",(char*)sectab_i->Name))
2614 kind = SECTIONKIND_CODE_OR_RODATA;
2615 if (0==strcmp(".data",(char*)sectab_i->Name) ||
2616 0==strcmp(".bss",(char*)sectab_i->Name))
2617 kind = SECTIONKIND_RWDATA;
2619 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
2620 sz = sectab_i->SizeOfRawData;
2621 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
2623 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
2624 end = start + sz - 1;
2626 if (kind == SECTIONKIND_OTHER
2627 /* Ignore sections called which contain stabs debugging
2629 && 0 != strcmp(".stab", (char*)sectab_i->Name)
2630 && 0 != strcmp(".stabstr", (char*)sectab_i->Name)
2631 /* ignore constructor section for now */
2632 && 0 != strcmp(".ctors", (char*)sectab_i->Name)
2633 /* ignore section generated from .ident */
2634 && 0!= strcmp("/4", (char*)sectab_i->Name)
2635 /* ignore unknown section that appeared in gcc 3.4.5(?) */
2636 && 0!= strcmp(".reloc", (char*)sectab_i->Name)
2638 errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", sectab_i->Name, oc->fileName);
2642 if (kind != SECTIONKIND_OTHER && end >= start) {
2643 addSection(oc, kind, start, end);
2644 addProddableBlock(oc, start, end - start + 1);
2648 /* Copy exported symbols into the ObjectCode. */
2650 oc->n_symbols = hdr->NumberOfSymbols;
2651 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2652 "ocGetNames_PEi386(oc->symbols)");
2653 /* Call me paranoid; I don't care. */
2654 for (i = 0; i < oc->n_symbols; i++)
2655 oc->symbols[i] = NULL;
2659 COFF_symbol* symtab_i;
2660 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2661 symtab_i = (COFF_symbol*)
2662 myindex ( sizeof_COFF_symbol, symtab, i );
2666 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
2667 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
2668 /* This symbol is global and defined, viz, exported */
2669 /* for MYIMAGE_SYMCLASS_EXTERNAL
2670 && !MYIMAGE_SYM_UNDEFINED,
2671 the address of the symbol is:
2672 address of relevant section + offset in section
2674 COFF_section* sectabent
2675 = (COFF_section*) myindex ( sizeof_COFF_section,
2677 symtab_i->SectionNumber-1 );
2678 addr = ((UChar*)(oc->image))
2679 + (sectabent->PointerToRawData
2683 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
2684 && symtab_i->Value > 0) {
2685 /* This symbol isn't in any section at all, ie, global bss.
2686 Allocate zeroed space for it. */
2687 addr = stgCallocBytes(1, symtab_i->Value,
2688 "ocGetNames_PEi386(non-anonymous bss)");
2689 addSection(oc, SECTIONKIND_RWDATA, addr,
2690 ((UChar*)addr) + symtab_i->Value - 1);
2691 addProddableBlock(oc, addr, symtab_i->Value);
2692 /* debugBelch("BSS section at 0x%x\n", addr); */
2695 if (addr != NULL ) {
2696 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
2697 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
2698 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
2699 ASSERT(i >= 0 && i < oc->n_symbols);
2700 /* cstring_from_COFF_symbol_name always succeeds. */
2701 oc->symbols[i] = (char*)sname;
2702 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
2706 "IGNORING symbol %d\n"
2710 printName ( symtab_i->Name, strtab );
2719 (Int32)(symtab_i->SectionNumber),
2720 (UInt32)symtab_i->Type,
2721 (UInt32)symtab_i->StorageClass,
2722 (UInt32)symtab_i->NumberOfAuxSymbols
2727 i += symtab_i->NumberOfAuxSymbols;
2736 ocResolve_PEi386 ( ObjectCode* oc )
2739 COFF_section* sectab;
2740 COFF_symbol* symtab;
2750 /* ToDo: should be variable-sized? But is at least safe in the
2751 sense of buffer-overrun-proof. */
2753 /* debugBelch("resolving for %s\n", oc->fileName); */
2755 hdr = (COFF_header*)(oc->image);
2756 sectab = (COFF_section*) (
2757 ((UChar*)(oc->image))
2758 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2760 symtab = (COFF_symbol*) (
2761 ((UChar*)(oc->image))
2762 + hdr->PointerToSymbolTable
2764 strtab = ((UChar*)(oc->image))
2765 + hdr->PointerToSymbolTable
2766 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2768 for (i = 0; i < hdr->NumberOfSections; i++) {
2769 COFF_section* sectab_i
2771 myindex ( sizeof_COFF_section, sectab, i );
2774 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2777 /* Ignore sections called which contain stabs debugging
2779 if (0 == strcmp(".stab", (char*)sectab_i->Name)
2780 || 0 == strcmp(".stabstr", (char*)sectab_i->Name)
2781 || 0 == strcmp(".ctors", (char*)sectab_i->Name))
2784 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2785 /* If the relocation field (a short) has overflowed, the
2786 * real count can be found in the first reloc entry.
2788 * See Section 4.1 (last para) of the PE spec (rev6.0).
2790 * Nov2003 update: the GNU linker still doesn't correctly
2791 * handle the generation of relocatable object files with
2792 * overflown relocations. Hence the output to warn of potential
2795 COFF_reloc* rel = (COFF_reloc*)
2796 myindex ( sizeof_COFF_reloc, reltab, 0 );
2797 noRelocs = rel->VirtualAddress;
2799 /* 10/05: we now assume (and check for) a GNU ld that is capable
2800 * of handling object files with (>2^16) of relocs.
2803 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
2808 noRelocs = sectab_i->NumberOfRelocations;
2813 for (; j < noRelocs; j++) {
2815 COFF_reloc* reltab_j
2817 myindex ( sizeof_COFF_reloc, reltab, j );
2819 /* the location to patch */
2821 ((UChar*)(oc->image))
2822 + (sectab_i->PointerToRawData
2823 + reltab_j->VirtualAddress
2824 - sectab_i->VirtualAddress )
2826 /* the existing contents of pP */
2828 /* the symbol to connect to */
2829 sym = (COFF_symbol*)
2830 myindex ( sizeof_COFF_symbol,
2831 symtab, reltab_j->SymbolTableIndex );
2834 "reloc sec %2d num %3d: type 0x%-4x "
2835 "vaddr 0x%-8x name `",
2837 (UInt32)reltab_j->Type,
2838 reltab_j->VirtualAddress );
2839 printName ( sym->Name, strtab );
2840 debugBelch("'\n" ));
2842 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
2843 COFF_section* section_sym
2844 = findPEi386SectionCalled ( oc, sym->Name );
2846 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
2849 S = ((UInt32)(oc->image))
2850 + (section_sym->PointerToRawData
2853 copyName ( sym->Name, strtab, symbol, 1000-1 );
2854 S = (UInt32) lookupSymbol( (char*)symbol );
2855 if ((void*)S != NULL) goto foundit;
2856 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
2860 checkProddableBlock(oc, pP);
2861 switch (reltab_j->Type) {
2862 case MYIMAGE_REL_I386_DIR32:
2865 case MYIMAGE_REL_I386_REL32:
2866 /* Tricky. We have to insert a displacement at
2867 pP which, when added to the PC for the _next_
2868 insn, gives the address of the target (S).
2869 Problem is to know the address of the next insn
2870 when we only know pP. We assume that this
2871 literal field is always the last in the insn,
2872 so that the address of the next insn is pP+4
2873 -- hence the constant 4.
2874 Also I don't know if A should be added, but so
2875 far it has always been zero.
2877 SOF 05/2005: 'A' (old contents of *pP) have been observed
2878 to contain values other than zero (the 'wx' object file
2879 that came with wxhaskell-0.9.4; dunno how it was compiled..).
2880 So, add displacement to old value instead of asserting
2881 A to be zero. Fixes wxhaskell-related crashes, and no other
2882 ill effects have been observed.
2884 Update: the reason why we're seeing these more elaborate
2885 relocations is due to a switch in how the NCG compiles SRTs
2886 and offsets to them from info tables. SRTs live in .(ro)data,
2887 while info tables live in .text, causing GAS to emit REL32/DISP32
2888 relocations with non-zero values. Adding the displacement is
2889 the right thing to do.
2891 *pP = S - ((UInt32)pP) - 4 + A;
2894 debugBelch("%s: unhandled PEi386 relocation type %d",
2895 oc->fileName, reltab_j->Type);
2902 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
2906 #endif /* defined(OBJFORMAT_PEi386) */
2909 /* --------------------------------------------------------------------------
2911 * ------------------------------------------------------------------------*/
2913 #if defined(OBJFORMAT_ELF)
2918 #if defined(sparc_HOST_ARCH)
2919 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
2920 #elif defined(i386_HOST_ARCH)
2921 # define ELF_TARGET_386 /* Used inside <elf.h> */
2922 #elif defined(x86_64_HOST_ARCH)
2923 # define ELF_TARGET_X64_64
2927 #if !defined(openbsd_HOST_OS)
2930 /* openbsd elf has things in different places, with diff names */
2931 # include <elf_abi.h>
2932 # include <machine/reloc.h>
2933 # define R_386_32 RELOC_32
2934 # define R_386_PC32 RELOC_PC32
2937 /* If elf.h doesn't define it */
2938 # ifndef R_X86_64_PC64
2939 # define R_X86_64_PC64 24
2943 * Define a set of types which can be used for both ELF32 and ELF64
2947 #define ELFCLASS ELFCLASS64
2948 #define Elf_Addr Elf64_Addr
2949 #define Elf_Word Elf64_Word
2950 #define Elf_Sword Elf64_Sword
2951 #define Elf_Ehdr Elf64_Ehdr
2952 #define Elf_Phdr Elf64_Phdr
2953 #define Elf_Shdr Elf64_Shdr
2954 #define Elf_Sym Elf64_Sym
2955 #define Elf_Rel Elf64_Rel
2956 #define Elf_Rela Elf64_Rela
2958 #define ELF_ST_TYPE ELF64_ST_TYPE
2961 #define ELF_ST_BIND ELF64_ST_BIND
2964 #define ELF_R_TYPE ELF64_R_TYPE
2967 #define ELF_R_SYM ELF64_R_SYM
2970 #define ELFCLASS ELFCLASS32
2971 #define Elf_Addr Elf32_Addr
2972 #define Elf_Word Elf32_Word
2973 #define Elf_Sword Elf32_Sword
2974 #define Elf_Ehdr Elf32_Ehdr
2975 #define Elf_Phdr Elf32_Phdr
2976 #define Elf_Shdr Elf32_Shdr
2977 #define Elf_Sym Elf32_Sym
2978 #define Elf_Rel Elf32_Rel
2979 #define Elf_Rela Elf32_Rela
2981 #define ELF_ST_TYPE ELF32_ST_TYPE
2984 #define ELF_ST_BIND ELF32_ST_BIND
2987 #define ELF_R_TYPE ELF32_R_TYPE
2990 #define ELF_R_SYM ELF32_R_SYM
2996 * Functions to allocate entries in dynamic sections. Currently we simply
2997 * preallocate a large number, and we don't check if a entry for the given
2998 * target already exists (a linear search is too slow). Ideally these
2999 * entries would be associated with symbols.
3002 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
3003 #define GOT_SIZE 0x20000
3004 #define FUNCTION_TABLE_SIZE 0x10000
3005 #define PLT_SIZE 0x08000
3008 static Elf_Addr got[GOT_SIZE];
3009 static unsigned int gotIndex;
3010 static Elf_Addr gp_val = (Elf_Addr)got;
3013 allocateGOTEntry(Elf_Addr target)
3017 if (gotIndex >= GOT_SIZE)
3018 barf("Global offset table overflow");
3020 entry = &got[gotIndex++];
3022 return (Elf_Addr)entry;
3026 #ifdef ELF_FUNCTION_DESC
3032 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
3033 static unsigned int functionTableIndex;
3036 allocateFunctionDesc(Elf_Addr target)
3038 FunctionDesc *entry;
3040 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
3041 barf("Function table overflow");
3043 entry = &functionTable[functionTableIndex++];
3045 entry->gp = (Elf_Addr)gp_val;
3046 return (Elf_Addr)entry;
3050 copyFunctionDesc(Elf_Addr target)
3052 FunctionDesc *olddesc = (FunctionDesc *)target;
3053 FunctionDesc *newdesc;
3055 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
3056 newdesc->gp = olddesc->gp;
3057 return (Elf_Addr)newdesc;
3064 unsigned char code[sizeof(plt_code)];
3068 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
3070 PLTEntry *plt = (PLTEntry *)oc->plt;
3073 if (oc->pltIndex >= PLT_SIZE)
3074 barf("Procedure table overflow");
3076 entry = &plt[oc->pltIndex++];
3077 memcpy(entry->code, plt_code, sizeof(entry->code));
3078 PLT_RELOC(entry->code, target);
3079 return (Elf_Addr)entry;
3085 return (PLT_SIZE * sizeof(PLTEntry));
3091 * Generic ELF functions
3095 findElfSection ( void* objImage, Elf_Word sh_type )
3097 char* ehdrC = (char*)objImage;
3098 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3099 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
3100 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3104 for (i = 0; i < ehdr->e_shnum; i++) {
3105 if (shdr[i].sh_type == sh_type
3106 /* Ignore the section header's string table. */
3107 && i != ehdr->e_shstrndx
3108 /* Ignore string tables named .stabstr, as they contain
3110 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3112 ptr = ehdrC + shdr[i].sh_offset;
3120 ocVerifyImage_ELF ( ObjectCode* oc )
3124 int i, j, nent, nstrtab, nsymtabs;
3128 char* ehdrC = (char*)(oc->image);
3129 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3131 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
3132 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
3133 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
3134 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
3135 errorBelch("%s: not an ELF object", oc->fileName);
3139 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
3140 errorBelch("%s: unsupported ELF format", oc->fileName);
3144 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
3145 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
3147 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
3148 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
3150 errorBelch("%s: unknown endiannness", oc->fileName);
3154 if (ehdr->e_type != ET_REL) {
3155 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
3158 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
3160 IF_DEBUG(linker,debugBelch( "Architecture is " ));
3161 switch (ehdr->e_machine) {
3162 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
3163 #ifdef EM_SPARC32PLUS
3164 case EM_SPARC32PLUS:
3166 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
3168 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
3170 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
3172 case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
3173 #elif defined(EM_AMD64)
3174 case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
3176 default: IF_DEBUG(linker,debugBelch( "unknown" ));
3177 errorBelch("%s: unknown architecture (e_machine == %d)"
3178 , oc->fileName, ehdr->e_machine);
3182 IF_DEBUG(linker,debugBelch(
3183 "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
3184 (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
3186 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
3188 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3190 if (ehdr->e_shstrndx == SHN_UNDEF) {
3191 errorBelch("%s: no section header string table", oc->fileName);
3194 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
3196 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3199 for (i = 0; i < ehdr->e_shnum; i++) {
3200 IF_DEBUG(linker,debugBelch("%2d: ", i ));
3201 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
3202 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
3203 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
3204 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
3205 ehdrC + shdr[i].sh_offset,
3206 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
3208 if (shdr[i].sh_type == SHT_REL) {
3209 IF_DEBUG(linker,debugBelch("Rel " ));
3210 } else if (shdr[i].sh_type == SHT_RELA) {
3211 IF_DEBUG(linker,debugBelch("RelA " ));
3213 IF_DEBUG(linker,debugBelch(" "));
3216 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
3220 IF_DEBUG(linker,debugBelch( "\nString tables" ));
3223 for (i = 0; i < ehdr->e_shnum; i++) {
3224 if (shdr[i].sh_type == SHT_STRTAB
3225 /* Ignore the section header's string table. */
3226 && i != ehdr->e_shstrndx
3227 /* Ignore string tables named .stabstr, as they contain
3229 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3231 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
3232 strtab = ehdrC + shdr[i].sh_offset;
3237 errorBelch("%s: no string tables, or too many", oc->fileName);
3242 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
3243 for (i = 0; i < ehdr->e_shnum; i++) {
3244 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3245 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
3247 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3248 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3249 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%ld rem)\n",
3251 (long)shdr[i].sh_size % sizeof(Elf_Sym)
3253 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
3254 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
3257 for (j = 0; j < nent; j++) {
3258 IF_DEBUG(linker,debugBelch(" %2d ", j ));
3259 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
3260 (int)stab[j].st_shndx,
3261 (int)stab[j].st_size,
3262 (char*)stab[j].st_value ));
3264 IF_DEBUG(linker,debugBelch("type=" ));
3265 switch (ELF_ST_TYPE(stab[j].st_info)) {
3266 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
3267 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
3268 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
3269 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
3270 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
3271 default: IF_DEBUG(linker,debugBelch("? " )); break;
3273 IF_DEBUG(linker,debugBelch(" " ));
3275 IF_DEBUG(linker,debugBelch("bind=" ));
3276 switch (ELF_ST_BIND(stab[j].st_info)) {
3277 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
3278 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
3279 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
3280 default: IF_DEBUG(linker,debugBelch("? " )); break;
3282 IF_DEBUG(linker,debugBelch(" " ));
3284 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3288 if (nsymtabs == 0) {
3289 errorBelch("%s: didn't find any symbol tables", oc->fileName);
3296 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3300 if (hdr->sh_type == SHT_PROGBITS
3301 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3302 /* .text-style section */
3303 return SECTIONKIND_CODE_OR_RODATA;
3306 if (hdr->sh_type == SHT_PROGBITS
3307 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3308 /* .data-style section */
3309 return SECTIONKIND_RWDATA;
3312 if (hdr->sh_type == SHT_PROGBITS
3313 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3314 /* .rodata-style section */
3315 return SECTIONKIND_CODE_OR_RODATA;
3318 if (hdr->sh_type == SHT_NOBITS
3319 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3320 /* .bss-style section */
3322 return SECTIONKIND_RWDATA;
3325 return SECTIONKIND_OTHER;
3330 ocGetNames_ELF ( ObjectCode* oc )
3335 char* ehdrC = (char*)(oc->image);
3336 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3337 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
3338 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3340 ASSERT(symhash != NULL);
3343 errorBelch("%s: no strtab", oc->fileName);
3348 for (i = 0; i < ehdr->e_shnum; i++) {
3349 /* Figure out what kind of section it is. Logic derived from
3350 Figure 1.14 ("Special Sections") of the ELF document
3351 ("Portable Formats Specification, Version 1.1"). */
3353 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
3355 if (is_bss && shdr[i].sh_size > 0) {
3356 /* This is a non-empty .bss section. Allocate zeroed space for
3357 it, and set its .sh_offset field such that
3358 ehdrC + .sh_offset == addr_of_zeroed_space. */
3359 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3360 "ocGetNames_ELF(BSS)");
3361 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3363 debugBelch("BSS section at 0x%x, size %d\n",
3364 zspace, shdr[i].sh_size);
3368 /* fill in the section info */
3369 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3370 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3371 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3372 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3375 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3377 /* copy stuff into this module's object symbol table */
3378 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3379 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3381 oc->n_symbols = nent;
3382 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3383 "ocGetNames_ELF(oc->symbols)");
3385 for (j = 0; j < nent; j++) {
3387 char isLocal = FALSE; /* avoids uninit-var warning */
3389 char* nm = strtab + stab[j].st_name;
3390 int secno = stab[j].st_shndx;
3392 /* Figure out if we want to add it; if so, set ad to its
3393 address. Otherwise leave ad == NULL. */
3395 if (secno == SHN_COMMON) {
3397 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3399 debugBelch("COMMON symbol, size %d name %s\n",
3400 stab[j].st_size, nm);
3402 /* Pointless to do addProddableBlock() for this area,
3403 since the linker should never poke around in it. */
3406 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3407 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3409 /* and not an undefined symbol */
3410 && stab[j].st_shndx != SHN_UNDEF
3411 /* and not in a "special section" */
3412 && stab[j].st_shndx < SHN_LORESERVE
3414 /* and it's a not a section or string table or anything silly */
3415 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
3416 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
3417 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
3420 /* Section 0 is the undefined section, hence > and not >=. */
3421 ASSERT(secno > 0 && secno < ehdr->e_shnum);
3423 if (shdr[secno].sh_type == SHT_NOBITS) {
3424 debugBelch(" BSS symbol, size %d off %d name %s\n",
3425 stab[j].st_size, stab[j].st_value, nm);
3428 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
3429 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
3432 #ifdef ELF_FUNCTION_DESC
3433 /* dlsym() and the initialisation table both give us function
3434 * descriptors, so to be consistent we store function descriptors
3435 * in the symbol table */
3436 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
3437 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
3439 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s\n",
3440 ad, oc->fileName, nm ));
3445 /* And the decision is ... */
3449 oc->symbols[j] = nm;
3452 /* Ignore entirely. */
3454 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
3458 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
3459 strtab + stab[j].st_name ));
3462 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
3463 (int)ELF_ST_BIND(stab[j].st_info),
3464 (int)ELF_ST_TYPE(stab[j].st_info),
3465 (int)stab[j].st_shndx,
3466 strtab + stab[j].st_name
3469 oc->symbols[j] = NULL;
3478 /* Do ELF relocations which lack an explicit addend. All x86-linux
3479 relocations appear to be of this form. */
3481 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
3482 Elf_Shdr* shdr, int shnum,
3483 Elf_Sym* stab, char* strtab )
3488 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
3489 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
3490 int target_shndx = shdr[shnum].sh_info;
3491 int symtab_shndx = shdr[shnum].sh_link;
3493 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3494 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
3495 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3496 target_shndx, symtab_shndx ));
3498 /* Skip sections that we're not interested in. */
3501 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
3502 if (kind == SECTIONKIND_OTHER) {
3503 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
3508 for (j = 0; j < nent; j++) {
3509 Elf_Addr offset = rtab[j].r_offset;
3510 Elf_Addr info = rtab[j].r_info;
3512 Elf_Addr P = ((Elf_Addr)targ) + offset;
3513 Elf_Word* pP = (Elf_Word*)P;
3518 StgStablePtr stablePtr;
3521 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
3522 j, (void*)offset, (void*)info ));
3524 IF_DEBUG(linker,debugBelch( " ZERO" ));
3527 Elf_Sym sym = stab[ELF_R_SYM(info)];
3528 /* First see if it is a local symbol. */
3529 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3530 /* Yes, so we can get the address directly from the ELF symbol
3532 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3534 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3535 + stab[ELF_R_SYM(info)].st_value);
3538 symbol = strtab + sym.st_name;
3539 stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
3540 if (NULL == stablePtr) {
3541 /* No, so look up the name in our global table. */
3542 S_tmp = lookupSymbol( symbol );
3543 S = (Elf_Addr)S_tmp;
3545 stableVal = deRefStablePtr( stablePtr );
3547 S = (Elf_Addr)S_tmp;
3551 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3554 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
3557 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
3558 (void*)P, (void*)S, (void*)A ));
3559 checkProddableBlock ( oc, pP );
3563 switch (ELF_R_TYPE(info)) {
3564 # ifdef i386_HOST_ARCH
3565 case R_386_32: *pP = value; break;
3566 case R_386_PC32: *pP = value - P; break;
3569 errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
3570 oc->fileName, (lnat)ELF_R_TYPE(info));
3578 /* Do ELF relocations for which explicit addends are supplied.
3579 sparc-solaris relocations appear to be of this form. */
3581 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
3582 Elf_Shdr* shdr, int shnum,
3583 Elf_Sym* stab, char* strtab )
3586 char *symbol = NULL;
3588 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
3589 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
3590 int target_shndx = shdr[shnum].sh_info;
3591 int symtab_shndx = shdr[shnum].sh_link;
3593 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3594 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
3595 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3596 target_shndx, symtab_shndx ));
3598 for (j = 0; j < nent; j++) {
3599 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3600 /* This #ifdef only serves to avoid unused-var warnings. */
3601 Elf_Addr offset = rtab[j].r_offset;
3602 Elf_Addr P = targ + offset;
3604 Elf_Addr info = rtab[j].r_info;
3605 Elf_Addr A = rtab[j].r_addend;
3609 # if defined(sparc_HOST_ARCH)
3610 Elf_Word* pP = (Elf_Word*)P;
3612 # elif defined(powerpc_HOST_ARCH)
3616 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
3617 j, (void*)offset, (void*)info,
3620 IF_DEBUG(linker,debugBelch( " ZERO" ));
3623 Elf_Sym sym = stab[ELF_R_SYM(info)];
3624 /* First see if it is a local symbol. */
3625 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3626 /* Yes, so we can get the address directly from the ELF symbol
3628 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3630 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3631 + stab[ELF_R_SYM(info)].st_value);
3632 #ifdef ELF_FUNCTION_DESC
3633 /* Make a function descriptor for this function */
3634 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
3635 S = allocateFunctionDesc(S + A);
3640 /* No, so look up the name in our global table. */
3641 symbol = strtab + sym.st_name;
3642 S_tmp = lookupSymbol( symbol );
3643 S = (Elf_Addr)S_tmp;
3645 #ifdef ELF_FUNCTION_DESC
3646 /* If a function, already a function descriptor - we would
3647 have to copy it to add an offset. */
3648 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
3649 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
3653 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3656 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
3659 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
3660 (void*)P, (void*)S, (void*)A ));
3661 /* checkProddableBlock ( oc, (void*)P ); */
3665 switch (ELF_R_TYPE(info)) {
3666 # if defined(sparc_HOST_ARCH)
3667 case R_SPARC_WDISP30:
3668 w1 = *pP & 0xC0000000;
3669 w2 = (Elf_Word)((value - P) >> 2);
3670 ASSERT((w2 & 0xC0000000) == 0);
3675 w1 = *pP & 0xFFC00000;
3676 w2 = (Elf_Word)(value >> 10);
3677 ASSERT((w2 & 0xFFC00000) == 0);
3683 w2 = (Elf_Word)(value & 0x3FF);
3684 ASSERT((w2 & ~0x3FF) == 0);
3689 /* According to the Sun documentation:
3691 This relocation type resembles R_SPARC_32, except it refers to an
3692 unaligned word. That is, the word to be relocated must be treated
3693 as four separate bytes with arbitrary alignment, not as a word
3694 aligned according to the architecture requirements.
3697 w2 = (Elf_Word)value;
3699 // SPARC doesn't do misaligned writes of 32 bit words,
3700 // so we have to do this one byte-at-a-time.
3701 char *pPc = (char*)pP;
3702 pPc[0] = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
3703 pPc[1] = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
3704 pPc[2] = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
3705 pPc[3] = (char) ((Elf_Word)(w2 & 0x000000ff));
3709 w2 = (Elf_Word)value;
3712 # elif defined(powerpc_HOST_ARCH)
3713 case R_PPC_ADDR16_LO:
3714 *(Elf32_Half*) P = value;
3717 case R_PPC_ADDR16_HI:
3718 *(Elf32_Half*) P = value >> 16;
3721 case R_PPC_ADDR16_HA:
3722 *(Elf32_Half*) P = (value + 0x8000) >> 16;
3726 *(Elf32_Word *) P = value;
3730 *(Elf32_Word *) P = value - P;
3736 if( delta << 6 >> 6 != delta )
3738 value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
3742 if( value == 0 || delta << 6 >> 6 != delta )
3744 barf( "Unable to make SymbolExtra for #%d",
3750 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
3751 | (delta & 0x3fffffc);
3755 #if x86_64_HOST_ARCH
3757 *(Elf64_Xword *)P = value;
3762 StgInt64 off = value - P;
3763 if (off >= 0x7fffffffL || off < -0x80000000L) {
3764 #if X86_64_ELF_NONPIC_HACK
3765 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3767 off = pltAddress + A - P;
3769 barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3770 symbol, off, oc->fileName );
3773 *(Elf64_Word *)P = (Elf64_Word)off;
3779 StgInt64 off = value - P;
3780 *(Elf64_Word *)P = (Elf64_Word)off;
3785 if (value >= 0x7fffffffL) {
3786 #if X86_64_ELF_NONPIC_HACK
3787 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3789 value = pltAddress + A;
3791 barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3792 symbol, value, oc->fileName );
3795 *(Elf64_Word *)P = (Elf64_Word)value;
3799 if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
3800 #if X86_64_ELF_NONPIC_HACK
3801 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3803 value = pltAddress + A;
3805 barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3806 symbol, value, oc->fileName );
3809 *(Elf64_Sword *)P = (Elf64_Sword)value;
3812 case R_X86_64_GOTPCREL:
3814 StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
3815 StgInt64 off = gotAddress + A - P;
3816 *(Elf64_Word *)P = (Elf64_Word)off;
3820 case R_X86_64_PLT32:
3822 StgInt64 off = value - P;
3823 if (off >= 0x7fffffffL || off < -0x80000000L) {
3824 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3826 off = pltAddress + A - P;
3828 *(Elf64_Word *)P = (Elf64_Word)off;
3834 errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
3835 oc->fileName, (lnat)ELF_R_TYPE(info));
3844 ocResolve_ELF ( ObjectCode* oc )
3848 Elf_Sym* stab = NULL;
3849 char* ehdrC = (char*)(oc->image);
3850 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
3851 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3853 /* first find "the" symbol table */
3854 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
3856 /* also go find the string table */
3857 strtab = findElfSection ( ehdrC, SHT_STRTAB );
3859 if (stab == NULL || strtab == NULL) {
3860 errorBelch("%s: can't find string or symbol table", oc->fileName);
3864 /* Process the relocation sections. */
3865 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
3866 if (shdr[shnum].sh_type == SHT_REL) {
3867 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
3868 shnum, stab, strtab );
3872 if (shdr[shnum].sh_type == SHT_RELA) {
3873 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
3874 shnum, stab, strtab );
3879 #if defined(powerpc_HOST_ARCH)
3880 ocFlushInstructionCache( oc );
3887 * PowerPC & X86_64 ELF specifics
3890 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3892 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
3898 ehdr = (Elf_Ehdr *) oc->image;
3899 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
3901 for( i = 0; i < ehdr->e_shnum; i++ )
3902 if( shdr[i].sh_type == SHT_SYMTAB )
3905 if( i == ehdr->e_shnum )
3907 errorBelch( "This ELF file contains no symtab" );
3911 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
3913 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
3914 (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
3919 return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
3922 #endif /* powerpc */
3926 /* --------------------------------------------------------------------------
3928 * ------------------------------------------------------------------------*/
3930 #if defined(OBJFORMAT_MACHO)
3933 Support for MachO linking on Darwin/MacOS X
3934 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
3936 I hereby formally apologize for the hackish nature of this code.
3937 Things that need to be done:
3938 *) implement ocVerifyImage_MachO
3939 *) add still more sanity checks.
3942 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
3943 #define mach_header mach_header_64
3944 #define segment_command segment_command_64
3945 #define section section_64
3946 #define nlist nlist_64
3949 #ifdef powerpc_HOST_ARCH
3950 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
3952 struct mach_header *header = (struct mach_header *) oc->image;
3953 struct load_command *lc = (struct load_command *) (header + 1);
3956 for( i = 0; i < header->ncmds; i++ )
3958 if( lc->cmd == LC_SYMTAB )
3960 // Find out the first and last undefined external
3961 // symbol, so we don't have to allocate too many
3963 struct symtab_command *symLC = (struct symtab_command *) lc;
3964 unsigned min = symLC->nsyms, max = 0;
3965 struct nlist *nlist =
3966 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
3968 for(i=0;i<symLC->nsyms;i++)
3970 if(nlist[i].n_type & N_STAB)
3972 else if(nlist[i].n_type & N_EXT)
3974 if((nlist[i].n_type & N_TYPE) == N_UNDF
3975 && (nlist[i].n_value == 0))
3985 return ocAllocateSymbolExtras(oc, max - min + 1, min);
3990 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3992 return ocAllocateSymbolExtras(oc,0,0);
3995 #ifdef x86_64_HOST_ARCH
3996 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
3998 struct mach_header *header = (struct mach_header *) oc->image;
3999 struct load_command *lc = (struct load_command *) (header + 1);
4002 for( i = 0; i < header->ncmds; i++ )
4004 if( lc->cmd == LC_SYMTAB )
4006 // Just allocate one entry for every symbol
4007 struct symtab_command *symLC = (struct symtab_command *) lc;
4009 return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
4012 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4014 return ocAllocateSymbolExtras(oc,0,0);
4018 static int ocVerifyImage_MachO(ObjectCode* oc)
4020 char *image = (char*) oc->image;
4021 struct mach_header *header = (struct mach_header*) image;
4023 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
4024 if(header->magic != MH_MAGIC_64)
4027 if(header->magic != MH_MAGIC)
4030 // FIXME: do some more verifying here
4034 static int resolveImports(
4037 struct symtab_command *symLC,
4038 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
4039 unsigned long *indirectSyms,
4040 struct nlist *nlist)
4043 size_t itemSize = 4;
4046 int isJumpTable = 0;
4047 if(!strcmp(sect->sectname,"__jump_table"))
4051 ASSERT(sect->reserved2 == itemSize);
4055 for(i=0; i*itemSize < sect->size;i++)
4057 // according to otool, reserved1 contains the first index into the indirect symbol table
4058 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
4059 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4062 if((symbol->n_type & N_TYPE) == N_UNDF
4063 && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
4064 addr = (void*) (symbol->n_value);
4066 addr = lookupSymbol(nm);
4069 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
4077 checkProddableBlock(oc,image + sect->offset + i*itemSize);
4078 *(image + sect->offset + i*itemSize) = 0xe9; // jmp
4079 *(unsigned*)(image + sect->offset + i*itemSize + 1)
4080 = (char*)addr - (image + sect->offset + i*itemSize + 5);
4085 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
4086 ((void**)(image + sect->offset))[i] = addr;
4093 static unsigned long relocateAddress(
4096 struct section* sections,
4097 unsigned long address)
4100 for(i = 0; i < nSections; i++)
4102 if(sections[i].addr <= address
4103 && address < sections[i].addr + sections[i].size)
4105 return (unsigned long)oc->image
4106 + sections[i].offset + address - sections[i].addr;
4109 barf("Invalid Mach-O file:"
4110 "Address out of bounds while relocating object file");
4114 static int relocateSection(
4117 struct symtab_command *symLC, struct nlist *nlist,
4118 int nSections, struct section* sections, struct section *sect)
4120 struct relocation_info *relocs;
4123 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
4125 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
4127 else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
4129 else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
4133 relocs = (struct relocation_info*) (image + sect->reloff);
4137 #ifdef x86_64_HOST_ARCH
4138 struct relocation_info *reloc = &relocs[i];
4140 char *thingPtr = image + sect->offset + reloc->r_address;
4142 /* We shouldn't need to initialise this, but gcc on OS X 64 bit
4143 complains that it may be used uninitialized if we don't */
4146 int type = reloc->r_type;
4148 checkProddableBlock(oc,thingPtr);
4149 switch(reloc->r_length)
4152 thing = *(uint8_t*)thingPtr;
4153 baseValue = (uint64_t)thingPtr + 1;
4156 thing = *(uint16_t*)thingPtr;
4157 baseValue = (uint64_t)thingPtr + 2;
4160 thing = *(uint32_t*)thingPtr;
4161 baseValue = (uint64_t)thingPtr + 4;
4164 thing = *(uint64_t*)thingPtr;
4165 baseValue = (uint64_t)thingPtr + 8;
4168 barf("Unknown size.");
4171 if(type == X86_64_RELOC_GOT
4172 || type == X86_64_RELOC_GOT_LOAD)
4174 ASSERT(reloc->r_extern);
4175 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)->addr;
4177 type = X86_64_RELOC_SIGNED;
4179 else if(reloc->r_extern)
4181 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4182 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4183 if(symbol->n_value == 0)
4184 value = (uint64_t) lookupSymbol(nm);
4186 value = relocateAddress(oc, nSections, sections,
4191 value = sections[reloc->r_symbolnum-1].offset
4192 - sections[reloc->r_symbolnum-1].addr
4196 if(type == X86_64_RELOC_BRANCH)
4198 if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
4200 ASSERT(reloc->r_extern);
4201 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
4204 ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
4205 type = X86_64_RELOC_SIGNED;
4210 case X86_64_RELOC_UNSIGNED:
4211 ASSERT(!reloc->r_pcrel);
4214 case X86_64_RELOC_SIGNED:
4215 case X86_64_RELOC_SIGNED_1:
4216 case X86_64_RELOC_SIGNED_2:
4217 case X86_64_RELOC_SIGNED_4:
4218 ASSERT(reloc->r_pcrel);
4219 thing += value - baseValue;
4221 case X86_64_RELOC_SUBTRACTOR:
4222 ASSERT(!reloc->r_pcrel);
4226 barf("unkown relocation");
4229 switch(reloc->r_length)
4232 *(uint8_t*)thingPtr = thing;
4235 *(uint16_t*)thingPtr = thing;
4238 *(uint32_t*)thingPtr = thing;
4241 *(uint64_t*)thingPtr = thing;
4245 if(relocs[i].r_address & R_SCATTERED)
4247 struct scattered_relocation_info *scat =
4248 (struct scattered_relocation_info*) &relocs[i];
4252 if(scat->r_length == 2)
4254 unsigned long word = 0;
4255 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
4256 checkProddableBlock(oc,wordPtr);
4258 // Note on relocation types:
4259 // i386 uses the GENERIC_RELOC_* types,
4260 // while ppc uses special PPC_RELOC_* types.
4261 // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
4262 // in both cases, all others are different.
4263 // Therefore, we use GENERIC_RELOC_VANILLA
4264 // and GENERIC_RELOC_PAIR instead of the PPC variants,
4265 // and use #ifdefs for the other types.
4267 // Step 1: Figure out what the relocated value should be
4268 if(scat->r_type == GENERIC_RELOC_VANILLA)
4270 word = *wordPtr + (unsigned long) relocateAddress(
4277 #ifdef powerpc_HOST_ARCH
4278 else if(scat->r_type == PPC_RELOC_SECTDIFF
4279 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4280 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4281 || scat->r_type == PPC_RELOC_HA16_SECTDIFF
4282 || scat->r_type == PPC_RELOC_LOCAL_SECTDIFF)
4284 else if(scat->r_type == GENERIC_RELOC_SECTDIFF
4285 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4288 struct scattered_relocation_info *pair =
4289 (struct scattered_relocation_info*) &relocs[i+1];
4291 if(!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR)
4292 barf("Invalid Mach-O file: "
4293 "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4295 word = (unsigned long)
4296 (relocateAddress(oc, nSections, sections, scat->r_value)
4297 - relocateAddress(oc, nSections, sections, pair->r_value));
4300 #ifdef powerpc_HOST_ARCH
4301 else if(scat->r_type == PPC_RELOC_HI16
4302 || scat->r_type == PPC_RELOC_LO16
4303 || scat->r_type == PPC_RELOC_HA16
4304 || scat->r_type == PPC_RELOC_LO14)
4305 { // these are generated by label+offset things
4306 struct relocation_info *pair = &relocs[i+1];
4307 if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
4308 barf("Invalid Mach-O file: "
4309 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4311 if(scat->r_type == PPC_RELOC_LO16)
4313 word = ((unsigned short*) wordPtr)[1];
4314 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4316 else if(scat->r_type == PPC_RELOC_LO14)
4318 barf("Unsupported Relocation: PPC_RELOC_LO14");
4319 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4320 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4322 else if(scat->r_type == PPC_RELOC_HI16)
4324 word = ((unsigned short*) wordPtr)[1] << 16;
4325 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4327 else if(scat->r_type == PPC_RELOC_HA16)
4329 word = ((unsigned short*) wordPtr)[1] << 16;
4330 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4334 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
4342 barf ("Don't know how to handle this Mach-O "
4343 "scattered relocation entry: "
4344 "object file %s; entry type %ld; "
4346 oc->fileName, scat->r_type, scat->r_address);
4350 #ifdef powerpc_HOST_ARCH
4351 if(scat->r_type == GENERIC_RELOC_VANILLA
4352 || scat->r_type == PPC_RELOC_SECTDIFF)
4354 if(scat->r_type == GENERIC_RELOC_VANILLA
4355 || scat->r_type == GENERIC_RELOC_SECTDIFF
4356 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4361 #ifdef powerpc_HOST_ARCH
4362 else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
4364 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4366 else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
4368 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4370 else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
4372 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4373 + ((word & (1<<15)) ? 1 : 0);
4379 barf("Can't handle Mach-O scattered relocation entry "
4380 "with this r_length tag: "
4381 "object file %s; entry type %ld; "
4382 "r_length tag %ld; address %#lx\n",
4383 oc->fileName, scat->r_type, scat->r_length,
4388 else /* scat->r_pcrel */
4390 barf("Don't know how to handle *PC-relative* Mach-O "
4391 "scattered relocation entry: "
4392 "object file %s; entry type %ld; address %#lx\n",
4393 oc->fileName, scat->r_type, scat->r_address);
4398 else /* !(relocs[i].r_address & R_SCATTERED) */
4400 struct relocation_info *reloc = &relocs[i];
4401 if(reloc->r_pcrel && !reloc->r_extern)
4404 if(reloc->r_length == 2)
4406 unsigned long word = 0;
4407 #ifdef powerpc_HOST_ARCH
4408 unsigned long jumpIsland = 0;
4409 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
4410 // to avoid warning and to catch
4414 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
4415 checkProddableBlock(oc,wordPtr);
4417 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4421 #ifdef powerpc_HOST_ARCH
4422 else if(reloc->r_type == PPC_RELOC_LO16)
4424 word = ((unsigned short*) wordPtr)[1];
4425 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4427 else if(reloc->r_type == PPC_RELOC_HI16)
4429 word = ((unsigned short*) wordPtr)[1] << 16;
4430 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4432 else if(reloc->r_type == PPC_RELOC_HA16)
4434 word = ((unsigned short*) wordPtr)[1] << 16;
4435 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4437 else if(reloc->r_type == PPC_RELOC_BR24)
4440 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
4445 barf("Can't handle this Mach-O relocation entry "
4447 "object file %s; entry type %ld; address %#lx\n",
4448 oc->fileName, reloc->r_type, reloc->r_address);
4452 if(!reloc->r_extern)
4455 sections[reloc->r_symbolnum-1].offset
4456 - sections[reloc->r_symbolnum-1].addr
4463 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4464 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4465 void *symbolAddress = lookupSymbol(nm);
4468 errorBelch("\nunknown symbol `%s'", nm);
4474 #ifdef powerpc_HOST_ARCH
4475 // In the .o file, this should be a relative jump to NULL
4476 // and we'll change it to a relative jump to the symbol
4477 ASSERT(word + reloc->r_address == 0);
4478 jumpIsland = (unsigned long)
4479 &makeSymbolExtra(oc,
4481 (unsigned long) symbolAddress)
4485 offsetToJumpIsland = word + jumpIsland
4486 - (((long)image) + sect->offset - sect->addr);
4489 word += (unsigned long) symbolAddress
4490 - (((long)image) + sect->offset - sect->addr);
4494 word += (unsigned long) symbolAddress;
4498 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4503 #ifdef powerpc_HOST_ARCH
4504 else if(reloc->r_type == PPC_RELOC_LO16)
4506 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4509 else if(reloc->r_type == PPC_RELOC_HI16)
4511 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4514 else if(reloc->r_type == PPC_RELOC_HA16)
4516 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4517 + ((word & (1<<15)) ? 1 : 0);
4520 else if(reloc->r_type == PPC_RELOC_BR24)
4522 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4524 // The branch offset is too large.
4525 // Therefore, we try to use a jump island.
4528 barf("unconditional relative branch out of range: "
4529 "no jump island available");
4532 word = offsetToJumpIsland;
4533 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4534 barf("unconditional relative branch out of range: "
4535 "jump island out of range");
4537 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
4544 barf("Can't handle Mach-O relocation entry (not scattered) "
4545 "with this r_length tag: "
4546 "object file %s; entry type %ld; "
4547 "r_length tag %ld; address %#lx\n",
4548 oc->fileName, reloc->r_type, reloc->r_length,
4558 static int ocGetNames_MachO(ObjectCode* oc)
4560 char *image = (char*) oc->image;
4561 struct mach_header *header = (struct mach_header*) image;
4562 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4563 unsigned i,curSymbol = 0;
4564 struct segment_command *segLC = NULL;
4565 struct section *sections;
4566 struct symtab_command *symLC = NULL;
4567 struct nlist *nlist;
4568 unsigned long commonSize = 0;
4569 char *commonStorage = NULL;
4570 unsigned long commonCounter;
4572 for(i=0;i<header->ncmds;i++)
4574 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4575 segLC = (struct segment_command*) lc;
4576 else if(lc->cmd == LC_SYMTAB)
4577 symLC = (struct symtab_command*) lc;
4578 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4581 sections = (struct section*) (segLC+1);
4582 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4586 barf("ocGetNames_MachO: no segment load command");
4588 for(i=0;i<segLC->nsects;i++)
4590 if(sections[i].size == 0)
4593 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
4595 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
4596 "ocGetNames_MachO(common symbols)");
4597 sections[i].offset = zeroFillArea - image;
4600 if(!strcmp(sections[i].sectname,"__text"))
4601 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
4602 (void*) (image + sections[i].offset),
4603 (void*) (image + sections[i].offset + sections[i].size));
4604 else if(!strcmp(sections[i].sectname,"__const"))
4605 addSection(oc, SECTIONKIND_RWDATA,
4606 (void*) (image + sections[i].offset),
4607 (void*) (image + sections[i].offset + sections[i].size));
4608 else if(!strcmp(sections[i].sectname,"__data"))
4609 addSection(oc, SECTIONKIND_RWDATA,
4610 (void*) (image + sections[i].offset),
4611 (void*) (image + sections[i].offset + sections[i].size));
4612 else if(!strcmp(sections[i].sectname,"__bss")
4613 || !strcmp(sections[i].sectname,"__common"))
4614 addSection(oc, SECTIONKIND_RWDATA,
4615 (void*) (image + sections[i].offset),
4616 (void*) (image + sections[i].offset + sections[i].size));
4618 addProddableBlock(oc, (void*) (image + sections[i].offset),
4622 // count external symbols defined here
4626 for(i=0;i<symLC->nsyms;i++)
4628 if(nlist[i].n_type & N_STAB)
4630 else if(nlist[i].n_type & N_EXT)
4632 if((nlist[i].n_type & N_TYPE) == N_UNDF
4633 && (nlist[i].n_value != 0))
4635 commonSize += nlist[i].n_value;
4638 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4643 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
4644 "ocGetNames_MachO(oc->symbols)");
4648 for(i=0;i<symLC->nsyms;i++)
4650 if(nlist[i].n_type & N_STAB)
4652 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4654 if(nlist[i].n_type & N_EXT)
4656 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4657 if((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm))
4658 ; // weak definition, and we already have a definition
4661 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4663 + sections[nlist[i].n_sect-1].offset
4664 - sections[nlist[i].n_sect-1].addr
4665 + nlist[i].n_value);
4666 oc->symbols[curSymbol++] = nm;
4673 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
4674 commonCounter = (unsigned long)commonStorage;
4677 for(i=0;i<symLC->nsyms;i++)
4679 if((nlist[i].n_type & N_TYPE) == N_UNDF
4680 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
4682 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4683 unsigned long sz = nlist[i].n_value;
4685 nlist[i].n_value = commonCounter;
4687 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4688 (void*)commonCounter);
4689 oc->symbols[curSymbol++] = nm;
4691 commonCounter += sz;
4698 static int ocResolve_MachO(ObjectCode* oc)
4700 char *image = (char*) oc->image;
4701 struct mach_header *header = (struct mach_header*) image;
4702 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4704 struct segment_command *segLC = NULL;
4705 struct section *sections;
4706 struct symtab_command *symLC = NULL;
4707 struct dysymtab_command *dsymLC = NULL;
4708 struct nlist *nlist;
4710 for(i=0;i<header->ncmds;i++)
4712 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4713 segLC = (struct segment_command*) lc;
4714 else if(lc->cmd == LC_SYMTAB)
4715 symLC = (struct symtab_command*) lc;
4716 else if(lc->cmd == LC_DYSYMTAB)
4717 dsymLC = (struct dysymtab_command*) lc;
4718 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4721 sections = (struct section*) (segLC+1);
4722 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4727 unsigned long *indirectSyms
4728 = (unsigned long*) (image + dsymLC->indirectsymoff);
4730 for(i=0;i<segLC->nsects;i++)
4732 if( !strcmp(sections[i].sectname,"__la_symbol_ptr")
4733 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
4734 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
4736 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4739 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
4740 || !strcmp(sections[i].sectname,"__pointers"))
4742 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4745 else if(!strcmp(sections[i].sectname,"__jump_table"))
4747 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4753 for(i=0;i<segLC->nsects;i++)
4755 if(!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
4759 #if defined (powerpc_HOST_ARCH)
4760 ocFlushInstructionCache( oc );
4766 #ifdef powerpc_HOST_ARCH
4768 * The Mach-O object format uses leading underscores. But not everywhere.
4769 * There is a small number of runtime support functions defined in
4770 * libcc_dynamic.a whose name does not have a leading underscore.
4771 * As a consequence, we can't get their address from C code.
4772 * We have to use inline assembler just to take the address of a function.
4776 extern void* symbolsWithoutUnderscore[];
4778 static void machoInitSymbolsWithoutUnderscore()
4780 void **p = symbolsWithoutUnderscore;
4781 __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
4783 #undef SymI_NeedsProto
4784 #define SymI_NeedsProto(x) \
4785 __asm__ volatile(".long " # x);
4787 RTS_MACHO_NOUNDERLINE_SYMBOLS
4789 __asm__ volatile(".text");
4791 #undef SymI_NeedsProto
4792 #define SymI_NeedsProto(x) \
4793 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
4795 RTS_MACHO_NOUNDERLINE_SYMBOLS
4797 #undef SymI_NeedsProto
4803 * Figure out by how much to shift the entire Mach-O file in memory
4804 * when loading so that its single segment ends up 16-byte-aligned
4806 static int machoGetMisalignment( FILE * f )
4808 struct mach_header header;
4811 fread(&header, sizeof(header), 1, f);
4814 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
4815 if(header.magic != MH_MAGIC_64)
4818 if(header.magic != MH_MAGIC)
4822 misalignment = (header.sizeofcmds + sizeof(header))
4825 return misalignment ? (16 - misalignment) : 0;