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