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