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