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