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