Merge branch 'master' of http://darcs.haskell.org/ghc
[ghc.git] / rts / Linker.c
1 /* -----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 2000-2012
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 #include "Proftimer.h"
32
33 #if !defined(mingw32_HOST_OS)
34 #include "posix/Signals.h"
35 #endif
36
37 // get protos for is*()
38 #include <ctype.h>
39
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43
44 #include <inttypes.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdio.h>
48 #include <assert.h>
49
50 #ifdef HAVE_SYS_STAT_H
51 #include <sys/stat.h>
52 #endif
53
54 #if defined(HAVE_DLFCN_H)
55 #include <dlfcn.h>
56 #endif
57
58 #if defined(cygwin32_HOST_OS)
59 #ifdef HAVE_DIRENT_H
60 #include <dirent.h>
61 #endif
62
63 #ifdef HAVE_SYS_TIME_H
64 #include <sys/time.h>
65 #endif
66 #include <regex.h>
67 #include <sys/fcntl.h>
68 #include <sys/termios.h>
69 #include <sys/utime.h>
70 #include <sys/utsname.h>
71 #include <sys/wait.h>
72 #endif
73
74 #if (defined(powerpc_HOST_ARCH) && defined(linux_HOST_OS)) \
75 || (!defined(powerpc_HOST_ARCH) && \
76 ( defined(linux_HOST_OS) || defined(freebsd_HOST_OS) || \
77 defined(dragonfly_HOST_OS) || defined(netbsd_HOST_OS ) || \
78 defined(openbsd_HOST_OS ) || defined(darwin_HOST_OS ) || \
79 defined(kfreebsdgnu_HOST_OS) || defined(gnu_HOST_OS)))
80 /* Don't use mmap on powerpc_HOST_ARCH as mmap doesn't support
81 * reallocating but we need to allocate jump islands just after each
82 * object images. Otherwise relative branches to jump islands can fail
83 * due to 24-bits displacement overflow.
84 */
85 #define USE_MMAP
86 #include <fcntl.h>
87 #include <sys/mman.h>
88
89 #ifdef HAVE_UNISTD_H
90 #include <unistd.h>
91 #endif
92
93 #endif
94
95
96 /* PowerPC has relative branch instructions with only 24 bit displacements
97 * and therefore needs jump islands contiguous with each object code module.
98 */
99 #if (defined(USE_MMAP) && defined(powerpc_HOST_ARCH) && defined(linux_HOST_OS))
100 #define USE_CONTIGUOUS_MMAP 1
101 #else
102 #define USE_CONTIGUOUS_MMAP 0
103 #endif
104
105 #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) || defined(gnu_HOST_OS)
106 # define OBJFORMAT_ELF
107 # include <regex.h> // regex is already used by dlopen() so this is OK
108 // to use here without requiring an additional lib
109 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
110 # define OBJFORMAT_PEi386
111 # include <windows.h>
112 # include <math.h>
113 #elif defined(darwin_HOST_OS)
114 # define OBJFORMAT_MACHO
115 # include <regex.h>
116 # include <mach/machine.h>
117 # include <mach-o/fat.h>
118 # include <mach-o/loader.h>
119 # include <mach-o/nlist.h>
120 # include <mach-o/reloc.h>
121 #if !defined(HAVE_DLFCN_H)
122 # include <mach-o/dyld.h>
123 #endif
124 #if defined(powerpc_HOST_ARCH)
125 # include <mach-o/ppc/reloc.h>
126 #endif
127 #if defined(x86_64_HOST_ARCH)
128 # include <mach-o/x86_64/reloc.h>
129 #endif
130 #endif
131
132 #if defined(x86_64_HOST_ARCH) && defined(darwin_HOST_OS)
133 #define ALWAYS_PIC
134 #endif
135
136 #if defined(dragonfly_HOST_OS)
137 #include <sys/tls.h>
138 #endif
139
140 // Defining this as 'int' rather than 'const int' means that we don't get
141 // warnings like
142 // error: function might be possible candidate for attribute ‘noreturn’
143 // from gcc:
144 #ifdef DYNAMIC_BY_DEFAULT
145 int dynamicByDefault = 1;
146 #else
147 int dynamicByDefault = 0;
148 #endif
149
150 /* Hash table mapping symbol names to Symbol */
151 static /*Str*/HashTable *symhash;
152
153 /* Hash table mapping symbol names to StgStablePtr */
154 static /*Str*/HashTable *stablehash;
155
156 /* List of currently loaded objects */
157 ObjectCode *objects = NULL; /* initially empty */
158
159 static HsInt loadOc( ObjectCode* oc );
160 static ObjectCode* mkOc( pathchar *path, char *image, int imageSize,
161 char *archiveMemberName
162 #ifndef USE_MMAP
163 #ifdef darwin_HOST_OS
164 , int misalignment
165 #endif
166 #endif
167 );
168
169 // Use wchar_t for pathnames on Windows (#5697)
170 #if defined(mingw32_HOST_OS)
171 #define pathcmp wcscmp
172 #define pathlen wcslen
173 #define pathopen _wfopen
174 #define pathstat _wstat
175 #define struct_stat struct _stat
176 #define open wopen
177 #define WSTR(s) L##s
178 #define PATH_FMT "S"
179 #else
180 #define pathcmp strcmp
181 #define pathlen strlen
182 #define pathopen fopen
183 #define pathstat stat
184 #define struct_stat struct stat
185 #define WSTR(s) s
186 #define PATH_FMT "s"
187 #endif
188
189 static pathchar* pathdup(pathchar *path)
190 {
191 pathchar *ret;
192 #if defined(mingw32_HOST_OS)
193 ret = wcsdup(path);
194 #else
195 /* sigh, strdup() isn't a POSIX function, so do it the long way */
196 ret = stgMallocBytes( strlen(path)+1, "loadObj" );
197 strcpy(ret, path);
198 #endif
199 return ret;
200 }
201
202
203 #if defined(OBJFORMAT_ELF)
204 static int ocVerifyImage_ELF ( ObjectCode* oc );
205 static int ocGetNames_ELF ( ObjectCode* oc );
206 static int ocResolve_ELF ( ObjectCode* oc );
207 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH)
208 static int ocAllocateSymbolExtras_ELF ( ObjectCode* oc );
209 #endif
210 #elif defined(OBJFORMAT_PEi386)
211 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
212 static int ocGetNames_PEi386 ( ObjectCode* oc );
213 static int ocResolve_PEi386 ( ObjectCode* oc );
214 static void *lookupSymbolInDLLs ( unsigned char *lbl );
215 static void zapTrailingAtSign ( unsigned char *sym );
216 #elif defined(OBJFORMAT_MACHO)
217 static int ocVerifyImage_MachO ( ObjectCode* oc );
218 static int ocGetNames_MachO ( ObjectCode* oc );
219 static int ocResolve_MachO ( ObjectCode* oc );
220
221 #ifndef USE_MMAP
222 static int machoGetMisalignment( FILE * );
223 #endif
224 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
225 static int ocAllocateSymbolExtras_MachO ( ObjectCode* oc );
226 #endif
227 #ifdef powerpc_HOST_ARCH
228 static void machoInitSymbolsWithoutUnderscore( void );
229 #endif
230 #endif
231
232 /* on x86_64 we have a problem with relocating symbol references in
233 * code that was compiled without -fPIC. By default, the small memory
234 * model is used, which assumes that symbol references can fit in a
235 * 32-bit slot. The system dynamic linker makes this work for
236 * references to shared libraries by either (a) allocating a jump
237 * table slot for code references, or (b) moving the symbol at load
238 * time (and copying its contents, if necessary) for data references.
239 *
240 * We unfortunately can't tell whether symbol references are to code
241 * or data. So for now we assume they are code (the vast majority
242 * are), and allocate jump-table slots. Unfortunately this will
243 * SILENTLY generate crashing code for data references. This hack is
244 * enabled by X86_64_ELF_NONPIC_HACK.
245 *
246 * One workaround is to use shared Haskell libraries. This is
247 * coming. Another workaround is to keep the static libraries but
248 * compile them with -fPIC, because that will generate PIC references
249 * to data which can be relocated. The PIC code is still too green to
250 * do this systematically, though.
251 *
252 * See bug #781
253 * See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
254 *
255 * Naming Scheme for Symbol Macros
256 *
257 * SymI_*: symbol is internal to the RTS. It resides in an object
258 * file/library that is statically.
259 * SymE_*: symbol is external to the RTS library. It might be linked
260 * dynamically.
261 *
262 * Sym*_HasProto : the symbol prototype is imported in an include file
263 * or defined explicitly
264 * Sym*_NeedsProto: the symbol is undefined and we add a dummy
265 * default proto extern void sym(void);
266 */
267 #define X86_64_ELF_NONPIC_HACK 1
268
269 /* Link objects into the lower 2Gb on x86_64. GHC assumes the
270 * small memory model on this architecture (see gcc docs,
271 * -mcmodel=small).
272 *
273 * MAP_32BIT not available on OpenBSD/amd64
274 */
275 #if defined(x86_64_HOST_ARCH) && defined(MAP_32BIT)
276 #define TRY_MAP_32BIT MAP_32BIT
277 #else
278 #define TRY_MAP_32BIT 0
279 #endif
280
281 /*
282 * Due to the small memory model (see above), on x86_64 we have to map
283 * all our non-PIC object files into the low 2Gb of the address space
284 * (why 2Gb and not 4Gb? Because all addresses must be reachable
285 * using a 32-bit signed PC-relative offset). On Linux we can do this
286 * using the MAP_32BIT flag to mmap(), however on other OSs
287 * (e.g. *BSD, see #2063, and also on Linux inside Xen, see #2512), we
288 * can't do this. So on these systems, we have to pick a base address
289 * in the low 2Gb of the address space and try to allocate memory from
290 * there.
291 *
292 * We pick a default address based on the OS, but also make this
293 * configurable via an RTS flag (+RTS -xm)
294 */
295 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
296
297 #if defined(MAP_32BIT)
298 // Try to use MAP_32BIT
299 #define MMAP_32BIT_BASE_DEFAULT 0
300 #else
301 // A guess: 1Gb.
302 #define MMAP_32BIT_BASE_DEFAULT 0x40000000
303 #endif
304
305 static void *mmap_32bit_base = (void *)MMAP_32BIT_BASE_DEFAULT;
306 #endif
307
308 /* MAP_ANONYMOUS is MAP_ANON on some systems, e.g. OpenBSD */
309 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
310 #define MAP_ANONYMOUS MAP_ANON
311 #endif
312
313 /* -----------------------------------------------------------------------------
314 * Built-in symbols from the RTS
315 */
316
317 typedef struct _RtsSymbolVal {
318 char *lbl;
319 void *addr;
320 } RtsSymbolVal;
321
322 #define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
323 SymI_HasProto(stg_mkWeakNoFinalizzerzh) \
324 SymI_HasProto(stg_mkWeakForeignEnvzh) \
325 SymI_HasProto(stg_makeStableNamezh) \
326 SymI_HasProto(stg_finalizzeWeakzh)
327
328 #if !defined (mingw32_HOST_OS)
329 #define RTS_POSIX_ONLY_SYMBOLS \
330 SymI_HasProto(__hscore_get_saved_termios) \
331 SymI_HasProto(__hscore_set_saved_termios) \
332 SymI_HasProto(shutdownHaskellAndSignal) \
333 SymI_HasProto(signal_handlers) \
334 SymI_HasProto(stg_sig_install) \
335 SymI_HasProto(rtsTimerSignal) \
336 SymI_HasProto(atexit) \
337 SymI_NeedsProto(nocldstop)
338 #endif
339
340 #if defined (cygwin32_HOST_OS)
341 #define RTS_MINGW_ONLY_SYMBOLS /**/
342 /* Don't have the ability to read import libs / archives, so
343 * we have to stupidly list a lot of what libcygwin.a
344 * exports; sigh.
345 */
346 #define RTS_CYGWIN_ONLY_SYMBOLS \
347 SymI_HasProto(regfree) \
348 SymI_HasProto(regexec) \
349 SymI_HasProto(regerror) \
350 SymI_HasProto(regcomp) \
351 SymI_HasProto(__errno) \
352 SymI_HasProto(access) \
353 SymI_HasProto(chmod) \
354 SymI_HasProto(chdir) \
355 SymI_HasProto(close) \
356 SymI_HasProto(creat) \
357 SymI_HasProto(dup) \
358 SymI_HasProto(dup2) \
359 SymI_HasProto(fstat) \
360 SymI_HasProto(fcntl) \
361 SymI_HasProto(getcwd) \
362 SymI_HasProto(getenv) \
363 SymI_HasProto(lseek) \
364 SymI_HasProto(open) \
365 SymI_HasProto(fpathconf) \
366 SymI_HasProto(pathconf) \
367 SymI_HasProto(stat) \
368 SymI_HasProto(pow) \
369 SymI_HasProto(tanh) \
370 SymI_HasProto(cosh) \
371 SymI_HasProto(sinh) \
372 SymI_HasProto(atan) \
373 SymI_HasProto(acos) \
374 SymI_HasProto(asin) \
375 SymI_HasProto(tan) \
376 SymI_HasProto(cos) \
377 SymI_HasProto(sin) \
378 SymI_HasProto(exp) \
379 SymI_HasProto(log) \
380 SymI_HasProto(sqrt) \
381 SymI_HasProto(localtime_r) \
382 SymI_HasProto(gmtime_r) \
383 SymI_HasProto(mktime) \
384 SymI_NeedsProto(_imp___tzname) \
385 SymI_HasProto(gettimeofday) \
386 SymI_HasProto(timezone) \
387 SymI_HasProto(tcgetattr) \
388 SymI_HasProto(tcsetattr) \
389 SymI_HasProto(memcpy) \
390 SymI_HasProto(memmove) \
391 SymI_HasProto(realloc) \
392 SymI_HasProto(malloc) \
393 SymI_HasProto(free) \
394 SymI_HasProto(fork) \
395 SymI_HasProto(lstat) \
396 SymI_HasProto(isatty) \
397 SymI_HasProto(mkdir) \
398 SymI_HasProto(opendir) \
399 SymI_HasProto(readdir) \
400 SymI_HasProto(rewinddir) \
401 SymI_HasProto(closedir) \
402 SymI_HasProto(link) \
403 SymI_HasProto(mkfifo) \
404 SymI_HasProto(pipe) \
405 SymI_HasProto(read) \
406 SymI_HasProto(rename) \
407 SymI_HasProto(rmdir) \
408 SymI_HasProto(select) \
409 SymI_HasProto(system) \
410 SymI_HasProto(write) \
411 SymI_HasProto(strcmp) \
412 SymI_HasProto(strcpy) \
413 SymI_HasProto(strncpy) \
414 SymI_HasProto(strerror) \
415 SymI_HasProto(sigaddset) \
416 SymI_HasProto(sigemptyset) \
417 SymI_HasProto(sigprocmask) \
418 SymI_HasProto(umask) \
419 SymI_HasProto(uname) \
420 SymI_HasProto(unlink) \
421 SymI_HasProto(utime) \
422 SymI_HasProto(waitpid)
423
424 #elif defined(mingw32_HOST_OS)
425 #define RTS_POSIX_ONLY_SYMBOLS /**/
426 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
427
428 #if HAVE_GETTIMEOFDAY
429 #define RTS_MINGW_GETTIMEOFDAY_SYM SymI_NeedsProto(gettimeofday)
430 #else
431 #define RTS_MINGW_GETTIMEOFDAY_SYM /**/
432 #endif
433
434 #if HAVE___MINGW_VFPRINTF
435 #define RTS___MINGW_VFPRINTF_SYM SymI_HasProto(__mingw_vfprintf)
436 #else
437 #define RTS___MINGW_VFPRINTF_SYM /**/
438 #endif
439
440 #if defined(i386_HOST_ARCH)
441 #define RTS_WIN32_ONLY(X) X
442 #else
443 #define RTS_WIN32_ONLY(X) /**/
444 #endif
445
446 #if defined(x86_64_HOST_ARCH)
447 #define RTS_WIN64_ONLY(X) X
448 #else
449 #define RTS_WIN64_ONLY(X) /**/
450 #endif
451
452 /* These are statically linked from the mingw libraries into the ghc
453 executable, so we have to employ this hack. */
454 #define RTS_MINGW_ONLY_SYMBOLS \
455 SymI_HasProto(stg_asyncReadzh) \
456 SymI_HasProto(stg_asyncWritezh) \
457 SymI_HasProto(stg_asyncDoProczh) \
458 SymI_HasProto(getWin32ProgArgv) \
459 SymI_HasProto(setWin32ProgArgv) \
460 SymI_HasProto(memset) \
461 SymI_HasProto(inet_ntoa) \
462 SymI_HasProto(inet_addr) \
463 SymI_HasProto(htonl) \
464 SymI_HasProto(recvfrom) \
465 SymI_HasProto(listen) \
466 SymI_HasProto(bind) \
467 SymI_HasProto(shutdown) \
468 SymI_HasProto(connect) \
469 SymI_HasProto(htons) \
470 SymI_HasProto(ntohs) \
471 SymI_HasProto(getservbyname) \
472 SymI_HasProto(getservbyport) \
473 SymI_HasProto(getprotobynumber) \
474 SymI_HasProto(getprotobyname) \
475 SymI_HasProto(gethostbyname) \
476 SymI_HasProto(gethostbyaddr) \
477 SymI_HasProto(gethostname) \
478 SymI_HasProto(strcpy) \
479 SymI_HasProto(strncpy) \
480 SymI_HasProto(abort) \
481 RTS_WIN32_ONLY(SymI_NeedsProto(_alloca)) \
482 SymI_HasProto(isxdigit) \
483 SymI_HasProto(isupper) \
484 SymI_HasProto(ispunct) \
485 SymI_HasProto(islower) \
486 SymI_HasProto(isspace) \
487 SymI_HasProto(isprint) \
488 SymI_HasProto(isdigit) \
489 SymI_HasProto(iscntrl) \
490 SymI_HasProto(isalpha) \
491 SymI_HasProto(isalnum) \
492 SymI_HasProto(isascii) \
493 RTS___MINGW_VFPRINTF_SYM \
494 SymI_HasProto(strcmp) \
495 SymI_HasProto(memmove) \
496 SymI_HasProto(realloc) \
497 SymI_HasProto(malloc) \
498 SymI_HasProto(pow) \
499 SymI_HasProto(tanh) \
500 SymI_HasProto(cosh) \
501 SymI_HasProto(sinh) \
502 SymI_HasProto(atan) \
503 SymI_HasProto(acos) \
504 SymI_HasProto(asin) \
505 SymI_HasProto(tan) \
506 SymI_HasProto(cos) \
507 SymI_HasProto(sin) \
508 SymI_HasProto(exp) \
509 SymI_HasProto(log) \
510 SymI_HasProto(sqrt) \
511 SymI_HasProto(powf) \
512 SymI_HasProto(tanhf) \
513 SymI_HasProto(coshf) \
514 SymI_HasProto(sinhf) \
515 SymI_HasProto(atanf) \
516 SymI_HasProto(acosf) \
517 SymI_HasProto(asinf) \
518 SymI_HasProto(tanf) \
519 SymI_HasProto(cosf) \
520 SymI_HasProto(sinf) \
521 SymI_HasProto(expf) \
522 SymI_HasProto(logf) \
523 SymI_HasProto(sqrtf) \
524 SymI_HasProto(erf) \
525 SymI_HasProto(erfc) \
526 SymI_HasProto(erff) \
527 SymI_HasProto(erfcf) \
528 SymI_HasProto(memcpy) \
529 SymI_HasProto(rts_InstallConsoleEvent) \
530 SymI_HasProto(rts_ConsoleHandlerDone) \
531 SymI_NeedsProto(mktime) \
532 RTS_WIN32_ONLY(SymI_NeedsProto(_imp___timezone)) \
533 RTS_WIN32_ONLY(SymI_NeedsProto(_imp___tzname)) \
534 RTS_WIN32_ONLY(SymI_NeedsProto(_imp__tzname)) \
535 RTS_WIN32_ONLY(SymI_NeedsProto(_imp___iob)) \
536 RTS_WIN32_ONLY(SymI_NeedsProto(_imp___osver)) \
537 SymI_NeedsProto(localtime) \
538 SymI_NeedsProto(gmtime) \
539 SymI_NeedsProto(opendir) \
540 SymI_NeedsProto(readdir) \
541 SymI_NeedsProto(rewinddir) \
542 RTS_WIN32_ONLY(SymI_NeedsProto(_imp____mb_cur_max)) \
543 RTS_WIN32_ONLY(SymI_NeedsProto(_imp___pctype)) \
544 RTS_WIN32_ONLY(SymI_NeedsProto(__chkstk)) \
545 RTS_WIN64_ONLY(SymI_NeedsProto(__imp___iob_func)) \
546 RTS_WIN64_ONLY(SymI_NeedsProto(___chkstk_ms)) \
547 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_localeconv)) \
548 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_islower)) \
549 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_isspace)) \
550 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_isxdigit)) \
551 RTS_WIN64_ONLY(SymI_HasProto(close)) \
552 RTS_WIN64_ONLY(SymI_HasProto(read)) \
553 RTS_WIN64_ONLY(SymI_HasProto(dup)) \
554 RTS_WIN64_ONLY(SymI_HasProto(dup2)) \
555 RTS_WIN64_ONLY(SymI_HasProto(write)) \
556 SymI_NeedsProto(getpid) \
557 RTS_WIN64_ONLY(SymI_HasProto(access)) \
558 SymI_HasProto(chmod) \
559 RTS_WIN64_ONLY(SymI_HasProto(creat)) \
560 RTS_WIN64_ONLY(SymI_HasProto(umask)) \
561 SymI_HasProto(unlink) \
562 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__errno)) \
563 RTS_WIN64_ONLY(SymI_NeedsProto(ftruncate64)) \
564 RTS_WIN64_ONLY(SymI_HasProto(setmode)) \
565 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__wstat64)) \
566 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__fstat64)) \
567 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__wsopen)) \
568 RTS_WIN64_ONLY(SymI_HasProto(__imp__environ)) \
569 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetFileAttributesA)) \
570 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetFileInformationByHandle)) \
571 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetFileType)) \
572 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetLastError)) \
573 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_QueryPerformanceFrequency)) \
574 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_QueryPerformanceCounter)) \
575 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetTickCount)) \
576 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_WaitForSingleObject)) \
577 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_PeekConsoleInputA)) \
578 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_ReadConsoleInputA)) \
579 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_PeekNamedPipe)) \
580 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__isatty)) \
581 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_select)) \
582 RTS_WIN64_ONLY(SymI_HasProto(isatty)) \
583 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__get_osfhandle)) \
584 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetConsoleMode)) \
585 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_SetConsoleMode)) \
586 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_FlushConsoleInputBuffer)) \
587 RTS_WIN64_ONLY(SymI_HasProto(free)) \
588 RTS_WIN64_ONLY(SymI_NeedsProto(raise)) \
589 RTS_WIN64_ONLY(SymI_NeedsProto(_getpid)) \
590 RTS_WIN64_ONLY(SymI_HasProto(getc)) \
591 RTS_WIN64_ONLY(SymI_HasProto(ungetc)) \
592 RTS_WIN64_ONLY(SymI_HasProto(puts)) \
593 RTS_WIN64_ONLY(SymI_HasProto(putc)) \
594 RTS_WIN64_ONLY(SymI_HasProto(putchar)) \
595 RTS_WIN64_ONLY(SymI_HasProto(fputc)) \
596 RTS_WIN64_ONLY(SymI_HasProto(fread)) \
597 RTS_WIN64_ONLY(SymI_HasProto(fwrite)) \
598 RTS_WIN64_ONLY(SymI_HasProto(ferror)) \
599 RTS_WIN64_ONLY(SymI_HasProto(printf)) \
600 RTS_WIN64_ONLY(SymI_HasProto(fprintf)) \
601 RTS_WIN64_ONLY(SymI_HasProto(sprintf)) \
602 RTS_WIN64_ONLY(SymI_HasProto(vsprintf)) \
603 RTS_WIN64_ONLY(SymI_HasProto(sscanf)) \
604 RTS_WIN64_ONLY(SymI_HasProto(ldexp)) \
605 RTS_WIN64_ONLY(SymI_HasProto(strlen)) \
606 RTS_WIN64_ONLY(SymI_HasProto(strnlen)) \
607 RTS_WIN64_ONLY(SymI_HasProto(strchr)) \
608 RTS_WIN64_ONLY(SymI_HasProto(strtol)) \
609 RTS_WIN64_ONLY(SymI_HasProto(strerror)) \
610 RTS_WIN64_ONLY(SymI_HasProto(memchr)) \
611 RTS_WIN64_ONLY(SymI_HasProto(memcmp)) \
612 RTS_WIN64_ONLY(SymI_HasProto(wcscpy)) \
613 RTS_WIN64_ONLY(SymI_HasProto(wcslen)) \
614 RTS_WIN64_ONLY(SymI_HasProto(_lseeki64)) \
615 RTS_WIN64_ONLY(SymI_HasProto(_wchmod)) \
616 RTS_WIN64_ONLY(SymI_HasProto(closesocket)) \
617 RTS_WIN64_ONLY(SymI_HasProto(send)) \
618 RTS_WIN64_ONLY(SymI_HasProto(recv)) \
619 RTS_WIN64_ONLY(SymI_HasProto(bsearch)) \
620 RTS_WIN64_ONLY(SymI_HasProto(CommandLineToArgvW)) \
621 RTS_WIN64_ONLY(SymI_HasProto(CreateBitmap)) \
622 RTS_WIN64_ONLY(SymI_HasProto(CreateBitmapIndirect)) \
623 RTS_WIN64_ONLY(SymI_HasProto(CreateCompatibleBitmap)) \
624 RTS_WIN64_ONLY(SymI_HasProto(CreateDIBPatternBrushPt)) \
625 RTS_WIN64_ONLY(SymI_HasProto(CreateDIBitmap)) \
626 RTS_WIN64_ONLY(SymI_HasProto(SetBitmapDimensionEx)) \
627 RTS_WIN64_ONLY(SymI_HasProto(GetBitmapDimensionEx)) \
628 RTS_WIN64_ONLY(SymI_HasProto(GetStockObject)) \
629 RTS_WIN64_ONLY(SymI_HasProto(GetObjectW)) \
630 RTS_WIN64_ONLY(SymI_HasProto(DeleteObject)) \
631 RTS_WIN64_ONLY(SymI_HasProto(SetDIBits)) \
632 RTS_WIN64_ONLY(SymI_HasProto(GetDIBits)) \
633 RTS_WIN64_ONLY(SymI_HasProto(CreateSolidBrush)) \
634 RTS_WIN64_ONLY(SymI_HasProto(CreateHatchBrush)) \
635 RTS_WIN64_ONLY(SymI_HasProto(CreatePatternBrush)) \
636 RTS_WIN64_ONLY(SymI_HasProto(CreateFontW)) \
637 RTS_WIN64_ONLY(SymI_HasProto(AngleArc)) \
638 RTS_WIN64_ONLY(SymI_HasProto(Arc)) \
639 RTS_WIN64_ONLY(SymI_HasProto(ArcTo)) \
640 RTS_WIN64_ONLY(SymI_HasProto(BeginPath)) \
641 RTS_WIN64_ONLY(SymI_HasProto(BitBlt)) \
642 RTS_WIN64_ONLY(SymI_HasProto(CancelDC)) \
643 RTS_WIN64_ONLY(SymI_HasProto(Chord)) \
644 RTS_WIN64_ONLY(SymI_HasProto(CloseFigure)) \
645 RTS_WIN64_ONLY(SymI_HasProto(CombineRgn)) \
646 RTS_WIN64_ONLY(SymI_HasProto(CreateCompatibleDC)) \
647 RTS_WIN64_ONLY(SymI_HasProto(CreateEllipticRgn)) \
648 RTS_WIN64_ONLY(SymI_HasProto(CreateEllipticRgnIndirect)) \
649 RTS_WIN64_ONLY(SymI_HasProto(CreatePen)) \
650 RTS_WIN64_ONLY(SymI_HasProto(CreatePolygonRgn)) \
651 RTS_WIN64_ONLY(SymI_HasProto(CreateRectRgn)) \
652 RTS_WIN64_ONLY(SymI_HasProto(CreateRectRgnIndirect)) \
653 RTS_WIN64_ONLY(SymI_HasProto(CreateRoundRectRgn)) \
654 RTS_WIN64_ONLY(SymI_HasProto(DeleteDC)) \
655 RTS_WIN64_ONLY(SymI_HasProto(Ellipse)) \
656 RTS_WIN64_ONLY(SymI_HasProto(EndPath)) \
657 RTS_WIN64_ONLY(SymI_HasProto(EqualRgn)) \
658 RTS_WIN64_ONLY(SymI_HasProto(ExtSelectClipRgn)) \
659 RTS_WIN64_ONLY(SymI_HasProto(FillPath)) \
660 RTS_WIN64_ONLY(SymI_HasProto(FillRgn)) \
661 RTS_WIN64_ONLY(SymI_HasProto(FlattenPath)) \
662 RTS_WIN64_ONLY(SymI_HasProto(FrameRgn)) \
663 RTS_WIN64_ONLY(SymI_HasProto(GetArcDirection)) \
664 RTS_WIN64_ONLY(SymI_HasProto(GetBkColor)) \
665 RTS_WIN64_ONLY(SymI_HasProto(GetBkMode)) \
666 RTS_WIN64_ONLY(SymI_HasProto(GetBrushOrgEx)) \
667 RTS_WIN64_ONLY(SymI_HasProto(GetCurrentObject)) \
668 RTS_WIN64_ONLY(SymI_HasProto(GetDCOrgEx)) \
669 RTS_WIN64_ONLY(SymI_HasProto(GetGraphicsMode)) \
670 RTS_WIN64_ONLY(SymI_HasProto(GetMiterLimit)) \
671 RTS_WIN64_ONLY(SymI_HasProto(GetPolyFillMode)) \
672 RTS_WIN64_ONLY(SymI_HasProto(GetRgnBox)) \
673 RTS_WIN64_ONLY(SymI_HasProto(GetStretchBltMode)) \
674 RTS_WIN64_ONLY(SymI_HasProto(GetTextAlign)) \
675 RTS_WIN64_ONLY(SymI_HasProto(GetTextCharacterExtra)) \
676 RTS_WIN64_ONLY(SymI_HasProto(GetTextColor)) \
677 RTS_WIN64_ONLY(SymI_HasProto(GetTextExtentPoint32W)) \
678 RTS_WIN64_ONLY(SymI_HasProto(InvertRgn)) \
679 RTS_WIN64_ONLY(SymI_HasProto(LineTo)) \
680 RTS_WIN64_ONLY(SymI_HasProto(MaskBlt)) \
681 RTS_WIN64_ONLY(SymI_HasProto(MoveToEx)) \
682 RTS_WIN64_ONLY(SymI_HasProto(OffsetRgn)) \
683 RTS_WIN64_ONLY(SymI_HasProto(PaintRgn)) \
684 RTS_WIN64_ONLY(SymI_HasProto(PathToRegion)) \
685 RTS_WIN64_ONLY(SymI_HasProto(Pie)) \
686 RTS_WIN64_ONLY(SymI_HasProto(PlgBlt)) \
687 RTS_WIN64_ONLY(SymI_HasProto(PolyBezier)) \
688 RTS_WIN64_ONLY(SymI_HasProto(PolyBezierTo)) \
689 RTS_WIN64_ONLY(SymI_HasProto(Polygon)) \
690 RTS_WIN64_ONLY(SymI_HasProto(Polyline)) \
691 RTS_WIN64_ONLY(SymI_HasProto(PolylineTo)) \
692 RTS_WIN64_ONLY(SymI_HasProto(PtInRegion)) \
693 RTS_WIN64_ONLY(SymI_HasProto(Rectangle)) \
694 RTS_WIN64_ONLY(SymI_HasProto(RectInRegion)) \
695 RTS_WIN64_ONLY(SymI_HasProto(RestoreDC)) \
696 RTS_WIN64_ONLY(SymI_HasProto(RoundRect)) \
697 RTS_WIN64_ONLY(SymI_HasProto(SaveDC)) \
698 RTS_WIN64_ONLY(SymI_HasProto(SelectClipPath)) \
699 RTS_WIN64_ONLY(SymI_HasProto(SelectClipRgn)) \
700 RTS_WIN64_ONLY(SymI_HasProto(SelectObject)) \
701 RTS_WIN64_ONLY(SymI_HasProto(SelectPalette)) \
702 RTS_WIN64_ONLY(SymI_HasProto(SetArcDirection)) \
703 RTS_WIN64_ONLY(SymI_HasProto(SetBkColor)) \
704 RTS_WIN64_ONLY(SymI_HasProto(SetBkMode)) \
705 RTS_WIN64_ONLY(SymI_HasProto(SetBrushOrgEx)) \
706 RTS_WIN64_ONLY(SymI_HasProto(SetGraphicsMode)) \
707 RTS_WIN64_ONLY(SymI_HasProto(SetMiterLimit)) \
708 RTS_WIN64_ONLY(SymI_HasProto(SetPolyFillMode)) \
709 RTS_WIN64_ONLY(SymI_HasProto(SetStretchBltMode)) \
710 RTS_WIN64_ONLY(SymI_HasProto(SetTextAlign)) \
711 RTS_WIN64_ONLY(SymI_HasProto(SetTextCharacterExtra)) \
712 RTS_WIN64_ONLY(SymI_HasProto(SetTextColor)) \
713 RTS_WIN64_ONLY(SymI_HasProto(StretchBlt)) \
714 RTS_WIN64_ONLY(SymI_HasProto(StrokeAndFillPath)) \
715 RTS_WIN64_ONLY(SymI_HasProto(StrokePath)) \
716 RTS_WIN64_ONLY(SymI_HasProto(TextOutW)) \
717 RTS_WIN64_ONLY(SymI_HasProto(timeGetTime)) \
718 RTS_WIN64_ONLY(SymI_HasProto(WidenPath)) \
719 RTS_WIN64_ONLY(SymI_HasProto(GetFileSecurityW)) \
720 RTS_WIN64_ONLY(SymI_HasProto(RegCloseKey)) \
721 RTS_WIN64_ONLY(SymI_HasProto(RegConnectRegistryW)) \
722 RTS_WIN64_ONLY(SymI_HasProto(RegCreateKeyExW)) \
723 RTS_WIN64_ONLY(SymI_HasProto(RegCreateKeyW)) \
724 RTS_WIN64_ONLY(SymI_HasProto(RegDeleteKeyW)) \
725 RTS_WIN64_ONLY(SymI_HasProto(RegDeleteValueW)) \
726 RTS_WIN64_ONLY(SymI_HasProto(RegEnumKeyW)) \
727 RTS_WIN64_ONLY(SymI_HasProto(RegEnumValueW)) \
728 RTS_WIN64_ONLY(SymI_HasProto(RegFlushKey)) \
729 RTS_WIN64_ONLY(SymI_HasProto(RegLoadKeyW)) \
730 RTS_WIN64_ONLY(SymI_HasProto(RegNotifyChangeKeyValue)) \
731 RTS_WIN64_ONLY(SymI_HasProto(RegOpenKeyExW)) \
732 RTS_WIN64_ONLY(SymI_HasProto(RegOpenKeyW)) \
733 RTS_WIN64_ONLY(SymI_HasProto(RegQueryInfoKeyW)) \
734 RTS_WIN64_ONLY(SymI_HasProto(RegQueryValueExW)) \
735 RTS_WIN64_ONLY(SymI_HasProto(RegQueryValueW)) \
736 RTS_WIN64_ONLY(SymI_HasProto(RegReplaceKeyW)) \
737 RTS_WIN64_ONLY(SymI_HasProto(RegRestoreKeyW)) \
738 RTS_WIN64_ONLY(SymI_HasProto(RegSaveKeyW)) \
739 RTS_WIN64_ONLY(SymI_HasProto(RegSetValueExW)) \
740 RTS_WIN64_ONLY(SymI_HasProto(RegSetValueW)) \
741 RTS_WIN64_ONLY(SymI_HasProto(RegUnLoadKeyW)) \
742 RTS_WIN64_ONLY(SymI_NeedsProto(SHGetFolderPathW)) \
743 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_SetWindowLongPtrW)) \
744 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetWindowLongPtrW)) \
745 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_MenuItemFromPoint)) \
746 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_ChildWindowFromPoint)) \
747 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_ChildWindowFromPointEx)) \
748 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_DeleteObject)) \
749 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_UnmapViewOfFile)) \
750 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_CloseHandle)) \
751 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_FreeLibrary)) \
752 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetMessageW)) \
753 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_TranslateMessage)) \
754 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_DispatchMessageW)) \
755 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_DefWindowProcW)) \
756 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetDIBits)) \
757 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GlobalAlloc)) \
758 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GlobalFree)) \
759 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_CreateFileW)) \
760 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_WriteFile)) \
761 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_CreateCompatibleBitmap)) \
762 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_SelectObject)) \
763 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_Polygon)) \
764 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_FormatMessageW)) \
765 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__localtime64)) \
766 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__tzname)) \
767 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__timezone)) \
768 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_CreatePipe)) \
769 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_SetHandleInformation)) \
770 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetStdHandle)) \
771 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetCurrentProcess)) \
772 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_DuplicateHandle)) \
773 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_CreateProcessW)) \
774 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_TerminateProcess)) \
775 RTS_WIN64_ONLY(SymI_NeedsProto(__imp__open_osfhandle)) \
776 RTS_WIN64_ONLY(SymI_NeedsProto(__imp_GetExitCodeProcess)) \
777 RTS_MINGW_GETTIMEOFDAY_SYM \
778 SymI_NeedsProto(closedir)
779
780 #else
781 #define RTS_MINGW_ONLY_SYMBOLS /**/
782 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
783 #endif
784
785
786 #if defined(darwin_HOST_OS) && HAVE_PRINTF_LDBLSTUB
787 #define RTS_DARWIN_ONLY_SYMBOLS \
788 SymI_NeedsProto(asprintf$LDBLStub) \
789 SymI_NeedsProto(err$LDBLStub) \
790 SymI_NeedsProto(errc$LDBLStub) \
791 SymI_NeedsProto(errx$LDBLStub) \
792 SymI_NeedsProto(fprintf$LDBLStub) \
793 SymI_NeedsProto(fscanf$LDBLStub) \
794 SymI_NeedsProto(fwprintf$LDBLStub) \
795 SymI_NeedsProto(fwscanf$LDBLStub) \
796 SymI_NeedsProto(printf$LDBLStub) \
797 SymI_NeedsProto(scanf$LDBLStub) \
798 SymI_NeedsProto(snprintf$LDBLStub) \
799 SymI_NeedsProto(sprintf$LDBLStub) \
800 SymI_NeedsProto(sscanf$LDBLStub) \
801 SymI_NeedsProto(strtold$LDBLStub) \
802 SymI_NeedsProto(swprintf$LDBLStub) \
803 SymI_NeedsProto(swscanf$LDBLStub) \
804 SymI_NeedsProto(syslog$LDBLStub) \
805 SymI_NeedsProto(vasprintf$LDBLStub) \
806 SymI_NeedsProto(verr$LDBLStub) \
807 SymI_NeedsProto(verrc$LDBLStub) \
808 SymI_NeedsProto(verrx$LDBLStub) \
809 SymI_NeedsProto(vfprintf$LDBLStub) \
810 SymI_NeedsProto(vfscanf$LDBLStub) \
811 SymI_NeedsProto(vfwprintf$LDBLStub) \
812 SymI_NeedsProto(vfwscanf$LDBLStub) \
813 SymI_NeedsProto(vprintf$LDBLStub) \
814 SymI_NeedsProto(vscanf$LDBLStub) \
815 SymI_NeedsProto(vsnprintf$LDBLStub) \
816 SymI_NeedsProto(vsprintf$LDBLStub) \
817 SymI_NeedsProto(vsscanf$LDBLStub) \
818 SymI_NeedsProto(vswprintf$LDBLStub) \
819 SymI_NeedsProto(vswscanf$LDBLStub) \
820 SymI_NeedsProto(vsyslog$LDBLStub) \
821 SymI_NeedsProto(vwarn$LDBLStub) \
822 SymI_NeedsProto(vwarnc$LDBLStub) \
823 SymI_NeedsProto(vwarnx$LDBLStub) \
824 SymI_NeedsProto(vwprintf$LDBLStub) \
825 SymI_NeedsProto(vwscanf$LDBLStub) \
826 SymI_NeedsProto(warn$LDBLStub) \
827 SymI_NeedsProto(warnc$LDBLStub) \
828 SymI_NeedsProto(warnx$LDBLStub) \
829 SymI_NeedsProto(wcstold$LDBLStub) \
830 SymI_NeedsProto(wprintf$LDBLStub) \
831 SymI_NeedsProto(wscanf$LDBLStub)
832 #else
833 #define RTS_DARWIN_ONLY_SYMBOLS
834 #endif
835
836 #ifndef SMP
837 # define MAIN_CAP_SYM SymI_HasProto(MainCapability)
838 #else
839 # define MAIN_CAP_SYM
840 #endif
841
842 #if !defined(mingw32_HOST_OS)
843 #define RTS_USER_SIGNALS_SYMBOLS \
844 SymI_HasProto(setIOManagerControlFd) \
845 SymI_HasProto(setIOManagerWakeupFd) \
846 SymI_HasProto(ioManagerWakeup) \
847 SymI_HasProto(blockUserSignals) \
848 SymI_HasProto(unblockUserSignals)
849 #else
850 #define RTS_USER_SIGNALS_SYMBOLS \
851 SymI_HasProto(ioManagerWakeup) \
852 SymI_HasProto(sendIOManagerEvent) \
853 SymI_HasProto(readIOManagerEvent) \
854 SymI_HasProto(getIOManagerEvent) \
855 SymI_HasProto(console_handler)
856 #endif
857
858 #define RTS_LIBFFI_SYMBOLS \
859 SymE_NeedsProto(ffi_prep_cif) \
860 SymE_NeedsProto(ffi_call) \
861 SymE_NeedsProto(ffi_type_void) \
862 SymE_NeedsProto(ffi_type_float) \
863 SymE_NeedsProto(ffi_type_double) \
864 SymE_NeedsProto(ffi_type_sint64) \
865 SymE_NeedsProto(ffi_type_uint64) \
866 SymE_NeedsProto(ffi_type_sint32) \
867 SymE_NeedsProto(ffi_type_uint32) \
868 SymE_NeedsProto(ffi_type_sint16) \
869 SymE_NeedsProto(ffi_type_uint16) \
870 SymE_NeedsProto(ffi_type_sint8) \
871 SymE_NeedsProto(ffi_type_uint8) \
872 SymE_NeedsProto(ffi_type_pointer)
873
874 #ifdef TABLES_NEXT_TO_CODE
875 #define RTS_RET_SYMBOLS /* nothing */
876 #else
877 #define RTS_RET_SYMBOLS \
878 SymI_HasProto(stg_enter_ret) \
879 SymI_HasProto(stg_gc_fun_ret) \
880 SymI_HasProto(stg_ap_v_ret) \
881 SymI_HasProto(stg_ap_f_ret) \
882 SymI_HasProto(stg_ap_d_ret) \
883 SymI_HasProto(stg_ap_l_ret) \
884 SymI_HasProto(stg_ap_v16_ret) \
885 SymI_HasProto(stg_ap_n_ret) \
886 SymI_HasProto(stg_ap_p_ret) \
887 SymI_HasProto(stg_ap_pv_ret) \
888 SymI_HasProto(stg_ap_pp_ret) \
889 SymI_HasProto(stg_ap_ppv_ret) \
890 SymI_HasProto(stg_ap_ppp_ret) \
891 SymI_HasProto(stg_ap_pppv_ret) \
892 SymI_HasProto(stg_ap_pppp_ret) \
893 SymI_HasProto(stg_ap_ppppp_ret) \
894 SymI_HasProto(stg_ap_pppppp_ret)
895 #endif
896
897 /* Modules compiled with -ticky may mention ticky counters */
898 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
899 #define RTS_TICKY_SYMBOLS \
900 SymI_NeedsProto(ticky_entry_ctrs) \
901 SymI_NeedsProto(top_ct) \
902 \
903 SymI_HasProto(ENT_VIA_NODE_ctr) \
904 SymI_HasProto(ENT_STATIC_THK_ctr) \
905 SymI_HasProto(ENT_DYN_THK_ctr) \
906 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
907 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
908 SymI_HasProto(ENT_STATIC_CON_ctr) \
909 SymI_HasProto(ENT_DYN_CON_ctr) \
910 SymI_HasProto(ENT_STATIC_IND_ctr) \
911 SymI_HasProto(ENT_DYN_IND_ctr) \
912 SymI_HasProto(ENT_PERM_IND_ctr) \
913 SymI_HasProto(ENT_PAP_ctr) \
914 SymI_HasProto(ENT_AP_ctr) \
915 SymI_HasProto(ENT_AP_STACK_ctr) \
916 SymI_HasProto(ENT_BH_ctr) \
917 SymI_HasProto(UNKNOWN_CALL_ctr) \
918 SymI_HasProto(SLOW_CALL_v_ctr) \
919 SymI_HasProto(SLOW_CALL_f_ctr) \
920 SymI_HasProto(SLOW_CALL_d_ctr) \
921 SymI_HasProto(SLOW_CALL_l_ctr) \
922 SymI_HasProto(SLOW_CALL_n_ctr) \
923 SymI_HasProto(SLOW_CALL_p_ctr) \
924 SymI_HasProto(SLOW_CALL_pv_ctr) \
925 SymI_HasProto(SLOW_CALL_pp_ctr) \
926 SymI_HasProto(SLOW_CALL_ppv_ctr) \
927 SymI_HasProto(SLOW_CALL_ppp_ctr) \
928 SymI_HasProto(SLOW_CALL_pppv_ctr) \
929 SymI_HasProto(SLOW_CALL_pppp_ctr) \
930 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
931 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
932 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
933 SymI_HasProto(ticky_slow_call_unevald) \
934 SymI_HasProto(SLOW_CALL_ctr) \
935 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
936 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
937 SymI_HasProto(KNOWN_CALL_ctr) \
938 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
939 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
940 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
941 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
942 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
943 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
944 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
945 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
946 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
947 SymI_HasProto(UPDF_OMITTED_ctr) \
948 SymI_HasProto(UPDF_PUSHED_ctr) \
949 SymI_HasProto(CATCHF_PUSHED_ctr) \
950 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
951 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
952 SymI_HasProto(UPD_SQUEEZED_ctr) \
953 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
954 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
955 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
956 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
957 SymI_HasProto(ALLOC_HEAP_ctr) \
958 SymI_HasProto(ALLOC_HEAP_tot) \
959 SymI_HasProto(ALLOC_FUN_ctr) \
960 SymI_HasProto(ALLOC_FUN_adm) \
961 SymI_HasProto(ALLOC_FUN_gds) \
962 SymI_HasProto(ALLOC_FUN_slp) \
963 SymI_HasProto(UPD_NEW_IND_ctr) \
964 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
965 SymI_HasProto(UPD_OLD_IND_ctr) \
966 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
967 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
968 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
969 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
970 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
971 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
972 SymI_HasProto(GC_SEL_MINOR_ctr) \
973 SymI_HasProto(GC_SEL_MAJOR_ctr) \
974 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
975 SymI_HasProto(ALLOC_UP_THK_ctr) \
976 SymI_HasProto(ALLOC_SE_THK_ctr) \
977 SymI_HasProto(ALLOC_THK_adm) \
978 SymI_HasProto(ALLOC_THK_gds) \
979 SymI_HasProto(ALLOC_THK_slp) \
980 SymI_HasProto(ALLOC_CON_ctr) \
981 SymI_HasProto(ALLOC_CON_adm) \
982 SymI_HasProto(ALLOC_CON_gds) \
983 SymI_HasProto(ALLOC_CON_slp) \
984 SymI_HasProto(ALLOC_TUP_ctr) \
985 SymI_HasProto(ALLOC_TUP_adm) \
986 SymI_HasProto(ALLOC_TUP_gds) \
987 SymI_HasProto(ALLOC_TUP_slp) \
988 SymI_HasProto(ALLOC_BH_ctr) \
989 SymI_HasProto(ALLOC_BH_adm) \
990 SymI_HasProto(ALLOC_BH_gds) \
991 SymI_HasProto(ALLOC_BH_slp) \
992 SymI_HasProto(ALLOC_PRIM_ctr) \
993 SymI_HasProto(ALLOC_PRIM_adm) \
994 SymI_HasProto(ALLOC_PRIM_gds) \
995 SymI_HasProto(ALLOC_PRIM_slp) \
996 SymI_HasProto(ALLOC_PAP_ctr) \
997 SymI_HasProto(ALLOC_PAP_adm) \
998 SymI_HasProto(ALLOC_PAP_gds) \
999 SymI_HasProto(ALLOC_PAP_slp) \
1000 SymI_HasProto(ALLOC_TSO_ctr) \
1001 SymI_HasProto(ALLOC_TSO_adm) \
1002 SymI_HasProto(ALLOC_TSO_gds) \
1003 SymI_HasProto(ALLOC_TSO_slp) \
1004 SymI_HasProto(RET_NEW_ctr) \
1005 SymI_HasProto(RET_OLD_ctr) \
1006 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
1007 SymI_HasProto(RET_SEMI_loads_avoided)
1008
1009
1010 // On most platforms, the garbage collector rewrites references
1011 // to small integer and char objects to a set of common, shared ones.
1012 //
1013 // We don't do this when compiling to Windows DLLs at the moment because
1014 // it doesn't support cross package data references well.
1015 //
1016 #if defined(COMPILING_WINDOWS_DLL)
1017 #define RTS_INTCHAR_SYMBOLS
1018 #else
1019 #define RTS_INTCHAR_SYMBOLS \
1020 SymI_HasProto(stg_CHARLIKE_closure) \
1021 SymI_HasProto(stg_INTLIKE_closure)
1022 #endif
1023
1024
1025 #define RTS_SYMBOLS \
1026 Maybe_Stable_Names \
1027 RTS_TICKY_SYMBOLS \
1028 SymI_HasProto(StgReturn) \
1029 SymI_HasProto(stg_gc_noregs) \
1030 SymI_HasProto(stg_ret_v_info) \
1031 SymI_HasProto(stg_ret_p_info) \
1032 SymI_HasProto(stg_ret_n_info) \
1033 SymI_HasProto(stg_ret_f_info) \
1034 SymI_HasProto(stg_ret_d_info) \
1035 SymI_HasProto(stg_ret_l_info) \
1036 SymI_HasProto(stg_gc_prim_p) \
1037 SymI_HasProto(stg_gc_prim_pp) \
1038 SymI_HasProto(stg_gc_prim_n) \
1039 SymI_HasProto(stg_enter_info) \
1040 SymI_HasProto(__stg_gc_enter_1) \
1041 SymI_HasProto(stg_gc_unpt_r1) \
1042 SymI_HasProto(stg_gc_unbx_r1) \
1043 SymI_HasProto(stg_gc_f1) \
1044 SymI_HasProto(stg_gc_d1) \
1045 SymI_HasProto(stg_gc_l1) \
1046 SymI_HasProto(stg_gc_pp) \
1047 SymI_HasProto(stg_gc_ppp) \
1048 SymI_HasProto(stg_gc_pppp) \
1049 SymI_HasProto(__stg_gc_fun) \
1050 SymI_HasProto(stg_gc_fun_info) \
1051 SymI_HasProto(stg_yield_noregs) \
1052 SymI_HasProto(stg_yield_to_interpreter) \
1053 SymI_HasProto(stg_block_noregs) \
1054 SymI_HasProto(stg_block_takemvar) \
1055 SymI_HasProto(stg_block_putmvar) \
1056 MAIN_CAP_SYM \
1057 SymI_HasProto(MallocFailHook) \
1058 SymI_HasProto(OnExitHook) \
1059 SymI_HasProto(OutOfHeapHook) \
1060 SymI_HasProto(StackOverflowHook) \
1061 SymI_HasProto(addDLL) \
1062 SymI_HasProto(__int_encodeDouble) \
1063 SymI_HasProto(__word_encodeDouble) \
1064 SymI_HasProto(__2Int_encodeDouble) \
1065 SymI_HasProto(__int_encodeFloat) \
1066 SymI_HasProto(__word_encodeFloat) \
1067 SymI_HasProto(stg_atomicallyzh) \
1068 SymI_HasProto(barf) \
1069 SymI_HasProto(debugBelch) \
1070 SymI_HasProto(errorBelch) \
1071 SymI_HasProto(sysErrorBelch) \
1072 SymI_HasProto(stg_getMaskingStatezh) \
1073 SymI_HasProto(stg_maskAsyncExceptionszh) \
1074 SymI_HasProto(stg_maskUninterruptiblezh) \
1075 SymI_HasProto(stg_catchzh) \
1076 SymI_HasProto(stg_catchRetryzh) \
1077 SymI_HasProto(stg_catchSTMzh) \
1078 SymI_HasProto(stg_checkzh) \
1079 SymI_HasProto(closure_flags) \
1080 SymI_HasProto(cmp_thread) \
1081 SymI_HasProto(createAdjustor) \
1082 SymI_HasProto(stg_decodeDoublezu2Intzh) \
1083 SymI_HasProto(stg_decodeFloatzuIntzh) \
1084 SymI_HasProto(defaultsHook) \
1085 SymI_HasProto(stg_delayzh) \
1086 SymI_HasProto(stg_deRefWeakzh) \
1087 SymI_HasProto(stg_deRefStablePtrzh) \
1088 SymI_HasProto(dirty_MUT_VAR) \
1089 SymI_HasProto(dirty_TVAR) \
1090 SymI_HasProto(stg_forkzh) \
1091 SymI_HasProto(stg_forkOnzh) \
1092 SymI_HasProto(forkProcess) \
1093 SymI_HasProto(forkOS_createThread) \
1094 SymI_HasProto(freeHaskellFunctionPtr) \
1095 SymI_HasProto(getOrSetGHCConcSignalSignalHandlerStore) \
1096 SymI_HasProto(getOrSetGHCConcWindowsPendingDelaysStore) \
1097 SymI_HasProto(getOrSetGHCConcWindowsIOManagerThreadStore) \
1098 SymI_HasProto(getOrSetGHCConcWindowsProddingStore) \
1099 SymI_HasProto(getOrSetSystemEventThreadEventManagerStore) \
1100 SymI_HasProto(getOrSetSystemEventThreadIOManagerThreadStore) \
1101 SymI_HasProto(getOrSetSystemTimerThreadEventManagerStore) \
1102 SymI_HasProto(getOrSetSystemTimerThreadIOManagerThreadStore) \
1103 SymI_HasProto(getGCStats) \
1104 SymI_HasProto(getGCStatsEnabled) \
1105 SymI_HasProto(genSymZh) \
1106 SymI_HasProto(genericRaise) \
1107 SymI_HasProto(getProgArgv) \
1108 SymI_HasProto(getFullProgArgv) \
1109 SymI_HasProto(getStablePtr) \
1110 SymI_HasProto(hs_init) \
1111 SymI_HasProto(hs_exit) \
1112 SymI_HasProto(hs_set_argv) \
1113 SymI_HasProto(hs_add_root) \
1114 SymI_HasProto(hs_perform_gc) \
1115 SymI_HasProto(hs_lock_stable_tables) \
1116 SymI_HasProto(hs_unlock_stable_tables) \
1117 SymI_HasProto(hs_free_stable_ptr) \
1118 SymI_HasProto(hs_free_stable_ptr_unsafe) \
1119 SymI_HasProto(hs_free_fun_ptr) \
1120 SymI_HasProto(hs_hpc_rootModule) \
1121 SymI_HasProto(hs_hpc_module) \
1122 SymI_HasProto(initLinker) \
1123 SymI_HasProto(stg_unpackClosurezh) \
1124 SymI_HasProto(stg_getApStackValzh) \
1125 SymI_HasProto(stg_getSparkzh) \
1126 SymI_HasProto(stg_numSparkszh) \
1127 SymI_HasProto(stg_isCurrentThreadBoundzh) \
1128 SymI_HasProto(stg_isEmptyMVarzh) \
1129 SymI_HasProto(stg_killThreadzh) \
1130 SymI_HasProto(loadArchive) \
1131 SymI_HasProto(loadObj) \
1132 SymI_HasProto(insertStableSymbol) \
1133 SymI_HasProto(insertSymbol) \
1134 SymI_HasProto(lookupSymbol) \
1135 SymI_HasProto(stg_makeStablePtrzh) \
1136 SymI_HasProto(stg_mkApUpd0zh) \
1137 SymI_HasProto(stg_myThreadIdzh) \
1138 SymI_HasProto(stg_labelThreadzh) \
1139 SymI_HasProto(stg_newArrayzh) \
1140 SymI_HasProto(stg_newArrayArrayzh) \
1141 SymI_HasProto(stg_newBCOzh) \
1142 SymI_HasProto(stg_newByteArrayzh) \
1143 SymI_HasProto_redirect(newCAF, newDynCAF) \
1144 SymI_HasProto(stg_newMVarzh) \
1145 SymI_HasProto(stg_newMutVarzh) \
1146 SymI_HasProto(stg_newTVarzh) \
1147 SymI_HasProto(stg_noDuplicatezh) \
1148 SymI_HasProto(stg_atomicModifyMutVarzh) \
1149 SymI_HasProto(stg_casMutVarzh) \
1150 SymI_HasProto(stg_newPinnedByteArrayzh) \
1151 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
1152 SymI_HasProto(newSpark) \
1153 SymI_HasProto(performGC) \
1154 SymI_HasProto(performMajorGC) \
1155 SymI_HasProto(prog_argc) \
1156 SymI_HasProto(prog_argv) \
1157 SymI_HasProto(stg_putMVarzh) \
1158 SymI_HasProto(stg_raisezh) \
1159 SymI_HasProto(stg_raiseIOzh) \
1160 SymI_HasProto(stg_readTVarzh) \
1161 SymI_HasProto(stg_readTVarIOzh) \
1162 SymI_HasProto(resumeThread) \
1163 SymI_HasProto(setNumCapabilities) \
1164 SymI_HasProto(getNumberOfProcessors) \
1165 SymI_HasProto(resolveObjs) \
1166 SymI_HasProto(stg_retryzh) \
1167 SymI_HasProto(rts_apply) \
1168 SymI_HasProto(rts_checkSchedStatus) \
1169 SymI_HasProto(rts_eval) \
1170 SymI_HasProto(rts_evalIO) \
1171 SymI_HasProto(rts_evalLazyIO) \
1172 SymI_HasProto(rts_evalStableIO) \
1173 SymI_HasProto(rts_eval_) \
1174 SymI_HasProto(rts_getBool) \
1175 SymI_HasProto(rts_getChar) \
1176 SymI_HasProto(rts_getDouble) \
1177 SymI_HasProto(rts_getFloat) \
1178 SymI_HasProto(rts_getInt) \
1179 SymI_HasProto(rts_getInt8) \
1180 SymI_HasProto(rts_getInt16) \
1181 SymI_HasProto(rts_getInt32) \
1182 SymI_HasProto(rts_getInt64) \
1183 SymI_HasProto(rts_getPtr) \
1184 SymI_HasProto(rts_getFunPtr) \
1185 SymI_HasProto(rts_getStablePtr) \
1186 SymI_HasProto(rts_getThreadId) \
1187 SymI_HasProto(rts_getWord) \
1188 SymI_HasProto(rts_getWord8) \
1189 SymI_HasProto(rts_getWord16) \
1190 SymI_HasProto(rts_getWord32) \
1191 SymI_HasProto(rts_getWord64) \
1192 SymI_HasProto(rts_lock) \
1193 SymI_HasProto(rts_mkBool) \
1194 SymI_HasProto(rts_mkChar) \
1195 SymI_HasProto(rts_mkDouble) \
1196 SymI_HasProto(rts_mkFloat) \
1197 SymI_HasProto(rts_mkInt) \
1198 SymI_HasProto(rts_mkInt8) \
1199 SymI_HasProto(rts_mkInt16) \
1200 SymI_HasProto(rts_mkInt32) \
1201 SymI_HasProto(rts_mkInt64) \
1202 SymI_HasProto(rts_mkPtr) \
1203 SymI_HasProto(rts_mkFunPtr) \
1204 SymI_HasProto(rts_mkStablePtr) \
1205 SymI_HasProto(rts_mkString) \
1206 SymI_HasProto(rts_mkWord) \
1207 SymI_HasProto(rts_mkWord8) \
1208 SymI_HasProto(rts_mkWord16) \
1209 SymI_HasProto(rts_mkWord32) \
1210 SymI_HasProto(rts_mkWord64) \
1211 SymI_HasProto(rts_unlock) \
1212 SymI_HasProto(rts_unsafeGetMyCapability) \
1213 SymI_HasProto(rtsSupportsBoundThreads) \
1214 SymI_HasProto(rts_isProfiled) \
1215 SymI_HasProto(setProgArgv) \
1216 SymI_HasProto(startupHaskell) \
1217 SymI_HasProto(shutdownHaskell) \
1218 SymI_HasProto(shutdownHaskellAndExit) \
1219 SymI_HasProto(stable_name_table) \
1220 SymI_HasProto(stable_ptr_table) \
1221 SymI_HasProto(stackOverflow) \
1222 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
1223 SymI_HasProto(stg_BLACKHOLE_info) \
1224 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
1225 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
1226 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
1227 SymI_HasProto(startTimer) \
1228 SymI_HasProto(stg_MVAR_CLEAN_info) \
1229 SymI_HasProto(stg_MVAR_DIRTY_info) \
1230 SymI_HasProto(stg_TVAR_CLEAN_info) \
1231 SymI_HasProto(stg_TVAR_DIRTY_info) \
1232 SymI_HasProto(stg_IND_STATIC_info) \
1233 SymI_HasProto(stg_ARR_WORDS_info) \
1234 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
1235 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
1236 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
1237 SymI_HasProto(stg_WEAK_info) \
1238 SymI_HasProto(stg_ap_v_info) \
1239 SymI_HasProto(stg_ap_f_info) \
1240 SymI_HasProto(stg_ap_d_info) \
1241 SymI_HasProto(stg_ap_l_info) \
1242 SymI_HasProto(stg_ap_v16_info) \
1243 SymI_HasProto(stg_ap_n_info) \
1244 SymI_HasProto(stg_ap_p_info) \
1245 SymI_HasProto(stg_ap_pv_info) \
1246 SymI_HasProto(stg_ap_pp_info) \
1247 SymI_HasProto(stg_ap_ppv_info) \
1248 SymI_HasProto(stg_ap_ppp_info) \
1249 SymI_HasProto(stg_ap_pppv_info) \
1250 SymI_HasProto(stg_ap_pppp_info) \
1251 SymI_HasProto(stg_ap_ppppp_info) \
1252 SymI_HasProto(stg_ap_pppppp_info) \
1253 SymI_HasProto(stg_ap_0_fast) \
1254 SymI_HasProto(stg_ap_v_fast) \
1255 SymI_HasProto(stg_ap_f_fast) \
1256 SymI_HasProto(stg_ap_d_fast) \
1257 SymI_HasProto(stg_ap_l_fast) \
1258 SymI_HasProto(stg_ap_v16_fast) \
1259 SymI_HasProto(stg_ap_n_fast) \
1260 SymI_HasProto(stg_ap_p_fast) \
1261 SymI_HasProto(stg_ap_pv_fast) \
1262 SymI_HasProto(stg_ap_pp_fast) \
1263 SymI_HasProto(stg_ap_ppv_fast) \
1264 SymI_HasProto(stg_ap_ppp_fast) \
1265 SymI_HasProto(stg_ap_pppv_fast) \
1266 SymI_HasProto(stg_ap_pppp_fast) \
1267 SymI_HasProto(stg_ap_ppppp_fast) \
1268 SymI_HasProto(stg_ap_pppppp_fast) \
1269 SymI_HasProto(stg_ap_1_upd_info) \
1270 SymI_HasProto(stg_ap_2_upd_info) \
1271 SymI_HasProto(stg_ap_3_upd_info) \
1272 SymI_HasProto(stg_ap_4_upd_info) \
1273 SymI_HasProto(stg_ap_5_upd_info) \
1274 SymI_HasProto(stg_ap_6_upd_info) \
1275 SymI_HasProto(stg_ap_7_upd_info) \
1276 SymI_HasProto(stg_exit) \
1277 SymI_HasProto(stg_sel_0_upd_info) \
1278 SymI_HasProto(stg_sel_10_upd_info) \
1279 SymI_HasProto(stg_sel_11_upd_info) \
1280 SymI_HasProto(stg_sel_12_upd_info) \
1281 SymI_HasProto(stg_sel_13_upd_info) \
1282 SymI_HasProto(stg_sel_14_upd_info) \
1283 SymI_HasProto(stg_sel_15_upd_info) \
1284 SymI_HasProto(stg_sel_1_upd_info) \
1285 SymI_HasProto(stg_sel_2_upd_info) \
1286 SymI_HasProto(stg_sel_3_upd_info) \
1287 SymI_HasProto(stg_sel_4_upd_info) \
1288 SymI_HasProto(stg_sel_5_upd_info) \
1289 SymI_HasProto(stg_sel_6_upd_info) \
1290 SymI_HasProto(stg_sel_7_upd_info) \
1291 SymI_HasProto(stg_sel_8_upd_info) \
1292 SymI_HasProto(stg_sel_9_upd_info) \
1293 SymI_HasProto(stg_upd_frame_info) \
1294 SymI_HasProto(stg_bh_upd_frame_info) \
1295 SymI_HasProto(suspendThread) \
1296 SymI_HasProto(stg_takeMVarzh) \
1297 SymI_HasProto(stg_threadStatuszh) \
1298 SymI_HasProto(stg_tryPutMVarzh) \
1299 SymI_HasProto(stg_tryTakeMVarzh) \
1300 SymI_HasProto(stg_unmaskAsyncExceptionszh) \
1301 SymI_HasProto(unloadObj) \
1302 SymI_HasProto(stg_unsafeThawArrayzh) \
1303 SymI_HasProto(stg_waitReadzh) \
1304 SymI_HasProto(stg_waitWritezh) \
1305 SymI_HasProto(stg_writeTVarzh) \
1306 SymI_HasProto(stg_yieldzh) \
1307 SymI_NeedsProto(stg_interp_constr_entry) \
1308 SymI_HasProto(stg_arg_bitmaps) \
1309 SymI_HasProto(large_alloc_lim) \
1310 SymI_HasProto(g0) \
1311 SymI_HasProto(allocate) \
1312 SymI_HasProto(allocateExec) \
1313 SymI_HasProto(freeExec) \
1314 SymI_HasProto(getAllocations) \
1315 SymI_HasProto(revertCAFs) \
1316 SymI_HasProto(RtsFlags) \
1317 SymI_NeedsProto(rts_breakpoint_io_action) \
1318 SymI_NeedsProto(rts_stop_next_breakpoint) \
1319 SymI_NeedsProto(rts_stop_on_exception) \
1320 SymI_HasProto(stopTimer) \
1321 SymI_HasProto(n_capabilities) \
1322 SymI_HasProto(enabled_capabilities) \
1323 SymI_HasProto(stg_traceCcszh) \
1324 SymI_HasProto(stg_traceEventzh) \
1325 SymI_HasProto(stg_traceMarkerzh) \
1326 SymI_HasProto(getMonotonicNSec) \
1327 SymI_HasProto(lockFile) \
1328 SymI_HasProto(unlockFile) \
1329 SymI_HasProto(startProfTimer) \
1330 SymI_HasProto(stopProfTimer) \
1331 RTS_USER_SIGNALS_SYMBOLS \
1332 RTS_INTCHAR_SYMBOLS
1333
1334
1335 // 64-bit support functions in libgcc.a
1336 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4 && !defined(_ABIN32)
1337 #define RTS_LIBGCC_SYMBOLS \
1338 SymI_NeedsProto(__divdi3) \
1339 SymI_NeedsProto(__udivdi3) \
1340 SymI_NeedsProto(__moddi3) \
1341 SymI_NeedsProto(__umoddi3) \
1342 SymI_NeedsProto(__muldi3) \
1343 SymI_NeedsProto(__ashldi3) \
1344 SymI_NeedsProto(__ashrdi3) \
1345 SymI_NeedsProto(__lshrdi3) \
1346 SymI_NeedsProto(__fixunsdfdi)
1347 #else
1348 #define RTS_LIBGCC_SYMBOLS
1349 #endif
1350
1351 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
1352 // Symbols that don't have a leading underscore
1353 // on Mac OS X. They have to receive special treatment,
1354 // see machoInitSymbolsWithoutUnderscore()
1355 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1356 SymI_NeedsProto(saveFP) \
1357 SymI_NeedsProto(restFP)
1358 #endif
1359
1360 /* entirely bogus claims about types of these symbols */
1361 #define SymI_NeedsProto(vvv) extern void vvv(void);
1362 #if defined(COMPILING_WINDOWS_DLL)
1363 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1364 # if defined(x86_64_HOST_ARCH)
1365 # define SymE_NeedsProto(vvv) extern void __imp_ ## vvv (void);
1366 # else
1367 # define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1368 # endif
1369 #else
1370 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1371 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1372 #endif
1373 #define SymI_HasProto(vvv) /**/
1374 #define SymI_HasProto_redirect(vvv,xxx) /**/
1375 RTS_SYMBOLS
1376 RTS_RET_SYMBOLS
1377 RTS_POSIX_ONLY_SYMBOLS
1378 RTS_MINGW_ONLY_SYMBOLS
1379 RTS_CYGWIN_ONLY_SYMBOLS
1380 RTS_DARWIN_ONLY_SYMBOLS
1381 RTS_LIBGCC_SYMBOLS
1382 RTS_LIBFFI_SYMBOLS
1383 #undef SymI_NeedsProto
1384 #undef SymI_HasProto
1385 #undef SymI_HasProto_redirect
1386 #undef SymE_HasProto
1387 #undef SymE_NeedsProto
1388
1389 #ifdef LEADING_UNDERSCORE
1390 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1391 #else
1392 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1393 #endif
1394
1395 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1396 (void*)(&(vvv)) },
1397 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1398 (void*)DLL_IMPORT_DATA_REF(vvv) },
1399
1400 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1401 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1402
1403 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1404 // another symbol. See newCAF/newDynCAF for an example.
1405 #define SymI_HasProto_redirect(vvv,xxx) \
1406 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1407 (void*)(&(xxx)) },
1408
1409 static RtsSymbolVal rtsSyms[] = {
1410 RTS_SYMBOLS
1411 RTS_RET_SYMBOLS
1412 RTS_POSIX_ONLY_SYMBOLS
1413 RTS_MINGW_ONLY_SYMBOLS
1414 RTS_CYGWIN_ONLY_SYMBOLS
1415 RTS_DARWIN_ONLY_SYMBOLS
1416 RTS_LIBGCC_SYMBOLS
1417 RTS_LIBFFI_SYMBOLS
1418 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1419 // dyld stub code contains references to this,
1420 // but it should never be called because we treat
1421 // lazy pointers as nonlazy.
1422 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1423 #endif
1424 { 0, 0 } /* sentinel */
1425 };
1426
1427
1428 /* -----------------------------------------------------------------------------
1429 * Insert symbols into hash tables, checking for duplicates.
1430 */
1431
1432 static void ghciInsertStrHashTable ( pathchar* obj_name,
1433 HashTable *table,
1434 char* key,
1435 void *data
1436 )
1437 {
1438 if (lookupHashTable(table, (StgWord)key) == NULL)
1439 {
1440 insertStrHashTable(table, (StgWord)key, data);
1441 return;
1442 }
1443 debugBelch(
1444 "\n\n"
1445 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1446 " %s\n"
1447 "whilst processing object file\n"
1448 " %" PATH_FMT "\n"
1449 "This could be caused by:\n"
1450 " * Loading two different object files which export the same symbol\n"
1451 " * Specifying the same object file twice on the GHCi command line\n"
1452 " * An incorrect `package.conf' entry, causing some object to be\n"
1453 " loaded twice.\n"
1454 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1455 "\n",
1456 (char*)key,
1457 obj_name
1458 );
1459 stg_exit(1);
1460 }
1461 /* -----------------------------------------------------------------------------
1462 * initialize the object linker
1463 */
1464
1465
1466 static int linker_init_done = 0 ;
1467
1468 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1469 static void *dl_prog_handle;
1470 static regex_t re_invalid;
1471 static regex_t re_realso;
1472 #ifdef THREADED_RTS
1473 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1474 #endif
1475 #endif
1476
1477 void
1478 initLinker( void )
1479 {
1480 RtsSymbolVal *sym;
1481 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1482 int compileResult;
1483 #endif
1484
1485 IF_DEBUG(linker, debugBelch("initLinker: start\n"));
1486
1487 /* Make initLinker idempotent, so we can call it
1488 before every relevant operation; that means we
1489 don't need to initialise the linker separately */
1490 if (linker_init_done == 1) {
1491 IF_DEBUG(linker, debugBelch("initLinker: idempotent return\n"));
1492 return;
1493 } else {
1494 linker_init_done = 1;
1495 }
1496
1497 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1498 initMutex(&dl_mutex);
1499 #endif
1500 stablehash = allocStrHashTable();
1501 symhash = allocStrHashTable();
1502
1503 /* populate the symbol table with stuff from the RTS */
1504 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1505 ghciInsertStrHashTable(WSTR("(GHCi built-in symbols)"),
1506 symhash, sym->lbl, sym->addr);
1507 IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
1508 }
1509 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1510 machoInitSymbolsWithoutUnderscore();
1511 # endif
1512
1513 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1514 # if defined(RTLD_DEFAULT)
1515 dl_prog_handle = RTLD_DEFAULT;
1516 # else
1517 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1518 # endif /* RTLD_DEFAULT */
1519
1520 compileResult = regcomp(&re_invalid,
1521 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short)",
1522 REG_EXTENDED);
1523 if (compileResult != 0) {
1524 barf("Compiling re_invalid failed");
1525 }
1526 compileResult = regcomp(&re_realso,
1527 "(GROUP|INPUT) *\\( *([^ )]+)",
1528 REG_EXTENDED);
1529 if (compileResult != 0) {
1530 barf("Compiling re_realso failed");
1531 }
1532 # endif
1533
1534 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1535 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1536 // User-override for mmap_32bit_base
1537 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1538 }
1539 #endif
1540
1541 #if defined(mingw32_HOST_OS)
1542 /*
1543 * These two libraries cause problems when added to the static link,
1544 * but are necessary for resolving symbols in GHCi, hence we load
1545 * them manually here.
1546 */
1547 addDLL(WSTR("msvcrt"));
1548 addDLL(WSTR("kernel32"));
1549 #endif
1550
1551 IF_DEBUG(linker, debugBelch("initLinker: done\n"));
1552 return;
1553 }
1554
1555 void
1556 exitLinker( void ) {
1557 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1558 if (linker_init_done == 1) {
1559 regfree(&re_invalid);
1560 regfree(&re_realso);
1561 #ifdef THREADED_RTS
1562 closeMutex(&dl_mutex);
1563 #endif
1564 }
1565 #endif
1566 }
1567
1568 /* -----------------------------------------------------------------------------
1569 * Loading DLL or .so dynamic libraries
1570 * -----------------------------------------------------------------------------
1571 *
1572 * Add a DLL from which symbols may be found. In the ELF case, just
1573 * do RTLD_GLOBAL-style add, so no further messing around needs to
1574 * happen in order that symbols in the loaded .so are findable --
1575 * lookupSymbol() will subsequently see them by dlsym on the program's
1576 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1577 *
1578 * In the PEi386 case, open the DLLs and put handles to them in a
1579 * linked list. When looking for a symbol, try all handles in the
1580 * list. This means that we need to load even DLLs that are guaranteed
1581 * to be in the ghc.exe image already, just so we can get a handle
1582 * to give to loadSymbol, so that we can find the symbols. For such
1583 * libraries, the LoadLibrary call should be a no-op except for returning
1584 * the handle.
1585 *
1586 */
1587
1588 #if defined(OBJFORMAT_PEi386)
1589 /* A record for storing handles into DLLs. */
1590
1591 typedef
1592 struct _OpenedDLL {
1593 pathchar* name;
1594 struct _OpenedDLL* next;
1595 HINSTANCE instance;
1596 }
1597 OpenedDLL;
1598
1599 /* A list thereof. */
1600 static OpenedDLL* opened_dlls = NULL;
1601 #endif
1602
1603 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1604
1605 /* Suppose in ghci we load a temporary SO for a module containing
1606 f = 1
1607 and then modify the module, recompile, and load another temporary
1608 SO with
1609 f = 2
1610 Then as we don't unload the first SO, dlsym will find the
1611 f = 1
1612 symbol whereas we want the
1613 f = 2
1614 symbol. We therefore need to keep our own SO handle list, and
1615 try SOs in the right order. */
1616
1617 typedef
1618 struct _OpenedSO {
1619 struct _OpenedSO* next;
1620 void *handle;
1621 }
1622 OpenedSO;
1623
1624 /* A list thereof. */
1625 static OpenedSO* openedSOs = NULL;
1626
1627 static const char *
1628 internal_dlopen(const char *dll_name)
1629 {
1630 OpenedSO* o_so;
1631 void *hdl;
1632 const char *errmsg;
1633 char *errmsg_copy;
1634
1635 // omitted: RTLD_NOW
1636 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1637 IF_DEBUG(linker,
1638 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1639
1640 //-------------- Begin critical section ------------------
1641 // This critical section is necessary because dlerror() is not
1642 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1643 // Also, the error message returned must be copied to preserve it
1644 // (see POSIX also)
1645
1646 ACQUIRE_LOCK(&dl_mutex);
1647 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1648
1649 errmsg = NULL;
1650 if (hdl == NULL) {
1651 /* dlopen failed; return a ptr to the error msg. */
1652 errmsg = dlerror();
1653 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1654 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1655 strcpy(errmsg_copy, errmsg);
1656 errmsg = errmsg_copy;
1657 }
1658 o_so = stgMallocBytes(sizeof(OpenedSO), "addDLL");
1659 o_so->handle = hdl;
1660 o_so->next = openedSOs;
1661 openedSOs = o_so;
1662
1663 RELEASE_LOCK(&dl_mutex);
1664 //--------------- End critical section -------------------
1665
1666 return errmsg;
1667 }
1668
1669 static void *
1670 internal_dlsym(void *hdl, const char *symbol) {
1671 OpenedSO* o_so;
1672 void *v;
1673
1674 // We acquire dl_mutex as concurrent dl* calls may alter dlerror
1675 ACQUIRE_LOCK(&dl_mutex);
1676 dlerror();
1677 for (o_so = openedSOs; o_so != NULL; o_so = o_so->next) {
1678 v = dlsym(o_so->handle, symbol);
1679 if (dlerror() == NULL) {
1680 RELEASE_LOCK(&dl_mutex);
1681 return v;
1682 }
1683 }
1684 v = dlsym(hdl, symbol)
1685 RELEASE_LOCK(&dl_mutex);
1686 return v;
1687 }
1688 # endif
1689
1690 const char *
1691 addDLL( pathchar *dll_name )
1692 {
1693 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1694 /* ------------------- ELF DLL loader ------------------- */
1695
1696 #define NMATCH 5
1697 regmatch_t match[NMATCH];
1698 const char *errmsg;
1699 FILE* fp;
1700 size_t match_length;
1701 #define MAXLINE 1000
1702 char line[MAXLINE];
1703 int result;
1704
1705 initLinker();
1706
1707 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1708 errmsg = internal_dlopen(dll_name);
1709
1710 if (errmsg == NULL) {
1711 return NULL;
1712 }
1713
1714 // GHC Trac ticket #2615
1715 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1716 // contain linker scripts rather than ELF-format object code. This
1717 // code handles the situation by recognizing the real object code
1718 // file name given in the linker script.
1719 //
1720 // If an "invalid ELF header" error occurs, it is assumed that the
1721 // .so file contains a linker script instead of ELF object code.
1722 // In this case, the code looks for the GROUP ( ... ) linker
1723 // directive. If one is found, the first file name inside the
1724 // parentheses is treated as the name of a dynamic library and the
1725 // code attempts to dlopen that file. If this is also unsuccessful,
1726 // an error message is returned.
1727
1728 // see if the error message is due to an invalid ELF header
1729 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1730 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1731 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1732 if (result == 0) {
1733 // success -- try to read the named file as a linker script
1734 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1735 MAXLINE-1);
1736 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1737 line[match_length] = '\0'; // make sure string is null-terminated
1738 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1739 if ((fp = fopen(line, "r")) == NULL) {
1740 return errmsg; // return original error if open fails
1741 }
1742 // try to find a GROUP or INPUT ( ... ) command
1743 while (fgets(line, MAXLINE, fp) != NULL) {
1744 IF_DEBUG(linker, debugBelch("input line = %s", line));
1745 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1746 // success -- try to dlopen the first named file
1747 IF_DEBUG(linker, debugBelch("match%s\n",""));
1748 line[match[2].rm_eo] = '\0';
1749 errmsg = internal_dlopen(line+match[2].rm_so);
1750 break;
1751 }
1752 // if control reaches here, no GROUP or INPUT ( ... ) directive
1753 // was found and the original error message is returned to the
1754 // caller
1755 }
1756 fclose(fp);
1757 }
1758 return errmsg;
1759
1760 # elif defined(OBJFORMAT_PEi386)
1761 /* ------------------- Win32 DLL loader ------------------- */
1762
1763 pathchar* buf;
1764 OpenedDLL* o_dll;
1765 HINSTANCE instance;
1766
1767 initLinker();
1768
1769 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1770
1771 /* See if we've already got it, and ignore if so. */
1772 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1773 if (0 == pathcmp(o_dll->name, dll_name))
1774 return NULL;
1775 }
1776
1777 /* The file name has no suffix (yet) so that we can try
1778 both foo.dll and foo.drv
1779
1780 The documentation for LoadLibrary says:
1781 If no file name extension is specified in the lpFileName
1782 parameter, the default library extension .dll is
1783 appended. However, the file name string can include a trailing
1784 point character (.) to indicate that the module name has no
1785 extension. */
1786
1787 buf = stgMallocBytes((pathlen(dll_name) + 10) * sizeof(wchar_t), "addDLL");
1788 swprintf(buf, L"%s.DLL", dll_name);
1789 instance = LoadLibraryW(buf);
1790 if (instance == NULL) {
1791 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1792 // KAA: allow loading of drivers (like winspool.drv)
1793 swprintf(buf, L"%s.DRV", dll_name);
1794 instance = LoadLibraryW(buf);
1795 if (instance == NULL) {
1796 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1797 // #1883: allow loading of unix-style libfoo.dll DLLs
1798 swprintf(buf, L"lib%s.DLL", dll_name);
1799 instance = LoadLibraryW(buf);
1800 if (instance == NULL) {
1801 goto error;
1802 }
1803 }
1804 }
1805 stgFree(buf);
1806
1807 /* Add this DLL to the list of DLLs in which to search for symbols. */
1808 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1809 o_dll->name = pathdup(dll_name);
1810 o_dll->instance = instance;
1811 o_dll->next = opened_dlls;
1812 opened_dlls = o_dll;
1813
1814 return NULL;
1815
1816 error:
1817 stgFree(buf);
1818 sysErrorBelch("%" PATH_FMT, dll_name);
1819
1820 /* LoadLibrary failed; return a ptr to the error msg. */
1821 return "addDLL: could not load DLL";
1822
1823 # else
1824 barf("addDLL: not implemented on this platform");
1825 # endif
1826 }
1827
1828 /* -----------------------------------------------------------------------------
1829 * insert a stable symbol in the hash table
1830 */
1831
1832 void
1833 insertStableSymbol(pathchar* obj_name, char* key, StgPtr p)
1834 {
1835 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1836 }
1837
1838
1839 /* -----------------------------------------------------------------------------
1840 * insert a symbol in the hash table
1841 */
1842 void
1843 insertSymbol(pathchar* obj_name, char* key, void* data)
1844 {
1845 ghciInsertStrHashTable(obj_name, symhash, key, data);
1846 }
1847
1848 /* -----------------------------------------------------------------------------
1849 * lookup a symbol in the hash table
1850 */
1851 void *
1852 lookupSymbol( char *lbl )
1853 {
1854 void *val;
1855 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s\n", lbl));
1856 initLinker() ;
1857 ASSERT(symhash != NULL);
1858 val = lookupStrHashTable(symhash, lbl);
1859
1860 if (val == NULL) {
1861 IF_DEBUG(linker, debugBelch("lookupSymbol: symbol not found\n"));
1862 # if defined(OBJFORMAT_ELF)
1863 return internal_dlsym(dl_prog_handle, lbl);
1864 # elif defined(OBJFORMAT_MACHO)
1865 # if HAVE_DLFCN_H
1866 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1867 interface.
1868
1869 HACK: On OS X, all symbols are prefixed with an underscore.
1870 However, dlsym wants us to omit the leading underscore from the
1871 symbol name -- the dlsym routine puts it back on before searching
1872 for the symbol. For now, we simply strip it off here (and ONLY
1873 here).
1874 */
1875 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s with dlsym\n", lbl));
1876 ASSERT(lbl[0] == '_');
1877 return internal_dlsym(dl_prog_handle, lbl + 1);
1878 # else
1879 if (NSIsSymbolNameDefined(lbl)) {
1880 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1881 return NSAddressOfSymbol(symbol);
1882 } else {
1883 return NULL;
1884 }
1885 # endif /* HAVE_DLFCN_H */
1886 # elif defined(OBJFORMAT_PEi386)
1887 void* sym;
1888
1889 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1890 if (sym != NULL) { return sym; };
1891
1892 // Also try looking up the symbol without the @N suffix. Some
1893 // DLLs have the suffixes on their symbols, some don't.
1894 zapTrailingAtSign ( (unsigned char*)lbl );
1895 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1896 if (sym != NULL) { return sym; };
1897 return NULL;
1898
1899 # else
1900 ASSERT(2+2 == 5);
1901 return NULL;
1902 # endif
1903 } else {
1904 IF_DEBUG(linker, debugBelch("lookupSymbol: value of %s is %p\n", lbl, val));
1905 return val;
1906 }
1907 }
1908
1909 /* -----------------------------------------------------------------------------
1910 * Debugging aid: look in GHCi's object symbol tables for symbols
1911 * within DELTA bytes of the specified address, and show their names.
1912 */
1913 #ifdef DEBUG
1914 void ghci_enquire ( char* addr );
1915
1916 void ghci_enquire ( char* addr )
1917 {
1918 int i;
1919 char* sym;
1920 char* a;
1921 const int DELTA = 64;
1922 ObjectCode* oc;
1923
1924 initLinker();
1925
1926 for (oc = objects; oc; oc = oc->next) {
1927 for (i = 0; i < oc->n_symbols; i++) {
1928 sym = oc->symbols[i];
1929 if (sym == NULL) continue;
1930 a = NULL;
1931 if (a == NULL) {
1932 a = lookupStrHashTable(symhash, sym);
1933 }
1934 if (a == NULL) {
1935 // debugBelch("ghci_enquire: can't find %s\n", sym);
1936 }
1937 else if (addr-DELTA <= a && a <= addr+DELTA) {
1938 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1939 }
1940 }
1941 }
1942 }
1943 #endif
1944
1945 #ifdef USE_MMAP
1946 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1947
1948 static void *
1949 mmapForLinker (size_t bytes, nat flags, int fd)
1950 {
1951 void *map_addr = NULL;
1952 void *result;
1953 int pagesize, size;
1954 static nat fixed = 0;
1955
1956 IF_DEBUG(linker, debugBelch("mmapForLinker: start\n"));
1957 pagesize = getpagesize();
1958 size = ROUND_UP(bytes, pagesize);
1959
1960 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1961 mmap_again:
1962
1963 if (mmap_32bit_base != 0) {
1964 map_addr = mmap_32bit_base;
1965 }
1966 #endif
1967
1968 IF_DEBUG(linker, debugBelch("mmapForLinker: \tprotection %#0x\n", PROT_EXEC | PROT_READ | PROT_WRITE));
1969 IF_DEBUG(linker, debugBelch("mmapForLinker: \tflags %#0x\n", MAP_PRIVATE | TRY_MAP_32BIT | fixed | flags));
1970 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1971 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1972
1973 if (result == MAP_FAILED) {
1974 sysErrorBelch("mmap %" FMT_Word " bytes at %p",(W_)size,map_addr);
1975 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1976 stg_exit(EXIT_FAILURE);
1977 }
1978
1979 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1980 if (mmap_32bit_base != 0) {
1981 if (result == map_addr) {
1982 mmap_32bit_base = (StgWord8*)map_addr + size;
1983 } else {
1984 if ((W_)result > 0x80000000) {
1985 // oops, we were given memory over 2Gb
1986 #if defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS)
1987 // Some platforms require MAP_FIXED. This is normally
1988 // a bad idea, because MAP_FIXED will overwrite
1989 // existing mappings.
1990 munmap(result,size);
1991 fixed = MAP_FIXED;
1992 goto mmap_again;
1993 #else
1994 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);
1995 #endif
1996 } else {
1997 // hmm, we were given memory somewhere else, but it's
1998 // still under 2Gb so we can use it. Next time, ask
1999 // for memory right after the place we just got some
2000 mmap_32bit_base = (StgWord8*)result + size;
2001 }
2002 }
2003 } else {
2004 if ((W_)result > 0x80000000) {
2005 // oops, we were given memory over 2Gb
2006 // ... try allocating memory somewhere else?;
2007 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
2008 munmap(result, size);
2009
2010 // Set a base address and try again... (guess: 1Gb)
2011 mmap_32bit_base = (void*)0x40000000;
2012 goto mmap_again;
2013 }
2014 }
2015 #endif
2016
2017 IF_DEBUG(linker, debugBelch("mmapForLinker: mapped %" FMT_Word " bytes starting at %p\n", (W_)size, result));
2018 IF_DEBUG(linker, debugBelch("mmapForLinker: done\n"));
2019 return result;
2020 }
2021 #endif // USE_MMAP
2022
2023 static ObjectCode*
2024 mkOc( pathchar *path, char *image, int imageSize,
2025 char *archiveMemberName
2026 #ifndef USE_MMAP
2027 #ifdef darwin_HOST_OS
2028 , int misalignment
2029 #endif
2030 #endif
2031 ) {
2032 ObjectCode* oc;
2033
2034 IF_DEBUG(linker, debugBelch("mkOc: start\n"));
2035 oc = stgMallocBytes(sizeof(ObjectCode), "loadArchive(oc)");
2036
2037 # if defined(OBJFORMAT_ELF)
2038 oc->formatName = "ELF";
2039 # elif defined(OBJFORMAT_PEi386)
2040 oc->formatName = "PEi386";
2041 # elif defined(OBJFORMAT_MACHO)
2042 oc->formatName = "Mach-O";
2043 # else
2044 stgFree(oc);
2045 barf("loadObj: not implemented on this platform");
2046 # endif
2047
2048 oc->image = image;
2049 oc->fileName = pathdup(path);
2050
2051 if (archiveMemberName) {
2052 oc->archiveMemberName = stgMallocBytes( strlen(archiveMemberName)+1, "loadObj" );
2053 strcpy(oc->archiveMemberName, archiveMemberName);
2054 }
2055 else {
2056 oc->archiveMemberName = NULL;
2057 }
2058
2059 oc->fileSize = imageSize;
2060 oc->symbols = NULL;
2061 oc->sections = NULL;
2062 oc->proddables = NULL;
2063
2064 #ifndef USE_MMAP
2065 #ifdef darwin_HOST_OS
2066 oc->misalignment = misalignment;
2067 #endif
2068 #endif
2069
2070 /* chain it onto the list of objects */
2071 oc->next = objects;
2072 objects = oc;
2073
2074 IF_DEBUG(linker, debugBelch("mkOc: done\n"));
2075 return oc;
2076 }
2077
2078 HsInt
2079 loadArchive( pathchar *path )
2080 {
2081 ObjectCode* oc;
2082 char *image;
2083 int memberSize;
2084 FILE *f;
2085 int n;
2086 size_t thisFileNameSize;
2087 char *fileName;
2088 size_t fileNameSize;
2089 int isObject, isGnuIndex;
2090 char tmp[20];
2091 char *gnuFileIndex;
2092 int gnuFileIndexSize;
2093 #if defined(darwin_HOST_OS)
2094 int i;
2095 uint32_t nfat_arch, nfat_offset, cputype, cpusubtype;
2096 #if defined(i386_HOST_ARCH)
2097 const uint32_t mycputype = CPU_TYPE_X86;
2098 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_ALL;
2099 #elif defined(x86_64_HOST_ARCH)
2100 const uint32_t mycputype = CPU_TYPE_X86_64;
2101 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_64_ALL;
2102 #elif defined(powerpc_HOST_ARCH)
2103 const uint32_t mycputype = CPU_TYPE_POWERPC;
2104 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
2105 #elif defined(powerpc64_HOST_ARCH)
2106 const uint32_t mycputype = CPU_TYPE_POWERPC64;
2107 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
2108 #else
2109 #error Unknown Darwin architecture
2110 #endif
2111 #if !defined(USE_MMAP)
2112 int misalignment;
2113 #endif
2114 #endif
2115
2116 IF_DEBUG(linker, debugBelch("loadArchive: start\n"));
2117 IF_DEBUG(linker, debugBelch("loadArchive: Loading archive `%" PATH_FMT" '\n", path));
2118
2119 if (dynamicByDefault) {
2120 barf("loadArchive called, but using dynlibs by default (%s)", path);
2121 }
2122
2123 gnuFileIndex = NULL;
2124 gnuFileIndexSize = 0;
2125
2126 fileNameSize = 32;
2127 fileName = stgMallocBytes(fileNameSize, "loadArchive(fileName)");
2128
2129 f = pathopen(path, WSTR("rb"));
2130 if (!f)
2131 barf("loadObj: can't read `%s'", path);
2132
2133 /* Check if this is an archive by looking for the magic "!<arch>\n"
2134 * string. Usually, if this fails, we barf and quit. On Darwin however,
2135 * we may have a fat archive, which contains archives for more than
2136 * one architecture. Fat archives start with the magic number 0xcafebabe,
2137 * always stored big endian. If we find a fat_header, we scan through
2138 * the fat_arch structs, searching through for one for our host
2139 * architecture. If a matching struct is found, we read the offset
2140 * of our archive data (nfat_offset) and seek forward nfat_offset bytes
2141 * from the start of the file.
2142 *
2143 * A subtlety is that all of the members of the fat_header and fat_arch
2144 * structs are stored big endian, so we need to call byte order
2145 * conversion functions.
2146 *
2147 * If we find the appropriate architecture in a fat archive, we gobble
2148 * its magic "!<arch>\n" string and continue processing just as if
2149 * we had a single architecture archive.
2150 */
2151
2152 n = fread ( tmp, 1, 8, f );
2153 if (n != 8)
2154 barf("loadArchive: Failed reading header from `%s'", path);
2155 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
2156
2157 #if defined(darwin_HOST_OS)
2158 /* Not a standard archive, look for a fat archive magic number: */
2159 if (ntohl(*(uint32_t *)tmp) == FAT_MAGIC) {
2160 nfat_arch = ntohl(*(uint32_t *)(tmp + 4));
2161 IF_DEBUG(linker, debugBelch("loadArchive: found a fat archive containing %d architectures\n", nfat_arch));
2162 nfat_offset = 0;
2163
2164 for (i = 0; i < (int)nfat_arch; i++) {
2165 /* search for the right arch */
2166 n = fread( tmp, 1, 20, f );
2167 if (n != 8)
2168 barf("loadArchive: Failed reading arch from `%s'", path);
2169 cputype = ntohl(*(uint32_t *)tmp);
2170 cpusubtype = ntohl(*(uint32_t *)(tmp + 4));
2171
2172 if (cputype == mycputype && cpusubtype == mycpusubtype) {
2173 IF_DEBUG(linker, debugBelch("loadArchive: found my archive in a fat archive\n"));
2174 nfat_offset = ntohl(*(uint32_t *)(tmp + 8));
2175 break;
2176 }
2177 }
2178
2179 if (nfat_offset == 0) {
2180 barf ("loadArchive: searched %d architectures, but no host arch found", (int)nfat_arch);
2181 }
2182 else {
2183 n = fseek( f, nfat_offset, SEEK_SET );
2184 if (n != 0)
2185 barf("loadArchive: Failed to seek to arch in `%s'", path);
2186 n = fread ( tmp, 1, 8, f );
2187 if (n != 8)
2188 barf("loadArchive: Failed reading header from `%s'", path);
2189 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
2190 barf("loadArchive: couldn't find archive in `%s' at offset %d", path, nfat_offset);
2191 }
2192 }
2193 }
2194 else {
2195 barf("loadArchive: Neither an archive, nor a fat archive: `%s'", path);
2196 }
2197
2198 #else
2199 barf("loadArchive: Not an archive: `%s'", path);
2200 #endif
2201 }
2202
2203 IF_DEBUG(linker, debugBelch("loadArchive: loading archive contents\n"));
2204
2205 while(1) {
2206 n = fread ( fileName, 1, 16, f );
2207 if (n != 16) {
2208 if (feof(f)) {
2209 IF_DEBUG(linker, debugBelch("loadArchive: EOF while reading from '%" PATH_FMT "'\n", path));
2210 break;
2211 }
2212 else {
2213 barf("loadArchive: Failed reading file name from `%s'", path);
2214 }
2215 }
2216
2217 #if defined(darwin_HOST_OS)
2218 if (strncmp(fileName, "!<arch>\n", 8) == 0) {
2219 IF_DEBUG(linker, debugBelch("loadArchive: found the start of another archive, breaking\n"));
2220 break;
2221 }
2222 #endif
2223
2224 n = fread ( tmp, 1, 12, f );
2225 if (n != 12)
2226 barf("loadArchive: Failed reading mod time from `%s'", path);
2227 n = fread ( tmp, 1, 6, f );
2228 if (n != 6)
2229 barf("loadArchive: Failed reading owner from `%s'", path);
2230 n = fread ( tmp, 1, 6, f );
2231 if (n != 6)
2232 barf("loadArchive: Failed reading group from `%s'", path);
2233 n = fread ( tmp, 1, 8, f );
2234 if (n != 8)
2235 barf("loadArchive: Failed reading mode from `%s'", path);
2236 n = fread ( tmp, 1, 10, f );
2237 if (n != 10)
2238 barf("loadArchive: Failed reading size from `%s'", path);
2239 tmp[10] = '\0';
2240 for (n = 0; isdigit(tmp[n]); n++);
2241 tmp[n] = '\0';
2242 memberSize = atoi(tmp);
2243
2244 IF_DEBUG(linker, debugBelch("loadArchive: size of this archive member is %d\n", memberSize));
2245 n = fread ( tmp, 1, 2, f );
2246 if (n != 2)
2247 barf("loadArchive: Failed reading magic from `%s'", path);
2248 if (strncmp(tmp, "\x60\x0A", 2) != 0)
2249 barf("loadArchive: Failed reading magic from `%s' at %ld. Got %c%c",
2250 path, ftell(f), tmp[0], tmp[1]);
2251
2252 isGnuIndex = 0;
2253 /* Check for BSD-variant large filenames */
2254 if (0 == strncmp(fileName, "#1/", 3)) {
2255 fileName[16] = '\0';
2256 if (isdigit(fileName[3])) {
2257 for (n = 4; isdigit(fileName[n]); n++);
2258 fileName[n] = '\0';
2259 thisFileNameSize = atoi(fileName + 3);
2260 memberSize -= thisFileNameSize;
2261 if (thisFileNameSize >= fileNameSize) {
2262 /* Double it to avoid potentially continually
2263 increasing it by 1 */
2264 fileNameSize = thisFileNameSize * 2;
2265 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
2266 }
2267 n = fread ( fileName, 1, thisFileNameSize, f );
2268 if (n != (int)thisFileNameSize) {
2269 barf("loadArchive: Failed reading filename from `%s'",
2270 path);
2271 }
2272 fileName[thisFileNameSize] = 0;
2273
2274 /* On OS X at least, thisFileNameSize is the size of the
2275 fileName field, not the length of the fileName
2276 itself. */
2277 thisFileNameSize = strlen(fileName);
2278 }
2279 else {
2280 barf("loadArchive: BSD-variant filename size not found while reading filename from `%s'", path);
2281 }
2282 }
2283 /* Check for GNU file index file */
2284 else if (0 == strncmp(fileName, "//", 2)) {
2285 fileName[0] = '\0';
2286 thisFileNameSize = 0;
2287 isGnuIndex = 1;
2288 }
2289 /* Check for a file in the GNU file index */
2290 else if (fileName[0] == '/') {
2291 if (isdigit(fileName[1])) {
2292 int i;
2293
2294 for (n = 2; isdigit(fileName[n]); n++);
2295 fileName[n] = '\0';
2296 n = atoi(fileName + 1);
2297
2298 if (gnuFileIndex == NULL) {
2299 barf("loadArchive: GNU-variant filename without an index while reading from `%s'", path);
2300 }
2301 if (n < 0 || n > gnuFileIndexSize) {
2302 barf("loadArchive: GNU-variant filename offset %d out of range [0..%d] while reading filename from `%s'", n, gnuFileIndexSize, path);
2303 }
2304 if (n != 0 && gnuFileIndex[n - 1] != '\n') {
2305 barf("loadArchive: GNU-variant filename offset %d invalid (range [0..%d]) while reading filename from `%s'", n, gnuFileIndexSize, path);
2306 }
2307 for (i = n; gnuFileIndex[i] != '/'; i++);
2308 thisFileNameSize = i - n;
2309 if (thisFileNameSize >= fileNameSize) {
2310 /* Double it to avoid potentially continually
2311 increasing it by 1 */
2312 fileNameSize = thisFileNameSize * 2;
2313 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
2314 }
2315 memcpy(fileName, gnuFileIndex + n, thisFileNameSize);
2316 fileName[thisFileNameSize] = '\0';
2317 }
2318 else if (fileName[1] == ' ') {
2319 fileName[0] = '\0';
2320 thisFileNameSize = 0;
2321 }
2322 else {
2323 barf("loadArchive: GNU-variant filename offset not found while reading filename from `%s'", path);
2324 }
2325 }
2326 /* Finally, the case where the filename field actually contains
2327 the filename */
2328 else {
2329 /* GNU ar terminates filenames with a '/', this allowing
2330 spaces in filenames. So first look to see if there is a
2331 terminating '/'. */
2332 for (thisFileNameSize = 0;
2333 thisFileNameSize < 16;
2334 thisFileNameSize++) {
2335 if (fileName[thisFileNameSize] == '/') {
2336 fileName[thisFileNameSize] = '\0';
2337 break;
2338 }
2339 }
2340 /* If we didn't find a '/', then a space teminates the
2341 filename. Note that if we don't find one, then
2342 thisFileNameSize ends up as 16, and we already have the
2343 '\0' at the end. */
2344 if (thisFileNameSize == 16) {
2345 for (thisFileNameSize = 0;
2346 thisFileNameSize < 16;
2347 thisFileNameSize++) {
2348 if (fileName[thisFileNameSize] == ' ') {
2349 fileName[thisFileNameSize] = '\0';
2350 break;
2351 }
2352 }
2353 }
2354 }
2355
2356 IF_DEBUG(linker,
2357 debugBelch("loadArchive: Found member file `%s'\n", fileName));
2358
2359 isObject = thisFileNameSize >= 2
2360 && fileName[thisFileNameSize - 2] == '.'
2361 && fileName[thisFileNameSize - 1] == 'o';
2362
2363 IF_DEBUG(linker, debugBelch("loadArchive: \tthisFileNameSize = %d\n", (int)thisFileNameSize));
2364 IF_DEBUG(linker, debugBelch("loadArchive: \tisObject = %d\n", isObject));
2365
2366 if (isObject) {
2367 char *archiveMemberName;
2368
2369 IF_DEBUG(linker, debugBelch("loadArchive: Member is an object file...loading...\n"));
2370
2371 /* We can't mmap from the archive directly, as object
2372 files need to be 8-byte aligned but files in .ar
2373 archives are 2-byte aligned. When possible we use mmap
2374 to get some anonymous memory, as on 64-bit platforms if
2375 we use malloc then we can be given memory above 2^32.
2376 In the mmap case we're probably wasting lots of space;
2377 we could do better. */
2378 #if defined(USE_MMAP)
2379 image = mmapForLinker(memberSize, MAP_ANONYMOUS, -1);
2380 #elif defined(mingw32_HOST_OS)
2381 // TODO: We would like to use allocateExec here, but allocateExec
2382 // cannot currently allocate blocks large enough.
2383 {
2384 int offset;
2385 #if defined(x86_64_HOST_ARCH)
2386 /* We get back 8-byte aligned memory (is that guaranteed?), but
2387 the offsets to the sections within the file are all 4 mod 8
2388 (is that guaranteed?). We therefore need to offset the image
2389 by 4, so that all the pointers are 8-byte aligned, so that
2390 pointer tagging works. */
2391 offset = 4;
2392 #else
2393 offset = 0;
2394 #endif
2395 image = VirtualAlloc(NULL, memberSize + offset,
2396 MEM_RESERVE | MEM_COMMIT,
2397 PAGE_EXECUTE_READWRITE);
2398 image += offset;
2399 }
2400 #elif defined(darwin_HOST_OS)
2401 /* See loadObj() */
2402 misalignment = machoGetMisalignment(f);
2403 image = stgMallocBytes(memberSize + misalignment, "loadArchive(image)");
2404 image += misalignment;
2405 #else
2406 image = stgMallocBytes(memberSize, "loadArchive(image)");
2407 #endif
2408 n = fread ( image, 1, memberSize, f );
2409 if (n != memberSize) {
2410 barf("loadArchive: error whilst reading `%s'", path);
2411 }
2412
2413 archiveMemberName = stgMallocBytes(pathlen(path) + thisFileNameSize + 3,
2414 "loadArchive(file)");
2415 sprintf(archiveMemberName, "%" PATH_FMT "(%.*s)",
2416 path, (int)thisFileNameSize, fileName);
2417
2418 oc = mkOc(path, image, memberSize, archiveMemberName
2419 #ifndef USE_MMAP
2420 #ifdef darwin_HOST_OS
2421 , misalignment
2422 #endif
2423 #endif
2424 );
2425
2426 stgFree(archiveMemberName);
2427
2428 if (0 == loadOc(oc)) {
2429 stgFree(fileName);
2430 return 0;
2431 }
2432 }
2433 else if (isGnuIndex) {
2434 if (gnuFileIndex != NULL) {
2435 barf("loadArchive: GNU-variant index found, but already have an index, while reading filename from `%s'", path);
2436 }
2437 IF_DEBUG(linker, debugBelch("loadArchive: Found GNU-variant file index\n"));
2438 #ifdef USE_MMAP
2439 gnuFileIndex = mmapForLinker(memberSize + 1, MAP_ANONYMOUS, -1);
2440 #else
2441 gnuFileIndex = stgMallocBytes(memberSize + 1, "loadArchive(image)");
2442 #endif
2443 n = fread ( gnuFileIndex, 1, memberSize, f );
2444 if (n != memberSize) {
2445 barf("loadArchive: error whilst reading `%s'", path);
2446 }
2447 gnuFileIndex[memberSize] = '/';
2448 gnuFileIndexSize = memberSize;
2449 }
2450 else {
2451 IF_DEBUG(linker, debugBelch("loadArchive: '%s' does not appear to be an object file\n", fileName));
2452 n = fseek(f, memberSize, SEEK_CUR);
2453 if (n != 0)
2454 barf("loadArchive: error whilst seeking by %d in `%s'",
2455 memberSize, path);
2456 }
2457
2458 /* .ar files are 2-byte aligned */
2459 if (memberSize % 2) {
2460 IF_DEBUG(linker, debugBelch("loadArchive: trying to read one pad byte\n"));
2461 n = fread ( tmp, 1, 1, f );
2462 if (n != 1) {
2463 if (feof(f)) {
2464 IF_DEBUG(linker, debugBelch("loadArchive: found EOF while reading one pad byte\n"));
2465 break;
2466 }
2467 else {
2468 barf("loadArchive: Failed reading padding from `%s'", path);
2469 }
2470 }
2471 IF_DEBUG(linker, debugBelch("loadArchive: successfully read one pad byte\n"));
2472 }
2473 IF_DEBUG(linker, debugBelch("loadArchive: reached end of archive loading while loop\n"));
2474 }
2475
2476 fclose(f);
2477
2478 stgFree(fileName);
2479 if (gnuFileIndex != NULL) {
2480 #ifdef USE_MMAP
2481 munmap(gnuFileIndex, gnuFileIndexSize + 1);
2482 #else
2483 stgFree(gnuFileIndex);
2484 #endif
2485 }
2486
2487 IF_DEBUG(linker, debugBelch("loadArchive: done\n"));
2488 return 1;
2489 }
2490
2491 /* -----------------------------------------------------------------------------
2492 * Load an obj (populate the global symbol table, but don't resolve yet)
2493 *
2494 * Returns: 1 if ok, 0 on error.
2495 */
2496 HsInt
2497 loadObj( pathchar *path )
2498 {
2499 ObjectCode* oc;
2500 char *image;
2501 int fileSize;
2502 struct_stat st;
2503 int r;
2504 #ifdef USE_MMAP
2505 int fd;
2506 #else
2507 FILE *f;
2508 # if defined(darwin_HOST_OS)
2509 int misalignment;
2510 # endif
2511 #endif
2512 IF_DEBUG(linker, debugBelch("loadObj %" PATH_FMT "\n", path));
2513
2514 if (dynamicByDefault) {
2515 barf("loadObj called, but using dynlibs by default (%s)", path);
2516 }
2517
2518 initLinker();
2519
2520 /* debugBelch("loadObj %s\n", path ); */
2521
2522 /* Check that we haven't already loaded this object.
2523 Ignore requests to load multiple times */
2524 {
2525 ObjectCode *o;
2526 int is_dup = 0;
2527 for (o = objects; o; o = o->next) {
2528 if (0 == pathcmp(o->fileName, path)) {
2529 is_dup = 1;
2530 break; /* don't need to search further */
2531 }
2532 }
2533 if (is_dup) {
2534 IF_DEBUG(linker, debugBelch(
2535 "GHCi runtime linker: warning: looks like you're trying to load the\n"
2536 "same object file twice:\n"
2537 " %" PATH_FMT "\n"
2538 "GHCi will ignore this, but be warned.\n"
2539 , path));
2540 return 1; /* success */
2541 }
2542 }
2543
2544 r = pathstat(path, &st);
2545 if (r == -1) {
2546 IF_DEBUG(linker, debugBelch("File doesn't exist\n"));
2547 return 0;
2548 }
2549
2550 fileSize = st.st_size;
2551
2552 #ifdef USE_MMAP
2553 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
2554
2555 #if defined(openbsd_HOST_OS)
2556 fd = open(path, O_RDONLY, S_IRUSR);
2557 #else
2558 fd = open(path, O_RDONLY);
2559 #endif
2560 if (fd == -1)
2561 barf("loadObj: can't open `%s'", path);
2562
2563 image = mmapForLinker(fileSize, 0, fd);
2564
2565 close(fd);
2566
2567 #else /* !USE_MMAP */
2568 /* load the image into memory */
2569 f = pathopen(path, WSTR("rb"));
2570 if (!f)
2571 barf("loadObj: can't read `%" PATH_FMT "'", path);
2572
2573 # if defined(mingw32_HOST_OS)
2574 // TODO: We would like to use allocateExec here, but allocateExec
2575 // cannot currently allocate blocks large enough.
2576 {
2577 int offset;
2578 #if defined(x86_64_HOST_ARCH)
2579 /* We get back 8-byte aligned memory (is that guaranteed?), but
2580 the offsets to the sections within the file are all 4 mod 8
2581 (is that guaranteed?). We therefore need to offset the image
2582 by 4, so that all the pointers are 8-byte aligned, so that
2583 pointer tagging works. */
2584 offset = 4;
2585 #else
2586 offset = 0;
2587 #endif
2588 image = VirtualAlloc(NULL, fileSize + offset, MEM_RESERVE | MEM_COMMIT,
2589 PAGE_EXECUTE_READWRITE);
2590 image += offset;
2591 }
2592 # elif defined(darwin_HOST_OS)
2593 // In a Mach-O .o file, all sections can and will be misaligned
2594 // if the total size of the headers is not a multiple of the
2595 // desired alignment. This is fine for .o files that only serve
2596 // as input for the static linker, but it's not fine for us,
2597 // as SSE (used by gcc for floating point) and Altivec require
2598 // 16-byte alignment.
2599 // We calculate the correct alignment from the header before
2600 // reading the file, and then we misalign image on purpose so
2601 // that the actual sections end up aligned again.
2602 misalignment = machoGetMisalignment(f);
2603 image = stgMallocBytes(fileSize + misalignment, "loadObj(image)");
2604 image += misalignment;
2605 # else
2606 image = stgMallocBytes(fileSize, "loadObj(image)");
2607 # endif
2608
2609 {
2610 int n;
2611 n = fread ( image, 1, fileSize, f );
2612 if (n != fileSize)
2613 barf("loadObj: error whilst reading `%s'", path);
2614 }
2615 fclose(f);
2616 #endif /* USE_MMAP */
2617
2618 oc = mkOc(path, image, fileSize, NULL
2619 #ifndef USE_MMAP
2620 #ifdef darwin_HOST_OS
2621 , misalignment
2622 #endif
2623 #endif
2624 );
2625
2626 return loadOc(oc);
2627 }
2628
2629 static HsInt
2630 loadOc( ObjectCode* oc ) {
2631 int r;
2632
2633 IF_DEBUG(linker, debugBelch("loadOc: start\n"));
2634
2635 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2636 r = ocAllocateSymbolExtras_MachO ( oc );
2637 if (!r) {
2638 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_MachO failed\n"));
2639 return r;
2640 }
2641 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH))
2642 r = ocAllocateSymbolExtras_ELF ( oc );
2643 if (!r) {
2644 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_ELF failed\n"));
2645 return r;
2646 }
2647 #endif
2648
2649 /* verify the in-memory image */
2650 # if defined(OBJFORMAT_ELF)
2651 r = ocVerifyImage_ELF ( oc );
2652 # elif defined(OBJFORMAT_PEi386)
2653 r = ocVerifyImage_PEi386 ( oc );
2654 # elif defined(OBJFORMAT_MACHO)
2655 r = ocVerifyImage_MachO ( oc );
2656 # else
2657 barf("loadObj: no verify method");
2658 # endif
2659 if (!r) {
2660 IF_DEBUG(linker, debugBelch("loadOc: ocVerifyImage_* failed\n"));
2661 return r;
2662 }
2663
2664 /* build the symbol list for this image */
2665 # if defined(OBJFORMAT_ELF)
2666 r = ocGetNames_ELF ( oc );
2667 # elif defined(OBJFORMAT_PEi386)
2668 r = ocGetNames_PEi386 ( oc );
2669 # elif defined(OBJFORMAT_MACHO)
2670 r = ocGetNames_MachO ( oc );
2671 # else
2672 barf("loadObj: no getNames method");
2673 # endif
2674 if (!r) {
2675 IF_DEBUG(linker, debugBelch("loadOc: ocGetNames_* failed\n"));
2676 return r;
2677 }
2678
2679 /* loaded, but not resolved yet */
2680 oc->status = OBJECT_LOADED;
2681 IF_DEBUG(linker, debugBelch("loadOc: done.\n"));
2682
2683 return 1;
2684 }
2685
2686 /* -----------------------------------------------------------------------------
2687 * resolve all the currently unlinked objects in memory
2688 *
2689 * Returns: 1 if ok, 0 on error.
2690 */
2691 HsInt
2692 resolveObjs( void )
2693 {
2694 ObjectCode *oc;
2695 int r;
2696
2697 IF_DEBUG(linker, debugBelch("resolveObjs: start\n"));
2698 initLinker();
2699
2700 for (oc = objects; oc; oc = oc->next) {
2701 if (oc->status != OBJECT_RESOLVED) {
2702 # if defined(OBJFORMAT_ELF)
2703 r = ocResolve_ELF ( oc );
2704 # elif defined(OBJFORMAT_PEi386)
2705 r = ocResolve_PEi386 ( oc );
2706 # elif defined(OBJFORMAT_MACHO)
2707 r = ocResolve_MachO ( oc );
2708 # else
2709 barf("resolveObjs: not implemented on this platform");
2710 # endif
2711 if (!r) { return r; }
2712 oc->status = OBJECT_RESOLVED;
2713 }
2714 }
2715 IF_DEBUG(linker, debugBelch("resolveObjs: done\n"));
2716 return 1;
2717 }
2718
2719 /* -----------------------------------------------------------------------------
2720 * delete an object from the pool
2721 */
2722 HsInt
2723 unloadObj( pathchar *path )
2724 {
2725 ObjectCode *oc, *prev;
2726 HsBool unloadedAnyObj = HS_BOOL_FALSE;
2727
2728 ASSERT(symhash != NULL);
2729 ASSERT(objects != NULL);
2730
2731 initLinker();
2732
2733 prev = NULL;
2734 for (oc = objects; oc; prev = oc, oc = oc->next) {
2735 if (!pathcmp(oc->fileName,path)) {
2736
2737 /* Remove all the mappings for the symbols within this
2738 * object..
2739 */
2740 {
2741 int i;
2742 for (i = 0; i < oc->n_symbols; i++) {
2743 if (oc->symbols[i] != NULL) {
2744 removeStrHashTable(symhash, oc->symbols[i], NULL);
2745 }
2746 }
2747 }
2748
2749 if (prev == NULL) {
2750 objects = oc->next;
2751 } else {
2752 prev->next = oc->next;
2753 }
2754
2755 // We're going to leave this in place, in case there are
2756 // any pointers from the heap into it:
2757 // #ifdef mingw32_HOST_OS
2758 // If uncommenting, note that currently oc->image is
2759 // not the right address to free on Win64, as we added
2760 // 4 bytes of padding at the start
2761 // VirtualFree(oc->image);
2762 // #else
2763 // stgFree(oc->image);
2764 // #endif
2765 stgFree(oc->fileName);
2766 stgFree(oc->archiveMemberName);
2767 stgFree(oc->symbols);
2768 stgFree(oc->sections);
2769 stgFree(oc);
2770
2771 /* This could be a member of an archive so continue
2772 * unloading other members. */
2773 unloadedAnyObj = HS_BOOL_TRUE;
2774 }
2775 }
2776
2777 if (unloadedAnyObj) {
2778 return 1;
2779 }
2780 else {
2781 errorBelch("unloadObj: can't find `%" PATH_FMT "' to unload", path);
2782 return 0;
2783 }
2784 }
2785
2786 /* -----------------------------------------------------------------------------
2787 * Sanity checking. For each ObjectCode, maintain a list of address ranges
2788 * which may be prodded during relocation, and abort if we try and write
2789 * outside any of these.
2790 */
2791 static void
2792 addProddableBlock ( ObjectCode* oc, void* start, int size )
2793 {
2794 ProddableBlock* pb
2795 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
2796
2797 IF_DEBUG(linker, debugBelch("addProddableBlock: %p %p %d\n", oc, start, size));
2798 ASSERT(size > 0);
2799 pb->start = start;
2800 pb->size = size;
2801 pb->next = oc->proddables;
2802 oc->proddables = pb;
2803 }
2804
2805 static void
2806 checkProddableBlock (ObjectCode *oc, void *addr, size_t size )
2807 {
2808 ProddableBlock* pb;
2809
2810 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
2811 char* s = (char*)(pb->start);
2812 char* e = s + pb->size;
2813 char* a = (char*)addr;
2814 if (a >= s && (a+size) <= e) return;
2815 }
2816 barf("checkProddableBlock: invalid fixup in runtime linker: %p", addr);
2817 }
2818
2819 /* -----------------------------------------------------------------------------
2820 * Section management.
2821 */
2822 static void
2823 addSection ( ObjectCode* oc, SectionKind kind,
2824 void* start, void* end )
2825 {
2826 Section* s = stgMallocBytes(sizeof(Section), "addSection");
2827 s->start = start;
2828 s->end = end;
2829 s->kind = kind;
2830 s->next = oc->sections;
2831 oc->sections = s;
2832
2833 IF_DEBUG(linker, debugBelch("addSection: %p-%p (size %lld), kind %d\n",
2834 start, ((char*)end)-1, ((long long)(size_t)end) - ((long long)(size_t)start) + 1, kind ));
2835 }
2836
2837
2838 /* --------------------------------------------------------------------------
2839 * Symbol Extras.
2840 * This is about allocating a small chunk of memory for every symbol in the
2841 * object file. We make sure that the SymboLExtras are always "in range" of
2842 * limited-range PC-relative instructions on various platforms by allocating
2843 * them right next to the object code itself.
2844 */
2845
2846 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH)
2847 #if !defined(x86_64_HOST_ARCH) || !defined(mingw32_HOST_OS)
2848
2849 /*
2850 ocAllocateSymbolExtras
2851
2852 Allocate additional space at the end of the object file image to make room
2853 for jump islands (powerpc, x86_64, arm) and GOT entries (x86_64).
2854
2855 PowerPC relative branch instructions have a 24 bit displacement field.
2856 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
2857 If a particular imported symbol is outside this range, we have to redirect
2858 the jump to a short piece of new code that just loads the 32bit absolute
2859 address and jumps there.
2860 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
2861 to 32 bits (+-2GB).
2862
2863 This function just allocates space for one SymbolExtra for every
2864 undefined symbol in the object file. The code for the jump islands is
2865 filled in by makeSymbolExtra below.
2866 */
2867
2868 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
2869 {
2870 #ifdef USE_MMAP
2871 int pagesize, n, m;
2872 #endif
2873 int aligned;
2874 #ifndef USE_MMAP
2875 int misalignment = 0;
2876 #ifdef darwin_HOST_OS
2877 misalignment = oc->misalignment;
2878 #endif
2879 #endif
2880
2881 if( count > 0 )
2882 {
2883 // round up to the nearest 4
2884 aligned = (oc->fileSize + 3) & ~3;
2885
2886 #ifdef USE_MMAP
2887 pagesize = getpagesize();
2888 n = ROUND_UP( oc->fileSize, pagesize );
2889 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
2890
2891 /* we try to use spare space at the end of the last page of the
2892 * image for the jump islands, but if there isn't enough space
2893 * then we have to map some (anonymously, remembering MAP_32BIT).
2894 */
2895 if( m > n ) // we need to allocate more pages
2896 {
2897 if (USE_CONTIGUOUS_MMAP)
2898 {
2899 /* Keep image and symbol_extras contiguous */
2900 void *new = mmapForLinker(n + (sizeof(SymbolExtra) * count),
2901 MAP_ANONYMOUS, -1);
2902 if (new)
2903 {
2904 memcpy(new, oc->image, oc->fileSize);
2905 munmap(oc->image, n);
2906 oc->image = new;
2907 oc->symbol_extras = (SymbolExtra *) (oc->image + n);
2908 }
2909 else
2910 oc->symbol_extras = NULL;
2911 }
2912 else
2913 {
2914 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
2915 MAP_ANONYMOUS, -1);
2916 }
2917 }
2918 else
2919 {
2920 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2921 }
2922 #else
2923 oc->image -= misalignment;
2924 oc->image = stgReallocBytes( oc->image,
2925 misalignment +
2926 aligned + sizeof (SymbolExtra) * count,
2927 "ocAllocateSymbolExtras" );
2928 oc->image += misalignment;
2929
2930 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2931 #endif /* USE_MMAP */
2932
2933 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
2934 }
2935 else
2936 oc->symbol_extras = NULL;
2937
2938 oc->first_symbol_extra = first;
2939 oc->n_symbol_extras = count;
2940
2941 return 1;
2942 }
2943
2944 #endif
2945 #endif // defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH)
2946
2947 #if defined(arm_HOST_ARCH)
2948
2949 static void
2950 ocFlushInstructionCache( ObjectCode *oc )
2951 {
2952 // Object code
2953 __clear_cache(oc->image, oc->image + oc->fileSize);
2954 // Jump islands
2955 __clear_cache(oc->symbol_extras, &oc->symbol_extras[oc->n_symbol_extras]);
2956 }
2957
2958 #endif
2959
2960 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2961 #if !defined(x86_64_HOST_ARCH) || !defined(mingw32_HOST_OS)
2962
2963 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
2964 unsigned long symbolNumber,
2965 unsigned long target )
2966 {
2967 SymbolExtra *extra;
2968
2969 ASSERT( symbolNumber >= oc->first_symbol_extra
2970 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
2971
2972 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
2973
2974 #ifdef powerpc_HOST_ARCH
2975 // lis r12, hi16(target)
2976 extra->jumpIsland.lis_r12 = 0x3d80;
2977 extra->jumpIsland.hi_addr = target >> 16;
2978
2979 // ori r12, r12, lo16(target)
2980 extra->jumpIsland.ori_r12_r12 = 0x618c;
2981 extra->jumpIsland.lo_addr = target & 0xffff;
2982
2983 // mtctr r12
2984 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2985
2986 // bctr
2987 extra->jumpIsland.bctr = 0x4e800420;
2988 #endif
2989 #ifdef x86_64_HOST_ARCH
2990 // jmp *-14(%rip)
2991 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2992 extra->addr = target;
2993 memcpy(extra->jumpIsland, jmp, 6);
2994 #endif
2995
2996 return extra;
2997 }
2998
2999 #endif
3000 #endif // defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
3001
3002 #ifdef arm_HOST_ARCH
3003 static SymbolExtra* makeArmSymbolExtra( ObjectCode* oc,
3004 unsigned long symbolNumber,
3005 unsigned long target,
3006 int fromThumb,
3007 int toThumb )
3008 {
3009 SymbolExtra *extra;
3010
3011 ASSERT( symbolNumber >= oc->first_symbol_extra
3012 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
3013
3014 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
3015
3016 // Make sure instruction mode bit is set properly
3017 if (toThumb)
3018 target |= 1;
3019 else
3020 target &= ~1;
3021
3022 if (!fromThumb) {
3023 // In ARM encoding:
3024 // movw r12, #0
3025 // movt r12, #0
3026 // bx r12
3027 uint32_t code[] = { 0xe300c000, 0xe340c000, 0xe12fff1c };
3028
3029 // Patch lower half-word into movw
3030 code[0] |= ((target>>12) & 0xf) << 16;
3031 code[0] |= target & 0xfff;
3032 // Patch upper half-word into movt
3033 target >>= 16;
3034 code[1] |= ((target>>12) & 0xf) << 16;
3035 code[1] |= target & 0xfff;
3036
3037 memcpy(extra->jumpIsland, code, 12);
3038
3039 } else {
3040 // In Thumb encoding:
3041 // movw r12, #0
3042 // movt r12, #0
3043 // bx r12
3044 uint16_t code[] = { 0xf240, 0x0c00,
3045 0xf2c0, 0x0c00,
3046 0x4760 };
3047
3048 // Patch lower half-word into movw
3049 code[0] |= (target>>12) & 0xf;
3050 code[0] |= ((target>>11) & 0x1) << 10;
3051 code[1] |= ((target>>8) & 0x7) << 12;
3052 code[1] |= target & 0xff;
3053 // Patch upper half-word into movt
3054 target >>= 16;
3055 code[2] |= (target>>12) & 0xf;
3056 code[2] |= ((target>>11) & 0x1) << 10;
3057 code[3] |= ((target>>8) & 0x7) << 12;
3058 code[3] |= target & 0xff;
3059
3060 memcpy(extra->jumpIsland, code, 10);
3061 }
3062
3063 return extra;
3064 }
3065 #endif // arm_HOST_ARCH
3066
3067 /* --------------------------------------------------------------------------
3068 * PowerPC specifics (instruction cache flushing)
3069 * ------------------------------------------------------------------------*/
3070
3071 #ifdef powerpc_HOST_ARCH
3072 /*
3073 ocFlushInstructionCache
3074
3075 Flush the data & instruction caches.
3076 Because the PPC has split data/instruction caches, we have to
3077 do that whenever we modify code at runtime.
3078 */
3079
3080 static void
3081 ocFlushInstructionCacheFrom(void* begin, size_t length)
3082 {
3083 size_t n = (length + 3) / 4;
3084 unsigned long* p = begin;
3085
3086 while (n--)
3087 {
3088 __asm__ volatile ( "dcbf 0,%0\n\t"
3089 "sync\n\t"
3090 "icbi 0,%0"
3091 :
3092 : "r" (p)
3093 );
3094 p++;
3095 }
3096 __asm__ volatile ( "sync\n\t"
3097 "isync"
3098 );
3099 }
3100
3101 static void
3102 ocFlushInstructionCache( ObjectCode *oc )
3103 {
3104 /* The main object code */
3105 ocFlushInstructionCacheFrom(oc->image
3106 #ifdef darwin_HOST_OS
3107 + oc->misalignment
3108 #endif
3109 , oc->fileSize);
3110
3111 /* Jump Islands */
3112 ocFlushInstructionCacheFrom(oc->symbol_extras, sizeof(SymbolExtra) * oc->n_symbol_extras);
3113 }
3114 #endif /* powerpc_HOST_ARCH */
3115
3116
3117 /* --------------------------------------------------------------------------
3118 * PEi386 specifics (Win32 targets)
3119 * ------------------------------------------------------------------------*/
3120
3121 /* The information for this linker comes from
3122 Microsoft Portable Executable
3123 and Common Object File Format Specification
3124 revision 5.1 January 1998
3125 which SimonM says comes from the MS Developer Network CDs.
3126
3127 It can be found there (on older CDs), but can also be found
3128 online at:
3129
3130 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
3131
3132 (this is Rev 6.0 from February 1999).
3133
3134 Things move, so if that fails, try searching for it via
3135
3136 http://www.google.com/search?q=PE+COFF+specification
3137
3138 The ultimate reference for the PE format is the Winnt.h
3139 header file that comes with the Platform SDKs; as always,
3140 implementations will drift wrt their documentation.
3141
3142 A good background article on the PE format is Matt Pietrek's
3143 March 1994 article in Microsoft System Journal (MSJ)
3144 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
3145 Win32 Portable Executable File Format." The info in there
3146 has recently been updated in a two part article in
3147 MSDN magazine, issues Feb and March 2002,
3148 "Inside Windows: An In-Depth Look into the Win32 Portable
3149 Executable File Format"
3150
3151 John Levine's book "Linkers and Loaders" contains useful
3152 info on PE too.
3153 */
3154
3155
3156 #if defined(OBJFORMAT_PEi386)
3157
3158
3159
3160 typedef unsigned char UChar;
3161 typedef unsigned short UInt16;
3162 typedef unsigned int UInt32;
3163 typedef int Int32;
3164 typedef unsigned long long int UInt64;
3165
3166
3167 typedef
3168 struct {
3169 UInt16 Machine;
3170 UInt16 NumberOfSections;
3171 UInt32 TimeDateStamp;
3172 UInt32 PointerToSymbolTable;
3173 UInt32 NumberOfSymbols;
3174 UInt16 SizeOfOptionalHeader;
3175 UInt16 Characteristics;
3176 }
3177 COFF_header;
3178
3179 #define sizeof_COFF_header 20
3180
3181
3182 typedef
3183 struct {
3184 UChar Name[8];
3185 UInt32 VirtualSize;
3186 UInt32 VirtualAddress;
3187 UInt32 SizeOfRawData;
3188 UInt32 PointerToRawData;
3189 UInt32 PointerToRelocations;
3190 UInt32 PointerToLinenumbers;
3191 UInt16 NumberOfRelocations;
3192 UInt16 NumberOfLineNumbers;
3193 UInt32 Characteristics;
3194 }
3195 COFF_section;
3196
3197 #define sizeof_COFF_section 40
3198
3199
3200 typedef
3201 struct {
3202 UChar Name[8];
3203 UInt32 Value;
3204 UInt16 SectionNumber;
3205 UInt16 Type;
3206 UChar StorageClass;
3207 UChar NumberOfAuxSymbols;
3208 }
3209 COFF_symbol;
3210
3211 #define sizeof_COFF_symbol 18
3212
3213
3214 typedef
3215 struct {
3216 UInt32 VirtualAddress;
3217 UInt32 SymbolTableIndex;
3218 UInt16 Type;
3219 }
3220 COFF_reloc;
3221
3222 #define sizeof_COFF_reloc 10
3223
3224
3225 /* From PE spec doc, section 3.3.2 */
3226 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
3227 windows.h -- for the same purpose, but I want to know what I'm
3228 getting, here. */
3229 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
3230 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
3231 #define MYIMAGE_FILE_DLL 0x2000
3232 #define MYIMAGE_FILE_SYSTEM 0x1000
3233 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
3234 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
3235 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
3236
3237 /* From PE spec doc, section 5.4.2 and 5.4.4 */
3238 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
3239 #define MYIMAGE_SYM_CLASS_STATIC 3
3240 #define MYIMAGE_SYM_UNDEFINED 0
3241
3242 /* From PE spec doc, section 4.1 */
3243 #define MYIMAGE_SCN_CNT_CODE 0x00000020
3244 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
3245 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
3246
3247 /* From PE spec doc, section 5.2.1 */
3248 #define MYIMAGE_REL_I386_DIR32 0x0006
3249 #define MYIMAGE_REL_I386_REL32 0x0014
3250
3251
3252 /* We use myindex to calculate array addresses, rather than
3253 simply doing the normal subscript thing. That's because
3254 some of the above structs have sizes which are not
3255 a whole number of words. GCC rounds their sizes up to a
3256 whole number of words, which means that the address calcs
3257 arising from using normal C indexing or pointer arithmetic
3258 are just plain wrong. Sigh.
3259 */
3260 static UChar *
3261 myindex ( int scale, void* base, int index )
3262 {
3263 return
3264 ((UChar*)base) + scale * index;
3265 }
3266
3267
3268 static void
3269 printName ( UChar* name, UChar* strtab )
3270 {
3271 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3272 UInt32 strtab_offset = * (UInt32*)(name+4);
3273 debugBelch("%s", strtab + strtab_offset );
3274 } else {
3275 int i;
3276 for (i = 0; i < 8; i++) {
3277 if (name[i] == 0) break;
3278 debugBelch("%c", name[i] );
3279 }
3280 }
3281 }
3282
3283
3284 static void
3285 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
3286 {
3287 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3288 UInt32 strtab_offset = * (UInt32*)(name+4);
3289 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
3290 dst[dstSize-1] = 0;
3291 } else {
3292 int i = 0;
3293 while (1) {
3294 if (i >= 8) break;
3295 if (name[i] == 0) break;
3296 dst[i] = name[i];
3297 i++;
3298 }
3299 dst[i] = 0;
3300 }
3301 }
3302
3303
3304 static UChar *
3305 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
3306 {
3307 UChar* newstr;
3308 /* If the string is longer than 8 bytes, look in the
3309 string table for it -- this will be correctly zero terminated.
3310 */
3311 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3312 UInt32 strtab_offset = * (UInt32*)(name+4);
3313 return ((UChar*)strtab) + strtab_offset;
3314 }
3315 /* Otherwise, if shorter than 8 bytes, return the original,
3316 which by defn is correctly terminated.
3317 */
3318 if (name[7]==0) return name;
3319 /* The annoying case: 8 bytes. Copy into a temporary
3320 (XXX which is never freed ...)
3321 */
3322 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
3323 ASSERT(newstr);
3324 strncpy((char*)newstr,(char*)name,8);
3325 newstr[8] = 0;
3326 return newstr;
3327 }
3328
3329 /* Getting the name of a section is mildly tricky, so we make a
3330 function for it. Sadly, in one case we have to copy the string
3331 (when it is exactly 8 bytes long there's no trailing '\0'), so for
3332 consistency we *always* copy the string; the caller must free it
3333 */
3334 static char *
3335 cstring_from_section_name (UChar* name, UChar* strtab)
3336 {
3337 char *newstr;
3338
3339 if (name[0]=='/') {
3340 int strtab_offset = strtol((char*)name+1,NULL,10);
3341 int len = strlen(((char*)strtab) + strtab_offset);
3342
3343 newstr = stgMallocBytes(len+1, "cstring_from_section_symbol_name");
3344 strcpy((char*)newstr, (char*)((UChar*)strtab) + strtab_offset);
3345 return newstr;
3346 }
3347 else
3348 {
3349 newstr = stgMallocBytes(9, "cstring_from_section_symbol_name");
3350 ASSERT(newstr);
3351 strncpy((char*)newstr,(char*)name,8);
3352 newstr[8] = 0;
3353 return newstr;
3354 }
3355 }
3356
3357 /* Just compares the short names (first 8 chars) */
3358 static COFF_section *
3359 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
3360 {
3361 int i;
3362 COFF_header* hdr
3363 = (COFF_header*)(oc->image);
3364 COFF_section* sectab
3365 = (COFF_section*) (
3366 ((UChar*)(oc->image))
3367 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3368 );
3369 for (i = 0; i < hdr->NumberOfSections; i++) {
3370 UChar* n1;
3371 UChar* n2;
3372 COFF_section* section_i
3373 = (COFF_section*)
3374 myindex ( sizeof_COFF_section, sectab, i );
3375 n1 = (UChar*) &(section_i->Name);
3376 n2 = name;
3377 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
3378 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
3379 n1[6]==n2[6] && n1[7]==n2[7])
3380 return section_i;
3381 }
3382
3383 return NULL;
3384 }
3385
3386 static void
3387 zapTrailingAtSign ( UChar* sym )
3388 {
3389 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
3390 int i, j;
3391 if (sym[0] == 0) return;
3392 i = 0;
3393 while (sym[i] != 0) i++;
3394 i--;
3395 j = i;
3396 while (j > 0 && my_isdigit(sym[j])) j--;
3397 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
3398 # undef my_isdigit
3399 }
3400
3401 static void *
3402 lookupSymbolInDLLs ( UChar *lbl )
3403 {
3404 OpenedDLL* o_dll;
3405 void *sym;
3406
3407 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
3408 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
3409
3410 if (lbl[0] == '_') {
3411 /* HACK: if the name has an initial underscore, try stripping
3412 it off & look that up first. I've yet to verify whether there's
3413 a Rule that governs whether an initial '_' *should always* be
3414 stripped off when mapping from import lib name to the DLL name.
3415 */
3416 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
3417 if (sym != NULL) {
3418 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
3419 return sym;
3420 }
3421 }
3422 sym = GetProcAddress(o_dll->instance, (char*)lbl);
3423 if (sym != NULL) {
3424 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
3425 return sym;
3426 }
3427 }
3428 return NULL;
3429 }
3430
3431
3432 static int
3433 ocVerifyImage_PEi386 ( ObjectCode* oc )
3434 {
3435 int i;
3436 UInt32 j, noRelocs;
3437 COFF_header* hdr;
3438 COFF_section* sectab;
3439 COFF_symbol* symtab;
3440 UChar* strtab;
3441 /* debugBelch("\nLOADING %s\n", oc->fileName); */
3442 hdr = (COFF_header*)(oc->image);
3443 sectab = (COFF_section*) (
3444 ((UChar*)(oc->image))
3445 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3446 );
3447 symtab = (COFF_symbol*) (
3448 ((UChar*)(oc->image))
3449 + hdr->PointerToSymbolTable
3450 );
3451 strtab = ((UChar*)symtab)
3452 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3453
3454 #if defined(i386_HOST_ARCH)
3455 if (hdr->Machine != 0x14c) {
3456 errorBelch("%" PATH_FMT ": Not x86 PEi386", oc->fileName);
3457 return 0;
3458 }
3459 #elif defined(x86_64_HOST_ARCH)
3460 if (hdr->Machine != 0x8664) {
3461 errorBelch("%" PATH_FMT ": Not x86_64 PEi386", oc->fileName);
3462 return 0;
3463 }
3464 #else
3465 errorBelch("PEi386 not supported on this arch");
3466 #endif
3467
3468 if (hdr->SizeOfOptionalHeader != 0) {
3469 errorBelch("%" PATH_FMT ": PEi386 with nonempty optional header", oc->fileName);
3470 return 0;
3471 }
3472 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
3473 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
3474 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
3475 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
3476 errorBelch("%" PATH_FMT ": Not a PEi386 object file", oc->fileName);
3477 return 0;
3478 }
3479 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
3480 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
3481 errorBelch("%" PATH_FMT ": Invalid PEi386 word size or endiannness: %d",
3482 oc->fileName,
3483 (int)(hdr->Characteristics));
3484 return 0;
3485 }
3486 /* If the string table size is way crazy, this might indicate that
3487 there are more than 64k relocations, despite claims to the
3488 contrary. Hence this test. */
3489 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
3490 #if 0
3491 if ( (*(UInt32*)strtab) > 600000 ) {
3492 /* Note that 600k has no special significance other than being
3493 big enough to handle the almost-2MB-sized lumps that
3494 constitute HSwin32*.o. */
3495 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
3496 return 0;
3497 }
3498 #endif
3499
3500 /* No further verification after this point; only debug printing. */
3501 i = 0;
3502 IF_DEBUG(linker, i=1);
3503 if (i == 0) return 1;
3504
3505 debugBelch( "sectab offset = %" FMT_Int "\n", ((UChar*)sectab) - ((UChar*)hdr) );
3506 debugBelch( "symtab offset = %" FMT_Int "\n", ((UChar*)symtab) - ((UChar*)hdr) );
3507 debugBelch( "strtab offset = %" FMT_Int "\n", ((UChar*)strtab) - ((UChar*)hdr) );
3508
3509 debugBelch("\n" );
3510 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
3511 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
3512 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
3513 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
3514 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
3515 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
3516 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
3517
3518 /* Print the section table. */
3519 debugBelch("\n" );
3520 for (i = 0; i < hdr->NumberOfSections; i++) {
3521 COFF_reloc* reltab;
3522 COFF_section* sectab_i
3523 = (COFF_section*)
3524 myindex ( sizeof_COFF_section, sectab, i );
3525 debugBelch(
3526 "\n"
3527 "section %d\n"
3528 " name `",
3529 i
3530 );
3531 printName ( sectab_i->Name, strtab );
3532 debugBelch(
3533 "'\n"
3534 " vsize %d\n"
3535 " vaddr %d\n"
3536 " data sz %d\n"
3537 " data off %d\n"
3538 " num rel %d\n"
3539 " off rel %d\n"
3540 " ptr raw 0x%x\n",
3541 sectab_i->VirtualSize,
3542 sectab_i->VirtualAddress,
3543 sectab_i->SizeOfRawData,
3544 sectab_i->PointerToRawData,
3545 sectab_i->NumberOfRelocations,
3546 sectab_i->PointerToRelocations,
3547 sectab_i->PointerToRawData
3548 );
3549 reltab = (COFF_reloc*) (
3550 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3551 );
3552
3553 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3554 /* If the relocation field (a short) has overflowed, the
3555 * real count can be found in the first reloc entry.
3556 *
3557 * See Section 4.1 (last para) of the PE spec (rev6.0).
3558 */
3559 COFF_reloc* rel = (COFF_reloc*)
3560 myindex ( sizeof_COFF_reloc, reltab, 0 );
3561 noRelocs = rel->VirtualAddress;
3562 j = 1;
3563 } else {
3564 noRelocs = sectab_i->NumberOfRelocations;
3565 j = 0;
3566 }
3567
3568 for (; j < noRelocs; j++) {
3569 COFF_symbol* sym;
3570 COFF_reloc* rel = (COFF_reloc*)
3571 myindex ( sizeof_COFF_reloc, reltab, j );
3572 debugBelch(
3573 " type 0x%-4x vaddr 0x%-8x name `",
3574 (UInt32)rel->Type,
3575 rel->VirtualAddress );
3576 sym = (COFF_symbol*)
3577 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
3578 /* Hmm..mysterious looking offset - what's it for? SOF */
3579 printName ( sym->Name, strtab -10 );
3580 debugBelch("'\n" );
3581 }
3582
3583 debugBelch("\n" );
3584 }
3585 debugBelch("\n" );
3586 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
3587 debugBelch("---START of string table---\n");
3588 for (i = 4; i < *(Int32*)strtab; i++) {
3589 if (strtab[i] == 0)
3590 debugBelch("\n"); else
3591 debugBelch("%c", strtab[i] );
3592 }
3593 debugBelch("--- END of string table---\n");
3594
3595 debugBelch("\n" );
3596 i = 0;
3597 while (1) {
3598 COFF_symbol* symtab_i;
3599 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3600 symtab_i = (COFF_symbol*)
3601 myindex ( sizeof_COFF_symbol, symtab, i );
3602 debugBelch(
3603 "symbol %d\n"
3604 " name `",
3605 i
3606 );
3607 printName ( symtab_i->Name, strtab );
3608 debugBelch(
3609 "'\n"
3610 " value 0x%x\n"
3611 " 1+sec# %d\n"
3612 " type 0x%x\n"
3613 " sclass 0x%x\n"
3614 " nAux %d\n",
3615 symtab_i->Value,
3616 (Int32)(symtab_i->SectionNumber),
3617 (UInt32)symtab_i->Type,
3618 (UInt32)symtab_i->StorageClass,
3619 (UInt32)symtab_i->NumberOfAuxSymbols
3620 );
3621 i += symtab_i->NumberOfAuxSymbols;
3622 i++;
3623 }
3624
3625 debugBelch("\n" );
3626 return 1;
3627 }
3628
3629
3630 static int
3631 ocGetNames_PEi386 ( ObjectCode* oc )
3632 {
3633 COFF_header* hdr;
3634 COFF_section* sectab;
3635 COFF_symbol* symtab;
3636 UChar* strtab;
3637
3638 UChar* sname;
3639 void* addr;
3640 int i;
3641
3642 hdr = (COFF_header*)(oc->image);
3643 sectab = (COFF_section*) (
3644 ((UChar*)(oc->image))
3645 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3646 );
3647 symtab = (COFF_symbol*) (
3648 ((UChar*)(oc->image))
3649 + hdr->PointerToSymbolTable
3650 );
3651 strtab = ((UChar*)(oc->image))
3652 + hdr->PointerToSymbolTable
3653 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3654
3655 /* Allocate space for any (local, anonymous) .bss sections. */
3656
3657 for (i = 0; i < hdr->NumberOfSections; i++) {
3658 UInt32 bss_sz;
3659 UChar* zspace;
3660 COFF_section* sectab_i
3661 = (COFF_section*)
3662 myindex ( sizeof_COFF_section, sectab, i );
3663
3664 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3665
3666 if (0 != strcmp(secname, ".bss")) {
3667 stgFree(secname);
3668 continue;
3669 }
3670
3671 stgFree(secname);
3672
3673 /* sof 10/05: the PE spec text isn't too clear regarding what
3674 * the SizeOfRawData field is supposed to hold for object
3675 * file sections containing just uninitialized data -- for executables,
3676 * it is supposed to be zero; unclear what it's supposed to be
3677 * for object files. However, VirtualSize is guaranteed to be
3678 * zero for object files, which definitely suggests that SizeOfRawData
3679 * will be non-zero (where else would the size of this .bss section be
3680 * stored?) Looking at the COFF_section info for incoming object files,
3681 * this certainly appears to be the case.
3682 *
3683 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
3684 * object files up until now. This turned out to bite us with ghc-6.4.1's use
3685 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
3686 * variable decls into to the .bss section. (The specific function in Q which
3687 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
3688 */
3689 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
3690 /* This is a non-empty .bss section. Allocate zeroed space for
3691 it, and set its PointerToRawData field such that oc->image +
3692 PointerToRawData == addr_of_zeroed_space. */
3693 bss_sz = sectab_i->VirtualSize;
3694 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
3695 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
3696 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
3697 addProddableBlock(oc, zspace, bss_sz);
3698 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
3699 }
3700
3701 /* Copy section information into the ObjectCode. */
3702
3703 for (i = 0; i < hdr->NumberOfSections; i++) {
3704 UChar* start;
3705 UChar* end;
3706 UInt32 sz;
3707
3708 SectionKind kind
3709 = SECTIONKIND_OTHER;
3710 COFF_section* sectab_i
3711 = (COFF_section*)
3712 myindex ( sizeof_COFF_section, sectab, i );
3713
3714 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3715
3716 IF_DEBUG(linker, debugBelch("section name = %s\n", secname ));
3717
3718 # if 0
3719 /* I'm sure this is the Right Way to do it. However, the
3720 alternative of testing the sectab_i->Name field seems to
3721 work ok with Cygwin.
3722 */
3723 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
3724 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
3725 kind = SECTIONKIND_CODE_OR_RODATA;
3726 # endif
3727
3728 if (0==strcmp(".text",(char*)secname) ||
3729 0==strcmp(".text.startup",(char*)secname) ||
3730 0==strcmp(".rdata",(char*)secname)||
3731 0==strcmp(".rodata",(char*)secname))
3732 kind = SECTIONKIND_CODE_OR_RODATA;
3733 if (0==strcmp(".data",(char*)secname) ||
3734 0==strcmp(".bss",(char*)secname))
3735 kind = SECTIONKIND_RWDATA;
3736
3737 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
3738 sz = sectab_i->SizeOfRawData;
3739 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
3740
3741 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
3742 end = start + sz - 1;
3743
3744 if (kind == SECTIONKIND_OTHER
3745 /* Ignore sections called which contain stabs debugging
3746 information. */
3747 && 0 != strcmp(".stab", (char*)secname)
3748 && 0 != strcmp(".stabstr", (char*)secname)
3749 /* Ignore sections called which contain exception information. */
3750 && 0 != strcmp(".pdata", (char*)secname)
3751 && 0 != strcmp(".xdata", (char*)secname)
3752 /* ignore constructor section for now */
3753 && 0 != strcmp(".ctors", (char*)secname)
3754 /* ignore section generated from .ident */
3755 && 0!= strncmp(".debug", (char*)secname, 6)
3756 /* ignore unknown section that appeared in gcc 3.4.5(?) */
3757 && 0!= strcmp(".reloc", (char*)secname)
3758 && 0 != strcmp(".rdata$zzz", (char*)secname)
3759 ) {
3760 errorBelch("Unknown PEi386 section name `%s' (while processing: %" PATH_FMT")", secname, oc->fileName);
3761 stgFree(secname);
3762 return 0;
3763 }
3764
3765 if (kind != SECTIONKIND_OTHER && end >= start) {
3766 if ((((size_t)(start)) % sizeof(void *)) != 0) {
3767 barf("Misaligned section: %p", start);
3768 }
3769
3770 addSection(oc, kind, start, end);
3771 addProddableBlock(oc, start, end - start + 1);
3772 }
3773
3774 stgFree(secname);
3775 }
3776
3777 /* Copy exported symbols into the ObjectCode. */
3778
3779 oc->n_symbols = hdr->NumberOfSymbols;
3780 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3781 "ocGetNames_PEi386(oc->symbols)");
3782 /* Call me paranoid; I don't care. */
3783 for (i = 0; i < oc->n_symbols; i++)
3784 oc->symbols[i] = NULL;
3785
3786 i = 0;
3787 while (1) {
3788 COFF_symbol* symtab_i;
3789 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3790 symtab_i = (COFF_symbol*)
3791 myindex ( sizeof_COFF_symbol, symtab, i );
3792
3793 addr = NULL;
3794
3795 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
3796 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
3797 /* This symbol is global and defined, viz, exported */
3798 /* for MYIMAGE_SYMCLASS_EXTERNAL
3799 && !MYIMAGE_SYM_UNDEFINED,
3800 the address of the symbol is:
3801 address of relevant section + offset in section
3802 */
3803 COFF_section* sectabent
3804 = (COFF_section*) myindex ( sizeof_COFF_section,
3805 sectab,
3806 symtab_i->SectionNumber-1 );
3807 addr = ((UChar*)(oc->image))
3808 + (sectabent->PointerToRawData
3809 + symtab_i->Value);
3810 }
3811 else
3812 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
3813 && symtab_i->Value > 0) {
3814 /* This symbol isn't in any section at all, ie, global bss.
3815 Allocate zeroed space for it. */
3816 addr = stgCallocBytes(1, symtab_i->Value,
3817 "ocGetNames_PEi386(non-anonymous bss)");
3818 addSection(oc, SECTIONKIND_RWDATA, addr,
3819 ((UChar*)addr) + symtab_i->Value - 1);
3820 addProddableBlock(oc, addr, symtab_i->Value);
3821 /* debugBelch("BSS section at 0x%x\n", addr); */
3822 }
3823
3824 if (addr != NULL ) {
3825 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
3826 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
3827 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
3828 ASSERT(i >= 0 && i < oc->n_symbols);
3829 /* cstring_from_COFF_symbol_name always succeeds. */
3830 oc->symbols[i] = (char*)sname;
3831 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
3832 } else {
3833 # if 0
3834 debugBelch(
3835 "IGNORING symbol %d\n"
3836 " name `",
3837 i
3838 );
3839 printName ( symtab_i->Name, strtab );
3840 debugBelch(
3841 "'\n"
3842 " value 0x%x\n"
3843 " 1+sec# %d\n"
3844 " type 0x%x\n"
3845 " sclass 0x%x\n"
3846 " nAux %d\n",
3847 symtab_i->Value,
3848 (Int32)(symtab_i->SectionNumber),
3849 (UInt32)symtab_i->Type,
3850 (UInt32)symtab_i->StorageClass,
3851 (UInt32)symtab_i->NumberOfAuxSymbols
3852 );
3853 # endif
3854 }
3855
3856 i += symtab_i->NumberOfAuxSymbols;
3857 i++;
3858 }
3859
3860 return 1;
3861 }
3862
3863
3864 static int
3865 ocResolve_PEi386 ( ObjectCode* oc )
3866 {
3867 COFF_header* hdr;
3868 COFF_section* sectab;
3869 COFF_symbol* symtab;
3870 UChar* strtab;
3871
3872 UInt32 A;
3873 size_t S;
3874 void * pP;
3875
3876 int i;
3877 UInt32 j, noRelocs;
3878
3879 /* ToDo: should be variable-sized? But is at least safe in the
3880 sense of buffer-overrun-proof. */
3881 UChar symbol[1000];
3882 /* debugBelch("resolving for %s\n", oc->fileName); */
3883
3884 hdr = (COFF_header*)(oc->image);
3885 sectab = (COFF_section*) (
3886 ((UChar*)(oc->image))
3887 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3888 );
3889 symtab = (COFF_symbol*) (
3890 ((UChar*)(oc->image))
3891 + hdr->PointerToSymbolTable
3892 );
3893 strtab = ((UChar*)(oc->image))
3894 + hdr->PointerToSymbolTable
3895 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3896
3897 for (i = 0; i < hdr->NumberOfSections; i++) {
3898 COFF_section* sectab_i
3899 = (COFF_section*)
3900 myindex ( sizeof_COFF_section, sectab, i );
3901 COFF_reloc* reltab
3902 = (COFF_reloc*) (
3903 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3904 );
3905
3906 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3907
3908 /* Ignore sections called which contain stabs debugging
3909 information. */
3910 if (0 == strcmp(".stab", (char*)secname)
3911 || 0 == strcmp(".stabstr", (char*)secname)
3912 || 0 == strcmp(".pdata", (char*)secname)
3913 || 0 == strcmp(".xdata", (char*)secname)
3914 || 0 == strcmp(".ctors", (char*)secname)
3915 || 0 == strncmp(".debug", (char*)secname, 6)
3916 || 0 == strcmp(".rdata$zzz", (char*)secname)) {
3917 stgFree(secname);
3918 continue;
3919 }
3920
3921 stgFree(secname);
3922
3923 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3924 /* If the relocation field (a short) has overflowed, the
3925 * real count can be found in the first reloc entry.
3926 *
3927 * See Section 4.1 (last para) of the PE spec (rev6.0).
3928 *
3929 * Nov2003 update: the GNU linker still doesn't correctly
3930 * handle the generation of relocatable object files with
3931 * overflown relocations. Hence the output to warn of potential
3932 * troubles.
3933 */
3934 COFF_reloc* rel = (COFF_reloc*)
3935 myindex ( sizeof_COFF_reloc, reltab, 0 );
3936 noRelocs = rel->VirtualAddress;
3937
3938 /* 10/05: we now assume (and check for) a GNU ld that is capable
3939 * of handling object files with (>2^16) of relocs.
3940 */
3941 #if 0
3942 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
3943 noRelocs);
3944 #endif
3945 j = 1;
3946 } else {
3947 noRelocs = sectab_i->NumberOfRelocations;
3948 j = 0;
3949 }
3950
3951 for (; j < noRelocs; j++) {
3952 COFF_symbol* sym;
3953 COFF_reloc* reltab_j
3954 = (COFF_reloc*)
3955 myindex ( sizeof_COFF_reloc, reltab, j );
3956
3957 /* the location to patch */
3958 pP = (
3959 ((UChar*)(oc->image))
3960 + (sectab_i->PointerToRawData
3961 + reltab_j->VirtualAddress
3962 - sectab_i->VirtualAddress )
3963 );
3964 /* the existing contents of pP */
3965 A = *(UInt32*)pP;
3966 /* the symbol to connect to */
3967 sym = (COFF_symbol*)
3968 myindex ( sizeof_COFF_symbol,
3969 symtab, reltab_j->SymbolTableIndex );
3970 IF_DEBUG(linker,
3971 debugBelch(
3972 "reloc sec %2d num %3d: type 0x%-4x "
3973 "vaddr 0x%-8x name `",
3974 i, j,
3975 (UInt32)reltab_j->Type,
3976 reltab_j->VirtualAddress );
3977 printName ( sym->Name, strtab );
3978 debugBelch("'\n" ));
3979
3980 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
3981 COFF_section* section_sym
3982 = findPEi386SectionCalled ( oc, sym->Name );
3983 if (!section_sym) {
3984 errorBelch("%" PATH_FMT ": can't find section `%s'", oc->fileName, sym->Name);
3985 return 0;
3986 }
3987 S = ((size_t)(oc->image))
3988 + ((size_t)(section_sym->PointerToRawData))
3989 + ((size_t)(sym->Value));
3990 } else {
3991 copyName ( sym->Name, strtab, symbol, 1000-1 );
3992 S = (size_t) lookupSymbol( (char*)symbol );
3993 if ((void*)S != NULL) goto foundit;
3994 errorBelch("%" PATH_FMT ": unknown symbol `%s'", oc->fileName, symbol);
3995 return 0;
3996 foundit:;
3997 }
3998 /* All supported relocations write at least 4 bytes */
3999 checkProddableBlock(oc, pP, 4);
4000 switch (reltab_j->Type) {
4001 #if defined(i386_HOST_ARCH)
4002 case MYIMAGE_REL_I386_DIR32:
4003 *(UInt32 *)pP = ((UInt32)S) + A;
4004 break;
4005 case MYIMAGE_REL_I386_REL32:
4006 /* Tricky. We have to insert a displacement at
4007 pP which, when added to the PC for the _next_
4008 insn, gives the address of the target (S).
4009 Problem is to know the address of the next insn