2009-04-11 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / image-writer.c
1 /*
2  * image-writer.c: Creation of object files or assembly files using the same interface.
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *   Paolo Molaro (lupus@ximian.com)
8  *
9  * (C) 2002 Ximian, Inc.
10  */
11
12 #include "config.h"
13 #include <sys/types.h>
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17 #ifdef HAVE_STDINT_H
18 #include <stdint.h>
19 #endif
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <string.h>
23 #ifndef PLATFORM_WIN32
24 #include <sys/time.h>
25 #else
26 #include <winsock2.h>
27 #include <windows.h>
28 #endif
29
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <limits.h>    /* for PAGESIZE */
33 #ifndef PAGESIZE
34 #define PAGESIZE 4096
35 #endif
36
37 #include "image-writer.h"
38
39 #ifndef PLATFORM_WIN32
40 #include <mono/utils/freebsd-elf32.h>
41 #include <mono/utils/freebsd-elf64.h>
42 #endif
43
44 #include "mini.h"
45
46 #define TV_DECLARE(name) gint64 name
47 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
48 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
49
50 #ifdef PLATFORM_WIN32
51 #define SHARED_EXT ".dll"
52 #elif defined(__ppc__) && defined(__MACH__)
53 #define SHARED_EXT ".dylib"
54 #else
55 #define SHARED_EXT ".so"
56 #endif
57
58 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
59 #define AS_STRING_DIRECTIVE ".asciz"
60 #else
61 /* GNU as */
62 #define AS_STRING_DIRECTIVE ".string"
63 #endif
64
65
66 // __MACH__
67 // .byte generates 1 byte per expression.
68 // .short generates 2 bytes per expression.
69 // .long generates 4 bytes per expression.
70 // .quad generates 8 bytes per expression.
71
72 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
73 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
74 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
75
76 #if defined(__x86_64__) && !defined(PLATFORM_WIN32)
77 #define USE_ELF_WRITER 1
78 #define USE_ELF_RELA 1
79 #endif
80
81 #if defined(__i386__) && !defined(PLATFORM_WIN32)
82 #define USE_ELF_WRITER 1
83 #endif
84
85 #if defined(__arm__) && !defined(__MACH__)
86 #define USE_ELF_WRITER 1
87 #endif
88
89 #if defined(__mips__)
90 #define USE_ELF_WRITER 1
91 #endif
92
93 #if defined(USE_ELF_WRITER)
94 #define USE_BIN_WRITER 1
95 #endif
96
97 #ifdef USE_BIN_WRITER
98
99 typedef struct _BinSymbol BinSymbol;
100 typedef struct _BinReloc BinReloc;
101 typedef struct _BinSection BinSection;
102
103 #endif
104
105 /* emit mode */
106 enum {
107         EMIT_NONE,
108         EMIT_BYTE,
109         EMIT_WORD,
110         EMIT_LONG
111 };
112
113 struct _MonoImageWriter {
114         MonoMemPool *mempool;
115         char *outfile;
116         gboolean use_bin_writer;
117         const char *current_section;
118         int current_subsection;
119         const char *section_stack [16];
120         int subsection_stack [16];
121         int stack_pos;
122         FILE *fp;
123         /* Bin writer */
124 #ifdef USE_BIN_WRITER
125         BinSymbol *symbols;
126         BinSection *sections;
127         BinSection *cur_section;
128         BinReloc *relocations;
129         GHashTable *labels;
130         int num_relocs;
131 #endif
132         /* Asm writer */
133         char *tmpfname;
134         int mode; /* emit mode */
135         int col_count; /* bytes emitted per .byte line */
136 };
137
138 static G_GNUC_UNUSED int
139 ilog2(register int value)
140 {
141         int count = -1;
142         while (value & ~0xf) count += 4, value >>= 4;
143         while (value) count++, value >>= 1;
144         return count;
145 }
146
147 #ifdef USE_BIN_WRITER
148
149 typedef struct _BinLabel BinLabel;
150 struct _BinLabel {
151         char *name;
152         BinSection *section;
153         int offset;
154 };
155
156 struct _BinReloc {
157         BinReloc *next;
158         char *val1;
159         char *val2;
160         BinSection *val2_section;
161         int val2_offset;
162         int offset;
163         BinSection *section;
164         int section_offset;
165         int reloc_type;
166 };
167
168 struct _BinSymbol {
169         BinSymbol *next;
170         char *name;
171         BinSection *section;
172         int offset;
173         gboolean is_function;
174         gboolean is_global;
175         char *end_label;
176 };
177
178 struct _BinSection {
179         BinSection *next;
180         BinSection *parent;
181         char *name;
182         int subsection;
183         guint8 *data;
184         int data_len;
185         int cur_offset;
186         int file_offset;
187         int virt_offset;
188         int shidx;
189 };
190
191 static void
192 bin_writer_emit_start (MonoImageWriter *acfg)
193 {
194         acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
195 }
196
197 static void
198 bin_writer_emit_section_change (MonoImageWriter *acfg, const char *section_name, int subsection_index)
199 {
200         BinSection *section;
201
202         if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
203                         && strcmp (acfg->cur_section->name, section_name) == 0)
204                 return;
205         for (section = acfg->sections; section; section = section->next) {
206                 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
207                         acfg->cur_section = section;
208                         return;
209                 }
210         }
211         if (!section) {
212                 section = g_new0 (BinSection, 1);
213                 section->name = g_strdup (section_name);
214                 section->subsection = subsection_index;
215                 section->next = acfg->sections;
216                 acfg->sections = section;
217                 acfg->cur_section = section;
218         }
219 }
220
221 static void
222 bin_writer_emit_symbol_inner (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean is_global, gboolean func)
223 {
224         BinSymbol *symbol = g_new0 (BinSymbol, 1);
225         symbol->name = g_strdup (name);
226         if (end_label)
227                 symbol->end_label = g_strdup (end_label);
228         symbol->is_function = func;
229         symbol->is_global = is_global;
230         symbol->section = acfg->cur_section;
231         /* FIXME: we align after this call... */
232         symbol->offset = symbol->section->cur_offset;
233         symbol->next = acfg->symbols;
234         acfg->symbols = symbol;
235 }
236
237 static void
238 bin_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
239 {
240         bin_writer_emit_symbol_inner (acfg, name, NULL, TRUE, func);
241 }
242
243 static void
244 bin_writer_emit_local_symbol (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean func)
245 {
246         bin_writer_emit_symbol_inner (acfg, name, end_label, FALSE, func);
247 }
248
249 static void
250 bin_writer_emit_label (MonoImageWriter *acfg, const char *name)
251 {
252         BinLabel *label = g_new0 (BinLabel, 1);
253         label->name = g_strdup (name);
254         label->section = acfg->cur_section;
255         label->offset = acfg->cur_section->cur_offset;
256         g_hash_table_insert (acfg->labels, label->name, label);
257 }
258
259 static void
260 bin_writer_emit_ensure_buffer (BinSection *section, int size)
261 {
262         int new_offset = section->cur_offset + size;
263         if (new_offset >= section->data_len) {
264                 int new_size = section->data_len? section->data_len * 2: 256;
265                 guint8 *data;
266                 while (new_size <= new_offset)
267                         new_size *= 2;
268                 data = g_malloc0 (new_size);
269                 memcpy (data, section->data, section->data_len);
270                 g_free (section->data);
271                 section->data = data;
272                 section->data_len = new_size;
273         }
274 }
275
276 static void
277 bin_writer_emit_bytes (MonoImageWriter *acfg, const guint8* buf, int size)
278 {
279         bin_writer_emit_ensure_buffer (acfg->cur_section, size);
280         memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
281         acfg->cur_section->cur_offset += size;
282 }
283
284 static void
285 bin_writer_emit_string (MonoImageWriter *acfg, const char *value)
286 {
287         int size = strlen (value) + 1;
288         bin_writer_emit_bytes (acfg, (const guint8*)value, size);
289 }
290
291 static void
292 bin_writer_emit_line (MonoImageWriter *acfg)
293 {
294         /* Nothing to do in binary writer */
295 }
296
297 static void 
298 bin_writer_emit_alignment (MonoImageWriter *acfg, int size)
299 {
300         int offset = acfg->cur_section->cur_offset;
301         int add;
302         offset += (size - 1);
303         offset &= ~(size - 1);
304         add = offset - acfg->cur_section->cur_offset;
305         if (add) {
306                 bin_writer_emit_ensure_buffer (acfg->cur_section, add);
307                 acfg->cur_section->cur_offset += add;
308         }
309 }
310
311 static void
312 bin_writer_emit_pointer_unaligned (MonoImageWriter *acfg, const char *target)
313 {
314         BinReloc *reloc;
315
316         if (!target)
317                 // FIXME:
318                 g_assert_not_reached ();
319         reloc = g_new0 (BinReloc, 1);
320         reloc->val1 = g_strdup (target);
321         reloc->section = acfg->cur_section;
322         reloc->section_offset = acfg->cur_section->cur_offset;
323         reloc->next = acfg->relocations;
324         acfg->relocations = reloc;
325         if (strcmp (reloc->section->name, ".data") == 0) {
326                 acfg->num_relocs++;
327                 //g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
328         }
329         acfg->cur_section->cur_offset += sizeof (gpointer);
330 }
331
332 static void
333 bin_writer_emit_pointer (MonoImageWriter *acfg, const char *target)
334 {
335         bin_writer_emit_alignment (acfg, sizeof (gpointer));
336         bin_writer_emit_pointer_unaligned (acfg, target);
337 }
338
339 static void
340 bin_writer_emit_int16 (MonoImageWriter *acfg, int value)
341 {
342         guint8 *data;
343         bin_writer_emit_ensure_buffer (acfg->cur_section, 2);
344         data = acfg->cur_section->data + acfg->cur_section->cur_offset;
345         acfg->cur_section->cur_offset += 2;
346         /* FIXME: little endian */
347         data [0] = value;
348         data [1] = value >> 8;
349 }
350
351 static void
352 bin_writer_emit_int32 (MonoImageWriter *acfg, int value)
353 {
354         guint8 *data;
355         bin_writer_emit_ensure_buffer (acfg->cur_section, 4);
356         data = acfg->cur_section->data + acfg->cur_section->cur_offset;
357         acfg->cur_section->cur_offset += 4;
358         /* FIXME: little endian */
359         data [0] = value;
360         data [1] = value >> 8;
361         data [2] = value >> 16;
362         data [3] = value >> 24;
363 }
364
365 static BinReloc*
366 create_reloc (MonoImageWriter *acfg, const char *end, const char* start, int offset)
367 {
368         BinReloc *reloc;
369         reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
370         reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
371         if (strcmp (start, ".") == 0) {
372                 reloc->val2_section = acfg->cur_section;
373                 reloc->val2_offset = acfg->cur_section->cur_offset;
374         } else {
375                 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
376         }
377         reloc->offset = offset;
378         reloc->section = acfg->cur_section;
379         reloc->section_offset = acfg->cur_section->cur_offset;
380         reloc->next = acfg->relocations;
381         acfg->relocations = reloc;
382         return reloc;
383 }
384
385 static void
386 bin_writer_emit_symbol_diff (MonoImageWriter *acfg, const char *end, const char* start, int offset)
387 {
388         create_reloc (acfg, end, start, offset);
389         acfg->cur_section->cur_offset += 4;
390         /*if (strcmp (reloc->section->name, ".data") == 0) {
391                 acfg->num_relocs++;
392                 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
393         }*/
394 }
395
396 /* 
397  * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
398  * Do not advance PC.
399  */
400 static G_GNUC_UNUSED void
401 bin_writer_emit_reloc (MonoImageWriter *acfg, int reloc_type, const char *symbol, int addend)
402 {
403         BinReloc *reloc = create_reloc (acfg, symbol, ".", addend);
404         reloc->reloc_type = reloc_type;
405 }
406
407 static void
408 bin_writer_emit_zero_bytes (MonoImageWriter *acfg, int num)
409 {
410         bin_writer_emit_ensure_buffer (acfg->cur_section, num);
411         acfg->cur_section->cur_offset += num;
412 }
413
414 #ifdef USE_ELF_WRITER
415
416 enum {
417         SECT_NULL,
418         SECT_HASH,
419         SECT_DYNSYM,
420         SECT_DYNSTR,
421         SECT_REL_DYN,
422         SECT_RELA_DYN,
423         SECT_TEXT,
424         SECT_DYNAMIC,
425         SECT_GOT_PLT,
426         SECT_DATA,
427         SECT_BSS,
428         SECT_DEBUG_FRAME,
429         SECT_DEBUG_INFO,
430         SECT_DEBUG_ABBREV,
431         SECT_DEBUG_LINE,
432         SECT_DEBUG_LOC,
433         SECT_SHSTRTAB,
434         SECT_SYMTAB,
435         SECT_STRTAB,
436         SECT_NUM
437 };
438
439 #if SIZEOF_VOID_P == 4
440
441 typedef Elf32_Ehdr ElfHeader;
442 typedef Elf32_Shdr ElfSectHeader;
443 typedef Elf32_Phdr ElfProgHeader;
444 typedef Elf32_Sym ElfSymbol;
445 typedef Elf32_Rel ElfReloc;
446 typedef Elf32_Rela ElfRelocA;
447 typedef Elf32_Dyn ElfDynamic;
448
449 #else
450
451 typedef Elf64_Ehdr ElfHeader;
452 typedef Elf64_Shdr ElfSectHeader;
453 typedef Elf64_Phdr ElfProgHeader;
454 typedef Elf64_Sym ElfSymbol;
455 typedef Elf64_Rel ElfReloc;
456 typedef Elf64_Rela ElfRelocA;
457 typedef Elf64_Dyn ElfDynamic;
458
459 #endif
460
461 typedef struct {
462         const char *name;
463         int type;
464         int esize;
465         int flags;
466         int align;
467 } SectInfo;
468
469 static SectInfo section_info [] = {
470         {"", 0, 0, 0, 0},
471         {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
472         {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
473         {".dynstr", SHT_STRTAB, 0, 2, 1},
474         {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
475         {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
476         {".text", SHT_PROGBITS, 0, 6, 4096},
477         {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
478         {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
479         {".data", SHT_PROGBITS, 0, 3, 8},
480         {".bss", SHT_NOBITS, 0, 3, 8},
481         {".debug_frame", SHT_PROGBITS, 0, 0, 8},
482         {".debug_info", SHT_PROGBITS, 0, 0, 1},
483         {".debug_abbrev", SHT_PROGBITS, 0, 0, 1},
484         {".debug_line", SHT_PROGBITS, 0, 0, 1},
485         {".debug_loc", SHT_PROGBITS, 0, 0, 1},
486         {".shstrtab", SHT_STRTAB, 0, 0, 1},
487         {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
488         {".strtab", SHT_STRTAB, 0, 0, 1}
489 };
490
491 typedef struct {
492         GString *data;
493         GHashTable *hash;
494 } ElfStrTable;
495
496 static int
497 str_table_add (ElfStrTable *table, const char* value)
498 {
499         int idx;
500         if (!table->data) {
501                 table->data = g_string_new_len ("", 1);
502                 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
503         }
504         idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
505         if (idx)
506                 return idx;
507         idx = table->data->len;
508         g_string_append (table->data, value);
509         g_string_append_c (table->data, 0);
510         g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
511         return idx;
512 }
513
514 static void
515 append_subsection (MonoImageWriter *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
516 {
517         int offset = sect->cur_offset;
518         /*offset += (sheaders [sect->shidx].sh_addralign - 1);
519         offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
520         offset += (8 - 1);
521         offset &= ~(8 - 1);
522         bin_writer_emit_ensure_buffer (sect, offset);
523         //g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
524         sect->cur_offset = offset;
525
526         bin_writer_emit_ensure_buffer (sect, add->cur_offset);
527         memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
528         add->parent = sect;
529         sect->cur_offset += add->cur_offset;
530         add->cur_offset = offset; /* it becomes the offset in the parent section */
531         //g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, (int)sheaders [sect->shidx].sh_addralign);
532         add->data = NULL;
533         add->data_len = 0;
534 }
535
536 /* merge the subsections */
537 static int
538 collect_sections (MonoImageWriter *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
539 {
540         int i, j, maxs, num_sections;
541         BinSection *sect;
542
543         num_sections = 0;
544         maxs = 0;
545         for (sect = acfg->sections; sect; sect = sect->next) {
546                 if (sect->subsection == 0) {
547                         out [num_sections++] = sect;
548                         g_assert (num_sections < num);
549                 }
550                 maxs = MAX (maxs, sect->subsection);
551         }
552         for (i = 0; i < num_sections; i++) {
553                 for (j = 1; j <= maxs; ++j) {
554                         for (sect = acfg->sections; sect; sect = sect->next) {
555                                 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
556                                         append_subsection (acfg, sheaders, out [i], sect);
557                                 }
558                         }
559                 }
560         }
561         return num_sections;
562 }
563
564 static unsigned long
565 elf_hash (const unsigned char *name)
566 {
567         unsigned long h = 0, g;
568         while (*name) {
569                 h = (h << 4) + *name++;
570                 if ((g = h & 0xf0000000))
571                         h ^= g >> 24;
572                 h &= ~g;
573         }
574         return h;
575 }
576
577 #define NUM_BUCKETS 17
578
579 static int*
580 build_hash (MonoImageWriter *acfg, int num_sections, ElfStrTable *dynstr)
581 {
582         int *data;
583         int num_symbols = 1 + num_sections + 3;
584         BinSymbol *symbol;
585
586         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
587                 if (!symbol->is_global)
588                         continue;
589                 num_symbols++;
590                 str_table_add (dynstr, symbol->name);
591                 /*g_print ("adding sym: %s\n", symbol->name);*/
592         }
593         str_table_add (dynstr, "__bss_start");
594         str_table_add (dynstr, "_edata");
595         str_table_add (dynstr, "_end");
596
597         data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
598         data [0] = NUM_BUCKETS;
599         data [1] = num_symbols;
600
601         return data;
602 }
603
604 static gsize
605 get_label_addr (MonoImageWriter *acfg, const char *name)
606 {
607         int offset;
608         BinLabel *lab;
609         BinSection *section;
610         gsize value;
611
612         lab = g_hash_table_lookup (acfg->labels, name);
613         if (!lab)
614                 g_error ("Undefined label: '%s'.\n", name);
615         section = lab->section;
616         offset = lab->offset;
617         if (section->parent) {
618                 value = section->parent->virt_offset + section->cur_offset + offset;
619         } else {
620                 value = section->virt_offset + offset;
621         }
622         return value;
623 }
624
625 static ElfSymbol*
626 collect_syms (MonoImageWriter *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
627 {
628         ElfSymbol *symbols;
629         BinSymbol *symbol;
630         BinSection *section;
631         int i;
632         int *bucket;
633         int *chain;
634         unsigned long hashc;
635
636         if (hash)
637                 symbols = g_new0 (ElfSymbol, hash [1]);
638         else {
639                 i = 0;
640                 for (symbol = acfg->symbols; symbol; symbol = symbol->next)
641                         i ++;
642                 
643                 symbols = g_new0 (ElfSymbol, i + SECT_NUM + 10); /* FIXME */
644         }
645
646         /* the first symbol is undef, all zeroes */
647         i = 1;
648         if (sheaders) {
649                 int j;
650                 for (j = 1; j < SECT_NUM; ++j) {
651                         symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
652                         symbols [i].st_shndx = j;
653                         symbols [i].st_value = sheaders [j].sh_addr;
654                         ++i;
655                 }
656         } else {
657                 for (section = acfg->sections; section; section = section->next) {
658                         if (section->parent)
659                                 continue;
660                         symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
661                         if (strcmp (section->name, ".text") == 0) {
662                                 symbols [i].st_shndx = SECT_TEXT;
663                                 section->shidx = SECT_TEXT;
664                                 section->file_offset = 4096;
665                                 symbols [i].st_value = section->virt_offset;
666                         } else if (strcmp (section->name, ".data") == 0) {
667                                 symbols [i].st_shndx = SECT_DATA;
668                                 section->shidx = SECT_DATA;
669                                 section->file_offset = 4096 + 28; /* FIXME */
670                                 symbols [i].st_value = section->virt_offset;
671                         } else if (strcmp (section->name, ".bss") == 0) {
672                                 symbols [i].st_shndx = SECT_BSS;
673                                 section->shidx = SECT_BSS;
674                                 section->file_offset = 4096 + 28 + 8; /* FIXME */
675                                 symbols [i].st_value = section->virt_offset;
676                         }
677                         ++i;
678                 }
679         }
680         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
681                 int offset;
682                 BinLabel *lab;
683                 if (!symbol->is_global && hash)
684                         continue;
685                 symbols [i].st_info = ELF32_ST_INFO (symbol->is_global ? STB_GLOBAL : STB_LOCAL, symbol->is_function? STT_FUNC : STT_OBJECT);
686                 symbols [i].st_name = str_table_add (strtab, symbol->name);
687                 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
688                 section = symbol->section;
689                 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
690                 lab = g_hash_table_lookup (acfg->labels, symbol->name);
691                 offset = lab->offset;
692                 if (section->parent) {
693                         symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
694                 } else {
695                         symbols [i].st_value = section->virt_offset + offset;
696                 }
697
698                 if (symbol->end_label) {
699                         BinLabel *elab = g_hash_table_lookup (acfg->labels, symbol->end_label);
700                         g_assert (elab);
701                         symbols [i].st_size = elab->offset - lab->offset;
702                 }
703                 ++i;
704         }
705         /* add special symbols */
706         symbols [i].st_name = str_table_add (strtab, "__bss_start");
707         symbols [i].st_shndx = 0xfff1;
708         symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
709         ++i;
710         symbols [i].st_name = str_table_add (strtab, "_edata");
711         symbols [i].st_shndx = 0xfff1;
712         symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
713         ++i;
714         symbols [i].st_name = str_table_add (strtab, "_end");
715         symbols [i].st_shndx = 0xfff1;
716         symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
717         ++i;
718
719         if (num_syms)
720                 *num_syms = i;
721
722         /* add to hash table */
723         if (hash) {
724                 bucket = hash + 2;
725                 chain = hash + 2 + hash [0];
726                 for (i = 0; i < hash [1]; ++i) {
727                         int slot;
728                         /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
729                         if (!symbols [i].st_name)
730                                 continue;
731                         hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
732                         slot = hashc % hash [0];
733                         /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
734                         if (bucket [slot]) {
735                                 chain [i] = bucket [slot];
736                                 bucket [slot] = i;
737                         } else {
738                                 bucket [slot] = i;
739                         }
740                 }
741         }
742         return symbols;
743 }
744
745 static void
746 reloc_symbols (MonoImageWriter *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
747 {
748         BinSection *section;
749         BinSymbol *symbol;
750         int i;
751
752         i = 1;
753         if (dynamic) {
754                 for (section = acfg->sections; section; section = section->next) {
755                         if (section->parent)
756                                 continue;
757                         symbols [i].st_value = sheaders [section->shidx].sh_addr;
758                         ++i;
759                 }
760         } else {
761                 for (i = 1; i < SECT_NUM; ++i) {
762                         symbols [i].st_value = sheaders [i].sh_addr;
763                 }
764         }
765         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
766                 int offset;
767                 BinLabel *lab;
768                 if (dynamic && !symbol->is_global)
769                         continue;
770                 section = symbol->section;
771                 lab = g_hash_table_lookup (acfg->labels, symbol->name);
772                 offset = lab->offset;
773                 if (section->parent) {
774                         symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
775                 } else {
776                         symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
777                 }
778                 ++i;
779         }
780         /* __bss_start */
781         symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
782         ++i;
783         /* _edata */
784         symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
785         ++i;
786         /* _end */
787         symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
788         ++i;
789 }
790
791 static void
792 resolve_reloc (MonoImageWriter *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
793 {
794         guint8 *data;
795         gssize end_val, start_val;
796         gsize vaddr;
797
798         end_val = get_label_addr (acfg, reloc->val1);
799         if (reloc->val2) {
800                 start_val = get_label_addr (acfg, reloc->val2);
801         } else if (reloc->val2_section) {
802                 start_val = reloc->val2_offset;
803                 if (reloc->val2_section->parent)
804                         start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
805                 else
806                         start_val += reloc->val2_section->virt_offset;
807         } else {
808                 start_val = 0;
809         }
810         end_val = end_val - start_val + reloc->offset;
811         if (reloc->section->parent) {
812                 data = reloc->section->parent->data;
813                 data += reloc->section->cur_offset;
814                 data += reloc->section_offset;
815                 vaddr = reloc->section->parent->virt_offset;
816                 vaddr += reloc->section->cur_offset;
817                 vaddr += reloc->section_offset;
818         } else {
819                 data = reloc->section->data;
820                 data += reloc->section_offset;
821                 vaddr = reloc->section->virt_offset;
822                 vaddr += reloc->section_offset;
823         }
824
825         *out_start_val = start_val;
826         *out_end_val = end_val;
827         *out_data = data;
828         *out_vaddr = vaddr;
829 }
830
831 #ifdef USE_ELF_RELA
832
833 static ElfRelocA*
834 resolve_relocations (MonoImageWriter *acfg)
835 {
836         BinReloc *reloc;
837         guint8 *data;
838         gsize end_val, start_val;
839         ElfRelocA *rr;
840         int i;
841         gsize vaddr;
842
843         rr = g_new0 (ElfRelocA, acfg->num_relocs);
844         i = 0;
845
846         for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
847                 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
848                 /* FIXME: little endian */
849                 data [0] = end_val;
850                 data [1] = end_val >> 8;
851                 data [2] = end_val >> 16;
852                 data [3] = end_val >> 24;
853                 // FIXME:
854                 if (start_val == 0 && reloc->val1 [0] != '.') {
855                         rr [i].r_offset = vaddr;
856                         rr [i].r_info = R_X86_64_RELATIVE;
857                         rr [i].r_addend = end_val;
858                         ++i;
859                         g_assert (i <= acfg->num_relocs);
860                 }
861         }
862         return rr;
863 }
864
865 #else /* USE_ELF_RELA */
866
867 static void
868 do_reloc (MonoImageWriter *acfg, BinReloc *reloc, guint8 *data, gssize addr)
869 {
870 #ifdef __arm__
871         /*
872          * We use the official ARM relocation types, but implement only the stuff actually
873          * needed by the code we generate.
874          */
875         switch (reloc->reloc_type) {
876         case R_ARM_CALL:
877         case R_ARM_JUMP24: {
878                 guint32 *code = (guint32*)(gpointer)data;
879                 guint32 ins = *code;
880                 int diff = addr;
881
882                 if (reloc->reloc_type == R_ARM_CALL)
883                         /* bl */
884                         g_assert (data [3] == 0xeb);
885                 else
886                         /* b */
887                         g_assert (data [3] == 0xea);
888                 if (diff >= 0 && diff <= 33554431) {
889                         diff >>= 2;
890                         ins = (ins & 0xff000000) | diff;
891                         *code = ins;
892                 } else if (diff <= 0 && diff >= -33554432) {
893                         diff >>= 2;
894                         ins = (ins & 0xff000000) | (diff & ~0xff000000);
895                         *code = ins;
896                 } else {
897                         g_assert_not_reached ();
898                 }
899                 break;
900         }
901         case R_ARM_ALU_PC_G0_NC: {
902                 /* Generated by emit_plt () */
903                 guint8 *code = data;
904                 guint32 val = addr;
905
906                 g_assert (val <= 0xffffff);
907                 if (val & 0xff0000)
908                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, (val & 0xFF0000) >> 16, 16);
909                 else
910                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
911                 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, (val & 0xFF00) >> 8, 24);
912                 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, val & 0xFF);
913                 break;
914         }               
915         default:
916                 g_assert_not_reached ();
917         }
918 #else
919         g_assert_not_reached ();
920 #endif
921 }
922
923 static ElfReloc*
924 resolve_relocations (MonoImageWriter *acfg)
925 {
926         BinReloc *reloc;
927         guint8 *data;
928         gsize end_val, start_val;
929         ElfReloc *rr;
930         int i;
931         gsize vaddr;
932
933         rr = g_new0 (ElfReloc, acfg->num_relocs);
934         i = 0;
935
936         for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
937                 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
938                 /* FIXME: little endian */
939                 if (reloc->reloc_type) {
940                         /* Must be static */
941                         g_assert (start_val > 0);
942                         do_reloc (acfg, reloc, data, end_val);
943                 } else {
944                         data [0] = end_val;
945                         data [1] = end_val >> 8;
946                         data [2] = end_val >> 16;
947                         data [3] = end_val >> 24;
948                 }
949                 // FIXME:
950                 if (start_val == 0 && reloc->val1 [0] != '.') {
951                         rr [i].r_offset = vaddr;
952                         rr [i].r_info = R_386_RELATIVE;
953                         ++i;
954                         g_assert (i <= acfg->num_relocs);
955                 }
956         }
957         return rr;
958 }
959
960 #endif /* USE_ELF_RELA */
961
962 static int
963 bin_writer_emit_writeout (MonoImageWriter *acfg)
964 {
965         FILE *file;
966         ElfHeader header;
967         ElfProgHeader progh [3];
968         ElfSectHeader secth [SECT_NUM];
969 #ifdef USE_ELF_RELA
970         ElfRelocA *relocs;
971 #else
972         ElfReloc *relocs;
973 #endif
974         ElfStrTable str_table = {NULL, NULL};
975         ElfStrTable sh_str_table = {NULL, NULL};
976         ElfStrTable dyn_str_table = {NULL, NULL};
977         BinSection* all_sections [32];
978         BinSection* sections [SECT_NUM];
979         ElfSymbol *dynsym;
980         ElfSymbol *symtab;
981         ElfDynamic dynamic [14];
982         int *hash;
983         int i, num_sections, file_offset, virt_offset, size, num_symtab;
984         int num_local_syms;
985
986         file = acfg->fp;
987
988         /* Section headers */
989         memset (&secth, 0, sizeof (secth));
990         memset (&dynamic, 0, sizeof (dynamic));
991         memset (&header, 0, sizeof (header));
992
993         for (i = 1; i < SECT_NUM; ++i) {
994                 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
995                 secth [i].sh_type = section_info [i].type;
996                 secth [i].sh_addralign = section_info [i].align;
997                 secth [i].sh_flags = section_info [i].flags;
998                 secth [i].sh_entsize = section_info [i].esize;
999         }
1000         secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1001         secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1002         secth [SECT_HASH].sh_link = SECT_DYNSYM;
1003         secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1004         secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1005         secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1006         secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1007         secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1008
1009         num_sections = collect_sections (acfg, secth, all_sections, 16);
1010         hash = build_hash (acfg, num_sections, &dyn_str_table);
1011         num_symtab = hash [1]; /* FIXME */
1012 #if 0
1013         g_print ("num_sections: %d\n", num_sections);
1014         g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1015         for (i = 0; i < num_sections; ++i) {
1016                 g_print ("section %s, size: %d, %x\n", all_sections [i]->name, all_sections [i]->cur_offset, all_sections [i]->cur_offset);
1017         }
1018 #endif
1019         /* Associate the bin sections with the ELF sections */
1020         memset (sections, 0, sizeof (sections));
1021         for (i = 0; i < num_sections; ++i) {
1022                 BinSection *sect = all_sections [i];
1023                 int j;
1024
1025                 for (j = 0; j < SECT_NUM; ++j) {
1026                         if (strcmp (sect->name, section_info [j].name) == 0) {
1027                                 sect->shidx = j;
1028                                 break;
1029                         }
1030                 }
1031
1032                 sections [all_sections [i]->shidx] = sect;
1033         }
1034
1035         /* at this point we know where in the file the first segment sections go */
1036         dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1037         num_local_syms = hash [1];
1038         symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1039
1040         file_offset = virt_offset = sizeof (header) + sizeof (progh);
1041         secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1042         size = sizeof (int) * (2 + hash [0] + hash [1]);
1043         virt_offset = (file_offset += size);
1044         secth [SECT_HASH].sh_size = size;
1045         secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1046         size = sizeof (ElfSymbol) * hash [1];
1047         virt_offset = (file_offset += size);
1048         secth [SECT_DYNSYM].sh_size = size;
1049         secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1050         size = dyn_str_table.data->len;
1051         virt_offset = (file_offset += size);
1052         secth [SECT_DYNSTR].sh_size = size;
1053         file_offset += 4-1;
1054         file_offset &= ~(4-1);
1055         secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1056 #ifndef USE_ELF_RELA
1057         size = sizeof (ElfReloc) * acfg->num_relocs;
1058 #else
1059         size = 0;
1060 #endif
1061         virt_offset = (file_offset += size);
1062         secth [SECT_REL_DYN].sh_size = size;
1063         secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1064 #ifdef USE_ELF_RELA
1065         size = sizeof (ElfRelocA) * acfg->num_relocs;
1066 #else
1067         size = 0;
1068 #endif
1069         virt_offset = (file_offset += size);
1070         secth [SECT_RELA_DYN].sh_size = size;
1071
1072         file_offset = ALIGN_TO (file_offset, secth [SECT_TEXT].sh_addralign);
1073         virt_offset = file_offset;
1074         secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1075         if (sections [SECT_TEXT]) {
1076                 size = sections [SECT_TEXT]->cur_offset;
1077                 secth [SECT_TEXT].sh_size = size;
1078                 file_offset += size;
1079         }
1080
1081         file_offset = ALIGN_TO (file_offset, secth [SECT_DYNAMIC].sh_addralign);
1082         virt_offset = file_offset;
1083
1084         /* .dynamic, .got.plt, .data, .bss here */
1085         /* Have to increase the virt offset since these go to a separate segment */
1086         virt_offset += PAGESIZE;
1087         secth [SECT_DYNAMIC].sh_addr = virt_offset;
1088         secth [SECT_DYNAMIC].sh_offset = file_offset;
1089         size = sizeof (dynamic);
1090         secth [SECT_DYNAMIC].sh_size = size;
1091         file_offset += size;
1092         virt_offset += size;
1093
1094         file_offset = ALIGN_TO (file_offset, secth [SECT_GOT_PLT].sh_addralign);
1095         virt_offset = ALIGN_TO (virt_offset, secth [SECT_GOT_PLT].sh_addralign);
1096         secth [SECT_GOT_PLT].sh_addr = virt_offset;
1097         secth [SECT_GOT_PLT].sh_offset = file_offset;
1098         size = 12;
1099         secth [SECT_GOT_PLT].sh_size = size;
1100         file_offset += size;
1101         virt_offset += size;
1102
1103         file_offset = ALIGN_TO (file_offset, secth [SECT_DATA].sh_addralign);
1104         virt_offset = ALIGN_TO (virt_offset, secth [SECT_DATA].sh_addralign);
1105         secth [SECT_DATA].sh_addr = virt_offset;
1106         secth [SECT_DATA].sh_offset = file_offset;
1107         if (sections [SECT_DATA]) {
1108                 size = sections [SECT_DATA]->cur_offset;
1109                 secth [SECT_DATA].sh_size = size;
1110                 file_offset += size;
1111                 virt_offset += size;
1112         }
1113
1114         file_offset = ALIGN_TO (file_offset, secth [SECT_BSS].sh_addralign);
1115         virt_offset = ALIGN_TO (virt_offset, secth [SECT_BSS].sh_addralign);
1116         secth [SECT_BSS].sh_addr = virt_offset;
1117         secth [SECT_BSS].sh_offset = file_offset;
1118         if (sections [SECT_BSS]) {
1119                 size = sections [SECT_BSS]->cur_offset;
1120                 secth [SECT_BSS].sh_size = size;
1121         }
1122
1123         /* virtual doesn't matter anymore */
1124         file_offset = ALIGN_TO (file_offset, secth [SECT_DEBUG_FRAME].sh_addralign);
1125         secth [SECT_DEBUG_FRAME].sh_offset = file_offset;
1126         if (sections [SECT_DEBUG_FRAME])
1127                 size = sections [SECT_DEBUG_FRAME]->cur_offset;
1128         else
1129                 size = 0;
1130         secth [SECT_DEBUG_FRAME].sh_size = size;
1131         file_offset += size;
1132
1133         secth [SECT_DEBUG_INFO].sh_offset = file_offset;
1134         if (sections [SECT_DEBUG_INFO])
1135                 size = sections [SECT_DEBUG_INFO]->cur_offset;
1136         else
1137                 size = 0;
1138         secth [SECT_DEBUG_INFO].sh_size = size;
1139         file_offset += size;
1140
1141         secth [SECT_DEBUG_ABBREV].sh_offset = file_offset;
1142         if (sections [SECT_DEBUG_ABBREV])
1143                 size = sections [SECT_DEBUG_ABBREV]->cur_offset;
1144         else
1145                 size = 0;
1146         secth [SECT_DEBUG_ABBREV].sh_size = size;
1147         file_offset += size;
1148
1149         secth [SECT_DEBUG_LINE].sh_offset = file_offset;
1150         if (sections [SECT_DEBUG_LINE])
1151                 size = sections [SECT_DEBUG_LINE]->cur_offset;
1152         else
1153                 size = 0;
1154         secth [SECT_DEBUG_LINE].sh_size = size;
1155         file_offset += size;
1156
1157         secth [SECT_DEBUG_LOC].sh_offset = file_offset;
1158         if (sections [SECT_DEBUG_LOC])
1159                 size = sections [SECT_DEBUG_LOC]->cur_offset;
1160         else
1161                 size = 0;
1162         secth [SECT_DEBUG_LOC].sh_size = size;
1163         file_offset += size;
1164
1165         file_offset = ALIGN_TO (file_offset, secth [SECT_SHSTRTAB].sh_addralign);
1166         secth [SECT_SHSTRTAB].sh_offset = file_offset;
1167         size = sh_str_table.data->len;
1168         secth [SECT_SHSTRTAB].sh_size = size;
1169         file_offset += size;
1170
1171         file_offset = ALIGN_TO (file_offset, secth [SECT_SYMTAB].sh_addralign);
1172         secth [SECT_SYMTAB].sh_offset = file_offset;
1173         size = sizeof (ElfSymbol) * num_local_syms;
1174         secth [SECT_SYMTAB].sh_size = size;
1175         file_offset += size;
1176
1177         file_offset = ALIGN_TO (file_offset, secth [SECT_STRTAB].sh_addralign);
1178         secth [SECT_STRTAB].sh_offset = file_offset;
1179         size = str_table.data->len;
1180         secth [SECT_STRTAB].sh_size = size;
1181         file_offset += size;
1182
1183         file_offset += 4-1;
1184         file_offset &= ~(4-1);
1185
1186         header.e_ident [EI_MAG0] = ELFMAG0;
1187         header.e_ident [EI_MAG1] = ELFMAG1;
1188         header.e_ident [EI_MAG2] = ELFMAG2;
1189         header.e_ident [EI_MAG3] = ELFMAG3;
1190         header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1191         header.e_ident [EI_DATA] = ELFDATA2LSB;
1192         header.e_ident [EI_VERSION] = EV_CURRENT;
1193         header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1194         header.e_ident [EI_ABIVERSION] = 0;
1195         for (i = EI_PAD; i < EI_NIDENT; ++i)
1196                 header.e_ident [i] = 0;
1197
1198         header.e_type = ET_DYN;
1199 #if defined(__i386__)
1200         header.e_machine = EM_386;
1201 #elif defined(__x86_64__)
1202         header.e_machine = EM_X86_64;
1203 #elif defined(__arm__)
1204         header.e_machine = EM_ARM;
1205 #else
1206         g_assert_not_reached ();
1207 #endif
1208         header.e_version = 1;
1209
1210         header.e_phoff = sizeof (header);
1211         header.e_ehsize = sizeof (header);
1212         header.e_phentsize = sizeof (ElfProgHeader);
1213         header.e_phnum = 3;
1214         header.e_entry = secth [SECT_TEXT].sh_addr;
1215         header.e_shstrndx = SECT_SHSTRTAB;
1216         header.e_shentsize = sizeof (ElfSectHeader);
1217         header.e_shnum = SECT_NUM;
1218         header.e_shoff = file_offset;
1219
1220         /* dynamic data */
1221         i = 0;
1222         dynamic [i].d_tag = DT_HASH;
1223         dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1224         ++i;
1225         dynamic [i].d_tag = DT_STRTAB;
1226         dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1227         ++i;
1228         dynamic [i].d_tag = DT_SYMTAB;
1229         dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1230         ++i;
1231         dynamic [i].d_tag = DT_STRSZ;
1232         dynamic [i].d_un.d_val = dyn_str_table.data->len;
1233         ++i;
1234         dynamic [i].d_tag = DT_SYMENT;
1235         dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1236         ++i;
1237 #ifdef USE_ELF_RELA
1238         dynamic [i].d_tag = DT_RELA;
1239         dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1240         ++i;
1241         dynamic [i].d_tag = DT_RELASZ;
1242         dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1243         ++i;
1244         dynamic [i].d_tag = DT_RELAENT;
1245         dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1246         ++i;
1247 #else
1248         dynamic [i].d_tag = DT_REL;
1249         dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1250         ++i;
1251         dynamic [i].d_tag = DT_RELSZ;
1252         dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1253         ++i;
1254         dynamic [i].d_tag = DT_RELENT;
1255         dynamic [i].d_un.d_val = sizeof (ElfReloc);
1256         ++i;
1257 #endif
1258         dynamic [i].d_tag = DT_RELCOUNT;
1259         dynamic [i].d_un.d_val = acfg->num_relocs;
1260         ++i;
1261
1262         /* Program header */
1263         memset (&progh, 0, sizeof (progh));
1264         progh [0].p_type = PT_LOAD;
1265         progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1266         progh [0].p_align = 4096;
1267         progh [0].p_flags = 5;
1268
1269         progh [1].p_type = PT_LOAD;
1270         progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1271         progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1272         progh [1].p_filesz = secth [SECT_BSS].sh_offset  - secth [SECT_DYNAMIC].sh_offset;
1273         progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1274         progh [1].p_align = 4096;
1275         progh [1].p_flags = 6;
1276
1277         progh [2].p_type = PT_DYNAMIC;
1278         progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1279         progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1280         progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1281         progh [2].p_align = SIZEOF_VOID_P;
1282         progh [2].p_flags = 6;
1283
1284         /* Compute the addresses of the bin sections, so relocation can be done */
1285         for (i = 0; i < SECT_NUM; ++i) {
1286                 if (sections [i]) {
1287                         sections [i]->file_offset = secth [i].sh_offset;
1288                         sections [i]->virt_offset = secth [i].sh_addr;
1289                 }
1290         }
1291
1292         reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1293         reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1294         relocs = resolve_relocations (acfg);
1295
1296         fwrite (&header, sizeof (header), 1, file);
1297         fwrite (&progh, sizeof (progh), 1, file);
1298         fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1299         fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1300         fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1301         /* .rel.dyn */
1302         fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1303         fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1304
1305         /* .rela.dyn */
1306         fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1307         fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1308
1309         /* .text */
1310         if (sections [SECT_TEXT]) {
1311                 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1312                 fwrite (sections [SECT_TEXT]->data, sections [SECT_TEXT]->cur_offset, 1, file);
1313         }
1314         /* .dynamic */
1315         fwrite (dynamic, sizeof (dynamic), 1, file);
1316
1317         /* .got.plt */
1318         size = secth [SECT_DYNAMIC].sh_addr;
1319         fwrite (&size, sizeof (size), 1, file);
1320
1321         /* .data */
1322         if (sections [SECT_DATA]) {
1323                 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1324                 fwrite (sections [SECT_DATA]->data, sections [SECT_DATA]->cur_offset, 1, file);
1325         }
1326
1327         fseek (file, secth [SECT_DEBUG_FRAME].sh_offset, SEEK_SET);
1328         if (sections [SECT_DEBUG_FRAME])
1329                 fwrite (sections [SECT_DEBUG_FRAME]->data, sections [SECT_DEBUG_FRAME]->cur_offset, 1, file);
1330         fseek (file, secth [SECT_DEBUG_INFO].sh_offset, SEEK_SET);
1331         if (sections [SECT_DEBUG_INFO])
1332                 fwrite (sections [SECT_DEBUG_INFO]->data, sections [SECT_DEBUG_INFO]->cur_offset, 1, file);
1333         fseek (file, secth [SECT_DEBUG_ABBREV].sh_offset, SEEK_SET);
1334         if (sections [SECT_DEBUG_ABBREV])
1335                 fwrite (sections [SECT_DEBUG_ABBREV]->data, sections [SECT_DEBUG_ABBREV]->cur_offset, 1, file);
1336         fseek (file, secth [SECT_DEBUG_LINE].sh_offset, SEEK_SET);
1337         if (sections [SECT_DEBUG_LINE])
1338                 fwrite (sections [SECT_DEBUG_LINE]->data, sections [SECT_DEBUG_LINE]->cur_offset, 1, file);
1339         fseek (file, secth [SECT_DEBUG_LINE].sh_offset, SEEK_SET);
1340         if (sections [SECT_DEBUG_LOC])
1341                 fwrite (sections [SECT_DEBUG_LOC]->data, sections [SECT_DEBUG_LOC]->cur_offset, 1, file);
1342         fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1343         fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1344         fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1345         fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1346         fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1347         fwrite (str_table.data->str, str_table.data->len, 1, file);
1348         /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1349         /*g_assert (file_offset >= ftell (file));*/
1350         fseek (file, file_offset, SEEK_SET);
1351         fwrite (&secth, sizeof (secth), 1, file);
1352         fclose (file);
1353
1354         return 0;
1355 }
1356
1357 #endif /* USE_ELF_WRITER */
1358
1359 #endif /* USE_BIN_WRITER */
1360
1361 /* ASM WRITER */
1362
1363 static void
1364 asm_writer_emit_start (MonoImageWriter *acfg)
1365 {
1366 }
1367
1368 static int
1369 asm_writer_emit_writeout (MonoImageWriter *acfg)
1370 {
1371         fclose (acfg->fp);
1372
1373         return 0;
1374 }
1375
1376 static void
1377 asm_writer_emit_unset_mode (MonoImageWriter *acfg)
1378 {
1379         if (acfg->mode == EMIT_NONE)
1380                 return;
1381         fprintf (acfg->fp, "\n");
1382         acfg->mode = EMIT_NONE;
1383 }
1384
1385 static void
1386 asm_writer_emit_section_change (MonoImageWriter *acfg, const char *section_name, int subsection_index)
1387 {
1388         asm_writer_emit_unset_mode (acfg);
1389 #if defined(PLATFORM_WIN32)
1390         fprintf (acfg->fp, ".section %s\n", section_name);
1391 #elif defined(__MACH__)
1392         if (strcmp(section_name, ".bss") == 0)
1393                 fprintf (acfg->fp, "%s\n", ".data");
1394         else
1395                 fprintf (acfg->fp, "%s\n", section_name);
1396 #elif defined(sparc)
1397         /* For solaris as, GNU as should accept the same */
1398         fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1399 #elif defined(__arm__)
1400         /* ARM gas doesn't seem to like subsections of .bss */
1401         if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data")) {
1402                 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1403         } else {
1404                 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1405                 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1406         }
1407 #else
1408         if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data") || !strcmp (section_name, ".bss")) {
1409                 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1410         } else {
1411                 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1412                 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1413         }
1414 #endif
1415 }
1416
1417 static void
1418 asm_writer_emit_symbol_type (MonoImageWriter *acfg, const char *name, gboolean func)
1419 {
1420         const char *stype;
1421
1422         if (func)
1423                 stype = "function";
1424         else
1425                 stype = "object";
1426
1427         asm_writer_emit_unset_mode (acfg);
1428 #if defined(__MACH__)
1429
1430 #elif defined(sparc) || defined(__arm__)
1431         fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1432 #elif defined(PLATFORM_WIN32)
1433
1434 #elif defined(__x86_64__) || defined(__i386__)
1435         fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1436 #else
1437         fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1438 #endif
1439 }
1440
1441 static void
1442 asm_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
1443 {
1444         asm_writer_emit_unset_mode (acfg);
1445 #if  (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1446     // mach-o always uses a '_' prefix.
1447         fprintf (acfg->fp, "\t.globl _%s\n", name);
1448 #else
1449         fprintf (acfg->fp, "\t.globl %s\n", name);
1450 #endif
1451
1452         asm_writer_emit_symbol_type (acfg, name, func);
1453 }
1454
1455 static void
1456 asm_writer_emit_local_symbol (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean func)
1457 {
1458         asm_writer_emit_unset_mode (acfg);
1459
1460         fprintf (acfg->fp, "\t.local %s\n", name);
1461
1462         asm_writer_emit_symbol_type (acfg, name, func);
1463 }
1464
1465 static void
1466 asm_writer_emit_label (MonoImageWriter *acfg, const char *name)
1467 {
1468         asm_writer_emit_unset_mode (acfg);
1469 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1470     // mach-o always uses a '_' prefix.
1471         fprintf (acfg->fp, "_%s:\n", name);
1472 #else
1473         fprintf (acfg->fp, "%s:\n", name);
1474 #endif
1475
1476 #if defined(PLATFORM_WIN32)
1477         /* Emit a normal label too */
1478         fprintf (acfg->fp, "%s:\n", name);
1479 #endif
1480 }
1481
1482 static void
1483 asm_writer_emit_string (MonoImageWriter *acfg, const char *value)
1484 {
1485         asm_writer_emit_unset_mode (acfg);
1486         fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1487 }
1488
1489 static void
1490 asm_writer_emit_line (MonoImageWriter *acfg)
1491 {
1492         asm_writer_emit_unset_mode (acfg);
1493         fprintf (acfg->fp, "\n");
1494 }
1495
1496 static void 
1497 asm_writer_emit_alignment (MonoImageWriter *acfg, int size)
1498 {
1499         asm_writer_emit_unset_mode (acfg);
1500 #if defined(__arm__)
1501         fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1502 #elif defined(__ppc__) && defined(__MACH__)
1503         // the mach-o assembler specifies alignments as powers of 2.
1504         fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1505 #elif defined(__powerpc__)
1506         /* ignore on linux/ppc */
1507 #else
1508         fprintf (acfg->fp, "\t.align %d\n", size);
1509 #endif
1510 }
1511
1512 static void
1513 asm_writer_emit_pointer_unaligned (MonoImageWriter *acfg, const char *target)
1514 {
1515         asm_writer_emit_unset_mode (acfg);
1516 #if defined(__x86_64__)
1517         fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1518 #elif defined(sparc) && SIZEOF_VOID_P == 8
1519         fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1520 #else
1521         fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1522 #endif
1523 }
1524
1525 static void
1526 asm_writer_emit_pointer (MonoImageWriter *acfg, const char *target)
1527 {
1528         asm_writer_emit_unset_mode (acfg);
1529         asm_writer_emit_alignment (acfg, sizeof (gpointer));
1530         asm_writer_emit_pointer_unaligned (acfg, target);
1531 }
1532
1533 static char *byte_to_str;
1534
1535 static void
1536 asm_writer_emit_bytes (MonoImageWriter *acfg, const guint8* buf, int size)
1537 {
1538         int i;
1539         if (acfg->mode != EMIT_BYTE) {
1540                 acfg->mode = EMIT_BYTE;
1541                 acfg->col_count = 0;
1542         }
1543
1544         if (byte_to_str == NULL) {
1545                 byte_to_str = g_new0 (char, 256 * 8);
1546                 for (i = 0; i < 256; ++i) {
1547                         sprintf (byte_to_str + (i * 8), ",%d", i);
1548                 }
1549         }
1550
1551         for (i = 0; i < size; ++i, ++acfg->col_count) {
1552                 if ((acfg->col_count % 32) == 0)
1553                         fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1554                 else
1555                         fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1556         }
1557 }
1558
1559 static inline void
1560 asm_writer_emit_int16 (MonoImageWriter *acfg, int value)
1561 {
1562         if (acfg->mode != EMIT_WORD) {
1563                 acfg->mode = EMIT_WORD;
1564                 acfg->col_count = 0;
1565         }
1566         if ((acfg->col_count++ % 8) == 0)
1567 #if defined(__MACH__)
1568                 fprintf (acfg->fp, "\n\t.short ");
1569 #elif defined(__arm__)
1570                 /* FIXME: Use .hword on other archs as well */
1571                 fprintf (acfg->fp, "\n\t.hword ");
1572 #else
1573                 fprintf (acfg->fp, "\n\t.word ");
1574 #endif
1575         else
1576                 fprintf (acfg->fp, ", ");
1577         fprintf (acfg->fp, "%d", value);
1578 }
1579
1580 static inline void
1581 asm_writer_emit_int32 (MonoImageWriter *acfg, int value)
1582 {
1583         if (acfg->mode != EMIT_LONG) {
1584                 acfg->mode = EMIT_LONG;
1585                 acfg->col_count = 0;
1586         }
1587         if ((acfg->col_count++ % 8) == 0)
1588                 fprintf (acfg->fp, "\n\t.long ");
1589         else
1590                 fprintf (acfg->fp, ",");
1591         fprintf (acfg->fp, "%d", value);
1592 }
1593
1594 static void
1595 asm_writer_emit_symbol_diff (MonoImageWriter *acfg, const char *end, const char* start, int offset)
1596 {
1597         if (acfg->mode != EMIT_LONG) {
1598                 acfg->mode = EMIT_LONG;
1599                 acfg->col_count = 0;
1600         }
1601         if ((acfg->col_count++ % 8) == 0)
1602                 fprintf (acfg->fp, "\n\t.long ");
1603         else
1604                 fprintf (acfg->fp, ",");
1605         if (offset > 0)
1606                 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1607         else if (offset < 0)
1608                 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1609         else
1610                 fprintf (acfg->fp, "%s - %s", end, start);
1611 }
1612
1613 static void
1614 asm_writer_emit_zero_bytes (MonoImageWriter *acfg, int num)
1615 {
1616         asm_writer_emit_unset_mode (acfg);
1617 #if defined(__MACH__)
1618         fprintf (acfg->fp, "\t.space %d\n", num);
1619 #else
1620         fprintf (acfg->fp, "\t.skip %d\n", num);
1621 #endif
1622 }
1623
1624 /* EMIT FUNCTIONS */
1625
1626 void
1627 img_writer_emit_start (MonoImageWriter *acfg)
1628 {
1629 #ifdef USE_BIN_WRITER
1630         if (acfg->use_bin_writer)
1631                 bin_writer_emit_start (acfg);
1632         else
1633                 asm_writer_emit_start (acfg);
1634 #else
1635         asm_writer_emit_start (acfg);
1636 #endif
1637 }
1638
1639 void
1640 img_writer_emit_section_change (MonoImageWriter *acfg, const char *section_name, int subsection_index)
1641 {
1642 #ifdef USE_BIN_WRITER
1643         if (acfg->use_bin_writer)
1644                 bin_writer_emit_section_change (acfg, section_name, subsection_index);
1645         else
1646                 asm_writer_emit_section_change (acfg, section_name, subsection_index);
1647 #else
1648         asm_writer_emit_section_change (acfg, section_name, subsection_index);
1649 #endif
1650
1651         acfg->current_section = section_name;
1652         acfg->current_subsection = subsection_index;
1653 }
1654
1655 void
1656 img_writer_emit_push_section (MonoImageWriter *acfg, const char *section_name, int subsection)
1657 {
1658         g_assert (acfg->stack_pos < 16 - 1);
1659         acfg->section_stack [acfg->stack_pos] = acfg->current_section;
1660         acfg->subsection_stack [acfg->stack_pos] = acfg->current_subsection;
1661         acfg->stack_pos ++;
1662
1663         img_writer_emit_section_change (acfg, section_name, subsection);
1664 }
1665
1666 void
1667 img_writer_emit_pop_section (MonoImageWriter *acfg)
1668 {
1669         g_assert (acfg->stack_pos > 0);
1670         acfg->stack_pos --;
1671         img_writer_emit_section_change (acfg, acfg->section_stack [acfg->stack_pos], acfg->subsection_stack [acfg->stack_pos]);
1672 }
1673
1674 void
1675 img_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
1676 {
1677 #ifdef USE_BIN_WRITER
1678         if (acfg->use_bin_writer)
1679                 bin_writer_emit_global (acfg, name, func);
1680         else
1681                 asm_writer_emit_global (acfg, name, func);
1682 #else
1683         asm_writer_emit_global (acfg, name, func);
1684 #endif
1685 }
1686
1687 void
1688 img_writer_emit_local_symbol (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean func)
1689 {
1690 #ifdef USE_BIN_WRITER
1691         if (acfg->use_bin_writer)
1692                 bin_writer_emit_local_symbol (acfg, name, end_label, func);
1693         else
1694                 asm_writer_emit_local_symbol (acfg, name, end_label, func);
1695 #else
1696         asm_writer_emit_local_symbol (acfg, name, end_label, func);
1697 #endif
1698 }
1699
1700 void
1701 img_writer_emit_label (MonoImageWriter *acfg, const char *name)
1702 {
1703 #ifdef USE_BIN_WRITER
1704         if (acfg->use_bin_writer)
1705                 bin_writer_emit_label (acfg, name);
1706         else
1707                 asm_writer_emit_label (acfg, name);
1708 #else
1709         asm_writer_emit_label (acfg, name);
1710 #endif
1711 }
1712
1713 void
1714 img_writer_emit_bytes (MonoImageWriter *acfg, const guint8* buf, int size)
1715 {
1716 #ifdef USE_BIN_WRITER
1717         if (acfg->use_bin_writer)
1718                 bin_writer_emit_bytes (acfg, buf, size);
1719         else
1720                 asm_writer_emit_bytes (acfg, buf, size);
1721 #else
1722         asm_writer_emit_bytes (acfg, buf, size);
1723 #endif
1724 }
1725
1726 void
1727 img_writer_emit_string (MonoImageWriter *acfg, const char *value)
1728 {
1729 #ifdef USE_BIN_WRITER
1730         if (acfg->use_bin_writer)
1731                 bin_writer_emit_string (acfg, value);
1732         else
1733                 asm_writer_emit_string (acfg, value);
1734 #else
1735         asm_writer_emit_string (acfg, value);
1736 #endif
1737 }
1738
1739 void
1740 img_writer_emit_line (MonoImageWriter *acfg)
1741 {
1742 #ifdef USE_BIN_WRITER
1743         if (acfg->use_bin_writer)
1744                 bin_writer_emit_line (acfg);
1745         else
1746                 asm_writer_emit_line (acfg);
1747 #else
1748                 asm_writer_emit_line (acfg);
1749 #endif
1750 }
1751
1752 void
1753 img_writer_emit_alignment (MonoImageWriter *acfg, int size)
1754 {
1755 #ifdef USE_BIN_WRITER
1756         if (acfg->use_bin_writer)
1757                 bin_writer_emit_alignment (acfg, size);
1758         else
1759                 asm_writer_emit_alignment (acfg, size);
1760 #else
1761         asm_writer_emit_alignment (acfg, size);
1762 #endif
1763 }
1764
1765 void
1766 img_writer_emit_pointer_unaligned (MonoImageWriter *acfg, const char *target)
1767 {
1768 #ifdef USE_BIN_WRITER
1769         if (acfg->use_bin_writer)
1770                 bin_writer_emit_pointer_unaligned (acfg, target);
1771         else
1772                 asm_writer_emit_pointer_unaligned (acfg, target);
1773 #else
1774         asm_writer_emit_pointer_unaligned (acfg, target);
1775 #endif
1776 }
1777
1778 void
1779 img_writer_emit_pointer (MonoImageWriter *acfg, const char *target)
1780 {
1781 #ifdef USE_BIN_WRITER
1782         if (acfg->use_bin_writer)
1783                 bin_writer_emit_pointer (acfg, target);
1784         else
1785                 asm_writer_emit_pointer (acfg, target);
1786 #else
1787         asm_writer_emit_pointer (acfg, target);
1788 #endif
1789 }
1790
1791 void
1792 img_writer_emit_int16 (MonoImageWriter *acfg, int value)
1793 {
1794 #ifdef USE_BIN_WRITER
1795         if (acfg->use_bin_writer)
1796                 bin_writer_emit_int16 (acfg, value);
1797         else
1798                 asm_writer_emit_int16 (acfg, value);
1799 #else
1800         asm_writer_emit_int16 (acfg, value);
1801 #endif
1802 }
1803
1804 void
1805 img_writer_emit_int32 (MonoImageWriter *acfg, int value)
1806 {
1807 #ifdef USE_BIN_WRITER
1808         if (acfg->use_bin_writer)
1809                 bin_writer_emit_int32 (acfg, value);
1810         else
1811                 asm_writer_emit_int32 (acfg, value);
1812 #else
1813         asm_writer_emit_int32 (acfg, value);
1814 #endif
1815 }
1816
1817 void
1818 img_writer_emit_symbol_diff (MonoImageWriter *acfg, const char *end, const char* start, int offset)
1819 {
1820 #ifdef USE_BIN_WRITER
1821         if (acfg->use_bin_writer)
1822                 bin_writer_emit_symbol_diff (acfg, end, start, offset);
1823         else
1824                 asm_writer_emit_symbol_diff (acfg, end, start, offset);
1825 #else
1826         asm_writer_emit_symbol_diff (acfg, end, start, offset);
1827 #endif
1828 }
1829
1830 void
1831 img_writer_emit_zero_bytes (MonoImageWriter *acfg, int num)
1832 {
1833 #ifdef USE_BIN_WRITER
1834         if (acfg->use_bin_writer)
1835                 bin_writer_emit_zero_bytes (acfg, num);
1836         else
1837                 asm_writer_emit_zero_bytes (acfg, num);
1838 #else
1839         asm_writer_emit_zero_bytes (acfg, num);
1840 #endif
1841 }
1842
1843 int
1844 img_writer_emit_writeout (MonoImageWriter *acfg)
1845 {
1846 #ifdef USE_BIN_WRITER
1847         if (acfg->use_bin_writer)
1848                 return bin_writer_emit_writeout (acfg);
1849         else
1850                 return asm_writer_emit_writeout (acfg);
1851 #else
1852                 return asm_writer_emit_writeout (acfg);
1853 #endif
1854 }
1855
1856 void
1857 img_writer_emit_byte (MonoImageWriter *acfg, guint8 val)
1858 {
1859         img_writer_emit_bytes (acfg, &val, 1);
1860 }
1861
1862 /* 
1863  * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
1864  * Do not advance PC.
1865  */
1866 void
1867 img_writer_emit_reloc (MonoImageWriter *acfg, int reloc_type, const char *symbol, int addend)
1868 {
1869         /* This is only supported by the bin writer */
1870 #ifdef USE_BIN_WRITER
1871         if (acfg->use_bin_writer)
1872                 bin_writer_emit_reloc (acfg, reloc_type, symbol, addend);
1873         else
1874                 g_assert_not_reached ();
1875 #else
1876                 g_assert_not_reached ();
1877 #endif
1878 }
1879
1880 /*
1881  * img_writer_emit_unset_mode:
1882  *
1883  *   Flush buffered data so it is safe to write to the output file from outside this
1884  * module. This is a nop for the binary writer.
1885  */
1886 void
1887 img_writer_emit_unset_mode (MonoImageWriter *acfg)
1888 {
1889         if (!acfg->use_bin_writer)
1890                 asm_writer_emit_unset_mode (acfg);
1891 }
1892
1893 /*
1894  * Return whenever the binary writer is supported on this platform.
1895  */
1896 gboolean
1897 bin_writer_supported (void)
1898 {
1899 #ifdef USE_BIN_WRITER
1900         return TRUE;
1901 #else
1902         return FALSE;
1903 #endif
1904 }
1905
1906 MonoImageWriter*
1907 img_writer_create (FILE *fp, gboolean use_bin_writer)
1908 {
1909         MonoImageWriter *w = g_new0 (MonoImageWriter, 1);
1910         
1911 #ifndef USE_BIN_WRITER
1912         g_assert (!use_bin_writer);
1913 #endif
1914
1915         w->fp = fp;
1916         w->use_bin_writer = use_bin_writer;
1917         w->mempool = mono_mempool_new ();
1918
1919         return w;
1920 }
1921
1922 void
1923 img_writer_destroy (MonoImageWriter *w)
1924 {
1925         // FIXME: Free all the stuff
1926         mono_mempool_destroy (w->mempool);
1927         g_free (w);
1928 }