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