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