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(ia64_HOST_ARCH) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
79 #if defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
87 #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)
88 # define OBJFORMAT_ELF
89 # include <regex.h> // regex is already used by dlopen() so this is OK
90 // to use here without requiring an additional lib
91 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
92 # define OBJFORMAT_PEi386
95 #elif defined(darwin_HOST_OS)
96 # define OBJFORMAT_MACHO
98 # include <mach-o/loader.h>
99 # include <mach-o/nlist.h>
100 # include <mach-o/reloc.h>
101 #if !defined(HAVE_DLFCN_H)
102 # include <mach-o/dyld.h>
104 #if defined(powerpc_HOST_ARCH)
105 # include <mach-o/ppc/reloc.h>
107 #if defined(x86_64_HOST_ARCH)
108 # include <mach-o/x86_64/reloc.h>
112 /* Hash table mapping symbol names to Symbol */
113 static /*Str*/HashTable *symhash;
115 /* Hash table mapping symbol names to StgStablePtr */
116 static /*Str*/HashTable *stablehash;
118 /* List of currently loaded objects */
119 ObjectCode *objects = NULL; /* initially empty */
121 #if defined(OBJFORMAT_ELF)
122 static int ocVerifyImage_ELF ( ObjectCode* oc );
123 static int ocGetNames_ELF ( ObjectCode* oc );
124 static int ocResolve_ELF ( ObjectCode* oc );
125 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
126 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
128 #elif defined(OBJFORMAT_PEi386)
129 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
130 static int ocGetNames_PEi386 ( ObjectCode* oc );
131 static int ocResolve_PEi386 ( ObjectCode* oc );
132 static void *lookupSymbolInDLLs ( unsigned char *lbl );
133 static void zapTrailingAtSign ( unsigned char *sym );
134 #elif defined(OBJFORMAT_MACHO)
135 static int ocVerifyImage_MachO ( ObjectCode* oc );
136 static int ocGetNames_MachO ( ObjectCode* oc );
137 static int ocResolve_MachO ( ObjectCode* oc );
140 static int machoGetMisalignment( FILE * );
142 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
143 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
145 #ifdef powerpc_HOST_ARCH
146 static void machoInitSymbolsWithoutUnderscore( void );
150 /* on x86_64 we have a problem with relocating symbol references in
151 * code that was compiled without -fPIC. By default, the small memory
152 * model is used, which assumes that symbol references can fit in a
153 * 32-bit slot. The system dynamic linker makes this work for
154 * references to shared libraries by either (a) allocating a jump
155 * table slot for code references, or (b) moving the symbol at load
156 * time (and copying its contents, if necessary) for data references.
158 * We unfortunately can't tell whether symbol references are to code
159 * or data. So for now we assume they are code (the vast majority
160 * are), and allocate jump-table slots. Unfortunately this will
161 * SILENTLY generate crashing code for data references. This hack is
162 * enabled by X86_64_ELF_NONPIC_HACK.
164 * One workaround is to use shared Haskell libraries. This is
165 * coming. Another workaround is to keep the static libraries but
166 * compile them with -fPIC, because that will generate PIC references
167 * to data which can be relocated. The PIC code is still too green to
168 * do this systematically, though.
171 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
173 * Naming Scheme for Symbol Macros
175 * SymI_*: symbol is internal to the RTS. It resides in an object
176 * file/library that is statically.
177 * SymE_*: symbol is external to the RTS library. It might be linked
180 * Sym*_HasProto : the symbol prototype is imported in an include file
181 * or defined explicitly
182 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
183 * default proto extern void sym(void);
185 #define X86_64_ELF_NONPIC_HACK 1
187 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
188 * small memory model on this architecture (see gcc docs,
191 * MAP_32BIT not available on OpenBSD/amd64
193 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
194 #define TRY_MAP_32BIT MAP_32BIT
196 #define TRY_MAP_32BIT 0
200 * Due to the small memory model (see above), on x86_64 we have to map
201 * all our non-PIC object files into the low 2Gb of the address space
202 * (why 2Gb and not 4Gb? Because all addresses must be reachable
203 * using a 32-bit signed PC-relative offset). On Linux we can do this
204 * using the MAP_32BIT flag to mmap(), however on other OSs
205 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
206 * can't do this. So on these systems, we have to pick a base address
207 * in the low 2Gb of the address space and try to allocate memory from
210 * We pick a default address based on the OS, but also make this
211 * configurable via an RTS flag (+RTS -xm)
213 #if defined(x86_64_HOST_ARCH)
215 #if defined(MAP_32BIT)
216 // Try to use MAP_32BIT
217 #define MMAP_32BIT_BASE_DEFAULT 0
220 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
223 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
226 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
227 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
228 #define MAP_ANONYMOUS MAP_ANON
231 /* -----------------------------------------------------------------------------
232 * Built-in symbols from the RTS
235 typedef struct _RtsSymbolVal {
240 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
241 SymI_HasProto(stg_mkWeakForeignEnvzh) \
242 SymI_HasProto(stg_makeStableNamezh) \
243 SymI_HasProto(stg_finalizzeWeakzh)
245 #if !defined (mingw32_HOST_OS)
246 #define RTS_POSIX_ONLY_SYMBOLS \
247 SymI_HasProto(__hscore_get_saved_termios) \
248 SymI_HasProto(__hscore_set_saved_termios) \
249 SymI_HasProto(shutdownHaskellAndSignal) \
250 SymI_HasProto(lockFile) \
251 SymI_HasProto(unlockFile) \
252 SymI_HasProto(signal_handlers) \
253 SymI_HasProto(stg_sig_install) \
254 SymI_NeedsProto(nocldstop)
257 #if defined (cygwin32_HOST_OS)
258 #define RTS_MINGW_ONLY_SYMBOLS /**/
259 /* Don't have the ability to read import libs / archives, so
260 * we have to stupidly list a lot of what libcygwin.a
263 #define RTS_CYGWIN_ONLY_SYMBOLS \
264 SymI_HasProto(regfree) \
265 SymI_HasProto(regexec) \
266 SymI_HasProto(regerror) \
267 SymI_HasProto(regcomp) \
268 SymI_HasProto(__errno) \
269 SymI_HasProto(access) \
270 SymI_HasProto(chmod) \
271 SymI_HasProto(chdir) \
272 SymI_HasProto(close) \
273 SymI_HasProto(creat) \
275 SymI_HasProto(dup2) \
276 SymI_HasProto(fstat) \
277 SymI_HasProto(fcntl) \
278 SymI_HasProto(getcwd) \
279 SymI_HasProto(getenv) \
280 SymI_HasProto(lseek) \
281 SymI_HasProto(open) \
282 SymI_HasProto(fpathconf) \
283 SymI_HasProto(pathconf) \
284 SymI_HasProto(stat) \
286 SymI_HasProto(tanh) \
287 SymI_HasProto(cosh) \
288 SymI_HasProto(sinh) \
289 SymI_HasProto(atan) \
290 SymI_HasProto(acos) \
291 SymI_HasProto(asin) \
297 SymI_HasProto(sqrt) \
298 SymI_HasProto(localtime_r) \
299 SymI_HasProto(gmtime_r) \
300 SymI_HasProto(mktime) \
301 SymI_NeedsProto(_imp___tzname) \
302 SymI_HasProto(gettimeofday) \
303 SymI_HasProto(timezone) \
304 SymI_HasProto(tcgetattr) \
305 SymI_HasProto(tcsetattr) \
306 SymI_HasProto(memcpy) \
307 SymI_HasProto(memmove) \
308 SymI_HasProto(realloc) \
309 SymI_HasProto(malloc) \
310 SymI_HasProto(free) \
311 SymI_HasProto(fork) \
312 SymI_HasProto(lstat) \
313 SymI_HasProto(isatty) \
314 SymI_HasProto(mkdir) \
315 SymI_HasProto(opendir) \
316 SymI_HasProto(readdir) \
317 SymI_HasProto(rewinddir) \
318 SymI_HasProto(closedir) \
319 SymI_HasProto(link) \
320 SymI_HasProto(mkfifo) \
321 SymI_HasProto(pipe) \
322 SymI_HasProto(read) \
323 SymI_HasProto(rename) \
324 SymI_HasProto(rmdir) \
325 SymI_HasProto(select) \
326 SymI_HasProto(system) \
327 SymI_HasProto(write) \
328 SymI_HasProto(strcmp) \
329 SymI_HasProto(strcpy) \
330 SymI_HasProto(strncpy) \
331 SymI_HasProto(strerror) \
332 SymI_HasProto(sigaddset) \
333 SymI_HasProto(sigemptyset) \
334 SymI_HasProto(sigprocmask) \
335 SymI_HasProto(umask) \
336 SymI_HasProto(uname) \
337 SymI_HasProto(unlink) \
338 SymI_HasProto(utime) \
339 SymI_HasProto(waitpid)
341 #elif !defined(mingw32_HOST_OS)
342 #define RTS_MINGW_ONLY_SYMBOLS /**/
343 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
344 #else /* defined(mingw32_HOST_OS) */
345 #define RTS_POSIX_ONLY_SYMBOLS /**/
346 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
348 /* Extra syms gen'ed by mingw-2's gcc-3.2: */
350 #define RTS_MINGW_EXTRA_SYMS \
351 SymI_NeedsProto(_imp____mb_cur_max) \
352 SymI_NeedsProto(_imp___pctype)
354 #define RTS_MINGW_EXTRA_SYMS
357 #if HAVE_GETTIMEOFDAY
358 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
360 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
363 #if HAVE___MINGW_VFPRINTF
364 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
366 #define RTS___MINGW_VFPRINTF_SYM /**/
369 /* These are statically linked from the mingw libraries into the ghc
370 executable, so we have to employ this hack. */
371 #define RTS_MINGW_ONLY_SYMBOLS \
372 SymI_HasProto(stg_asyncReadzh) \
373 SymI_HasProto(stg_asyncWritezh) \
374 SymI_HasProto(stg_asyncDoProczh) \
375 SymI_HasProto(memset) \
376 SymI_HasProto(inet_ntoa) \
377 SymI_HasProto(inet_addr) \
378 SymI_HasProto(htonl) \
379 SymI_HasProto(recvfrom) \
380 SymI_HasProto(listen) \
381 SymI_HasProto(bind) \
382 SymI_HasProto(shutdown) \
383 SymI_HasProto(connect) \
384 SymI_HasProto(htons) \
385 SymI_HasProto(ntohs) \
386 SymI_HasProto(getservbyname) \
387 SymI_HasProto(getservbyport) \
388 SymI_HasProto(getprotobynumber) \
389 SymI_HasProto(getprotobyname) \
390 SymI_HasProto(gethostbyname) \
391 SymI_HasProto(gethostbyaddr) \
392 SymI_HasProto(gethostname) \
393 SymI_HasProto(strcpy) \
394 SymI_HasProto(strncpy) \
395 SymI_HasProto(abort) \
396 SymI_NeedsProto(_alloca) \
397 SymI_HasProto(isxdigit) \
398 SymI_HasProto(isupper) \
399 SymI_HasProto(ispunct) \
400 SymI_HasProto(islower) \
401 SymI_HasProto(isspace) \
402 SymI_HasProto(isprint) \
403 SymI_HasProto(isdigit) \
404 SymI_HasProto(iscntrl) \
405 SymI_HasProto(isalpha) \
406 SymI_HasProto(isalnum) \
407 SymI_HasProto(isascii) \
408 RTS___MINGW_VFPRINTF_SYM \
409 SymI_HasProto(strcmp) \
410 SymI_HasProto(memmove) \
411 SymI_HasProto(realloc) \
412 SymI_HasProto(malloc) \
414 SymI_HasProto(tanh) \
415 SymI_HasProto(cosh) \
416 SymI_HasProto(sinh) \
417 SymI_HasProto(atan) \
418 SymI_HasProto(acos) \
419 SymI_HasProto(asin) \
425 SymI_HasProto(sqrt) \
426 SymI_HasProto(powf) \
427 SymI_HasProto(tanhf) \
428 SymI_HasProto(coshf) \
429 SymI_HasProto(sinhf) \
430 SymI_HasProto(atanf) \
431 SymI_HasProto(acosf) \
432 SymI_HasProto(asinf) \
433 SymI_HasProto(tanf) \
434 SymI_HasProto(cosf) \
435 SymI_HasProto(sinf) \
436 SymI_HasProto(expf) \
437 SymI_HasProto(logf) \
438 SymI_HasProto(sqrtf) \
440 SymI_HasProto(erfc) \
441 SymI_HasProto(erff) \
442 SymI_HasProto(erfcf) \
443 SymI_HasProto(memcpy) \
444 SymI_HasProto(rts_InstallConsoleEvent) \
445 SymI_HasProto(rts_ConsoleHandlerDone) \
446 SymI_NeedsProto(mktime) \
447 SymI_NeedsProto(_imp___timezone) \
448 SymI_NeedsProto(_imp___tzname) \
449 SymI_NeedsProto(_imp__tzname) \
450 SymI_NeedsProto(_imp___iob) \
451 SymI_NeedsProto(_imp___osver) \
452 SymI_NeedsProto(localtime) \
453 SymI_NeedsProto(gmtime) \
454 SymI_NeedsProto(opendir) \
455 SymI_NeedsProto(readdir) \
456 SymI_NeedsProto(rewinddir) \
457 RTS_MINGW_EXTRA_SYMS \
458 RTS_MINGW_GETTIMEOFDAY_SYM \
459 SymI_NeedsProto(closedir)
462 #if defined(darwin_TARGET_OS) && HAVE_PRINTF_LDBLSTUB
463 #define RTS_DARWIN_ONLY_SYMBOLS \
464 SymI_NeedsProto(asprintf$LDBLStub) \
465 SymI_NeedsProto(err$LDBLStub) \
466 SymI_NeedsProto(errc$LDBLStub) \
467 SymI_NeedsProto(errx$LDBLStub) \
468 SymI_NeedsProto(fprintf$LDBLStub) \
469 SymI_NeedsProto(fscanf$LDBLStub) \
470 SymI_NeedsProto(fwprintf$LDBLStub) \
471 SymI_NeedsProto(fwscanf$LDBLStub) \
472 SymI_NeedsProto(printf$LDBLStub) \
473 SymI_NeedsProto(scanf$LDBLStub) \
474 SymI_NeedsProto(snprintf$LDBLStub) \
475 SymI_NeedsProto(sprintf$LDBLStub) \
476 SymI_NeedsProto(sscanf$LDBLStub) \
477 SymI_NeedsProto(strtold$LDBLStub) \
478 SymI_NeedsProto(swprintf$LDBLStub) \
479 SymI_NeedsProto(swscanf$LDBLStub) \
480 SymI_NeedsProto(syslog$LDBLStub) \
481 SymI_NeedsProto(vasprintf$LDBLStub) \
482 SymI_NeedsProto(verr$LDBLStub) \
483 SymI_NeedsProto(verrc$LDBLStub) \
484 SymI_NeedsProto(verrx$LDBLStub) \
485 SymI_NeedsProto(vfprintf$LDBLStub) \
486 SymI_NeedsProto(vfscanf$LDBLStub) \
487 SymI_NeedsProto(vfwprintf$LDBLStub) \
488 SymI_NeedsProto(vfwscanf$LDBLStub) \
489 SymI_NeedsProto(vprintf$LDBLStub) \
490 SymI_NeedsProto(vscanf$LDBLStub) \
491 SymI_NeedsProto(vsnprintf$LDBLStub) \
492 SymI_NeedsProto(vsprintf$LDBLStub) \
493 SymI_NeedsProto(vsscanf$LDBLStub) \
494 SymI_NeedsProto(vswprintf$LDBLStub) \
495 SymI_NeedsProto(vswscanf$LDBLStub) \
496 SymI_NeedsProto(vsyslog$LDBLStub) \
497 SymI_NeedsProto(vwarn$LDBLStub) \
498 SymI_NeedsProto(vwarnc$LDBLStub) \
499 SymI_NeedsProto(vwarnx$LDBLStub) \
500 SymI_NeedsProto(vwprintf$LDBLStub) \
501 SymI_NeedsProto(vwscanf$LDBLStub) \
502 SymI_NeedsProto(warn$LDBLStub) \
503 SymI_NeedsProto(warnc$LDBLStub) \
504 SymI_NeedsProto(warnx$LDBLStub) \
505 SymI_NeedsProto(wcstold$LDBLStub) \
506 SymI_NeedsProto(wprintf$LDBLStub) \
507 SymI_NeedsProto(wscanf$LDBLStub)
509 #define RTS_DARWIN_ONLY_SYMBOLS
513 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
515 # define MAIN_CAP_SYM
518 #if !defined(mingw32_HOST_OS)
519 #define RTS_USER_SIGNALS_SYMBOLS \
520 SymI_HasProto(setIOManagerPipe) \
521 SymI_HasProto(ioManagerWakeup) \
522 SymI_HasProto(ioManagerSync) \
523 SymI_HasProto(blockUserSignals) \
524 SymI_HasProto(unblockUserSignals)
526 #define RTS_USER_SIGNALS_SYMBOLS \
527 SymI_HasProto(ioManagerWakeup) \
528 SymI_HasProto(sendIOManagerEvent) \
529 SymI_HasProto(readIOManagerEvent) \
530 SymI_HasProto(getIOManagerEvent) \
531 SymI_HasProto(console_handler)
534 #define RTS_LIBFFI_SYMBOLS \
535 SymE_NeedsProto(ffi_prep_cif) \
536 SymE_NeedsProto(ffi_call) \
537 SymE_NeedsProto(ffi_type_void) \
538 SymE_NeedsProto(ffi_type_float) \
539 SymE_NeedsProto(ffi_type_double) \
540 SymE_NeedsProto(ffi_type_sint64) \
541 SymE_NeedsProto(ffi_type_uint64) \
542 SymE_NeedsProto(ffi_type_sint32) \
543 SymE_NeedsProto(ffi_type_uint32) \
544 SymE_NeedsProto(ffi_type_sint16) \
545 SymE_NeedsProto(ffi_type_uint16) \
546 SymE_NeedsProto(ffi_type_sint8) \
547 SymE_NeedsProto(ffi_type_uint8) \
548 SymE_NeedsProto(ffi_type_pointer)
550 #ifdef TABLES_NEXT_TO_CODE
551 #define RTS_RET_SYMBOLS /* nothing */
553 #define RTS_RET_SYMBOLS \
554 SymI_HasProto(stg_enter_ret) \
555 SymI_HasProto(stg_gc_fun_ret) \
556 SymI_HasProto(stg_ap_v_ret) \
557 SymI_HasProto(stg_ap_f_ret) \
558 SymI_HasProto(stg_ap_d_ret) \
559 SymI_HasProto(stg_ap_l_ret) \
560 SymI_HasProto(stg_ap_n_ret) \
561 SymI_HasProto(stg_ap_p_ret) \
562 SymI_HasProto(stg_ap_pv_ret) \
563 SymI_HasProto(stg_ap_pp_ret) \
564 SymI_HasProto(stg_ap_ppv_ret) \
565 SymI_HasProto(stg_ap_ppp_ret) \
566 SymI_HasProto(stg_ap_pppv_ret) \
567 SymI_HasProto(stg_ap_pppp_ret) \
568 SymI_HasProto(stg_ap_ppppp_ret) \
569 SymI_HasProto(stg_ap_pppppp_ret)
572 /* Modules compiled with -ticky may mention ticky counters */
573 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
574 #define RTS_TICKY_SYMBOLS \
575 SymI_NeedsProto(ticky_entry_ctrs) \
576 SymI_NeedsProto(top_ct) \
578 SymI_HasProto(ENT_VIA_NODE_ctr) \
579 SymI_HasProto(ENT_STATIC_THK_ctr) \
580 SymI_HasProto(ENT_DYN_THK_ctr) \
581 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
582 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
583 SymI_HasProto(ENT_STATIC_CON_ctr) \
584 SymI_HasProto(ENT_DYN_CON_ctr) \
585 SymI_HasProto(ENT_STATIC_IND_ctr) \
586 SymI_HasProto(ENT_DYN_IND_ctr) \
587 SymI_HasProto(ENT_PERM_IND_ctr) \
588 SymI_HasProto(ENT_PAP_ctr) \
589 SymI_HasProto(ENT_AP_ctr) \
590 SymI_HasProto(ENT_AP_STACK_ctr) \
591 SymI_HasProto(ENT_BH_ctr) \
592 SymI_HasProto(UNKNOWN_CALL_ctr) \
593 SymI_HasProto(SLOW_CALL_v_ctr) \
594 SymI_HasProto(SLOW_CALL_f_ctr) \
595 SymI_HasProto(SLOW_CALL_d_ctr) \
596 SymI_HasProto(SLOW_CALL_l_ctr) \
597 SymI_HasProto(SLOW_CALL_n_ctr) \
598 SymI_HasProto(SLOW_CALL_p_ctr) \
599 SymI_HasProto(SLOW_CALL_pv_ctr) \
600 SymI_HasProto(SLOW_CALL_pp_ctr) \
601 SymI_HasProto(SLOW_CALL_ppv_ctr) \
602 SymI_HasProto(SLOW_CALL_ppp_ctr) \
603 SymI_HasProto(SLOW_CALL_pppv_ctr) \
604 SymI_HasProto(SLOW_CALL_pppp_ctr) \
605 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
606 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
607 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
608 SymI_HasProto(ticky_slow_call_unevald) \
609 SymI_HasProto(SLOW_CALL_ctr) \
610 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
611 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
612 SymI_HasProto(KNOWN_CALL_ctr) \
613 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
614 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
615 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
616 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
617 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
618 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
619 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
620 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
621 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
622 SymI_HasProto(UPDF_OMITTED_ctr) \
623 SymI_HasProto(UPDF_PUSHED_ctr) \
624 SymI_HasProto(CATCHF_PUSHED_ctr) \
625 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
626 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
627 SymI_HasProto(UPD_SQUEEZED_ctr) \
628 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
629 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
630 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
631 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
632 SymI_HasProto(ALLOC_HEAP_ctr) \
633 SymI_HasProto(ALLOC_HEAP_tot) \
634 SymI_HasProto(ALLOC_FUN_ctr) \
635 SymI_HasProto(ALLOC_FUN_adm) \
636 SymI_HasProto(ALLOC_FUN_gds) \
637 SymI_HasProto(ALLOC_FUN_slp) \
638 SymI_HasProto(UPD_NEW_IND_ctr) \
639 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
640 SymI_HasProto(UPD_OLD_IND_ctr) \
641 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
642 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
643 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
644 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
645 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
646 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
647 SymI_HasProto(GC_SEL_MINOR_ctr) \
648 SymI_HasProto(GC_SEL_MAJOR_ctr) \
649 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
650 SymI_HasProto(ALLOC_UP_THK_ctr) \
651 SymI_HasProto(ALLOC_SE_THK_ctr) \
652 SymI_HasProto(ALLOC_THK_adm) \
653 SymI_HasProto(ALLOC_THK_gds) \
654 SymI_HasProto(ALLOC_THK_slp) \
655 SymI_HasProto(ALLOC_CON_ctr) \
656 SymI_HasProto(ALLOC_CON_adm) \
657 SymI_HasProto(ALLOC_CON_gds) \
658 SymI_HasProto(ALLOC_CON_slp) \
659 SymI_HasProto(ALLOC_TUP_ctr) \
660 SymI_HasProto(ALLOC_TUP_adm) \
661 SymI_HasProto(ALLOC_TUP_gds) \
662 SymI_HasProto(ALLOC_TUP_slp) \
663 SymI_HasProto(ALLOC_BH_ctr) \
664 SymI_HasProto(ALLOC_BH_adm) \
665 SymI_HasProto(ALLOC_BH_gds) \
666 SymI_HasProto(ALLOC_BH_slp) \
667 SymI_HasProto(ALLOC_PRIM_ctr) \
668 SymI_HasProto(ALLOC_PRIM_adm) \
669 SymI_HasProto(ALLOC_PRIM_gds) \
670 SymI_HasProto(ALLOC_PRIM_slp) \
671 SymI_HasProto(ALLOC_PAP_ctr) \
672 SymI_HasProto(ALLOC_PAP_adm) \
673 SymI_HasProto(ALLOC_PAP_gds) \
674 SymI_HasProto(ALLOC_PAP_slp) \
675 SymI_HasProto(ALLOC_TSO_ctr) \
676 SymI_HasProto(ALLOC_TSO_adm) \
677 SymI_HasProto(ALLOC_TSO_gds) \
678 SymI_HasProto(ALLOC_TSO_slp) \
679 SymI_HasProto(RET_NEW_ctr) \
680 SymI_HasProto(RET_OLD_ctr) \
681 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
682 SymI_HasProto(RET_SEMI_loads_avoided)
685 // On most platforms, the garbage collector rewrites references
686 // to small integer and char objects to a set of common, shared ones.
688 // We don't do this when compiling to Windows DLLs at the moment because
689 // it doesn't support cross package data references well.
691 #if defined(__PIC__) && defined(mingw32_HOST_OS)
692 #define RTS_INTCHAR_SYMBOLS
694 #define RTS_INTCHAR_SYMBOLS \
695 SymI_HasProto(stg_CHARLIKE_closure) \
696 SymI_HasProto(stg_INTLIKE_closure)
700 #define RTS_SYMBOLS \
703 SymI_HasProto(StgReturn) \
704 SymI_HasProto(stg_enter_info) \
705 SymI_HasProto(stg_gc_void_info) \
706 SymI_HasProto(__stg_gc_enter_1) \
707 SymI_HasProto(stg_gc_noregs) \
708 SymI_HasProto(stg_gc_unpt_r1_info) \
709 SymI_HasProto(stg_gc_unpt_r1) \
710 SymI_HasProto(stg_gc_unbx_r1_info) \
711 SymI_HasProto(stg_gc_unbx_r1) \
712 SymI_HasProto(stg_gc_f1_info) \
713 SymI_HasProto(stg_gc_f1) \
714 SymI_HasProto(stg_gc_d1_info) \
715 SymI_HasProto(stg_gc_d1) \
716 SymI_HasProto(stg_gc_l1_info) \
717 SymI_HasProto(stg_gc_l1) \
718 SymI_HasProto(__stg_gc_fun) \
719 SymI_HasProto(stg_gc_fun_info) \
720 SymI_HasProto(stg_gc_gen) \
721 SymI_HasProto(stg_gc_gen_info) \
722 SymI_HasProto(stg_gc_gen_hp) \
723 SymI_HasProto(stg_gc_ut) \
724 SymI_HasProto(stg_gen_yield) \
725 SymI_HasProto(stg_yield_noregs) \
726 SymI_HasProto(stg_yield_to_interpreter) \
727 SymI_HasProto(stg_gen_block) \
728 SymI_HasProto(stg_block_noregs) \
729 SymI_HasProto(stg_block_1) \
730 SymI_HasProto(stg_block_takemvar) \
731 SymI_HasProto(stg_block_putmvar) \
733 SymI_HasProto(MallocFailHook) \
734 SymI_HasProto(OnExitHook) \
735 SymI_HasProto(OutOfHeapHook) \
736 SymI_HasProto(StackOverflowHook) \
737 SymI_HasProto(addDLL) \
738 SymI_HasProto(__int_encodeDouble) \
739 SymI_HasProto(__word_encodeDouble) \
740 SymI_HasProto(__2Int_encodeDouble) \
741 SymI_HasProto(__int_encodeFloat) \
742 SymI_HasProto(__word_encodeFloat) \
743 SymI_HasProto(stg_atomicallyzh) \
744 SymI_HasProto(barf) \
745 SymI_HasProto(debugBelch) \
746 SymI_HasProto(errorBelch) \
747 SymI_HasProto(sysErrorBelch) \
748 SymI_HasProto(stg_asyncExceptionsBlockedzh) \
749 SymI_HasProto(stg_blockAsyncExceptionszh) \
750 SymI_HasProto(stg_catchzh) \
751 SymI_HasProto(stg_catchRetryzh) \
752 SymI_HasProto(stg_catchSTMzh) \
753 SymI_HasProto(stg_checkzh) \
754 SymI_HasProto(closure_flags) \
755 SymI_HasProto(cmp_thread) \
756 SymI_HasProto(createAdjustor) \
757 SymI_HasProto(stg_decodeDoublezu2Intzh) \
758 SymI_HasProto(stg_decodeFloatzuIntzh) \
759 SymI_HasProto(defaultsHook) \
760 SymI_HasProto(stg_delayzh) \
761 SymI_HasProto(stg_deRefWeakzh) \
762 SymI_HasProto(stg_deRefStablePtrzh) \
763 SymI_HasProto(dirty_MUT_VAR) \
764 SymI_HasProto(stg_forkzh) \
765 SymI_HasProto(stg_forkOnzh) \
766 SymI_HasProto(forkProcess) \
767 SymI_HasProto(forkOS_createThread) \
768 SymI_HasProto(freeHaskellFunctionPtr) \
769 SymI_HasProto(getOrSetTypeableStore) \
770 SymI_HasProto(getOrSetGHCConcSignalHandlerStore) \
771 SymI_HasProto(getOrSetGHCConcPendingEventsStore) \
772 SymI_HasProto(getOrSetGHCConcPendingDelaysStore) \
773 SymI_HasProto(getOrSetGHCConcIOManagerThreadStore) \
774 SymI_HasProto(getOrSetGHCConcProddingStore) \
775 SymI_HasProto(genSymZh) \
776 SymI_HasProto(genericRaise) \
777 SymI_HasProto(getProgArgv) \
778 SymI_HasProto(getFullProgArgv) \
779 SymI_HasProto(getStablePtr) \
780 SymI_HasProto(hs_init) \
781 SymI_HasProto(hs_exit) \
782 SymI_HasProto(hs_set_argv) \
783 SymI_HasProto(hs_add_root) \
784 SymI_HasProto(hs_perform_gc) \
785 SymI_HasProto(hs_free_stable_ptr) \
786 SymI_HasProto(hs_free_fun_ptr) \
787 SymI_HasProto(hs_hpc_rootModule) \
788 SymI_HasProto(hs_hpc_module) \
789 SymI_HasProto(initLinker) \
790 SymI_HasProto(stg_unpackClosurezh) \
791 SymI_HasProto(stg_getApStackValzh) \
792 SymI_HasProto(stg_getSparkzh) \
793 SymI_HasProto(stg_isCurrentThreadBoundzh) \
794 SymI_HasProto(stg_isEmptyMVarzh) \
795 SymI_HasProto(stg_killThreadzh) \
796 SymI_HasProto(loadObj) \
797 SymI_HasProto(insertStableSymbol) \
798 SymI_HasProto(insertSymbol) \
799 SymI_HasProto(lookupSymbol) \
800 SymI_HasProto(stg_makeStablePtrzh) \
801 SymI_HasProto(stg_mkApUpd0zh) \
802 SymI_HasProto(stg_myThreadIdzh) \
803 SymI_HasProto(stg_labelThreadzh) \
804 SymI_HasProto(stg_newArrayzh) \
805 SymI_HasProto(stg_newBCOzh) \
806 SymI_HasProto(stg_newByteArrayzh) \
807 SymI_HasProto_redirect(newCAF, newDynCAF) \
808 SymI_HasProto(stg_newMVarzh) \
809 SymI_HasProto(stg_newMutVarzh) \
810 SymI_HasProto(stg_newTVarzh) \
811 SymI_HasProto(stg_noDuplicatezh) \
812 SymI_HasProto(stg_atomicModifyMutVarzh) \
813 SymI_HasProto(stg_newPinnedByteArrayzh) \
814 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
815 SymI_HasProto(newSpark) \
816 SymI_HasProto(performGC) \
817 SymI_HasProto(performMajorGC) \
818 SymI_HasProto(prog_argc) \
819 SymI_HasProto(prog_argv) \
820 SymI_HasProto(stg_putMVarzh) \
821 SymI_HasProto(stg_raisezh) \
822 SymI_HasProto(stg_raiseIOzh) \
823 SymI_HasProto(stg_readTVarzh) \
824 SymI_HasProto(stg_readTVarIOzh) \
825 SymI_HasProto(resumeThread) \
826 SymI_HasProto(resolveObjs) \
827 SymI_HasProto(stg_retryzh) \
828 SymI_HasProto(rts_apply) \
829 SymI_HasProto(rts_checkSchedStatus) \
830 SymI_HasProto(rts_eval) \
831 SymI_HasProto(rts_evalIO) \
832 SymI_HasProto(rts_evalLazyIO) \
833 SymI_HasProto(rts_evalStableIO) \
834 SymI_HasProto(rts_eval_) \
835 SymI_HasProto(rts_getBool) \
836 SymI_HasProto(rts_getChar) \
837 SymI_HasProto(rts_getDouble) \
838 SymI_HasProto(rts_getFloat) \
839 SymI_HasProto(rts_getInt) \
840 SymI_HasProto(rts_getInt8) \
841 SymI_HasProto(rts_getInt16) \
842 SymI_HasProto(rts_getInt32) \
843 SymI_HasProto(rts_getInt64) \
844 SymI_HasProto(rts_getPtr) \
845 SymI_HasProto(rts_getFunPtr) \
846 SymI_HasProto(rts_getStablePtr) \
847 SymI_HasProto(rts_getThreadId) \
848 SymI_HasProto(rts_getWord) \
849 SymI_HasProto(rts_getWord8) \
850 SymI_HasProto(rts_getWord16) \
851 SymI_HasProto(rts_getWord32) \
852 SymI_HasProto(rts_getWord64) \
853 SymI_HasProto(rts_lock) \
854 SymI_HasProto(rts_mkBool) \
855 SymI_HasProto(rts_mkChar) \
856 SymI_HasProto(rts_mkDouble) \
857 SymI_HasProto(rts_mkFloat) \
858 SymI_HasProto(rts_mkInt) \
859 SymI_HasProto(rts_mkInt8) \
860 SymI_HasProto(rts_mkInt16) \
861 SymI_HasProto(rts_mkInt32) \
862 SymI_HasProto(rts_mkInt64) \
863 SymI_HasProto(rts_mkPtr) \
864 SymI_HasProto(rts_mkFunPtr) \
865 SymI_HasProto(rts_mkStablePtr) \
866 SymI_HasProto(rts_mkString) \
867 SymI_HasProto(rts_mkWord) \
868 SymI_HasProto(rts_mkWord8) \
869 SymI_HasProto(rts_mkWord16) \
870 SymI_HasProto(rts_mkWord32) \
871 SymI_HasProto(rts_mkWord64) \
872 SymI_HasProto(rts_unlock) \
873 SymI_HasProto(rts_unsafeGetMyCapability) \
874 SymI_HasProto(rtsSupportsBoundThreads) \
875 SymI_HasProto(setProgArgv) \
876 SymI_HasProto(startupHaskell) \
877 SymI_HasProto(shutdownHaskell) \
878 SymI_HasProto(shutdownHaskellAndExit) \
879 SymI_HasProto(stable_ptr_table) \
880 SymI_HasProto(stackOverflow) \
881 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
882 SymI_HasProto(stg_BLACKHOLE_info) \
883 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
884 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
885 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
886 SymI_HasProto(startTimer) \
887 SymI_HasProto(stg_MVAR_CLEAN_info) \
888 SymI_HasProto(stg_MVAR_DIRTY_info) \
889 SymI_HasProto(stg_IND_STATIC_info) \
890 SymI_HasProto(stg_ARR_WORDS_info) \
891 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
892 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
893 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
894 SymI_HasProto(stg_WEAK_info) \
895 SymI_HasProto(stg_ap_v_info) \
896 SymI_HasProto(stg_ap_f_info) \
897 SymI_HasProto(stg_ap_d_info) \
898 SymI_HasProto(stg_ap_l_info) \
899 SymI_HasProto(stg_ap_n_info) \
900 SymI_HasProto(stg_ap_p_info) \
901 SymI_HasProto(stg_ap_pv_info) \
902 SymI_HasProto(stg_ap_pp_info) \
903 SymI_HasProto(stg_ap_ppv_info) \
904 SymI_HasProto(stg_ap_ppp_info) \
905 SymI_HasProto(stg_ap_pppv_info) \
906 SymI_HasProto(stg_ap_pppp_info) \
907 SymI_HasProto(stg_ap_ppppp_info) \
908 SymI_HasProto(stg_ap_pppppp_info) \
909 SymI_HasProto(stg_ap_0_fast) \
910 SymI_HasProto(stg_ap_v_fast) \
911 SymI_HasProto(stg_ap_f_fast) \
912 SymI_HasProto(stg_ap_d_fast) \
913 SymI_HasProto(stg_ap_l_fast) \
914 SymI_HasProto(stg_ap_n_fast) \
915 SymI_HasProto(stg_ap_p_fast) \
916 SymI_HasProto(stg_ap_pv_fast) \
917 SymI_HasProto(stg_ap_pp_fast) \
918 SymI_HasProto(stg_ap_ppv_fast) \
919 SymI_HasProto(stg_ap_ppp_fast) \
920 SymI_HasProto(stg_ap_pppv_fast) \
921 SymI_HasProto(stg_ap_pppp_fast) \
922 SymI_HasProto(stg_ap_ppppp_fast) \
923 SymI_HasProto(stg_ap_pppppp_fast) \
924 SymI_HasProto(stg_ap_1_upd_info) \
925 SymI_HasProto(stg_ap_2_upd_info) \
926 SymI_HasProto(stg_ap_3_upd_info) \
927 SymI_HasProto(stg_ap_4_upd_info) \
928 SymI_HasProto(stg_ap_5_upd_info) \
929 SymI_HasProto(stg_ap_6_upd_info) \
930 SymI_HasProto(stg_ap_7_upd_info) \
931 SymI_HasProto(stg_exit) \
932 SymI_HasProto(stg_sel_0_upd_info) \
933 SymI_HasProto(stg_sel_10_upd_info) \
934 SymI_HasProto(stg_sel_11_upd_info) \
935 SymI_HasProto(stg_sel_12_upd_info) \
936 SymI_HasProto(stg_sel_13_upd_info) \
937 SymI_HasProto(stg_sel_14_upd_info) \
938 SymI_HasProto(stg_sel_15_upd_info) \
939 SymI_HasProto(stg_sel_1_upd_info) \
940 SymI_HasProto(stg_sel_2_upd_info) \
941 SymI_HasProto(stg_sel_3_upd_info) \
942 SymI_HasProto(stg_sel_4_upd_info) \
943 SymI_HasProto(stg_sel_5_upd_info) \
944 SymI_HasProto(stg_sel_6_upd_info) \
945 SymI_HasProto(stg_sel_7_upd_info) \
946 SymI_HasProto(stg_sel_8_upd_info) \
947 SymI_HasProto(stg_sel_9_upd_info) \
948 SymI_HasProto(stg_upd_frame_info) \
949 SymI_HasProto(stg_bh_upd_frame_info) \
950 SymI_HasProto(suspendThread) \
951 SymI_HasProto(stg_takeMVarzh) \
952 SymI_HasProto(stg_threadStatuszh) \
953 SymI_HasProto(stg_tryPutMVarzh) \
954 SymI_HasProto(stg_tryTakeMVarzh) \
955 SymI_HasProto(stg_unblockAsyncExceptionszh) \
956 SymI_HasProto(unloadObj) \
957 SymI_HasProto(stg_unsafeThawArrayzh) \
958 SymI_HasProto(stg_waitReadzh) \
959 SymI_HasProto(stg_waitWritezh) \
960 SymI_HasProto(stg_writeTVarzh) \
961 SymI_HasProto(stg_yieldzh) \
962 SymI_NeedsProto(stg_interp_constr_entry) \
963 SymI_HasProto(alloc_blocks_lim) \
965 SymI_HasProto(allocate) \
966 SymI_HasProto(allocateExec) \
967 SymI_HasProto(freeExec) \
968 SymI_HasProto(getAllocations) \
969 SymI_HasProto(revertCAFs) \
970 SymI_HasProto(RtsFlags) \
971 SymI_NeedsProto(rts_breakpoint_io_action) \
972 SymI_NeedsProto(rts_stop_next_breakpoint) \
973 SymI_NeedsProto(rts_stop_on_exception) \
974 SymI_HasProto(stopTimer) \
975 SymI_HasProto(n_capabilities) \
976 SymI_HasProto(stg_traceCcszh) \
977 SymI_HasProto(stg_traceEventzh) \
978 RTS_USER_SIGNALS_SYMBOLS \
982 // 64-bit support functions in libgcc.a
983 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
984 #define RTS_LIBGCC_SYMBOLS \
985 SymI_NeedsProto(__divdi3) \
986 SymI_NeedsProto(__udivdi3) \
987 SymI_NeedsProto(__moddi3) \
988 SymI_NeedsProto(__umoddi3) \
989 SymI_NeedsProto(__muldi3) \
990 SymI_NeedsProto(__ashldi3) \
991 SymI_NeedsProto(__ashrdi3) \
992 SymI_NeedsProto(__lshrdi3)
994 #define RTS_LIBGCC_SYMBOLS
997 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
998 // Symbols that don't have a leading underscore
999 // on Mac OS X. They have to receive special treatment,
1000 // see machoInitSymbolsWithoutUnderscore()
1001 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1002 SymI_NeedsProto(saveFP) \
1003 SymI_NeedsProto(restFP)
1006 /* entirely bogus claims about types of these symbols */
1007 #define SymI_NeedsProto(vvv) extern void vvv(void);
1008 #if defined(__PIC__) && defined(mingw32_TARGET_OS)
1009 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1010 #define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1012 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1013 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1015 #define SymI_HasProto(vvv) /**/
1016 #define SymI_HasProto_redirect(vvv,xxx) /**/
1019 RTS_POSIX_ONLY_SYMBOLS
1020 RTS_MINGW_ONLY_SYMBOLS
1021 RTS_CYGWIN_ONLY_SYMBOLS
1022 RTS_DARWIN_ONLY_SYMBOLS
1025 #undef SymI_NeedsProto
1026 #undef SymI_HasProto
1027 #undef SymI_HasProto_redirect
1028 #undef SymE_HasProto
1029 #undef SymE_NeedsProto
1031 #ifdef LEADING_UNDERSCORE
1032 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1034 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1037 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1039 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1040 (void*)DLL_IMPORT_DATA_REF(vvv) },
1042 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1043 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1045 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1046 // another symbol. See newCAF/newDynCAF for an example.
1047 #define SymI_HasProto_redirect(vvv,xxx) \
1048 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1051 static RtsSymbolVal rtsSyms[] = {
1054 RTS_POSIX_ONLY_SYMBOLS
1055 RTS_MINGW_ONLY_SYMBOLS
1056 RTS_CYGWIN_ONLY_SYMBOLS
1057 RTS_DARWIN_ONLY_SYMBOLS
1060 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1061 // dyld stub code contains references to this,
1062 // but it should never be called because we treat
1063 // lazy pointers as nonlazy.
1064 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1066 { 0, 0 } /* sentinel */
1071 /* -----------------------------------------------------------------------------
1072 * Insert symbols into hash tables, checking for duplicates.
1075 static void ghciInsertStrHashTable ( char* obj_name,
1081 if (lookupHashTable(table, (StgWord)key) == NULL)
1083 insertStrHashTable(table, (StgWord)key, data);
1088 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1090 "whilst processing object file\n"
1092 "This could be caused by:\n"
1093 " * Loading two different object files which export the same symbol\n"
1094 " * Specifying the same object file twice on the GHCi command line\n"
1095 " * An incorrect `package.conf' entry, causing some object to be\n"
1097 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1104 /* -----------------------------------------------------------------------------
1105 * initialize the object linker
1109 static int linker_init_done = 0 ;
1111 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1112 static void *dl_prog_handle;
1113 static regex_t re_invalid;
1114 static regex_t re_realso;
1116 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1124 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1128 /* Make initLinker idempotent, so we can call it
1129 before evey relevant operation; that means we
1130 don't need to initialise the linker separately */
1131 if (linker_init_done == 1) { return; } else {
1132 linker_init_done = 1;
1135 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1136 initMutex(&dl_mutex);
1138 stablehash = allocStrHashTable();
1139 symhash = allocStrHashTable();
1141 /* populate the symbol table with stuff from the RTS */
1142 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1143 ghciInsertStrHashTable("(GHCi built-in symbols)",
1144 symhash, sym->lbl, sym->addr);
1146 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1147 machoInitSymbolsWithoutUnderscore();
1150 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1151 # if defined(RTLD_DEFAULT)
1152 dl_prog_handle = RTLD_DEFAULT;
1154 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1155 # endif /* RTLD_DEFAULT */
1157 compileResult = regcomp(&re_invalid,
1158 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*invalid ELF header",
1160 ASSERT( compileResult == 0 );
1161 compileResult = regcomp(&re_realso,
1162 "GROUP *\\( *(([^ )])+)",
1164 ASSERT( compileResult == 0 );
1167 #if defined(x86_64_HOST_ARCH)
1168 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1169 // User-override for mmap_32bit_base
1170 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1174 #if defined(mingw32_HOST_OS)
1176 * These two libraries cause problems when added to the static link,
1177 * but are necessary for resolving symbols in GHCi, hence we load
1178 * them manually here.
1186 exitLinker( void ) {
1187 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1188 if (linker_init_done == 1) {
1189 regfree(&re_invalid);
1190 regfree(&re_realso);
1192 closeMutex(&dl_mutex);
1198 /* -----------------------------------------------------------------------------
1199 * Loading DLL or .so dynamic libraries
1200 * -----------------------------------------------------------------------------
1202 * Add a DLL from which symbols may be found. In the ELF case, just
1203 * do RTLD_GLOBAL-style add, so no further messing around needs to
1204 * happen in order that symbols in the loaded .so are findable --
1205 * lookupSymbol() will subsequently see them by dlsym on the program's
1206 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1208 * In the PEi386 case, open the DLLs and put handles to them in a
1209 * linked list. When looking for a symbol, try all handles in the
1210 * list. This means that we need to load even DLLs that are guaranteed
1211 * to be in the ghc.exe image already, just so we can get a handle
1212 * to give to loadSymbol, so that we can find the symbols. For such
1213 * libraries, the LoadLibrary call should be a no-op except for returning
1218 #if defined(OBJFORMAT_PEi386)
1219 /* A record for storing handles into DLLs. */
1224 struct _OpenedDLL* next;
1229 /* A list thereof. */
1230 static OpenedDLL* opened_dlls = NULL;
1233 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1236 internal_dlopen(const char *dll_name)
1242 // omitted: RTLD_NOW
1243 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1245 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1247 //-------------- Begin critical section ------------------
1248 // This critical section is necessary because dlerror() is not
1249 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1250 // Also, the error message returned must be copied to preserve it
1253 ACQUIRE_LOCK(&dl_mutex);
1254 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1258 /* dlopen failed; return a ptr to the error msg. */
1260 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1261 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1262 strcpy(errmsg_copy, errmsg);
1263 errmsg = errmsg_copy;
1265 RELEASE_LOCK(&dl_mutex);
1266 //--------------- End critical section -------------------
1273 addDLL( char *dll_name )
1275 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1276 /* ------------------- ELF DLL loader ------------------- */
1279 regmatch_t match[NMATCH];
1282 size_t match_length;
1283 #define MAXLINE 1000
1289 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1290 errmsg = internal_dlopen(dll_name);
1292 if (errmsg == NULL) {
1296 // GHC Trac ticket #2615
1297 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1298 // contain linker scripts rather than ELF-format object code. This
1299 // code handles the situation by recognizing the real object code
1300 // file name given in the linker script.
1302 // If an "invalid ELF header" error occurs, it is assumed that the
1303 // .so file contains a linker script instead of ELF object code.
1304 // In this case, the code looks for the GROUP ( ... ) linker
1305 // directive. If one is found, the first file name inside the
1306 // parentheses is treated as the name of a dynamic library and the
1307 // code attempts to dlopen that file. If this is also unsuccessful,
1308 // an error message is returned.
1310 // see if the error message is due to an invalid ELF header
1311 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1312 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1313 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1315 // success -- try to read the named file as a linker script
1316 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1318 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1319 line[match_length] = '\0'; // make sure string is null-terminated
1320 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1321 if ((fp = fopen(line, "r")) == NULL) {
1322 return errmsg; // return original error if open fails
1324 // try to find a GROUP ( ... ) command
1325 while (fgets(line, MAXLINE, fp) != NULL) {
1326 IF_DEBUG(linker, debugBelch("input line = %s", line));
1327 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1328 // success -- try to dlopen the first named file
1329 IF_DEBUG(linker, debugBelch("match%s\n",""));
1330 line[match[1].rm_eo] = '\0';
1331 errmsg = internal_dlopen(line+match[1].rm_so);
1334 // if control reaches here, no GROUP ( ... ) directive was found
1335 // and the original error message is returned to the caller
1341 # elif defined(OBJFORMAT_PEi386)
1342 /* ------------------- Win32 DLL loader ------------------- */
1350 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1352 /* See if we've already got it, and ignore if so. */
1353 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1354 if (0 == strcmp(o_dll->name, dll_name))
1358 /* The file name has no suffix (yet) so that we can try
1359 both foo.dll and foo.drv
1361 The documentation for LoadLibrary says:
1362 If no file name extension is specified in the lpFileName
1363 parameter, the default library extension .dll is
1364 appended. However, the file name string can include a trailing
1365 point character (.) to indicate that the module name has no
1368 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1369 sprintf(buf, "%s.DLL", dll_name);
1370 instance = LoadLibrary(buf);
1371 if (instance == NULL) {
1372 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1373 // KAA: allow loading of drivers (like winspool.drv)
1374 sprintf(buf, "%s.DRV", dll_name);
1375 instance = LoadLibrary(buf);
1376 if (instance == NULL) {
1377 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1378 // #1883: allow loading of unix-style libfoo.dll DLLs
1379 sprintf(buf, "lib%s.DLL", dll_name);
1380 instance = LoadLibrary(buf);
1381 if (instance == NULL) {
1388 /* Add this DLL to the list of DLLs in which to search for symbols. */
1389 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1390 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
1391 strcpy(o_dll->name, dll_name);
1392 o_dll->instance = instance;
1393 o_dll->next = opened_dlls;
1394 opened_dlls = o_dll;
1400 sysErrorBelch(dll_name);
1402 /* LoadLibrary failed; return a ptr to the error msg. */
1403 return "addDLL: could not load DLL";
1406 barf("addDLL: not implemented on this platform");
1410 /* -----------------------------------------------------------------------------
1411 * insert a stable symbol in the hash table
1415 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1417 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1421 /* -----------------------------------------------------------------------------
1422 * insert a symbol in the hash table
1425 insertSymbol(char* obj_name, char* key, void* data)
1427 ghciInsertStrHashTable(obj_name, symhash, key, data);
1430 /* -----------------------------------------------------------------------------
1431 * lookup a symbol in the hash table
1434 lookupSymbol( char *lbl )
1438 ASSERT(symhash != NULL);
1439 val = lookupStrHashTable(symhash, lbl);
1442 # if defined(OBJFORMAT_ELF)
1443 return dlsym(dl_prog_handle, lbl);
1444 # elif defined(OBJFORMAT_MACHO)
1446 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1449 HACK: On OS X, global symbols are prefixed with an underscore.
1450 However, dlsym wants us to omit the leading underscore from the
1451 symbol name. For now, we simply strip it off here (and ONLY
1454 ASSERT(lbl[0] == '_');
1455 return dlsym(dl_prog_handle, lbl+1);
1457 if(NSIsSymbolNameDefined(lbl)) {
1458 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1459 return NSAddressOfSymbol(symbol);
1463 # endif /* HAVE_DLFCN_H */
1464 # elif defined(OBJFORMAT_PEi386)
1467 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1468 if (sym != NULL) { return sym; };
1470 // Also try looking up the symbol without the @N suffix. Some
1471 // DLLs have the suffixes on their symbols, some don't.
1472 zapTrailingAtSign ( (unsigned char*)lbl );
1473 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1474 if (sym != NULL) { return sym; };
1486 /* -----------------------------------------------------------------------------
1487 * Debugging aid: look in GHCi's object symbol tables for symbols
1488 * within DELTA bytes of the specified address, and show their names.
1491 void ghci_enquire ( char* addr );
1493 void ghci_enquire ( char* addr )
1498 const int DELTA = 64;
1503 for (oc = objects; oc; oc = oc->next) {
1504 for (i = 0; i < oc->n_symbols; i++) {
1505 sym = oc->symbols[i];
1506 if (sym == NULL) continue;
1509 a = lookupStrHashTable(symhash, sym);
1512 // debugBelch("ghci_enquire: can't find %s\n", sym);
1514 else if (addr-DELTA <= a && a <= addr+DELTA) {
1515 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1523 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1526 mmapForLinker (size_t bytes, nat flags, int fd)
1528 void *map_addr = NULL;
1531 static nat fixed = 0;
1533 pagesize = getpagesize();
1534 size = ROUND_UP(bytes, pagesize);
1536 #if defined(x86_64_HOST_ARCH)
1539 if (mmap_32bit_base != 0) {
1540 map_addr = mmap_32bit_base;
1544 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1545 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1547 if (result == MAP_FAILED) {
1548 sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1549 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1550 stg_exit(EXIT_FAILURE);
1553 #if defined(x86_64_HOST_ARCH)
1554 if (mmap_32bit_base != 0) {
1555 if (result == map_addr) {
1556 mmap_32bit_base = (StgWord8*)map_addr + size;
1558 if ((W_)result > 0x80000000) {
1559 // oops, we were given memory over 2Gb
1560 #if defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS)
1561 // Some platforms require MAP_FIXED. This is normally
1562 // a bad idea, because MAP_FIXED will overwrite
1563 // existing mappings.
1564 munmap(result,size);
1568 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);
1571 // hmm, we were given memory somewhere else, but it's
1572 // still under 2Gb so we can use it. Next time, ask
1573 // for memory right after the place we just got some
1574 mmap_32bit_base = (StgWord8*)result + size;
1578 if ((W_)result > 0x80000000) {
1579 // oops, we were given memory over 2Gb
1580 // ... try allocating memory somewhere else?;
1581 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1582 munmap(result, size);
1584 // Set a base address and try again... (guess: 1Gb)
1585 mmap_32bit_base = (void*)0x40000000;
1595 /* -----------------------------------------------------------------------------
1596 * Load an obj (populate the global symbol table, but don't resolve yet)
1598 * Returns: 1 if ok, 0 on error.
1601 loadObj( char *path )
1613 /* debugBelch("loadObj %s\n", path ); */
1615 /* Check that we haven't already loaded this object.
1616 Ignore requests to load multiple times */
1620 for (o = objects; o; o = o->next) {
1621 if (0 == strcmp(o->fileName, path)) {
1623 break; /* don't need to search further */
1627 IF_DEBUG(linker, debugBelch(
1628 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1629 "same object file twice:\n"
1631 "GHCi will ignore this, but be warned.\n"
1633 return 1; /* success */
1637 oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
1639 # if defined(OBJFORMAT_ELF)
1640 oc->formatName = "ELF";
1641 # elif defined(OBJFORMAT_PEi386)
1642 oc->formatName = "PEi386";
1643 # elif defined(OBJFORMAT_MACHO)
1644 oc->formatName = "Mach-O";
1647 barf("loadObj: not implemented on this platform");
1650 r = stat(path, &st);
1651 if (r == -1) { return 0; }
1653 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1654 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1655 strcpy(oc->fileName, path);
1657 oc->fileSize = st.st_size;
1659 oc->sections = NULL;
1660 oc->proddables = NULL;
1662 /* chain it onto the list of objects */
1667 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
1669 #if defined(openbsd_HOST_OS)
1670 fd = open(path, O_RDONLY, S_IRUSR);
1672 fd = open(path, O_RDONLY);
1675 barf("loadObj: can't open `%s'", path);
1677 oc->image = mmapForLinker(oc->fileSize, 0, fd);
1681 #else /* !USE_MMAP */
1682 /* load the image into memory */
1683 f = fopen(path, "rb");
1685 barf("loadObj: can't read `%s'", path);
1687 # if defined(mingw32_HOST_OS)
1688 // TODO: We would like to use allocateExec here, but allocateExec
1689 // cannot currently allocate blocks large enough.
1690 oc->image = VirtualAlloc(NULL, oc->fileSize, MEM_RESERVE | MEM_COMMIT,
1691 PAGE_EXECUTE_READWRITE);
1692 # elif defined(darwin_HOST_OS)
1693 // In a Mach-O .o file, all sections can and will be misaligned
1694 // if the total size of the headers is not a multiple of the
1695 // desired alignment. This is fine for .o files that only serve
1696 // as input for the static linker, but it's not fine for us,
1697 // as SSE (used by gcc for floating point) and Altivec require
1698 // 16-byte alignment.
1699 // We calculate the correct alignment from the header before
1700 // reading the file, and then we misalign oc->image on purpose so
1701 // that the actual sections end up aligned again.
1702 oc->misalignment = machoGetMisalignment(f);
1703 oc->image = stgMallocBytes(oc->fileSize + oc->misalignment, "loadObj(image)");
1704 oc->image += oc->misalignment;
1706 oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
1711 n = fread ( oc->image, 1, oc->fileSize, f );
1712 if (n != oc->fileSize)
1713 barf("loadObj: error whilst reading `%s'", path);
1716 #endif /* USE_MMAP */
1718 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1719 r = ocAllocateSymbolExtras_MachO ( oc );
1720 if (!r) { return r; }
1721 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1722 r = ocAllocateSymbolExtras_ELF ( oc );
1723 if (!r) { return r; }
1726 /* verify the in-memory image */
1727 # if defined(OBJFORMAT_ELF)
1728 r = ocVerifyImage_ELF ( oc );
1729 # elif defined(OBJFORMAT_PEi386)
1730 r = ocVerifyImage_PEi386 ( oc );
1731 # elif defined(OBJFORMAT_MACHO)
1732 r = ocVerifyImage_MachO ( oc );
1734 barf("loadObj: no verify method");
1736 if (!r) { return r; }
1738 /* build the symbol list for this image */
1739 # if defined(OBJFORMAT_ELF)
1740 r = ocGetNames_ELF ( oc );
1741 # elif defined(OBJFORMAT_PEi386)
1742 r = ocGetNames_PEi386 ( oc );
1743 # elif defined(OBJFORMAT_MACHO)
1744 r = ocGetNames_MachO ( oc );
1746 barf("loadObj: no getNames method");
1748 if (!r) { return r; }
1750 /* loaded, but not resolved yet */
1751 oc->status = OBJECT_LOADED;
1756 /* -----------------------------------------------------------------------------
1757 * resolve all the currently unlinked objects in memory
1759 * Returns: 1 if ok, 0 on error.
1769 for (oc = objects; oc; oc = oc->next) {
1770 if (oc->status != OBJECT_RESOLVED) {
1771 # if defined(OBJFORMAT_ELF)
1772 r = ocResolve_ELF ( oc );
1773 # elif defined(OBJFORMAT_PEi386)
1774 r = ocResolve_PEi386 ( oc );
1775 # elif defined(OBJFORMAT_MACHO)
1776 r = ocResolve_MachO ( oc );
1778 barf("resolveObjs: not implemented on this platform");
1780 if (!r) { return r; }
1781 oc->status = OBJECT_RESOLVED;
1787 /* -----------------------------------------------------------------------------
1788 * delete an object from the pool
1791 unloadObj( char *path )
1793 ObjectCode *oc, *prev;
1795 ASSERT(symhash != NULL);
1796 ASSERT(objects != NULL);
1801 for (oc = objects; oc; prev = oc, oc = oc->next) {
1802 if (!strcmp(oc->fileName,path)) {
1804 /* Remove all the mappings for the symbols within this
1809 for (i = 0; i < oc->n_symbols; i++) {
1810 if (oc->symbols[i] != NULL) {
1811 removeStrHashTable(symhash, oc->symbols[i], NULL);
1819 prev->next = oc->next;
1822 // We're going to leave this in place, in case there are
1823 // any pointers from the heap into it:
1824 // #ifdef mingw32_HOST_OS
1825 // VirtualFree(oc->image);
1827 // stgFree(oc->image);
1829 stgFree(oc->fileName);
1830 stgFree(oc->symbols);
1831 stgFree(oc->sections);
1837 errorBelch("unloadObj: can't find `%s' to unload", path);
1841 /* -----------------------------------------------------------------------------
1842 * Sanity checking. For each ObjectCode, maintain a list of address ranges
1843 * which may be prodded during relocation, and abort if we try and write
1844 * outside any of these.
1846 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1849 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1850 /* debugBelch("aPB %p %p %d\n", oc, start, size); */
1854 pb->next = oc->proddables;
1855 oc->proddables = pb;
1858 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1861 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1862 char* s = (char*)(pb->start);
1863 char* e = s + pb->size - 1;
1864 char* a = (char*)addr;
1865 /* Assumes that the biggest fixup involves a 4-byte write. This
1866 probably needs to be changed to 8 (ie, +7) on 64-bit
1868 if (a >= s && (a+3) <= e) return;
1870 barf("checkProddableBlock: invalid fixup in runtime linker");
1873 /* -----------------------------------------------------------------------------
1874 * Section management.
1876 static void addSection ( ObjectCode* oc, SectionKind kind,
1877 void* start, void* end )
1879 Section* s = stgMallocBytes(sizeof(Section), "addSection");
1883 s->next = oc->sections;
1886 debugBelch("addSection: %p-%p (size %d), kind %d\n",
1887 start, ((char*)end)-1, end - start + 1, kind );
1892 /* --------------------------------------------------------------------------
1894 * This is about allocating a small chunk of memory for every symbol in the
1895 * object file. We make sure that the SymboLExtras are always "in range" of
1896 * limited-range PC-relative instructions on various platforms by allocating
1897 * them right next to the object code itself.
1900 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
1903 ocAllocateSymbolExtras
1905 Allocate additional space at the end of the object file image to make room
1906 for jump islands (powerpc, x86_64) and GOT entries (x86_64).
1908 PowerPC relative branch instructions have a 24 bit displacement field.
1909 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
1910 If a particular imported symbol is outside this range, we have to redirect
1911 the jump to a short piece of new code that just loads the 32bit absolute
1912 address and jumps there.
1913 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
1916 This function just allocates space for one SymbolExtra for every
1917 undefined symbol in the object file. The code for the jump islands is
1918 filled in by makeSymbolExtra below.
1921 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
1928 int misalignment = 0;
1929 #ifdef darwin_HOST_OS
1930 misalignment = oc->misalignment;
1936 // round up to the nearest 4
1937 aligned = (oc->fileSize + 3) & ~3;
1940 pagesize = getpagesize();
1941 n = ROUND_UP( oc->fileSize, pagesize );
1942 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
1944 /* we try to use spare space at the end of the last page of the
1945 * image for the jump islands, but if there isn't enough space
1946 * then we have to map some (anonymously, remembering MAP_32BIT).
1948 if( m > n ) // we need to allocate more pages
1950 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
1955 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1958 oc->image -= misalignment;
1959 oc->image = stgReallocBytes( oc->image,
1961 aligned + sizeof (SymbolExtra) * count,
1962 "ocAllocateSymbolExtras" );
1963 oc->image += misalignment;
1965 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1966 #endif /* USE_MMAP */
1968 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
1971 oc->symbol_extras = NULL;
1973 oc->first_symbol_extra = first;
1974 oc->n_symbol_extras = count;
1979 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
1980 unsigned long symbolNumber,
1981 unsigned long target )
1985 ASSERT( symbolNumber >= oc->first_symbol_extra
1986 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
1988 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
1990 #ifdef powerpc_HOST_ARCH
1991 // lis r12, hi16(target)
1992 extra->jumpIsland.lis_r12 = 0x3d80;
1993 extra->jumpIsland.hi_addr = target >> 16;
1995 // ori r12, r12, lo16(target)
1996 extra->jumpIsland.ori_r12_r12 = 0x618c;
1997 extra->jumpIsland.lo_addr = target & 0xffff;
2000 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2003 extra->jumpIsland.bctr = 0x4e800420;
2005 #ifdef x86_64_HOST_ARCH
2007 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2008 extra->addr = target;
2009 memcpy(extra->jumpIsland, jmp, 6);
2017 /* --------------------------------------------------------------------------
2018 * PowerPC specifics (instruction cache flushing)
2019 * ------------------------------------------------------------------------*/
2021 #ifdef powerpc_TARGET_ARCH
2023 ocFlushInstructionCache
2025 Flush the data & instruction caches.
2026 Because the PPC has split data/instruction caches, we have to
2027 do that whenever we modify code at runtime.
2030 static void ocFlushInstructionCache( ObjectCode *oc )
2032 int n = (oc->fileSize + sizeof( SymbolExtra ) * oc->n_symbol_extras + 3) / 4;
2033 unsigned long *p = (unsigned long *) oc->image;
2037 __asm__ volatile ( "dcbf 0,%0\n\t"
2045 __asm__ volatile ( "sync\n\t"
2051 /* --------------------------------------------------------------------------
2052 * PEi386 specifics (Win32 targets)
2053 * ------------------------------------------------------------------------*/
2055 /* The information for this linker comes from
2056 Microsoft Portable Executable
2057 and Common Object File Format Specification
2058 revision 5.1 January 1998
2059 which SimonM says comes from the MS Developer Network CDs.
2061 It can be found there (on older CDs), but can also be found
2064 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
2066 (this is Rev 6.0 from February 1999).
2068 Things move, so if that fails, try searching for it via
2070 http://www.google.com/search?q=PE+COFF+specification
2072 The ultimate reference for the PE format is the Winnt.h
2073 header file that comes with the Platform SDKs; as always,
2074 implementations will drift wrt their documentation.
2076 A good background article on the PE format is Matt Pietrek's
2077 March 1994 article in Microsoft System Journal (MSJ)
2078 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
2079 Win32 Portable Executable File Format." The info in there
2080 has recently been updated in a two part article in
2081 MSDN magazine, issues Feb and March 2002,
2082 "Inside Windows: An In-Depth Look into the Win32 Portable
2083 Executable File Format"
2085 John Levine's book "Linkers and Loaders" contains useful
2090 #if defined(OBJFORMAT_PEi386)
2094 typedef unsigned char UChar;
2095 typedef unsigned short UInt16;
2096 typedef unsigned int UInt32;
2103 UInt16 NumberOfSections;
2104 UInt32 TimeDateStamp;
2105 UInt32 PointerToSymbolTable;
2106 UInt32 NumberOfSymbols;
2107 UInt16 SizeOfOptionalHeader;
2108 UInt16 Characteristics;
2112 #define sizeof_COFF_header 20
2119 UInt32 VirtualAddress;
2120 UInt32 SizeOfRawData;
2121 UInt32 PointerToRawData;
2122 UInt32 PointerToRelocations;
2123 UInt32 PointerToLinenumbers;
2124 UInt16 NumberOfRelocations;
2125 UInt16 NumberOfLineNumbers;
2126 UInt32 Characteristics;
2130 #define sizeof_COFF_section 40
2137 UInt16 SectionNumber;
2140 UChar NumberOfAuxSymbols;
2144 #define sizeof_COFF_symbol 18
2149 UInt32 VirtualAddress;
2150 UInt32 SymbolTableIndex;
2155 #define sizeof_COFF_reloc 10
2158 /* From PE spec doc, section 3.3.2 */
2159 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
2160 windows.h -- for the same purpose, but I want to know what I'm
2162 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
2163 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
2164 #define MYIMAGE_FILE_DLL 0x2000
2165 #define MYIMAGE_FILE_SYSTEM 0x1000
2166 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
2167 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
2168 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
2170 /* From PE spec doc, section 5.4.2 and 5.4.4 */
2171 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
2172 #define MYIMAGE_SYM_CLASS_STATIC 3
2173 #define MYIMAGE_SYM_UNDEFINED 0
2175 /* From PE spec doc, section 4.1 */
2176 #define MYIMAGE_SCN_CNT_CODE 0x00000020
2177 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
2178 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
2180 /* From PE spec doc, section 5.2.1 */
2181 #define MYIMAGE_REL_I386_DIR32 0x0006
2182 #define MYIMAGE_REL_I386_REL32 0x0014
2185 /* We use myindex to calculate array addresses, rather than
2186 simply doing the normal subscript thing. That's because
2187 some of the above structs have sizes which are not
2188 a whole number of words. GCC rounds their sizes up to a
2189 whole number of words, which means that the address calcs
2190 arising from using normal C indexing or pointer arithmetic
2191 are just plain wrong. Sigh.
2194 myindex ( int scale, void* base, int index )
2197 ((UChar*)base) + scale * index;
2202 printName ( UChar* name, UChar* strtab )
2204 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2205 UInt32 strtab_offset = * (UInt32*)(name+4);
2206 debugBelch("%s", strtab + strtab_offset );
2209 for (i = 0; i < 8; i++) {
2210 if (name[i] == 0) break;
2211 debugBelch("%c", name[i] );
2218 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
2220 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2221 UInt32 strtab_offset = * (UInt32*)(name+4);
2222 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
2228 if (name[i] == 0) break;
2238 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
2241 /* If the string is longer than 8 bytes, look in the
2242 string table for it -- this will be correctly zero terminated.
2244 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2245 UInt32 strtab_offset = * (UInt32*)(name+4);
2246 return ((UChar*)strtab) + strtab_offset;
2248 /* Otherwise, if shorter than 8 bytes, return the original,
2249 which by defn is correctly terminated.
2251 if (name[7]==0) return name;
2252 /* The annoying case: 8 bytes. Copy into a temporary
2253 (which is never freed ...)
2255 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
2257 strncpy((char*)newstr,(char*)name,8);
2263 /* Just compares the short names (first 8 chars) */
2264 static COFF_section *
2265 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
2269 = (COFF_header*)(oc->image);
2270 COFF_section* sectab
2272 ((UChar*)(oc->image))
2273 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2275 for (i = 0; i < hdr->NumberOfSections; i++) {
2278 COFF_section* section_i
2280 myindex ( sizeof_COFF_section, sectab, i );
2281 n1 = (UChar*) &(section_i->Name);
2283 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2284 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2285 n1[6]==n2[6] && n1[7]==n2[7])
2294 zapTrailingAtSign ( UChar* sym )
2296 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2298 if (sym[0] == 0) return;
2300 while (sym[i] != 0) i++;
2303 while (j > 0 && my_isdigit(sym[j])) j--;
2304 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2309 lookupSymbolInDLLs ( UChar *lbl )
2314 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2315 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2317 if (lbl[0] == '_') {
2318 /* HACK: if the name has an initial underscore, try stripping
2319 it off & look that up first. I've yet to verify whether there's
2320 a Rule that governs whether an initial '_' *should always* be
2321 stripped off when mapping from import lib name to the DLL name.
2323 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
2325 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2329 sym = GetProcAddress(o_dll->instance, (char*)lbl);
2331 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2340 ocVerifyImage_PEi386 ( ObjectCode* oc )
2345 COFF_section* sectab;
2346 COFF_symbol* symtab;
2348 /* debugBelch("\nLOADING %s\n", oc->fileName); */
2349 hdr = (COFF_header*)(oc->image);
2350 sectab = (COFF_section*) (
2351 ((UChar*)(oc->image))
2352 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2354 symtab = (COFF_symbol*) (
2355 ((UChar*)(oc->image))
2356 + hdr->PointerToSymbolTable
2358 strtab = ((UChar*)symtab)
2359 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2361 if (hdr->Machine != 0x14c) {
2362 errorBelch("%s: Not x86 PEi386", oc->fileName);
2365 if (hdr->SizeOfOptionalHeader != 0) {
2366 errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2369 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2370 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2371 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2372 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2373 errorBelch("%s: Not a PEi386 object file", oc->fileName);
2376 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2377 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2378 errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2380 (int)(hdr->Characteristics));
2383 /* If the string table size is way crazy, this might indicate that
2384 there are more than 64k relocations, despite claims to the
2385 contrary. Hence this test. */
2386 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2388 if ( (*(UInt32*)strtab) > 600000 ) {
2389 /* Note that 600k has no special significance other than being
2390 big enough to handle the almost-2MB-sized lumps that
2391 constitute HSwin32*.o. */
2392 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2397 /* No further verification after this point; only debug printing. */
2399 IF_DEBUG(linker, i=1);
2400 if (i == 0) return 1;
2402 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2403 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2404 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2407 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
2408 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
2409 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2410 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
2411 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
2412 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
2413 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
2415 /* Print the section table. */
2417 for (i = 0; i < hdr->NumberOfSections; i++) {
2419 COFF_section* sectab_i
2421 myindex ( sizeof_COFF_section, sectab, i );
2428 printName ( sectab_i->Name, strtab );
2438 sectab_i->VirtualSize,
2439 sectab_i->VirtualAddress,
2440 sectab_i->SizeOfRawData,
2441 sectab_i->PointerToRawData,
2442 sectab_i->NumberOfRelocations,
2443 sectab_i->PointerToRelocations,
2444 sectab_i->PointerToRawData
2446 reltab = (COFF_reloc*) (
2447 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2450 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2451 /* If the relocation field (a short) has overflowed, the
2452 * real count can be found in the first reloc entry.
2454 * See Section 4.1 (last para) of the PE spec (rev6.0).
2456 COFF_reloc* rel = (COFF_reloc*)
2457 myindex ( sizeof_COFF_reloc, reltab, 0 );
2458 noRelocs = rel->VirtualAddress;
2461 noRelocs = sectab_i->NumberOfRelocations;
2465 for (; j < noRelocs; j++) {
2467 COFF_reloc* rel = (COFF_reloc*)
2468 myindex ( sizeof_COFF_reloc, reltab, j );
2470 " type 0x%-4x vaddr 0x%-8x name `",
2472 rel->VirtualAddress );
2473 sym = (COFF_symbol*)
2474 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
2475 /* Hmm..mysterious looking offset - what's it for? SOF */
2476 printName ( sym->Name, strtab -10 );
2483 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
2484 debugBelch("---START of string table---\n");
2485 for (i = 4; i < *(Int32*)strtab; i++) {
2487 debugBelch("\n"); else
2488 debugBelch("%c", strtab[i] );
2490 debugBelch("--- END of string table---\n");
2495 COFF_symbol* symtab_i;
2496 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2497 symtab_i = (COFF_symbol*)
2498 myindex ( sizeof_COFF_symbol, symtab, i );
2504 printName ( symtab_i->Name, strtab );
2513 (Int32)(symtab_i->SectionNumber),
2514 (UInt32)symtab_i->Type,
2515 (UInt32)symtab_i->StorageClass,
2516 (UInt32)symtab_i->NumberOfAuxSymbols
2518 i += symtab_i->NumberOfAuxSymbols;
2528 ocGetNames_PEi386 ( ObjectCode* oc )
2531 COFF_section* sectab;
2532 COFF_symbol* symtab;
2539 hdr = (COFF_header*)(oc->image);
2540 sectab = (COFF_section*) (
2541 ((UChar*)(oc->image))
2542 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2544 symtab = (COFF_symbol*) (
2545 ((UChar*)(oc->image))
2546 + hdr->PointerToSymbolTable
2548 strtab = ((UChar*)(oc->image))
2549 + hdr->PointerToSymbolTable
2550 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2552 /* Allocate space for any (local, anonymous) .bss sections. */
2554 for (i = 0; i < hdr->NumberOfSections; i++) {
2557 COFF_section* sectab_i
2559 myindex ( sizeof_COFF_section, sectab, i );
2560 if (0 != strcmp((char*)sectab_i->Name, ".bss")) continue;
2561 /* sof 10/05: the PE spec text isn't too clear regarding what
2562 * the SizeOfRawData field is supposed to hold for object
2563 * file sections containing just uninitialized data -- for executables,
2564 * it is supposed to be zero; unclear what it's supposed to be
2565 * for object files. However, VirtualSize is guaranteed to be
2566 * zero for object files, which definitely suggests that SizeOfRawData
2567 * will be non-zero (where else would the size of this .bss section be
2568 * stored?) Looking at the COFF_section info for incoming object files,
2569 * this certainly appears to be the case.
2571 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
2572 * object files up until now. This turned out to bite us with ghc-6.4.1's use
2573 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
2574 * variable decls into to the .bss section. (The specific function in Q which
2575 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
2577 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
2578 /* This is a non-empty .bss section. Allocate zeroed space for
2579 it, and set its PointerToRawData field such that oc->image +
2580 PointerToRawData == addr_of_zeroed_space. */
2581 bss_sz = sectab_i->VirtualSize;
2582 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
2583 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
2584 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
2585 addProddableBlock(oc, zspace, bss_sz);
2586 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
2589 /* Copy section information into the ObjectCode. */
2591 for (i = 0; i < hdr->NumberOfSections; i++) {
2597 = SECTIONKIND_OTHER;
2598 COFF_section* sectab_i
2600 myindex ( sizeof_COFF_section, sectab, i );
2601 IF_DEBUG(linker, debugBelch("section name = %s\n", sectab_i->Name ));
2604 /* I'm sure this is the Right Way to do it. However, the
2605 alternative of testing the sectab_i->Name field seems to
2606 work ok with Cygwin.
2608 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
2609 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
2610 kind = SECTIONKIND_CODE_OR_RODATA;
2613 if (0==strcmp(".text",(char*)sectab_i->Name) ||
2614 0==strcmp(".rdata",(char*)sectab_i->Name)||
2615 0==strcmp(".rodata",(char*)sectab_i->Name))
2616 kind = SECTIONKIND_CODE_OR_RODATA;
2617 if (0==strcmp(".data",(char*)sectab_i->Name) ||
2618 0==strcmp(".bss",(char*)sectab_i->Name))
2619 kind = SECTIONKIND_RWDATA;
2621 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
2622 sz = sectab_i->SizeOfRawData;
2623 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
2625 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
2626 end = start + sz - 1;
2628 if (kind == SECTIONKIND_OTHER
2629 /* Ignore sections called which contain stabs debugging
2631 && 0 != strcmp(".stab", (char*)sectab_i->Name)
2632 && 0 != strcmp(".stabstr", (char*)sectab_i->Name)
2633 /* ignore constructor section for now */
2634 && 0 != strcmp(".ctors", (char*)sectab_i->Name)
2635 /* ignore section generated from .ident */
2636 && 0!= strcmp("/4", (char*)sectab_i->Name)
2637 /* ignore unknown section that appeared in gcc 3.4.5(?) */
2638 && 0!= strcmp(".reloc", (char*)sectab_i->Name)
2640 errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", sectab_i->Name, oc->fileName);
2644 if (kind != SECTIONKIND_OTHER && end >= start) {
2645 addSection(oc, kind, start, end);
2646 addProddableBlock(oc, start, end - start + 1);
2650 /* Copy exported symbols into the ObjectCode. */
2652 oc->n_symbols = hdr->NumberOfSymbols;
2653 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2654 "ocGetNames_PEi386(oc->symbols)");
2655 /* Call me paranoid; I don't care. */
2656 for (i = 0; i < oc->n_symbols; i++)
2657 oc->symbols[i] = NULL;
2661 COFF_symbol* symtab_i;
2662 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2663 symtab_i = (COFF_symbol*)
2664 myindex ( sizeof_COFF_symbol, symtab, i );
2668 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
2669 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
2670 /* This symbol is global and defined, viz, exported */
2671 /* for MYIMAGE_SYMCLASS_EXTERNAL
2672 && !MYIMAGE_SYM_UNDEFINED,
2673 the address of the symbol is:
2674 address of relevant section + offset in section
2676 COFF_section* sectabent
2677 = (COFF_section*) myindex ( sizeof_COFF_section,
2679 symtab_i->SectionNumber-1 );
2680 addr = ((UChar*)(oc->image))
2681 + (sectabent->PointerToRawData
2685 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
2686 && symtab_i->Value > 0) {
2687 /* This symbol isn't in any section at all, ie, global bss.
2688 Allocate zeroed space for it. */
2689 addr = stgCallocBytes(1, symtab_i->Value,
2690 "ocGetNames_PEi386(non-anonymous bss)");
2691 addSection(oc, SECTIONKIND_RWDATA, addr,
2692 ((UChar*)addr) + symtab_i->Value - 1);
2693 addProddableBlock(oc, addr, symtab_i->Value);
2694 /* debugBelch("BSS section at 0x%x\n", addr); */
2697 if (addr != NULL ) {
2698 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
2699 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
2700 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
2701 ASSERT(i >= 0 && i < oc->n_symbols);
2702 /* cstring_from_COFF_symbol_name always succeeds. */
2703 oc->symbols[i] = (char*)sname;
2704 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
2708 "IGNORING symbol %d\n"
2712 printName ( symtab_i->Name, strtab );
2721 (Int32)(symtab_i->SectionNumber),
2722 (UInt32)symtab_i->Type,
2723 (UInt32)symtab_i->StorageClass,
2724 (UInt32)symtab_i->NumberOfAuxSymbols
2729 i += symtab_i->NumberOfAuxSymbols;
2738 ocResolve_PEi386 ( ObjectCode* oc )
2741 COFF_section* sectab;
2742 COFF_symbol* symtab;
2752 /* ToDo: should be variable-sized? But is at least safe in the
2753 sense of buffer-overrun-proof. */
2755 /* debugBelch("resolving for %s\n", oc->fileName); */
2757 hdr = (COFF_header*)(oc->image);
2758 sectab = (COFF_section*) (
2759 ((UChar*)(oc->image))
2760 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2762 symtab = (COFF_symbol*) (
2763 ((UChar*)(oc->image))
2764 + hdr->PointerToSymbolTable
2766 strtab = ((UChar*)(oc->image))
2767 + hdr->PointerToSymbolTable
2768 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2770 for (i = 0; i < hdr->NumberOfSections; i++) {
2771 COFF_section* sectab_i
2773 myindex ( sizeof_COFF_section, sectab, i );
2776 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2779 /* Ignore sections called which contain stabs debugging
2781 if (0 == strcmp(".stab", (char*)sectab_i->Name)
2782 || 0 == strcmp(".stabstr", (char*)sectab_i->Name)
2783 || 0 == strcmp(".ctors", (char*)sectab_i->Name))
2786 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2787 /* If the relocation field (a short) has overflowed, the
2788 * real count can be found in the first reloc entry.
2790 * See Section 4.1 (last para) of the PE spec (rev6.0).
2792 * Nov2003 update: the GNU linker still doesn't correctly
2793 * handle the generation of relocatable object files with
2794 * overflown relocations. Hence the output to warn of potential
2797 COFF_reloc* rel = (COFF_reloc*)
2798 myindex ( sizeof_COFF_reloc, reltab, 0 );
2799 noRelocs = rel->VirtualAddress;
2801 /* 10/05: we now assume (and check for) a GNU ld that is capable
2802 * of handling object files with (>2^16) of relocs.
2805 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
2810 noRelocs = sectab_i->NumberOfRelocations;
2815 for (; j < noRelocs; j++) {
2817 COFF_reloc* reltab_j
2819 myindex ( sizeof_COFF_reloc, reltab, j );
2821 /* the location to patch */
2823 ((UChar*)(oc->image))
2824 + (sectab_i->PointerToRawData
2825 + reltab_j->VirtualAddress
2826 - sectab_i->VirtualAddress )
2828 /* the existing contents of pP */
2830 /* the symbol to connect to */
2831 sym = (COFF_symbol*)
2832 myindex ( sizeof_COFF_symbol,
2833 symtab, reltab_j->SymbolTableIndex );
2836 "reloc sec %2d num %3d: type 0x%-4x "
2837 "vaddr 0x%-8x name `",
2839 (UInt32)reltab_j->Type,
2840 reltab_j->VirtualAddress );
2841 printName ( sym->Name, strtab );
2842 debugBelch("'\n" ));
2844 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
2845 COFF_section* section_sym
2846 = findPEi386SectionCalled ( oc, sym->Name );
2848 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
2851 S = ((UInt32)(oc->image))
2852 + (section_sym->PointerToRawData
2855 copyName ( sym->Name, strtab, symbol, 1000-1 );
2856 S = (UInt32) lookupSymbol( (char*)symbol );
2857 if ((void*)S != NULL) goto foundit;
2858 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
2862 checkProddableBlock(oc, pP);
2863 switch (reltab_j->Type) {
2864 case MYIMAGE_REL_I386_DIR32:
2867 case MYIMAGE_REL_I386_REL32:
2868 /* Tricky. We have to insert a displacement at
2869 pP which, when added to the PC for the _next_
2870 insn, gives the address of the target (S).
2871 Problem is to know the address of the next insn
2872 when we only know pP. We assume that this
2873 literal field is always the last in the insn,
2874 so that the address of the next insn is pP+4
2875 -- hence the constant 4.
2876 Also I don't know if A should be added, but so
2877 far it has always been zero.
2879 SOF 05/2005: 'A' (old contents of *pP) have been observed
2880 to contain values other than zero (the 'wx' object file
2881 that came with wxhaskell-0.9.4; dunno how it was compiled..).
2882 So, add displacement to old value instead of asserting
2883 A to be zero. Fixes wxhaskell-related crashes, and no other
2884 ill effects have been observed.
2886 Update: the reason why we're seeing these more elaborate
2887 relocations is due to a switch in how the NCG compiles SRTs
2888 and offsets to them from info tables. SRTs live in .(ro)data,
2889 while info tables live in .text, causing GAS to emit REL32/DISP32
2890 relocations with non-zero values. Adding the displacement is
2891 the right thing to do.
2893 *pP = S - ((UInt32)pP) - 4 + A;
2896 debugBelch("%s: unhandled PEi386 relocation type %d",
2897 oc->fileName, reltab_j->Type);
2904 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
2908 #endif /* defined(OBJFORMAT_PEi386) */
2911 /* --------------------------------------------------------------------------
2913 * ------------------------------------------------------------------------*/
2915 #if defined(OBJFORMAT_ELF)
2920 #if defined(sparc_HOST_ARCH)
2921 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
2922 #elif defined(i386_HOST_ARCH)
2923 # define ELF_TARGET_386 /* Used inside <elf.h> */
2924 #elif defined(x86_64_HOST_ARCH)
2925 # define ELF_TARGET_X64_64
2929 #if !defined(openbsd_HOST_OS)
2932 /* openbsd elf has things in different places, with diff names */
2933 # include <elf_abi.h>
2934 # include <machine/reloc.h>
2935 # define R_386_32 RELOC_32
2936 # define R_386_PC32 RELOC_PC32
2939 /* If elf.h doesn't define it */
2940 # ifndef R_X86_64_PC64
2941 # define R_X86_64_PC64 24
2945 * Define a set of types which can be used for both ELF32 and ELF64
2949 #define ELFCLASS ELFCLASS64
2950 #define Elf_Addr Elf64_Addr
2951 #define Elf_Word Elf64_Word
2952 #define Elf_Sword Elf64_Sword
2953 #define Elf_Ehdr Elf64_Ehdr
2954 #define Elf_Phdr Elf64_Phdr
2955 #define Elf_Shdr Elf64_Shdr
2956 #define Elf_Sym Elf64_Sym
2957 #define Elf_Rel Elf64_Rel
2958 #define Elf_Rela Elf64_Rela
2960 #define ELF_ST_TYPE ELF64_ST_TYPE
2963 #define ELF_ST_BIND ELF64_ST_BIND
2966 #define ELF_R_TYPE ELF64_R_TYPE
2969 #define ELF_R_SYM ELF64_R_SYM
2972 #define ELFCLASS ELFCLASS32
2973 #define Elf_Addr Elf32_Addr
2974 #define Elf_Word Elf32_Word
2975 #define Elf_Sword Elf32_Sword
2976 #define Elf_Ehdr Elf32_Ehdr
2977 #define Elf_Phdr Elf32_Phdr
2978 #define Elf_Shdr Elf32_Shdr
2979 #define Elf_Sym Elf32_Sym
2980 #define Elf_Rel Elf32_Rel
2981 #define Elf_Rela Elf32_Rela
2983 #define ELF_ST_TYPE ELF32_ST_TYPE
2986 #define ELF_ST_BIND ELF32_ST_BIND
2989 #define ELF_R_TYPE ELF32_R_TYPE
2992 #define ELF_R_SYM ELF32_R_SYM
2998 * Functions to allocate entries in dynamic sections. Currently we simply
2999 * preallocate a large number, and we don't check if a entry for the given
3000 * target already exists (a linear search is too slow). Ideally these
3001 * entries would be associated with symbols.
3004 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
3005 #define GOT_SIZE 0x20000
3006 #define FUNCTION_TABLE_SIZE 0x10000
3007 #define PLT_SIZE 0x08000
3010 static Elf_Addr got[GOT_SIZE];
3011 static unsigned int gotIndex;
3012 static Elf_Addr gp_val = (Elf_Addr)got;
3015 allocateGOTEntry(Elf_Addr target)
3019 if (gotIndex >= GOT_SIZE)
3020 barf("Global offset table overflow");
3022 entry = &got[gotIndex++];
3024 return (Elf_Addr)entry;
3028 #ifdef ELF_FUNCTION_DESC
3034 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
3035 static unsigned int functionTableIndex;
3038 allocateFunctionDesc(Elf_Addr target)
3040 FunctionDesc *entry;
3042 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
3043 barf("Function table overflow");
3045 entry = &functionTable[functionTableIndex++];
3047 entry->gp = (Elf_Addr)gp_val;
3048 return (Elf_Addr)entry;
3052 copyFunctionDesc(Elf_Addr target)
3054 FunctionDesc *olddesc = (FunctionDesc *)target;
3055 FunctionDesc *newdesc;
3057 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
3058 newdesc->gp = olddesc->gp;
3059 return (Elf_Addr)newdesc;
3066 unsigned char code[sizeof(plt_code)];
3070 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
3072 PLTEntry *plt = (PLTEntry *)oc->plt;
3075 if (oc->pltIndex >= PLT_SIZE)
3076 barf("Procedure table overflow");
3078 entry = &plt[oc->pltIndex++];
3079 memcpy(entry->code, plt_code, sizeof(entry->code));
3080 PLT_RELOC(entry->code, target);
3081 return (Elf_Addr)entry;
3087 return (PLT_SIZE * sizeof(PLTEntry));
3093 * Generic ELF functions
3097 findElfSection ( void* objImage, Elf_Word sh_type )
3099 char* ehdrC = (char*)objImage;
3100 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3101 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
3102 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3106 for (i = 0; i < ehdr->e_shnum; i++) {
3107 if (shdr[i].sh_type == sh_type
3108 /* Ignore the section header's string table. */
3109 && i != ehdr->e_shstrndx
3110 /* Ignore string tables named .stabstr, as they contain
3112 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3114 ptr = ehdrC + shdr[i].sh_offset;
3122 ocVerifyImage_ELF ( ObjectCode* oc )
3126 int i, j, nent, nstrtab, nsymtabs;
3130 char* ehdrC = (char*)(oc->image);
3131 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3133 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
3134 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
3135 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
3136 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
3137 errorBelch("%s: not an ELF object", oc->fileName);
3141 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
3142 errorBelch("%s: unsupported ELF format", oc->fileName);
3146 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
3147 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
3149 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
3150 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
3152 errorBelch("%s: unknown endiannness", oc->fileName);
3156 if (ehdr->e_type != ET_REL) {
3157 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
3160 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
3162 IF_DEBUG(linker,debugBelch( "Architecture is " ));
3163 switch (ehdr->e_machine) {
3164 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
3165 #ifdef EM_SPARC32PLUS
3166 case EM_SPARC32PLUS:
3168 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
3170 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
3172 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
3174 case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
3175 #elif defined(EM_AMD64)
3176 case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
3178 default: IF_DEBUG(linker,debugBelch( "unknown" ));
3179 errorBelch("%s: unknown architecture (e_machine == %d)"
3180 , oc->fileName, ehdr->e_machine);
3184 IF_DEBUG(linker,debugBelch(
3185 "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
3186 (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
3188 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
3190 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3192 if (ehdr->e_shstrndx == SHN_UNDEF) {
3193 errorBelch("%s: no section header string table", oc->fileName);
3196 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
3198 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3201 for (i = 0; i < ehdr->e_shnum; i++) {
3202 IF_DEBUG(linker,debugBelch("%2d: ", i ));
3203 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
3204 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
3205 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
3206 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
3207 ehdrC + shdr[i].sh_offset,
3208 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
3210 if (shdr[i].sh_type == SHT_REL) {
3211 IF_DEBUG(linker,debugBelch("Rel " ));
3212 } else if (shdr[i].sh_type == SHT_RELA) {
3213 IF_DEBUG(linker,debugBelch("RelA " ));
3215 IF_DEBUG(linker,debugBelch(" "));
3218 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
3222 IF_DEBUG(linker,debugBelch( "\nString tables" ));
3225 for (i = 0; i < ehdr->e_shnum; i++) {
3226 if (shdr[i].sh_type == SHT_STRTAB
3227 /* Ignore the section header's string table. */
3228 && i != ehdr->e_shstrndx
3229 /* Ignore string tables named .stabstr, as they contain
3231 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3233 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
3234 strtab = ehdrC + shdr[i].sh_offset;
3239 errorBelch("%s: no string tables, or too many", oc->fileName);
3244 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
3245 for (i = 0; i < ehdr->e_shnum; i++) {
3246 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3247 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
3249 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3250 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3251 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%ld rem)\n",
3253 (long)shdr[i].sh_size % sizeof(Elf_Sym)
3255 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
3256 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
3259 for (j = 0; j < nent; j++) {
3260 IF_DEBUG(linker,debugBelch(" %2d ", j ));
3261 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
3262 (int)stab[j].st_shndx,
3263 (int)stab[j].st_size,
3264 (char*)stab[j].st_value ));
3266 IF_DEBUG(linker,debugBelch("type=" ));
3267 switch (ELF_ST_TYPE(stab[j].st_info)) {
3268 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
3269 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
3270 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
3271 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
3272 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
3273 default: IF_DEBUG(linker,debugBelch("? " )); break;
3275 IF_DEBUG(linker,debugBelch(" " ));
3277 IF_DEBUG(linker,debugBelch("bind=" ));
3278 switch (ELF_ST_BIND(stab[j].st_info)) {
3279 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
3280 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
3281 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
3282 default: IF_DEBUG(linker,debugBelch("? " )); break;
3284 IF_DEBUG(linker,debugBelch(" " ));
3286 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3290 if (nsymtabs == 0) {
3291 errorBelch("%s: didn't find any symbol tables", oc->fileName);
3298 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3302 if (hdr->sh_type == SHT_PROGBITS
3303 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3304 /* .text-style section */
3305 return SECTIONKIND_CODE_OR_RODATA;
3308 if (hdr->sh_type == SHT_PROGBITS
3309 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3310 /* .data-style section */
3311 return SECTIONKIND_RWDATA;
3314 if (hdr->sh_type == SHT_PROGBITS
3315 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3316 /* .rodata-style section */
3317 return SECTIONKIND_CODE_OR_RODATA;
3320 if (hdr->sh_type == SHT_NOBITS
3321 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3322 /* .bss-style section */
3324 return SECTIONKIND_RWDATA;
3327 return SECTIONKIND_OTHER;
3332 ocGetNames_ELF ( ObjectCode* oc )
3337 char* ehdrC = (char*)(oc->image);
3338 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3339 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
3340 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3342 ASSERT(symhash != NULL);
3345 errorBelch("%s: no strtab", oc->fileName);
3350 for (i = 0; i < ehdr->e_shnum; i++) {
3351 /* Figure out what kind of section it is. Logic derived from
3352 Figure 1.14 ("Special Sections") of the ELF document
3353 ("Portable Formats Specification, Version 1.1"). */
3355 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
3357 if (is_bss && shdr[i].sh_size > 0) {
3358 /* This is a non-empty .bss section. Allocate zeroed space for
3359 it, and set its .sh_offset field such that
3360 ehdrC + .sh_offset == addr_of_zeroed_space. */
3361 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3362 "ocGetNames_ELF(BSS)");
3363 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3365 debugBelch("BSS section at 0x%x, size %d\n",
3366 zspace, shdr[i].sh_size);
3370 /* fill in the section info */
3371 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3372 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3373 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3374 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3377 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3379 /* copy stuff into this module's object symbol table */
3380 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3381 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3383 oc->n_symbols = nent;
3384 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3385 "ocGetNames_ELF(oc->symbols)");
3387 for (j = 0; j < nent; j++) {
3389 char isLocal = FALSE; /* avoids uninit-var warning */
3391 char* nm = strtab + stab[j].st_name;
3392 int secno = stab[j].st_shndx;
3394 /* Figure out if we want to add it; if so, set ad to its
3395 address. Otherwise leave ad == NULL. */
3397 if (secno == SHN_COMMON) {
3399 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3401 debugBelch("COMMON symbol, size %d name %s\n",
3402 stab[j].st_size, nm);
3404 /* Pointless to do addProddableBlock() for this area,
3405 since the linker should never poke around in it. */
3408 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3409 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3411 /* and not an undefined symbol */
3412 && stab[j].st_shndx != SHN_UNDEF
3413 /* and not in a "special section" */
3414 && stab[j].st_shndx < SHN_LORESERVE
3416 /* and it's a not a section or string table or anything silly */
3417 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
3418 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
3419 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
3422 /* Section 0 is the undefined section, hence > and not >=. */
3423 ASSERT(secno > 0 && secno < ehdr->e_shnum);
3425 if (shdr[secno].sh_type == SHT_NOBITS) {
3426 debugBelch(" BSS symbol, size %d off %d name %s\n",
3427 stab[j].st_size, stab[j].st_value, nm);
3430 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
3431 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
3434 #ifdef ELF_FUNCTION_DESC
3435 /* dlsym() and the initialisation table both give us function
3436 * descriptors, so to be consistent we store function descriptors
3437 * in the symbol table */
3438 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
3439 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
3441 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s\n",
3442 ad, oc->fileName, nm ));
3447 /* And the decision is ... */
3451 oc->symbols[j] = nm;
3454 /* Ignore entirely. */
3456 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
3460 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
3461 strtab + stab[j].st_name ));
3464 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
3465 (int)ELF_ST_BIND(stab[j].st_info),
3466 (int)ELF_ST_TYPE(stab[j].st_info),
3467 (int)stab[j].st_shndx,
3468 strtab + stab[j].st_name
3471 oc->symbols[j] = NULL;
3480 /* Do ELF relocations which lack an explicit addend. All x86-linux
3481 relocations appear to be of this form. */
3483 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
3484 Elf_Shdr* shdr, int shnum,
3485 Elf_Sym* stab, char* strtab )
3490 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
3491 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
3492 int target_shndx = shdr[shnum].sh_info;
3493 int symtab_shndx = shdr[shnum].sh_link;
3495 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3496 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
3497 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3498 target_shndx, symtab_shndx ));
3500 /* Skip sections that we're not interested in. */
3503 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
3504 if (kind == SECTIONKIND_OTHER) {
3505 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
3510 for (j = 0; j < nent; j++) {
3511 Elf_Addr offset = rtab[j].r_offset;
3512 Elf_Addr info = rtab[j].r_info;
3514 Elf_Addr P = ((Elf_Addr)targ) + offset;
3515 Elf_Word* pP = (Elf_Word*)P;
3520 StgStablePtr stablePtr;
3523 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
3524 j, (void*)offset, (void*)info ));
3526 IF_DEBUG(linker,debugBelch( " ZERO" ));
3529 Elf_Sym sym = stab[ELF_R_SYM(info)];
3530 /* First see if it is a local symbol. */
3531 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3532 /* Yes, so we can get the address directly from the ELF symbol
3534 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3536 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3537 + stab[ELF_R_SYM(info)].st_value);
3540 symbol = strtab + sym.st_name;
3541 stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
3542 if (NULL == stablePtr) {
3543 /* No, so look up the name in our global table. */
3544 S_tmp = lookupSymbol( symbol );
3545 S = (Elf_Addr)S_tmp;
3547 stableVal = deRefStablePtr( stablePtr );
3549 S = (Elf_Addr)S_tmp;
3553 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3556 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
3559 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
3560 (void*)P, (void*)S, (void*)A ));
3561 checkProddableBlock ( oc, pP );
3565 switch (ELF_R_TYPE(info)) {
3566 # ifdef i386_HOST_ARCH
3567 case R_386_32: *pP = value; break;
3568 case R_386_PC32: *pP = value - P; break;
3571 errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
3572 oc->fileName, (lnat)ELF_R_TYPE(info));
3580 /* Do ELF relocations for which explicit addends are supplied.
3581 sparc-solaris relocations appear to be of this form. */
3583 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
3584 Elf_Shdr* shdr, int shnum,
3585 Elf_Sym* stab, char* strtab )
3588 char *symbol = NULL;
3590 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
3591 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
3592 int target_shndx = shdr[shnum].sh_info;
3593 int symtab_shndx = shdr[shnum].sh_link;
3595 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3596 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
3597 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3598 target_shndx, symtab_shndx ));
3600 for (j = 0; j < nent; j++) {
3601 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3602 /* This #ifdef only serves to avoid unused-var warnings. */
3603 Elf_Addr offset = rtab[j].r_offset;
3604 Elf_Addr P = targ + offset;
3606 Elf_Addr info = rtab[j].r_info;
3607 Elf_Addr A = rtab[j].r_addend;
3611 # if defined(sparc_HOST_ARCH)
3612 Elf_Word* pP = (Elf_Word*)P;
3614 # elif defined(powerpc_HOST_ARCH)
3618 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
3619 j, (void*)offset, (void*)info,
3622 IF_DEBUG(linker,debugBelch( " ZERO" ));
3625 Elf_Sym sym = stab[ELF_R_SYM(info)];
3626 /* First see if it is a local symbol. */
3627 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3628 /* Yes, so we can get the address directly from the ELF symbol
3630 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3632 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3633 + stab[ELF_R_SYM(info)].st_value);
3634 #ifdef ELF_FUNCTION_DESC
3635 /* Make a function descriptor for this function */
3636 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
3637 S = allocateFunctionDesc(S + A);
3642 /* No, so look up the name in our global table. */
3643 symbol = strtab + sym.st_name;
3644 S_tmp = lookupSymbol( symbol );
3645 S = (Elf_Addr)S_tmp;
3647 #ifdef ELF_FUNCTION_DESC
3648 /* If a function, already a function descriptor - we would
3649 have to copy it to add an offset. */
3650 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
3651 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
3655 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3658 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
3661 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
3662 (void*)P, (void*)S, (void*)A ));
3663 /* checkProddableBlock ( oc, (void*)P ); */
3667 switch (ELF_R_TYPE(info)) {
3668 # if defined(sparc_HOST_ARCH)
3669 case R_SPARC_WDISP30:
3670 w1 = *pP & 0xC0000000;
3671 w2 = (Elf_Word)((value - P) >> 2);
3672 ASSERT((w2 & 0xC0000000) == 0);
3677 w1 = *pP & 0xFFC00000;
3678 w2 = (Elf_Word)(value >> 10);
3679 ASSERT((w2 & 0xFFC00000) == 0);
3685 w2 = (Elf_Word)(value & 0x3FF);
3686 ASSERT((w2 & ~0x3FF) == 0);
3691 /* According to the Sun documentation:
3693 This relocation type resembles R_SPARC_32, except it refers to an
3694 unaligned word. That is, the word to be relocated must be treated
3695 as four separate bytes with arbitrary alignment, not as a word
3696 aligned according to the architecture requirements.
3699 w2 = (Elf_Word)value;
3701 // SPARC doesn't do misaligned writes of 32 bit words,
3702 // so we have to do this one byte-at-a-time.
3703 char *pPc = (char*)pP;
3704 pPc[0] = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
3705 pPc[1] = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
3706 pPc[2] = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
3707 pPc[3] = (char) ((Elf_Word)(w2 & 0x000000ff));
3711 w2 = (Elf_Word)value;
3714 # elif defined(powerpc_HOST_ARCH)
3715 case R_PPC_ADDR16_LO:
3716 *(Elf32_Half*) P = value;
3719 case R_PPC_ADDR16_HI:
3720 *(Elf32_Half*) P = value >> 16;
3723 case R_PPC_ADDR16_HA:
3724 *(Elf32_Half*) P = (value + 0x8000) >> 16;
3728 *(Elf32_Word *) P = value;
3732 *(Elf32_Word *) P = value - P;
3738 if( delta << 6 >> 6 != delta )
3740 value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
3744 if( value == 0 || delta << 6 >> 6 != delta )
3746 barf( "Unable to make SymbolExtra for #%d",
3752 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
3753 | (delta & 0x3fffffc);
3757 #if x86_64_HOST_ARCH
3759 *(Elf64_Xword *)P = value;
3764 StgInt64 off = value - P;
3765 if (off >= 0x7fffffffL || off < -0x80000000L) {
3766 #if X86_64_ELF_NONPIC_HACK
3767 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3769 off = pltAddress + A - P;
3771 barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3772 symbol, off, oc->fileName );
3775 *(Elf64_Word *)P = (Elf64_Word)off;
3781 StgInt64 off = value - P;
3782 *(Elf64_Word *)P = (Elf64_Word)off;
3787 if (value >= 0x7fffffffL) {
3788 #if X86_64_ELF_NONPIC_HACK
3789 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3791 value = pltAddress + A;
3793 barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3794 symbol, value, oc->fileName );
3797 *(Elf64_Word *)P = (Elf64_Word)value;
3801 if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
3802 #if X86_64_ELF_NONPIC_HACK
3803 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3805 value = pltAddress + A;
3807 barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3808 symbol, value, oc->fileName );
3811 *(Elf64_Sword *)P = (Elf64_Sword)value;
3814 case R_X86_64_GOTPCREL:
3816 StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
3817 StgInt64 off = gotAddress + A - P;
3818 *(Elf64_Word *)P = (Elf64_Word)off;
3822 case R_X86_64_PLT32:
3824 StgInt64 off = value - P;
3825 if (off >= 0x7fffffffL || off < -0x80000000L) {
3826 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3828 off = pltAddress + A - P;
3830 *(Elf64_Word *)P = (Elf64_Word)off;
3836 errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
3837 oc->fileName, (lnat)ELF_R_TYPE(info));
3846 ocResolve_ELF ( ObjectCode* oc )
3850 Elf_Sym* stab = NULL;
3851 char* ehdrC = (char*)(oc->image);
3852 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
3853 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3855 /* first find "the" symbol table */
3856 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
3858 /* also go find the string table */
3859 strtab = findElfSection ( ehdrC, SHT_STRTAB );
3861 if (stab == NULL || strtab == NULL) {
3862 errorBelch("%s: can't find string or symbol table", oc->fileName);
3866 /* Process the relocation sections. */
3867 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
3868 if (shdr[shnum].sh_type == SHT_REL) {
3869 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
3870 shnum, stab, strtab );
3874 if (shdr[shnum].sh_type == SHT_RELA) {
3875 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
3876 shnum, stab, strtab );
3881 #if defined(powerpc_HOST_ARCH)
3882 ocFlushInstructionCache( oc );
3889 * PowerPC & X86_64 ELF specifics
3892 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3894 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
3900 ehdr = (Elf_Ehdr *) oc->image;
3901 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
3903 for( i = 0; i < ehdr->e_shnum; i++ )
3904 if( shdr[i].sh_type == SHT_SYMTAB )
3907 if( i == ehdr->e_shnum )
3909 errorBelch( "This ELF file contains no symtab" );
3913 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
3915 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
3916 (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
3921 return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
3924 #endif /* powerpc */
3928 /* --------------------------------------------------------------------------
3930 * ------------------------------------------------------------------------*/
3932 #if defined(OBJFORMAT_MACHO)
3935 Support for MachO linking on Darwin/MacOS X
3936 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
3938 I hereby formally apologize for the hackish nature of this code.
3939 Things that need to be done:
3940 *) implement ocVerifyImage_MachO
3941 *) add still more sanity checks.
3944 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
3945 #define mach_header mach_header_64
3946 #define segment_command segment_command_64
3947 #define section section_64
3948 #define nlist nlist_64
3951 #ifdef powerpc_HOST_ARCH
3952 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
3954 struct mach_header *header = (struct mach_header *) oc->image;
3955 struct load_command *lc = (struct load_command *) (header + 1);
3958 for( i = 0; i < header->ncmds; i++ )
3960 if( lc->cmd == LC_SYMTAB )
3962 // Find out the first and last undefined external
3963 // symbol, so we don't have to allocate too many
3965 struct symtab_command *symLC = (struct symtab_command *) lc;
3966 unsigned min = symLC->nsyms, max = 0;
3967 struct nlist *nlist =
3968 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
3970 for(i=0;i<symLC->nsyms;i++)
3972 if(nlist[i].n_type & N_STAB)
3974 else if(nlist[i].n_type & N_EXT)
3976 if((nlist[i].n_type & N_TYPE) == N_UNDF
3977 && (nlist[i].n_value == 0))
3987 return ocAllocateSymbolExtras(oc, max - min + 1, min);
3992 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3994 return ocAllocateSymbolExtras(oc,0,0);
3997 #ifdef x86_64_HOST_ARCH
3998 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4000 struct mach_header *header = (struct mach_header *) oc->image;
4001 struct load_command *lc = (struct load_command *) (header + 1);
4004 for( i = 0; i < header->ncmds; i++ )
4006 if( lc->cmd == LC_SYMTAB )
4008 // Just allocate one entry for every symbol
4009 struct symtab_command *symLC = (struct symtab_command *) lc;
4011 return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
4014 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4016 return ocAllocateSymbolExtras(oc,0,0);
4020 static int ocVerifyImage_MachO(ObjectCode* oc)
4022 char *image = (char*) oc->image;
4023 struct mach_header *header = (struct mach_header*) image;
4025 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
4026 if(header->magic != MH_MAGIC_64)
4029 if(header->magic != MH_MAGIC)
4032 // FIXME: do some more verifying here
4036 static int resolveImports(
4039 struct symtab_command *symLC,
4040 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
4041 unsigned long *indirectSyms,
4042 struct nlist *nlist)
4045 size_t itemSize = 4;
4048 int isJumpTable = 0;
4049 if(!strcmp(sect->sectname,"__jump_table"))
4053 ASSERT(sect->reserved2 == itemSize);
4057 for(i=0; i*itemSize < sect->size;i++)
4059 // according to otool, reserved1 contains the first index into the indirect symbol table
4060 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
4061 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4064 if((symbol->n_type & N_TYPE) == N_UNDF
4065 && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
4066 addr = (void*) (symbol->n_value);
4068 addr = lookupSymbol(nm);
4071 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
4079 checkProddableBlock(oc,image + sect->offset + i*itemSize);
4080 *(image + sect->offset + i*itemSize) = 0xe9; // jmp
4081 *(unsigned*)(image + sect->offset + i*itemSize + 1)
4082 = (char*)addr - (image + sect->offset + i*itemSize + 5);
4087 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
4088 ((void**)(image + sect->offset))[i] = addr;
4095 static unsigned long relocateAddress(
4098 struct section* sections,
4099 unsigned long address)
4102 for(i = 0; i < nSections; i++)
4104 if(sections[i].addr <= address
4105 && address < sections[i].addr + sections[i].size)
4107 return (unsigned long)oc->image
4108 + sections[i].offset + address - sections[i].addr;
4111 barf("Invalid Mach-O file:"
4112 "Address out of bounds while relocating object file");
4116 static int relocateSection(
4119 struct symtab_command *symLC, struct nlist *nlist,
4120 int nSections, struct section* sections, struct section *sect)
4122 struct relocation_info *relocs;
4125 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
4127 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
4129 else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
4131 else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
4135 relocs = (struct relocation_info*) (image + sect->reloff);
4139 #ifdef x86_64_HOST_ARCH
4140 struct relocation_info *reloc = &relocs[i];
4142 char *thingPtr = image + sect->offset + reloc->r_address;
4144 /* We shouldn't need to initialise this, but gcc on OS X 64 bit
4145 complains that it may be used uninitialized if we don't */
4148 int type = reloc->r_type;
4150 checkProddableBlock(oc,thingPtr);
4151 switch(reloc->r_length)
4154 thing = *(uint8_t*)thingPtr;
4155 baseValue = (uint64_t)thingPtr + 1;
4158 thing = *(uint16_t*)thingPtr;
4159 baseValue = (uint64_t)thingPtr + 2;
4162 thing = *(uint32_t*)thingPtr;
4163 baseValue = (uint64_t)thingPtr + 4;
4166 thing = *(uint64_t*)thingPtr;
4167 baseValue = (uint64_t)thingPtr + 8;
4170 barf("Unknown size.");
4173 if(type == X86_64_RELOC_GOT
4174 || type == X86_64_RELOC_GOT_LOAD)
4176 ASSERT(reloc->r_extern);
4177 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)->addr;
4179 type = X86_64_RELOC_SIGNED;
4181 else if(reloc->r_extern)
4183 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4184 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4185 if(symbol->n_value == 0)
4186 value = (uint64_t) lookupSymbol(nm);
4188 value = relocateAddress(oc, nSections, sections,
4193 value = sections[reloc->r_symbolnum-1].offset
4194 - sections[reloc->r_symbolnum-1].addr
4198 if(type == X86_64_RELOC_BRANCH)
4200 if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
4202 ASSERT(reloc->r_extern);
4203 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
4206 ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
4207 type = X86_64_RELOC_SIGNED;
4212 case X86_64_RELOC_UNSIGNED:
4213 ASSERT(!reloc->r_pcrel);
4216 case X86_64_RELOC_SIGNED:
4217 case X86_64_RELOC_SIGNED_1:
4218 case X86_64_RELOC_SIGNED_2:
4219 case X86_64_RELOC_SIGNED_4:
4220 ASSERT(reloc->r_pcrel);
4221 thing += value - baseValue;
4223 case X86_64_RELOC_SUBTRACTOR:
4224 ASSERT(!reloc->r_pcrel);
4228 barf("unkown relocation");
4231 switch(reloc->r_length)
4234 *(uint8_t*)thingPtr = thing;
4237 *(uint16_t*)thingPtr = thing;
4240 *(uint32_t*)thingPtr = thing;
4243 *(uint64_t*)thingPtr = thing;
4247 if(relocs[i].r_address & R_SCATTERED)
4249 struct scattered_relocation_info *scat =
4250 (struct scattered_relocation_info*) &relocs[i];
4254 if(scat->r_length == 2)
4256 unsigned long word = 0;
4257 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
4258 checkProddableBlock(oc,wordPtr);
4260 // Note on relocation types:
4261 // i386 uses the GENERIC_RELOC_* types,
4262 // while ppc uses special PPC_RELOC_* types.
4263 // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
4264 // in both cases, all others are different.
4265 // Therefore, we use GENERIC_RELOC_VANILLA
4266 // and GENERIC_RELOC_PAIR instead of the PPC variants,
4267 // and use #ifdefs for the other types.
4269 // Step 1: Figure out what the relocated value should be
4270 if(scat->r_type == GENERIC_RELOC_VANILLA)
4272 word = *wordPtr + (unsigned long) relocateAddress(
4279 #ifdef powerpc_HOST_ARCH
4280 else if(scat->r_type == PPC_RELOC_SECTDIFF
4281 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4282 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4283 || scat->r_type == PPC_RELOC_HA16_SECTDIFF)
4285 else if(scat->r_type == GENERIC_RELOC_SECTDIFF
4286 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4289 struct scattered_relocation_info *pair =
4290 (struct scattered_relocation_info*) &relocs[i+1];
4292 if(!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR)
4293 barf("Invalid Mach-O file: "
4294 "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4296 word = (unsigned long)
4297 (relocateAddress(oc, nSections, sections, scat->r_value)
4298 - relocateAddress(oc, nSections, sections, pair->r_value));
4301 #ifdef powerpc_HOST_ARCH
4302 else if(scat->r_type == PPC_RELOC_HI16
4303 || scat->r_type == PPC_RELOC_LO16
4304 || scat->r_type == PPC_RELOC_HA16
4305 || scat->r_type == PPC_RELOC_LO14)
4306 { // these are generated by label+offset things
4307 struct relocation_info *pair = &relocs[i+1];
4308 if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
4309 barf("Invalid Mach-O file: "
4310 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4312 if(scat->r_type == PPC_RELOC_LO16)
4314 word = ((unsigned short*) wordPtr)[1];
4315 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4317 else if(scat->r_type == PPC_RELOC_LO14)
4319 barf("Unsupported Relocation: PPC_RELOC_LO14");
4320 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4321 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4323 else if(scat->r_type == PPC_RELOC_HI16)
4325 word = ((unsigned short*) wordPtr)[1] << 16;
4326 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4328 else if(scat->r_type == PPC_RELOC_HA16)
4330 word = ((unsigned short*) wordPtr)[1] << 16;
4331 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4335 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
4343 barf ("Don't know how to handle this Mach-O "
4344 "scattered relocation entry: "
4345 "object file %s; entry type %ld; "
4347 oc->fileName, scat->r_type, scat->r_address);
4351 #ifdef powerpc_HOST_ARCH
4352 if(scat->r_type == GENERIC_RELOC_VANILLA
4353 || scat->r_type == PPC_RELOC_SECTDIFF)
4355 if(scat->r_type == GENERIC_RELOC_VANILLA
4356 || scat->r_type == GENERIC_RELOC_SECTDIFF
4357 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4362 #ifdef powerpc_HOST_ARCH
4363 else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
4365 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4367 else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
4369 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4371 else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
4373 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4374 + ((word & (1<<15)) ? 1 : 0);
4380 barf("Can't handle Mach-O scattered relocation entry "
4381 "with this r_length tag: "
4382 "object file %s; entry type %ld; "
4383 "r_length tag %ld; address %#lx\n",
4384 oc->fileName, scat->r_type, scat->r_length,
4389 else /* scat->r_pcrel */
4391 barf("Don't know how to handle *PC-relative* Mach-O "
4392 "scattered relocation entry: "
4393 "object file %s; entry type %ld; address %#lx\n",
4394 oc->fileName, scat->r_type, scat->r_address);
4399 else /* !(relocs[i].r_address & R_SCATTERED) */
4401 struct relocation_info *reloc = &relocs[i];
4402 if(reloc->r_pcrel && !reloc->r_extern)
4405 if(reloc->r_length == 2)
4407 unsigned long word = 0;
4408 #ifdef powerpc_HOST_ARCH
4409 unsigned long jumpIsland = 0;
4410 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
4411 // to avoid warning and to catch
4415 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
4416 checkProddableBlock(oc,wordPtr);
4418 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4422 #ifdef powerpc_HOST_ARCH
4423 else if(reloc->r_type == PPC_RELOC_LO16)
4425 word = ((unsigned short*) wordPtr)[1];
4426 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4428 else if(reloc->r_type == PPC_RELOC_HI16)
4430 word = ((unsigned short*) wordPtr)[1] << 16;
4431 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4433 else if(reloc->r_type == PPC_RELOC_HA16)
4435 word = ((unsigned short*) wordPtr)[1] << 16;
4436 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4438 else if(reloc->r_type == PPC_RELOC_BR24)
4441 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
4446 barf("Can't handle this Mach-O relocation entry "
4448 "object file %s; entry type %ld; address %#lx\n",
4449 oc->fileName, reloc->r_type, reloc->r_address);
4453 if(!reloc->r_extern)
4456 sections[reloc->r_symbolnum-1].offset
4457 - sections[reloc->r_symbolnum-1].addr
4464 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4465 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4466 void *symbolAddress = lookupSymbol(nm);
4469 errorBelch("\nunknown symbol `%s'", nm);
4475 #ifdef powerpc_HOST_ARCH
4476 // In the .o file, this should be a relative jump to NULL
4477 // and we'll change it to a relative jump to the symbol
4478 ASSERT(word + reloc->r_address == 0);
4479 jumpIsland = (unsigned long)
4480 &makeSymbolExtra(oc,
4482 (unsigned long) symbolAddress)
4486 offsetToJumpIsland = word + jumpIsland
4487 - (((long)image) + sect->offset - sect->addr);
4490 word += (unsigned long) symbolAddress
4491 - (((long)image) + sect->offset - sect->addr);
4495 word += (unsigned long) symbolAddress;
4499 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4504 #ifdef powerpc_HOST_ARCH
4505 else if(reloc->r_type == PPC_RELOC_LO16)
4507 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4510 else if(reloc->r_type == PPC_RELOC_HI16)
4512 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4515 else if(reloc->r_type == PPC_RELOC_HA16)
4517 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4518 + ((word & (1<<15)) ? 1 : 0);
4521 else if(reloc->r_type == PPC_RELOC_BR24)
4523 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4525 // The branch offset is too large.
4526 // Therefore, we try to use a jump island.
4529 barf("unconditional relative branch out of range: "
4530 "no jump island available");
4533 word = offsetToJumpIsland;
4534 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4535 barf("unconditional relative branch out of range: "
4536 "jump island out of range");
4538 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
4545 barf("Can't handle Mach-O relocation entry (not scattered) "
4546 "with this r_length tag: "
4547 "object file %s; entry type %ld; "
4548 "r_length tag %ld; address %#lx\n",
4549 oc->fileName, reloc->r_type, reloc->r_length,
4559 static int ocGetNames_MachO(ObjectCode* oc)
4561 char *image = (char*) oc->image;
4562 struct mach_header *header = (struct mach_header*) image;
4563 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4564 unsigned i,curSymbol = 0;
4565 struct segment_command *segLC = NULL;
4566 struct section *sections;
4567 struct symtab_command *symLC = NULL;
4568 struct nlist *nlist;
4569 unsigned long commonSize = 0;
4570 char *commonStorage = NULL;
4571 unsigned long commonCounter;
4573 for(i=0;i<header->ncmds;i++)
4575 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4576 segLC = (struct segment_command*) lc;
4577 else if(lc->cmd == LC_SYMTAB)
4578 symLC = (struct symtab_command*) lc;
4579 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4582 sections = (struct section*) (segLC+1);
4583 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4587 barf("ocGetNames_MachO: no segment load command");
4589 for(i=0;i<segLC->nsects;i++)
4591 if(sections[i].size == 0)
4594 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
4596 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
4597 "ocGetNames_MachO(common symbols)");
4598 sections[i].offset = zeroFillArea - image;
4601 if(!strcmp(sections[i].sectname,"__text"))
4602 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
4603 (void*) (image + sections[i].offset),
4604 (void*) (image + sections[i].offset + sections[i].size));
4605 else if(!strcmp(sections[i].sectname,"__const"))
4606 addSection(oc, SECTIONKIND_RWDATA,
4607 (void*) (image + sections[i].offset),
4608 (void*) (image + sections[i].offset + sections[i].size));
4609 else if(!strcmp(sections[i].sectname,"__data"))
4610 addSection(oc, SECTIONKIND_RWDATA,
4611 (void*) (image + sections[i].offset),
4612 (void*) (image + sections[i].offset + sections[i].size));
4613 else if(!strcmp(sections[i].sectname,"__bss")
4614 || !strcmp(sections[i].sectname,"__common"))
4615 addSection(oc, SECTIONKIND_RWDATA,
4616 (void*) (image + sections[i].offset),
4617 (void*) (image + sections[i].offset + sections[i].size));
4619 addProddableBlock(oc, (void*) (image + sections[i].offset),
4623 // count external symbols defined here
4627 for(i=0;i<symLC->nsyms;i++)
4629 if(nlist[i].n_type & N_STAB)
4631 else if(nlist[i].n_type & N_EXT)
4633 if((nlist[i].n_type & N_TYPE) == N_UNDF
4634 && (nlist[i].n_value != 0))
4636 commonSize += nlist[i].n_value;
4639 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4644 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
4645 "ocGetNames_MachO(oc->symbols)");
4649 for(i=0;i<symLC->nsyms;i++)
4651 if(nlist[i].n_type & N_STAB)
4653 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4655 if(nlist[i].n_type & N_EXT)
4657 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4658 if((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm))
4659 ; // weak definition, and we already have a definition
4662 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4664 + sections[nlist[i].n_sect-1].offset
4665 - sections[nlist[i].n_sect-1].addr
4666 + nlist[i].n_value);
4667 oc->symbols[curSymbol++] = nm;
4674 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
4675 commonCounter = (unsigned long)commonStorage;
4678 for(i=0;i<symLC->nsyms;i++)
4680 if((nlist[i].n_type & N_TYPE) == N_UNDF
4681 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
4683 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4684 unsigned long sz = nlist[i].n_value;
4686 nlist[i].n_value = commonCounter;
4688 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4689 (void*)commonCounter);
4690 oc->symbols[curSymbol++] = nm;
4692 commonCounter += sz;
4699 static int ocResolve_MachO(ObjectCode* oc)
4701 char *image = (char*) oc->image;
4702 struct mach_header *header = (struct mach_header*) image;
4703 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4705 struct segment_command *segLC = NULL;
4706 struct section *sections;
4707 struct symtab_command *symLC = NULL;
4708 struct dysymtab_command *dsymLC = NULL;
4709 struct nlist *nlist;
4711 for(i=0;i<header->ncmds;i++)
4713 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4714 segLC = (struct segment_command*) lc;
4715 else if(lc->cmd == LC_SYMTAB)
4716 symLC = (struct symtab_command*) lc;
4717 else if(lc->cmd == LC_DYSYMTAB)
4718 dsymLC = (struct dysymtab_command*) lc;
4719 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4722 sections = (struct section*) (segLC+1);
4723 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4728 unsigned long *indirectSyms
4729 = (unsigned long*) (image + dsymLC->indirectsymoff);
4731 for(i=0;i<segLC->nsects;i++)
4733 if( !strcmp(sections[i].sectname,"__la_symbol_ptr")
4734 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
4735 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
4737 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4740 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
4741 || !strcmp(sections[i].sectname,"__pointers"))
4743 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4746 else if(!strcmp(sections[i].sectname,"__jump_table"))
4748 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4754 for(i=0;i<segLC->nsects;i++)
4756 if(!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
4760 #if defined (powerpc_HOST_ARCH)
4761 ocFlushInstructionCache( oc );
4767 #ifdef powerpc_HOST_ARCH
4769 * The Mach-O object format uses leading underscores. But not everywhere.
4770 * There is a small number of runtime support functions defined in
4771 * libcc_dynamic.a whose name does not have a leading underscore.
4772 * As a consequence, we can't get their address from C code.
4773 * We have to use inline assembler just to take the address of a function.
4777 extern void* symbolsWithoutUnderscore[];
4779 static void machoInitSymbolsWithoutUnderscore()
4781 void **p = symbolsWithoutUnderscore;
4782 __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
4784 #undef SymI_NeedsProto
4785 #define SymI_NeedsProto(x) \
4786 __asm__ volatile(".long " # x);
4788 RTS_MACHO_NOUNDERLINE_SYMBOLS
4790 __asm__ volatile(".text");
4792 #undef SymI_NeedsProto
4793 #define SymI_NeedsProto(x) \
4794 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
4796 RTS_MACHO_NOUNDERLINE_SYMBOLS
4798 #undef SymI_NeedsProto
4804 * Figure out by how much to shift the entire Mach-O file in memory
4805 * when loading so that its single segment ends up 16-byte-aligned
4807 static int machoGetMisalignment( FILE * f )
4809 struct mach_header header;
4812 fread(&header, sizeof(header), 1, f);
4815 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
4816 if(header.magic != MH_MAGIC_64)
4819 if(header.magic != MH_MAGIC)
4823 misalignment = (header.sizeofcmds + sizeof(header))
4826 return misalignment ? (16 - misalignment) : 0;