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