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