1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2004
7 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
13 /* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and
14 MREMAP_MAYMOVE from <sys/mman.h>.
16 #if defined(__linux__) || defined(__GLIBC__)
23 #include "sm/Storage.h"
26 #include "LinkerInternals.h"
29 #include "StgPrimFloat.h" // for __int_encodeFloat etc.
32 #if !defined(mingw32_HOST_OS)
33 #include "posix/Signals.h"
36 // get protos for is*()
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
49 #ifdef HAVE_SYS_STAT_H
53 #if defined(HAVE_DLFCN_H)
57 #if defined(cygwin32_HOST_OS)
62 #ifdef HAVE_SYS_TIME_H
66 #include <sys/fcntl.h>
67 #include <sys/termios.h>
68 #include <sys/utime.h>
69 #include <sys/utsname.h>
73 #if defined(linux_HOST_OS ) || defined(freebsd_HOST_OS) || \
74 defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS ) || \
75 defined(openbsd_HOST_OS ) || \
76 ( defined(darwin_HOST_OS ) && !defined(powerpc_HOST_ARCH) ) || \
77 defined(kfreebsdgnu_HOST_OS)
78 /* Don't use mmap on powerpc-apple-darwin as mmap doesn't support
79 * reallocating but we need to allocate jump islands just after each
80 * object images. Otherwise relative branches to jump islands can fail
81 * due to 24-bits displacement overflow.
93 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
94 # define OBJFORMAT_ELF
95 # include <regex.h> // regex is already used by dlopen() so this is OK
96 // to use here without requiring an additional lib
97 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
98 # define OBJFORMAT_PEi386
101 #elif defined(darwin_HOST_OS)
102 # define OBJFORMAT_MACHO
104 # include <mach-o/loader.h>
105 # include <mach-o/nlist.h>
106 # include <mach-o/reloc.h>
107 #if !defined(HAVE_DLFCN_H)
108 # include <mach-o/dyld.h>
110 #if defined(powerpc_HOST_ARCH)
111 # include <mach-o/ppc/reloc.h>
113 #if defined(x86_64_HOST_ARCH)
114 # include <mach-o/x86_64/reloc.h>
118 #if defined(x86_64_HOST_ARCH) && defined(darwin_HOST_OS)
122 /* Hash table mapping symbol names to Symbol */
123 static /*Str*/HashTable *symhash;
125 /* Hash table mapping symbol names to StgStablePtr */
126 static /*Str*/HashTable *stablehash;
128 /* List of currently loaded objects */
129 ObjectCode *objects = NULL; /* initially empty */
131 static HsInt loadOc( ObjectCode* oc );
132 static ObjectCode* mkOc( char *path, char *image, int imageSize,
133 char *archiveMemberName
135 #ifdef darwin_HOST_OS
141 #if defined(OBJFORMAT_ELF)
142 static int ocVerifyImage_ELF ( ObjectCode* oc );
143 static int ocGetNames_ELF ( ObjectCode* oc );
144 static int ocResolve_ELF ( ObjectCode* oc );
145 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
146 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
148 #elif defined(OBJFORMAT_PEi386)
149 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
150 static int ocGetNames_PEi386 ( ObjectCode* oc );
151 static int ocResolve_PEi386 ( ObjectCode* oc );
152 static void *lookupSymbolInDLLs ( unsigned char *lbl );
153 static void zapTrailingAtSign ( unsigned char *sym );
154 #elif defined(OBJFORMAT_MACHO)
155 static int ocVerifyImage_MachO ( ObjectCode* oc );
156 static int ocGetNames_MachO ( ObjectCode* oc );
157 static int ocResolve_MachO ( ObjectCode* oc );
160 static int machoGetMisalignment( FILE * );
162 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
163 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
165 #ifdef powerpc_HOST_ARCH
166 static void machoInitSymbolsWithoutUnderscore( void );
170 /* on x86_64 we have a problem with relocating symbol references in
171 * code that was compiled without -fPIC. By default, the small memory
172 * model is used, which assumes that symbol references can fit in a
173 * 32-bit slot. The system dynamic linker makes this work for
174 * references to shared libraries by either (a) allocating a jump
175 * table slot for code references, or (b) moving the symbol at load
176 * time (and copying its contents, if necessary) for data references.
178 * We unfortunately can't tell whether symbol references are to code
179 * or data. So for now we assume they are code (the vast majority
180 * are), and allocate jump-table slots. Unfortunately this will
181 * SILENTLY generate crashing code for data references. This hack is
182 * enabled by X86_64_ELF_NONPIC_HACK.
184 * One workaround is to use shared Haskell libraries. This is
185 * coming. Another workaround is to keep the static libraries but
186 * compile them with -fPIC, because that will generate PIC references
187 * to data which can be relocated. The PIC code is still too green to
188 * do this systematically, though.
191 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
193 * Naming Scheme for Symbol Macros
195 * SymI_*: symbol is internal to the RTS. It resides in an object
196 * file/library that is statically.
197 * SymE_*: symbol is external to the RTS library. It might be linked
200 * Sym*_HasProto : the symbol prototype is imported in an include file
201 * or defined explicitly
202 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
203 * default proto extern void sym(void);
205 #define X86_64_ELF_NONPIC_HACK 1
207 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
208 * small memory model on this architecture (see gcc docs,
211 * MAP_32BIT not available on OpenBSD/amd64
213 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
214 #define TRY_MAP_32BIT MAP_32BIT
216 #define TRY_MAP_32BIT 0
220 * Due to the small memory model (see above), on x86_64 we have to map
221 * all our non-PIC object files into the low 2Gb of the address space
222 * (why 2Gb and not 4Gb? Because all addresses must be reachable
223 * using a 32-bit signed PC-relative offset). On Linux we can do this
224 * using the MAP_32BIT flag to mmap(), however on other OSs
225 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
226 * can't do this. So on these systems, we have to pick a base address
227 * in the low 2Gb of the address space and try to allocate memory from
230 * We pick a default address based on the OS, but also make this
231 * configurable via an RTS flag (+RTS -xm)
233 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
235 #if defined(MAP_32BIT)
236 // Try to use MAP_32BIT
237 #define MMAP_32BIT_BASE_DEFAULT 0
240 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
243 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
246 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
247 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
248 #define MAP_ANONYMOUS MAP_ANON
251 /* -----------------------------------------------------------------------------
252 * Built-in symbols from the RTS
255 typedef struct _RtsSymbolVal {
260 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
261 SymI_HasProto(stg_mkWeakForeignEnvzh) \
262 SymI_HasProto(stg_makeStableNamezh) \
263 SymI_HasProto(stg_finalizzeWeakzh)
265 #if !defined (mingw32_HOST_OS)
266 #define RTS_POSIX_ONLY_SYMBOLS \
267 SymI_HasProto(__hscore_get_saved_termios) \
268 SymI_HasProto(__hscore_set_saved_termios) \
269 SymI_HasProto(shutdownHaskellAndSignal) \
270 SymI_HasProto(lockFile) \
271 SymI_HasProto(unlockFile) \
272 SymI_HasProto(signal_handlers) \
273 SymI_HasProto(stg_sig_install) \
274 SymI_HasProto(rtsTimerSignal) \
275 SymI_HasProto(atexit) \
276 SymI_NeedsProto(nocldstop)
279 #if defined (cygwin32_HOST_OS)
280 #define RTS_MINGW_ONLY_SYMBOLS /**/
281 /* Don't have the ability to read import libs / archives, so
282 * we have to stupidly list a lot of what libcygwin.a
285 #define RTS_CYGWIN_ONLY_SYMBOLS \
286 SymI_HasProto(regfree) \
287 SymI_HasProto(regexec) \
288 SymI_HasProto(regerror) \
289 SymI_HasProto(regcomp) \
290 SymI_HasProto(__errno) \
291 SymI_HasProto(access) \
292 SymI_HasProto(chmod) \
293 SymI_HasProto(chdir) \
294 SymI_HasProto(close) \
295 SymI_HasProto(creat) \
297 SymI_HasProto(dup2) \
298 SymI_HasProto(fstat) \
299 SymI_HasProto(fcntl) \
300 SymI_HasProto(getcwd) \
301 SymI_HasProto(getenv) \
302 SymI_HasProto(lseek) \
303 SymI_HasProto(open) \
304 SymI_HasProto(fpathconf) \
305 SymI_HasProto(pathconf) \
306 SymI_HasProto(stat) \
308 SymI_HasProto(tanh) \
309 SymI_HasProto(cosh) \
310 SymI_HasProto(sinh) \
311 SymI_HasProto(atan) \
312 SymI_HasProto(acos) \
313 SymI_HasProto(asin) \
319 SymI_HasProto(sqrt) \
320 SymI_HasProto(localtime_r) \
321 SymI_HasProto(gmtime_r) \
322 SymI_HasProto(mktime) \
323 SymI_NeedsProto(_imp___tzname) \
324 SymI_HasProto(gettimeofday) \
325 SymI_HasProto(timezone) \
326 SymI_HasProto(tcgetattr) \
327 SymI_HasProto(tcsetattr) \
328 SymI_HasProto(memcpy) \
329 SymI_HasProto(memmove) \
330 SymI_HasProto(realloc) \
331 SymI_HasProto(malloc) \
332 SymI_HasProto(free) \
333 SymI_HasProto(fork) \
334 SymI_HasProto(lstat) \
335 SymI_HasProto(isatty) \
336 SymI_HasProto(mkdir) \
337 SymI_HasProto(opendir) \
338 SymI_HasProto(readdir) \
339 SymI_HasProto(rewinddir) \
340 SymI_HasProto(closedir) \
341 SymI_HasProto(link) \
342 SymI_HasProto(mkfifo) \
343 SymI_HasProto(pipe) \
344 SymI_HasProto(read) \
345 SymI_HasProto(rename) \
346 SymI_HasProto(rmdir) \
347 SymI_HasProto(select) \
348 SymI_HasProto(system) \
349 SymI_HasProto(write) \
350 SymI_HasProto(strcmp) \
351 SymI_HasProto(strcpy) \
352 SymI_HasProto(strncpy) \
353 SymI_HasProto(strerror) \
354 SymI_HasProto(sigaddset) \
355 SymI_HasProto(sigemptyset) \
356 SymI_HasProto(sigprocmask) \
357 SymI_HasProto(umask) \
358 SymI_HasProto(uname) \
359 SymI_HasProto(unlink) \
360 SymI_HasProto(utime) \
361 SymI_HasProto(waitpid)
363 #elif !defined(mingw32_HOST_OS)
364 #define RTS_MINGW_ONLY_SYMBOLS /**/
365 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
366 #else /* defined(mingw32_HOST_OS) */
367 #define RTS_POSIX_ONLY_SYMBOLS /**/
368 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
370 #if HAVE_GETTIMEOFDAY
371 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
373 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
376 #if HAVE___MINGW_VFPRINTF
377 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
379 #define RTS___MINGW_VFPRINTF_SYM /**/
382 /* These are statically linked from the mingw libraries into the ghc
383 executable, so we have to employ this hack. */
384 #define RTS_MINGW_ONLY_SYMBOLS \
385 SymI_HasProto(stg_asyncReadzh) \
386 SymI_HasProto(stg_asyncWritezh) \
387 SymI_HasProto(stg_asyncDoProczh) \
388 SymI_HasProto(memset) \
389 SymI_HasProto(inet_ntoa) \
390 SymI_HasProto(inet_addr) \
391 SymI_HasProto(htonl) \
392 SymI_HasProto(recvfrom) \
393 SymI_HasProto(listen) \
394 SymI_HasProto(bind) \
395 SymI_HasProto(shutdown) \
396 SymI_HasProto(connect) \
397 SymI_HasProto(htons) \
398 SymI_HasProto(ntohs) \
399 SymI_HasProto(getservbyname) \
400 SymI_HasProto(getservbyport) \
401 SymI_HasProto(getprotobynumber) \
402 SymI_HasProto(getprotobyname) \
403 SymI_HasProto(gethostbyname) \
404 SymI_HasProto(gethostbyaddr) \
405 SymI_HasProto(gethostname) \
406 SymI_HasProto(strcpy) \
407 SymI_HasProto(strncpy) \
408 SymI_HasProto(abort) \
409 SymI_NeedsProto(_alloca) \
410 SymI_HasProto(isxdigit) \
411 SymI_HasProto(isupper) \
412 SymI_HasProto(ispunct) \
413 SymI_HasProto(islower) \
414 SymI_HasProto(isspace) \
415 SymI_HasProto(isprint) \
416 SymI_HasProto(isdigit) \
417 SymI_HasProto(iscntrl) \
418 SymI_HasProto(isalpha) \
419 SymI_HasProto(isalnum) \
420 SymI_HasProto(isascii) \
421 RTS___MINGW_VFPRINTF_SYM \
422 SymI_HasProto(strcmp) \
423 SymI_HasProto(memmove) \
424 SymI_HasProto(realloc) \
425 SymI_HasProto(malloc) \
427 SymI_HasProto(tanh) \
428 SymI_HasProto(cosh) \
429 SymI_HasProto(sinh) \
430 SymI_HasProto(atan) \
431 SymI_HasProto(acos) \
432 SymI_HasProto(asin) \
438 SymI_HasProto(sqrt) \
439 SymI_HasProto(powf) \
440 SymI_HasProto(tanhf) \
441 SymI_HasProto(coshf) \
442 SymI_HasProto(sinhf) \
443 SymI_HasProto(atanf) \
444 SymI_HasProto(acosf) \
445 SymI_HasProto(asinf) \
446 SymI_HasProto(tanf) \
447 SymI_HasProto(cosf) \
448 SymI_HasProto(sinf) \
449 SymI_HasProto(expf) \
450 SymI_HasProto(logf) \
451 SymI_HasProto(sqrtf) \
453 SymI_HasProto(erfc) \
454 SymI_HasProto(erff) \
455 SymI_HasProto(erfcf) \
456 SymI_HasProto(memcpy) \
457 SymI_HasProto(rts_InstallConsoleEvent) \
458 SymI_HasProto(rts_ConsoleHandlerDone) \
459 SymI_NeedsProto(mktime) \
460 SymI_NeedsProto(_imp___timezone) \
461 SymI_NeedsProto(_imp___tzname) \
462 SymI_NeedsProto(_imp__tzname) \
463 SymI_NeedsProto(_imp___iob) \
464 SymI_NeedsProto(_imp___osver) \
465 SymI_NeedsProto(localtime) \
466 SymI_NeedsProto(gmtime) \
467 SymI_NeedsProto(opendir) \
468 SymI_NeedsProto(readdir) \
469 SymI_NeedsProto(rewinddir) \
470 SymI_NeedsProto(_imp____mb_cur_max) \
471 SymI_NeedsProto(_imp___pctype) \
472 SymI_NeedsProto(__chkstk) \
473 RTS_MINGW_GETTIMEOFDAY_SYM \
474 SymI_NeedsProto(closedir)
478 #if defined(darwin_HOST_OS) && HAVE_PRINTF_LDBLSTUB
479 #define RTS_DARWIN_ONLY_SYMBOLS \
480 SymI_NeedsProto(asprintf$LDBLStub) \
481 SymI_NeedsProto(err$LDBLStub) \
482 SymI_NeedsProto(errc$LDBLStub) \
483 SymI_NeedsProto(errx$LDBLStub) \
484 SymI_NeedsProto(fprintf$LDBLStub) \
485 SymI_NeedsProto(fscanf$LDBLStub) \
486 SymI_NeedsProto(fwprintf$LDBLStub) \
487 SymI_NeedsProto(fwscanf$LDBLStub) \
488 SymI_NeedsProto(printf$LDBLStub) \
489 SymI_NeedsProto(scanf$LDBLStub) \
490 SymI_NeedsProto(snprintf$LDBLStub) \
491 SymI_NeedsProto(sprintf$LDBLStub) \
492 SymI_NeedsProto(sscanf$LDBLStub) \
493 SymI_NeedsProto(strtold$LDBLStub) \
494 SymI_NeedsProto(swprintf$LDBLStub) \
495 SymI_NeedsProto(swscanf$LDBLStub) \
496 SymI_NeedsProto(syslog$LDBLStub) \
497 SymI_NeedsProto(vasprintf$LDBLStub) \
498 SymI_NeedsProto(verr$LDBLStub) \
499 SymI_NeedsProto(verrc$LDBLStub) \
500 SymI_NeedsProto(verrx$LDBLStub) \
501 SymI_NeedsProto(vfprintf$LDBLStub) \
502 SymI_NeedsProto(vfscanf$LDBLStub) \
503 SymI_NeedsProto(vfwprintf$LDBLStub) \
504 SymI_NeedsProto(vfwscanf$LDBLStub) \
505 SymI_NeedsProto(vprintf$LDBLStub) \
506 SymI_NeedsProto(vscanf$LDBLStub) \
507 SymI_NeedsProto(vsnprintf$LDBLStub) \
508 SymI_NeedsProto(vsprintf$LDBLStub) \
509 SymI_NeedsProto(vsscanf$LDBLStub) \
510 SymI_NeedsProto(vswprintf$LDBLStub) \
511 SymI_NeedsProto(vswscanf$LDBLStub) \
512 SymI_NeedsProto(vsyslog$LDBLStub) \
513 SymI_NeedsProto(vwarn$LDBLStub) \
514 SymI_NeedsProto(vwarnc$LDBLStub) \
515 SymI_NeedsProto(vwarnx$LDBLStub) \
516 SymI_NeedsProto(vwprintf$LDBLStub) \
517 SymI_NeedsProto(vwscanf$LDBLStub) \
518 SymI_NeedsProto(warn$LDBLStub) \
519 SymI_NeedsProto(warnc$LDBLStub) \
520 SymI_NeedsProto(warnx$LDBLStub) \
521 SymI_NeedsProto(wcstold$LDBLStub) \
522 SymI_NeedsProto(wprintf$LDBLStub) \
523 SymI_NeedsProto(wscanf$LDBLStub)
525 #define RTS_DARWIN_ONLY_SYMBOLS
529 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
531 # define MAIN_CAP_SYM
534 #if !defined(mingw32_HOST_OS)
535 #define RTS_USER_SIGNALS_SYMBOLS \
536 SymI_HasProto(setIOManagerControlFd) \
537 SymI_HasProto(setIOManagerWakeupFd) \
538 SymI_HasProto(ioManagerWakeup) \
539 SymI_HasProto(blockUserSignals) \
540 SymI_HasProto(unblockUserSignals)
542 #define RTS_USER_SIGNALS_SYMBOLS \
543 SymI_HasProto(ioManagerWakeup) \
544 SymI_HasProto(sendIOManagerEvent) \
545 SymI_HasProto(readIOManagerEvent) \
546 SymI_HasProto(getIOManagerEvent) \
547 SymI_HasProto(console_handler)
550 #define RTS_LIBFFI_SYMBOLS \
551 SymE_NeedsProto(ffi_prep_cif) \
552 SymE_NeedsProto(ffi_call) \
553 SymE_NeedsProto(ffi_type_void) \
554 SymE_NeedsProto(ffi_type_float) \
555 SymE_NeedsProto(ffi_type_double) \
556 SymE_NeedsProto(ffi_type_sint64) \
557 SymE_NeedsProto(ffi_type_uint64) \
558 SymE_NeedsProto(ffi_type_sint32) \
559 SymE_NeedsProto(ffi_type_uint32) \
560 SymE_NeedsProto(ffi_type_sint16) \
561 SymE_NeedsProto(ffi_type_uint16) \
562 SymE_NeedsProto(ffi_type_sint8) \
563 SymE_NeedsProto(ffi_type_uint8) \
564 SymE_NeedsProto(ffi_type_pointer)
566 #ifdef TABLES_NEXT_TO_CODE
567 #define RTS_RET_SYMBOLS /* nothing */
569 #define RTS_RET_SYMBOLS \
570 SymI_HasProto(stg_enter_ret) \
571 SymI_HasProto(stg_gc_fun_ret) \
572 SymI_HasProto(stg_ap_v_ret) \
573 SymI_HasProto(stg_ap_f_ret) \
574 SymI_HasProto(stg_ap_d_ret) \
575 SymI_HasProto(stg_ap_l_ret) \
576 SymI_HasProto(stg_ap_n_ret) \
577 SymI_HasProto(stg_ap_p_ret) \
578 SymI_HasProto(stg_ap_pv_ret) \
579 SymI_HasProto(stg_ap_pp_ret) \
580 SymI_HasProto(stg_ap_ppv_ret) \
581 SymI_HasProto(stg_ap_ppp_ret) \
582 SymI_HasProto(stg_ap_pppv_ret) \
583 SymI_HasProto(stg_ap_pppp_ret) \
584 SymI_HasProto(stg_ap_ppppp_ret) \
585 SymI_HasProto(stg_ap_pppppp_ret)
588 /* Modules compiled with -ticky may mention ticky counters */
589 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
590 #define RTS_TICKY_SYMBOLS \
591 SymI_NeedsProto(ticky_entry_ctrs) \
592 SymI_NeedsProto(top_ct) \
594 SymI_HasProto(ENT_VIA_NODE_ctr) \
595 SymI_HasProto(ENT_STATIC_THK_ctr) \
596 SymI_HasProto(ENT_DYN_THK_ctr) \
597 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
598 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
599 SymI_HasProto(ENT_STATIC_CON_ctr) \
600 SymI_HasProto(ENT_DYN_CON_ctr) \
601 SymI_HasProto(ENT_STATIC_IND_ctr) \
602 SymI_HasProto(ENT_DYN_IND_ctr) \
603 SymI_HasProto(ENT_PERM_IND_ctr) \
604 SymI_HasProto(ENT_PAP_ctr) \
605 SymI_HasProto(ENT_AP_ctr) \
606 SymI_HasProto(ENT_AP_STACK_ctr) \
607 SymI_HasProto(ENT_BH_ctr) \
608 SymI_HasProto(UNKNOWN_CALL_ctr) \
609 SymI_HasProto(SLOW_CALL_v_ctr) \
610 SymI_HasProto(SLOW_CALL_f_ctr) \
611 SymI_HasProto(SLOW_CALL_d_ctr) \
612 SymI_HasProto(SLOW_CALL_l_ctr) \
613 SymI_HasProto(SLOW_CALL_n_ctr) \
614 SymI_HasProto(SLOW_CALL_p_ctr) \
615 SymI_HasProto(SLOW_CALL_pv_ctr) \
616 SymI_HasProto(SLOW_CALL_pp_ctr) \
617 SymI_HasProto(SLOW_CALL_ppv_ctr) \
618 SymI_HasProto(SLOW_CALL_ppp_ctr) \
619 SymI_HasProto(SLOW_CALL_pppv_ctr) \
620 SymI_HasProto(SLOW_CALL_pppp_ctr) \
621 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
622 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
623 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
624 SymI_HasProto(ticky_slow_call_unevald) \
625 SymI_HasProto(SLOW_CALL_ctr) \
626 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
627 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
628 SymI_HasProto(KNOWN_CALL_ctr) \
629 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
630 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
631 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
632 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
633 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
634 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
635 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
636 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
637 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
638 SymI_HasProto(UPDF_OMITTED_ctr) \
639 SymI_HasProto(UPDF_PUSHED_ctr) \
640 SymI_HasProto(CATCHF_PUSHED_ctr) \
641 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
642 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
643 SymI_HasProto(UPD_SQUEEZED_ctr) \
644 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
645 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
646 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
647 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
648 SymI_HasProto(ALLOC_HEAP_ctr) \
649 SymI_HasProto(ALLOC_HEAP_tot) \
650 SymI_HasProto(ALLOC_FUN_ctr) \
651 SymI_HasProto(ALLOC_FUN_adm) \
652 SymI_HasProto(ALLOC_FUN_gds) \
653 SymI_HasProto(ALLOC_FUN_slp) \
654 SymI_HasProto(UPD_NEW_IND_ctr) \
655 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
656 SymI_HasProto(UPD_OLD_IND_ctr) \
657 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
658 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
659 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
660 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
661 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
662 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
663 SymI_HasProto(GC_SEL_MINOR_ctr) \
664 SymI_HasProto(GC_SEL_MAJOR_ctr) \
665 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
666 SymI_HasProto(ALLOC_UP_THK_ctr) \
667 SymI_HasProto(ALLOC_SE_THK_ctr) \
668 SymI_HasProto(ALLOC_THK_adm) \
669 SymI_HasProto(ALLOC_THK_gds) \
670 SymI_HasProto(ALLOC_THK_slp) \
671 SymI_HasProto(ALLOC_CON_ctr) \
672 SymI_HasProto(ALLOC_CON_adm) \
673 SymI_HasProto(ALLOC_CON_gds) \
674 SymI_HasProto(ALLOC_CON_slp) \
675 SymI_HasProto(ALLOC_TUP_ctr) \
676 SymI_HasProto(ALLOC_TUP_adm) \
677 SymI_HasProto(ALLOC_TUP_gds) \
678 SymI_HasProto(ALLOC_TUP_slp) \
679 SymI_HasProto(ALLOC_BH_ctr) \
680 SymI_HasProto(ALLOC_BH_adm) \
681 SymI_HasProto(ALLOC_BH_gds) \
682 SymI_HasProto(ALLOC_BH_slp) \
683 SymI_HasProto(ALLOC_PRIM_ctr) \
684 SymI_HasProto(ALLOC_PRIM_adm) \
685 SymI_HasProto(ALLOC_PRIM_gds) \
686 SymI_HasProto(ALLOC_PRIM_slp) \
687 SymI_HasProto(ALLOC_PAP_ctr) \
688 SymI_HasProto(ALLOC_PAP_adm) \
689 SymI_HasProto(ALLOC_PAP_gds) \
690 SymI_HasProto(ALLOC_PAP_slp) \
691 SymI_HasProto(ALLOC_TSO_ctr) \
692 SymI_HasProto(ALLOC_TSO_adm) \
693 SymI_HasProto(ALLOC_TSO_gds) \
694 SymI_HasProto(ALLOC_TSO_slp) \
695 SymI_HasProto(RET_NEW_ctr) \
696 SymI_HasProto(RET_OLD_ctr) \
697 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
698 SymI_HasProto(RET_SEMI_loads_avoided)
701 // On most platforms, the garbage collector rewrites references
702 // to small integer and char objects to a set of common, shared ones.
704 // We don't do this when compiling to Windows DLLs at the moment because
705 // it doesn't support cross package data references well.
707 #if defined(__PIC__) && defined(mingw32_HOST_OS)
708 #define RTS_INTCHAR_SYMBOLS
710 #define RTS_INTCHAR_SYMBOLS \
711 SymI_HasProto(stg_CHARLIKE_closure) \
712 SymI_HasProto(stg_INTLIKE_closure)
716 #define RTS_SYMBOLS \
719 SymI_HasProto(StgReturn) \
720 SymI_HasProto(stg_enter_info) \
721 SymI_HasProto(stg_gc_void_info) \
722 SymI_HasProto(__stg_gc_enter_1) \
723 SymI_HasProto(stg_gc_noregs) \
724 SymI_HasProto(stg_gc_unpt_r1_info) \
725 SymI_HasProto(stg_gc_unpt_r1) \
726 SymI_HasProto(stg_gc_unbx_r1_info) \
727 SymI_HasProto(stg_gc_unbx_r1) \
728 SymI_HasProto(stg_gc_f1_info) \
729 SymI_HasProto(stg_gc_f1) \
730 SymI_HasProto(stg_gc_d1_info) \
731 SymI_HasProto(stg_gc_d1) \
732 SymI_HasProto(stg_gc_l1_info) \
733 SymI_HasProto(stg_gc_l1) \
734 SymI_HasProto(__stg_gc_fun) \
735 SymI_HasProto(stg_gc_fun_info) \
736 SymI_HasProto(stg_gc_gen) \
737 SymI_HasProto(stg_gc_gen_info) \
738 SymI_HasProto(stg_gc_gen_hp) \
739 SymI_HasProto(stg_gc_ut) \
740 SymI_HasProto(stg_gen_yield) \
741 SymI_HasProto(stg_yield_noregs) \
742 SymI_HasProto(stg_yield_to_interpreter) \
743 SymI_HasProto(stg_gen_block) \
744 SymI_HasProto(stg_block_noregs) \
745 SymI_HasProto(stg_block_1) \
746 SymI_HasProto(stg_block_takemvar) \
747 SymI_HasProto(stg_block_putmvar) \
749 SymI_HasProto(MallocFailHook) \
750 SymI_HasProto(OnExitHook) \
751 SymI_HasProto(OutOfHeapHook) \
752 SymI_HasProto(StackOverflowHook) \
753 SymI_HasProto(addDLL) \
754 SymI_HasProto(__int_encodeDouble) \
755 SymI_HasProto(__word_encodeDouble) \
756 SymI_HasProto(__2Int_encodeDouble) \
757 SymI_HasProto(__int_encodeFloat) \
758 SymI_HasProto(__word_encodeFloat) \
759 SymI_HasProto(stg_atomicallyzh) \
760 SymI_HasProto(barf) \
761 SymI_HasProto(debugBelch) \
762 SymI_HasProto(errorBelch) \
763 SymI_HasProto(sysErrorBelch) \
764 SymI_HasProto(stg_getMaskingStatezh) \
765 SymI_HasProto(stg_maskAsyncExceptionszh) \
766 SymI_HasProto(stg_maskUninterruptiblezh) \
767 SymI_HasProto(stg_catchzh) \
768 SymI_HasProto(stg_catchRetryzh) \
769 SymI_HasProto(stg_catchSTMzh) \
770 SymI_HasProto(stg_checkzh) \
771 SymI_HasProto(closure_flags) \
772 SymI_HasProto(cmp_thread) \
773 SymI_HasProto(createAdjustor) \
774 SymI_HasProto(stg_decodeDoublezu2Intzh) \
775 SymI_HasProto(stg_decodeFloatzuIntzh) \
776 SymI_HasProto(defaultsHook) \
777 SymI_HasProto(stg_delayzh) \
778 SymI_HasProto(stg_deRefWeakzh) \
779 SymI_HasProto(stg_deRefStablePtrzh) \
780 SymI_HasProto(dirty_MUT_VAR) \
781 SymI_HasProto(stg_forkzh) \
782 SymI_HasProto(stg_forkOnzh) \
783 SymI_HasProto(forkProcess) \
784 SymI_HasProto(forkOS_createThread) \
785 SymI_HasProto(freeHaskellFunctionPtr) \
786 SymI_HasProto(getOrSetTypeableStore) \
787 SymI_HasProto(getOrSetGHCConcSignalSignalHandlerStore) \
788 SymI_HasProto(getOrSetGHCConcWindowsPendingDelaysStore) \
789 SymI_HasProto(getOrSetGHCConcWindowsIOManagerThreadStore) \
790 SymI_HasProto(getOrSetGHCConcWindowsProddingStore) \
791 SymI_HasProto(getOrSetSystemEventThreadEventManagerStore) \
792 SymI_HasProto(getOrSetSystemEventThreadIOManagerThreadStore) \
793 SymI_HasProto(genSymZh) \
794 SymI_HasProto(genericRaise) \
795 SymI_HasProto(getProgArgv) \
796 SymI_HasProto(getFullProgArgv) \
797 SymI_HasProto(getStablePtr) \
798 SymI_HasProto(hs_init) \
799 SymI_HasProto(hs_exit) \
800 SymI_HasProto(hs_set_argv) \
801 SymI_HasProto(hs_add_root) \
802 SymI_HasProto(hs_perform_gc) \
803 SymI_HasProto(hs_free_stable_ptr) \
804 SymI_HasProto(hs_free_fun_ptr) \
805 SymI_HasProto(hs_hpc_rootModule) \
806 SymI_HasProto(hs_hpc_module) \
807 SymI_HasProto(initLinker) \
808 SymI_HasProto(stg_unpackClosurezh) \
809 SymI_HasProto(stg_getApStackValzh) \
810 SymI_HasProto(stg_getSparkzh) \
811 SymI_HasProto(stg_numSparkszh) \
812 SymI_HasProto(stg_isCurrentThreadBoundzh) \
813 SymI_HasProto(stg_isEmptyMVarzh) \
814 SymI_HasProto(stg_killThreadzh) \
815 SymI_HasProto(loadArchive) \
816 SymI_HasProto(loadObj) \
817 SymI_HasProto(insertStableSymbol) \
818 SymI_HasProto(insertSymbol) \
819 SymI_HasProto(lookupSymbol) \
820 SymI_HasProto(stg_makeStablePtrzh) \
821 SymI_HasProto(stg_mkApUpd0zh) \
822 SymI_HasProto(stg_myThreadIdzh) \
823 SymI_HasProto(stg_labelThreadzh) \
824 SymI_HasProto(stg_newArrayzh) \
825 SymI_HasProto(stg_newBCOzh) \
826 SymI_HasProto(stg_newByteArrayzh) \
827 SymI_HasProto_redirect(newCAF, newDynCAF) \
828 SymI_HasProto(stg_newMVarzh) \
829 SymI_HasProto(stg_newMutVarzh) \
830 SymI_HasProto(stg_newTVarzh) \
831 SymI_HasProto(stg_noDuplicatezh) \
832 SymI_HasProto(stg_atomicModifyMutVarzh) \
833 SymI_HasProto(stg_newPinnedByteArrayzh) \
834 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
835 SymI_HasProto(newSpark) \
836 SymI_HasProto(performGC) \
837 SymI_HasProto(performMajorGC) \
838 SymI_HasProto(prog_argc) \
839 SymI_HasProto(prog_argv) \
840 SymI_HasProto(stg_putMVarzh) \
841 SymI_HasProto(stg_raisezh) \
842 SymI_HasProto(stg_raiseIOzh) \
843 SymI_HasProto(stg_readTVarzh) \
844 SymI_HasProto(stg_readTVarIOzh) \
845 SymI_HasProto(resumeThread) \
846 SymI_HasProto(resolveObjs) \
847 SymI_HasProto(stg_retryzh) \
848 SymI_HasProto(rts_apply) \
849 SymI_HasProto(rts_checkSchedStatus) \
850 SymI_HasProto(rts_eval) \
851 SymI_HasProto(rts_evalIO) \
852 SymI_HasProto(rts_evalLazyIO) \
853 SymI_HasProto(rts_evalStableIO) \
854 SymI_HasProto(rts_eval_) \
855 SymI_HasProto(rts_getBool) \
856 SymI_HasProto(rts_getChar) \
857 SymI_HasProto(rts_getDouble) \
858 SymI_HasProto(rts_getFloat) \
859 SymI_HasProto(rts_getInt) \
860 SymI_HasProto(rts_getInt8) \
861 SymI_HasProto(rts_getInt16) \
862 SymI_HasProto(rts_getInt32) \
863 SymI_HasProto(rts_getInt64) \
864 SymI_HasProto(rts_getPtr) \
865 SymI_HasProto(rts_getFunPtr) \
866 SymI_HasProto(rts_getStablePtr) \
867 SymI_HasProto(rts_getThreadId) \
868 SymI_HasProto(rts_getWord) \
869 SymI_HasProto(rts_getWord8) \
870 SymI_HasProto(rts_getWord16) \
871 SymI_HasProto(rts_getWord32) \
872 SymI_HasProto(rts_getWord64) \
873 SymI_HasProto(rts_lock) \
874 SymI_HasProto(rts_mkBool) \
875 SymI_HasProto(rts_mkChar) \
876 SymI_HasProto(rts_mkDouble) \
877 SymI_HasProto(rts_mkFloat) \
878 SymI_HasProto(rts_mkInt) \
879 SymI_HasProto(rts_mkInt8) \
880 SymI_HasProto(rts_mkInt16) \
881 SymI_HasProto(rts_mkInt32) \
882 SymI_HasProto(rts_mkInt64) \
883 SymI_HasProto(rts_mkPtr) \
884 SymI_HasProto(rts_mkFunPtr) \
885 SymI_HasProto(rts_mkStablePtr) \
886 SymI_HasProto(rts_mkString) \
887 SymI_HasProto(rts_mkWord) \
888 SymI_HasProto(rts_mkWord8) \
889 SymI_HasProto(rts_mkWord16) \
890 SymI_HasProto(rts_mkWord32) \
891 SymI_HasProto(rts_mkWord64) \
892 SymI_HasProto(rts_unlock) \
893 SymI_HasProto(rts_unsafeGetMyCapability) \
894 SymI_HasProto(rtsSupportsBoundThreads) \
895 SymI_HasProto(rts_isProfiled) \
896 SymI_HasProto(setProgArgv) \
897 SymI_HasProto(startupHaskell) \
898 SymI_HasProto(shutdownHaskell) \
899 SymI_HasProto(shutdownHaskellAndExit) \
900 SymI_HasProto(stable_ptr_table) \
901 SymI_HasProto(stackOverflow) \
902 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
903 SymI_HasProto(stg_BLACKHOLE_info) \
904 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
905 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
906 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
907 SymI_HasProto(startTimer) \
908 SymI_HasProto(stg_MVAR_CLEAN_info) \
909 SymI_HasProto(stg_MVAR_DIRTY_info) \
910 SymI_HasProto(stg_IND_STATIC_info) \
911 SymI_HasProto(stg_ARR_WORDS_info) \
912 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
913 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
914 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
915 SymI_HasProto(stg_WEAK_info) \
916 SymI_HasProto(stg_ap_v_info) \
917 SymI_HasProto(stg_ap_f_info) \
918 SymI_HasProto(stg_ap_d_info) \
919 SymI_HasProto(stg_ap_l_info) \
920 SymI_HasProto(stg_ap_n_info) \
921 SymI_HasProto(stg_ap_p_info) \
922 SymI_HasProto(stg_ap_pv_info) \
923 SymI_HasProto(stg_ap_pp_info) \
924 SymI_HasProto(stg_ap_ppv_info) \
925 SymI_HasProto(stg_ap_ppp_info) \
926 SymI_HasProto(stg_ap_pppv_info) \
927 SymI_HasProto(stg_ap_pppp_info) \
928 SymI_HasProto(stg_ap_ppppp_info) \
929 SymI_HasProto(stg_ap_pppppp_info) \
930 SymI_HasProto(stg_ap_0_fast) \
931 SymI_HasProto(stg_ap_v_fast) \
932 SymI_HasProto(stg_ap_f_fast) \
933 SymI_HasProto(stg_ap_d_fast) \
934 SymI_HasProto(stg_ap_l_fast) \
935 SymI_HasProto(stg_ap_n_fast) \
936 SymI_HasProto(stg_ap_p_fast) \
937 SymI_HasProto(stg_ap_pv_fast) \
938 SymI_HasProto(stg_ap_pp_fast) \
939 SymI_HasProto(stg_ap_ppv_fast) \
940 SymI_HasProto(stg_ap_ppp_fast) \
941 SymI_HasProto(stg_ap_pppv_fast) \
942 SymI_HasProto(stg_ap_pppp_fast) \
943 SymI_HasProto(stg_ap_ppppp_fast) \
944 SymI_HasProto(stg_ap_pppppp_fast) \
945 SymI_HasProto(stg_ap_1_upd_info) \
946 SymI_HasProto(stg_ap_2_upd_info) \
947 SymI_HasProto(stg_ap_3_upd_info) \
948 SymI_HasProto(stg_ap_4_upd_info) \
949 SymI_HasProto(stg_ap_5_upd_info) \
950 SymI_HasProto(stg_ap_6_upd_info) \
951 SymI_HasProto(stg_ap_7_upd_info) \
952 SymI_HasProto(stg_exit) \
953 SymI_HasProto(stg_sel_0_upd_info) \
954 SymI_HasProto(stg_sel_10_upd_info) \
955 SymI_HasProto(stg_sel_11_upd_info) \
956 SymI_HasProto(stg_sel_12_upd_info) \
957 SymI_HasProto(stg_sel_13_upd_info) \
958 SymI_HasProto(stg_sel_14_upd_info) \
959 SymI_HasProto(stg_sel_15_upd_info) \
960 SymI_HasProto(stg_sel_1_upd_info) \
961 SymI_HasProto(stg_sel_2_upd_info) \
962 SymI_HasProto(stg_sel_3_upd_info) \
963 SymI_HasProto(stg_sel_4_upd_info) \
964 SymI_HasProto(stg_sel_5_upd_info) \
965 SymI_HasProto(stg_sel_6_upd_info) \
966 SymI_HasProto(stg_sel_7_upd_info) \
967 SymI_HasProto(stg_sel_8_upd_info) \
968 SymI_HasProto(stg_sel_9_upd_info) \
969 SymI_HasProto(stg_upd_frame_info) \
970 SymI_HasProto(stg_bh_upd_frame_info) \
971 SymI_HasProto(suspendThread) \
972 SymI_HasProto(stg_takeMVarzh) \
973 SymI_HasProto(stg_threadStatuszh) \
974 SymI_HasProto(stg_tryPutMVarzh) \
975 SymI_HasProto(stg_tryTakeMVarzh) \
976 SymI_HasProto(stg_unmaskAsyncExceptionszh) \
977 SymI_HasProto(unloadObj) \
978 SymI_HasProto(stg_unsafeThawArrayzh) \
979 SymI_HasProto(stg_waitReadzh) \
980 SymI_HasProto(stg_waitWritezh) \
981 SymI_HasProto(stg_writeTVarzh) \
982 SymI_HasProto(stg_yieldzh) \
983 SymI_NeedsProto(stg_interp_constr_entry) \
984 SymI_HasProto(stg_arg_bitmaps) \
985 SymI_HasProto(large_alloc_lim) \
987 SymI_HasProto(allocate) \
988 SymI_HasProto(allocateExec) \
989 SymI_HasProto(freeExec) \
990 SymI_HasProto(getAllocations) \
991 SymI_HasProto(revertCAFs) \
992 SymI_HasProto(RtsFlags) \
993 SymI_NeedsProto(rts_breakpoint_io_action) \
994 SymI_NeedsProto(rts_stop_next_breakpoint) \
995 SymI_NeedsProto(rts_stop_on_exception) \
996 SymI_HasProto(stopTimer) \
997 SymI_HasProto(n_capabilities) \
998 SymI_HasProto(stg_traceCcszh) \
999 SymI_HasProto(stg_traceEventzh) \
1000 RTS_USER_SIGNALS_SYMBOLS \
1004 // 64-bit support functions in libgcc.a
1005 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
1006 #define RTS_LIBGCC_SYMBOLS \
1007 SymI_NeedsProto(__divdi3) \
1008 SymI_NeedsProto(__udivdi3) \
1009 SymI_NeedsProto(__moddi3) \
1010 SymI_NeedsProto(__umoddi3) \
1011 SymI_NeedsProto(__muldi3) \
1012 SymI_NeedsProto(__ashldi3) \
1013 SymI_NeedsProto(__ashrdi3) \
1014 SymI_NeedsProto(__lshrdi3)
1016 #define RTS_LIBGCC_SYMBOLS
1019 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
1020 // Symbols that don't have a leading underscore
1021 // on Mac OS X. They have to receive special treatment,
1022 // see machoInitSymbolsWithoutUnderscore()
1023 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1024 SymI_NeedsProto(saveFP) \
1025 SymI_NeedsProto(restFP)
1028 /* entirely bogus claims about types of these symbols */
1029 #define SymI_NeedsProto(vvv) extern void vvv(void);
1030 #if defined(__PIC__) && defined(mingw32_HOST_OS)
1031 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1032 #define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1034 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1035 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1037 #define SymI_HasProto(vvv) /**/
1038 #define SymI_HasProto_redirect(vvv,xxx) /**/
1041 RTS_POSIX_ONLY_SYMBOLS
1042 RTS_MINGW_ONLY_SYMBOLS
1043 RTS_CYGWIN_ONLY_SYMBOLS
1044 RTS_DARWIN_ONLY_SYMBOLS
1047 #undef SymI_NeedsProto
1048 #undef SymI_HasProto
1049 #undef SymI_HasProto_redirect
1050 #undef SymE_HasProto
1051 #undef SymE_NeedsProto
1053 #ifdef LEADING_UNDERSCORE
1054 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1056 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1059 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1061 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1062 (void*)DLL_IMPORT_DATA_REF(vvv) },
1064 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1065 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1067 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1068 // another symbol. See newCAF/newDynCAF for an example.
1069 #define SymI_HasProto_redirect(vvv,xxx) \
1070 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1073 static RtsSymbolVal rtsSyms[] = {
1076 RTS_POSIX_ONLY_SYMBOLS
1077 RTS_MINGW_ONLY_SYMBOLS
1078 RTS_CYGWIN_ONLY_SYMBOLS
1079 RTS_DARWIN_ONLY_SYMBOLS
1082 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1083 // dyld stub code contains references to this,
1084 // but it should never be called because we treat
1085 // lazy pointers as nonlazy.
1086 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1088 { 0, 0 } /* sentinel */
1093 /* -----------------------------------------------------------------------------
1094 * Insert symbols into hash tables, checking for duplicates.
1097 static void ghciInsertStrHashTable ( char* obj_name,
1103 if (lookupHashTable(table, (StgWord)key) == NULL)
1105 insertStrHashTable(table, (StgWord)key, data);
1110 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1112 "whilst processing object file\n"
1114 "This could be caused by:\n"
1115 " * Loading two different object files which export the same symbol\n"
1116 " * Specifying the same object file twice on the GHCi command line\n"
1117 " * An incorrect `package.conf' entry, causing some object to be\n"
1119 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1126 /* -----------------------------------------------------------------------------
1127 * initialize the object linker
1131 static int linker_init_done = 0 ;
1133 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1134 static void *dl_prog_handle;
1135 static regex_t re_invalid;
1136 static regex_t re_realso;
1138 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1146 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1150 IF_DEBUG(linker, debugBelch("initLinker: start\n"));
1152 /* Make initLinker idempotent, so we can call it
1153 before evey relevant operation; that means we
1154 don't need to initialise the linker separately */
1155 if (linker_init_done == 1) {
1156 IF_DEBUG(linker, debugBelch("initLinker: idempotent return\n"));
1159 linker_init_done = 1;
1162 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1163 initMutex(&dl_mutex);
1165 stablehash = allocStrHashTable();
1166 symhash = allocStrHashTable();
1168 /* populate the symbol table with stuff from the RTS */
1169 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1170 ghciInsertStrHashTable("(GHCi built-in symbols)",
1171 symhash, sym->lbl, sym->addr);
1172 IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
1174 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1175 machoInitSymbolsWithoutUnderscore();
1178 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1179 # if defined(RTLD_DEFAULT)
1180 dl_prog_handle = RTLD_DEFAULT;
1182 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1183 # endif /* RTLD_DEFAULT */
1185 compileResult = regcomp(&re_invalid,
1186 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*invalid ELF header",
1188 ASSERT( compileResult == 0 );
1189 compileResult = regcomp(&re_realso,
1190 "GROUP *\\( *(([^ )])+)",
1192 ASSERT( compileResult == 0 );
1195 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1196 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1197 // User-override for mmap_32bit_base
1198 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1202 #if defined(mingw32_HOST_OS)
1204 * These two libraries cause problems when added to the static link,
1205 * but are necessary for resolving symbols in GHCi, hence we load
1206 * them manually here.
1212 IF_DEBUG(linker, debugBelch("initLinker: done\n"));
1217 exitLinker( void ) {
1218 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1219 if (linker_init_done == 1) {
1220 regfree(&re_invalid);
1221 regfree(&re_realso);
1223 closeMutex(&dl_mutex);
1229 /* -----------------------------------------------------------------------------
1230 * Loading DLL or .so dynamic libraries
1231 * -----------------------------------------------------------------------------
1233 * Add a DLL from which symbols may be found. In the ELF case, just
1234 * do RTLD_GLOBAL-style add, so no further messing around needs to
1235 * happen in order that symbols in the loaded .so are findable --
1236 * lookupSymbol() will subsequently see them by dlsym on the program's
1237 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1239 * In the PEi386 case, open the DLLs and put handles to them in a
1240 * linked list. When looking for a symbol, try all handles in the
1241 * list. This means that we need to load even DLLs that are guaranteed
1242 * to be in the ghc.exe image already, just so we can get a handle
1243 * to give to loadSymbol, so that we can find the symbols. For such
1244 * libraries, the LoadLibrary call should be a no-op except for returning
1249 #if defined(OBJFORMAT_PEi386)
1250 /* A record for storing handles into DLLs. */
1255 struct _OpenedDLL* next;
1260 /* A list thereof. */
1261 static OpenedDLL* opened_dlls = NULL;
1264 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1267 internal_dlopen(const char *dll_name)
1273 // omitted: RTLD_NOW
1274 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1276 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1278 //-------------- Begin critical section ------------------
1279 // This critical section is necessary because dlerror() is not
1280 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1281 // Also, the error message returned must be copied to preserve it
1284 ACQUIRE_LOCK(&dl_mutex);
1285 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1289 /* dlopen failed; return a ptr to the error msg. */
1291 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1292 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1293 strcpy(errmsg_copy, errmsg);
1294 errmsg = errmsg_copy;
1296 RELEASE_LOCK(&dl_mutex);
1297 //--------------- End critical section -------------------
1304 addDLL( char *dll_name )
1306 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1307 /* ------------------- ELF DLL loader ------------------- */
1310 regmatch_t match[NMATCH];
1313 size_t match_length;
1314 #define MAXLINE 1000
1320 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1321 errmsg = internal_dlopen(dll_name);
1323 if (errmsg == NULL) {
1327 // GHC Trac ticket #2615
1328 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1329 // contain linker scripts rather than ELF-format object code. This
1330 // code handles the situation by recognizing the real object code
1331 // file name given in the linker script.
1333 // If an "invalid ELF header" error occurs, it is assumed that the
1334 // .so file contains a linker script instead of ELF object code.
1335 // In this case, the code looks for the GROUP ( ... ) linker
1336 // directive. If one is found, the first file name inside the
1337 // parentheses is treated as the name of a dynamic library and the
1338 // code attempts to dlopen that file. If this is also unsuccessful,
1339 // an error message is returned.
1341 // see if the error message is due to an invalid ELF header
1342 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1343 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1344 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1346 // success -- try to read the named file as a linker script
1347 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1349 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1350 line[match_length] = '\0'; // make sure string is null-terminated
1351 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1352 if ((fp = fopen(line, "r")) == NULL) {
1353 return errmsg; // return original error if open fails
1355 // try to find a GROUP ( ... ) command
1356 while (fgets(line, MAXLINE, fp) != NULL) {
1357 IF_DEBUG(linker, debugBelch("input line = %s", line));
1358 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1359 // success -- try to dlopen the first named file
1360 IF_DEBUG(linker, debugBelch("match%s\n",""));
1361 line[match[1].rm_eo] = '\0';
1362 errmsg = internal_dlopen(line+match[1].rm_so);
1365 // if control reaches here, no GROUP ( ... ) directive was found
1366 // and the original error message is returned to the caller
1372 # elif defined(OBJFORMAT_PEi386)
1373 /* ------------------- Win32 DLL loader ------------------- */
1381 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1383 /* See if we've already got it, and ignore if so. */
1384 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1385 if (0 == strcmp(o_dll->name, dll_name))
1389 /* The file name has no suffix (yet) so that we can try
1390 both foo.dll and foo.drv
1392 The documentation for LoadLibrary says:
1393 If no file name extension is specified in the lpFileName
1394 parameter, the default library extension .dll is
1395 appended. However, the file name string can include a trailing
1396 point character (.) to indicate that the module name has no
1399 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1400 sprintf(buf, "%s.DLL", dll_name);
1401 instance = LoadLibrary(buf);
1402 if (instance == NULL) {
1403 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1404 // KAA: allow loading of drivers (like winspool.drv)
1405 sprintf(buf, "%s.DRV", dll_name);
1406 instance = LoadLibrary(buf);
1407 if (instance == NULL) {
1408 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1409 // #1883: allow loading of unix-style libfoo.dll DLLs
1410 sprintf(buf, "lib%s.DLL", dll_name);
1411 instance = LoadLibrary(buf);
1412 if (instance == NULL) {
1419 /* Add this DLL to the list of DLLs in which to search for symbols. */
1420 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1421 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
1422 strcpy(o_dll->name, dll_name);
1423 o_dll->instance = instance;
1424 o_dll->next = opened_dlls;
1425 opened_dlls = o_dll;
1431 sysErrorBelch(dll_name);
1433 /* LoadLibrary failed; return a ptr to the error msg. */
1434 return "addDLL: could not load DLL";
1437 barf("addDLL: not implemented on this platform");
1441 /* -----------------------------------------------------------------------------
1442 * insert a stable symbol in the hash table
1446 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1448 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1452 /* -----------------------------------------------------------------------------
1453 * insert a symbol in the hash table
1456 insertSymbol(char* obj_name, char* key, void* data)
1458 ghciInsertStrHashTable(obj_name, symhash, key, data);
1461 /* -----------------------------------------------------------------------------
1462 * lookup a symbol in the hash table
1465 lookupSymbol( char *lbl )
1468 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s\n", lbl));
1470 ASSERT(symhash != NULL);
1471 val = lookupStrHashTable(symhash, lbl);
1474 IF_DEBUG(linker, debugBelch("lookupSymbol: symbol not found\n"));
1475 # if defined(OBJFORMAT_ELF)
1476 return dlsym(dl_prog_handle, lbl);
1477 # elif defined(OBJFORMAT_MACHO)
1479 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1482 HACK: On OS X, global symbols are prefixed with an underscore.
1483 However, dlsym wants us to omit the leading underscore from the
1484 symbol name. For now, we simply strip it off here (and ONLY
1487 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s with dlsym\n", lbl));
1488 ASSERT(lbl[0] == '_');
1489 return dlsym(dl_prog_handle, lbl+1);
1491 if(NSIsSymbolNameDefined(lbl)) {
1492 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1493 return NSAddressOfSymbol(symbol);
1497 # endif /* HAVE_DLFCN_H */
1498 # elif defined(OBJFORMAT_PEi386)
1501 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1502 if (sym != NULL) { return sym; };
1504 // Also try looking up the symbol without the @N suffix. Some
1505 // DLLs have the suffixes on their symbols, some don't.
1506 zapTrailingAtSign ( (unsigned char*)lbl );
1507 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1508 if (sym != NULL) { return sym; };
1516 IF_DEBUG(linker, debugBelch("lookupSymbol: value of %s is %p\n", lbl, val));
1521 /* -----------------------------------------------------------------------------
1522 * Debugging aid: look in GHCi's object symbol tables for symbols
1523 * within DELTA bytes of the specified address, and show their names.
1526 void ghci_enquire ( char* addr );
1528 void ghci_enquire ( char* addr )
1533 const int DELTA = 64;
1538 for (oc = objects; oc; oc = oc->next) {
1539 for (i = 0; i < oc->n_symbols; i++) {
1540 sym = oc->symbols[i];
1541 if (sym == NULL) continue;
1544 a = lookupStrHashTable(symhash, sym);
1547 // debugBelch("ghci_enquire: can't find %s\n", sym);
1549 else if (addr-DELTA <= a && a <= addr+DELTA) {
1550 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1558 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1561 mmapForLinker (size_t bytes, nat flags, int fd)
1563 void *map_addr = NULL;
1566 static nat fixed = 0;
1568 pagesize = getpagesize();
1569 size = ROUND_UP(bytes, pagesize);
1571 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1574 if (mmap_32bit_base != 0) {
1575 map_addr = mmap_32bit_base;
1579 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1580 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1582 if (result == MAP_FAILED) {
1583 sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1584 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1585 stg_exit(EXIT_FAILURE);
1588 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1589 if (mmap_32bit_base != 0) {
1590 if (result == map_addr) {
1591 mmap_32bit_base = (StgWord8*)map_addr + size;
1593 if ((W_)result > 0x80000000) {
1594 // oops, we were given memory over 2Gb
1595 #if defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS)
1596 // Some platforms require MAP_FIXED. This is normally
1597 // a bad idea, because MAP_FIXED will overwrite
1598 // existing mappings.
1599 munmap(result,size);
1603 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);
1606 // hmm, we were given memory somewhere else, but it's
1607 // still under 2Gb so we can use it. Next time, ask
1608 // for memory right after the place we just got some
1609 mmap_32bit_base = (StgWord8*)result + size;
1613 if ((W_)result > 0x80000000) {
1614 // oops, we were given memory over 2Gb
1615 // ... try allocating memory somewhere else?;
1616 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1617 munmap(result, size);
1619 // Set a base address and try again... (guess: 1Gb)
1620 mmap_32bit_base = (void*)0x40000000;
1631 mkOc( char *path, char *image, int imageSize,
1632 char *archiveMemberName
1634 #ifdef darwin_HOST_OS
1641 oc = stgMallocBytes(sizeof(ObjectCode), "loadArchive(oc)");
1643 # if defined(OBJFORMAT_ELF)
1644 oc->formatName = "ELF";
1645 # elif defined(OBJFORMAT_PEi386)
1646 oc->formatName = "PEi386";
1647 # elif defined(OBJFORMAT_MACHO)
1648 oc->formatName = "Mach-O";
1651 barf("loadObj: not implemented on this platform");
1655 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1656 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1657 strcpy(oc->fileName, path);
1659 if (archiveMemberName) {
1660 oc->archiveMemberName = stgMallocBytes( strlen(archiveMemberName)+1, "loadObj" );
1661 strcpy(oc->archiveMemberName, archiveMemberName);
1664 oc->archiveMemberName = NULL;
1667 oc->fileSize = imageSize;
1669 oc->sections = NULL;
1670 oc->proddables = NULL;
1673 #ifdef darwin_HOST_OS
1674 oc->misalignment = misalignment;
1678 /* chain it onto the list of objects */
1686 loadArchive( char *path )
1693 size_t thisFileNameSize;
1695 size_t fileNameSize;
1696 int isObject, isGnuIndex;
1699 int gnuFileIndexSize;
1700 #if !defined(USE_MMAP) && defined(darwin_HOST_OS)
1704 IF_DEBUG(linker, debugBelch("loadArchive: Loading archive `%s'\n", path));
1706 gnuFileIndex = NULL;
1707 gnuFileIndexSize = 0;
1710 fileName = stgMallocBytes(fileNameSize, "loadArchive(fileName)");
1712 f = fopen(path, "rb");
1714 barf("loadObj: can't read `%s'", path);
1716 n = fread ( tmp, 1, 8, f );
1717 if (strncmp(tmp, "!<arch>\n", 8) != 0)
1718 barf("loadArchive: Not an archive: `%s'", path);
1721 n = fread ( fileName, 1, 16, f );
1727 barf("loadArchive: Failed reading file name from `%s'", path);
1730 n = fread ( tmp, 1, 12, f );
1732 barf("loadArchive: Failed reading mod time from `%s'", path);
1733 n = fread ( tmp, 1, 6, f );
1735 barf("loadArchive: Failed reading owner from `%s'", path);
1736 n = fread ( tmp, 1, 6, f );
1738 barf("loadArchive: Failed reading group from `%s'", path);
1739 n = fread ( tmp, 1, 8, f );
1741 barf("loadArchive: Failed reading mode from `%s'", path);
1742 n = fread ( tmp, 1, 10, f );
1744 barf("loadArchive: Failed reading size from `%s'", path);
1746 for (n = 0; isdigit(tmp[n]); n++);
1748 memberSize = atoi(tmp);
1749 n = fread ( tmp, 1, 2, f );
1750 if (strncmp(tmp, "\x60\x0A", 2) != 0)
1751 barf("loadArchive: Failed reading magic from `%s' at %ld. Got %c%c",
1752 path, ftell(f), tmp[0], tmp[1]);
1755 /* Check for BSD-variant large filenames */
1756 if (0 == strncmp(fileName, "#1/", 3)) {
1757 fileName[16] = '\0';
1758 if (isdigit(fileName[3])) {
1759 for (n = 4; isdigit(fileName[n]); n++);
1761 thisFileNameSize = atoi(fileName + 3);
1762 memberSize -= thisFileNameSize;
1763 if (thisFileNameSize >= fileNameSize) {
1764 /* Double it to avoid potentially continually
1765 increasing it by 1 */
1766 fileNameSize = thisFileNameSize * 2;
1767 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1769 n = fread ( fileName, 1, thisFileNameSize, f );
1770 if (n != (int)thisFileNameSize) {
1771 barf("loadArchive: Failed reading filename from `%s'",
1774 fileName[thisFileNameSize] = 0;
1777 barf("loadArchive: BSD-variant filename size not found while reading filename from `%s'", path);
1780 /* Check for GNU file index file */
1781 else if (0 == strncmp(fileName, "//", 2)) {
1783 thisFileNameSize = 0;
1786 /* Check for a file in the GNU file index */
1787 else if (fileName[0] == '/') {
1788 if (isdigit(fileName[1])) {
1791 for (n = 2; isdigit(fileName[n]); n++);
1793 n = atoi(fileName + 1);
1795 if (gnuFileIndex == NULL) {
1796 barf("loadArchive: GNU-variant filename without an index while reading from `%s'", path);
1798 if (n < 0 || n > gnuFileIndexSize) {
1799 barf("loadArchive: GNU-variant filename offset %d out of range [0..%d] while reading filename from `%s'", n, gnuFileIndexSize, path);
1801 if (n != 0 && gnuFileIndex[n - 1] != '\n') {
1802 barf("loadArchive: GNU-variant filename offset %d invalid (range [0..%d]) while reading filename from `%s'", n, gnuFileIndexSize, path);
1804 for (i = n; gnuFileIndex[i] != '/'; i++);
1805 thisFileNameSize = i - n;
1806 if (thisFileNameSize >= fileNameSize) {
1807 /* Double it to avoid potentially continually
1808 increasing it by 1 */
1809 fileNameSize = thisFileNameSize * 2;
1810 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1812 memcpy(fileName, gnuFileIndex + n, thisFileNameSize);
1813 fileName[thisFileNameSize] = '\0';
1815 else if (fileName[1] == ' ') {
1817 thisFileNameSize = 0;
1820 barf("loadArchive: GNU-variant filename offset not found while reading filename from `%s'", path);
1823 /* Finally, the case where the filename field actually contains
1826 /* GNU ar terminates filenames with a '/', this allowing
1827 spaces in filenames. So first look to see if there is a
1829 for (thisFileNameSize = 0;
1830 thisFileNameSize < 16;
1831 thisFileNameSize++) {
1832 if (fileName[thisFileNameSize] == '/') {
1833 fileName[thisFileNameSize] = '\0';
1837 /* If we didn't find a '/', then a space teminates the
1838 filename. Note that if we don't find one, then
1839 thisFileNameSize ends up as 16, and we already have the
1841 if (thisFileNameSize == 16) {
1842 for (thisFileNameSize = 0;
1843 thisFileNameSize < 16;
1844 thisFileNameSize++) {
1845 if (fileName[thisFileNameSize] == ' ') {
1846 fileName[thisFileNameSize] = '\0';
1854 debugBelch("loadArchive: Found member file `%s'\n", fileName));
1856 isObject = thisFileNameSize >= 2
1857 && fileName[thisFileNameSize - 2] == '.'
1858 && fileName[thisFileNameSize - 1] == 'o';
1861 char *archiveMemberName;
1863 IF_DEBUG(linker, debugBelch("loadArchive: Member is an object file...loading...\n"));
1865 /* We can't mmap from the archive directly, as object
1866 files need to be 8-byte aligned but files in .ar
1867 archives are 2-byte aligned. When possible we use mmap
1868 to get some anonymous memory, as on 64-bit platforms if
1869 we use malloc then we can be given memory above 2^32.
1870 In the mmap case we're probably wasting lots of space;
1871 we could do better. */
1872 #if defined(USE_MMAP)
1873 image = mmapForLinker(memberSize, MAP_ANONYMOUS, -1);
1874 #elif defined(darwin_HOST_OS)
1876 misalignment = machoGetMisalignment(f);
1877 image = stgMallocBytes(memberSize + misalignment, "loadArchive(image)");
1878 image += misalignment;
1880 image = stgMallocBytes(memberSize, "loadArchive(image)");
1882 n = fread ( image, 1, memberSize, f );
1883 if (n != memberSize) {
1884 barf("loadArchive: error whilst reading `%s'", path);
1887 archiveMemberName = stgMallocBytes(strlen(path) + thisFileNameSize + 3,
1888 "loadArchive(file)");
1889 sprintf(archiveMemberName, "%s(%.*s)",
1890 path, (int)thisFileNameSize, fileName);
1892 oc = mkOc(path, image, memberSize, archiveMemberName
1894 #ifdef darwin_HOST_OS
1900 stgFree(archiveMemberName);
1902 if (0 == loadOc(oc)) {
1907 else if (isGnuIndex) {
1908 if (gnuFileIndex != NULL) {
1909 barf("loadArchive: GNU-variant index found, but already have an index, while reading filename from `%s'", path);
1911 IF_DEBUG(linker, debugBelch("loadArchive: Found GNU-variant file index\n"));
1913 gnuFileIndex = mmapForLinker(memberSize + 1, MAP_ANONYMOUS, -1);
1915 gnuFileIndex = stgMallocBytes(memberSize + 1, "loadArchive(image)");
1917 n = fread ( gnuFileIndex, 1, memberSize, f );
1918 if (n != memberSize) {
1919 barf("loadArchive: error whilst reading `%s'", path);
1921 gnuFileIndex[memberSize] = '/';
1922 gnuFileIndexSize = memberSize;
1925 n = fseek(f, memberSize, SEEK_CUR);
1927 barf("loadArchive: error whilst seeking by %d in `%s'",
1930 /* .ar files are 2-byte aligned */
1931 if (memberSize % 2) {
1932 n = fread ( tmp, 1, 1, f );
1938 barf("loadArchive: Failed reading padding from `%s'", path);
1947 if (gnuFileIndex != NULL) {
1949 munmap(gnuFileIndex, gnuFileIndexSize + 1);
1951 stgFree(gnuFileIndex);
1958 /* -----------------------------------------------------------------------------
1959 * Load an obj (populate the global symbol table, but don't resolve yet)
1961 * Returns: 1 if ok, 0 on error.
1964 loadObj( char *path )
1975 # if defined(darwin_HOST_OS)
1979 IF_DEBUG(linker, debugBelch("loadObj %s\n", path));
1983 /* debugBelch("loadObj %s\n", path ); */
1985 /* Check that we haven't already loaded this object.
1986 Ignore requests to load multiple times */
1990 for (o = objects; o; o = o->next) {
1991 if (0 == strcmp(o->fileName, path)) {
1993 break; /* don't need to search further */
1997 IF_DEBUG(linker, debugBelch(
1998 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1999 "same object file twice:\n"
2001 "GHCi will ignore this, but be warned.\n"
2003 return 1; /* success */
2007 r = stat(path, &st);
2009 IF_DEBUG(linker, debugBelch("File doesn't exist\n"));
2013 fileSize = st.st_size;
2016 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
2018 #if defined(openbsd_HOST_OS)
2019 fd = open(path, O_RDONLY, S_IRUSR);
2021 fd = open(path, O_RDONLY);
2024 barf("loadObj: can't open `%s'", path);
2026 image = mmapForLinker(fileSize, 0, fd);
2030 #else /* !USE_MMAP */
2031 /* load the image into memory */
2032 f = fopen(path, "rb");
2034 barf("loadObj: can't read `%s'", path);
2036 # if defined(mingw32_HOST_OS)
2037 // TODO: We would like to use allocateExec here, but allocateExec
2038 // cannot currently allocate blocks large enough.
2039 image = VirtualAlloc(NULL, fileSize, MEM_RESERVE | MEM_COMMIT,
2040 PAGE_EXECUTE_READWRITE);
2041 # elif defined(darwin_HOST_OS)
2042 // In a Mach-O .o file, all sections can and will be misaligned
2043 // if the total size of the headers is not a multiple of the
2044 // desired alignment. This is fine for .o files that only serve
2045 // as input for the static linker, but it's not fine for us,
2046 // as SSE (used by gcc for floating point) and Altivec require
2047 // 16-byte alignment.
2048 // We calculate the correct alignment from the header before
2049 // reading the file, and then we misalign image on purpose so
2050 // that the actual sections end up aligned again.
2051 misalignment = machoGetMisalignment(f);
2052 image = stgMallocBytes(fileSize + misalignment, "loadObj(image)");
2053 image += misalignment;
2055 image = stgMallocBytes(fileSize, "loadObj(image)");
2060 n = fread ( image, 1, fileSize, f );
2062 barf("loadObj: error whilst reading `%s'", path);
2065 #endif /* USE_MMAP */
2067 oc = mkOc(path, image, fileSize, NULL
2069 #ifdef darwin_HOST_OS
2079 loadOc( ObjectCode* oc ) {
2082 IF_DEBUG(linker, debugBelch("loadOc\n"));
2084 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2085 r = ocAllocateSymbolExtras_MachO ( oc );
2087 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO failed\n"));
2090 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2091 r = ocAllocateSymbolExtras_ELF ( oc );
2093 IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_ELF failed\n"));
2098 /* verify the in-memory image */
2099 # if defined(OBJFORMAT_ELF)
2100 r = ocVerifyImage_ELF ( oc );
2101 # elif defined(OBJFORMAT_PEi386)
2102 r = ocVerifyImage_PEi386 ( oc );
2103 # elif defined(OBJFORMAT_MACHO)
2104 r = ocVerifyImage_MachO ( oc );
2106 barf("loadObj: no verify method");
2109 IF_DEBUG(linker, debugBelch("ocVerifyImage_* failed\n"));
2113 /* build the symbol list for this image */
2114 # if defined(OBJFORMAT_ELF)
2115 r = ocGetNames_ELF ( oc );
2116 # elif defined(OBJFORMAT_PEi386)
2117 r = ocGetNames_PEi386 ( oc );
2118 # elif defined(OBJFORMAT_MACHO)
2119 r = ocGetNames_MachO ( oc );
2121 barf("loadObj: no getNames method");
2124 IF_DEBUG(linker, debugBelch("ocGetNames_* failed\n"));
2128 /* loaded, but not resolved yet */
2129 oc->status = OBJECT_LOADED;
2130 IF_DEBUG(linker, debugBelch("loadObj done.\n"));
2135 /* -----------------------------------------------------------------------------
2136 * resolve all the currently unlinked objects in memory
2138 * Returns: 1 if ok, 0 on error.
2146 IF_DEBUG(linker, debugBelch("resolveObjs: start\n"));
2149 for (oc = objects; oc; oc = oc->next) {
2150 if (oc->status != OBJECT_RESOLVED) {
2151 # if defined(OBJFORMAT_ELF)
2152 r = ocResolve_ELF ( oc );
2153 # elif defined(OBJFORMAT_PEi386)
2154 r = ocResolve_PEi386 ( oc );
2155 # elif defined(OBJFORMAT_MACHO)
2156 r = ocResolve_MachO ( oc );
2158 barf("resolveObjs: not implemented on this platform");
2160 if (!r) { return r; }
2161 oc->status = OBJECT_RESOLVED;
2164 IF_DEBUG(linker, debugBelch("resolveObjs: done\n"));
2168 /* -----------------------------------------------------------------------------
2169 * delete an object from the pool
2172 unloadObj( char *path )
2174 ObjectCode *oc, *prev;
2175 HsBool unloadedAnyObj = HS_BOOL_FALSE;
2177 ASSERT(symhash != NULL);
2178 ASSERT(objects != NULL);
2183 for (oc = objects; oc; prev = oc, oc = oc->next) {
2184 if (!strcmp(oc->fileName,path)) {
2186 /* Remove all the mappings for the symbols within this
2191 for (i = 0; i < oc->n_symbols; i++) {
2192 if (oc->symbols[i] != NULL) {
2193 removeStrHashTable(symhash, oc->symbols[i], NULL);
2201 prev->next = oc->next;
2204 // We're going to leave this in place, in case there are
2205 // any pointers from the heap into it:
2206 // #ifdef mingw32_HOST_OS
2207 // VirtualFree(oc->image);
2209 // stgFree(oc->image);
2211 stgFree(oc->fileName);
2212 stgFree(oc->symbols);
2213 stgFree(oc->sections);
2216 /* This could be a member of an archive so continue
2217 * unloading other members. */
2218 unloadedAnyObj = HS_BOOL_TRUE;
2222 if (unloadedAnyObj) {
2226 errorBelch("unloadObj: can't find `%s' to unload", path);
2231 /* -----------------------------------------------------------------------------
2232 * Sanity checking. For each ObjectCode, maintain a list of address ranges
2233 * which may be prodded during relocation, and abort if we try and write
2234 * outside any of these.
2236 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
2239 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
2240 IF_DEBUG(linker, debugBelch("addProddableBlock %p %p %d\n", oc, start, size));
2244 pb->next = oc->proddables;
2245 oc->proddables = pb;
2248 static void checkProddableBlock ( ObjectCode* oc, void* addr )
2251 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
2252 char* s = (char*)(pb->start);
2253 char* e = s + pb->size - 1;
2254 char* a = (char*)addr;
2255 /* Assumes that the biggest fixup involves a 4-byte write. This
2256 probably needs to be changed to 8 (ie, +7) on 64-bit
2258 if (a >= s && (a+3) <= e) return;
2260 barf("checkProddableBlock: invalid fixup in runtime linker");
2263 /* -----------------------------------------------------------------------------
2264 * Section management.
2266 static void addSection ( ObjectCode* oc, SectionKind kind,
2267 void* start, void* end )
2269 Section* s = stgMallocBytes(sizeof(Section), "addSection");
2273 s->next = oc->sections;
2276 debugBelch("addSection: %p-%p (size %d), kind %d\n",
2277 start, ((char*)end)-1, end - start + 1, kind );
2282 /* --------------------------------------------------------------------------
2284 * This is about allocating a small chunk of memory for every symbol in the
2285 * object file. We make sure that the SymboLExtras are always "in range" of
2286 * limited-range PC-relative instructions on various platforms by allocating
2287 * them right next to the object code itself.
2290 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2293 ocAllocateSymbolExtras
2295 Allocate additional space at the end of the object file image to make room
2296 for jump islands (powerpc, x86_64) and GOT entries (x86_64).
2298 PowerPC relative branch instructions have a 24 bit displacement field.
2299 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
2300 If a particular imported symbol is outside this range, we have to redirect
2301 the jump to a short piece of new code that just loads the 32bit absolute
2302 address and jumps there.
2303 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
2306 This function just allocates space for one SymbolExtra for every
2307 undefined symbol in the object file. The code for the jump islands is
2308 filled in by makeSymbolExtra below.
2311 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
2318 int misalignment = 0;
2319 #ifdef darwin_HOST_OS
2320 misalignment = oc->misalignment;
2326 // round up to the nearest 4
2327 aligned = (oc->fileSize + 3) & ~3;
2330 pagesize = getpagesize();
2331 n = ROUND_UP( oc->fileSize, pagesize );
2332 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
2334 /* we try to use spare space at the end of the last page of the
2335 * image for the jump islands, but if there isn't enough space
2336 * then we have to map some (anonymously, remembering MAP_32BIT).
2338 if( m > n ) // we need to allocate more pages
2340 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
2345 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2348 oc->image -= misalignment;
2349 oc->image = stgReallocBytes( oc->image,
2351 aligned + sizeof (SymbolExtra) * count,
2352 "ocAllocateSymbolExtras" );
2353 oc->image += misalignment;
2355 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2356 #endif /* USE_MMAP */
2358 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
2361 oc->symbol_extras = NULL;
2363 oc->first_symbol_extra = first;
2364 oc->n_symbol_extras = count;
2369 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
2370 unsigned long symbolNumber,
2371 unsigned long target )
2375 ASSERT( symbolNumber >= oc->first_symbol_extra
2376 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
2378 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
2380 #ifdef powerpc_HOST_ARCH
2381 // lis r12, hi16(target)
2382 extra->jumpIsland.lis_r12 = 0x3d80;
2383 extra->jumpIsland.hi_addr = target >> 16;
2385 // ori r12, r12, lo16(target)
2386 extra->jumpIsland.ori_r12_r12 = 0x618c;
2387 extra->jumpIsland.lo_addr = target & 0xffff;
2390 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2393 extra->jumpIsland.bctr = 0x4e800420;
2395 #ifdef x86_64_HOST_ARCH
2397 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2398 extra->addr = target;
2399 memcpy(extra->jumpIsland, jmp, 6);
2407 /* --------------------------------------------------------------------------
2408 * PowerPC specifics (instruction cache flushing)
2409 * ------------------------------------------------------------------------*/
2411 #ifdef powerpc_HOST_ARCH
2413 ocFlushInstructionCache
2415 Flush the data & instruction caches.
2416 Because the PPC has split data/instruction caches, we have to
2417 do that whenever we modify code at runtime.
2419 static void ocFlushInstructionCacheFrom(void* begin, size_t length)
2421 size_t n = (length + 3) / 4;
2422 unsigned long* p = begin;
2426 __asm__ volatile ( "dcbf 0,%0\n\t"
2434 __asm__ volatile ( "sync\n\t"
2438 static void ocFlushInstructionCache( ObjectCode *oc )
2440 /* The main object code */
2441 ocFlushInstructionCacheFrom(oc->image + oc->misalignment, oc->fileSize);
2444 ocFlushInstructionCacheFrom(oc->symbol_extras, sizeof(SymbolExtra) * oc->n_symbol_extras);
2448 /* --------------------------------------------------------------------------
2449 * PEi386 specifics (Win32 targets)
2450 * ------------------------------------------------------------------------*/
2452 /* The information for this linker comes from
2453 Microsoft Portable Executable
2454 and Common Object File Format Specification
2455 revision 5.1 January 1998
2456 which SimonM says comes from the MS Developer Network CDs.
2458 It can be found there (on older CDs), but can also be found
2461 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
2463 (this is Rev 6.0 from February 1999).
2465 Things move, so if that fails, try searching for it via
2467 http://www.google.com/search?q=PE+COFF+specification
2469 The ultimate reference for the PE format is the Winnt.h
2470 header file that comes with the Platform SDKs; as always,
2471 implementations will drift wrt their documentation.
2473 A good background article on the PE format is Matt Pietrek's
2474 March 1994 article in Microsoft System Journal (MSJ)
2475 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
2476 Win32 Portable Executable File Format." The info in there
2477 has recently been updated in a two part article in
2478 MSDN magazine, issues Feb and March 2002,
2479 "Inside Windows: An In-Depth Look into the Win32 Portable
2480 Executable File Format"
2482 John Levine's book "Linkers and Loaders" contains useful
2487 #if defined(OBJFORMAT_PEi386)
2491 typedef unsigned char UChar;
2492 typedef unsigned short UInt16;
2493 typedef unsigned int UInt32;
2500 UInt16 NumberOfSections;
2501 UInt32 TimeDateStamp;
2502 UInt32 PointerToSymbolTable;
2503 UInt32 NumberOfSymbols;
2504 UInt16 SizeOfOptionalHeader;
2505 UInt16 Characteristics;
2509 #define sizeof_COFF_header 20
2516 UInt32 VirtualAddress;
2517 UInt32 SizeOfRawData;
2518 UInt32 PointerToRawData;
2519 UInt32 PointerToRelocations;
2520 UInt32 PointerToLinenumbers;
2521 UInt16 NumberOfRelocations;
2522 UInt16 NumberOfLineNumbers;
2523 UInt32 Characteristics;
2527 #define sizeof_COFF_section 40
2534 UInt16 SectionNumber;
2537 UChar NumberOfAuxSymbols;
2541 #define sizeof_COFF_symbol 18
2546 UInt32 VirtualAddress;
2547 UInt32 SymbolTableIndex;
2552 #define sizeof_COFF_reloc 10
2555 /* From PE spec doc, section 3.3.2 */
2556 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
2557 windows.h -- for the same purpose, but I want to know what I'm
2559 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
2560 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
2561 #define MYIMAGE_FILE_DLL 0x2000
2562 #define MYIMAGE_FILE_SYSTEM 0x1000
2563 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
2564 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
2565 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
2567 /* From PE spec doc, section 5.4.2 and 5.4.4 */
2568 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
2569 #define MYIMAGE_SYM_CLASS_STATIC 3
2570 #define MYIMAGE_SYM_UNDEFINED 0
2572 /* From PE spec doc, section 4.1 */
2573 #define MYIMAGE_SCN_CNT_CODE 0x00000020
2574 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
2575 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
2577 /* From PE spec doc, section 5.2.1 */
2578 #define MYIMAGE_REL_I386_DIR32 0x0006
2579 #define MYIMAGE_REL_I386_REL32 0x0014
2582 /* We use myindex to calculate array addresses, rather than
2583 simply doing the normal subscript thing. That's because
2584 some of the above structs have sizes which are not
2585 a whole number of words. GCC rounds their sizes up to a
2586 whole number of words, which means that the address calcs
2587 arising from using normal C indexing or pointer arithmetic
2588 are just plain wrong. Sigh.
2591 myindex ( int scale, void* base, int index )
2594 ((UChar*)base) + scale * index;
2599 printName ( UChar* name, UChar* strtab )
2601 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2602 UInt32 strtab_offset = * (UInt32*)(name+4);
2603 debugBelch("%s", strtab + strtab_offset );
2606 for (i = 0; i < 8; i++) {
2607 if (name[i] == 0) break;
2608 debugBelch("%c", name[i] );
2615 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
2617 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2618 UInt32 strtab_offset = * (UInt32*)(name+4);
2619 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
2625 if (name[i] == 0) break;
2635 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
2638 /* If the string is longer than 8 bytes, look in the
2639 string table for it -- this will be correctly zero terminated.
2641 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2642 UInt32 strtab_offset = * (UInt32*)(name+4);
2643 return ((UChar*)strtab) + strtab_offset;
2645 /* Otherwise, if shorter than 8 bytes, return the original,
2646 which by defn is correctly terminated.
2648 if (name[7]==0) return name;
2649 /* The annoying case: 8 bytes. Copy into a temporary
2650 (XXX which is never freed ...)
2652 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
2654 strncpy((char*)newstr,(char*)name,8);
2659 /* Getting the name of a section is mildly tricky, so we make a
2660 function for it. Sadly, in one case we have to copy the string
2661 (when it is exactly 8 bytes long there's no trailing '\0'), so for
2662 consistency we *always* copy the string; the caller must free it
2665 cstring_from_section_name (UChar* name, UChar* strtab)
2670 int strtab_offset = strtol((char*)name+1,NULL,10);
2671 int len = strlen(((char*)strtab) + strtab_offset);
2673 newstr = stgMallocBytes(len, "cstring_from_section_symbol_name");
2674 strcpy((char*)newstr, (char*)((UChar*)strtab) + strtab_offset);
2679 newstr = stgMallocBytes(9, "cstring_from_section_symbol_name");
2681 strncpy((char*)newstr,(char*)name,8);
2687 /* Just compares the short names (first 8 chars) */
2688 static COFF_section *
2689 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
2693 = (COFF_header*)(oc->image);
2694 COFF_section* sectab
2696 ((UChar*)(oc->image))
2697 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2699 for (i = 0; i < hdr->NumberOfSections; i++) {
2702 COFF_section* section_i
2704 myindex ( sizeof_COFF_section, sectab, i );
2705 n1 = (UChar*) &(section_i->Name);
2707 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2708 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2709 n1[6]==n2[6] && n1[7]==n2[7])
2718 zapTrailingAtSign ( UChar* sym )
2720 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2722 if (sym[0] == 0) return;
2724 while (sym[i] != 0) i++;
2727 while (j > 0 && my_isdigit(sym[j])) j--;
2728 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2733 lookupSymbolInDLLs ( UChar *lbl )
2738 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2739 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2741 if (lbl[0] == '_') {
2742 /* HACK: if the name has an initial underscore, try stripping
2743 it off & look that up first. I've yet to verify whether there's
2744 a Rule that governs whether an initial '_' *should always* be
2745 stripped off when mapping from import lib name to the DLL name.
2747 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
2749 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2753 sym = GetProcAddress(o_dll->instance, (char*)lbl);
2755 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2764 ocVerifyImage_PEi386 ( ObjectCode* oc )
2769 COFF_section* sectab;
2770 COFF_symbol* symtab;
2772 /* debugBelch("\nLOADING %s\n", oc->fileName); */
2773 hdr = (COFF_header*)(oc->image);
2774 sectab = (COFF_section*) (
2775 ((UChar*)(oc->image))
2776 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2778 symtab = (COFF_symbol*) (
2779 ((UChar*)(oc->image))
2780 + hdr->PointerToSymbolTable
2782 strtab = ((UChar*)symtab)
2783 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2785 if (hdr->Machine != 0x14c) {
2786 errorBelch("%s: Not x86 PEi386", oc->fileName);
2789 if (hdr->SizeOfOptionalHeader != 0) {
2790 errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2793 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2794 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2795 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2796 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2797 errorBelch("%s: Not a PEi386 object file", oc->fileName);
2800 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2801 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2802 errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2804 (int)(hdr->Characteristics));
2807 /* If the string table size is way crazy, this might indicate that
2808 there are more than 64k relocations, despite claims to the
2809 contrary. Hence this test. */
2810 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2812 if ( (*(UInt32*)strtab) > 600000 ) {
2813 /* Note that 600k has no special significance other than being
2814 big enough to handle the almost-2MB-sized lumps that
2815 constitute HSwin32*.o. */
2816 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2821 /* No further verification after this point; only debug printing. */
2823 IF_DEBUG(linker, i=1);
2824 if (i == 0) return 1;
2826 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2827 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2828 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2831 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
2832 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
2833 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2834 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
2835 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
2836 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
2837 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
2839 /* Print the section table. */
2841 for (i = 0; i < hdr->NumberOfSections; i++) {
2843 COFF_section* sectab_i
2845 myindex ( sizeof_COFF_section, sectab, i );
2852 printName ( sectab_i->Name, strtab );
2862 sectab_i->VirtualSize,
2863 sectab_i->VirtualAddress,
2864 sectab_i->SizeOfRawData,
2865 sectab_i->PointerToRawData,
2866 sectab_i->NumberOfRelocations,
2867 sectab_i->PointerToRelocations,
2868 sectab_i->PointerToRawData
2870 reltab = (COFF_reloc*) (
2871 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2874 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2875 /* If the relocation field (a short) has overflowed, the
2876 * real count can be found in the first reloc entry.
2878 * See Section 4.1 (last para) of the PE spec (rev6.0).
2880 COFF_reloc* rel = (COFF_reloc*)
2881 myindex ( sizeof_COFF_reloc, reltab, 0 );
2882 noRelocs = rel->VirtualAddress;
2885 noRelocs = sectab_i->NumberOfRelocations;
2889 for (; j < noRelocs; j++) {
2891 COFF_reloc* rel = (COFF_reloc*)
2892 myindex ( sizeof_COFF_reloc, reltab, j );
2894 " type 0x%-4x vaddr 0x%-8x name `",
2896 rel->VirtualAddress );
2897 sym = (COFF_symbol*)
2898 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
2899 /* Hmm..mysterious looking offset - what's it for? SOF */
2900 printName ( sym->Name, strtab -10 );
2907 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
2908 debugBelch("---START of string table---\n");
2909 for (i = 4; i < *(Int32*)strtab; i++) {
2911 debugBelch("\n"); else
2912 debugBelch("%c", strtab[i] );
2914 debugBelch("--- END of string table---\n");
2919 COFF_symbol* symtab_i;
2920 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2921 symtab_i = (COFF_symbol*)
2922 myindex ( sizeof_COFF_symbol, symtab, i );
2928 printName ( symtab_i->Name, strtab );
2937 (Int32)(symtab_i->SectionNumber),
2938 (UInt32)symtab_i->Type,
2939 (UInt32)symtab_i->StorageClass,
2940 (UInt32)symtab_i->NumberOfAuxSymbols
2942 i += symtab_i->NumberOfAuxSymbols;
2952 ocGetNames_PEi386 ( ObjectCode* oc )
2955 COFF_section* sectab;
2956 COFF_symbol* symtab;
2963 hdr = (COFF_header*)(oc->image);
2964 sectab = (COFF_section*) (
2965 ((UChar*)(oc->image))
2966 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2968 symtab = (COFF_symbol*) (
2969 ((UChar*)(oc->image))
2970 + hdr->PointerToSymbolTable
2972 strtab = ((UChar*)(oc->image))
2973 + hdr->PointerToSymbolTable
2974 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2976 /* Allocate space for any (local, anonymous) .bss sections. */
2978 for (i = 0; i < hdr->NumberOfSections; i++) {
2981 COFF_section* sectab_i
2983 myindex ( sizeof_COFF_section, sectab, i );
2985 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
2987 if (0 != strcmp(secname, ".bss")) {
2994 /* sof 10/05: the PE spec text isn't too clear regarding what
2995 * the SizeOfRawData field is supposed to hold for object
2996 * file sections containing just uninitialized data -- for executables,
2997 * it is supposed to be zero; unclear what it's supposed to be
2998 * for object files. However, VirtualSize is guaranteed to be
2999 * zero for object files, which definitely suggests that SizeOfRawData
3000 * will be non-zero (where else would the size of this .bss section be
3001 * stored?) Looking at the COFF_section info for incoming object files,
3002 * this certainly appears to be the case.
3004 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
3005 * object files up until now. This turned out to bite us with ghc-6.4.1's use
3006 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
3007 * variable decls into to the .bss section. (The specific function in Q which
3008 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
3010 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
3011 /* This is a non-empty .bss section. Allocate zeroed space for
3012 it, and set its PointerToRawData field such that oc->image +
3013 PointerToRawData == addr_of_zeroed_space. */
3014 bss_sz = sectab_i->VirtualSize;
3015 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
3016 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
3017 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
3018 addProddableBlock(oc, zspace, bss_sz);
3019 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
3022 /* Copy section information into the ObjectCode. */
3024 for (i = 0; i < hdr->NumberOfSections; i++) {
3030 = SECTIONKIND_OTHER;
3031 COFF_section* sectab_i
3033 myindex ( sizeof_COFF_section, sectab, i );
3035 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3037 IF_DEBUG(linker, debugBelch("section name = %s\n", secname ));
3040 /* I'm sure this is the Right Way to do it. However, the
3041 alternative of testing the sectab_i->Name field seems to
3042 work ok with Cygwin.
3044 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
3045 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
3046 kind = SECTIONKIND_CODE_OR_RODATA;
3049 if (0==strcmp(".text",(char*)secname) ||
3050 0==strcmp(".rdata",(char*)secname)||
3051 0==strcmp(".rodata",(char*)secname))
3052 kind = SECTIONKIND_CODE_OR_RODATA;
3053 if (0==strcmp(".data",(char*)secname) ||
3054 0==strcmp(".bss",(char*)secname))
3055 kind = SECTIONKIND_RWDATA;
3057 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
3058 sz = sectab_i->SizeOfRawData;
3059 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
3061 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
3062 end = start + sz - 1;
3064 if (kind == SECTIONKIND_OTHER
3065 /* Ignore sections called which contain stabs debugging
3067 && 0 != strcmp(".stab", (char*)secname)
3068 && 0 != strcmp(".stabstr", (char*)secname)
3069 /* ignore constructor section for now */
3070 && 0 != strcmp(".ctors", (char*)secname)
3071 /* ignore section generated from .ident */
3072 && 0!= strncmp(".debug", (char*)secname, 6)
3073 /* ignore unknown section that appeared in gcc 3.4.5(?) */
3074 && 0!= strcmp(".reloc", (char*)secname)
3075 && 0 != strcmp(".rdata$zzz", (char*)secname)
3077 errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", secname, oc->fileName);
3082 if (kind != SECTIONKIND_OTHER && end >= start) {
3083 addSection(oc, kind, start, end);
3084 addProddableBlock(oc, start, end - start + 1);
3090 /* Copy exported symbols into the ObjectCode. */
3092 oc->n_symbols = hdr->NumberOfSymbols;
3093 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3094 "ocGetNames_PEi386(oc->symbols)");
3095 /* Call me paranoid; I don't care. */
3096 for (i = 0; i < oc->n_symbols; i++)
3097 oc->symbols[i] = NULL;
3101 COFF_symbol* symtab_i;
3102 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3103 symtab_i = (COFF_symbol*)
3104 myindex ( sizeof_COFF_symbol, symtab, i );
3108 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
3109 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
3110 /* This symbol is global and defined, viz, exported */
3111 /* for MYIMAGE_SYMCLASS_EXTERNAL
3112 && !MYIMAGE_SYM_UNDEFINED,
3113 the address of the symbol is:
3114 address of relevant section + offset in section
3116 COFF_section* sectabent
3117 = (COFF_section*) myindex ( sizeof_COFF_section,
3119 symtab_i->SectionNumber-1 );
3120 addr = ((UChar*)(oc->image))
3121 + (sectabent->PointerToRawData
3125 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
3126 && symtab_i->Value > 0) {
3127 /* This symbol isn't in any section at all, ie, global bss.
3128 Allocate zeroed space for it. */
3129 addr = stgCallocBytes(1, symtab_i->Value,
3130 "ocGetNames_PEi386(non-anonymous bss)");
3131 addSection(oc, SECTIONKIND_RWDATA, addr,
3132 ((UChar*)addr) + symtab_i->Value - 1);
3133 addProddableBlock(oc, addr, symtab_i->Value);
3134 /* debugBelch("BSS section at 0x%x\n", addr); */
3137 if (addr != NULL ) {
3138 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
3139 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
3140 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
3141 ASSERT(i >= 0 && i < oc->n_symbols);
3142 /* cstring_from_COFF_symbol_name always succeeds. */
3143 oc->symbols[i] = (char*)sname;
3144 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
3148 "IGNORING symbol %d\n"
3152 printName ( symtab_i->Name, strtab );
3161 (Int32)(symtab_i->SectionNumber),
3162 (UInt32)symtab_i->Type,
3163 (UInt32)symtab_i->StorageClass,
3164 (UInt32)symtab_i->NumberOfAuxSymbols
3169 i += symtab_i->NumberOfAuxSymbols;
3178 ocResolve_PEi386 ( ObjectCode* oc )
3181 COFF_section* sectab;
3182 COFF_symbol* symtab;
3192 /* ToDo: should be variable-sized? But is at least safe in the
3193 sense of buffer-overrun-proof. */
3195 /* debugBelch("resolving for %s\n", oc->fileName); */
3197 hdr = (COFF_header*)(oc->image);
3198 sectab = (COFF_section*) (
3199 ((UChar*)(oc->image))
3200 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3202 symtab = (COFF_symbol*) (
3203 ((UChar*)(oc->image))
3204 + hdr->PointerToSymbolTable
3206 strtab = ((UChar*)(oc->image))
3207 + hdr->PointerToSymbolTable
3208 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3210 for (i = 0; i < hdr->NumberOfSections; i++) {
3211 COFF_section* sectab_i
3213 myindex ( sizeof_COFF_section, sectab, i );
3216 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3219 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3221 /* Ignore sections called which contain stabs debugging
3223 if (0 == strcmp(".stab", (char*)secname)
3224 || 0 == strcmp(".stabstr", (char*)secname)
3225 || 0 == strcmp(".ctors", (char*)secname)
3226 || 0 == strncmp(".debug", (char*)secname, 6)
3227 || 0 == strcmp(".rdata$zzz", (char*)secname)) {
3234 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3235 /* If the relocation field (a short) has overflowed, the
3236 * real count can be found in the first reloc entry.
3238 * See Section 4.1 (last para) of the PE spec (rev6.0).
3240 * Nov2003 update: the GNU linker still doesn't correctly
3241 * handle the generation of relocatable object files with
3242 * overflown relocations. Hence the output to warn of potential
3245 COFF_reloc* rel = (COFF_reloc*)
3246 myindex ( sizeof_COFF_reloc, reltab, 0 );
3247 noRelocs = rel->VirtualAddress;
3249 /* 10/05: we now assume (and check for) a GNU ld that is capable
3250 * of handling object files with (>2^16) of relocs.
3253 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
3258 noRelocs = sectab_i->NumberOfRelocations;
3263 for (; j < noRelocs; j++) {
3265 COFF_reloc* reltab_j
3267 myindex ( sizeof_COFF_reloc, reltab, j );
3269 /* the location to patch */
3271 ((UChar*)(oc->image))
3272 + (sectab_i->PointerToRawData
3273 + reltab_j->VirtualAddress
3274 - sectab_i->VirtualAddress )
3276 /* the existing contents of pP */
3278 /* the symbol to connect to */
3279 sym = (COFF_symbol*)
3280 myindex ( sizeof_COFF_symbol,
3281 symtab, reltab_j->SymbolTableIndex );
3284 "reloc sec %2d num %3d: type 0x%-4x "
3285 "vaddr 0x%-8x name `",
3287 (UInt32)reltab_j->Type,
3288 reltab_j->VirtualAddress );
3289 printName ( sym->Name, strtab );
3290 debugBelch("'\n" ));
3292 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
3293 COFF_section* section_sym
3294 = findPEi386SectionCalled ( oc, sym->Name );
3296 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
3299 S = ((UInt32)(oc->image))
3300 + (section_sym->PointerToRawData
3303 copyName ( sym->Name, strtab, symbol, 1000-1 );
3304 S = (UInt32) lookupSymbol( (char*)symbol );
3305 if ((void*)S != NULL) goto foundit;
3306 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3310 checkProddableBlock(oc, pP);
3311 switch (reltab_j->Type) {
3312 case MYIMAGE_REL_I386_DIR32:
3315 case MYIMAGE_REL_I386_REL32:
3316 /* Tricky. We have to insert a displacement at
3317 pP which, when added to the PC for the _next_
3318 insn, gives the address of the target (S).
3319 Problem is to know the address of the next insn
3320 when we only know pP. We assume that this
3321 literal field is always the last in the insn,
3322 so that the address of the next insn is pP+4
3323 -- hence the constant 4.
3324 Also I don't know if A should be added, but so
3325 far it has always been zero.
3327 SOF 05/2005: 'A' (old contents of *pP) have been observed
3328 to contain values other than zero (the 'wx' object file
3329 that came with wxhaskell-0.9.4; dunno how it was compiled..).
3330 So, add displacement to old value instead of asserting
3331 A to be zero. Fixes wxhaskell-related crashes, and no other
3332 ill effects have been observed.
3334 Update: the reason why we're seeing these more elaborate
3335 relocations is due to a switch in how the NCG compiles SRTs
3336 and offsets to them from info tables. SRTs live in .(ro)data,
3337 while info tables live in .text, causing GAS to emit REL32/DISP32
3338 relocations with non-zero values. Adding the displacement is
3339 the right thing to do.
3341 *pP = S - ((UInt32)pP) - 4 + A;
3344 debugBelch("%s: unhandled PEi386 relocation type %d",
3345 oc->fileName, reltab_j->Type);
3352 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
3356 #endif /* defined(OBJFORMAT_PEi386) */
3359 /* --------------------------------------------------------------------------
3361 * ------------------------------------------------------------------------*/
3363 #if defined(OBJFORMAT_ELF)
3368 #if defined(sparc_HOST_ARCH)
3369 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
3370 #elif defined(i386_HOST_ARCH)
3371 # define ELF_TARGET_386 /* Used inside <elf.h> */
3372 #elif defined(x86_64_HOST_ARCH)
3373 # define ELF_TARGET_X64_64
3377 #if !defined(openbsd_HOST_OS)
3380 /* openbsd elf has things in different places, with diff names */
3381 # include <elf_abi.h>
3382 # include <machine/reloc.h>
3383 # define R_386_32 RELOC_32
3384 # define R_386_PC32 RELOC_PC32
3387 /* If elf.h doesn't define it */
3388 # ifndef R_X86_64_PC64
3389 # define R_X86_64_PC64 24
3393 * Define a set of types which can be used for both ELF32 and ELF64
3397 #define ELFCLASS ELFCLASS64
3398 #define Elf_Addr Elf64_Addr
3399 #define Elf_Word Elf64_Word
3400 #define Elf_Sword Elf64_Sword
3401 #define Elf_Ehdr Elf64_Ehdr
3402 #define Elf_Phdr Elf64_Phdr
3403 #define Elf_Shdr Elf64_Shdr
3404 #define Elf_Sym Elf64_Sym
3405 #define Elf_Rel Elf64_Rel
3406 #define Elf_Rela Elf64_Rela
3408 #define ELF_ST_TYPE ELF64_ST_TYPE
3411 #define ELF_ST_BIND ELF64_ST_BIND
3414 #define ELF_R_TYPE ELF64_R_TYPE
3417 #define ELF_R_SYM ELF64_R_SYM
3420 #define ELFCLASS ELFCLASS32
3421 #define Elf_Addr Elf32_Addr
3422 #define Elf_Word Elf32_Word
3423 #define Elf_Sword Elf32_Sword
3424 #define Elf_Ehdr Elf32_Ehdr
3425 #define Elf_Phdr Elf32_Phdr
3426 #define Elf_Shdr Elf32_Shdr
3427 #define Elf_Sym Elf32_Sym
3428 #define Elf_Rel Elf32_Rel
3429 #define Elf_Rela Elf32_Rela
3431 #define ELF_ST_TYPE ELF32_ST_TYPE
3434 #define ELF_ST_BIND ELF32_ST_BIND
3437 #define ELF_R_TYPE ELF32_R_TYPE
3440 #define ELF_R_SYM ELF32_R_SYM
3446 * Functions to allocate entries in dynamic sections. Currently we simply
3447 * preallocate a large number, and we don't check if a entry for the given
3448 * target already exists (a linear search is too slow). Ideally these
3449 * entries would be associated with symbols.
3452 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
3453 #define GOT_SIZE 0x20000
3454 #define FUNCTION_TABLE_SIZE 0x10000
3455 #define PLT_SIZE 0x08000
3458 static Elf_Addr got[GOT_SIZE];
3459 static unsigned int gotIndex;
3460 static Elf_Addr gp_val = (Elf_Addr)got;
3463 allocateGOTEntry(Elf_Addr target)
3467 if (gotIndex >= GOT_SIZE)
3468 barf("Global offset table overflow");
3470 entry = &got[gotIndex++];
3472 return (Elf_Addr)entry;
3476 #ifdef ELF_FUNCTION_DESC
3482 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
3483 static unsigned int functionTableIndex;
3486 allocateFunctionDesc(Elf_Addr target)
3488 FunctionDesc *entry;
3490 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
3491 barf("Function table overflow");
3493 entry = &functionTable[functionTableIndex++];
3495 entry->gp = (Elf_Addr)gp_val;
3496 return (Elf_Addr)entry;
3500 copyFunctionDesc(Elf_Addr target)
3502 FunctionDesc *olddesc = (FunctionDesc *)target;
3503 FunctionDesc *newdesc;
3505 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
3506 newdesc->gp = olddesc->gp;
3507 return (Elf_Addr)newdesc;
3514 unsigned char code[sizeof(plt_code)];
3518 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
3520 PLTEntry *plt = (PLTEntry *)oc->plt;
3523 if (oc->pltIndex >= PLT_SIZE)
3524 barf("Procedure table overflow");
3526 entry = &plt[oc->pltIndex++];
3527 memcpy(entry->code, plt_code, sizeof(entry->code));
3528 PLT_RELOC(entry->code, target);
3529 return (Elf_Addr)entry;
3535 return (PLT_SIZE * sizeof(PLTEntry));
3541 * Generic ELF functions
3545 findElfSection ( void* objImage, Elf_Word sh_type )
3547 char* ehdrC = (char*)objImage;
3548 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3549 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
3550 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3554 for (i = 0; i < ehdr->e_shnum; i++) {
3555 if (shdr[i].sh_type == sh_type
3556 /* Ignore the section header's string table. */
3557 && i != ehdr->e_shstrndx
3558 /* Ignore string tables named .stabstr, as they contain
3560 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3562 ptr = ehdrC + shdr[i].sh_offset;
3570 ocVerifyImage_ELF ( ObjectCode* oc )
3574 int i, j, nent, nstrtab, nsymtabs;
3578 char* ehdrC = (char*)(oc->image);
3579 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3581 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
3582 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
3583 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
3584 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
3585 errorBelch("%s: not an ELF object", oc->fileName);
3589 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
3590 errorBelch("%s: unsupported ELF format", oc->fileName);
3594 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
3595 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
3597 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
3598 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
3600 errorBelch("%s: unknown endiannness", oc->fileName);
3604 if (ehdr->e_type != ET_REL) {
3605 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
3608 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
3610 IF_DEBUG(linker,debugBelch( "Architecture is " ));
3611 switch (ehdr->e_machine) {
3612 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
3613 #ifdef EM_SPARC32PLUS
3614 case EM_SPARC32PLUS:
3616 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
3618 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
3620 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
3622 case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
3623 #elif defined(EM_AMD64)
3624 case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
3626 default: IF_DEBUG(linker,debugBelch( "unknown" ));
3627 errorBelch("%s: unknown architecture (e_machine == %d)"
3628 , oc->fileName, ehdr->e_machine);
3632 IF_DEBUG(linker,debugBelch(
3633 "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
3634 (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
3636 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
3638 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3640 if (ehdr->e_shstrndx == SHN_UNDEF) {
3641 errorBelch("%s: no section header string table", oc->fileName);
3644 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
3646 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3649 for (i = 0; i < ehdr->e_shnum; i++) {
3650 IF_DEBUG(linker,debugBelch("%2d: ", i ));
3651 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
3652 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
3653 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
3654 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
3655 ehdrC + shdr[i].sh_offset,
3656 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
3658 if (shdr[i].sh_type == SHT_REL) {
3659 IF_DEBUG(linker,debugBelch("Rel " ));
3660 } else if (shdr[i].sh_type == SHT_RELA) {
3661 IF_DEBUG(linker,debugBelch("RelA " ));
3663 IF_DEBUG(linker,debugBelch(" "));
3666 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
3670 IF_DEBUG(linker,debugBelch( "\nString tables" ));
3673 for (i = 0; i < ehdr->e_shnum; i++) {
3674 if (shdr[i].sh_type == SHT_STRTAB
3675 /* Ignore the section header's string table. */
3676 && i != ehdr->e_shstrndx
3677 /* Ignore string tables named .stabstr, as they contain
3679 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3681 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
3682 strtab = ehdrC + shdr[i].sh_offset;
3687 errorBelch("%s: no string tables, or too many", oc->fileName);
3692 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
3693 for (i = 0; i < ehdr->e_shnum; i++) {
3694 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3695 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
3697 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3698 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3699 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%ld rem)\n",
3701 (long)shdr[i].sh_size % sizeof(Elf_Sym)
3703 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
3704 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
3707 for (j = 0; j < nent; j++) {
3708 IF_DEBUG(linker,debugBelch(" %2d ", j ));
3709 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
3710 (int)stab[j].st_shndx,
3711 (int)stab[j].st_size,
3712 (char*)stab[j].st_value ));
3714 IF_DEBUG(linker,debugBelch("type=" ));
3715 switch (ELF_ST_TYPE(stab[j].st_info)) {
3716 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
3717 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
3718 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
3719 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
3720 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
3721 default: IF_DEBUG(linker,debugBelch("? " )); break;
3723 IF_DEBUG(linker,debugBelch(" " ));
3725 IF_DEBUG(linker,debugBelch("bind=" ));
3726 switch (ELF_ST_BIND(stab[j].st_info)) {
3727 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
3728 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
3729 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
3730 default: IF_DEBUG(linker,debugBelch("? " )); break;
3732 IF_DEBUG(linker,debugBelch(" " ));
3734 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3738 if (nsymtabs == 0) {
3739 errorBelch("%s: didn't find any symbol tables", oc->fileName);
3746 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3750 if (hdr->sh_type == SHT_PROGBITS
3751 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3752 /* .text-style section */
3753 return SECTIONKIND_CODE_OR_RODATA;
3756 if (hdr->sh_type == SHT_PROGBITS
3757 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3758 /* .data-style section */
3759 return SECTIONKIND_RWDATA;
3762 if (hdr->sh_type == SHT_PROGBITS
3763 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3764 /* .rodata-style section */
3765 return SECTIONKIND_CODE_OR_RODATA;
3768 if (hdr->sh_type == SHT_NOBITS
3769 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3770 /* .bss-style section */
3772 return SECTIONKIND_RWDATA;
3775 return SECTIONKIND_OTHER;
3780 ocGetNames_ELF ( ObjectCode* oc )
3785 char* ehdrC = (char*)(oc->image);
3786 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3787 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
3788 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3790 ASSERT(symhash != NULL);
3793 errorBelch("%s: no strtab", oc->fileName);
3798 for (i = 0; i < ehdr->e_shnum; i++) {
3799 /* Figure out what kind of section it is. Logic derived from
3800 Figure 1.14 ("Special Sections") of the ELF document
3801 ("Portable Formats Specification, Version 1.1"). */
3803 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
3805 if (is_bss && shdr[i].sh_size > 0) {
3806 /* This is a non-empty .bss section. Allocate zeroed space for
3807 it, and set its .sh_offset field such that
3808 ehdrC + .sh_offset == addr_of_zeroed_space. */
3809 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3810 "ocGetNames_ELF(BSS)");
3811 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3813 debugBelch("BSS section at 0x%x, size %d\n",
3814 zspace, shdr[i].sh_size);
3818 /* fill in the section info */
3819 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3820 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3821 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3822 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3825 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3827 /* copy stuff into this module's object symbol table */
3828 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3829 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3831 oc->n_symbols = nent;
3832 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3833 "ocGetNames_ELF(oc->symbols)");
3835 for (j = 0; j < nent; j++) {
3837 char isLocal = FALSE; /* avoids uninit-var warning */
3839 char* nm = strtab + stab[j].st_name;
3840 int secno = stab[j].st_shndx;
3842 /* Figure out if we want to add it; if so, set ad to its
3843 address. Otherwise leave ad == NULL. */
3845 if (secno == SHN_COMMON) {
3847 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3849 debugBelch("COMMON symbol, size %d name %s\n",
3850 stab[j].st_size, nm);
3852 /* Pointless to do addProddableBlock() for this area,
3853 since the linker should never poke around in it. */
3856 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3857 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3859 /* and not an undefined symbol */
3860 && stab[j].st_shndx != SHN_UNDEF
3861 /* and not in a "special section" */
3862 && stab[j].st_shndx < SHN_LORESERVE
3864 /* and it's a not a section or string table or anything silly */
3865 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
3866 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
3867 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
3870 /* Section 0 is the undefined section, hence > and not >=. */
3871 ASSERT(secno > 0 && secno < ehdr->e_shnum);
3873 if (shdr[secno].sh_type == SHT_NOBITS) {
3874 debugBelch(" BSS symbol, size %d off %d name %s\n",
3875 stab[j].st_size, stab[j].st_value, nm);
3878 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
3879 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
3882 #ifdef ELF_FUNCTION_DESC
3883 /* dlsym() and the initialisation table both give us function
3884 * descriptors, so to be consistent we store function descriptors
3885 * in the symbol table */
3886 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
3887 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
3889 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s\n",
3890 ad, oc->fileName, nm ));
3895 /* And the decision is ... */
3899 oc->symbols[j] = nm;
3902 /* Ignore entirely. */
3904 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
3908 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
3909 strtab + stab[j].st_name ));
3912 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
3913 (int)ELF_ST_BIND(stab[j].st_info),
3914 (int)ELF_ST_TYPE(stab[j].st_info),
3915 (int)stab[j].st_shndx,
3916 strtab + stab[j].st_name
3919 oc->symbols[j] = NULL;
3928 /* Do ELF relocations which lack an explicit addend. All x86-linux
3929 relocations appear to be of this form. */
3931 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
3932 Elf_Shdr* shdr, int shnum,
3933 Elf_Sym* stab, char* strtab )
3938 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
3939 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
3940 int target_shndx = shdr[shnum].sh_info;
3941 int symtab_shndx = shdr[shnum].sh_link;
3943 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3944 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
3945 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3946 target_shndx, symtab_shndx ));
3948 /* Skip sections that we're not interested in. */
3951 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
3952 if (kind == SECTIONKIND_OTHER) {
3953 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
3958 for (j = 0; j < nent; j++) {
3959 Elf_Addr offset = rtab[j].r_offset;
3960 Elf_Addr info = rtab[j].r_info;
3962 Elf_Addr P = ((Elf_Addr)targ) + offset;
3963 Elf_Word* pP = (Elf_Word*)P;
3968 StgStablePtr stablePtr;
3971 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
3972 j, (void*)offset, (void*)info ));
3974 IF_DEBUG(linker,debugBelch( " ZERO" ));
3977 Elf_Sym sym = stab[ELF_R_SYM(info)];
3978 /* First see if it is a local symbol. */
3979 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3980 /* Yes, so we can get the address directly from the ELF symbol
3982 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3984 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3985 + stab[ELF_R_SYM(info)].st_value);
3988 symbol = strtab + sym.st_name;
3989 stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
3990 if (NULL == stablePtr) {
3991 /* No, so look up the name in our global table. */
3992 S_tmp = lookupSymbol( symbol );
3993 S = (Elf_Addr)S_tmp;
3995 stableVal = deRefStablePtr( stablePtr );
3997 S = (Elf_Addr)S_tmp;
4001 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4004 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
4007 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
4008 (void*)P, (void*)S, (void*)A ));
4009 checkProddableBlock ( oc, pP );
4013 switch (ELF_R_TYPE(info)) {
4014 # ifdef i386_HOST_ARCH
4015 case R_386_32: *pP = value; break;
4016 case R_386_PC32: *pP = value - P; break;
4019 errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
4020 oc->fileName, (lnat)ELF_R_TYPE(info));
4028 /* Do ELF relocations for which explicit addends are supplied.
4029 sparc-solaris relocations appear to be of this form. */
4031 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
4032 Elf_Shdr* shdr, int shnum,
4033 Elf_Sym* stab, char* strtab )
4036 char *symbol = NULL;
4038 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
4039 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
4040 int target_shndx = shdr[shnum].sh_info;
4041 int symtab_shndx = shdr[shnum].sh_link;
4043 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
4044 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
4045 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
4046 target_shndx, symtab_shndx ));
4048 for (j = 0; j < nent; j++) {
4049 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4050 /* This #ifdef only serves to avoid unused-var warnings. */
4051 Elf_Addr offset = rtab[j].r_offset;
4052 Elf_Addr P = targ + offset;
4054 Elf_Addr info = rtab[j].r_info;
4055 Elf_Addr A = rtab[j].r_addend;
4059 # if defined(sparc_HOST_ARCH)
4060 Elf_Word* pP = (Elf_Word*)P;
4062 # elif defined(powerpc_HOST_ARCH)
4066 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
4067 j, (void*)offset, (void*)info,
4070 IF_DEBUG(linker,debugBelch( " ZERO" ));
4073 Elf_Sym sym = stab[ELF_R_SYM(info)];
4074 /* First see if it is a local symbol. */
4075 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
4076 /* Yes, so we can get the address directly from the ELF symbol
4078 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
4080 (ehdrC + shdr[ sym.st_shndx ].sh_offset
4081 + stab[ELF_R_SYM(info)].st_value);
4082 #ifdef ELF_FUNCTION_DESC
4083 /* Make a function descriptor for this function */
4084 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
4085 S = allocateFunctionDesc(S + A);
4090 /* No, so look up the name in our global table. */
4091 symbol = strtab + sym.st_name;
4092 S_tmp = lookupSymbol( symbol );
4093 S = (Elf_Addr)S_tmp;
4095 #ifdef ELF_FUNCTION_DESC
4096 /* If a function, already a function descriptor - we would
4097 have to copy it to add an offset. */
4098 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
4099 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
4103 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4106 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
4109 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
4110 (void*)P, (void*)S, (void*)A ));
4111 /* checkProddableBlock ( oc, (void*)P ); */
4115 switch (ELF_R_TYPE(info)) {
4116 # if defined(sparc_HOST_ARCH)
4117 case R_SPARC_WDISP30:
4118 w1 = *pP & 0xC0000000;
4119 w2 = (Elf_Word)((value - P) >> 2);
4120 ASSERT((w2 & 0xC0000000) == 0);
4125 w1 = *pP & 0xFFC00000;
4126 w2 = (Elf_Word)(value >> 10);
4127 ASSERT((w2 & 0xFFC00000) == 0);
4133 w2 = (Elf_Word)(value & 0x3FF);
4134 ASSERT((w2 & ~0x3FF) == 0);
4139 /* According to the Sun documentation:
4141 This relocation type resembles R_SPARC_32, except it refers to an
4142 unaligned word. That is, the word to be relocated must be treated
4143 as four separate bytes with arbitrary alignment, not as a word
4144 aligned according to the architecture requirements.
4147 w2 = (Elf_Word)value;
4149 // SPARC doesn't do misaligned writes of 32 bit words,
4150 // so we have to do this one byte-at-a-time.
4151 char *pPc = (char*)pP;
4152 pPc[0] = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
4153 pPc[1] = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
4154 pPc[2] = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
4155 pPc[3] = (char) ((Elf_Word)(w2 & 0x000000ff));
4159 w2 = (Elf_Word)value;
4162 # elif defined(powerpc_HOST_ARCH)
4163 case R_PPC_ADDR16_LO:
4164 *(Elf32_Half*) P = value;
4167 case R_PPC_ADDR16_HI:
4168 *(Elf32_Half*) P = value >> 16;
4171 case R_PPC_ADDR16_HA:
4172 *(Elf32_Half*) P = (value + 0x8000) >> 16;
4176 *(Elf32_Word *) P = value;
4180 *(Elf32_Word *) P = value - P;
4186 if( delta << 6 >> 6 != delta )
4188 value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
4192 if( value == 0 || delta << 6 >> 6 != delta )
4194 barf( "Unable to make SymbolExtra for #%d",
4200 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
4201 | (delta & 0x3fffffc);
4205 #if x86_64_HOST_ARCH
4207 *(Elf64_Xword *)P = value;
4212 #if defined(ALWAYS_PIC)
4213 barf("R_X86_64_PC32 relocation, but ALWAYS_PIC.");
4215 StgInt64 off = value - P;
4216 if (off >= 0x7fffffffL || off < -0x80000000L) {
4217 #if X86_64_ELF_NONPIC_HACK
4218 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4220 off = pltAddress + A - P;
4222 barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4223 symbol, off, oc->fileName );
4226 *(Elf64_Word *)P = (Elf64_Word)off;
4233 StgInt64 off = value - P;
4234 *(Elf64_Word *)P = (Elf64_Word)off;
4239 #if defined(ALWAYS_PIC)
4240 barf("R_X86_64_32 relocation, but ALWAYS_PIC.");
4242 if (value >= 0x7fffffffL) {
4243 #if X86_64_ELF_NONPIC_HACK
4244 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4246 value = pltAddress + A;
4248 barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4249 symbol, value, oc->fileName );
4252 *(Elf64_Word *)P = (Elf64_Word)value;
4257 #if defined(ALWAYS_PIC)
4258 barf("R_X86_64_32S relocation, but ALWAYS_PIC.");
4260 if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
4261 #if X86_64_ELF_NONPIC_HACK
4262 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4264 value = pltAddress + A;
4266 barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4267 symbol, value, oc->fileName );
4270 *(Elf64_Sword *)P = (Elf64_Sword)value;
4274 case R_X86_64_GOTPCREL:
4276 StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
4277 StgInt64 off = gotAddress + A - P;
4278 *(Elf64_Word *)P = (Elf64_Word)off;
4282 case R_X86_64_PLT32:
4284 #if defined(ALWAYS_PIC)
4285 barf("R_X86_64_PLT32 relocation, but ALWAYS_PIC.");
4287 StgInt64 off = value - P;
4288 if (off >= 0x7fffffffL || off < -0x80000000L) {
4289 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4291 off = pltAddress + A - P;
4293 *(Elf64_Word *)P = (Elf64_Word)off;
4300 errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
4301 oc->fileName, (lnat)ELF_R_TYPE(info));
4310 ocResolve_ELF ( ObjectCode* oc )
4314 Elf_Sym* stab = NULL;
4315 char* ehdrC = (char*)(oc->image);
4316 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
4317 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
4319 /* first find "the" symbol table */
4320 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
4322 /* also go find the string table */
4323 strtab = findElfSection ( ehdrC, SHT_STRTAB );
4325 if (stab == NULL || strtab == NULL) {
4326 errorBelch("%s: can't find string or symbol table", oc->fileName);
4330 /* Process the relocation sections. */
4331 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
4332 if (shdr[shnum].sh_type == SHT_REL) {
4333 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
4334 shnum, stab, strtab );
4338 if (shdr[shnum].sh_type == SHT_RELA) {
4339 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
4340 shnum, stab, strtab );
4345 #if defined(powerpc_HOST_ARCH)
4346 ocFlushInstructionCache( oc );
4353 * PowerPC & X86_64 ELF specifics
4356 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4358 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
4364 ehdr = (Elf_Ehdr *) oc->image;
4365 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
4367 for( i = 0; i < ehdr->e_shnum; i++ )
4368 if( shdr[i].sh_type == SHT_SYMTAB )
4371 if( i == ehdr->e_shnum )
4373 errorBelch( "This ELF file contains no symtab" );
4377 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
4379 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
4380 (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
4385 return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
4388 #endif /* powerpc */
4392 /* --------------------------------------------------------------------------
4394 * ------------------------------------------------------------------------*/
4396 #if defined(OBJFORMAT_MACHO)
4399 Support for MachO linking on Darwin/MacOS X
4400 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
4402 I hereby formally apologize for the hackish nature of this code.
4403 Things that need to be done:
4404 *) implement ocVerifyImage_MachO
4405 *) add still more sanity checks.
4408 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4409 #define mach_header mach_header_64
4410 #define segment_command segment_command_64
4411 #define section section_64
4412 #define nlist nlist_64
4415 #ifdef powerpc_HOST_ARCH
4416 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4418 struct mach_header *header = (struct mach_header *) oc->image;
4419 struct load_command *lc = (struct load_command *) (header + 1);
4422 for( i = 0; i < header->ncmds; i++ )
4424 if( lc->cmd == LC_SYMTAB )
4426 // Find out the first and last undefined external
4427 // symbol, so we don't have to allocate too many
4429 struct symtab_command *symLC = (struct symtab_command *) lc;
4430 unsigned min = symLC->nsyms, max = 0;
4431 struct nlist *nlist =
4432 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
4434 for(i=0;i<symLC->nsyms;i++)
4436 if(nlist[i].n_type & N_STAB)
4438 else if(nlist[i].n_type & N_EXT)
4440 if((nlist[i].n_type & N_TYPE) == N_UNDF
4441 && (nlist[i].n_value == 0))
4451 return ocAllocateSymbolExtras(oc, max - min + 1, min);
4456 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4458 return ocAllocateSymbolExtras(oc,0,0);
4461 #ifdef x86_64_HOST_ARCH
4462 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4464 struct mach_header *header = (struct mach_header *) oc->image;
4465 struct load_command *lc = (struct load_command *) (header + 1);
4468 for( i = 0; i < header->ncmds; i++ )
4470 if( lc->cmd == LC_SYMTAB )
4472 // Just allocate one entry for every symbol
4473 struct symtab_command *symLC = (struct symtab_command *) lc;
4475 return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
4478 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4480 return ocAllocateSymbolExtras(oc,0,0);
4484 static int ocVerifyImage_MachO(ObjectCode* oc)
4486 char *image = (char*) oc->image;
4487 struct mach_header *header = (struct mach_header*) image;
4489 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4490 if(header->magic != MH_MAGIC_64) {
4491 errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4492 oc->fileName, MH_MAGIC_64, header->magic);
4496 if(header->magic != MH_MAGIC) {
4497 errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4498 oc->fileName, MH_MAGIC, header->magic);
4502 // FIXME: do some more verifying here
4506 static int resolveImports(
4509 struct symtab_command *symLC,
4510 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
4511 unsigned long *indirectSyms,
4512 struct nlist *nlist)
4515 size_t itemSize = 4;
4517 IF_DEBUG(linker, debugBelch("resolveImports: start\n"));
4520 int isJumpTable = 0;
4521 if(!strcmp(sect->sectname,"__jump_table"))
4525 ASSERT(sect->reserved2 == itemSize);
4529 for(i=0; i*itemSize < sect->size;i++)
4531 // according to otool, reserved1 contains the first index into the indirect symbol table
4532 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
4533 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4536 IF_DEBUG(linker, debugBelch("resolveImports: resolving %s\n", nm));
4537 if ((symbol->n_type & N_TYPE) == N_UNDF
4538 && (symbol->n_type & N_EXT) && (symbol->n_value != 0)) {
4539 addr = (void*) (symbol->n_value);
4540 IF_DEBUG(linker, debugBelch("resolveImports: undefined external %s has value %p\n", nm, addr));
4542 addr = lookupSymbol(nm);
4543 IF_DEBUG(linker, debugBelch("resolveImports: looking up %s, %p\n", nm, addr));
4547 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
4555 checkProddableBlock(oc,image + sect->offset + i*itemSize);
4556 *(image + sect->offset + i*itemSize) = 0xe9; // jmp
4557 *(unsigned*)(image + sect->offset + i*itemSize + 1)
4558 = (char*)addr - (image + sect->offset + i*itemSize + 5);
4563 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
4564 ((void**)(image + sect->offset))[i] = addr;
4568 IF_DEBUG(linker, debugBelch("resolveImports: done\n"));
4572 static unsigned long relocateAddress(
4575 struct section* sections,
4576 unsigned long address)
4579 IF_DEBUG(linker, debugBelch("relocateAddress: start\n"));
4580 for (i = 0; i < nSections; i++)
4582 IF_DEBUG(linker, debugBelch(" relocating address in section %d\n", i));
4583 if (sections[i].addr <= address
4584 && address < sections[i].addr + sections[i].size)
4586 return (unsigned long)oc->image
4587 + sections[i].offset + address - sections[i].addr;
4590 barf("Invalid Mach-O file:"
4591 "Address out of bounds while relocating object file");
4595 static int relocateSection(
4598 struct symtab_command *symLC, struct nlist *nlist,
4599 int nSections, struct section* sections, struct section *sect)
4601 struct relocation_info *relocs;
4604 IF_DEBUG(linker, debugBelch("relocateSection: start\n"));
4606 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
4608 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
4610 else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
4612 else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
4616 IF_DEBUG(linker, debugBelch("relocateSection: number of relocations: %d\n", n));
4618 relocs = (struct relocation_info*) (image + sect->reloff);
4622 #ifdef x86_64_HOST_ARCH
4623 struct relocation_info *reloc = &relocs[i];
4625 char *thingPtr = image + sect->offset + reloc->r_address;
4627 /* We shouldn't need to initialise this, but gcc on OS X 64 bit
4628 complains that it may be used uninitialized if we don't */
4631 int type = reloc->r_type;
4633 checkProddableBlock(oc,thingPtr);
4634 switch(reloc->r_length)
4637 thing = *(uint8_t*)thingPtr;
4638 baseValue = (uint64_t)thingPtr + 1;
4641 thing = *(uint16_t*)thingPtr;
4642 baseValue = (uint64_t)thingPtr + 2;
4645 thing = *(uint32_t*)thingPtr;
4646 baseValue = (uint64_t)thingPtr + 4;
4649 thing = *(uint64_t*)thingPtr;
4650 baseValue = (uint64_t)thingPtr + 8;
4653 barf("Unknown size.");
4657 debugBelch("relocateSection: length = %d, thing = %" PRId64 ", baseValue = %p\n",
4658 reloc->r_length, thing, (char *)baseValue));
4660 if (type == X86_64_RELOC_GOT
4661 || type == X86_64_RELOC_GOT_LOAD)
4663 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4664 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4666 IF_DEBUG(linker, debugBelch("relocateSection: making jump island for %s, extern = %d, X86_64_RELOC_GOT\n", nm, reloc->r_extern));
4667 ASSERT(reloc->r_extern);
4668 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, (unsigned long)lookupSymbol(nm))->addr;
4670 type = X86_64_RELOC_SIGNED;
4672 else if(reloc->r_extern)
4674 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4675 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4677 IF_DEBUG(linker, debugBelch("relocateSection: looking up external symbol %s\n", nm));
4678 IF_DEBUG(linker, debugBelch(" : type = %d\n", symbol->n_type));
4679 IF_DEBUG(linker, debugBelch(" : sect = %d\n", symbol->n_sect));
4680 IF_DEBUG(linker, debugBelch(" : desc = %d\n", symbol->n_desc));
4681 IF_DEBUG(linker, debugBelch(" : value = %p\n", (void *)symbol->n_value));
4682 if ((symbol->n_type & N_TYPE) == N_SECT) {
4683 value = relocateAddress(oc, nSections, sections,
4685 IF_DEBUG(linker, debugBelch("relocateSection, defined external symbol %s, relocated address %p\n", nm, (void *)value));
4688 value = (uint64_t) lookupSymbol(nm);
4689 IF_DEBUG(linker, debugBelch("relocateSection: external symbol %s, address %p\n", nm, (void *)value));
4694 // If the relocation is not through the global offset table
4695 // or external, then set the value to the baseValue. This
4696 // will leave displacements into the __const section
4697 // unchanged (as they ought to be).
4702 IF_DEBUG(linker, debugBelch("relocateSection: value = %p\n", (void *)value));
4704 if (type == X86_64_RELOC_BRANCH)
4706 if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
4708 ASSERT(reloc->r_extern);
4709 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
4712 ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
4713 type = X86_64_RELOC_SIGNED;
4718 case X86_64_RELOC_UNSIGNED:
4719 ASSERT(!reloc->r_pcrel);
4722 case X86_64_RELOC_SIGNED:
4723 case X86_64_RELOC_SIGNED_1:
4724 case X86_64_RELOC_SIGNED_2:
4725 case X86_64_RELOC_SIGNED_4:
4726 ASSERT(reloc->r_pcrel);
4727 thing += value - baseValue;
4729 case X86_64_RELOC_SUBTRACTOR:
4730 ASSERT(!reloc->r_pcrel);
4734 barf("unkown relocation");
4737 switch(reloc->r_length)
4740 *(uint8_t*)thingPtr = thing;
4743 *(uint16_t*)thingPtr = thing;
4746 *(uint32_t*)thingPtr = thing;
4749 *(uint64_t*)thingPtr = thing;
4753 if(relocs[i].r_address & R_SCATTERED)
4755 struct scattered_relocation_info *scat =
4756 (struct scattered_relocation_info*) &relocs[i];
4760 if(scat->r_length == 2)
4762 unsigned long word = 0;
4763 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
4764 checkProddableBlock(oc,wordPtr);
4766 // Note on relocation types:
4767 // i386 uses the GENERIC_RELOC_* types,
4768 // while ppc uses special PPC_RELOC_* types.
4769 // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
4770 // in both cases, all others are different.
4771 // Therefore, we use GENERIC_RELOC_VANILLA
4772 // and GENERIC_RELOC_PAIR instead of the PPC variants,
4773 // and use #ifdefs for the other types.
4775 // Step 1: Figure out what the relocated value should be
4776 if(scat->r_type == GENERIC_RELOC_VANILLA)
4778 word = *wordPtr + (unsigned long) relocateAddress(
4785 #ifdef powerpc_HOST_ARCH
4786 else if(scat->r_type == PPC_RELOC_SECTDIFF
4787 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4788 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4789 || scat->r_type == PPC_RELOC_HA16_SECTDIFF
4790 || scat->r_type == PPC_RELOC_LOCAL_SECTDIFF)
4792 else if(scat->r_type == GENERIC_RELOC_SECTDIFF
4793 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4796 struct scattered_relocation_info *pair =
4797 (struct scattered_relocation_info*) &relocs[i+1];
4799 if(!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR)
4800 barf("Invalid Mach-O file: "
4801 "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4803 word = (unsigned long)
4804 (relocateAddress(oc, nSections, sections, scat->r_value)
4805 - relocateAddress(oc, nSections, sections, pair->r_value));
4808 #ifdef powerpc_HOST_ARCH
4809 else if(scat->r_type == PPC_RELOC_HI16
4810 || scat->r_type == PPC_RELOC_LO16
4811 || scat->r_type == PPC_RELOC_HA16
4812 || scat->r_type == PPC_RELOC_LO14)
4813 { // these are generated by label+offset things
4814 struct relocation_info *pair = &relocs[i+1];
4815 if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
4816 barf("Invalid Mach-O file: "
4817 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4819 if(scat->r_type == PPC_RELOC_LO16)
4821 word = ((unsigned short*) wordPtr)[1];
4822 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4824 else if(scat->r_type == PPC_RELOC_LO14)
4826 barf("Unsupported Relocation: PPC_RELOC_LO14");
4827 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4828 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4830 else if(scat->r_type == PPC_RELOC_HI16)
4832 word = ((unsigned short*) wordPtr)[1] << 16;
4833 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4835 else if(scat->r_type == PPC_RELOC_HA16)
4837 word = ((unsigned short*) wordPtr)[1] << 16;
4838 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4842 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
4850 barf ("Don't know how to handle this Mach-O "
4851 "scattered relocation entry: "
4852 "object file %s; entry type %ld; "
4854 OC_INFORMATIVE_FILENAME(oc),
4860 #ifdef powerpc_HOST_ARCH
4861 if(scat->r_type == GENERIC_RELOC_VANILLA
4862 || scat->r_type == PPC_RELOC_SECTDIFF)
4864 if(scat->r_type == GENERIC_RELOC_VANILLA
4865 || scat->r_type == GENERIC_RELOC_SECTDIFF
4866 || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4871 #ifdef powerpc_HOST_ARCH
4872 else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
4874 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4876 else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
4878 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4880 else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
4882 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4883 + ((word & (1<<15)) ? 1 : 0);
4889 barf("Can't handle Mach-O scattered relocation entry "
4890 "with this r_length tag: "
4891 "object file %s; entry type %ld; "
4892 "r_length tag %ld; address %#lx\n",
4893 OC_INFORMATIVE_FILENAME(oc),
4900 else /* scat->r_pcrel */
4902 barf("Don't know how to handle *PC-relative* Mach-O "
4903 "scattered relocation entry: "
4904 "object file %s; entry type %ld; address %#lx\n",
4905 OC_INFORMATIVE_FILENAME(oc),
4912 else /* !(relocs[i].r_address & R_SCATTERED) */
4914 struct relocation_info *reloc = &relocs[i];
4915 if(reloc->r_pcrel && !reloc->r_extern)
4918 if(reloc->r_length == 2)
4920 unsigned long word = 0;
4921 #ifdef powerpc_HOST_ARCH
4922 unsigned long jumpIsland = 0;
4923 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
4924 // to avoid warning and to catch
4928 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
4929 checkProddableBlock(oc,wordPtr);
4931 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4935 #ifdef powerpc_HOST_ARCH
4936 else if(reloc->r_type == PPC_RELOC_LO16)
4938 word = ((unsigned short*) wordPtr)[1];
4939 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4941 else if(reloc->r_type == PPC_RELOC_HI16)
4943 word = ((unsigned short*) wordPtr)[1] << 16;
4944 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4946 else if(reloc->r_type == PPC_RELOC_HA16)
4948 word = ((unsigned short*) wordPtr)[1] << 16;
4949 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4951 else if(reloc->r_type == PPC_RELOC_BR24)
4954 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
4959 barf("Can't handle this Mach-O relocation entry "
4961 "object file %s; entry type %ld; address %#lx\n",
4962 OC_INFORMATIVE_FILENAME(oc),
4968 if(!reloc->r_extern)
4971 sections[reloc->r_symbolnum-1].offset
4972 - sections[reloc->r_symbolnum-1].addr
4979 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4980 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4981 void *symbolAddress = lookupSymbol(nm);
4984 errorBelch("\nunknown symbol `%s'", nm);
4990 #ifdef powerpc_HOST_ARCH
4991 // In the .o file, this should be a relative jump to NULL
4992 // and we'll change it to a relative jump to the symbol
4993 ASSERT(word + reloc->r_address == 0);
4994 jumpIsland = (unsigned long)
4995 &makeSymbolExtra(oc,
4997 (unsigned long) symbolAddress)
5001 offsetToJumpIsland = word + jumpIsland
5002 - (((long)image) + sect->offset - sect->addr);
5005 word += (unsigned long) symbolAddress
5006 - (((long)image) + sect->offset - sect->addr);
5010 word += (unsigned long) symbolAddress;
5014 if(reloc->r_type == GENERIC_RELOC_VANILLA)
5019 #ifdef powerpc_HOST_ARCH
5020 else if(reloc->r_type == PPC_RELOC_LO16)
5022 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
5025 else if(reloc->r_type == PPC_RELOC_HI16)
5027 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
5030 else if(reloc->r_type == PPC_RELOC_HA16)
5032 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
5033 + ((word & (1<<15)) ? 1 : 0);
5036 else if(reloc->r_type == PPC_RELOC_BR24)
5038 if((word & 0x03) != 0)
5039 barf("%s: unconditional relative branch with a displacement "
5040 "which isn't a multiple of 4 bytes: %#lx",
5041 OC_INFORMATIVE_FILENAME(oc),
5044 if((word & 0xFE000000) != 0xFE000000 &&
5045 (word & 0xFE000000) != 0x00000000)
5047 // The branch offset is too large.
5048 // Therefore, we try to use a jump island.
5051 barf("%s: unconditional relative branch out of range: "
5052 "no jump island available: %#lx",
5053 OC_INFORMATIVE_FILENAME(oc),
5057 word = offsetToJumpIsland;
5058 if((word & 0xFE000000) != 0xFE000000 &&
5059 (word & 0xFE000000) != 0x00000000)
5060 barf("%s: unconditional relative branch out of range: "
5061 "jump island out of range: %#lx",
5062 OC_INFORMATIVE_FILENAME(oc),
5065 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
5072 barf("Can't handle Mach-O relocation entry (not scattered) "
5073 "with this r_length tag: "
5074 "object file %s; entry type %ld; "
5075 "r_length tag %ld; address %#lx\n",
5076 OC_INFORMATIVE_FILENAME(oc),
5085 IF_DEBUG(linker, debugBelch("relocateSection: done\n"));
5089 static int ocGetNames_MachO(ObjectCode* oc)
5091 char *image = (char*) oc->image;
5092 struct mach_header *header = (struct mach_header*) image;
5093 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5094 unsigned i,curSymbol = 0;
5095 struct segment_command *segLC = NULL;
5096 struct section *sections;
5097 struct symtab_command *symLC = NULL;
5098 struct nlist *nlist;
5099 unsigned long commonSize = 0;
5100 char *commonStorage = NULL;
5101 unsigned long commonCounter;
5103 IF_DEBUG(linker,debugBelch("ocGetNames_MachO: start\n"));
5105 for(i=0;i<header->ncmds;i++)
5107 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
5108 segLC = (struct segment_command*) lc;
5109 else if(lc->cmd == LC_SYMTAB)
5110 symLC = (struct symtab_command*) lc;
5111 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5114 sections = (struct section*) (segLC+1);
5115 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5119 barf("ocGetNames_MachO: no segment load command");
5121 for(i=0;i<segLC->nsects;i++)
5123 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: segment %d\n", i));
5124 if (sections[i].size == 0)
5127 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
5129 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
5130 "ocGetNames_MachO(common symbols)");
5131 sections[i].offset = zeroFillArea - image;
5134 if(!strcmp(sections[i].sectname,"__text"))
5135 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
5136 (void*) (image + sections[i].offset),
5137 (void*) (image + sections[i].offset + sections[i].size));
5138 else if(!strcmp(sections[i].sectname,"__const"))
5139 addSection(oc, SECTIONKIND_RWDATA,
5140 (void*) (image + sections[i].offset),
5141 (void*) (image + sections[i].offset + sections[i].size));
5142 else if(!strcmp(sections[i].sectname,"__data"))
5143 addSection(oc, SECTIONKIND_RWDATA,
5144 (void*) (image + sections[i].offset),
5145 (void*) (image + sections[i].offset + sections[i].size));
5146 else if(!strcmp(sections[i].sectname,"__bss")
5147 || !strcmp(sections[i].sectname,"__common"))
5148 addSection(oc, SECTIONKIND_RWDATA,
5149 (void*) (image + sections[i].offset),
5150 (void*) (image + sections[i].offset + sections[i].size));
5152 addProddableBlock(oc, (void*) (image + sections[i].offset),
5156 // count external symbols defined here
5160 for(i=0;i<symLC->nsyms;i++)
5162 if(nlist[i].n_type & N_STAB)
5164 else if(nlist[i].n_type & N_EXT)
5166 if((nlist[i].n_type & N_TYPE) == N_UNDF
5167 && (nlist[i].n_value != 0))
5169 commonSize += nlist[i].n_value;
5172 else if((nlist[i].n_type & N_TYPE) == N_SECT)
5177 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: %d external symbols\n", oc->n_symbols));
5178 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
5179 "ocGetNames_MachO(oc->symbols)");
5183 for(i=0;i<symLC->nsyms;i++)
5185 if(nlist[i].n_type & N_STAB)
5187 else if((nlist[i].n_type & N_TYPE) == N_SECT)
5189 if(nlist[i].n_type & N_EXT)
5191 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5192 if ((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm)) {
5193 // weak definition, and we already have a definition
5194 IF_DEBUG(linker, debugBelch(" weak: %s\n", nm));
5198 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting %s\n", nm));
5199 ghciInsertStrHashTable(oc->fileName, symhash, nm,
5201 + sections[nlist[i].n_sect-1].offset
5202 - sections[nlist[i].n_sect-1].addr
5203 + nlist[i].n_value);
5204 oc->symbols[curSymbol++] = nm;
5211 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
5212 commonCounter = (unsigned long)commonStorage;
5215 for(i=0;i<symLC->nsyms;i++)
5217 if((nlist[i].n_type & N_TYPE) == N_UNDF
5218 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
5220 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5221 unsigned long sz = nlist[i].n_value;
5223 nlist[i].n_value = commonCounter;
5225 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting common symbol: %s\n", nm));
5226 ghciInsertStrHashTable(oc->fileName, symhash, nm,
5227 (void*)commonCounter);
5228 oc->symbols[curSymbol++] = nm;
5230 commonCounter += sz;
5237 static int ocResolve_MachO(ObjectCode* oc)
5239 char *image = (char*) oc->image;
5240 struct mach_header *header = (struct mach_header*) image;
5241 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5243 struct segment_command *segLC = NULL;
5244 struct section *sections;
5245 struct symtab_command *symLC = NULL;
5246 struct dysymtab_command *dsymLC = NULL;
5247 struct nlist *nlist;
5249 IF_DEBUG(linker, debugBelch("ocResolve_MachO: start\n"));
5250 for (i = 0; i < header->ncmds; i++)
5252 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
5253 segLC = (struct segment_command*) lc;
5254 else if(lc->cmd == LC_SYMTAB)
5255 symLC = (struct symtab_command*) lc;
5256 else if(lc->cmd == LC_DYSYMTAB)
5257 dsymLC = (struct dysymtab_command*) lc;
5258 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5261 sections = (struct section*) (segLC+1);
5262 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5267 unsigned long *indirectSyms
5268 = (unsigned long*) (image + dsymLC->indirectsymoff);
5270 IF_DEBUG(linker, debugBelch("ocResolve_MachO: resolving dsymLC\n"));
5271 for (i = 0; i < segLC->nsects; i++)
5273 if( !strcmp(sections[i].sectname,"__la_symbol_ptr")
5274 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
5275 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
5277 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5280 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
5281 || !strcmp(sections[i].sectname,"__pointers"))
5283 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5286 else if(!strcmp(sections[i].sectname,"__jump_table"))
5288 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
5293 IF_DEBUG(linker, debugBelch("ocResolve_MachO: unknown section\n"));
5298 for(i=0;i<segLC->nsects;i++)
5300 IF_DEBUG(linker, debugBelch("ocResolve_MachO: relocating section %d\n", i));
5302 if (!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
5306 #if defined (powerpc_HOST_ARCH)
5307 ocFlushInstructionCache( oc );
5313 #ifdef powerpc_HOST_ARCH
5315 * The Mach-O object format uses leading underscores. But not everywhere.
5316 * There is a small number of runtime support functions defined in
5317 * libcc_dynamic.a whose name does not have a leading underscore.
5318 * As a consequence, we can't get their address from C code.
5319 * We have to use inline assembler just to take the address of a function.
5323 extern void* symbolsWithoutUnderscore[];
5325 static void machoInitSymbolsWithoutUnderscore()
5327 void **p = symbolsWithoutUnderscore;
5328 __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
5330 #undef SymI_NeedsProto
5331 #define SymI_NeedsProto(x) \
5332 __asm__ volatile(".long " # x);
5334 RTS_MACHO_NOUNDERLINE_SYMBOLS
5336 __asm__ volatile(".text");
5338 #undef SymI_NeedsProto
5339 #define SymI_NeedsProto(x) \
5340 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
5342 RTS_MACHO_NOUNDERLINE_SYMBOLS
5344 #undef SymI_NeedsProto
5350 * Figure out by how much to shift the entire Mach-O file in memory
5351 * when loading so that its single segment ends up 16-byte-aligned
5353 static int machoGetMisalignment( FILE * f )
5355 struct mach_header header;
5359 int n = fread(&header, sizeof(header), 1, f);
5361 barf("machoGetMisalignment: can't read the Mach-O header");
5364 fseek(f, -sizeof(header), SEEK_CUR);
5366 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
5367 if(header.magic != MH_MAGIC_64) {
5368 barf("Bad magic. Expected: %08x, got: %08x.",
5369 MH_MAGIC_64, header.magic);
5372 if(header.magic != MH_MAGIC) {
5373 barf("Bad magic. Expected: %08x, got: %08x.",
5374 MH_MAGIC, header.magic);
5378 misalignment = (header.sizeofcmds + sizeof(header))
5381 return misalignment ? (16 - misalignment) : 0;