Merge pull request #2794 from xmcclure/win-aot-basic
[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 #if defined(TARGET_ASM_APPLE)
1690         fprintf (acfg->fp, ".subsections_via_symbols\n");
1691 #endif
1692 }
1693
1694 static int
1695 asm_writer_emit_writeout (MonoImageWriter *acfg)
1696 {
1697         fclose (acfg->fp);
1698
1699         return 0;
1700 }
1701
1702 static void
1703 asm_writer_emit_unset_mode (MonoImageWriter *acfg)
1704 {
1705         if (acfg->mode == EMIT_NONE)
1706                 return;
1707         fprintf (acfg->fp, "\n");
1708         acfg->mode = EMIT_NONE;
1709 }
1710
1711 static void
1712 asm_writer_emit_section_change (MonoImageWriter *acfg, const char *section_name, int subsection_index)
1713 {
1714         asm_writer_emit_unset_mode (acfg);
1715 #if defined(TARGET_ASM_APPLE)
1716         if (strcmp(section_name, ".bss") == 0)
1717                 fprintf (acfg->fp, "%s\n", ".data");
1718         else if (strstr (section_name, ".debug") == section_name) {
1719                 //g_assert (subsection_index == 0);
1720                 fprintf (acfg->fp, ".section __DWARF, __%s,regular,debug\n", section_name + 1);
1721         } else
1722                 fprintf (acfg->fp, "%s\n", section_name);
1723 #elif defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_POWERPC)
1724         /* ARM gas doesn't seem to like subsections of .bss */
1725         if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data")) {
1726                 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1727         } else {
1728                 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1729                 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1730         }
1731 #elif defined(HOST_WIN32)
1732         fprintf (acfg->fp, ".section %s\n", section_name);
1733 #else
1734         if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data") || !strcmp (section_name, ".bss")) {
1735                 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1736         } else {
1737                 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1738                 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1739         }
1740 #endif
1741 }
1742
1743 static inline
1744 const char *get_label (const char *s)
1745 {
1746 #ifdef TARGET_ASM_APPLE
1747         if (s [0] == '.' && s [1] == 'L')
1748                 /* apple uses "L" instead of ".L" to mark temporary labels */
1749                 s ++;
1750 #endif
1751         return s;
1752 }
1753
1754 static void
1755 asm_writer_emit_symbol_type (MonoImageWriter *acfg, const char *name, gboolean func)
1756 {
1757         const char *stype;
1758
1759         if (func)
1760                 stype = "function";
1761         else
1762                 stype = "object";
1763
1764         asm_writer_emit_unset_mode (acfg);
1765
1766 #if defined(TARGET_ASM_APPLE)
1767
1768 #elif defined(TARGET_WIN32)
1769         if (func)
1770                 fprintf (acfg->fp, "\t.def %s; .scl 2; .type 32; .endef\n", name);
1771         else
1772                 fprintf (acfg->fp, "\t.data\n");
1773 #elif defined(TARGET_ARM)
1774         fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1775 #else
1776         fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1777 #endif
1778 }
1779
1780 static void
1781 asm_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
1782 {
1783         asm_writer_emit_unset_mode (acfg);
1784
1785         fprintf (acfg->fp, "\t.globl %s\n", name);
1786
1787         asm_writer_emit_symbol_type (acfg, name, func);
1788 }
1789
1790 static void
1791 asm_writer_emit_local_symbol (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean func)
1792 {
1793         asm_writer_emit_unset_mode (acfg);
1794
1795 #if !defined(TARGET_ASM_APPLE) && !defined(TARGET_WIN32)
1796         fprintf (acfg->fp, "\t.local %s\n", name);
1797 #endif
1798
1799         asm_writer_emit_symbol_type (acfg, name, func);
1800 }
1801
1802 static void
1803 asm_writer_emit_symbol_size (MonoImageWriter *acfg, const char *name, const char *end_label)
1804 {
1805         asm_writer_emit_unset_mode (acfg);
1806
1807
1808 #if !defined(TARGET_ASM_APPLE) && !defined(TARGET_WIN32)
1809         fprintf (acfg->fp, "\t.size %s,%s-%s\n", name, end_label, name);
1810 #endif
1811 }
1812
1813 static void
1814 asm_writer_emit_label (MonoImageWriter *acfg, const char *name)
1815 {
1816         asm_writer_emit_unset_mode (acfg);
1817         fprintf (acfg->fp, "%s:\n", get_label (name));
1818 }
1819
1820 static void
1821 asm_writer_emit_string (MonoImageWriter *acfg, const char *value)
1822 {
1823         asm_writer_emit_unset_mode (acfg);
1824         fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1825 }
1826
1827 static void
1828 asm_writer_emit_line (MonoImageWriter *acfg)
1829 {
1830         asm_writer_emit_unset_mode (acfg);
1831         fprintf (acfg->fp, "\n");
1832 }
1833
1834 static void 
1835 asm_writer_emit_alignment (MonoImageWriter *acfg, int size)
1836 {
1837         asm_writer_emit_unset_mode (acfg);
1838 #if defined(TARGET_ARM)
1839         fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1840 #elif defined(__ppc__) && defined(TARGET_ASM_APPLE)
1841         // the mach-o assembler specifies alignments as powers of 2.
1842         fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1843 #elif defined(TARGET_ASM_GAS)
1844         fprintf (acfg->fp, "\t.balign %d\n", size);
1845 #elif defined(TARGET_ASM_APPLE)
1846         fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1847 #else
1848         fprintf (acfg->fp, "\t.align %d\n", size);
1849 #endif
1850 }
1851
1852 #ifndef USE_BIN_WRITER
1853 static void 
1854 asm_writer_emit_alignment_fill (MonoImageWriter *acfg, int size, int fill)
1855 {
1856         asm_writer_emit_unset_mode (acfg);
1857 #if defined(TARGET_ASM_APPLE)
1858         fprintf (acfg->fp, "\t.align %d, 0x%0x\n", ilog2 (size), fill);
1859 #else
1860         asm_writer_emit_alignment (acfg, size);
1861 #endif
1862 }
1863 #endif
1864
1865 #ifdef __native_client_codegen__
1866 static void
1867 asm_writer_emit_nacl_call_alignment (MonoImageWriter *acfg) {
1868   int padding = kNaClAlignment - kNaClLengthOfCallImm;
1869   guint8 padc = '\x90';
1870
1871   fprintf (acfg->fp, "\n\t.align %d", kNaClAlignment);
1872   while (padding > 0) {
1873     fprintf (acfg->fp, "\n\t.byte %d", padc);
1874     padding -= 1;
1875   }
1876 }
1877 #endif  /* __native_client_codegen__ */
1878
1879 static void
1880 asm_writer_emit_pointer_unaligned (MonoImageWriter *acfg, const char *target)
1881 {
1882         asm_writer_emit_unset_mode (acfg);
1883         fprintf (acfg->fp, "\t%s %s\n", AS_POINTER_DIRECTIVE, target ? target : "0");
1884 }
1885
1886 static void
1887 asm_writer_emit_pointer (MonoImageWriter *acfg, const char *target)
1888 {
1889         asm_writer_emit_unset_mode (acfg);
1890         asm_writer_emit_alignment (acfg, sizeof (gpointer));
1891         asm_writer_emit_pointer_unaligned (acfg, target);
1892 }
1893
1894 static char *byte_to_str;
1895
1896 static void
1897 asm_writer_emit_bytes (MonoImageWriter *acfg, const guint8* buf, int size)
1898 {
1899         int i;
1900         if (acfg->mode != EMIT_BYTE) {
1901                 acfg->mode = EMIT_BYTE;
1902                 acfg->col_count = 0;
1903         }
1904
1905         if (byte_to_str == NULL) {
1906                 byte_to_str = g_new0 (char, 256 * 8);
1907                 for (i = 0; i < 256; ++i) {
1908                         sprintf (byte_to_str + (i * 8), ",%d", i);
1909                 }
1910         }
1911
1912         for (i = 0; i < size; ++i, ++acfg->col_count) {
1913                 if ((acfg->col_count % 32) == 0)
1914                         fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1915                 else
1916                         fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1917         }
1918 }
1919
1920 static inline void
1921 asm_writer_emit_int16 (MonoImageWriter *acfg, int value)
1922 {
1923         if (acfg->mode != EMIT_WORD) {
1924                 acfg->mode = EMIT_WORD;
1925                 acfg->col_count = 0;
1926         }
1927         if ((acfg->col_count++ % 8) == 0)
1928                 fprintf (acfg->fp, "\n\t%s ", AS_INT16_DIRECTIVE);
1929         else
1930                 fprintf (acfg->fp, ", ");
1931         fprintf (acfg->fp, "%d", value);
1932 }
1933
1934 static inline void
1935 asm_writer_emit_int32 (MonoImageWriter *acfg, int value)
1936 {
1937         if (acfg->mode != EMIT_LONG) {
1938                 acfg->mode = EMIT_LONG;
1939                 acfg->col_count = 0;
1940         }
1941         if ((acfg->col_count++ % 8) == 0)
1942                 fprintf (acfg->fp, "\n\t%s ", AS_INT32_DIRECTIVE);
1943         else
1944                 fprintf (acfg->fp, ",");
1945         fprintf (acfg->fp, "%d", value);
1946 }
1947
1948 static void
1949 asm_writer_emit_symbol_diff (MonoImageWriter *acfg, const char *end, const char* start, int offset)
1950 {
1951 #ifdef TARGET_ASM_APPLE
1952         //char symbol [128];
1953 #endif
1954
1955         if (acfg->mode != EMIT_LONG) {
1956                 acfg->mode = EMIT_LONG;
1957                 acfg->col_count = 0;
1958         }
1959
1960         // FIXME: This doesn't seem to work on the iphone
1961 #if 0
1962         //#ifdef TARGET_ASM_APPLE
1963         /* The apple assembler needs a separate symbol to be able to handle complex expressions */
1964         sprintf (symbol, "LTMP_SYM%d", acfg->label_gen);
1965         start = get_label (start);
1966         end = get_label (end);
1967         acfg->label_gen ++;
1968         if (offset > 0)
1969                 fprintf (acfg->fp, "\n%s=%s - %s + %d", symbol, end, start, offset);
1970         else if (offset < 0)
1971                 fprintf (acfg->fp, "\n%s=%s - %s %d", symbol, end, start, offset);
1972         else
1973                 fprintf (acfg->fp, "\n%s=%s - %s", symbol, end, start);
1974
1975         fprintf (acfg->fp, "\n\t%s ", AS_INT32_DIRECTIVE);
1976         fprintf (acfg->fp, "%s", symbol);
1977 #else
1978         start = get_label (start);
1979         end = get_label (end);
1980
1981         if (offset == 0 && strcmp (start, ".") != 0) {
1982                 char symbol [128];
1983                 sprintf (symbol, "%sDIFF_SYM%d", AS_TEMP_LABEL_PREFIX, acfg->label_gen);
1984                 acfg->label_gen ++;
1985                 fprintf (acfg->fp, "\n%s=%s - %s", symbol, end, start);
1986                 fprintf (acfg->fp, "\n\t%s ", AS_INT32_DIRECTIVE);
1987                 fprintf (acfg->fp, "%s", symbol);
1988                 return;
1989         }
1990
1991         if ((acfg->col_count++ % 8) == 0)
1992                 fprintf (acfg->fp, "\n\t%s ", AS_INT32_DIRECTIVE);
1993         else
1994                 fprintf (acfg->fp, ",");
1995         if (offset > 0)
1996                 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1997         else if (offset < 0)
1998                 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1999         else
2000                 fprintf (acfg->fp, "%s - %s", end, start);
2001 #endif
2002 }
2003
2004 static void
2005 asm_writer_emit_zero_bytes (MonoImageWriter *acfg, int num)
2006 {
2007         asm_writer_emit_unset_mode (acfg);
2008         fprintf (acfg->fp, "\t%s %d\n", AS_SKIP_DIRECTIVE, num);
2009 }
2010
2011 /* EMIT FUNCTIONS */
2012
2013 void
2014 mono_img_writer_emit_start (MonoImageWriter *acfg)
2015 {
2016 #ifdef USE_BIN_WRITER
2017         if (acfg->use_bin_writer)
2018                 bin_writer_emit_start (acfg);
2019         else
2020                 asm_writer_emit_start (acfg);
2021 #else
2022         asm_writer_emit_start (acfg);
2023 #endif
2024 }
2025
2026 void
2027 mono_img_writer_emit_section_change (MonoImageWriter *acfg, const char *section_name, int subsection_index)
2028 {
2029 #ifdef USE_BIN_WRITER
2030         if (acfg->use_bin_writer)
2031                 bin_writer_emit_section_change (acfg, section_name, subsection_index);
2032         else
2033                 asm_writer_emit_section_change (acfg, section_name, subsection_index);
2034 #else
2035         asm_writer_emit_section_change (acfg, section_name, subsection_index);
2036 #endif
2037
2038         acfg->current_section = section_name;
2039         acfg->current_subsection = subsection_index;
2040 }
2041
2042 void
2043 mono_img_writer_emit_push_section (MonoImageWriter *acfg, const char *section_name, int subsection)
2044 {
2045         g_assert (acfg->stack_pos < 16 - 1);
2046         acfg->section_stack [acfg->stack_pos] = acfg->current_section;
2047         acfg->subsection_stack [acfg->stack_pos] = acfg->current_subsection;
2048         acfg->stack_pos ++;
2049
2050         mono_img_writer_emit_section_change (acfg, section_name, subsection);
2051 }
2052
2053 void
2054 mono_img_writer_emit_pop_section (MonoImageWriter *acfg)
2055 {
2056         g_assert (acfg->stack_pos > 0);
2057         acfg->stack_pos --;
2058         mono_img_writer_emit_section_change (acfg, acfg->section_stack [acfg->stack_pos], acfg->subsection_stack [acfg->stack_pos]);
2059 }
2060
2061 void
2062 mono_img_writer_set_section_addr (MonoImageWriter *acfg, guint64 addr)
2063 {
2064 #ifdef USE_BIN_WRITER
2065         if (!acfg->use_bin_writer)
2066                 NOT_IMPLEMENTED;
2067         else
2068                 bin_writer_set_section_addr (acfg, addr);
2069 #else
2070         NOT_IMPLEMENTED;
2071 #endif
2072 }
2073
2074 void
2075 mono_img_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
2076 {
2077 #ifdef USE_BIN_WRITER
2078         if (acfg->use_bin_writer)
2079                 bin_writer_emit_global (acfg, name, func);
2080         else
2081                 asm_writer_emit_global (acfg, name, func);
2082 #else
2083         asm_writer_emit_global (acfg, name, func);
2084 #endif
2085 }
2086
2087 void
2088 mono_img_writer_emit_local_symbol (MonoImageWriter *acfg, const char *name, const char *end_label, gboolean func)
2089 {
2090 #ifdef USE_BIN_WRITER
2091         if (acfg->use_bin_writer)
2092                 bin_writer_emit_local_symbol (acfg, name, end_label, func);
2093         else
2094                 asm_writer_emit_local_symbol (acfg, name, end_label, func);
2095 #else
2096         asm_writer_emit_local_symbol (acfg, name, end_label, func);
2097 #endif
2098 }
2099
2100 void
2101 mono_img_writer_emit_symbol_size (MonoImageWriter *acfg, const char *name, const char *end_label)
2102 {
2103         if (!acfg->use_bin_writer)
2104                 asm_writer_emit_symbol_size (acfg, name, end_label);
2105 }
2106
2107 void
2108 mono_img_writer_emit_label (MonoImageWriter *acfg, const char *name)
2109 {
2110 #ifdef USE_BIN_WRITER
2111         if (acfg->use_bin_writer)
2112                 bin_writer_emit_label (acfg, name);
2113         else
2114                 asm_writer_emit_label (acfg, name);
2115 #else
2116         asm_writer_emit_label (acfg, name);
2117 #endif
2118 }
2119
2120 void
2121 mono_img_writer_emit_bytes (MonoImageWriter *acfg, const guint8* buf, int size)
2122 {
2123 #ifdef USE_BIN_WRITER
2124         if (acfg->use_bin_writer)
2125                 bin_writer_emit_bytes (acfg, buf, size);
2126         else
2127                 asm_writer_emit_bytes (acfg, buf, size);
2128 #else
2129         asm_writer_emit_bytes (acfg, buf, size);
2130 #endif
2131 }
2132
2133 void
2134 mono_img_writer_emit_string (MonoImageWriter *acfg, const char *value)
2135 {
2136 #ifdef USE_BIN_WRITER
2137         if (acfg->use_bin_writer)
2138                 bin_writer_emit_string (acfg, value);
2139         else
2140                 asm_writer_emit_string (acfg, value);
2141 #else
2142         asm_writer_emit_string (acfg, value);
2143 #endif
2144 }
2145
2146 void
2147 mono_img_writer_emit_line (MonoImageWriter *acfg)
2148 {
2149 #ifdef USE_BIN_WRITER
2150         if (acfg->use_bin_writer)
2151                 bin_writer_emit_line (acfg);
2152         else
2153                 asm_writer_emit_line (acfg);
2154 #else
2155                 asm_writer_emit_line (acfg);
2156 #endif
2157 }
2158
2159 void
2160 mono_img_writer_emit_alignment (MonoImageWriter *acfg, int size)
2161 {
2162 #ifdef USE_BIN_WRITER
2163         if (acfg->use_bin_writer)
2164                 bin_writer_emit_alignment (acfg, size);
2165         else
2166                 asm_writer_emit_alignment (acfg, size);
2167 #else
2168         asm_writer_emit_alignment (acfg, size);
2169 #endif
2170 }
2171
2172 void
2173 mono_img_writer_emit_alignment_fill (MonoImageWriter *acfg, int size, int fill)
2174 {
2175 #ifdef USE_BIN_WRITER
2176         if (acfg->use_bin_writer)
2177                 bin_writer_emit_alignment (acfg, size);
2178         else
2179                 asm_writer_emit_alignment (acfg, size);
2180 #else
2181         asm_writer_emit_alignment_fill (acfg, size, fill);
2182 #endif
2183 }
2184
2185 #ifdef __native_client_codegen__
2186 void
2187 mono_img_writer_emit_nacl_call_alignment (MonoImageWriter *acfg) {
2188 #ifdef USE_BIN_WRITER
2189         if (acfg->use_bin_writer)
2190                 bin_writer_emit_nacl_call_alignment (acfg);
2191         else
2192                 asm_writer_emit_nacl_call_alignment (acfg);
2193 #else
2194         g_assert_not_reached();
2195 #endif
2196 }
2197 #endif  /* __native_client_codegen__ */
2198
2199 void
2200 mono_img_writer_emit_pointer_unaligned (MonoImageWriter *acfg, const char *target)
2201 {
2202 #ifdef USE_BIN_WRITER
2203         if (acfg->use_bin_writer)
2204                 bin_writer_emit_pointer_unaligned (acfg, target);
2205         else
2206                 asm_writer_emit_pointer_unaligned (acfg, target);
2207 #else
2208         asm_writer_emit_pointer_unaligned (acfg, target);
2209 #endif
2210 }
2211
2212 void
2213 mono_img_writer_emit_pointer (MonoImageWriter *acfg, const char *target)
2214 {
2215 #ifdef USE_BIN_WRITER
2216         if (acfg->use_bin_writer)
2217                 bin_writer_emit_pointer (acfg, target);
2218         else
2219                 asm_writer_emit_pointer (acfg, target);
2220 #else
2221         asm_writer_emit_pointer (acfg, target);
2222 #endif
2223 }
2224
2225 void
2226 mono_img_writer_emit_int16 (MonoImageWriter *acfg, int value)
2227 {
2228 #ifdef USE_BIN_WRITER
2229         if (acfg->use_bin_writer)
2230                 bin_writer_emit_int16 (acfg, value);
2231         else
2232                 asm_writer_emit_int16 (acfg, value);
2233 #else
2234         asm_writer_emit_int16 (acfg, value);
2235 #endif
2236 }
2237
2238 void
2239 mono_img_writer_emit_int32 (MonoImageWriter *acfg, int value)
2240 {
2241 #ifdef USE_BIN_WRITER
2242         if (acfg->use_bin_writer)
2243                 bin_writer_emit_int32 (acfg, value);
2244         else
2245                 asm_writer_emit_int32 (acfg, value);
2246 #else
2247         asm_writer_emit_int32 (acfg, value);
2248 #endif
2249 }
2250
2251 void
2252 mono_img_writer_emit_symbol_diff (MonoImageWriter *acfg, const char *end, const char* start, int offset)
2253 {
2254 #ifdef USE_BIN_WRITER
2255         if (acfg->use_bin_writer)
2256                 bin_writer_emit_symbol_diff (acfg, end, start, offset);
2257         else
2258                 asm_writer_emit_symbol_diff (acfg, end, start, offset);
2259 #else
2260         asm_writer_emit_symbol_diff (acfg, end, start, offset);
2261 #endif
2262 }
2263
2264 void
2265 mono_img_writer_emit_zero_bytes (MonoImageWriter *acfg, int num)
2266 {
2267 #ifdef USE_BIN_WRITER
2268         if (acfg->use_bin_writer)
2269                 bin_writer_emit_zero_bytes (acfg, num);
2270         else
2271                 asm_writer_emit_zero_bytes (acfg, num);
2272 #else
2273         asm_writer_emit_zero_bytes (acfg, num);
2274 #endif
2275 }
2276
2277 int
2278 mono_img_writer_emit_writeout (MonoImageWriter *acfg)
2279 {
2280 #ifdef USE_BIN_WRITER
2281         if (acfg->use_bin_writer)
2282                 return bin_writer_emit_writeout (acfg);
2283         else
2284                 return asm_writer_emit_writeout (acfg);
2285 #else
2286                 return asm_writer_emit_writeout (acfg);
2287 #endif
2288 }
2289
2290 void
2291 mono_img_writer_emit_byte (MonoImageWriter *acfg, guint8 val)
2292 {
2293         mono_img_writer_emit_bytes (acfg, &val, 1);
2294 }
2295
2296 /* 
2297  * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
2298  * Do not advance PC.
2299  */
2300 void
2301 mono_img_writer_emit_reloc (MonoImageWriter *acfg, int reloc_type, const char *symbol, int addend)
2302 {
2303         /* This is only supported by the bin writer */
2304 #ifdef USE_BIN_WRITER
2305         if (acfg->use_bin_writer)
2306                 bin_writer_emit_reloc (acfg, reloc_type, symbol, addend);
2307         else
2308                 g_assert_not_reached ();
2309 #else
2310                 g_assert_not_reached ();
2311 #endif
2312 }
2313
2314 /*
2315  * mono_img_writer_emit_unset_mode:
2316  *
2317  *   Flush buffered data so it is safe to write to the output file from outside this
2318  * module. This is a nop for the binary writer.
2319  */
2320 void
2321 mono_img_writer_emit_unset_mode (MonoImageWriter *acfg)
2322 {
2323         if (!acfg->use_bin_writer)
2324                 asm_writer_emit_unset_mode (acfg);
2325 }
2326
2327 /*
2328  * mono_img_writer_get_output:
2329  *
2330  *   Return the output buffer of a binary writer emitting to memory. The returned memory
2331  * is from malloc, and it is owned by the caller.
2332  */
2333 guint8*
2334 mono_img_writer_get_output (MonoImageWriter *acfg, guint32 *size)
2335 {
2336 #ifdef USE_BIN_WRITER
2337         guint8 *buf;
2338
2339         g_assert (acfg->use_bin_writer);
2340
2341         buf = acfg->out_buf;
2342         *size = acfg->out_buf_size;
2343         acfg->out_buf = NULL;
2344         return buf;
2345 #else
2346         g_assert_not_reached ();
2347         return NULL;
2348 #endif
2349 }
2350
2351 /*
2352  * Return whenever the binary writer is supported on this platform.
2353  */
2354 gboolean
2355 mono_bin_writer_supported (void)
2356 {
2357 #ifdef USE_BIN_WRITER
2358         return TRUE;
2359 #else
2360         return FALSE;
2361 #endif
2362 }
2363
2364 /*
2365  * mono_img_writer_create:
2366  *
2367  *   Create an image writer writing to FP. If USE_BIN_WRITER is TRUE, FP can be NULL,
2368  * in this case the image writer will write to a memory buffer obtainable by calling
2369  * mono_img_writer_get_output ().
2370  */
2371 MonoImageWriter*
2372 mono_img_writer_create (FILE *fp, gboolean use_bin_writer)
2373 {
2374         MonoImageWriter *w = g_new0 (MonoImageWriter, 1);
2375         
2376 #ifndef USE_BIN_WRITER
2377         g_assert (!use_bin_writer);
2378 #endif
2379
2380         if (!use_bin_writer)
2381                 g_assert (fp);
2382
2383         w->fp = fp;
2384         w->use_bin_writer = use_bin_writer;
2385         w->mempool = mono_mempool_new ();
2386
2387         return w;
2388 }
2389
2390 void
2391 mono_img_writer_destroy (MonoImageWriter *w)
2392 {
2393         // FIXME: Free all the stuff
2394         mono_mempool_destroy (w->mempool);
2395         g_free (w);
2396 }
2397
2398 gboolean
2399 mono_img_writer_subsections_supported (MonoImageWriter *acfg)
2400 {
2401 #ifdef TARGET_ASM_APPLE
2402         return acfg->use_bin_writer;
2403 #else
2404         return TRUE;
2405 #endif
2406 }
2407
2408 FILE *
2409 mono_img_writer_get_fp (MonoImageWriter *acfg)
2410 {
2411         return acfg->fp;
2412 }
2413
2414 const char *
2415 mono_img_writer_get_temp_label_prefix (MonoImageWriter *acfg)
2416 {
2417         return AS_TEMP_LABEL_PREFIX;
2418 }