fixed popf TF flag bug (should never hapen in user code except in test-i386!)
[qemu] / dyngen.c
1 /*
2  *  Generic Dynamic compiler generator
3  * 
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdarg.h>
24 #include <inttypes.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27
28 #include "config.h"
29
30 /* elf format definitions. We use these macros to test the CPU to
31    allow cross compilation (this tool must be ran on the build
32    platform) */
33 #if defined(HOST_I386)
34
35 #define ELF_CLASS       ELFCLASS32
36 #define ELF_ARCH        EM_386
37 #define elf_check_arch(x) ( ((x) == EM_386) || ((x) == EM_486) )
38 #undef ELF_USES_RELOCA
39
40 #elif defined(HOST_PPC)
41
42 #define ELF_CLASS       ELFCLASS32
43 #define ELF_ARCH        EM_PPC
44 #define elf_check_arch(x) ((x) == EM_PPC)
45 #define ELF_USES_RELOCA
46
47 #elif defined(HOST_S390)
48
49 #define ELF_CLASS       ELFCLASS32
50 #define ELF_ARCH        EM_S390
51 #define elf_check_arch(x) ((x) == EM_S390)
52 #define ELF_USES_RELOCA
53
54 #elif defined(HOST_ALPHA)
55
56 #define ELF_CLASS       ELFCLASS64
57 #define ELF_ARCH        EM_ALPHA
58 #define elf_check_arch(x) ((x) == EM_ALPHA)
59 #define ELF_USES_RELOCA
60
61 #elif defined(HOST_IA64)
62
63 #define ELF_CLASS       ELFCLASS64
64 #define ELF_ARCH        EM_IA_64
65 #define elf_check_arch(x) ((x) == EM_IA_64)
66 #define ELF_USES_RELOCA
67
68 #elif defined(HOST_SPARC)
69
70 #define ELF_CLASS       ELFCLASS32
71 #define ELF_ARCH        EM_SPARC
72 #define elf_check_arch(x) ((x) == EM_SPARC || (x) == EM_SPARC32PLUS)
73 #define ELF_USES_RELOCA
74
75 #elif defined(HOST_SPARC64)
76
77 #define ELF_CLASS       ELFCLASS64
78 #define ELF_ARCH        EM_SPARCV9
79 #define elf_check_arch(x) ((x) == EM_SPARCV9)
80 #define ELF_USES_RELOCA
81
82 #else
83 #error unsupported CPU - please update the code
84 #endif
85
86 #include "elf.h"
87
88 #if ELF_CLASS == ELFCLASS32
89 typedef int32_t host_long;
90 typedef uint32_t host_ulong;
91 #define swabls(x) swab32s(x)
92 #else
93 typedef int64_t host_long;
94 typedef uint64_t host_ulong;
95 #define swabls(x) swab64s(x)
96 #endif
97
98 #include "thunk.h"
99
100 /* all dynamically generated functions begin with this code */
101 #define OP_PREFIX "op_"
102
103 int elf_must_swap(struct elfhdr *h)
104 {
105   union {
106       uint32_t i;
107       uint8_t b[4];
108   } swaptest;
109
110   swaptest.i = 1;
111   return (h->e_ident[EI_DATA] == ELFDATA2MSB) != 
112       (swaptest.b[0] == 0);
113 }
114   
115 void swab16s(uint16_t *p)
116 {
117     *p = bswap16(*p);
118 }
119
120 void swab32s(uint32_t *p)
121 {
122     *p = bswap32(*p);
123 }
124
125 void swab64s(uint64_t *p)
126 {
127     *p = bswap64(*p);
128 }
129
130 void elf_swap_ehdr(struct elfhdr *h)
131 {
132     swab16s(&h->e_type);                        /* Object file type */
133     swab16s(&h->        e_machine);             /* Architecture */
134     swab32s(&h->        e_version);             /* Object file version */
135     swabls(&h-> e_entry);               /* Entry point virtual address */
136     swabls(&h-> e_phoff);               /* Program header table file offset */
137     swabls(&h-> e_shoff);               /* Section header table file offset */
138     swab32s(&h->        e_flags);               /* Processor-specific flags */
139     swab16s(&h->        e_ehsize);              /* ELF header size in bytes */
140     swab16s(&h->        e_phentsize);           /* Program header table entry size */
141     swab16s(&h->        e_phnum);               /* Program header table entry count */
142     swab16s(&h->        e_shentsize);           /* Section header table entry size */
143     swab16s(&h->        e_shnum);               /* Section header table entry count */
144     swab16s(&h->        e_shstrndx);            /* Section header string table index */
145 }
146
147 void elf_swap_shdr(struct elf_shdr *h)
148 {
149   swab32s(&h->  sh_name);               /* Section name (string tbl index) */
150   swab32s(&h->  sh_type);               /* Section type */
151   swabls(&h->   sh_flags);              /* Section flags */
152   swabls(&h->   sh_addr);               /* Section virtual addr at execution */
153   swabls(&h->   sh_offset);             /* Section file offset */
154   swabls(&h->   sh_size);               /* Section size in bytes */
155   swab32s(&h->  sh_link);               /* Link to another section */
156   swab32s(&h->  sh_info);               /* Additional section information */
157   swabls(&h->   sh_addralign);          /* Section alignment */
158   swabls(&h->   sh_entsize);            /* Entry size if section holds table */
159 }
160
161 void elf_swap_phdr(struct elf_phdr *h)
162 {
163     swab32s(&h->p_type);                        /* Segment type */
164     swabls(&h->p_offset);               /* Segment file offset */
165     swabls(&h->p_vaddr);                /* Segment virtual address */
166     swabls(&h->p_paddr);                /* Segment physical address */
167     swabls(&h->p_filesz);               /* Segment size in file */
168     swabls(&h->p_memsz);                /* Segment size in memory */
169     swab32s(&h->p_flags);               /* Segment flags */
170     swabls(&h->p_align);                /* Segment alignment */
171 }
172
173 int do_swap;
174
175 uint16_t get16(uint16_t *p)
176 {
177     uint16_t val;
178     val = *p;
179     if (do_swap)
180         val = bswap16(val);
181     return val;
182 }
183
184 uint32_t get32(uint32_t *p)
185 {
186     uint32_t val;
187     val = *p;
188     if (do_swap)
189         val = bswap32(val);
190     return val;
191 }
192
193 void put16(uint16_t *p, uint16_t val)
194 {
195     if (do_swap)
196         val = bswap16(val);
197     *p = val;
198 }
199
200 void put32(uint32_t *p, uint32_t val)
201 {
202     if (do_swap)
203         val = bswap32(val);
204     *p = val;
205 }
206
207 void __attribute__((noreturn)) __attribute__((format (printf, 1, 2))) error(const char *fmt, ...)
208 {
209     va_list ap;
210     va_start(ap, fmt);
211     fprintf(stderr, "dyngen: ");
212     vfprintf(stderr, fmt, ap);
213     fprintf(stderr, "\n");
214     va_end(ap);
215     exit(1);
216 }
217
218
219 struct elf_shdr *find_elf_section(struct elf_shdr *shdr, int shnum, const char *shstr, 
220                                   const char *name)
221 {
222     int i;
223     const char *shname;
224     struct elf_shdr *sec;
225
226     for(i = 0; i < shnum; i++) {
227         sec = &shdr[i];
228         if (!sec->sh_name)
229             continue;
230         shname = shstr + sec->sh_name;
231         if (!strcmp(shname, name))
232             return sec;
233     }
234     return NULL;
235 }
236
237 void *load_data(int fd, long offset, unsigned int size)
238 {
239     char *data;
240
241     data = malloc(size);
242     if (!data)
243         return NULL;
244     lseek(fd, offset, SEEK_SET);
245     if (read(fd, data, size) != size) {
246         free(data);
247         return NULL;
248     }
249     return data;
250 }
251
252 int strstart(const char *str, const char *val, const char **ptr)
253 {
254     const char *p, *q;
255     p = str;
256     q = val;
257     while (*q != '\0') {
258         if (*p != *q)
259             return 0;
260         p++;
261         q++;
262     }
263     if (ptr)
264         *ptr = p;
265     return 1;
266 }
267
268 #define MAX_ARGS 3
269
270 /* generate op code */
271 void gen_code(const char *name, host_ulong offset, host_ulong size, 
272               FILE *outfile, uint8_t *text, ELF_RELOC *relocs, int nb_relocs, int reloc_sh_type,
273               ElfW(Sym) *symtab, char *strtab, int gen_switch)
274 {
275     int copy_size = 0;
276     uint8_t *p_start, *p_end;
277     host_ulong start_offset;
278     int nb_args, i, n;
279     uint8_t args_present[MAX_ARGS];
280     const char *sym_name, *p;
281     ELF_RELOC *rel;
282
283     /* Compute exact size excluding prologue and epilogue instructions.
284      * Increment start_offset to skip epilogue instructions, then compute
285      * copy_size the indicate the size of the remaining instructions (in
286      * bytes).
287      */
288     p_start = text + offset;
289     p_end = p_start + size;
290     start_offset = offset;
291     switch(ELF_ARCH) {
292     case EM_386:
293         {
294             uint8_t *p;
295             p = p_end - 1;
296             if (p == p_start)
297                 error("empty code for %s", name);
298             if (p[0] != 0xc3)
299                 error("ret expected at the end of %s", name);
300             copy_size = p - p_start;
301         }
302         break;
303     case EM_PPC:
304         {
305             uint8_t *p;
306             p = (void *)(p_end - 4);
307             if (p == p_start)
308                 error("empty code for %s", name);
309             if (get32((uint32_t *)p) != 0x4e800020)
310                 error("blr expected at the end of %s", name);
311             copy_size = p - p_start;
312         }
313         break;
314     case EM_S390:
315         {
316             uint8_t *p;
317             p = (void *)(p_end - 2);
318             if (p == p_start)
319                 error("empty code for %s", name);
320             if (get16((uint16_t *)p) != 0x07fe && get16((uint16_t *)p) != 0x07f4)
321                 error("br %%r14 expected at the end of %s", name);
322             copy_size = p - p_start;
323         }
324         break;
325     case EM_ALPHA:
326         {
327             uint8_t *p;
328             p = p_end - 4;
329             if (p == p_start)
330                 error("empty code for %s", name);
331             if (get32((uint32_t *)p) != 0x6bfa8001)
332                 error("ret expected at the end of %s", name);
333             copy_size = p - p_start;        
334         }
335         break;
336     case EM_IA_64:
337         {
338             uint8_t *p;
339             p = (void *)(p_end - 4);
340             if (p == p_start)
341                 error("empty code for %s", name);
342             /* br.ret.sptk.many b0;; */
343             /* 08 00 84 00 */
344             if (get32((uint32_t *)p) != 0x00840008)
345                 error("br.ret.sptk.many b0;; expected at the end of %s", name);
346             copy_size = p - p_start;
347         }
348         break;
349     case EM_SPARC:
350     case EM_SPARC32PLUS:
351         {
352             uint32_t start_insn, end_insn1, end_insn2, skip_insn;
353             uint8_t *p;
354             p = (void *)(p_end - 8);
355             if (p <= p_start)
356                 error("empty code for %s", name);
357             start_insn = get32((uint32_t *)(p_start + 0x0));
358             end_insn1 = get32((uint32_t *)(p + 0x0));
359             end_insn2 = get32((uint32_t *)(p + 0x4));
360             if ((start_insn & ~0x1fff) == 0x9de3a000) {
361                 p_start += 0x4;
362                 start_offset += 0x4;
363                 if ((int)(start_insn | ~0x1fff) < -128)
364                     error("Found bogus save at the start of %s", name);
365                 if (end_insn1 != 0x81c7e008 || end_insn2 != 0x81e80000)
366                     error("ret; restore; not found at end of %s", name);
367             } else {
368                 error("No save at the beginning of %s", name);
369             }
370
371             /* Skip a preceeding nop, if present.  */
372             if (p > p_start) {
373                 skip_insn = get32((uint32_t *)(p - 0x4));
374                 if (skip_insn == 0x01000000)
375                     p -= 4;
376             }
377
378             copy_size = p - p_start;
379         }
380         break;
381     case EM_SPARCV9:
382         {
383             uint32_t start_insn, end_insn1, end_insn2, skip_insn;
384             uint8_t *p;
385             p = (void *)(p_end - 8);
386             if (p <= p_start)
387                 error("empty code for %s", name);
388             start_insn = get32((uint32_t *)(p_start + 0x0));
389             end_insn1 = get32((uint32_t *)(p + 0x0));
390             end_insn2 = get32((uint32_t *)(p + 0x4));
391             if ((start_insn & ~0x1fff) == 0x9de3a000) {
392                 p_start += 0x4;
393                 start_offset += 0x4;
394                 if ((int)(start_insn | ~0x1fff) < -256)
395                     error("Found bogus save at the start of %s", name);
396                 if (end_insn1 != 0x81c7e008 || end_insn2 != 0x81e80000)
397                     error("ret; restore; not found at end of %s", name);
398             } else {
399                 error("No save at the beginning of %s", name);
400             }
401
402             /* Skip a preceeding nop, if present.  */
403             if (p > p_start) {
404                 skip_insn = get32((uint32_t *)(p - 0x4));
405                 if (skip_insn == 0x01000000)
406                     p -= 4;
407             }
408
409             copy_size = p - p_start;
410         }
411         break;
412     default:
413         error("unknown ELF architecture");
414     }
415
416     /* compute the number of arguments by looking at the relocations */
417     for(i = 0;i < MAX_ARGS; i++)
418         args_present[i] = 0;
419
420     for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
421         if (rel->r_offset >= start_offset &&
422             rel->r_offset < start_offset + copy_size) {
423             sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
424             if (strstart(sym_name, "__op_param", &p)) {
425                 n = strtoul(p, NULL, 10);
426                 if (n >= MAX_ARGS)
427                     error("too many arguments in %s", name);
428                 args_present[n - 1] = 1;
429             }
430         }
431     }
432     
433     nb_args = 0;
434     while (nb_args < MAX_ARGS && args_present[nb_args])
435         nb_args++;
436     for(i = nb_args; i < MAX_ARGS; i++) {
437         if (args_present[i])
438             error("inconsistent argument numbering in %s", name);
439     }
440
441     if (gen_switch == 2) {
442         fprintf(outfile, "DEF(%s, %d)\n", name + 3, nb_args);
443     } else if (gen_switch == 1) {
444
445         /* output C code */
446         fprintf(outfile, "case INDEX_%s: {\n", name);
447         if (nb_args > 0) {
448             fprintf(outfile, "    long ");
449             for(i = 0; i < nb_args; i++) {
450                 if (i != 0)
451                     fprintf(outfile, ", ");
452                 fprintf(outfile, "param%d", i + 1);
453             }
454             fprintf(outfile, ";\n");
455         }
456         fprintf(outfile, "    extern void %s();\n", name);
457
458         for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
459             if (rel->r_offset >= start_offset &&
460                 rel->r_offset < start_offset + copy_size) {
461                 sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
462                 if (*sym_name && !strstart(sym_name, "__op_param", &p)) {
463 #if defined(HOST_SPARC)
464                     if (sym_name[0] == '.') {
465                         fprintf(outfile,
466                                 "extern char __dot_%s __asm__(\"%s\");\n",
467                                 sym_name+1, sym_name);
468                         continue;
469                     }
470 #endif
471                     fprintf(outfile, "extern char %s;\n", sym_name);
472                 }
473             }
474         }
475
476         fprintf(outfile, "    memcpy(gen_code_ptr, (void *)((char *)&%s+%d), %d);\n", name, start_offset - offset, copy_size);
477         for(i = 0; i < nb_args; i++) {
478             fprintf(outfile, "    param%d = *opparam_ptr++;\n", i + 1);
479         }
480
481         /* patch relocations */
482 #if defined(HOST_I386)
483             {
484                 char name[256];
485                 int type;
486                 int addend;
487                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
488                 if (rel->r_offset >= start_offset &&
489                     rel->r_offset < start_offset + copy_size) {
490                     sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
491                     if (strstart(sym_name, "__op_param", &p)) {
492                         snprintf(name, sizeof(name), "param%s", p);
493                     } else {
494                         snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
495                     }
496                     type = ELF32_R_TYPE(rel->r_info);
497                     addend = get32((uint32_t *)(text + rel->r_offset));
498                     switch(type) {
499                     case R_386_32:
500                         fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
501                                 rel->r_offset - start_offset, name, addend);
502                         break;
503                     case R_386_PC32:
504                         fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s - (long)(gen_code_ptr + %d) + %d;\n", 
505                                 rel->r_offset - start_offset, name, rel->r_offset - start_offset, addend);
506                         break;
507                     default:
508                         error("unsupported i386 relocation (%d)", type);
509                     }
510                 }
511                 }
512             }
513 #elif defined(HOST_PPC)
514             {
515                 char name[256];
516                 int type;
517                 int addend;
518                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
519                     if (rel->r_offset >= start_offset &&
520                         rel->r_offset < start_offset + copy_size) {
521                         sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
522                         if (strstart(sym_name, "__op_param", &p)) {
523                             snprintf(name, sizeof(name), "param%s", p);
524                         } else {
525                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
526                         }
527                         type = ELF32_R_TYPE(rel->r_info);
528                         addend = rel->r_addend;
529                         switch(type) {
530                         case R_PPC_ADDR32:
531                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
532                                     rel->r_offset - start_offset, name, addend);
533                             break;
534                         case R_PPC_ADDR16_LO:
535                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d);\n", 
536                                     rel->r_offset - start_offset, name, addend);
537                             break;
538                         case R_PPC_ADDR16_HI:
539                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d) >> 16;\n", 
540                                     rel->r_offset - start_offset, name, addend);
541                             break;
542                         case R_PPC_ADDR16_HA:
543                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d + 0x8000) >> 16;\n", 
544                                     rel->r_offset - start_offset, name, addend);
545                             break;
546                         case R_PPC_REL24:
547                             /* warning: must be at 32 MB distancy */
548                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = (*(uint32_t *)(gen_code_ptr + %d) & ~0x03fffffc) | ((%s - (long)(gen_code_ptr + %d) + %d) & 0x03fffffc);\n", 
549                                     rel->r_offset - start_offset, rel->r_offset - start_offset, name, rel->r_offset - start_offset, addend);
550                             break;
551                         default:
552                             error("unsupported powerpc relocation (%d)", type);
553                         }
554                     }
555                 }
556             }
557 #elif defined(HOST_S390)
558             {
559                 char name[256];
560                 int type;
561                 int addend;
562                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
563                     if (rel->r_offset >= start_offset &&
564                         rel->r_offset < start_offset + copy_size) {
565                         sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
566                         if (strstart(sym_name, "__op_param", &p)) {
567                             snprintf(name, sizeof(name), "param%s", p);
568                         } else {
569                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
570                         }
571                         type = ELF32_R_TYPE(rel->r_info);
572                         addend = rel->r_addend;
573                         switch(type) {
574                         case R_390_32:
575                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
576                                     rel->r_offset - start_offset, name, addend);
577                             break;
578                         case R_390_16:
579                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = %s + %d;\n", 
580                                     rel->r_offset - start_offset, name, addend);
581                             break;
582                         case R_390_8:
583                             fprintf(outfile, "    *(uint8_t *)(gen_code_ptr + %d) = %s + %d;\n", 
584                                     rel->r_offset - start_offset, name, addend);
585                             break;
586                         default:
587                             error("unsupported s390 relocation (%d)", type);
588                         }
589                     }
590                 }
591             }
592 #elif defined(HOST_ALPHA)
593             {
594                 for (i = 0, rel = relocs; i < nb_relocs; i++, rel++) {
595                     if (rel->r_offset >= start_offset && rel->r_offset < start_offset + copy_size) {
596                         int type;
597
598                         type = ELF64_R_TYPE(rel->r_info);
599                         sym_name = strtab + symtab[ELF64_R_SYM(rel->r_info)].st_name;
600                         switch (type) {
601                         case R_ALPHA_GPDISP:
602                             /* The gp is just 32 bit, and never changes, so it's easiest to emit it
603                                as an immediate instead of constructing it from the pv or ra.  */
604                             fprintf(outfile, "    immediate_ldah(gen_code_ptr + %ld, gp);\n",
605                                     rel->r_offset - start_offset);
606                             fprintf(outfile, "    immediate_lda(gen_code_ptr + %ld, gp);\n",
607                                     rel->r_offset - start_offset + rel->r_addend);
608                             break;
609                         case R_ALPHA_LITUSE:
610                             /* jsr to literal hint. Could be used to optimize to bsr. Ignore for
611                                now, since some called functions (libc) need pv to be set up.  */
612                             break;
613                         case R_ALPHA_HINT:
614                             /* Branch target prediction hint. Ignore for now.  Should be already
615                                correct for in-function jumps.  */
616                             break;
617                         case R_ALPHA_LITERAL:
618                             /* Load a literal from the GOT relative to the gp.  Since there's only a
619                                single gp, nothing is to be done.  */
620                             break;
621                         case R_ALPHA_GPRELHIGH:
622                             /* Handle fake relocations against __op_param symbol.  Need to emit the
623                                high part of the immediate value instead.  Other symbols need no
624                                special treatment.  */
625                             if (strstart(sym_name, "__op_param", &p))
626                                 fprintf(outfile, "    immediate_ldah(gen_code_ptr + %ld, param%s);\n",
627                                         rel->r_offset - start_offset, p);
628                             break;
629                         case R_ALPHA_GPRELLOW:
630                             if (strstart(sym_name, "__op_param", &p))
631                                 fprintf(outfile, "    immediate_lda(gen_code_ptr + %ld, param%s);\n",
632                                         rel->r_offset - start_offset, p);
633                             break;
634                         case R_ALPHA_BRSGP:
635                             /* PC-relative jump. Tweak offset to skip the two instructions that try to
636                                set up the gp from the pv.  */
637                             fprintf(outfile, "    fix_bsr(gen_code_ptr + %ld, (uint8_t *) &%s - (gen_code_ptr + %ld) + 4);\n",
638                                     rel->r_offset - start_offset, sym_name, rel->r_offset - start_offset);
639                             break;
640                         default:
641                             error("unsupported Alpha relocation (%d)", type);
642                         }
643                     }
644                 }
645             }
646 #elif defined(HOST_IA64)
647             {
648                 char name[256];
649                 int type;
650                 int addend;
651                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
652                     if (rel->r_offset >= start_offset && rel->r_offset < start_offset + copy_size) {
653                         sym_name = strtab + symtab[ELF64_R_SYM(rel->r_info)].st_name;
654                         if (strstart(sym_name, "__op_param", &p)) {
655                             snprintf(name, sizeof(name), "param%s", p);
656                         } else {
657                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
658                         }
659                         type = ELF64_R_TYPE(rel->r_info);
660                         addend = rel->r_addend;
661                         switch(type) {
662                         case R_IA64_LTOFF22:
663                             error("must implemnt R_IA64_LTOFF22 relocation");
664                         case R_IA64_PCREL21B:
665                             error("must implemnt R_IA64_PCREL21B relocation");
666                         default:
667                             error("unsupported ia64 relocation (%d)", type);
668                         }
669                     }
670                 }
671             }
672 #elif defined(HOST_SPARC)
673             {
674                 char name[256];
675                 int type;
676                 int addend;
677                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
678                     if (rel->r_offset >= start_offset &&
679                         rel->r_offset < start_offset + copy_size) {
680                         sym_name = strtab + symtab[ELF32_R_SYM(rel->r_info)].st_name;
681                         if (strstart(sym_name, "__op_param", &p)) {
682                             snprintf(name, sizeof(name), "param%s", p);
683                         } else {
684                                 if (sym_name[0] == '.')
685                                         snprintf(name, sizeof(name),
686                                                  "(long)(&__dot_%s)",
687                                                  sym_name + 1);
688                                 else
689                                         snprintf(name, sizeof(name),
690                                                  "(long)(&%s)", sym_name);
691                         }
692                         type = ELF32_R_TYPE(rel->r_info);
693                         addend = rel->r_addend;
694                         switch(type) {
695                         case R_SPARC_32:
696                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
697                                     rel->r_offset - start_offset, name, addend);
698                             break;
699                         case R_SPARC_HI22:
700                             fprintf(outfile,
701                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
702                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
703                                     " & ~0x3fffff) "
704                                     " | (((%s + %d) >> 10) & 0x3fffff);\n",
705                                     rel->r_offset - start_offset,
706                                     rel->r_offset - start_offset,
707                                     name, addend);
708                             break;
709                         case R_SPARC_LO10:
710                             fprintf(outfile,
711                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
712                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
713                                     " & ~0x3ff) "
714                                     " | ((%s + %d) & 0x3ff);\n",
715                                     rel->r_offset - start_offset,
716                                     rel->r_offset - start_offset,
717                                     name, addend);
718                             break;
719                         case R_SPARC_WDISP30:
720                             fprintf(outfile,
721                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
722                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
723                                     " & ~0x3fffffff) "
724                                     " | ((((%s + %d) - (long)(gen_code_ptr + %d))>>2) "
725                                     "    & 0x3fffffff);\n",
726                                     rel->r_offset - start_offset,
727                                     rel->r_offset - start_offset,
728                                     name, addend,
729                                     rel->r_offset - start_offset);
730                             break;
731                         default:
732                             error("unsupported sparc relocation (%d)", type);
733                         }
734                     }
735                 }
736             }
737 #elif defined(HOST_SPARC64)
738             {
739                 char name[256];
740                 int type;
741                 int addend;
742                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
743                     if (rel->r_offset >= start_offset &&
744                         rel->r_offset < start_offset + copy_size) {
745                         sym_name = strtab + symtab[ELF64_R_SYM(rel->r_info)].st_name;
746                         if (strstart(sym_name, "__op_param", &p)) {
747                             snprintf(name, sizeof(name), "param%s", p);
748                         } else {
749                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
750                         }
751                         type = ELF64_R_TYPE(rel->r_info);
752                         addend = rel->r_addend;
753                         switch(type) {
754                         case R_SPARC_32:
755                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n",
756                                     rel->r_offset - start_offset, name, addend);
757                             break;
758                         case R_SPARC_HI22:
759                             fprintf(outfile,
760                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
761                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
762                                     " & ~0x3fffff) "
763                                     " | (((%s + %d) >> 10) & 0x3fffff);\n",
764                                     rel->r_offset - start_offset,
765                                     rel->r_offset - start_offset,
766                                     name, addend);
767                             break;
768                         case R_SPARC_LO10:
769                             fprintf(outfile,
770                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
771                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
772                                     " & ~0x3ff) "
773                                     " | ((%s + %d) & 0x3ff);\n",
774                                     rel->r_offset - start_offset,
775                                     rel->r_offset - start_offset,
776                                     name, addend);
777                             break;
778                         case R_SPARC_WDISP30:
779                             fprintf(outfile,
780                                     "    *(uint32_t *)(gen_code_ptr + %d) = "
781                                     "((*(uint32_t *)(gen_code_ptr + %d)) "
782                                     " & ~0x3fffffff) "
783                                     " | ((((%s + %d) - (long)(gen_code_ptr + %d))>>2) "
784                                     "    & 0x3fffffff);\n",
785                                     rel->r_offset - start_offset,
786                                     rel->r_offset - start_offset,
787                                     name, addend,
788                                     rel->r_offset - start_offset);
789                             break;
790                         default:
791                             error("unsupported sparc64 relocation (%d)", type);
792                         }
793                     }
794                 }
795             }
796 #else
797 #error unsupported CPU
798 #endif
799         fprintf(outfile, "    gen_code_ptr += %d;\n", copy_size);
800         fprintf(outfile, "}\n");
801         fprintf(outfile, "break;\n\n");
802     } else {
803         fprintf(outfile, "static inline void gen_%s(", name);
804         if (nb_args == 0) {
805             fprintf(outfile, "void");
806         } else {
807             for(i = 0; i < nb_args; i++) {
808                 if (i != 0)
809                     fprintf(outfile, ", ");
810                 fprintf(outfile, "long param%d", i + 1);
811             }
812         }
813         fprintf(outfile, ")\n");
814         fprintf(outfile, "{\n");
815         for(i = 0; i < nb_args; i++) {
816             fprintf(outfile, "    *gen_opparam_ptr++ = param%d;\n", i + 1);
817         }
818         fprintf(outfile, "    *gen_opc_ptr++ = INDEX_%s;\n", name);
819         fprintf(outfile, "}\n\n");
820     }
821 }
822
823 /* load an elf object file */
824 int load_elf(const char *filename, FILE *outfile, int do_print_enum)
825 {
826     int fd;
827     struct elfhdr ehdr;
828     struct elf_shdr *sec, *shdr, *symtab_sec, *strtab_sec, *text_sec;
829     int i, j, nb_syms;
830     ElfW(Sym) *symtab, *sym;
831     char *shstr, *strtab;
832     uint8_t *text;
833     void *relocs;
834     int nb_relocs, reloc_sh_type;
835     
836     fd = open(filename, O_RDONLY);
837     if (fd < 0) 
838         error("can't open file '%s'", filename);
839     
840     /* Read ELF header.  */
841     if (read(fd, &ehdr, sizeof (ehdr)) != sizeof (ehdr))
842         error("unable to read file header");
843
844     /* Check ELF identification.  */
845     if (ehdr.e_ident[EI_MAG0] != ELFMAG0
846      || ehdr.e_ident[EI_MAG1] != ELFMAG1
847      || ehdr.e_ident[EI_MAG2] != ELFMAG2
848      || ehdr.e_ident[EI_MAG3] != ELFMAG3
849      || ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
850         error("bad ELF header");
851     }
852
853     do_swap = elf_must_swap(&ehdr);
854     if (do_swap)
855         elf_swap_ehdr(&ehdr);
856     if (ehdr.e_ident[EI_CLASS] != ELF_CLASS)
857         error("Unsupported ELF class");
858     if (ehdr.e_type != ET_REL)
859         error("ELF object file expected");
860     if (ehdr.e_version != EV_CURRENT)
861         error("Invalid ELF version");
862     if (!elf_check_arch(ehdr.e_machine))
863         error("Unsupported CPU (e_machine=%d)", ehdr.e_machine);
864
865     /* read section headers */
866     shdr = load_data(fd, ehdr.e_shoff, ehdr.e_shnum * sizeof(struct elf_shdr));
867     if (do_swap) {
868         for(i = 0; i < ehdr.e_shnum; i++) {
869             elf_swap_shdr(&shdr[i]);
870         }
871     }
872
873     sec = &shdr[ehdr.e_shstrndx];
874     shstr = load_data(fd, sec->sh_offset, sec->sh_size);
875
876     /* text section */
877
878     text_sec = find_elf_section(shdr, ehdr.e_shnum, shstr, ".text");
879     if (!text_sec)
880         error("could not find .text section");
881     text = load_data(fd, text_sec->sh_offset, text_sec->sh_size);
882
883     /* find text relocations, if any */
884     nb_relocs = 0;
885     relocs = NULL;
886     reloc_sh_type = 0;
887     for(i = 0; i < ehdr.e_shnum; i++) {
888         sec = &shdr[i];
889         if ((sec->sh_type == SHT_REL || sec->sh_type == SHT_RELA) &&
890             sec->sh_info == (text_sec - shdr)) {
891             reloc_sh_type = sec->sh_type;
892             relocs = load_data(fd, sec->sh_offset, sec->sh_size);
893             nb_relocs = sec->sh_size / sec->sh_entsize;
894             if (do_swap) {
895                 if (sec->sh_type == SHT_REL) {
896                     ElfW(Rel) *rel = relocs;
897                     for(j = 0, rel = relocs; j < nb_relocs; j++, rel++) {
898                         swabls(&rel->r_offset);
899                         swabls(&rel->r_info);
900                     }
901                 } else {
902                     ElfW(Rela) *rel = relocs;
903                     for(j = 0, rel = relocs; j < nb_relocs; j++, rel++) {
904                         swabls(&rel->r_offset);
905                         swabls(&rel->r_info);
906                         swabls(&rel->r_addend);
907                     }
908                 }
909             }
910             break;
911         }
912     }
913
914     symtab_sec = find_elf_section(shdr, ehdr.e_shnum, shstr, ".symtab");
915     if (!symtab_sec)
916         error("could not find .symtab section");
917     strtab_sec = &shdr[symtab_sec->sh_link];
918
919     symtab = load_data(fd, symtab_sec->sh_offset, symtab_sec->sh_size);
920     strtab = load_data(fd, strtab_sec->sh_offset, strtab_sec->sh_size);
921     
922     nb_syms = symtab_sec->sh_size / sizeof(ElfW(Sym));
923     if (do_swap) {
924         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
925             swab32s(&sym->st_name);
926             swabls(&sym->st_value);
927             swabls(&sym->st_size);
928             swab16s(&sym->st_shndx);
929         }
930     }
931
932     if (do_print_enum) {
933         fprintf(outfile, "DEF(end, 0)\n");
934         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
935             const char *name, *p;
936             name = strtab + sym->st_name;
937             if (strstart(name, OP_PREFIX, &p)) {
938                 gen_code(name, sym->st_value, sym->st_size, outfile, 
939                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 2);
940             }
941         }
942     } else {
943         /* generate big code generation switch */
944 #ifdef HOST_ALPHA
945 fprintf(outfile,
946 "register int gp asm(\"$29\");\n"
947 "static inline void immediate_ldah(void *p, int val) {\n"
948 "    uint32_t *dest = p;\n"
949 "    long high = ((val >> 16) + ((val >> 15) & 1)) & 0xffff;\n"
950 "\n"
951 "    *dest &= ~0xffff;\n"
952 "    *dest |= high;\n"
953 "    *dest |= 31 << 16;\n"
954 "}\n"
955 "static inline void immediate_lda(void *dest, int val) {\n"
956 "    *(uint16_t *) dest = val;\n"
957 "}\n"
958 "void fix_bsr(void *p, int offset) {\n"
959 "    uint32_t *dest = p;\n"
960 "    *dest &= ~((1 << 21) - 1);\n"
961 "    *dest |= (offset >> 2) & ((1 << 21) - 1);\n"
962 "}\n");
963 #endif
964 fprintf(outfile,
965 "int dyngen_code(uint8_t *gen_code_buf,\n"
966 "                const uint16_t *opc_buf, const uint32_t *opparam_buf)\n"
967 "{\n"
968 "    uint8_t *gen_code_ptr;\n"
969 "    const uint16_t *opc_ptr;\n"
970 "    const uint32_t *opparam_ptr;\n"
971 "    gen_code_ptr = gen_code_buf;\n"
972 "    opc_ptr = opc_buf;\n"
973 "    opparam_ptr = opparam_buf;\n");
974
975         /* Generate prologue, if needed. */ 
976         switch(ELF_ARCH) {
977         case EM_SPARC:
978                 fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x9c23a080; /* sub %%sp, 128, %%sp */\n");
979                 fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0xbc27a080; /* sub %%fp, 128, %%fp */\n");
980                 break;
981
982         case EM_SPARCV9:
983                 fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x9c23a100; /* sub %%sp, 256, %%sp */\n");
984                 fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0xbc27a100; /* sub %%fp, 256, %%fp */\n");
985                 break;
986         };
987
988 fprintf(outfile,
989 "    for(;;) {\n"
990 "        switch(*opc_ptr++) {\n"
991 );
992
993         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
994             const char *name;
995             name = strtab + sym->st_name;
996             if (strstart(name, OP_PREFIX, NULL)) {
997 #if 0
998                 printf("%4d: %s pos=0x%08x len=%d\n", 
999                        i, name, sym->st_value, sym->st_size);
1000 #endif
1001                 if (sym->st_shndx != (text_sec - shdr))
1002                     error("invalid section for opcode (0x%x)", sym->st_shndx);
1003                 gen_code(name, sym->st_value, sym->st_size, outfile, 
1004                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 1);
1005             }
1006         }
1007
1008 fprintf(outfile,
1009 "        default:\n"
1010 "            goto the_end;\n"
1011 "        }\n"
1012 "    }\n"
1013 " the_end:\n"
1014 );
1015
1016 /* generate epilogue */ 
1017     switch(ELF_ARCH) {
1018     case EM_386:
1019         fprintf(outfile, "*gen_code_ptr++ = 0xc3; /* ret */\n");
1020         break;
1021     case EM_PPC:
1022         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x4e800020; /* blr */\n");
1023         break;
1024     case EM_S390:
1025         fprintf(outfile, "*((uint16_t *)gen_code_ptr)++ = 0x07fe; /* br %%r14 */\n");
1026         break;
1027     case EM_ALPHA:
1028         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x6bfa8001; /* ret */\n");
1029         break;
1030     case EM_IA_64:
1031         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x00840008; /* br.ret.sptk.many b0;; */\n");
1032         break;
1033     case EM_SPARC:
1034     case EM_SPARC32PLUS:
1035         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0xbc07a080; /* add %%fp, 256, %%fp */\n");
1036         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x81c62008; /* jmpl %%i0 + 8, %%g0 */\n");
1037         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x9c03a080; /* add %%sp, 256, %%sp */\n");
1038         break;
1039     case EM_SPARCV9:
1040         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x81c7e008; /* ret */\n");
1041         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x81e80000; /* restore */\n");
1042         break;
1043     default:
1044         error("unknown ELF architecture");
1045     }
1046     
1047     fprintf(outfile, "return gen_code_ptr -  gen_code_buf;\n");
1048     fprintf(outfile, "}\n\n");
1049
1050 /* generate gen_xxx functions */
1051 /* XXX: suppress the use of these functions to simplify code */
1052         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
1053             const char *name;
1054             name = strtab + sym->st_name;
1055             if (strstart(name, OP_PREFIX, NULL)) {
1056                 if (sym->st_shndx != (text_sec - shdr))
1057                     error("invalid section for opcode (0x%x)", sym->st_shndx);
1058                 gen_code(name, sym->st_value, sym->st_size, outfile, 
1059                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 0);
1060             }
1061         }
1062     }
1063
1064     close(fd);
1065     return 0;
1066 }
1067
1068 void usage(void)
1069 {
1070     printf("dyngen (c) 2003 Fabrice Bellard\n"
1071            "usage: dyngen [-o outfile] [-c] objfile\n"
1072            "Generate a dynamic code generator from an object file\n"
1073            "-c     output enum of operations\n"
1074            );
1075     exit(1);
1076 }
1077
1078 int main(int argc, char **argv)
1079 {
1080     int c, do_print_enum;
1081     const char *filename, *outfilename;
1082     FILE *outfile;
1083
1084     outfilename = "out.c";
1085     do_print_enum = 0;
1086     for(;;) {
1087         c = getopt(argc, argv, "ho:c");
1088         if (c == -1)
1089             break;
1090         switch(c) {
1091         case 'h':
1092             usage();
1093             break;
1094         case 'o':
1095             outfilename = optarg;
1096             break;
1097         case 'c':
1098             do_print_enum = 1;
1099             break;
1100         }
1101     }
1102     if (optind >= argc)
1103         usage();
1104     filename = argv[optind];
1105     outfile = fopen(outfilename, "w");
1106     if (!outfile)
1107         error("could not open '%s'", outfilename);
1108     load_elf(filename, outfile, do_print_enum);
1109     fclose(outfile);
1110     return 0;
1111 }