[project @ 2005-05-05 18:14:27 by sof]
[ghc-hetmet.git] / ghc / 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 #ifdef __linux__
17 #define _GNU_SOURCE
18 #endif
19
20 #include "Rts.h"
21 #include "RtsFlags.h"
22 #include "HsFFI.h"
23 #include "Hash.h"
24 #include "Linker.h"
25 #include "LinkerInternals.h"
26 #include "RtsUtils.h"
27 #include "Schedule.h"
28 #include "Storage.h"
29
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33
34 #include <stdlib.h>
35 #include <string.h>
36
37 #ifdef HAVE_SYS_STAT_H
38 #include <sys/stat.h>
39 #endif
40
41 #if defined(HAVE_DLFCN_H)
42 #include <dlfcn.h>
43 #endif
44
45 #if defined(cygwin32_HOST_OS)
46 #ifdef HAVE_DIRENT_H
47 #include <dirent.h>
48 #endif
49
50 #ifdef HAVE_SYS_TIME_H
51 #include <sys/time.h>
52 #endif
53 #include <regex.h>
54 #include <sys/fcntl.h>
55 #include <sys/termios.h>
56 #include <sys/utime.h>
57 #include <sys/utsname.h>
58 #include <sys/wait.h>
59 #endif
60
61 #if defined(ia64_HOST_ARCH) || defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
62 #define USE_MMAP
63 #include <fcntl.h>
64 #include <sys/mman.h>
65
66 #if defined(openbsd_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
70 #endif
71
72 #endif
73
74 #if defined(linux_HOST_OS) || defined(solaris2_HOST_OS) || defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS) || defined(openbsd_HOST_OS)
75 #  define OBJFORMAT_ELF
76 #elif defined(cygwin32_HOST_OS) || defined (mingw32_HOST_OS)
77 #  define OBJFORMAT_PEi386
78 #  include <windows.h>
79 #  include <math.h>
80 #elif defined(darwin_HOST_OS)
81 #  include <mach-o/ppc/reloc.h>
82 #  define OBJFORMAT_MACHO
83 #  include <mach-o/loader.h>
84 #  include <mach-o/nlist.h>
85 #  include <mach-o/reloc.h>
86 #  include <mach-o/dyld.h>
87 #endif
88
89 /* Hash table mapping symbol names to Symbol */
90 static /*Str*/HashTable *symhash;
91
92 /* List of currently loaded objects */
93 ObjectCode *objects = NULL;     /* initially empty */
94
95 #if defined(OBJFORMAT_ELF)
96 static int ocVerifyImage_ELF    ( ObjectCode* oc );
97 static int ocGetNames_ELF       ( ObjectCode* oc );
98 static int ocResolve_ELF        ( ObjectCode* oc );
99 #if defined(powerpc_HOST_ARCH)
100 static int ocAllocateJumpIslands_ELF ( ObjectCode* oc );
101 #endif
102 #elif defined(OBJFORMAT_PEi386)
103 static int ocVerifyImage_PEi386 ( ObjectCode* oc );
104 static int ocGetNames_PEi386    ( ObjectCode* oc );
105 static int ocResolve_PEi386     ( ObjectCode* oc );
106 #elif defined(OBJFORMAT_MACHO)
107 static int ocAllocateJumpIslands_MachO ( ObjectCode* oc );
108 static int ocVerifyImage_MachO    ( ObjectCode* oc );
109 static int ocGetNames_MachO       ( ObjectCode* oc );
110 static int ocResolve_MachO        ( ObjectCode* oc );
111
112 static void machoInitSymbolsWithoutUnderscore( void );
113 #endif
114
115 /* -----------------------------------------------------------------------------
116  * Built-in symbols from the RTS
117  */
118
119 typedef struct _RtsSymbolVal {
120     char   *lbl;
121     void   *addr;
122 } RtsSymbolVal;
123
124
125 #if !defined(PAR)
126 #define Maybe_ForeignObj        SymX(mkForeignObjzh_fast)
127
128 #define Maybe_Stable_Names      SymX(mkWeakzh_fast)                     \
129                                 SymX(makeStableNamezh_fast)             \
130                                 SymX(finalizzeWeakzh_fast)
131 #else
132 /* These are not available in GUM!!! -- HWL */
133 #define Maybe_ForeignObj
134 #define Maybe_Stable_Names
135 #endif
136
137 #if !defined (mingw32_HOST_OS)
138 #define RTS_POSIX_ONLY_SYMBOLS                  \
139       SymX(stg_sig_install)                     \
140       Sym(nocldstop)
141 #endif
142
143 #if defined (cygwin32_HOST_OS)
144 #define RTS_MINGW_ONLY_SYMBOLS /**/
145 /* Don't have the ability to read import libs / archives, so
146  * we have to stupidly list a lot of what libcygwin.a
147  * exports; sigh.
148  */
149 #define RTS_CYGWIN_ONLY_SYMBOLS                 \
150       SymX(regfree)                             \
151       SymX(regexec)                             \
152       SymX(regerror)                            \
153       SymX(regcomp)                             \
154       SymX(__errno)                             \
155       SymX(access)                              \
156       SymX(chmod)                               \
157       SymX(chdir)                               \
158       SymX(close)                               \
159       SymX(creat)                               \
160       SymX(dup)                                 \
161       SymX(dup2)                                \
162       SymX(fstat)                               \
163       SymX(fcntl)                               \
164       SymX(getcwd)                              \
165       SymX(getenv)                              \
166       SymX(lseek)                               \
167       SymX(open)                                \
168       SymX(fpathconf)                           \
169       SymX(pathconf)                            \
170       SymX(stat)                                \
171       SymX(pow)                                 \
172       SymX(tanh)                                \
173       SymX(cosh)                                \
174       SymX(sinh)                                \
175       SymX(atan)                                \
176       SymX(acos)                                \
177       SymX(asin)                                \
178       SymX(tan)                                 \
179       SymX(cos)                                 \
180       SymX(sin)                                 \
181       SymX(exp)                                 \
182       SymX(log)                                 \
183       SymX(sqrt)                                \
184       SymX(localtime_r)                         \
185       SymX(gmtime_r)                            \
186       SymX(mktime)                              \
187       Sym(_imp___tzname)                        \
188       SymX(gettimeofday)                        \
189       SymX(timezone)                            \
190       SymX(tcgetattr)                           \
191       SymX(tcsetattr)                           \
192       SymX(memcpy)                              \
193       SymX(memmove)                             \
194       SymX(realloc)                             \
195       SymX(malloc)                              \
196       SymX(free)                                \
197       SymX(fork)                                \
198       SymX(lstat)                               \
199       SymX(isatty)                              \
200       SymX(mkdir)                               \
201       SymX(opendir)                             \
202       SymX(readdir)                             \
203       SymX(rewinddir)                           \
204       SymX(closedir)                            \
205       SymX(link)                                \
206       SymX(mkfifo)                              \
207       SymX(pipe)                                \
208       SymX(read)                                \
209       SymX(rename)                              \
210       SymX(rmdir)                               \
211       SymX(select)                              \
212       SymX(system)                              \
213       SymX(write)                               \
214       SymX(strcmp)                              \
215       SymX(strcpy)                              \
216       SymX(strncpy)                             \
217       SymX(strerror)                            \
218       SymX(sigaddset)                           \
219       SymX(sigemptyset)                         \
220       SymX(sigprocmask)                         \
221       SymX(umask)                               \
222       SymX(uname)                               \
223       SymX(unlink)                              \
224       SymX(utime)                               \
225       SymX(waitpid)
226
227 #elif !defined(mingw32_HOST_OS)
228 #define RTS_MINGW_ONLY_SYMBOLS /**/
229 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
230 #else /* defined(mingw32_HOST_OS) */
231 #define RTS_POSIX_ONLY_SYMBOLS  /**/
232 #define RTS_CYGWIN_ONLY_SYMBOLS /**/
233
234 /* Extra syms gen'ed by mingw-2's gcc-3.2: */
235 #if __GNUC__>=3
236 #define RTS_MINGW_EXTRA_SYMS                    \
237       Sym(_imp____mb_cur_max)                   \
238       Sym(_imp___pctype)
239 #else
240 #define RTS_MINGW_EXTRA_SYMS
241 #endif
242
243 /* These are statically linked from the mingw libraries into the ghc
244    executable, so we have to employ this hack. */
245 #define RTS_MINGW_ONLY_SYMBOLS                  \
246       SymX(asyncReadzh_fast)                    \
247       SymX(asyncWritezh_fast)                   \
248       SymX(asyncDoProczh_fast)                  \
249       SymX(memset)                              \
250       SymX(inet_ntoa)                           \
251       SymX(inet_addr)                           \
252       SymX(htonl)                               \
253       SymX(recvfrom)                            \
254       SymX(listen)                              \
255       SymX(bind)                                \
256       SymX(shutdown)                            \
257       SymX(connect)                             \
258       SymX(htons)                               \
259       SymX(ntohs)                               \
260       SymX(getservbyname)                       \
261       SymX(getservbyport)                       \
262       SymX(getprotobynumber)                    \
263       SymX(getprotobyname)                      \
264       SymX(gethostbyname)                       \
265       SymX(gethostbyaddr)                       \
266       SymX(gethostname)                         \
267       SymX(strcpy)                              \
268       SymX(strncpy)                             \
269       SymX(abort)                               \
270       Sym(_alloca)                              \
271       Sym(isxdigit)                             \
272       Sym(isupper)                              \
273       Sym(ispunct)                              \
274       Sym(islower)                              \
275       Sym(isspace)                              \
276       Sym(isprint)                              \
277       Sym(isdigit)                              \
278       Sym(iscntrl)                              \
279       Sym(isalpha)                              \
280       Sym(isalnum)                              \
281       SymX(strcmp)                              \
282       SymX(memmove)                             \
283       SymX(realloc)                             \
284       SymX(malloc)                              \
285       SymX(pow)                                 \
286       SymX(tanh)                                \
287       SymX(cosh)                                \
288       SymX(sinh)                                \
289       SymX(atan)                                \
290       SymX(acos)                                \
291       SymX(asin)                                \
292       SymX(tan)                                 \
293       SymX(cos)                                 \
294       SymX(sin)                                 \
295       SymX(exp)                                 \
296       SymX(log)                                 \
297       SymX(sqrt)                                \
298       SymX(memcpy)                              \
299       SymX(rts_InstallConsoleEvent)             \
300       SymX(rts_ConsoleHandlerDone)              \
301       Sym(mktime)                               \
302       Sym(_imp___timezone)                      \
303       Sym(_imp___tzname)                        \
304       Sym(_imp___iob)                           \
305       Sym(_imp___osver)                         \
306       Sym(localtime)                            \
307       Sym(gmtime)                               \
308       Sym(opendir)                              \
309       Sym(readdir)                              \
310       Sym(rewinddir)                            \
311       RTS_MINGW_EXTRA_SYMS                      \
312       Sym(closedir)
313 #endif
314
315 #ifndef SMP
316 # define MAIN_CAP_SYM SymX(MainCapability)
317 #else
318 # define MAIN_CAP_SYM
319 #endif
320
321 #if !defined(mingw32_HOST_OS)
322 #define RTS_USER_SIGNALS_SYMBOLS \
323    SymX(startSignalHandler) \
324    SymX(setIOManagerPipe)
325 #else
326 #define RTS_USER_SIGNALS_SYMBOLS /* nothing */
327 #endif
328
329 #ifdef TABLES_NEXT_TO_CODE
330 #define RTS_RET_SYMBOLS /* nothing */
331 #else
332 #define RTS_RET_SYMBOLS                         \
333       SymX(stg_enter_ret)                       \
334       SymX(stg_gc_fun_ret)                      \
335       SymX(stg_ap_0_ret)                        \
336       SymX(stg_ap_v_ret)                        \
337       SymX(stg_ap_f_ret)                        \
338       SymX(stg_ap_d_ret)                        \
339       SymX(stg_ap_l_ret)                        \
340       SymX(stg_ap_n_ret)                        \
341       SymX(stg_ap_p_ret)                        \
342       SymX(stg_ap_pv_ret)                       \
343       SymX(stg_ap_pp_ret)                       \
344       SymX(stg_ap_ppv_ret)                      \
345       SymX(stg_ap_ppp_ret)                      \
346       SymX(stg_ap_pppv_ret)                     \
347       SymX(stg_ap_pppp_ret)                     \
348       SymX(stg_ap_ppppp_ret)                    \
349       SymX(stg_ap_pppppp_ret)
350 #endif
351
352 #define RTS_SYMBOLS                             \
353       Maybe_ForeignObj                          \
354       Maybe_Stable_Names                        \
355       Sym(StgReturn)                            \
356       SymX(stg_enter_info)                      \
357       SymX(stg_gc_void_info)                    \
358       SymX(__stg_gc_enter_1)                    \
359       SymX(stg_gc_noregs)                       \
360       SymX(stg_gc_unpt_r1_info)                 \
361       SymX(stg_gc_unpt_r1)                      \
362       SymX(stg_gc_unbx_r1_info)                 \
363       SymX(stg_gc_unbx_r1)                      \
364       SymX(stg_gc_f1_info)                      \
365       SymX(stg_gc_f1)                           \
366       SymX(stg_gc_d1_info)                      \
367       SymX(stg_gc_d1)                           \
368       SymX(stg_gc_l1_info)                      \
369       SymX(stg_gc_l1)                           \
370       SymX(__stg_gc_fun)                        \
371       SymX(stg_gc_fun_info)                     \
372       SymX(stg_gc_gen)                          \
373       SymX(stg_gc_gen_info)                     \
374       SymX(stg_gc_gen_hp)                       \
375       SymX(stg_gc_ut)                           \
376       SymX(stg_gen_yield)                       \
377       SymX(stg_yield_noregs)                    \
378       SymX(stg_yield_to_interpreter)            \
379       SymX(stg_gen_block)                       \
380       SymX(stg_block_noregs)                    \
381       SymX(stg_block_1)                         \
382       SymX(stg_block_takemvar)                  \
383       SymX(stg_block_putmvar)                   \
384       SymX(stg_seq_frame_info)                  \
385       MAIN_CAP_SYM                              \
386       SymX(MallocFailHook)                      \
387       SymX(OnExitHook)                          \
388       SymX(OutOfHeapHook)                       \
389       SymX(StackOverflowHook)                   \
390       SymX(__encodeDouble)                      \
391       SymX(__encodeFloat)                       \
392       SymX(addDLL)                              \
393       SymX(__gmpn_gcd_1)                        \
394       SymX(__gmpz_cmp)                          \
395       SymX(__gmpz_cmp_si)                       \
396       SymX(__gmpz_cmp_ui)                       \
397       SymX(__gmpz_get_si)                       \
398       SymX(__gmpz_get_ui)                       \
399       SymX(__int_encodeDouble)                  \
400       SymX(__int_encodeFloat)                   \
401       SymX(andIntegerzh_fast)                   \
402       SymX(atomicallyzh_fast)                   \
403       SymX(barf)                                \
404       SymX(debugBelch)                          \
405       SymX(errorBelch)                          \
406       SymX(blockAsyncExceptionszh_fast)         \
407       SymX(catchzh_fast)                        \
408       SymX(catchRetryzh_fast)                   \
409       SymX(catchSTMzh_fast)                     \
410       SymX(closure_flags)                       \
411       SymX(cmp_thread)                          \
412       SymX(cmpIntegerzh_fast)                   \
413       SymX(cmpIntegerIntzh_fast)                \
414       SymX(complementIntegerzh_fast)            \
415       SymX(createAdjustor)                      \
416       SymX(decodeDoublezh_fast)                 \
417       SymX(decodeFloatzh_fast)                  \
418       SymX(defaultsHook)                        \
419       SymX(delayzh_fast)                        \
420       SymX(deRefWeakzh_fast)                    \
421       SymX(deRefStablePtrzh_fast)               \
422       SymX(divExactIntegerzh_fast)              \
423       SymX(divModIntegerzh_fast)                \
424       SymX(forkzh_fast)                         \
425       SymX(forkProcess)                         \
426       SymX(forkOS_createThread)                 \
427       SymX(freeHaskellFunctionPtr)              \
428       SymX(freeStablePtr)                       \
429       SymX(gcdIntegerzh_fast)                   \
430       SymX(gcdIntegerIntzh_fast)                \
431       SymX(gcdIntzh_fast)                       \
432       SymX(genSymZh)                            \
433       SymX(genericRaise)                        \
434       SymX(getProgArgv)                         \
435       SymX(getStablePtr)                        \
436       SymX(hs_init)                             \
437       SymX(hs_exit)                             \
438       SymX(hs_set_argv)                         \
439       SymX(hs_add_root)                         \
440       SymX(hs_perform_gc)                       \
441       SymX(hs_free_stable_ptr)                  \
442       SymX(hs_free_fun_ptr)                     \
443       SymX(initLinker)                          \
444       SymX(int2Integerzh_fast)                  \
445       SymX(integer2Intzh_fast)                  \
446       SymX(integer2Wordzh_fast)                 \
447       SymX(isCurrentThreadBoundzh_fast)         \
448       SymX(isDoubleDenormalized)                \
449       SymX(isDoubleInfinite)                    \
450       SymX(isDoubleNaN)                         \
451       SymX(isDoubleNegativeZero)                \
452       SymX(isEmptyMVarzh_fast)                  \
453       SymX(isFloatDenormalized)                 \
454       SymX(isFloatInfinite)                     \
455       SymX(isFloatNaN)                          \
456       SymX(isFloatNegativeZero)                 \
457       SymX(killThreadzh_fast)                   \
458       SymX(loadObj)                             \
459       SymX(lookupSymbol)                        \
460       SymX(makeStablePtrzh_fast)                \
461       SymX(minusIntegerzh_fast)                 \
462       SymX(mkApUpd0zh_fast)                     \
463       SymX(myThreadIdzh_fast)                   \
464       SymX(labelThreadzh_fast)                  \
465       SymX(newArrayzh_fast)                     \
466       SymX(newBCOzh_fast)                       \
467       SymX(newByteArrayzh_fast)                 \
468       SymX_redirect(newCAF, newDynCAF)          \
469       SymX(newMVarzh_fast)                      \
470       SymX(newMutVarzh_fast)                    \
471       SymX(newTVarzh_fast)                      \
472       SymX(atomicModifyMutVarzh_fast)           \
473       SymX(newPinnedByteArrayzh_fast)           \
474       SymX(orIntegerzh_fast)                    \
475       SymX(performGC)                           \
476       SymX(performMajorGC)                      \
477       SymX(plusIntegerzh_fast)                  \
478       SymX(prog_argc)                           \
479       SymX(prog_argv)                           \
480       SymX(putMVarzh_fast)                      \
481       SymX(quotIntegerzh_fast)                  \
482       SymX(quotRemIntegerzh_fast)               \
483       SymX(raisezh_fast)                        \
484       SymX(raiseIOzh_fast)                      \
485       SymX(readTVarzh_fast)                     \
486       SymX(remIntegerzh_fast)                   \
487       SymX(resetNonBlockingFd)                  \
488       SymX(resumeThread)                        \
489       SymX(resolveObjs)                         \
490       SymX(retryzh_fast)                        \
491       SymX(rts_apply)                           \
492       SymX(rts_checkSchedStatus)                \
493       SymX(rts_eval)                            \
494       SymX(rts_evalIO)                          \
495       SymX(rts_evalLazyIO)                      \
496       SymX(rts_evalStableIO)                    \
497       SymX(rts_eval_)                           \
498       SymX(rts_getBool)                         \
499       SymX(rts_getChar)                         \
500       SymX(rts_getDouble)                       \
501       SymX(rts_getFloat)                        \
502       SymX(rts_getInt)                          \
503       SymX(rts_getInt32)                        \
504       SymX(rts_getPtr)                          \
505       SymX(rts_getFunPtr)                       \
506       SymX(rts_getStablePtr)                    \
507       SymX(rts_getThreadId)                     \
508       SymX(rts_getWord)                         \
509       SymX(rts_getWord32)                       \
510       SymX(rts_lock)                            \
511       SymX(rts_mkBool)                          \
512       SymX(rts_mkChar)                          \
513       SymX(rts_mkDouble)                        \
514       SymX(rts_mkFloat)                         \
515       SymX(rts_mkInt)                           \
516       SymX(rts_mkInt16)                         \
517       SymX(rts_mkInt32)                         \
518       SymX(rts_mkInt64)                         \
519       SymX(rts_mkInt8)                          \
520       SymX(rts_mkPtr)                           \
521       SymX(rts_mkFunPtr)                        \
522       SymX(rts_mkStablePtr)                     \
523       SymX(rts_mkString)                        \
524       SymX(rts_mkWord)                          \
525       SymX(rts_mkWord16)                        \
526       SymX(rts_mkWord32)                        \
527       SymX(rts_mkWord64)                        \
528       SymX(rts_mkWord8)                         \
529       SymX(rts_unlock)                          \
530       SymX(rtsSupportsBoundThreads)             \
531       SymX(run_queue_hd)                        \
532       SymX(__hscore_get_saved_termios)          \
533       SymX(__hscore_set_saved_termios)          \
534       SymX(setProgArgv)                         \
535       SymX(startupHaskell)                      \
536       SymX(shutdownHaskell)                     \
537       SymX(shutdownHaskellAndExit)              \
538       SymX(stable_ptr_table)                    \
539       SymX(stackOverflow)                       \
540       SymX(stg_CAF_BLACKHOLE_info)              \
541       SymX(awakenBlockedQueue)                  \
542       SymX(stg_CHARLIKE_closure)                \
543       SymX(stg_EMPTY_MVAR_info)                 \
544       SymX(stg_IND_STATIC_info)                 \
545       SymX(stg_INTLIKE_closure)                 \
546       SymX(stg_MUT_ARR_PTRS_FROZEN_info)        \
547       SymX(stg_MUT_ARR_PTRS_FROZEN0_info)       \
548       SymX(stg_WEAK_info)                       \
549       SymX(stg_ap_0_info)                       \
550       SymX(stg_ap_v_info)                       \
551       SymX(stg_ap_f_info)                       \
552       SymX(stg_ap_d_info)                       \
553       SymX(stg_ap_l_info)                       \
554       SymX(stg_ap_n_info)                       \
555       SymX(stg_ap_p_info)                       \
556       SymX(stg_ap_pv_info)                      \
557       SymX(stg_ap_pp_info)                      \
558       SymX(stg_ap_ppv_info)                     \
559       SymX(stg_ap_ppp_info)                     \
560       SymX(stg_ap_pppv_info)                    \
561       SymX(stg_ap_pppp_info)                    \
562       SymX(stg_ap_ppppp_info)                   \
563       SymX(stg_ap_pppppp_info)                  \
564       SymX(stg_ap_1_upd_info)                   \
565       SymX(stg_ap_2_upd_info)                   \
566       SymX(stg_ap_3_upd_info)                   \
567       SymX(stg_ap_4_upd_info)                   \
568       SymX(stg_ap_5_upd_info)                   \
569       SymX(stg_ap_6_upd_info)                   \
570       SymX(stg_ap_7_upd_info)                   \
571       SymX(stg_exit)                            \
572       SymX(stg_sel_0_upd_info)                  \
573       SymX(stg_sel_10_upd_info)                 \
574       SymX(stg_sel_11_upd_info)                 \
575       SymX(stg_sel_12_upd_info)                 \
576       SymX(stg_sel_13_upd_info)                 \
577       SymX(stg_sel_14_upd_info)                 \
578       SymX(stg_sel_15_upd_info)                 \
579       SymX(stg_sel_1_upd_info)                  \
580       SymX(stg_sel_2_upd_info)                  \
581       SymX(stg_sel_3_upd_info)                  \
582       SymX(stg_sel_4_upd_info)                  \
583       SymX(stg_sel_5_upd_info)                  \
584       SymX(stg_sel_6_upd_info)                  \
585       SymX(stg_sel_7_upd_info)                  \
586       SymX(stg_sel_8_upd_info)                  \
587       SymX(stg_sel_9_upd_info)                  \
588       SymX(stg_upd_frame_info)                  \
589       SymX(suspendThread)                       \
590       SymX(takeMVarzh_fast)                     \
591       SymX(timesIntegerzh_fast)                 \
592       SymX(tryPutMVarzh_fast)                   \
593       SymX(tryTakeMVarzh_fast)                  \
594       SymX(unblockAsyncExceptionszh_fast)       \
595       SymX(unloadObj)                           \
596       SymX(unsafeThawArrayzh_fast)              \
597       SymX(waitReadzh_fast)                     \
598       SymX(waitWritezh_fast)                    \
599       SymX(word2Integerzh_fast)                 \
600       SymX(writeTVarzh_fast)                    \
601       SymX(xorIntegerzh_fast)                   \
602       SymX(yieldzh_fast)                        \
603       RTS_USER_SIGNALS_SYMBOLS
604
605 #ifdef SUPPORT_LONG_LONGS
606 #define RTS_LONG_LONG_SYMS                      \
607       SymX(int64ToIntegerzh_fast)               \
608       SymX(word64ToIntegerzh_fast)
609 #else
610 #define RTS_LONG_LONG_SYMS /* nothing */
611 #endif
612
613 // 64-bit support functions in libgcc.a
614 #if defined(__GNUC__) && SIZEOF_VOID_P <= 4
615 #define RTS_LIBGCC_SYMBOLS                      \
616       Sym(__divdi3)                             \
617       Sym(__udivdi3)                            \
618       Sym(__moddi3)                             \
619       Sym(__umoddi3)                            \
620       Sym(__muldi3)                             \
621       Sym(__ashldi3)                            \
622       Sym(__ashrdi3)                            \
623       Sym(__lshrdi3)                            \
624       Sym(__eprintf)
625 #elif defined(ia64_HOST_ARCH)
626 #define RTS_LIBGCC_SYMBOLS                      \
627       Sym(__divdi3)                             \
628       Sym(__udivdi3)                            \
629       Sym(__moddi3)                             \
630       Sym(__umoddi3)                            \
631       Sym(__divsf3)                             \
632       Sym(__divdf3)
633 #else
634 #define RTS_LIBGCC_SYMBOLS
635 #endif
636
637 #ifdef darwin_HOST_OS
638       // Symbols that don't have a leading underscore
639       // on Mac OS X. They have to receive special treatment,
640       // see machoInitSymbolsWithoutUnderscore()
641 #define RTS_MACHO_NOUNDERLINE_SYMBOLS           \
642       Sym(saveFP)                               \
643       Sym(restFP)
644 #endif
645
646 /* entirely bogus claims about types of these symbols */
647 #define Sym(vvv)  extern void vvv(void);
648 #define SymX(vvv) /**/
649 #define SymX_redirect(vvv,xxx) /**/
650 RTS_SYMBOLS
651 RTS_RET_SYMBOLS
652 RTS_LONG_LONG_SYMS
653 RTS_POSIX_ONLY_SYMBOLS
654 RTS_MINGW_ONLY_SYMBOLS
655 RTS_CYGWIN_ONLY_SYMBOLS
656 RTS_LIBGCC_SYMBOLS
657 #undef Sym
658 #undef SymX
659 #undef SymX_redirect
660
661 #ifdef LEADING_UNDERSCORE
662 #define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
663 #else
664 #define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
665 #endif
666
667 #define Sym(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
668                     (void*)(&(vvv)) },
669 #define SymX(vvv) Sym(vvv)
670
671 // SymX_redirect allows us to redirect references to one symbol to
672 // another symbol.  See newCAF/newDynCAF for an example.
673 #define SymX_redirect(vvv,xxx) \
674     { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
675       (void*)(&(xxx)) },
676
677 static RtsSymbolVal rtsSyms[] = {
678       RTS_SYMBOLS
679       RTS_RET_SYMBOLS
680       RTS_LONG_LONG_SYMS
681       RTS_POSIX_ONLY_SYMBOLS
682       RTS_MINGW_ONLY_SYMBOLS
683       RTS_CYGWIN_ONLY_SYMBOLS
684       RTS_LIBGCC_SYMBOLS
685       { 0, 0 } /* sentinel */
686 };
687
688 /* -----------------------------------------------------------------------------
689  * Insert symbols into hash tables, checking for duplicates.
690  */
691 static void ghciInsertStrHashTable ( char* obj_name,
692                                      HashTable *table,
693                                      char* key,
694                                      void *data
695                                    )
696 {
697    if (lookupHashTable(table, (StgWord)key) == NULL)
698    {
699       insertStrHashTable(table, (StgWord)key, data);
700       return;
701    }
702    debugBelch(
703       "\n\n"
704       "GHCi runtime linker: fatal error: I found a duplicate definition for symbol\n"
705       "   %s\n"
706       "whilst processing object file\n"
707       "   %s\n"
708       "This could be caused by:\n"
709       "   * Loading two different object files which export the same symbol\n"
710       "   * Specifying the same object file twice on the GHCi command line\n"
711       "   * An incorrect `package.conf' entry, causing some object to be\n"
712       "     loaded twice.\n"
713       "GHCi cannot safely continue in this situation.  Exiting now.  Sorry.\n"
714       "\n",
715       (char*)key,
716       obj_name
717    );
718    exit(1);
719 }
720
721
722 /* -----------------------------------------------------------------------------
723  * initialize the object linker
724  */
725
726
727 static int linker_init_done = 0 ;
728
729 #if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
730 static void *dl_prog_handle;
731 #endif
732
733 /* dlopen(NULL,..) doesn't work so we grab libc explicitly */
734 #if defined(openbsd_HOST_OS)
735 static void *dl_libc_handle;
736 #endif
737
738 void
739 initLinker( void )
740 {
741     RtsSymbolVal *sym;
742
743     /* Make initLinker idempotent, so we can call it
744        before evey relevant operation; that means we
745        don't need to initialise the linker separately */
746     if (linker_init_done == 1) { return; } else {
747       linker_init_done = 1;
748     }
749
750     symhash = allocStrHashTable();
751
752     /* populate the symbol table with stuff from the RTS */
753     for (sym = rtsSyms; sym->lbl != NULL; sym++) {
754         ghciInsertStrHashTable("(GHCi built-in symbols)",
755                                symhash, sym->lbl, sym->addr);
756     }
757 #   if defined(OBJFORMAT_MACHO)
758     machoInitSymbolsWithoutUnderscore();
759 #   endif
760
761 #   if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
762 #   if defined(RTLD_DEFAULT)
763     dl_prog_handle = RTLD_DEFAULT;
764 #   else
765     dl_prog_handle = dlopen(NULL, RTLD_LAZY);
766 #   if defined(openbsd_HOST_OS)
767     dl_libc_handle = dlopen("libc.so", RTLD_LAZY);
768 #   endif
769 #   endif /* RTLD_DEFAULT */
770 #   endif
771 }
772
773 /* -----------------------------------------------------------------------------
774  *                  Loading DLL or .so dynamic libraries
775  * -----------------------------------------------------------------------------
776  *
777  * Add a DLL from which symbols may be found.  In the ELF case, just
778  * do RTLD_GLOBAL-style add, so no further messing around needs to
779  * happen in order that symbols in the loaded .so are findable --
780  * lookupSymbol() will subsequently see them by dlsym on the program's
781  * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
782  *
783  * In the PEi386 case, open the DLLs and put handles to them in a
784  * linked list.  When looking for a symbol, try all handles in the
785  * list.  This means that we need to load even DLLs that are guaranteed
786  * to be in the ghc.exe image already, just so we can get a handle
787  * to give to loadSymbol, so that we can find the symbols.  For such
788  * libraries, the LoadLibrary call should be a no-op except for returning
789  * the handle.
790  *
791  */
792
793 #if defined(OBJFORMAT_PEi386)
794 /* A record for storing handles into DLLs. */
795
796 typedef
797    struct _OpenedDLL {
798       char*              name;
799       struct _OpenedDLL* next;
800       HINSTANCE instance;
801    }
802    OpenedDLL;
803
804 /* A list thereof. */
805 static OpenedDLL* opened_dlls = NULL;
806 #endif
807
808 char *
809 addDLL( char *dll_name )
810 {
811 #  if defined(OBJFORMAT_ELF) || defined(OBJFORMAT_MACHO)
812    /* ------------------- ELF DLL loader ------------------- */
813    void *hdl;
814    char *errmsg;
815
816    initLinker();
817
818    hdl= dlopen(dll_name, RTLD_NOW | RTLD_GLOBAL);
819
820    if (hdl == NULL) {
821       /* dlopen failed; return a ptr to the error msg. */
822       errmsg = dlerror();
823       if (errmsg == NULL) errmsg = "addDLL: unknown error";
824       return errmsg;
825    } else {
826       return NULL;
827    }
828    /*NOTREACHED*/
829
830 #  elif defined(OBJFORMAT_PEi386)
831    /* ------------------- Win32 DLL loader ------------------- */
832
833    char*      buf;
834    OpenedDLL* o_dll;
835    HINSTANCE  instance;
836
837    initLinker();
838
839    /* debugBelch("\naddDLL; dll_name = `%s'\n", dll_name); */
840
841    /* See if we've already got it, and ignore if so. */
842    for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
843       if (0 == strcmp(o_dll->name, dll_name))
844          return NULL;
845    }
846
847    /* The file name has no suffix (yet) so that we can try
848       both foo.dll and foo.drv
849
850       The documentation for LoadLibrary says:
851         If no file name extension is specified in the lpFileName
852         parameter, the default library extension .dll is
853         appended. However, the file name string can include a trailing
854         point character (.) to indicate that the module name has no
855         extension. */
856
857    buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
858    sprintf(buf, "%s.DLL", dll_name);
859    instance = LoadLibrary(buf);
860    if (instance == NULL) {
861          sprintf(buf, "%s.DRV", dll_name);      // KAA: allow loading of drivers (like winspool.drv)
862          instance = LoadLibrary(buf);
863          if (instance == NULL) {
864                 stgFree(buf);
865
866             /* LoadLibrary failed; return a ptr to the error msg. */
867             return "addDLL: unknown error";
868          }
869    }
870    stgFree(buf);
871
872    /* Add this DLL to the list of DLLs in which to search for symbols. */
873    o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
874    o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
875    strcpy(o_dll->name, dll_name);
876    o_dll->instance = instance;
877    o_dll->next     = opened_dlls;
878    opened_dlls     = o_dll;
879
880    return NULL;
881 #  else
882    barf("addDLL: not implemented on this platform");
883 #  endif
884 }
885
886 /* -----------------------------------------------------------------------------
887  * lookup a symbol in the hash table
888  */
889 void *
890 lookupSymbol( char *lbl )
891 {
892     void *val;
893     initLinker() ;
894     ASSERT(symhash != NULL);
895     val = lookupStrHashTable(symhash, lbl);
896
897     if (val == NULL) {
898 #       if defined(OBJFORMAT_ELF)
899 #       if defined(openbsd_HOST_OS)
900         val = dlsym(dl_prog_handle, lbl);
901         return (val != NULL) ? val : dlsym(dl_libc_handle,lbl);
902 #       else /* not openbsd */
903         return dlsym(dl_prog_handle, lbl);
904 #       endif
905 #       elif defined(OBJFORMAT_MACHO)
906         if(NSIsSymbolNameDefined(lbl)) {
907             NSSymbol symbol = NSLookupAndBindSymbol(lbl);
908             return NSAddressOfSymbol(symbol);
909         } else {
910             return NULL;
911         }
912 #       elif defined(OBJFORMAT_PEi386)
913         OpenedDLL* o_dll;
914         void* sym;
915         for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
916           /* debugBelch("look in %s for %s\n", o_dll->name, lbl); */
917            if (lbl[0] == '_') {
918               /* HACK: if the name has an initial underscore, try stripping
919                  it off & look that up first. I've yet to verify whether there's
920                  a Rule that governs whether an initial '_' *should always* be
921                  stripped off when mapping from import lib name to the DLL name.
922               */
923               sym = GetProcAddress(o_dll->instance, (lbl+1));
924               if (sym != NULL) {
925                 /*debugBelch("found %s in %s\n", lbl+1,o_dll->name);*/
926                 return sym;
927               }
928            }
929            sym = GetProcAddress(o_dll->instance, lbl);
930            if (sym != NULL) {
931              /*debugBelch("found %s in %s\n", lbl,o_dll->name);*/
932              return sym;
933            }
934         }
935         return NULL;
936 #       else
937         ASSERT(2+2 == 5);
938         return NULL;
939 #       endif
940     } else {
941         return val;
942     }
943 }
944
945 static
946 __attribute((unused))
947 void *
948 lookupLocalSymbol( ObjectCode* oc, char *lbl )
949 {
950     void *val;
951     initLinker() ;
952     val = lookupStrHashTable(oc->lochash, lbl);
953
954     if (val == NULL) {
955         return NULL;
956     } else {
957         return val;
958     }
959 }
960
961
962 /* -----------------------------------------------------------------------------
963  * Debugging aid: look in GHCi's object symbol tables for symbols
964  * within DELTA bytes of the specified address, and show their names.
965  */
966 #ifdef DEBUG
967 void ghci_enquire ( char* addr );
968
969 void ghci_enquire ( char* addr )
970 {
971    int   i;
972    char* sym;
973    char* a;
974    const int DELTA = 64;
975    ObjectCode* oc;
976
977    initLinker();
978
979    for (oc = objects; oc; oc = oc->next) {
980       for (i = 0; i < oc->n_symbols; i++) {
981          sym = oc->symbols[i];
982          if (sym == NULL) continue;
983          // debugBelch("enquire %p %p\n", sym, oc->lochash);
984          a = NULL;
985          if (oc->lochash != NULL) {
986             a = lookupStrHashTable(oc->lochash, sym);
987          }
988          if (a == NULL) {
989             a = lookupStrHashTable(symhash, sym);
990          }
991          if (a == NULL) {
992              // debugBelch("ghci_enquire: can't find %s\n", sym);
993          }
994          else if (addr-DELTA <= a && a <= addr+DELTA) {
995             debugBelch("%p + %3d  ==  `%s'\n", addr, a - addr, sym);
996          }
997       }
998    }
999 }
1000 #endif
1001
1002 #ifdef ia64_HOST_ARCH
1003 static unsigned int PLTSize(void);
1004 #endif
1005
1006 /* -----------------------------------------------------------------------------
1007  * Load an obj (populate the global symbol table, but don't resolve yet)
1008  *
1009  * Returns: 1 if ok, 0 on error.
1010  */
1011 HsInt
1012 loadObj( char *path )
1013 {
1014    ObjectCode* oc;
1015    struct stat st;
1016    int r, n;
1017 #ifdef USE_MMAP
1018    int fd, pagesize;
1019    void *map_addr = NULL;
1020 #else
1021    FILE *f;
1022 #endif
1023
1024    initLinker();
1025
1026    /* debugBelch("loadObj %s\n", path ); */
1027
1028    /* Check that we haven't already loaded this object. 
1029       Ignore requests to load multiple times */
1030    {
1031        ObjectCode *o;
1032        int is_dup = 0;
1033        for (o = objects; o; o = o->next) {
1034           if (0 == strcmp(o->fileName, path)) {
1035              is_dup = 1;
1036              break; /* don't need to search further */
1037           }
1038        }
1039        if (is_dup) {
1040           IF_DEBUG(linker, debugBelch(
1041             "GHCi runtime linker: warning: looks like you're trying to load the\n"
1042             "same object file twice:\n"
1043             "   %s\n"
1044             "GHCi will ignore this, but be warned.\n"
1045             , path));
1046           return 1; /* success */
1047        }
1048    }
1049
1050    oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");
1051
1052 #  if defined(OBJFORMAT_ELF)
1053    oc->formatName = "ELF";
1054 #  elif defined(OBJFORMAT_PEi386)
1055    oc->formatName = "PEi386";
1056 #  elif defined(OBJFORMAT_MACHO)
1057    oc->formatName = "Mach-O";
1058 #  else
1059    stgFree(oc);
1060    barf("loadObj: not implemented on this platform");
1061 #  endif
1062
1063    r = stat(path, &st);
1064    if (r == -1) { return 0; }
1065
1066    /* sigh, strdup() isn't a POSIX function, so do it the long way */
1067    oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
1068    strcpy(oc->fileName, path);
1069
1070    oc->fileSize          = st.st_size;
1071    oc->symbols           = NULL;
1072    oc->sections          = NULL;
1073    oc->lochash           = allocStrHashTable();
1074    oc->proddables        = NULL;
1075
1076    /* chain it onto the list of objects */
1077    oc->next              = objects;
1078    objects               = oc;
1079
1080 #ifdef USE_MMAP
1081 #define ROUND_UP(x,size) ((x + size - 1) & ~(size - 1))
1082
1083    /* On many architectures malloc'd memory isn't executable, so we need to use mmap. */
1084
1085 #if defined(openbsd_HOST_OS)
1086    fd = open(path, O_RDONLY, S_IRUSR);
1087 #else
1088    fd = open(path, O_RDONLY);
1089 #endif
1090    if (fd == -1)
1091       barf("loadObj: can't open `%s'", path);
1092
1093    pagesize = getpagesize();
1094
1095 #ifdef ia64_HOST_ARCH
1096    /* The PLT needs to be right before the object */
1097    n = ROUND_UP(PLTSize(), pagesize);
1098    oc->plt = mmap(NULL, n, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
1099    if (oc->plt == MAP_FAILED)
1100       barf("loadObj: can't allocate PLT");
1101
1102    oc->pltIndex = 0;
1103    map_addr = oc->plt + n;
1104 #endif
1105
1106    n = ROUND_UP(oc->fileSize, pagesize);
1107
1108    /* Link objects into the lower 2Gb on x86_64.  GHC assumes the
1109     * small memory model on this architecture (see gcc docs,
1110     * -mcmodel=small).
1111     */
1112 #ifdef x86_64_HOST_ARCH
1113 #define EXTRA_MAP_FLAGS MAP_32BIT
1114 #else
1115 #define EXTRA_MAP_FLAGS 0
1116 #endif
1117
1118    oc->image = mmap(map_addr, n, PROT_EXEC|PROT_READ|PROT_WRITE, 
1119                     MAP_PRIVATE|EXTRA_MAP_FLAGS, fd, 0);
1120    if (oc->image == MAP_FAILED)
1121       barf("loadObj: can't map `%s'", path);
1122
1123    close(fd);
1124
1125 #else /* !USE_MMAP */
1126
1127    oc->image = stgMallocBytes(oc->fileSize, "loadObj(image)");
1128
1129    /* load the image into memory */
1130    f = fopen(path, "rb");
1131    if (!f)
1132        barf("loadObj: can't read `%s'", path);
1133
1134    n = fread ( oc->image, 1, oc->fileSize, f );
1135    if (n != oc->fileSize)
1136       barf("loadObj: error whilst reading `%s'", path);
1137
1138    fclose(f);
1139
1140 #endif /* USE_MMAP */
1141
1142 #  if defined(OBJFORMAT_MACHO)
1143    r = ocAllocateJumpIslands_MachO ( oc );
1144    if (!r) { return r; }
1145 #  elif defined(OBJFORMAT_ELF) && defined(powerpc_HOST_ARCH)
1146    r = ocAllocateJumpIslands_ELF ( oc );
1147    if (!r) { return r; }
1148 #endif
1149
1150    /* verify the in-memory image */
1151 #  if defined(OBJFORMAT_ELF)
1152    r = ocVerifyImage_ELF ( oc );
1153 #  elif defined(OBJFORMAT_PEi386)
1154    r = ocVerifyImage_PEi386 ( oc );
1155 #  elif defined(OBJFORMAT_MACHO)
1156    r = ocVerifyImage_MachO ( oc );
1157 #  else
1158    barf("loadObj: no verify method");
1159 #  endif
1160    if (!r) { return r; }
1161
1162    /* build the symbol list for this image */
1163 #  if defined(OBJFORMAT_ELF)
1164    r = ocGetNames_ELF ( oc );
1165 #  elif defined(OBJFORMAT_PEi386)
1166    r = ocGetNames_PEi386 ( oc );
1167 #  elif defined(OBJFORMAT_MACHO)
1168    r = ocGetNames_MachO ( oc );
1169 #  else
1170    barf("loadObj: no getNames method");
1171 #  endif
1172    if (!r) { return r; }
1173
1174    /* loaded, but not resolved yet */
1175    oc->status = OBJECT_LOADED;
1176
1177    return 1;
1178 }
1179
1180 /* -----------------------------------------------------------------------------
1181  * resolve all the currently unlinked objects in memory
1182  *
1183  * Returns: 1 if ok, 0 on error.
1184  */
1185 HsInt
1186 resolveObjs( void )
1187 {
1188     ObjectCode *oc;
1189     int r;
1190
1191     initLinker();
1192
1193     for (oc = objects; oc; oc = oc->next) {
1194         if (oc->status != OBJECT_RESOLVED) {
1195 #           if defined(OBJFORMAT_ELF)
1196             r = ocResolve_ELF ( oc );
1197 #           elif defined(OBJFORMAT_PEi386)
1198             r = ocResolve_PEi386 ( oc );
1199 #           elif defined(OBJFORMAT_MACHO)
1200             r = ocResolve_MachO ( oc );
1201 #           else
1202             barf("resolveObjs: not implemented on this platform");
1203 #           endif
1204             if (!r) { return r; }
1205             oc->status = OBJECT_RESOLVED;
1206         }
1207     }
1208     return 1;
1209 }
1210
1211 /* -----------------------------------------------------------------------------
1212  * delete an object from the pool
1213  */
1214 HsInt
1215 unloadObj( char *path )
1216 {
1217     ObjectCode *oc, *prev;
1218
1219     ASSERT(symhash != NULL);
1220     ASSERT(objects != NULL);
1221
1222     initLinker();
1223
1224     prev = NULL;
1225     for (oc = objects; oc; prev = oc, oc = oc->next) {
1226         if (!strcmp(oc->fileName,path)) {
1227
1228             /* Remove all the mappings for the symbols within this
1229              * object..
1230              */
1231             {
1232                 int i;
1233                 for (i = 0; i < oc->n_symbols; i++) {
1234                    if (oc->symbols[i] != NULL) {
1235                        removeStrHashTable(symhash, oc->symbols[i], NULL);
1236                    }
1237                 }
1238             }
1239
1240             if (prev == NULL) {
1241                 objects = oc->next;
1242             } else {
1243                 prev->next = oc->next;
1244             }
1245
1246             /* We're going to leave this in place, in case there are
1247                any pointers from the heap into it: */
1248             /* stgFree(oc->image); */
1249             stgFree(oc->fileName);
1250             stgFree(oc->symbols);
1251             stgFree(oc->sections);
1252             /* The local hash table should have been freed at the end
1253                of the ocResolve_ call on it. */
1254             ASSERT(oc->lochash == NULL);
1255             stgFree(oc);
1256             return 1;
1257         }
1258     }
1259
1260     errorBelch("unloadObj: can't find `%s' to unload", path);
1261     return 0;
1262 }
1263
1264 /* -----------------------------------------------------------------------------
1265  * Sanity checking.  For each ObjectCode, maintain a list of address ranges
1266  * which may be prodded during relocation, and abort if we try and write
1267  * outside any of these.
1268  */
1269 static void addProddableBlock ( ObjectCode* oc, void* start, int size )
1270 {
1271    ProddableBlock* pb
1272       = stgMallocBytes(sizeof(ProddableBlock), "addProddableBlock");
1273    /* debugBelch("aPB %p %p %d\n", oc, start, size); */
1274    ASSERT(size > 0);
1275    pb->start      = start;
1276    pb->size       = size;
1277    pb->next       = oc->proddables;
1278    oc->proddables = pb;
1279 }
1280
1281 static void checkProddableBlock ( ObjectCode* oc, void* addr )
1282 {
1283    ProddableBlock* pb;
1284    for (pb = oc->proddables; pb != NULL; pb = pb->next) {
1285       char* s = (char*)(pb->start);
1286       char* e = s + pb->size - 1;
1287       char* a = (char*)addr;
1288       /* Assumes that the biggest fixup involves a 4-byte write.  This
1289          probably needs to be changed to 8 (ie, +7) on 64-bit
1290          plats. */
1291       if (a >= s && (a+3) <= e) return;
1292    }
1293    barf("checkProddableBlock: invalid fixup in runtime linker");
1294 }
1295
1296 /* -----------------------------------------------------------------------------
1297  * Section management.
1298  */
1299 static void addSection ( ObjectCode* oc, SectionKind kind,
1300                          void* start, void* end )
1301 {
1302    Section* s   = stgMallocBytes(sizeof(Section), "addSection");
1303    s->start     = start;
1304    s->end       = end;
1305    s->kind      = kind;
1306    s->next      = oc->sections;
1307    oc->sections = s;
1308    /*
1309    debugBelch("addSection: %p-%p (size %d), kind %d\n",
1310                    start, ((char*)end)-1, end - start + 1, kind );
1311    */
1312 }
1313
1314
1315 /* --------------------------------------------------------------------------
1316  * PowerPC specifics (jump islands)
1317  * ------------------------------------------------------------------------*/
1318
1319 #if defined(powerpc_HOST_ARCH)
1320
1321 /*
1322   ocAllocateJumpIslands
1323   
1324   Allocate additional space at the end of the object file image to make room
1325   for jump islands.
1326   
1327   PowerPC relative branch instructions have a 24 bit displacement field.
1328   As PPC code is always 4-byte-aligned, this yields a +-32MB range.
1329   If a particular imported symbol is outside this range, we have to redirect
1330   the jump to a short piece of new code that just loads the 32bit absolute
1331   address and jumps there.
1332   This function just allocates space for one 16 byte ppcJumpIsland for every
1333   undefined symbol in the object file. The code for the islands is filled in by
1334   makeJumpIsland below.
1335 */
1336
1337 static int ocAllocateJumpIslands( ObjectCode* oc, int count, int first )
1338 {
1339 #ifdef USE_MMAP
1340   int pagesize, n, m;
1341 #endif
1342   int aligned;
1343
1344   if( count > 0 )
1345   {
1346     // round up to the nearest 4
1347     aligned = (oc->fileSize + 3) & ~3;
1348
1349 #ifdef USE_MMAP
1350     #ifndef linux_HOST_OS /* mremap is a linux extension */
1351         #error ocAllocateJumpIslands doesnt want USE_MMAP to be defined
1352     #endif
1353
1354     pagesize = getpagesize();
1355     n = ROUND_UP( oc->fileSize, pagesize );
1356     m = ROUND_UP( aligned + sizeof (ppcJumpIsland) * count, pagesize );
1357
1358     /* The effect of this mremap() call is only the ensure that we have
1359      * a sufficient number of virtually contiguous pages.  As returned from
1360      * mremap, the pages past the end of the file are not backed.  We give
1361      * them a backing by using MAP_FIXED to map in anonymous pages.
1362      */
1363     if( (oc->image = mremap( oc->image, n, m, MREMAP_MAYMOVE )) == MAP_FAILED )
1364     {
1365       errorBelch( "Unable to mremap for Jump Islands\n" );
1366       return 0;
1367     }
1368
1369     if( mmap( oc->image + n, m - n, PROT_READ | PROT_WRITE | PROT_EXEC,
1370               MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 0, 0 ) == MAP_FAILED )
1371     {
1372       errorBelch( "Unable to mmap( MAP_FIXED ) for Jump Islands\n" );
1373       return 0;
1374     }
1375
1376 #else
1377     oc->image = stgReallocBytes( oc->image,
1378                                  aligned + sizeof (ppcJumpIsland) * count,
1379                                  "ocAllocateJumpIslands" );
1380 #endif /* USE_MMAP */
1381
1382     oc->jump_islands = (ppcJumpIsland *) (oc->image + aligned);
1383     memset( oc->jump_islands, 0, sizeof (ppcJumpIsland) * count );
1384   }
1385   else
1386     oc->jump_islands = NULL;
1387
1388   oc->island_start_symbol = first;
1389   oc->n_islands = count;
1390
1391   return 1;
1392 }
1393
1394 static unsigned long makeJumpIsland( ObjectCode* oc,
1395                                      unsigned long symbolNumber,
1396                                      unsigned long target )
1397 {
1398   ppcJumpIsland *island;
1399
1400   if( symbolNumber < oc->island_start_symbol ||
1401       symbolNumber - oc->island_start_symbol > oc->n_islands)
1402     return 0;
1403
1404   island = &oc->jump_islands[symbolNumber - oc->island_start_symbol];
1405
1406   // lis r12, hi16(target)
1407   island->lis_r12     = 0x3d80;
1408   island->hi_addr     = target >> 16;
1409
1410   // ori r12, r12, lo16(target)
1411   island->ori_r12_r12 = 0x618c;
1412   island->lo_addr     = target & 0xffff;
1413
1414   // mtctr r12
1415   island->mtctr_r12   = 0x7d8903a6;
1416
1417   // bctr
1418   island->bctr        = 0x4e800420;
1419     
1420   return (unsigned long) island;
1421 }
1422
1423 /*
1424    ocFlushInstructionCache
1425
1426    Flush the data & instruction caches.
1427    Because the PPC has split data/instruction caches, we have to
1428    do that whenever we modify code at runtime.
1429  */
1430
1431 static void ocFlushInstructionCache( ObjectCode *oc )
1432 {
1433     int n = (oc->fileSize + sizeof( ppcJumpIsland ) * oc->n_islands + 3) / 4;
1434     unsigned long *p = (unsigned long *) oc->image;
1435
1436     while( n-- )
1437     {
1438         __asm__ volatile ( "dcbf 0,%0\n\t"
1439                            "sync\n\t"
1440                            "icbi 0,%0"
1441                            :
1442                            : "r" (p)
1443                          );
1444         p++;
1445     }
1446     __asm__ volatile ( "sync\n\t"
1447                        "isync"
1448                      );
1449 }
1450 #endif
1451
1452 /* --------------------------------------------------------------------------
1453  * PEi386 specifics (Win32 targets)
1454  * ------------------------------------------------------------------------*/
1455
1456 /* The information for this linker comes from
1457       Microsoft Portable Executable
1458       and Common Object File Format Specification
1459       revision 5.1 January 1998
1460    which SimonM says comes from the MS Developer Network CDs.
1461
1462    It can be found there (on older CDs), but can also be found
1463    online at:
1464
1465       http://www.microsoft.com/hwdev/hardware/PECOFF.asp
1466
1467    (this is Rev 6.0 from February 1999).
1468
1469    Things move, so if that fails, try searching for it via
1470
1471       http://www.google.com/search?q=PE+COFF+specification
1472
1473    The ultimate reference for the PE format is the Winnt.h
1474    header file that comes with the Platform SDKs; as always,
1475    implementations will drift wrt their documentation.
1476
1477    A good background article on the PE format is Matt Pietrek's
1478    March 1994 article in Microsoft System Journal (MSJ)
1479    (Vol.9, No. 3): "Peering Inside the PE: A Tour of the
1480    Win32 Portable Executable File Format." The info in there
1481    has recently been updated in a two part article in
1482    MSDN magazine, issues Feb and March 2002,
1483    "Inside Windows: An In-Depth Look into the Win32 Portable
1484    Executable File Format"
1485
1486    John Levine's book "Linkers and Loaders" contains useful
1487    info on PE too.
1488 */
1489
1490
1491 #if defined(OBJFORMAT_PEi386)
1492
1493
1494
1495 typedef unsigned char  UChar;
1496 typedef unsigned short UInt16;
1497 typedef unsigned int   UInt32;
1498 typedef          int   Int32;
1499
1500
1501 typedef
1502    struct {
1503       UInt16 Machine;
1504       UInt16 NumberOfSections;
1505       UInt32 TimeDateStamp;
1506       UInt32 PointerToSymbolTable;
1507       UInt32 NumberOfSymbols;
1508       UInt16 SizeOfOptionalHeader;
1509       UInt16 Characteristics;
1510    }
1511    COFF_header;
1512
1513 #define sizeof_COFF_header 20
1514
1515
1516 typedef
1517    struct {
1518       UChar  Name[8];
1519       UInt32 VirtualSize;
1520       UInt32 VirtualAddress;
1521       UInt32 SizeOfRawData;
1522       UInt32 PointerToRawData;
1523       UInt32 PointerToRelocations;
1524       UInt32 PointerToLinenumbers;
1525       UInt16 NumberOfRelocations;
1526       UInt16 NumberOfLineNumbers;
1527       UInt32 Characteristics;
1528    }
1529    COFF_section;
1530
1531 #define sizeof_COFF_section 40
1532
1533
1534 typedef
1535    struct {
1536       UChar  Name[8];
1537       UInt32 Value;
1538       UInt16 SectionNumber;
1539       UInt16 Type;
1540       UChar  StorageClass;
1541       UChar  NumberOfAuxSymbols;
1542    }
1543    COFF_symbol;
1544
1545 #define sizeof_COFF_symbol 18
1546
1547
1548 typedef
1549    struct {
1550       UInt32 VirtualAddress;
1551       UInt32 SymbolTableIndex;
1552       UInt16 Type;
1553    }
1554    COFF_reloc;
1555
1556 #define sizeof_COFF_reloc 10
1557
1558
1559 /* From PE spec doc, section 3.3.2 */
1560 /* Note use of MYIMAGE_* since IMAGE_* are already defined in
1561    windows.h -- for the same purpose, but I want to know what I'm
1562    getting, here. */
1563 #define MYIMAGE_FILE_RELOCS_STRIPPED     0x0001
1564 #define MYIMAGE_FILE_EXECUTABLE_IMAGE    0x0002
1565 #define MYIMAGE_FILE_DLL                 0x2000
1566 #define MYIMAGE_FILE_SYSTEM              0x1000
1567 #define MYIMAGE_FILE_BYTES_REVERSED_HI   0x8000
1568 #define MYIMAGE_FILE_BYTES_REVERSED_LO   0x0080
1569 #define MYIMAGE_FILE_32BIT_MACHINE       0x0100
1570
1571 /* From PE spec doc, section 5.4.2 and 5.4.4 */
1572 #define MYIMAGE_SYM_CLASS_EXTERNAL       2
1573 #define MYIMAGE_SYM_CLASS_STATIC         3
1574 #define MYIMAGE_SYM_UNDEFINED            0
1575
1576 /* From PE spec doc, section 4.1 */
1577 #define MYIMAGE_SCN_CNT_CODE             0x00000020
1578 #define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
1579 #define MYIMAGE_SCN_LNK_NRELOC_OVFL      0x01000000
1580
1581 /* From PE spec doc, section 5.2.1 */
1582 #define MYIMAGE_REL_I386_DIR32           0x0006
1583 #define MYIMAGE_REL_I386_REL32           0x0014
1584
1585
1586 /* We use myindex to calculate array addresses, rather than
1587    simply doing the normal subscript thing.  That's because
1588    some of the above structs have sizes which are not
1589    a whole number of words.  GCC rounds their sizes up to a
1590    whole number of words, which means that the address calcs
1591    arising from using normal C indexing or pointer arithmetic
1592    are just plain wrong.  Sigh.
1593 */
1594 static UChar *
1595 myindex ( int scale, void* base, int index )
1596 {
1597    return
1598       ((UChar*)base) + scale * index;
1599 }
1600
1601
1602 static void
1603 printName ( UChar* name, UChar* strtab )
1604 {
1605    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1606       UInt32 strtab_offset = * (UInt32*)(name+4);
1607       debugBelch("%s", strtab + strtab_offset );
1608    } else {
1609       int i;
1610       for (i = 0; i < 8; i++) {
1611          if (name[i] == 0) break;
1612          debugBelch("%c", name[i] );
1613       }
1614    }
1615 }
1616
1617
1618 static void
1619 copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
1620 {
1621    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1622       UInt32 strtab_offset = * (UInt32*)(name+4);
1623       strncpy ( dst, strtab+strtab_offset, dstSize );
1624       dst[dstSize-1] = 0;
1625    } else {
1626       int i = 0;
1627       while (1) {
1628          if (i >= 8) break;
1629          if (name[i] == 0) break;
1630          dst[i] = name[i];
1631          i++;
1632       }
1633       dst[i] = 0;
1634    }
1635 }
1636
1637
1638 static UChar *
1639 cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
1640 {
1641    UChar* newstr;
1642    /* If the string is longer than 8 bytes, look in the
1643       string table for it -- this will be correctly zero terminated.
1644    */
1645    if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
1646       UInt32 strtab_offset = * (UInt32*)(name+4);
1647       return ((UChar*)strtab) + strtab_offset;
1648    }
1649    /* Otherwise, if shorter than 8 bytes, return the original,
1650       which by defn is correctly terminated.
1651    */
1652    if (name[7]==0) return name;
1653    /* The annoying case: 8 bytes.  Copy into a temporary
1654       (which is never freed ...)
1655    */
1656    newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
1657    ASSERT(newstr);
1658    strncpy(newstr,name,8);
1659    newstr[8] = 0;
1660    return newstr;
1661 }
1662
1663
1664 /* Just compares the short names (first 8 chars) */
1665 static COFF_section *
1666 findPEi386SectionCalled ( ObjectCode* oc,  char* name )
1667 {
1668    int i;
1669    COFF_header* hdr
1670       = (COFF_header*)(oc->image);
1671    COFF_section* sectab
1672       = (COFF_section*) (
1673            ((UChar*)(oc->image))
1674            + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1675         );
1676    for (i = 0; i < hdr->NumberOfSections; i++) {
1677       UChar* n1;
1678       UChar* n2;
1679       COFF_section* section_i
1680          = (COFF_section*)
1681            myindex ( sizeof_COFF_section, sectab, i );
1682       n1 = (UChar*) &(section_i->Name);
1683       n2 = name;
1684       if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] &&
1685           n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] &&
1686           n1[6]==n2[6] && n1[7]==n2[7])
1687          return section_i;
1688    }
1689
1690    return NULL;
1691 }
1692
1693
1694 static void
1695 zapTrailingAtSign ( UChar* sym )
1696 {
1697 #  define my_isdigit(c) ((c) >= '0' && (c) <= '9')
1698    int i, j;
1699    if (sym[0] == 0) return;
1700    i = 0;
1701    while (sym[i] != 0) i++;
1702    i--;
1703    j = i;
1704    while (j > 0 && my_isdigit(sym[j])) j--;
1705    if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
1706 #  undef my_isdigit
1707 }
1708
1709
1710 static int
1711 ocVerifyImage_PEi386 ( ObjectCode* oc )
1712 {
1713    int i;
1714    UInt32 j, noRelocs;
1715    COFF_header*  hdr;
1716    COFF_section* sectab;
1717    COFF_symbol*  symtab;
1718    UChar*        strtab;
1719    /* debugBelch("\nLOADING %s\n", oc->fileName); */
1720    hdr = (COFF_header*)(oc->image);
1721    sectab = (COFF_section*) (
1722                ((UChar*)(oc->image))
1723                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1724             );
1725    symtab = (COFF_symbol*) (
1726                ((UChar*)(oc->image))
1727                + hdr->PointerToSymbolTable
1728             );
1729    strtab = ((UChar*)symtab)
1730             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1731
1732    if (hdr->Machine != 0x14c) {
1733       errorBelch("Not x86 PEi386");
1734       return 0;
1735    }
1736    if (hdr->SizeOfOptionalHeader != 0) {
1737       errorBelch("PEi386 with nonempty optional header");
1738       return 0;
1739    }
1740    if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
1741         (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
1742         (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
1743         (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
1744       errorBelch("Not a PEi386 object file");
1745       return 0;
1746    }
1747    if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
1748         /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
1749       errorBelch("Invalid PEi386 word size or endiannness: %d",
1750             (int)(hdr->Characteristics));
1751       return 0;
1752    }
1753    /* If the string table size is way crazy, this might indicate that
1754       there are more than 64k relocations, despite claims to the
1755       contrary.  Hence this test. */
1756    /* debugBelch("strtab size %d\n", * (UInt32*)strtab); */
1757 #if 0
1758    if ( (*(UInt32*)strtab) > 600000 ) {
1759       /* Note that 600k has no special significance other than being
1760          big enough to handle the almost-2MB-sized lumps that
1761          constitute HSwin32*.o. */
1762       debugBelch("PEi386 object has suspiciously large string table; > 64k relocs?");
1763       return 0;
1764    }
1765 #endif
1766
1767    /* No further verification after this point; only debug printing. */
1768    i = 0;
1769    IF_DEBUG(linker, i=1);
1770    if (i == 0) return 1;
1771
1772    debugBelch( "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
1773    debugBelch( "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
1774    debugBelch( "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );
1775
1776    debugBelch("\n" );
1777    debugBelch( "Machine:           0x%x\n", (UInt32)(hdr->Machine) );
1778    debugBelch( "# sections:        %d\n",   (UInt32)(hdr->NumberOfSections) );
1779    debugBelch( "time/date:         0x%x\n", (UInt32)(hdr->TimeDateStamp) );
1780    debugBelch( "symtab offset:     %d\n",   (UInt32)(hdr->PointerToSymbolTable) );
1781    debugBelch( "# symbols:         %d\n",   (UInt32)(hdr->NumberOfSymbols) );
1782    debugBelch( "sz of opt hdr:     %d\n",   (UInt32)(hdr->SizeOfOptionalHeader) );
1783    debugBelch( "characteristics:   0x%x\n", (UInt32)(hdr->Characteristics) );
1784
1785    /* Print the section table. */
1786    debugBelch("\n" );
1787    for (i = 0; i < hdr->NumberOfSections; i++) {
1788       COFF_reloc* reltab;
1789       COFF_section* sectab_i
1790          = (COFF_section*)
1791            myindex ( sizeof_COFF_section, sectab, i );
1792       debugBelch(
1793                 "\n"
1794                 "section %d\n"
1795                 "     name `",
1796                 i
1797               );
1798       printName ( sectab_i->Name, strtab );
1799       debugBelch(
1800                 "'\n"
1801                 "    vsize %d\n"
1802                 "    vaddr %d\n"
1803                 "  data sz %d\n"
1804                 " data off %d\n"
1805                 "  num rel %d\n"
1806                 "  off rel %d\n"
1807                 "  ptr raw 0x%x\n",
1808                 sectab_i->VirtualSize,
1809                 sectab_i->VirtualAddress,
1810                 sectab_i->SizeOfRawData,
1811                 sectab_i->PointerToRawData,
1812                 sectab_i->NumberOfRelocations,
1813                 sectab_i->PointerToRelocations,
1814                 sectab_i->PointerToRawData
1815               );
1816       reltab = (COFF_reloc*) (
1817                   ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
1818                );
1819
1820       if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
1821         /* If the relocation field (a short) has overflowed, the
1822          * real count can be found in the first reloc entry.
1823          *
1824          * See Section 4.1 (last para) of the PE spec (rev6.0).
1825          */
1826         COFF_reloc* rel = (COFF_reloc*)
1827                            myindex ( sizeof_COFF_reloc, reltab, 0 );
1828         noRelocs = rel->VirtualAddress;
1829         j = 1;
1830       } else {
1831         noRelocs = sectab_i->NumberOfRelocations;
1832         j = 0;
1833       }
1834
1835       for (; j < noRelocs; j++) {
1836          COFF_symbol* sym;
1837          COFF_reloc* rel = (COFF_reloc*)
1838                            myindex ( sizeof_COFF_reloc, reltab, j );
1839          debugBelch(
1840                    "        type 0x%-4x   vaddr 0x%-8x   name `",
1841                    (UInt32)rel->Type,
1842                    rel->VirtualAddress );
1843          sym = (COFF_symbol*)
1844                myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
1845          /* Hmm..mysterious looking offset - what's it for? SOF */
1846          printName ( sym->Name, strtab -10 );
1847          debugBelch("'\n" );
1848       }
1849
1850       debugBelch("\n" );
1851    }
1852    debugBelch("\n" );
1853    debugBelch("string table has size 0x%x\n", * (UInt32*)strtab );
1854    debugBelch("---START of string table---\n");
1855    for (i = 4; i < *(Int32*)strtab; i++) {
1856       if (strtab[i] == 0)
1857          debugBelch("\n"); else
1858          debugBelch("%c", strtab[i] );
1859    }
1860    debugBelch("--- END  of string table---\n");
1861
1862    debugBelch("\n" );
1863    i = 0;
1864    while (1) {
1865       COFF_symbol* symtab_i;
1866       if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1867       symtab_i = (COFF_symbol*)
1868                  myindex ( sizeof_COFF_symbol, symtab, i );
1869       debugBelch(
1870                 "symbol %d\n"
1871                 "     name `",
1872                 i
1873               );
1874       printName ( symtab_i->Name, strtab );
1875       debugBelch(
1876                 "'\n"
1877                 "    value 0x%x\n"
1878                 "   1+sec# %d\n"
1879                 "     type 0x%x\n"
1880                 "   sclass 0x%x\n"
1881                 "     nAux %d\n",
1882                 symtab_i->Value,
1883                 (Int32)(symtab_i->SectionNumber),
1884                 (UInt32)symtab_i->Type,
1885                 (UInt32)symtab_i->StorageClass,
1886                 (UInt32)symtab_i->NumberOfAuxSymbols
1887               );
1888       i += symtab_i->NumberOfAuxSymbols;
1889       i++;
1890    }
1891
1892    debugBelch("\n" );
1893    return 1;
1894 }
1895
1896
1897 static int
1898 ocGetNames_PEi386 ( ObjectCode* oc )
1899 {
1900    COFF_header*  hdr;
1901    COFF_section* sectab;
1902    COFF_symbol*  symtab;
1903    UChar*        strtab;
1904
1905    UChar* sname;
1906    void*  addr;
1907    int    i;
1908
1909    hdr = (COFF_header*)(oc->image);
1910    sectab = (COFF_section*) (
1911                ((UChar*)(oc->image))
1912                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
1913             );
1914    symtab = (COFF_symbol*) (
1915                ((UChar*)(oc->image))
1916                + hdr->PointerToSymbolTable
1917             );
1918    strtab = ((UChar*)(oc->image))
1919             + hdr->PointerToSymbolTable
1920             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
1921
1922    /* Allocate space for any (local, anonymous) .bss sections. */
1923
1924    for (i = 0; i < hdr->NumberOfSections; i++) {
1925       UChar* zspace;
1926       COFF_section* sectab_i
1927          = (COFF_section*)
1928            myindex ( sizeof_COFF_section, sectab, i );
1929       if (0 != strcmp(sectab_i->Name, ".bss")) continue;
1930       if (sectab_i->VirtualSize == 0) continue;
1931       /* This is a non-empty .bss section.  Allocate zeroed space for
1932          it, and set its PointerToRawData field such that oc->image +
1933          PointerToRawData == addr_of_zeroed_space.  */
1934       zspace = stgCallocBytes(1, sectab_i->VirtualSize,
1935                               "ocGetNames_PEi386(anonymous bss)");
1936       sectab_i->PointerToRawData = ((UChar*)zspace) - ((UChar*)(oc->image));
1937       addProddableBlock(oc, zspace, sectab_i->VirtualSize);
1938       /* debugBelch("BSS anon section at 0x%x\n", zspace); */
1939    }
1940
1941    /* Copy section information into the ObjectCode. */
1942
1943    for (i = 0; i < hdr->NumberOfSections; i++) {
1944       UChar* start;
1945       UChar* end;
1946       UInt32 sz;
1947
1948       SectionKind kind
1949          = SECTIONKIND_OTHER;
1950       COFF_section* sectab_i
1951          = (COFF_section*)
1952            myindex ( sizeof_COFF_section, sectab, i );
1953       IF_DEBUG(linker, debugBelch("section name = %s\n", sectab_i->Name ));
1954
1955 #     if 0
1956       /* I'm sure this is the Right Way to do it.  However, the
1957          alternative of testing the sectab_i->Name field seems to
1958          work ok with Cygwin.
1959       */
1960       if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE ||
1961           sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
1962          kind = SECTIONKIND_CODE_OR_RODATA;
1963 #     endif
1964
1965       if (0==strcmp(".text",sectab_i->Name) ||
1966           0==strcmp(".rdata",sectab_i->Name)||
1967           0==strcmp(".rodata",sectab_i->Name))
1968          kind = SECTIONKIND_CODE_OR_RODATA;
1969       if (0==strcmp(".data",sectab_i->Name) ||
1970           0==strcmp(".bss",sectab_i->Name))
1971          kind = SECTIONKIND_RWDATA;
1972
1973       ASSERT(sectab_i->SizeOfRawData == 0 || sectab_i->VirtualSize == 0);
1974       sz = sectab_i->SizeOfRawData;
1975       if (sz < sectab_i->VirtualSize) sz = sectab_i->VirtualSize;
1976
1977       start = ((UChar*)(oc->image)) + sectab_i->PointerToRawData;
1978       end   = start + sz - 1;
1979
1980       if (kind == SECTIONKIND_OTHER
1981           /* Ignore sections called which contain stabs debugging
1982              information. */
1983           && 0 != strcmp(".stab", sectab_i->Name)
1984           && 0 != strcmp(".stabstr", sectab_i->Name)
1985          ) {
1986          errorBelch("Unknown PEi386 section name `%s' (while processing: %s)", sectab_i->Name, oc->fileName);
1987          return 0;
1988       }
1989
1990       if (kind != SECTIONKIND_OTHER && end >= start) {
1991          addSection(oc, kind, start, end);
1992          addProddableBlock(oc, start, end - start + 1);
1993       }
1994    }
1995
1996    /* Copy exported symbols into the ObjectCode. */
1997
1998    oc->n_symbols = hdr->NumberOfSymbols;
1999    oc->symbols   = stgMallocBytes(oc->n_symbols * sizeof(char*),
2000                                   "ocGetNames_PEi386(oc->symbols)");
2001    /* Call me paranoid; I don't care. */
2002    for (i = 0; i < oc->n_symbols; i++)
2003       oc->symbols[i] = NULL;
2004
2005    i = 0;
2006    while (1) {
2007       COFF_symbol* symtab_i;
2008       if (i >= (Int32)(hdr->NumberOfSymbols)) break;
2009       symtab_i = (COFF_symbol*)
2010                  myindex ( sizeof_COFF_symbol, symtab, i );
2011
2012       addr  = NULL;
2013
2014       if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL
2015           && symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
2016          /* This symbol is global and defined, viz, exported */
2017          /* for MYIMAGE_SYMCLASS_EXTERNAL
2018                 && !MYIMAGE_SYM_UNDEFINED,
2019             the address of the symbol is:
2020                 address of relevant section + offset in section
2021          */
2022          COFF_section* sectabent
2023             = (COFF_section*) myindex ( sizeof_COFF_section,
2024                                         sectab,
2025                                         symtab_i->SectionNumber-1 );
2026          addr = ((UChar*)(oc->image))
2027                 + (sectabent->PointerToRawData
2028                    + symtab_i->Value);
2029       }
2030       else
2031       if (symtab_i->SectionNumber == MYIMAGE_SYM_UNDEFINED
2032           && symtab_i->Value > 0) {
2033          /* This symbol isn't in any section at all, ie, global bss.
2034             Allocate zeroed space for it. */
2035          addr = stgCallocBytes(1, symtab_i->Value,
2036                                "ocGetNames_PEi386(non-anonymous bss)");
2037          addSection(oc, SECTIONKIND_RWDATA, addr,
2038                         ((UChar*)addr) + symtab_i->Value - 1);
2039          addProddableBlock(oc, addr, symtab_i->Value);
2040          /* debugBelch("BSS      section at 0x%x\n", addr); */
2041       }
2042
2043       if (addr != NULL ) {
2044          sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
2045          /* debugBelch("addSymbol %p `%s \n", addr,sname);  */
2046          IF_DEBUG(linker, debugBelch("addSymbol %p `%s'\n", addr,sname);)
2047          ASSERT(i >= 0 && i < oc->n_symbols);
2048          /* cstring_from_COFF_symbol_name always succeeds. */
2049          oc->symbols[i] = sname;
2050          ghciInsertStrHashTable(oc->fileName, symhash, sname, addr);
2051       } else {
2052 #        if 0
2053          debugBelch(
2054                    "IGNORING symbol %d\n"
2055                    "     name `",
2056                    i
2057                  );
2058          printName ( symtab_i->Name, strtab );
2059          debugBelch(
2060                    "'\n"
2061                    "    value 0x%x\n"
2062                    "   1+sec# %d\n"
2063                    "     type 0x%x\n"
2064                    "   sclass 0x%x\n"
2065                    "     nAux %d\n",
2066                    symtab_i->Value,
2067                    (Int32)(symtab_i->SectionNumber),
2068                    (UInt32)symtab_i->Type,
2069                    (UInt32)symtab_i->StorageClass,
2070                    (UInt32)symtab_i->NumberOfAuxSymbols
2071                  );
2072 #        endif
2073       }
2074
2075       i += symtab_i->NumberOfAuxSymbols;
2076       i++;
2077    }
2078
2079    return 1;
2080 }
2081
2082
2083 static int
2084 ocResolve_PEi386 ( ObjectCode* oc )
2085 {
2086    COFF_header*  hdr;
2087    COFF_section* sectab;
2088    COFF_symbol*  symtab;
2089    UChar*        strtab;
2090
2091    UInt32        A;
2092    UInt32        S;
2093    UInt32*       pP;
2094
2095    int i;
2096    UInt32 j, noRelocs;
2097
2098    /* ToDo: should be variable-sized?  But is at least safe in the
2099       sense of buffer-overrun-proof. */
2100    char symbol[1000];
2101    /* debugBelch("resolving for %s\n", oc->fileName); */
2102
2103    hdr = (COFF_header*)(oc->image);
2104    sectab = (COFF_section*) (
2105                ((UChar*)(oc->image))
2106                + sizeof_COFF_header + hdr->SizeOfOptionalHeader
2107             );
2108    symtab = (COFF_symbol*) (
2109                ((UChar*)(oc->image))
2110                + hdr->PointerToSymbolTable
2111             );
2112    strtab = ((UChar*)(oc->image))
2113             + hdr->PointerToSymbolTable
2114             + hdr->NumberOfSymbols * sizeof_COFF_symbol;
2115
2116    for (i = 0; i < hdr->NumberOfSections; i++) {
2117       COFF_section* sectab_i
2118          = (COFF_section*)
2119            myindex ( sizeof_COFF_section, sectab, i );
2120       COFF_reloc* reltab
2121          = (COFF_reloc*) (
2122               ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
2123            );
2124
2125       /* Ignore sections called which contain stabs debugging
2126          information. */
2127       if (0 == strcmp(".stab", sectab_i->Name)
2128           || 0 == strcmp(".stabstr", sectab_i->Name))
2129          continue;
2130
2131       if ( sectab_i->Characteristics & MYIMAGE_SCN_LNK_NRELOC_OVFL ) {
2132         /* If the relocation field (a short) has overflowed, the
2133          * real count can be found in the first reloc entry.
2134          *
2135          * See Section 4.1 (last para) of the PE spec (rev6.0).
2136          *
2137          * Nov2003 update: the GNU linker still doesn't correctly
2138          * handle the generation of relocatable object files with
2139          * overflown relocations. Hence the output to warn of potential
2140          * troubles.
2141          */
2142         COFF_reloc* rel = (COFF_reloc*)
2143                            myindex ( sizeof_COFF_reloc, reltab, 0 );
2144         noRelocs = rel->VirtualAddress;
2145         debugBelch("WARNING: Overflown relocation field (# relocs found: %u)\n",
2146                    noRelocs);
2147         j = 1;
2148       } else {
2149         noRelocs = sectab_i->NumberOfRelocations;
2150         j = 0;
2151       }
2152
2153
2154       for (; j < noRelocs; j++) {
2155          COFF_symbol* sym;
2156          COFF_reloc* reltab_j
2157             = (COFF_reloc*)
2158               myindex ( sizeof_COFF_reloc, reltab, j );
2159
2160          /* the location to patch */
2161          pP = (UInt32*)(
2162                  ((UChar*)(oc->image))
2163                  + (sectab_i->PointerToRawData
2164                     + reltab_j->VirtualAddress
2165                     - sectab_i->VirtualAddress )
2166               );
2167          /* the existing contents of pP */
2168          A = *pP;
2169          /* the symbol to connect to */
2170          sym = (COFF_symbol*)
2171                myindex ( sizeof_COFF_symbol,
2172                          symtab, reltab_j->SymbolTableIndex );
2173          IF_DEBUG(linker,
2174                   debugBelch(
2175                             "reloc sec %2d num %3d:  type 0x%-4x   "
2176                             "vaddr 0x%-8x   name `",
2177                             i, j,
2178                             (UInt32)reltab_j->Type,
2179                             reltab_j->VirtualAddress );
2180                             printName ( sym->Name, strtab );
2181                             debugBelch("'\n" ));
2182
2183          if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
2184             COFF_section* section_sym
2185                = findPEi386SectionCalled ( oc, sym->Name );
2186             if (!section_sym) {
2187                errorBelch("%s: can't find section `%s'", oc->fileName, sym->Name);
2188                return 0;
2189             }
2190             S = ((UInt32)(oc->image))
2191                 + (section_sym->PointerToRawData
2192                    + sym->Value);
2193          } else {
2194             copyName ( sym->Name, strtab, symbol, 1000-1 );
2195             (void*)S = lookupLocalSymbol( oc, symbol );
2196             if ((void*)S != NULL) goto foundit;
2197             (void*)S = lookupSymbol( symbol );
2198             if ((void*)S != NULL) goto foundit;
2199             zapTrailingAtSign ( symbol );
2200             (void*)S = lookupLocalSymbol( oc, symbol );
2201             if ((void*)S != NULL) goto foundit;
2202             (void*)S = lookupSymbol( symbol );
2203             if ((void*)S != NULL) goto foundit;
2204             /* Newline first because the interactive linker has printed "linking..." */
2205             errorBelch("\n%s: unknown symbol `%s'", oc->fileName, symbol);
2206             return 0;
2207            foundit:;
2208          }
2209          checkProddableBlock(oc, pP);
2210          switch (reltab_j->Type) {
2211             case MYIMAGE_REL_I386_DIR32:
2212                *pP = A + S;
2213                break;
2214             case MYIMAGE_REL_I386_REL32:
2215                /* Tricky.  We have to insert a displacement at
2216                   pP which, when added to the PC for the _next_
2217                   insn, gives the address of the target (S).
2218                   Problem is to know the address of the next insn
2219                   when we only know pP.  We assume that this
2220                   literal field is always the last in the insn,
2221                   so that the address of the next insn is pP+4
2222                   -- hence the constant 4.
2223                   Also I don't know if A should be added, but so
2224                   far it has always been zero.
2225
2226                   SOF 05/2005: 'A' (old contents of *pP) have been observed
2227                   to contain values other than zero (the 'wx' object file
2228                   that came with wxhaskell-0.9.4; dunno how it was compiled..).
2229                   So, add displacement to old value instead of asserting
2230                   A to be zero. Fixes wxhaskell-related crashes, and no other
2231                   ill effects have been observed.
2232                */
2233                *pP = S - ((UInt32)pP) - 4 + A;
2234                break;
2235             default:
2236                debugBelch("%s: unhandled PEi386 relocation type %d",
2237                      oc->fileName, reltab_j->Type);
2238                return 0;
2239          }
2240
2241       }
2242    }
2243
2244    IF_DEBUG(linker, debugBelch("completed %s", oc->fileName));
2245    return 1;
2246 }
2247
2248 #endif /* defined(OBJFORMAT_PEi386) */
2249
2250
2251 /* --------------------------------------------------------------------------
2252  * ELF specifics
2253  * ------------------------------------------------------------------------*/
2254
2255 #if defined(OBJFORMAT_ELF)
2256
2257 #define FALSE 0
2258 #define TRUE  1
2259
2260 #if defined(sparc_HOST_ARCH)
2261 #  define ELF_TARGET_SPARC  /* Used inside <elf.h> */
2262 #elif defined(i386_HOST_ARCH)
2263 #  define ELF_TARGET_386    /* Used inside <elf.h> */
2264 #elif defined(x86_64_HOST_ARCH)
2265 #  define ELF_TARGET_X64_64
2266 #  define ELF_64BIT
2267 #elif defined (ia64_HOST_ARCH)
2268 #  define ELF_TARGET_IA64   /* Used inside <elf.h> */
2269 #  define ELF_64BIT
2270 #  define ELF_FUNCTION_DESC /* calling convention uses function descriptors */
2271 #  define ELF_NEED_GOT      /* needs Global Offset Table */
2272 #  define ELF_NEED_PLT      /* needs Procedure Linkage Tables */
2273 #endif
2274
2275 #if !defined(openbsd_HOST_OS)
2276 #include <elf.h>
2277 #else
2278 /* openbsd elf has things in different places, with diff names */
2279 #include <elf_abi.h>
2280 #include <machine/reloc.h>
2281 #define R_386_32    RELOC_32
2282 #define R_386_PC32  RELOC_PC32
2283 #endif
2284
2285 /*
2286  * Define a set of types which can be used for both ELF32 and ELF64
2287  */
2288
2289 #ifdef ELF_64BIT
2290 #define ELFCLASS    ELFCLASS64
2291 #define Elf_Addr    Elf64_Addr
2292 #define Elf_Word    Elf64_Word
2293 #define Elf_Sword   Elf64_Sword
2294 #define Elf_Ehdr    Elf64_Ehdr
2295 #define Elf_Phdr    Elf64_Phdr
2296 #define Elf_Shdr    Elf64_Shdr
2297 #define Elf_Sym     Elf64_Sym
2298 #define Elf_Rel     Elf64_Rel
2299 #define Elf_Rela    Elf64_Rela
2300 #define ELF_ST_TYPE ELF64_ST_TYPE
2301 #define ELF_ST_BIND ELF64_ST_BIND
2302 #define ELF_R_TYPE  ELF64_R_TYPE
2303 #define ELF_R_SYM   ELF64_R_SYM
2304 #else
2305 #define ELFCLASS    ELFCLASS32
2306 #define Elf_Addr    Elf32_Addr
2307 #define Elf_Word    Elf32_Word
2308 #define Elf_Sword   Elf32_Sword
2309 #define Elf_Ehdr    Elf32_Ehdr
2310 #define Elf_Phdr    Elf32_Phdr
2311 #define Elf_Shdr    Elf32_Shdr
2312 #define Elf_Sym     Elf32_Sym
2313 #define Elf_Rel     Elf32_Rel
2314 #define Elf_Rela    Elf32_Rela
2315 #ifndef ELF_ST_TYPE
2316 #define ELF_ST_TYPE ELF32_ST_TYPE
2317 #endif
2318 #ifndef ELF_ST_BIND
2319 #define ELF_ST_BIND ELF32_ST_BIND
2320 #endif
2321 #ifndef ELF_R_TYPE
2322 #define ELF_R_TYPE  ELF32_R_TYPE
2323 #endif
2324 #ifndef ELF_R_SYM
2325 #define ELF_R_SYM   ELF32_R_SYM
2326 #endif
2327 #endif
2328
2329
2330 /*
2331  * Functions to allocate entries in dynamic sections.  Currently we simply
2332  * preallocate a large number, and we don't check if a entry for the given
2333  * target already exists (a linear search is too slow).  Ideally these
2334  * entries would be associated with symbols.
2335  */
2336
2337 /* These sizes sufficient to load HSbase + HShaskell98 + a few modules */
2338 #define GOT_SIZE            0x20000
2339 #define FUNCTION_TABLE_SIZE 0x10000
2340 #define PLT_SIZE            0x08000
2341
2342 #ifdef ELF_NEED_GOT
2343 static Elf_Addr got[GOT_SIZE];
2344 static unsigned int gotIndex;
2345 static Elf_Addr gp_val = (Elf_Addr)got;
2346
2347 static Elf_Addr
2348 allocateGOTEntry(Elf_Addr target)
2349 {
2350    Elf_Addr *entry;
2351
2352    if (gotIndex >= GOT_SIZE)
2353       barf("Global offset table overflow");
2354
2355    entry = &got[gotIndex++];
2356    *entry = target;
2357    return (Elf_Addr)entry;
2358 }
2359 #endif
2360
2361 #ifdef ELF_FUNCTION_DESC
2362 typedef struct {
2363    Elf_Addr ip;
2364    Elf_Addr gp;
2365 } FunctionDesc;
2366
2367 static FunctionDesc functionTable[FUNCTION_TABLE_SIZE];
2368 static unsigned int functionTableIndex;
2369
2370 static Elf_Addr
2371 allocateFunctionDesc(Elf_Addr target)
2372 {
2373    FunctionDesc *entry;
2374
2375    if (functionTableIndex >= FUNCTION_TABLE_SIZE)
2376       barf("Function table overflow");
2377
2378    entry = &functionTable[functionTableIndex++];
2379    entry->ip = target;
2380    entry->gp = (Elf_Addr)gp_val;
2381    return (Elf_Addr)entry;
2382 }
2383
2384 static Elf_Addr
2385 copyFunctionDesc(Elf_Addr target)
2386 {
2387    FunctionDesc *olddesc = (FunctionDesc *)target;
2388    FunctionDesc *newdesc;
2389
2390    newdesc = (FunctionDesc *)allocateFunctionDesc(olddesc->ip);
2391    newdesc->gp = olddesc->gp;
2392    return (Elf_Addr)newdesc;
2393 }
2394 #endif
2395
2396 #ifdef ELF_NEED_PLT
2397 #ifdef ia64_HOST_ARCH
2398 static void ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value);
2399 static void ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc);
2400
2401 static unsigned char plt_code[] =
2402 {
2403    /* taken from binutils bfd/elfxx-ia64.c */
2404    0x0b, 0x78, 0x00, 0x02, 0x00, 0x24,  /*   [MMI]       addl r15=0,r1;;    */
2405    0x00, 0x41, 0x3c, 0x30, 0x28, 0xc0,  /*               ld8 r16=[r15],8    */
2406    0x01, 0x08, 0x00, 0x84,              /*               mov r14=r1;;       */
2407    0x11, 0x08, 0x00, 0x1e, 0x18, 0x10,  /*   [MIB]       ld8 r1=[r15]       */
2408    0x60, 0x80, 0x04, 0x80, 0x03, 0x00,  /*               mov b6=r16         */
2409    0x60, 0x00, 0x80, 0x00               /*               br.few b6;;        */
2410 };
2411
2412 /* If we can't get to the function descriptor via gp, take a local copy of it */
2413 #define PLT_RELOC(code, target) { \
2414    Elf64_Sxword rel_value = target - gp_val; \
2415    if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff)) \
2416       ia64_reloc_gprel22((Elf_Addr)code, copyFunctionDesc(target)); \
2417    else \
2418       ia64_reloc_gprel22((Elf_Addr)code, target); \
2419    }
2420 #endif
2421
2422 typedef struct {
2423    unsigned char code[sizeof(plt_code)];
2424 } PLTEntry;
2425
2426 static Elf_Addr
2427 allocatePLTEntry(Elf_Addr target, ObjectCode *oc)
2428 {
2429    PLTEntry *plt = (PLTEntry *)oc->plt;
2430    PLTEntry *entry;
2431
2432    if (oc->pltIndex >= PLT_SIZE)
2433       barf("Procedure table overflow");
2434
2435    entry = &plt[oc->pltIndex++];
2436    memcpy(entry->code, plt_code, sizeof(entry->code));
2437    PLT_RELOC(entry->code, target);
2438    return (Elf_Addr)entry;
2439 }
2440
2441 static unsigned int
2442 PLTSize(void)
2443 {
2444    return (PLT_SIZE * sizeof(PLTEntry));
2445 }
2446 #endif
2447
2448
2449 /*
2450  * Generic ELF functions
2451  */
2452
2453 static char *
2454 findElfSection ( void* objImage, Elf_Word sh_type )
2455 {
2456    char* ehdrC = (char*)objImage;
2457    Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2458    Elf_Shdr* shdr = (Elf_Shdr*)(ehdrC + ehdr->e_shoff);
2459    char* sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2460    char* ptr = NULL;
2461    int i;
2462
2463    for (i = 0; i < ehdr->e_shnum; i++) {
2464       if (shdr[i].sh_type == sh_type
2465           /* Ignore the section header's string table. */
2466           && i != ehdr->e_shstrndx
2467           /* Ignore string tables named .stabstr, as they contain
2468              debugging info. */
2469           && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2470          ) {
2471          ptr = ehdrC + shdr[i].sh_offset;
2472          break;
2473       }
2474    }
2475    return ptr;
2476 }
2477
2478 #if defined(ia64_HOST_ARCH)
2479 static Elf_Addr
2480 findElfSegment ( void* objImage, Elf_Addr vaddr )
2481 {
2482    char* ehdrC = (char*)objImage;
2483    Elf_Ehdr* ehdr = (Elf_Ehdr*)ehdrC;
2484    Elf_Phdr* phdr = (Elf_Phdr*)(ehdrC + ehdr->e_phoff);
2485    Elf_Addr segaddr = 0;
2486    int i;
2487
2488    for (i = 0; i < ehdr->e_phnum; i++) {
2489       segaddr = phdr[i].p_vaddr;
2490       if ((vaddr >= segaddr) && (vaddr < segaddr + phdr[i].p_memsz))
2491               break;
2492    }
2493    return segaddr;
2494 }
2495 #endif
2496
2497 static int
2498 ocVerifyImage_ELF ( ObjectCode* oc )
2499 {
2500    Elf_Shdr* shdr;
2501    Elf_Sym*  stab;
2502    int i, j, nent, nstrtab, nsymtabs;
2503    char* sh_strtab;
2504    char* strtab;
2505
2506    char*     ehdrC = (char*)(oc->image);
2507    Elf_Ehdr* ehdr  = (Elf_Ehdr*)ehdrC;
2508
2509    if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
2510        ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
2511        ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
2512        ehdr->e_ident[EI_MAG3] != ELFMAG3) {
2513       errorBelch("%s: not an ELF object", oc->fileName);
2514       return 0;
2515    }
2516
2517    if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
2518       errorBelch("%s: unsupported ELF format", oc->fileName);
2519       return 0;
2520    }
2521
2522    if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
2523        IF_DEBUG(linker,debugBelch( "Is little-endian\n" ));
2524    } else
2525    if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
2526        IF_DEBUG(linker,debugBelch( "Is big-endian\n" ));
2527    } else {
2528        errorBelch("%s: unknown endiannness", oc->fileName);
2529        return 0;
2530    }
2531
2532    if (ehdr->e_type != ET_REL) {
2533       errorBelch("%s: not a relocatable object (.o) file", oc->fileName);
2534       return 0;
2535    }
2536    IF_DEBUG(linker, debugBelch( "Is a relocatable object (.o) file\n" ));
2537
2538    IF_DEBUG(linker,debugBelch( "Architecture is " ));
2539    switch (ehdr->e_machine) {
2540       case EM_386:   IF_DEBUG(linker,debugBelch( "x86" )); break;
2541       case EM_SPARC: IF_DEBUG(linker,debugBelch( "sparc" )); break;
2542 #ifdef EM_IA_64
2543       case EM_IA_64: IF_DEBUG(linker,debugBelch( "ia64" )); break;
2544 #endif
2545       case EM_PPC:   IF_DEBUG(linker,debugBelch( "powerpc32" )); break;
2546 #ifdef EM_X86_64
2547       case EM_X86_64: IF_DEBUG(linker,debugBelch( "x86_64" )); break;
2548 #endif
2549       default:       IF_DEBUG(linker,debugBelch( "unknown" ));
2550                      errorBelch("%s: unknown architecture", oc->fileName);
2551                      return 0;
2552    }
2553
2554    IF_DEBUG(linker,debugBelch(
2555              "\nSection header table: start %d, n_entries %d, ent_size %d\n",
2556              ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize  ));
2557
2558    ASSERT (ehdr->e_shentsize == sizeof(Elf_Shdr));
2559
2560    shdr = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2561
2562    if (ehdr->e_shstrndx == SHN_UNDEF) {
2563       errorBelch("%s: no section header string table", oc->fileName);
2564       return 0;
2565    } else {
2566       IF_DEBUG(linker,debugBelch( "Section header string table is section %d\n",
2567                           ehdr->e_shstrndx));
2568       sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
2569    }
2570
2571    for (i = 0; i < ehdr->e_shnum; i++) {
2572       IF_DEBUG(linker,debugBelch("%2d:  ", i ));
2573       IF_DEBUG(linker,debugBelch("type=%2d  ", (int)shdr[i].sh_type ));
2574       IF_DEBUG(linker,debugBelch("size=%4d  ", (int)shdr[i].sh_size ));
2575       IF_DEBUG(linker,debugBelch("offs=%4d  ", (int)shdr[i].sh_offset ));
2576       IF_DEBUG(linker,debugBelch("  (%p .. %p)  ",
2577                ehdrC + shdr[i].sh_offset,
2578                       ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1));
2579
2580       if (shdr[i].sh_type == SHT_REL) {
2581           IF_DEBUG(linker,debugBelch("Rel  " ));
2582       } else if (shdr[i].sh_type == SHT_RELA) {
2583           IF_DEBUG(linker,debugBelch("RelA " ));
2584       } else {
2585           IF_DEBUG(linker,debugBelch("     "));
2586       }
2587       if (sh_strtab) {
2588           IF_DEBUG(linker,debugBelch("sname=%s\n", sh_strtab + shdr[i].sh_name ));
2589       }
2590    }
2591
2592    IF_DEBUG(linker,debugBelch( "\nString tables" ));
2593    strtab = NULL;
2594    nstrtab = 0;
2595    for (i = 0; i < ehdr->e_shnum; i++) {
2596       if (shdr[i].sh_type == SHT_STRTAB
2597           /* Ignore the section header's string table. */
2598           && i != ehdr->e_shstrndx
2599           /* Ignore string tables named .stabstr, as they contain
2600              debugging info. */
2601           && 0 != memcmp(".stabstr", sh_strtab + shdr[i].sh_name, 8)
2602          ) {
2603          IF_DEBUG(linker,debugBelch("   section %d is a normal string table", i ));
2604          strtab = ehdrC + shdr[i].sh_offset;
2605          nstrtab++;
2606       }
2607    }
2608    if (nstrtab != 1) {
2609       errorBelch("%s: no string tables, or too many", oc->fileName);
2610       return 0;
2611    }
2612
2613    nsymtabs = 0;
2614    IF_DEBUG(linker,debugBelch( "\nSymbol tables" ));
2615    for (i = 0; i < ehdr->e_shnum; i++) {
2616       if (shdr[i].sh_type != SHT_SYMTAB) continue;
2617       IF_DEBUG(linker,debugBelch( "section %d is a symbol table\n", i ));
2618       nsymtabs++;
2619       stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2620       nent = shdr[i].sh_size / sizeof(Elf_Sym);
2621       IF_DEBUG(linker,debugBelch( "   number of entries is apparently %d (%d rem)\n",
2622                nent,
2623                shdr[i].sh_size % sizeof(Elf_Sym)
2624              ));
2625       if (0 != shdr[i].sh_size % sizeof(Elf_Sym)) {
2626          errorBelch("%s: non-integral number of symbol table entries", oc->fileName);
2627          return 0;
2628       }
2629       for (j = 0; j < nent; j++) {
2630          IF_DEBUG(linker,debugBelch("   %2d  ", j ));
2631          IF_DEBUG(linker,debugBelch("  sec=%-5d  size=%-3d  val=%5p  ",
2632                              (int)stab[j].st_shndx,
2633                              (int)stab[j].st_size,
2634                              (char*)stab[j].st_value ));
2635
2636          IF_DEBUG(linker,debugBelch("type=" ));
2637          switch (ELF_ST_TYPE(stab[j].st_info)) {
2638             case STT_NOTYPE:  IF_DEBUG(linker,debugBelch("notype " )); break;
2639             case STT_OBJECT:  IF_DEBUG(linker,debugBelch("object " )); break;
2640             case STT_FUNC  :  IF_DEBUG(linker,debugBelch("func   " )); break;
2641             case STT_SECTION: IF_DEBUG(linker,debugBelch("section" )); break;
2642             case STT_FILE:    IF_DEBUG(linker,debugBelch("file   " )); break;
2643             default:          IF_DEBUG(linker,debugBelch("?      " )); break;
2644          }
2645          IF_DEBUG(linker,debugBelch("  " ));
2646
2647          IF_DEBUG(linker,debugBelch("bind=" ));
2648          switch (ELF_ST_BIND(stab[j].st_info)) {
2649             case STB_LOCAL :  IF_DEBUG(linker,debugBelch("local " )); break;
2650             case STB_GLOBAL:  IF_DEBUG(linker,debugBelch("global" )); break;
2651             case STB_WEAK  :  IF_DEBUG(linker,debugBelch("weak  " )); break;
2652             default:          IF_DEBUG(linker,debugBelch("?     " )); break;
2653          }
2654          IF_DEBUG(linker,debugBelch("  " ));
2655
2656          IF_DEBUG(linker,debugBelch("name=%s\n", strtab + stab[j].st_name ));
2657       }
2658    }
2659
2660    if (nsymtabs == 0) {
2661       errorBelch("%s: didn't find any symbol tables", oc->fileName);
2662       return 0;
2663    }
2664
2665    return 1;
2666 }
2667
2668 static int getSectionKind_ELF( Elf_Shdr *hdr, int *is_bss )
2669 {
2670     *is_bss = FALSE;
2671
2672     if (hdr->sh_type == SHT_PROGBITS
2673         && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_EXECINSTR)) {
2674         /* .text-style section */
2675         return SECTIONKIND_CODE_OR_RODATA;
2676     }
2677
2678     if (hdr->sh_type == SHT_PROGBITS
2679             && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
2680             /* .data-style section */
2681             return SECTIONKIND_RWDATA;
2682     }
2683
2684     if (hdr->sh_type == SHT_PROGBITS
2685         && (hdr->sh_flags & SHF_ALLOC) && !(hdr->sh_flags & SHF_WRITE)) {
2686         /* .rodata-style section */
2687         return SECTIONKIND_CODE_OR_RODATA;
2688     }
2689
2690     if (hdr->sh_type == SHT_NOBITS
2691         && (hdr->sh_flags & SHF_ALLOC) && (hdr->sh_flags & SHF_WRITE)) {
2692         /* .bss-style section */
2693         *is_bss = TRUE;
2694         return SECTIONKIND_RWDATA;
2695     }
2696
2697     return SECTIONKIND_OTHER;
2698 }
2699
2700
2701 static int
2702 ocGetNames_ELF ( ObjectCode* oc )
2703 {
2704    int i, j, k, nent;
2705    Elf_Sym* stab;
2706
2707    char*     ehdrC    = (char*)(oc->image);
2708    Elf_Ehdr* ehdr     = (Elf_Ehdr*)ehdrC;
2709    char*     strtab   = findElfSection ( ehdrC, SHT_STRTAB );
2710    Elf_Shdr* shdr     = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
2711
2712    ASSERT(symhash != NULL);
2713
2714    if (!strtab) {
2715       errorBelch("%s: no strtab", oc->fileName);
2716       return 0;
2717    }
2718
2719    k = 0;
2720    for (i = 0; i < ehdr->e_shnum; i++) {
2721       /* Figure out what kind of section it is.  Logic derived from
2722          Figure 1.14 ("Special Sections") of the ELF document
2723          ("Portable Formats Specification, Version 1.1"). */
2724       int         is_bss = FALSE;
2725       SectionKind kind   = getSectionKind_ELF(&shdr[i], &is_bss);
2726
2727       if (is_bss && shdr[i].sh_size > 0) {
2728          /* This is a non-empty .bss section.  Allocate zeroed space for
2729             it, and set its .sh_offset field such that
2730             ehdrC + .sh_offset == addr_of_zeroed_space.  */
2731          char* zspace = stgCallocBytes(1, shdr[i].sh_size,
2732                                        "ocGetNames_ELF(BSS)");
2733          shdr[i].sh_offset = ((char*)zspace) - ((char*)ehdrC);
2734          /*
2735          debugBelch("BSS section at 0x%x, size %d\n",
2736                          zspace, shdr[i].sh_size);
2737          */
2738       }
2739
2740       /* fill in the section info */
2741       if (kind != SECTIONKIND_OTHER && shdr[i].sh_size > 0) {
2742          addProddableBlock(oc, ehdrC + shdr[i].sh_offset, shdr[i].sh_size);
2743          addSection(oc, kind, ehdrC + shdr[i].sh_offset,
2744                         ehdrC + shdr[i].sh_offset + shdr[i].sh_size - 1);
2745       }
2746
2747       if (shdr[i].sh_type != SHT_SYMTAB) continue;
2748
2749       /* copy stuff into this module's object symbol table */
2750       stab = (Elf_Sym*) (ehdrC + shdr[i].sh_offset);
2751       nent = shdr[i].sh_size / sizeof(Elf_Sym);
2752
2753       oc->n_symbols = nent;
2754       oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
2755                                    "ocGetNames_ELF(oc->symbols)");
2756
2757       for (j = 0; j < nent; j++) {
2758
2759          char  isLocal = FALSE; /* avoids uninit-var warning */
2760          char* ad      = NULL;
2761          char* nm      = strtab + stab[j].st_name;
2762          int   secno   = stab[j].st_shndx;
2763
2764          /* Figure out if we want to add it; if so, set ad to its
2765             address.  Otherwise leave ad == NULL. */
2766
2767          if (secno == SHN_COMMON) {
2768             isLocal = FALSE;
2769             ad = stgCallocBytes(1, stab[j].st_size, "ocGetNames_ELF(COMMON)");
2770             /*
2771             debugBelch("COMMON symbol, size %d name %s\n",
2772                             stab[j].st_size, nm);
2773             */
2774             /* Pointless to do addProddableBlock() for this area,
2775                since the linker should never poke around in it. */
2776          }
2777          else
2778          if ( ( ELF_ST_BIND(stab[j].st_info)==STB_GLOBAL
2779                 || ELF_ST_BIND(stab[j].st_info)==STB_LOCAL
2780               )
2781               /* and not an undefined symbol */
2782               && stab[j].st_shndx != SHN_UNDEF
2783               /* and not in a "special section" */
2784               && stab[j].st_shndx < SHN_LORESERVE
2785               &&
2786               /* and it's a not a section or string table or anything silly */
2787               ( ELF_ST_TYPE(stab[j].st_info)==STT_FUNC ||
2788                 ELF_ST_TYPE(stab[j].st_info)==STT_OBJECT ||
2789                 ELF_ST_TYPE(stab[j].st_info)==STT_NOTYPE
2790               )
2791             ) {
2792             /* Section 0 is the undefined section, hence > and not >=. */
2793             ASSERT(secno > 0 && secno < ehdr->e_shnum);
2794             /*
2795             if (shdr[secno].sh_type == SHT_NOBITS) {
2796                debugBelch("   BSS symbol, size %d off %d name %s\n",
2797                                stab[j].st_size, stab[j].st_value, nm);
2798             }
2799             */
2800             ad = ehdrC + shdr[ secno ].sh_offset + stab[j].st_value;
2801             if (ELF_ST_BIND(stab[j].st_info)==STB_LOCAL) {
2802                isLocal = TRUE;
2803             } else {
2804 #ifdef ELF_FUNCTION_DESC
2805                /* dlsym() and the initialisation table both give us function
2806                 * descriptors, so to be consistent we store function descriptors
2807                 * in the symbol table */
2808                if (ELF_ST_TYPE(stab[j].st_info) == STT_FUNC)
2809                    ad = (char *)allocateFunctionDesc((Elf_Addr)ad);
2810 #endif
2811                IF_DEBUG(linker,debugBelch( "addOTabName(GLOB): %10p  %s %s",
2812                                       ad, oc->fileName, nm ));
2813                isLocal = FALSE;
2814             }
2815          }
2816
2817          /* And the decision is ... */
2818
2819          if (ad != NULL) {
2820             ASSERT(nm != NULL);
2821             oc->symbols[j] = nm;
2822             /* Acquire! */
2823             if (isLocal) {
2824                /* Ignore entirely. */
2825             } else {
2826                ghciInsertStrHashTable(oc->fileName, symhash, nm, ad);
2827             }
2828          } else {
2829             /* Skip. */
2830             IF_DEBUG(linker,debugBelch( "skipping `%s'\n",
2831                                    strtab + stab[j].st_name ));
2832             /*
2833             debugBelch(
2834                     "skipping   bind = %d,  type = %d,  shndx = %d   `%s'\n",
2835                     (int)ELF_ST_BIND(stab[j].st_info),
2836                     (int)ELF_ST_TYPE(stab[j].st_info),
2837                     (int)stab[j].st_shndx,
2838                     strtab + stab[j].st_name
2839                    );
2840             */
2841             oc->symbols[j] = NULL;
2842          }
2843
2844       }
2845    }
2846
2847    return 1;
2848 }
2849
2850 /* Do ELF relocations which lack an explicit addend.  All x86-linux
2851    relocations appear to be of this form. */
2852 static int
2853 do_Elf_Rel_relocations ( ObjectCode* oc, char* ehdrC,
2854                          Elf_Shdr* shdr, int shnum,
2855                          Elf_Sym*  stab, char* strtab )
2856 {
2857    int j;
2858    char *symbol;
2859    Elf_Word* targ;
2860    Elf_Rel*  rtab = (Elf_Rel*) (ehdrC + shdr[shnum].sh_offset);
2861    int         nent = shdr[shnum].sh_size / sizeof(Elf_Rel);
2862    int target_shndx = shdr[shnum].sh_info;
2863    int symtab_shndx = shdr[shnum].sh_link;
2864
2865    stab  = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2866    targ  = (Elf_Word*)(ehdrC + shdr[ target_shndx ].sh_offset);
2867    IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
2868                           target_shndx, symtab_shndx ));
2869
2870    /* Skip sections that we're not interested in. */
2871    {
2872        int is_bss;
2873        SectionKind kind = getSectionKind_ELF(&shdr[target_shndx], &is_bss);
2874        if (kind == SECTIONKIND_OTHER) {
2875            IF_DEBUG(linker,debugBelch( "skipping (target section not loaded)"));
2876            return 1;
2877        }
2878    }
2879
2880    for (j = 0; j < nent; j++) {
2881       Elf_Addr offset = rtab[j].r_offset;
2882       Elf_Addr info   = rtab[j].r_info;
2883
2884       Elf_Addr  P  = ((Elf_Addr)targ) + offset;
2885       Elf_Word* pP = (Elf_Word*)P;
2886       Elf_Addr  A  = *pP;
2887       Elf_Addr  S;
2888       void*     S_tmp;
2889       Elf_Addr  value;
2890
2891       IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p)",
2892                              j, (void*)offset, (void*)info ));
2893       if (!info) {
2894          IF_DEBUG(linker,debugBelch( " ZERO" ));
2895          S = 0;
2896       } else {
2897          Elf_Sym sym = stab[ELF_R_SYM(info)];
2898          /* First see if it is a local symbol. */
2899          if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
2900             /* Yes, so we can get the address directly from the ELF symbol
2901                table. */
2902             symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
2903             S = (Elf_Addr)
2904                 (ehdrC + shdr[ sym.st_shndx ].sh_offset
2905                        + stab[ELF_R_SYM(info)].st_value);
2906
2907          } else {
2908             /* No, so look up the name in our global table. */
2909             symbol = strtab + sym.st_name;
2910             S_tmp = lookupSymbol( symbol );
2911             S = (Elf_Addr)S_tmp;
2912          }
2913          if (!S) {
2914             errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
2915             return 0;
2916          }
2917          IF_DEBUG(linker,debugBelch( "`%s' resolves to %p\n", symbol, (void*)S ));
2918       }
2919
2920       IF_DEBUG(linker,debugBelch( "Reloc: P = %p   S = %p   A = %p\n",
2921                              (void*)P, (void*)S, (void*)A ));
2922       checkProddableBlock ( oc, pP );
2923
2924       value = S + A;
2925
2926       switch (ELF_R_TYPE(info)) {
2927 #        ifdef i386_HOST_ARCH
2928          case R_386_32:   *pP = value;     break;
2929          case R_386_PC32: *pP = value - P; break;
2930 #        endif
2931          default:
2932             errorBelch("%s: unhandled ELF relocation(Rel) type %d\n",
2933                   oc->fileName, ELF_R_TYPE(info));
2934             return 0;
2935       }
2936
2937    }
2938    return 1;
2939 }
2940
2941 /* Do ELF relocations for which explicit addends are supplied.
2942    sparc-solaris relocations appear to be of this form. */
2943 static int
2944 do_Elf_Rela_relocations ( ObjectCode* oc, char* ehdrC,
2945                           Elf_Shdr* shdr, int shnum,
2946                           Elf_Sym*  stab, char* strtab )
2947 {
2948    int j;
2949    char *symbol;
2950    Elf_Addr targ;
2951    Elf_Rela* rtab = (Elf_Rela*) (ehdrC + shdr[shnum].sh_offset);
2952    int         nent = shdr[shnum].sh_size / sizeof(Elf_Rela);
2953    int target_shndx = shdr[shnum].sh_info;
2954    int symtab_shndx = shdr[shnum].sh_link;
2955
2956    stab  = (Elf_Sym*) (ehdrC + shdr[ symtab_shndx ].sh_offset);
2957    targ  = (Elf_Addr) (ehdrC + shdr[ target_shndx ].sh_offset);
2958    IF_DEBUG(linker,debugBelch( "relocations for section %d using symtab %d\n",
2959                           target_shndx, symtab_shndx ));
2960
2961    for (j = 0; j < nent; j++) {
2962 #if defined(DEBUG) || defined(sparc_HOST_ARCH) || defined(ia64_HOST_ARCH) || defined(powerpc_HOST_ARCH) || defined(x86_64_HOST_ARCH)
2963       /* This #ifdef only serves to avoid unused-var warnings. */
2964       Elf_Addr  offset = rtab[j].r_offset;
2965       Elf_Addr  P      = targ + offset;
2966 #endif
2967       Elf_Addr  info   = rtab[j].r_info;
2968       Elf_Addr  A      = rtab[j].r_addend;
2969       Elf_Addr  S;
2970       void*     S_tmp;
2971       Elf_Addr  value;
2972 #     if defined(sparc_HOST_ARCH)
2973       Elf_Word* pP = (Elf_Word*)P;
2974       Elf_Word  w1, w2;
2975 #     elif defined(ia64_HOST_ARCH)
2976       Elf64_Xword *pP = (Elf64_Xword *)P;
2977       Elf_Addr addr;
2978 #     elif defined(powerpc_HOST_ARCH)
2979       Elf_Sword delta;
2980 #     endif
2981
2982       IF_DEBUG(linker,debugBelch( "Rel entry %3d is raw(%6p %6p %6p)   ",
2983                              j, (void*)offset, (void*)info,
2984                                 (void*)A ));
2985       if (!info) {
2986          IF_DEBUG(linker,debugBelch( " ZERO" ));
2987          S = 0;
2988       } else {
2989          Elf_Sym sym = stab[ELF_R_SYM(info)];
2990          /* First see if it is a local symbol. */
2991          if (ELF_ST_BIND(sym.st_info) == STB_LOCAL) {
2992             /* Yes, so we can get the address directly from the ELF symbol
2993                table. */
2994             symbol = sym.st_name==0 ? "(noname)" : strtab+sym.st_name;
2995             S = (Elf_Addr)
2996                 (ehdrC + shdr[ sym.st_shndx ].sh_offset
2997                        + stab[ELF_R_SYM(info)].st_value);
2998 #ifdef ELF_FUNCTION_DESC
2999             /* Make a function descriptor for this function */
3000             if (S && ELF_ST_TYPE(sym.st_info) == STT_FUNC) {
3001                S = allocateFunctionDesc(S + A);
3002                A = 0;
3003             }
3004 #endif
3005          } else {
3006             /* No, so look up the name in our global table. */
3007             symbol = strtab + sym.st_name;
3008             S_tmp = lookupSymbol( symbol );
3009             S = (Elf_Addr)S_tmp;
3010
3011 #ifdef ELF_FUNCTION_DESC
3012             /* If a function, already a function descriptor - we would
3013                have to copy it to add an offset. */
3014             if (S && (ELF_ST_TYPE(sym.st_info) == STT_FUNC) && (A != 0))
3015                errorBelch("%s: function %s with addend %p", oc->fileName, symbol, (void *)A);
3016 #endif
3017          }
3018          if (!S) {
3019            errorBelch("%s: unknown symbol `%s'", oc->fileName, symbol);
3020            return 0;
3021          }
3022          IF_DEBUG(linker,debugBelch( "`%s' resolves to %p", symbol, (void*)S ));
3023       }
3024
3025       IF_DEBUG(linker,debugBelch("Reloc: P = %p   S = %p   A = %p\n",
3026                                         (void*)P, (void*)S, (void*)A ));
3027       /* checkProddableBlock ( oc, (void*)P ); */
3028
3029       value = S + A;
3030
3031       switch (ELF_R_TYPE(info)) {
3032 #        if defined(sparc_HOST_ARCH)
3033          case R_SPARC_WDISP30:
3034             w1 = *pP & 0xC0000000;
3035             w2 = (Elf_Word)((value - P) >> 2);
3036             ASSERT((w2 & 0xC0000000) == 0);
3037             w1 |= w2;
3038             *pP = w1;
3039             break;
3040          case R_SPARC_HI22:
3041             w1 = *pP & 0xFFC00000;
3042             w2 = (Elf_Word)(value >> 10);
3043             ASSERT((w2 & 0xFFC00000) == 0);
3044             w1 |= w2;
3045             *pP = w1;
3046             break;
3047          case R_SPARC_LO10:
3048             w1 = *pP & ~0x3FF;
3049             w2 = (Elf_Word)(value & 0x3FF);
3050             ASSERT((w2 & ~0x3FF) == 0);
3051             w1 |= w2;
3052             *pP = w1;
3053             break;
3054          /* According to the Sun documentation:
3055             R_SPARC_UA32
3056             This relocation type resembles R_SPARC_32, except it refers to an
3057             unaligned word. That is, the word to be relocated must be treated
3058             as four separate bytes with arbitrary alignment, not as a word
3059             aligned according to the architecture requirements.
3060
3061             (JRS: which means that freeloading on the R_SPARC_32 case
3062             is probably wrong, but hey ...)
3063          */
3064          case R_SPARC_UA32:
3065          case R_SPARC_32:
3066             w2 = (Elf_Word)value;
3067             *pP = w2;
3068             break;
3069 #        elif defined(ia64_HOST_ARCH)
3070          case R_IA64_DIR64LSB:
3071          case R_IA64_FPTR64LSB:
3072             *pP = value;
3073             break;
3074          case R_IA64_PCREL64LSB:
3075             *pP = value - P;
3076             break;
3077          case R_IA64_SEGREL64LSB:
3078             addr = findElfSegment(ehdrC, value);
3079             *pP = value - addr;
3080             break;
3081          case R_IA64_GPREL22:
3082             ia64_reloc_gprel22(P, value);
3083             break;
3084          case R_IA64_LTOFF22:
3085          case R_IA64_LTOFF22X:
3086          case R_IA64_LTOFF_FPTR22:
3087             addr = allocateGOTEntry(value);
3088             ia64_reloc_gprel22(P, addr);
3089             break;
3090          case R_IA64_PCREL21B:
3091             ia64_reloc_pcrel21(P, S, oc);
3092             break;
3093          case R_IA64_LDXMOV:
3094             /* This goes with R_IA64_LTOFF22X and points to the load to
3095              * convert into a move.  We don't implement relaxation. */
3096             break;
3097 #        elif defined(powerpc_HOST_ARCH)
3098          case R_PPC_ADDR16_LO:
3099             *(Elf32_Half*) P = value;
3100             break;
3101
3102          case R_PPC_ADDR16_HI:
3103             *(Elf32_Half*) P = value >> 16;
3104             break;
3105  
3106          case R_PPC_ADDR16_HA:
3107             *(Elf32_Half*) P = (value + 0x8000) >> 16;
3108             break;
3109
3110          case R_PPC_ADDR32:
3111             *(Elf32_Word *) P = value;
3112             break;
3113
3114          case R_PPC_REL32:
3115             *(Elf32_Word *) P = value - P;
3116             break;
3117
3118          case R_PPC_REL24:
3119             delta = value - P;
3120
3121             if( delta << 6 >> 6 != delta )
3122             {
3123                value = makeJumpIsland( oc, ELF_R_SYM(info), value );
3124                delta = value - P;
3125
3126                if( value == 0 || delta << 6 >> 6 != delta )
3127                {
3128                   barf( "Unable to make ppcJumpIsland for #%d",
3129                         ELF_R_SYM(info) );
3130                   return 0;
3131                }
3132             }
3133
3134             *(Elf_Word *) P = (*(Elf_Word *) P & 0xfc000003)
3135                                           | (delta & 0x3fffffc);
3136             break;
3137 #        endif
3138
3139 #if x86_64_HOST_OS
3140       case R_X86_64_64:
3141           *(Elf64_Xword *)P = value;
3142           break;
3143
3144       case R_X86_64_PC32:
3145           *(Elf64_Word *)P = (Elf64_Word) (value - P);
3146           break;
3147
3148       case R_X86_64_32:
3149           *(Elf64_Word *)P = (Elf64_Word)value;
3150           break;
3151
3152       case R_X86_64_32S:
3153           *(Elf64_Sword *)P = (Elf64_Sword)value;
3154           break;
3155 #endif
3156
3157          default:
3158             errorBelch("%s: unhandled ELF relocation(RelA) type %d\n",
3159                   oc->fileName, ELF_R_TYPE(info));
3160             return 0;
3161       }
3162
3163    }
3164    return 1;
3165 }
3166
3167 static int
3168 ocResolve_ELF ( ObjectCode* oc )
3169 {
3170    char *strtab;
3171    int   shnum, ok;
3172    Elf_Sym*  stab  = NULL;
3173    char*     ehdrC = (char*)(oc->image);
3174    Elf_Ehdr* ehdr  = (Elf_Ehdr*) ehdrC;
3175    Elf_Shdr* shdr  = (Elf_Shdr*) (ehdrC + ehdr->e_shoff);
3176
3177    /* first find "the" symbol table */
3178    stab = (Elf_Sym*) findElfSection ( ehdrC, SHT_SYMTAB );
3179
3180    /* also go find the string table */
3181    strtab = findElfSection ( ehdrC, SHT_STRTAB );
3182
3183    if (stab == NULL || strtab == NULL) {
3184       errorBelch("%s: can't find string or symbol table", oc->fileName);
3185       return 0;
3186    }
3187
3188    /* Process the relocation sections. */
3189    for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
3190       if (shdr[shnum].sh_type == SHT_REL) {
3191          ok = do_Elf_Rel_relocations ( oc, ehdrC, shdr,
3192                                        shnum, stab, strtab );
3193          if (!ok) return ok;
3194       }
3195       else
3196       if (shdr[shnum].sh_type == SHT_RELA) {
3197          ok = do_Elf_Rela_relocations ( oc, ehdrC, shdr,
3198                                         shnum, stab, strtab );
3199          if (!ok) return ok;
3200       }
3201    }
3202
3203    /* Free the local symbol table; we won't need it again. */
3204    freeHashTable(oc->lochash, NULL);
3205    oc->lochash = NULL;
3206
3207 #if defined(powerpc_HOST_ARCH)
3208    ocFlushInstructionCache( oc );
3209 #endif
3210
3211    return 1;
3212 }
3213
3214 /*
3215  * IA64 specifics
3216  * Instructions are 41 bits long, packed into 128 bit bundles with a 5-bit template
3217  * at the front.  The following utility functions pack and unpack instructions, and
3218  * take care of the most common relocations.
3219  */
3220
3221 #ifdef ia64_HOST_ARCH
3222
3223 static Elf64_Xword
3224 ia64_extract_instruction(Elf64_Xword *target)
3225 {
3226    Elf64_Xword w1, w2;
3227    int slot = (Elf_Addr)target & 3;
3228    (Elf_Addr)target &= ~3;
3229
3230    w1 = *target;
3231    w2 = *(target+1);
3232
3233    switch (slot)
3234    {
3235       case 0:
3236          return ((w1 >> 5) & 0x1ffffffffff);
3237       case 1:
3238          return (w1 >> 46) | ((w2 & 0x7fffff) << 18);
3239       case 2:
3240          return (w2 >> 23);
3241       default:
3242          barf("ia64_extract_instruction: invalid slot %p", target);
3243    }
3244 }
3245
3246 static void
3247 ia64_deposit_instruction(Elf64_Xword *target, Elf64_Xword value)
3248 {
3249    int slot = (Elf_Addr)target & 3;
3250    (Elf_Addr)target &= ~3;
3251
3252    switch (slot)
3253    {
3254       case 0:
3255          *target |= value << 5;
3256          break;
3257       case 1:
3258          *target |= value << 46;
3259          *(target+1) |= value >> 18;
3260          break;
3261       case 2:
3262          *(target+1) |= value << 23;
3263          break;
3264    }
3265 }
3266
3267 static void
3268 ia64_reloc_gprel22(Elf_Addr target, Elf_Addr value)
3269 {
3270    Elf64_Xword instruction;
3271    Elf64_Sxword rel_value;
3272
3273    rel_value = value - gp_val;
3274    if ((rel_value > 0x1fffff) || (rel_value < -0x1fffff))
3275       barf("GP-relative data out of range (address = 0x%lx, gp = 0x%lx)", value, gp_val);
3276
3277    instruction = ia64_extract_instruction((Elf64_Xword *)target);
3278    instruction |= (((rel_value >> 0) & 0x07f) << 13)            /* imm7b */
3279                     | (((rel_value >> 7) & 0x1ff) << 27)        /* imm9d */
3280                     | (((rel_value >> 16) & 0x01f) << 22)       /* imm5c */
3281                     | ((Elf64_Xword)(rel_value < 0) << 36);     /* s */
3282    ia64_deposit_instruction((Elf64_Xword *)target, instruction);
3283 }
3284
3285 static void
3286 ia64_reloc_pcrel21(Elf_Addr target, Elf_Addr value, ObjectCode *oc)
3287 {
3288    Elf64_Xword instruction;
3289    Elf64_Sxword rel_value;
3290    Elf_Addr entry;
3291
3292    entry = allocatePLTEntry(value, oc);
3293
3294    rel_value = (entry >> 4) - (target >> 4);
3295    if ((rel_value > 0xfffff) || (rel_value < -0xfffff))
3296       barf("PLT entry too far away (entry = 0x%lx, target = 0x%lx)", entry, target);
3297
3298    instruction = ia64_extract_instruction((Elf64_Xword *)target);
3299    instruction |= ((rel_value & 0xfffff) << 13)                 /* imm20b */
3300                     | ((Elf64_Xword)(rel_value < 0) << 36);     /* s */
3301    ia64_deposit_instruction((Elf64_Xword *)target, instruction);
3302 }
3303
3304 #endif /* ia64 */
3305
3306 /*
3307  * PowerPC ELF specifics
3308  */
3309
3310 #ifdef powerpc_HOST_ARCH
3311
3312 static int ocAllocateJumpIslands_ELF( ObjectCode *oc )
3313 {
3314   Elf_Ehdr *ehdr;
3315   Elf_Shdr* shdr;
3316   int i;
3317
3318   ehdr = (Elf_Ehdr *) oc->image;
3319   shdr = (Elf_Shdr *) ( ((char *)oc->image) + ehdr->e_shoff );
3320
3321   for( i = 0; i < ehdr->e_shnum; i++ )
3322     if( shdr[i].sh_type == SHT_SYMTAB )
3323       break;
3324
3325   if( i == ehdr->e_shnum )
3326   {
3327     errorBelch( "This ELF file contains no symtab" );
3328     return 0;
3329   }
3330
3331   if( shdr[i].sh_entsize != sizeof( Elf_Sym ) )
3332   {
3333     errorBelch( "The entry size (%d) of the symtab isn't %d\n",
3334       shdr[i].sh_entsize, sizeof( Elf_Sym ) );
3335     
3336     return 0;
3337   }
3338
3339   return ocAllocateJumpIslands( oc, shdr[i].sh_size / sizeof( Elf_Sym ), 0 );
3340 }
3341
3342 #endif /* powerpc */
3343
3344 #endif /* ELF */
3345
3346 /* --------------------------------------------------------------------------
3347  * Mach-O specifics
3348  * ------------------------------------------------------------------------*/
3349
3350 #if defined(OBJFORMAT_MACHO)
3351
3352 /*
3353   Support for MachO linking on Darwin/MacOS X on PowerPC chips
3354   by Wolfgang Thaller (wolfgang.thaller@gmx.net)
3355
3356   I hereby formally apologize for the hackish nature of this code.
3357   Things that need to be done:
3358   *) implement ocVerifyImage_MachO
3359   *) add still more sanity checks.
3360 */
3361
3362 static int ocAllocateJumpIslands_MachO(ObjectCode* oc)
3363 {
3364     struct mach_header *header = (struct mach_header *) oc->image;
3365     struct load_command *lc = (struct load_command *) (header + 1);
3366     unsigned i;
3367
3368     for( i = 0; i < header->ncmds; i++ )
3369     {   
3370         if( lc->cmd == LC_SYMTAB )
3371         {
3372                 // Find out the first and last undefined external
3373                 // symbol, so we don't have to allocate too many
3374                 // jump islands.
3375             struct symtab_command *symLC = (struct symtab_command *) lc;
3376             unsigned min = symLC->nsyms, max = 0;
3377             struct nlist *nlist =
3378                 symLC ? (struct nlist*) ((char*) oc->image + symLC->symoff)
3379                       : NULL;
3380             for(i=0;i<symLC->nsyms;i++)
3381             {
3382                 if(nlist[i].n_type & N_STAB)
3383                     ;
3384                 else if(nlist[i].n_type & N_EXT)
3385                 {
3386                     if((nlist[i].n_type & N_TYPE) == N_UNDF
3387                         && (nlist[i].n_value == 0))
3388                     {
3389                         if(i < min)
3390                             min = i;
3391                         if(i > max)
3392                             max = i;
3393                     }
3394                 }
3395             }
3396             if(max >= min)
3397                 return ocAllocateJumpIslands(oc, max - min + 1, min);
3398
3399             break;
3400         }
3401         
3402         lc = (struct load_command *) ( ((char *)lc) + lc->cmdsize );
3403     }
3404     return ocAllocateJumpIslands(oc,0,0);
3405 }
3406
3407 static int ocVerifyImage_MachO(ObjectCode* oc STG_UNUSED)
3408 {
3409     // FIXME: do some verifying here
3410     return 1;
3411 }
3412
3413 static int resolveImports(
3414     ObjectCode* oc,
3415     char *image,
3416     struct symtab_command *symLC,
3417     struct section *sect,    // ptr to lazy or non-lazy symbol pointer section
3418     unsigned long *indirectSyms,
3419     struct nlist *nlist)
3420 {
3421     unsigned i;
3422
3423     for(i=0;i*4<sect->size;i++)
3424     {
3425         // according to otool, reserved1 contains the first index into the indirect symbol table
3426         struct nlist *symbol = &nlist[indirectSyms[sect->reserved1+i]];
3427         char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3428         void *addr = NULL;
3429
3430         if((symbol->n_type & N_TYPE) == N_UNDF
3431             && (symbol->n_type & N_EXT) && (symbol->n_value != 0))
3432             addr = (void*) (symbol->n_value);
3433         else if((addr = lookupLocalSymbol(oc,nm)) != NULL)
3434             ;
3435         else
3436             addr = lookupSymbol(nm);
3437         if(!addr)
3438         {
3439             errorBelch("\n%s: unknown symbol `%s'", oc->fileName, nm);
3440             return 0;
3441         }
3442         ASSERT(addr);
3443         checkProddableBlock(oc,((void**)(image + sect->offset)) + i);
3444         ((void**)(image + sect->offset))[i] = addr;
3445     }
3446
3447     return 1;
3448 }
3449
3450 static unsigned long relocateAddress(
3451     ObjectCode* oc,
3452     int nSections,
3453     struct section* sections,
3454     unsigned long address)
3455 {
3456     int i;
3457     for(i = 0; i < nSections; i++)
3458     {
3459         if(sections[i].addr <= address
3460             && address < sections[i].addr + sections[i].size)
3461         {
3462             return (unsigned long)oc->image
3463                     + sections[i].offset + address - sections[i].addr;
3464         }
3465     }
3466     barf("Invalid Mach-O file:"
3467          "Address out of bounds while relocating object file");
3468     return 0;
3469 }
3470
3471 static int relocateSection(
3472     ObjectCode* oc,
3473     char *image,
3474     struct symtab_command *symLC, struct nlist *nlist,
3475     int nSections, struct section* sections, struct section *sect)
3476 {
3477     struct relocation_info *relocs;
3478     int i,n;
3479
3480     if(!strcmp(sect->sectname,"__la_symbol_ptr"))
3481         return 1;
3482     else if(!strcmp(sect->sectname,"__nl_symbol_ptr"))
3483         return 1;
3484
3485     n = sect->nreloc;
3486     relocs = (struct relocation_info*) (image + sect->reloff);
3487
3488     for(i=0;i<n;i++)
3489     {
3490         if(relocs[i].r_address & R_SCATTERED)
3491         {
3492             struct scattered_relocation_info *scat =
3493                 (struct scattered_relocation_info*) &relocs[i];
3494
3495             if(!scat->r_pcrel)
3496             {
3497                 if(scat->r_length == 2)
3498                 {
3499                     unsigned long word = 0;
3500                     unsigned long* wordPtr = (unsigned long*) (image + sect->offset + scat->r_address);
3501                     checkProddableBlock(oc,wordPtr);
3502
3503                     // Step 1: Figure out what the relocated value should be
3504                     if(scat->r_type == GENERIC_RELOC_VANILLA)
3505                     {
3506                         word = *wordPtr + (unsigned long) relocateAddress(
3507                                                                 oc,
3508                                                                 nSections,
3509                                                                 sections,
3510                                                                 scat->r_value)
3511                                         - scat->r_value;
3512                     }
3513                     else if(scat->r_type == PPC_RELOC_SECTDIFF
3514                         || scat->r_type == PPC_RELOC_LO16_SECTDIFF
3515                         || scat->r_type == PPC_RELOC_HI16_SECTDIFF
3516                         || scat->r_type == PPC_RELOC_HA16_SECTDIFF)
3517                     {
3518                         struct scattered_relocation_info *pair =
3519                                 (struct scattered_relocation_info*) &relocs[i+1];
3520
3521                         if(!pair->r_scattered || pair->r_type != PPC_RELOC_PAIR)
3522                             barf("Invalid Mach-O file: "
3523                                  "PPC_RELOC_*_SECTDIFF not followed by PPC_RELOC_PAIR");
3524
3525                         word = (unsigned long)
3526                                (relocateAddress(oc, nSections, sections, scat->r_value)
3527                               - relocateAddress(oc, nSections, sections, pair->r_value));
3528                         i++;
3529                     }
3530                     else if(scat->r_type == PPC_RELOC_HI16
3531                          || scat->r_type == PPC_RELOC_LO16
3532                          || scat->r_type == PPC_RELOC_HA16
3533                          || scat->r_type == PPC_RELOC_LO14)
3534                     {   // these are generated by label+offset things
3535                         struct relocation_info *pair = &relocs[i+1];
3536                         if((pair->r_address & R_SCATTERED) || pair->r_type != PPC_RELOC_PAIR)
3537                             barf("Invalid Mach-O file: "
3538                                  "PPC_RELOC_* not followed by PPC_RELOC_PAIR");
3539                         
3540                         if(scat->r_type == PPC_RELOC_LO16)
3541                         {
3542                             word = ((unsigned short*) wordPtr)[1];
3543                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3544                         }
3545                         else if(scat->r_type == PPC_RELOC_LO14)
3546                         {
3547                             barf("Unsupported Relocation: PPC_RELOC_LO14");
3548                             word = ((unsigned short*) wordPtr)[1] & 0xFFFC;
3549                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3550                         }
3551                         else if(scat->r_type == PPC_RELOC_HI16)
3552                         {
3553                             word = ((unsigned short*) wordPtr)[1] << 16;
3554                             word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
3555                         }
3556                         else if(scat->r_type == PPC_RELOC_HA16)
3557                         {
3558                             word = ((unsigned short*) wordPtr)[1] << 16;
3559                             word += ((short)relocs[i+1].r_address & (short)0xFFFF);
3560                         }
3561                        
3562                         
3563                         word += (unsigned long) relocateAddress(oc, nSections, sections, scat->r_value)
3564                                                 - scat->r_value;
3565                         
3566                         i++;
3567                     }
3568                     else
3569                         continue;  // ignore the others
3570
3571                     if(scat->r_type == GENERIC_RELOC_VANILLA
3572                         || scat->r_type == PPC_RELOC_SECTDIFF)
3573                     {
3574                         *wordPtr = word;
3575                     }
3576                     else if(scat->r_type == PPC_RELOC_LO16_SECTDIFF || scat->r_type == PPC_RELOC_LO16)
3577                     {
3578                         ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
3579                     }
3580                     else if(scat->r_type == PPC_RELOC_HI16_SECTDIFF || scat->r_type == PPC_RELOC_HI16)
3581                     {
3582                         ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
3583                     }
3584                     else if(scat->r_type == PPC_RELOC_HA16_SECTDIFF || scat->r_type == PPC_RELOC_HA16)
3585                     {
3586                         ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
3587                             + ((word & (1<<15)) ? 1 : 0);
3588                     }
3589                 }
3590             }
3591
3592             continue; // FIXME: I hope it's OK to ignore all the others.
3593         }
3594         else
3595         {
3596             struct relocation_info *reloc = &relocs[i];
3597             if(reloc->r_pcrel && !reloc->r_extern)
3598                 continue;
3599
3600             if(reloc->r_length == 2)
3601             {
3602                 unsigned long word = 0;
3603                 unsigned long jumpIsland = 0;
3604                 long offsetToJumpIsland = 0xBADBAD42; // initialise to bad value
3605                                                       // to avoid warning and to catch
3606                                                       // bugs.
3607
3608                 unsigned long* wordPtr = (unsigned long*) (image + sect->offset + reloc->r_address);
3609                 checkProddableBlock(oc,wordPtr);
3610
3611                 if(reloc->r_type == GENERIC_RELOC_VANILLA)
3612                 {
3613                     word = *wordPtr;
3614                 }
3615                 else if(reloc->r_type == PPC_RELOC_LO16)
3616                 {
3617                     word = ((unsigned short*) wordPtr)[1];
3618                     word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF) << 16;
3619                 }
3620                 else if(reloc->r_type == PPC_RELOC_HI16)
3621                 {
3622                     word = ((unsigned short*) wordPtr)[1] << 16;
3623                     word |= ((unsigned long) relocs[i+1].r_address & 0xFFFF);
3624                 }
3625                 else if(reloc->r_type == PPC_RELOC_HA16)
3626                 {
3627                     word = ((unsigned short*) wordPtr)[1] << 16;
3628                     word += ((short)relocs[i+1].r_address & (short)0xFFFF);
3629                 }
3630                 else if(reloc->r_type == PPC_RELOC_BR24)
3631                 {
3632                     word = *wordPtr;
3633                     word = (word & 0x03FFFFFC) | ((word & 0x02000000) ? 0xFC000000 : 0);
3634                 }
3635
3636
3637                 if(!reloc->r_extern)
3638                 {
3639                     long delta =
3640                         sections[reloc->r_symbolnum-1].offset
3641                         - sections[reloc->r_symbolnum-1].addr
3642                         + ((long) image);
3643
3644                     word += delta;
3645                 }
3646                 else
3647                 {
3648                     struct nlist *symbol = &nlist[reloc->r_symbolnum];
3649                     char *nm = image + symLC->stroff + symbol->n_un.n_strx;
3650                     void *symbolAddress = lookupSymbol(nm);
3651                     if(!symbolAddress)
3652                     {
3653                         errorBelch("\nunknown symbol `%s'", nm);
3654                         return 0;
3655                     }
3656
3657                     if(reloc->r_pcrel)
3658                     {  
3659                             // In the .o file, this should be a relative jump to NULL
3660                             // and we'll change it to a jump to a relative jump to the symbol
3661                         ASSERT(-word == reloc->r_address);
3662                         word = (unsigned long) symbolAddress;
3663                         jumpIsland = makeJumpIsland(oc,reloc->r_symbolnum,word);
3664                         word -= ((long)image) + sect->offset + reloc->r_address;
3665                         if(jumpIsland != 0)
3666                         {
3667                             offsetToJumpIsland = jumpIsland
3668                                 - (((long)image) + sect->offset + reloc->r_address);
3669                         }
3670                     }
3671                     else
3672                     {
3673                         word += (unsigned long) symbolAddress;
3674                     }
3675                 }
3676
3677                 if(reloc->r_type == GENERIC_RELOC_VANILLA)
3678                 {
3679                     *wordPtr = word;
3680                     continue;
3681                 }
3682                 else if(reloc->r_type == PPC_RELOC_LO16)
3683                 {
3684                     ((unsigned short*) wordPtr)[1] = word & 0xFFFF;
3685                     i++; continue;
3686                 }
3687                 else if(reloc->r_type == PPC_RELOC_HI16)
3688                 {
3689                     ((unsigned short*) wordPtr)[1] = (word >> 16) & 0xFFFF;
3690                     i++; continue;
3691                 }
3692                 else if(reloc->r_type == PPC_RELOC_HA16)
3693                 {
3694                     ((unsigned short*) wordPtr)[1] = ((word >> 16) & 0xFFFF)
3695                         + ((word & (1<<15)) ? 1 : 0);
3696                     i++; continue;
3697                 }
3698                 else if(reloc->r_type == PPC_RELOC_BR24)
3699                 {
3700                     if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
3701                     {
3702                         // The branch offset is too large.
3703                         // Therefore, we try to use a jump island.
3704                         if(jumpIsland == 0)
3705                         {
3706                             barf("unconditional relative branch out of range: "
3707                                  "no jump island available");
3708                         }
3709                         
3710                         word = offsetToJumpIsland;
3711                         if((long)word > (long)0x01FFFFFF || (long)word < (long)0xFFE00000)
3712                             barf("unconditional relative branch out of range: "
3713                                  "jump island out of range");
3714                     }
3715                     *wordPtr = (*wordPtr & 0xFC000003) | (word & 0x03FFFFFC);
3716                     continue;
3717                 }
3718             }
3719             barf("\nunknown relocation %d",reloc->r_type);
3720             return 0;
3721         }
3722     }
3723     return 1;
3724 }
3725
3726 static int ocGetNames_MachO(ObjectCode* oc)
3727 {
3728     char *image = (char*) oc->image;
3729     struct mach_header *header = (struct mach_header*) image;
3730     struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3731     unsigned i,curSymbol = 0;
3732     struct segment_command *segLC = NULL;
3733     struct section *sections;
3734     struct symtab_command *symLC = NULL;
3735     struct nlist *nlist;
3736     unsigned long commonSize = 0;
3737     char    *commonStorage = NULL;
3738     unsigned long commonCounter;
3739
3740     for(i=0;i<header->ncmds;i++)
3741     {
3742         if(lc->cmd == LC_SEGMENT)
3743             segLC = (struct segment_command*) lc;
3744         else if(lc->cmd == LC_SYMTAB)
3745             symLC = (struct symtab_command*) lc;
3746         lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3747     }
3748
3749     sections = (struct section*) (segLC+1);
3750     nlist = symLC ? (struct nlist*) (image + symLC->symoff)
3751                   : NULL;
3752
3753     for(i=0;i<segLC->nsects;i++)
3754     {
3755         if(sections[i].size == 0)
3756             continue;
3757
3758         if((sections[i].flags & SECTION_TYPE) == S_ZEROFILL)
3759         {
3760             char * zeroFillArea = stgCallocBytes(1,sections[i].size,
3761                                       "ocGetNames_MachO(common symbols)");
3762             sections[i].offset = zeroFillArea - image;
3763         }
3764
3765         if(!strcmp(sections[i].sectname,"__text"))
3766             addSection(oc, SECTIONKIND_CODE_OR_RODATA,
3767                 (void*) (image + sections[i].offset),
3768                 (void*) (image + sections[i].offset + sections[i].size));
3769         else if(!strcmp(sections[i].sectname,"__const"))
3770             addSection(oc, SECTIONKIND_RWDATA,
3771                 (void*) (image + sections[i].offset),
3772                 (void*) (image + sections[i].offset + sections[i].size));
3773         else if(!strcmp(sections[i].sectname,"__data"))
3774             addSection(oc, SECTIONKIND_RWDATA,
3775                 (void*) (image + sections[i].offset),
3776                 (void*) (image + sections[i].offset + sections[i].size));
3777         else if(!strcmp(sections[i].sectname,"__bss")
3778                 || !strcmp(sections[i].sectname,"__common"))
3779             addSection(oc, SECTIONKIND_RWDATA,
3780                 (void*) (image + sections[i].offset),
3781                 (void*) (image + sections[i].offset + sections[i].size));
3782
3783         addProddableBlock(oc, (void*) (image + sections[i].offset),
3784                                         sections[i].size);
3785     }
3786
3787         // count external symbols defined here
3788     oc->n_symbols = 0;
3789     if(symLC)
3790     {
3791         for(i=0;i<symLC->nsyms;i++)
3792         {
3793             if(nlist[i].n_type & N_STAB)
3794                 ;
3795             else if(nlist[i].n_type & N_EXT)
3796             {
3797                 if((nlist[i].n_type & N_TYPE) == N_UNDF
3798                     && (nlist[i].n_value != 0))
3799                 {
3800                     commonSize += nlist[i].n_value;
3801                     oc->n_symbols++;
3802                 }
3803                 else if((nlist[i].n_type & N_TYPE) == N_SECT)
3804                     oc->n_symbols++;
3805             }
3806         }
3807     }
3808     oc->symbols = stgMallocBytes(oc->n_symbols * sizeof(char*),
3809                                    "ocGetNames_MachO(oc->symbols)");
3810
3811     if(symLC)
3812     {
3813         for(i=0;i<symLC->nsyms;i++)
3814         {
3815             if(nlist[i].n_type & N_STAB)
3816                 ;
3817             else if((nlist[i].n_type & N_TYPE) == N_SECT)
3818             {
3819                 if(nlist[i].n_type & N_EXT)
3820                 {
3821                     char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3822                     ghciInsertStrHashTable(oc->fileName, symhash, nm,
3823                                             image
3824                                             + sections[nlist[i].n_sect-1].offset
3825                                             - sections[nlist[i].n_sect-1].addr
3826                                             + nlist[i].n_value);
3827                     oc->symbols[curSymbol++] = nm;
3828                 }
3829                 else
3830                 {
3831                     char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3832                     ghciInsertStrHashTable(oc->fileName, oc->lochash, nm,
3833                                             image
3834                                             + sections[nlist[i].n_sect-1].offset
3835                                             - sections[nlist[i].n_sect-1].addr
3836                                             + nlist[i].n_value);
3837                 }
3838             }
3839         }
3840     }
3841
3842     commonStorage = stgCallocBytes(1,commonSize,"ocGetNames_MachO(common symbols)");
3843     commonCounter = (unsigned long)commonStorage;
3844     if(symLC)
3845     {
3846         for(i=0;i<symLC->nsyms;i++)
3847         {
3848             if((nlist[i].n_type & N_TYPE) == N_UNDF
3849                     && (nlist[i].n_type & N_EXT) && (nlist[i].n_value != 0))
3850             {
3851                 char *nm = image + symLC->stroff + nlist[i].n_un.n_strx;
3852                 unsigned long sz = nlist[i].n_value;
3853
3854                 nlist[i].n_value = commonCounter;
3855
3856                 ghciInsertStrHashTable(oc->fileName, symhash, nm,
3857                                        (void*)commonCounter);
3858                 oc->symbols[curSymbol++] = nm;
3859
3860                 commonCounter += sz;
3861             }
3862         }
3863     }
3864     return 1;
3865 }
3866
3867 static int ocResolve_MachO(ObjectCode* oc)
3868 {
3869     char *image = (char*) oc->image;
3870     struct mach_header *header = (struct mach_header*) image;
3871     struct load_command *lc = (struct load_command*) (image + sizeof(struct mach_header));
3872     unsigned i;
3873     struct segment_command *segLC = NULL;
3874     struct section *sections, *la_ptrs = NULL, *nl_ptrs = NULL;
3875     struct symtab_command *symLC = NULL;
3876     struct dysymtab_command *dsymLC = NULL;
3877     struct nlist *nlist;
3878
3879     for(i=0;i<header->ncmds;i++)
3880     {
3881         if(lc->cmd == LC_SEGMENT)
3882             segLC = (struct segment_command*) lc;
3883         else if(lc->cmd == LC_SYMTAB)
3884             symLC = (struct symtab_command*) lc;
3885         else if(lc->cmd == LC_DYSYMTAB)
3886             dsymLC = (struct dysymtab_command*) lc;
3887         lc = (struct load_command *) ( ((char*)lc) + lc->cmdsize );
3888     }
3889
3890     sections = (struct section*) (segLC+1);
3891     nlist = symLC ? (struct nlist*) (image + symLC->symoff)
3892                   : NULL;
3893
3894     for(i=0;i<segLC->nsects;i++)
3895     {
3896         if(!strcmp(sections[i].sectname,"__la_symbol_ptr"))
3897             la_ptrs = &sections[i];
3898         else if(!strcmp(sections[i].sectname,"__nl_symbol_ptr"))
3899             nl_ptrs = &sections[i];
3900     }
3901
3902     if(dsymLC)
3903     {
3904         unsigned long *indirectSyms
3905             = (unsigned long*) (image + dsymLC->indirectsymoff);
3906
3907         if(la_ptrs)
3908             if(!resolveImports(oc,image,symLC,la_ptrs,indirectSyms,nlist))
3909                 return 0;
3910         if(nl_ptrs)
3911             if(!resolveImports(oc,image,symLC,nl_ptrs,indirectSyms,nlist))
3912                 return 0;
3913     }
3914     
3915     for(i=0;i<segLC->nsects;i++)
3916     {
3917         if(!relocateSection(oc,image,symLC,nlist,segLC->nsects,sections,&sections[i]))
3918             return 0;
3919     }
3920
3921     /* Free the local symbol table; we won't need it again. */
3922     freeHashTable(oc->lochash, NULL);
3923     oc->lochash = NULL;
3924
3925 #if defined (powerpc_HOST_ARCH)
3926     ocFlushInstructionCache( oc );
3927 #endif
3928
3929     return 1;
3930 }
3931
3932 /*
3933  * The Mach-O object format uses leading underscores. But not everywhere.
3934  * There is a small number of runtime support functions defined in
3935  * libcc_dynamic.a whose name does not have a leading underscore.
3936  * As a consequence, we can't get their address from C code.
3937  * We have to use inline assembler just to take the address of a function.
3938  * Yuck.
3939  */
3940
3941 static void machoInitSymbolsWithoutUnderscore()
3942 {
3943     extern void* symbolsWithoutUnderscore[];
3944     void **p = symbolsWithoutUnderscore;
3945     __asm__ volatile(".globl _symbolsWithoutUnderscore\n.data\n_symbolsWithoutUnderscore:");
3946
3947 #undef Sym
3948 #define Sym(x)  \
3949     __asm__ volatile(".long " # x);
3950
3951     RTS_MACHO_NOUNDERLINE_SYMBOLS
3952
3953     __asm__ volatile(".text");
3954     
3955 #undef Sym
3956 #define Sym(x)  \
3957     ghciInsertStrHashTable("(GHCi built-in symbols)", symhash, #x, *p++);
3958     
3959     RTS_MACHO_NOUNDERLINE_SYMBOLS
3960     
3961 #undef Sym
3962 }
3963 #endif