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