1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2004
7 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
13 /* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and
14 MREMAP_MAYMOVE from <sys/mman.h>.
23 #include "sm/Storage.h"
25 #include "LinkerInternals.h"
28 #include "StgPrimFloat.h" // for __int_encodeFloat etc.
31 #if !defined(mingw32_HOST_OS)
32 #include "posix/Signals.h"
35 #ifdef HAVE_SYS_TYPES_H
36 #include <sys/types.h>
42 #ifdef HAVE_SYS_STAT_H
46 #if defined(HAVE_DLFCN_H)
50 #if defined(cygwin32_HOST_OS)
55 #ifdef HAVE_SYS_TIME_H
59 #include <sys/fcntl.h>
60 #include <sys/termios.h>
61 #include <sys/utime.h>
62 #include <sys/utsname.h>
66 #if defined(ia64_HOST_ARCH) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
71 #if defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
79 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
80 # define OBJFORMAT_ELF
81 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
82 # define OBJFORMAT_PEi386
85 #elif defined(darwin_HOST_OS)
86 # define OBJFORMAT_MACHO
87 # include <mach-o/loader.h>
88 # include <mach-o/nlist.h>
89 # include <mach-o/reloc.h>
90 #if !defined(HAVE_DLFCN_H)
91 # include <mach-o/dyld.h>
93 #if defined(powerpc_HOST_ARCH)
94 # include <mach-o/ppc/reloc.h>
96 #if defined(x86_64_HOST_ARCH)
97 # include <mach-o/x86_64/reloc.h>
101 /* Hash table mapping symbol names to Symbol */
102 static /*Str*/HashTable *symhash;
104 /* Hash table mapping symbol names to StgStablePtr */
105 static /*Str*/HashTable *stablehash;
107 /* List of currently loaded objects */
108 ObjectCode *objects = NULL; /* initially empty */
110 #if defined(OBJFORMAT_ELF)
111 static int ocVerifyImage_ELF ( ObjectCode* oc );
112 static int ocGetNames_ELF ( ObjectCode* oc );
113 static int ocResolve_ELF ( ObjectCode* oc );
114 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
115 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
117 #elif defined(OBJFORMAT_PEi386)
118 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
119 static int ocGetNames_PEi386 ( ObjectCode* oc );
120 static int ocResolve_PEi386 ( ObjectCode* oc );
121 static void *lookupSymbolInDLLs ( unsigned char *lbl );
122 static void zapTrailingAtSign ( unsigned char *sym );
123 #elif defined(OBJFORMAT_MACHO)
124 static int ocVerifyImage_MachO ( ObjectCode* oc );
125 static int ocGetNames_MachO ( ObjectCode* oc );
126 static int ocResolve_MachO ( ObjectCode* oc );
128 static int machoGetMisalignment( FILE * );
129 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
130 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
132 #ifdef powerpc_HOST_ARCH
133 static void machoInitSymbolsWithoutUnderscore( void );
137 /* on x86_64 we have a problem with relocating symbol references in
138 * code that was compiled without -fPIC. By default, the small memory
139 * model is used, which assumes that symbol references can fit in a
140 * 32-bit slot. The system dynamic linker makes this work for
141 * references to shared libraries by either (a) allocating a jump
142 * table slot for code references, or (b) moving the symbol at load
143 * time (and copying its contents, if necessary) for data references.
145 * We unfortunately can't tell whether symbol references are to code
146 * or data. So for now we assume they are code (the vast majority
147 * are), and allocate jump-table slots. Unfortunately this will
148 * SILENTLY generate crashing code for data references. This hack is
149 * enabled by X86_64_ELF_NONPIC_HACK.
151 * One workaround is to use shared Haskell libraries. This is
152 * coming. Another workaround is to keep the static libraries but
153 * compile them with -fPIC, because that will generate PIC references
154 * to data which can be relocated. The PIC code is still too green to
155 * do this systematically, though.
158 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
160 * Naming Scheme for Symbol Macros
162 * SymI_*: symbol is internal to the RTS. It resides in an object
163 * file/library that is statically.
164 * SymE_*: symbol is external to the RTS library. It might be linked
167 * Sym*_HasProto : the symbol prototype is imported in an include file
168 * or defined explicitly
169 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
170 * default proto extern void sym(void);
172 #define X86_64_ELF_NONPIC_HACK 1
174 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
175 * small memory model on this architecture (see gcc docs,
178 * MAP_32BIT not available on OpenBSD/amd64
180 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
181 #define TRY_MAP_32BIT MAP_32BIT
183 #define TRY_MAP_32BIT 0
187 * Due to the small memory model (see above), on x86_64 we have to map
188 * all our non-PIC object files into the low 2Gb of the address space
189 * (why 2Gb and not 4Gb? Because all addresses must be reachable
190 * using a 32-bit signed PC-relative offset). On Linux we can do this
191 * using the MAP_32BIT flag to mmap(), however on other OSs
192 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
193 * can't do this. So on these systems, we have to pick a base address
194 * in the low 2Gb of the address space and try to allocate memory from
197 * We pick a default address based on the OS, but also make this
198 * configurable via an RTS flag (+RTS -xm)
200 #if defined(x86_64_HOST_ARCH)
202 #if defined(MAP_32BIT)
203 // Try to use MAP_32BIT
204 #define MMAP_32BIT_BASE_DEFAULT 0
207 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
210 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
213 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
214 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
215 #define MAP_ANONYMOUS MAP_ANON
218 /* -----------------------------------------------------------------------------
219 * Built-in symbols from the RTS
222 typedef struct _RtsSymbolVal {
227 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
228 SymI_HasProto(stg_mkWeakForeignEnvzh) \
229 SymI_HasProto(stg_makeStableNamezh) \
230 SymI_HasProto(stg_finalizzeWeakzh)
232 #if !defined (mingw32_HOST_OS)
233 #define RTS_POSIX_ONLY_SYMBOLS \
234 SymI_HasProto(__hscore_get_saved_termios) \
235 SymI_HasProto(__hscore_set_saved_termios) \
236 SymI_HasProto(shutdownHaskellAndSignal) \
237 SymI_HasProto(lockFile) \
238 SymI_HasProto(unlockFile) \
239 SymI_HasProto(signal_handlers) \
240 SymI_HasProto(stg_sig_install) \
241 SymI_NeedsProto(nocldstop)
244 #if defined (cygwin32_HOST_OS)
245 #define RTS_MINGW_ONLY_SYMBOLS /**/
246 /* Don't have the ability to read import libs / archives, so
247 * we have to stupidly list a lot of what libcygwin.a
250 #define RTS_CYGWIN_ONLY_SYMBOLS \
251 SymI_HasProto(regfree) \
252 SymI_HasProto(regexec) \
253 SymI_HasProto(regerror) \
254 SymI_HasProto(regcomp) \
255 SymI_HasProto(__errno) \
256 SymI_HasProto(access) \
257 SymI_HasProto(chmod) \
258 SymI_HasProto(chdir) \
259 SymI_HasProto(close) \
260 SymI_HasProto(creat) \
262 SymI_HasProto(dup2) \
263 SymI_HasProto(fstat) \
264 SymI_HasProto(fcntl) \
265 SymI_HasProto(getcwd) \
266 SymI_HasProto(getenv) \
267 SymI_HasProto(lseek) \
268 SymI_HasProto(open) \
269 SymI_HasProto(fpathconf) \
270 SymI_HasProto(pathconf) \
271 SymI_HasProto(stat) \
273 SymI_HasProto(tanh) \
274 SymI_HasProto(cosh) \
275 SymI_HasProto(sinh) \
276 SymI_HasProto(atan) \
277 SymI_HasProto(acos) \
278 SymI_HasProto(asin) \
284 SymI_HasProto(sqrt) \
285 SymI_HasProto(localtime_r) \
286 SymI_HasProto(gmtime_r) \
287 SymI_HasProto(mktime) \
288 SymI_NeedsProto(_imp___tzname) \
289 SymI_HasProto(gettimeofday) \
290 SymI_HasProto(timezone) \
291 SymI_HasProto(tcgetattr) \
292 SymI_HasProto(tcsetattr) \
293 SymI_HasProto(memcpy) \
294 SymI_HasProto(memmove) \
295 SymI_HasProto(realloc) \
296 SymI_HasProto(malloc) \
297 SymI_HasProto(free) \
298 SymI_HasProto(fork) \
299 SymI_HasProto(lstat) \
300 SymI_HasProto(isatty) \
301 SymI_HasProto(mkdir) \
302 SymI_HasProto(opendir) \
303 SymI_HasProto(readdir) \
304 SymI_HasProto(rewinddir) \
305 SymI_HasProto(closedir) \
306 SymI_HasProto(link) \
307 SymI_HasProto(mkfifo) \
308 SymI_HasProto(pipe) \
309 SymI_HasProto(read) \
310 SymI_HasProto(rename) \
311 SymI_HasProto(rmdir) \
312 SymI_HasProto(select) \
313 SymI_HasProto(system) \
314 SymI_HasProto(write) \
315 SymI_HasProto(strcmp) \
316 SymI_HasProto(strcpy) \
317 SymI_HasProto(strncpy) \
318 SymI_HasProto(strerror) \
319 SymI_HasProto(sigaddset) \
320 SymI_HasProto(sigemptyset) \
321 SymI_HasProto(sigprocmask) \
322 SymI_HasProto(umask) \
323 SymI_HasProto(uname) \
324 SymI_HasProto(unlink) \
325 SymI_HasProto(utime) \
326 SymI_HasProto(waitpid)
328 #elif !defined(mingw32_HOST_OS)
329 #define RTS_MINGW_ONLY_SYMBOLS /**/
330 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
331 #else /* defined(mingw32_HOST_OS) */
332 #define RTS_POSIX_ONLY_SYMBOLS /**/
333 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
335 /* Extra syms gen'ed by mingw-2's gcc-3.2: */
337 #define RTS_MINGW_EXTRA_SYMS \
338 SymI_NeedsProto(_imp____mb_cur_max) \
339 SymI_NeedsProto(_imp___pctype)
341 #define RTS_MINGW_EXTRA_SYMS
344 #if HAVE_GETTIMEOFDAY
345 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
347 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
350 #if HAVE___MINGW_VFPRINTF
351 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
353 #define RTS___MINGW_VFPRINTF_SYM /**/
356 /* These are statically linked from the mingw libraries into the ghc
357 executable, so we have to employ this hack. */
358 #define RTS_MINGW_ONLY_SYMBOLS \
359 SymI_HasProto(stg_asyncReadzh) \
360 SymI_HasProto(stg_asyncWritezh) \
361 SymI_HasProto(stg_asyncDoProczh) \
362 SymI_HasProto(memset) \
363 SymI_HasProto(inet_ntoa) \
364 SymI_HasProto(inet_addr) \
365 SymI_HasProto(htonl) \
366 SymI_HasProto(recvfrom) \
367 SymI_HasProto(listen) \
368 SymI_HasProto(bind) \
369 SymI_HasProto(shutdown) \
370 SymI_HasProto(connect) \
371 SymI_HasProto(htons) \
372 SymI_HasProto(ntohs) \
373 SymI_HasProto(getservbyname) \
374 SymI_HasProto(getservbyport) \
375 SymI_HasProto(getprotobynumber) \
376 SymI_HasProto(getprotobyname) \
377 SymI_HasProto(gethostbyname) \
378 SymI_HasProto(gethostbyaddr) \
379 SymI_HasProto(gethostname) \
380 SymI_HasProto(strcpy) \
381 SymI_HasProto(strncpy) \
382 SymI_HasProto(abort) \
383 SymI_NeedsProto(_alloca) \
384 SymI_NeedsProto(isxdigit) \
385 SymI_NeedsProto(isupper) \
386 SymI_NeedsProto(ispunct) \
387 SymI_NeedsProto(islower) \
388 SymI_NeedsProto(isspace) \
389 SymI_NeedsProto(isprint) \
390 SymI_NeedsProto(isdigit) \
391 SymI_NeedsProto(iscntrl) \
392 SymI_NeedsProto(isalpha) \
393 SymI_NeedsProto(isalnum) \
394 SymI_NeedsProto(isascii) \
395 RTS___MINGW_VFPRINTF_SYM \
396 SymI_HasProto(strcmp) \
397 SymI_HasProto(memmove) \
398 SymI_HasProto(realloc) \
399 SymI_HasProto(malloc) \
401 SymI_HasProto(tanh) \
402 SymI_HasProto(cosh) \
403 SymI_HasProto(sinh) \
404 SymI_HasProto(atan) \
405 SymI_HasProto(acos) \
406 SymI_HasProto(asin) \
412 SymI_HasProto(sqrt) \
413 SymI_HasProto(powf) \
414 SymI_HasProto(tanhf) \
415 SymI_HasProto(coshf) \
416 SymI_HasProto(sinhf) \
417 SymI_HasProto(atanf) \
418 SymI_HasProto(acosf) \
419 SymI_HasProto(asinf) \
420 SymI_HasProto(tanf) \
421 SymI_HasProto(cosf) \
422 SymI_HasProto(sinf) \
423 SymI_HasProto(expf) \
424 SymI_HasProto(logf) \
425 SymI_HasProto(sqrtf) \
427 SymI_HasProto(erfc) \
428 SymI_HasProto(erff) \
429 SymI_HasProto(erfcf) \
430 SymI_HasProto(memcpy) \
431 SymI_HasProto(rts_InstallConsoleEvent) \
432 SymI_HasProto(rts_ConsoleHandlerDone) \
433 SymI_NeedsProto(mktime) \
434 SymI_NeedsProto(_imp___timezone) \
435 SymI_NeedsProto(_imp___tzname) \
436 SymI_NeedsProto(_imp__tzname) \
437 SymI_NeedsProto(_imp___iob) \
438 SymI_NeedsProto(_imp___osver) \
439 SymI_NeedsProto(localtime) \
440 SymI_NeedsProto(gmtime) \
441 SymI_NeedsProto(opendir) \
442 SymI_NeedsProto(readdir) \
443 SymI_NeedsProto(rewinddir) \
444 RTS_MINGW_EXTRA_SYMS \
445 RTS_MINGW_GETTIMEOFDAY_SYM \
446 SymI_NeedsProto(closedir)
449 #if defined(darwin_TARGET_OS) && HAVE_PRINTF_LDBLSTUB
450 #define RTS_DARWIN_ONLY_SYMBOLS \
451 SymI_NeedsProto(asprintf$LDBLStub) \
452 SymI_NeedsProto(err$LDBLStub) \
453 SymI_NeedsProto(errc$LDBLStub) \
454 SymI_NeedsProto(errx$LDBLStub) \
455 SymI_NeedsProto(fprintf$LDBLStub) \
456 SymI_NeedsProto(fscanf$LDBLStub) \
457 SymI_NeedsProto(fwprintf$LDBLStub) \
458 SymI_NeedsProto(fwscanf$LDBLStub) \
459 SymI_NeedsProto(printf$LDBLStub) \
460 SymI_NeedsProto(scanf$LDBLStub) \
461 SymI_NeedsProto(snprintf$LDBLStub) \
462 SymI_NeedsProto(sprintf$LDBLStub) \
463 SymI_NeedsProto(sscanf$LDBLStub) \
464 SymI_NeedsProto(strtold$LDBLStub) \
465 SymI_NeedsProto(swprintf$LDBLStub) \
466 SymI_NeedsProto(swscanf$LDBLStub) \
467 SymI_NeedsProto(syslog$LDBLStub) \
468 SymI_NeedsProto(vasprintf$LDBLStub) \
469 SymI_NeedsProto(verr$LDBLStub) \
470 SymI_NeedsProto(verrc$LDBLStub) \
471 SymI_NeedsProto(verrx$LDBLStub) \
472 SymI_NeedsProto(vfprintf$LDBLStub) \
473 SymI_NeedsProto(vfscanf$LDBLStub) \
474 SymI_NeedsProto(vfwprintf$LDBLStub) \
475 SymI_NeedsProto(vfwscanf$LDBLStub) \
476 SymI_NeedsProto(vprintf$LDBLStub) \
477 SymI_NeedsProto(vscanf$LDBLStub) \
478 SymI_NeedsProto(vsnprintf$LDBLStub) \
479 SymI_NeedsProto(vsprintf$LDBLStub) \
480 SymI_NeedsProto(vsscanf$LDBLStub) \
481 SymI_NeedsProto(vswprintf$LDBLStub) \
482 SymI_NeedsProto(vswscanf$LDBLStub) \
483 SymI_NeedsProto(vsyslog$LDBLStub) \
484 SymI_NeedsProto(vwarn$LDBLStub) \
485 SymI_NeedsProto(vwarnc$LDBLStub) \
486 SymI_NeedsProto(vwarnx$LDBLStub) \
487 SymI_NeedsProto(vwprintf$LDBLStub) \
488 SymI_NeedsProto(vwscanf$LDBLStub) \
489 SymI_NeedsProto(warn$LDBLStub) \
490 SymI_NeedsProto(warnc$LDBLStub) \
491 SymI_NeedsProto(warnx$LDBLStub) \
492 SymI_NeedsProto(wcstold$LDBLStub) \
493 SymI_NeedsProto(wprintf$LDBLStub) \
494 SymI_NeedsProto(wscanf$LDBLStub)
496 #define RTS_DARWIN_ONLY_SYMBOLS
500 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
502 # define MAIN_CAP_SYM
505 #if !defined(mingw32_HOST_OS)
506 #define RTS_USER_SIGNALS_SYMBOLS \
507 SymI_HasProto(setIOManagerPipe) \
508 SymI_HasProto(blockUserSignals) \
509 SymI_HasProto(unblockUserSignals)
511 #define RTS_USER_SIGNALS_SYMBOLS \
512 SymI_HasProto(sendIOManagerEvent) \
513 SymI_HasProto(readIOManagerEvent) \
514 SymI_HasProto(getIOManagerEvent) \
515 SymI_HasProto(console_handler)
518 #define RTS_LIBFFI_SYMBOLS \
519 SymE_NeedsProto(ffi_prep_cif) \
520 SymE_NeedsProto(ffi_call) \
521 SymE_NeedsProto(ffi_type_void) \
522 SymE_NeedsProto(ffi_type_float) \
523 SymE_NeedsProto(ffi_type_double) \
524 SymE_NeedsProto(ffi_type_sint64) \
525 SymE_NeedsProto(ffi_type_uint64) \
526 SymE_NeedsProto(ffi_type_sint32) \
527 SymE_NeedsProto(ffi_type_uint32) \
528 SymE_NeedsProto(ffi_type_sint16) \
529 SymE_NeedsProto(ffi_type_uint16) \
530 SymE_NeedsProto(ffi_type_sint8) \
531 SymE_NeedsProto(ffi_type_uint8) \
532 SymE_NeedsProto(ffi_type_pointer)
534 #ifdef TABLES_NEXT_TO_CODE
535 #define RTS_RET_SYMBOLS /* nothing */
537 #define RTS_RET_SYMBOLS \
538 SymI_HasProto(stg_enter_ret) \
539 SymI_HasProto(stg_gc_fun_ret) \
540 SymI_HasProto(stg_ap_v_ret) \
541 SymI_HasProto(stg_ap_f_ret) \
542 SymI_HasProto(stg_ap_d_ret) \
543 SymI_HasProto(stg_ap_l_ret) \
544 SymI_HasProto(stg_ap_n_ret) \
545 SymI_HasProto(stg_ap_p_ret) \
546 SymI_HasProto(stg_ap_pv_ret) \
547 SymI_HasProto(stg_ap_pp_ret) \
548 SymI_HasProto(stg_ap_ppv_ret) \
549 SymI_HasProto(stg_ap_ppp_ret) \
550 SymI_HasProto(stg_ap_pppv_ret) \
551 SymI_HasProto(stg_ap_pppp_ret) \
552 SymI_HasProto(stg_ap_ppppp_ret) \
553 SymI_HasProto(stg_ap_pppppp_ret)
556 #define RTS_SYMBOLS \
558 SymI_HasProto(StgReturn) \
559 SymI_HasProto(stg_enter_info) \
560 SymI_HasProto(stg_gc_void_info) \
561 SymI_HasProto(__stg_gc_enter_1) \
562 SymI_HasProto(stg_gc_noregs) \
563 SymI_HasProto(stg_gc_unpt_r1_info) \
564 SymI_HasProto(stg_gc_unpt_r1) \
565 SymI_HasProto(stg_gc_unbx_r1_info) \
566 SymI_HasProto(stg_gc_unbx_r1) \
567 SymI_HasProto(stg_gc_f1_info) \
568 SymI_HasProto(stg_gc_f1) \
569 SymI_HasProto(stg_gc_d1_info) \
570 SymI_HasProto(stg_gc_d1) \
571 SymI_HasProto(stg_gc_l1_info) \
572 SymI_HasProto(stg_gc_l1) \
573 SymI_HasProto(__stg_gc_fun) \
574 SymI_HasProto(stg_gc_fun_info) \
575 SymI_HasProto(stg_gc_gen) \
576 SymI_HasProto(stg_gc_gen_info) \
577 SymI_HasProto(stg_gc_gen_hp) \
578 SymI_HasProto(stg_gc_ut) \
579 SymI_HasProto(stg_gen_yield) \
580 SymI_HasProto(stg_yield_noregs) \
581 SymI_HasProto(stg_yield_to_interpreter) \
582 SymI_HasProto(stg_gen_block) \
583 SymI_HasProto(stg_block_noregs) \
584 SymI_HasProto(stg_block_1) \
585 SymI_HasProto(stg_block_takemvar) \
586 SymI_HasProto(stg_block_putmvar) \
588 SymI_HasProto(MallocFailHook) \
589 SymI_HasProto(OnExitHook) \
590 SymI_HasProto(OutOfHeapHook) \
591 SymI_HasProto(StackOverflowHook) \
592 SymI_HasProto(addDLL) \
593 SymI_HasProto(__int_encodeDouble) \
594 SymI_HasProto(__word_encodeDouble) \
595 SymI_HasProto(__2Int_encodeDouble) \
596 SymI_HasProto(__int_encodeFloat) \
597 SymI_HasProto(__word_encodeFloat) \
598 SymI_HasProto(stg_atomicallyzh) \
599 SymI_HasProto(barf) \
600 SymI_HasProto(debugBelch) \
601 SymI_HasProto(errorBelch) \
602 SymI_HasProto(sysErrorBelch) \
603 SymI_HasProto(stg_asyncExceptionsBlockedzh) \
604 SymI_HasProto(stg_blockAsyncExceptionszh) \
605 SymI_HasProto(stg_catchzh) \
606 SymI_HasProto(stg_catchRetryzh) \
607 SymI_HasProto(stg_catchSTMzh) \
608 SymI_HasProto(stg_checkzh) \
609 SymI_HasProto(closure_flags) \
610 SymI_HasProto(cmp_thread) \
611 SymI_HasProto(createAdjustor) \
612 SymI_HasProto(stg_decodeDoublezu2Intzh) \
613 SymI_HasProto(stg_decodeFloatzuIntzh) \
614 SymI_HasProto(defaultsHook) \
615 SymI_HasProto(stg_delayzh) \
616 SymI_HasProto(stg_deRefWeakzh) \
617 SymI_HasProto(stg_deRefStablePtrzh) \
618 SymI_HasProto(dirty_MUT_VAR) \
619 SymI_HasProto(stg_forkzh) \
620 SymI_HasProto(stg_forkOnzh) \
621 SymI_HasProto(forkProcess) \
622 SymI_HasProto(forkOS_createThread) \
623 SymI_HasProto(freeHaskellFunctionPtr) \
624 SymI_HasProto(getOrSetTypeableStore) \
625 SymI_HasProto(getOrSetSignalHandlerStore) \
626 SymI_HasProto(genSymZh) \
627 SymI_HasProto(genericRaise) \
628 SymI_HasProto(getProgArgv) \
629 SymI_HasProto(getFullProgArgv) \
630 SymI_HasProto(getStablePtr) \
631 SymI_HasProto(hs_init) \
632 SymI_HasProto(hs_exit) \
633 SymI_HasProto(hs_set_argv) \
634 SymI_HasProto(hs_add_root) \
635 SymI_HasProto(hs_perform_gc) \
636 SymI_HasProto(hs_free_stable_ptr) \
637 SymI_HasProto(hs_free_fun_ptr) \
638 SymI_HasProto(hs_hpc_rootModule) \
639 SymI_HasProto(hs_hpc_module) \
640 SymI_HasProto(initLinker) \
641 SymI_HasProto(stg_unpackClosurezh) \
642 SymI_HasProto(stg_getApStackValzh) \
643 SymI_HasProto(stg_getSparkzh) \
644 SymI_HasProto(stg_isCurrentThreadBoundzh) \
645 SymI_HasProto(stg_isEmptyMVarzh) \
646 SymI_HasProto(stg_killThreadzh) \
647 SymI_HasProto(loadObj) \
648 SymI_HasProto(insertStableSymbol) \
649 SymI_HasProto(insertSymbol) \
650 SymI_HasProto(lookupSymbol) \
651 SymI_HasProto(stg_makeStablePtrzh) \
652 SymI_HasProto(stg_mkApUpd0zh) \
653 SymI_HasProto(stg_myThreadIdzh) \
654 SymI_HasProto(stg_labelThreadzh) \
655 SymI_HasProto(stg_newArrayzh) \
656 SymI_HasProto(stg_newBCOzh) \
657 SymI_HasProto(stg_newByteArrayzh) \
658 SymI_HasProto_redirect(newCAF, newDynCAF) \
659 SymI_HasProto(stg_newMVarzh) \
660 SymI_HasProto(stg_newMutVarzh) \
661 SymI_HasProto(stg_newTVarzh) \
662 SymI_HasProto(stg_noDuplicatezh) \
663 SymI_HasProto(stg_atomicModifyMutVarzh) \
664 SymI_HasProto(stg_newPinnedByteArrayzh) \
665 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
666 SymI_HasProto(newSpark) \
667 SymI_HasProto(performGC) \
668 SymI_HasProto(performMajorGC) \
669 SymI_HasProto(prog_argc) \
670 SymI_HasProto(prog_argv) \
671 SymI_HasProto(stg_putMVarzh) \
672 SymI_HasProto(stg_raisezh) \
673 SymI_HasProto(stg_raiseIOzh) \
674 SymI_HasProto(stg_readTVarzh) \
675 SymI_HasProto(stg_readTVarIOzh) \
676 SymI_HasProto(resumeThread) \
677 SymI_HasProto(resolveObjs) \
678 SymI_HasProto(stg_retryzh) \
679 SymI_HasProto(rts_apply) \
680 SymI_HasProto(rts_checkSchedStatus) \
681 SymI_HasProto(rts_eval) \
682 SymI_HasProto(rts_evalIO) \
683 SymI_HasProto(rts_evalLazyIO) \
684 SymI_HasProto(rts_evalStableIO) \
685 SymI_HasProto(rts_eval_) \
686 SymI_HasProto(rts_getBool) \
687 SymI_HasProto(rts_getChar) \
688 SymI_HasProto(rts_getDouble) \
689 SymI_HasProto(rts_getFloat) \
690 SymI_HasProto(rts_getInt) \
691 SymI_HasProto(rts_getInt8) \
692 SymI_HasProto(rts_getInt16) \
693 SymI_HasProto(rts_getInt32) \
694 SymI_HasProto(rts_getInt64) \
695 SymI_HasProto(rts_getPtr) \
696 SymI_HasProto(rts_getFunPtr) \
697 SymI_HasProto(rts_getStablePtr) \
698 SymI_HasProto(rts_getThreadId) \
699 SymI_HasProto(rts_getWord) \
700 SymI_HasProto(rts_getWord8) \
701 SymI_HasProto(rts_getWord16) \
702 SymI_HasProto(rts_getWord32) \
703 SymI_HasProto(rts_getWord64) \
704 SymI_HasProto(rts_lock) \
705 SymI_HasProto(rts_mkBool) \
706 SymI_HasProto(rts_mkChar) \
707 SymI_HasProto(rts_mkDouble) \
708 SymI_HasProto(rts_mkFloat) \
709 SymI_HasProto(rts_mkInt) \
710 SymI_HasProto(rts_mkInt8) \
711 SymI_HasProto(rts_mkInt16) \
712 SymI_HasProto(rts_mkInt32) \
713 SymI_HasProto(rts_mkInt64) \
714 SymI_HasProto(rts_mkPtr) \
715 SymI_HasProto(rts_mkFunPtr) \
716 SymI_HasProto(rts_mkStablePtr) \
717 SymI_HasProto(rts_mkString) \
718 SymI_HasProto(rts_mkWord) \
719 SymI_HasProto(rts_mkWord8) \
720 SymI_HasProto(rts_mkWord16) \
721 SymI_HasProto(rts_mkWord32) \
722 SymI_HasProto(rts_mkWord64) \
723 SymI_HasProto(rts_unlock) \
724 SymI_HasProto(rts_unsafeGetMyCapability) \
725 SymI_HasProto(rtsSupportsBoundThreads) \
726 SymI_HasProto(setProgArgv) \
727 SymI_HasProto(startupHaskell) \
728 SymI_HasProto(shutdownHaskell) \
729 SymI_HasProto(shutdownHaskellAndExit) \
730 SymI_HasProto(stable_ptr_table) \
731 SymI_HasProto(stackOverflow) \
732 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
733 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
734 SymI_HasProto(startTimer) \
735 SymI_HasProto(stg_CHARLIKE_closure) \
736 SymI_HasProto(stg_MVAR_CLEAN_info) \
737 SymI_HasProto(stg_MVAR_DIRTY_info) \
738 SymI_HasProto(stg_IND_STATIC_info) \
739 SymI_HasProto(stg_INTLIKE_closure) \
740 SymI_HasProto(stg_ARR_WORDS_info) \
741 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
742 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
743 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
744 SymI_HasProto(stg_WEAK_info) \
745 SymI_HasProto(stg_ap_v_info) \
746 SymI_HasProto(stg_ap_f_info) \
747 SymI_HasProto(stg_ap_d_info) \
748 SymI_HasProto(stg_ap_l_info) \
749 SymI_HasProto(stg_ap_n_info) \
750 SymI_HasProto(stg_ap_p_info) \
751 SymI_HasProto(stg_ap_pv_info) \
752 SymI_HasProto(stg_ap_pp_info) \
753 SymI_HasProto(stg_ap_ppv_info) \
754 SymI_HasProto(stg_ap_ppp_info) \
755 SymI_HasProto(stg_ap_pppv_info) \
756 SymI_HasProto(stg_ap_pppp_info) \
757 SymI_HasProto(stg_ap_ppppp_info) \
758 SymI_HasProto(stg_ap_pppppp_info) \
759 SymI_HasProto(stg_ap_0_fast) \
760 SymI_HasProto(stg_ap_v_fast) \
761 SymI_HasProto(stg_ap_f_fast) \
762 SymI_HasProto(stg_ap_d_fast) \
763 SymI_HasProto(stg_ap_l_fast) \
764 SymI_HasProto(stg_ap_n_fast) \
765 SymI_HasProto(stg_ap_p_fast) \
766 SymI_HasProto(stg_ap_pv_fast) \
767 SymI_HasProto(stg_ap_pp_fast) \
768 SymI_HasProto(stg_ap_ppv_fast) \
769 SymI_HasProto(stg_ap_ppp_fast) \
770 SymI_HasProto(stg_ap_pppv_fast) \
771 SymI_HasProto(stg_ap_pppp_fast) \
772 SymI_HasProto(stg_ap_ppppp_fast) \
773 SymI_HasProto(stg_ap_pppppp_fast) \
774 SymI_HasProto(stg_ap_1_upd_info) \
775 SymI_HasProto(stg_ap_2_upd_info) \
776 SymI_HasProto(stg_ap_3_upd_info) \
777 SymI_HasProto(stg_ap_4_upd_info) \
778 SymI_HasProto(stg_ap_5_upd_info) \
779 SymI_HasProto(stg_ap_6_upd_info) \
780 SymI_HasProto(stg_ap_7_upd_info) \
781 SymI_HasProto(stg_exit) \
782 SymI_HasProto(stg_sel_0_upd_info) \
783 SymI_HasProto(stg_sel_10_upd_info) \
784 SymI_HasProto(stg_sel_11_upd_info) \
785 SymI_HasProto(stg_sel_12_upd_info) \
786 SymI_HasProto(stg_sel_13_upd_info) \
787 SymI_HasProto(stg_sel_14_upd_info) \
788 SymI_HasProto(stg_sel_15_upd_info) \
789 SymI_HasProto(stg_sel_1_upd_info) \
790 SymI_HasProto(stg_sel_2_upd_info) \
791 SymI_HasProto(stg_sel_3_upd_info) \
792 SymI_HasProto(stg_sel_4_upd_info) \
793 SymI_HasProto(stg_sel_5_upd_info) \
794 SymI_HasProto(stg_sel_6_upd_info) \
795 SymI_HasProto(stg_sel_7_upd_info) \
796 SymI_HasProto(stg_sel_8_upd_info) \
797 SymI_HasProto(stg_sel_9_upd_info) \
798 SymI_HasProto(stg_upd_frame_info) \
799 SymI_HasProto(suspendThread) \
800 SymI_HasProto(stg_takeMVarzh) \
801 SymI_HasProto(stg_threadStatuszh) \
802 SymI_HasProto(stg_tryPutMVarzh) \
803 SymI_HasProto(stg_tryTakeMVarzh) \
804 SymI_HasProto(stg_unblockAsyncExceptionszh) \
805 SymI_HasProto(unloadObj) \
806 SymI_HasProto(stg_unsafeThawArrayzh) \
807 SymI_HasProto(stg_waitReadzh) \
808 SymI_HasProto(stg_waitWritezh) \
809 SymI_HasProto(stg_writeTVarzh) \
810 SymI_HasProto(stg_yieldzh) \
811 SymI_NeedsProto(stg_interp_constr_entry) \
812 SymI_HasProto(alloc_blocks) \
813 SymI_HasProto(alloc_blocks_lim) \
814 SymI_HasProto(allocateLocal) \
815 SymI_HasProto(allocateExec) \
816 SymI_HasProto(freeExec) \
817 SymI_HasProto(getAllocations) \
818 SymI_HasProto(revertCAFs) \
819 SymI_HasProto(RtsFlags) \
820 SymI_NeedsProto(rts_breakpoint_io_action) \
821 SymI_NeedsProto(rts_stop_next_breakpoint) \
822 SymI_NeedsProto(rts_stop_on_exception) \
823 SymI_HasProto(stopTimer) \
824 SymI_HasProto(n_capabilities) \
825 SymI_HasProto(stg_traceCcszh) \
826 SymI_HasProto(stg_traceEventzh) \
827 RTS_USER_SIGNALS_SYMBOLS
830 // 64-bit support functions in libgcc.a
831 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
832 #define RTS_LIBGCC_SYMBOLS \
833 SymI_NeedsProto(__divdi3) \
834 SymI_NeedsProto(__udivdi3) \
835 SymI_NeedsProto(__moddi3) \
836 SymI_NeedsProto(__umoddi3) \
837 SymI_NeedsProto(__muldi3) \
838 SymI_NeedsProto(__ashldi3) \
839 SymI_NeedsProto(__ashrdi3) \
840 SymI_NeedsProto(__lshrdi3) \
841 SymI_NeedsProto(__eprintf)
843 #define RTS_LIBGCC_SYMBOLS
846 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
847 // Symbols that don't have a leading underscore
848 // on Mac OS X. They have to receive special treatment,
849 // see machoInitSymbolsWithoutUnderscore()
850 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
851 SymI_NeedsProto(saveFP) \
852 SymI_NeedsProto(restFP)
855 /* entirely bogus claims about types of these symbols */
856 #define SymI_NeedsProto(vvv) extern void vvv(void);
857 #if defined(__PIC__) && defined(mingw32_TARGET_OS)
858 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
859 #define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
861 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
862 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
864 #define SymI_HasProto(vvv) /**/
865 #define SymI_HasProto_redirect(vvv,xxx) /**/
868 RTS_POSIX_ONLY_SYMBOLS
869 RTS_MINGW_ONLY_SYMBOLS
870 RTS_CYGWIN_ONLY_SYMBOLS
871 RTS_DARWIN_ONLY_SYMBOLS
874 #undef SymI_NeedsProto
876 #undef SymI_HasProto_redirect
878 #undef SymE_NeedsProto
880 #ifdef LEADING_UNDERSCORE
881 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
883 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
886 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
888 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
889 (void*)DLL_IMPORT_DATA_REF(vvv) },
891 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
892 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
894 // SymI_HasProto_redirect allows us to redirect references to one symbol to
895 // another symbol. See newCAF/newDynCAF for an example.
896 #define SymI_HasProto_redirect(vvv,xxx) \
897 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
900 static RtsSymbolVal rtsSyms[] = {
903 RTS_POSIX_ONLY_SYMBOLS
904 RTS_MINGW_ONLY_SYMBOLS
905 RTS_CYGWIN_ONLY_SYMBOLS
906 RTS_DARWIN_ONLY_SYMBOLS
909 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
910 // dyld stub code contains references to this,
911 // but it should never be called because we treat
912 // lazy pointers as nonlazy.
913 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
915 { 0, 0 } /* sentinel */
920 /* -----------------------------------------------------------------------------
921 * Insert symbols into hash tables, checking for duplicates.
924 static void ghciInsertStrHashTable ( char* obj_name,
930 if (lookupHashTable(table, (StgWord)key) == NULL)
932 insertStrHashTable(table, (StgWord)key, data);
937 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
939 "whilst processing object file\n"
941 "This could be caused by:\n"
942 " * Loading two different object files which export the same symbol\n"
943 " * Specifying the same object file twice on the GHCi command line\n"
944 " * An incorrect `package.conf' entry, causing some object to be\n"
946 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
953 /* -----------------------------------------------------------------------------
954 * initialize the object linker
958 static int linker_init_done = 0 ;
960 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
961 static void *dl_prog_handle;
969 /* Make initLinker idempotent, so we can call it
970 before evey relevant operation; that means we
971 don't need to initialise the linker separately */
972 if (linker_init_done == 1) { return; } else {
973 linker_init_done = 1;
976 stablehash = allocStrHashTable();
977 symhash = allocStrHashTable();
979 /* populate the symbol table with stuff from the RTS */
980 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
981 ghciInsertStrHashTable("(GHCi built-in symbols)",
982 symhash, sym->lbl, sym->addr);
984 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
985 machoInitSymbolsWithoutUnderscore();
988 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
989 # if defined(RTLD_DEFAULT)
990 dl_prog_handle = RTLD_DEFAULT;
992 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
993 # endif /* RTLD_DEFAULT */
996 #if defined(x86_64_HOST_ARCH)
997 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
998 // User-override for mmap_32bit_base
999 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1003 #if defined(mingw32_HOST_OS)
1005 * These two libraries cause problems when added to the static link,
1006 * but are necessary for resolving symbols in GHCi, hence we load
1007 * them manually here.
1014 /* -----------------------------------------------------------------------------
1015 * Loading DLL or .so dynamic libraries
1016 * -----------------------------------------------------------------------------
1018 * Add a DLL from which symbols may be found. In the ELF case, just
1019 * do RTLD_GLOBAL-style add, so no further messing around needs to
1020 * happen in order that symbols in the loaded .so are findable --
1021 * lookupSymbol() will subsequently see them by dlsym on the program's
1022 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1024 * In the PEi386 case, open the DLLs and put handles to them in a
1025 * linked list. When looking for a symbol, try all handles in the
1026 * list. This means that we need to load even DLLs that are guaranteed
1027 * to be in the ghc.exe image already, just so we can get a handle
1028 * to give to loadSymbol, so that we can find the symbols. For such
1029 * libraries, the LoadLibrary call should be a no-op except for returning
1034 #if defined(OBJFORMAT_PEi386)
1035 /* A record for storing handles into DLLs. */
1040 struct _OpenedDLL* next;
1045 /* A list thereof. */
1046 static OpenedDLL* opened_dlls = NULL;
1050 addDLL( char *dll_name )
1052 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1053 /* ------------------- ELF DLL loader ------------------- */
1059 // omitted: RTLD_NOW
1060 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1061 hdl= dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1064 /* dlopen failed; return a ptr to the error msg. */
1066 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1073 # elif defined(OBJFORMAT_PEi386)
1074 /* ------------------- Win32 DLL loader ------------------- */
1082 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1084 /* See if we've already got it, and ignore if so. */
1085 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1086 if (0 == strcmp(o_dll->name, dll_name))
1090 /* The file name has no suffix (yet) so that we can try
1091 both foo.dll and foo.drv
1093 The documentation for LoadLibrary says:
1094 If no file name extension is specified in the lpFileName
1095 parameter, the default library extension .dll is
1096 appended. However, the file name string can include a trailing
1097 point character (.) to indicate that the module name has no
1100 buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1101 sprintf(buf, "%s.DLL", dll_name);
1102 instance = LoadLibrary(buf);
1103 if (instance == NULL) {
1104 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1105 // KAA: allow loading of drivers (like winspool.drv)
1106 sprintf(buf, "%s.DRV", dll_name);
1107 instance = LoadLibrary(buf);
1108 if (instance == NULL) {
1109 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1110 // #1883: allow loading of unix-style libfoo.dll DLLs
1111 sprintf(buf, "lib%s.DLL", dll_name);
1112 instance = LoadLibrary(buf);
1113 if (instance == NULL) {
1120 /* Add this DLL to the list of DLLs in which to search for symbols. */
1121 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1122 o_dll->name = stgMallocBytes(1+strlen(dll_name), "addDLL");
1123 strcpy(o_dll->name, dll_name);
1124 o_dll->instance = instance;
1125 o_dll->next = opened_dlls;
1126 opened_dlls = o_dll;
1132 sysErrorBelch(dll_name);
1134 /* LoadLibrary failed; return a ptr to the error msg. */
1135 return "addDLL: could not load DLL";
1138 barf("addDLL: not implemented on this platform");
1142 /* -----------------------------------------------------------------------------
1143 * insert a stable symbol in the hash table
1147 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1149 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1153 /* -----------------------------------------------------------------------------
1154 * insert a symbol in the hash table
1157 insertSymbol(char* obj_name, char* key, void* data)
1159 ghciInsertStrHashTable(obj_name, symhash, key, data);
1162 /* -----------------------------------------------------------------------------
1163 * lookup a symbol in the hash table
1166 lookupSymbol( char *lbl )
1170 ASSERT(symhash != NULL);
1171 val = lookupStrHashTable(symhash, lbl);
1174 # if defined(OBJFORMAT_ELF)
1175 return dlsym(dl_prog_handle, lbl);
1176 # elif defined(OBJFORMAT_MACHO)
1178 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1181 HACK: On OS X, global symbols are prefixed with an underscore.
1182 However, dlsym wants us to omit the leading underscore from the
1183 symbol name. For now, we simply strip it off here (and ONLY
1186 ASSERT(lbl[0] == '_');
1187 return dlsym(dl_prog_handle, lbl+1);
1189 if(NSIsSymbolNameDefined(lbl)) {
1190 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1191 return NSAddressOfSymbol(symbol);
1195 # endif /* HAVE_DLFCN_H */
1196 # elif defined(OBJFORMAT_PEi386)
1199 sym = lookupSymbolInDLLs(lbl);
1200 if (sym != NULL) { return sym; };
1202 // Also try looking up the symbol without the @N suffix. Some
1203 // DLLs have the suffixes on their symbols, some don't.
1204 zapTrailingAtSign ( lbl );
1205 sym = lookupSymbolInDLLs(lbl);
1206 if (sym != NULL) { return sym; };
1218 /* -----------------------------------------------------------------------------
1219 * Debugging aid: look in GHCi's object symbol tables for symbols
1220 * within DELTA bytes of the specified address, and show their names.
1223 void ghci_enquire ( char* addr );
1225 void ghci_enquire ( char* addr )
1230 const int DELTA = 64;
1235 for (oc = objects; oc; oc = oc->next) {
1236 for (i = 0; i < oc->n_symbols; i++) {
1237 sym = oc->symbols[i];
1238 if (sym == NULL) continue;
1241 a = lookupStrHashTable(symhash, sym);
1244 // debugBelch("ghci_enquire: can't find %s\n", sym);
1246 else if (addr-DELTA <= a && a <= addr+DELTA) {
1247 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1255 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1258 mmapForLinker (size_t bytes, nat flags, int fd)
1260 void *map_addr = NULL;
1263 static nat fixed = 0;
1265 pagesize = getpagesize();
1266 size = ROUND_UP(bytes, pagesize);
1268 #if defined(x86_64_HOST_ARCH)
1271 if (mmap_32bit_base != 0) {
1272 map_addr = mmap_32bit_base;
1276 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1277 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1279 if (result == MAP_FAILED) {
1280 sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1281 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1282 stg_exit(EXIT_FAILURE);
1285 #if defined(x86_64_HOST_ARCH)
1286 if (mmap_32bit_base != 0) {
1287 if (result == map_addr) {
1288 mmap_32bit_base = (StgWord8*)map_addr + size;
1290 if ((W_)result > 0x80000000) {
1291 // oops, we were given memory over 2Gb
1292 #if defined(freebsd_HOST_OS)
1293 // Some platforms require MAP_FIXED. This is normally
1294 // a bad idea, because MAP_FIXED will overwrite
1295 // existing mappings.
1296 munmap(result,size);
1300 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);
1303 // hmm, we were given memory somewhere else, but it's
1304 // still under 2Gb so we can use it. Next time, ask
1305 // for memory right after the place we just got some
1306 mmap_32bit_base = (StgWord8*)result + size;
1310 if ((W_)result > 0x80000000) {
1311 // oops, we were given memory over 2Gb
1312 // ... try allocating memory somewhere else?;
1313 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1314 munmap(result, size);
1316 // Set a base address and try again... (guess: 1Gb)
1317 mmap_32bit_base = (void*)0x40000000;
1327 /* -----------------------------------------------------------------------------
1328 * Load an obj (populate the global symbol table, but don't resolve yet)
1330 * Returns: 1 if ok, 0 on error.
1333 loadObj( char *path )
1345 /* debugBelch("loadObj %s\n", path ); */
1347 /* Check that we haven't already loaded this object.
1348 Ignore requests to load multiple times */
1352 for (o = objects; o; o = o->next) {
1353 if (0 == strcmp(o->fileName, path)) {
1355 break; /* don't need to search further */
1359 IF_DEBUG(linker, debugBelch(
1360 "GHCi runtime linker: warning: looks like you're trying to load the\n"
1361 "same object file twice:\n"
1363 "GHCi will ignore this, but be warned.\n"
1365 return 1; /* success */
1369 oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
1371 # if defined(OBJFORMAT_ELF)
1372 oc->formatName = "ELF";
1373 # elif defined(OBJFORMAT_PEi386)
1374 oc->formatName = "PEi386";
1375 # elif defined(OBJFORMAT_MACHO)
1376 oc->formatName = "Mach-O";
1379 barf("loadObj: not implemented on this platform");
1382 r = stat(path, &st);
1383 if (r == -1) { return 0; }
1385 /* sigh, strdup() isn't a POSIX function, so do it the long way */
1386 oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1387 strcpy(oc->fileName, path);
1389 oc->fileSize = st.st_size;
1391 oc->sections = NULL;
1392 oc->proddables = NULL;
1394 /* chain it onto the list of objects */
1399 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
1401 #if defined(openbsd_HOST_OS)
1402 fd = open(path, O_RDONLY, S_IRUSR);
1404 fd = open(path, O_RDONLY);
1407 barf("loadObj: can't open `%s'", path);
1409 oc->image = mmapForLinker(oc->fileSize, 0, fd);
1413 #else /* !USE_MMAP */
1414 /* load the image into memory */
1415 f = fopen(path, "rb");
1417 barf("loadObj: can't read `%s'", path);
1419 # if defined(mingw32_HOST_OS)
1420 // TODO: We would like to use allocateExec here, but allocateExec
1421 // cannot currently allocate blocks large enough.
1422 oc->image = VirtualAlloc(NULL, oc->fileSize, MEM_RESERVE | MEM_COMMIT,
1423 PAGE_EXECUTE_READWRITE);
1424 # elif defined(darwin_HOST_OS)
1425 // In a Mach-O .o file, all sections can and will be misaligned
1426 // if the total size of the headers is not a multiple of the
1427 // desired alignment. This is fine for .o files that only serve
1428 // as input for the static linker, but it's not fine for us,
1429 // as SSE (used by gcc for floating point) and Altivec require
1430 // 16-byte alignment.
1431 // We calculate the correct alignment from the header before
1432 // reading the file, and then we misalign oc->image on purpose so
1433 // that the actual sections end up aligned again.
1434 oc->misalignment = machoGetMisalignment(f);
1435 oc->image = stgMallocBytes(oc->fileSize + oc->misalignment, "loadObj(image)");
1436 oc->image += oc->misalignment;
1438 oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
1443 n = fread ( oc->image, 1, oc->fileSize, f );
1444 if (n != oc->fileSize)
1445 barf("loadObj: error whilst reading `%s'", path);
1448 #endif /* USE_MMAP */
1450 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1451 r = ocAllocateSymbolExtras_MachO ( oc );
1452 if (!r) { return r; }
1453 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
1454 r = ocAllocateSymbolExtras_ELF ( oc );
1455 if (!r) { return r; }
1458 /* verify the in-memory image */
1459 # if defined(OBJFORMAT_ELF)
1460 r = ocVerifyImage_ELF ( oc );
1461 # elif defined(OBJFORMAT_PEi386)
1462 r = ocVerifyImage_PEi386 ( oc );
1463 # elif defined(OBJFORMAT_MACHO)
1464 r = ocVerifyImage_MachO ( oc );
1466 barf("loadObj: no verify method");
1468 if (!r) { return r; }
1470 /* build the symbol list for this image */
1471 # if defined(OBJFORMAT_ELF)
1472 r = ocGetNames_ELF ( oc );
1473 # elif defined(OBJFORMAT_PEi386)
1474 r = ocGetNames_PEi386 ( oc );
1475 # elif defined(OBJFORMAT_MACHO)
1476 r = ocGetNames_MachO ( oc );
1478 barf("loadObj: no getNames method");
1480 if (!r) { return r; }
1482 /* loaded, but not resolved yet */
1483 oc->status = OBJECT_LOADED;
1488 /* -----------------------------------------------------------------------------
1489 * resolve all the currently unlinked objects in memory
1491 * Returns: 1 if ok, 0 on error.
1501 for (oc = objects; oc; oc = oc->next) {
1502 if (oc->status != OBJECT_RESOLVED) {
1503 # if defined(OBJFORMAT_ELF)
1504 r = ocResolve_ELF ( oc );
1505 # elif defined(OBJFORMAT_PEi386)
1506 r = ocResolve_PEi386 ( oc );
1507 # elif defined(OBJFORMAT_MACHO)
1508 r = ocResolve_MachO ( oc );
1510 barf("resolveObjs: not implemented on this platform");
1512 if (!r) { return r; }
1513 oc->status = OBJECT_RESOLVED;
1519 /* -----------------------------------------------------------------------------
1520 * delete an object from the pool
1523 unloadObj( char *path )
1525 ObjectCode *oc, *prev;
1527 ASSERT(symhash != NULL);
1528 ASSERT(objects != NULL);
1533 for (oc = objects; oc; prev = oc, oc = oc->next) {
1534 if (!strcmp(oc->fileName,path)) {
1536 /* Remove all the mappings for the symbols within this
1541 for (i = 0; i < oc->n_symbols; i++) {
1542 if (oc->symbols[i] != NULL) {
1543 removeStrHashTable(symhash, oc->symbols[i], NULL);
1551 prev->next = oc->next;
1554 // We're going to leave this in place, in case there are
1555 // any pointers from the heap into it:
1556 // #ifdef mingw32_HOST_OS
1557 // VirtualFree(oc->image);
1559 // stgFree(oc->image);
1561 stgFree(oc->fileName);
1562 stgFree(oc->symbols);
1563 stgFree(oc->sections);
1569 errorBelch("unloadObj: can't find `%s' to unload", path);
1573 /* -----------------------------------------------------------------------------
1574 * Sanity checking. For each ObjectCode, maintain a list of address ranges
1575 * which may be prodded during relocation, and abort if we try and write
1576 * outside any of these.
1578 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1581 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1582 /* debugBelch("aPB %p %p %d\n", oc, start, size); */
1586 pb->next = oc->proddables;
1587 oc->proddables = pb;
1590 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1593 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1594 char* s = (char*)(pb->start);
1595 char* e = s + pb->size - 1;
1596 char* a = (char*)addr;
1597 /* Assumes that the biggest fixup involves a 4-byte write. This
1598 probably needs to be changed to 8 (ie, +7) on 64-bit
1600 if (a >= s && (a+3) <= e) return;
1602 barf("checkProddableBlock: invalid fixup in runtime linker");
1605 /* -----------------------------------------------------------------------------
1606 * Section management.
1608 static void addSection ( ObjectCode* oc, SectionKind kind,
1609 void* start, void* end )
1611 Section* s = stgMallocBytes(sizeof(Section), "addSection");
1615 s->next = oc->sections;
1618 debugBelch("addSection: %p-%p (size %d), kind %d\n",
1619 start, ((char*)end)-1, end - start + 1, kind );
1624 /* --------------------------------------------------------------------------
1626 * This is about allocating a small chunk of memory for every symbol in the
1627 * object file. We make sure that the SymboLExtras are always "in range" of
1628 * limited-range PC-relative instructions on various platforms by allocating
1629 * them right next to the object code itself.
1632 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
1635 ocAllocateSymbolExtras
1637 Allocate additional space at the end of the object file image to make room
1638 for jump islands (powerpc, x86_64) and GOT entries (x86_64).
1640 PowerPC relative branch instructions have a 24 bit displacement field.
1641 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
1642 If a particular imported symbol is outside this range, we have to redirect
1643 the jump to a short piece of new code that just loads the 32bit absolute
1644 address and jumps there.
1645 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
1648 This function just allocates space for one SymbolExtra for every
1649 undefined symbol in the object file. The code for the jump islands is
1650 filled in by makeSymbolExtra below.
1653 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
1660 int misalignment = 0;
1661 #ifdef darwin_HOST_OS
1662 misalignment = oc->misalignment;
1668 // round up to the nearest 4
1669 aligned = (oc->fileSize + 3) & ~3;
1672 pagesize = getpagesize();
1673 n = ROUND_UP( oc->fileSize, pagesize );
1674 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
1676 /* we try to use spare space at the end of the last page of the
1677 * image for the jump islands, but if there isn't enough space
1678 * then we have to map some (anonymously, remembering MAP_32BIT).
1680 if( m > n ) // we need to allocate more pages
1682 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
1687 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1690 oc->image -= misalignment;
1691 oc->image = stgReallocBytes( oc->image,
1693 aligned + sizeof (SymbolExtra) * count,
1694 "ocAllocateSymbolExtras" );
1695 oc->image += misalignment;
1697 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
1698 #endif /* USE_MMAP */
1700 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
1703 oc->symbol_extras = NULL;
1705 oc->first_symbol_extra = first;
1706 oc->n_symbol_extras = count;
1711 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
1712 unsigned long symbolNumber,
1713 unsigned long target )
1717 ASSERT( symbolNumber >= oc->first_symbol_extra
1718 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
1720 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
1722 #ifdef powerpc_HOST_ARCH
1723 // lis r12, hi16(target)
1724 extra->jumpIsland.lis_r12 = 0x3d80;
1725 extra->jumpIsland.hi_addr = target >> 16;
1727 // ori r12, r12, lo16(target)
1728 extra->jumpIsland.ori_r12_r12 = 0x618c;
1729 extra->jumpIsland.lo_addr = target & 0xffff;
1732 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
1735 extra->jumpIsland.bctr = 0x4e800420;
1737 #ifdef x86_64_HOST_ARCH
1739 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
1740 extra->addr = target;
1741 memcpy(extra->jumpIsland, jmp, 6);
1749 /* --------------------------------------------------------------------------
1750 * PowerPC specifics (instruction cache flushing)
1751 * ------------------------------------------------------------------------*/
1753 #ifdef powerpc_TARGET_ARCH
1755 ocFlushInstructionCache
1757 Flush the data & instruction caches.
1758 Because the PPC has split data/instruction caches, we have to
1759 do that whenever we modify code at runtime.
1762 static void ocFlushInstructionCache( ObjectCode *oc )
1764 int n = (oc->fileSize + sizeof( SymbolExtra ) * oc->n_symbol_extras + 3) / 4;
1765 unsigned long *p = (unsigned long *) oc->image;
1769 __asm__ volatile ( "dcbf 0,%0\n\t"
1777 __asm__ volatile ( "sync\n\t"
1783 /* --------------------------------------------------------------------------
1784 * PEi386 specifics (Win32 targets)
1785 * ------------------------------------------------------------------------*/
1787 /* The information for this linker comes from
1788 Microsoft Portable Executable
1789 and Common Object File Format Specification
1790 revision 5.1 January 1998
1791 which SimonM says comes from the MS Developer Network CDs.
1793 It can be found there (on older CDs), but can also be found
1796 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
1798 (this is Rev 6.0 from February 1999).
1800 Things move, so if that fails, try searching for it via
1802 http://www.google.com/search?q=PE+COFF+specification
1804 The ultimate reference for the PE format is the Winnt.h
1805 header file that comes with the Platform SDKs; as always,
1806 implementations will drift wrt their documentation.
1808 A good background article on the PE format is Matt Pietrek's
1809 March 1994 article in Microsoft System Journal (MSJ)
1810 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
1811 Win32 Portable Executable File Format." The info in there
1812 has recently been updated in a two part article in
1813 MSDN magazine, issues Feb and March 2002,
1814 "Inside Windows: An In-Depth Look into the Win32 Portable
1815 Executable File Format"
1817 John Levine's book "Linkers and Loaders" contains useful
1822 #if defined(OBJFORMAT_PEi386)
1826 typedef unsigned char UChar;
1827 typedef unsigned short UInt16;
1828 typedef unsigned int UInt32;
1835 UInt16 NumberOfSections;
1836 UInt32 TimeDateStamp;
1837 UInt32 PointerToSymbolTable;
1838 UInt32 NumberOfSymbols;
1839 UInt16 SizeOfOptionalHeader;
1840 UInt16 Characteristics;
1844 #define sizeof_COFF_header 20
1851 UInt32 VirtualAddress;
1852 UInt32 SizeOfRawData;
1853 UInt32 PointerToRawData;
1854 UInt32 PointerToRelocations;
1855 UInt32 PointerToLinenumbers;
1856 UInt16 NumberOfRelocations;
1857 UInt16 NumberOfLineNumbers;
1858 UInt32 Characteristics;
1862 #define sizeof_COFF_section 40
1869 UInt16 SectionNumber;
1872 UChar NumberOfAuxSymbols;
1876 #define sizeof_COFF_symbol 18
1881 UInt32 VirtualAddress;
1882 UInt32 SymbolTableIndex;
1887 #define sizeof_COFF_reloc 10
1890 /* From PE spec doc, section 3.3.2 */
1891 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
1892 windows.h -- for the same purpose, but I want to know what I'm
1894 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
1895 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
1896 #define MYIMAGE_FILE_DLL 0x2000
1897 #define MYIMAGE_FILE_SYSTEM 0x1000
1898 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
1899 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
1900 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
1902 /* From PE spec doc, section 5.4.2 and 5.4.4 */
1903 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
1904 #define MYIMAGE_SYM_CLASS_STATIC 3
1905 #define MYIMAGE_SYM_UNDEFINED 0
1907 /* From PE spec doc, section 4.1 */
1908 #define MYIMAGE_SCN_CNT_CODE 0x00000020
1909 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
1910 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
1912 /* From PE spec doc, section 5.2.1 */
1913 #define MYIMAGE_REL_I386_DIR32 0x0006
1914 #define MYIMAGE_REL_I386_REL32 0x0014
1917 /* We use myindex to calculate array addresses, rather than
1918 simply doing the normal subscript thing. That's because
1919 some of the above structs have sizes which are not
1920 a whole number of words. GCC rounds their sizes up to a
1921 whole number of words, which means that the address calcs
1922 arising from using normal C indexing or pointer arithmetic
1923 are just plain wrong. Sigh.
1926 myindex ( int scale, void* base, int index )
1929 ((UChar*)base) + scale * index;
1934 printName ( UChar* name, UChar* strtab )
1936 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1937 UInt32 strtab_offset = * (UInt32*)(name+4);
1938 debugBelch("%s", strtab + strtab_offset );
1941 for (i = 0; i < 8; i++) {
1942 if (name[i] == 0) break;
1943 debugBelch("%c", name[i] );
1950 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
1952 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1953 UInt32 strtab_offset = * (UInt32*)(name+4);
1954 strncpy ( dst, strtab+strtab_offset, dstSize );
1960 if (name[i] == 0) break;
1970 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
1973 /* If the string is longer than 8 bytes, look in the
1974 string table for it -- this will be correctly zero terminated.
1976 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1977 UInt32 strtab_offset = * (UInt32*)(name+4);
1978 return ((UChar*)strtab) + strtab_offset;
1980 /* Otherwise, if shorter than 8 bytes, return the original,
1981 which by defn is correctly terminated.
1983 if (name[7]==0) return name;
1984 /* The annoying case: 8 bytes. Copy into a temporary
1985 (which is never freed ...)
1987 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
1989 strncpy(newstr,name,8);
1995 /* Just compares the short names (first 8 chars) */
1996 static COFF_section *
1997 findPEi386SectionCalled ( ObjectCode* oc, char* name )
2001 = (COFF_header*)(oc->image);
2002 COFF_section* sectab
2004 ((UChar*)(oc->image))
2005 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2007 for (i = 0; i < hdr->NumberOfSections; i++) {
2010 COFF_section* section_i
2012 myindex ( sizeof_COFF_section, sectab, i );
2013 n1 = (UChar*) &(section_i->Name);
2015 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2016 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2017 n1[6]==n2[6] && n1[7]==n2[7])
2026 zapTrailingAtSign ( UChar* sym )
2028 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2030 if (sym[0] == 0) return;
2032 while (sym[i] != 0) i++;
2035 while (j > 0 && my_isdigit(sym[j])) j--;
2036 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2041 lookupSymbolInDLLs ( UChar *lbl )
2046 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2047 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2049 if (lbl[0] == '_') {
2050 /* HACK: if the name has an initial underscore, try stripping
2051 it off & look that up first. I've yet to verify whether there's
2052 a Rule that governs whether an initial '_' *should always* be
2053 stripped off when mapping from import lib name to the DLL name.
2055 sym = GetProcAddress(o_dll->instance, (lbl+1));
2057 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2061 sym = GetProcAddress(o_dll->instance, lbl);
2063 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2072 ocVerifyImage_PEi386 ( ObjectCode* oc )
2077 COFF_section* sectab;
2078 COFF_symbol* symtab;
2080 /* debugBelch("\nLOADING %s\n", oc->fileName); */
2081 hdr = (COFF_header*)(oc->image);
2082 sectab = (COFF_section*) (
2083 ((UChar*)(oc->image))
2084 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2086 symtab = (COFF_symbol*) (
2087 ((UChar*)(oc->image))
2088 + hdr->PointerToSymbolTable
2090 strtab = ((UChar*)symtab)
2091 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2093 if (hdr->Machine != 0x14c) {
2094 errorBelch("%s: Not x86 PEi386", oc->fileName);
2097 if (hdr->SizeOfOptionalHeader != 0) {
2098 errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2101 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2102 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2103 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2104 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2105 errorBelch("%s: Not a PEi386 object file", oc->fileName);
2108 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2109 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2110 errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2112 (int)(hdr->Characteristics));
2115 /* If the string table size is way crazy, this might indicate that
2116 there are more than 64k relocations, despite claims to the
2117 contrary. Hence this test. */
2118 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2120 if ( (*(UInt32*)strtab) > 600000 ) {
2121 /* Note that 600k has no special significance other than being
2122 big enough to handle the almost-2MB-sized lumps that
2123 constitute HSwin32*.o. */
2124 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2129 /* No further verification after this point; only debug printing. */
2131 IF_DEBUG(linker, i=1);
2132 if (i == 0) return 1;
2134 debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2135 debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2136 debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2139 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
2140 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
2141 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2142 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
2143 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
2144 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
2145 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
2147 /* Print the section table. */
2149 for (i = 0; i < hdr->NumberOfSections; i++) {
2151 COFF_section* sectab_i
2153 myindex ( sizeof_COFF_section, sectab, i );
2160 printName ( sectab_i->Name, strtab );
2170 sectab_i->VirtualSize,
2171 sectab_i->VirtualAddress,
2172 sectab_i->SizeOfRawData,
2173 sectab_i->PointerToRawData,
2174 sectab_i->NumberOfRelocations,
2175 sectab_i->PointerToRelocations,
2176 sectab_i->PointerToRawData
2178 reltab = (COFF_reloc*) (
2179 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2182 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2183 /* If the relocation field (a short) has overflowed, the
2184 * real count can be found in the first reloc entry.
2186 * See Section 4.1 (last para) of the PE spec (rev6.0).
2188 COFF_reloc* rel = (COFF_reloc*)
2189 myindex ( sizeof_COFF_reloc, reltab, 0 );
2190 noRelocs = rel->VirtualAddress;
2193 noRelocs = sectab_i->NumberOfRelocations;
2197 for (; j < noRelocs; j++) {
2199 COFF_reloc* rel = (COFF_reloc*)
2200 myindex ( sizeof_COFF_reloc, reltab, j );
2202 " type 0x%-4x vaddr 0x%-8x name `",
2204 rel->VirtualAddress );
2205 sym = (COFF_symbol*)
2206 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
2207 /* Hmm..mysterious looking offset - what's it for? SOF */
2208 printName ( sym->Name, strtab -10 );
2215 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
2216 debugBelch("---START of string table---\n");
2217 for (i = 4; i < *(Int32*)strtab; i++) {
2219 debugBelch("\n"); else
2220 debugBelch("%c", strtab[i] );
2222 debugBelch("--- END of string table---\n");
2227 COFF_symbol* symtab_i;
2228 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2229 symtab_i = (COFF_symbol*)
2230 myindex ( sizeof_COFF_symbol, symtab, i );
2236 printName ( symtab_i->Name, strtab );
2245 (Int32)(symtab_i->SectionNumber),
2246 (UInt32)symtab_i->Type,
2247 (UInt32)symtab_i->StorageClass,
2248 (UInt32)symtab_i->NumberOfAuxSymbols
2250 i += symtab_i->NumberOfAuxSymbols;
2260 ocGetNames_PEi386 ( ObjectCode* oc )
2263 COFF_section* sectab;
2264 COFF_symbol* symtab;
2271 hdr = (COFF_header*)(oc->image);
2272 sectab = (COFF_section*) (
2273 ((UChar*)(oc->image))
2274 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2276 symtab = (COFF_symbol*) (
2277 ((UChar*)(oc->image))
2278 + hdr->PointerToSymbolTable
2280 strtab = ((UChar*)(oc->image))
2281 + hdr->PointerToSymbolTable
2282 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2284 /* Allocate space for any (local, anonymous) .bss sections. */
2286 for (i = 0; i < hdr->NumberOfSections; i++) {
2289 COFF_section* sectab_i
2291 myindex ( sizeof_COFF_section, sectab, i );
2292 if (0 != strcmp(sectab_i->Name, ".bss")) continue;
2293 /* sof 10/05: the PE spec text isn't too clear regarding what
2294 * the SizeOfRawData field is supposed to hold for object
2295 * file sections containing just uninitialized data -- for executables,
2296 * it is supposed to be zero; unclear what it's supposed to be
2297 * for object files. However, VirtualSize is guaranteed to be
2298 * zero for object files, which definitely suggests that SizeOfRawData
2299 * will be non-zero (where else would the size of this .bss section be
2300 * stored?) Looking at the COFF_section info for incoming object files,
2301 * this certainly appears to be the case.
2303 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
2304 * object files up until now. This turned out to bite us with ghc-6.4.1's use
2305 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
2306 * variable decls into to the .bss section. (The specific function in Q which
2307 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
2309 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
2310 /* This is a non-empty .bss section. Allocate zeroed space for
2311 it, and set its PointerToRawData field such that oc->image +
2312 PointerToRawData == addr_of_zeroed_space. */
2313 bss_sz = sectab_i->VirtualSize;
2314 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
2315 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
2316 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
2317 addProddableBlock(oc, zspace, bss_sz);
2318 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
2321 /* Copy section information into the ObjectCode. */
2323 for (i = 0; i < hdr->NumberOfSections; i++) {
2329 = SECTIONKIND_OTHER;
2330 COFF_section* sectab_i
2332 myindex ( sizeof_COFF_section, sectab, i );
2333 IF_DEBUG(linker, debugBelch("section name = %s\n", sectab_i->Name ));
2336 /* I'm sure this is the Right Way to do it. However, the
2337 alternative of testing the sectab_i->Name field seems to
2338 work ok with Cygwin.
2340 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
2341 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
2342 kind = SECTIONKIND_CODE_OR_RODATA;
2345 if (0==strcmp(".text",sectab_i->Name) ||
2346 0==strcmp(".rdata",sectab_i->Name)||
2347 0==strcmp(".rodata",sectab_i->Name))
2348 kind = SECTIONKIND_CODE_OR_RODATA;
2349 if (0==strcmp(".data",sectab_i->Name) ||
2350 0==strcmp(".bss",sectab_i->Name))
2351 kind = SECTIONKIND_RWDATA;
2353 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
2354 sz = sectab_i->SizeOfRawData;
2355 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
2357 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
2358 end = start + sz - 1;
2360 if (kind == SECTIONKIND_OTHER
2361 /* Ignore sections called which contain stabs debugging
2363 && 0 != strcmp(".stab", sectab_i->Name)
2364 && 0 != strcmp(".stabstr", sectab_i->Name)
2365 /* ignore constructor section for now */
2366 && 0 != strcmp(".ctors", sectab_i->Name)
2367 /* ignore section generated from .ident */
2368 && 0!= strcmp("/4", sectab_i->Name)
2369 /* ignore unknown section that appeared in gcc 3.4.5(?) */
2370 && 0!= strcmp(".reloc", sectab_i->Name)
2372 errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", sectab_i->Name, oc->fileName);
2376 if (kind != SECTIONKIND_OTHER && end >= start) {
2377 addSection(oc, kind, start, end);
2378 addProddableBlock(oc, start, end - start + 1);
2382 /* Copy exported symbols into the ObjectCode. */
2384 oc->n_symbols = hdr->NumberOfSymbols;
2385 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2386 "ocGetNames_PEi386(oc->symbols)");
2387 /* Call me paranoid; I don't care. */
2388 for (i = 0; i < oc->n_symbols; i++)
2389 oc->symbols[i] = NULL;
2393 COFF_symbol* symtab_i;
2394 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2395 symtab_i = (COFF_symbol*)
2396 myindex ( sizeof_COFF_symbol, symtab, i );
2400 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
2401 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
2402 /* This symbol is global and defined, viz, exported */
2403 /* for MYIMAGE_SYMCLASS_EXTERNAL
2404 && !MYIMAGE_SYM_UNDEFINED,
2405 the address of the symbol is:
2406 address of relevant section + offset in section
2408 COFF_section* sectabent
2409 = (COFF_section*) myindex ( sizeof_COFF_section,
2411 symtab_i->SectionNumber-1 );
2412 addr = ((UChar*)(oc->image))
2413 + (sectabent->PointerToRawData
2417 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
2418 && symtab_i->Value > 0) {
2419 /* This symbol isn't in any section at all, ie, global bss.
2420 Allocate zeroed space for it. */
2421 addr = stgCallocBytes(1, symtab_i->Value,
2422 "ocGetNames_PEi386(non-anonymous bss)");
2423 addSection(oc, SECTIONKIND_RWDATA, addr,
2424 ((UChar*)addr) + symtab_i->Value - 1);
2425 addProddableBlock(oc, addr, symtab_i->Value);
2426 /* debugBelch("BSS section at 0x%x\n", addr); */
2429 if (addr != NULL ) {
2430 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
2431 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
2432 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
2433 ASSERT(i >= 0 && i < oc->n_symbols);
2434 /* cstring_from_COFF_symbol_name always succeeds. */
2435 oc->symbols[i] = sname;
2436 ghciInsertStrHashTable(oc->fileName, symhash, sname, addr);
2440 "IGNORING symbol %d\n"
2444 printName ( symtab_i->Name, strtab );
2453 (Int32)(symtab_i->SectionNumber),
2454 (UInt32)symtab_i->Type,
2455 (UInt32)symtab_i->StorageClass,
2456 (UInt32)symtab_i->NumberOfAuxSymbols
2461 i += symtab_i->NumberOfAuxSymbols;
2470 ocResolve_PEi386 ( ObjectCode* oc )
2473 COFF_section* sectab;
2474 COFF_symbol* symtab;
2484 /* ToDo: should be variable-sized? But is at least safe in the
2485 sense of buffer-overrun-proof. */
2487 /* debugBelch("resolving for %s\n", oc->fileName); */
2489 hdr = (COFF_header*)(oc->image);
2490 sectab = (COFF_section*) (
2491 ((UChar*)(oc->image))
2492 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2494 symtab = (COFF_symbol*) (
2495 ((UChar*)(oc->image))
2496 + hdr->PointerToSymbolTable
2498 strtab = ((UChar*)(oc->image))
2499 + hdr->PointerToSymbolTable
2500 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2502 for (i = 0; i < hdr->NumberOfSections; i++) {
2503 COFF_section* sectab_i
2505 myindex ( sizeof_COFF_section, sectab, i );
2508 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2511 /* Ignore sections called which contain stabs debugging
2513 if (0 == strcmp(".stab", sectab_i->Name)
2514 || 0 == strcmp(".stabstr", sectab_i->Name)
2515 || 0 == strcmp(".ctors", sectab_i->Name))
2518 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2519 /* If the relocation field (a short) has overflowed, the
2520 * real count can be found in the first reloc entry.
2522 * See Section 4.1 (last para) of the PE spec (rev6.0).
2524 * Nov2003 update: the GNU linker still doesn't correctly
2525 * handle the generation of relocatable object files with
2526 * overflown relocations. Hence the output to warn of potential
2529 COFF_reloc* rel = (COFF_reloc*)
2530 myindex ( sizeof_COFF_reloc, reltab, 0 );
2531 noRelocs = rel->VirtualAddress;
2533 /* 10/05: we now assume (and check for) a GNU ld that is capable
2534 * of handling object files with (>2^16) of relocs.
2537 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
2542 noRelocs = sectab_i->NumberOfRelocations;
2547 for (; j < noRelocs; j++) {
2549 COFF_reloc* reltab_j
2551 myindex ( sizeof_COFF_reloc, reltab, j );
2553 /* the location to patch */
2555 ((UChar*)(oc->image))
2556 + (sectab_i->PointerToRawData
2557 + reltab_j->VirtualAddress
2558 - sectab_i->VirtualAddress )
2560 /* the existing contents of pP */
2562 /* the symbol to connect to */
2563 sym = (COFF_symbol*)
2564 myindex ( sizeof_COFF_symbol,
2565 symtab, reltab_j->SymbolTableIndex );
2568 "reloc sec %2d num %3d: type 0x%-4x "
2569 "vaddr 0x%-8x name `",
2571 (UInt32)reltab_j->Type,
2572 reltab_j->VirtualAddress );
2573 printName ( sym->Name, strtab );
2574 debugBelch("'\n" ));
2576 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
2577 COFF_section* section_sym
2578 = findPEi386SectionCalled ( oc, sym->Name );
2580 errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
2583 S = ((UInt32)(oc->image))
2584 + (section_sym->PointerToRawData
2587 copyName ( sym->Name, strtab, symbol, 1000-1 );
2588 S = (UInt32) lookupSymbol( symbol );
2589 if ((void*)S != NULL) goto foundit;
2590 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
2594 checkProddableBlock(oc, pP);
2595 switch (reltab_j->Type) {
2596 case MYIMAGE_REL_I386_DIR32:
2599 case MYIMAGE_REL_I386_REL32:
2600 /* Tricky. We have to insert a displacement at
2601 pP which, when added to the PC for the _next_
2602 insn, gives the address of the target (S).
2603 Problem is to know the address of the next insn
2604 when we only know pP. We assume that this
2605 literal field is always the last in the insn,
2606 so that the address of the next insn is pP+4
2607 -- hence the constant 4.
2608 Also I don't know if A should be added, but so
2609 far it has always been zero.
2611 SOF 05/2005: 'A' (old contents of *pP) have been observed
2612 to contain values other than zero (the 'wx' object file
2613 that came with wxhaskell-0.9.4; dunno how it was compiled..).
2614 So, add displacement to old value instead of asserting
2615 A to be zero. Fixes wxhaskell-related crashes, and no other
2616 ill effects have been observed.
2618 Update: the reason why we're seeing these more elaborate
2619 relocations is due to a switch in how the NCG compiles SRTs
2620 and offsets to them from info tables. SRTs live in .(ro)data,
2621 while info tables live in .text, causing GAS to emit REL32/DISP32
2622 relocations with non-zero values. Adding the displacement is
2623 the right thing to do.
2625 *pP = S - ((UInt32)pP) - 4 + A;
2628 debugBelch("%s: unhandled PEi386 relocation type %d",
2629 oc->fileName, reltab_j->Type);
2636 IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
2640 #endif /* defined(OBJFORMAT_PEi386) */
2643 /* --------------------------------------------------------------------------
2645 * ------------------------------------------------------------------------*/
2647 #if defined(OBJFORMAT_ELF)
2652 #if defined(sparc_HOST_ARCH)
2653 # define ELF_TARGET_SPARC /* Used inside <elf.h> */
2654 #elif defined(i386_HOST_ARCH)
2655 # define ELF_TARGET_386 /* Used inside <elf.h> */
2656 #elif defined(x86_64_HOST_ARCH)
2657 # define ELF_TARGET_X64_64
2661 #if !defined(openbsd_HOST_OS)
2664 /* openbsd elf has things in different places, with diff names */
2665 # include <elf_abi.h>
2666 # include <machine/reloc.h>
2667 # define R_386_32 RELOC_32
2668 # define R_386_PC32 RELOC_PC32
2671 /* If elf.h doesn't define it */
2672 # ifndef R_X86_64_PC64
2673 # define R_X86_64_PC64 24
2677 * Define a set of types which can be used for both ELF32 and ELF64
2681 #define ELFCLASS ELFCLASS64
2682 #define Elf_Addr Elf64_Addr
2683 #define Elf_Word Elf64_Word
2684 #define Elf_Sword Elf64_Sword
2685 #define Elf_Ehdr Elf64_Ehdr
2686 #define Elf_Phdr Elf64_Phdr
2687 #define Elf_Shdr Elf64_Shdr
2688 #define Elf_Sym Elf64_Sym
2689 #define Elf_Rel Elf64_Rel
2690 #define Elf_Rela Elf64_Rela
2691 #define ELF_ST_TYPE ELF64_ST_TYPE
2692 #define ELF_ST_BIND ELF64_ST_BIND
2693 #define ELF_R_TYPE ELF64_R_TYPE
2694 #define ELF_R_SYM ELF64_R_SYM
2696 #define ELFCLASS ELFCLASS32
2697 #define Elf_Addr Elf32_Addr
2698 #define Elf_Word Elf32_Word
2699 #define Elf_Sword Elf32_Sword
2700 #define Elf_Ehdr Elf32_Ehdr
2701 #define Elf_Phdr Elf32_Phdr
2702 #define Elf_Shdr Elf32_Shdr
2703 #define Elf_Sym Elf32_Sym
2704 #define Elf_Rel Elf32_Rel
2705 #define Elf_Rela Elf32_Rela
2707 #define ELF_ST_TYPE ELF32_ST_TYPE
2710 #define ELF_ST_BIND ELF32_ST_BIND
2713 #define ELF_R_TYPE ELF32_R_TYPE
2716 #define ELF_R_SYM ELF32_R_SYM
2722 * Functions to allocate entries in dynamic sections. Currently we simply
2723 * preallocate a large number, and we don't check if a entry for the given
2724 * target already exists (a linear search is too slow). Ideally these
2725 * entries would be associated with symbols.
2728 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
2729 #define GOT_SIZE 0x20000
2730 #define FUNCTION_TABLE_SIZE 0x10000
2731 #define PLT_SIZE 0x08000
2734 static Elf_Addr got[GOT_SIZE];
2735 static unsigned int gotIndex;
2736 static Elf_Addr gp_val = (Elf_Addr)got;
2739 allocateGOTEntry(Elf_Addr target)
2743 if (gotIndex >= GOT_SIZE)
2744 barf("Global offset table overflow");
2746 entry = &got[gotIndex++];
2748 return (Elf_Addr)entry;
2752 #ifdef ELF_FUNCTION_DESC
2758 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
2759 static unsigned int functionTableIndex;
2762 allocateFunctionDesc(Elf_Addr target)
2764 FunctionDesc *entry;
2766 if (functionTableIndex >= FUNCTION_TABLE_SIZE)
2767 barf("Function table overflow");
2769 entry = &functionTable[functionTableIndex++];
2771 entry->gp = (Elf_Addr)gp_val;
2772 return (Elf_Addr)entry;
2776 copyFunctionDesc(Elf_Addr target)
2778 FunctionDesc *olddesc = (FunctionDesc *)target;
2779 FunctionDesc *newdesc;
2781 newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
2782 newdesc->gp = olddesc->gp;
2783 return (Elf_Addr)newdesc;
2790 unsigned char code[sizeof(plt_code)];
2794 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
2796 PLTEntry *plt = (PLTEntry *)oc->plt;
2799 if (oc->pltIndex >= PLT_SIZE)
2800 barf("Procedure table overflow");
2802 entry = &plt[oc->pltIndex++];
2803 memcpy(entry->code, plt_code, sizeof(entry->code));
2804 PLT_RELOC(entry->code, target);
2805 return (Elf_Addr)entry;
2811 return (PLT_SIZE * sizeof(PLTEntry));
2817 * Generic ELF functions
2821 findElfSection ( void* objImage, Elf_Word sh_type )
2823 char* ehdrC = (char*)objImage;
2824 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2825 Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
2826 char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2830 for (i = 0; i < ehdr->e_shnum; i++) {
2831 if (shdr[i].sh_type == sh_type
2832 /* Ignore the section header's string table. */
2833 && i != ehdr->e_shstrndx
2834 /* Ignore string tables named .stabstr, as they contain
2836 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2838 ptr = ehdrC + shdr[i].sh_offset;
2846 ocVerifyImage_ELF ( ObjectCode* oc )
2850 int i, j, nent, nstrtab, nsymtabs;
2854 char* ehdrC = (char*)(oc->image);
2855 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2857 if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
2858 ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
2859 ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
2860 ehdr->e_ident[EI_MAG3] != ELFMAG3) {
2861 errorBelch("%s: not an ELF object", oc->fileName);
2865 if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
2866 errorBelch("%s: unsupported ELF format", oc->fileName);
2870 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
2871 IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
2873 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
2874 IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
2876 errorBelch("%s: unknown endiannness", oc->fileName);
2880 if (ehdr->e_type != ET_REL) {
2881 errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
2884 IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
2886 IF_DEBUG(linker,debugBelch( "Architecture is " ));
2887 switch (ehdr->e_machine) {
2888 case EM_386: IF_DEBUG(linker,debugBelch( "x86" )); break;
2889 #ifdef EM_SPARC32PLUS
2890 case EM_SPARC32PLUS:
2892 case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
2894 case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
2896 case EM_PPC: IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
2898 case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
2899 #elif defined(EM_AMD64)
2900 case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
2902 default: IF_DEBUG(linker,debugBelch( "unknown" ));
2903 errorBelch("%s: unknown architecture (e_machine == %d)"
2904 , oc->fileName, ehdr->e_machine);
2908 IF_DEBUG(linker,debugBelch(
2909 "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
2910 (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize ));
2912 ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
2914 shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2916 if (ehdr->e_shstrndx == SHN_UNDEF) {
2917 errorBelch("%s: no section header string table", oc->fileName);
2920 IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
2922 sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2925 for (i = 0; i < ehdr->e_shnum; i++) {
2926 IF_DEBUG(linker,debugBelch("%2d: ", i ));
2927 IF_DEBUG(linker,debugBelch("type=%2d ", (int)shdr[i].sh_type ));
2928 IF_DEBUG(linker,debugBelch("size=%4d ", (int)shdr[i].sh_size ));
2929 IF_DEBUG(linker,debugBelch("offs=%4d ", (int)shdr[i].sh_offset ));
2930 IF_DEBUG(linker,debugBelch(" (%p .. %p) ",
2931 ehdrC + shdr[i].sh_offset,
2932 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
2934 if (shdr[i].sh_type == SHT_REL) {
2935 IF_DEBUG(linker,debugBelch("Rel " ));
2936 } else if (shdr[i].sh_type == SHT_RELA) {
2937 IF_DEBUG(linker,debugBelch("RelA " ));
2939 IF_DEBUG(linker,debugBelch(" "));
2942 IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
2946 IF_DEBUG(linker,debugBelch( "\nString tables" ));
2949 for (i = 0; i < ehdr->e_shnum; i++) {
2950 if (shdr[i].sh_type == SHT_STRTAB
2951 /* Ignore the section header's string table. */
2952 && i != ehdr->e_shstrndx
2953 /* Ignore string tables named .stabstr, as they contain
2955 && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2957 IF_DEBUG(linker,debugBelch(" section %d is a normal string table", i ));
2958 strtab = ehdrC + shdr[i].sh_offset;
2963 errorBelch("%s: no string tables, or too many", oc->fileName);
2968 IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
2969 for (i = 0; i < ehdr->e_shnum; i++) {
2970 if (shdr[i].sh_type != SHT_SYMTAB) continue;
2971 IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
2973 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2974 nent = shdr[i].sh_size / sizeof(Elf_Sym);
2975 IF_DEBUG(linker,debugBelch( " number of entries is apparently %d (%ld rem)\n",
2977 (long)shdr[i].sh_size % sizeof(Elf_Sym)
2979 if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
2980 errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
2983 for (j = 0; j < nent; j++) {
2984 IF_DEBUG(linker,debugBelch(" %2d ", j ));
2985 IF_DEBUG(linker,debugBelch(" sec=%-5d size=%-3d val=%5p ",
2986 (int)stab[j].st_shndx,
2987 (int)stab[j].st_size,
2988 (char*)stab[j].st_value ));
2990 IF_DEBUG(linker,debugBelch("type=" ));
2991 switch (ELF_ST_TYPE(stab[j].st_info)) {
2992 case STT_NOTYPE: IF_DEBUG(linker,debugBelch("notype " )); break;
2993 case STT_OBJECT: IF_DEBUG(linker,debugBelch("object " )); break;
2994 case STT_FUNC : IF_DEBUG(linker,debugBelch("func " )); break;
2995 case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
2996 case STT_FILE: IF_DEBUG(linker,debugBelch("file " )); break;
2997 default: IF_DEBUG(linker,debugBelch("? " )); break;
2999 IF_DEBUG(linker,debugBelch(" " ));
3001 IF_DEBUG(linker,debugBelch("bind=" ));
3002 switch (ELF_ST_BIND(stab[j].st_info)) {
3003 case STB_LOCAL : IF_DEBUG(linker,debugBelch("local " )); break;
3004 case STB_GLOBAL: IF_DEBUG(linker,debugBelch("global" )); break;
3005 case STB_WEAK : IF_DEBUG(linker,debugBelch("weak " )); break;
3006 default: IF_DEBUG(linker,debugBelch("? " )); break;
3008 IF_DEBUG(linker,debugBelch(" " ));
3010 IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3014 if (nsymtabs == 0) {
3015 errorBelch("%s: didn't find any symbol tables", oc->fileName);
3022 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3026 if (hdr->sh_type == SHT_PROGBITS
3027 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3028 /* .text-style section */
3029 return SECTIONKIND_CODE_OR_RODATA;
3032 if (hdr->sh_type == SHT_PROGBITS
3033 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3034 /* .data-style section */
3035 return SECTIONKIND_RWDATA;
3038 if (hdr->sh_type == SHT_PROGBITS
3039 && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3040 /* .rodata-style section */
3041 return SECTIONKIND_CODE_OR_RODATA;
3044 if (hdr->sh_type == SHT_NOBITS
3045 && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3046 /* .bss-style section */
3048 return SECTIONKIND_RWDATA;
3051 return SECTIONKIND_OTHER;
3056 ocGetNames_ELF ( ObjectCode* oc )
3061 char* ehdrC = (char*)(oc->image);
3062 Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3063 char* strtab = findElfSection ( ehdrC, SHT_STRTAB );
3064 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3066 ASSERT(symhash != NULL);
3069 errorBelch("%s: no strtab", oc->fileName);
3074 for (i = 0; i < ehdr->e_shnum; i++) {
3075 /* Figure out what kind of section it is. Logic derived from
3076 Figure 1.14 ("Special Sections") of the ELF document
3077 ("Portable Formats Specification, Version 1.1"). */
3079 SectionKind kind = getSectionKind_ELF(&shdr[i], &is_bss);
3081 if (is_bss && shdr[i].sh_size > 0) {
3082 /* This is a non-empty .bss section. Allocate zeroed space for
3083 it, and set its .sh_offset field such that
3084 ehdrC + .sh_offset == addr_of_zeroed_space. */
3085 char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3086 "ocGetNames_ELF(BSS)");
3087 shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3089 debugBelch("BSS section at 0x%x, size %d\n",
3090 zspace, shdr[i].sh_size);
3094 /* fill in the section info */
3095 if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3096 addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3097 addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3098 ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3101 if (shdr[i].sh_type != SHT_SYMTAB) continue;
3103 /* copy stuff into this module's object symbol table */
3104 stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3105 nent = shdr[i].sh_size / sizeof(Elf_Sym);
3107 oc->n_symbols = nent;
3108 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3109 "ocGetNames_ELF(oc->symbols)");
3111 for (j = 0; j < nent; j++) {
3113 char isLocal = FALSE; /* avoids uninit-var warning */
3115 char* nm = strtab + stab[j].st_name;
3116 int secno = stab[j].st_shndx;
3118 /* Figure out if we want to add it; if so, set ad to its
3119 address. Otherwise leave ad == NULL. */
3121 if (secno == SHN_COMMON) {
3123 ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3125 debugBelch("COMMON symbol, size %d name %s\n",
3126 stab[j].st_size, nm);
3128 /* Pointless to do addProddableBlock() for this area,
3129 since the linker should never poke around in it. */
3132 if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3133 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3135 /* and not an undefined symbol */
3136 && stab[j].st_shndx != SHN_UNDEF
3137 /* and not in a "special section" */
3138 && stab[j].st_shndx < SHN_LORESERVE
3140 /* and it's a not a section or string table or anything silly */
3141 ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
3142 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
3143 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
3146 /* Section 0 is the undefined section, hence > and not >=. */
3147 ASSERT(secno > 0 && secno < ehdr->e_shnum);
3149 if (shdr[secno].sh_type == SHT_NOBITS) {
3150 debugBelch(" BSS symbol, size %d off %d name %s\n",
3151 stab[j].st_size, stab[j].st_value, nm);
3154 ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
3155 if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
3158 #ifdef ELF_FUNCTION_DESC
3159 /* dlsym() and the initialisation table both give us function
3160 * descriptors, so to be consistent we store function descriptors
3161 * in the symbol table */
3162 if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
3163 ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
3165 IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p %s %s\n",
3166 ad, oc->fileName, nm ));
3171 /* And the decision is ... */
3175 oc->symbols[j] = nm;
3178 /* Ignore entirely. */
3180 ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
3184 IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
3185 strtab + stab[j].st_name ));
3188 "skipping bind = %d, type = %d, shndx = %d `%s'\n",
3189 (int)ELF_ST_BIND(stab[j].st_info),
3190 (int)ELF_ST_TYPE(stab[j].st_info),
3191 (int)stab[j].st_shndx,
3192 strtab + stab[j].st_name
3195 oc->symbols[j] = NULL;
3204 /* Do ELF relocations which lack an explicit addend. All x86-linux
3205 relocations appear to be of this form. */
3207 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
3208 Elf_Shdr* shdr, int shnum,
3209 Elf_Sym* stab, char* strtab )
3214 Elf_Rel* rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
3215 int nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
3216 int target_shndx = shdr[shnum].sh_info;
3217 int symtab_shndx = shdr[shnum].sh_link;
3219 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3220 targ = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
3221 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3222 target_shndx, symtab_shndx ));
3224 /* Skip sections that we're not interested in. */
3227 SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
3228 if (kind == SECTIONKIND_OTHER) {
3229 IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
3234 for (j = 0; j < nent; j++) {
3235 Elf_Addr offset = rtab[j].r_offset;
3236 Elf_Addr info = rtab[j].r_info;
3238 Elf_Addr P = ((Elf_Addr)targ) + offset;
3239 Elf_Word* pP = (Elf_Word*)P;
3244 StgStablePtr stablePtr;
3247 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
3248 j, (void*)offset, (void*)info ));
3250 IF_DEBUG(linker,debugBelch( " ZERO" ));
3253 Elf_Sym sym = stab[ELF_R_SYM(info)];
3254 /* First see if it is a local symbol. */
3255 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3256 /* Yes, so we can get the address directly from the ELF symbol
3258 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3260 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3261 + stab[ELF_R_SYM(info)].st_value);
3264 symbol = strtab + sym.st_name;
3265 stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
3266 if (NULL == stablePtr) {
3267 /* No, so look up the name in our global table. */
3268 S_tmp = lookupSymbol( symbol );
3269 S = (Elf_Addr)S_tmp;
3271 stableVal = deRefStablePtr( stablePtr );
3273 S = (Elf_Addr)S_tmp;
3277 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3280 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
3283 IF_DEBUG(linker,debugBelch( "Reloc: P = %p S = %p A = %p\n",
3284 (void*)P, (void*)S, (void*)A ));
3285 checkProddableBlock ( oc, pP );
3289 switch (ELF_R_TYPE(info)) {
3290 # ifdef i386_HOST_ARCH
3291 case R_386_32: *pP = value; break;
3292 case R_386_PC32: *pP = value - P; break;
3295 errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
3296 oc->fileName, (lnat)ELF_R_TYPE(info));
3304 /* Do ELF relocations for which explicit addends are supplied.
3305 sparc-solaris relocations appear to be of this form. */
3307 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
3308 Elf_Shdr* shdr, int shnum,
3309 Elf_Sym* stab, char* strtab )
3312 char *symbol = NULL;
3314 Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
3315 int nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
3316 int target_shndx = shdr[shnum].sh_info;
3317 int symtab_shndx = shdr[shnum].sh_link;
3319 stab = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3320 targ = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
3321 IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3322 target_shndx, symtab_shndx ));
3324 for (j = 0; j < nent; j++) {
3325 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3326 /* This #ifdef only serves to avoid unused-var warnings. */
3327 Elf_Addr offset = rtab[j].r_offset;
3328 Elf_Addr P = targ + offset;
3330 Elf_Addr info = rtab[j].r_info;
3331 Elf_Addr A = rtab[j].r_addend;
3335 # if defined(sparc_HOST_ARCH)
3336 Elf_Word* pP = (Elf_Word*)P;
3338 # elif defined(powerpc_HOST_ARCH)
3342 IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p) ",
3343 j, (void*)offset, (void*)info,
3346 IF_DEBUG(linker,debugBelch( " ZERO" ));
3349 Elf_Sym sym = stab[ELF_R_SYM(info)];
3350 /* First see if it is a local symbol. */
3351 if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3352 /* Yes, so we can get the address directly from the ELF symbol
3354 symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3356 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3357 + stab[ELF_R_SYM(info)].st_value);
3358 #ifdef ELF_FUNCTION_DESC
3359 /* Make a function descriptor for this function */
3360 if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
3361 S = allocateFunctionDesc(S + A);
3366 /* No, so look up the name in our global table. */
3367 symbol = strtab + sym.st_name;
3368 S_tmp = lookupSymbol( symbol );
3369 S = (Elf_Addr)S_tmp;
3371 #ifdef ELF_FUNCTION_DESC
3372 /* If a function, already a function descriptor - we would
3373 have to copy it to add an offset. */
3374 if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
3375 errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
3379 errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3382 IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
3385 IF_DEBUG(linker,debugBelch("Reloc: P = %p S = %p A = %p\n",
3386 (void*)P, (void*)S, (void*)A ));
3387 /* checkProddableBlock ( oc, (void*)P ); */
3391 switch (ELF_R_TYPE(info)) {
3392 # if defined(sparc_HOST_ARCH)
3393 case R_SPARC_WDISP30:
3394 w1 = *pP & 0xC0000000;
3395 w2 = (Elf_Word)((value - P) >> 2);
3396 ASSERT((w2 & 0xC0000000) == 0);
3401 w1 = *pP & 0xFFC00000;
3402 w2 = (Elf_Word)(value >> 10);
3403 ASSERT((w2 & 0xFFC00000) == 0);
3409 w2 = (Elf_Word)(value & 0x3FF);
3410 ASSERT((w2 & ~0x3FF) == 0);
3415 /* According to the Sun documentation:
3417 This relocation type resembles R_SPARC_32, except it refers to an
3418 unaligned word. That is, the word to be relocated must be treated
3419 as four separate bytes with arbitrary alignment, not as a word
3420 aligned according to the architecture requirements.
3423 w2 = (Elf_Word)value;
3425 // SPARC doesn't do misaligned writes of 32 bit words,
3426 // so we have to do this one byte-at-a-time.
3427 char *pPc = (char*)pP;
3428 pPc[0] = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
3429 pPc[1] = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
3430 pPc[2] = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
3431 pPc[3] = (char) ((Elf_Word)(w2 & 0x000000ff));
3435 w2 = (Elf_Word)value;
3438 # elif defined(powerpc_HOST_ARCH)
3439 case R_PPC_ADDR16_LO:
3440 *(Elf32_Half*) P = value;
3443 case R_PPC_ADDR16_HI:
3444 *(Elf32_Half*) P = value >> 16;
3447 case R_PPC_ADDR16_HA:
3448 *(Elf32_Half*) P = (value + 0x8000) >> 16;
3452 *(Elf32_Word *) P = value;
3456 *(Elf32_Word *) P = value - P;
3462 if( delta << 6 >> 6 != delta )
3464 value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
3468 if( value == 0 || delta << 6 >> 6 != delta )
3470 barf( "Unable to make SymbolExtra for #%d",
3476 *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
3477 | (delta & 0x3fffffc);
3481 #if x86_64_HOST_ARCH
3483 *(Elf64_Xword *)P = value;
3488 StgInt64 off = value - P;
3489 if (off >= 0x7fffffffL || off < -0x80000000L) {
3490 #if X86_64_ELF_NONPIC_HACK
3491 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3493 off = pltAddress + A - P;
3495 barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3496 symbol, off, oc->fileName );
3499 *(Elf64_Word *)P = (Elf64_Word)off;
3505 StgInt64 off = value - P;
3506 *(Elf64_Word *)P = (Elf64_Word)off;
3511 if (value >= 0x7fffffffL) {
3512 #if X86_64_ELF_NONPIC_HACK
3513 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3515 value = pltAddress + A;
3517 barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3518 symbol, value, oc->fileName );
3521 *(Elf64_Word *)P = (Elf64_Word)value;
3525 if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
3526 #if X86_64_ELF_NONPIC_HACK
3527 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3529 value = pltAddress + A;
3531 barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
3532 symbol, value, oc->fileName );
3535 *(Elf64_Sword *)P = (Elf64_Sword)value;
3538 case R_X86_64_GOTPCREL:
3540 StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
3541 StgInt64 off = gotAddress + A - P;
3542 *(Elf64_Word *)P = (Elf64_Word)off;
3546 case R_X86_64_PLT32:
3548 StgInt64 off = value - P;
3549 if (off >= 0x7fffffffL || off < -0x80000000L) {
3550 StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
3552 off = pltAddress + A - P;
3554 *(Elf64_Word *)P = (Elf64_Word)off;
3560 errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
3561 oc->fileName, (lnat)ELF_R_TYPE(info));
3570 ocResolve_ELF ( ObjectCode* oc )
3574 Elf_Sym* stab = NULL;
3575 char* ehdrC = (char*)(oc->image);
3576 Elf_Ehdr* ehdr = (Elf_Ehdr*) ehdrC;
3577 Elf_Shdr* shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3579 /* first find "the" symbol table */
3580 stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
3582 /* also go find the string table */
3583 strtab = findElfSection ( ehdrC, SHT_STRTAB );
3585 if (stab == NULL || strtab == NULL) {
3586 errorBelch("%s: can't find string or symbol table", oc->fileName);
3590 /* Process the relocation sections. */
3591 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
3592 if (shdr[shnum].sh_type == SHT_REL) {
3593 ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
3594 shnum, stab, strtab );
3598 if (shdr[shnum].sh_type == SHT_RELA) {
3599 ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
3600 shnum, stab, strtab );
3605 #if defined(powerpc_HOST_ARCH)
3606 ocFlushInstructionCache( oc );
3613 * PowerPC & X86_64 ELF specifics
3616 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3618 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
3624 ehdr = (Elf_Ehdr *) oc->image;
3625 shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
3627 for( i = 0; i < ehdr->e_shnum; i++ )
3628 if( shdr[i].sh_type == SHT_SYMTAB )
3631 if( i == ehdr->e_shnum )
3633 errorBelch( "This ELF file contains no symtab" );
3637 if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
3639 errorBelch( "The entry size (%d) of the symtab isn't %d\n",
3640 (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
3645 return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
3648 #endif /* powerpc */
3652 /* --------------------------------------------------------------------------
3654 * ------------------------------------------------------------------------*/
3656 #if defined(OBJFORMAT_MACHO)
3659 Support for MachO linking on Darwin/MacOS X
3660 by Wolfgang Thaller (wolfgang.thaller@gmx.net)
3662 I hereby formally apologize for the hackish nature of this code.
3663 Things that need to be done:
3664 *) implement ocVerifyImage_MachO
3665 *) add still more sanity checks.
3668 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
3669 #define mach_header mach_header_64
3670 #define segment_command segment_command_64
3671 #define section section_64
3672 #define nlist nlist_64
3675 #ifdef powerpc_HOST_ARCH
3676 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
3678 struct mach_header *header = (struct mach_header *) oc->image;
3679 struct load_command *lc = (struct load_command *) (header + 1);
3682 for( i = 0; i < header->ncmds; i++ )
3684 if( lc->cmd == LC_SYMTAB )
3686 // Find out the first and last undefined external
3687 // symbol, so we don't have to allocate too many
3689 struct symtab_command *symLC = (struct symtab_command *) lc;
3690 unsigned min = symLC->nsyms, max = 0;
3691 struct nlist *nlist =
3692 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
3694 for(i=0;i<symLC->nsyms;i++)
3696 if(nlist[i].n_type & N_STAB)
3698 else if(nlist[i].n_type & N_EXT)
3700 if((nlist[i].n_type & N_TYPE) == N_UNDF
3701 && (nlist[i].n_value == 0))
3711 return ocAllocateSymbolExtras(oc, max - min + 1, min);
3716 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3718 return ocAllocateSymbolExtras(oc,0,0);
3721 #ifdef x86_64_HOST_ARCH
3722 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
3724 struct mach_header *header = (struct mach_header *) oc->image;
3725 struct load_command *lc = (struct load_command *) (header + 1);
3728 for( i = 0; i < header->ncmds; i++ )
3730 if( lc->cmd == LC_SYMTAB )
3732 // Just allocate one entry for every symbol
3733 struct symtab_command *symLC = (struct symtab_command *) lc;
3735 return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
3738 lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3740 return ocAllocateSymbolExtras(oc,0,0);
3744 static int ocVerifyImage_MachO(ObjectCode* oc)
3746 char *image = (char*) oc->image;
3747 struct mach_header *header = (struct mach_header*) image;
3749 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
3750 if(header->magic != MH_MAGIC_64)
3753 if(header->magic != MH_MAGIC)
3756 // FIXME: do some more verifying here
3760 static int resolveImports(
3763 struct symtab_command *symLC,
3764 struct section *sect, // ptr to lazy or non-lazy symbol pointer section
3765 unsigned long *indirectSyms,
3766 struct nlist *nlist)
3769 size_t itemSize = 4;
3772 int isJumpTable = 0;
3773 if(!strcmp(sect->sectname,"__jump_table"))
3777 ASSERT(sect->reserved2 == itemSize);
3781 for(i=0; i*itemSize < sect->size;i++)
3783 // according to otool, reserved1 contains the first index into the indirect symbol table
3784 struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
3785 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3788 if((symbol->n_type & N_TYPE) == N_UNDF
3789 && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
3790 addr = (void*) (symbol->n_value);
3792 addr = lookupSymbol(nm);
3795 errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
3803 checkProddableBlock(oc,image + sect->offset + i*itemSize);
3804 *(image + sect->offset + i*itemSize) = 0xe9; // jmp
3805 *(unsigned*)(image + sect->offset + i*itemSize + 1)
3806 = (char*)addr - (image + sect->offset + i*itemSize + 5);
3811 checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
3812 ((void**)(image + sect->offset))[i] = addr;
3819 static unsigned long relocateAddress(
3822 struct section* sections,
3823 unsigned long address)
3826 for(i = 0; i < nSections; i++)
3828 if(sections[i].addr <= address
3829 && address < sections[i].addr + sections[i].size)
3831 return (unsigned long)oc->image
3832 + sections[i].offset + address - sections[i].addr;
3835 barf("Invalid Mach-O file:"
3836 "Address out of bounds while relocating object file");
3840 static int relocateSection(
3843 struct symtab_command *symLC, struct nlist *nlist,
3844 int nSections, struct section* sections, struct section *sect)
3846 struct relocation_info *relocs;
3849 if(!strcmp(sect->sectname,"__la_symbol_ptr"))
3851 else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
3853 else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
3855 else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
3859 relocs = (struct relocation_info*) (image + sect->reloff);
3863 #ifdef x86_64_HOST_ARCH
3864 struct relocation_info *reloc = &relocs[i];
3866 char *thingPtr = image + sect->offset + reloc->r_address;
3868 /* We shouldn't need to initialise this, but gcc on OS X 64 bit
3869 complains that it may be used uninitialized if we don't */
3872 int type = reloc->r_type;
3874 checkProddableBlock(oc,thingPtr);
3875 switch(reloc->r_length)
3878 thing = *(uint8_t*)thingPtr;
3879 baseValue = (uint64_t)thingPtr + 1;
3882 thing = *(uint16_t*)thingPtr;
3883 baseValue = (uint64_t)thingPtr + 2;
3886 thing = *(uint32_t*)thingPtr;
3887 baseValue = (uint64_t)thingPtr + 4;
3890 thing = *(uint64_t*)thingPtr;
3891 baseValue = (uint64_t)thingPtr + 8;
3894 barf("Unknown size.");
3897 if(type == X86_64_RELOC_GOT
3898 || type == X86_64_RELOC_GOT_LOAD)
3900 ASSERT(reloc->r_extern);
3901 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)->addr;
3903 type = X86_64_RELOC_SIGNED;
3905 else if(reloc->r_extern)
3907 struct nlist *symbol = &nlist[reloc->r_symbolnum];
3908 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3909 if(symbol->n_value == 0)
3910 value = (uint64_t) lookupSymbol(nm);
3912 value = relocateAddress(oc, nSections, sections,
3917 value = sections[reloc->r_symbolnum-1].offset
3918 - sections[reloc->r_symbolnum-1].addr
3922 if(type == X86_64_RELOC_BRANCH)
3924 if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
3926 ASSERT(reloc->r_extern);
3927 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
3930 ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
3931 type = X86_64_RELOC_SIGNED;
3936 case X86_64_RELOC_UNSIGNED:
3937 ASSERT(!reloc->r_pcrel);
3940 case X86_64_RELOC_SIGNED:
3941 ASSERT(reloc->r_pcrel);
3942 thing += value - baseValue;
3944 case X86_64_RELOC_SUBTRACTOR:
3945 ASSERT(!reloc->r_pcrel);
3949 barf("unkown relocation");
3952 switch(reloc->r_length)
3955 *(uint8_t*)thingPtr = thing;
3958 *(uint16_t*)thingPtr = thing;
3961 *(uint32_t*)thingPtr = thing;
3964 *(uint64_t*)thingPtr = thing;
3968 if(relocs[i].r_address & R_SCATTERED)
3970 struct scattered_relocation_info *scat =
3971 (struct scattered_relocation_info*) &relocs[i];
3975 if(scat->r_length == 2)
3977 unsigned long word = 0;
3978 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
3979 checkProddableBlock(oc,wordPtr);
3981 // Note on relocation types:
3982 // i386 uses the GENERIC_RELOC_* types,
3983 // while ppc uses special PPC_RELOC_* types.
3984 // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
3985 // in both cases, all others are different.
3986 // Therefore, we use GENERIC_RELOC_VANILLA
3987 // and GENERIC_RELOC_PAIR instead of the PPC variants,
3988 // and use #ifdefs for the other types.
3990 // Step 1: Figure out what the relocated value should be
3991 if(scat->r_type == GENERIC_RELOC_VANILLA)
3993 word = *wordPtr + (unsigned long) relocateAddress(
4000 #ifdef powerpc_HOST_ARCH
4001 else if(scat->r_type == PPC_RELOC_SECTDIFF
4002 || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4003 || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4004 || scat->r_type == PPC_RELOC_HA16_SECTDIFF)
4006 else if(scat->r_type == GENERIC_RELOC_SECTDIFF)
4009 struct scattered_relocation_info *pair =
4010 (struct scattered_relocation_info*) &relocs[i+1];
4012 if(!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR)
4013 barf("Invalid Mach-O file: "
4014 "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4016 word = (unsigned long)
4017 (relocateAddress(oc, nSections, sections, scat->r_value)
4018 - relocateAddress(oc, nSections, sections, pair->r_value));
4021 #ifdef powerpc_HOST_ARCH
4022 else if(scat->r_type == PPC_RELOC_HI16
4023 || scat->r_type == PPC_RELOC_LO16
4024 || scat->r_type == PPC_RELOC_HA16
4025 || scat->r_type == PPC_RELOC_LO14)
4026 { // these are generated by label+offset things
4027 struct relocation_info *pair = &relocs[i+1];
4028 if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
4029 barf("Invalid Mach-O file: "
4030 "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4032 if(scat->r_type == PPC_RELOC_LO16)
4034 word = ((unsigned short*) wordPtr)[1];
4035 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4037 else if(scat->r_type == PPC_RELOC_LO14)
4039 barf("Unsupported Relocation: PPC_RELOC_LO14");
4040 word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4041 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4043 else if(scat->r_type == PPC_RELOC_HI16)
4045 word = ((unsigned short*) wordPtr)[1] << 16;
4046 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4048 else if(scat->r_type == PPC_RELOC_HA16)
4050 word = ((unsigned short*) wordPtr)[1] << 16;
4051 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4055 word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
4062 continue; // ignore the others
4064 #ifdef powerpc_HOST_ARCH
4065 if(scat->r_type == GENERIC_RELOC_VANILLA
4066 || scat->r_type == PPC_RELOC_SECTDIFF)
4068 if(scat->r_type == GENERIC_RELOC_VANILLA
4069 || scat->r_type == GENERIC_RELOC_SECTDIFF)
4074 #ifdef powerpc_HOST_ARCH
4075 else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
4077 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4079 else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
4081 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4083 else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
4085 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4086 + ((word & (1<<15)) ? 1 : 0);
4092 continue; // FIXME: I hope it's OK to ignore all the others.
4096 struct relocation_info *reloc = &relocs[i];
4097 if(reloc->r_pcrel && !reloc->r_extern)
4100 if(reloc->r_length == 2)
4102 unsigned long word = 0;
4103 #ifdef powerpc_HOST_ARCH
4104 unsigned long jumpIsland = 0;
4105 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
4106 // to avoid warning and to catch
4110 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
4111 checkProddableBlock(oc,wordPtr);
4113 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4117 #ifdef powerpc_HOST_ARCH
4118 else if(reloc->r_type == PPC_RELOC_LO16)
4120 word = ((unsigned short*) wordPtr)[1];
4121 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4123 else if(reloc->r_type == PPC_RELOC_HI16)
4125 word = ((unsigned short*) wordPtr)[1] << 16;
4126 word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4128 else if(reloc->r_type == PPC_RELOC_HA16)
4130 word = ((unsigned short*) wordPtr)[1] << 16;
4131 word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4133 else if(reloc->r_type == PPC_RELOC_BR24)
4136 word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
4140 if(!reloc->r_extern)
4143 sections[reloc->r_symbolnum-1].offset
4144 - sections[reloc->r_symbolnum-1].addr
4151 struct nlist *symbol = &nlist[reloc->r_symbolnum];
4152 char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4153 void *symbolAddress = lookupSymbol(nm);
4156 errorBelch("\nunknown symbol `%s'", nm);
4162 #ifdef powerpc_HOST_ARCH
4163 // In the .o file, this should be a relative jump to NULL
4164 // and we'll change it to a relative jump to the symbol
4165 ASSERT(word + reloc->r_address == 0);
4166 jumpIsland = (unsigned long)
4167 &makeSymbolExtra(oc,
4169 (unsigned long) symbolAddress)
4173 offsetToJumpIsland = word + jumpIsland
4174 - (((long)image) + sect->offset - sect->addr);
4177 word += (unsigned long) symbolAddress
4178 - (((long)image) + sect->offset - sect->addr);
4182 word += (unsigned long) symbolAddress;
4186 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4191 #ifdef powerpc_HOST_ARCH
4192 else if(reloc->r_type == PPC_RELOC_LO16)
4194 ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4197 else if(reloc->r_type == PPC_RELOC_HI16)
4199 ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4202 else if(reloc->r_type == PPC_RELOC_HA16)
4204 ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4205 + ((word & (1<<15)) ? 1 : 0);
4208 else if(reloc->r_type == PPC_RELOC_BR24)
4210 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4212 // The branch offset is too large.
4213 // Therefore, we try to use a jump island.
4216 barf("unconditional relative branch out of range: "
4217 "no jump island available");
4220 word = offsetToJumpIsland;
4221 if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
4222 barf("unconditional relative branch out of range: "
4223 "jump island out of range");
4225 *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
4230 barf("\nunknown relocation %d",reloc->r_type);
4238 static int ocGetNames_MachO(ObjectCode* oc)
4240 char *image = (char*) oc->image;
4241 struct mach_header *header = (struct mach_header*) image;
4242 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4243 unsigned i,curSymbol = 0;
4244 struct segment_command *segLC = NULL;
4245 struct section *sections;
4246 struct symtab_command *symLC = NULL;
4247 struct nlist *nlist;
4248 unsigned long commonSize = 0;
4249 char *commonStorage = NULL;
4250 unsigned long commonCounter;
4252 for(i=0;i<header->ncmds;i++)
4254 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4255 segLC = (struct segment_command*) lc;
4256 else if(lc->cmd == LC_SYMTAB)
4257 symLC = (struct symtab_command*) lc;
4258 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4261 sections = (struct section*) (segLC+1);
4262 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4266 barf("ocGetNames_MachO: no segment load command");
4268 for(i=0;i<segLC->nsects;i++)
4270 if(sections[i].size == 0)
4273 if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
4275 char * zeroFillArea = stgCallocBytes(1,sections[i].size,
4276 "ocGetNames_MachO(common symbols)");
4277 sections[i].offset = zeroFillArea - image;
4280 if(!strcmp(sections[i].sectname,"__text"))
4281 addSection(oc, SECTIONKIND_CODE_OR_RODATA,
4282 (void*) (image + sections[i].offset),
4283 (void*) (image + sections[i].offset + sections[i].size));
4284 else if(!strcmp(sections[i].sectname,"__const"))
4285 addSection(oc, SECTIONKIND_RWDATA,
4286 (void*) (image + sections[i].offset),
4287 (void*) (image + sections[i].offset + sections[i].size));
4288 else if(!strcmp(sections[i].sectname,"__data"))
4289 addSection(oc, SECTIONKIND_RWDATA,
4290 (void*) (image + sections[i].offset),
4291 (void*) (image + sections[i].offset + sections[i].size));
4292 else if(!strcmp(sections[i].sectname,"__bss")
4293 || !strcmp(sections[i].sectname,"__common"))
4294 addSection(oc, SECTIONKIND_RWDATA,
4295 (void*) (image + sections[i].offset),
4296 (void*) (image + sections[i].offset + sections[i].size));
4298 addProddableBlock(oc, (void*) (image + sections[i].offset),
4302 // count external symbols defined here
4306 for(i=0;i<symLC->nsyms;i++)
4308 if(nlist[i].n_type & N_STAB)
4310 else if(nlist[i].n_type & N_EXT)
4312 if((nlist[i].n_type & N_TYPE) == N_UNDF
4313 && (nlist[i].n_value != 0))
4315 commonSize += nlist[i].n_value;
4318 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4323 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
4324 "ocGetNames_MachO(oc->symbols)");
4328 for(i=0;i<symLC->nsyms;i++)
4330 if(nlist[i].n_type & N_STAB)
4332 else if((nlist[i].n_type & N_TYPE) == N_SECT)
4334 if(nlist[i].n_type & N_EXT)
4336 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4337 if((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm))
4338 ; // weak definition, and we already have a definition
4341 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4343 + sections[nlist[i].n_sect-1].offset
4344 - sections[nlist[i].n_sect-1].addr
4345 + nlist[i].n_value);
4346 oc->symbols[curSymbol++] = nm;
4353 commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
4354 commonCounter = (unsigned long)commonStorage;
4357 for(i=0;i<symLC->nsyms;i++)
4359 if((nlist[i].n_type & N_TYPE) == N_UNDF
4360 && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
4362 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
4363 unsigned long sz = nlist[i].n_value;
4365 nlist[i].n_value = commonCounter;
4367 ghciInsertStrHashTable(oc->fileName, symhash, nm,
4368 (void*)commonCounter);
4369 oc->symbols[curSymbol++] = nm;
4371 commonCounter += sz;
4378 static int ocResolve_MachO(ObjectCode* oc)
4380 char *image = (char*) oc->image;
4381 struct mach_header *header = (struct mach_header*) image;
4382 struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
4384 struct segment_command *segLC = NULL;
4385 struct section *sections;
4386 struct symtab_command *symLC = NULL;
4387 struct dysymtab_command *dsymLC = NULL;
4388 struct nlist *nlist;
4390 for(i=0;i<header->ncmds;i++)
4392 if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
4393 segLC = (struct segment_command*) lc;
4394 else if(lc->cmd == LC_SYMTAB)
4395 symLC = (struct symtab_command*) lc;
4396 else if(lc->cmd == LC_DYSYMTAB)
4397 dsymLC = (struct dysymtab_command*) lc;
4398 lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
4401 sections = (struct section*) (segLC+1);
4402 nlist = symLC ? (struct nlist*) (image + symLC->symoff)
4407 unsigned long *indirectSyms
4408 = (unsigned long*) (image + dsymLC->indirectsymoff);
4410 for(i=0;i<segLC->nsects;i++)
4412 if( !strcmp(sections[i].sectname,"__la_symbol_ptr")
4413 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
4414 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
4416 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4419 else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
4420 || !strcmp(sections[i].sectname,"__pointers"))
4422 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4425 else if(!strcmp(sections[i].sectname,"__jump_table"))
4427 if(!resolveImports(oc,image,symLC,§ions[i],indirectSyms,nlist))
4433 for(i=0;i<segLC->nsects;i++)
4435 if(!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,§ions[i]))
4439 #if defined (powerpc_HOST_ARCH)
4440 ocFlushInstructionCache( oc );
4446 #ifdef powerpc_HOST_ARCH
4448 * The Mach-O object format uses leading underscores. But not everywhere.
4449 * There is a small number of runtime support functions defined in
4450 * libcc_dynamic.a whose name does not have a leading underscore.
4451 * As a consequence, we can't get their address from C code.
4452 * We have to use inline assembler just to take the address of a function.
4456 static void machoInitSymbolsWithoutUnderscore()
4458 extern void* symbolsWithoutUnderscore[];
4459 void **p = symbolsWithoutUnderscore;
4460 __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
4462 #undef SymI_NeedsProto
4463 #define SymI_NeedsProto(x) \
4464 __asm__ volatile(".long " # x);
4466 RTS_MACHO_NOUNDERLINE_SYMBOLS
4468 __asm__ volatile(".text");
4470 #undef SymI_NeedsProto
4471 #define SymI_NeedsProto(x) \
4472 ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
4474 RTS_MACHO_NOUNDERLINE_SYMBOLS
4476 #undef SymI_NeedsProto
4481 * Figure out by how much to shift the entire Mach-O file in memory
4482 * when loading so that its single segment ends up 16-byte-aligned
4484 static int machoGetMisalignment( FILE * f )
4486 struct mach_header header;
4489 fread(&header, sizeof(header), 1, f);
4492 #if x86_64_TARGET_ARCH || powerpc64_TARGET_ARCH
4493 if(header.magic != MH_MAGIC_64)
4496 if(header.magic != MH_MAGIC)
4500 misalignment = (header.sizeofcmds + sizeof(header))
4503 return misalignment ? (16 - misalignment) : 0;