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