Linker.c 58 KB
Newer Older
1
/* -----------------------------------------------------------------------------
chak's avatar
chak committed
2
 * $Id: Linker.c,v 1.53 2001/07/22 03:28:25 chak Exp $
3
4
5
6
7
8
9
10
11
12
13
14
 *
 * (c) The GHC Team, 2000
 *
 * RTS Object Linker
 *
 * ---------------------------------------------------------------------------*/

#include "Rts.h"
#include "RtsFlags.h"
#include "HsFFI.h"
#include "Hash.h"
#include "Linker.h"
15
#include "LinkerInternals.h"
16
#include "RtsUtils.h"
17
#include "StoragePriv.h"
18

19
#ifdef HAVE_SYS_TYPES_H
20
#include <sys/types.h>
21
22
23
#endif

#ifdef HAVE_SYS_STAT_H
24
#include <sys/stat.h>
25
#endif
26

27
#ifdef HAVE_DLFCN_H
28
#include <dlfcn.h>
29
#endif
30

31
#if defined(linux_TARGET_OS) || defined(solaris2_TARGET_OS) || defined(freebsd_TARGET_OS)
32
#  define OBJFORMAT_ELF
33
#elif defined(cygwin32_TARGET_OS) || defined (mingw32_TARGET_OS)
34
#  define OBJFORMAT_PEi386
35
#  include <windows.h>
36
37
#endif

38
39
40
/* Hash table mapping symbol names to Symbol */
/*Str*/HashTable *symhash;

41
#if defined(OBJFORMAT_ELF)
42
43
44
static int ocVerifyImage_ELF    ( ObjectCode* oc );
static int ocGetNames_ELF       ( ObjectCode* oc );
static int ocResolve_ELF        ( ObjectCode* oc );
45
#elif defined(OBJFORMAT_PEi386)
46
47
48
49
50
51
52
53
54
static int ocVerifyImage_PEi386 ( ObjectCode* oc );
static int ocGetNames_PEi386    ( ObjectCode* oc );
static int ocResolve_PEi386     ( ObjectCode* oc );
#endif

/* -----------------------------------------------------------------------------
 * Built-in symbols from the RTS
 */

55
56
57
58
59
60
typedef struct _RtsSymbolVal {
    char   *lbl;
    void   *addr;
} RtsSymbolVal;


61
62
63
64
65
66
67
68
69
70
71
#if !defined(PAR)
#define Maybe_ForeignObj        SymX(mkForeignObjzh_fast)

#define Maybe_Stable_Names      SymX(mkWeakzh_fast)			\
      				SymX(makeStableNamezh_fast)		\
      				SymX(finalizzeWeakzh_fast)
#else
/* These are not available in GUM!!! -- HWL */
#define Maybe_ForeignObj
#define Maybe_Stable_Names
#endif
72
73

#if !defined (mingw32_TARGET_OS)
74

75
#define RTS_POSIX_ONLY_SYMBOLS                  \
76
77
      SymX(stg_sig_install)			\
      Sym(nocldstop)
78
79
#define RTS_MINGW_ONLY_SYMBOLS /**/

80
#else
81

82
#define RTS_POSIX_ONLY_SYMBOLS
83
84
85

/* These are statically linked from the mingw libraries into the ghc
   executable, so we have to employ this hack. */
86
#define RTS_MINGW_ONLY_SYMBOLS                  \
87
      SymX(memset)                              \
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
      SymX(inet_ntoa)                           \
      SymX(inet_addr)                           \
      SymX(htonl)                               \
      SymX(recvfrom)                            \
      SymX(listen)                              \
      SymX(bind)                                \
      SymX(shutdown)                            \
      SymX(connect)                             \
      SymX(htons)                               \
      SymX(ntohs)                               \
      SymX(getservbyname)                       \
      SymX(getservbyport)                       \
      SymX(getprotobynumber)                    \
      SymX(getprotobyname)                      \
      SymX(gethostbyname)                       \
      SymX(gethostbyaddr)                       \
      SymX(gethostname)                         \
      SymX(strcpy)                              \
      SymX(strncpy)                             \
      SymX(abort)                               \
      Sym(_alloca)                              \
      Sym(isxdigit)                             \
      Sym(isupper)                              \
      Sym(ispunct)                              \
      Sym(islower)                              \
      Sym(isspace)                              \
      Sym(isprint)                              \
      Sym(isdigit)                              \
      Sym(iscntrl)                              \
      Sym(isalpha)                              \
      Sym(isalnum)                              \
      SymX(strcmp)                              \
120
121
122
      SymX(memmove)                             \
      SymX(realloc)                             \
      SymX(malloc)                              \
123
124
125
126
127
128
129
130
131
132
133
134
135
136
      SymX(pow)                                 \
      SymX(tanh)                                \
      SymX(cosh)                                \
      SymX(sinh)                                \
      SymX(atan)                                \
      SymX(acos)                                \
      SymX(asin)                                \
      SymX(tan)                                 \
      SymX(cos)                                 \
      SymX(sin)                                 \
      SymX(exp)                                 \
      SymX(log)                                 \
      SymX(sqrt)                                \
      SymX(memcpy)                              \
137
      Sym(mktime)                               \
138
      Sym(_imp___timezone)                      \
139
140
141
142
      Sym(_imp___tzname)                        \
      Sym(localtime)                            \
      Sym(gmtime)                               \
      SymX(getenv)                              \
143
      SymX(free)                                \
144
145
146
147
148
149
      SymX(rename)                              \
      Sym(opendir)                              \
      Sym(readdir)                              \
      Sym(closedir)                             \
      SymX(GetCurrentProcess)                   \
      SymX(GetProcessTimes)                     \
rrt's avatar
rrt committed
150
      SymX(CloseHandle)                         \
151
152
153
      SymX(GetExitCodeProcess)                  \
      SymX(WaitForSingleObject)                 \
      SymX(CreateProcessA)                      \
sof's avatar
sof committed
154
155
156
157
      Sym(__divdi3)                             \
      Sym(__udivdi3)                            \
      Sym(__moddi3)                             \
      Sym(__umoddi3)                            \
158
      SymX(_errno)
159
#endif
160

161

162
163
164
165
166
167
168
169
170
#define RTS_SYMBOLS				\
      SymX(MainRegTable)			\
      Sym(stg_gc_enter_1)			\
      Sym(stg_gc_noregs)			\
      Sym(stg_gc_seq_1)				\
      Sym(stg_gc_d1)				\
      Sym(stg_gc_f1)				\
      Sym(stg_gc_ut_1_0)			\
      Sym(stg_gc_ut_0_1)			\
171
      Sym(stg_gc_unpt_r1)			\
172
173
174
175
176
177
      Sym(stg_gc_unbx_r1)			\
      Sym(stg_chk_0)				\
      Sym(stg_chk_1)				\
      Sym(stg_gen_chk)				\
      SymX(stg_exit)				\
      SymX(stg_update_PAP)			\
178
      SymX(stg_ap_1_upd_info)			\
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
      SymX(stg_ap_2_upd_info)			\
      SymX(stg_ap_3_upd_info)			\
      SymX(stg_ap_4_upd_info)			\
      SymX(stg_ap_5_upd_info)			\
      SymX(stg_ap_6_upd_info)			\
      SymX(stg_ap_7_upd_info)			\
      SymX(stg_ap_8_upd_info)			\
      SymX(stg_sel_0_upd_info)			\
      SymX(stg_sel_1_upd_info)			\
      SymX(stg_sel_2_upd_info)			\
      SymX(stg_sel_3_upd_info)			\
      SymX(stg_sel_4_upd_info)			\
      SymX(stg_sel_5_upd_info)			\
      SymX(stg_sel_6_upd_info)			\
      SymX(stg_sel_7_upd_info)			\
      SymX(stg_sel_8_upd_info)			\
      SymX(stg_sel_9_upd_info)			\
      SymX(stg_sel_10_upd_info)			\
      SymX(stg_sel_11_upd_info)			\
      SymX(stg_sel_12_upd_info)			\
199
200
201
      SymX(stg_sel_13_upd_info)			\
      SymX(stg_sel_14_upd_info)			\
      SymX(stg_sel_15_upd_info)			\
202
203
      SymX(stg_upd_frame_info)			\
      SymX(stg_seq_frame_info)			\
204
      SymX(stg_CAF_BLACKHOLE_info)		\
205
206
207
      SymX(stg_IND_STATIC_info)			\
      SymX(stg_EMPTY_MVAR_info)			\
      SymX(stg_MUT_ARR_PTRS_FROZEN_info)	\
208
      SymX(stg_WEAK_info)                       \
209
210
      SymX(stg_CHARLIKE_closure)		\
      SymX(stg_INTLIKE_closure)			\
211
      SymX(newCAF)				\
212
      SymX(newBCOzh_fast)			\
213
      SymX(mkApUpd0zh_fast)			\
214
215
216
217
      SymX(putMVarzh_fast)			\
      SymX(newMVarzh_fast)			\
      SymX(takeMVarzh_fast)			\
      SymX(tryTakeMVarzh_fast)			\
218
      SymX(tryPutMVarzh_fast)			\
219
220
      SymX(catchzh_fast)			\
      SymX(raisezh_fast)			\
221
      SymX(forkzh_fast)				\
222
223
224
225
226
227
228
229
230
      SymX(delayzh_fast)			\
      SymX(yieldzh_fast)			\
      SymX(killThreadzh_fast)			\
      SymX(waitReadzh_fast)			\
      SymX(waitWritezh_fast)			\
      SymX(suspendThread)			\
      SymX(resumeThread)			\
      SymX(stackOverflow)			\
      SymX(int2Integerzh_fast)			\
231
      SymX(word2Integerzh_fast)			\
232
      Maybe_ForeignObj				\
233
234
235
236
237
238
      SymX(__encodeDouble)			\
      SymX(decodeDoublezh_fast)			\
      SymX(decodeFloatzh_fast)			\
      SymX(gcdIntegerzh_fast)			\
      SymX(newArrayzh_fast)			\
      SymX(unsafeThawArrayzh_fast)		\
239
      SymX(newByteArrayzh_fast)			\
240
241
242
243
244
245
246
247
248
      SymX(newMutVarzh_fast)			\
      SymX(quotRemIntegerzh_fast)		\
      SymX(quotIntegerzh_fast)			\
      SymX(remIntegerzh_fast)			\
      SymX(divExactIntegerzh_fast)		\
      SymX(divModIntegerzh_fast)		\
      SymX(timesIntegerzh_fast)			\
      SymX(minusIntegerzh_fast)			\
      SymX(plusIntegerzh_fast)			\
249
250
251
252
      SymX(andIntegerzh_fast)			\
      SymX(orIntegerzh_fast)			\
      SymX(xorIntegerzh_fast)			\
      SymX(complementIntegerzh_fast)		\
253
      Maybe_Stable_Names			\
254
255
256
257
258
259
260
261
262
263
264
265
266
267
      SymX(blockAsyncExceptionszh_fast)		\
      SymX(unblockAsyncExceptionszh_fast)	\
      SymX(isDoubleNaN)				\
      SymX(isDoubleInfinite)			\
      SymX(isDoubleDenormalized)		\
      SymX(isDoubleNegativeZero)		\
      SymX(__encodeFloat)			\
      SymX(isFloatNaN)				\
      SymX(isFloatInfinite)			\
      SymX(isFloatDenormalized)			\
      SymX(isFloatNegativeZero)			\
      SymX(__int_encodeFloat)			\
      SymX(__int_encodeDouble)			\
      SymX(__gmpz_cmp_si)			\
268
      SymX(__gmpz_cmp_ui)			\
269
270
      SymX(__gmpz_cmp)				\
      SymX(__gmpn_gcd_1)			\
271
272
      SymX(__gmpz_get_si)			\
      SymX(__gmpz_get_ui)			\
273
274
275
      SymX(prog_argv)				\
      SymX(prog_argc)				\
      SymX(resetNonBlockingFd)			\
276
      SymX(performGC)				\
277
278
279
280
      SymX(getStablePtr)			\
      SymX(stable_ptr_table)			\
      SymX(shutdownHaskellAndExit)		\
      Sym(stg_enterStackTop)			\
281
      Sym(stg_yield_to_interpreter)		\
282
283
      Sym(StgReturn)				\
      Sym(init_stack)				\
284
285
286
287
288
289
290
291
292
293
294
295
      SymX(cmp_thread)				\
      Sym(__init_PrelGHC)			\
      SymX(freeHaskellFunctionPtr)		\
      SymX(OnExitHook)				\
      SymX(ErrorHdrHook)			\
      SymX(NoRunnableThreadsHook)		\
      SymX(StackOverflowHook)			\
      SymX(OutOfHeapHook)			\
      SymX(MallocFailHook)			\
      SymX(PatErrorHdrHook)			\
      SymX(defaultsHook)			\
      SymX(PreTraceHook)			\
296
297
      SymX(PostTraceHook)			\
      SymX(createAdjustor)			\
298
      SymX(rts_mkChar)				\
299
      SymX(rts_mkInt)				\
300
301
302
303
304
305
306
307
308
309
310
311
      SymX(rts_mkInt8)				\
      SymX(rts_mkInt16)				\
      SymX(rts_mkInt32)				\
      SymX(rts_mkInt64)				\
      SymX(rts_mkWord)				\
      SymX(rts_mkWord8)				\
      SymX(rts_mkWord16)			\
      SymX(rts_mkWord32)			\
      SymX(rts_mkWord64)			\
      SymX(rts_mkPtr)				\
      SymX(rts_mkFloat)				\
      SymX(rts_mkDouble)			\
312
      SymX(rts_mkStablePtr)			\
313
314
      SymX(rts_mkBool)				\
      SymX(rts_mkString)			\
315
      SymX(rts_apply)				\
316
317
318
319
320
321
322
323
324
325
326
327
328
329
      SymX(rts_mkAddr)				\
      SymX(rts_getChar)				\
      SymX(rts_getInt)				\
      SymX(rts_getInt32)			\
      SymX(rts_getWord)				\
      SymX(rts_getWord32)			\
      SymX(rts_getPtr)				\
      SymX(rts_getFloat)			\
      SymX(rts_getDouble)			\
      SymX(rts_getStablePtr)			\
      SymX(rts_getBool)				\
      SymX(rts_getAddr)				\
      SymX(rts_eval)				\
      SymX(rts_eval_)				\
330
      SymX(rts_evalIO)				\
331
332
      SymX(rts_evalLazyIO)			\
      SymX(rts_checkSchedStatus)
333
334
335
336

#ifndef SUPPORT_LONG_LONGS
#define RTS_LONG_LONG_SYMS /* nothing */
#else
337
#define RTS_LONG_LONG_SYMS			\
338
339
340
      SymX(int64ToIntegerzh_fast)		\
      SymX(word64ToIntegerzh_fast)
#endif /* SUPPORT_LONG_LONGS */
341
342
343
344
345

/* entirely bogus claims about types of these symbols */
#define Sym(vvv)  extern void (vvv);
#define SymX(vvv) /**/
RTS_SYMBOLS
346
RTS_LONG_LONG_SYMS
347
RTS_POSIX_ONLY_SYMBOLS
348
RTS_MINGW_ONLY_SYMBOLS
349
350
351
352
353
354
355
356
357
358
359
360
361
#undef Sym
#undef SymX

#ifdef LEADING_UNDERSCORE
#define MAYBE_LEADING_UNDERSCORE_STR(s) ("_" s)
#else
#define MAYBE_LEADING_UNDERSCORE_STR(s) (s)
#endif

#define Sym(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
                    (void*)(&(vvv)) },
#define SymX(vvv) Sym(vvv)

362
static RtsSymbolVal rtsSyms[] = {
363
      RTS_SYMBOLS
364
      RTS_LONG_LONG_SYMS
365
      RTS_POSIX_ONLY_SYMBOLS
366
      RTS_MINGW_ONLY_SYMBOLS
367
368
369
370
371
372
      { 0, 0 } /* sentinel */
};

/* -----------------------------------------------------------------------------
 * initialize the object linker
 */
373
#if defined(OBJFORMAT_ELF)
374
static void *dl_prog_handle;
375
#endif
376
377
378
379

void
initLinker( void )
{
380
    RtsSymbolVal *sym;
381
382
383
384
385

    symhash = allocStrHashTable();

    /* populate the symbol table with stuff from the RTS */
    for (sym = rtsSyms; sym->lbl != NULL; sym++) {
386
	insertStrHashTable(symhash, sym->lbl, sym->addr);
387
    }
388
#   if defined(OBJFORMAT_ELF)
389
    dl_prog_handle = dlopen(NULL, RTLD_LAZY);
390
#   endif
391
392
}

393
394
395
396
397
/* -----------------------------------------------------------------------------
 * Add a DLL from which symbols may be found.  In the ELF case, just
 * do RTLD_GLOBAL-style add, so no further messing around needs to
 * happen in order that symbols in the loaded .so are findable --
 * lookupSymbol() will subsequently see them by dlsym on the program's
398
399
400
401
402
 * dl-handle.  Returns NULL if success, otherwise ptr to an err msg.
 *
 * In the PEi386 case, open the DLLs and put handles to them in a 
 * linked list.  When looking for a symbol, try all handles in the
 * list.
403
 */
404
405
406
407
408
409

#if defined(OBJFORMAT_PEi386)
/* A record for storing handles into DLLs. */

typedef
   struct _OpenedDLL {
410
      char*              name;
411
412
413
414
415
416
417
418
419
420
421
      struct _OpenedDLL* next;
      HINSTANCE instance;
   } 
   OpenedDLL;

/* A list thereof. */
static OpenedDLL* opened_dlls = NULL;
#endif



422
char*
423
addDLL ( char* path, char* dll_name )
424
425
426
427
{
#  if defined(OBJFORMAT_ELF)
   void *hdl;
   char *buf;
428
   char *errmsg;
429

430
431
432
433
434
435
436
   if (path == NULL || strlen(path) == 0) {
      buf = stgMallocBytes(strlen(dll_name) + 10, "addDll");
      sprintf(buf, "lib%s.so", dll_name);
   } else {
      buf = stgMallocBytes(strlen(path) + 1 + strlen(dll_name) + 10, "addDll");
      sprintf(buf, "%s/lib%s.so", path, dll_name);
   }
437
   hdl = dlopen(buf, RTLD_NOW | RTLD_GLOBAL );
438
   free(buf);
439
440
441
442
443
444
445
446
   if (hdl == NULL) {
      /* dlopen failed; return a ptr to the error msg. */
      errmsg = dlerror();
      if (errmsg == NULL) errmsg = "addDLL: unknown error";
      return errmsg;
   } else {
      return NULL;
   }
447
448
   /*NOTREACHED*/

449
#  elif defined(OBJFORMAT_PEi386)
450

451
   /* Add this DLL to the list of DLLs in which to search for symbols.
452
      The path argument is ignored. */
453
   char*      buf;
454
   OpenedDLL* o_dll;
455
   HINSTANCE  instance;
456
457
458
459
460
461
462

   /* fprintf(stderr, "\naddDLL; path=`%s', dll_name = `%s'\n", path, dll_name); */

   /* See if we've already got it, and ignore if so. */
   for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
      if (0 == strcmp(o_dll->name, dll_name))
         return NULL;
463
464
   }

465
   buf = stgMallocBytes(strlen(dll_name) + 10, "addDLL");
466
467
468
469
470
   sprintf(buf, "%s.DLL", dll_name);
   instance = LoadLibrary(buf);
   free(buf);
   if (instance == NULL) {
     /* LoadLibrary failed; return a ptr to the error msg. */
471
     return "addDLL: unknown error";
472
473
474
   }

   o_dll = stgMallocBytes( sizeof(OpenedDLL), "addDLL" );
475
476
   o_dll->name     = stgMallocBytes(1+strlen(dll_name), "addDLL");
   strcpy(o_dll->name, dll_name);
477
   o_dll->instance = instance;
478
479
   o_dll->next     = opened_dlls;
   opened_dlls     = o_dll;
480
481

   return NULL;
482
483
484
485
486
#  else
   barf("addDLL: not implemented on this platform");
#  endif
}

487
488
489
490
491
492
/* -----------------------------------------------------------------------------
 * lookup a symbol in the hash table
 */  
void *
lookupSymbol( char *lbl )
{
493
    void *val;
494
    ASSERT(symhash != NULL);
495
496
497
    val = lookupStrHashTable(symhash, lbl);

    if (val == NULL) {
498
#       if defined(OBJFORMAT_ELF)
499
	return dlsym(dl_prog_handle, lbl);
500
#       elif defined(OBJFORMAT_PEi386)
501
502
503
        OpenedDLL* o_dll;
        void* sym;
        for (o_dll = opened_dlls; o_dll != NULL; o_dll = o_dll->next) {
504
           /* fprintf(stderr, "look in %s for %s\n", o_dll->name, lbl); */
sof's avatar
sof committed
505
506
507
508
509
510
511
512
513
	   if (lbl[0] == '_') {
	     /* HACK: if the name has an initial underscore, try stripping
		it off & look that up first. I've yet to verify whether there's
		a Rule that governs whether an initial '_' *should always* be
		stripped off when mapping from import lib name to the DLL name.
	     */
	     sym = GetProcAddress(o_dll->instance, (lbl+1));
	     if (sym != NULL) return sym;
	   }
514
515
516
           sym = GetProcAddress(o_dll->instance, lbl);
           if (sym != NULL) return sym;
        }
517
518
        return NULL;
#       endif
519
    } else {
520
	return val;
521
522
523
    }
}

524
525
526
527
static 
void *
lookupLocalSymbol( ObjectCode* oc, char *lbl )
{
528
    void *val;
529
530
531
532
533
    val = lookupStrHashTable(oc->lochash, lbl);

    if (val == NULL) {
        return NULL;
    } else {
534
	return val;
535
536
537
538
    }
}


539
540
541
542
543
544
545
546
547
548
549
550
551
/* -----------------------------------------------------------------------------
 * Load an obj (populate the global symbol table, but don't resolve yet)
 *
 * Returns: 1 if ok, 0 on error.
 */
HsInt
loadObj( char *path )
{
   ObjectCode* oc;
   struct stat st;
   int r, n;
   FILE *f;

552
   /* fprintf(stderr, "loadObj %s\n", path ); */
553
#  ifdef DEBUG
554
555
556
557
558
559
   /* assert that we haven't already loaded this object */
   { 
       ObjectCode *o;
       for (o = objects; o; o = o->next)
	   ASSERT(strcmp(o->fileName, path));
   }
560
#  endif /* DEBUG */   
561
562
563

   oc = stgMallocBytes(sizeof(ObjectCode), "loadObj(oc)");

564
#  if defined(OBJFORMAT_ELF)
565
   oc->formatName = "ELF";
566
#  elif defined(OBJFORMAT_PEi386)
567
568
569
570
571
572
573
574
575
   oc->formatName = "PEi386";
#  else
   free(oc);
   barf("loadObj: not implemented on this platform");
#  endif

   r = stat(path, &st);
   if (r == -1) { return 0; }

576
   /* sigh, strdup() isn't a POSIX function, so do it the long way */
577
578
579
   oc->fileName = stgMallocBytes( strlen(path)+1, "loadObj" );
   strcpy(oc->fileName, path);

580
581
582
583
   oc->fileSize          = st.st_size;
   oc->image             = stgMallocBytes( st.st_size, "loadObj(image)" );
   oc->symbols           = NULL;
   oc->sections          = NULL;
584
   oc->lochash           = allocStrHashTable();
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601

   /* chain it onto the list of objects */
   oc->next              = objects;
   objects               = oc;

   /* load the image into memory */
   f = fopen(path, "rb");
   if (!f) {
       barf("loadObj: can't read `%s'", path);
   }
   n = fread ( oc->image, 1, oc->fileSize, f );
   if (n != oc->fileSize) {
      fclose(f);
      barf("loadObj: error whilst reading `%s'", path);
   }

   /* verify the in-memory image */
602
#  if defined(OBJFORMAT_ELF)
603
   r = ocVerifyImage_ELF ( oc );
604
#  elif defined(OBJFORMAT_PEi386)
605
606
607
608
609
610
611
   r = ocVerifyImage_PEi386 ( oc );
#  else
   barf("loadObj: no verify method");
#  endif
   if (!r) { return r; }

   /* build the symbol list for this image */
612
#  if defined(OBJFORMAT_ELF)
613
   r = ocGetNames_ELF ( oc );
614
#  elif defined(OBJFORMAT_PEi386)
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
   r = ocGetNames_PEi386 ( oc );
#  else
   barf("loadObj: no getNames method");
#  endif
   if (!r) { return r; }

   /* loaded, but not resolved yet */
   oc->status = OBJECT_LOADED;

   return 1;
}

/* -----------------------------------------------------------------------------
 * resolve all the currently unlinked objects in memory
 *
 * Returns: 1 if ok, 0 on error.
 */
HsInt 
resolveObjs( void )
{
    ObjectCode *oc;
    int r;

    for (oc = objects; oc; oc = oc->next) {
	if (oc->status != OBJECT_RESOLVED) {
640
#           if defined(OBJFORMAT_ELF)
641
	    r = ocResolve_ELF ( oc );
642
#           elif defined(OBJFORMAT_PEi386)
643
	    r = ocResolve_PEi386 ( oc );
644
#           else
645
	    barf("resolveObjs: not implemented on this platform");
646
#           endif
647
648
649
650
651
652
653
654
655
656
657
658
659
	    if (!r) { return r; }
	    oc->status = OBJECT_RESOLVED;
	}
    }
    return 1;
}

/* -----------------------------------------------------------------------------
 * delete an object from the pool
 */
HsInt
unloadObj( char *path )
{
660
    ObjectCode *oc, *prev;
661

662
663
664
    ASSERT(symhash != NULL);
    ASSERT(objects != NULL);

665
666
    prev = NULL;
    for (oc = objects; oc; prev = oc, oc = oc->next) {
667
668
669
670
671
672
	if (!strcmp(oc->fileName,path)) {

	    /* Remove all the mappings for the symbols within this
	     * object..
	     */
	    { 
673
674
675
676
677
678
679
                int i;
                for (i = 0; i < oc->n_symbols; i++) {
                   if (oc->symbols[i] != NULL) {
                       removeStrHashTable(symhash, oc->symbols[i], NULL);
                   }
                }
            }
680

681
682
683
684
685
686
	    if (prev == NULL) {
		objects = oc->next;
	    } else {
		prev->next = oc->next;
	    }

687
688
689
	    /* We're going to leave this in place, in case there are
	       any pointers from the heap into it: */
	    /* free(oc->image); */
690
	    free(oc->fileName);
691
692
	    free(oc->symbols);
	    free(oc->sections);
693
694
695
	    /* The local hash table should have been freed at the end
               of the ocResolve_ call on it. */
            ASSERT(oc->lochash == NULL);
696
697
698
699
	    free(oc);
	    return 1;
	}
    }
700

701
702
703
704
705
    belch("unloadObj: can't find `%s' to unload", path);
    return 0;
}

/* --------------------------------------------------------------------------
706
 * PEi386 specifics (Win32 targets)
707
708
709
710
711
712
713
714
715
716
 * ------------------------------------------------------------------------*/

/* The information for this linker comes from 
      Microsoft Portable Executable 
      and Common Object File Format Specification
      revision 5.1 January 1998
   which SimonM says comes from the MS Developer Network CDs.
*/
      

717
#if defined(OBJFORMAT_PEi386)
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785



typedef unsigned char  UChar;
typedef unsigned short UInt16;
typedef unsigned int   UInt32;
typedef          int   Int32;


typedef 
   struct {
      UInt16 Machine;
      UInt16 NumberOfSections;
      UInt32 TimeDateStamp;
      UInt32 PointerToSymbolTable;
      UInt32 NumberOfSymbols;
      UInt16 SizeOfOptionalHeader;
      UInt16 Characteristics;
   }
   COFF_header;

#define sizeof_COFF_header 20


typedef 
   struct {
      UChar  Name[8];
      UInt32 VirtualSize;
      UInt32 VirtualAddress;
      UInt32 SizeOfRawData;
      UInt32 PointerToRawData;
      UInt32 PointerToRelocations;
      UInt32 PointerToLinenumbers;
      UInt16 NumberOfRelocations;
      UInt16 NumberOfLineNumbers;
      UInt32 Characteristics; 
   }
   COFF_section;

#define sizeof_COFF_section 40


typedef
   struct {
      UChar  Name[8];
      UInt32 Value;
      UInt16 SectionNumber;
      UInt16 Type;
      UChar  StorageClass;
      UChar  NumberOfAuxSymbols;
   }
   COFF_symbol;

#define sizeof_COFF_symbol 18


typedef
   struct {
      UInt32 VirtualAddress;
      UInt32 SymbolTableIndex;
      UInt16 Type;
   }
   COFF_reloc;

#define sizeof_COFF_reloc 10


/* From PE spec doc, section 3.3.2 */
786
787
788
789
790
791
792
793
794
795
/* Note use of MYIMAGE_* since IMAGE_* are already defined in
   windows.h -- for the same purpose, but I want to know what I'm
   getting, here. */
#define MYIMAGE_FILE_RELOCS_STRIPPED     0x0001
#define MYIMAGE_FILE_EXECUTABLE_IMAGE    0x0002
#define MYIMAGE_FILE_DLL                 0x2000
#define MYIMAGE_FILE_SYSTEM              0x1000
#define MYIMAGE_FILE_BYTES_REVERSED_HI   0x8000
#define MYIMAGE_FILE_BYTES_REVERSED_LO   0x0080
#define MYIMAGE_FILE_32BIT_MACHINE       0x0100
796
797

/* From PE spec doc, section 5.4.2 and 5.4.4 */
798
799
800
#define MYIMAGE_SYM_CLASS_EXTERNAL       2
#define MYIMAGE_SYM_CLASS_STATIC         3
#define MYIMAGE_SYM_UNDEFINED            0
801
802

/* From PE spec doc, section 4.1 */
803
804
#define MYIMAGE_SCN_CNT_CODE             0x00000020
#define MYIMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
805
806

/* From PE spec doc, section 5.2.1 */
807
808
#define MYIMAGE_REL_I386_DIR32           0x0006
#define MYIMAGE_REL_I386_REL32           0x0014
809
810
811
812
813
814
815
816
817
818
819


/* We use myindex to calculate array addresses, rather than
   simply doing the normal subscript thing.  That's because
   some of the above structs have sizes which are not 
   a whole number of words.  GCC rounds their sizes up to a
   whole number of words, which means that the address calcs
   arising from using normal C indexing or pointer arithmetic
   are just plain wrong.  Sigh.
*/
static UChar *
820
myindex ( int scale, void* base, int index )
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
{
   return
      ((UChar*)base) + scale * index;
}


static void
printName ( UChar* name, UChar* strtab )
{
   if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
      UInt32 strtab_offset = * (UInt32*)(name+4);
      fprintf ( stderr, "%s", strtab + strtab_offset );
   } else {
      int i;
      for (i = 0; i < 8; i++) {
         if (name[i] == 0) break;
         fprintf ( stderr, "%c", name[i] );
      }
   }
}


static void
copyName ( UChar* name, UChar* strtab, UChar* dst, int dstSize )
{
   if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
      UInt32 strtab_offset = * (UInt32*)(name+4);
      strncpy ( dst, strtab+strtab_offset, dstSize );
      dst[dstSize-1] = 0;
   } else {
      int i = 0;
      while (1) {
         if (i >= 8) break;
         if (name[i] == 0) break;
         dst[i] = name[i];
         i++;
      }
      dst[i] = 0;
   }
}


static UChar *
cstring_from_COFF_symbol_name ( UChar* name, UChar* strtab )
{
   UChar* newstr;
   /* If the string is longer than 8 bytes, look in the
      string table for it -- this will be correctly zero terminated. 
   */
   if (name[0]==0 && name[1]==0 && name[2]==0 && name[3]==0) {
      UInt32 strtab_offset = * (UInt32*)(name+4);
      return ((UChar*)strtab) + strtab_offset;
   }
   /* Otherwise, if shorter than 8 bytes, return the original,
      which by defn is correctly terminated.
   */
   if (name[7]==0) return name;
   /* The annoying case: 8 bytes.  Copy into a temporary
      (which is never freed ...)
   */
881
882
883
884
   newstr = stgMallocBytes(9, "cstring_from_COFF_symbol_name");
   ASSERT(newstr);
   strncpy(newstr,name,8);
   newstr[8] = 0;
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
   return newstr;
}


/* Just compares the short names (first 8 chars) */
static COFF_section *
findPEi386SectionCalled ( ObjectCode* oc,  char* name )
{
   int i;
   COFF_header* hdr 
      = (COFF_header*)(oc->image);
   COFF_section* sectab 
      = (COFF_section*) (
           ((UChar*)(oc->image)) 
           + sizeof_COFF_header + hdr->SizeOfOptionalHeader
        );
   for (i = 0; i < hdr->NumberOfSections; i++) {
      UChar* n1;
      UChar* n2;
      COFF_section* section_i 
         = (COFF_section*)
906
           myindex ( sizeof_COFF_section, sectab, i );
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
      n1 = (UChar*) &(section_i->Name);
      n2 = name;
      if (n1[0]==n2[0] && n1[1]==n2[1] && n1[2]==n2[2] && 
          n1[3]==n2[3] && n1[4]==n2[4] && n1[5]==n2[5] && 
          n1[6]==n2[6] && n1[7]==n2[7])
         return section_i;
   }

   return NULL;
}


static void
zapTrailingAtSign ( UChar* sym )
{
922
#  define my_isdigit(c) ((c) >= '0' && (c) <= '9')
923
924
925
926
927
928
   int i, j;
   if (sym[0] == 0) return;
   i = 0; 
   while (sym[i] != 0) i++;
   i--;
   j = i;
929
   while (j > 0 && my_isdigit(sym[j])) j--;
930
   if (j > 0 && sym[j] == '@' && j != i) sym[j] = 0;
931
#  undef my_isdigit
932
933
934
935
936
937
938
939
940
941
942
}


static int
ocVerifyImage_PEi386 ( ObjectCode* oc )
{
   int i, j;
   COFF_header*  hdr;
   COFF_section* sectab;
   COFF_symbol*  symtab;
   UChar*        strtab;
943
   /* fprintf(stderr, "\nLOADING %s\n", oc->fileName); */
944
945
946
947
948
949
950
951
952
   hdr = (COFF_header*)(oc->image);
   sectab = (COFF_section*) (
               ((UChar*)(oc->image)) 
               + sizeof_COFF_header + hdr->SizeOfOptionalHeader
            );
   symtab = (COFF_symbol*) (
               ((UChar*)(oc->image))
               + hdr->PointerToSymbolTable 
            );
953
   strtab = ((UChar*)symtab)
954
955
956
            + hdr->NumberOfSymbols * sizeof_COFF_symbol;

   if (hdr->Machine != 0x14c) {
957
958
      belch("Not x86 PEi386");
      return 0;
959
960
   }
   if (hdr->SizeOfOptionalHeader != 0) {
961
962
      belch("PEi386 with nonempty optional header");
      return 0;
963
   }
964
965
966
967
   if ( /* (hdr->Characteristics & MYIMAGE_FILE_RELOCS_STRIPPED) || */
        (hdr->Characteristics & MYIMAGE_FILE_EXECUTABLE_IMAGE) ||
        (hdr->Characteristics & MYIMAGE_FILE_DLL) ||
        (hdr->Characteristics & MYIMAGE_FILE_SYSTEM) ) {
968
969
      belch("Not a PEi386 object file");
      return 0;
970
   }
971
972
973
974
975
976
977
978
979
   if ( (hdr->Characteristics & MYIMAGE_FILE_BYTES_REVERSED_HI)
        /* || !(hdr->Characteristics & MYIMAGE_FILE_32BIT_MACHINE) */ ) {
      belch("Invalid PEi386 word size or endiannness: %d", 
            (int)(hdr->Characteristics));
      return 0;
   }
   /* fprintf(stderr, "strtab size %d\n", * (UInt32*)strtab); */
   if (* (UInt32*)strtab > 510000) {
      belch("PEi386 object has suspiciously large string table; > 64k relocs?");
980
      return 0;
981
982
983
   }

   /* No further verification after this point; only debug printing. */
984
985
986
   i = 0;
   IF_DEBUG(linker, i=1);
   if (i == 0) return 1;
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

   fprintf ( stderr, 
             "sectab offset = %d\n", ((UChar*)sectab) - ((UChar*)hdr) );
   fprintf ( stderr, 
             "symtab offset = %d\n", ((UChar*)symtab) - ((UChar*)hdr) );
   fprintf ( stderr, 
             "strtab offset = %d\n", ((UChar*)strtab) - ((UChar*)hdr) );

   fprintf ( stderr, "\n" );
   fprintf ( stderr, 
             "Machine:           0x%x\n", (UInt32)(hdr->Machine) );
   fprintf ( stderr, 
             "# sections:        %d\n",   (UInt32)(hdr->NumberOfSections) );
   fprintf ( stderr,
             "time/date:         0x%x\n", (UInt32)(hdr->TimeDateStamp) );
   fprintf ( stderr,
             "symtab offset:     %d\n",   (UInt32)(hdr->PointerToSymbolTable) );
   fprintf ( stderr, 
             "# symbols:         %d\n",   (UInt32)(hdr->NumberOfSymbols) );
   fprintf ( stderr, 
             "sz of opt hdr:     %d\n",   (UInt32)(hdr->SizeOfOptionalHeader) );
   fprintf ( stderr,
             "characteristics:   0x%x\n", (UInt32)(hdr->Characteristics) );

1011
   /* Print the section table. */
1012
1013
1014
1015
1016
   fprintf ( stderr, "\n" );
   for (i = 0; i < hdr->NumberOfSections; i++) {
      COFF_reloc* reltab;
      COFF_section* sectab_i
         = (COFF_section*)
1017
           myindex ( sizeof_COFF_section, sectab, i );
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
      fprintf ( stderr, 
                "\n"
                "section %d\n"
                "     name `",
                i 
              );
      printName ( sectab_i->Name, strtab );
      fprintf ( stderr, 
                "'\n"
                "    vsize %d\n"
                "    vaddr %d\n"
                "  data sz %d\n"
                " data off %d\n"
                "  num rel %d\n"
                "  off rel %d\n",
                sectab_i->VirtualSize,
                sectab_i->VirtualAddress,
                sectab_i->SizeOfRawData,
                sectab_i->PointerToRawData,
                sectab_i->NumberOfRelocations,
                sectab_i->PointerToRelocations
              );
      reltab = (COFF_reloc*) (
                  ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
               );
1043

1044
1045
1046
      for (j = 0; j < sectab_i->NumberOfRelocations; j++) {
         COFF_symbol* sym;
         COFF_reloc* rel = (COFF_reloc*)
1047
                           myindex ( sizeof_COFF_reloc, reltab, j );
1048
1049
1050
1051
1052
         fprintf ( stderr, 
                   "        type 0x%-4x   vaddr 0x%-8x   name `",
                   (UInt32)rel->Type, 
                   rel->VirtualAddress );
         sym = (COFF_symbol*)
1053
               myindex ( sizeof_COFF_symbol, symtab, rel->SymbolTableIndex );
1054
         printName ( sym->Name, strtab -10 );
1055
1056
1057
1058
1059
         fprintf ( stderr, "'\n" );
      }
      fprintf ( stderr, "\n" );
   }

1060
1061
1062
1063
1064
1065
1066
1067
1068
   fprintf ( stderr, "\n" );
   fprintf ( stderr, "string table has size 0x%x\n", * (UInt32*)strtab );
   fprintf ( stderr, "---START of string table---\n");
   for (i = 4; i < *(Int32*)strtab; i++) {
      if (strtab[i] == 0) 
         fprintf ( stderr, "\n"); else 
         fprintf( stderr, "%c", strtab[i] );
   }
   fprintf ( stderr, "--- END  of string table---\n");
1069
1070
1071
1072
1073

   fprintf ( stderr, "\n" );
   i = 0;
   while (1) {
      COFF_symbol* symtab_i;
1074
      if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1075
      symtab_i = (COFF_symbol*)
1076
                 myindex ( sizeof_COFF_symbol, symtab, i );
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
      fprintf ( stderr, 
                "symbol %d\n"
                "     name `",
                i 
              );
      printName ( symtab_i->Name, strtab );
      fprintf ( stderr, 
                "'\n"
                "    value 0x%x\n"
                "     sec# %d\n"
                "     type 0x%x\n"
                "   sclass 0x%x\n"
                "     nAux %d\n",
                symtab_i->Value,
                (Int32)(symtab_i->SectionNumber) - 1,
                (UInt32)symtab_i->Type,
                (UInt32)symtab_i->StorageClass,
                (UInt32)symtab_i->NumberOfAuxSymbols 
              );
      i += symtab_i->NumberOfAuxSymbols;
      i++;
   }

   fprintf ( stderr, "\n" );
1101
   return 1;
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
}


static int
ocGetNames_PEi386 ( ObjectCode* oc )
{
   COFF_header*  hdr;
   COFF_section* sectab;
   COFF_symbol*  symtab;
   UChar*        strtab;

   UChar* sname;
   void*  addr;
   int    i;
   
   hdr = (COFF_header*)(oc->image);
   sectab = (COFF_section*) (
               ((UChar*)(oc->image)) 
               + sizeof_COFF_header + hdr->SizeOfOptionalHeader
            );
   symtab = (COFF_symbol*) (
               ((UChar*)(oc->image))
               + hdr->PointerToSymbolTable 
            );
   strtab = ((UChar*)(oc->image))
            + hdr->PointerToSymbolTable
            + hdr->NumberOfSymbols * sizeof_COFF_symbol;

   /* Copy exported symbols into the ObjectCode. */
1131
1132
1133
1134
1135
1136
1137
1138

   oc->n_symbols = hdr->NumberOfSymbols;
   oc->symbols   = stgMallocBytes(oc->n_symbols * sizeof(char*),
                                  "ocGetNames_PEi386(oc->symbols)");
   /* Call me paranoid; I don't care. */
   for (i = 0; i < oc->n_symbols; i++) 
      oc->symbols[i] = NULL;

1139
1140
1141
   i = 0;
   while (1) {
      COFF_symbol* symtab_i;
1142
      if (i >= (Int32)(hdr->NumberOfSymbols)) break;
1143
      symtab_i = (COFF_symbol*)
1144
                 myindex ( sizeof_COFF_symbol, symtab, i );
1145

1146
1147
      if (symtab_i->StorageClass == MYIMAGE_SYM_CLASS_EXTERNAL &&
          symtab_i->SectionNumber != MYIMAGE_SYM_UNDEFINED) {
1148
1149
1150
1151

         /* This symbol is global and defined, viz, exported */
         COFF_section* sectabent;

1152
1153
         /* cstring_from_COFF_symbol_name always succeeds. */
         sname = cstring_from_COFF_symbol_name ( symtab_i->Name, strtab );
1154

1155
1156
         /* for MYIMAGE_SYMCLASS_EXTERNAL 
                && !MYIMAGE_SYM_UNDEFINED,
1157
1158
1159
1160
1161
            the address of the symbol is: 
                address of relevant section + offset in section
         */
         sectabent = (COFF_section*)
                     myindex ( sizeof_COFF_section, 
1162
1163
                               sectab,
                               symtab_i->SectionNumber-1 );
1164
1165
1166
         addr = ((UChar*)(oc->image))
                + (sectabent->PointerToRawData
                   + symtab_i->Value);
rrt's avatar
rrt committed
1167
         /* fprintf(stderr,"addSymbol %p `%s'\n", addr,sname); */
1168
1169
1170
1171
         IF_DEBUG(linker, belch("addSymbol %p `%s'\n", addr,sname);)
         ASSERT(i >= 0 && i < oc->n_symbols);
         oc->symbols[i] = sname;
         insertStrHashTable(symhash, sname, addr);
1172
1173
1174
1175
1176
1177
      }
      i += symtab_i->NumberOfAuxSymbols;
      i++;
   }

   /* Copy section information into the ObjectCode. */
1178
1179
1180
1181
1182
1183

   oc->n_sections = hdr->NumberOfSections;
   oc->sections = stgMallocBytes( oc->n_sections * sizeof(Section), 
                                  "ocGetNamesPEi386" );

   for (i = 0; i < oc->n_sections; i++) {
1184
1185
1186
1187
1188
1189
1190
      UChar* start;
      UChar* end;

      SectionKind kind 
         = SECTIONKIND_OTHER;
      COFF_section* sectab_i
         = (COFF_section*)
1191
           myindex ( sizeof_COFF_section, sectab, i );
rrt's avatar
rrt committed
1192
      IF_DEBUG(linker, belch("section name = %s\n", sectab_i->Name ));
1193
1194
1195
1196
1197
1198

#if 0
      /* I'm sure this is the Right Way to do it.  However, the 
         alternative of testing the sectab_i->Name field seems to
         work ok with Cygwin.
      */
1199
1200
      if (sectab_i->Characteristics & MYIMAGE_SCN_CNT_CODE || 
          sectab_i->Characteristics & MYIMAGE_SCN_CNT_INITIALIZED_DATA)
1201
1202
1203
         kind = SECTIONKIND_CODE_OR_RODATA;
#endif

1204
1205
      if (0==strcmp(".text",sectab_i->Name) ||
          0==strcmp(".rodata",sectab_i->Name))
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
         kind = SECTIONKIND_CODE_OR_RODATA;
      if (0==strcmp(".data",sectab_i->Name) ||
          0==strcmp(".bss",sectab_i->Name))
         kind = SECTIONKIND_RWDATA;

      start = ((UChar*)(oc->image)) 
              + sectab_i->PointerToRawData;
      end   = start 
              + sectab_i->SizeOfRawData - 1;

1216
1217
1218
      if (kind == SECTIONKIND_OTHER) {
         belch("Unknown PEi386 section name `%s'", sectab_i->Name);
         return 0;
1219
      }
1220
1221
1222
1223

      oc->sections[i].start = start;
      oc->sections[i].end   = end;
      oc->sections[i].kind  = kind;
1224
1225
   }

1226
   return 1;   
1227
1228
1229
1230
}


static int
1231
ocResolve_PEi386 ( ObjectCode* oc )
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
{
   COFF_header*  hdr;
   COFF_section* sectab;
   COFF_symbol*  symtab;
   UChar*        strtab;

   UInt32        A;
   UInt32        S;
   UInt32*       pP;

   int i, j;
1243
1244
1245
1246

   /* ToDo: should be variable-sized?  But is at least safe in the
      sense of buffer-overrun-proof. */
   char symbol[1000];
1247
1248
   /* fprintf(stderr, "resolving for %s\n", oc->fileName); */

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
   hdr = (COFF_header*)(oc->image);
   sectab = (COFF_section*) (
               ((UChar*)(oc->image)) 
               + sizeof_COFF_header + hdr->SizeOfOptionalHeader
            );
   symtab = (COFF_symbol*) (
               ((UChar*)(oc->image))
               + hdr->PointerToSymbolTable 
            );
   strtab = ((UChar*)(oc->image))
            + hdr->PointerToSymbolTable
            + hdr->NumberOfSymbols * sizeof_COFF_symbol;

   for (i = 0; i < hdr->NumberOfSections; i++) {
      COFF_section* sectab_i
         = (COFF_section*)
1265
           myindex ( sizeof_COFF_section, sectab, i );
1266
1267
1268
1269
1270
1271
1272
1273
      COFF_reloc* reltab
         = (COFF_reloc*) (
              ((UChar*)(oc->image)) + sectab_i->PointerToRelocations
           );
      for (j = 0; j < sectab_i->NumberOfRelocations; j++) {
         COFF_symbol* sym;
         COFF_reloc* reltab_j 
            = (COFF_reloc*)
1274
              myindex ( sizeof_COFF_reloc, reltab, j );
1275
1276
1277
1278
1279

         /* the location to patch */
         pP = (UInt32*)(
                 ((UChar*)(oc->image)) 
                 + (sectab_i->PointerToRawData 
1280
1281
                    + reltab_j->VirtualAddress
                    - sectab_i->VirtualAddress )
1282
1283
1284
1285
1286
1287
              );
         /* the existing contents of pP */
         A = *pP;
         /* the symbol to connect to */
         sym = (COFF_symbol*)
               myindex ( sizeof_COFF_symbol, 
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
                         symtab, reltab_j->SymbolTableIndex );
         IF_DEBUG(linker,
                  fprintf ( stderr, 
                            "reloc sec %2d num %3d:  type 0x%-4x   "
                            "vaddr 0x%-8x   name `",
                            i, j,
                            (UInt32)reltab_j->Type, 
                            reltab_j->VirtualAddress );
                            printName ( sym->Name, strtab );
                            fprintf ( stderr, "'\n" ));
1298

1299
         if (sym->StorageClass == MYIMAGE_SYM_CLASS_STATIC) {
1300
1301
1302
1303
            COFF_section* section_sym 
               = findPEi386SectionCalled ( oc, sym->Name );
            if (!section_sym) {
               fprintf ( stderr, "bad section = `%s'\n", sym->Name );
1304
1305
               barf("Can't find abovementioned PEi386 section");
               return 0;
1306
1307
1308
1309
1310
            }
            S = ((UInt32)(oc->image))
                + (section_sym->PointerToRawData
                   + sym->Value);
         } else {
1311
            copyName ( sym->Name, strtab, symbol, 1000-1 );
1312
1313
1314
1315
1316
1317
1318
1319
1320
            zapTrailingAtSign ( symbol );
            (void*)S = lookupLocalSymbol( oc, symbol );
            if ((void*)S == NULL)
               (void*)S = lookupSymbol( symbol );
            if (S == 0) {
	        belch("ocResolve_PEi386: %s: unknown symbol `%s'", 
                      oc->fileName, symbol);
	        return 0;
            }
1321
1322
1323
         }

         switch (reltab_j->Type) {
1324
            case MYIMAGE_REL_I386_DIR32: 
1325
1326
               *pP = A + S; 
               break;
1327
            case MYIMAGE_REL_I386_REL32:
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
               /* Tricky.  We have to insert a displacement at
                  pP which, when added to the PC for the _next_
                  insn, gives the address of the target (S).
                  Problem is to know the address of the next insn
                  when we only know pP.  We assume that this
                  literal field is always the last in the insn,
                  so that the address of the next insn is pP+4
                  -- hence the constant 4.
                  Also I don't know if A should be added, but so
                  far it has always been zero.
	       */
               ASSERT(A==0);
               *pP = S - ((UInt32)pP) - 4;
               break;
            default: 
               fprintf(stderr, 
                       "unhandled PEi386 relocation type %d\n",
                       reltab_j->Type);
1346
1347
               barf("unhandled PEi386 relocation type");
               return 0;
1348
1349
1350
1351
1352
         }

      }
   }
   
1353
   /* fprintf(stderr, "completed     %s\n", oc->fileName); */
1354
   return 1;
1355
1356
}

1357
#endif /* defined(OBJFORMAT_PEi386) */
1358
1359
1360


/* --------------------------------------------------------------------------
1361
 * ELF specifics
1362
1363
 * ------------------------------------------------------------------------*/

1364
#if defined(OBJFORMAT_ELF)
1365
1366
1367
1368

#define FALSE 0
#define TRUE  1

1369
#if defined(sparc_TARGET_ARCH)
1370
#  define ELF_TARGET_SPARC  /* Used inside <elf.h> */
chak's avatar
chak committed
1371
1372
#elif defined(i386_TARGET_ARCH)
#  define ELF_TARGET_386    /* Used inside <elf.h> */
1373
#endif
chak's avatar
chak committed
1374
1375
1376
/* There is a similar case for IA64 in the Solaris2 headers if this
 * ever becomes relevant.
 */
1377

1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
#include <elf.h>

static char *
findElfSection ( void* objImage, Elf32_Word sh_type )
{
   int i;
   char* ehdrC = (char*)objImage;
   Elf32_Ehdr* ehdr = ( Elf32_Ehdr*)ehdrC;
   Elf32_Shdr* shdr = (Elf32_Shdr*) (ehdrC + ehdr->e_shoff);
   char* ptr = NULL;
   for (i = 0; i < ehdr->e_shnum; i++) {
      if (shdr[i].sh_type == sh_type &&
          i !=  ehdr->e_shstrndx) {
         ptr = ehdrC + shdr[i].sh_offset;
         break;
      }
   }
   return ptr;
}


static int
ocVerifyImage_ELF ( ObjectCode* oc )
{
   Elf32_Shdr* shdr;
   Elf32_Sym*  stab;
   int i, j, nent, nstrtab, nsymtabs;
   char* sh_strtab;
   char* strtab;

   char*       ehdrC = (char*)(oc->image);
   Elf32_Ehdr* ehdr  = ( Elf32_Ehdr*)ehdrC;

   if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
       ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
       ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
       ehdr->e_ident[EI_MAG3] != ELFMAG3) {
      belch("ocVerifyImage_ELF: not an ELF header");
      return 0;
   }
   IF_DEBUG(linker,belch( "Is an ELF header" ));

   if (ehdr->e_ident[EI_CLASS] != ELFCLASS32) {
      belch("ocVerifyImage_ELF: not 32 bit ELF" );
      return 0;
   }

   IF_DEBUG(linker,belch( "Is 32 bit ELF" ));

   if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
       IF_DEBUG(linker,belch( "Is little-endian" ));
   } else
   if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
       IF_DEBUG(linker,belch( "Is big-endian" ));
   } else {
       belch("ocVerifyImage_ELF: unknown endiannness");
       return 0;
   }

   if (ehdr->e_type != ET_REL) {
      belch("ocVerifyImage_ELF: not a relocatable object (.o) file");
      return 0;
   }
   IF_DEBUG(linker, belch( "Is a relocatable object (.o) file" ));

   IF_DEBUG(linker,belch( "Architecture is " ));
   switch (ehdr->e_machine) {
      case EM_386:   IF_DEBUG(linker,belch( "x86" )); break;
      case EM_SPARC: IF_DEBUG(linker,belch( "sparc" )); break;
      default:       IF_DEBUG(linker,belch( "unknown" )); 
                     belch("ocVerifyImage_ELF: unknown architecture");
                     return 0;
   }

   IF_DEBUG(linker,belch(
             "\nSection header table: start %d, n_entries %d, ent_size %d", 
             ehdr->e_shoff, ehdr->e_shnum, ehdr->e_shentsize  ));

   ASSERT (ehdr->e_shentsize == sizeof(Elf32_Shdr));

   shdr = (Elf32_Shdr*) (ehdrC + ehdr->e_shoff);

   if (ehdr->e_shstrndx == SHN_UNDEF) {
      belch("ocVerifyImage_ELF: no section header string table");
      return 0;
   } else {
      IF_DEBUG(linker,belch( "Section header string table is section %d", 
                          ehdr->e_shstrndx));
      sh_strtab = ehdrC + shdr[ehdr->e_shstrndx].sh_offset;
   }

   for (i = 0; i < ehdr->e_shnum; i++) {
      IF_DEBUG(linker,fprintf(stderr, "%2d:  ", i ));
1471
1472
1473
      IF_DEBUG(linker,fprintf(stderr, "type=%2d  ", (int)shdr[i].sh_type ));
      IF_DEBUG(linker,fprintf(stderr, "size=%4d  ", (int)shdr[i].sh_size ));
      IF_DEBUG(linker,fprintf(stderr, "offs=%4d  ", (int)shdr[i].sh_offset ));
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531