Merge branch 'master' of darcs.haskell.org:/home/darcs/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_n_ret) \
885 SymI_HasProto(stg_ap_p_ret) \
886 SymI_HasProto(stg_ap_pv_ret) \
887 SymI_HasProto(stg_ap_pp_ret) \
888 SymI_HasProto(stg_ap_ppv_ret) \
889 SymI_HasProto(stg_ap_ppp_ret) \
890 SymI_HasProto(stg_ap_pppv_ret) \
891 SymI_HasProto(stg_ap_pppp_ret) \
892 SymI_HasProto(stg_ap_ppppp_ret) \
893 SymI_HasProto(stg_ap_pppppp_ret)
894 #endif
895
896 /* Modules compiled with -ticky may mention ticky counters */
897 /* This list should marry up with the one in $(TOP)/includes/stg/Ticky.h */
898 #define RTS_TICKY_SYMBOLS \
899 SymI_NeedsProto(ticky_entry_ctrs) \
900 SymI_NeedsProto(top_ct) \
901 \
902 SymI_HasProto(ENT_VIA_NODE_ctr) \
903 SymI_HasProto(ENT_STATIC_THK_ctr) \
904 SymI_HasProto(ENT_DYN_THK_ctr) \
905 SymI_HasProto(ENT_STATIC_FUN_DIRECT_ctr) \
906 SymI_HasProto(ENT_DYN_FUN_DIRECT_ctr) \
907 SymI_HasProto(ENT_STATIC_CON_ctr) \
908 SymI_HasProto(ENT_DYN_CON_ctr) \
909 SymI_HasProto(ENT_STATIC_IND_ctr) \
910 SymI_HasProto(ENT_DYN_IND_ctr) \
911 SymI_HasProto(ENT_PERM_IND_ctr) \
912 SymI_HasProto(ENT_PAP_ctr) \
913 SymI_HasProto(ENT_AP_ctr) \
914 SymI_HasProto(ENT_AP_STACK_ctr) \
915 SymI_HasProto(ENT_BH_ctr) \
916 SymI_HasProto(UNKNOWN_CALL_ctr) \
917 SymI_HasProto(SLOW_CALL_v_ctr) \
918 SymI_HasProto(SLOW_CALL_f_ctr) \
919 SymI_HasProto(SLOW_CALL_d_ctr) \
920 SymI_HasProto(SLOW_CALL_l_ctr) \
921 SymI_HasProto(SLOW_CALL_n_ctr) \
922 SymI_HasProto(SLOW_CALL_p_ctr) \
923 SymI_HasProto(SLOW_CALL_pv_ctr) \
924 SymI_HasProto(SLOW_CALL_pp_ctr) \
925 SymI_HasProto(SLOW_CALL_ppv_ctr) \
926 SymI_HasProto(SLOW_CALL_ppp_ctr) \
927 SymI_HasProto(SLOW_CALL_pppv_ctr) \
928 SymI_HasProto(SLOW_CALL_pppp_ctr) \
929 SymI_HasProto(SLOW_CALL_ppppp_ctr) \
930 SymI_HasProto(SLOW_CALL_pppppp_ctr) \
931 SymI_HasProto(SLOW_CALL_OTHER_ctr) \
932 SymI_HasProto(ticky_slow_call_unevald) \
933 SymI_HasProto(SLOW_CALL_ctr) \
934 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_ctr) \
935 SymI_HasProto(MULTI_CHUNK_SLOW_CALL_CHUNKS_ctr) \
936 SymI_HasProto(KNOWN_CALL_ctr) \
937 SymI_HasProto(KNOWN_CALL_TOO_FEW_ARGS_ctr) \
938 SymI_HasProto(KNOWN_CALL_EXTRA_ARGS_ctr) \
939 SymI_HasProto(SLOW_CALL_FUN_TOO_FEW_ctr) \
940 SymI_HasProto(SLOW_CALL_FUN_CORRECT_ctr) \
941 SymI_HasProto(SLOW_CALL_FUN_TOO_MANY_ctr) \
942 SymI_HasProto(SLOW_CALL_PAP_TOO_FEW_ctr) \
943 SymI_HasProto(SLOW_CALL_PAP_CORRECT_ctr) \
944 SymI_HasProto(SLOW_CALL_PAP_TOO_MANY_ctr) \
945 SymI_HasProto(SLOW_CALL_UNEVALD_ctr) \
946 SymI_HasProto(UPDF_OMITTED_ctr) \
947 SymI_HasProto(UPDF_PUSHED_ctr) \
948 SymI_HasProto(CATCHF_PUSHED_ctr) \
949 SymI_HasProto(UPDF_RCC_PUSHED_ctr) \
950 SymI_HasProto(UPDF_RCC_OMITTED_ctr) \
951 SymI_HasProto(UPD_SQUEEZED_ctr) \
952 SymI_HasProto(UPD_CON_IN_NEW_ctr) \
953 SymI_HasProto(UPD_CON_IN_PLACE_ctr) \
954 SymI_HasProto(UPD_PAP_IN_NEW_ctr) \
955 SymI_HasProto(UPD_PAP_IN_PLACE_ctr) \
956 SymI_HasProto(ALLOC_HEAP_ctr) \
957 SymI_HasProto(ALLOC_HEAP_tot) \
958 SymI_HasProto(ALLOC_FUN_ctr) \
959 SymI_HasProto(ALLOC_FUN_adm) \
960 SymI_HasProto(ALLOC_FUN_gds) \
961 SymI_HasProto(ALLOC_FUN_slp) \
962 SymI_HasProto(UPD_NEW_IND_ctr) \
963 SymI_HasProto(UPD_NEW_PERM_IND_ctr) \
964 SymI_HasProto(UPD_OLD_IND_ctr) \
965 SymI_HasProto(UPD_OLD_PERM_IND_ctr) \
966 SymI_HasProto(UPD_BH_UPDATABLE_ctr) \
967 SymI_HasProto(UPD_BH_SINGLE_ENTRY_ctr) \
968 SymI_HasProto(UPD_CAF_BH_UPDATABLE_ctr) \
969 SymI_HasProto(UPD_CAF_BH_SINGLE_ENTRY_ctr) \
970 SymI_HasProto(GC_SEL_ABANDONED_ctr) \
971 SymI_HasProto(GC_SEL_MINOR_ctr) \
972 SymI_HasProto(GC_SEL_MAJOR_ctr) \
973 SymI_HasProto(GC_FAILED_PROMOTION_ctr) \
974 SymI_HasProto(ALLOC_UP_THK_ctr) \
975 SymI_HasProto(ALLOC_SE_THK_ctr) \
976 SymI_HasProto(ALLOC_THK_adm) \
977 SymI_HasProto(ALLOC_THK_gds) \
978 SymI_HasProto(ALLOC_THK_slp) \
979 SymI_HasProto(ALLOC_CON_ctr) \
980 SymI_HasProto(ALLOC_CON_adm) \
981 SymI_HasProto(ALLOC_CON_gds) \
982 SymI_HasProto(ALLOC_CON_slp) \
983 SymI_HasProto(ALLOC_TUP_ctr) \
984 SymI_HasProto(ALLOC_TUP_adm) \
985 SymI_HasProto(ALLOC_TUP_gds) \
986 SymI_HasProto(ALLOC_TUP_slp) \
987 SymI_HasProto(ALLOC_BH_ctr) \
988 SymI_HasProto(ALLOC_BH_adm) \
989 SymI_HasProto(ALLOC_BH_gds) \
990 SymI_HasProto(ALLOC_BH_slp) \
991 SymI_HasProto(ALLOC_PRIM_ctr) \
992 SymI_HasProto(ALLOC_PRIM_adm) \
993 SymI_HasProto(ALLOC_PRIM_gds) \
994 SymI_HasProto(ALLOC_PRIM_slp) \
995 SymI_HasProto(ALLOC_PAP_ctr) \
996 SymI_HasProto(ALLOC_PAP_adm) \
997 SymI_HasProto(ALLOC_PAP_gds) \
998 SymI_HasProto(ALLOC_PAP_slp) \
999 SymI_HasProto(ALLOC_TSO_ctr) \
1000 SymI_HasProto(ALLOC_TSO_adm) \
1001 SymI_HasProto(ALLOC_TSO_gds) \
1002 SymI_HasProto(ALLOC_TSO_slp) \
1003 SymI_HasProto(RET_NEW_ctr) \
1004 SymI_HasProto(RET_OLD_ctr) \
1005 SymI_HasProto(RET_UNBOXED_TUP_ctr) \
1006 SymI_HasProto(RET_SEMI_loads_avoided)
1007
1008
1009 // On most platforms, the garbage collector rewrites references
1010 // to small integer and char objects to a set of common, shared ones.
1011 //
1012 // We don't do this when compiling to Windows DLLs at the moment because
1013 // it doesn't support cross package data references well.
1014 //
1015 #if defined(COMPILING_WINDOWS_DLL)
1016 #define RTS_INTCHAR_SYMBOLS
1017 #else
1018 #define RTS_INTCHAR_SYMBOLS \
1019 SymI_HasProto(stg_CHARLIKE_closure) \
1020 SymI_HasProto(stg_INTLIKE_closure)
1021 #endif
1022
1023
1024 #define RTS_SYMBOLS \
1025 Maybe_Stable_Names \
1026 RTS_TICKY_SYMBOLS \
1027 SymI_HasProto(StgReturn) \
1028 SymI_HasProto(stg_gc_noregs) \
1029 SymI_HasProto(stg_ret_v_info) \
1030 SymI_HasProto(stg_ret_p_info) \
1031 SymI_HasProto(stg_ret_n_info) \
1032 SymI_HasProto(stg_ret_f_info) \
1033 SymI_HasProto(stg_ret_d_info) \
1034 SymI_HasProto(stg_ret_l_info) \
1035 SymI_HasProto(stg_gc_prim_p) \
1036 SymI_HasProto(stg_gc_prim_pp) \
1037 SymI_HasProto(stg_gc_prim_n) \
1038 SymI_HasProto(stg_enter_info) \
1039 SymI_HasProto(__stg_gc_enter_1) \
1040 SymI_HasProto(stg_gc_unpt_r1) \
1041 SymI_HasProto(stg_gc_unbx_r1) \
1042 SymI_HasProto(stg_gc_f1) \
1043 SymI_HasProto(stg_gc_d1) \
1044 SymI_HasProto(stg_gc_l1) \
1045 SymI_HasProto(stg_gc_pp) \
1046 SymI_HasProto(stg_gc_ppp) \
1047 SymI_HasProto(stg_gc_pppp) \
1048 SymI_HasProto(__stg_gc_fun) \
1049 SymI_HasProto(stg_gc_fun_info) \
1050 SymI_HasProto(stg_yield_noregs) \
1051 SymI_HasProto(stg_yield_to_interpreter) \
1052 SymI_HasProto(stg_block_noregs) \
1053 SymI_HasProto(stg_block_takemvar) \
1054 SymI_HasProto(stg_block_putmvar) \
1055 MAIN_CAP_SYM \
1056 SymI_HasProto(MallocFailHook) \
1057 SymI_HasProto(OnExitHook) \
1058 SymI_HasProto(OutOfHeapHook) \
1059 SymI_HasProto(StackOverflowHook) \
1060 SymI_HasProto(addDLL) \
1061 SymI_HasProto(__int_encodeDouble) \
1062 SymI_HasProto(__word_encodeDouble) \
1063 SymI_HasProto(__2Int_encodeDouble) \
1064 SymI_HasProto(__int_encodeFloat) \
1065 SymI_HasProto(__word_encodeFloat) \
1066 SymI_HasProto(stg_atomicallyzh) \
1067 SymI_HasProto(barf) \
1068 SymI_HasProto(debugBelch) \
1069 SymI_HasProto(errorBelch) \
1070 SymI_HasProto(sysErrorBelch) \
1071 SymI_HasProto(stg_getMaskingStatezh) \
1072 SymI_HasProto(stg_maskAsyncExceptionszh) \
1073 SymI_HasProto(stg_maskUninterruptiblezh) \
1074 SymI_HasProto(stg_catchzh) \
1075 SymI_HasProto(stg_catchRetryzh) \
1076 SymI_HasProto(stg_catchSTMzh) \
1077 SymI_HasProto(stg_checkzh) \
1078 SymI_HasProto(closure_flags) \
1079 SymI_HasProto(cmp_thread) \
1080 SymI_HasProto(createAdjustor) \
1081 SymI_HasProto(stg_decodeDoublezu2Intzh) \
1082 SymI_HasProto(stg_decodeFloatzuIntzh) \
1083 SymI_HasProto(defaultsHook) \
1084 SymI_HasProto(stg_delayzh) \
1085 SymI_HasProto(stg_deRefWeakzh) \
1086 SymI_HasProto(stg_deRefStablePtrzh) \
1087 SymI_HasProto(dirty_MUT_VAR) \
1088 SymI_HasProto(dirty_TVAR) \
1089 SymI_HasProto(stg_forkzh) \
1090 SymI_HasProto(stg_forkOnzh) \
1091 SymI_HasProto(forkProcess) \
1092 SymI_HasProto(forkOS_createThread) \
1093 SymI_HasProto(freeHaskellFunctionPtr) \
1094 SymI_HasProto(getOrSetGHCConcSignalSignalHandlerStore) \
1095 SymI_HasProto(getOrSetGHCConcWindowsPendingDelaysStore) \
1096 SymI_HasProto(getOrSetGHCConcWindowsIOManagerThreadStore) \
1097 SymI_HasProto(getOrSetGHCConcWindowsProddingStore) \
1098 SymI_HasProto(getOrSetSystemEventThreadEventManagerStore) \
1099 SymI_HasProto(getOrSetSystemEventThreadIOManagerThreadStore) \
1100 SymI_HasProto(getGCStats) \
1101 SymI_HasProto(getGCStatsEnabled) \
1102 SymI_HasProto(genSymZh) \
1103 SymI_HasProto(genericRaise) \
1104 SymI_HasProto(getProgArgv) \
1105 SymI_HasProto(getFullProgArgv) \
1106 SymI_HasProto(getStablePtr) \
1107 SymI_HasProto(hs_init) \
1108 SymI_HasProto(hs_exit) \
1109 SymI_HasProto(hs_set_argv) \
1110 SymI_HasProto(hs_add_root) \
1111 SymI_HasProto(hs_perform_gc) \
1112 SymI_HasProto(hs_free_stable_ptr) \
1113 SymI_HasProto(hs_free_fun_ptr) \
1114 SymI_HasProto(hs_hpc_rootModule) \
1115 SymI_HasProto(hs_hpc_module) \
1116 SymI_HasProto(initLinker) \
1117 SymI_HasProto(stg_unpackClosurezh) \
1118 SymI_HasProto(stg_getApStackValzh) \
1119 SymI_HasProto(stg_getSparkzh) \
1120 SymI_HasProto(stg_numSparkszh) \
1121 SymI_HasProto(stg_isCurrentThreadBoundzh) \
1122 SymI_HasProto(stg_isEmptyMVarzh) \
1123 SymI_HasProto(stg_killThreadzh) \
1124 SymI_HasProto(loadArchive) \
1125 SymI_HasProto(loadObj) \
1126 SymI_HasProto(insertStableSymbol) \
1127 SymI_HasProto(insertSymbol) \
1128 SymI_HasProto(lookupSymbol) \
1129 SymI_HasProto(stg_makeStablePtrzh) \
1130 SymI_HasProto(stg_mkApUpd0zh) \
1131 SymI_HasProto(stg_myThreadIdzh) \
1132 SymI_HasProto(stg_labelThreadzh) \
1133 SymI_HasProto(stg_newArrayzh) \
1134 SymI_HasProto(stg_newArrayArrayzh) \
1135 SymI_HasProto(stg_newBCOzh) \
1136 SymI_HasProto(stg_newByteArrayzh) \
1137 SymI_HasProto_redirect(newCAF, newDynCAF) \
1138 SymI_HasProto(stg_newMVarzh) \
1139 SymI_HasProto(stg_newMutVarzh) \
1140 SymI_HasProto(stg_newTVarzh) \
1141 SymI_HasProto(stg_noDuplicatezh) \
1142 SymI_HasProto(stg_atomicModifyMutVarzh) \
1143 SymI_HasProto(stg_casMutVarzh) \
1144 SymI_HasProto(stg_newPinnedByteArrayzh) \
1145 SymI_HasProto(stg_newAlignedPinnedByteArrayzh) \
1146 SymI_HasProto(newSpark) \
1147 SymI_HasProto(performGC) \
1148 SymI_HasProto(performMajorGC) \
1149 SymI_HasProto(prog_argc) \
1150 SymI_HasProto(prog_argv) \
1151 SymI_HasProto(stg_putMVarzh) \
1152 SymI_HasProto(stg_raisezh) \
1153 SymI_HasProto(stg_raiseIOzh) \
1154 SymI_HasProto(stg_readTVarzh) \
1155 SymI_HasProto(stg_readTVarIOzh) \
1156 SymI_HasProto(resumeThread) \
1157 SymI_HasProto(setNumCapabilities) \
1158 SymI_HasProto(getNumberOfProcessors) \
1159 SymI_HasProto(resolveObjs) \
1160 SymI_HasProto(stg_retryzh) \
1161 SymI_HasProto(rts_apply) \
1162 SymI_HasProto(rts_checkSchedStatus) \
1163 SymI_HasProto(rts_eval) \
1164 SymI_HasProto(rts_evalIO) \
1165 SymI_HasProto(rts_evalLazyIO) \
1166 SymI_HasProto(rts_evalStableIO) \
1167 SymI_HasProto(rts_eval_) \
1168 SymI_HasProto(rts_getBool) \
1169 SymI_HasProto(rts_getChar) \
1170 SymI_HasProto(rts_getDouble) \
1171 SymI_HasProto(rts_getFloat) \
1172 SymI_HasProto(rts_getInt) \
1173 SymI_HasProto(rts_getInt8) \
1174 SymI_HasProto(rts_getInt16) \
1175 SymI_HasProto(rts_getInt32) \
1176 SymI_HasProto(rts_getInt64) \
1177 SymI_HasProto(rts_getPtr) \
1178 SymI_HasProto(rts_getFunPtr) \
1179 SymI_HasProto(rts_getStablePtr) \
1180 SymI_HasProto(rts_getThreadId) \
1181 SymI_HasProto(rts_getWord) \
1182 SymI_HasProto(rts_getWord8) \
1183 SymI_HasProto(rts_getWord16) \
1184 SymI_HasProto(rts_getWord32) \
1185 SymI_HasProto(rts_getWord64) \
1186 SymI_HasProto(rts_lock) \
1187 SymI_HasProto(rts_mkBool) \
1188 SymI_HasProto(rts_mkChar) \
1189 SymI_HasProto(rts_mkDouble) \
1190 SymI_HasProto(rts_mkFloat) \
1191 SymI_HasProto(rts_mkInt) \
1192 SymI_HasProto(rts_mkInt8) \
1193 SymI_HasProto(rts_mkInt16) \
1194 SymI_HasProto(rts_mkInt32) \
1195 SymI_HasProto(rts_mkInt64) \
1196 SymI_HasProto(rts_mkPtr) \
1197 SymI_HasProto(rts_mkFunPtr) \
1198 SymI_HasProto(rts_mkStablePtr) \
1199 SymI_HasProto(rts_mkString) \
1200 SymI_HasProto(rts_mkWord) \
1201 SymI_HasProto(rts_mkWord8) \
1202 SymI_HasProto(rts_mkWord16) \
1203 SymI_HasProto(rts_mkWord32) \
1204 SymI_HasProto(rts_mkWord64) \
1205 SymI_HasProto(rts_unlock) \
1206 SymI_HasProto(rts_unsafeGetMyCapability) \
1207 SymI_HasProto(rtsSupportsBoundThreads) \
1208 SymI_HasProto(rts_isProfiled) \
1209 SymI_HasProto(setProgArgv) \
1210 SymI_HasProto(startupHaskell) \
1211 SymI_HasProto(shutdownHaskell) \
1212 SymI_HasProto(shutdownHaskellAndExit) \
1213 SymI_HasProto(stable_ptr_table) \
1214 SymI_HasProto(stackOverflow) \
1215 SymI_HasProto(stg_CAF_BLACKHOLE_info) \
1216 SymI_HasProto(stg_BLACKHOLE_info) \
1217 SymI_HasProto(__stg_EAGER_BLACKHOLE_info) \
1218 SymI_HasProto(stg_BLOCKING_QUEUE_CLEAN_info) \
1219 SymI_HasProto(stg_BLOCKING_QUEUE_DIRTY_info) \
1220 SymI_HasProto(startTimer) \
1221 SymI_HasProto(stg_MVAR_CLEAN_info) \
1222 SymI_HasProto(stg_MVAR_DIRTY_info) \
1223 SymI_HasProto(stg_TVAR_CLEAN_info) \
1224 SymI_HasProto(stg_TVAR_DIRTY_info) \
1225 SymI_HasProto(stg_IND_STATIC_info) \
1226 SymI_HasProto(stg_ARR_WORDS_info) \
1227 SymI_HasProto(stg_MUT_ARR_PTRS_DIRTY_info) \
1228 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN_info) \
1229 SymI_HasProto(stg_MUT_ARR_PTRS_FROZEN0_info) \
1230 SymI_HasProto(stg_WEAK_info) \
1231 SymI_HasProto(stg_ap_v_info) \
1232 SymI_HasProto(stg_ap_f_info) \
1233 SymI_HasProto(stg_ap_d_info) \
1234 SymI_HasProto(stg_ap_l_info) \
1235 SymI_HasProto(stg_ap_n_info) \
1236 SymI_HasProto(stg_ap_p_info) \
1237 SymI_HasProto(stg_ap_pv_info) \
1238 SymI_HasProto(stg_ap_pp_info) \
1239 SymI_HasProto(stg_ap_ppv_info) \
1240 SymI_HasProto(stg_ap_ppp_info) \
1241 SymI_HasProto(stg_ap_pppv_info) \
1242 SymI_HasProto(stg_ap_pppp_info) \
1243 SymI_HasProto(stg_ap_ppppp_info) \
1244 SymI_HasProto(stg_ap_pppppp_info) \
1245 SymI_HasProto(stg_ap_0_fast) \
1246 SymI_HasProto(stg_ap_v_fast) \
1247 SymI_HasProto(stg_ap_f_fast) \
1248 SymI_HasProto(stg_ap_d_fast) \
1249 SymI_HasProto(stg_ap_l_fast) \
1250 SymI_HasProto(stg_ap_n_fast) \
1251 SymI_HasProto(stg_ap_p_fast) \
1252 SymI_HasProto(stg_ap_pv_fast) \
1253 SymI_HasProto(stg_ap_pp_fast) \
1254 SymI_HasProto(stg_ap_ppv_fast) \
1255 SymI_HasProto(stg_ap_ppp_fast) \
1256 SymI_HasProto(stg_ap_pppv_fast) \
1257 SymI_HasProto(stg_ap_pppp_fast) \
1258 SymI_HasProto(stg_ap_ppppp_fast) \
1259 SymI_HasProto(stg_ap_pppppp_fast) \
1260 SymI_HasProto(stg_ap_1_upd_info) \
1261 SymI_HasProto(stg_ap_2_upd_info) \
1262 SymI_HasProto(stg_ap_3_upd_info) \
1263 SymI_HasProto(stg_ap_4_upd_info) \
1264 SymI_HasProto(stg_ap_5_upd_info) \
1265 SymI_HasProto(stg_ap_6_upd_info) \
1266 SymI_HasProto(stg_ap_7_upd_info) \
1267 SymI_HasProto(stg_exit) \
1268 SymI_HasProto(stg_sel_0_upd_info) \
1269 SymI_HasProto(stg_sel_10_upd_info) \
1270 SymI_HasProto(stg_sel_11_upd_info) \
1271 SymI_HasProto(stg_sel_12_upd_info) \
1272 SymI_HasProto(stg_sel_13_upd_info) \
1273 SymI_HasProto(stg_sel_14_upd_info) \
1274 SymI_HasProto(stg_sel_15_upd_info) \
1275 SymI_HasProto(stg_sel_1_upd_info) \
1276 SymI_HasProto(stg_sel_2_upd_info) \
1277 SymI_HasProto(stg_sel_3_upd_info) \
1278 SymI_HasProto(stg_sel_4_upd_info) \
1279 SymI_HasProto(stg_sel_5_upd_info) \
1280 SymI_HasProto(stg_sel_6_upd_info) \
1281 SymI_HasProto(stg_sel_7_upd_info) \
1282 SymI_HasProto(stg_sel_8_upd_info) \
1283 SymI_HasProto(stg_sel_9_upd_info) \
1284 SymI_HasProto(stg_upd_frame_info) \
1285 SymI_HasProto(stg_bh_upd_frame_info) \
1286 SymI_HasProto(suspendThread) \
1287 SymI_HasProto(stg_takeMVarzh) \
1288 SymI_HasProto(stg_threadStatuszh) \
1289 SymI_HasProto(stg_tryPutMVarzh) \
1290 SymI_HasProto(stg_tryTakeMVarzh) \
1291 SymI_HasProto(stg_unmaskAsyncExceptionszh) \
1292 SymI_HasProto(unloadObj) \
1293 SymI_HasProto(stg_unsafeThawArrayzh) \
1294 SymI_HasProto(stg_waitReadzh) \
1295 SymI_HasProto(stg_waitWritezh) \
1296 SymI_HasProto(stg_writeTVarzh) \
1297 SymI_HasProto(stg_yieldzh) \
1298 SymI_NeedsProto(stg_interp_constr_entry) \
1299 SymI_HasProto(stg_arg_bitmaps) \
1300 SymI_HasProto(large_alloc_lim) \
1301 SymI_HasProto(g0) \
1302 SymI_HasProto(allocate) \
1303 SymI_HasProto(allocateExec) \
1304 SymI_HasProto(freeExec) \
1305 SymI_HasProto(getAllocations) \
1306 SymI_HasProto(revertCAFs) \
1307 SymI_HasProto(RtsFlags) \
1308 SymI_NeedsProto(rts_breakpoint_io_action) \
1309 SymI_NeedsProto(rts_stop_next_breakpoint) \
1310 SymI_NeedsProto(rts_stop_on_exception) \
1311 SymI_HasProto(stopTimer) \
1312 SymI_HasProto(n_capabilities) \
1313 SymI_HasProto(enabled_capabilities) \
1314 SymI_HasProto(stg_traceCcszh) \
1315 SymI_HasProto(stg_traceEventzh) \
1316 SymI_HasProto(stg_traceMarkerzh) \
1317 SymI_HasProto(getMonotonicNSec) \
1318 SymI_HasProto(lockFile) \
1319 SymI_HasProto(unlockFile) \
1320 SymI_HasProto(startProfTimer) \
1321 SymI_HasProto(stopProfTimer) \
1322 RTS_USER_SIGNALS_SYMBOLS \
1323 RTS_INTCHAR_SYMBOLS
1324
1325
1326 // 64-bit support functions in libgcc.a
1327 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4 && !defined(_ABIN32)
1328 #define RTS_LIBGCC_SYMBOLS \
1329 SymI_NeedsProto(__divdi3) \
1330 SymI_NeedsProto(__udivdi3) \
1331 SymI_NeedsProto(__moddi3) \
1332 SymI_NeedsProto(__umoddi3) \
1333 SymI_NeedsProto(__muldi3) \
1334 SymI_NeedsProto(__ashldi3) \
1335 SymI_NeedsProto(__ashrdi3) \
1336 SymI_NeedsProto(__lshrdi3) \
1337 SymI_NeedsProto(__fixunsdfdi)
1338 #else
1339 #define RTS_LIBGCC_SYMBOLS
1340 #endif
1341
1342 #if defined(darwin_HOST_OS) && defined(powerpc_HOST_ARCH)
1343 // Symbols that don't have a leading underscore
1344 // on Mac OS X. They have to receive special treatment,
1345 // see machoInitSymbolsWithoutUnderscore()
1346 #define RTS_MACHO_NOUNDERLINE_SYMBOLS \
1347 SymI_NeedsProto(saveFP) \
1348 SymI_NeedsProto(restFP)
1349 #endif
1350
1351 /* entirely bogus claims about types of these symbols */
1352 #define SymI_NeedsProto(vvv) extern void vvv(void);
1353 #if defined(COMPILING_WINDOWS_DLL)
1354 #define SymE_HasProto(vvv) SymE_HasProto(vvv);
1355 # if defined(x86_64_HOST_ARCH)
1356 # define SymE_NeedsProto(vvv) extern void __imp_ ## vvv (void);
1357 # else
1358 # define SymE_NeedsProto(vvv) extern void _imp__ ## vvv (void);
1359 # endif
1360 #else
1361 #define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
1362 #define SymE_HasProto(vvv) SymI_HasProto(vvv)
1363 #endif
1364 #define SymI_HasProto(vvv) /**/
1365 #define SymI_HasProto_redirect(vvv,xxx) /**/
1366 RTS_SYMBOLS
1367 RTS_RET_SYMBOLS
1368 RTS_POSIX_ONLY_SYMBOLS
1369 RTS_MINGW_ONLY_SYMBOLS
1370 RTS_CYGWIN_ONLY_SYMBOLS
1371 RTS_DARWIN_ONLY_SYMBOLS
1372 RTS_LIBGCC_SYMBOLS
1373 RTS_LIBFFI_SYMBOLS
1374 #undef SymI_NeedsProto
1375 #undef SymI_HasProto
1376 #undef SymI_HasProto_redirect
1377 #undef SymE_HasProto
1378 #undef SymE_NeedsProto
1379
1380 #ifdef LEADING_UNDERSCORE
1381 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
1382 #else
1383 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
1384 #endif
1385
1386 #define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1387 (void*)(&(vvv)) },
1388 #define SymE_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1389 (void*)DLL_IMPORT_DATA_REF(vvv) },
1390
1391 #define SymI_NeedsProto(vvv) SymI_HasProto(vvv)
1392 #define SymE_NeedsProto(vvv) SymE_HasProto(vvv)
1393
1394 // SymI_HasProto_redirect allows us to redirect references to one symbol to
1395 // another symbol. See newCAF/newDynCAF for an example.
1396 #define SymI_HasProto_redirect(vvv,xxx) \
1397 { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
1398 (void*)(&(xxx)) },
1399
1400 static RtsSymbolVal rtsSyms[] = {
1401 RTS_SYMBOLS
1402 RTS_RET_SYMBOLS
1403 RTS_POSIX_ONLY_SYMBOLS
1404 RTS_MINGW_ONLY_SYMBOLS
1405 RTS_CYGWIN_ONLY_SYMBOLS
1406 RTS_DARWIN_ONLY_SYMBOLS
1407 RTS_LIBGCC_SYMBOLS
1408 RTS_LIBFFI_SYMBOLS
1409 #if defined(darwin_HOST_OS) && defined(i386_HOST_ARCH)
1410 // dyld stub code contains references to this,
1411 // but it should never be called because we treat
1412 // lazy pointers as nonlazy.
1413 { "dyld_stub_binding_helper", (void*)0xDEADBEEF },
1414 #endif
1415 { 0, 0 } /* sentinel */
1416 };
1417
1418
1419 /* -----------------------------------------------------------------------------
1420 * Insert symbols into hash tables, checking for duplicates.
1421 */
1422
1423 static void ghciInsertStrHashTable ( pathchar* obj_name,
1424 HashTable *table,
1425 char* key,
1426 void *data
1427 )
1428 {
1429 if (lookupHashTable(table, (StgWord)key) == NULL)
1430 {
1431 insertStrHashTable(table, (StgWord)key, data);
1432 return;
1433 }
1434 debugBelch(
1435 "\n\n"
1436 "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
1437 " %s\n"
1438 "whilst processing object file\n"
1439 " %" PATH_FMT "\n"
1440 "This could be caused by:\n"
1441 " * Loading two different object files which export the same symbol\n"
1442 " * Specifying the same object file twice on the GHCi command line\n"
1443 " * An incorrect `package.conf' entry, causing some object to be\n"
1444 " loaded twice.\n"
1445 "GHCi cannot safely continue in this situation. Exiting now. Sorry.\n"
1446 "\n",
1447 (char*)key,
1448 obj_name
1449 );
1450 stg_exit(1);
1451 }
1452 /* -----------------------------------------------------------------------------
1453 * initialize the object linker
1454 */
1455
1456
1457 static int linker_init_done = 0 ;
1458
1459 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1460 static void *dl_prog_handle;
1461 static regex_t re_invalid;
1462 static regex_t re_realso;
1463 #ifdef THREADED_RTS
1464 static Mutex dl_mutex; // mutex to protect dlopen/dlerror critical section
1465 #endif
1466 #endif
1467
1468 void
1469 initLinker( void )
1470 {
1471 RtsSymbolVal *sym;
1472 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1473 int compileResult;
1474 #endif
1475
1476 IF_DEBUG(linker, debugBelch("initLinker: start\n"));
1477
1478 /* Make initLinker idempotent, so we can call it
1479 before every relevant operation; that means we
1480 don't need to initialise the linker separately */
1481 if (linker_init_done == 1) {
1482 IF_DEBUG(linker, debugBelch("initLinker: idempotent return\n"));
1483 return;
1484 } else {
1485 linker_init_done = 1;
1486 }
1487
1488 #if defined(THREADED_RTS) && (defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO))
1489 initMutex(&dl_mutex);
1490 #endif
1491 stablehash = allocStrHashTable();
1492 symhash = allocStrHashTable();
1493
1494 /* populate the symbol table with stuff from the RTS */
1495 for (sym = rtsSyms; sym->lbl != NULL; sym++) {
1496 ghciInsertStrHashTable(WSTR("(GHCi built-in symbols)"),
1497 symhash, sym->lbl, sym->addr);
1498 IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
1499 }
1500 # if defined(OBJFORMAT_MACHO) && defined(powerpc_HOST_ARCH)
1501 machoInitSymbolsWithoutUnderscore();
1502 # endif
1503
1504 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1505 # if defined(RTLD_DEFAULT)
1506 dl_prog_handle = RTLD_DEFAULT;
1507 # else
1508 dl_prog_handle = dlopen(NULL, RTLD_LAZY);
1509 # endif /* RTLD_DEFAULT */
1510
1511 compileResult = regcomp(&re_invalid,
1512 "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short)",
1513 REG_EXTENDED);
1514 if (compileResult != 0) {
1515 barf("Compiling re_invalid failed");
1516 }
1517 compileResult = regcomp(&re_realso,
1518 "(GROUP|INPUT) *\\( *([^ )]+)",
1519 REG_EXTENDED);
1520 if (compileResult != 0) {
1521 barf("Compiling re_realso failed");
1522 }
1523 # endif
1524
1525 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1526 if (RtsFlags.MiscFlags.linkerMemBase != 0) {
1527 // User-override for mmap_32bit_base
1528 mmap_32bit_base = (void*)RtsFlags.MiscFlags.linkerMemBase;
1529 }
1530 #endif
1531
1532 #if defined(mingw32_HOST_OS)
1533 /*
1534 * These two libraries cause problems when added to the static link,
1535 * but are necessary for resolving symbols in GHCi, hence we load
1536 * them manually here.
1537 */
1538 addDLL(WSTR("msvcrt"));
1539 addDLL(WSTR("kernel32"));
1540 #endif
1541
1542 IF_DEBUG(linker, debugBelch("initLinker: done\n"));
1543 return;
1544 }
1545
1546 void
1547 exitLinker( void ) {
1548 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1549 if (linker_init_done == 1) {
1550 regfree(&re_invalid);
1551 regfree(&re_realso);
1552 #ifdef THREADED_RTS
1553 closeMutex(&dl_mutex);
1554 #endif
1555 }
1556 #endif
1557 }
1558
1559 /* -----------------------------------------------------------------------------
1560 * Loading DLL or .so dynamic libraries
1561 * -----------------------------------------------------------------------------
1562 *
1563 * Add a DLL from which symbols may be found. In the ELF case, just
1564 * do RTLD_GLOBAL-style add, so no further messing around needs to
1565 * happen in order that symbols in the loaded .so are findable --
1566 * lookupSymbol() will subsequently see them by dlsym on the program's
1567 * dl-handle. Returns NULL if success, otherwise ptr to an err msg.
1568 *
1569 * In the PEi386 case, open the DLLs and put handles to them in a
1570 * linked list. When looking for a symbol, try all handles in the
1571 * list. This means that we need to load even DLLs that are guaranteed
1572 * to be in the ghc.exe image already, just so we can get a handle
1573 * to give to loadSymbol, so that we can find the symbols. For such
1574 * libraries, the LoadLibrary call should be a no-op except for returning
1575 * the handle.
1576 *
1577 */
1578
1579 #if defined(OBJFORMAT_PEi386)
1580 /* A record for storing handles into DLLs. */
1581
1582 typedef
1583 struct _OpenedDLL {
1584 pathchar* name;
1585 struct _OpenedDLL* next;
1586 HINSTANCE instance;
1587 }
1588 OpenedDLL;
1589
1590 /* A list thereof. */
1591 static OpenedDLL* opened_dlls = NULL;
1592 #endif
1593
1594 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1595
1596 /* Suppose in ghci we load a temporary SO for a module containing
1597 f = 1
1598 and then modify the module, recompile, and load another temporary
1599 SO with
1600 f = 2
1601 Then as we don't unload the first SO, dlsym will find the
1602 f = 1
1603 symbol whereas we want the
1604 f = 2
1605 symbol. We therefore need to keep our own SO handle list, and
1606 try SOs in the right order. */
1607
1608 typedef
1609 struct _OpenedSO {
1610 struct _OpenedSO* next;
1611 void *handle;
1612 }
1613 OpenedSO;
1614
1615 /* A list thereof. */
1616 static OpenedSO* openedSOs = NULL;
1617
1618 static const char *
1619 internal_dlopen(const char *dll_name)
1620 {
1621 OpenedSO* o_so;
1622 void *hdl;
1623 const char *errmsg;
1624 char *errmsg_copy;
1625
1626 // omitted: RTLD_NOW
1627 // see http://www.haskell.org/pipermail/cvs-ghc/2007-September/038570.html
1628 IF_DEBUG(linker,
1629 debugBelch("internal_dlopen: dll_name = '%s'\n", dll_name));
1630
1631 //-------------- Begin critical section ------------------
1632 // This critical section is necessary because dlerror() is not
1633 // required to be reentrant (see POSIX -- IEEE Std 1003.1-2008)
1634 // Also, the error message returned must be copied to preserve it
1635 // (see POSIX also)
1636
1637 ACQUIRE_LOCK(&dl_mutex);
1638 hdl = dlopen(dll_name, RTLD_LAZY | RTLD_GLOBAL);
1639
1640 errmsg = NULL;
1641 if (hdl == NULL) {
1642 /* dlopen failed; return a ptr to the error msg. */
1643 errmsg = dlerror();
1644 if (errmsg == NULL) errmsg = "addDLL: unknown error";
1645 errmsg_copy = stgMallocBytes(strlen(errmsg)+1, "addDLL");
1646 strcpy(errmsg_copy, errmsg);
1647 errmsg = errmsg_copy;
1648 }
1649 o_so = stgMallocBytes(sizeof(OpenedSO), "addDLL");
1650 o_so->handle = hdl;
1651 o_so->next = openedSOs;
1652 openedSOs = o_so;
1653
1654 RELEASE_LOCK(&dl_mutex);
1655 //--------------- End critical section -------------------
1656
1657 return errmsg;
1658 }
1659
1660 static void *
1661 internal_dlsym(void *hdl, const char *symbol) {
1662 OpenedSO* o_so;
1663 void *v;
1664
1665 // We acquire dl_mutex as concurrent dl* calls may alter dlerror
1666 ACQUIRE_LOCK(&dl_mutex);
1667 dlerror();
1668 for (o_so = openedSOs; o_so != NULL; o_so = o_so->next) {
1669 v = dlsym(o_so->handle, symbol);
1670 if (dlerror() == NULL) {
1671 RELEASE_LOCK(&dl_mutex);
1672 return v;
1673 }
1674 }
1675 v = dlsym(hdl, symbol)
1676 RELEASE_LOCK(&dl_mutex);
1677 return v;
1678 }
1679 # endif
1680
1681 const char *
1682 addDLL( pathchar *dll_name )
1683 {
1684 # if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
1685 /* ------------------- ELF DLL loader ------------------- */
1686
1687 #define NMATCH 5
1688 regmatch_t match[NMATCH];
1689 const char *errmsg;
1690 FILE* fp;
1691 size_t match_length;
1692 #define MAXLINE 1000
1693 char line[MAXLINE];
1694 int result;
1695
1696 initLinker();
1697
1698 IF_DEBUG(linker, debugBelch("addDLL: dll_name = '%s'\n", dll_name));
1699 errmsg = internal_dlopen(dll_name);
1700
1701 if (errmsg == NULL) {
1702 return NULL;
1703 }
1704
1705 // GHC Trac ticket #2615
1706 // On some systems (e.g., Gentoo Linux) dynamic files (e.g. libc.so)
1707 // contain linker scripts rather than ELF-format object code. This
1708 // code handles the situation by recognizing the real object code
1709 // file name given in the linker script.
1710 //
1711 // If an "invalid ELF header" error occurs, it is assumed that the
1712 // .so file contains a linker script instead of ELF object code.
1713 // In this case, the code looks for the GROUP ( ... ) linker
1714 // directive. If one is found, the first file name inside the
1715 // parentheses is treated as the name of a dynamic library and the
1716 // code attempts to dlopen that file. If this is also unsuccessful,
1717 // an error message is returned.
1718
1719 // see if the error message is due to an invalid ELF header
1720 IF_DEBUG(linker, debugBelch("errmsg = '%s'\n", errmsg));
1721 result = regexec(&re_invalid, errmsg, (size_t) NMATCH, match, 0);
1722 IF_DEBUG(linker, debugBelch("result = %i\n", result));
1723 if (result == 0) {
1724 // success -- try to read the named file as a linker script
1725 match_length = (size_t) stg_min((match[1].rm_eo - match[1].rm_so),
1726 MAXLINE-1);
1727 strncpy(line, (errmsg+(match[1].rm_so)),match_length);
1728 line[match_length] = '\0'; // make sure string is null-terminated
1729 IF_DEBUG(linker, debugBelch ("file name = '%s'\n", line));
1730 if ((fp = fopen(line, "r")) == NULL) {
1731 return errmsg; // return original error if open fails
1732 }
1733 // try to find a GROUP or INPUT ( ... ) command
1734 while (fgets(line, MAXLINE, fp) != NULL) {
1735 IF_DEBUG(linker, debugBelch("input line = %s", line));
1736 if (regexec(&re_realso, line, (size_t) NMATCH, match, 0) == 0) {
1737 // success -- try to dlopen the first named file
1738 IF_DEBUG(linker, debugBelch("match%s\n",""));
1739 line[match[2].rm_eo] = '\0';
1740 errmsg = internal_dlopen(line+match[2].rm_so);
1741 break;
1742 }
1743 // if control reaches here, no GROUP or INPUT ( ... ) directive
1744 // was found and the original error message is returned to the
1745 // caller
1746 }
1747 fclose(fp);
1748 }
1749 return errmsg;
1750
1751 # elif defined(OBJFORMAT_PEi386)
1752 /* ------------------- Win32 DLL loader ------------------- */
1753
1754 pathchar* buf;
1755 OpenedDLL* o_dll;
1756 HINSTANCE instance;
1757
1758 initLinker();
1759
1760 /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
1761
1762 /* See if we've already got it, and ignore if so. */
1763 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
1764 if (0 == pathcmp(o_dll->name, dll_name))
1765 return NULL;
1766 }
1767
1768 /* The file name has no suffix (yet) so that we can try
1769 both foo.dll and foo.drv
1770
1771 The documentation for LoadLibrary says:
1772 If no file name extension is specified in the lpFileName
1773 parameter, the default library extension .dll is
1774 appended. However, the file name string can include a trailing
1775 point character (.) to indicate that the module name has no
1776 extension. */
1777
1778 buf = stgMallocBytes((pathlen(dll_name) + 10) * sizeof(wchar_t), "addDLL");
1779 swprintf(buf, L"%s.DLL", dll_name);
1780 instance = LoadLibraryW(buf);
1781 if (instance == NULL) {
1782 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1783 // KAA: allow loading of drivers (like winspool.drv)
1784 swprintf(buf, L"%s.DRV", dll_name);
1785 instance = LoadLibraryW(buf);
1786 if (instance == NULL) {
1787 if (GetLastError() != ERROR_MOD_NOT_FOUND) goto error;
1788 // #1883: allow loading of unix-style libfoo.dll DLLs
1789 swprintf(buf, L"lib%s.DLL", dll_name);
1790 instance = LoadLibraryW(buf);
1791 if (instance == NULL) {
1792 goto error;
1793 }
1794 }
1795 }
1796 stgFree(buf);
1797
1798 /* Add this DLL to the list of DLLs in which to search for symbols. */
1799 o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
1800 o_dll->name = pathdup(dll_name);
1801 o_dll->instance = instance;
1802 o_dll->next = opened_dlls;
1803 opened_dlls = o_dll;
1804
1805 return NULL;
1806
1807 error:
1808 stgFree(buf);
1809 sysErrorBelch("%" PATH_FMT, dll_name);
1810
1811 /* LoadLibrary failed; return a ptr to the error msg. */
1812 return "addDLL: could not load DLL";
1813
1814 # else
1815 barf("addDLL: not implemented on this platform");
1816 # endif
1817 }
1818
1819 /* -----------------------------------------------------------------------------
1820 * insert a stable symbol in the hash table
1821 */
1822
1823 void
1824 insertStableSymbol(pathchar* obj_name, char* key, StgPtr p)
1825 {
1826 ghciInsertStrHashTable(obj_name, stablehash, key, getStablePtr(p));
1827 }
1828
1829
1830 /* -----------------------------------------------------------------------------
1831 * insert a symbol in the hash table
1832 */
1833 void
1834 insertSymbol(pathchar* obj_name, char* key, void* data)
1835 {
1836 ghciInsertStrHashTable(obj_name, symhash, key, data);
1837 }
1838
1839 /* -----------------------------------------------------------------------------
1840 * lookup a symbol in the hash table
1841 */
1842 void *
1843 lookupSymbol( char *lbl )
1844 {
1845 void *val;
1846 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s\n", lbl));
1847 initLinker() ;
1848 ASSERT(symhash != NULL);
1849 val = lookupStrHashTable(symhash, lbl);
1850
1851 if (val == NULL) {
1852 IF_DEBUG(linker, debugBelch("lookupSymbol: symbol not found\n"));
1853 # if defined(OBJFORMAT_ELF)
1854 return internal_dlsym(dl_prog_handle, lbl);
1855 # elif defined(OBJFORMAT_MACHO)
1856 # if HAVE_DLFCN_H
1857 /* On OS X 10.3 and later, we use dlsym instead of the old legacy
1858 interface.
1859
1860 HACK: On OS X, all symbols are prefixed with an underscore.
1861 However, dlsym wants us to omit the leading underscore from the
1862 symbol name -- the dlsym routine puts it back on before searching
1863 for the symbol. For now, we simply strip it off here (and ONLY
1864 here).
1865 */
1866 IF_DEBUG(linker, debugBelch("lookupSymbol: looking up %s with dlsym\n", lbl));
1867 ASSERT(lbl[0] == '_');
1868 return internal_dlsym(dl_prog_handle, lbl + 1);
1869 # else
1870 if (NSIsSymbolNameDefined(lbl)) {
1871 NSSymbol symbol = NSLookupAndBindSymbol(lbl);
1872 return NSAddressOfSymbol(symbol);
1873 } else {
1874 return NULL;
1875 }
1876 # endif /* HAVE_DLFCN_H */
1877 # elif defined(OBJFORMAT_PEi386)
1878 void* sym;
1879
1880 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1881 if (sym != NULL) { return sym; };
1882
1883 // Also try looking up the symbol without the @N suffix. Some
1884 // DLLs have the suffixes on their symbols, some don't.
1885 zapTrailingAtSign ( (unsigned char*)lbl );
1886 sym = lookupSymbolInDLLs((unsigned char*)lbl);
1887 if (sym != NULL) { return sym; };
1888 return NULL;
1889
1890 # else
1891 ASSERT(2+2 == 5);
1892 return NULL;
1893 # endif
1894 } else {
1895 IF_DEBUG(linker, debugBelch("lookupSymbol: value of %s is %p\n", lbl, val));
1896 return val;
1897 }
1898 }
1899
1900 /* -----------------------------------------------------------------------------
1901 * Debugging aid: look in GHCi's object symbol tables for symbols
1902 * within DELTA bytes of the specified address, and show their names.
1903 */
1904 #ifdef DEBUG
1905 void ghci_enquire ( char* addr );
1906
1907 void ghci_enquire ( char* addr )
1908 {
1909 int i;
1910 char* sym;
1911 char* a;
1912 const int DELTA = 64;
1913 ObjectCode* oc;
1914
1915 initLinker();
1916
1917 for (oc = objects; oc; oc = oc->next) {
1918 for (i = 0; i < oc->n_symbols; i++) {
1919 sym = oc->symbols[i];
1920 if (sym == NULL) continue;
1921 a = NULL;
1922 if (a == NULL) {
1923 a = lookupStrHashTable(symhash, sym);
1924 }
1925 if (a == NULL) {
1926 // debugBelch("ghci_enquire: can't find %s\n", sym);
1927 }
1928 else if (addr-DELTA <= a && a <= addr+DELTA) {
1929 debugBelch("%p + %3d == `%s'\n", addr, (int)(a - addr), sym);
1930 }
1931 }
1932 }
1933 }
1934 #endif
1935
1936 #ifdef USE_MMAP
1937 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1938
1939 static void *
1940 mmapForLinker (size_t bytes, nat flags, int fd)
1941 {
1942 void *map_addr = NULL;
1943 void *result;
1944 int pagesize, size;
1945 static nat fixed = 0;
1946
1947 IF_DEBUG(linker, debugBelch("mmapForLinker: start\n"));
1948 pagesize = getpagesize();
1949 size = ROUND_UP(bytes, pagesize);
1950
1951 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1952 mmap_again:
1953
1954 if (mmap_32bit_base != 0) {
1955 map_addr = mmap_32bit_base;
1956 }
1957 #endif
1958
1959 IF_DEBUG(linker, debugBelch("mmapForLinker: \tprotection %#0x\n", PROT_EXEC | PROT_READ | PROT_WRITE));
1960 IF_DEBUG(linker, debugBelch("mmapForLinker: \tflags %#0x\n", MAP_PRIVATE | TRY_MAP_32BIT | fixed | flags));
1961 result = mmap(map_addr, size, PROT_EXEC|PROT_READ|PROT_WRITE,
1962 MAP_PRIVATE|TRY_MAP_32BIT|fixed|flags, fd, 0);
1963
1964 if (result == MAP_FAILED) {
1965 sysErrorBelch("mmap %" FMT_Word " bytes at %p",(W_)size,map_addr);
1966 errorBelch("Try specifying an address with +RTS -xm<addr> -RTS");
1967 stg_exit(EXIT_FAILURE);
1968 }
1969
1970 #if !defined(ALWAYS_PIC) && defined(x86_64_HOST_ARCH)
1971 if (mmap_32bit_base != 0) {
1972 if (result == map_addr) {
1973 mmap_32bit_base = (StgWord8*)map_addr + size;
1974 } else {
1975 if ((W_)result > 0x80000000) {
1976 // oops, we were given memory over 2Gb
1977 #if defined(freebsd_HOST_OS) || defined(kfreebsdgnu_HOST_OS) || defined(dragonfly_HOST_OS)
1978 // Some platforms require MAP_FIXED. This is normally
1979 // a bad idea, because MAP_FIXED will overwrite
1980 // existing mappings.
1981 munmap(result,size);
1982 fixed = MAP_FIXED;
1983 goto mmap_again;
1984 #else
1985 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);
1986 #endif
1987 } else {
1988 // hmm, we were given memory somewhere else, but it's
1989 // still under 2Gb so we can use it. Next time, ask
1990 // for memory right after the place we just got some
1991 mmap_32bit_base = (StgWord8*)result + size;
1992 }
1993 }
1994 } else {
1995 if ((W_)result > 0x80000000) {
1996 // oops, we were given memory over 2Gb
1997 // ... try allocating memory somewhere else?;
1998 debugTrace(DEBUG_linker,"MAP_32BIT didn't work; gave us %lu bytes at 0x%p", bytes, result);
1999 munmap(result, size);
2000
2001 // Set a base address and try again... (guess: 1Gb)
2002 mmap_32bit_base = (void*)0x40000000;
2003 goto mmap_again;
2004 }
2005 }
2006 #endif
2007
2008 IF_DEBUG(linker, debugBelch("mmapForLinker: mapped %" FMT_Word " bytes starting at %p\n", (W_)size, result));
2009 IF_DEBUG(linker, debugBelch("mmapForLinker: done\n"));
2010 return result;
2011 }
2012 #endif // USE_MMAP
2013
2014 static ObjectCode*
2015 mkOc( pathchar *path, char *image, int imageSize,
2016 char *archiveMemberName
2017 #ifndef USE_MMAP
2018 #ifdef darwin_HOST_OS
2019 , int misalignment
2020 #endif
2021 #endif
2022 ) {
2023 ObjectCode* oc;
2024
2025 IF_DEBUG(linker, debugBelch("mkOc: start\n"));
2026 oc = stgMallocBytes(sizeof(ObjectCode), "loadArchive(oc)");
2027
2028 # if defined(OBJFORMAT_ELF)
2029 oc->formatName = "ELF";
2030 # elif defined(OBJFORMAT_PEi386)
2031 oc->formatName = "PEi386";
2032 # elif defined(OBJFORMAT_MACHO)
2033 oc->formatName = "Mach-O";
2034 # else
2035 stgFree(oc);
2036 barf("loadObj: not implemented on this platform");
2037 # endif
2038
2039 oc->image = image;
2040 oc->fileName = pathdup(path);
2041
2042 if (archiveMemberName) {
2043 oc->archiveMemberName = stgMallocBytes( strlen(archiveMemberName)+1, "loadObj" );
2044 strcpy(oc->archiveMemberName, archiveMemberName);
2045 }
2046 else {
2047 oc->archiveMemberName = NULL;
2048 }
2049
2050 oc->fileSize = imageSize;
2051 oc->symbols = NULL;
2052 oc->sections = NULL;
2053 oc->proddables = NULL;
2054
2055 #ifndef USE_MMAP
2056 #ifdef darwin_HOST_OS
2057 oc->misalignment = misalignment;
2058 #endif
2059 #endif
2060
2061 /* chain it onto the list of objects */
2062 oc->next = objects;
2063 objects = oc;
2064
2065 IF_DEBUG(linker, debugBelch("mkOc: done\n"));
2066 return oc;
2067 }
2068
2069 HsInt
2070 loadArchive( pathchar *path )
2071 {
2072 ObjectCode* oc;
2073 char *image;
2074 int memberSize;
2075 FILE *f;
2076 int n;
2077 size_t thisFileNameSize;
2078 char *fileName;
2079 size_t fileNameSize;
2080 int isObject, isGnuIndex;
2081 char tmp[20];
2082 char *gnuFileIndex;
2083 int gnuFileIndexSize;
2084 #if defined(darwin_HOST_OS)
2085 int i;
2086 uint32_t nfat_arch, nfat_offset, cputype, cpusubtype;
2087 #if defined(i386_HOST_ARCH)
2088 const uint32_t mycputype = CPU_TYPE_X86;
2089 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_ALL;
2090 #elif defined(x86_64_HOST_ARCH)
2091 const uint32_t mycputype = CPU_TYPE_X86_64;
2092 const uint32_t mycpusubtype = CPU_SUBTYPE_X86_64_ALL;
2093 #elif defined(powerpc_HOST_ARCH)
2094 const uint32_t mycputype = CPU_TYPE_POWERPC;
2095 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
2096 #elif defined(powerpc64_HOST_ARCH)
2097 const uint32_t mycputype = CPU_TYPE_POWERPC64;
2098 const uint32_t mycpusubtype = CPU_SUBTYPE_POWERPC_ALL;
2099 #else
2100 #error Unknown Darwin architecture
2101 #endif
2102 #if !defined(USE_MMAP)
2103 int misalignment;
2104 #endif
2105 #endif
2106
2107 IF_DEBUG(linker, debugBelch("loadArchive: start\n"));
2108 IF_DEBUG(linker, debugBelch("loadArchive: Loading archive `%" PATH_FMT" '\n", path));
2109
2110 if (dynamicByDefault) {
2111 barf("loadArchive called, but using dynlibs by default (%s)", path);
2112 }
2113
2114 gnuFileIndex = NULL;
2115 gnuFileIndexSize = 0;
2116
2117 fileNameSize = 32;
2118 fileName = stgMallocBytes(fileNameSize, "loadArchive(fileName)");
2119
2120 f = pathopen(path, WSTR("rb"));
2121 if (!f)
2122 barf("loadObj: can't read `%s'", path);
2123
2124 /* Check if this is an archive by looking for the magic "!<arch>\n"
2125 * string. Usually, if this fails, we barf and quit. On Darwin however,
2126 * we may have a fat archive, which contains archives for more than
2127 * one architecture. Fat archives start with the magic number 0xcafebabe,
2128 * always stored big endian. If we find a fat_header, we scan through
2129 * the fat_arch structs, searching through for one for our host
2130 * architecture. If a matching struct is found, we read the offset
2131 * of our archive data (nfat_offset) and seek forward nfat_offset bytes
2132 * from the start of the file.
2133 *
2134 * A subtlety is that all of the members of the fat_header and fat_arch
2135 * structs are stored big endian, so we need to call byte order
2136 * conversion functions.
2137 *
2138 * If we find the appropriate architecture in a fat archive, we gobble
2139 * its magic "!<arch>\n" string and continue processing just as if
2140 * we had a single architecture archive.
2141 */
2142
2143 n = fread ( tmp, 1, 8, f );
2144 if (n != 8)
2145 barf("loadArchive: Failed reading header from `%s'", path);
2146 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
2147
2148 #if defined(darwin_HOST_OS)
2149 /* Not a standard archive, look for a fat archive magic number: */
2150 if (ntohl(*(uint32_t *)tmp) == FAT_MAGIC) {
2151 nfat_arch = ntohl(*(uint32_t *)(tmp + 4));
2152 IF_DEBUG(linker, debugBelch("loadArchive: found a fat archive containing %d architectures\n", nfat_arch));
2153 nfat_offset = 0;
2154
2155 for (i = 0; i < (int)nfat_arch; i++) {
2156 /* search for the right arch */
2157 n = fread( tmp, 1, 20, f );
2158 if (n != 8)
2159 barf("loadArchive: Failed reading arch from `%s'", path);
2160 cputype = ntohl(*(uint32_t *)tmp);
2161 cpusubtype = ntohl(*(uint32_t *)(tmp + 4));
2162
2163 if (cputype == mycputype && cpusubtype == mycpusubtype) {
2164 IF_DEBUG(linker, debugBelch("loadArchive: found my archive in a fat archive\n"));
2165 nfat_offset = ntohl(*(uint32_t *)(tmp + 8));
2166 break;
2167 }
2168 }
2169
2170 if (nfat_offset == 0) {
2171 barf ("loadArchive: searched %d architectures, but no host arch found", (int)nfat_arch);
2172 }
2173 else {
2174 n = fseek( f, nfat_offset, SEEK_SET );
2175 if (n != 0)
2176 barf("loadArchive: Failed to seek to arch in `%s'", path);
2177 n = fread ( tmp, 1, 8, f );
2178 if (n != 8)
2179 barf("loadArchive: Failed reading header from `%s'", path);
2180 if (strncmp(tmp, "!<arch>\n", 8) != 0) {
2181 barf("loadArchive: couldn't find archive in `%s' at offset %d", path, nfat_offset);
2182 }
2183 }
2184 }
2185 else {
2186 barf("loadArchive: Neither an archive, nor a fat archive: `%s'", path);
2187 }
2188
2189 #else
2190 barf("loadArchive: Not an archive: `%s'", path);
2191 #endif
2192 }
2193
2194 IF_DEBUG(linker, debugBelch("loadArchive: loading archive contents\n"));
2195
2196 while(1) {
2197 n = fread ( fileName, 1, 16, f );
2198 if (n != 16) {
2199 if (feof(f)) {
2200 IF_DEBUG(linker, debugBelch("loadArchive: EOF while reading from '%" PATH_FMT "'\n", path));
2201 break;
2202 }
2203 else {
2204 barf("loadArchive: Failed reading file name from `%s'", path);
2205 }
2206 }
2207
2208 #if defined(darwin_HOST_OS)
2209 if (strncmp(fileName, "!<arch>\n", 8) == 0) {
2210 IF_DEBUG(linker, debugBelch("loadArchive: found the start of another archive, breaking\n"));
2211 break;
2212 }
2213 #endif
2214
2215 n = fread ( tmp, 1, 12, f );
2216 if (n != 12)
2217 barf("loadArchive: Failed reading mod time from `%s'", path);
2218 n = fread ( tmp, 1, 6, f );
2219 if (n != 6)
2220 barf("loadArchive: Failed reading owner from `%s'", path);
2221 n = fread ( tmp, 1, 6, f );
2222 if (n != 6)
2223 barf("loadArchive: Failed reading group from `%s'", path);
2224 n = fread ( tmp, 1, 8, f );
2225 if (n != 8)
2226 barf("loadArchive: Failed reading mode from `%s'", path);
2227 n = fread ( tmp, 1, 10, f );
2228 if (n != 10)
2229 barf("loadArchive: Failed reading size from `%s'", path);
2230 tmp[10] = '\0';
2231 for (n = 0; isdigit(tmp[n]); n++);
2232 tmp[n] = '\0';
2233 memberSize = atoi(tmp);
2234
2235 IF_DEBUG(linker, debugBelch("loadArchive: size of this archive member is %d\n", memberSize));
2236 n = fread ( tmp, 1, 2, f );
2237 if (n != 2)
2238 barf("loadArchive: Failed reading magic from `%s'", path);
2239 if (strncmp(tmp, "\x60\x0A", 2) != 0)
2240 barf("loadArchive: Failed reading magic from `%s' at %ld. Got %c%c",
2241 path, ftell(f), tmp[0], tmp[1]);
2242
2243 isGnuIndex = 0;
2244 /* Check for BSD-variant large filenames */
2245 if (0 == strncmp(fileName, "#1/", 3)) {
2246 fileName[16] = '\0';
2247 if (isdigit(fileName[3])) {
2248 for (n = 4; isdigit(fileName[n]); n++);
2249 fileName[n] = '\0';
2250 thisFileNameSize = atoi(fileName + 3);
2251 memberSize -= thisFileNameSize;
2252 if (thisFileNameSize >= fileNameSize) {
2253 /* Double it to avoid potentially continually
2254 increasing it by 1 */
2255 fileNameSize = thisFileNameSize * 2;
2256 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
2257 }
2258 n = fread ( fileName, 1, thisFileNameSize, f );
2259 if (n != (int)thisFileNameSize) {
2260 barf("loadArchive: Failed reading filename from `%s'",
2261 path);
2262 }
2263 fileName[thisFileNameSize] = 0;
2264
2265 /* On OS X at least, thisFileNameSize is the size of the
2266 fileName field, not the length of the fileName
2267 itself. */
2268 thisFileNameSize = strlen(fileName);
2269 }
2270 else {
2271 barf("loadArchive: BSD-variant filename size not found while reading filename from `%s'", path);
2272 }
2273 }
2274 /* Check for GNU file index file */
2275 else if (0 == strncmp(fileName, "//", 2)) {
2276 fileName[0] = '\0';
2277 thisFileNameSize = 0;
2278 isGnuIndex = 1;
2279 }
2280 /* Check for a file in the GNU file index */
2281 else if (fileName[0] == '/') {
2282 if (isdigit(fileName[1])) {
2283 int i;
2284
2285 for (n = 2; isdigit(fileName[n]); n++);
2286 fileName[n] = '\0';
2287 n = atoi(fileName + 1);
2288
2289 if (gnuFileIndex == NULL) {
2290 barf("loadArchive: GNU-variant filename without an index while reading from `%s'", path);
2291 }
2292 if (n < 0 || n > gnuFileIndexSize) {
2293 barf("loadArchive: GNU-variant filename offset %d out of range [0..%d] while reading filename from `%s'", n, gnuFileIndexSize, path);
2294 }
2295 if (n != 0 && gnuFileIndex[n - 1] != '\n') {
2296 barf("loadArchive: GNU-variant filename offset %d invalid (range [0..%d]) while reading filename from `%s'", n, gnuFileIndexSize, path);
2297 }
2298 for (i = n; gnuFileIndex[i] != '/'; i++);
2299 thisFileNameSize = i - n;
2300 if (thisFileNameSize >= fileNameSize) {
2301 /* Double it to avoid potentially continually
2302 increasing it by 1 */
2303 fileNameSize = thisFileNameSize * 2;
2304 fileName = stgReallocBytes(fileName, fileNameSize, "loadArchive(fileName)");
2305 }
2306 memcpy(fileName, gnuFileIndex + n, thisFileNameSize);
2307 fileName[thisFileNameSize] = '\0';
2308 }
2309 else if (fileName[1] == ' ') {
2310 fileName[0] = '\0';
2311 thisFileNameSize = 0;
2312 }
2313 else {
2314 barf("loadArchive: GNU-variant filename offset not found while reading filename from `%s'", path);
2315 }
2316 }
2317 /* Finally, the case where the filename field actually contains
2318 the filename */
2319 else {
2320 /* GNU ar terminates filenames with a '/', this allowing
2321 spaces in filenames. So first look to see if there is a
2322 terminating '/'. */
2323 for (thisFileNameSize = 0;
2324 thisFileNameSize < 16;
2325 thisFileNameSize++) {
2326 if (fileName[thisFileNameSize] == '/') {
2327 fileName[thisFileNameSize] = '\0';
2328 break;
2329 }
2330 }
2331 /* If we didn't find a '/', then a space teminates the
2332 filename. Note that if we don't find one, then
2333 thisFileNameSize ends up as 16, and we already have the
2334 '\0' at the end. */
2335 if (thisFileNameSize == 16) {
2336 for (thisFileNameSize = 0;
2337 thisFileNameSize < 16;
2338 thisFileNameSize++) {
2339 if (fileName[thisFileNameSize] == ' ') {
2340 fileName[thisFileNameSize] = '\0';
2341 break;
2342 }
2343 }
2344 }
2345 }
2346
2347 IF_DEBUG(linker,
2348 debugBelch("loadArchive: Found member file `%s'\n", fileName));
2349
2350 isObject = thisFileNameSize >= 2
2351 && fileName[thisFileNameSize - 2] == '.'
2352 && fileName[thisFileNameSize - 1] == 'o';
2353
2354 IF_DEBUG(linker, debugBelch("loadArchive: \tthisFileNameSize = %d\n", (int)thisFileNameSize));
2355 IF_DEBUG(linker, debugBelch("loadArchive: \tisObject = %d\n", isObject));
2356
2357 if (isObject) {
2358 char *archiveMemberName;
2359
2360 IF_DEBUG(linker, debugBelch("loadArchive: Member is an object file...loading...\n"));
2361
2362 /* We can't mmap from the archive directly, as object
2363 files need to be 8-byte aligned but files in .ar
2364 archives are 2-byte aligned. When possible we use mmap
2365 to get some anonymous memory, as on 64-bit platforms if
2366 we use malloc then we can be given memory above 2^32.
2367 In the mmap case we're probably wasting lots of space;
2368 we could do better. */
2369 #if defined(USE_MMAP)
2370 image = mmapForLinker(memberSize, MAP_ANONYMOUS, -1);
2371 #elif defined(mingw32_HOST_OS)
2372 // TODO: We would like to use allocateExec here, but allocateExec
2373 // cannot currently allocate blocks large enough.
2374 {
2375 int offset;
2376 #if defined(x86_64_HOST_ARCH)
2377 /* We get back 8-byte aligned memory (is that guaranteed?), but
2378 the offsets to the sections within the file are all 4 mod 8
2379 (is that guaranteed?). We therefore need to offset the image
2380 by 4, so that all the pointers are 8-byte aligned, so that
2381 pointer tagging works. */
2382 offset = 4;
2383 #else
2384 offset = 0;
2385 #endif
2386 image = VirtualAlloc(NULL, memberSize + offset,
2387 MEM_RESERVE | MEM_COMMIT,
2388 PAGE_EXECUTE_READWRITE);
2389 image += offset;
2390 }
2391 #elif defined(darwin_HOST_OS)
2392 /* See loadObj() */
2393 misalignment = machoGetMisalignment(f);
2394 image = stgMallocBytes(memberSize + misalignment, "loadArchive(image)");
2395 image += misalignment;
2396 #else
2397 image = stgMallocBytes(memberSize, "loadArchive(image)");
2398 #endif
2399 n = fread ( image, 1, memberSize, f );
2400 if (n != memberSize) {
2401 barf("loadArchive: error whilst reading `%s'", path);
2402 }
2403
2404 archiveMemberName = stgMallocBytes(pathlen(path) + thisFileNameSize + 3,
2405 "loadArchive(file)");
2406 sprintf(archiveMemberName, "%" PATH_FMT "(%.*s)",
2407 path, (int)thisFileNameSize, fileName);
2408
2409 oc = mkOc(path, image, memberSize, archiveMemberName
2410 #ifndef USE_MMAP
2411 #ifdef darwin_HOST_OS
2412 , misalignment
2413 #endif
2414 #endif
2415 );
2416
2417 stgFree(archiveMemberName);
2418
2419 if (0 == loadOc(oc)) {
2420 stgFree(fileName);
2421 return 0;
2422 }
2423 }
2424 else if (isGnuIndex) {
2425 if (gnuFileIndex != NULL) {
2426 barf("loadArchive: GNU-variant index found, but already have an index, while reading filename from `%s'", path);
2427 }
2428 IF_DEBUG(linker, debugBelch("loadArchive: Found GNU-variant file index\n"));
2429 #ifdef USE_MMAP
2430 gnuFileIndex = mmapForLinker(memberSize + 1, MAP_ANONYMOUS, -1);
2431 #else
2432 gnuFileIndex = stgMallocBytes(memberSize + 1, "loadArchive(image)");
2433 #endif
2434 n = fread ( gnuFileIndex, 1, memberSize, f );
2435 if (n != memberSize) {
2436 barf("loadArchive: error whilst reading `%s'", path);
2437 }
2438 gnuFileIndex[memberSize] = '/';
2439 gnuFileIndexSize = memberSize;
2440 }
2441 else {
2442 IF_DEBUG(linker, debugBelch("loadArchive: '%s' does not appear to be an object file\n", fileName));
2443 n = fseek(f, memberSize, SEEK_CUR);
2444 if (n != 0)
2445 barf("loadArchive: error whilst seeking by %d in `%s'",
2446 memberSize, path);
2447 }
2448
2449 /* .ar files are 2-byte aligned */
2450 if (memberSize % 2) {
2451 IF_DEBUG(linker, debugBelch("loadArchive: trying to read one pad byte\n"));
2452 n = fread ( tmp, 1, 1, f );
2453 if (n != 1) {
2454 if (feof(f)) {
2455 IF_DEBUG(linker, debugBelch("loadArchive: found EOF while reading one pad byte\n"));
2456 break;
2457 }
2458 else {
2459 barf("loadArchive: Failed reading padding from `%s'", path);
2460 }
2461 }
2462 IF_DEBUG(linker, debugBelch("loadArchive: successfully read one pad byte\n"));
2463 }
2464 IF_DEBUG(linker, debugBelch("loadArchive: reached end of archive loading while loop\n"));
2465 }
2466
2467 fclose(f);
2468
2469 stgFree(fileName);
2470 if (gnuFileIndex != NULL) {
2471 #ifdef USE_MMAP
2472 munmap(gnuFileIndex, gnuFileIndexSize + 1);
2473 #else
2474 stgFree(gnuFileIndex);
2475 #endif
2476 }
2477
2478 IF_DEBUG(linker, debugBelch("loadArchive: done\n"));
2479 return 1;
2480 }
2481
2482 /* -----------------------------------------------------------------------------
2483 * Load an obj (populate the global symbol table, but don't resolve yet)
2484 *
2485 * Returns: 1 if ok, 0 on error.
2486 */
2487 HsInt
2488 loadObj( pathchar *path )
2489 {
2490 ObjectCode* oc;
2491 char *image;
2492 int fileSize;
2493 struct_stat st;
2494 int r;
2495 #ifdef USE_MMAP
2496 int fd;
2497 #else
2498 FILE *f;
2499 # if defined(darwin_HOST_OS)
2500 int misalignment;
2501 # endif
2502 #endif
2503 IF_DEBUG(linker, debugBelch("loadObj %" PATH_FMT "\n", path));
2504
2505 if (dynamicByDefault) {
2506 barf("loadObj called, but using dynlibs by default (%s)", path);
2507 }
2508
2509 initLinker();
2510
2511 /* debugBelch("loadObj %s\n", path ); */
2512
2513 /* Check that we haven't already loaded this object.
2514 Ignore requests to load multiple times */
2515 {
2516 ObjectCode *o;
2517 int is_dup = 0;
2518 for (o = objects; o; o = o->next) {
2519 if (0 == pathcmp(o->fileName, path)) {
2520 is_dup = 1;
2521 break; /* don't need to search further */
2522 }
2523 }
2524 if (is_dup) {
2525 IF_DEBUG(linker, debugBelch(
2526 "GHCi runtime linker: warning: looks like you're trying to load the\n"
2527 "same object file twice:\n"
2528 " %" PATH_FMT "\n"
2529 "GHCi will ignore this, but be warned.\n"
2530 , path));
2531 return 1; /* success */
2532 }
2533 }
2534
2535 r = pathstat(path, &st);
2536 if (r == -1) {
2537 IF_DEBUG(linker, debugBelch("File doesn't exist\n"));
2538 return 0;
2539 }
2540
2541 fileSize = st.st_size;
2542
2543 #ifdef USE_MMAP
2544 /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
2545
2546 #if defined(openbsd_HOST_OS)
2547 fd = open(path, O_RDONLY, S_IRUSR);
2548 #else
2549 fd = open(path, O_RDONLY);
2550 #endif
2551 if (fd == -1)
2552 barf("loadObj: can't open `%s'", path);
2553
2554 image = mmapForLinker(fileSize, 0, fd);
2555
2556 close(fd);
2557
2558 #else /* !USE_MMAP */
2559 /* load the image into memory */
2560 f = pathopen(path, WSTR("rb"));
2561 if (!f)
2562 barf("loadObj: can't read `%" PATH_FMT "'", path);
2563
2564 # if defined(mingw32_HOST_OS)
2565 // TODO: We would like to use allocateExec here, but allocateExec
2566 // cannot currently allocate blocks large enough.
2567 {
2568 int offset;
2569 #if defined(x86_64_HOST_ARCH)
2570 /* We get back 8-byte aligned memory (is that guaranteed?), but
2571 the offsets to the sections within the file are all 4 mod 8
2572 (is that guaranteed?). We therefore need to offset the image
2573 by 4, so that all the pointers are 8-byte aligned, so that
2574 pointer tagging works. */
2575 offset = 4;
2576 #else
2577 offset = 0;
2578 #endif
2579 image = VirtualAlloc(NULL, fileSize + offset, MEM_RESERVE | MEM_COMMIT,
2580 PAGE_EXECUTE_READWRITE);
2581 image += offset;
2582 }
2583 # elif defined(darwin_HOST_OS)
2584 // In a Mach-O .o file, all sections can and will be misaligned
2585 // if the total size of the headers is not a multiple of the
2586 // desired alignment. This is fine for .o files that only serve
2587 // as input for the static linker, but it's not fine for us,
2588 // as SSE (used by gcc for floating point) and Altivec require
2589 // 16-byte alignment.
2590 // We calculate the correct alignment from the header before
2591 // reading the file, and then we misalign image on purpose so
2592 // that the actual sections end up aligned again.
2593 misalignment = machoGetMisalignment(f);
2594 image = stgMallocBytes(fileSize + misalignment, "loadObj(image)");
2595 image += misalignment;
2596 # else
2597 image = stgMallocBytes(fileSize, "loadObj(image)");
2598 # endif
2599
2600 {
2601 int n;
2602 n = fread ( image, 1, fileSize, f );
2603 if (n != fileSize)
2604 barf("loadObj: error whilst reading `%s'", path);
2605 }
2606 fclose(f);
2607 #endif /* USE_MMAP */
2608
2609 oc = mkOc(path, image, fileSize, NULL
2610 #ifndef USE_MMAP
2611 #ifdef darwin_HOST_OS
2612 , misalignment
2613 #endif
2614 #endif
2615 );
2616
2617 return loadOc(oc);
2618 }
2619
2620 static HsInt
2621 loadOc( ObjectCode* oc ) {
2622 int r;
2623
2624 IF_DEBUG(linker, debugBelch("loadOc: start\n"));
2625
2626 # if defined(OBJFORMAT_MACHO) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH))
2627 r = ocAllocateSymbolExtras_MachO ( oc );
2628 if (!r) {
2629 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_MachO failed\n"));
2630 return r;
2631 }
2632 # elif defined(OBJFORMAT_ELF) && (defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH))
2633 r = ocAllocateSymbolExtras_ELF ( oc );
2634 if (!r) {
2635 IF_DEBUG(linker, debugBelch("loadOc: ocAllocateSymbolExtras_ELF failed\n"));
2636 return r;
2637 }
2638 #endif
2639
2640 /* verify the in-memory image */
2641 # if defined(OBJFORMAT_ELF)
2642 r = ocVerifyImage_ELF ( oc );
2643 # elif defined(OBJFORMAT_PEi386)
2644 r = ocVerifyImage_PEi386 ( oc );
2645 # elif defined(OBJFORMAT_MACHO)
2646 r = ocVerifyImage_MachO ( oc );
2647 # else
2648 barf("loadObj: no verify method");
2649 # endif
2650 if (!r) {
2651 IF_DEBUG(linker, debugBelch("loadOc: ocVerifyImage_* failed\n"));
2652 return r;
2653 }
2654
2655 /* build the symbol list for this image */
2656 # if defined(OBJFORMAT_ELF)
2657 r = ocGetNames_ELF ( oc );
2658 # elif defined(OBJFORMAT_PEi386)
2659 r = ocGetNames_PEi386 ( oc );
2660 # elif defined(OBJFORMAT_MACHO)
2661 r = ocGetNames_MachO ( oc );
2662 # else
2663 barf("loadObj: no getNames method");
2664 # endif
2665 if (!r) {
2666 IF_DEBUG(linker, debugBelch("loadOc: ocGetNames_* failed\n"));
2667 return r;
2668 }
2669
2670 /* loaded, but not resolved yet */
2671 oc->status = OBJECT_LOADED;
2672 IF_DEBUG(linker, debugBelch("loadOc: done.\n"));
2673
2674 return 1;
2675 }
2676
2677 /* -----------------------------------------------------------------------------
2678 * resolve all the currently unlinked objects in memory
2679 *
2680 * Returns: 1 if ok, 0 on error.
2681 */
2682 HsInt
2683 resolveObjs( void )
2684 {
2685 ObjectCode *oc;
2686 int r;
2687
2688 IF_DEBUG(linker, debugBelch("resolveObjs: start\n"));
2689 initLinker();
2690
2691 for (oc = objects; oc; oc = oc->next) {
2692 if (oc->status != OBJECT_RESOLVED) {
2693 # if defined(OBJFORMAT_ELF)
2694 r = ocResolve_ELF ( oc );
2695 # elif defined(OBJFORMAT_PEi386)
2696 r = ocResolve_PEi386 ( oc );
2697 # elif defined(OBJFORMAT_MACHO)
2698 r = ocResolve_MachO ( oc );
2699 # else
2700 barf("resolveObjs: not implemented on this platform");
2701 # endif
2702 if (!r) { return r; }
2703 oc->status = OBJECT_RESOLVED;
2704 }
2705 }
2706 IF_DEBUG(linker, debugBelch("resolveObjs: done\n"));
2707 return 1;
2708 }
2709
2710 /* -----------------------------------------------------------------------------
2711 * delete an object from the pool
2712 */
2713 HsInt
2714 unloadObj( pathchar *path )
2715 {
2716 ObjectCode *oc, *prev;
2717 HsBool unloadedAnyObj = HS_BOOL_FALSE;
2718
2719 ASSERT(symhash != NULL);
2720 ASSERT(objects != NULL);
2721
2722 initLinker();
2723
2724 prev = NULL;
2725 for (oc = objects; oc; prev = oc, oc = oc->next) {
2726 if (!pathcmp(oc->fileName,path)) {
2727
2728 /* Remove all the mappings for the symbols within this
2729 * object..
2730 */
2731 {
2732 int i;
2733 for (i = 0; i < oc->n_symbols; i++) {
2734 if (oc->symbols[i] != NULL) {
2735 removeStrHashTable(symhash, oc->symbols[i], NULL);
2736 }
2737 }
2738 }
2739
2740 if (prev == NULL) {
2741 objects = oc->next;
2742 } else {
2743 prev->next = oc->next;
2744 }
2745
2746 // We're going to leave this in place, in case there are
2747 // any pointers from the heap into it:
2748 // #ifdef mingw32_HOST_OS
2749 // If uncommenting, note that currently oc->image is
2750 // not the right address to free on Win64, as we added
2751 // 4 bytes of padding at the start
2752 // VirtualFree(oc->image);
2753 // #else
2754 // stgFree(oc->image);
2755 // #endif
2756 stgFree(oc->fileName);
2757 stgFree(oc->archiveMemberName);
2758 stgFree(oc->symbols);
2759 stgFree(oc->sections);
2760 stgFree(oc);
2761
2762 /* This could be a member of an archive so continue
2763 * unloading other members. */
2764 unloadedAnyObj = HS_BOOL_TRUE;
2765 }
2766 }
2767
2768 if (unloadedAnyObj) {
2769 return 1;
2770 }
2771 else {
2772 errorBelch("unloadObj: can't find `%" PATH_FMT "' to unload", path);
2773 return 0;
2774 }
2775 }
2776
2777 /* -----------------------------------------------------------------------------
2778 * Sanity checking. For each ObjectCode, maintain a list of address ranges
2779 * which may be prodded during relocation, and abort if we try and write
2780 * outside any of these.
2781 */
2782 static void
2783 addProddableBlock ( ObjectCode* oc, void* start, int size )
2784 {
2785 ProddableBlock* pb
2786 = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
2787
2788 IF_DEBUG(linker, debugBelch("addProddableBlock: %p %p %d\n", oc, start, size));
2789 ASSERT(size > 0);
2790 pb->start = start;
2791 pb->size = size;
2792 pb->next = oc->proddables;
2793 oc->proddables = pb;
2794 }
2795
2796 static void
2797 checkProddableBlock (ObjectCode *oc, void *addr, size_t size )
2798 {
2799 ProddableBlock* pb;
2800
2801 for (pb = oc->proddables; pb != NULL; pb = pb->next) {
2802 char* s = (char*)(pb->start);
2803 char* e = s + pb->size;
2804 char* a = (char*)addr;
2805 if (a >= s && (a+size) <= e) return;
2806 }
2807 barf("checkProddableBlock: invalid fixup in runtime linker: %p", addr);
2808 }
2809
2810 /* -----------------------------------------------------------------------------
2811 * Section management.
2812 */
2813 static void
2814 addSection ( ObjectCode* oc, SectionKind kind,
2815 void* start, void* end )
2816 {
2817 Section* s = stgMallocBytes(sizeof(Section), "addSection");
2818 s->start = start;
2819 s->end = end;
2820 s->kind = kind;
2821 s->next = oc->sections;
2822 oc->sections = s;
2823
2824 IF_DEBUG(linker, debugBelch("addSection: %p-%p (size %lld), kind %d\n",
2825 start, ((char*)end)-1, ((long long)(size_t)end) - ((long long)(size_t)start) + 1, kind ));
2826 }
2827
2828
2829 /* --------------------------------------------------------------------------
2830 * Symbol Extras.
2831 * This is about allocating a small chunk of memory for every symbol in the
2832 * object file. We make sure that the SymboLExtras are always "in range" of
2833 * limited-range PC-relative instructions on various platforms by allocating
2834 * them right next to the object code itself.
2835 */
2836
2837 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH)
2838 #if !defined(x86_64_HOST_ARCH) || !defined(mingw32_HOST_OS)
2839
2840 /*
2841 ocAllocateSymbolExtras
2842
2843 Allocate additional space at the end of the object file image to make room
2844 for jump islands (powerpc, x86_64, arm) and GOT entries (x86_64).
2845
2846 PowerPC relative branch instructions have a 24 bit displacement field.
2847 As PPC code is always 4-byte-aligned, this yields a +-32MB range.
2848 If a particular imported symbol is outside this range, we have to redirect
2849 the jump to a short piece of new code that just loads the 32bit absolute
2850 address and jumps there.
2851 On x86_64, PC-relative jumps and PC-relative accesses to the GOT are limited
2852 to 32 bits (+-2GB).
2853
2854 This function just allocates space for one SymbolExtra for every
2855 undefined symbol in the object file. The code for the jump islands is
2856 filled in by makeSymbolExtra below.
2857 */
2858
2859 static int ocAllocateSymbolExtras( ObjectCode* oc, int count, int first )
2860 {
2861 #ifdef USE_MMAP
2862 int pagesize, n, m;
2863 #endif
2864 int aligned;
2865 #ifndef USE_MMAP
2866 int misalignment = 0;
2867 #ifdef darwin_HOST_OS
2868 misalignment = oc->misalignment;
2869 #endif
2870 #endif
2871
2872 if( count > 0 )
2873 {
2874 // round up to the nearest 4
2875 aligned = (oc->fileSize + 3) & ~3;
2876
2877 #ifdef USE_MMAP
2878 pagesize = getpagesize();
2879 n = ROUND_UP( oc->fileSize, pagesize );
2880 m = ROUND_UP( aligned + sizeof (SymbolExtra) * count, pagesize );
2881
2882 /* we try to use spare space at the end of the last page of the
2883 * image for the jump islands, but if there isn't enough space
2884 * then we have to map some (anonymously, remembering MAP_32BIT).
2885 */
2886 if( m > n ) // we need to allocate more pages
2887 {
2888 if (USE_CONTIGUOUS_MMAP)
2889 {
2890 /* Keep image and symbol_extras contiguous */
2891 void *new = mmapForLinker(n + (sizeof(SymbolExtra) * count),
2892 MAP_ANONYMOUS, -1);
2893 if (new)
2894 {
2895 memcpy(new, oc->image, oc->fileSize);
2896 munmap(oc->image, n);
2897 oc->image = new;
2898 oc->symbol_extras = (SymbolExtra *) (oc->image + n);
2899 }
2900 else
2901 oc->symbol_extras = NULL;
2902 }
2903 else
2904 {
2905 oc->symbol_extras = mmapForLinker(sizeof(SymbolExtra) * count,
2906 MAP_ANONYMOUS, -1);
2907 }
2908 }
2909 else
2910 {
2911 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2912 }
2913 #else
2914 oc->image -= misalignment;
2915 oc->image = stgReallocBytes( oc->image,
2916 misalignment +
2917 aligned + sizeof (SymbolExtra) * count,
2918 "ocAllocateSymbolExtras" );
2919 oc->image += misalignment;
2920
2921 oc->symbol_extras = (SymbolExtra *) (oc->image + aligned);
2922 #endif /* USE_MMAP */
2923
2924 memset( oc->symbol_extras, 0, sizeof (SymbolExtra) * count );
2925 }
2926 else
2927 oc->symbol_extras = NULL;
2928
2929 oc->first_symbol_extra = first;
2930 oc->n_symbol_extras = count;
2931
2932 return 1;
2933 }
2934
2935 #endif
2936 #endif // defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH) || defined(arm_HOST_ARCH)
2937
2938 #if defined(arm_HOST_ARCH)
2939
2940 static void
2941 ocFlushInstructionCache( ObjectCode *oc )
2942 {
2943 // Object code
2944 __clear_cache(oc->image, oc->image + oc->fileSize);
2945 // Jump islands
2946 __clear_cache(oc->symbol_extras, &oc->symbol_extras[oc->n_symbol_extras]);
2947 }
2948
2949 #endif
2950
2951 #if defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2952 #if !defined(x86_64_HOST_ARCH) || !defined(mingw32_HOST_OS)
2953
2954 static SymbolExtra* makeSymbolExtra( ObjectCode* oc,
2955 unsigned long symbolNumber,
2956 unsigned long target )
2957 {
2958 SymbolExtra *extra;
2959
2960 ASSERT( symbolNumber >= oc->first_symbol_extra
2961 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
2962
2963 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
2964
2965 #ifdef powerpc_HOST_ARCH
2966 // lis r12, hi16(target)
2967 extra->jumpIsland.lis_r12 = 0x3d80;
2968 extra->jumpIsland.hi_addr = target >> 16;
2969
2970 // ori r12, r12, lo16(target)
2971 extra->jumpIsland.ori_r12_r12 = 0x618c;
2972 extra->jumpIsland.lo_addr = target & 0xffff;
2973
2974 // mtctr r12
2975 extra->jumpIsland.mtctr_r12 = 0x7d8903a6;
2976
2977 // bctr
2978 extra->jumpIsland.bctr = 0x4e800420;
2979 #endif
2980 #ifdef x86_64_HOST_ARCH
2981 // jmp *-14(%rip)
2982 static uint8_t jmp[] = { 0xFF, 0x25, 0xF2, 0xFF, 0xFF, 0xFF };
2983 extra->addr = target;
2984 memcpy(extra->jumpIsland, jmp, 6);
2985 #endif
2986
2987 return extra;
2988 }
2989
2990 #endif
2991 #endif // defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2992
2993 #ifdef arm_HOST_ARCH
2994 static SymbolExtra* makeArmSymbolExtra( ObjectCode* oc,
2995 unsigned long symbolNumber,
2996 unsigned long target,
2997 int fromThumb,
2998 int toThumb )
2999 {
3000 SymbolExtra *extra;
3001
3002 ASSERT( symbolNumber >= oc->first_symbol_extra
3003 && symbolNumber - oc->first_symbol_extra < oc->n_symbol_extras);
3004
3005 extra = &oc->symbol_extras[symbolNumber - oc->first_symbol_extra];
3006
3007 // Make sure instruction mode bit is set properly
3008 if (toThumb)
3009 target |= 1;
3010 else
3011 target &= ~1;
3012
3013 if (!fromThumb) {
3014 // In ARM encoding:
3015 // movw r12, #0
3016 // movt r12, #0
3017 // bx r12
3018 uint32_t code[] = { 0xe300c000, 0xe340c000, 0xe12fff1c };
3019
3020 // Patch lower half-word into movw
3021 code[0] |= ((target>>12) & 0xf) << 16;
3022 code[0] |= target & 0xfff;
3023 // Patch upper half-word into movt
3024 target >>= 16;
3025 code[1] |= ((target>>12) & 0xf) << 16;
3026 code[1] |= target & 0xfff;
3027
3028 memcpy(extra->jumpIsland, code, 12);
3029
3030 } else {
3031 // In Thumb encoding:
3032 // movw r12, #0
3033 // movt r12, #0
3034 // bx r12
3035 uint16_t code[] = { 0xf240, 0x0c00,
3036 0xf2c0, 0x0c00,
3037 0x4760 };
3038
3039 // Patch lower half-word into movw
3040 code[0] |= (target>>12) & 0xf;
3041 code[0] |= ((target>>11) & 0x1) << 10;
3042 code[1] |= ((target>>8) & 0x7) << 12;
3043 code[1] |= target & 0xff;
3044 // Patch upper half-word into movt
3045 target >>= 16;
3046 code[2] |= (target>>12) & 0xf;
3047 code[2] |= ((target>>11) & 0x1) << 10;
3048 code[3] |= ((target>>8) & 0x7) << 12;
3049 code[3] |= target & 0xff;
3050
3051 memcpy(extra->jumpIsland, code, 10);
3052 }
3053
3054 return extra;
3055 }
3056 #endif // arm_HOST_ARCH
3057
3058 /* --------------------------------------------------------------------------
3059 * PowerPC specifics (instruction cache flushing)
3060 * ------------------------------------------------------------------------*/
3061
3062 #ifdef powerpc_HOST_ARCH
3063 /*
3064 ocFlushInstructionCache
3065
3066 Flush the data & instruction caches.
3067 Because the PPC has split data/instruction caches, we have to
3068 do that whenever we modify code at runtime.
3069 */
3070
3071 static void
3072 ocFlushInstructionCacheFrom(void* begin, size_t length)
3073 {
3074 size_t n = (length + 3) / 4;
3075 unsigned long* p = begin;
3076
3077 while (n--)
3078 {
3079 __asm__ volatile ( "dcbf 0,%0\n\t"
3080 "sync\n\t"
3081 "icbi 0,%0"
3082 :
3083 : "r" (p)
3084 );
3085 p++;
3086 }
3087 __asm__ volatile ( "sync\n\t"
3088 "isync"
3089 );
3090 }
3091
3092 static void
3093 ocFlushInstructionCache( ObjectCode *oc )
3094 {
3095 /* The main object code */
3096 ocFlushInstructionCacheFrom(oc->image
3097 #ifdef darwin_HOST_OS
3098 + oc->misalignment
3099 #endif
3100 , oc->fileSize);
3101
3102 /* Jump Islands */
3103 ocFlushInstructionCacheFrom(oc->symbol_extras, sizeof(SymbolExtra) * oc->n_symbol_extras);
3104 }
3105 #endif /* powerpc_HOST_ARCH */
3106
3107
3108 /* --------------------------------------------------------------------------
3109 * PEi386 specifics (Win32 targets)
3110 * ------------------------------------------------------------------------*/
3111
3112 /* The information for this linker comes from
3113 Microsoft Portable Executable
3114 and Common Object File Format Specification
3115 revision 5.1 January 1998
3116 which SimonM says comes from the MS Developer Network CDs.
3117
3118 It can be found there (on older CDs), but can also be found
3119 online at:
3120
3121 http://www.microsoft.com/hwdev/hardware/PECOFF.asp
3122
3123 (this is Rev 6.0 from February 1999).
3124
3125 Things move, so if that fails, try searching for it via
3126
3127 http://www.google.com/search?q=PE+COFF+specification
3128
3129 The ultimate reference for the PE format is the Winnt.h
3130 header file that comes with the Platform SDKs; as always,
3131 implementations will drift wrt their documentation.
3132
3133 A good background article on the PE format is Matt Pietrek's
3134 March 1994 article in Microsoft System Journal (MSJ)
3135 (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
3136 Win32 Portable Executable File Format." The info in there
3137 has recently been updated in a two part article in
3138 MSDN magazine, issues Feb and March 2002,
3139 "Inside Windows: An In-Depth Look into the Win32 Portable
3140 Executable File Format"
3141
3142 John Levine's book "Linkers and Loaders" contains useful
3143 info on PE too.
3144 */
3145
3146
3147 #if defined(OBJFORMAT_PEi386)
3148
3149
3150
3151 typedef unsigned char UChar;
3152 typedef unsigned short UInt16;
3153 typedef unsigned int UInt32;
3154 typedef int Int32;
3155 typedef unsigned long long int UInt64;
3156
3157
3158 typedef
3159 struct {
3160 UInt16 Machine;
3161 UInt16 NumberOfSections;
3162 UInt32 TimeDateStamp;
3163 UInt32 PointerToSymbolTable;
3164 UInt32 NumberOfSymbols;
3165 UInt16 SizeOfOptionalHeader;
3166 UInt16 Characteristics;
3167 }
3168 COFF_header;
3169
3170 #define sizeof_COFF_header 20
3171
3172
3173 typedef
3174 struct {
3175 UChar Name[8];
3176 UInt32 VirtualSize;
3177 UInt32 VirtualAddress;
3178 UInt32 SizeOfRawData;
3179 UInt32 PointerToRawData;
3180 UInt32 PointerToRelocations;
3181 UInt32 PointerToLinenumbers;
3182 UInt16 NumberOfRelocations;
3183 UInt16 NumberOfLineNumbers;
3184 UInt32 Characteristics;
3185 }
3186 COFF_section;
3187
3188 #define sizeof_COFF_section 40
3189
3190
3191 typedef
3192 struct {
3193 UChar Name[8];
3194 UInt32 Value;
3195 UInt16 SectionNumber;
3196 UInt16 Type;
3197 UChar StorageClass;
3198 UChar NumberOfAuxSymbols;
3199 }
3200 COFF_symbol;
3201
3202 #define sizeof_COFF_symbol 18
3203
3204
3205 typedef
3206 struct {
3207 UInt32 VirtualAddress;
3208 UInt32 SymbolTableIndex;
3209 UInt16 Type;
3210 }
3211 COFF_reloc;
3212
3213 #define sizeof_COFF_reloc 10
3214
3215
3216 /* From PE spec doc, section 3.3.2 */
3217 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
3218 windows.h -- for the same purpose, but I want to know what I'm
3219 getting, here. */
3220 #define MYIMAGE_FILE_RELOCS_STRIPPED 0x0001
3221 #define MYIMAGE_FILE_EXECUTABLE_IMAGE 0x0002
3222 #define MYIMAGE_FILE_DLL 0x2000
3223 #define MYIMAGE_FILE_SYSTEM 0x1000
3224 #define MYIMAGE_FILE_BYTES_REVERSED_HI 0x8000
3225 #define MYIMAGE_FILE_BYTES_REVERSED_LO 0x0080
3226 #define MYIMAGE_FILE_32BIT_MACHINE 0x0100
3227
3228 /* From PE spec doc, section 5.4.2 and 5.4.4 */
3229 #define MYIMAGE_SYM_CLASS_EXTERNAL 2
3230 #define MYIMAGE_SYM_CLASS_STATIC 3
3231 #define MYIMAGE_SYM_UNDEFINED 0
3232
3233 /* From PE spec doc, section 4.1 */
3234 #define MYIMAGE_SCN_CNT_CODE 0x00000020
3235 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
3236 #define MYIMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
3237
3238 /* From PE spec doc, section 5.2.1 */
3239 #define MYIMAGE_REL_I386_DIR32 0x0006
3240 #define MYIMAGE_REL_I386_REL32 0x0014
3241
3242
3243 /* We use myindex to calculate array addresses, rather than
3244 simply doing the normal subscript thing. That's because
3245 some of the above structs have sizes which are not
3246 a whole number of words. GCC rounds their sizes up to a
3247 whole number of words, which means that the address calcs
3248 arising from using normal C indexing or pointer arithmetic
3249 are just plain wrong. Sigh.
3250 */
3251 static UChar *
3252 myindex ( int scale, void* base, int index )
3253 {
3254 return
3255 ((UChar*)base) + scale * index;
3256 }
3257
3258
3259 static void
3260 printName ( UChar* name, UChar* strtab )
3261 {
3262 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3263 UInt32 strtab_offset = * (UInt32*)(name+4);
3264 debugBelch("%s", strtab + strtab_offset );
3265 } else {
3266 int i;
3267 for (i = 0; i < 8; i++) {
3268 if (name[i] == 0) break;
3269 debugBelch("%c", name[i] );
3270 }
3271 }
3272 }
3273
3274
3275 static void
3276 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
3277 {
3278 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3279 UInt32 strtab_offset = * (UInt32*)(name+4);
3280 strncpy ( (char*)dst, (char*)strtab+strtab_offset, dstSize );
3281 dst[dstSize-1] = 0;
3282 } else {
3283 int i = 0;
3284 while (1) {
3285 if (i >= 8) break;
3286 if (name[i] == 0) break;
3287 dst[i] = name[i];
3288 i++;
3289 }
3290 dst[i] = 0;
3291 }
3292 }
3293
3294
3295 static UChar *
3296 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
3297 {
3298 UChar* newstr;
3299 /* If the string is longer than 8 bytes, look in the
3300 string table for it -- this will be correctly zero terminated.
3301 */
3302 if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
3303 UInt32 strtab_offset = * (UInt32*)(name+4);
3304 return ((UChar*)strtab) + strtab_offset;
3305 }
3306 /* Otherwise, if shorter than 8 bytes, return the original,
3307 which by defn is correctly terminated.
3308 */
3309 if (name[7]==0) return name;
3310 /* The annoying case: 8 bytes. Copy into a temporary
3311 (XXX which is never freed ...)
3312 */
3313 newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
3314 ASSERT(newstr);
3315 strncpy((char*)newstr,(char*)name,8);
3316 newstr[8] = 0;
3317 return newstr;
3318 }
3319
3320 /* Getting the name of a section is mildly tricky, so we make a
3321 function for it. Sadly, in one case we have to copy the string
3322 (when it is exactly 8 bytes long there's no trailing '\0'), so for
3323 consistency we *always* copy the string; the caller must free it
3324 */
3325 static char *
3326 cstring_from_section_name (UChar* name, UChar* strtab)
3327 {
3328 char *newstr;
3329
3330 if (name[0]=='/') {
3331 int strtab_offset = strtol((char*)name+1,NULL,10);
3332 int len = strlen(((char*)strtab) + strtab_offset);
3333
3334 newstr = stgMallocBytes(len+1, "cstring_from_section_symbol_name");
3335 strcpy((char*)newstr, (char*)((UChar*)strtab) + strtab_offset);
3336 return newstr;
3337 }
3338 else
3339 {
3340 newstr = stgMallocBytes(9, "cstring_from_section_symbol_name");
3341 ASSERT(newstr);
3342 strncpy((char*)newstr,(char*)name,8);
3343 newstr[8] = 0;
3344 return newstr;
3345 }
3346 }
3347
3348 /* Just compares the short names (first 8 chars) */
3349 static COFF_section *
3350 findPEi386SectionCalled ( ObjectCode* oc, UChar* name )
3351 {
3352 int i;
3353 COFF_header* hdr
3354 = (COFF_header*)(oc->image);
3355 COFF_section* sectab
3356 = (COFF_section*) (
3357 ((UChar*)(oc->image))
3358 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3359 );
3360 for (i = 0; i < hdr->NumberOfSections; i++) {
3361 UChar* n1;
3362 UChar* n2;
3363 COFF_section* section_i
3364 = (COFF_section*)
3365 myindex ( sizeof_COFF_section, sectab, i );
3366 n1 = (UChar*) &(section_i->Name);
3367 n2 = name;
3368 if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
3369 n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
3370 n1[6]==n2[6] && n1[7]==n2[7])
3371 return section_i;
3372 }
3373
3374 return NULL;
3375 }
3376
3377 static void
3378 zapTrailingAtSign ( UChar* sym )
3379 {
3380 # define my_isdigit(c) ((c) >= '0' && (c) <= '9')
3381 int i, j;
3382 if (sym[0] == 0) return;
3383 i = 0;
3384 while (sym[i] != 0) i++;
3385 i--;
3386 j = i;
3387 while (j > 0 && my_isdigit(sym[j])) j--;
3388 if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
3389 # undef my_isdigit
3390 }
3391
3392 static void *
3393 lookupSymbolInDLLs ( UChar *lbl )
3394 {
3395 OpenedDLL* o_dll;
3396 void *sym;
3397
3398 for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
3399 /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
3400
3401 if (lbl[0] == '_') {
3402 /* HACK: if the name has an initial underscore, try stripping
3403 it off & look that up first. I've yet to verify whether there's
3404 a Rule that governs whether an initial '_' *should always* be
3405 stripped off when mapping from import lib name to the DLL name.
3406 */
3407 sym = GetProcAddress(o_dll->instance, (char*)(lbl+1));
3408 if (sym != NULL) {
3409 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
3410 return sym;
3411 }
3412 }
3413 sym = GetProcAddress(o_dll->instance, (char*)lbl);
3414 if (sym != NULL) {
3415 /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
3416 return sym;
3417 }
3418 }
3419 return NULL;
3420 }
3421
3422
3423 static int
3424 ocVerifyImage_PEi386 ( ObjectCode* oc )
3425 {
3426 int i;
3427 UInt32 j, noRelocs;
3428 COFF_header* hdr;
3429 COFF_section* sectab;
3430 COFF_symbol* symtab;
3431 UChar* strtab;
3432 /* debugBelch("\nLOADING %s\n", oc->fileName); */
3433 hdr = (COFF_header*)(oc->image);
3434 sectab = (COFF_section*) (
3435 ((UChar*)(oc->image))
3436 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3437 );
3438 symtab = (COFF_symbol*) (
3439 ((UChar*)(oc->image))
3440 + hdr->PointerToSymbolTable
3441 );
3442 strtab = ((UChar*)symtab)
3443 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3444
3445 #if defined(i386_HOST_ARCH)
3446 if (hdr->Machine != 0x14c) {
3447 errorBelch("%" PATH_FMT ": Not x86 PEi386", oc->fileName);
3448 return 0;
3449 }
3450 #elif defined(x86_64_HOST_ARCH)
3451 if (hdr->Machine != 0x8664) {
3452 errorBelch("%" PATH_FMT ": Not x86_64 PEi386", oc->fileName);
3453 return 0;
3454 }
3455 #else
3456 errorBelch("PEi386 not supported on this arch");
3457 #endif
3458
3459 if (hdr->SizeOfOptionalHeader != 0) {
3460 errorBelch("%" PATH_FMT ": PEi386 with nonempty optional header", oc->fileName);
3461 return 0;
3462 }
3463 if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
3464 (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
3465 (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
3466 (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
3467 errorBelch("%" PATH_FMT ": Not a PEi386 object file", oc->fileName);
3468 return 0;
3469 }
3470 if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
3471 /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
3472 errorBelch("%" PATH_FMT ": Invalid PEi386 word size or endiannness: %d",
3473 oc->fileName,
3474 (int)(hdr->Characteristics));
3475 return 0;
3476 }
3477 /* If the string table size is way crazy, this might indicate that
3478 there are more than 64k relocations, despite claims to the
3479 contrary. Hence this test. */
3480 /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
3481 #if 0
3482 if ( (*(UInt32*)strtab) > 600000 ) {
3483 /* Note that 600k has no special significance other than being
3484 big enough to handle the almost-2MB-sized lumps that
3485 constitute HSwin32*.o. */
3486 debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
3487 return 0;
3488 }
3489 #endif
3490
3491 /* No further verification after this point; only debug printing. */
3492 i = 0;
3493 IF_DEBUG(linker, i=1);
3494 if (i == 0) return 1;
3495
3496 debugBelch( "sectab offset = %" FMT_Int "\n", ((UChar*)sectab) - ((UChar*)hdr) );
3497 debugBelch( "symtab offset = %" FMT_Int "\n", ((UChar*)symtab) - ((UChar*)hdr) );
3498 debugBelch( "strtab offset = %" FMT_Int "\n", ((UChar*)strtab) - ((UChar*)hdr) );
3499
3500 debugBelch("\n" );
3501 debugBelch( "Machine: 0x%x\n", (UInt32)(hdr->Machine) );
3502 debugBelch( "# sections: %d\n", (UInt32)(hdr->NumberOfSections) );
3503 debugBelch( "time/date: 0x%x\n", (UInt32)(hdr->TimeDateStamp) );
3504 debugBelch( "symtab offset: %d\n", (UInt32)(hdr->PointerToSymbolTable) );
3505 debugBelch( "# symbols: %d\n", (UInt32)(hdr->NumberOfSymbols) );
3506 debugBelch( "sz of opt hdr: %d\n", (UInt32)(hdr->SizeOfOptionalHeader) );
3507 debugBelch( "characteristics: 0x%x\n", (UInt32)(hdr->Characteristics) );
3508
3509 /* Print the section table. */
3510 debugBelch("\n" );
3511 for (i = 0; i < hdr->NumberOfSections; i++) {
3512 COFF_reloc* reltab;
3513 COFF_section* sectab_i
3514 = (COFF_section*)
3515 myindex ( sizeof_COFF_section, sectab, i );
3516 debugBelch(
3517 "\n"
3518 "section %d\n"
3519 " name `",
3520 i
3521 );
3522 printName ( sectab_i->Name, strtab );
3523 debugBelch(
3524 "'\n"
3525 " vsize %d\n"
3526 " vaddr %d\n"
3527 " data sz %d\n"
3528 " data off %d\n"
3529 " num rel %d\n"
3530 " off rel %d\n"
3531 " ptr raw 0x%x\n",
3532 sectab_i->VirtualSize,
3533 sectab_i->VirtualAddress,
3534 sectab_i->SizeOfRawData,
3535 sectab_i->PointerToRawData,
3536 sectab_i->NumberOfRelocations,
3537 sectab_i->PointerToRelocations,
3538 sectab_i->PointerToRawData
3539 );
3540 reltab = (COFF_reloc*) (
3541 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3542 );
3543
3544 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3545 /* If the relocation field (a short) has overflowed, the
3546 * real count can be found in the first reloc entry.
3547 *
3548 * See Section 4.1 (last para) of the PE spec (rev6.0).
3549 */
3550 COFF_reloc* rel = (COFF_reloc*)
3551 myindex ( sizeof_COFF_reloc, reltab, 0 );
3552 noRelocs = rel->VirtualAddress;
3553 j = 1;
3554 } else {
3555 noRelocs = sectab_i->NumberOfRelocations;
3556 j = 0;
3557 }
3558
3559 for (; j < noRelocs; j++) {
3560 COFF_symbol* sym;
3561 COFF_reloc* rel = (COFF_reloc*)
3562 myindex ( sizeof_COFF_reloc, reltab, j );
3563 debugBelch(
3564 " type 0x%-4x vaddr 0x%-8x name `",
3565 (UInt32)rel->Type,
3566 rel->VirtualAddress );
3567 sym = (COFF_symbol*)
3568 myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
3569 /* Hmm..mysterious looking offset - what's it for? SOF */
3570 printName ( sym->Name, strtab -10 );
3571 debugBelch("'\n" );
3572 }
3573
3574 debugBelch("\n" );
3575 }
3576 debugBelch("\n" );
3577 debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
3578 debugBelch("---START of string table---\n");
3579 for (i = 4; i < *(Int32*)strtab; i++) {
3580 if (strtab[i] == 0)
3581 debugBelch("\n"); else
3582 debugBelch("%c", strtab[i] );
3583 }
3584 debugBelch("--- END of string table---\n");
3585
3586 debugBelch("\n" );
3587 i = 0;
3588 while (1) {
3589 COFF_symbol* symtab_i;
3590 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3591 symtab_i = (COFF_symbol*)
3592 myindex ( sizeof_COFF_symbol, symtab, i );
3593 debugBelch(
3594 "symbol %d\n"
3595 " name `",
3596 i
3597 );
3598 printName ( symtab_i->Name, strtab );
3599 debugBelch(
3600 "'\n"
3601 " value 0x%x\n"
3602 " 1+sec# %d\n"
3603 " type 0x%x\n"
3604 " sclass 0x%x\n"
3605 " nAux %d\n",
3606 symtab_i->Value,
3607 (Int32)(symtab_i->SectionNumber),
3608 (UInt32)symtab_i->Type,
3609 (UInt32)symtab_i->StorageClass,
3610 (UInt32)symtab_i->NumberOfAuxSymbols
3611 );
3612 i += symtab_i->NumberOfAuxSymbols;
3613 i++;
3614 }
3615
3616 debugBelch("\n" );
3617 return 1;
3618 }
3619
3620
3621 static int
3622 ocGetNames_PEi386 ( ObjectCode* oc )
3623 {
3624 COFF_header* hdr;
3625 COFF_section* sectab;
3626 COFF_symbol* symtab;
3627 UChar* strtab;
3628
3629 UChar* sname;
3630 void* addr;
3631 int i;
3632
3633 hdr = (COFF_header*)(oc->image);
3634 sectab = (COFF_section*) (
3635 ((UChar*)(oc->image))
3636 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3637 );
3638 symtab = (COFF_symbol*) (
3639 ((UChar*)(oc->image))
3640 + hdr->PointerToSymbolTable
3641 );
3642 strtab = ((UChar*)(oc->image))
3643 + hdr->PointerToSymbolTable
3644 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3645
3646 /* Allocate space for any (local, anonymous) .bss sections. */
3647
3648 for (i = 0; i < hdr->NumberOfSections; i++) {
3649 UInt32 bss_sz;
3650 UChar* zspace;
3651 COFF_section* sectab_i
3652 = (COFF_section*)
3653 myindex ( sizeof_COFF_section, sectab, i );
3654
3655 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3656
3657 if (0 != strcmp(secname, ".bss")) {
3658 stgFree(secname);
3659 continue;
3660 }
3661
3662 stgFree(secname);
3663
3664 /* sof 10/05: the PE spec text isn't too clear regarding what
3665 * the SizeOfRawData field is supposed to hold for object
3666 * file sections containing just uninitialized data -- for executables,
3667 * it is supposed to be zero; unclear what it's supposed to be
3668 * for object files. However, VirtualSize is guaranteed to be
3669 * zero for object files, which definitely suggests that SizeOfRawData
3670 * will be non-zero (where else would the size of this .bss section be
3671 * stored?) Looking at the COFF_section info for incoming object files,
3672 * this certainly appears to be the case.
3673 *
3674 * => I suspect we've been incorrectly handling .bss sections in (relocatable)
3675 * object files up until now. This turned out to bite us with ghc-6.4.1's use
3676 * of gcc-3.4.x, which has started to emit initially-zeroed-out local 'static'
3677 * variable decls into to the .bss section. (The specific function in Q which
3678 * triggered this is libraries/base/cbits/dirUtils.c:__hscore_getFolderPath())
3679 */
3680 if (sectab_i->VirtualSize == 0 && sectab_i->SizeOfRawData == 0) continue;
3681 /* This is a non-empty .bss section. Allocate zeroed space for
3682 it, and set its PointerToRawData field such that oc->image +
3683 PointerToRawData == addr_of_zeroed_space. */
3684 bss_sz = sectab_i->VirtualSize;
3685 if ( bss_sz < sectab_i->SizeOfRawData) { bss_sz = sectab_i->SizeOfRawData; }
3686 zspace = stgCallocBytes(1, bss_sz, "ocGetNames_PEi386(anonymous bss)");
3687 sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
3688 addProddableBlock(oc, zspace, bss_sz);
3689 /* debugBelch("BSS anon section at 0x%x\n", zspace); */
3690 }
3691
3692 /* Copy section information into the ObjectCode. */
3693
3694 for (i = 0; i < hdr->NumberOfSections; i++) {
3695 UChar* start;
3696 UChar* end;
3697 UInt32 sz;
3698
3699 SectionKind kind
3700 = SECTIONKIND_OTHER;
3701 COFF_section* sectab_i
3702 = (COFF_section*)
3703 myindex ( sizeof_COFF_section, sectab, i );
3704
3705 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3706
3707 IF_DEBUG(linker, debugBelch("section name = %s\n", secname ));
3708
3709 # if 0
3710 /* I'm sure this is the Right Way to do it. However, the
3711 alternative of testing the sectab_i->Name field seems to
3712 work ok with Cygwin.
3713 */
3714 if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
3715 sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
3716 kind = SECTIONKIND_CODE_OR_RODATA;
3717 # endif
3718
3719 if (0==strcmp(".text",(char*)secname) ||
3720 0==strcmp(".text.startup",(char*)secname) ||
3721 0==strcmp(".rdata",(char*)secname)||
3722 0==strcmp(".rodata",(char*)secname))
3723 kind = SECTIONKIND_CODE_OR_RODATA;
3724 if (0==strcmp(".data",(char*)secname) ||
3725 0==strcmp(".bss",(char*)secname))
3726 kind = SECTIONKIND_RWDATA;
3727
3728 ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
3729 sz = sectab_i->SizeOfRawData;
3730 if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
3731
3732 start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
3733 end = start + sz - 1;
3734
3735 if (kind == SECTIONKIND_OTHER
3736 /* Ignore sections called which contain stabs debugging
3737 information. */
3738 && 0 != strcmp(".stab", (char*)secname)
3739 && 0 != strcmp(".stabstr", (char*)secname)
3740 /* Ignore sections called which contain exception information. */
3741 && 0 != strcmp(".pdata", (char*)secname)
3742 && 0 != strcmp(".xdata", (char*)secname)
3743 /* ignore constructor section for now */
3744 && 0 != strcmp(".ctors", (char*)secname)
3745 /* ignore section generated from .ident */
3746 && 0!= strncmp(".debug", (char*)secname, 6)
3747 /* ignore unknown section that appeared in gcc 3.4.5(?) */
3748 && 0!= strcmp(".reloc", (char*)secname)
3749 && 0 != strcmp(".rdata$zzz", (char*)secname)
3750 ) {
3751 errorBelch("Unknown PEi386 section name `%s' (while processing: %" PATH_FMT")", secname, oc->fileName);
3752 stgFree(secname);
3753 return 0;
3754 }
3755
3756 if (kind != SECTIONKIND_OTHER && end >= start) {
3757 if ((((size_t)(start)) % sizeof(void *)) != 0) {
3758 barf("Misaligned section: %p", start);
3759 }
3760
3761 addSection(oc, kind, start, end);
3762 addProddableBlock(oc, start, end - start + 1);
3763 }
3764
3765 stgFree(secname);
3766 }
3767
3768 /* Copy exported symbols into the ObjectCode. */
3769
3770 oc->n_symbols = hdr->NumberOfSymbols;
3771 oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3772 "ocGetNames_PEi386(oc->symbols)");
3773 /* Call me paranoid; I don't care. */
3774 for (i = 0; i < oc->n_symbols; i++)
3775 oc->symbols[i] = NULL;
3776
3777 i = 0;
3778 while (1) {
3779 COFF_symbol* symtab_i;
3780 if (i >= (Int32)(hdr->NumberOfSymbols)) break;
3781 symtab_i = (COFF_symbol*)
3782 myindex ( sizeof_COFF_symbol, symtab, i );
3783
3784 addr = NULL;
3785
3786 if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
3787 && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
3788 /* This symbol is global and defined, viz, exported */
3789 /* for MYIMAGE_SYMCLASS_EXTERNAL
3790 && !MYIMAGE_SYM_UNDEFINED,
3791 the address of the symbol is:
3792 address of relevant section + offset in section
3793 */
3794 COFF_section* sectabent
3795 = (COFF_section*) myindex ( sizeof_COFF_section,
3796 sectab,
3797 symtab_i->SectionNumber-1 );
3798 addr = ((UChar*)(oc->image))
3799 + (sectabent->PointerToRawData
3800 + symtab_i->Value);
3801 }
3802 else
3803 if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
3804 && symtab_i->Value > 0) {
3805 /* This symbol isn't in any section at all, ie, global bss.
3806 Allocate zeroed space for it. */
3807 addr = stgCallocBytes(1, symtab_i->Value,
3808 "ocGetNames_PEi386(non-anonymous bss)");
3809 addSection(oc, SECTIONKIND_RWDATA, addr,
3810 ((UChar*)addr) + symtab_i->Value - 1);
3811 addProddableBlock(oc, addr, symtab_i->Value);
3812 /* debugBelch("BSS section at 0x%x\n", addr); */
3813 }
3814
3815 if (addr != NULL ) {
3816 sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
3817 /* debugBelch("addSymbol %p `%s \n", addr,sname); */
3818 IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
3819 ASSERT(i >= 0 && i < oc->n_symbols);
3820 /* cstring_from_COFF_symbol_name always succeeds. */
3821 oc->symbols[i] = (char*)sname;
3822 ghciInsertStrHashTable(oc->fileName, symhash, (char*)sname, addr);
3823 } else {
3824 # if 0
3825 debugBelch(
3826 "IGNORING symbol %d\n"
3827 " name `",
3828 i
3829 );
3830 printName ( symtab_i->Name, strtab );
3831 debugBelch(
3832 "'\n"
3833 " value 0x%x\n"
3834 " 1+sec# %d\n"
3835 " type 0x%x\n"
3836 " sclass 0x%x\n"
3837 " nAux %d\n",
3838 symtab_i->Value,
3839 (Int32)(symtab_i->SectionNumber),
3840 (UInt32)symtab_i->Type,
3841 (UInt32)symtab_i->StorageClass,
3842 (UInt32)symtab_i->NumberOfAuxSymbols
3843 );
3844 # endif
3845 }
3846
3847 i += symtab_i->NumberOfAuxSymbols;
3848 i++;
3849 }
3850
3851 return 1;
3852 }
3853
3854
3855 static int
3856 ocResolve_PEi386 ( ObjectCode* oc )
3857 {
3858 COFF_header* hdr;
3859 COFF_section* sectab;
3860 COFF_symbol* symtab;
3861 UChar* strtab;
3862
3863 UInt32 A;
3864 size_t S;
3865 void * pP;
3866
3867 int i;
3868 UInt32 j, noRelocs;
3869
3870 /* ToDo: should be variable-sized? But is at least safe in the
3871 sense of buffer-overrun-proof. */
3872 UChar symbol[1000];
3873 /* debugBelch("resolving for %s\n", oc->fileName); */
3874
3875 hdr = (COFF_header*)(oc->image);
3876 sectab = (COFF_section*) (
3877 ((UChar*)(oc->image))
3878 + sizeof_COFF_header + hdr->SizeOfOptionalHeader
3879 );
3880 symtab = (COFF_symbol*) (
3881 ((UChar*)(oc->image))
3882 + hdr->PointerToSymbolTable
3883 );
3884 strtab = ((UChar*)(oc->image))
3885 + hdr->PointerToSymbolTable
3886 + hdr->NumberOfSymbols * sizeof_COFF_symbol;
3887
3888 for (i = 0; i < hdr->NumberOfSections; i++) {
3889 COFF_section* sectab_i
3890 = (COFF_section*)
3891 myindex ( sizeof_COFF_section, sectab, i );
3892 COFF_reloc* reltab
3893 = (COFF_reloc*) (
3894 ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
3895 );
3896
3897 char *secname = cstring_from_section_name(sectab_i->Name, strtab);
3898
3899 /* Ignore sections called which contain stabs debugging
3900 information. */
3901 if (0 == strcmp(".stab", (char*)secname)
3902 || 0 == strcmp(".stabstr", (char*)secname)
3903 || 0 == strcmp(".pdata", (char*)secname)
3904 || 0 == strcmp(".xdata", (char*)secname)
3905 || 0 == strcmp(".ctors", (char*)secname)
3906 || 0 == strncmp(".debug", (char*)secname, 6)
3907 || 0 == strcmp(".rdata$zzz", (char*)secname)) {
3908 stgFree(secname);
3909 continue;
3910 }
3911
3912 stgFree(secname);
3913
3914 if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
3915 /* If the relocation field (a short) has overflowed, the
3916 * real count can be found in the first reloc entry.
3917 *
3918 * See Section 4.1 (last para) of the PE spec (rev6.0).
3919 *
3920 * Nov2003 update: the GNU linker still doesn't correctly
3921 * handle the generation of relocatable object files with
3922 * overflown relocations. Hence the output to warn of potential
3923 * troubles.
3924 */
3925 COFF_reloc* rel = (COFF_reloc*)
3926 myindex ( sizeof_COFF_reloc, reltab, 0 );
3927 noRelocs = rel->VirtualAddress;
3928
3929 /* 10/05: we now assume (and check for) a GNU ld that is capable
3930 * of handling object files with (>2^16) of relocs.
3931 */
3932 #if 0
3933 debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
3934 noRelocs);
3935 #endif
3936 j = 1;
3937 } else {
3938 noRelocs = sectab_i->NumberOfRelocations;
3939 j = 0;
3940 }
3941
3942 for (; j < noRelocs; j++) {
3943 COFF_symbol* sym;
3944 COFF_reloc* reltab_j
3945 = (COFF_reloc*)
3946 myindex ( sizeof_COFF_reloc, reltab, j );
3947
3948 /* the location to patch */
3949 pP = (
3950 ((UChar*)(oc->image))
3951 + (sectab_i->PointerToRawData
3952 + reltab_j->VirtualAddress
3953 - sectab_i->VirtualAddress )
3954 );
3955 /* the existing contents of pP */
3956 A = *(UInt32*)pP;
3957 /* the symbol to connect to */
3958 sym = (COFF_symbol*)
3959 myindex ( sizeof_COFF_symbol,
3960 symtab, reltab_j->SymbolTableIndex );
3961 IF_DEBUG(linker,
3962 debugBelch(
3963 "reloc sec %2d num %3d: type 0x%-4x "
3964 "vaddr 0x%-8x name `",
3965 i, j,
3966 (UInt32)reltab_j->Type,
3967 reltab_j->VirtualAddress );
3968 printName ( sym->Name, strtab );
3969 debugBelch("'\n" ));
3970
3971 if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
3972 COFF_section* section_sym
3973 = findPEi386SectionCalled ( oc, sym->Name );
3974 if (!section_sym) {
3975 errorBelch("%" PATH_FMT ": can't find section `%s'", oc->fileName, sym->Name);
3976 return 0;
3977 }
3978 S = ((size_t)(oc->image))
3979 + ((size_t)(section_sym->PointerToRawData))
3980 + ((size_t)(sym->Value));
3981 } else {
3982 copyName ( sym->Name, strtab, symbol, 1000-1 );
3983 S = (size_t) lookupSymbol( (char*)symbol );
3984 if ((void*)S != NULL) goto foundit;
3985 errorBelch("%" PATH_FMT ": unknown symbol `%s'", oc->fileName, symbol);
3986 return 0;
3987 foundit:;
3988 }
3989 /* All supported relocations write at least 4 bytes */
3990 checkProddableBlock(oc, pP, 4);
3991 switch (reltab_j->Type) {
3992 #if defined(i386_HOST_ARCH)
3993 case MYIMAGE_REL_I386_DIR32:
3994 *(UInt32 *)pP = ((UInt32)S) + A;
3995 break;
3996 case MYIMAGE_REL_I386_REL32:
3997 /* Tricky. We have to insert a displacement at
3998 pP which, when added to the PC for the _next_
3999 insn, gives the address of the target (S).
4000 Problem is to know the address of the next insn
4001 when we only know pP. We assume that this
4002 literal field is always the last in the insn,
4003 so that the address of the next insn is pP+4
4004 -- hence the constant 4.
4005 Also I don't know if A should be added, but so
4006 far it has always been zero.
4007
4008 SOF 05/2005: 'A' (old contents of *pP) have been observed
4009 to contain values other than zero (the 'wx' object file
4010 that came with wxhaskell-0.9.4; dunno how it was compiled..).