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