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