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