add atexit (#4456)
[ghc-hetmet.git] / rts / Linker.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2000-2004
4  *
5  * RTS Object Linker
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #if 0
10 #include "PosixSource.h"
11 #endif
12
13 /* Linux needs _GNU_SOURCE to get RTLD_DEFAULT from <dlfcn.h> and
14    MREMAP_MAYMOVE from <sys/mman.h>.
15  */
16 #if defined(__linux__)  || defined(__GLIBC__)
17 #define _GNU_SOURCE 1
18 #endif
19
20 #include "Rts.h"
21 #include "HsFFI.h"
22
23 #include "sm/Storage.h"
24 #include "Stats.h"
25 #include "Hash.h"
26 #include "LinkerInternals.h"
27 #include "RtsUtils.h"
28 #include "Trace.h"
29 #include "StgPrimFloat.h" // for __int_encodeFloat etc.
30 #include "Stable.h"
31
32 #if !defined(mingw32_HOST_OS)
33 #include "posix/Signals.h"
34 #endif
35
36 // get protos for is*()
37 #include <ctype.h>
38
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
41 #endif
42
43 #include <inttypes.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <stdio.h>
47 #include <assert.h>
48
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif
52
53 #if defined(HAVE_DLFCN_H)
54 #include <dlfcn.h>
55 #endif
56
57 #if defined(cygwin32_HOST_OS)
58 #ifdef HAVE_DIRENT_H
59 #include <dirent.h>
60 #endif
61
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif
65 #include <regex.h>
66 #include <sys/fcntl.h>
67 #include <sys/termios.h>
68 #include <sys/utime.h>
69 #include <sys/utsname.h>
70 #include <sys/wait.h>
71 #endif
72
73 #if defined(linux_HOST_OS    ) || defined(freebsd_HOST_OS) || \
74     defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS ) || \
75     defined(openbsd_HOST_OS  ) || \
76     ( defined(darwin_HOST_OS ) && !defined(powerpc_HOST_ARCH) ) || \
77     defined(kfreebsdgnu_HOST_OS)
78 /* Don't use mmap on powerpc-apple-darwin as mmap doesn't support
79  * reallocating but we need to allocate jump islands just after each
80  * object images. Otherwise relative branches to jump islands can fail
81  * due to 24-bits displacement overflow.
82  */
83 #define USE_MMAP
84 #include <fcntl.h>
85 #include <sys/mman.h>
86
87 #ifdef HAVE_UNISTD_H
88 #include <unistd.h>
89 #endif
90
91 #endif
92
93 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
94 #  define OBJFORMAT_ELF
95 #  include <regex.h>    // regex is already used by dlopen() so this is OK
96                         // to use here without requiring an additional lib
97 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
98 #  define OBJFORMAT_PEi386
99 #  include <windows.h>
100 #  include <math.h>
101 #elif defined(darwin_HOST_OS)
102 #  define OBJFORMAT_MACHO
103 #  include <regex.h>
104 #  include <mach-o/loader.h>
105 #  include <mach-o/nlist.h>
106 #  include <mach-o/reloc.h>
107 #if !defined(HAVE_DLFCN_H)
108 #  include <mach-o/dyld.h>
109 #endif
110 #if defined(powerpc_HOST_ARCH)
111 #  include <mach-o/ppc/reloc.h>
112 #endif
113 #if defined(x86_64_HOST_ARCH)
114 #  include <mach-o/x86_64/reloc.h>
115 #endif
116 #endif
117
118 #if defined(x86_64_HOST_ARCH) && defined(darwin_HOST_OS)
119 #define ALWAYS_PIC
120 #endif
121
122 /* Hash table mapping symbol names to Symbol */
123 static /*Str*/HashTable *symhash;
124
125 /* Hash table mapping symbol names to StgStablePtr */
126 static /*Str*/HashTable *stablehash;
127
128 /* List of currently loaded objects */
129 ObjectCode *objects = NULL;     /* initially empty */
130
131 static HsInt loadOc( ObjectCode* oc );
132 static ObjectCode* mkOc( char *path, char *image, int imageSize,
133                          char *archiveMemberName
134 #ifndef USE_MMAP
135 #ifdef darwin_HOST_OS
136                        , int misalignment
137 #endif
138 #endif
139                        );
140
141 #if defined(OBJFORMAT_ELF)
142 static int ocVerifyImage_ELF    ( ObjectCode* oc );
143 static int ocGetNames_ELF       ( ObjectCode* oc );
144 static int ocResolve_ELF        ( ObjectCode* oc );
145 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
146 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
147 #endif
148 #elif defined(OBJFORMAT_PEi386)
149 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
150 static int ocGetNames_PEi386    ( ObjectCode* oc );
151 static int ocResolve_PEi386     ( ObjectCode* oc );
152 static void *lookupSymbolInDLLs ( unsigned char *lbl );
153 static void zapTrailingAtSign   ( unsigned char *sym );
154 #elif defined(OBJFORMAT_MACHO)
155 static int ocVerifyImage_MachO    ( ObjectCode* oc );
156 static int ocGetNames_MachO       ( ObjectCode* oc );
157 static int ocResolve_MachO        ( ObjectCode* oc );
158
159 #ifndef USE_MMAP
160 static int machoGetMisalignment( FILE * );
161 #endif
162 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
163 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
164 #endif
165 #ifdef powerpc_HOST_ARCH
166 static void machoInitSymbolsWithoutUnderscore( void );
167 #endif
168 #endif
169
170 /* on x86_64 we have a problem with relocating symbol references in
171  * code that was compiled without -fPIC.  By default, the small memory
172  * model is used, which assumes that symbol references can fit in a
173  * 32-bit slot.  The system dynamic linker makes this work for
174  * references to shared libraries by either (a) allocating a jump
175  * table slot for code references, or (b) moving the symbol at load
176  * time (and copying its contents, if necessary) for data references.
177  *
178  * We unfortunately can't tell whether symbol references are to code
179  * or data.  So for now we assume they are code (the vast majority
180  * are), and allocate jump-table slots.  Unfortunately this will
181  * SILENTLY generate crashing code for data references.  This hack is
182  * enabled by X86_64_ELF_NONPIC_HACK.
183  *
184  * One workaround is to use shared Haskell libraries.  This is
185  * coming.  Another workaround is to keep the static libraries but
186  * compile them with -fPIC, because that will generate PIC references
187  * to data which can be relocated.  The PIC code is still too green to
188  * do this systematically, though.
189  *
190  * See bug #781
191  * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
192  *
193  * Naming Scheme for Symbol Macros
194  *
195  * SymI_*: symbol is internal to the RTS. It resides in an object
196  *         file/library that is statically.
197  * SymE_*: symbol is external to the RTS library. It might be linked
198  *         dynamically.
199  *
200  * Sym*_HasProto  : the symbol prototype is imported in an include file
201  *                  or defined explicitly
202  * Sym*_NeedsProto: the symbol is undefined and we add a dummy
203  *                  default proto extern void sym(void);
204  */
205 #define X86_64_ELF_NONPIC_HACK 1
206
207 /* Link objects into the lower 2Gb on x86_64.  GHC assumes the
208  * small memory model on this architecture (see gcc docs,
209  * -mcmodel=small).
210  *
211  * MAP_32BIT not available on OpenBSD/amd64
212  */
213 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
214 #define TRY_MAP_32BIT MAP_32BIT
215 #else
216 #define TRY_MAP_32BIT 0
217 #endif
218
219 /*
220  * Due to the small memory model (see above), on x86_64 we have to map
221  * all our non-PIC object files into the low 2Gb of the address space
222  * (why 2Gb and not 4Gb?  Because all addresses must be reachable
223  * using a 32-bit signed PC-relative offset). On Linux we can do this
224  * using the MAP_32BIT flag to mmap(), however on other OSs
225  * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
226  * can't do this.  So on these systems, we have to pick a base address
227  * in the low 2Gb of the address space and try to allocate memory from
228  * there.
229  *
230  * We pick a default address based on the OS, but also make this
231  * configurable via an RTS flag (+RTS -xm)
232  */
233 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
234
235 #if defined(MAP_32BIT)
236 // Try to use MAP_32BIT
237 #define MMAP_32BIT_BASE_DEFAULT 0
238 #else
239 // A guess: 1Gb.
240 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
241 #endif
242
243 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
244 #endif
245
246 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
247 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
248 #define MAP_ANONYMOUS MAP_ANON
249 #endif
250
251 /* -----------------------------------------------------------------------------
252  * Built-in symbols from the RTS
253  */
254
255 typedef struct _RtsSymbolVal {
256     char   *lbl;
257     void   *addr;
258 } RtsSymbolVal;
259
260 #define Maybe_Stable_Names      SymI_HasProto(stg_mkWeakzh)                     \
261                                 SymI_HasProto(stg_mkWeakForeignEnvzh)           \
262                                 SymI_HasProto(stg_makeStableNamezh)             \
263                                 SymI_HasProto(stg_finalizzeWeakzh)
264
265 #if !defined (mingw32_HOST_OS)
266 #define RTS_POSIX_ONLY_SYMBOLS                  \
267       SymI_HasProto(__hscore_get_saved_termios) \
268       SymI_HasProto(__hscore_set_saved_termios) \
269       SymI_HasProto(shutdownHaskellAndSignal)   \
270       SymI_HasProto(lockFile)                   \
271       SymI_HasProto(unlockFile)                 \
272       SymI_HasProto(signal_handlers)            \
273       SymI_HasProto(stg_sig_install)            \
274       SymI_HasProto(rtsTimerSignal)             \
275       SymI_HasProto(atexit)                     \
276       SymI_NeedsProto(nocldstop)
277 #endif
278
279 #if defined (cygwin32_HOST_OS)
280 #define RTS_MINGW_ONLY_SYMBOLS /**/
281 /* Don't have the ability to read import libs / archives, so
282  * we have to stupidly list a lot of what libcygwin.a
283  * exports; sigh.
284  */
285 #define RTS_CYGWIN_ONLY_SYMBOLS                          \
286       SymI_HasProto(regfree)                             \
287       SymI_HasProto(regexec)                             \
288       SymI_HasProto(regerror)                            \
289       SymI_HasProto(regcomp)                             \
290       SymI_HasProto(__errno)                             \
291       SymI_HasProto(access)                              \
292       SymI_HasProto(chmod)                               \
293       SymI_HasProto(chdir)                               \
294       SymI_HasProto(close)                               \
295       SymI_HasProto(creat)                               \
296       SymI_HasProto(dup)                                 \
297       SymI_HasProto(dup2)                                \
298       SymI_HasProto(fstat)                               \
299       SymI_HasProto(fcntl)                               \
300       SymI_HasProto(getcwd)                              \
301       SymI_HasProto(getenv)                              \
302       SymI_HasProto(lseek)                               \
303       SymI_HasProto(open)                                \
304       SymI_HasProto(fpathconf)                           \
305       SymI_HasProto(pathconf)                            \
306       SymI_HasProto(stat)                                \
307       SymI_HasProto(pow)                                 \
308       SymI_HasProto(tanh)                                \
309       SymI_HasProto(cosh)                                \
310       SymI_HasProto(sinh)                                \
311       SymI_HasProto(atan)                                \
312       SymI_HasProto(acos)                                \
313       SymI_HasProto(asin)                                \
314       SymI_HasProto(tan)                                 \
315       SymI_HasProto(cos)                                 \
316       SymI_HasProto(sin)                                 \
317       SymI_HasProto(exp)                                 \
318       SymI_HasProto(log)                                 \
319       SymI_HasProto(sqrt)                                \
320       SymI_HasProto(localtime_r)                         \
321       SymI_HasProto(gmtime_r)                            \
322       SymI_HasProto(mktime)                              \
323       SymI_NeedsProto(_imp___tzname)                     \
324       SymI_HasProto(gettimeofday)                        \
325       SymI_HasProto(timezone)                            \
326       SymI_HasProto(tcgetattr)                           \
327       SymI_HasProto(tcsetattr)                           \
328       SymI_HasProto(memcpy)                              \
329       SymI_HasProto(memmove)                             \
330       SymI_HasProto(realloc)                             \
331       SymI_HasProto(malloc)                              \
332       SymI_HasProto(free)                                \
333       SymI_HasProto(fork)                                \
334       SymI_HasProto(lstat)                               \
335       SymI_HasProto(isatty)                              \
336       SymI_HasProto(mkdir)                               \
337       SymI_HasProto(opendir)                             \
338       SymI_HasProto(readdir)                             \
339       SymI_HasProto(rewinddir)                           \
340       SymI_HasProto(closedir)                            \
341       SymI_HasProto(link)                                \
342       SymI_HasProto(mkfifo)                              \
343       SymI_HasProto(pipe)                                \
344       SymI_HasProto(read)                                \
345       SymI_HasProto(rename)                              \
346       SymI_HasProto(rmdir)                               \
347       SymI_HasProto(select)                              \
348       SymI_HasProto(system)                              \
349       SymI_HasProto(write)                               \
350       SymI_HasProto(strcmp)                              \
351       SymI_HasProto(strcpy)                              \
352       SymI_HasProto(strncpy)                             \
353       SymI_HasProto(strerror)                            \
354       SymI_HasProto(sigaddset)                           \
355       SymI_HasProto(sigemptyset)                         \
356       SymI_HasProto(sigprocmask)                         \
357       SymI_HasProto(umask)                               \
358       SymI_HasProto(uname)                               \
359       SymI_HasProto(unlink)                              \
360       SymI_HasProto(utime)                               \
361       SymI_HasProto(waitpid)
362
363 #elif !defined(mingw32_HOST_OS)
364 #define RTS_MINGW_ONLY_SYMBOLS /**/
365 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
366 #else /* defined(mingw32_HOST_OS) */
367 #define RTS_POSIX_ONLY_SYMBOLS  /**/
368 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
369
370 #if HAVE_GETTIMEOFDAY
371 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
372 #else
373 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
374 #endif
375
376 #if HAVE___MINGW_VFPRINTF
377 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
378 #else
379 #define RTS___MINGW_VFPRINTF_SYM /**/
380 #endif
381
382 /* These are statically linked from the mingw libraries into the ghc
383    executable, so we have to employ this hack. */
384 #define RTS_MINGW_ONLY_SYMBOLS                           \
385       SymI_HasProto(stg_asyncReadzh)                     \
386       SymI_HasProto(stg_asyncWritezh)                    \
387       SymI_HasProto(stg_asyncDoProczh)                   \
388       SymI_HasProto(memset)                              \
389       SymI_HasProto(inet_ntoa)                           \
390       SymI_HasProto(inet_addr)                           \
391       SymI_HasProto(htonl)                               \
392       SymI_HasProto(recvfrom)                            \
393       SymI_HasProto(listen)                              \
394       SymI_HasProto(bind)                                \
395       SymI_HasProto(shutdown)                            \
396       SymI_HasProto(connect)                             \
397       SymI_HasProto(htons)                               \
398       SymI_HasProto(ntohs)                               \
399       SymI_HasProto(getservbyname)                       \
400       SymI_HasProto(getservbyport)                       \
401       SymI_HasProto(getprotobynumber)                    \
402       SymI_HasProto(getprotobyname)                      \
403       SymI_HasProto(gethostbyname)                       \
404       SymI_HasProto(gethostbyaddr)                       \
405       SymI_HasProto(gethostname)                         \
406       SymI_HasProto(strcpy)                              \
407       SymI_HasProto(strncpy)                             \
408       SymI_HasProto(abort)                               \
409       SymI_NeedsProto(_alloca)                           \
410       SymI_HasProto(isxdigit)                            \
411       SymI_HasProto(isupper)                             \
412       SymI_HasProto(ispunct)                             \
413       SymI_HasProto(islower)                             \
414       SymI_HasProto(isspace)                             \
415       SymI_HasProto(isprint)                             \
416       SymI_HasProto(isdigit)                             \
417       SymI_HasProto(iscntrl)                             \
418       SymI_HasProto(isalpha)                             \
419       SymI_HasProto(isalnum)                             \
420       SymI_HasProto(isascii)                             \
421       RTS___MINGW_VFPRINTF_SYM                           \
422       SymI_HasProto(strcmp)                              \
423       SymI_HasProto(memmove)                             \
424       SymI_HasProto(realloc)                             \
425       SymI_HasProto(malloc)                              \
426       SymI_HasProto(pow)                                 \
427       SymI_HasProto(tanh)                                \
428       SymI_HasProto(cosh)                                \
429       SymI_HasProto(sinh)                                \
430       SymI_HasProto(atan)                                \
431       SymI_HasProto(acos)                                \
432       SymI_HasProto(asin)                                \
433       SymI_HasProto(tan)                                 \
434       SymI_HasProto(cos)                                 \
435       SymI_HasProto(sin)                                 \
436       SymI_HasProto(exp)                                 \
437       SymI_HasProto(log)                                 \
438       SymI_HasProto(sqrt)                                \
439       SymI_HasProto(powf)                                \
440       SymI_HasProto(tanhf)                               \
441       SymI_HasProto(coshf)                               \
442       SymI_HasProto(sinhf)                               \
443       SymI_HasProto(atanf)                               \
444       SymI_HasProto(acosf)                               \
445       SymI_HasProto(asinf)                               \
446       SymI_HasProto(tanf)                                \
447       SymI_HasProto(cosf)                                \
448       SymI_HasProto(sinf)                                \
449       SymI_HasProto(expf)                                \
450       SymI_HasProto(logf)                                \
451       SymI_HasProto(sqrtf)                               \
452       SymI_HasProto(erf)                                 \
453       SymI_HasProto(erfc)                                \
454       SymI_HasProto(erff)                                \
455       SymI_HasProto(erfcf)                               \
456       SymI_HasProto(memcpy)                              \
457       SymI_HasProto(rts_InstallConsoleEvent)             \
458       SymI_HasProto(rts_ConsoleHandlerDone)              \
459       SymI_NeedsProto(mktime)                            \
460       SymI_NeedsProto(_imp___timezone)                   \
461       SymI_NeedsProto(_imp___tzname)                     \
462       SymI_NeedsProto(_imp__tzname)                      \
463       SymI_NeedsProto(_imp___iob)                        \
464       SymI_NeedsProto(_imp___osver)                      \
465       SymI_NeedsProto(localtime)                         \
466       SymI_NeedsProto(gmtime)                            \
467       SymI_NeedsProto(opendir)                           \
468       SymI_NeedsProto(readdir)                           \
469       SymI_NeedsProto(rewinddir)                         \
470       SymI_NeedsProto(_imp____mb_cur_max)                \
471       SymI_NeedsProto(_imp___pctype)                     \
472       SymI_NeedsProto(__chkstk)                          \
473       RTS_MINGW_GETTIMEOFDAY_SYM                         \
474       SymI_NeedsProto(closedir)
475 #endif
476
477
478 #if defined(darwin_HOST_OS) && HAVE_PRINTF_LDBLSTUB
479 #define RTS_DARWIN_ONLY_SYMBOLS                             \
480      SymI_NeedsProto(asprintf$LDBLStub)                     \
481      SymI_NeedsProto(err$LDBLStub)                          \
482      SymI_NeedsProto(errc$LDBLStub)                         \
483      SymI_NeedsProto(errx$LDBLStub)                         \
484      SymI_NeedsProto(fprintf$LDBLStub)                      \
485      SymI_NeedsProto(fscanf$LDBLStub)                       \
486      SymI_NeedsProto(fwprintf$LDBLStub)                     \
487      SymI_NeedsProto(fwscanf$LDBLStub)                      \
488      SymI_NeedsProto(printf$LDBLStub)                       \
489      SymI_NeedsProto(scanf$LDBLStub)                        \
490      SymI_NeedsProto(snprintf$LDBLStub)                     \
491      SymI_NeedsProto(sprintf$LDBLStub)                      \
492      SymI_NeedsProto(sscanf$LDBLStub)                       \
493      SymI_NeedsProto(strtold$LDBLStub)                      \
494      SymI_NeedsProto(swprintf$LDBLStub)                     \
495      SymI_NeedsProto(swscanf$LDBLStub)                      \
496      SymI_NeedsProto(syslog$LDBLStub)                       \
497      SymI_NeedsProto(vasprintf$LDBLStub)                    \
498      SymI_NeedsProto(verr$LDBLStub)                         \
499      SymI_NeedsProto(verrc$LDBLStub)                        \
500      SymI_NeedsProto(verrx$LDBLStub)                        \
501      SymI_NeedsProto(vfprintf$LDBLStub)                     \
502      SymI_NeedsProto(vfscanf$LDBLStub)                      \
503      SymI_NeedsProto(vfwprintf$LDBLStub)                    \
504      SymI_NeedsProto(vfwscanf$LDBLStub)                     \
505      SymI_NeedsProto(vprintf$LDBLStub)                      \
506      SymI_NeedsProto(vscanf$LDBLStub)                       \
507      SymI_NeedsProto(vsnprintf$LDBLStub)                    \
508      SymI_NeedsProto(vsprintf$LDBLStub)                     \
509      SymI_NeedsProto(vsscanf$LDBLStub)                      \
510      SymI_NeedsProto(vswprintf$LDBLStub)                    \
511      SymI_NeedsProto(vswscanf$LDBLStub)                     \
512      SymI_NeedsProto(vsyslog$LDBLStub)                      \
513      SymI_NeedsProto(vwarn$LDBLStub)                        \
514      SymI_NeedsProto(vwarnc$LDBLStub)                       \
515      SymI_NeedsProto(vwarnx$LDBLStub)                       \
516      SymI_NeedsProto(vwprintf$LDBLStub)                     \
517      SymI_NeedsProto(vwscanf$LDBLStub)                      \
518      SymI_NeedsProto(warn$LDBLStub)                         \
519      SymI_NeedsProto(warnc$LDBLStub)                        \
520      SymI_NeedsProto(warnx$LDBLStub)                        \
521      SymI_NeedsProto(wcstold$LDBLStub)                      \
522      SymI_NeedsProto(wprintf$LDBLStub)                      \
523      SymI_NeedsProto(wscanf$LDBLStub)
524 #else
525 #define RTS_DARWIN_ONLY_SYMBOLS
526 #endif
527
528 #ifndef SMP
529 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
530 #else
531 # define MAIN_CAP_SYM
532 #endif
533
534 #if !defined(mingw32_HOST_OS)
535 #define RTS_USER_SIGNALS_SYMBOLS        \
536    SymI_HasProto(setIOManagerControlFd) \
537    SymI_HasProto(setIOManagerWakeupFd)  \
538    SymI_HasProto(ioManagerWakeup)       \
539    SymI_HasProto(blockUserSignals)      \
540    SymI_HasProto(unblockUserSignals)
541 #else
542 #define RTS_USER_SIGNALS_SYMBOLS        \
543    SymI_HasProto(ioManagerWakeup)       \
544    SymI_HasProto(sendIOManagerEvent)    \
545    SymI_HasProto(readIOManagerEvent)    \
546    SymI_HasProto(getIOManagerEvent)     \
547    SymI_HasProto(console_handler)
548 #endif
549
550 #define RTS_LIBFFI_SYMBOLS                                  \
551      SymE_NeedsProto(ffi_prep_cif)                          \
552      SymE_NeedsProto(ffi_call)                              \
553      SymE_NeedsProto(ffi_type_void)                         \
554      SymE_NeedsProto(ffi_type_float)                        \
555      SymE_NeedsProto(ffi_type_double)                       \
556      SymE_NeedsProto(ffi_type_sint64)                       \
557      SymE_NeedsProto(ffi_type_uint64)                       \
558      SymE_NeedsProto(ffi_type_sint32)                       \
559      SymE_NeedsProto(ffi_type_uint32)                       \
560      SymE_NeedsProto(ffi_type_sint16)                       \
561      SymE_NeedsProto(ffi_type_uint16)                       \
562      SymE_NeedsProto(ffi_type_sint8)                        \
563      SymE_NeedsProto(ffi_type_uint8)                        \
564      SymE_NeedsProto(ffi_type_pointer)
565
566 #ifdef TABLES_NEXT_TO_CODE
567 #define RTS_RET_SYMBOLS /* nothing */
568 #else
569 #define RTS_RET_SYMBOLS                                 \
570       SymI_HasProto(stg_enter_ret)                      \
571       SymI_HasProto(stg_gc_fun_ret)                     \
572       SymI_HasProto(stg_ap_v_ret)                       \
573       SymI_HasProto(stg_ap_f_ret)                       \
574       SymI_HasProto(stg_ap_d_ret)                       \
575       SymI_HasProto(stg_ap_l_ret)                       \
576       SymI_HasProto(stg_ap_n_ret)                       \
577       SymI_HasProto(stg_ap_p_ret)                       \
578       SymI_HasProto(stg_ap_pv_ret)                      \
579       SymI_HasProto(stg_ap_pp_ret)                      \
580       SymI_HasProto(stg_ap_ppv_ret)                     \
581       SymI_HasProto(stg_ap_ppp_ret)                     \
582       SymI_HasProto(stg_ap_pppv_ret)                    \
583       SymI_HasProto(stg_ap_pppp_ret)                    \
584       SymI_HasProto(stg_ap_ppppp_ret)                   \
585       SymI_HasProto(stg_ap_pppppp_ret)
586 #endif
587
588 /* Modules compiled with -ticky may mention ticky counters */
589 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
590 #define RTS_TICKY_SYMBOLS                               \
591       SymI_NeedsProto(ticky_entry_ctrs)                 \
592       SymI_NeedsProto(top_ct)                           \
593                                                         \
594       SymI_HasProto(ENT_VIA_NODE_ctr)                   \
595       SymI_HasProto(ENT_STATIC_THK_ctr)                 \
596       SymI_HasProto(ENT_DYN_THK_ctr)                    \
597       SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr)          \
598       SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr)             \
599       SymI_HasProto(ENT_STATIC_CON_ctr)                 \
600       SymI_HasProto(ENT_DYN_CON_ctr)                    \
601       SymI_HasProto(ENT_STATIC_IND_ctr)                 \
602       SymI_HasProto(ENT_DYN_IND_ctr)                    \
603       SymI_HasProto(ENT_PERM_IND_ctr)                   \
604       SymI_HasProto(ENT_PAP_ctr)                        \
605       SymI_HasProto(ENT_AP_ctr)                         \
606       SymI_HasProto(ENT_AP_STACK_ctr)                   \
607       SymI_HasProto(ENT_BH_ctr)                         \
608       SymI_HasProto(UNKNOWN_CALL_ctr)                   \
609       SymI_HasProto(SLOW_CALL_v_ctr)                    \
610       SymI_HasProto(SLOW_CALL_f_ctr)                    \
611       SymI_HasProto(SLOW_CALL_d_ctr)                    \
612       SymI_HasProto(SLOW_CALL_l_ctr)                    \
613       SymI_HasProto(SLOW_CALL_n_ctr)                    \
614       SymI_HasProto(SLOW_CALL_p_ctr)                    \
615       SymI_HasProto(SLOW_CALL_pv_ctr)                   \
616       SymI_HasProto(SLOW_CALL_pp_ctr)                   \
617       SymI_HasProto(SLOW_CALL_ppv_ctr)                  \
618       SymI_HasProto(SLOW_CALL_ppp_ctr)                  \
619       SymI_HasProto(SLOW_CALL_pppv_ctr)                 \
620       SymI_HasProto(SLOW_CALL_pppp_ctr)                 \
621       SymI_HasProto(SLOW_CALL_ppppp_ctr)                \
622       SymI_HasProto(SLOW_CALL_pppppp_ctr)               \
623       SymI_HasProto(SLOW_CALL_OTHER_ctr)                \
624       SymI_HasProto(ticky_slow_call_unevald)            \
625       SymI_HasProto(SLOW_CALL_ctr)                      \
626       SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr)          \
627       SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr)   \
628       SymI_HasProto(KNOWN_CALL_ctr)                     \
629       SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr)        \
630       SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr)          \
631       SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr)          \
632       SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr)          \
633       SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr)         \
634       SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr)          \
635       SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr)          \
636       SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr)         \
637       SymI_HasProto(SLOW_CALL_UNEVALD_ctr)              \
638       SymI_HasProto(UPDF_OMITTED_ctr)                   \
639       SymI_HasProto(UPDF_PUSHED_ctr)                    \
640       SymI_HasProto(CATCHF_PUSHED_ctr)                  \
641       SymI_HasProto(UPDF_RCC_PUSHED_ctr)                \
642       SymI_HasProto(UPDF_RCC_OMITTED_ctr)               \
643       SymI_HasProto(UPD_SQUEEZED_ctr)                   \
644       SymI_HasProto(UPD_CON_IN_NEW_ctr)                 \
645       SymI_HasProto(UPD_CON_IN_PLACE_ctr)               \
646       SymI_HasProto(UPD_PAP_IN_NEW_ctr)                 \
647       SymI_HasProto(UPD_PAP_IN_PLACE_ctr)               \
648       SymI_HasProto(ALLOC_HEAP_ctr)                     \
649       SymI_HasProto(ALLOC_HEAP_tot)                     \
650       SymI_HasProto(ALLOC_FUN_ctr)                      \
651       SymI_HasProto(ALLOC_FUN_adm)                      \
652       SymI_HasProto(ALLOC_FUN_gds)                      \
653       SymI_HasProto(ALLOC_FUN_slp)                      \
654       SymI_HasProto(UPD_NEW_IND_ctr)                    \
655       SymI_HasProto(UPD_NEW_PERM_IND_ctr)               \
656       SymI_HasProto(UPD_OLD_IND_ctr)                    \
657       SymI_HasProto(UPD_OLD_PERM_IND_ctr)               \
658       SymI_HasProto(UPD_BH_UPDATABLE_ctr)               \
659       SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr)            \
660       SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr)           \
661       SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr)        \
662       SymI_HasProto(GC_SEL_ABANDONED_ctr)               \
663       SymI_HasProto(GC_SEL_MINOR_ctr)                   \
664       SymI_HasProto(GC_SEL_MAJOR_ctr)                   \
665       SymI_HasProto(GC_FAILED_PROMOTION_ctr)            \
666       SymI_HasProto(ALLOC_UP_THK_ctr)                   \
667       SymI_HasProto(ALLOC_SE_THK_ctr)                   \
668       SymI_HasProto(ALLOC_THK_adm)                      \
669       SymI_HasProto(ALLOC_THK_gds)                      \
670       SymI_HasProto(ALLOC_THK_slp)                      \
671       SymI_HasProto(ALLOC_CON_ctr)                      \
672       SymI_HasProto(ALLOC_CON_adm)                      \
673       SymI_HasProto(ALLOC_CON_gds)                      \
674       SymI_HasProto(ALLOC_CON_slp)                      \
675       SymI_HasProto(ALLOC_TUP_ctr)                      \
676       SymI_HasProto(ALLOC_TUP_adm)                      \
677       SymI_HasProto(ALLOC_TUP_gds)                      \
678       SymI_HasProto(ALLOC_TUP_slp)                      \
679       SymI_HasProto(ALLOC_BH_ctr)                       \
680       SymI_HasProto(ALLOC_BH_adm)                       \
681       SymI_HasProto(ALLOC_BH_gds)                       \
682       SymI_HasProto(ALLOC_BH_slp)                       \
683       SymI_HasProto(ALLOC_PRIM_ctr)                     \
684       SymI_HasProto(ALLOC_PRIM_adm)                     \
685       SymI_HasProto(ALLOC_PRIM_gds)                     \
686       SymI_HasProto(ALLOC_PRIM_slp)                     \
687       SymI_HasProto(ALLOC_PAP_ctr)                      \
688       SymI_HasProto(ALLOC_PAP_adm)                      \
689       SymI_HasProto(ALLOC_PAP_gds)                      \
690       SymI_HasProto(ALLOC_PAP_slp)                      \
691       SymI_HasProto(ALLOC_TSO_ctr)                      \
692       SymI_HasProto(ALLOC_TSO_adm)                      \
693       SymI_HasProto(ALLOC_TSO_gds)                      \
694       SymI_HasProto(ALLOC_TSO_slp)                      \
695       SymI_HasProto(RET_NEW_ctr)                        \
696       SymI_HasProto(RET_OLD_ctr)                        \
697       SymI_HasProto(RET_UNBOXED_TUP_ctr)                \
698       SymI_HasProto(RET_SEMI_loads_avoided)
699
700
701 // On most platforms, the garbage collector rewrites references
702 //      to small integer and char objects to a set of common, shared ones.
703 //
704 // We don't do this when compiling to Windows DLLs at the moment because
705 //      it doesn't support cross package data references well.
706 //
707 #if defined(__PIC__) && defined(mingw32_HOST_OS)
708 #define RTS_INTCHAR_SYMBOLS
709 #else
710 #define RTS_INTCHAR_SYMBOLS                             \
711       SymI_HasProto(stg_CHARLIKE_closure)               \
712       SymI_HasProto(stg_INTLIKE_closure)
713 #endif
714
715
716 #define RTS_SYMBOLS                                     \
717       Maybe_Stable_Names                                \
718       RTS_TICKY_SYMBOLS                                 \
719       SymI_HasProto(StgReturn)                          \
720       SymI_HasProto(stg_enter_info)                     \
721       SymI_HasProto(stg_gc_void_info)                   \
722       SymI_HasProto(__stg_gc_enter_1)                   \
723       SymI_HasProto(stg_gc_noregs)                      \
724       SymI_HasProto(stg_gc_unpt_r1_info)                \
725       SymI_HasProto(stg_gc_unpt_r1)                     \
726       SymI_HasProto(stg_gc_unbx_r1_info)                \
727       SymI_HasProto(stg_gc_unbx_r1)                     \
728       SymI_HasProto(stg_gc_f1_info)                     \
729       SymI_HasProto(stg_gc_f1)                          \
730       SymI_HasProto(stg_gc_d1_info)                     \
731       SymI_HasProto(stg_gc_d1)                          \
732       SymI_HasProto(stg_gc_l1_info)                     \
733       SymI_HasProto(stg_gc_l1)                          \
734       SymI_HasProto(__stg_gc_fun)                       \
735       SymI_HasProto(stg_gc_fun_info)                    \
736       SymI_HasProto(stg_gc_gen)                         \
737       SymI_HasProto(stg_gc_gen_info)                    \
738       SymI_HasProto(stg_gc_gen_hp)                      \
739       SymI_HasProto(stg_gc_ut)                          \
740       SymI_HasProto(stg_gen_yield)                      \
741       SymI_HasProto(stg_yield_noregs)                   \
742       SymI_HasProto(stg_yield_to_interpreter)           \
743       SymI_HasProto(stg_gen_block)                      \
744       SymI_HasProto(stg_block_noregs)                   \
745       SymI_HasProto(stg_block_1)                        \
746       SymI_HasProto(stg_block_takemvar)                 \
747       SymI_HasProto(stg_block_putmvar)                  \
748       MAIN_CAP_SYM                                      \
749       SymI_HasProto(MallocFailHook)                     \
750       SymI_HasProto(OnExitHook)                         \
751       SymI_HasProto(OutOfHeapHook)                      \
752       SymI_HasProto(StackOverflowHook)                  \
753       SymI_HasProto(addDLL)                             \
754       SymI_HasProto(__int_encodeDouble)                 \
755       SymI_HasProto(__word_encodeDouble)                \
756       SymI_HasProto(__2Int_encodeDouble)                \
757       SymI_HasProto(__int_encodeFloat)                  \
758       SymI_HasProto(__word_encodeFloat)                 \
759       SymI_HasProto(stg_atomicallyzh)                   \
760       SymI_HasProto(barf)                               \
761       SymI_HasProto(debugBelch)                         \
762       SymI_HasProto(errorBelch)                         \
763       SymI_HasProto(sysErrorBelch)                      \
764       SymI_HasProto(stg_getMaskingStatezh)              \
765       SymI_HasProto(stg_maskAsyncExceptionszh)          \
766       SymI_HasProto(stg_maskUninterruptiblezh)          \
767       SymI_HasProto(stg_catchzh)                        \
768       SymI_HasProto(stg_catchRetryzh)                   \
769       SymI_HasProto(stg_catchSTMzh)                     \
770       SymI_HasProto(stg_checkzh)                        \
771       SymI_HasProto(closure_flags)                      \
772       SymI_HasProto(cmp_thread)                         \
773       SymI_HasProto(createAdjustor)                     \
774       SymI_HasProto(stg_decodeDoublezu2Intzh)           \
775       SymI_HasProto(stg_decodeFloatzuIntzh)             \
776       SymI_HasProto(defaultsHook)                       \
777       SymI_HasProto(stg_delayzh)                        \
778       SymI_HasProto(stg_deRefWeakzh)                    \
779       SymI_HasProto(stg_deRefStablePtrzh)               \
780       SymI_HasProto(dirty_MUT_VAR)                      \
781       SymI_HasProto(stg_forkzh)                         \
782       SymI_HasProto(stg_forkOnzh)                       \
783       SymI_HasProto(forkProcess)                        \
784       SymI_HasProto(forkOS_createThread)                \
785       SymI_HasProto(freeHaskellFunctionPtr)             \
786       SymI_HasProto(getOrSetTypeableStore)              \
787       SymI_HasProto(getOrSetGHCConcSignalSignalHandlerStore)            \
788       SymI_HasProto(getOrSetGHCConcWindowsPendingDelaysStore)           \
789       SymI_HasProto(getOrSetGHCConcWindowsIOManagerThreadStore)         \
790       SymI_HasProto(getOrSetGHCConcWindowsProddingStore)                \
791       SymI_HasProto(getOrSetSystemEventThreadEventManagerStore)         \
792       SymI_HasProto(getOrSetSystemEventThreadIOManagerThreadStore)      \
793       SymI_HasProto(genSymZh)                           \
794       SymI_HasProto(genericRaise)                       \
795       SymI_HasProto(getProgArgv)                        \
796       SymI_HasProto(getFullProgArgv)                    \
797       SymI_HasProto(getStablePtr)                       \
798       SymI_HasProto(hs_init)                            \
799       SymI_HasProto(hs_exit)                            \
800       SymI_HasProto(hs_set_argv)                        \
801       SymI_HasProto(hs_add_root)                        \
802       SymI_HasProto(hs_perform_gc)                      \
803       SymI_HasProto(hs_free_stable_ptr)                 \
804       SymI_HasProto(hs_free_fun_ptr)                    \
805       SymI_HasProto(hs_hpc_rootModule)                  \
806       SymI_HasProto(hs_hpc_module)                      \
807       SymI_HasProto(initLinker)                         \
808       SymI_HasProto(stg_unpackClosurezh)                \
809       SymI_HasProto(stg_getApStackValzh)                \
810       SymI_HasProto(stg_getSparkzh)                     \
811       SymI_HasProto(stg_numSparkszh)                    \
812       SymI_HasProto(stg_isCurrentThreadBoundzh)         \
813       SymI_HasProto(stg_isEmptyMVarzh)                  \
814       SymI_HasProto(stg_killThreadzh)                   \
815       SymI_HasProto(loadArchive)                        \
816       SymI_HasProto(loadObj)                            \
817       SymI_HasProto(insertStableSymbol)                 \
818       SymI_HasProto(insertSymbol)                       \
819       SymI_HasProto(lookupSymbol)                       \
820       SymI_HasProto(stg_makeStablePtrzh)                \
821       SymI_HasProto(stg_mkApUpd0zh)                     \
822       SymI_HasProto(stg_myThreadIdzh)                   \
823       SymI_HasProto(stg_labelThreadzh)                  \
824       SymI_HasProto(stg_newArrayzh)                     \
825       SymI_HasProto(stg_newBCOzh)                       \
826       SymI_HasProto(stg_newByteArrayzh)                 \
827       SymI_HasProto_redirect(newCAF, newDynCAF)         \
828       SymI_HasProto(stg_newMVarzh)                      \
829       SymI_HasProto(stg_newMutVarzh)                    \
830       SymI_HasProto(stg_newTVarzh)                      \
831       SymI_HasProto(stg_noDuplicatezh)                  \
832       SymI_HasProto(stg_atomicModifyMutVarzh)           \
833       SymI_HasProto(stg_newPinnedByteArrayzh)           \
834       SymI_HasProto(stg_newAlignedPinnedByteArrayzh)    \
835       SymI_HasProto(newSpark)                           \
836       SymI_HasProto(performGC)                          \
837       SymI_HasProto(performMajorGC)                     \
838       SymI_HasProto(prog_argc)                          \
839       SymI_HasProto(prog_argv)                          \
840       SymI_HasProto(stg_putMVarzh)                      \
841       SymI_HasProto(stg_raisezh)                        \
842       SymI_HasProto(stg_raiseIOzh)                      \
843       SymI_HasProto(stg_readTVarzh)                     \
844       SymI_HasProto(stg_readTVarIOzh)                   \
845       SymI_HasProto(resumeThread)                       \
846       SymI_HasProto(resolveObjs)                        \
847       SymI_HasProto(stg_retryzh)                        \
848       SymI_HasProto(rts_apply)                          \
849       SymI_HasProto(rts_checkSchedStatus)               \
850       SymI_HasProto(rts_eval)                           \
851       SymI_HasProto(rts_evalIO)                         \
852       SymI_HasProto(rts_evalLazyIO)                     \
853       SymI_HasProto(rts_evalStableIO)                   \
854       SymI_HasProto(rts_eval_)                          \
855       SymI_HasProto(rts_getBool)                        \
856       SymI_HasProto(rts_getChar)                        \
857       SymI_HasProto(rts_getDouble)                      \
858       SymI_HasProto(rts_getFloat)                       \
859       SymI_HasProto(rts_getInt)                         \
860       SymI_HasProto(rts_getInt8)                        \
861       SymI_HasProto(rts_getInt16)                       \
862       SymI_HasProto(rts_getInt32)                       \
863       SymI_HasProto(rts_getInt64)                       \
864       SymI_HasProto(rts_getPtr)                         \
865       SymI_HasProto(rts_getFunPtr)                      \
866       SymI_HasProto(rts_getStablePtr)                   \
867       SymI_HasProto(rts_getThreadId)                    \
868       SymI_HasProto(rts_getWord)                        \
869       SymI_HasProto(rts_getWord8)                       \
870       SymI_HasProto(rts_getWord16)                      \
871       SymI_HasProto(rts_getWord32)                      \
872       SymI_HasProto(rts_getWord64)                      \
873       SymI_HasProto(rts_lock)                           \
874       SymI_HasProto(rts_mkBool)                         \
875       SymI_HasProto(rts_mkChar)                         \
876       SymI_HasProto(rts_mkDouble)                       \
877       SymI_HasProto(rts_mkFloat)                        \
878       SymI_HasProto(rts_mkInt)                          \
879       SymI_HasProto(rts_mkInt8)                         \
880       SymI_HasProto(rts_mkInt16)                        \
881       SymI_HasProto(rts_mkInt32)                        \
882       SymI_HasProto(rts_mkInt64)                        \
883       SymI_HasProto(rts_mkPtr)                          \
884       SymI_HasProto(rts_mkFunPtr)                       \
885       SymI_HasProto(rts_mkStablePtr)                    \
886       SymI_HasProto(rts_mkString)                       \
887       SymI_HasProto(rts_mkWord)                         \
888       SymI_HasProto(rts_mkWord8)                        \
889       SymI_HasProto(rts_mkWord16)                       \
890       SymI_HasProto(rts_mkWord32)                       \
891       SymI_HasProto(rts_mkWord64)                       \
892       SymI_HasProto(rts_unlock)                         \
893       SymI_HasProto(rts_unsafeGetMyCapability)          \
894       SymI_HasProto(rtsSupportsBoundThreads)            \
895       SymI_HasProto(rts_isProfiled)                     \
896       SymI_HasProto(setProgArgv)                        \
897       SymI_HasProto(startupHaskell)                     \
898       SymI_HasProto(shutdownHaskell)                    \
899       SymI_HasProto(shutdownHaskellAndExit)             \
900       SymI_HasProto(stable_ptr_table)                   \
901       SymI_HasProto(stackOverflow)                      \
902       SymI_HasProto(stg_CAF_BLACKHOLE_info)             \
903       SymI_HasProto(stg_BLACKHOLE_info)                 \
904       SymI_HasProto(__stg_EAGER_BLACKHOLE_info)         \
905       SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info)      \
906       SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info)      \
907       SymI_HasProto(startTimer)                         \
908       SymI_HasProto(stg_MVAR_CLEAN_info)                \
909       SymI_HasProto(stg_MVAR_DIRTY_info)                \
910       SymI_HasProto(stg_IND_STATIC_info)                \
911       SymI_HasProto(stg_ARR_WORDS_info)                 \
912       SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info)        \
913       SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info)       \
914       SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info)      \
915       SymI_HasProto(stg_WEAK_info)                      \
916       SymI_HasProto(stg_ap_v_info)                      \
917       SymI_HasProto(stg_ap_f_info)                      \
918       SymI_HasProto(stg_ap_d_info)                      \
919       SymI_HasProto(stg_ap_l_info)                      \
920       SymI_HasProto(stg_ap_n_info)                      \
921       SymI_HasProto(stg_ap_p_info)                      \
922       SymI_HasProto(stg_ap_pv_info)                     \
923       SymI_HasProto(stg_ap_pp_info)                     \
924       SymI_HasProto(stg_ap_ppv_info)                    \
925       SymI_HasProto(stg_ap_ppp_info)                    \
926       SymI_HasProto(stg_ap_pppv_info)                   \
927       SymI_HasProto(stg_ap_pppp_info)                   \
928       SymI_HasProto(stg_ap_ppppp_info)                  \
929       SymI_HasProto(stg_ap_pppppp_info)                 \
930       SymI_HasProto(stg_ap_0_fast)                      \
931       SymI_HasProto(stg_ap_v_fast)                      \
932       SymI_HasProto(stg_ap_f_fast)                      \
933       SymI_HasProto(stg_ap_d_fast)                      \
934       SymI_HasProto(stg_ap_l_fast)                      \
935       SymI_HasProto(stg_ap_n_fast)                      \
936       SymI_HasProto(stg_ap_p_fast)                      \
937       SymI_HasProto(stg_ap_pv_fast)                     \
938       SymI_HasProto(stg_ap_pp_fast)                     \
939       SymI_HasProto(stg_ap_ppv_fast)                    \
940       SymI_HasProto(stg_ap_ppp_fast)                    \
941       SymI_HasProto(stg_ap_pppv_fast)                   \
942       SymI_HasProto(stg_ap_pppp_fast)                   \
943       SymI_HasProto(stg_ap_ppppp_fast)                  \
944       SymI_HasProto(stg_ap_pppppp_fast)                 \
945       SymI_HasProto(stg_ap_1_upd_info)                  \
946       SymI_HasProto(stg_ap_2_upd_info)                  \
947       SymI_HasProto(stg_ap_3_upd_info)                  \
948       SymI_HasProto(stg_ap_4_upd_info)                  \
949       SymI_HasProto(stg_ap_5_upd_info)                  \
950       SymI_HasProto(stg_ap_6_upd_info)                  \
951       SymI_HasProto(stg_ap_7_upd_info)                  \
952       SymI_HasProto(stg_exit)                           \
953       SymI_HasProto(stg_sel_0_upd_info)                 \
954       SymI_HasProto(stg_sel_10_upd_info)                \
955       SymI_HasProto(stg_sel_11_upd_info)                \
956       SymI_HasProto(stg_sel_12_upd_info)                \
957       SymI_HasProto(stg_sel_13_upd_info)                \
958       SymI_HasProto(stg_sel_14_upd_info)                \
959       SymI_HasProto(stg_sel_15_upd_info)                \
960       SymI_HasProto(stg_sel_1_upd_info)                 \
961       SymI_HasProto(stg_sel_2_upd_info)                 \
962       SymI_HasProto(stg_sel_3_upd_info)                 \
963       SymI_HasProto(stg_sel_4_upd_info)                 \
964       SymI_HasProto(stg_sel_5_upd_info)                 \
965       SymI_HasProto(stg_sel_6_upd_info)                 \
966       SymI_HasProto(stg_sel_7_upd_info)                 \
967       SymI_HasProto(stg_sel_8_upd_info)                 \
968       SymI_HasProto(stg_sel_9_upd_info)                 \
969       SymI_HasProto(stg_upd_frame_info)                 \
970       SymI_HasProto(stg_bh_upd_frame_info)              \
971       SymI_HasProto(suspendThread)                      \
972       SymI_HasProto(stg_takeMVarzh)                     \
973       SymI_HasProto(stg_threadStatuszh)                 \
974       SymI_HasProto(stg_tryPutMVarzh)                   \
975       SymI_HasProto(stg_tryTakeMVarzh)                  \
976       SymI_HasProto(stg_unmaskAsyncExceptionszh)        \
977       SymI_HasProto(unloadObj)                          \
978       SymI_HasProto(stg_unsafeThawArrayzh)              \
979       SymI_HasProto(stg_waitReadzh)                     \
980       SymI_HasProto(stg_waitWritezh)                    \
981       SymI_HasProto(stg_writeTVarzh)                    \
982       SymI_HasProto(stg_yieldzh)                        \
983       SymI_NeedsProto(stg_interp_constr_entry)          \
984       SymI_HasProto(stg_arg_bitmaps)                    \
985       SymI_HasProto(large_alloc_lim)                    \
986       SymI_HasProto(g0)                                 \
987       SymI_HasProto(allocate)                           \
988       SymI_HasProto(allocateExec)                       \
989       SymI_HasProto(freeExec)                           \
990       SymI_HasProto(getAllocations)                     \
991       SymI_HasProto(revertCAFs)                         \
992       SymI_HasProto(RtsFlags)                           \
993       SymI_NeedsProto(rts_breakpoint_io_action)         \
994       SymI_NeedsProto(rts_stop_next_breakpoint)         \
995       SymI_NeedsProto(rts_stop_on_exception)            \
996       SymI_HasProto(stopTimer)                          \
997       SymI_HasProto(n_capabilities)                     \
998       SymI_HasProto(stg_traceCcszh)                     \
999       SymI_HasProto(stg_traceEventzh)                   \
1000       RTS_USER_SIGNALS_SYMBOLS                          \
1001       RTS_INTCHAR_SYMBOLS
1002
1003
1004 // 64-bit support functions in libgcc.a
1005 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
1006 #define RTS_LIBGCC_SYMBOLS                             \
1007       SymI_NeedsProto(__divdi3)                        \
1008       SymI_NeedsProto(__udivdi3)                       \
1009       SymI_NeedsProto(__moddi3)                        \
1010       SymI_NeedsProto(__umoddi3)                       \
1011       SymI_NeedsProto(__muldi3)                        \
1012       SymI_NeedsProto(__ashldi3)                       \
1013       SymI_NeedsProto(__ashrdi3)                       \
1014       SymI_NeedsProto(__lshrdi3)
1015 #else
1016 #define RTS_LIBGCC_SYMBOLS
1017 #endif
1018
1019 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
1020       // Symbols that don't have a leading underscore
1021       // on Mac OS X. They have to receive special treatment,
1022       // see machoInitSymbolsWithoutUnderscore()
1023 #define RTS_MACHO_NOUNDERLINE_SYMBOLS                   \
1024       SymI_NeedsProto(saveFP)                           \
1025       SymI_NeedsProto(restFP)
1026 #endif
1027
1028 /* entirely bogus claims about types of these symbols */
1029 #define SymI_NeedsProto(vvv)  extern void vvv(void);
1030 #if defined(__PIC__) && defined(mingw32_HOST_OS)
1031 #define SymE_HasProto(vvv)    SymE_HasProto(vvv);
1032 #define SymE_NeedsProto(vvv)    extern void _imp__ ## vvv (void);
1033 #else
1034 #define SymE_NeedsProto(vvv)  SymI_NeedsProto(vvv);
1035 #define SymE_HasProto(vvv)    SymI_HasProto(vvv)
1036 #endif
1037 #define SymI_HasProto(vvv) /**/
1038 #define SymI_HasProto_redirect(vvv,xxx) /**/
1039 RTS_SYMBOLS
1040 RTS_RET_SYMBOLS
1041 RTS_POSIX_ONLY_SYMBOLS
1042 RTS_MINGW_ONLY_SYMBOLS
1043 RTS_CYGWIN_ONLY_SYMBOLS
1044 RTS_DARWIN_ONLY_SYMBOLS
1045 RTS_LIBGCC_SYMBOLS
1046 RTS_LIBFFI_SYMBOLS
1047 #undef SymI_NeedsProto
1048 #undef SymI_HasProto
1049 #undef SymI_HasProto_redirect
1050 #undef SymE_HasProto
1051 #undef SymE_NeedsProto
1052
1053 #ifdef LEADING_UNDERSCORE
1054 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1055 #else
1056 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1057 #endif
1058
1059 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1060                     (void*)(&(vvv)) },
1061 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1062             (void*)DLL_IMPORT_DATA_REF(vvv) },
1063
1064 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1065 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1066
1067 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1068 // another symbol.  See newCAF/newDynCAF for an example.
1069 #define SymI_HasProto_redirect(vvv,xxx)   \
1070     { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1071       (void*)(&(xxx)) },
1072
1073 static RtsSymbolVal rtsSyms[] = {
1074       RTS_SYMBOLS
1075       RTS_RET_SYMBOLS
1076       RTS_POSIX_ONLY_SYMBOLS
1077       RTS_MINGW_ONLY_SYMBOLS
1078       RTS_CYGWIN_ONLY_SYMBOLS
1079       RTS_DARWIN_ONLY_SYMBOLS
1080       RTS_LIBGCC_SYMBOLS
1081       RTS_LIBFFI_SYMBOLS
1082 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1083       // dyld stub code contains references to this,
1084       // but it should never be called because we treat
1085       // lazy pointers as nonlazy.
1086       { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1087 #endif
1088       { 0, 0 } /* sentinel */
1089 };
1090
1091
1092
1093 /* -----------------------------------------------------------------------------
1094  * Insert symbols into hash tables, checking for duplicates.
1095  */
1096
1097 static void ghciInsertStrHashTable ( char* obj_name,
1098                                      HashTable *table,
1099                                      char* key,
1100                                      void *data
1101                                    )
1102 {
1103    if (lookupHashTable(table, (StgWord)key) == NULL)
1104    {
1105       insertStrHashTable(table, (StgWord)key, data);
1106       return;
1107    }
1108    debugBelch(
1109       "\n\n"
1110       "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1111       "   %s\n"
1112       "whilst processing object file\n"
1113       "   %s\n"
1114       "This could be caused by:\n"
1115       "   * Loading two different object files which export the same symbol\n"
1116       "   * Specifying the same object file twice on the GHCi command line\n"
1117       "   * An incorrect `package.conf' entry, causing some object to be\n"
1118       "     loaded twice.\n"
1119       "GHCi cannot safely continue in this situation.  Exiting now.  Sorry.\n"
1120       "\n",
1121       (char*)key,
1122       obj_name
1123    );
1124    stg_exit(1);
1125 }
1126 /* -----------------------------------------------------------------------------
1127  * initialize the object linker
1128  */
1129
1130
1131 static int linker_init_done = 0 ;
1132
1133 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1134 static void *dl_prog_handle;
1135 static regex_t re_invalid;
1136 static regex_t re_realso;
1137 #ifdef THREADED_RTS
1138 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1139 #endif
1140 #endif
1141
1142 void
1143 initLinker( void )
1144 {
1145     RtsSymbolVal *sym;
1146 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1147     int compileResult;
1148 #endif
1149
1150     IF_DEBUG(linker, debugBelch("initLinker: start\n"));
1151
1152     /* Make initLinker idempotent, so we can call it
1153        before evey relevant operation; that means we
1154        don't need to initialise the linker separately */
1155     if (linker_init_done == 1) {
1156         IF_DEBUG(linker, debugBelch("initLinker: idempotent return\n"));
1157         return;
1158     } else {
1159         linker_init_done = 1;
1160     }
1161
1162 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1163     initMutex(&dl_mutex);
1164 #endif
1165     stablehash = allocStrHashTable();
1166     symhash = allocStrHashTable();
1167
1168     /* populate the symbol table with stuff from the RTS */
1169     for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1170         ghciInsertStrHashTable("(GHCi built-in symbols)",
1171                                symhash, sym->lbl, sym->addr);
1172         IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
1173     }
1174 #   if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1175     machoInitSymbolsWithoutUnderscore();
1176 #   endif
1177
1178 #   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1179 #   if defined(RTLD_DEFAULT)
1180     dl_prog_handle = RTLD_DEFAULT;
1181 #   else
1182     dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1183 #   endif /* RTLD_DEFAULT */
1184
1185     compileResult = regcomp(&re_invalid,
1186            "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*invalid ELF header",
1187            REG_EXTENDED);
1188     ASSERT( compileResult == 0 );
1189     compileResult = regcomp(&re_realso,
1190            "GROUP *\\( *(([^ )])+)",
1191            REG_EXTENDED);
1192     ASSERT( compileResult == 0 );
1193 #   endif
1194
1195 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1196     if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1197         // User-override for mmap_32bit_base
1198         mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1199     }
1200 #endif
1201
1202 #if defined(mingw32_HOST_OS)
1203     /*
1204      * These two libraries cause problems when added to the static link,
1205      * but are necessary for resolving symbols in GHCi, hence we load
1206      * them manually here.
1207      */
1208     addDLL("msvcrt");
1209     addDLL("kernel32");
1210 #endif
1211
1212     IF_DEBUG(linker, debugBelch("initLinker: done\n"));
1213     return;
1214 }
1215
1216 void
1217 exitLinker( void ) {
1218 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1219    if (linker_init_done == 1) {
1220       regfree(&re_invalid);
1221       regfree(&re_realso);
1222 #ifdef THREADED_RTS
1223       closeMutex(&dl_mutex);
1224 #endif
1225    }
1226 #endif
1227 }
1228
1229 /* -----------------------------------------------------------------------------
1230  *                  Loading DLL or .so dynamic libraries
1231  * -----------------------------------------------------------------------------
1232  *
1233  * Add a DLL from which symbols may be found.  In the ELF case, just
1234  * do RTLD_GLOBAL-style add, so no further messing around needs to
1235  * happen in order that symbols in the loaded .so are findable --
1236  * lookupSymbol() will subsequently see them by dlsym on the program's
1237  * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
1238  *
1239  * In the PEi386 case, open the DLLs and put handles to them in a
1240  * linked list.  When looking for a symbol, try all handles in the
1241  * list.  This means that we need to load even DLLs that are guaranteed
1242  * to be in the ghc.exe image already, just so we can get a handle
1243  * to give to loadSymbol, so that we can find the symbols.  For such
1244  * libraries, the LoadLibrary call should be a no-op except for returning
1245  * the handle.
1246  *
1247  */
1248
1249 #if defined(OBJFORMAT_PEi386)
1250 /* A record for storing handles into DLLs. */
1251
1252 typedef
1253    struct _OpenedDLL {
1254       char*              name;
1255       struct _OpenedDLL* next;
1256       HINSTANCE instance;
1257    }
1258    OpenedDLL;
1259
1260 /* A list thereof. */
1261 static OpenedDLL* opened_dlls = NULL;
1262 #endif
1263
1264 #  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1265
1266 static const char *
1267 internal_dlopen(const char *dll_name)
1268 {
1269    void *hdl;
1270    const char *errmsg;
1271    char *errmsg_copy;
1272
1273    // omitted: RTLD_NOW
1274    // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1275    IF_DEBUG(linker,
1276       debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1277
1278    //-------------- Begin critical section ------------------
1279    // This critical section is necessary because dlerror() is not
1280    // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1281    // Also, the error message returned must be copied to preserve it
1282    // (see POSIX also)
1283
1284    ACQUIRE_LOCK(&dl_mutex);
1285    hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1286
1287    errmsg = NULL;
1288    if (hdl == NULL) {
1289       /* dlopen failed; return a ptr to the error msg. */
1290       errmsg = dlerror();
1291       if (errmsg == NULL) errmsg = "addDLL: unknown error";
1292       errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1293       strcpy(errmsg_copy, errmsg);
1294       errmsg = errmsg_copy;
1295    }
1296    RELEASE_LOCK(&dl_mutex);
1297    //--------------- End critical section -------------------
1298
1299    return errmsg;
1300 }
1301 #  endif
1302
1303 const char *
1304 addDLL( char *dll_name )
1305 {
1306 #  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1307    /* ------------------- ELF DLL loader ------------------- */
1308
1309 #define NMATCH 5
1310    regmatch_t match[NMATCH];
1311    const char *errmsg;
1312    FILE* fp;
1313    size_t match_length;
1314 #define MAXLINE 1000
1315    char line[MAXLINE];
1316    int result;
1317
1318    initLinker();
1319
1320    IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1321    errmsg = internal_dlopen(dll_name);
1322
1323    if (errmsg == NULL) {
1324       return NULL;
1325    }
1326
1327    // GHC Trac ticket #2615
1328    // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1329    // contain linker scripts rather than ELF-format object code. This
1330    // code handles the situation by recognizing the real object code
1331    // file name given in the linker script.
1332    //
1333    // If an "invalid ELF header" error occurs, it is assumed that the
1334    // .so file contains a linker script instead of ELF object code.
1335    // In this case, the code looks for the GROUP ( ... ) linker
1336    // directive. If one is found, the first file name inside the
1337    // parentheses is treated as the name of a dynamic library and the
1338    // code attempts to dlopen that file. If this is also unsuccessful,
1339    // an error message is returned.
1340
1341    // see if the error message is due to an invalid ELF header
1342    IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1343    result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1344    IF_DEBUG(linker, debugBelch("result = %i\n", result));
1345    if (result == 0) {
1346       // success -- try to read the named file as a linker script
1347       match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1348                                  MAXLINE-1);
1349       strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1350       line[match_length] = '\0'; // make sure string is null-terminated
1351       IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1352       if ((fp = fopen(line, "r")) == NULL) {
1353          return errmsg; // return original error if open fails
1354       }
1355       // try to find a GROUP ( ... ) command
1356       while (fgets(line, MAXLINE, fp) != NULL) {
1357          IF_DEBUG(linker, debugBelch("input line = %s", line));
1358          if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1359             // success -- try to dlopen the first named file
1360             IF_DEBUG(linker, debugBelch("match%s\n",""));
1361             line[match[1].rm_eo] = '\0';
1362             errmsg = internal_dlopen(line+match[1].rm_so);
1363             break;
1364          }
1365          // if control reaches here, no GROUP ( ... ) directive was found
1366          // and the original error message is returned to the caller
1367       }
1368       fclose(fp);
1369    }
1370    return errmsg;
1371
1372 #  elif defined(OBJFORMAT_PEi386)
1373    /* ------------------- Win32 DLL loader ------------------- */
1374
1375    char*      buf;
1376    OpenedDLL* o_dll;
1377    HINSTANCE  instance;
1378
1379    initLinker();
1380
1381    /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1382
1383    /* See if we've already got it, and ignore if so. */
1384    for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1385       if (0 == strcmp(o_dll->name, dll_name))
1386          return NULL;
1387    }
1388
1389    /* The file name has no suffix (yet) so that we can try
1390       both foo.dll and foo.drv
1391
1392       The documentation for LoadLibrary says:
1393         If no file name extension is specified in the lpFileName
1394         parameter, the default library extension .dll is
1395         appended. However, the file name string can include a trailing
1396         point character (.) to indicate that the module name has no
1397         extension. */
1398
1399    buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
1400    sprintf(buf, "%s.DLL", dll_name);
1401    instance = LoadLibrary(buf);
1402    if (instance == NULL) {
1403        if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1404        // KAA: allow loading of drivers (like winspool.drv)
1405        sprintf(buf, "%s.DRV", dll_name);
1406        instance = LoadLibrary(buf);
1407        if (instance == NULL) {
1408            if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1409            // #1883: allow loading of unix-style libfoo.dll DLLs
1410            sprintf(buf, "lib%s.DLL", dll_name);
1411            instance = LoadLibrary(buf);
1412            if (instance == NULL) {
1413                goto error;
1414            }
1415        }
1416    }
1417    stgFree(buf);
1418
1419    /* Add this DLL to the list of DLLs in which to search for symbols. */
1420    o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1421    o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
1422    strcpy(o_dll->name, dll_name);
1423    o_dll->instance = instance;
1424    o_dll->next     = opened_dlls;
1425    opened_dlls     = o_dll;
1426
1427    return NULL;
1428
1429 error:
1430    stgFree(buf);
1431    sysErrorBelch(dll_name);
1432
1433    /* LoadLibrary failed; return a ptr to the error msg. */
1434    return "addDLL: could not load DLL";
1435
1436 #  else
1437    barf("addDLL: not implemented on this platform");
1438 #  endif
1439 }
1440
1441 /* -----------------------------------------------------------------------------
1442  * insert a stable symbol in the hash table
1443  */
1444
1445 void
1446 insertStableSymbol(char* obj_name, char* key, StgPtr p)
1447 {
1448   ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1449 }
1450
1451
1452 /* -----------------------------------------------------------------------------
1453  * insert a symbol in the hash table
1454  */
1455 void
1456 insertSymbol(char* obj_name, char* key, void* data)
1457 {
1458   ghciInsertStrHashTable(obj_name, symhash, key, data);
1459 }
1460
1461 /* -----------------------------------------------------------------------------
1462  * lookup a symbol in the hash table
1463  */
1464 void *
1465 lookupSymbol( char *lbl )
1466 {
1467     void *val;
1468     IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s\n", lbl));
1469     initLinker() ;
1470     ASSERT(symhash != NULL);
1471     val = lookupStrHashTable(symhash, lbl);
1472
1473     if (val == NULL) {
1474         IF_DEBUG(linker, debugBelch("lookupSymbol: symbol not found\n"));
1475 #       if defined(OBJFORMAT_ELF)
1476         return dlsym(dl_prog_handle, lbl);
1477 #       elif defined(OBJFORMAT_MACHO)
1478 #       if HAVE_DLFCN_H
1479         /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1480            interface.
1481
1482            HACK: On OS X, global symbols are prefixed with an underscore.
1483                  However, dlsym wants us to omit the leading underscore from the
1484                  symbol name. For now, we simply strip it off here (and ONLY
1485                  here).
1486         */
1487         IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s with dlsym\n", lbl));
1488         ASSERT(lbl[0] == '_');
1489         return dlsym(dl_prog_handle, lbl+1);
1490 #       else
1491         if(NSIsSymbolNameDefined(lbl)) {
1492             NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1493             return NSAddressOfSymbol(symbol);
1494         } else {
1495             return NULL;
1496         }
1497 #       endif /* HAVE_DLFCN_H */
1498 #       elif defined(OBJFORMAT_PEi386)
1499         void* sym;
1500
1501         sym = lookupSymbolInDLLs((unsigned char*)lbl);
1502         if (sym != NULL) { return sym; };
1503
1504         // Also try looking up the symbol without the @N suffix.  Some
1505         // DLLs have the suffixes on their symbols, some don't.
1506         zapTrailingAtSign ( (unsigned char*)lbl );
1507         sym = lookupSymbolInDLLs((unsigned char*)lbl);
1508         if (sym != NULL) { return sym; };
1509         return NULL;
1510
1511 #       else
1512         ASSERT(2+2 == 5);
1513         return NULL;
1514 #       endif
1515     } else {
1516         IF_DEBUG(linker, debugBelch("lookupSymbol: value of %s is %p\n", lbl, val));
1517         return val;
1518     }
1519 }
1520
1521 /* -----------------------------------------------------------------------------
1522  * Debugging aid: look in GHCi's object symbol tables for symbols
1523  * within DELTA bytes of the specified address, and show their names.
1524  */
1525 #ifdef DEBUG
1526 void ghci_enquire ( char* addr );
1527
1528 void ghci_enquire ( char* addr )
1529 {
1530    int   i;
1531    char* sym;
1532    char* a;
1533    const int DELTA = 64;
1534    ObjectCode* oc;
1535
1536    initLinker();
1537
1538    for (oc = objects; oc; oc = oc->next) {
1539       for (i = 0; i < oc->n_symbols; i++) {
1540          sym = oc->symbols[i];
1541          if (sym == NULL) continue;
1542          a = NULL;
1543          if (a == NULL) {
1544             a = lookupStrHashTable(symhash, sym);
1545          }
1546          if (a == NULL) {
1547              // debugBelch("ghci_enquire: can't find %s\n", sym);
1548          }
1549          else if (addr-DELTA <= a && a <= addr+DELTA) {
1550             debugBelch("%p + %3d  ==  `%s'\n", addr, (int)(a - addr), sym);
1551          }
1552       }
1553    }
1554 }
1555 #endif
1556
1557 #ifdef USE_MMAP
1558 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1559
1560 static void *
1561 mmapForLinker (size_t bytes, nat flags, int fd)
1562 {
1563    void *map_addr = NULL;
1564    void *result;
1565    int pagesize, size;
1566    static nat fixed = 0;
1567
1568    pagesize = getpagesize();
1569    size = ROUND_UP(bytes, pagesize);
1570
1571 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1572 mmap_again:
1573
1574    if (mmap_32bit_base != 0) {
1575        map_addr = mmap_32bit_base;
1576    }
1577 #endif
1578
1579    result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1580                     MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1581
1582    if (result == MAP_FAILED) {
1583        sysErrorBelch("mmap %lu bytes at %p",(lnat)size,map_addr);
1584        errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1585        stg_exit(EXIT_FAILURE);
1586    }
1587
1588 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1589    if (mmap_32bit_base != 0) {
1590        if (result == map_addr) {
1591            mmap_32bit_base = (StgWord8*)map_addr + size;
1592        } else {
1593            if ((W_)result > 0x80000000) {
1594                // oops, we were given memory over 2Gb
1595 #if defined(freebsd_HOST_OS)  || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS)
1596                // Some platforms require MAP_FIXED.  This is normally
1597                // a bad idea, because MAP_FIXED will overwrite
1598                // existing mappings.
1599                munmap(result,size);
1600                fixed = MAP_FIXED;
1601                goto mmap_again;
1602 #else
1603                barf("loadObj: failed to mmap() memory below 2Gb; asked for %lu bytes at %p.  Try specifying an address with +RTS -xm<addr> -RTS", size, map_addr, result);
1604 #endif
1605            } else {
1606                // hmm, we were given memory somewhere else, but it's
1607                // still under 2Gb so we can use it.  Next time, ask
1608                // for memory right after the place we just got some
1609                mmap_32bit_base = (StgWord8*)result + size;
1610            }
1611        }
1612    } else {
1613        if ((W_)result > 0x80000000) {
1614            // oops, we were given memory over 2Gb
1615            // ... try allocating memory somewhere else?;
1616            debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1617            munmap(result, size);
1618
1619            // Set a base address and try again... (guess: 1Gb)
1620            mmap_32bit_base = (void*)0x40000000;
1621            goto mmap_again;
1622        }
1623    }
1624 #endif
1625
1626    return result;
1627 }
1628 #endif // USE_MMAP
1629
1630 static ObjectCode*
1631 mkOc( char *path, char *image, int imageSize,
1632       char *archiveMemberName
1633 #ifndef USE_MMAP
1634 #ifdef darwin_HOST_OS
1635     , int misalignment
1636 #endif
1637 #endif
1638     ) {
1639    ObjectCode* oc;
1640
1641    oc = stgMallocBytes(sizeof(ObjectCode), "loadArchive(oc)");
1642
1643 #  if defined(OBJFORMAT_ELF)
1644    oc->formatName = "ELF";
1645 #  elif defined(OBJFORMAT_PEi386)
1646    oc->formatName = "PEi386";
1647 #  elif defined(OBJFORMAT_MACHO)
1648    oc->formatName = "Mach-O";
1649 #  else
1650    stgFree(oc);
1651    barf("loadObj: not implemented on this platform");
1652 #  endif
1653
1654    oc->image = image;
1655    /* sigh, strdup() isn't a POSIX function, so do it the long way */
1656    oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1657    strcpy(oc->fileName, path);
1658
1659    if (archiveMemberName) {
1660        oc->archiveMemberName = stgMallocBytes( strlen(archiveMemberName)+1, "loadObj" );
1661        strcpy(oc->archiveMemberName, archiveMemberName);
1662    }
1663    else {
1664        oc->archiveMemberName = NULL;
1665    }
1666
1667    oc->fileSize          = imageSize;
1668    oc->symbols           = NULL;
1669    oc->sections          = NULL;
1670    oc->proddables        = NULL;
1671
1672 #ifndef USE_MMAP
1673 #ifdef darwin_HOST_OS
1674    oc->misalignment = misalignment;
1675 #endif
1676 #endif
1677
1678    /* chain it onto the list of objects */
1679    oc->next              = objects;
1680    objects               = oc;
1681
1682    return oc;
1683 }
1684
1685 HsInt
1686 loadArchive( char *path )
1687 {
1688     ObjectCode* oc;
1689     char *image;
1690     int memberSize;
1691     FILE *f;
1692     int n;
1693     size_t thisFileNameSize;
1694     char *fileName;
1695     size_t fileNameSize;
1696     int isObject, isGnuIndex;
1697     char tmp[12];
1698     char *gnuFileIndex;
1699     int gnuFileIndexSize;
1700 #if !defined(USE_MMAP) && defined(darwin_HOST_OS)
1701     int misalignment;
1702 #endif
1703
1704     IF_DEBUG(linker, debugBelch("loadArchive: Loading archive `%s'\n", path));
1705
1706     gnuFileIndex = NULL;
1707     gnuFileIndexSize = 0;
1708
1709     fileNameSize = 32;
1710     fileName = stgMallocBytes(fileNameSize, "loadArchive(fileName)");
1711
1712     f = fopen(path, "rb");
1713     if (!f)
1714         barf("loadObj: can't read `%s'", path);
1715
1716     n = fread ( tmp, 1, 8, f );
1717     if (strncmp(tmp, "!<arch>\n", 8) != 0)
1718         barf("loadArchive: Not an archive: `%s'", path);
1719
1720     while(1) {
1721         n = fread ( fileName, 1, 16, f );
1722         if (n != 16) {
1723             if (feof(f)) {
1724                 break;
1725             }
1726             else {
1727                 barf("loadArchive: Failed reading file name from `%s'", path);
1728             }
1729         }
1730         n = fread ( tmp, 1, 12, f );
1731         if (n != 12)
1732             barf("loadArchive: Failed reading mod time from `%s'", path);
1733         n = fread ( tmp, 1, 6, f );
1734         if (n != 6)
1735             barf("loadArchive: Failed reading owner from `%s'", path);
1736         n = fread ( tmp, 1, 6, f );
1737         if (n != 6)
1738             barf("loadArchive: Failed reading group from `%s'", path);
1739         n = fread ( tmp, 1, 8, f );
1740         if (n != 8)
1741             barf("loadArchive: Failed reading mode from `%s'", path);
1742         n = fread ( tmp, 1, 10, f );
1743         if (n != 10)
1744             barf("loadArchive: Failed reading size from `%s'", path);
1745         tmp[10] = '\0';
1746         for (n = 0; isdigit(tmp[n]); n++);
1747         tmp[n] = '\0';
1748         memberSize = atoi(tmp);
1749         n = fread ( tmp, 1, 2, f );
1750         if (strncmp(tmp, "\x60\x0A", 2) != 0)
1751             barf("loadArchive: Failed reading magic from `%s' at %ld. Got %c%c",
1752                  path, ftell(f), tmp[0], tmp[1]);
1753
1754         isGnuIndex = 0;
1755         /* Check for BSD-variant large filenames */
1756         if (0 == strncmp(fileName, "#1/", 3)) {
1757             fileName[16] = '\0';
1758             if (isdigit(fileName[3])) {
1759                 for (n = 4; isdigit(fileName[n]); n++);
1760                 fileName[n] = '\0';
1761                 thisFileNameSize = atoi(fileName + 3);
1762                 memberSize -= thisFileNameSize;
1763                 if (thisFileNameSize >= fileNameSize) {
1764                     /* Double it to avoid potentially continually
1765                        increasing it by 1 */
1766                     fileNameSize = thisFileNameSize * 2;
1767                     fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1768                 }
1769                 n = fread ( fileName, 1, thisFileNameSize, f );
1770                 if (n != (int)thisFileNameSize) {
1771                     barf("loadArchive: Failed reading filename from `%s'",
1772                          path);
1773                 }
1774                 fileName[thisFileNameSize] = 0;
1775             }
1776             else {
1777                 barf("loadArchive: BSD-variant filename size not found while reading filename from `%s'", path);
1778             }
1779         }
1780         /* Check for GNU file index file */
1781         else if (0 == strncmp(fileName, "//", 2)) {
1782             fileName[0] = '\0';
1783             thisFileNameSize = 0;
1784             isGnuIndex = 1;
1785         }
1786         /* Check for a file in the GNU file index */
1787         else if (fileName[0] == '/') {
1788             if (isdigit(fileName[1])) {
1789                 int i;
1790
1791                 for (n = 2; isdigit(fileName[n]); n++);
1792                 fileName[n] = '\0';
1793                 n = atoi(fileName + 1);
1794
1795                 if (gnuFileIndex == NULL) {
1796                     barf("loadArchive: GNU-variant filename without an index while reading from `%s'", path);
1797                 }
1798                 if (n < 0 || n > gnuFileIndexSize) {
1799                     barf("loadArchive: GNU-variant filename offset %d out of range [0..%d] while reading filename from `%s'", n, gnuFileIndexSize, path);
1800                 }
1801                 if (n != 0 && gnuFileIndex[n - 1] != '\n') {
1802                     barf("loadArchive: GNU-variant filename offset %d invalid (range [0..%d]) while reading filename from `%s'", n, gnuFileIndexSize, path);
1803                 }
1804                 for (i = n; gnuFileIndex[i] != '/'; i++);
1805                 thisFileNameSize = i - n;
1806                 if (thisFileNameSize >= fileNameSize) {
1807                     /* Double it to avoid potentially continually
1808                        increasing it by 1 */
1809                     fileNameSize = thisFileNameSize * 2;
1810                     fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
1811                 }
1812                 memcpy(fileName, gnuFileIndex + n, thisFileNameSize);
1813                 fileName[thisFileNameSize] = '\0';
1814             }
1815             else if (fileName[1] == ' ') {
1816                 fileName[0] = '\0';
1817                 thisFileNameSize = 0;
1818             }
1819             else {
1820                 barf("loadArchive: GNU-variant filename offset not found while reading filename from `%s'", path);
1821             }
1822         }
1823         /* Finally, the case where the filename field actually contains
1824            the filename */
1825         else {
1826             /* GNU ar terminates filenames with a '/', this allowing
1827                spaces in filenames. So first look to see if there is a
1828                terminating '/'. */
1829             for (thisFileNameSize = 0;
1830                  thisFileNameSize < 16;
1831                  thisFileNameSize++) {
1832                 if (fileName[thisFileNameSize] == '/') {
1833                     fileName[thisFileNameSize] = '\0';
1834                     break;
1835                 }
1836             }
1837             /* If we didn't find a '/', then a space teminates the
1838                filename. Note that if we don't find one, then
1839                thisFileNameSize ends up as 16, and we already have the
1840                '\0' at the end. */
1841             if (thisFileNameSize == 16) {
1842                 for (thisFileNameSize = 0;
1843                      thisFileNameSize < 16;
1844                      thisFileNameSize++) {
1845                     if (fileName[thisFileNameSize] == ' ') {
1846                         fileName[thisFileNameSize] = '\0';
1847                         break;
1848                     }
1849                 }
1850             }
1851         }
1852
1853         IF_DEBUG(linker,
1854                  debugBelch("loadArchive: Found member file `%s'\n", fileName));
1855
1856         isObject = thisFileNameSize >= 2
1857                 && fileName[thisFileNameSize - 2] == '.'
1858                 && fileName[thisFileNameSize - 1] == 'o';
1859
1860         if (isObject) {
1861             char *archiveMemberName;
1862
1863             IF_DEBUG(linker, debugBelch("loadArchive: Member is an object file...loading...\n"));
1864
1865             /* We can't mmap from the archive directly, as object
1866                files need to be 8-byte aligned but files in .ar
1867                archives are 2-byte aligned. When possible we use mmap
1868                to get some anonymous memory, as on 64-bit platforms if
1869                we use malloc then we can be given memory above 2^32.
1870                In the mmap case we're probably wasting lots of space;
1871                we could do better. */
1872 #if defined(USE_MMAP)
1873             image = mmapForLinker(memberSize, MAP_ANONYMOUS, -1);
1874 #elif defined(darwin_HOST_OS)
1875             /* See loadObj() */
1876             misalignment = machoGetMisalignment(f);
1877             image = stgMallocBytes(memberSize + misalignment, "loadArchive(image)");
1878             image += misalignment;
1879 #else
1880             image = stgMallocBytes(memberSize, "loadArchive(image)");
1881 #endif
1882             n = fread ( image, 1, memberSize, f );
1883             if (n != memberSize) {
1884                 barf("loadArchive: error whilst reading `%s'", path);
1885             }
1886
1887             archiveMemberName = stgMallocBytes(strlen(path) + thisFileNameSize + 3,
1888                                                "loadArchive(file)");
1889             sprintf(archiveMemberName, "%s(%.*s)",
1890                     path, (int)thisFileNameSize, fileName);
1891
1892             oc = mkOc(path, image, memberSize, archiveMemberName
1893 #ifndef USE_MMAP
1894 #ifdef darwin_HOST_OS
1895                      , misalignment
1896 #endif
1897 #endif
1898                      );
1899
1900             stgFree(archiveMemberName);
1901
1902             if (0 == loadOc(oc)) {
1903                 stgFree(fileName);
1904                 return 0;
1905             }
1906         }
1907         else if (isGnuIndex) {
1908             if (gnuFileIndex != NULL) {
1909                 barf("loadArchive: GNU-variant index found, but already have an index, while reading filename from `%s'", path);
1910             }
1911             IF_DEBUG(linker, debugBelch("loadArchive: Found GNU-variant file index\n"));
1912 #ifdef USE_MMAP
1913             gnuFileIndex = mmapForLinker(memberSize + 1, MAP_ANONYMOUS, -1);
1914 #else
1915             gnuFileIndex = stgMallocBytes(memberSize + 1, "loadArchive(image)");
1916 #endif
1917             n = fread ( gnuFileIndex, 1, memberSize, f );
1918             if (n != memberSize) {
1919                 barf("loadArchive: error whilst reading `%s'", path);
1920             }
1921             gnuFileIndex[memberSize] = '/';
1922             gnuFileIndexSize = memberSize;
1923         }
1924         else {
1925             n = fseek(f, memberSize, SEEK_CUR);
1926             if (n != 0)
1927                 barf("loadArchive: error whilst seeking by %d in `%s'",
1928                      memberSize, path);
1929         }
1930         /* .ar files are 2-byte aligned */
1931         if (memberSize % 2) {
1932             n = fread ( tmp, 1, 1, f );
1933             if (n != 1) {
1934                 if (feof(f)) {
1935                     break;
1936                 }
1937                 else {
1938                     barf("loadArchive: Failed reading padding from `%s'", path);
1939                 }
1940             }
1941         }
1942     }
1943
1944     fclose(f);
1945
1946     stgFree(fileName);
1947     if (gnuFileIndex != NULL) {
1948 #ifdef USE_MMAP
1949         munmap(gnuFileIndex, gnuFileIndexSize + 1);
1950 #else
1951         stgFree(gnuFileIndex);
1952 #endif
1953     }
1954
1955     return 1;
1956 }
1957
1958 /* -----------------------------------------------------------------------------
1959  * Load an obj (populate the global symbol table, but don't resolve yet)
1960  *
1961  * Returns: 1 if ok, 0 on error.
1962  */
1963 HsInt
1964 loadObj( char *path )
1965 {
1966    ObjectCode* oc;
1967    char *image;
1968    int fileSize;
1969    struct stat st;
1970    int r;
1971 #ifdef USE_MMAP
1972    int fd;
1973 #else
1974    FILE *f;
1975 #  if defined(darwin_HOST_OS)
1976    int misalignment;
1977 #  endif
1978 #endif
1979    IF_DEBUG(linker, debugBelch("loadObj %s\n", path));
1980
1981    initLinker();
1982
1983    /* debugBelch("loadObj %s\n", path ); */
1984
1985    /* Check that we haven't already loaded this object.
1986       Ignore requests to load multiple times */
1987    {
1988        ObjectCode *o;
1989        int is_dup = 0;
1990        for (o = objects; o; o = o->next) {
1991           if (0 == strcmp(o->fileName, path)) {
1992              is_dup = 1;
1993              break; /* don't need to search further */
1994           }
1995        }
1996        if (is_dup) {
1997           IF_DEBUG(linker, debugBelch(
1998             "GHCi runtime linker: warning: looks like you're trying to load the\n"
1999             "same object file twice:\n"
2000             "   %s\n"
2001             "GHCi will ignore this, but be warned.\n"
2002             , path));
2003           return 1; /* success */
2004        }
2005    }
2006
2007    r = stat(path, &st);
2008    if (r == -1) {
2009        IF_DEBUG(linker, debugBelch("File doesn't exist\n"));
2010        return 0;
2011    }
2012
2013    fileSize = st.st_size;
2014
2015 #ifdef USE_MMAP
2016    /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
2017
2018 #if defined(openbsd_HOST_OS)
2019    fd = open(path, O_RDONLY, S_IRUSR);
2020 #else
2021    fd = open(path, O_RDONLY);
2022 #endif
2023    if (fd == -1)
2024       barf("loadObj: can't open `%s'", path);
2025
2026    image = mmapForLinker(fileSize, 0, fd);
2027
2028    close(fd);
2029
2030 #else /* !USE_MMAP */
2031    /* load the image into memory */
2032    f = fopen(path, "rb");
2033    if (!f)
2034        barf("loadObj: can't read `%s'", path);
2035
2036 #   if defined(mingw32_HOST_OS)
2037         // TODO: We would like to use allocateExec here, but allocateExec
2038         //       cannot currently allocate blocks large enough.
2039     image = VirtualAlloc(NULL, fileSize, MEM_RESERVE | MEM_COMMIT,
2040                              PAGE_EXECUTE_READWRITE);
2041 #   elif defined(darwin_HOST_OS)
2042     // In a Mach-O .o file, all sections can and will be misaligned
2043     // if the total size of the headers is not a multiple of the
2044     // desired alignment. This is fine for .o files that only serve
2045     // as input for the static linker, but it's not fine for us,
2046     // as SSE (used by gcc for floating point) and Altivec require
2047     // 16-byte alignment.
2048     // We calculate the correct alignment from the header before
2049     // reading the file, and then we misalign image on purpose so
2050     // that the actual sections end up aligned again.
2051    misalignment = machoGetMisalignment(f);
2052    image = stgMallocBytes(fileSize + misalignment, "loadObj(image)");
2053    image += misalignment;
2054 #  else
2055    image = stgMallocBytes(fileSize, "loadObj(image)");
2056 #  endif
2057
2058    {
2059        int n;
2060        n = fread ( image, 1, fileSize, f );
2061        if (n != fileSize)
2062            barf("loadObj: error whilst reading `%s'", path);
2063    }
2064    fclose(f);
2065 #endif /* USE_MMAP */
2066
2067    oc = mkOc(path, image, fileSize, NULL
2068 #ifndef USE_MMAP
2069 #ifdef darwin_HOST_OS
2070             , misalignment
2071 #endif
2072 #endif
2073             );
2074
2075    return loadOc(oc);
2076 }
2077
2078 static HsInt
2079 loadOc( ObjectCode* oc ) {
2080    int r;
2081
2082    IF_DEBUG(linker, debugBelch("loadOc\n"));
2083
2084 #  if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2085    r = ocAllocateSymbolExtras_MachO ( oc );
2086    if (!r) {
2087        IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_MachO failed\n"));
2088        return r;
2089    }
2090 #  elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2091    r = ocAllocateSymbolExtras_ELF ( oc );
2092    if (!r) {
2093        IF_DEBUG(linker, debugBelch("ocAllocateSymbolExtras_ELF failed\n"));
2094        return r;
2095    }
2096 #endif
2097
2098    /* verify the in-memory image */
2099 #  if defined(OBJFORMAT_ELF)
2100    r = ocVerifyImage_ELF ( oc );
2101 #  elif defined(OBJFORMAT_PEi386)
2102    r = ocVerifyImage_PEi386 ( oc );
2103 #  elif defined(OBJFORMAT_MACHO)
2104    r = ocVerifyImage_MachO ( oc );
2105 #  else
2106    barf("loadObj: no verify method");
2107 #  endif
2108    if (!r) {
2109        IF_DEBUG(linker, debugBelch("ocVerifyImage_* failed\n"));
2110        return r;
2111    }
2112
2113    /* build the symbol list for this image */
2114 #  if defined(OBJFORMAT_ELF)
2115    r = ocGetNames_ELF ( oc );
2116 #  elif defined(OBJFORMAT_PEi386)
2117    r = ocGetNames_PEi386 ( oc );
2118 #  elif defined(OBJFORMAT_MACHO)
2119    r = ocGetNames_MachO ( oc );
2120 #  else
2121    barf("loadObj: no getNames method");
2122 #  endif
2123    if (!r) {
2124        IF_DEBUG(linker, debugBelch("ocGetNames_* failed\n"));
2125        return r;
2126    }
2127
2128    /* loaded, but not resolved yet */
2129    oc->status = OBJECT_LOADED;
2130    IF_DEBUG(linker, debugBelch("loadObj done.\n"));
2131
2132    return 1;
2133 }
2134
2135 /* -----------------------------------------------------------------------------
2136  * resolve all the currently unlinked objects in memory
2137  *
2138  * Returns: 1 if ok, 0 on error.
2139  */
2140 HsInt
2141 resolveObjs( void )
2142 {
2143     ObjectCode *oc;
2144     int r;
2145
2146     IF_DEBUG(linker, debugBelch("resolveObjs: start\n"));
2147     initLinker();
2148
2149     for (oc = objects; oc; oc = oc->next) {
2150         if (oc->status != OBJECT_RESOLVED) {
2151 #           if defined(OBJFORMAT_ELF)
2152             r = ocResolve_ELF ( oc );
2153 #           elif defined(OBJFORMAT_PEi386)
2154             r = ocResolve_PEi386 ( oc );
2155 #           elif defined(OBJFORMAT_MACHO)
2156             r = ocResolve_MachO ( oc );
2157 #           else
2158             barf("resolveObjs: not implemented on this platform");
2159 #           endif
2160             if (!r) { return r; }
2161             oc->status = OBJECT_RESOLVED;
2162         }
2163     }
2164     IF_DEBUG(linker, debugBelch("resolveObjs: done\n"));
2165     return 1;
2166 }
2167
2168 /* -----------------------------------------------------------------------------
2169  * delete an object from the pool
2170  */
2171 HsInt
2172 unloadObj( char *path )
2173 {
2174     ObjectCode *oc, *prev;
2175     HsBool unloadedAnyObj = HS_BOOL_FALSE;
2176
2177     ASSERT(symhash != NULL);
2178     ASSERT(objects != NULL);
2179
2180     initLinker();
2181
2182     prev = NULL;
2183     for (oc = objects; oc; prev = oc, oc = oc->next) {
2184         if (!strcmp(oc->fileName,path)) {
2185
2186             /* Remove all the mappings for the symbols within this
2187              * object..
2188              */
2189             {
2190                 int i;
2191                 for (i = 0; i < oc->n_symbols; i++) {
2192                    if (oc->symbols[i] != NULL) {
2193                        removeStrHashTable(symhash, oc->symbols[i], NULL);
2194                    }
2195                 }
2196             }
2197
2198             if (prev == NULL) {
2199                 objects = oc->next;
2200             } else {
2201                 prev->next = oc->next;
2202             }
2203
2204             // We're going to leave this in place, in case there are
2205             // any pointers from the heap into it:
2206                 // #ifdef mingw32_HOST_OS
2207                 //  VirtualFree(oc->image);
2208                 // #else
2209             //  stgFree(oc->image);
2210             // #endif
2211             stgFree(oc->fileName);
2212             stgFree(oc->symbols);
2213             stgFree(oc->sections);
2214             stgFree(oc);
2215
2216             /* This could be a member of an archive so continue
2217              * unloading other members. */
2218             unloadedAnyObj = HS_BOOL_TRUE;
2219         }
2220     }
2221
2222     if (unloadedAnyObj) {
2223         return 1;
2224     }
2225     else {
2226         errorBelch("unloadObj: can't find `%s' to unload", path);
2227         return 0;
2228     }
2229 }
2230
2231 /* -----------------------------------------------------------------------------
2232  * Sanity checking.  For each ObjectCode, maintain a list of address ranges
2233  * which may be prodded during relocation, and abort if we try and write
2234  * outside any of these.
2235  */
2236 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
2237 {
2238    ProddableBlock* pb
2239       = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
2240    IF_DEBUG(linker, debugBelch("addProddableBlock %p %p %d\n", oc, start, size));
2241    ASSERT(size > 0);
2242    pb->start      = start;
2243    pb->size       = size;
2244    pb->next       = oc->proddables;
2245    oc->proddables = pb;
2246 }
2247
2248 static void checkProddableBlock ( ObjectCode* oc, void* addr )
2249 {
2250    ProddableBlock* pb;
2251    for (pb = oc->proddables; pb != NULL; pb = pb->next) {
2252       char* s = (char*)(pb->start);
2253       char* e = s + pb->size - 1;
2254       char* a = (char*)addr;
2255       /* Assumes that the biggest fixup involves a 4-byte write.  This
2256          probably needs to be changed to 8 (ie, +7) on 64-bit
2257          plats. */
2258       if (a >= s && (a+3) <= e) return;
2259    }
2260    barf("checkProddableBlock: invalid fixup in runtime linker");
2261 }
2262
2263 /* -----------------------------------------------------------------------------
2264  * Section management.
2265  */
2266 static void addSection ( ObjectCode* oc, SectionKind kind,
2267                          void* start, void* end )
2268 {
2269    Section* s   = stgMallocBytes(sizeof(Section), "addSection");
2270    s->start     = start;
2271    s->end       = end;
2272    s->kind      = kind;
2273    s->next      = oc->sections;
2274    oc->sections = s;
2275    /*
2276    debugBelch("addSection: %p-%p (size %d), kind %d\n",
2277                    start, ((char*)end)-1, end - start + 1, kind );
2278    */
2279 }
2280
2281
2282 /* --------------------------------------------------------------------------
2283  * Symbol Extras.
2284  * This is about allocating a small chunk of memory for every symbol in the
2285  * object file. We make sure that the SymboLExtras are always "in range" of
2286  * limited-range PC-relative instructions on various platforms by allocating
2287  * them right next to the object code itself.
2288  */
2289
2290 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2291
2292 /*
2293   ocAllocateSymbolExtras
2294
2295   Allocate additional space at the end of the object file image to make room
2296   for jump islands (powerpc, x86_64) and GOT entries (x86_64).
2297
2298   PowerPC relative branch instructions have a 24 bit displacement field.
2299   As PPC code is always 4-byte-aligned, this yields a +-32MB range.
2300   If a particular imported symbol is outside this range, we have to redirect
2301   the jump to a short piece of new code that just loads the 32bit absolute
2302   address and jumps there.
2303   On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
2304   to 32 bits (+-2GB).
2305
2306   This function just allocates space for one SymbolExtra for every
2307   undefined symbol in the object file. The code for the jump islands is
2308   filled in by makeSymbolExtra below.
2309 */
2310
2311 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
2312 {
2313 #ifdef USE_MMAP
2314   int pagesize, n, m;
2315 #endif
2316   int aligned;
2317 #ifndef USE_MMAP
2318   int misalignment = 0;
2319 #ifdef darwin_HOST_OS
2320   misalignment = oc->misalignment;
2321 #endif
2322 #endif
2323
2324   if( count > 0 )
2325   {
2326     // round up to the nearest 4
2327     aligned = (oc->fileSize + 3) & ~3;
2328
2329 #ifdef USE_MMAP
2330     pagesize = getpagesize();
2331     n = ROUND_UP( oc->fileSize, pagesize );
2332     m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
2333
2334     /* we try to use spare space at the end of the last page of the
2335      * image for the jump islands, but if there isn't enough space
2336      * then we have to map some (anonymously, remembering MAP_32BIT).
2337      */
2338     if( m > n ) // we need to allocate more pages
2339     {
2340         oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
2341                                           MAP_ANONYMOUS, -1);
2342     }
2343     else
2344     {
2345         oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2346     }
2347 #else
2348     oc->image -= misalignment;
2349     oc->image = stgReallocBytes( oc->image,
2350                                  misalignment +
2351                                  aligned + sizeof (SymbolExtra) * count,
2352                                  "ocAllocateSymbolExtras" );
2353     oc->image += misalignment;
2354
2355     oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2356 #endif /* USE_MMAP */
2357
2358     memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
2359   }
2360   else
2361     oc->symbol_extras = NULL;
2362
2363   oc->first_symbol_extra = first;
2364   oc->n_symbol_extras = count;
2365
2366   return 1;
2367 }
2368
2369 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
2370                                      unsigned long symbolNumber,
2371                                      unsigned long target )
2372 {
2373   SymbolExtra *extra;
2374
2375   ASSERT( symbolNumber >= oc->first_symbol_extra
2376         && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
2377
2378   extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
2379
2380 #ifdef powerpc_HOST_ARCH
2381   // lis r12, hi16(target)
2382   extra->jumpIsland.lis_r12     = 0x3d80;
2383   extra->jumpIsland.hi_addr     = target >> 16;
2384
2385   // ori r12, r12, lo16(target)
2386   extra->jumpIsland.ori_r12_r12 = 0x618c;
2387   extra->jumpIsland.lo_addr     = target & 0xffff;
2388
2389   // mtctr r12
2390   extra->jumpIsland.mtctr_r12   = 0x7d8903a6;
2391
2392   // bctr
2393   extra->jumpIsland.bctr        = 0x4e800420;
2394 #endif
2395 #ifdef x86_64_HOST_ARCH
2396         // jmp *-14(%rip)
2397   static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2398   extra->addr = target;
2399   memcpy(extra->jumpIsland, jmp, 6);
2400 #endif
2401
2402   return extra;
2403 }
2404
2405 #endif
2406
2407 /* --------------------------------------------------------------------------
2408  * PowerPC specifics (instruction cache flushing)
2409  * ------------------------------------------------------------------------*/
2410
2411 #ifdef powerpc_HOST_ARCH
2412 /*
2413    ocFlushInstructionCache
2414
2415    Flush the data & instruction caches.
2416    Because the PPC has split data/instruction caches, we have to
2417    do that whenever we modify code at runtime.
2418  */
2419 static void ocFlushInstructionCacheFrom(void* begin, size_t length)
2420 {
2421     size_t         n = (length + 3) / 4;
2422     unsigned long* p = begin;
2423
2424     while (n--)
2425     {
2426         __asm__ volatile ( "dcbf 0,%0\n\t"
2427                            "sync\n\t"
2428                            "icbi 0,%0"
2429                            :
2430                            : "r" (p)
2431                          );
2432         p++;
2433     }
2434     __asm__ volatile ( "sync\n\t"
2435                        "isync"
2436                      );
2437 }
2438 static void ocFlushInstructionCache( ObjectCode *oc )
2439 {
2440     /* The main object code */
2441     ocFlushInstructionCacheFrom(oc->image + oc->misalignment, oc->fileSize);
2442
2443     /* Jump Islands */
2444     ocFlushInstructionCacheFrom(oc->symbol_extras, sizeof(SymbolExtra) * oc->n_symbol_extras);
2445 }
2446 #endif
2447
2448 /* --------------------------------------------------------------------------
2449  * PEi386 specifics (Win32 targets)
2450  * ------------------------------------------------------------------------*/
2451
2452 /* The information for this linker comes from
2453       Microsoft Portable Executable
2454       and Common Object File Format Specification
2455       revision 5.1 January 1998
2456    which SimonM says comes from the MS Developer Network CDs.
2457
2458    It can be found there (on older CDs), but can also be found
2459    online at:
2460
2461       http://www.microsoft.com/hwdev/hardware/PECOFF.asp
2462
2463    (this is Rev 6.0 from February 1999).
2464
2465    Things move, so if that fails, try searching for it via
2466
2467       http://www.google.com/search?q=PE+COFF+specification
2468
2469    The ultimate reference for the PE format is the Winnt.h
2470    header file that comes with the Platform SDKs; as always,
2471    implementations will drift wrt their documentation.
2472
2473    A good background article on the PE format is Matt Pietrek's
2474    March 1994 article in Microsoft System Journal (MSJ)
2475    (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
2476    Win32 Portable Executable File Format." The info in there
2477    has recently been updated in a two part article in
2478    MSDN magazine, issues Feb and March 2002,
2479    "Inside Windows: An In-Depth Look into the Win32 Portable
2480    Executable File Format"
2481
2482    John Levine's book "Linkers and Loaders" contains useful
2483    info on PE too.
2484 */
2485
2486
2487 #if defined(OBJFORMAT_PEi386)
2488
2489
2490
2491 typedef unsigned char  UChar;
2492 typedef unsigned short UInt16;
2493 typedef unsigned int   UInt32;
2494 typedef          int   Int32;
2495
2496
2497 typedef
2498    struct {
2499       UInt16 Machine;
2500       UInt16 NumberOfSections;
2501       UInt32 TimeDateStamp;
2502       UInt32 PointerToSymbolTable;
2503       UInt32 NumberOfSymbols;
2504       UInt16 SizeOfOptionalHeader;
2505       UInt16 Characteristics;
2506    }
2507    COFF_header;
2508
2509 #define sizeof_COFF_header 20
2510
2511
2512 typedef
2513    struct {
2514       UChar  Name[8];
2515       UInt32 VirtualSize;
2516       UInt32 VirtualAddress;
2517       UInt32 SizeOfRawData;
2518       UInt32 PointerToRawData;
2519       UInt32 PointerToRelocations;
2520       UInt32 PointerToLinenumbers;
2521       UInt16 NumberOfRelocations;
2522       UInt16 NumberOfLineNumbers;
2523       UInt32 Characteristics;
2524    }
2525    COFF_section;
2526
2527 #define sizeof_COFF_section 40
2528
2529
2530 typedef
2531    struct {
2532       UChar  Name[8];
2533       UInt32 Value;
2534       UInt16 SectionNumber;
2535       UInt16 Type;
2536       UChar  StorageClass;
2537       UChar  NumberOfAuxSymbols;
2538    }
2539    COFF_symbol;
2540
2541 #define sizeof_COFF_symbol 18
2542
2543
2544 typedef
2545    struct {
2546       UInt32 VirtualAddress;
2547       UInt32 SymbolTableIndex;
2548       UInt16 Type;
2549    }
2550    COFF_reloc;
2551
2552 #define sizeof_COFF_reloc 10
2553
2554
2555 /* From PE spec doc, section 3.3.2 */
2556 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
2557    windows.h -- for the same purpose, but I want to know what I'm
2558    getting, here. */
2559 #define MYIMAGE_FILE_RELOCS_STRIPPED     0x0001
2560 #define MYIMAGE_FILE_EXECUTABLE_IMAGE    0x0002
2561 #define MYIMAGE_FILE_DLL                 0x2000
2562 #define MYIMAGE_FILE_SYSTEM              0x1000
2563 #define MYIMAGE_FILE_BYTES_REVERSED_HI   0x8000
2564 #define MYIMAGE_FILE_BYTES_REVERSED_LO   0x0080
2565 #define MYIMAGE_FILE_32BIT_MACHINE       0x0100
2566
2567 /* From PE spec doc, section 5.4.2 and 5.4.4 */
2568 #define MYIMAGE_SYM_CLASS_EXTERNAL       2
2569 #define MYIMAGE_SYM_CLASS_STATIC         3
2570 #define MYIMAGE_SYM_UNDEFINED            0
2571
2572 /* From PE spec doc, section 4.1 */
2573 #define MYIMAGE_SCN_CNT_CODE             0x00000020
2574 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
2575 #define MYIMAGE_SCN_LNK_NRELOC_OVFL      0x01000000
2576
2577 /* From PE spec doc, section 5.2.1 */
2578 #define MYIMAGE_REL_I386_DIR32           0x0006
2579 #define MYIMAGE_REL_I386_REL32           0x0014
2580
2581
2582 /* We use myindex to calculate array addresses, rather than
2583    simply doing the normal subscript thing.  That's because
2584    some of the above structs have sizes which are not
2585    a whole number of words.  GCC rounds their sizes up to a
2586    whole number of words, which means that the address calcs
2587    arising from using normal C indexing or pointer arithmetic
2588    are just plain wrong.  Sigh.
2589 */
2590 static UChar *
2591 myindex ( int scale, void* base, int index )
2592 {
2593    return
2594       ((UChar*)base) + scale * index;
2595 }
2596
2597
2598 static void
2599 printName ( UChar* name, UChar* strtab )
2600 {
2601    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2602       UInt32 strtab_offset = * (UInt32*)(name+4);
2603       debugBelch("%s", strtab + strtab_offset );
2604    } else {
2605       int i;
2606       for (i = 0; i < 8; i++) {
2607          if (name[i] == 0) break;
2608          debugBelch("%c", name[i] );
2609       }
2610    }
2611 }
2612
2613
2614 static void
2615 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
2616 {
2617    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2618       UInt32 strtab_offset = * (UInt32*)(name+4);
2619       strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
2620       dst[dstSize-1] = 0;
2621    } else {
2622       int i = 0;
2623       while (1) {
2624          if (i >= 8) break;
2625          if (name[i] == 0) break;
2626          dst[i] = name[i];
2627          i++;
2628       }
2629       dst[i] = 0;
2630    }
2631 }
2632
2633
2634 static UChar *
2635 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
2636 {
2637    UChar* newstr;
2638    /* If the string is longer than 8 bytes, look in the
2639       string table for it -- this will be correctly zero terminated.
2640    */
2641    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
2642       UInt32 strtab_offset = * (UInt32*)(name+4);
2643       return ((UChar*)strtab) + strtab_offset;
2644    }
2645    /* Otherwise, if shorter than 8 bytes, return the original,
2646       which by defn is correctly terminated.
2647    */
2648    if (name[7]==0) return name;
2649    /* The annoying case: 8 bytes.  Copy into a temporary
2650       (XXX which is never freed ...)
2651    */
2652    newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
2653    ASSERT(newstr);
2654    strncpy((char*)newstr,(char*)name,8);
2655    newstr[8] = 0;
2656    return newstr;
2657 }
2658
2659 /* Getting the name of a section is mildly tricky, so we make a
2660    function for it.  Sadly, in one case we have to copy the string
2661    (when it is exactly 8 bytes long there's no trailing '\0'), so for
2662    consistency we *always* copy the string; the caller must free it
2663 */
2664 static char *
2665 cstring_from_section_name (UChar* name, UChar* strtab)
2666 {
2667     char *newstr;
2668
2669     if (name[0]=='/') {
2670         int strtab_offset = strtol((char*)name+1,NULL,10);
2671         int len = strlen(((char*)strtab) + strtab_offset);
2672
2673         newstr = stgMallocBytes(len, "cstring_from_section_symbol_name");
2674         strcpy((char*)newstr, (char*)((UChar*)strtab) + strtab_offset);
2675         return newstr;
2676     }
2677     else
2678     {
2679         newstr = stgMallocBytes(9, "cstring_from_section_symbol_name");
2680         ASSERT(newstr);
2681         strncpy((char*)newstr,(char*)name,8);
2682         newstr[8] = 0;
2683         return newstr;
2684     }
2685 }
2686
2687 /* Just compares the short names (first 8 chars) */
2688 static COFF_section *
2689 findPEi386SectionCalled ( ObjectCode* oc,  UChar* name )
2690 {
2691    int i;
2692    COFF_header* hdr
2693       = (COFF_header*)(oc->image);
2694    COFF_section* sectab
2695       = (COFF_section*) (
2696            ((UChar*)(oc->image))
2697            + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2698         );
2699    for (i = 0; i < hdr->NumberOfSections; i++) {
2700       UChar* n1;
2701       UChar* n2;
2702       COFF_section* section_i
2703          = (COFF_section*)
2704            myindex ( sizeof_COFF_section, sectab, i );
2705       n1 = (UChar*) &(section_i->Name);
2706       n2 = name;
2707       if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
2708           n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
2709           n1[6]==n2[6] && n1[7]==n2[7])
2710          return section_i;
2711    }
2712
2713    return NULL;
2714 }
2715
2716
2717 static void
2718 zapTrailingAtSign ( UChar* sym )
2719 {
2720 #  define my_isdigit(c) ((c) >= '0' && (c) <= '9')
2721    int i, j;
2722    if (sym[0] == 0) return;
2723    i = 0;
2724    while (sym[i] != 0) i++;
2725    i--;
2726    j = i;
2727    while (j > 0 && my_isdigit(sym[j])) j--;
2728    if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
2729 #  undef my_isdigit
2730 }
2731
2732 static void *
2733 lookupSymbolInDLLs ( UChar *lbl )
2734 {
2735     OpenedDLL* o_dll;
2736     void *sym;
2737
2738     for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
2739         /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
2740
2741         if (lbl[0] == '_') {
2742             /* HACK: if the name has an initial underscore, try stripping
2743                it off & look that up first. I've yet to verify whether there's
2744                a Rule that governs whether an initial '_' *should always* be
2745                stripped off when mapping from import lib name to the DLL name.
2746             */
2747             sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
2748             if (sym != NULL) {
2749                 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
2750                 return sym;
2751             }
2752         }
2753         sym = GetProcAddress(o_dll->instance, (char*)lbl);
2754         if (sym != NULL) {
2755             /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
2756             return sym;
2757            }
2758     }
2759     return NULL;
2760 }
2761
2762
2763 static int
2764 ocVerifyImage_PEi386 ( ObjectCode* oc )
2765 {
2766    int i;
2767    UInt32 j, noRelocs;
2768    COFF_header*  hdr;
2769    COFF_section* sectab;
2770    COFF_symbol*  symtab;
2771    UChar*        strtab;
2772    /* debugBelch("\nLOADING %s\n", oc->fileName); */
2773    hdr = (COFF_header*)(oc->image);
2774    sectab = (COFF_section*) (
2775                ((UChar*)(oc->image))
2776                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2777             );
2778    symtab = (COFF_symbol*) (
2779                ((UChar*)(oc->image))
2780                + hdr->PointerToSymbolTable
2781             );
2782    strtab = ((UChar*)symtab)
2783             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2784
2785    if (hdr->Machine != 0x14c) {
2786       errorBelch("%s: Not x86 PEi386", oc->fileName);
2787       return 0;
2788    }
2789    if (hdr->SizeOfOptionalHeader != 0) {
2790       errorBelch("%s: PEi386 with nonempty optional header", oc->fileName);
2791       return 0;
2792    }
2793    if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
2794         (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
2795         (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
2796         (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
2797       errorBelch("%s: Not a PEi386 object file", oc->fileName);
2798       return 0;
2799    }
2800    if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
2801         /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
2802       errorBelch("%s: Invalid PEi386 word size or endiannness: %d",
2803                  oc->fileName,
2804                  (int)(hdr->Characteristics));
2805       return 0;
2806    }
2807    /* If the string table size is way crazy, this might indicate that
2808       there are more than 64k relocations, despite claims to the
2809       contrary.  Hence this test. */
2810    /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
2811 #if 0
2812    if ( (*(UInt32*)strtab) > 600000 ) {
2813       /* Note that 600k has no special significance other than being
2814          big enough to handle the almost-2MB-sized lumps that
2815          constitute HSwin32*.o. */
2816       debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
2817       return 0;
2818    }
2819 #endif
2820
2821    /* No further verification after this point; only debug printing. */
2822    i = 0;
2823    IF_DEBUG(linker, i=1);
2824    if (i == 0) return 1;
2825
2826    debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
2827    debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
2828    debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
2829
2830    debugBelch("\n" );
2831    debugBelch( "Machine:           0x%x\n", (UInt32)(hdr->Machine) );
2832    debugBelch( "# sections:        %d\n",   (UInt32)(hdr->NumberOfSections) );
2833    debugBelch( "time/date:         0x%x\n", (UInt32)(hdr->TimeDateStamp) );
2834    debugBelch( "symtab offset:     %d\n",   (UInt32)(hdr->PointerToSymbolTable) );
2835    debugBelch( "# symbols:         %d\n",   (UInt32)(hdr->NumberOfSymbols) );
2836    debugBelch( "sz of opt hdr:     %d\n",   (UInt32)(hdr->SizeOfOptionalHeader) );
2837    debugBelch( "characteristics:   0x%x\n", (UInt32)(hdr->Characteristics) );
2838
2839    /* Print the section table. */
2840    debugBelch("\n" );
2841    for (i = 0; i < hdr->NumberOfSections; i++) {
2842       COFF_reloc* reltab;
2843       COFF_section* sectab_i
2844          = (COFF_section*)
2845            myindex ( sizeof_COFF_section, sectab, i );
2846       debugBelch(
2847                 "\n"
2848                 "section %d\n"
2849                 "     name `",
2850                 i
2851               );
2852       printName ( sectab_i->Name, strtab );
2853       debugBelch(
2854                 "'\n"
2855                 "    vsize %d\n"
2856                 "    vaddr %d\n"
2857                 "  data sz %d\n"
2858                 " data off %d\n"
2859                 "  num rel %d\n"
2860                 "  off rel %d\n"
2861                 "  ptr raw 0x%x\n",
2862                 sectab_i->VirtualSize,
2863                 sectab_i->VirtualAddress,
2864                 sectab_i->SizeOfRawData,
2865                 sectab_i->PointerToRawData,
2866                 sectab_i->NumberOfRelocations,
2867                 sectab_i->PointerToRelocations,
2868                 sectab_i->PointerToRawData
2869               );
2870       reltab = (COFF_reloc*) (
2871                   ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2872                );
2873
2874       if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2875         /* If the relocation field (a short) has overflowed, the
2876          * real count can be found in the first reloc entry.
2877          *
2878          * See Section 4.1 (last para) of the PE spec (rev6.0).
2879          */
2880         COFF_reloc* rel = (COFF_reloc*)
2881                            myindex ( sizeof_COFF_reloc, reltab, 0 );
2882         noRelocs = rel->VirtualAddress;
2883         j = 1;
2884       } else {
2885         noRelocs = sectab_i->NumberOfRelocations;
2886         j = 0;
2887       }
2888
2889       for (; j < noRelocs; j++) {
2890          COFF_symbol* sym;
2891          COFF_reloc* rel = (COFF_reloc*)
2892                            myindex ( sizeof_COFF_reloc, reltab, j );
2893          debugBelch(
2894                    "        type 0x%-4x   vaddr 0x%-8x   name `",
2895                    (UInt32)rel->Type,
2896                    rel->VirtualAddress );
2897          sym = (COFF_symbol*)
2898                myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
2899          /* Hmm..mysterious looking offset - what's it for? SOF */
2900          printName ( sym->Name, strtab -10 );
2901          debugBelch("'\n" );
2902       }
2903
2904       debugBelch("\n" );
2905    }
2906    debugBelch("\n" );
2907    debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
2908    debugBelch("---START of string table---\n");
2909    for (i = 4; i < *(Int32*)strtab; i++) {
2910       if (strtab[i] == 0)
2911          debugBelch("\n"); else
2912          debugBelch("%c", strtab[i] );
2913    }
2914    debugBelch("--- END  of string table---\n");
2915
2916    debugBelch("\n" );
2917    i = 0;
2918    while (1) {
2919       COFF_symbol* symtab_i;
2920       if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2921       symtab_i = (COFF_symbol*)
2922                  myindex ( sizeof_COFF_symbol, symtab, i );
2923       debugBelch(
2924                 "symbol %d\n"
2925                 "     name `",
2926                 i
2927               );
2928       printName ( symtab_i->Name, strtab );
2929       debugBelch(
2930                 "'\n"
2931                 "    value 0x%x\n"
2932                 "   1+sec# %d\n"
2933                 "     type 0x%x\n"
2934                 "   sclass 0x%x\n"
2935                 "     nAux %d\n",
2936                 symtab_i->Value,
2937                 (Int32)(symtab_i->SectionNumber),
2938                 (UInt32)symtab_i->Type,
2939                 (UInt32)symtab_i->StorageClass,
2940                 (UInt32)symtab_i->NumberOfAuxSymbols
2941               );
2942       i += symtab_i->NumberOfAuxSymbols;
2943       i++;
2944    }
2945
2946    debugBelch("\n" );
2947    return 1;
2948 }
2949
2950
2951 static int
2952 ocGetNames_PEi386 ( ObjectCode* oc )
2953 {
2954    COFF_header*  hdr;
2955    COFF_section* sectab;
2956    COFF_symbol*  symtab;
2957    UChar*        strtab;
2958
2959    UChar* sname;
2960    void*  addr;
2961    int    i;
2962
2963    hdr = (COFF_header*)(oc->image);
2964    sectab = (COFF_section*) (
2965                ((UChar*)(oc->image))
2966                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2967             );
2968    symtab = (COFF_symbol*) (
2969                ((UChar*)(oc->image))
2970                + hdr->PointerToSymbolTable
2971             );
2972    strtab = ((UChar*)(oc->image))
2973             + hdr->PointerToSymbolTable
2974             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2975
2976    /* Allocate space for any (local, anonymous) .bss sections. */
2977
2978    for (i = 0; i < hdr->NumberOfSections; i++) {
2979       UInt32 bss_sz;
2980       UChar* zspace;
2981       COFF_section* sectab_i
2982          = (COFF_section*)
2983            myindex ( sizeof_COFF_section, sectab, i );
2984
2985       char *secname = cstring_from_section_name(sectab_i->Name, strtab);
2986
2987       if (0 != strcmp(secname, ".bss")) {
2988           stgFree(secname);
2989           continue;
2990       }
2991
2992       stgFree(secname);
2993
2994       /* sof 10/05: the PE spec text isn't too clear regarding what
2995        * the SizeOfRawData field is supposed to hold for object
2996        * file sections containing just uninitialized data -- for executables,
2997        * it is supposed to be zero; unclear what it's supposed to be
2998        * for object files. However, VirtualSize is guaranteed to be
2999        * zero for object files, which definitely suggests that SizeOfRawData
3000        * will be non-zero (where else would the size of this .bss section be
3001        * stored?) Looking at the COFF_section info for incoming object files,
3002        * this certainly appears to be the case.
3003        *
3004        * => I suspect we've been incorrectly handling .bss sections in (relocatable)
3005        * object files up until now. This turned out to bite us with ghc-6.4.1's use
3006        * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
3007        * variable decls into to the .bss section. (The specific function in Q which
3008        * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
3009        */
3010       if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
3011       /* This is a non-empty .bss section.  Allocate zeroed space for
3012          it, and set its PointerToRawData field such that oc->image +
3013          PointerToRawData == addr_of_zeroed_space.  */
3014       bss_sz = sectab_i->VirtualSize;
3015       if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
3016       zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
3017       sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
3018       addProddableBlock(oc, zspace, bss_sz);
3019       /* debugBelch("BSS anon section at 0x%x\n", zspace); */
3020    }
3021
3022    /* Copy section information into the ObjectCode. */
3023
3024    for (i = 0; i < hdr->NumberOfSections; i++) {
3025       UChar* start;
3026       UChar* end;
3027       UInt32 sz;
3028
3029       SectionKind kind
3030          = SECTIONKIND_OTHER;
3031       COFF_section* sectab_i
3032          = (COFF_section*)
3033            myindex ( sizeof_COFF_section, sectab, i );
3034
3035       char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3036
3037       IF_DEBUG(linker, debugBelch("section name = %s\n", secname ));
3038
3039 #     if 0
3040       /* I'm sure this is the Right Way to do it.  However, the
3041          alternative of testing the sectab_i->Name field seems to
3042          work ok with Cygwin.
3043       */
3044       if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
3045           sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
3046          kind = SECTIONKIND_CODE_OR_RODATA;
3047 #     endif
3048
3049       if (0==strcmp(".text",(char*)secname) ||
3050           0==strcmp(".rdata",(char*)secname)||
3051           0==strcmp(".rodata",(char*)secname))
3052          kind = SECTIONKIND_CODE_OR_RODATA;
3053       if (0==strcmp(".data",(char*)secname) ||
3054           0==strcmp(".bss",(char*)secname))
3055          kind = SECTIONKIND_RWDATA;
3056
3057       ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
3058       sz = sectab_i->SizeOfRawData;
3059       if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
3060
3061       start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
3062       end   = start + sz - 1;
3063
3064       if (kind == SECTIONKIND_OTHER
3065           /* Ignore sections called which contain stabs debugging
3066              information. */
3067           && 0 != strcmp(".stab", (char*)secname)
3068           && 0 != strcmp(".stabstr", (char*)secname)
3069           /* ignore constructor section for now */
3070           && 0 != strcmp(".ctors", (char*)secname)
3071           /* ignore section generated from .ident */
3072           && 0!= strncmp(".debug", (char*)secname, 6)
3073           /* ignore unknown section that appeared in gcc 3.4.5(?) */
3074           && 0!= strcmp(".reloc", (char*)secname)
3075           && 0 != strcmp(".rdata$zzz", (char*)secname)
3076          ) {
3077          errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", secname, oc->fileName);
3078          stgFree(secname);
3079          return 0;
3080       }
3081
3082       if (kind != SECTIONKIND_OTHER && end >= start) {
3083          addSection(oc, kind, start, end);
3084          addProddableBlock(oc, start, end - start + 1);
3085       }
3086
3087       stgFree(secname);
3088    }
3089
3090    /* Copy exported symbols into the ObjectCode. */
3091
3092    oc->n_symbols = hdr->NumberOfSymbols;
3093    oc->symbols   = stgMallocBytes(oc->n_symbols * sizeof(char*),
3094                                   "ocGetNames_PEi386(oc->symbols)");
3095    /* Call me paranoid; I don't care. */
3096    for (i = 0; i < oc->n_symbols; i++)
3097       oc->symbols[i] = NULL;
3098
3099    i = 0;
3100    while (1) {
3101       COFF_symbol* symtab_i;
3102       if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3103       symtab_i = (COFF_symbol*)
3104                  myindex ( sizeof_COFF_symbol, symtab, i );
3105
3106       addr  = NULL;
3107
3108       if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
3109           && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
3110          /* This symbol is global and defined, viz, exported */
3111          /* for MYIMAGE_SYMCLASS_EXTERNAL
3112                 && !MYIMAGE_SYM_UNDEFINED,
3113             the address of the symbol is:
3114                 address of relevant section + offset in section
3115          */
3116          COFF_section* sectabent
3117             = (COFF_section*) myindex ( sizeof_COFF_section,
3118                                         sectab,
3119                                         symtab_i->SectionNumber-1 );
3120          addr = ((UChar*)(oc->image))
3121                 + (sectabent->PointerToRawData
3122                    + symtab_i->Value);
3123       }
3124       else
3125       if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
3126           && symtab_i->Value > 0) {
3127          /* This symbol isn't in any section at all, ie, global bss.
3128             Allocate zeroed space for it. */
3129          addr = stgCallocBytes(1, symtab_i->Value,
3130                                "ocGetNames_PEi386(non-anonymous bss)");
3131          addSection(oc, SECTIONKIND_RWDATA, addr,
3132                         ((UChar*)addr) + symtab_i->Value - 1);
3133          addProddableBlock(oc, addr, symtab_i->Value);
3134          /* debugBelch("BSS      section at 0x%x\n", addr); */
3135       }
3136
3137       if (addr != NULL ) {
3138          sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
3139          /* debugBelch("addSymbol %p `%s \n", addr,sname);  */
3140          IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
3141          ASSERT(i >= 0 && i < oc->n_symbols);
3142          /* cstring_from_COFF_symbol_name always succeeds. */
3143          oc->symbols[i] = (char*)sname;
3144          ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
3145       } else {
3146 #        if 0
3147          debugBelch(
3148                    "IGNORING symbol %d\n"
3149                    "     name `",
3150                    i
3151                  );
3152          printName ( symtab_i->Name, strtab );
3153          debugBelch(
3154                    "'\n"
3155                    "    value 0x%x\n"
3156                    "   1+sec# %d\n"
3157                    "     type 0x%x\n"
3158                    "   sclass 0x%x\n"
3159                    "     nAux %d\n",
3160                    symtab_i->Value,
3161                    (Int32)(symtab_i->SectionNumber),
3162                    (UInt32)symtab_i->Type,
3163                    (UInt32)symtab_i->StorageClass,
3164                    (UInt32)symtab_i->NumberOfAuxSymbols
3165                  );
3166 #        endif
3167       }
3168
3169       i += symtab_i->NumberOfAuxSymbols;
3170       i++;
3171    }
3172
3173    return 1;
3174 }
3175
3176
3177 static int
3178 ocResolve_PEi386 ( ObjectCode* oc )
3179 {
3180    COFF_header*  hdr;
3181    COFF_section* sectab;
3182    COFF_symbol*  symtab;
3183    UChar*        strtab;
3184
3185    UInt32        A;
3186    UInt32        S;
3187    UInt32*       pP;
3188
3189    int i;
3190    UInt32 j, noRelocs;
3191
3192    /* ToDo: should be variable-sized?  But is at least safe in the
3193       sense of buffer-overrun-proof. */
3194    UChar symbol[1000];
3195    /* debugBelch("resolving for %s\n", oc->fileName); */
3196
3197    hdr = (COFF_header*)(oc->image);
3198    sectab = (COFF_section*) (
3199                ((UChar*)(oc->image))
3200                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3201             );
3202    symtab = (COFF_symbol*) (
3203                ((UChar*)(oc->image))
3204                + hdr->PointerToSymbolTable
3205             );
3206    strtab = ((UChar*)(oc->image))
3207             + hdr->PointerToSymbolTable
3208             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3209
3210    for (i = 0; i < hdr->NumberOfSections; i++) {
3211       COFF_section* sectab_i
3212          = (COFF_section*)
3213            myindex ( sizeof_COFF_section, sectab, i );
3214       COFF_reloc* reltab
3215          = (COFF_reloc*) (
3216               ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3217            );
3218
3219       char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3220
3221       /* Ignore sections called which contain stabs debugging
3222          information. */
3223       if (0 == strcmp(".stab", (char*)secname)
3224           || 0 == strcmp(".stabstr", (char*)secname)
3225           || 0 == strcmp(".ctors", (char*)secname)
3226           || 0 == strncmp(".debug", (char*)secname, 6)
3227           || 0 == strcmp(".rdata$zzz", (char*)secname)) {
3228           stgFree(secname);
3229           continue;
3230       }
3231
3232       stgFree(secname);
3233
3234       if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3235         /* If the relocation field (a short) has overflowed, the
3236          * real count can be found in the first reloc entry.
3237          *
3238          * See Section 4.1 (last para) of the PE spec (rev6.0).
3239          *
3240          * Nov2003 update: the GNU linker still doesn't correctly
3241          * handle the generation of relocatable object files with
3242          * overflown relocations. Hence the output to warn of potential
3243          * troubles.
3244          */
3245         COFF_reloc* rel = (COFF_reloc*)
3246                            myindex ( sizeof_COFF_reloc, reltab, 0 );
3247         noRelocs = rel->VirtualAddress;
3248
3249         /* 10/05: we now assume (and check for) a GNU ld that is capable
3250          * of handling object files with (>2^16) of relocs.
3251          */
3252 #if 0
3253         debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
3254                    noRelocs);
3255 #endif
3256         j = 1;
3257       } else {
3258         noRelocs = sectab_i->NumberOfRelocations;
3259         j = 0;
3260       }
3261
3262
3263       for (; j < noRelocs; j++) {
3264          COFF_symbol* sym;
3265          COFF_reloc* reltab_j
3266             = (COFF_reloc*)
3267               myindex ( sizeof_COFF_reloc, reltab, j );
3268
3269          /* the location to patch */
3270          pP = (UInt32*)(
3271                  ((UChar*)(oc->image))
3272                  + (sectab_i->PointerToRawData
3273                     + reltab_j->VirtualAddress
3274                     - sectab_i->VirtualAddress )
3275               );
3276          /* the existing contents of pP */
3277          A = *pP;
3278          /* the symbol to connect to */
3279          sym = (COFF_symbol*)
3280                myindex ( sizeof_COFF_symbol,
3281                          symtab, reltab_j->SymbolTableIndex );
3282          IF_DEBUG(linker,
3283                   debugBelch(
3284                             "reloc sec %2d num %3d:  type 0x%-4x   "
3285                             "vaddr 0x%-8x   name `",
3286                             i, j,
3287                             (UInt32)reltab_j->Type,
3288                             reltab_j->VirtualAddress );
3289                             printName ( sym->Name, strtab );
3290                             debugBelch("'\n" ));
3291
3292          if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
3293             COFF_section* section_sym
3294                = findPEi386SectionCalled ( oc, sym->Name );
3295             if (!section_sym) {
3296                errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
3297                return 0;
3298             }
3299             S = ((UInt32)(oc->image))
3300                 + (section_sym->PointerToRawData
3301                    + sym->Value);
3302          } else {
3303             copyName ( sym->Name, strtab, symbol, 1000-1 );
3304             S = (UInt32) lookupSymbol( (char*)symbol );
3305             if ((void*)S != NULL) goto foundit;
3306             errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3307             return 0;
3308            foundit:;
3309          }
3310          checkProddableBlock(oc, pP);
3311          switch (reltab_j->Type) {
3312             case MYIMAGE_REL_I386_DIR32:
3313                *pP = A + S;
3314                break;
3315             case MYIMAGE_REL_I386_REL32:
3316                /* Tricky.  We have to insert a displacement at
3317                   pP which, when added to the PC for the _next_
3318                   insn, gives the address of the target (S).
3319                   Problem is to know the address of the next insn
3320                   when we only know pP.  We assume that this
3321                   literal field is always the last in the insn,
3322                   so that the address of the next insn is pP+4
3323                   -- hence the constant 4.
3324                   Also I don't know if A should be added, but so
3325                   far it has always been zero.
3326
3327                   SOF 05/2005: 'A' (old contents of *pP) have been observed
3328                   to contain values other than zero (the 'wx' object file
3329                   that came with wxhaskell-0.9.4; dunno how it was compiled..).
3330                   So, add displacement to old value instead of asserting
3331                   A to be zero. Fixes wxhaskell-related crashes, and no other
3332                   ill effects have been observed.
3333
3334                   Update: the reason why we're seeing these more elaborate
3335                   relocations is due to a switch in how the NCG compiles SRTs
3336                   and offsets to them from info tables. SRTs live in .(ro)data,
3337                   while info tables live in .text, causing GAS to emit REL32/DISP32
3338                   relocations with non-zero values. Adding the displacement is
3339                   the right thing to do.
3340                */
3341                *pP = S - ((UInt32)pP) - 4 + A;
3342                break;
3343             default:
3344                debugBelch("%s: unhandled PEi386 relocation type %d",
3345                      oc->fileName, reltab_j->Type);
3346                return 0;
3347          }
3348
3349       }
3350    }
3351
3352    IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
3353    return 1;
3354 }
3355
3356 #endif /* defined(OBJFORMAT_PEi386) */
3357
3358
3359 /* --------------------------------------------------------------------------
3360  * ELF specifics
3361  * ------------------------------------------------------------------------*/
3362
3363 #if defined(OBJFORMAT_ELF)
3364
3365 #define FALSE 0
3366 #define TRUE  1
3367
3368 #if defined(sparc_HOST_ARCH)
3369 #  define ELF_TARGET_SPARC  /* Used inside <elf.h> */
3370 #elif defined(i386_HOST_ARCH)
3371 #  define ELF_TARGET_386    /* Used inside <elf.h> */
3372 #elif defined(x86_64_HOST_ARCH)
3373 #  define ELF_TARGET_X64_64
3374 #  define ELF_64BIT
3375 #endif
3376
3377 #if !defined(openbsd_HOST_OS)
3378 #  include <elf.h>
3379 #else
3380 /* openbsd elf has things in different places, with diff names */
3381 #  include <elf_abi.h>
3382 #  include <machine/reloc.h>
3383 #  define R_386_32    RELOC_32
3384 #  define R_386_PC32  RELOC_PC32
3385 #endif
3386
3387 /* If elf.h doesn't define it */
3388 #  ifndef R_X86_64_PC64
3389 #    define R_X86_64_PC64 24
3390 #  endif
3391
3392 /*
3393  * Define a set of types which can be used for both ELF32 and ELF64
3394  */
3395
3396 #ifdef ELF_64BIT
3397 #define ELFCLASS    ELFCLASS64
3398 #define Elf_Addr    Elf64_Addr
3399 #define Elf_Word    Elf64_Word
3400 #define Elf_Sword   Elf64_Sword
3401 #define Elf_Ehdr    Elf64_Ehdr
3402 #define Elf_Phdr    Elf64_Phdr
3403 #define Elf_Shdr    Elf64_Shdr
3404 #define Elf_Sym     Elf64_Sym
3405 #define Elf_Rel     Elf64_Rel
3406 #define Elf_Rela    Elf64_Rela
3407 #ifndef ELF_ST_TYPE
3408 #define ELF_ST_TYPE ELF64_ST_TYPE
3409 #endif
3410 #ifndef ELF_ST_BIND
3411 #define ELF_ST_BIND ELF64_ST_BIND
3412 #endif
3413 #ifndef ELF_R_TYPE
3414 #define ELF_R_TYPE  ELF64_R_TYPE
3415 #endif
3416 #ifndef ELF_R_SYM
3417 #define ELF_R_SYM   ELF64_R_SYM
3418 #endif
3419 #else
3420 #define ELFCLASS    ELFCLASS32
3421 #define Elf_Addr    Elf32_Addr
3422 #define Elf_Word    Elf32_Word
3423 #define Elf_Sword   Elf32_Sword
3424 #define Elf_Ehdr    Elf32_Ehdr
3425 #define Elf_Phdr    Elf32_Phdr
3426 #define Elf_Shdr    Elf32_Shdr
3427 #define Elf_Sym     Elf32_Sym
3428 #define Elf_Rel     Elf32_Rel
3429 #define Elf_Rela    Elf32_Rela
3430 #ifndef ELF_ST_TYPE
3431 #define ELF_ST_TYPE ELF32_ST_TYPE
3432 #endif
3433 #ifndef ELF_ST_BIND
3434 #define ELF_ST_BIND ELF32_ST_BIND
3435 #endif
3436 #ifndef ELF_R_TYPE
3437 #define ELF_R_TYPE  ELF32_R_TYPE
3438 #endif
3439 #ifndef ELF_R_SYM
3440 #define ELF_R_SYM   ELF32_R_SYM
3441 #endif
3442 #endif
3443
3444
3445 /*
3446  * Functions to allocate entries in dynamic sections.  Currently we simply
3447  * preallocate a large number, and we don't check if a entry for the given
3448  * target already exists (a linear search is too slow).  Ideally these
3449  * entries would be associated with symbols.
3450  */
3451
3452 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
3453 #define GOT_SIZE            0x20000
3454 #define FUNCTION_TABLE_SIZE 0x10000
3455 #define PLT_SIZE            0x08000
3456
3457 #ifdef ELF_NEED_GOT
3458 static Elf_Addr got[GOT_SIZE];
3459 static unsigned int gotIndex;
3460 static Elf_Addr gp_val = (Elf_Addr)got;
3461
3462 static Elf_Addr
3463 allocateGOTEntry(Elf_Addr target)
3464 {
3465    Elf_Addr *entry;
3466
3467    if (gotIndex >= GOT_SIZE)
3468       barf("Global offset table overflow");
3469
3470    entry = &got[gotIndex++];
3471    *entry = target;
3472    return (Elf_Addr)entry;
3473 }
3474 #endif
3475
3476 #ifdef ELF_FUNCTION_DESC
3477 typedef struct {
3478    Elf_Addr ip;
3479    Elf_Addr gp;
3480 } FunctionDesc;
3481
3482 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
3483 static unsigned int functionTableIndex;
3484
3485 static Elf_Addr
3486 allocateFunctionDesc(Elf_Addr target)
3487 {
3488    FunctionDesc *entry;
3489
3490    if (functionTableIndex >= FUNCTION_TABLE_SIZE)
3491       barf("Function table overflow");
3492
3493    entry = &functionTable[functionTableIndex++];
3494    entry->ip = target;
3495    entry->gp = (Elf_Addr)gp_val;
3496    return (Elf_Addr)entry;
3497 }
3498
3499 static Elf_Addr
3500 copyFunctionDesc(Elf_Addr target)
3501 {
3502    FunctionDesc *olddesc = (FunctionDesc *)target;
3503    FunctionDesc *newdesc;
3504
3505    newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
3506    newdesc->gp = olddesc->gp;
3507    return (Elf_Addr)newdesc;
3508 }
3509 #endif
3510
3511 #ifdef ELF_NEED_PLT
3512
3513 typedef struct {
3514    unsigned char code[sizeof(plt_code)];
3515 } PLTEntry;
3516
3517 static Elf_Addr
3518 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
3519 {
3520    PLTEntry *plt = (PLTEntry *)oc->plt;
3521    PLTEntry *entry;
3522
3523    if (oc->pltIndex >= PLT_SIZE)
3524       barf("Procedure table overflow");
3525
3526    entry = &plt[oc->pltIndex++];
3527    memcpy(entry->code, plt_code, sizeof(entry->code));
3528    PLT_RELOC(entry->code, target);
3529    return (Elf_Addr)entry;
3530 }
3531
3532 static unsigned int
3533 PLTSize(void)
3534 {
3535    return (PLT_SIZE * sizeof(PLTEntry));
3536 }
3537 #endif
3538
3539
3540 /*
3541  * Generic ELF functions
3542  */
3543
3544 static char *
3545 findElfSection ( void* objImage, Elf_Word sh_type )
3546 {
3547    char* ehdrC = (char*)objImage;
3548    Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
3549    Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
3550    char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3551    char* ptr = NULL;
3552    int i;
3553
3554    for (i = 0; i < ehdr->e_shnum; i++) {
3555       if (shdr[i].sh_type == sh_type
3556           /* Ignore the section header's string table. */
3557           && i != ehdr->e_shstrndx
3558           /* Ignore string tables named .stabstr, as they contain
3559              debugging info. */
3560           && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3561          ) {
3562          ptr = ehdrC + shdr[i].sh_offset;
3563          break;
3564       }
3565    }
3566    return ptr;
3567 }
3568
3569 static int
3570 ocVerifyImage_ELF ( ObjectCode* oc )
3571 {
3572    Elf_Shdr* shdr;
3573    Elf_Sym*  stab;
3574    int i, j, nent, nstrtab, nsymtabs;
3575    char* sh_strtab;
3576    char* strtab;
3577
3578    char*     ehdrC = (char*)(oc->image);
3579    Elf_Ehdr* ehdr  = (Elf_Ehdr*)ehdrC;
3580
3581    if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
3582        ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
3583        ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
3584        ehdr->e_ident[EI_MAG3] != ELFMAG3) {
3585       errorBelch("%s: not an ELF object", oc->fileName);
3586       return 0;
3587    }
3588
3589    if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
3590       errorBelch("%s: unsupported ELF format", oc->fileName);
3591       return 0;
3592    }
3593
3594    if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
3595        IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
3596    } else
3597    if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
3598        IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
3599    } else {
3600        errorBelch("%s: unknown endiannness", oc->fileName);
3601        return 0;
3602    }
3603
3604    if (ehdr->e_type != ET_REL) {
3605       errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
3606       return 0;
3607    }
3608    IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
3609
3610    IF_DEBUG(linker,debugBelch( "Architecture is " ));
3611    switch (ehdr->e_machine) {
3612       case EM_386:   IF_DEBUG(linker,debugBelch( "x86" )); break;
3613 #ifdef EM_SPARC32PLUS
3614       case EM_SPARC32PLUS:
3615 #endif
3616       case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
3617 #ifdef EM_IA_64
3618       case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
3619 #endif
3620       case EM_PPC:   IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
3621 #ifdef EM_X86_64
3622       case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
3623 #elif defined(EM_AMD64)
3624       case EM_AMD64: IF_DEBUG(linker,debugBelch( "amd64" )); break;
3625 #endif
3626       default:       IF_DEBUG(linker,debugBelch( "unknown" ));
3627                      errorBelch("%s: unknown architecture (e_machine == %d)"
3628                                 , oc->fileName, ehdr->e_machine);
3629                      return 0;
3630    }
3631
3632    IF_DEBUG(linker,debugBelch(
3633              "\nSection header table: start %ld, n_entries %d, ent_size %d\n",
3634              (long)ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize  ));
3635
3636    ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
3637
3638    shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3639
3640    if (ehdr->e_shstrndx == SHN_UNDEF) {
3641       errorBelch("%s: no section header string table", oc->fileName);
3642       return 0;
3643    } else {
3644       IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
3645                           ehdr->e_shstrndx));
3646       sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
3647    }
3648
3649    for (i = 0; i < ehdr->e_shnum; i++) {
3650       IF_DEBUG(linker,debugBelch("%2d:  ", i ));
3651       IF_DEBUG(linker,debugBelch("type=%2d  ", (int)shdr[i].sh_type ));
3652       IF_DEBUG(linker,debugBelch("size=%4d  ", (int)shdr[i].sh_size ));
3653       IF_DEBUG(linker,debugBelch("offs=%4d  ", (int)shdr[i].sh_offset ));
3654       IF_DEBUG(linker,debugBelch("  (%p .. %p)  ",
3655                ehdrC + shdr[i].sh_offset,
3656                       ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
3657
3658       if (shdr[i].sh_type == SHT_REL) {
3659           IF_DEBUG(linker,debugBelch("Rel  " ));
3660       } else if (shdr[i].sh_type == SHT_RELA) {
3661           IF_DEBUG(linker,debugBelch("RelA " ));
3662       } else {
3663           IF_DEBUG(linker,debugBelch("     "));
3664       }
3665       if (sh_strtab) {
3666           IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
3667       }
3668    }
3669
3670    IF_DEBUG(linker,debugBelch( "\nString tables" ));
3671    strtab = NULL;
3672    nstrtab = 0;
3673    for (i = 0; i < ehdr->e_shnum; i++) {
3674       if (shdr[i].sh_type == SHT_STRTAB
3675           /* Ignore the section header's string table. */
3676           && i != ehdr->e_shstrndx
3677           /* Ignore string tables named .stabstr, as they contain
3678              debugging info. */
3679           && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
3680          ) {
3681          IF_DEBUG(linker,debugBelch("   section %d is a normal string table", i ));
3682          strtab = ehdrC + shdr[i].sh_offset;
3683          nstrtab++;
3684       }
3685    }
3686    if (nstrtab != 1) {
3687       errorBelch("%s: no string tables, or too many", oc->fileName);
3688       return 0;
3689    }
3690
3691    nsymtabs = 0;
3692    IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
3693    for (i = 0; i < ehdr->e_shnum; i++) {
3694       if (shdr[i].sh_type != SHT_SYMTAB) continue;
3695       IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
3696       nsymtabs++;
3697       stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3698       nent = shdr[i].sh_size / sizeof(Elf_Sym);
3699       IF_DEBUG(linker,debugBelch( "   number of entries is apparently %d (%ld rem)\n",
3700                nent,
3701                (long)shdr[i].sh_size % sizeof(Elf_Sym)
3702              ));
3703       if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
3704          errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
3705          return 0;
3706       }
3707       for (j = 0; j < nent; j++) {
3708          IF_DEBUG(linker,debugBelch("   %2d  ", j ));
3709          IF_DEBUG(linker,debugBelch("  sec=%-5d  size=%-3d  val=%5p  ",
3710                              (int)stab[j].st_shndx,
3711                              (int)stab[j].st_size,
3712                              (char*)stab[j].st_value ));
3713
3714          IF_DEBUG(linker,debugBelch("type=" ));
3715          switch (ELF_ST_TYPE(stab[j].st_info)) {
3716             case STT_NOTYPE:  IF_DEBUG(linker,debugBelch("notype " )); break;
3717             case STT_OBJECT:  IF_DEBUG(linker,debugBelch("object " )); break;
3718             case STT_FUNC  :  IF_DEBUG(linker,debugBelch("func   " )); break;
3719             case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
3720             case STT_FILE:    IF_DEBUG(linker,debugBelch("file   " )); break;
3721             default:          IF_DEBUG(linker,debugBelch("?      " )); break;
3722          }
3723          IF_DEBUG(linker,debugBelch("  " ));
3724
3725          IF_DEBUG(linker,debugBelch("bind=" ));
3726          switch (ELF_ST_BIND(stab[j].st_info)) {
3727             case STB_LOCAL :  IF_DEBUG(linker,debugBelch("local " )); break;
3728             case STB_GLOBAL:  IF_DEBUG(linker,debugBelch("global" )); break;
3729             case STB_WEAK  :  IF_DEBUG(linker,debugBelch("weak  " )); break;
3730             default:          IF_DEBUG(linker,debugBelch("?     " )); break;
3731          }
3732          IF_DEBUG(linker,debugBelch("  " ));
3733
3734          IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
3735       }
3736    }
3737
3738    if (nsymtabs == 0) {
3739       errorBelch("%s: didn't find any symbol tables", oc->fileName);
3740       return 0;
3741    }
3742
3743    return 1;
3744 }
3745
3746 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
3747 {
3748     *is_bss = FALSE;
3749
3750     if (hdr->sh_type == SHT_PROGBITS
3751         && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
3752         /* .text-style section */
3753         return SECTIONKIND_CODE_OR_RODATA;
3754     }
3755
3756     if (hdr->sh_type == SHT_PROGBITS
3757             && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3758             /* .data-style section */
3759             return SECTIONKIND_RWDATA;
3760     }
3761
3762     if (hdr->sh_type == SHT_PROGBITS
3763         && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
3764         /* .rodata-style section */
3765         return SECTIONKIND_CODE_OR_RODATA;
3766     }
3767
3768     if (hdr->sh_type == SHT_NOBITS
3769         && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
3770         /* .bss-style section */
3771         *is_bss = TRUE;
3772         return SECTIONKIND_RWDATA;
3773     }
3774
3775     return SECTIONKIND_OTHER;
3776 }
3777
3778
3779 static int
3780 ocGetNames_ELF ( ObjectCode* oc )
3781 {
3782    int i, j, k, nent;
3783    Elf_Sym* stab;
3784
3785    char*     ehdrC    = (char*)(oc->image);
3786    Elf_Ehdr* ehdr     = (Elf_Ehdr*)ehdrC;
3787    char*     strtab   = findElfSection ( ehdrC, SHT_STRTAB );
3788    Elf_Shdr* shdr     = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3789
3790    ASSERT(symhash != NULL);
3791
3792    if (!strtab) {
3793       errorBelch("%s: no strtab", oc->fileName);
3794       return 0;
3795    }
3796
3797    k = 0;
3798    for (i = 0; i < ehdr->e_shnum; i++) {
3799       /* Figure out what kind of section it is.  Logic derived from
3800          Figure 1.14 ("Special Sections") of the ELF document
3801          ("Portable Formats Specification, Version 1.1"). */
3802       int         is_bss = FALSE;
3803       SectionKind kind   = getSectionKind_ELF(&shdr[i], &is_bss);
3804
3805       if (is_bss && shdr[i].sh_size > 0) {
3806          /* This is a non-empty .bss section.  Allocate zeroed space for
3807             it, and set its .sh_offset field such that
3808             ehdrC + .sh_offset == addr_of_zeroed_space.  */
3809          char* zspace = stgCallocBytes(1, shdr[i].sh_size,
3810                                        "ocGetNames_ELF(BSS)");
3811          shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
3812          /*
3813          debugBelch("BSS section at 0x%x, size %d\n",
3814                          zspace, shdr[i].sh_size);
3815          */
3816       }
3817
3818       /* fill in the section info */
3819       if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
3820          addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
3821          addSection(oc, kind, ehdrC + shdr[i].sh_offset,
3822                         ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
3823       }
3824
3825       if (shdr[i].sh_type != SHT_SYMTAB) continue;
3826
3827       /* copy stuff into this module's object symbol table */
3828       stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
3829       nent = shdr[i].sh_size / sizeof(Elf_Sym);
3830
3831       oc->n_symbols = nent;
3832       oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3833                                    "ocGetNames_ELF(oc->symbols)");
3834
3835       for (j = 0; j < nent; j++) {
3836
3837          char  isLocal = FALSE; /* avoids uninit-var warning */
3838          char* ad      = NULL;
3839          char* nm      = strtab + stab[j].st_name;
3840          int   secno   = stab[j].st_shndx;
3841
3842          /* Figure out if we want to add it; if so, set ad to its
3843             address.  Otherwise leave ad == NULL. */
3844
3845          if (secno == SHN_COMMON) {
3846             isLocal = FALSE;
3847             ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
3848             /*
3849             debugBelch("COMMON symbol, size %d name %s\n",
3850                             stab[j].st_size, nm);
3851             */
3852             /* Pointless to do addProddableBlock() for this area,
3853                since the linker should never poke around in it. */
3854          }
3855          else
3856          if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
3857                 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
3858               )
3859               /* and not an undefined symbol */
3860               && stab[j].st_shndx != SHN_UNDEF
3861               /* and not in a "special section" */
3862               && stab[j].st_shndx < SHN_LORESERVE
3863               &&
3864               /* and it's a not a section or string table or anything silly */
3865               ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
3866                 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
3867                 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
3868               )
3869             ) {
3870             /* Section 0 is the undefined section, hence > and not >=. */
3871             ASSERT(secno > 0 && secno < ehdr->e_shnum);
3872             /*
3873             if (shdr[secno].sh_type == SHT_NOBITS) {
3874                debugBelch("   BSS symbol, size %d off %d name %s\n",
3875                                stab[j].st_size, stab[j].st_value, nm);
3876             }
3877             */
3878             ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
3879             if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
3880                isLocal = TRUE;
3881             } else {
3882 #ifdef ELF_FUNCTION_DESC
3883                /* dlsym() and the initialisation table both give us function
3884                 * descriptors, so to be consistent we store function descriptors
3885                 * in the symbol table */
3886                if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
3887                    ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
3888 #endif
3889                IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p  %s %s\n",
3890                                       ad, oc->fileName, nm ));
3891                isLocal = FALSE;
3892             }
3893          }
3894
3895          /* And the decision is ... */
3896
3897          if (ad != NULL) {
3898             ASSERT(nm != NULL);
3899             oc->symbols[j] = nm;
3900             /* Acquire! */
3901             if (isLocal) {
3902                /* Ignore entirely. */
3903             } else {
3904                ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
3905             }
3906          } else {
3907             /* Skip. */
3908             IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
3909                                    strtab + stab[j].st_name ));
3910             /*
3911             debugBelch(
3912                     "skipping   bind = %d,  type = %d,  shndx = %d   `%s'\n",
3913                     (int)ELF_ST_BIND(stab[j].st_info),
3914                     (int)ELF_ST_TYPE(stab[j].st_info),
3915                     (int)stab[j].st_shndx,
3916                     strtab + stab[j].st_name
3917                    );
3918             */
3919             oc->symbols[j] = NULL;
3920          }
3921
3922       }
3923    }
3924
3925    return 1;
3926 }
3927
3928 /* Do ELF relocations which lack an explicit addend.  All x86-linux
3929    relocations appear to be of this form. */
3930 static int
3931 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
3932                          Elf_Shdr* shdr, int shnum,
3933                          Elf_Sym*  stab, char* strtab )
3934 {
3935    int j;
3936    char *symbol;
3937    Elf_Word* targ;
3938    Elf_Rel*  rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
3939    int         nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
3940    int target_shndx = shdr[shnum].sh_info;
3941    int symtab_shndx = shdr[shnum].sh_link;
3942
3943    stab  = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
3944    targ  = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
3945    IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
3946                           target_shndx, symtab_shndx ));
3947
3948    /* Skip sections that we're not interested in. */
3949    {
3950        int is_bss;
3951        SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
3952        if (kind == SECTIONKIND_OTHER) {
3953            IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
3954            return 1;
3955        }
3956    }
3957
3958    for (j = 0; j < nent; j++) {
3959       Elf_Addr offset = rtab[j].r_offset;
3960       Elf_Addr info   = rtab[j].r_info;
3961
3962       Elf_Addr  P  = ((Elf_Addr)targ) + offset;
3963       Elf_Word* pP = (Elf_Word*)P;
3964       Elf_Addr  A  = *pP;
3965       Elf_Addr  S;
3966       void*     S_tmp;
3967       Elf_Addr  value;
3968       StgStablePtr stablePtr;
3969       StgPtr stableVal;
3970
3971       IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
3972                              j, (void*)offset, (void*)info ));
3973       if (!info) {
3974          IF_DEBUG(linker,debugBelch( " ZERO" ));
3975          S = 0;
3976       } else {
3977          Elf_Sym sym = stab[ELF_R_SYM(info)];
3978          /* First see if it is a local symbol. */
3979          if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
3980             /* Yes, so we can get the address directly from the ELF symbol
3981                table. */
3982             symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
3983             S = (Elf_Addr)
3984                 (ehdrC + shdr[ sym.st_shndx ].sh_offset
3985                        + stab[ELF_R_SYM(info)].st_value);
3986
3987          } else {
3988             symbol = strtab + sym.st_name;
3989             stablePtr = (StgStablePtr)lookupHashTable(stablehash, (StgWord)symbol);
3990             if (NULL == stablePtr) {
3991               /* No, so look up the name in our global table. */
3992               S_tmp = lookupSymbol( symbol );
3993               S = (Elf_Addr)S_tmp;
3994             } else {
3995               stableVal = deRefStablePtr( stablePtr );
3996               S_tmp = stableVal;
3997               S = (Elf_Addr)S_tmp;
3998             }
3999          }
4000          if (!S) {
4001             errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4002             return 0;
4003          }
4004          IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
4005       }
4006
4007       IF_DEBUG(linker,debugBelch( "Reloc: P = %p   S = %p   A = %p\n",
4008                              (void*)P, (void*)S, (void*)A ));
4009       checkProddableBlock ( oc, pP );
4010
4011       value = S + A;
4012
4013       switch (ELF_R_TYPE(info)) {
4014 #        ifdef i386_HOST_ARCH
4015          case R_386_32:   *pP = value;     break;
4016          case R_386_PC32: *pP = value - P; break;
4017 #        endif
4018          default:
4019             errorBelch("%s: unhandled ELF relocation(Rel) type %lu\n",
4020                   oc->fileName, (lnat)ELF_R_TYPE(info));
4021             return 0;
4022       }
4023
4024    }
4025    return 1;
4026 }
4027
4028 /* Do ELF relocations for which explicit addends are supplied.
4029    sparc-solaris relocations appear to be of this form. */
4030 static int
4031 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
4032                           Elf_Shdr* shdr, int shnum,
4033                           Elf_Sym*  stab, char* strtab )
4034 {
4035    int j;
4036    char *symbol = NULL;
4037    Elf_Addr targ;
4038    Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
4039    int         nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
4040    int target_shndx = shdr[shnum].sh_info;
4041    int symtab_shndx = shdr[shnum].sh_link;
4042
4043    stab  = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
4044    targ  = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
4045    IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
4046                           target_shndx, symtab_shndx ));
4047
4048    for (j = 0; j < nent; j++) {
4049 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4050       /* This #ifdef only serves to avoid unused-var warnings. */
4051       Elf_Addr  offset = rtab[j].r_offset;
4052       Elf_Addr  P      = targ + offset;
4053 #endif
4054       Elf_Addr  info   = rtab[j].r_info;
4055       Elf_Addr  A      = rtab[j].r_addend;
4056       Elf_Addr  S;
4057       void*     S_tmp;
4058       Elf_Addr  value;
4059 #     if defined(sparc_HOST_ARCH)
4060       Elf_Word* pP = (Elf_Word*)P;
4061       Elf_Word  w1, w2;
4062 #     elif defined(powerpc_HOST_ARCH)
4063       Elf_Sword delta;
4064 #     endif
4065
4066       IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p)   ",
4067                              j, (void*)offset, (void*)info,
4068                                 (void*)A ));
4069       if (!info) {
4070          IF_DEBUG(linker,debugBelch( " ZERO" ));
4071          S = 0;
4072       } else {
4073          Elf_Sym sym = stab[ELF_R_SYM(info)];
4074          /* First see if it is a local symbol. */
4075          if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
4076             /* Yes, so we can get the address directly from the ELF symbol
4077                table. */
4078             symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
4079             S = (Elf_Addr)
4080                 (ehdrC + shdr[ sym.st_shndx ].sh_offset
4081                        + stab[ELF_R_SYM(info)].st_value);
4082 #ifdef ELF_FUNCTION_DESC
4083             /* Make a function descriptor for this function */
4084             if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
4085                S = allocateFunctionDesc(S + A);
4086                A = 0;
4087             }
4088 #endif
4089          } else {
4090             /* No, so look up the name in our global table. */
4091             symbol = strtab + sym.st_name;
4092             S_tmp = lookupSymbol( symbol );
4093             S = (Elf_Addr)S_tmp;
4094
4095 #ifdef ELF_FUNCTION_DESC
4096             /* If a function, already a function descriptor - we would
4097                have to copy it to add an offset. */
4098             if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
4099                errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
4100 #endif
4101          }
4102          if (!S) {
4103            errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
4104            return 0;
4105          }
4106          IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
4107       }
4108
4109       IF_DEBUG(linker,debugBelch("Reloc: P = %p   S = %p   A = %p\n",
4110                                         (void*)P, (void*)S, (void*)A ));
4111       /* checkProddableBlock ( oc, (void*)P ); */
4112
4113       value = S + A;
4114
4115       switch (ELF_R_TYPE(info)) {
4116 #        if defined(sparc_HOST_ARCH)
4117          case R_SPARC_WDISP30:
4118             w1 = *pP & 0xC0000000;
4119             w2 = (Elf_Word)((value - P) >> 2);
4120             ASSERT((w2 & 0xC0000000) == 0);
4121             w1 |= w2;
4122             *pP = w1;
4123             break;
4124          case R_SPARC_HI22:
4125             w1 = *pP & 0xFFC00000;
4126             w2 = (Elf_Word)(value >> 10);
4127             ASSERT((w2 & 0xFFC00000) == 0);
4128             w1 |= w2;
4129             *pP = w1;
4130             break;
4131          case R_SPARC_LO10:
4132             w1 = *pP & ~0x3FF;
4133             w2 = (Elf_Word)(value & 0x3FF);
4134             ASSERT((w2 & ~0x3FF) == 0);
4135             w1 |= w2;
4136             *pP = w1;
4137             break;
4138
4139          /* According to the Sun documentation:
4140             R_SPARC_UA32
4141             This relocation type resembles R_SPARC_32, except it refers to an
4142             unaligned word. That is, the word to be relocated must be treated
4143             as four separate bytes with arbitrary alignment, not as a word
4144             aligned according to the architecture requirements.
4145          */
4146          case R_SPARC_UA32:
4147             w2  = (Elf_Word)value;
4148
4149             // SPARC doesn't do misaligned writes of 32 bit words,
4150             //       so we have to do this one byte-at-a-time.
4151             char *pPc   = (char*)pP;
4152             pPc[0]      = (char) ((Elf_Word)(w2 & 0xff000000) >> 24);
4153             pPc[1]      = (char) ((Elf_Word)(w2 & 0x00ff0000) >> 16);
4154             pPc[2]      = (char) ((Elf_Word)(w2 & 0x0000ff00) >> 8);
4155             pPc[3]      = (char) ((Elf_Word)(w2 & 0x000000ff));
4156             break;
4157
4158          case R_SPARC_32:
4159             w2 = (Elf_Word)value;
4160             *pP = w2;
4161             break;
4162 #        elif defined(powerpc_HOST_ARCH)
4163          case R_PPC_ADDR16_LO:
4164             *(Elf32_Half*) P = value;
4165             break;
4166
4167          case R_PPC_ADDR16_HI:
4168             *(Elf32_Half*) P = value >> 16;
4169             break;
4170
4171          case R_PPC_ADDR16_HA:
4172             *(Elf32_Half*) P = (value + 0x8000) >> 16;
4173             break;
4174
4175          case R_PPC_ADDR32:
4176             *(Elf32_Word *) P = value;
4177             break;
4178
4179          case R_PPC_REL32:
4180             *(Elf32_Word *) P = value - P;
4181             break;
4182
4183          case R_PPC_REL24:
4184             delta = value - P;
4185
4186             if( delta << 6 >> 6 != delta )
4187             {
4188                value = (Elf_Addr) (&makeSymbolExtra( oc, ELF_R_SYM(info), value )
4189                                         ->jumpIsland);
4190                delta = value - P;
4191
4192                if( value == 0 || delta << 6 >> 6 != delta )
4193                {
4194                   barf( "Unable to make SymbolExtra for #%d",
4195                         ELF_R_SYM(info) );
4196                   return 0;
4197                }
4198             }
4199
4200             *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
4201                                           | (delta & 0x3fffffc);
4202             break;
4203 #        endif
4204
4205 #if x86_64_HOST_ARCH
4206       case R_X86_64_64:
4207           *(Elf64_Xword *)P = value;
4208           break;
4209
4210       case R_X86_64_PC32:
4211       {
4212 #if defined(ALWAYS_PIC)
4213           barf("R_X86_64_PC32 relocation, but ALWAYS_PIC.");
4214 #else
4215           StgInt64 off = value - P;
4216           if (off >= 0x7fffffffL || off < -0x80000000L) {
4217 #if X86_64_ELF_NONPIC_HACK
4218               StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4219                                                 -> jumpIsland;
4220               off = pltAddress + A - P;
4221 #else
4222               barf("R_X86_64_PC32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4223                    symbol, off, oc->fileName );
4224 #endif
4225           }
4226           *(Elf64_Word *)P = (Elf64_Word)off;
4227 #endif
4228           break;
4229       }
4230
4231       case R_X86_64_PC64:
4232       {
4233           StgInt64 off = value - P;
4234           *(Elf64_Word *)P = (Elf64_Word)off;
4235           break;
4236       }
4237
4238       case R_X86_64_32:
4239 #if defined(ALWAYS_PIC)
4240           barf("R_X86_64_32 relocation, but ALWAYS_PIC.");
4241 #else
4242           if (value >= 0x7fffffffL) {
4243 #if X86_64_ELF_NONPIC_HACK
4244               StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4245                                                 -> jumpIsland;
4246               value = pltAddress + A;
4247 #else
4248               barf("R_X86_64_32 relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4249                    symbol, value, oc->fileName );
4250 #endif
4251           }
4252           *(Elf64_Word *)P = (Elf64_Word)value;
4253 #endif
4254           break;
4255
4256       case R_X86_64_32S:
4257 #if defined(ALWAYS_PIC)
4258           barf("R_X86_64_32S relocation, but ALWAYS_PIC.");
4259 #else
4260           if ((StgInt64)value > 0x7fffffffL || (StgInt64)value < -0x80000000L) {
4261 #if X86_64_ELF_NONPIC_HACK
4262               StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4263                                                 -> jumpIsland;
4264               value = pltAddress + A;
4265 #else
4266               barf("R_X86_64_32S relocation out of range: %s = %p\nRecompile %s with -fPIC.",
4267                    symbol, value, oc->fileName );
4268 #endif
4269           }
4270           *(Elf64_Sword *)P = (Elf64_Sword)value;
4271 #endif
4272           break;
4273
4274       case R_X86_64_GOTPCREL:
4275       {
4276           StgInt64 gotAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)->addr;
4277           StgInt64 off = gotAddress + A - P;
4278           *(Elf64_Word *)P = (Elf64_Word)off;
4279           break;
4280       }
4281
4282       case R_X86_64_PLT32:
4283       {
4284 #if defined(ALWAYS_PIC)
4285           barf("R_X86_64_PLT32 relocation, but ALWAYS_PIC.");
4286 #else
4287           StgInt64 off = value - P;
4288           if (off >= 0x7fffffffL || off < -0x80000000L) {
4289               StgInt64 pltAddress = (StgInt64) &makeSymbolExtra(oc, ELF_R_SYM(info), S)
4290                                                     -> jumpIsland;
4291               off = pltAddress + A - P;
4292           }
4293           *(Elf64_Word *)P = (Elf64_Word)off;
4294 #endif
4295           break;
4296       }
4297 #endif
4298
4299          default:
4300             errorBelch("%s: unhandled ELF relocation(RelA) type %lu\n",
4301                   oc->fileName, (lnat)ELF_R_TYPE(info));
4302             return 0;
4303       }
4304
4305    }
4306    return 1;
4307 }
4308
4309 static int
4310 ocResolve_ELF ( ObjectCode* oc )
4311 {
4312    char *strtab;
4313    int   shnum, ok;
4314    Elf_Sym*  stab  = NULL;
4315    char*     ehdrC = (char*)(oc->image);
4316    Elf_Ehdr* ehdr  = (Elf_Ehdr*) ehdrC;
4317    Elf_Shdr* shdr  = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
4318
4319    /* first find "the" symbol table */
4320    stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
4321
4322    /* also go find the string table */
4323    strtab = findElfSection ( ehdrC, SHT_STRTAB );
4324
4325    if (stab == NULL || strtab == NULL) {
4326       errorBelch("%s: can't find string or symbol table", oc->fileName);
4327       return 0;
4328    }
4329
4330    /* Process the relocation sections. */
4331    for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
4332       if (shdr[shnum].sh_type == SHT_REL) {
4333          ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
4334                                        shnum, stab, strtab );
4335          if (!ok) return ok;
4336       }
4337       else
4338       if (shdr[shnum].sh_type == SHT_RELA) {
4339          ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
4340                                         shnum, stab, strtab );
4341          if (!ok) return ok;
4342       }
4343    }
4344
4345 #if defined(powerpc_HOST_ARCH)
4346    ocFlushInstructionCache( oc );
4347 #endif
4348
4349    return 1;
4350 }
4351
4352 /*
4353  * PowerPC & X86_64 ELF specifics
4354  */
4355
4356 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
4357
4358 static int ocAllocateSymbolExtras_ELF( ObjectCode *oc )
4359 {
4360   Elf_Ehdr *ehdr;
4361   Elf_Shdr* shdr;
4362   int i;
4363
4364   ehdr = (Elf_Ehdr *) oc->image;
4365   shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
4366
4367   for( i = 0; i < ehdr->e_shnum; i++ )
4368     if( shdr[i].sh_type == SHT_SYMTAB )
4369       break;
4370
4371   if( i == ehdr->e_shnum )
4372   {
4373     errorBelch( "This ELF file contains no symtab" );
4374     return 0;
4375   }
4376
4377   if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
4378   {
4379     errorBelch( "The entry size (%d) of the symtab isn't %d\n",
4380       (int) shdr[i].sh_entsize, (int) sizeof( Elf_Sym ) );
4381
4382     return 0;
4383   }
4384
4385   return ocAllocateSymbolExtras( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
4386 }
4387
4388 #endif /* powerpc */
4389
4390 #endif /* ELF */
4391
4392 /* --------------------------------------------------------------------------
4393  * Mach-O specifics
4394  * ------------------------------------------------------------------------*/
4395
4396 #if defined(OBJFORMAT_MACHO)
4397
4398 /*
4399   Support for MachO linking on Darwin/MacOS X
4400   by Wolfgang Thaller (wolfgang.thaller@gmx.net)
4401
4402   I hereby formally apologize for the hackish nature of this code.
4403   Things that need to be done:
4404   *) implement ocVerifyImage_MachO
4405   *) add still more sanity checks.
4406 */
4407
4408 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4409 #define mach_header mach_header_64
4410 #define segment_command segment_command_64
4411 #define section section_64
4412 #define nlist nlist_64
4413 #endif
4414
4415 #ifdef powerpc_HOST_ARCH
4416 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4417 {
4418     struct mach_header *header = (struct mach_header *) oc->image;
4419     struct load_command *lc = (struct load_command *) (header + 1);
4420     unsigned i;
4421
4422     for( i = 0; i < header->ncmds; i++ )
4423     {
4424         if( lc->cmd == LC_SYMTAB )
4425         {
4426                 // Find out the first and last undefined external
4427                 // symbol, so we don't have to allocate too many
4428                 // jump islands.
4429             struct symtab_command *symLC = (struct symtab_command *) lc;
4430             unsigned min = symLC->nsyms, max = 0;
4431             struct nlist *nlist =
4432                 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
4433                       : NULL;
4434             for(i=0;i<symLC->nsyms;i++)
4435             {
4436                 if(nlist[i].n_type & N_STAB)
4437                     ;
4438                 else if(nlist[i].n_type & N_EXT)
4439                 {
4440                     if((nlist[i].n_type & N_TYPE) == N_UNDF
4441                         && (nlist[i].n_value == 0))
4442                     {
4443                         if(i < min)
4444                             min = i;
4445                         if(i > max)
4446                             max = i;
4447                     }
4448                 }
4449             }
4450             if(max >= min)
4451                 return ocAllocateSymbolExtras(oc, max - min + 1, min);
4452
4453             break;
4454         }
4455
4456         lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4457     }
4458     return ocAllocateSymbolExtras(oc,0,0);
4459 }
4460 #endif
4461 #ifdef x86_64_HOST_ARCH
4462 static int ocAllocateSymbolExtras_MachO(ObjectCode* oc)
4463 {
4464     struct mach_header *header = (struct mach_header *) oc->image;
4465     struct load_command *lc = (struct load_command *) (header + 1);
4466     unsigned i;
4467
4468     for( i = 0; i < header->ncmds; i++ )
4469     {
4470         if( lc->cmd == LC_SYMTAB )
4471         {
4472                 // Just allocate one entry for every symbol
4473             struct symtab_command *symLC = (struct symtab_command *) lc;
4474
4475             return ocAllocateSymbolExtras(oc, symLC->nsyms, 0);
4476         }
4477
4478         lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
4479     }
4480     return ocAllocateSymbolExtras(oc,0,0);
4481 }
4482 #endif
4483
4484 static int ocVerifyImage_MachO(ObjectCode* oc)
4485 {
4486     char *image = (char*) oc->image;
4487     struct mach_header *header = (struct mach_header*) image;
4488
4489 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
4490     if(header->magic != MH_MAGIC_64) {
4491         errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4492                    oc->fileName, MH_MAGIC_64, header->magic);
4493         return 0;
4494     }
4495 #else
4496     if(header->magic != MH_MAGIC) {
4497         errorBelch("%s: Bad magic. Expected: %08x, got: %08x.\n",
4498                    oc->fileName, MH_MAGIC, header->magic);
4499         return 0;
4500     }
4501 #endif
4502     // FIXME: do some more verifying here
4503     return 1;
4504 }
4505
4506 static int resolveImports(
4507     ObjectCode* oc,
4508     char *image,
4509     struct symtab_command *symLC,
4510     struct section *sect,    // ptr to lazy or non-lazy symbol pointer section
4511     unsigned long *indirectSyms,
4512     struct nlist *nlist)
4513 {
4514     unsigned i;
4515     size_t itemSize = 4;
4516
4517     IF_DEBUG(linker, debugBelch("resolveImports: start\n"));
4518
4519 #if i386_HOST_ARCH
4520     int isJumpTable = 0;
4521     if(!strcmp(sect->sectname,"__jump_table"))
4522     {
4523         isJumpTable = 1;
4524         itemSize = 5;
4525         ASSERT(sect->reserved2 == itemSize);
4526     }
4527 #endif
4528
4529     for(i=0; i*itemSize < sect->size;i++)
4530     {
4531         // according to otool, reserved1 contains the first index into the indirect symbol table
4532         struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
4533         char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4534         void *addr = NULL;
4535
4536         IF_DEBUG(linker, debugBelch("resolveImports: resolving %s\n", nm));
4537         if ((symbol->n_type & N_TYPE) == N_UNDF
4538             && (symbol->n_type & N_EXT) && (symbol->n_value != 0)) {
4539             addr = (void*) (symbol->n_value);
4540             IF_DEBUG(linker, debugBelch("resolveImports: undefined external %s has value %p\n", nm, addr));
4541         } else {
4542             addr = lookupSymbol(nm);
4543             IF_DEBUG(linker, debugBelch("resolveImports: looking up %s, %p\n", nm, addr));
4544         }
4545         if (!addr)
4546         {
4547             errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
4548             return 0;
4549         }
4550         ASSERT(addr);
4551
4552 #if i386_HOST_ARCH
4553         if(isJumpTable)
4554         {
4555             checkProddableBlock(oc,image + sect->offset + i*itemSize);
4556             *(image + sect->offset + i*itemSize) = 0xe9; // jmp
4557             *(unsigned*)(image + sect->offset + i*itemSize + 1)
4558                 = (char*)addr - (image + sect->offset + i*itemSize + 5);
4559         }
4560         else
4561 #endif
4562         {
4563             checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
4564             ((void**)(image + sect->offset))[i] = addr;
4565         }
4566     }
4567
4568     IF_DEBUG(linker, debugBelch("resolveImports: done\n"));
4569     return 1;
4570 }
4571
4572 static unsigned long relocateAddress(
4573     ObjectCode* oc,
4574     int nSections,
4575     struct section* sections,
4576     unsigned long address)
4577 {
4578     int i;
4579     IF_DEBUG(linker, debugBelch("relocateAddress: start\n"));
4580     for (i = 0; i < nSections; i++)
4581     {
4582             IF_DEBUG(linker, debugBelch("    relocating address in section %d\n", i));
4583         if (sections[i].addr <= address
4584             && address < sections[i].addr + sections[i].size)
4585         {
4586             return (unsigned long)oc->image
4587                     + sections[i].offset + address - sections[i].addr;
4588         }
4589     }
4590     barf("Invalid Mach-O file:"
4591          "Address out of bounds while relocating object file");
4592     return 0;
4593 }
4594
4595 static int relocateSection(
4596     ObjectCode* oc,
4597     char *image,
4598     struct symtab_command *symLC, struct nlist *nlist,
4599     int nSections, struct section* sections, struct section *sect)
4600 {
4601     struct relocation_info *relocs;
4602     int i, n;
4603
4604     IF_DEBUG(linker, debugBelch("relocateSection: start\n"));
4605
4606     if(!strcmp(sect->sectname,"__la_symbol_ptr"))
4607         return 1;
4608     else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
4609         return 1;
4610     else if(!strcmp(sect->sectname,"__la_sym_ptr2"))
4611         return 1;
4612     else if(!strcmp(sect->sectname,"__la_sym_ptr3"))
4613         return 1;
4614
4615     n = sect->nreloc;
4616     IF_DEBUG(linker, debugBelch("relocateSection: number of relocations: %d\n", n));
4617
4618     relocs = (struct relocation_info*) (image + sect->reloff);
4619
4620     for(i=0;i<n;i++)
4621     {
4622 #ifdef x86_64_HOST_ARCH
4623         struct relocation_info *reloc = &relocs[i];
4624
4625         char    *thingPtr = image + sect->offset + reloc->r_address;
4626         uint64_t thing;
4627         /* We shouldn't need to initialise this, but gcc on OS X 64 bit
4628            complains that it may be used uninitialized if we don't */
4629         uint64_t value = 0;
4630         uint64_t baseValue;
4631         int type = reloc->r_type;
4632
4633         checkProddableBlock(oc,thingPtr);
4634         switch(reloc->r_length)
4635         {
4636             case 0:
4637                 thing = *(uint8_t*)thingPtr;
4638                 baseValue = (uint64_t)thingPtr + 1;
4639                 break;
4640             case 1:
4641                 thing = *(uint16_t*)thingPtr;
4642                 baseValue = (uint64_t)thingPtr + 2;
4643                 break;
4644             case 2:
4645                 thing = *(uint32_t*)thingPtr;
4646                 baseValue = (uint64_t)thingPtr + 4;
4647                 break;
4648             case 3:
4649                 thing = *(uint64_t*)thingPtr;
4650                 baseValue = (uint64_t)thingPtr + 8;
4651                 break;
4652             default:
4653                 barf("Unknown size.");
4654         }
4655
4656         IF_DEBUG(linker,
4657                  debugBelch("relocateSection: length = %d, thing = %" PRId64 ", baseValue = %p\n",
4658                             reloc->r_length, thing, (char *)baseValue));
4659
4660         if (type == X86_64_RELOC_GOT
4661            || type == X86_64_RELOC_GOT_LOAD)
4662         {
4663             struct nlist *symbol = &nlist[reloc->r_symbolnum];
4664             char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4665
4666             IF_DEBUG(linker, debugBelch("relocateSection: making jump island for %s, extern = %d, X86_64_RELOC_GOT\n", nm, reloc->r_extern));
4667             ASSERT(reloc->r_extern);
4668             value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, (unsigned long)lookupSymbol(nm))->addr;
4669
4670             type = X86_64_RELOC_SIGNED;
4671         }
4672         else if(reloc->r_extern)
4673         {
4674             struct nlist *symbol = &nlist[reloc->r_symbolnum];
4675             char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4676
4677             IF_DEBUG(linker, debugBelch("relocateSection: looking up external symbol %s\n", nm));
4678             IF_DEBUG(linker, debugBelch("               : type  = %d\n", symbol->n_type));
4679             IF_DEBUG(linker, debugBelch("               : sect  = %d\n", symbol->n_sect));
4680             IF_DEBUG(linker, debugBelch("               : desc  = %d\n", symbol->n_desc));
4681             IF_DEBUG(linker, debugBelch("               : value = %p\n", (void *)symbol->n_value));
4682             if ((symbol->n_type & N_TYPE) == N_SECT) {
4683                 value = relocateAddress(oc, nSections, sections,
4684                                         symbol->n_value);
4685                 IF_DEBUG(linker, debugBelch("relocateSection, defined external symbol %s, relocated address %p\n", nm, (void *)value));
4686             }
4687             else {
4688                 value = (uint64_t) lookupSymbol(nm);
4689                 IF_DEBUG(linker, debugBelch("relocateSection: external symbol %s, address %p\n", nm, (void *)value));
4690             }
4691         }
4692         else
4693         {
4694             // If the relocation is not through the global offset table
4695             // or external, then set the value to the baseValue.  This
4696             // will leave displacements into the __const section
4697             // unchanged (as they ought to be).
4698
4699             value = baseValue;
4700         }
4701
4702         IF_DEBUG(linker, debugBelch("relocateSection: value = %p\n", (void *)value));
4703
4704         if (type == X86_64_RELOC_BRANCH)
4705         {
4706             if((int32_t)(value - baseValue) != (int64_t)(value - baseValue))
4707             {
4708                 ASSERT(reloc->r_extern);
4709                 value = (uint64_t) &makeSymbolExtra(oc, reloc->r_symbolnum, value)
4710                                         -> jumpIsland;
4711             }
4712             ASSERT((int32_t)(value - baseValue) == (int64_t)(value - baseValue));
4713             type = X86_64_RELOC_SIGNED;
4714         }
4715
4716         switch(type)
4717         {
4718             case X86_64_RELOC_UNSIGNED:
4719                 ASSERT(!reloc->r_pcrel);
4720                 thing += value;
4721                 break;
4722             case X86_64_RELOC_SIGNED:
4723             case X86_64_RELOC_SIGNED_1:
4724             case X86_64_RELOC_SIGNED_2:
4725             case X86_64_RELOC_SIGNED_4:
4726                 ASSERT(reloc->r_pcrel);
4727                 thing += value - baseValue;
4728                 break;
4729             case X86_64_RELOC_SUBTRACTOR:
4730                 ASSERT(!reloc->r_pcrel);
4731                 thing -= value;
4732                 break;
4733             default:
4734                 barf("unkown relocation");
4735         }
4736
4737         switch(reloc->r_length)
4738         {
4739             case 0:
4740                 *(uint8_t*)thingPtr = thing;
4741                 break;
4742             case 1:
4743                 *(uint16_t*)thingPtr = thing;
4744                 break;
4745             case 2:
4746                 *(uint32_t*)thingPtr = thing;
4747                 break;
4748             case 3:
4749                 *(uint64_t*)thingPtr = thing;
4750                 break;
4751         }
4752 #else
4753         if(relocs[i].r_address & R_SCATTERED)
4754         {
4755             struct scattered_relocation_info *scat =
4756                 (struct scattered_relocation_info*) &relocs[i];
4757
4758             if(!scat->r_pcrel)
4759             {
4760                 if(scat->r_length == 2)
4761                 {
4762                     unsigned long word = 0;
4763                     unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
4764                     checkProddableBlock(oc,wordPtr);
4765
4766                     // Note on relocation types:
4767                     // i386 uses the GENERIC_RELOC_* types,
4768                     // while ppc uses special PPC_RELOC_* types.
4769                     // *_RELOC_VANILLA and *_RELOC_PAIR have the same value
4770                     // in both cases, all others are different.
4771                     // Therefore, we use GENERIC_RELOC_VANILLA
4772                     // and GENERIC_RELOC_PAIR instead of the PPC variants,
4773                     // and use #ifdefs for the other types.
4774
4775                     // Step 1: Figure out what the relocated value should be
4776                     if(scat->r_type == GENERIC_RELOC_VANILLA)
4777                     {
4778                         word = *wordPtr + (unsigned long) relocateAddress(
4779                                                                 oc,
4780                                                                 nSections,
4781                                                                 sections,
4782                                                                 scat->r_value)
4783                                         - scat->r_value;
4784                     }
4785 #ifdef powerpc_HOST_ARCH
4786                     else if(scat->r_type == PPC_RELOC_SECTDIFF
4787                         || scat->r_type == PPC_RELOC_LO16_SECTDIFF
4788                         || scat->r_type == PPC_RELOC_HI16_SECTDIFF
4789                         || scat->r_type == PPC_RELOC_HA16_SECTDIFF
4790                         || scat->r_type == PPC_RELOC_LOCAL_SECTDIFF)
4791 #else
4792                     else if(scat->r_type == GENERIC_RELOC_SECTDIFF
4793                         || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4794 #endif
4795                     {
4796                         struct scattered_relocation_info *pair =
4797                                 (struct scattered_relocation_info*) &relocs[i+1];
4798
4799                         if(!pair->r_scattered || pair->r_type != GENERIC_RELOC_PAIR)
4800                             barf("Invalid Mach-O file: "
4801                                  "RELOC_*_SECTDIFF not followed by RELOC_PAIR");
4802
4803                         word = (unsigned long)
4804                                (relocateAddress(oc, nSections, sections, scat->r_value)
4805                               - relocateAddress(oc, nSections, sections, pair->r_value));
4806                         i++;
4807                     }
4808 #ifdef powerpc_HOST_ARCH
4809                     else if(scat->r_type == PPC_RELOC_HI16
4810                          || scat->r_type == PPC_RELOC_LO16
4811                          || scat->r_type == PPC_RELOC_HA16
4812                          || scat->r_type == PPC_RELOC_LO14)
4813                     {   // these are generated by label+offset things
4814                         struct relocation_info *pair = &relocs[i+1];
4815                         if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
4816                             barf("Invalid Mach-O file: "
4817                                  "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
4818
4819                         if(scat->r_type == PPC_RELOC_LO16)
4820                         {
4821                             word = ((unsigned short*) wordPtr)[1];
4822                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4823                         }
4824                         else if(scat->r_type == PPC_RELOC_LO14)
4825                         {
4826                             barf("Unsupported Relocation: PPC_RELOC_LO14");
4827                             word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
4828                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4829                         }
4830                         else if(scat->r_type == PPC_RELOC_HI16)
4831                         {
4832                             word = ((unsigned short*) wordPtr)[1] << 16;
4833                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4834                         }
4835                         else if(scat->r_type == PPC_RELOC_HA16)
4836                         {
4837                             word = ((unsigned short*) wordPtr)[1] << 16;
4838                             word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4839                         }
4840
4841
4842                         word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
4843                                                 - scat->r_value;
4844
4845                         i++;
4846                     }
4847  #endif
4848                     else
4849                     {
4850                         barf ("Don't know how to handle this Mach-O "
4851                               "scattered relocation entry: "
4852                               "object file %s; entry type %ld; "
4853                               "address %#lx\n",
4854                               OC_INFORMATIVE_FILENAME(oc),
4855                               scat->r_type,
4856                               scat->r_address);
4857                         return 0;
4858                      }
4859
4860 #ifdef powerpc_HOST_ARCH
4861                     if(scat->r_type == GENERIC_RELOC_VANILLA
4862                         || scat->r_type == PPC_RELOC_SECTDIFF)
4863 #else
4864                     if(scat->r_type == GENERIC_RELOC_VANILLA
4865                         || scat->r_type == GENERIC_RELOC_SECTDIFF
4866                         || scat->r_type == GENERIC_RELOC_LOCAL_SECTDIFF)
4867 #endif
4868                     {
4869                         *wordPtr = word;
4870                     }
4871 #ifdef powerpc_HOST_ARCH
4872                     else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
4873                     {
4874                         ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
4875                     }
4876                     else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
4877                     {
4878                         ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
4879                     }
4880                     else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
4881                     {
4882                         ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
4883                             + ((word & (1<<15)) ? 1 : 0);
4884                     }
4885 #endif
4886                 }
4887                 else
4888                 {
4889                     barf("Can't handle Mach-O scattered relocation entry "
4890                          "with this r_length tag: "
4891                          "object file %s; entry type %ld; "
4892                          "r_length tag %ld; address %#lx\n",
4893                          OC_INFORMATIVE_FILENAME(oc),
4894                          scat->r_type,
4895                          scat->r_length,
4896                          scat->r_address);
4897                     return 0;
4898                 }
4899             }
4900             else /* scat->r_pcrel */
4901             {
4902                 barf("Don't know how to handle *PC-relative* Mach-O "
4903                      "scattered relocation entry: "
4904                      "object file %s; entry type %ld; address %#lx\n",
4905                      OC_INFORMATIVE_FILENAME(oc),
4906                      scat->r_type,
4907                      scat->r_address);
4908                return 0;
4909             }
4910
4911         }
4912         else /* !(relocs[i].r_address & R_SCATTERED) */
4913         {
4914             struct relocation_info *reloc = &relocs[i];
4915             if(reloc->r_pcrel && !reloc->r_extern)
4916                 continue;
4917
4918             if(reloc->r_length == 2)
4919             {
4920                 unsigned long word = 0;
4921 #ifdef powerpc_HOST_ARCH
4922                 unsigned long jumpIsland = 0;
4923                 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
4924                                                       // to avoid warning and to catch
4925                                                       // bugs.
4926 #endif
4927
4928                 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
4929                 checkProddableBlock(oc,wordPtr);
4930
4931                 if(reloc->r_type == GENERIC_RELOC_VANILLA)
4932                 {
4933                     word = *wordPtr;
4934                 }
4935 #ifdef powerpc_HOST_ARCH
4936                 else if(reloc->r_type == PPC_RELOC_LO16)
4937                 {
4938                     word = ((unsigned short*) wordPtr)[1];
4939                     word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
4940                 }
4941                 else if(reloc->r_type == PPC_RELOC_HI16)
4942                 {
4943                     word = ((unsigned short*) wordPtr)[1] << 16;
4944                     word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
4945                 }
4946                 else if(reloc->r_type == PPC_RELOC_HA16)
4947                 {
4948                     word = ((unsigned short*) wordPtr)[1] << 16;
4949                     word += ((short)relocs[i+1].r_address & (short)0xFFFF);
4950                 }
4951                 else if(reloc->r_type == PPC_RELOC_BR24)
4952                 {
4953                     word = *wordPtr;
4954                     word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
4955                 }
4956 #endif
4957                 else
4958                 {
4959                     barf("Can't handle this Mach-O relocation entry "
4960                          "(not scattered): "
4961                          "object file %s; entry type %ld; address %#lx\n",
4962                          OC_INFORMATIVE_FILENAME(oc),
4963                          reloc->r_type,
4964                          reloc->r_address);
4965                     return 0;
4966                 }
4967
4968                 if(!reloc->r_extern)
4969                 {
4970                     long delta =
4971                         sections[reloc->r_symbolnum-1].offset
4972                         - sections[reloc->r_symbolnum-1].addr
4973                         + ((long) image);
4974
4975                     word += delta;
4976                 }
4977                 else
4978                 {
4979                     struct nlist *symbol = &nlist[reloc->r_symbolnum];
4980                     char *nm = image + symLC->stroff + symbol->n_un.n_strx;
4981                     void *symbolAddress = lookupSymbol(nm);
4982                     if(!symbolAddress)
4983                     {
4984                         errorBelch("\nunknown symbol `%s'", nm);
4985                         return 0;
4986                     }
4987
4988                     if(reloc->r_pcrel)
4989                     {
4990 #ifdef powerpc_HOST_ARCH
4991                             // In the .o file, this should be a relative jump to NULL
4992                             // and we'll change it to a relative jump to the symbol
4993                         ASSERT(word + reloc->r_address == 0);
4994                         jumpIsland = (unsigned long)
4995                                         &makeSymbolExtra(oc,
4996                                                          reloc->r_symbolnum,
4997                                                          (unsigned long) symbolAddress)
4998                                          -> jumpIsland;
4999                         if(jumpIsland != 0)
5000                         {
5001                             offsetToJumpIsland = word + jumpIsland
5002                                 - (((long)image) + sect->offset - sect->addr);
5003                         }
5004 #endif
5005                         word += (unsigned long) symbolAddress
5006                                 - (((long)image) + sect->offset - sect->addr);
5007                     }
5008                     else
5009                     {
5010                         word += (unsigned long) symbolAddress;
5011                     }
5012                 }
5013
5014                 if(reloc->r_type == GENERIC_RELOC_VANILLA)
5015                 {
5016                     *wordPtr = word;
5017                     continue;
5018                 }
5019 #ifdef powerpc_HOST_ARCH
5020                 else if(reloc->r_type == PPC_RELOC_LO16)
5021                 {
5022                     ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
5023                     i++; continue;
5024                 }
5025                 else if(reloc->r_type == PPC_RELOC_HI16)
5026                 {
5027                     ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
5028                     i++; continue;
5029                 }
5030                 else if(reloc->r_type == PPC_RELOC_HA16)
5031                 {
5032                     ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
5033                         + ((word & (1<<15)) ? 1 : 0);
5034                     i++; continue;
5035                 }
5036                 else if(reloc->r_type == PPC_RELOC_BR24)
5037                 {
5038                     if((word & 0x03) != 0)
5039                         barf("%s: unconditional relative branch with a displacement "
5040                              "which isn't a multiple of 4 bytes: %#lx",
5041                              OC_INFORMATIVE_FILENAME(oc),
5042                              word);
5043
5044                     if((word & 0xFE000000) != 0xFE000000 &&
5045                        (word & 0xFE000000) != 0x00000000)
5046                     {
5047                         // The branch offset is too large.
5048                         // Therefore, we try to use a jump island.
5049                         if(jumpIsland == 0)
5050                         {
5051                             barf("%s: unconditional relative branch out of range: "
5052                                  "no jump island available: %#lx",
5053                                  OC_INFORMATIVE_FILENAME(oc),
5054                                  word);
5055                         }
5056
5057                         word = offsetToJumpIsland;
5058                         if((word & 0xFE000000) != 0xFE000000 &&
5059                            (word & 0xFE000000) != 0x00000000)
5060                             barf("%s: unconditional relative branch out of range: "
5061                                  "jump island out of range: %#lx",
5062                                  OC_INFORMATIVE_FILENAME(oc),
5063                                  word);
5064                     }
5065                     *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
5066                     continue;
5067                 }
5068 #endif
5069             }
5070             else
5071             {
5072                  barf("Can't handle Mach-O relocation entry (not scattered) "
5073                       "with this r_length tag: "
5074                       "object file %s; entry type %ld; "
5075                       "r_length tag %ld; address %#lx\n",
5076                       OC_INFORMATIVE_FILENAME(oc),
5077                       reloc->r_type,
5078                       reloc->r_length,
5079                       reloc->r_address);
5080                  return 0;
5081             }
5082         }
5083 #endif
5084     }
5085     IF_DEBUG(linker, debugBelch("relocateSection: done\n"));
5086     return 1;
5087 }
5088
5089 static int ocGetNames_MachO(ObjectCode* oc)
5090 {
5091     char *image = (char*) oc->image;
5092     struct mach_header *header = (struct mach_header*) image;
5093     struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5094     unsigned i,curSymbol = 0;
5095     struct segment_command *segLC = NULL;
5096     struct section *sections;
5097     struct symtab_command *symLC = NULL;
5098     struct nlist *nlist;
5099     unsigned long commonSize = 0;
5100     char    *commonStorage = NULL;
5101     unsigned long commonCounter;
5102
5103     IF_DEBUG(linker,debugBelch("ocGetNames_MachO: start\n"));
5104
5105     for(i=0;i<header->ncmds;i++)
5106     {
5107         if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
5108             segLC = (struct segment_command*) lc;
5109         else if(lc->cmd == LC_SYMTAB)
5110             symLC = (struct symtab_command*) lc;
5111         lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5112     }
5113
5114     sections = (struct section*) (segLC+1);
5115     nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5116                   : NULL;
5117
5118     if(!segLC)
5119         barf("ocGetNames_MachO: no segment load command");
5120
5121     for(i=0;i<segLC->nsects;i++)
5122     {
5123         IF_DEBUG(linker, debugBelch("ocGetNames_MachO: segment %d\n", i));
5124         if (sections[i].size == 0)
5125             continue;
5126
5127         if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
5128         {
5129             char * zeroFillArea = stgCallocBytes(1,sections[i].size,
5130                                       "ocGetNames_MachO(common symbols)");
5131             sections[i].offset = zeroFillArea - image;
5132         }
5133
5134         if(!strcmp(sections[i].sectname,"__text"))
5135             addSection(oc, SECTIONKIND_CODE_OR_RODATA,
5136                 (void*) (image + sections[i].offset),
5137                 (void*) (image + sections[i].offset + sections[i].size));
5138         else if(!strcmp(sections[i].sectname,"__const"))
5139             addSection(oc, SECTIONKIND_RWDATA,
5140                 (void*) (image + sections[i].offset),
5141                 (void*) (image + sections[i].offset + sections[i].size));
5142         else if(!strcmp(sections[i].sectname,"__data"))
5143             addSection(oc, SECTIONKIND_RWDATA,
5144                 (void*) (image + sections[i].offset),
5145                 (void*) (image + sections[i].offset + sections[i].size));
5146         else if(!strcmp(sections[i].sectname,"__bss")
5147                 || !strcmp(sections[i].sectname,"__common"))
5148             addSection(oc, SECTIONKIND_RWDATA,
5149                 (void*) (image + sections[i].offset),
5150                 (void*) (image + sections[i].offset + sections[i].size));
5151
5152         addProddableBlock(oc, (void*) (image + sections[i].offset),
5153                                         sections[i].size);
5154     }
5155
5156         // count external symbols defined here
5157     oc->n_symbols = 0;
5158     if(symLC)
5159     {
5160         for(i=0;i<symLC->nsyms;i++)
5161         {
5162             if(nlist[i].n_type & N_STAB)
5163                 ;
5164             else if(nlist[i].n_type & N_EXT)
5165             {
5166                 if((nlist[i].n_type & N_TYPE) == N_UNDF
5167                     && (nlist[i].n_value != 0))
5168                 {
5169                     commonSize += nlist[i].n_value;
5170                     oc->n_symbols++;
5171                 }
5172                 else if((nlist[i].n_type & N_TYPE) == N_SECT)
5173                     oc->n_symbols++;
5174             }
5175         }
5176     }
5177     IF_DEBUG(linker, debugBelch("ocGetNames_MachO: %d external symbols\n", oc->n_symbols));
5178     oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
5179                                    "ocGetNames_MachO(oc->symbols)");
5180
5181     if(symLC)
5182     {
5183         for(i=0;i<symLC->nsyms;i++)
5184         {
5185             if(nlist[i].n_type & N_STAB)
5186                 ;
5187             else if((nlist[i].n_type & N_TYPE) == N_SECT)
5188             {
5189                 if(nlist[i].n_type & N_EXT)
5190                 {
5191                     char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5192                     if ((nlist[i].n_desc & N_WEAK_DEF) && lookupSymbol(nm)) {
5193                         // weak definition, and we already have a definition
5194                         IF_DEBUG(linker, debugBelch("    weak: %s\n", nm));
5195                     }
5196                     else
5197                     {
5198                             IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting %s\n", nm));
5199                             ghciInsertStrHashTable(oc->fileName, symhash, nm,
5200                                                     image
5201                                                     + sections[nlist[i].n_sect-1].offset
5202                                                     - sections[nlist[i].n_sect-1].addr
5203                                                     + nlist[i].n_value);
5204                             oc->symbols[curSymbol++] = nm;
5205                     }
5206                 }
5207             }
5208         }
5209     }
5210
5211     commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
5212     commonCounter = (unsigned long)commonStorage;
5213     if(symLC)
5214     {
5215         for(i=0;i<symLC->nsyms;i++)
5216         {
5217             if((nlist[i].n_type & N_TYPE) == N_UNDF
5218                     && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
5219             {
5220                 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
5221                 unsigned long sz = nlist[i].n_value;
5222
5223                 nlist[i].n_value = commonCounter;
5224
5225                 IF_DEBUG(linker, debugBelch("ocGetNames_MachO: inserting common symbol: %s\n", nm));
5226                 ghciInsertStrHashTable(oc->fileName, symhash, nm,
5227                                        (void*)commonCounter);
5228                 oc->symbols[curSymbol++] = nm;
5229
5230                 commonCounter += sz;
5231             }
5232         }
5233     }
5234     return 1;
5235 }
5236
5237 static int ocResolve_MachO(ObjectCode* oc)
5238 {
5239     char *image = (char*) oc->image;
5240     struct mach_header *header = (struct mach_header*) image;
5241     struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
5242     unsigned i;
5243     struct segment_command *segLC = NULL;
5244     struct section *sections;
5245     struct symtab_command *symLC = NULL;
5246     struct dysymtab_command *dsymLC = NULL;
5247     struct nlist *nlist;
5248
5249     IF_DEBUG(linker, debugBelch("ocResolve_MachO: start\n"));
5250     for (i = 0; i < header->ncmds; i++)
5251     {
5252         if(lc->cmd == LC_SEGMENT || lc->cmd == LC_SEGMENT_64)
5253             segLC = (struct segment_command*) lc;
5254         else if(lc->cmd == LC_SYMTAB)
5255             symLC = (struct symtab_command*) lc;
5256         else if(lc->cmd == LC_DYSYMTAB)
5257             dsymLC = (struct dysymtab_command*) lc;
5258         lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
5259     }
5260
5261     sections = (struct section*) (segLC+1);
5262     nlist = symLC ? (struct nlist*) (image + symLC->symoff)
5263                   : NULL;
5264
5265     if(dsymLC)
5266     {
5267         unsigned long *indirectSyms
5268             = (unsigned long*) (image + dsymLC->indirectsymoff);
5269
5270         IF_DEBUG(linker, debugBelch("ocResolve_MachO: resolving dsymLC\n"));
5271         for (i = 0; i < segLC->nsects; i++)
5272         {
5273             if(    !strcmp(sections[i].sectname,"__la_symbol_ptr")
5274                 || !strcmp(sections[i].sectname,"__la_sym_ptr2")
5275                 || !strcmp(sections[i].sectname,"__la_sym_ptr3"))
5276             {
5277                 if(!resolveImports(oc,image,symLC,&sections[i],indirectSyms,nlist))
5278                     return 0;
5279             }
5280             else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr")
5281                 ||  !strcmp(sections[i].sectname,"__pointers"))
5282             {
5283                 if(!resolveImports(oc,image,symLC,&sections[i],indirectSyms,nlist))
5284                     return 0;
5285             }
5286             else if(!strcmp(sections[i].sectname,"__jump_table"))
5287             {
5288                 if(!resolveImports(oc,image,symLC,&sections[i],indirectSyms,nlist))
5289                     return 0;
5290             }
5291             else
5292             {
5293                 IF_DEBUG(linker, debugBelch("ocResolve_MachO: unknown section\n"));
5294             }
5295         }
5296     }
5297
5298     for(i=0;i<segLC->nsects;i++)
5299     {
5300             IF_DEBUG(linker, debugBelch("ocResolve_MachO: relocating section %d\n", i));
5301
5302         if (!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,&sections[i]))
5303             return 0;
5304     }
5305
5306 #if defined (powerpc_HOST_ARCH)
5307     ocFlushInstructionCache( oc );
5308 #endif
5309
5310     return 1;
5311 }
5312
5313 #ifdef powerpc_HOST_ARCH
5314 /*
5315  * The Mach-O object format uses leading underscores. But not everywhere.
5316  * There is a small number of runtime support functions defined in
5317  * libcc_dynamic.a whose name does not have a leading underscore.
5318  * As a consequence, we can't get their address from C code.
5319  * We have to use inline assembler just to take the address of a function.
5320  * Yuck.
5321  */
5322
5323 extern void* symbolsWithoutUnderscore[];
5324
5325 static void machoInitSymbolsWithoutUnderscore()
5326 {
5327     void **p = symbolsWithoutUnderscore;
5328     __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
5329
5330 #undef SymI_NeedsProto
5331 #define SymI_NeedsProto(x)  \
5332     __asm__ volatile(".long " # x);
5333
5334     RTS_MACHO_NOUNDERLINE_SYMBOLS
5335
5336     __asm__ volatile(".text");
5337
5338 #undef SymI_NeedsProto
5339 #define SymI_NeedsProto(x)  \
5340     ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
5341
5342     RTS_MACHO_NOUNDERLINE_SYMBOLS
5343
5344 #undef SymI_NeedsProto
5345 }
5346 #endif
5347
5348 #ifndef USE_MMAP
5349 /*
5350  * Figure out by how much to shift the entire Mach-O file in memory
5351  * when loading so that its single segment ends up 16-byte-aligned
5352  */
5353 static int machoGetMisalignment( FILE * f )
5354 {
5355     struct mach_header header;
5356     int misalignment;
5357
5358     {
5359         int n = fread(&header, sizeof(header), 1, f);
5360         if (n != 1) {
5361             barf("machoGetMisalignment: can't read the Mach-O header");
5362         }
5363     }
5364     fseek(f, -sizeof(header), SEEK_CUR);
5365
5366 #if x86_64_HOST_ARCH || powerpc64_HOST_ARCH
5367     if(header.magic != MH_MAGIC_64) {
5368         barf("Bad magic. Expected: %08x, got: %08x.",
5369              MH_MAGIC_64, header.magic);
5370     }
5371 #else
5372     if(header.magic != MH_MAGIC) {
5373         barf("Bad magic. Expected: %08x, got: %08x.",
5374              MH_MAGIC, header.magic);
5375     }
5376 #endif
5377
5378     misalignment = (header.sizeofcmds + sizeof(header))
5379                     & 0xF;
5380
5381     return misalignment ? (16 - misalignment) : 0;
5382 }
5383 #endif
5384
5385 #endif