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