Linker.c 144 KB
Newer Older
1 2
/* -----------------------------------------------------------------------------
 *
3
 * (c) The GHC Team, 2000-2004
4 5 6 7 8
 *
 * RTS Object Linker
 *
 * ---------------------------------------------------------------------------*/

sof's avatar
sof committed
9
#if 0
10
#include "PosixSource.h"
sof's avatar
sof committed
11
#endif
12

13
/* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and
14 15
   MREMAP_MAYMOVE from <sys/mman.h>.
 */
16 17 18 19
#ifdef __linux__
#define _GNU_SOURCE
#endif

20 21 22 23 24
#include "Rts.h"
#include "RtsFlags.h"
#include "HsFFI.h"
#include "Hash.h"
#include "Linker.h"
25
#include "LinkerInternals.h"
26
#include "RtsUtils.h"
27
#include "Schedule.h"
28
#include "Sparks.h"
ei@vuokko.info's avatar
ei@vuokko.info committed
29
#include "RtsTypeable.h"
30

31
#ifdef HAVE_SYS_TYPES_H
32
#include <sys/types.h>
33 34
#endif

35 36 37
#include <stdlib.h>
#include <string.h>

38
#ifdef HAVE_SYS_STAT_H
39
#include <sys/stat.h>
40
#endif
41

42
#if defined(HAVE_DLFCN_H)
43
#include <dlfcn.h>
44
#endif
45

46
#if defined(cygwin32_HOST_OS)
sof's avatar
sof committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <regex.h>
#include <sys/fcntl.h>
#include <sys/termios.h>
#include <sys/utime.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#endif

62
#if defined(ia64_HOST_ARCH) || defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
63 64 65
#define USE_MMAP
#include <fcntl.h>
#include <sys/mman.h>
dons's avatar
dons committed
66

67
#if defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
dons's avatar
dons committed
68 69 70 71 72
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif

73 74
#endif

75
#if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
76
#  define OBJFORMAT_ELF
77
#elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
78
#  define OBJFORMAT_PEi386
79
#  include <windows.h>
sof's avatar
sof committed
80
#  include <math.h>
81
#elif defined(darwin_HOST_OS)
82 83 84 85
#  define OBJFORMAT_MACHO
#  include <mach-o/loader.h>
#  include <mach-o/nlist.h>
#  include <mach-o/reloc.h>
86
#if !defined(HAVE_DLFCN_H)
87
#  include <mach-o/dyld.h>
88
#endif
89 90 91
#if defined(powerpc_HOST_ARCH)
#  include <mach-o/ppc/reloc.h>
#endif
92 93 94
#if defined(x86_64_HOST_ARCH)
#  include <mach-o/x86_64/reloc.h>
#endif
95 96
#endif

97
/* Hash table mapping symbol names to Symbol */
98
static /*Str*/HashTable *symhash;
99

100 101 102
/* Hash table mapping symbol names to StgStablePtr */
static /*Str*/HashTable *stablehash;

103 104 105
/* List of currently loaded objects */
ObjectCode *objects = NULL;	/* initially empty */

106
#if defined(OBJFORMAT_ELF)
107 108 109
static int ocVerifyImage_ELF    ( ObjectCode* oc );
static int ocGetNames_ELF       ( ObjectCode* oc );
static int ocResolve_ELF        ( ObjectCode* oc );
110
#if defined(powerpc_HOST_ARCH)
111
static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
112
#endif
113
#elif defined(OBJFORMAT_PEi386)
114 115 116
static int ocVerifyImage_PEi386 ( ObjectCode* oc );
static int ocGetNames_PEi386    ( ObjectCode* oc );
static int ocResolve_PEi386     ( ObjectCode* oc );
117 118 119 120
#elif defined(OBJFORMAT_MACHO)
static int ocVerifyImage_MachO    ( ObjectCode* oc );
static int ocGetNames_MachO       ( ObjectCode* oc );
static int ocResolve_MachO        ( ObjectCode* oc );
121

122
static int machoGetMisalignment( FILE * );
123 124 125
#if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
#endif
126
#ifdef powerpc_HOST_ARCH
127
static void machoInitSymbolsWithoutUnderscore( void );
128
#endif
129
#endif
130

131
#if defined(x86_64_HOST_ARCH) && defined(OBJFORMAT_ELF)
132 133 134
static void*x86_64_high_symbol( char *lbl, void *addr );
#endif

135 136 137 138
/* -----------------------------------------------------------------------------
 * Built-in symbols from the RTS
 */

139 140 141 142 143 144
typedef struct _RtsSymbolVal {
    char   *lbl;
    void   *addr;
} RtsSymbolVal;


145 146 147 148 149 150 151 152
#if !defined(PAR)
#define Maybe_Stable_Names      SymX(mkWeakzh_fast)			\
      				SymX(makeStableNamezh_fast)		\
      				SymX(finalizzeWeakzh_fast)
#else
/* These are not available in GUM!!! -- HWL */
#define Maybe_Stable_Names
#endif
153

154
#if !defined (mingw32_HOST_OS)
155
#define RTS_POSIX_ONLY_SYMBOLS                  \
156
      SymX(signal_handlers)			\
157 158
      SymX(stg_sig_install)			\
      Sym(nocldstop)
sof's avatar
sof committed
159
#endif
160

161
#if defined (cygwin32_HOST_OS)
sof's avatar
sof committed
162 163 164
#define RTS_MINGW_ONLY_SYMBOLS /**/
/* Don't have the ability to read import libs / archives, so
 * we have to stupidly list a lot of what libcygwin.a
165
 * exports; sigh.
sof's avatar
sof committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
 */
#define RTS_CYGWIN_ONLY_SYMBOLS                 \
      SymX(regfree)                             \
      SymX(regexec)                             \
      SymX(regerror)                            \
      SymX(regcomp)                             \
      SymX(__errno)                             \
      SymX(access)                              \
      SymX(chmod)                               \
      SymX(chdir)                               \
      SymX(close)                               \
      SymX(creat)                               \
      SymX(dup)                                 \
      SymX(dup2)                                \
      SymX(fstat)                               \
      SymX(fcntl)                               \
      SymX(getcwd)                              \
      SymX(getenv)                              \
      SymX(lseek)                               \
      SymX(open)                                \
      SymX(fpathconf)                           \
      SymX(pathconf)                            \
      SymX(stat)                                \
      SymX(pow)                                 \
      SymX(tanh)                                \
      SymX(cosh)                                \
      SymX(sinh)                                \
      SymX(atan)                                \
      SymX(acos)                                \
      SymX(asin)                                \
      SymX(tan)                                 \
      SymX(cos)                                 \
      SymX(sin)                                 \
      SymX(exp)                                 \
      SymX(log)                                 \
      SymX(sqrt)                                \
      SymX(localtime_r)                         \
      SymX(gmtime_r)                            \
      SymX(mktime)                              \
      Sym(_imp___tzname)                        \
      SymX(gettimeofday)                        \
      SymX(timezone)                            \
      SymX(tcgetattr)                           \
      SymX(tcsetattr)                           \
      SymX(memcpy)                              \
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
      SymX(free)                                \
      SymX(fork)                                \
      SymX(lstat)                               \
      SymX(isatty)                              \
      SymX(mkdir)                               \
      SymX(opendir)                             \
      SymX(readdir)                             \
      SymX(rewinddir)                           \
      SymX(closedir)                            \
      SymX(link)                                \
      SymX(mkfifo)                              \
      SymX(pipe)                                \
      SymX(read)                                \
      SymX(rename)                              \
      SymX(rmdir)                               \
      SymX(select)                              \
      SymX(system)                              \
      SymX(write)                               \
      SymX(strcmp)                              \
      SymX(strcpy)                              \
      SymX(strncpy)                             \
      SymX(strerror)                            \
      SymX(sigaddset)                           \
      SymX(sigemptyset)                         \
      SymX(sigprocmask)                         \
      SymX(umask)                               \
      SymX(uname)                               \
      SymX(unlink)                              \
      SymX(utime)                               \
243
      SymX(waitpid)
244

245
#elif !defined(mingw32_HOST_OS)
sof's avatar
sof committed
246 247
#define RTS_MINGW_ONLY_SYMBOLS /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
248
#else /* defined(mingw32_HOST_OS) */
sof's avatar
sof committed
249 250
#define RTS_POSIX_ONLY_SYMBOLS  /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
251

252 253 254 255
/* Extra syms gen'ed by mingw-2's gcc-3.2: */
#if __GNUC__>=3
#define RTS_MINGW_EXTRA_SYMS                    \
      Sym(_imp____mb_cur_max)                   \
256
      Sym(_imp___pctype)
257 258 259 260
#else
#define RTS_MINGW_EXTRA_SYMS
#endif

261 262 263 264 265 266
#if HAVE_GETTIMEOFDAY
#define RTS_MINGW_GETTIMEOFDAY_SYM Sym(gettimeofday)
#else
#define RTS_MINGW_GETTIMEOFDAY_SYM /**/
#endif

267 268
/* These are statically linked from the mingw libraries into the ghc
   executable, so we have to employ this hack. */
269
#define RTS_MINGW_ONLY_SYMBOLS                  \
sof's avatar
sof committed
270 271
      SymX(asyncReadzh_fast)			\
      SymX(asyncWritezh_fast)			\
sof's avatar
sof committed
272
      SymX(asyncDoProczh_fast)			\
273
      SymX(memset)                              \
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      SymX(inet_ntoa)                           \
      SymX(inet_addr)                           \
      SymX(htonl)                               \
      SymX(recvfrom)                            \
      SymX(listen)                              \
      SymX(bind)                                \
      SymX(shutdown)                            \
      SymX(connect)                             \
      SymX(htons)                               \
      SymX(ntohs)                               \
      SymX(getservbyname)                       \
      SymX(getservbyport)                       \
      SymX(getprotobynumber)                    \
      SymX(getprotobyname)                      \
      SymX(gethostbyname)                       \
      SymX(gethostbyaddr)                       \
      SymX(gethostname)                         \
      SymX(strcpy)                              \
      SymX(strncpy)                             \
      SymX(abort)                               \
      Sym(_alloca)                              \
      Sym(isxdigit)                             \
      Sym(isupper)                              \
      Sym(ispunct)                              \
      Sym(islower)                              \
      Sym(isspace)                              \
      Sym(isprint)                              \
      Sym(isdigit)                              \
      Sym(iscntrl)                              \
      Sym(isalpha)                              \
      Sym(isalnum)                              \
      SymX(strcmp)                              \
306 307 308
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
309 310 311 312 313 314 315 316 317 318 319 320 321
      SymX(pow)                                 \
      SymX(tanh)                                \
      SymX(cosh)                                \
      SymX(sinh)                                \
      SymX(atan)                                \
      SymX(acos)                                \
      SymX(asin)                                \
      SymX(tan)                                 \
      SymX(cos)                                 \
      SymX(sin)                                 \
      SymX(exp)                                 \
      SymX(log)                                 \
      SymX(sqrt)                                \
322 323 324 325 326 327 328 329 330 331 332 333 334
      SymX(powf)                                 \
      SymX(tanhf)                                \
      SymX(coshf)                                \
      SymX(sinhf)                                \
      SymX(atanf)                                \
      SymX(acosf)                                \
      SymX(asinf)                                \
      SymX(tanf)                                 \
      SymX(cosf)                                 \
      SymX(sinf)                                 \
      SymX(expf)                                 \
      SymX(logf)                                 \
      SymX(sqrtf)                                \
335
      SymX(memcpy)                              \
sof's avatar
sof committed
336 337
      SymX(rts_InstallConsoleEvent)             \
      SymX(rts_ConsoleHandlerDone)              \
338
      Sym(mktime)                               \
339
      Sym(_imp___timezone)                      \
340
      Sym(_imp___tzname)                        \
341
      Sym(_imp__tzname)                         \
342
      Sym(_imp___iob)                           \
sof's avatar
sof committed
343
      Sym(_imp___osver)                         \
344 345 346 347
      Sym(localtime)                            \
      Sym(gmtime)                               \
      Sym(opendir)                              \
      Sym(readdir)                              \
sof's avatar
sof committed
348
      Sym(rewinddir)                            \
349
      RTS_MINGW_EXTRA_SYMS                      \
350
      RTS_MINGW_GETTIMEOFDAY_SYM		\
351
      Sym(closedir)
352
#endif
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
#if defined(darwin_TARGET_OS) && HAVE_PRINTF_LDBLSTUB
#define RTS_DARWIN_ONLY_SYMBOLS			\
     Sym(asprintf$LDBLStub)                     \
     Sym(err$LDBLStub)                          \
     Sym(errc$LDBLStub)                         \
     Sym(errx$LDBLStub)                         \
     Sym(fprintf$LDBLStub)                      \
     Sym(fscanf$LDBLStub)                       \
     Sym(fwprintf$LDBLStub)                     \
     Sym(fwscanf$LDBLStub)                      \
     Sym(printf$LDBLStub)                       \
     Sym(scanf$LDBLStub)                        \
     Sym(snprintf$LDBLStub)                     \
     Sym(sprintf$LDBLStub)                      \
     Sym(sscanf$LDBLStub)                       \
     Sym(strtold$LDBLStub)                      \
     Sym(swprintf$LDBLStub)                     \
     Sym(swscanf$LDBLStub)                      \
     Sym(syslog$LDBLStub)                       \
     Sym(vasprintf$LDBLStub)                    \
     Sym(verr$LDBLStub)                         \
     Sym(verrc$LDBLStub)                        \
     Sym(verrx$LDBLStub)                        \
     Sym(vfprintf$LDBLStub)                     \
     Sym(vfscanf$LDBLStub)                      \
     Sym(vfwprintf$LDBLStub)                    \
     Sym(vfwscanf$LDBLStub)                     \
     Sym(vprintf$LDBLStub)                      \
     Sym(vscanf$LDBLStub)                       \
     Sym(vsnprintf$LDBLStub)                    \
     Sym(vsprintf$LDBLStub)                     \
     Sym(vsscanf$LDBLStub)                      \
     Sym(vswprintf$LDBLStub)                    \
     Sym(vswscanf$LDBLStub)                     \
     Sym(vsyslog$LDBLStub)                      \
     Sym(vwarn$LDBLStub)                        \
     Sym(vwarnc$LDBLStub)                       \
     Sym(vwarnx$LDBLStub)                       \
     Sym(vwprintf$LDBLStub)                     \
     Sym(vwscanf$LDBLStub)                      \
     Sym(warn$LDBLStub)                         \
     Sym(warnc$LDBLStub)                        \
     Sym(warnx$LDBLStub)                        \
     Sym(wcstold$LDBLStub)                      \
     Sym(wprintf$LDBLStub)                      \
     Sym(wscanf$LDBLStub)
#else
#define RTS_DARWIN_ONLY_SYMBOLS
#endif

sof's avatar
sof committed
404 405 406 407 408
#ifndef SMP
# define MAIN_CAP_SYM SymX(MainCapability)
#else
# define MAIN_CAP_SYM
#endif
409

sof's avatar
sof committed
410 411 412 413
#if !defined(mingw32_HOST_OS)
#define RTS_USER_SIGNALS_SYMBOLS \
   SymX(setIOManagerPipe)
#else
Simon Marlow's avatar
Simon Marlow committed
414 415 416 417 418
#define RTS_USER_SIGNALS_SYMBOLS \
   SymX(sendIOManagerEvent) \
   SymX(readIOManagerEvent) \
   SymX(getIOManagerEvent) \
   SymX(console_handler)
sof's avatar
sof committed
419 420
#endif

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
#ifdef TABLES_NEXT_TO_CODE
#define RTS_RET_SYMBOLS /* nothing */
#else
#define RTS_RET_SYMBOLS 			\
      SymX(stg_enter_ret)			\
      SymX(stg_gc_fun_ret)			\
      SymX(stg_ap_v_ret)			\
      SymX(stg_ap_f_ret)			\
      SymX(stg_ap_d_ret)			\
      SymX(stg_ap_l_ret)			\
      SymX(stg_ap_n_ret)			\
      SymX(stg_ap_p_ret)			\
      SymX(stg_ap_pv_ret)			\
      SymX(stg_ap_pp_ret)			\
      SymX(stg_ap_ppv_ret)			\
      SymX(stg_ap_ppp_ret)			\
      SymX(stg_ap_pppv_ret)			\
      SymX(stg_ap_pppp_ret)			\
      SymX(stg_ap_ppppp_ret)			\
      SymX(stg_ap_pppppp_ret)
#endif

443
#define RTS_SYMBOLS				\
444 445
      Maybe_Stable_Names			\
      Sym(StgReturn)				\
446 447
      SymX(stg_enter_info)			\
      SymX(stg_gc_void_info)			\
448 449
      SymX(__stg_gc_enter_1)			\
      SymX(stg_gc_noregs)			\
450
      SymX(stg_gc_unpt_r1_info)			\
451
      SymX(stg_gc_unpt_r1)			\
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
      SymX(stg_gc_unbx_r1_info)			\
      SymX(stg_gc_unbx_r1)			\
      SymX(stg_gc_f1_info)			\
      SymX(stg_gc_f1)				\
      SymX(stg_gc_d1_info)			\
      SymX(stg_gc_d1)				\
      SymX(stg_gc_l1_info)			\
      SymX(stg_gc_l1)				\
      SymX(__stg_gc_fun)			\
      SymX(stg_gc_fun_info)			\
      SymX(stg_gc_gen)				\
      SymX(stg_gc_gen_info)			\
      SymX(stg_gc_gen_hp)			\
      SymX(stg_gc_ut)				\
      SymX(stg_gen_yield)			\
      SymX(stg_yield_noregs)			\
468
      SymX(stg_yield_to_interpreter)		\
469 470 471 472 473
      SymX(stg_gen_block)			\
      SymX(stg_block_noregs)			\
      SymX(stg_block_1)				\
      SymX(stg_block_takemvar)			\
      SymX(stg_block_putmvar)			\
sof's avatar
sof committed
474
      MAIN_CAP_SYM                              \
475 476 477 478 479 480
      SymX(MallocFailHook)			\
      SymX(OnExitHook)				\
      SymX(OutOfHeapHook)			\
      SymX(StackOverflowHook)			\
      SymX(__encodeDouble)			\
      SymX(__encodeFloat)			\
dons's avatar
dons committed
481
      SymX(addDLL)               		\
482 483 484 485 486 487
      SymExtern(__gmpn_gcd_1)			\
      SymExtern(__gmpz_cmp)			\
      SymExtern(__gmpz_cmp_si)			\
      SymExtern(__gmpz_cmp_ui)			\
      SymExtern(__gmpz_get_si)			\
      SymExtern(__gmpz_get_ui)			\
488 489 490
      SymX(__int_encodeDouble)			\
      SymX(__int_encodeFloat)			\
      SymX(andIntegerzh_fast)			\
491
      SymX(atomicallyzh_fast)			\
492
      SymX(barf)				\
493 494
      SymX(debugBelch)				\
      SymX(errorBelch)				\
495 496
      SymX(blockAsyncExceptionszh_fast)		\
      SymX(catchzh_fast)			\
497 498
      SymX(catchRetryzh_fast)			\
      SymX(catchSTMzh_fast)			\
tharris@microsoft.com's avatar
tharris@microsoft.com committed
499
      SymX(checkzh_fast)                        \
sof's avatar
sof committed
500
      SymX(closure_flags)                       \
501
      SymX(cmp_thread)				\
sof's avatar
sof committed
502 503
      SymX(cmpIntegerzh_fast)	        	\
      SymX(cmpIntegerIntzh_fast)	      	\
sof's avatar
sof committed
504
      SymX(complementIntegerzh_fast)		\
505 506 507 508 509
      SymX(createAdjustor)			\
      SymX(decodeDoublezh_fast)			\
      SymX(decodeFloatzh_fast)			\
      SymX(defaultsHook)			\
      SymX(delayzh_fast)			\
sof's avatar
sof committed
510 511
      SymX(deRefWeakzh_fast)			\
      SymX(deRefStablePtrzh_fast)		\
512
      SymX(dirty_MUT_VAR)			\
513 514 515
      SymX(divExactIntegerzh_fast)		\
      SymX(divModIntegerzh_fast)		\
      SymX(forkzh_fast)				\
Simon Marlow's avatar
Simon Marlow committed
516
      SymX(forkOnzh_fast)			\
517
      SymX(forkProcess)				\
518
      SymX(forkOS_createThread)			\
519
      SymX(freeHaskellFunctionPtr)		\
sof's avatar
sof committed
520
      SymX(freeStablePtr)		        \
ei@vuokko.info's avatar
ei@vuokko.info committed
521
      SymX(getOrSetTypeableStore)		\
522
      SymX(gcdIntegerzh_fast)			\
sof's avatar
sof committed
523 524
      SymX(gcdIntegerIntzh_fast)		\
      SymX(gcdIntzh_fast)			\
525
      SymX(genSymZh)				\
dons's avatar
dons committed
526
      SymX(genericRaise)			\
527
      SymX(getProgArgv)				\
528
      SymX(getFullProgArgv)				\
529
      SymX(getStablePtr)			\
530 531 532 533 534 535 536
      SymX(hs_init)				\
      SymX(hs_exit)				\
      SymX(hs_set_argv)				\
      SymX(hs_add_root)				\
      SymX(hs_perform_gc)			\
      SymX(hs_free_stable_ptr)			\
      SymX(hs_free_fun_ptr)			\
537
      SymX(hs_hpc_rootModule)		        \
538
      SymX(initLinker)				\
539 540
      SymX(unpackClosurezh_fast)                \
      SymX(getApStackValzh_fast)                \
541
      SymX(int2Integerzh_fast)			\
sof's avatar
sof committed
542 543
      SymX(integer2Intzh_fast)			\
      SymX(integer2Wordzh_fast)			\
544
      SymX(isCurrentThreadBoundzh_fast)		\
545 546 547 548
      SymX(isDoubleDenormalized)		\
      SymX(isDoubleInfinite)			\
      SymX(isDoubleNaN)				\
      SymX(isDoubleNegativeZero)		\
sof's avatar
sof committed
549
      SymX(isEmptyMVarzh_fast)			\
550 551 552 553 554
      SymX(isFloatDenormalized)			\
      SymX(isFloatInfinite)			\
      SymX(isFloatNaN)				\
      SymX(isFloatNegativeZero)			\
      SymX(killThreadzh_fast)			\
dons's avatar
dons committed
555
      SymX(loadObj)          			\
556 557
      SymX(insertStableSymbol) 			\
      SymX(insertSymbol)     			\
dons's avatar
dons committed
558
      SymX(lookupSymbol)     			\
sof's avatar
sof committed
559
      SymX(makeStablePtrzh_fast)		\
560 561
      SymX(minusIntegerzh_fast)			\
      SymX(mkApUpd0zh_fast)			\
sof's avatar
sof committed
562
      SymX(myThreadIdzh_fast)			\
563
      SymX(labelThreadzh_fast)                  \
564 565 566
      SymX(newArrayzh_fast)			\
      SymX(newBCOzh_fast)			\
      SymX(newByteArrayzh_fast)			\
567
      SymX_redirect(newCAF, newDynCAF)		\
568 569
      SymX(newMVarzh_fast)			\
      SymX(newMutVarzh_fast)			\
570
      SymX(newTVarzh_fast)			\
571
      SymX(noDuplicatezh_fast)			\
572
      SymX(atomicModifyMutVarzh_fast)		\
573
      SymX(newPinnedByteArrayzh_fast)		\
574
      SymX(newSpark)				\
575 576
      SymX(orIntegerzh_fast)			\
      SymX(performGC)				\
577
      SymX(performMajorGC)			\
578 579 580 581 582 583 584
      SymX(plusIntegerzh_fast)			\
      SymX(prog_argc)				\
      SymX(prog_argv)				\
      SymX(putMVarzh_fast)			\
      SymX(quotIntegerzh_fast)			\
      SymX(quotRemIntegerzh_fast)		\
      SymX(raisezh_fast)			\
585
      SymX(raiseIOzh_fast)			\
586
      SymX(readTVarzh_fast)			\
587 588 589
      SymX(remIntegerzh_fast)			\
      SymX(resetNonBlockingFd)			\
      SymX(resumeThread)			\
dons's avatar
dons committed
590
      SymX(resolveObjs)                         \
591
      SymX(retryzh_fast)                        \
592 593 594 595 596
      SymX(rts_apply)				\
      SymX(rts_checkSchedStatus)		\
      SymX(rts_eval)				\
      SymX(rts_evalIO)				\
      SymX(rts_evalLazyIO)			\
597
      SymX(rts_evalStableIO)			\
598 599 600 601 602 603
      SymX(rts_eval_)				\
      SymX(rts_getBool)				\
      SymX(rts_getChar)				\
      SymX(rts_getDouble)			\
      SymX(rts_getFloat)			\
      SymX(rts_getInt)				\
604 605
      SymX(rts_getInt8)				\
      SymX(rts_getInt16)			\
606
      SymX(rts_getInt32)			\
607
      SymX(rts_getInt64)			\
608
      SymX(rts_getPtr)				\
609
      SymX(rts_getFunPtr)			\
610
      SymX(rts_getStablePtr)			\
611
      SymX(rts_getThreadId)			\
612
      SymX(rts_getWord)				\
613 614
      SymX(rts_getWord8)			\
      SymX(rts_getWord16)			\
615
      SymX(rts_getWord32)			\
616
      SymX(rts_getWord64)			\
617
      SymX(rts_lock)				\
618 619 620 621 622
      SymX(rts_mkBool)				\
      SymX(rts_mkChar)				\
      SymX(rts_mkDouble)			\
      SymX(rts_mkFloat)				\
      SymX(rts_mkInt)				\
623
      SymX(rts_mkInt8)				\
624 625 626 627
      SymX(rts_mkInt16)				\
      SymX(rts_mkInt32)				\
      SymX(rts_mkInt64)				\
      SymX(rts_mkPtr)				\
628
      SymX(rts_mkFunPtr)			\
629 630 631
      SymX(rts_mkStablePtr)			\
      SymX(rts_mkString)			\
      SymX(rts_mkWord)				\
632
      SymX(rts_mkWord8)				\
633 634 635
      SymX(rts_mkWord16)			\
      SymX(rts_mkWord32)			\
      SymX(rts_mkWord64)			\
636
      SymX(rts_unlock)				\
637
      SymX(rtsSupportsBoundThreads)		\
638 639
      SymX(__hscore_get_saved_termios)		\
      SymX(__hscore_set_saved_termios)		\
640
      SymX(setProgArgv)				\
641 642
      SymX(startupHaskell)			\
      SymX(shutdownHaskell)			\
643 644 645 646
      SymX(shutdownHaskellAndExit)		\
      SymX(stable_ptr_table)			\
      SymX(stackOverflow)			\
      SymX(stg_CAF_BLACKHOLE_info)		\
647
      SymX(awakenBlockedQueue)			\
648
      SymX(stg_CHARLIKE_closure)		\
649 650
      SymX(stg_MVAR_CLEAN_info)			\
      SymX(stg_MVAR_DIRTY_info)			\
651 652
      SymX(stg_IND_STATIC_info)			\
      SymX(stg_INTLIKE_closure)			\
653
      SymX(stg_MUT_ARR_PTRS_DIRTY_info)		\
654
      SymX(stg_MUT_ARR_PTRS_FROZEN_info)	\
655
      SymX(stg_MUT_ARR_PTRS_FROZEN0_info)	\
656
      SymX(stg_WEAK_info)                       \
657 658 659 660 661 662 663 664 665 666
      SymX(stg_ap_v_info)			\
      SymX(stg_ap_f_info)			\
      SymX(stg_ap_d_info)			\
      SymX(stg_ap_l_info)			\
      SymX(stg_ap_n_info)			\
      SymX(stg_ap_p_info)			\
      SymX(stg_ap_pv_info)			\
      SymX(stg_ap_pp_info)			\
      SymX(stg_ap_ppv_info)			\
      SymX(stg_ap_ppp_info)			\
667
      SymX(stg_ap_pppv_info)			\
668 669 670
      SymX(stg_ap_pppp_info)			\
      SymX(stg_ap_ppppp_info)			\
      SymX(stg_ap_pppppp_info)			\
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
      SymX(stg_ap_0_fast)			\
      SymX(stg_ap_v_fast)			\
      SymX(stg_ap_f_fast)			\
      SymX(stg_ap_d_fast)			\
      SymX(stg_ap_l_fast)			\
      SymX(stg_ap_n_fast)			\
      SymX(stg_ap_p_fast)			\
      SymX(stg_ap_pv_fast)			\
      SymX(stg_ap_pp_fast)			\
      SymX(stg_ap_ppv_fast)			\
      SymX(stg_ap_ppp_fast)			\
      SymX(stg_ap_pppv_fast)			\
      SymX(stg_ap_pppp_fast)			\
      SymX(stg_ap_ppppp_fast)			\
      SymX(stg_ap_pppppp_fast)			\
686
      SymX(stg_ap_1_upd_info)			\
687 688 689 690 691 692
      SymX(stg_ap_2_upd_info)			\
      SymX(stg_ap_3_upd_info)			\
      SymX(stg_ap_4_upd_info)			\
      SymX(stg_ap_5_upd_info)			\
      SymX(stg_ap_6_upd_info)			\
      SymX(stg_ap_7_upd_info)			\
693
      SymX(stg_exit)				\
694
      SymX(stg_sel_0_upd_info)			\
695 696 697 698 699 700
      SymX(stg_sel_10_upd_info)			\
      SymX(stg_sel_11_upd_info)			\
      SymX(stg_sel_12_upd_info)			\
      SymX(stg_sel_13_upd_info)			\
      SymX(stg_sel_14_upd_info)			\
      SymX(stg_sel_15_upd_info)			\
701 702 703 704 705 706 707 708 709
      SymX(stg_sel_1_upd_info)			\
      SymX(stg_sel_2_upd_info)			\
      SymX(stg_sel_3_upd_info)			\
      SymX(stg_sel_4_upd_info)			\
      SymX(stg_sel_5_upd_info)			\
      SymX(stg_sel_6_upd_info)			\
      SymX(stg_sel_7_upd_info)			\
      SymX(stg_sel_8_upd_info)			\
      SymX(stg_sel_9_upd_info)			\
710 711
      SymX(stg_upd_frame_info)			\
      SymX(suspendThread)			\
712
      SymX(takeMVarzh_fast)			\
713
      SymX(timesIntegerzh_fast)			\
714
      SymX(tryPutMVarzh_fast)			\
715 716
      SymX(tryTakeMVarzh_fast)			\
      SymX(unblockAsyncExceptionszh_fast)	\
dons's avatar
dons committed
717
      SymX(unloadObj)                           \
718
      SymX(unsafeThawArrayzh_fast)		\
719 720
      SymX(waitReadzh_fast)			\
      SymX(waitWritezh_fast)			\
721
      SymX(word2Integerzh_fast)			\
722
      SymX(writeTVarzh_fast)			\
723
      SymX(xorIntegerzh_fast)			\
sof's avatar
sof committed
724
      SymX(yieldzh_fast)                        \
725
      SymX(stg_interp_constr_entry)             \
726 727
      SymX(allocateExec)	                \
      SymX(freeExec)		                \
728 729 730
      SymX(getAllocations)                      \
      SymX(revertCAFs)                          \
      SymX(RtsFlags)                            \
731
      SymX(rts_breakpoint_io_action)		\
732 733
      SymX(rts_stop_next_breakpoint)		\
      SymX(rts_stop_on_exception)		\
734
      SymX(stopTimer)				\
735
      SymX(n_capabilities)			\
sof's avatar
sof committed
736
      RTS_USER_SIGNALS_SYMBOLS
737

738
#ifdef SUPPORT_LONG_LONGS
739
#define RTS_LONG_LONG_SYMS			\
740 741
      SymX(int64ToIntegerzh_fast)		\
      SymX(word64ToIntegerzh_fast)
742 743 744 745
#else
#define RTS_LONG_LONG_SYMS /* nothing */
#endif

746 747 748
// 64-bit support functions in libgcc.a
#if defined(__GNUC__) && SIZEOF_VOID_P <= 4
#define RTS_LIBGCC_SYMBOLS			\
749 750 751
      Sym(__divdi3)                             \
      Sym(__udivdi3)                            \
      Sym(__moddi3)                             \
752
      Sym(__umoddi3)				\
753
      Sym(__muldi3)				\
754 755 756 757
      Sym(__ashldi3)				\
      Sym(__ashrdi3)				\
      Sym(__lshrdi3)				\
      Sym(__eprintf)
758
#elif defined(ia64_HOST_ARCH)
759 760 761 762 763 764 765
#define RTS_LIBGCC_SYMBOLS			\
      Sym(__divdi3)				\
      Sym(__udivdi3)                            \
      Sym(__moddi3)				\
      Sym(__umoddi3)				\
      Sym(__divsf3)				\
      Sym(__divdf3)
766 767 768 769
#else
#define RTS_LIBGCC_SYMBOLS
#endif

770
#if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
771 772 773 774 775 776
      // Symbols that don't have a leading underscore
      // on Mac OS X. They have to receive special treatment,
      // see machoInitSymbolsWithoutUnderscore()
#define RTS_MACHO_NOUNDERLINE_SYMBOLS		\
      Sym(saveFP)				\
      Sym(restFP)
777
#endif
778 779

/* entirely bogus claims about types of these symbols */
780
#define Sym(vvv)  extern void vvv(void);
781
#if defined(__PIC__) && defined(mingw32_TARGET_OS)
782 783 784 785
#define SymExtern(vvv)  extern void _imp__ ## vvv (void);
#else
#define SymExtern(vvv)  SymX(vvv)
#endif
786
#define SymX(vvv) /**/
787
#define SymX_redirect(vvv,xxx) /**/
788
RTS_SYMBOLS
789
RTS_RET_SYMBOLS
790
RTS_LONG_LONG_SYMS
791
RTS_POSIX_ONLY_SYMBOLS
792
RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
793
RTS_CYGWIN_ONLY_SYMBOLS
794
RTS_DARWIN_ONLY_SYMBOLS
795
RTS_LIBGCC_SYMBOLS
796 797
#undef Sym
#undef SymX
798
#undef SymX_redirect
799
#undef SymExtern
800 801 802 803 804 805 806 807 808 809

#ifdef LEADING_UNDERSCORE
#define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
#else
#define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
#endif

#define Sym(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
                    (void*)(&(vvv)) },
#define SymX(vvv) Sym(vvv)
810
#define SymExtern(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
811
	    (void*)DLL_IMPORT_DATA_REF(vvv) },
812

813 814 815 816 817 818
// SymX_redirect allows us to redirect references to one symbol to
// another symbol.  See newCAF/newDynCAF for an example.
#define SymX_redirect(vvv,xxx) \
    { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
      (void*)(&(xxx)) },

819
static RtsSymbolVal rtsSyms[] = {
820
      RTS_SYMBOLS
821
      RTS_RET_SYMBOLS
822
      RTS_LONG_LONG_SYMS
823
      RTS_POSIX_ONLY_SYMBOLS
824
      RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
825
      RTS_CYGWIN_ONLY_SYMBOLS
826
      RTS_DARWIN_ONLY_SYMBOLS
827
      RTS_LIBGCC_SYMBOLS
828 829 830 831
#if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
      // dyld stub code contains references to this,
      // but it should never be called because we treat
      // lazy pointers as nonlazy.
832
      { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
833
#endif
834 835 836
      { 0, 0 } /* sentinel */
};

837 838


839 840 841
/* -----------------------------------------------------------------------------
 * Insert symbols into hash tables, checking for duplicates.
 */
842

843 844
static void ghciInsertStrHashTable ( char* obj_name,
                                     HashTable *table,
845
                                     char* key,
846 847 848 849 850 851 852 853
                                     void *data
				   )
{
   if (lookupHashTable(table, (StgWord)key) == NULL)
   {
      insertStrHashTable(table, (StgWord)key, data);
      return;
   }
854
   debugBelch(
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
      "\n\n"
      "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
      "   %s\n"
      "whilst processing object file\n"
      "   %s\n"
      "This could be caused by:\n"
      "   * Loading two different object files which export the same symbol\n"
      "   * Specifying the same object file twice on the GHCi command line\n"
      "   * An incorrect `package.conf' entry, causing some object to be\n"
      "     loaded twice.\n"
      "GHCi cannot safely continue in this situation.  Exiting now.  Sorry.\n"
      "\n",
      (char*)key,
      obj_name
   );
   exit(1);
}
872 873 874
/* -----------------------------------------------------------------------------
 * initialize the object linker
 */
875 876 877 878


static int linker_init_done = 0 ;

879
#if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
880
static void *dl_prog_handle;
881
#endif
882 883 884 885

void
initLinker( void )
{
886
    RtsSymbolVal *sym;
887

888 889 890 891 892 893 894
    /* Make initLinker idempotent, so we can call it
       before evey relevant operation; that means we
       don't need to initialise the linker separately */
    if (linker_init_done == 1) { return; } else {
      linker_init_done = 1;
    }

895
    stablehash = allocStrHashTable();
896 897 898 899
    symhash = allocStrHashTable();

    /* populate the symbol table with stuff from the RTS */
    for (sym = rtsSyms; sym->lbl != NULL; sym++) {
900 901
	ghciInsertStrHashTable("(GHCi built-in symbols)",
                               symhash, sym->lbl, sym->addr);
902
    }
903
#   if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
904 905 906
    machoInitSymbolsWithoutUnderscore();
#   endif

907
#   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
908
#   if defined(RTLD_DEFAULT)
909 910
    dl_prog_handle = RTLD_DEFAULT;
#   else
911
    dl_prog_handle = dlopen(NULL, RTLD_LAZY);
912
#   endif /* RTLD_DEFAULT */
913
#   endif
914 915
}

916
/* -----------------------------------------------------------------------------
917 918 919
 *                  Loading DLL or .so dynamic libraries
 * -----------------------------------------------------------------------------
 *
920 921 922 923
 * Add a DLL from which symbols may be found.  In the ELF case, just
 * do RTLD_GLOBAL-style add, so no further messing around needs to
 * happen in order that symbols in the loaded .so are findable --
 * lookupSymbol() will subsequently see them by dlsym on the program's
924 925
 * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
 *
926
 * In the PEi386 case, open the DLLs and put handles to them in a
927
 * linked list.  When looking for a symbol, try all handles in the
928 929 930 931 932
 * list.  This means that we need to load even DLLs that are guaranteed
 * to be in the ghc.exe image already, just so we can get a handle
 * to give to loadSymbol, so that we can find the symbols.  For such
 * libraries, the LoadLibrary call should be a no-op except for returning
 * the handle.
933
 *
934
 */
935 936 937 938 939 940

#if defined(OBJFORMAT_PEi386)
/* A record for storing handles into DLLs. */

typedef
   struct _OpenedDLL {
941
      char*              name;
942 943
      struct _OpenedDLL* next;
      HINSTANCE instance;
944
   }
945 946 947 948 949 950
   OpenedDLL;

/* A list thereof. */
static OpenedDLL* opened_dlls = NULL;
#endif

951
const char *
952
addDLL( char *dll_name )
953
{
954
#  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
955
   /* ------------------- ELF DLL loader ------------------- */
956
   void *hdl;
957
   const char *errmsg;
958

959 960
   initLinker();

961
   hdl= dlopen(dll_name, RTLD_NOW | RTLD_GLOBAL);
dons's avatar
dons committed
962

963 964 965 966 967 968 969 970
   if (hdl == NULL) {
      /* dlopen failed; return a ptr to the error msg. */
      errmsg = dlerror();
      if (errmsg == NULL) errmsg = "addDLL: unknown error";
      return errmsg;
   } else {
      return NULL;
   }
971 972
   /*NOTREACHED*/

973
#  elif defined(OBJFORMAT_PEi386)
974
   /* ------------------- Win32 DLL loader ------------------- */
975

976
   char*      buf;
977
   OpenedDLL* o_dll;
978
   HINSTANCE  instance;
979

980 981
   initLinker();

982
   /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
983 984 985 986 987

   /* See if we've already got it, and ignore if so. */
   for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
      if (0 == strcmp(o_dll->name, dll_name))
         return NULL;
988 989
   }

990 991 992 993 994 995 996 997 998 999
   /* The file name has no suffix (yet) so that we can try
      both foo.dll and foo.drv

      The documentation for LoadLibrary says:
      	If no file name extension is specified in the lpFileName
      	parameter, the default library extension .dll is
      	appended. However, the file name string can include a trailing
      	point character (.) to indicate that the module name has no
      	extension. */

1000
   buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1001 1002 1003
   sprintf(buf, "%s.DLL", dll_name);
   instance = LoadLibrary(buf);
   if (instance == NULL) {
1004
	 sprintf(buf, "%s.DRV", dll_name);	// KAA: allow loading of drivers (like winspool.drv)
1005 1006
	 instance = LoadLibrary(buf);
	 if (instance == NULL) {
sof's avatar
sof committed
1007
		stgFree(buf);
1008 1009 1010 1011

	    /* LoadLibrary failed; return a ptr to the error msg. */
	    return "addDLL: unknown error";
   	 }
1012
   }
sof's avatar
sof committed
1013
   stgFree(buf);
1014

1015
   /* Add this DLL to the list of DLLs in which to search for symbols. */
1016
   o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1017 1018
   o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
   strcpy(o_dll->name, dll_name);
1019
   o_dll->instance = instance;
1020 1021
   o_dll->next     = opened_dlls;
   opened_dlls     = o_dll;
1022 1023

   return NULL;
1024 1025 1026 1027 1028
#  else
   barf("addDLL: not implemented on this platform");
#  endif
}

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
/* -----------------------------------------------------------------------------
 * insert a stable symbol in the hash table
 */

void
insertStableSymbol(char* obj_name, char* key, StgPtr p)
{
  ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
}


/* -----------------------------------------------------------------------------
 * insert a symbol in the hash table
 */
void
insertSymbol(char* obj_name, char* key, void* data)
{
  ghciInsertStrHashTable(obj_name, symhash, key, data);
}

1049 1050
/* -----------------------------------------------------------------------------
 * lookup a symbol in the hash table
1051
 */
1052 1053 1054
void *
lookupSymbol( char *lbl )
{
1055
    void *val;
1056
    initLinker() ;
1057
    ASSERT(symhash != NULL);
1058 1059 1060
    val = lookupStrHashTable(symhash, lbl);

    if (val == NULL) {
1061
#       if defined(OBJFORMAT_ELF)
1062
#	if defined(x86_64_HOST_ARCH)
1063 1064 1065 1066 1067 1068 1069 1070 1071
	val = dlsym(dl_prog_handle, lbl);
	if (val >= (void *)0x80000000) {
	    void *new_val;
	    new_val = x86_64_high_symbol(lbl, val);
	    IF_DEBUG(linker,debugBelch("lookupSymbol: relocating out of range symbol: %s = %p, now %p\n", lbl, val, new_val));
	    return new_val;
	} else {
	    return val;
	}
1072
#	else
1073
	return dlsym(dl_prog_handle, lbl);
dons's avatar
dons committed
1074
#	endif
1075
#       elif defined(OBJFORMAT_MACHO)
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
#       if HAVE_DLFCN_H
        /* On OS X 10.3 and later, we use dlsym instead of the old legacy
           interface.

           HACK: On OS X, global symbols are prefixed with an underscore.
                 However, dlsym wants us to omit the leading underscore from the
                 symbol name. For now, we simply strip it off here (and ONLY
                 here).
        */
        ASSERT(lbl[0] == '_');
        return dlsym(dl_prog_handle, lbl+1);
#       else
1088 1089 1090 1091 1092 1093
	if(NSIsSymbolNameDefined(lbl)) {
	    NSSymbol symbol = NSLookupAndBindSymbol(lbl);
	    return NSAddressOfSymbol(symbol);
	} else {
	    return NULL;
	}
1094
#       endif /* HAVE_DLFCN_H */
1095
#       elif defined(OBJFORMAT_PEi386)
1096 1097