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