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