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