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