Linker.c 116 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 14 15 16 17

//  Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h>.
#ifdef __linux__
#define _GNU_SOURCE
#endif

18 19 20 21 22
#include "Rts.h"
#include "RtsFlags.h"
#include "HsFFI.h"
#include "Hash.h"
#include "Linker.h"
23
#include "LinkerInternals.h"
24
#include "RtsUtils.h"
25
#include "Schedule.h"
26
#include "Storage.h"
27

28
#ifdef HAVE_SYS_TYPES_H
29
#include <sys/types.h>
30 31
#endif

32 33 34
#include <stdlib.h>
#include <string.h>

35
#ifdef HAVE_SYS_STAT_H
36
#include <sys/stat.h>
37
#endif
38

39 40 41
#if defined(HAVE_FRAMEWORK_HASKELLSUPPORT)
#include <HaskellSupport/dlfcn.h>
#elif defined(HAVE_DLFCN_H)
42
#include <dlfcn.h>
43
#endif
44

sof's avatar
sof committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#if defined(cygwin32_TARGET_OS)
#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

dons's avatar
dons committed
61
#if defined(ia64_TARGET_ARCH) || defined(openbsd_TARGET_OS)
62 63 64
#define USE_MMAP
#include <fcntl.h>
#include <sys/mman.h>
dons's avatar
dons committed
65 66 67 68 69 70 71

#if defined(openbsd_TARGET_OS) 
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif

72 73
#endif

dons's avatar
dons committed
74
#if defined(linux_TARGET_OS) || defined(solaris2_TARGET_OS) || defined(freebsd_TARGET_OS) || defined(netbsd_TARGET_OS) || defined(openbsd_TARGET_OS)
75
#  define OBJFORMAT_ELF
76
#elif defined(cygwin32_TARGET_OS) || defined (mingw32_TARGET_OS)
77
#  define OBJFORMAT_PEi386
78
#  include <windows.h>
sof's avatar
sof committed
79
#  include <math.h>
80
#elif defined(darwin_TARGET_OS)
81
#  include <mach-o/ppc/reloc.h>
82 83 84 85
#  define OBJFORMAT_MACHO
#  include <mach-o/loader.h>
#  include <mach-o/nlist.h>
#  include <mach-o/reloc.h>
86
#  include <mach-o/dyld.h>
87 88
#endif

89
/* Hash table mapping symbol names to Symbol */
90
static /*Str*/HashTable *symhash;
91

92 93 94
/* List of currently loaded objects */
ObjectCode *objects = NULL;	/* initially empty */

95
#if defined(OBJFORMAT_ELF)
96 97 98
static int ocVerifyImage_ELF    ( ObjectCode* oc );
static int ocGetNames_ELF       ( ObjectCode* oc );
static int ocResolve_ELF        ( ObjectCode* oc );
99 100 101
#if defined(powerpc_TARGET_ARCH)
static int ocAllocateJumpIslands_ELF ( ObjectCode* oc );
#endif
102
#elif defined(OBJFORMAT_PEi386)
103 104 105
static int ocVerifyImage_PEi386 ( ObjectCode* oc );
static int ocGetNames_PEi386    ( ObjectCode* oc );
static int ocResolve_PEi386     ( ObjectCode* oc );
106
#elif defined(OBJFORMAT_MACHO)
107
static int ocAllocateJumpIslands_MachO ( ObjectCode* oc );
108 109 110
static int ocVerifyImage_MachO    ( ObjectCode* oc );
static int ocGetNames_MachO       ( ObjectCode* oc );
static int ocResolve_MachO        ( ObjectCode* oc );
111

112
static void machoInitSymbolsWithoutUnderscore( void );
113 114 115 116 117 118
#endif

/* -----------------------------------------------------------------------------
 * Built-in symbols from the RTS
 */

119 120 121 122 123 124
typedef struct _RtsSymbolVal {
    char   *lbl;
    void   *addr;
} RtsSymbolVal;


125 126 127 128 129 130 131 132 133 134 135
#if !defined(PAR)
#define Maybe_ForeignObj        SymX(mkForeignObjzh_fast)

#define Maybe_Stable_Names      SymX(mkWeakzh_fast)			\
      				SymX(makeStableNamezh_fast)		\
      				SymX(finalizzeWeakzh_fast)
#else
/* These are not available in GUM!!! -- HWL */
#define Maybe_ForeignObj
#define Maybe_Stable_Names
#endif
136 137

#if !defined (mingw32_TARGET_OS)
138
#define RTS_POSIX_ONLY_SYMBOLS                  \
139 140
      SymX(stg_sig_install)			\
      Sym(nocldstop)
sof's avatar
sof committed
141
#endif
142

sof's avatar
sof committed
143 144 145 146
#if defined (cygwin32_TARGET_OS)
#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
147
 * exports; sigh.
sof's avatar
sof committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 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
 */
#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)                               \
225
      SymX(waitpid)
226

sof's avatar
sof committed
227 228 229 230 231 232
#elif !defined(mingw32_TARGET_OS)
#define RTS_MINGW_ONLY_SYMBOLS /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
#else /* defined(mingw32_TARGET_OS) */
#define RTS_POSIX_ONLY_SYMBOLS  /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
233

234 235 236 237
/* Extra syms gen'ed by mingw-2's gcc-3.2: */
#if __GNUC__>=3
#define RTS_MINGW_EXTRA_SYMS                    \
      Sym(_imp____mb_cur_max)                   \
238
      Sym(_imp___pctype)
239 240 241 242
#else
#define RTS_MINGW_EXTRA_SYMS
#endif

243 244
/* These are statically linked from the mingw libraries into the ghc
   executable, so we have to employ this hack. */
245
#define RTS_MINGW_ONLY_SYMBOLS                  \
sof's avatar
sof committed
246 247
      SymX(asyncReadzh_fast)			\
      SymX(asyncWritezh_fast)			\
sof's avatar
sof committed
248
      SymX(asyncDoProczh_fast)			\
249
      SymX(memset)                              \
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      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)                              \
282 283 284
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
285 286 287 288 289 290 291 292 293 294 295 296 297 298
      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(memcpy)                              \
299
      Sym(mktime)                               \
300
      Sym(_imp___timezone)                      \
301
      Sym(_imp___tzname)                        \
302
      Sym(_imp___iob)                           \
303 304 305 306
      Sym(localtime)                            \
      Sym(gmtime)                               \
      Sym(opendir)                              \
      Sym(readdir)                              \
sof's avatar
sof committed
307
      Sym(rewinddir)                            \
308
      RTS_MINGW_EXTRA_SYMS                      \
309
      Sym(closedir)
310
#endif
311

sof's avatar
sof committed
312 313 314 315 316
#ifndef SMP
# define MAIN_CAP_SYM SymX(MainCapability)
#else
# define MAIN_CAP_SYM
#endif
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
#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_0_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

341
#define RTS_SYMBOLS				\
342 343 344
      Maybe_ForeignObj				\
      Maybe_Stable_Names			\
      Sym(StgReturn)				\
345 346
      SymX(stg_enter_info)			\
      SymX(stg_gc_void_info)			\
347 348
      SymX(__stg_gc_enter_1)			\
      SymX(stg_gc_noregs)			\
349
      SymX(stg_gc_unpt_r1_info)			\
350
      SymX(stg_gc_unpt_r1)			\
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
      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)			\
367
      SymX(stg_yield_to_interpreter)		\
368 369 370 371 372 373
      SymX(stg_gen_block)			\
      SymX(stg_block_noregs)			\
      SymX(stg_block_1)				\
      SymX(stg_block_takemvar)			\
      SymX(stg_block_putmvar)			\
      SymX(stg_seq_frame_info)			\
sof's avatar
sof committed
374
      MAIN_CAP_SYM                              \
375 376 377 378 379 380
      SymX(MallocFailHook)			\
      SymX(OnExitHook)				\
      SymX(OutOfHeapHook)			\
      SymX(StackOverflowHook)			\
      SymX(__encodeDouble)			\
      SymX(__encodeFloat)			\
dons's avatar
dons committed
381
      SymX(addDLL)               		\
382 383 384 385 386 387 388 389 390
      SymX(__gmpn_gcd_1)			\
      SymX(__gmpz_cmp)				\
      SymX(__gmpz_cmp_si)			\
      SymX(__gmpz_cmp_ui)			\
      SymX(__gmpz_get_si)			\
      SymX(__gmpz_get_ui)			\
      SymX(__int_encodeDouble)			\
      SymX(__int_encodeFloat)			\
      SymX(andIntegerzh_fast)			\
391
      SymX(barf)				\
392 393
      SymX(blockAsyncExceptionszh_fast)		\
      SymX(catchzh_fast)			\
sof's avatar
sof committed
394
      SymX(closure_flags)                       \
395
      SymX(cmp_thread)				\
sof's avatar
sof committed
396 397
      SymX(cmpIntegerzh_fast)	        	\
      SymX(cmpIntegerIntzh_fast)	      	\
sof's avatar
sof committed
398
      SymX(complementIntegerzh_fast)		\
399 400 401 402 403
      SymX(createAdjustor)			\
      SymX(decodeDoublezh_fast)			\
      SymX(decodeFloatzh_fast)			\
      SymX(defaultsHook)			\
      SymX(delayzh_fast)			\
sof's avatar
sof committed
404 405
      SymX(deRefWeakzh_fast)			\
      SymX(deRefStablePtrzh_fast)		\
406 407 408
      SymX(divExactIntegerzh_fast)		\
      SymX(divModIntegerzh_fast)		\
      SymX(forkzh_fast)				\
409
      SymX(forkProcess)				\
410
      SymX(forkOS_createThread)			\
411
      SymX(freeHaskellFunctionPtr)		\
sof's avatar
sof committed
412
      SymX(freeStablePtr)		        \
413
      SymX(gcdIntegerzh_fast)			\
sof's avatar
sof committed
414 415
      SymX(gcdIntegerIntzh_fast)		\
      SymX(gcdIntzh_fast)			\
416
      SymX(genSymZh)				\
417 418
      SymX(getProgArgv)				\
      SymX(getStablePtr)			\
dons's avatar
dons committed
419
      SymX(initLinker)  			\
420
      SymX(int2Integerzh_fast)			\
sof's avatar
sof committed
421 422
      SymX(integer2Intzh_fast)			\
      SymX(integer2Wordzh_fast)			\
423
      SymX(isCurrentThreadBoundzh_fast)		\
424 425 426 427
      SymX(isDoubleDenormalized)		\
      SymX(isDoubleInfinite)			\
      SymX(isDoubleNaN)				\
      SymX(isDoubleNegativeZero)		\
sof's avatar
sof committed
428
      SymX(isEmptyMVarzh_fast)			\
429 430 431 432 433
      SymX(isFloatDenormalized)			\
      SymX(isFloatInfinite)			\
      SymX(isFloatNaN)				\
      SymX(isFloatNegativeZero)			\
      SymX(killThreadzh_fast)			\
dons's avatar
dons committed
434 435
      SymX(loadObj)          			\
      SymX(lookupSymbol)     			\
sof's avatar
sof committed
436
      SymX(makeStablePtrzh_fast)		\
437 438
      SymX(minusIntegerzh_fast)			\
      SymX(mkApUpd0zh_fast)			\
sof's avatar
sof committed
439
      SymX(myThreadIdzh_fast)			\
440
      SymX(labelThreadzh_fast)                  \
441 442 443
      SymX(newArrayzh_fast)			\
      SymX(newBCOzh_fast)			\
      SymX(newByteArrayzh_fast)			\
444
      SymX_redirect(newCAF, newDynCAF)		\
445 446
      SymX(newMVarzh_fast)			\
      SymX(newMutVarzh_fast)			\
447
      SymX(atomicModifyMutVarzh_fast)		\
448 449 450
      SymX(newPinnedByteArrayzh_fast)		\
      SymX(orIntegerzh_fast)			\
      SymX(performGC)				\
451
      SymX(performMajorGC)			\
452 453 454 455 456 457 458
      SymX(plusIntegerzh_fast)			\
      SymX(prog_argc)				\
      SymX(prog_argv)				\
      SymX(putMVarzh_fast)			\
      SymX(quotIntegerzh_fast)			\
      SymX(quotRemIntegerzh_fast)		\
      SymX(raisezh_fast)			\
459
      SymX(raiseIOzh_fast)			\
460 461 462
      SymX(remIntegerzh_fast)			\
      SymX(resetNonBlockingFd)			\
      SymX(resumeThread)			\
dons's avatar
dons committed
463
      SymX(resolveObjs)                         \
464 465 466 467 468
      SymX(rts_apply)				\
      SymX(rts_checkSchedStatus)		\
      SymX(rts_eval)				\
      SymX(rts_evalIO)				\
      SymX(rts_evalLazyIO)			\
469
      SymX(rts_evalStableIO)			\
470 471 472 473 474 475 476 477
      SymX(rts_eval_)				\
      SymX(rts_getBool)				\
      SymX(rts_getChar)				\
      SymX(rts_getDouble)			\
      SymX(rts_getFloat)			\
      SymX(rts_getInt)				\
      SymX(rts_getInt32)			\
      SymX(rts_getPtr)				\
478
      SymX(rts_getFunPtr)			\
479
      SymX(rts_getStablePtr)			\
480
      SymX(rts_getThreadId)			\
481 482
      SymX(rts_getWord)				\
      SymX(rts_getWord32)			\
483
      SymX(rts_lock)				\
484 485 486 487 488 489 490 491 492 493
      SymX(rts_mkBool)				\
      SymX(rts_mkChar)				\
      SymX(rts_mkDouble)			\
      SymX(rts_mkFloat)				\
      SymX(rts_mkInt)				\
      SymX(rts_mkInt16)				\
      SymX(rts_mkInt32)				\
      SymX(rts_mkInt64)				\
      SymX(rts_mkInt8)				\
      SymX(rts_mkPtr)				\
494
      SymX(rts_mkFunPtr)			\
495 496 497 498 499 500 501
      SymX(rts_mkStablePtr)			\
      SymX(rts_mkString)			\
      SymX(rts_mkWord)				\
      SymX(rts_mkWord16)			\
      SymX(rts_mkWord32)			\
      SymX(rts_mkWord64)			\
      SymX(rts_mkWord8)				\
502
      SymX(rts_unlock)				\
503
      SymX(rtsSupportsBoundThreads)		\
504
      SymX(run_queue_hd)			\
505 506
      SymX(__hscore_get_saved_termios)		\
      SymX(__hscore_set_saved_termios)		\
507
      SymX(setProgArgv)				\
508 509
      SymX(startupHaskell)			\
      SymX(shutdownHaskell)			\
510 511 512 513
      SymX(shutdownHaskellAndExit)		\
      SymX(stable_ptr_table)			\
      SymX(stackOverflow)			\
      SymX(stg_CAF_BLACKHOLE_info)		\
514 515
      SymX(stg_BLACKHOLE_BQ_info)		\
      SymX(awakenBlockedQueue)			\
516 517 518 519 520 521
      SymX(stg_CHARLIKE_closure)		\
      SymX(stg_EMPTY_MVAR_info)			\
      SymX(stg_IND_STATIC_info)			\
      SymX(stg_INTLIKE_closure)			\
      SymX(stg_MUT_ARR_PTRS_FROZEN_info)	\
      SymX(stg_WEAK_info)                       \
522
      SymX(stg_ap_0_info)			\
523 524 525 526 527 528 529 530 531 532
      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)			\
533
      SymX(stg_ap_pppv_info)			\
534 535 536
      SymX(stg_ap_pppp_info)			\
      SymX(stg_ap_ppppp_info)			\
      SymX(stg_ap_pppppp_info)			\
537
      SymX(stg_ap_1_upd_info)			\
538 539 540 541 542 543
      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)			\
544
      SymX(stg_exit)				\
545
      SymX(stg_sel_0_upd_info)			\
546 547 548 549 550 551
      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)			\
552 553 554 555 556 557 558 559 560
      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)			\
561 562
      SymX(stg_upd_frame_info)			\
      SymX(suspendThread)			\
563
      SymX(takeMVarzh_fast)			\
564
      SymX(timesIntegerzh_fast)			\
565
      SymX(tryPutMVarzh_fast)			\
566 567
      SymX(tryTakeMVarzh_fast)			\
      SymX(unblockAsyncExceptionszh_fast)	\
dons's avatar
dons committed
568
      SymX(unloadObj)                           \
569
      SymX(unsafeThawArrayzh_fast)		\
570 571
      SymX(waitReadzh_fast)			\
      SymX(waitWritezh_fast)			\
572 573
      SymX(word2Integerzh_fast)			\
      SymX(xorIntegerzh_fast)			\
574
      SymX(yieldzh_fast)
575

576
#ifdef SUPPORT_LONG_LONGS
577
#define RTS_LONG_LONG_SYMS			\
578 579
      SymX(int64ToIntegerzh_fast)		\
      SymX(word64ToIntegerzh_fast)
580 581 582 583
#else
#define RTS_LONG_LONG_SYMS /* nothing */
#endif

584 585 586
// 64-bit support functions in libgcc.a
#if defined(__GNUC__) && SIZEOF_VOID_P <= 4
#define RTS_LIBGCC_SYMBOLS			\
587 588 589
      Sym(__divdi3)                             \
      Sym(__udivdi3)                            \
      Sym(__moddi3)                             \
590 591 592 593 594
      Sym(__umoddi3)				\
      Sym(__ashldi3)				\
      Sym(__ashrdi3)				\
      Sym(__lshrdi3)				\
      Sym(__eprintf)
595 596 597 598 599 600 601 602
#elif defined(ia64_TARGET_ARCH)
#define RTS_LIBGCC_SYMBOLS			\
      Sym(__divdi3)				\
      Sym(__udivdi3)                            \
      Sym(__moddi3)				\
      Sym(__umoddi3)				\
      Sym(__divsf3)				\
      Sym(__divdf3)
603 604 605 606
#else
#define RTS_LIBGCC_SYMBOLS
#endif

607
#ifdef darwin_TARGET_OS
608 609 610 611 612 613
      // 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)
614
#endif
615 616

/* entirely bogus claims about types of these symbols */
617
#define Sym(vvv)  extern void vvv(void);
618
#define SymX(vvv) /**/
619
#define SymX_redirect(vvv,xxx) /**/
620
RTS_SYMBOLS
621
RTS_RET_SYMBOLS
622
RTS_LONG_LONG_SYMS
623
RTS_POSIX_ONLY_SYMBOLS
624
RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
625
RTS_CYGWIN_ONLY_SYMBOLS
626
RTS_LIBGCC_SYMBOLS
627 628
#undef Sym
#undef SymX
629
#undef SymX_redirect
630 631 632 633 634 635 636 637 638 639 640

#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)

641 642 643 644 645 646
// 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)) },

647
static RtsSymbolVal rtsSyms[] = {
648
      RTS_SYMBOLS
649
      RTS_RET_SYMBOLS
650
      RTS_LONG_LONG_SYMS
651
      RTS_POSIX_ONLY_SYMBOLS
652
      RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
653
      RTS_CYGWIN_ONLY_SYMBOLS
654
      RTS_LIBGCC_SYMBOLS
655 656 657
      { 0, 0 } /* sentinel */
};

658 659 660 661 662
/* -----------------------------------------------------------------------------
 * Insert symbols into hash tables, checking for duplicates.
 */
static void ghciInsertStrHashTable ( char* obj_name,
                                     HashTable *table,
663
                                     char* key,
664 665 666 667 668 669 670 671
                                     void *data
				   )
{
   if (lookupHashTable(table, (StgWord)key) == NULL)
   {
      insertStrHashTable(table, (StgWord)key, data);
      return;
   }
672
   debugBelch(
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
      "\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);
}


692 693 694
/* -----------------------------------------------------------------------------
 * initialize the object linker
 */
695 696 697 698


static int linker_init_done = 0 ;

699
#if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
700
static void *dl_prog_handle;
701
#endif
702

dons's avatar
dons committed
703 704 705 706 707
/* dlopen(NULL,..) doesn't work so we grab libc explicitly */
#if defined(openbsd_TARGET_OS)
static void *dl_libc_handle;
#endif

708 709 710
void
initLinker( void )
{
711
    RtsSymbolVal *sym;
712

713 714 715 716 717 718 719
    /* 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;
    }

720 721 722 723
    symhash = allocStrHashTable();

    /* populate the symbol table with stuff from the RTS */
    for (sym = rtsSyms; sym->lbl != NULL; sym++) {
724 725
	ghciInsertStrHashTable("(GHCi built-in symbols)",
                               symhash, sym->lbl, sym->addr);
726
    }
727 728 729 730
#   if defined(OBJFORMAT_MACHO)
    machoInitSymbolsWithoutUnderscore();
#   endif

731
#   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
732
#   if defined(RTLD_DEFAULT)
733 734
    dl_prog_handle = RTLD_DEFAULT;
#   else
735
    dl_prog_handle = dlopen(NULL, RTLD_LAZY);
dons's avatar
dons committed
736 737 738
#   if defined(openbsd_TARGET_OS)
    dl_libc_handle = dlopen("libc.so", RTLD_LAZY);
#   endif
739
#   endif // RTLD_DEFAULT
740
#   endif
741 742
}

743
/* -----------------------------------------------------------------------------
744 745 746
 *                  Loading DLL or .so dynamic libraries
 * -----------------------------------------------------------------------------
 *
747 748 749 750
 * 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
751 752
 * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
 *
753
 * In the PEi386 case, open the DLLs and put handles to them in a
754
 * linked list.  When looking for a symbol, try all handles in the
755 756 757 758 759
 * 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.
760
 *
761
 */
762 763 764 765 766 767

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

typedef
   struct _OpenedDLL {
768
      char*              name;
769 770
      struct _OpenedDLL* next;
      HINSTANCE instance;
771
   }
772 773 774 775 776 777
   OpenedDLL;

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

778 779
char *
addDLL( char *dll_name )
780
{
781
#  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
782
   /* ------------------- ELF DLL loader ------------------- */
783
   void *hdl;
784
   char *errmsg;
785

786 787
   initLinker();

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

790 791 792 793 794 795 796 797
   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;
   }
798 799
   /*NOTREACHED*/

800
#  elif defined(OBJFORMAT_PEi386)
801
   /* ------------------- Win32 DLL loader ------------------- */
802

803
   char*      buf;
804
   OpenedDLL* o_dll;
805
   HINSTANCE  instance;
806

807 808
   initLinker();

809
   /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
810 811 812 813 814

   /* 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;
815 816
   }

817 818 819 820 821 822 823 824 825 826
   /* 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. */

827
   buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
828 829 830
   sprintf(buf, "%s.DLL", dll_name);
   instance = LoadLibrary(buf);
   if (instance == NULL) {
831
	 sprintf(buf, "%s.DRV", dll_name);	// KAA: allow loading of drivers (like winspool.drv)
832 833
	 instance = LoadLibrary(buf);
	 if (instance == NULL) {
sof's avatar
sof committed
834
		stgFree(buf);
835 836 837 838

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

842
   /* Add this DLL to the list of DLLs in which to search for symbols. */
843
   o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
844 845
   o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
   strcpy(o_dll->name, dll_name);
846
   o_dll->instance = instance;
847 848
   o_dll->next     = opened_dlls;
   opened_dlls     = o_dll;
849 850

   return NULL;
851 852 853 854 855
#  else
   barf("addDLL: not implemented on this platform");
#  endif
}

856 857
/* -----------------------------------------------------------------------------
 * lookup a symbol in the hash table
858
 */
859 860 861
void *
lookupSymbol( char *lbl )
{
862
    void *val;
863
    initLinker() ;
864
    ASSERT(symhash != NULL);
865 866 867
    val = lookupStrHashTable(symhash, lbl);

    if (val == NULL) {
868
#       if defined(OBJFORMAT_ELF)
dons's avatar
dons committed
869 870 871 872
#	if defined(openbsd_TARGET_OS)
	val = dlsym(dl_prog_handle, lbl);
	return (val != NULL) ? val : dlsym(dl_libc_handle,lbl);
#	else /* not openbsd */
873
	return dlsym(dl_prog_handle, lbl);
dons's avatar
dons committed
874
#	endif
875 876 877 878 879 880 881
#       elif defined(OBJFORMAT_MACHO)
	if(NSIsSymbolNameDefined(lbl)) {
	    NSSymbol symbol = NSLookupAndBindSymbol(lbl);
	    return NSAddressOfSymbol(symbol);
	} else {
	    return NULL;
	}
882
#       elif defined(OBJFORMAT_PEi386)
883 884 885
        OpenedDLL* o_dll;
        void* sym;
        for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
886
	  /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
887 888 889 890 891 892 893
           if (lbl[0] == '_') {
              /* HACK: if the name has an initial underscore, try stripping
                 it off & look that up first. I've yet to verify whether there's
                 a Rule that governs whether an initial '_' *should always* be
                 stripped off when mapping from import lib name to the DLL name.
              */
              sym = GetProcAddress(o_dll->instance, (lbl+1));
sof's avatar
sof committed
894
              if (sym != NULL) {
895
		/*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
sof's avatar
sof committed
896
		return sym;
897
	      }
898
           }
899
           sym = GetProcAddress(o_dll->instance, lbl);
sof's avatar
sof committed
900
           if (sym != NULL) {
901
	     /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
sof's avatar
sof committed
902 903
	     return sym;
	   }
904
        }
905
        return NULL;
ken's avatar
ken committed
906 907 908
#       else
        ASSERT(2+2 == 5);
        return NULL;
909
#       endif
910
    } else {
911
	return val;
912 913 914
    }
}

915
static
916
__attribute((unused))
917 918 919
void *
lookupLocalSymbol( ObjectCode* oc, char *lbl )
{
920
    void *val;
921
    initLinker() ;
922 923 924 925 926
    val = lookupStrHashTable(oc->lochash, lbl);

    if (val == NULL) {
        return NULL;
    } else {
927
	return val;
928 929 930 931
    }
}


932 933 934 935 936 937 938 939 940 941 942 943 944 945
/* -----------------------------------------------------------------------------
 * Debugging aid: look in GHCi's object symbol tables for symbols
 * within DELTA bytes of the specified address, and show their names.
 */
#ifdef DEBUG
void ghci_enquire ( char* addr );

void ghci_enquire ( char* addr )
{
   int   i;
   char* sym;
   char* a;
   const int DELTA = 64;
   ObjectCode* oc;
946 947 948

   initLinker();

949 950 951 952
   for (oc = objects; oc; oc = oc->next) {
      for (i = 0; i < oc->n_symbols; i++) {
         sym = oc->symbols[i];
         if (sym == NULL) continue;
953
         // debugBelch("enquire %p %p\n", sym, oc->lochash);
954
         a = NULL;
955
         if (oc->lochash != NULL) {
956
            a = lookupStrHashTable(oc->lochash, sym);
957 958
	 }
         if (a == NULL) {
959
            a = lookupStrHashTable(symhash, sym);
960
	 }
961
         if (a == NULL) {
962
	     // debugBelch("ghci_enquire: can't find %s\n", sym);
963
         }
964
         else if (addr-DELTA <= a && a <= addr+DELTA) {
965
            debugBelch("%p + %3d  ==  `%s'\n", addr, a - addr, sym);
966 967 968 969 970 971
         }
      }
   }
}
#endif

972 973 974
#ifdef ia64_TARGET_ARCH
static unsigned int PLTSize(void);
#endif
975

976 977 978 979 980 981 982 983 984 985 986
/* -----------------------------------------------------------------------------
 * Load an obj (populate the global symbol table, but don't resolve yet)
 *
 * Returns: 1 if ok, 0 on error.
 */
HsInt
loadObj( char *path )
{
   ObjectCode* oc;
   struct stat st;
   int r, n;
987 988
#ifdef USE_MMAP
   int fd, pagesize;
989
   void *map_addr = NULL;
990
#else
991
   FILE *f;
992
#endif
993

994 995
   initLinker();

996
   /* debugBelch("loadObj %s\n", path ); */
997

dons's avatar
dons committed
998 999
   /* Check that we haven't already loaded this object. 
      Ignore requests to load multiple times */
1000
   {
1001
       ObjectCode *o;
1002 1003
       int is_dup = 0;
       for (o = objects; o; o = o->next) {
dons's avatar
dons committed
1004
          if (0 == strcmp(o->fileName, path)) {
1005
             is_dup = 1;
dons's avatar
dons committed
1006 1007
             break; /* don't need to search further */
          }
1008 1009
       }
       if (is_dup) {
1010
          IF_DEBUG(linker, debugBelch(
1011 1012 1013
            "GHCi runtime linker: warning: looks like you're trying to load the\n"
            "same object file twice:\n"
            "   %s\n"
dons's avatar
dons committed
1014 1015 1016
            "GHCi will ignore this, but be warned.\n"
            , path));
          return 1; /* success */
1017
       }
1018 1019 1020 1021
   }

   oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");

1022
#  if defined(OBJFORMAT_ELF)
1023
   oc->formatName = "ELF";
1024
#  elif defined(OBJFORMAT_PEi386)
1025
   oc->formatName = "PEi386";
1026 1027
#  elif defined(OBJFORMAT_MACHO)
   oc->formatName = "Mach-O";