Linker.c 138 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
/* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and 
   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 "Storage.h"
29
#include "Sparks.h"
ei@vuokko.info's avatar
ei@vuokko.info committed
30
#include "RtsTypeable.h"
31

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

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

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

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

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

63
#if defined(ia64_HOST_ARCH) || defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
64 65 66
#define USE_MMAP
#include <fcntl.h>
#include <sys/mman.h>
67

68
#if defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
69 70 71 72 73
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif

74 75
#endif

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

93
/* Hash table mapping symbol names to Symbol */
94
static /*Str*/HashTable *symhash;
95

96 97 98 99 100 101 102 103 104 105 106
typedef struct {
  void *addr;
} rootEntry;

/* Hash table mapping symbol names to StgStablePtr */
static /*Str*/HashTable *stablehash;
rootEntry *root_ptr_table = NULL;
static rootEntry *root_ptr_free = NULL;

static unsigned int RPT_size = 0;

107 108 109
/* List of currently loaded objects */
ObjectCode *objects = NULL;	/* initially empty */

110
#if defined(OBJFORMAT_ELF)
111 112 113
static int ocVerifyImage_ELF    ( ObjectCode* oc );
static int ocGetNames_ELF       ( ObjectCode* oc );
static int ocResolve_ELF        ( ObjectCode* oc );
114
#if defined(powerpc_HOST_ARCH)
115 116
static int ocAllocateJumpIslands_ELF ( ObjectCode* oc );
#endif
117
#elif defined(OBJFORMAT_PEi386)
118 119 120
static int ocVerifyImage_PEi386 ( ObjectCode* oc );
static int ocGetNames_PEi386    ( ObjectCode* oc );
static int ocResolve_PEi386     ( ObjectCode* oc );
121 122 123 124
#elif defined(OBJFORMAT_MACHO)
static int ocVerifyImage_MachO    ( ObjectCode* oc );
static int ocGetNames_MachO       ( ObjectCode* oc );
static int ocResolve_MachO        ( ObjectCode* oc );
125

126
static int machoGetMisalignment( FILE * );
127 128
#ifdef powerpc_HOST_ARCH
static int ocAllocateJumpIslands_MachO ( ObjectCode* oc );
129
static void machoInitSymbolsWithoutUnderscore( void );
130
#endif
131
#endif
132

133 134 135 136
#if defined(x86_64_HOST_ARCH)
static void*x86_64_high_symbol( char *lbl, void *addr );
#endif

137 138 139 140
/* -----------------------------------------------------------------------------
 * Built-in symbols from the RTS
 */

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


147 148 149 150 151 152 153 154
#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
155

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

163
#if defined (cygwin32_HOST_OS)
sof's avatar
sof committed
164 165 166
#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
167
 * exports; sigh.
sof's avatar
sof committed
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 243 244
 */
#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)                               \
245
      SymX(waitpid)
246

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

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

263 264
/* These are statically linked from the mingw libraries into the ghc
   executable, so we have to employ this hack. */
265
#define RTS_MINGW_ONLY_SYMBOLS                  \
sof's avatar
sof committed
266 267
      SymX(asyncReadzh_fast)			\
      SymX(asyncWritezh_fast)			\
sof's avatar
sof committed
268
      SymX(asyncDoProczh_fast)			\
269
      SymX(memset)                              \
270 271 272 273 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
      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)                              \
302 303 304
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
305 306 307 308 309 310 311 312 313 314 315 316 317
      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)                                \
318 319 320 321 322 323 324 325 326 327 328 329 330
      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)                                \
331
      SymX(memcpy)                              \
sof's avatar
sof committed
332 333
      SymX(rts_InstallConsoleEvent)             \
      SymX(rts_ConsoleHandlerDone)              \
334
      Sym(mktime)                               \
335
      Sym(_imp___timezone)                      \
336
      Sym(_imp___tzname)                        \
337
      Sym(_imp__tzname)                         \
338
      Sym(_imp___iob)                           \
sof's avatar
sof committed
339
      Sym(_imp___osver)                         \
340 341 342 343
      Sym(localtime)                            \
      Sym(gmtime)                               \
      Sym(opendir)                              \
      Sym(readdir)                              \
sof's avatar
sof committed
344
      Sym(rewinddir)                            \
345
      RTS_MINGW_EXTRA_SYMS                      \
346
      Sym(closedir)
347
#endif
348

349 350 351 352 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
#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
399 400 401 402 403
#ifndef SMP
# define MAIN_CAP_SYM SymX(MainCapability)
#else
# define MAIN_CAP_SYM
#endif
404

sof's avatar
sof committed
405 406 407 408 409 410 411
#if !defined(mingw32_HOST_OS)
#define RTS_USER_SIGNALS_SYMBOLS \
   SymX(setIOManagerPipe)
#else
#define RTS_USER_SIGNALS_SYMBOLS /* nothing */
#endif

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
#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

434
#define RTS_SYMBOLS				\
435 436
      Maybe_Stable_Names			\
      Sym(StgReturn)				\
437 438
      SymX(stg_enter_info)			\
      SymX(stg_gc_void_info)			\
439 440
      SymX(__stg_gc_enter_1)			\
      SymX(stg_gc_noregs)			\
441
      SymX(stg_gc_unpt_r1_info)			\
442
      SymX(stg_gc_unpt_r1)			\
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
      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)			\
459
      SymX(stg_yield_to_interpreter)		\
460 461 462 463 464 465
      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
466
      MAIN_CAP_SYM                              \
467 468 469 470 471 472
      SymX(MallocFailHook)			\
      SymX(OnExitHook)				\
      SymX(OutOfHeapHook)			\
      SymX(StackOverflowHook)			\
      SymX(__encodeDouble)			\
      SymX(__encodeFloat)			\
473
      SymX(addDLL)               		\
474 475 476 477 478 479 480 481 482
      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)			\
483
      SymX(atomicallyzh_fast)			\
484
      SymX(barf)				\
485 486
      SymX(debugBelch)				\
      SymX(errorBelch)				\
487 488
      SymX(blockAsyncExceptionszh_fast)		\
      SymX(catchzh_fast)			\
489 490
      SymX(catchRetryzh_fast)			\
      SymX(catchSTMzh_fast)			\
tharris@microsoft.com's avatar
tharris@microsoft.com committed
491
      SymX(checkzh_fast)                        \
sof's avatar
sof committed
492
      SymX(closure_flags)                       \
493
      SymX(cmp_thread)				\
sof's avatar
sof committed
494 495
      SymX(cmpIntegerzh_fast)	        	\
      SymX(cmpIntegerIntzh_fast)	      	\
sof's avatar
sof committed
496
      SymX(complementIntegerzh_fast)		\
497 498 499 500 501
      SymX(createAdjustor)			\
      SymX(decodeDoublezh_fast)			\
      SymX(decodeFloatzh_fast)			\
      SymX(defaultsHook)			\
      SymX(delayzh_fast)			\
sof's avatar
sof committed
502 503
      SymX(deRefWeakzh_fast)			\
      SymX(deRefStablePtrzh_fast)		\
504
      SymX(dirty_MUT_VAR)			\
505 506 507
      SymX(divExactIntegerzh_fast)		\
      SymX(divModIntegerzh_fast)		\
      SymX(forkzh_fast)				\
Simon Marlow's avatar
Simon Marlow committed
508
      SymX(forkOnzh_fast)			\
509
      SymX(forkProcess)				\
510
      SymX(forkOS_createThread)			\
511
      SymX(freeHaskellFunctionPtr)		\
sof's avatar
sof committed
512
      SymX(freeStablePtr)		        \
ei@vuokko.info's avatar
ei@vuokko.info committed
513
      SymX(getOrSetTypeableStore)		\
514
      SymX(gcdIntegerzh_fast)			\
sof's avatar
sof committed
515 516
      SymX(gcdIntegerIntzh_fast)		\
      SymX(gcdIntzh_fast)			\
517
      SymX(genSymZh)				\
518
      SymX(genericRaise)			\
519 520
      SymX(getProgArgv)				\
      SymX(getStablePtr)			\
521 522 523 524 525 526 527 528
      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)			\
      SymX(initLinker)				\
529
      SymX(int2Integerzh_fast)			\
sof's avatar
sof committed
530 531
      SymX(integer2Intzh_fast)			\
      SymX(integer2Wordzh_fast)			\
532
      SymX(isCurrentThreadBoundzh_fast)		\
533 534 535 536
      SymX(isDoubleDenormalized)		\
      SymX(isDoubleInfinite)			\
      SymX(isDoubleNaN)				\
      SymX(isDoubleNegativeZero)		\
sof's avatar
sof committed
537
      SymX(isEmptyMVarzh_fast)			\
538 539 540 541 542
      SymX(isFloatDenormalized)			\
      SymX(isFloatInfinite)			\
      SymX(isFloatNaN)				\
      SymX(isFloatNegativeZero)			\
      SymX(killThreadzh_fast)			\
543
      SymX(loadObj)          			\
544 545
      SymX(insertStableSymbol) 			\
      SymX(insertSymbol)     			\
546
      SymX(lookupSymbol)     			\
sof's avatar
sof committed
547
      SymX(makeStablePtrzh_fast)		\
548 549
      SymX(minusIntegerzh_fast)			\
      SymX(mkApUpd0zh_fast)			\
sof's avatar
sof committed
550
      SymX(myThreadIdzh_fast)			\
551
      SymX(labelThreadzh_fast)                  \
552 553 554
      SymX(newArrayzh_fast)			\
      SymX(newBCOzh_fast)			\
      SymX(newByteArrayzh_fast)			\
555
      SymX_redirect(newCAF, newDynCAF)		\
556 557
      SymX(newMVarzh_fast)			\
      SymX(newMutVarzh_fast)			\
558
      SymX(newTVarzh_fast)			\
559
      SymX(atomicModifyMutVarzh_fast)		\
560
      SymX(newPinnedByteArrayzh_fast)		\
561
      SymX(newSpark)				\
562 563
      SymX(orIntegerzh_fast)			\
      SymX(performGC)				\
564
      SymX(performMajorGC)			\
565 566 567 568 569 570 571
      SymX(plusIntegerzh_fast)			\
      SymX(prog_argc)				\
      SymX(prog_argv)				\
      SymX(putMVarzh_fast)			\
      SymX(quotIntegerzh_fast)			\
      SymX(quotRemIntegerzh_fast)		\
      SymX(raisezh_fast)			\
572
      SymX(raiseIOzh_fast)			\
573
      SymX(readTVarzh_fast)			\
574 575 576
      SymX(remIntegerzh_fast)			\
      SymX(resetNonBlockingFd)			\
      SymX(resumeThread)			\
577
      SymX(resolveObjs)                         \
578
      SymX(retryzh_fast)                        \
579 580 581 582 583
      SymX(rts_apply)				\
      SymX(rts_checkSchedStatus)		\
      SymX(rts_eval)				\
      SymX(rts_evalIO)				\
      SymX(rts_evalLazyIO)			\
584
      SymX(rts_evalStableIO)			\
585 586 587 588 589 590 591 592
      SymX(rts_eval_)				\
      SymX(rts_getBool)				\
      SymX(rts_getChar)				\
      SymX(rts_getDouble)			\
      SymX(rts_getFloat)			\
      SymX(rts_getInt)				\
      SymX(rts_getInt32)			\
      SymX(rts_getPtr)				\
593
      SymX(rts_getFunPtr)			\
594
      SymX(rts_getStablePtr)			\
595
      SymX(rts_getThreadId)			\
596 597
      SymX(rts_getWord)				\
      SymX(rts_getWord32)			\
598
      SymX(rts_lock)				\
599 600 601 602 603 604 605 606 607 608
      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)				\
609
      SymX(rts_mkFunPtr)			\
610 611 612 613 614 615 616
      SymX(rts_mkStablePtr)			\
      SymX(rts_mkString)			\
      SymX(rts_mkWord)				\
      SymX(rts_mkWord16)			\
      SymX(rts_mkWord32)			\
      SymX(rts_mkWord64)			\
      SymX(rts_mkWord8)				\
617
      SymX(rts_unlock)				\
618
      SymX(rtsSupportsBoundThreads)		\
619 620
      SymX(__hscore_get_saved_termios)		\
      SymX(__hscore_set_saved_termios)		\
621
      SymX(setProgArgv)				\
622 623
      SymX(startupHaskell)			\
      SymX(shutdownHaskell)			\
624 625 626 627
      SymX(shutdownHaskellAndExit)		\
      SymX(stable_ptr_table)			\
      SymX(stackOverflow)			\
      SymX(stg_CAF_BLACKHOLE_info)		\
628
      SymX(awakenBlockedQueue)			\
629 630 631 632
      SymX(stg_CHARLIKE_closure)		\
      SymX(stg_EMPTY_MVAR_info)			\
      SymX(stg_IND_STATIC_info)			\
      SymX(stg_INTLIKE_closure)			\
633
      SymX(stg_MUT_ARR_PTRS_DIRTY_info)		\
634
      SymX(stg_MUT_ARR_PTRS_FROZEN_info)	\
635
      SymX(stg_MUT_ARR_PTRS_FROZEN0_info)	\
636
      SymX(stg_WEAK_info)                       \
637 638 639 640 641 642 643 644 645 646
      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)			\
647
      SymX(stg_ap_pppv_info)			\
648 649 650
      SymX(stg_ap_pppp_info)			\
      SymX(stg_ap_ppppp_info)			\
      SymX(stg_ap_pppppp_info)			\
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
      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)			\
666
      SymX(stg_ap_1_upd_info)			\
667 668 669 670 671 672
      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)			\
673
      SymX(stg_exit)				\
674
      SymX(stg_sel_0_upd_info)			\
675 676 677 678 679 680
      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)			\
681 682 683 684 685 686 687 688 689
      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)			\
690 691
      SymX(stg_upd_frame_info)			\
      SymX(suspendThread)			\
692
      SymX(takeMVarzh_fast)			\
693
      SymX(timesIntegerzh_fast)			\
694
      SymX(tryPutMVarzh_fast)			\
695 696
      SymX(tryTakeMVarzh_fast)			\
      SymX(unblockAsyncExceptionszh_fast)	\
697
      SymX(unloadObj)                           \
698
      SymX(unsafeThawArrayzh_fast)		\
699 700
      SymX(waitReadzh_fast)			\
      SymX(waitWritezh_fast)			\
701
      SymX(word2Integerzh_fast)			\
702
      SymX(writeTVarzh_fast)			\
703
      SymX(xorIntegerzh_fast)			\
sof's avatar
sof committed
704
      SymX(yieldzh_fast)                        \
705 706 707 708 709 710 711 712 713
      SymX(stg_interp_constr_entry)             \
      SymX(stg_interp_constr1_entry)            \
      SymX(stg_interp_constr2_entry)            \
      SymX(stg_interp_constr3_entry)            \
      SymX(stg_interp_constr4_entry)            \
      SymX(stg_interp_constr5_entry)            \
      SymX(stg_interp_constr6_entry)            \
      SymX(stg_interp_constr7_entry)            \
      SymX(stg_interp_constr8_entry)            \
714 715
      SymX(allocateExec)	                \
      SymX(freeExec)		                \
716 717 718
      SymX(getAllocations)                      \
      SymX(revertCAFs)                          \
      SymX(RtsFlags)                            \
sof's avatar
sof committed
719
      RTS_USER_SIGNALS_SYMBOLS
720

721
#ifdef SUPPORT_LONG_LONGS
722
#define RTS_LONG_LONG_SYMS			\
723 724
      SymX(int64ToIntegerzh_fast)		\
      SymX(word64ToIntegerzh_fast)
725 726 727 728
#else
#define RTS_LONG_LONG_SYMS /* nothing */
#endif

729 730 731
// 64-bit support functions in libgcc.a
#if defined(__GNUC__) && SIZEOF_VOID_P <= 4
#define RTS_LIBGCC_SYMBOLS			\
732 733 734
      Sym(__divdi3)                             \
      Sym(__udivdi3)                            \
      Sym(__moddi3)                             \
735
      Sym(__umoddi3)				\
736
      Sym(__muldi3)				\
737 738 739 740
      Sym(__ashldi3)				\
      Sym(__ashrdi3)				\
      Sym(__lshrdi3)				\
      Sym(__eprintf)
741
#elif defined(ia64_HOST_ARCH)
742 743 744 745 746 747 748
#define RTS_LIBGCC_SYMBOLS			\
      Sym(__divdi3)				\
      Sym(__udivdi3)                            \
      Sym(__moddi3)				\
      Sym(__umoddi3)				\
      Sym(__divsf3)				\
      Sym(__divdf3)
749 750 751 752
#else
#define RTS_LIBGCC_SYMBOLS
#endif

753
#if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
754 755 756 757 758 759
      // 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)
760
#endif
761 762

/* entirely bogus claims about types of these symbols */
763
#define Sym(vvv)  extern void vvv(void);
764
#define SymX(vvv) /**/
765
#define SymX_redirect(vvv,xxx) /**/
766
RTS_SYMBOLS
767
RTS_RET_SYMBOLS
768
RTS_LONG_LONG_SYMS
769
RTS_POSIX_ONLY_SYMBOLS
770
RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
771
RTS_CYGWIN_ONLY_SYMBOLS
772
RTS_DARWIN_ONLY_SYMBOLS
773
RTS_LIBGCC_SYMBOLS
774 775
#undef Sym
#undef SymX
776
#undef SymX_redirect
777 778 779 780 781 782 783 784 785 786 787

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

788 789 790 791 792 793
// 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)) },

794
static RtsSymbolVal rtsSyms[] = {
795
      RTS_SYMBOLS
796
      RTS_RET_SYMBOLS
797
      RTS_LONG_LONG_SYMS
798
      RTS_POSIX_ONLY_SYMBOLS
799
      RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
800
      RTS_CYGWIN_ONLY_SYMBOLS
801
      RTS_LIBGCC_SYMBOLS
802 803 804 805
#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.
806
      { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
807
#endif
808 809 810
      { 0, 0 } /* sentinel */
};

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

/* -----------------------------------------------------------------------------
 * Utilities for handling root pointers.
 * -------------------------------------------------------------------------- */


#define INIT_RPT_SIZE 64

STATIC_INLINE void
initFreeList(rootEntry *table, nat n, rootEntry *free)
{
  rootEntry *p;

  for (p = table + n - 1; p >= table; p--) {
    p->addr   = (P_)free;
    free = p;
  }
  root_ptr_free = table;
}

Simon Marlow's avatar
Simon Marlow committed
831
static void
832 833 834 835 836 837 838 839 840 841 842 843 844
initRootPtrTable(void)
{
  if (RPT_size > 0)
    return;

  RPT_size = INIT_RPT_SIZE;
  root_ptr_table = stgMallocBytes(RPT_size * sizeof(rootEntry),
                                    "initRootPtrTable");

  initFreeList(root_ptr_table,INIT_RPT_SIZE,NULL);
}


Simon Marlow's avatar
Simon Marlow committed
845
static void
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
enlargeRootPtrTable(void)
{
  nat old_RPT_size = RPT_size;

  // 2nd and subsequent times
  RPT_size *= 2;
  root_ptr_table =
    stgReallocBytes(root_ptr_table,
                    RPT_size * sizeof(rootEntry),
                    "enlargeRootPtrTable");

  initFreeList(root_ptr_table + old_RPT_size, old_RPT_size, NULL);
}

static void
addRootObject(void *addr)
{
  StgWord rt;
864
  initRootPtrTable();
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  if (root_ptr_free == NULL) {
    enlargeRootPtrTable();
  }

  rt = root_ptr_free - root_ptr_table;
  root_ptr_free  = (rootEntry*)(root_ptr_free->addr);
  root_ptr_table[rt].addr = addr;
}

/* -----------------------------------------------------------------------------
 * Treat root pointers as roots for the garbage collector.
 * -------------------------------------------------------------------------- */

void
markRootPtrTable(evac_fn evac)
{
  rootEntry *p, *end_root_ptr_table;
  StgPtr q;

  end_root_ptr_table = &root_ptr_table[RPT_size];

  for (p = root_ptr_table; p < end_root_ptr_table; p++) {
    q = p->addr;

    if (q && (q < (P_)root_ptr_table || q >= (P_)end_root_ptr_table)) {
        evac((StgClosure **)p->addr);
    }
  }
}

/* -----------------------------------------------------------------------------
 * End of utilities for handling root pointers.
 * -------------------------------------------------------------------------- */


900 901 902 903 904
/* -----------------------------------------------------------------------------
 * Insert symbols into hash tables, checking for duplicates.
 */
static void ghciInsertStrHashTable ( char* obj_name,
                                     HashTable *table,
905
                                     char* key,
906 907 908 909 910 911 912 913
                                     void *data
				   )
{
   if (lookupHashTable(table, (StgWord)key) == NULL)
   {
      insertStrHashTable(table, (StgWord)key, data);
      return;
   }
914
   debugBelch(
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
      "\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);
}


934 935 936
/* -----------------------------------------------------------------------------
 * initialize the object linker
 */
937 938 939 940


static int linker_init_done = 0 ;

941
#if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
942
static void *dl_prog_handle;
943
#endif
944 945 946 947

void
initLinker( void )
{
948
    RtsSymbolVal *sym;
949

950 951 952 953 954 955 956
    /* 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;
    }

957
    stablehash = allocStrHashTable();
958 959 960 961
    symhash = allocStrHashTable();

    /* populate the symbol table with stuff from the RTS */
    for (sym = rtsSyms; sym->lbl != NULL; sym++) {
962 963
	ghciInsertStrHashTable("(GHCi built-in symbols)",
                               symhash, sym->lbl, sym->addr);
964
    }
965
#   if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
966 967 968
    machoInitSymbolsWithoutUnderscore();
#   endif

969
#   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
970
#   if defined(RTLD_DEFAULT)
971 972
    dl_prog_handle = RTLD_DEFAULT;
#   else
973
    dl_prog_handle = dlopen(NULL, RTLD_LAZY);
974
#   endif /* RTLD_DEFAULT */
975
#   endif
976 977
}

978
/* -----------------------------------------------------------------------------
979 980 981
 *                  Loading DLL or .so dynamic libraries
 * -----------------------------------------------------------------------------
 *
982 983 984 985
 * 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
986 987
 * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
 *
988
 * In the PEi386 case, open the DLLs and put handles to them in a
989
 * linked list.  When looking for a symbol, try all handles in the
990 991 992 993 994
 * 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.
995
 *
996
 */
997 998 999 1000 1001 1002

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

typedef
   struct _OpenedDLL {
1003
      char*              name;
1004 1005
      struct _OpenedDLL* next;
      HINSTANCE instance;
1006
   }
1007 1008 1009 1010 1011 1012
   OpenedDLL;

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

1013 1014
char *
addDLL( char *dll_name )
1015
{
1016
#  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1017
   /* ------------------- ELF DLL loader ------------------- */
1018
   void *hdl;
1019
   char *errmsg;
1020

1021 1022
   initLinker();

1023
   hdl= dlopen(dll_name, RTLD_NOW | RTLD_GLOBAL);
1024

1025 1026 1027 1028 1029 1030 1031 1032
   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;
   }
1033 1034
   /*NOTREACHED*/

1035
#  elif defined(OBJFORMAT_PEi386)
1036
   /* ------------------- Win32 DLL loader ------------------- */
1037

1038
   char*      buf;
1039
   OpenedDLL* o_dll;
1040
   HINSTANCE  instance;
1041

1042 1043
   initLinker();

1044
   /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1045 1046 1047 1048 1049

   /* 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;
1050 1051
   }

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
   /* 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. */

1062
   buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1063 1064 1065
   sprintf(buf, "%s.DLL", dll_name);
   instance = LoadLibrary(buf);
   if (instance == NULL) {
1066
	 sprintf(buf, "%s.DRV", dll_name);	// KAA: allow loading of drivers (like winspool.drv)
1067 1068
	 instance = LoadLibrary(buf);
	 if (instance == NULL) {
sof's avatar
sof committed
1069
		stgFree(buf);
1070 1071 1072 1073

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

1077
   /* Add this DLL to the list of DLLs in which to search for symbols. */
1078
   o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1079 1080
   o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
   strcpy(o_dll->name, dll_name);
1081
   o_dll->instance = instance;
1082 1083
   o_dll->next     = opened_dlls;
   opened_dlls     = o_dll;
1084 1085

   return NULL;
1086 1087 1088 1089 1090
#  else
   barf("addDLL: not implemented on this platform");
#  endif
}

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
/* -----------------------------------------------------------------------------
 * 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);
}

1111 1112
/* -----------------------------------------------------------------------------
 * lookup a symbol in the hash table
1113
 */
1114 1115 1116
void *
lookupSymbol( char *lbl )
{
1117
    void *val;
1118
    initLinker() ;
1119
    ASSERT(symhash != NULL);
1120 1121 1122
    val = lookupStrHashTable(symhash, lbl);

    if (val == NULL) {
1123
#       if defined(OBJFORMAT_ELF)
1124
#	if defined(x86_64_HOST_ARCH)
1125 1126 1127 1128 1129 1130 1131 1132 1133
	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;
	}
1134
#	else
1135
	return dlsym(dl_prog_handle, lbl);
1136
#	endif
1137 1138 1139 1140 1141 1142 1143
#       elif defined(OBJFORMAT_MACHO)
	if(NSIsSymbolNameDefined(lbl)) {
	    NSSymbol symbol = NSLookupAndBindSymbol(lbl);
	    return NSAddressOfSymbol(symbol);
	} else {
	    return NULL;
	}
1144
#       elif defined(OBJFORMAT_PEi386)
1145 1146 1147
        OpenedDLL* o_dll;
        void* sym;
        for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1148
	  /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
1149 1150 1151 1152 1153 1154 1155
           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
1156
              if (sym != NULL) {
1157
		/*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
sof's avatar
sof committed
1158
		return sym;
1159
	      }
1160
           }
1161
           sym = GetProcAddress(o_dll->instance, lbl);
sof's avatar
sof committed
1162
           if (sym != NULL) {
1163
	     /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
sof's avatar
sof committed
1164 1165
	     return sym;
	   }
1166
        }
1167
        return NULL;
ken's avatar
ken committed
1168 1169 1170
#       else
        ASSERT(2+2 == 5);
        return NULL;
1171
#       endif
1172
    } else {
1173
	return val;
1174 1175 1176
    }
}

1177
static
1178
__attribute((unused))
1179 1180 1181
void *
lookupLocalSymbol( ObjectCode* oc, char *lbl )
{
1182
    void *val;
1183
    initLinker() ;
1184 1185 1186 1187 1188
    val = lookupStrHashTable(oc->lochash, lbl);

    if (val == NULL) {
        return NULL;
    } else {
1189
	return val;
1190 1191 1192 1193
    }
}


1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
/* -----------------------------------------------------------------------------
 * 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;
1208 1209 1210

   initLinker();

1211 1212 1213 1214
   for (oc = objects; oc; oc = oc->next) {
      for (i = 0; i < oc->n_symbols; i++) {
         sym = oc->symbols[i];
         if (sym == NULL) continue;
1215
         // debugBelch("enquire %p %p\n", sym, oc->lochash);
1216
         a = NULL;
1217
         if (oc->lochash != NULL) {
1218
            a = lookupStrHashTable(oc->lochash, sym);
1219 1220
	 }
         if (a == NULL) {
1221
            a = lookupStrHashTable(symhash, sym);
1222
	 }
1223
         if (a == NULL) {
1224
	     // debugBelch("ghci_enquire: can't find %s\n", sym);
1225
         }
1226
         else if (addr-DELTA <= a && a <= addr+DELTA) {
1227
            debugBelch("%p + %3d  ==  `%s'\n", addr, (int)(a - addr), sym);
1228 1229 1230 1231 1232 1233
         }
      }
   }
}
#endif

1234
#ifdef ia64_HOST_ARCH
1235 1236
static unsigned int PLTSize(void);
#endif
1237

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
/* -----------------------------------------------------------------------------
 * 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;
1249 1250
#ifdef USE_MMAP
   int fd, pagesize;
1251
   void *map_addr = NULL;
1252
#else
1253
   FILE *f;
1254
   int misalignment;
1255
#endif
1256 1257
   initLinker();

1258
   /* debugBelch("loadObj %s\n", path ); */
1259

1260 1261
   /* Check that we haven't already loaded this object. 
      Ignore requests to load multiple times */
1262
   {
1263
       ObjectCode *o;
1264 1265
       int is_dup = 0;
       for (o = objects; o; o = o->next) {
1266
          if (0 == strcmp(o->fileName, path)) {
1267
             is_dup = 1;
1268 1269
             break; /* don't need to search further */
          }
1270 1271
       }
       if (is_dup) {
1272
          IF_DEBUG(linker, debugBelch(
1273 1274 1275
            "GHCi runtime linker: warning: looks like you're trying to load the\n"
            "same object file twice:\n"
            "   %s\n"
1276 1277 1278
            "GHCi will ignore this, but be warned.\n"
            , path));
          return 1; /* success */
1279
       }
1280 1281 1282 1283
   }

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

1284
#  if defined(OBJFORMAT_ELF)
1285
   oc->formatName = "ELF";
1286
#  elif defined(OBJFORMAT_PEi386)
1287
   oc->formatName = "PEi386";
1288 1289
#  elif defined(OBJFORMAT_MACHO)
   oc->formatName = "Mach-O";
1290
#  else
sof's avatar
sof committed
1291
   stgFree(oc);
1292 1293 1294 1295 1296 1297
   barf("loadObj: not implemented on this platform");
#  endif

   r = stat(path, &st);
   if (r == -1) { return 0; }

1298
   /* sigh, strdup() isn't a POSIX function, so do it the long way */
1299 1300 1301
   oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
   strcpy(oc->fileName, path);

1302 1303 1304
   oc->fileSize          = st.st_size;
   oc->symbols           = NULL;
   oc->sections          = NULL;
1305
   oc->lochash           = allocStrHashTable();
1306
   oc->proddables        = NULL;
1307 1308 1309 1310 1311

   /* chain it onto the list of objects */
   oc->next              = objects;
   objects               = oc;

1312 1313 1314 1315 1316
#ifdef USE_MMAP
#define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))

   /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */

1317
#if defined(openbsd_HOST_OS)
1318 1319
   fd = open(path, O_RDONLY, S_IRUSR);
#else
1320
   fd = open(path, O_RDONLY);
1321
#endif
1322 1323