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