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