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