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