Linker.c 132 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

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

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

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

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

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

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

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

72
73
#endif

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

91
/* Hash table mapping symbol names to Symbol */
92
static /*Str*/HashTable *symhash;
93

94
95
96
/* List of currently loaded objects */
ObjectCode *objects = NULL;	/* initially empty */

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

113
static int machoGetMisalignment( FILE * );
114
115
#ifdef powerpc_HOST_ARCH
static int ocAllocateJumpIslands_MachO ( ObjectCode* oc );
116
static void machoInitSymbolsWithoutUnderscore( void );
117
#endif
118
#endif
119

120
121
122
123
#if defined(x86_64_HOST_ARCH)
static void*x86_64_high_symbol( char *lbl, void *addr );
#endif

124
125
126
127
/* -----------------------------------------------------------------------------
 * Built-in symbols from the RTS
 */

128
129
130
131
132
133
typedef struct _RtsSymbolVal {
    char   *lbl;
    void   *addr;
} RtsSymbolVal;


134
135
136
137
138
139
140
141
#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
142

143
#if !defined (mingw32_HOST_OS)
144
#define RTS_POSIX_ONLY_SYMBOLS                  \
145
      SymX(signal_handlers)			\
146
147
      SymX(stg_sig_install)			\
      Sym(nocldstop)
sof's avatar
sof committed
148
#endif
149

150
#if defined (cygwin32_HOST_OS)
sof's avatar
sof committed
151
152
153
#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
154
 * exports; sigh.
sof's avatar
sof committed
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
225
226
227
228
229
230
231
 */
#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)                               \
232
      SymX(waitpid)
233

234
#elif !defined(mingw32_HOST_OS)
sof's avatar
sof committed
235
236
#define RTS_MINGW_ONLY_SYMBOLS /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
237
#else /* defined(mingw32_HOST_OS) */
sof's avatar
sof committed
238
239
#define RTS_POSIX_ONLY_SYMBOLS  /**/
#define RTS_CYGWIN_ONLY_SYMBOLS /**/
240

241
242
243
244
/* Extra syms gen'ed by mingw-2's gcc-3.2: */
#if __GNUC__>=3
#define RTS_MINGW_EXTRA_SYMS                    \
      Sym(_imp____mb_cur_max)                   \
245
      Sym(_imp___pctype)
246
247
248
249
#else
#define RTS_MINGW_EXTRA_SYMS
#endif

250
251
/* These are statically linked from the mingw libraries into the ghc
   executable, so we have to employ this hack. */
252
#define RTS_MINGW_ONLY_SYMBOLS                  \
sof's avatar
sof committed
253
254
      SymX(asyncReadzh_fast)			\
      SymX(asyncWritezh_fast)			\
sof's avatar
sof committed
255
      SymX(asyncDoProczh_fast)			\
256
      SymX(memset)                              \
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
282
283
284
285
286
287
288
      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)                              \
289
290
291
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
292
293
294
295
296
297
298
299
300
301
302
303
304
305
      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)                              \
sof's avatar
sof committed
306
307
      SymX(rts_InstallConsoleEvent)             \
      SymX(rts_ConsoleHandlerDone)              \
308
      Sym(mktime)                               \
309
      Sym(_imp___timezone)                      \
310
      Sym(_imp___tzname)                        \
311
      Sym(_imp___iob)                           \
sof's avatar
sof committed
312
      Sym(_imp___osver)                         \
313
314
315
316
      Sym(localtime)                            \
      Sym(gmtime)                               \
      Sym(opendir)                              \
      Sym(readdir)                              \
sof's avatar
sof committed
317
      Sym(rewinddir)                            \
318
      RTS_MINGW_EXTRA_SYMS                      \
319
      Sym(closedir)
320
#endif
321

322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#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
372
373
374
375
376
#ifndef SMP
# define MAIN_CAP_SYM SymX(MainCapability)
#else
# define MAIN_CAP_SYM
#endif
377

sof's avatar
sof committed
378
379
380
381
382
383
384
#if !defined(mingw32_HOST_OS)
#define RTS_USER_SIGNALS_SYMBOLS \
   SymX(setIOManagerPipe)
#else
#define RTS_USER_SIGNALS_SYMBOLS /* nothing */
#endif

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#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

408
#define RTS_SYMBOLS				\
409
410
      Maybe_Stable_Names			\
      Sym(StgReturn)				\
411
412
      SymX(stg_enter_info)			\
      SymX(stg_gc_void_info)			\
413
414
      SymX(__stg_gc_enter_1)			\
      SymX(stg_gc_noregs)			\
415
      SymX(stg_gc_unpt_r1_info)			\
416
      SymX(stg_gc_unpt_r1)			\
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
      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)			\
433
      SymX(stg_yield_to_interpreter)		\
434
435
436
437
438
439
      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
440
      MAIN_CAP_SYM                              \
441
442
443
444
445
446
      SymX(MallocFailHook)			\
      SymX(OnExitHook)				\
      SymX(OutOfHeapHook)			\
      SymX(StackOverflowHook)			\
      SymX(__encodeDouble)			\
      SymX(__encodeFloat)			\
dons's avatar
dons committed
447
      SymX(addDLL)               		\
448
449
450
451
452
453
454
455
456
      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)			\
457
      SymX(atomicallyzh_fast)			\
458
      SymX(barf)				\
459
460
      SymX(debugBelch)				\
      SymX(errorBelch)				\
461
462
      SymX(blockAsyncExceptionszh_fast)		\
      SymX(catchzh_fast)			\
463
464
      SymX(catchRetryzh_fast)			\
      SymX(catchSTMzh_fast)			\
sof's avatar
sof committed
465
      SymX(closure_flags)                       \
466
      SymX(cmp_thread)				\
sof's avatar
sof committed
467
468
      SymX(cmpIntegerzh_fast)	        	\
      SymX(cmpIntegerIntzh_fast)	      	\
sof's avatar
sof committed
469
      SymX(complementIntegerzh_fast)		\
470
471
472
473
474
      SymX(createAdjustor)			\
      SymX(decodeDoublezh_fast)			\
      SymX(decodeFloatzh_fast)			\
      SymX(defaultsHook)			\
      SymX(delayzh_fast)			\
sof's avatar
sof committed
475
476
      SymX(deRefWeakzh_fast)			\
      SymX(deRefStablePtrzh_fast)		\
477
478
479
      SymX(divExactIntegerzh_fast)		\
      SymX(divModIntegerzh_fast)		\
      SymX(forkzh_fast)				\
480
      SymX(forkProcess)				\
481
      SymX(forkOS_createThread)			\
482
      SymX(freeHaskellFunctionPtr)		\
sof's avatar
sof committed
483
      SymX(freeStablePtr)		        \
484
      SymX(gcdIntegerzh_fast)			\
sof's avatar
sof committed
485
486
      SymX(gcdIntegerIntzh_fast)		\
      SymX(gcdIntzh_fast)			\
487
      SymX(genSymZh)				\
dons's avatar
dons committed
488
      SymX(genericRaise)			\
489
490
      SymX(getProgArgv)				\
      SymX(getStablePtr)			\
491
492
493
494
495
496
497
498
      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)				\
499
      SymX(int2Integerzh_fast)			\
sof's avatar
sof committed
500
501
      SymX(integer2Intzh_fast)			\
      SymX(integer2Wordzh_fast)			\
502
      SymX(isCurrentThreadBoundzh_fast)		\
503
504
505
506
      SymX(isDoubleDenormalized)		\
      SymX(isDoubleInfinite)			\
      SymX(isDoubleNaN)				\
      SymX(isDoubleNegativeZero)		\
sof's avatar
sof committed
507
      SymX(isEmptyMVarzh_fast)			\
508
509
510
511
512
      SymX(isFloatDenormalized)			\
      SymX(isFloatInfinite)			\
      SymX(isFloatNaN)				\
      SymX(isFloatNegativeZero)			\
      SymX(killThreadzh_fast)			\
dons's avatar
dons committed
513
514
      SymX(loadObj)          			\
      SymX(lookupSymbol)     			\
sof's avatar
sof committed
515
      SymX(makeStablePtrzh_fast)		\
516
517
      SymX(minusIntegerzh_fast)			\
      SymX(mkApUpd0zh_fast)			\
sof's avatar
sof committed
518
      SymX(myThreadIdzh_fast)			\
519
      SymX(labelThreadzh_fast)                  \
520
521
522
      SymX(newArrayzh_fast)			\
      SymX(newBCOzh_fast)			\
      SymX(newByteArrayzh_fast)			\
523
      SymX_redirect(newCAF, newDynCAF)		\
524
525
      SymX(newMVarzh_fast)			\
      SymX(newMutVarzh_fast)			\
526
      SymX(newTVarzh_fast)			\
527
      SymX(atomicModifyMutVarzh_fast)		\
528
529
530
      SymX(newPinnedByteArrayzh_fast)		\
      SymX(orIntegerzh_fast)			\
      SymX(performGC)				\
531
      SymX(performMajorGC)			\
532
533
534
535
536
537
538
      SymX(plusIntegerzh_fast)			\
      SymX(prog_argc)				\
      SymX(prog_argv)				\
      SymX(putMVarzh_fast)			\
      SymX(quotIntegerzh_fast)			\
      SymX(quotRemIntegerzh_fast)		\
      SymX(raisezh_fast)			\
539
      SymX(raiseIOzh_fast)			\
540
      SymX(readTVarzh_fast)			\
541
542
543
      SymX(remIntegerzh_fast)			\
      SymX(resetNonBlockingFd)			\
      SymX(resumeThread)			\
dons's avatar
dons committed
544
      SymX(resolveObjs)                         \
545
      SymX(retryzh_fast)                        \
546
547
548
549
550
      SymX(rts_apply)				\
      SymX(rts_checkSchedStatus)		\
      SymX(rts_eval)				\
      SymX(rts_evalIO)				\
      SymX(rts_evalLazyIO)			\
551
      SymX(rts_evalStableIO)			\
552
553
554
555
556
557
558
559
      SymX(rts_eval_)				\
      SymX(rts_getBool)				\
      SymX(rts_getChar)				\
      SymX(rts_getDouble)			\
      SymX(rts_getFloat)			\
      SymX(rts_getInt)				\
      SymX(rts_getInt32)			\
      SymX(rts_getPtr)				\
560
      SymX(rts_getFunPtr)			\
561
      SymX(rts_getStablePtr)			\
562
      SymX(rts_getThreadId)			\
563
564
      SymX(rts_getWord)				\
      SymX(rts_getWord32)			\
565
      SymX(rts_lock)				\
566
567
568
569
570
571
572
573
574
575
      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)				\
576
      SymX(rts_mkFunPtr)			\
577
578
579
580
581
582
583
      SymX(rts_mkStablePtr)			\
      SymX(rts_mkString)			\
      SymX(rts_mkWord)				\
      SymX(rts_mkWord16)			\
      SymX(rts_mkWord32)			\
      SymX(rts_mkWord64)			\
      SymX(rts_mkWord8)				\
584
      SymX(rts_unlock)				\
585
      SymX(rtsSupportsBoundThreads)		\
586
587
      SymX(__hscore_get_saved_termios)		\
      SymX(__hscore_set_saved_termios)		\
588
      SymX(setProgArgv)				\
589
590
      SymX(startupHaskell)			\
      SymX(shutdownHaskell)			\
591
592
593
594
      SymX(shutdownHaskellAndExit)		\
      SymX(stable_ptr_table)			\
      SymX(stackOverflow)			\
      SymX(stg_CAF_BLACKHOLE_info)		\
595
      SymX(awakenBlockedQueue)			\
596
597
598
599
600
      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)	\
601
      SymX(stg_MUT_ARR_PTRS_FROZEN0_info)	\
602
      SymX(stg_WEAK_info)                       \
603
      SymX(stg_ap_0_info)			\
604
605
606
607
608
609
610
611
612
613
      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)			\
614
      SymX(stg_ap_pppv_info)			\
615
616
617
      SymX(stg_ap_pppp_info)			\
      SymX(stg_ap_ppppp_info)			\
      SymX(stg_ap_pppppp_info)			\
618
      SymX(stg_ap_1_upd_info)			\
619
620
621
622
623
624
      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)			\
625
      SymX(stg_exit)				\
626
      SymX(stg_sel_0_upd_info)			\
627
628
629
630
631
632
      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)			\
633
634
635
636
637
638
639
640
641
      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)			\
642
643
      SymX(stg_upd_frame_info)			\
      SymX(suspendThread)			\
644
      SymX(takeMVarzh_fast)			\
645
      SymX(timesIntegerzh_fast)			\
646
      SymX(tryPutMVarzh_fast)			\
647
648
      SymX(tryTakeMVarzh_fast)			\
      SymX(unblockAsyncExceptionszh_fast)	\
dons's avatar
dons committed
649
      SymX(unloadObj)                           \
650
      SymX(unsafeThawArrayzh_fast)		\
651
652
      SymX(waitReadzh_fast)			\
      SymX(waitWritezh_fast)			\
653
      SymX(word2Integerzh_fast)			\
654
      SymX(writeTVarzh_fast)			\
655
      SymX(xorIntegerzh_fast)			\
sof's avatar
sof committed
656
657
      SymX(yieldzh_fast)                        \
      RTS_USER_SIGNALS_SYMBOLS
658

659
#ifdef SUPPORT_LONG_LONGS
660
#define RTS_LONG_LONG_SYMS			\
661
662
      SymX(int64ToIntegerzh_fast)		\
      SymX(word64ToIntegerzh_fast)
663
664
665
666
#else
#define RTS_LONG_LONG_SYMS /* nothing */
#endif

667
668
669
// 64-bit support functions in libgcc.a
#if defined(__GNUC__) && SIZEOF_VOID_P <= 4
#define RTS_LIBGCC_SYMBOLS			\
670
671
672
      Sym(__divdi3)                             \
      Sym(__udivdi3)                            \
      Sym(__moddi3)                             \
673
      Sym(__umoddi3)				\
674
      Sym(__muldi3)				\
675
676
677
678
      Sym(__ashldi3)				\
      Sym(__ashrdi3)				\
      Sym(__lshrdi3)				\
      Sym(__eprintf)
679
#elif defined(ia64_HOST_ARCH)
680
681
682
683
684
685
686
#define RTS_LIBGCC_SYMBOLS			\
      Sym(__divdi3)				\
      Sym(__udivdi3)                            \
      Sym(__moddi3)				\
      Sym(__umoddi3)				\
      Sym(__divsf3)				\
      Sym(__divdf3)
687
688
689
690
#else
#define RTS_LIBGCC_SYMBOLS
#endif

691
#if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
692
693
694
695
696
697
      // 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)
698
#endif
699
700

/* entirely bogus claims about types of these symbols */
701
#define Sym(vvv)  extern void vvv(void);
702
#define SymX(vvv) /**/
703
#define SymX_redirect(vvv,xxx) /**/
704
RTS_SYMBOLS
705
RTS_RET_SYMBOLS
706
RTS_LONG_LONG_SYMS
707
RTS_POSIX_ONLY_SYMBOLS
708
RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
709
RTS_CYGWIN_ONLY_SYMBOLS
710
RTS_DARWIN_ONLY_SYMBOLS
711
RTS_LIBGCC_SYMBOLS
712
713
#undef Sym
#undef SymX
714
#undef SymX_redirect
715
716
717
718
719
720
721
722
723
724
725

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

726
727
728
729
730
731
// 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)) },

732
static RtsSymbolVal rtsSyms[] = {
733
      RTS_SYMBOLS
734
      RTS_RET_SYMBOLS
735
      RTS_LONG_LONG_SYMS
736
      RTS_POSIX_ONLY_SYMBOLS
737
      RTS_MINGW_ONLY_SYMBOLS
sof's avatar
sof committed
738
      RTS_CYGWIN_ONLY_SYMBOLS
739
      RTS_LIBGCC_SYMBOLS
740
741
742
743
#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.
744
      { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
745
#endif
746
747
748
      { 0, 0 } /* sentinel */
};

749
750
751
752
753
/* -----------------------------------------------------------------------------
 * Insert symbols into hash tables, checking for duplicates.
 */
static void ghciInsertStrHashTable ( char* obj_name,
                                     HashTable *table,
754
                                     char* key,
755
756
757
758
759
760
761
762
                                     void *data
				   )
{
   if (lookupHashTable(table, (StgWord)key) == NULL)
   {
      insertStrHashTable(table, (StgWord)key, data);
      return;
   }
763
   debugBelch(
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
      "\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);
}


783
784
785
/* -----------------------------------------------------------------------------
 * initialize the object linker
 */
786
787
788
789


static int linker_init_done = 0 ;

790
#if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
791
static void *dl_prog_handle;
792
#endif
793

dons's avatar
dons committed
794
/* dlopen(NULL,..) doesn't work so we grab libc explicitly */
795
#if defined(openbsd_HOST_OS)
dons's avatar
dons committed
796
797
798
static void *dl_libc_handle;
#endif

799
800
801
void
initLinker( void )
{
802
    RtsSymbolVal *sym;
803

804
805
806
807
808
809
810
    /* 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;
    }

811
812
813
814
    symhash = allocStrHashTable();

    /* populate the symbol table with stuff from the RTS */
    for (sym = rtsSyms; sym->lbl != NULL; sym++) {
815
816
	ghciInsertStrHashTable("(GHCi built-in symbols)",
                               symhash, sym->lbl, sym->addr);
817
    }
818
#   if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
819
820
821
    machoInitSymbolsWithoutUnderscore();
#   endif

822
#   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
823
#   if defined(RTLD_DEFAULT)
824
825
    dl_prog_handle = RTLD_DEFAULT;
#   else
826
    dl_prog_handle = dlopen(NULL, RTLD_LAZY);
827
#   if defined(openbsd_HOST_OS)
dons's avatar
dons committed
828
829
    dl_libc_handle = dlopen("libc.so", RTLD_LAZY);
#   endif
830
#   endif /* RTLD_DEFAULT */
831
#   endif
832
833
}

834
/* -----------------------------------------------------------------------------
835
836
837
 *                  Loading DLL or .so dynamic libraries
 * -----------------------------------------------------------------------------
 *
838
839
840
841
 * 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
842
843
 * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
 *
844
 * In the PEi386 case, open the DLLs and put handles to them in a
845
 * linked list.  When looking for a symbol, try all handles in the
846
847
848
849
850
 * 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.
851
 *
852
 */
853
854
855
856
857
858

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

typedef
   struct _OpenedDLL {
859
      char*              name;
860
861
      struct _OpenedDLL* next;
      HINSTANCE instance;
862
   }
863
864
865
866
867
868
   OpenedDLL;

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

869
870
char *
addDLL( char *dll_name )
871
{
872
#  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
873
   /* ------------------- ELF DLL loader ------------------- */
874
   void *hdl;
875
   char *errmsg;
876

877
878
   initLinker();

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

881
882
883
884
885
886
887
888
   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;
   }
889
890
   /*NOTREACHED*/

891
#  elif defined(OBJFORMAT_PEi386)
892
   /* ------------------- Win32 DLL loader ------------------- */
893

894
   char*      buf;
895
   OpenedDLL* o_dll;
896
   HINSTANCE  instance;
897

898
899
   initLinker();

900
   /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
901
902
903
904
905

   /* 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;
906
907
   }

908
909
910
911
912
913
914
915
916
917
   /* 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. */

918
   buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
919
920
921
   sprintf(buf, "%s.DLL", dll_name);
   instance = LoadLibrary(buf);
   if (instance == NULL) {
922
	 sprintf(buf, "%s.DRV", dll_name);	// KAA: allow loading of drivers (like winspool.drv)
923
924
	 instance = LoadLibrary(buf);
	 if (instance == NULL) {
sof's avatar
sof committed
925
		stgFree(buf);
926
927
928
929

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

933
   /* Add this DLL to the list of DLLs in which to search for symbols. */
934
   o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
935
936
   o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
   strcpy(o_dll->name, dll_name);
937
   o_dll->instance = instance;
938
939
   o_dll->next     = opened_dlls;
   opened_dlls     = o_dll;
940
941

   return NULL;
942
943
944
945
946
#  else
   barf("addDLL: not implemented on this platform");
#  endif
}

947
948
/* -----------------------------------------------------------------------------
 * lookup a symbol in the hash table
949
 */
950
951
952
void *
lookupSymbol( char *lbl )
{
953
    void *val;
954
    initLinker() ;
955
    ASSERT(symhash != NULL);
956
957
958
    val = lookupStrHashTable(symhash, lbl);

    if (val == NULL) {
959
#       if defined(OBJFORMAT_ELF)
960
#	if defined(openbsd_HOST_OS)
dons's avatar
dons committed
961
962
	val = dlsym(dl_prog_handle, lbl);
	return (val != NULL) ? val : dlsym(dl_libc_handle,lbl);
963
964
965
966
967
968
969
970
971
972
#	elif defined(x86_64_HOST_ARCH)
	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;
	}
dons's avatar
dons committed
973
#	else /* not openbsd */
974
	return dlsym(dl_prog_handle, lbl);
dons's avatar
dons committed
975
#	endif
976
977
978
979
980
981
982
#       elif defined(OBJFORMAT_MACHO)
	if(NSIsSymbolNameDefined(lbl)) {
	    NSSymbol symbol = NSLookupAndBindSymbol(lbl);
	    return NSAddressOfSymbol(symbol);
	} else {
	    return NULL;
	}
983
#       elif defined(OBJFORMAT_PEi386)
984
985
986
        OpenedDLL* o_dll;
        void* sym;
        for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
987
	  /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
988
989
990
991
992
993
994
           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
995
              if (sym != NULL) {
996
		/*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
sof's avatar
sof committed
997
		return sym;
998
	      }
999
           }
1000
           sym = GetProcAddress(o_dll->instance, lbl);
sof's avatar
sof committed
1001
           if (sym != NULL) {
1002
	     /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
sof's avatar
sof committed
1003
1004
	     return sym;
	   }
1005
        }
1006
        return NULL;
ken's avatar
ken committed
1007
1008
1009
#       else
        ASSERT(2+2 == 5);
        return NULL;
1010
#       endif
1011
    } else {
1012
	return val;
1013
1014
1015
    }
}

1016
static
1017
__attribute((unused))
1018
1019
1020
void *
lookupLocalSymbol( ObjectCode* oc, char *lbl )
{
1021
    void *val;
1022
    initLinker() ;
1023
1024
1025
1026
1027
    val = lookupStrHashTable(oc->lochash, lbl);

    if (val == NULL) {
        return NULL;
    } else {
1028
	return val;
1029
1030
1031
1032
    }
}


1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
/* -----------------------------------------------------------------------------
 * 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;
1047
1048
1049

   initLinker();

1050
1051
1052
1053
   for (oc = objects; oc; oc = oc->next) {
      for (i = 0; i < oc->n_symbols; i++) {
         sym = oc->symbols[i];
         if (sym == NULL) continue;
1054
         // debugBelch("enquire %p %p\n", sym, oc->lochash);
1055
         a = NULL;
1056
         if (oc->lochash != NULL) {
1057
            a = lookupStrHashTable(oc->lochash, sym);
1058
1059
	 }
         if (a == NULL) {
1060
            a = lookupStrHashTable(symhash, sym);
1061
	 }
1062
         if (a == NULL) {
1063
	     // debugBelch("ghci_enquire: can't find %s\n", sym);
1064
         }
1065
         else if (addr-DELTA <= a && a <= addr+DELTA) {
1066
            debugBelch("%p + %3d  ==  `%s'\n", addr, (int)(a - addr), sym);
1067
1068
1069
1070
1071
1072
         }
      }
   }
}
#endif

1073
#ifdef ia64_HOST_ARCH
1074
1075
static unsigned int PLTSize(void);
#endif
1076

1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
/* -----------------------------------------------------------------------------
 * 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;
1088
1089
#ifdef USE_MMAP
   int fd, pagesize;
1090
   void *map_addr = NULL;
1091
#else
1092
   FILE *f;
1093
   int misalignment;
1094
#endif
1095
1096
   initLinker();

1097
   /* debugBelch("loadObj %s\n", path ); */
1098

dons's avatar
dons committed
1099
1100
   /* Check that we haven't already loaded this object. 
      Ignore requests to load multiple times */
1101
   {
1102
       ObjectCode *o;
1103
1104
       int is_dup = 0;
       for (o = objects; o; o = o->next) {
dons's avatar
dons committed
1105
          if (0 == strcmp(o->fileName, path)) {
1106
             is_dup = 1;
dons's avatar
dons committed
1107
1108
             break; /* don't need to search further */
          }
1109
1110
       }
       if (is_dup) {
1111
          IF_DEBUG(linker, debugBelch(
1112
1113
1114
            "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
1115
1116
1117
            "GHCi will ignore this, but be warned.\n"
            , path));
          return 1; /* success */
1118
       }
1119
1120
1121
1122
   }

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

1123
#  if defined(OBJFORMAT_ELF)
1124
   oc->formatName = "ELF";
1125
#  elif defined(OBJFORMAT_PEi386)
1126
   oc->formatName = "PEi386";
1127
1128
#  elif defined(OBJFORMAT_MACHO)
   oc->formatName = "Mach-O";
1129
#  else
sof's avatar
sof committed
1130
   stgFree(oc);
1131
1132
1133
1134
1135
1136
   barf("loadObj: not implemented on this platform");
#  endif

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

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

1141
1142
1143
   oc->fileSize          = st.st_size;
   oc->symbols           = NULL;
   oc->sections          = NULL;
1144
   oc->lochash           = allocStrHashTable();
1145
   oc->proddables        = NULL;
1146
1147
1148
1149
1150

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

1151
1152
1153
1154
1155
#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. */

1156
#if defined(openbsd_HOST_OS)
dons's avatar
dons committed
1157
1158
   fd = open(path, O_RDONLY, S_IRUSR);
#else
1159
   fd = open(path, O_RDONLY);
dons's avatar
dons committed
1160
#endif
1161
1162
1163
1164
1165
   if (fd == -1)
      barf("loadObj: can't open `%s'", path);

   pagesize = getpagesize();

1166
#ifdef ia64_HOST_ARCH
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
   /* The PLT needs to be right before the object */
   n = ROUND_UP(PLTSize(), pagesize);
   oc->plt = mmap(NULL, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
   if (oc->plt == MAP_FAILED)
      barf("loadObj: can't allocate PLT");

   oc->pltIndex = 0;
   map_addr = oc->plt + n;
#endif

   n = ROUND_UP(oc->fileSize, pagesize);
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190

   /* Link objects into the lower 2Gb on x86_64.  GHC assumes the
    * small memory model on this architecture (see gcc docs,
    * -mcmodel=small).
    */
#ifdef x86_64_HOST_ARCH
#define EXTRA_MAP_FLAGS MAP_32BIT
#else
#define EXTRA_MAP_FLAGS 0
#endif

   oc->image = mmap(map_addr, n, PROT_EXEC|PROT_READ|PROT_WRITE, 
		    MAP_PRIVATE|EXTRA_MAP_FLAGS, fd, 0);
1191
1192
1193
1194
1195
1196
1197
   if (oc->image == MAP_FAILED)
      barf("loadObj: can't map `%s'", path);

   close(fd);

#else /* !USE_MMAP */

1198
1199
   /* load the image into memory */
   f = fopen(path, "rb");
1200
   if (!f)
1201