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