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