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