ia64 support - alpha support
[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 #else
69 #error unsupported CPU - please update the code
70 #endif
71
72 #include "elf.h"
73
74 #if ELF_CLASS == ELFCLASS32
75 typedef int32_t host_long;
76 typedef uint32_t host_ulong;
77 #define swabls(x) swab32s(x)
78 #else
79 typedef int64_t host_long;
80 typedef uint64_t host_ulong;
81 #define swabls(x) swab64s(x)
82 #endif
83
84 #include "thunk.h"
85
86 /* all dynamically generated functions begin with this code */
87 #define OP_PREFIX "op_"
88
89 int elf_must_swap(struct elfhdr *h)
90 {
91   union {
92       uint32_t i;
93       uint8_t b[4];
94   } swaptest;
95
96   swaptest.i = 1;
97   return (h->e_ident[EI_DATA] == ELFDATA2MSB) != 
98       (swaptest.b[0] == 0);
99 }
100   
101 void swab16s(uint16_t *p)
102 {
103     *p = bswap16(*p);
104 }
105
106 void swab32s(uint32_t *p)
107 {
108     *p = bswap32(*p);
109 }
110
111 void swab64s(uint64_t *p)
112 {
113     *p = bswap64(*p);
114 }
115
116 void elf_swap_ehdr(struct elfhdr *h)
117 {
118     swab16s(&h->e_type);                        /* Object file type */
119     swab16s(&h->        e_machine);             /* Architecture */
120     swab32s(&h->        e_version);             /* Object file version */
121     swabls(&h-> e_entry);               /* Entry point virtual address */
122     swabls(&h-> e_phoff);               /* Program header table file offset */
123     swabls(&h-> e_shoff);               /* Section header table file offset */
124     swab32s(&h->        e_flags);               /* Processor-specific flags */
125     swab16s(&h->        e_ehsize);              /* ELF header size in bytes */
126     swab16s(&h->        e_phentsize);           /* Program header table entry size */
127     swab16s(&h->        e_phnum);               /* Program header table entry count */
128     swab16s(&h->        e_shentsize);           /* Section header table entry size */
129     swab16s(&h->        e_shnum);               /* Section header table entry count */
130     swab16s(&h->        e_shstrndx);            /* Section header string table index */
131 }
132
133 void elf_swap_shdr(struct elf_shdr *h)
134 {
135   swab32s(&h->  sh_name);               /* Section name (string tbl index) */
136   swab32s(&h->  sh_type);               /* Section type */
137   swabls(&h->   sh_flags);              /* Section flags */
138   swabls(&h->   sh_addr);               /* Section virtual addr at execution */
139   swabls(&h->   sh_offset);             /* Section file offset */
140   swabls(&h->   sh_size);               /* Section size in bytes */
141   swab32s(&h->  sh_link);               /* Link to another section */
142   swab32s(&h->  sh_info);               /* Additional section information */
143   swabls(&h->   sh_addralign);          /* Section alignment */
144   swabls(&h->   sh_entsize);            /* Entry size if section holds table */
145 }
146
147 void elf_swap_phdr(struct elf_phdr *h)
148 {
149     swab32s(&h->p_type);                        /* Segment type */
150     swabls(&h->p_offset);               /* Segment file offset */
151     swabls(&h->p_vaddr);                /* Segment virtual address */
152     swabls(&h->p_paddr);                /* Segment physical address */
153     swabls(&h->p_filesz);               /* Segment size in file */
154     swabls(&h->p_memsz);                /* Segment size in memory */
155     swab32s(&h->p_flags);               /* Segment flags */
156     swabls(&h->p_align);                /* Segment alignment */
157 }
158
159 int do_swap;
160
161 uint16_t get16(uint16_t *p)
162 {
163     uint16_t val;
164     val = *p;
165     if (do_swap)
166         val = bswap16(val);
167     return val;
168 }
169
170 uint32_t get32(uint32_t *p)
171 {
172     uint32_t val;
173     val = *p;
174     if (do_swap)
175         val = bswap32(val);
176     return val;
177 }
178
179 void put16(uint16_t *p, uint16_t val)
180 {
181     if (do_swap)
182         val = bswap16(val);
183     *p = val;
184 }
185
186 void put32(uint32_t *p, uint32_t val)
187 {
188     if (do_swap)
189         val = bswap32(val);
190     *p = val;
191 }
192
193 void __attribute__((noreturn)) __attribute__((format (printf, 1, 2))) error(const char *fmt, ...)
194 {
195     va_list ap;
196     va_start(ap, fmt);
197     fprintf(stderr, "dyngen: ");
198     vfprintf(stderr, fmt, ap);
199     fprintf(stderr, "\n");
200     va_end(ap);
201     exit(1);
202 }
203
204
205 struct elf_shdr *find_elf_section(struct elf_shdr *shdr, int shnum, const char *shstr, 
206                                   const char *name)
207 {
208     int i;
209     const char *shname;
210     struct elf_shdr *sec;
211
212     for(i = 0; i < shnum; i++) {
213         sec = &shdr[i];
214         if (!sec->sh_name)
215             continue;
216         shname = shstr + sec->sh_name;
217         if (!strcmp(shname, name))
218             return sec;
219     }
220     return NULL;
221 }
222
223 void *load_data(int fd, long offset, unsigned int size)
224 {
225     char *data;
226
227     data = malloc(size);
228     if (!data)
229         return NULL;
230     lseek(fd, offset, SEEK_SET);
231     if (read(fd, data, size) != size) {
232         free(data);
233         return NULL;
234     }
235     return data;
236 }
237
238 int strstart(const char *str, const char *val, const char **ptr)
239 {
240     const char *p, *q;
241     p = str;
242     q = val;
243     while (*q != '\0') {
244         if (*p != *q)
245             return 0;
246         p++;
247         q++;
248     }
249     if (ptr)
250         *ptr = p;
251     return 1;
252 }
253
254 #define MAX_ARGS 3
255
256 /* generate op code */
257 void gen_code(const char *name, host_ulong offset, host_ulong size, 
258               FILE *outfile, uint8_t *text, ELF_RELOC *relocs, int nb_relocs, int reloc_sh_type,
259               ElfW(Sym) *symtab, char *strtab, int gen_switch)
260 {
261     int copy_size = 0;
262     uint8_t *p_start, *p_end;
263     int nb_args, i, n;
264     uint8_t args_present[MAX_ARGS];
265     const char *sym_name, *p;
266     ELF_RELOC *rel;
267
268     /* compute exact size excluding return instruction */
269     p_start = text + offset;
270     p_end = p_start + size;
271     switch(ELF_ARCH) {
272     case EM_386:
273         {
274             uint8_t *p;
275             p = p_end - 1;
276             if (p == p_start)
277                 error("empty code for %s", name);
278             if (p[0] != 0xc3)
279                 error("ret expected at the end of %s", name);
280             copy_size = p - p_start;
281         }
282         break;
283     case EM_PPC:
284         {
285             uint8_t *p;
286             p = (void *)(p_end - 4);
287             if (p == p_start)
288                 error("empty code for %s", name);
289             if (get32((uint32_t *)p) != 0x4e800020)
290                 error("blr expected at the end of %s", name);
291             copy_size = p - p_start;
292         }
293         break;
294     case EM_S390:
295         {
296             uint8_t *p;
297             p = (void *)(p_end - 2);
298             if (p == p_start)
299                 error("empty code for %s", name);
300             if (get16((uint16_t *)p) != 0x07fe && get16((uint16_t *)p) != 0x07f4)
301                 error("br %%r14 expected at the end of %s", name);
302             copy_size = p - p_start;
303         }
304         break;
305     case EM_ALPHA:
306         {
307             uint8_t *p;
308             p = p_end - 4;
309             if (p == p_start)
310                 error("empty code for %s", name);
311             if (get32((uint32_t *)p) != 0x6bfa8001)
312                 error("ret expected at the end of %s", name);
313             copy_size = p - p_start;        
314         }
315         break;
316     case EM_IA_64:
317         {
318             uint8_t *p;
319             p = (void *)(p_end - 4);
320             if (p == p_start)
321                 error("empty code for %s", name);
322             /* br.ret.sptk.many b0;; */
323             /* 08 00 84 00 */
324             if (get32((uint32_t *)p) != 0x00840008)
325                 error("br.ret.sptk.many b0;; expected at the end of %s", name);
326             copy_size = p - p_start;
327         }
328         break;
329     default:
330         error("unknown ELF architecture");
331     }
332
333     /* compute the number of arguments by looking at the relocations */
334     for(i = 0;i < MAX_ARGS; i++)
335         args_present[i] = 0;
336
337     for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
338         if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
339             sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
340             if (strstart(sym_name, "__op_param", &p)) {
341                 n = strtoul(p, NULL, 10);
342                 if (n >= MAX_ARGS)
343                     error("too many arguments in %s", name);
344                 args_present[n - 1] = 1;
345             }
346         }
347     }
348     
349     nb_args = 0;
350     while (nb_args < MAX_ARGS && args_present[nb_args])
351         nb_args++;
352     for(i = nb_args; i < MAX_ARGS; i++) {
353         if (args_present[i])
354             error("inconsistent argument numbering in %s", name);
355     }
356
357     if (gen_switch == 2) {
358         fprintf(outfile, "DEF(%s, %d)\n", name + 3, nb_args);
359     } else if (gen_switch == 1) {
360
361         /* output C code */
362         fprintf(outfile, "case INDEX_%s: {\n", name);
363         if (nb_args > 0) {
364             fprintf(outfile, "    long ");
365             for(i = 0; i < nb_args; i++) {
366                 if (i != 0)
367                     fprintf(outfile, ", ");
368                 fprintf(outfile, "param%d", i + 1);
369             }
370             fprintf(outfile, ";\n");
371         }
372         fprintf(outfile, "    extern void %s();\n", name);
373
374         for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
375             if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
376                 sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
377                 if (!strstart(sym_name, "__op_param", &p)) {
378                     fprintf(outfile, "extern char %s;\n", sym_name);
379                 }
380             }
381         }
382
383         fprintf(outfile, "    memcpy(gen_code_ptr, &%s, %d);\n", name, copy_size);
384         for(i = 0; i < nb_args; i++) {
385             fprintf(outfile, "    param%d = *opparam_ptr++;\n", i + 1);
386         }
387
388         /* patch relocations */
389 #if defined(HOST_I386)
390             {
391                 char name[256];
392                 int type;
393                 int addend;
394                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
395                 if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
396                     sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
397                     if (strstart(sym_name, "__op_param", &p)) {
398                         snprintf(name, sizeof(name), "param%s", p);
399                     } else {
400                         snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
401                     }
402                     type = ELF32_R_TYPE(rel->r_info);
403                     addend = get32((uint32_t *)(text + rel->r_offset));
404                     switch(type) {
405                     case R_386_32:
406                         fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
407                                 rel->r_offset - offset, name, addend);
408                         break;
409                     case R_386_PC32:
410                         fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s - (long)(gen_code_ptr + %d) + %d;\n", 
411                                 rel->r_offset - offset, name, rel->r_offset - offset, addend);
412                         break;
413                     default:
414                         error("unsupported i386 relocation (%d)", type);
415                     }
416                 }
417                 }
418             }
419 #elif defined(HOST_PPC)
420             {
421                 char name[256];
422                 int type;
423                 int addend;
424                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
425                     if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
426                         sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
427                         if (strstart(sym_name, "__op_param", &p)) {
428                             snprintf(name, sizeof(name), "param%s", p);
429                         } else {
430                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
431                         }
432                         type = ELF32_R_TYPE(rel->r_info);
433                         addend = rel->r_addend;
434                         switch(type) {
435                         case R_PPC_ADDR32:
436                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
437                                     rel->r_offset - offset, name, addend);
438                             break;
439                         case R_PPC_ADDR16_LO:
440                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d);\n", 
441                                     rel->r_offset - offset, name, addend);
442                             break;
443                         case R_PPC_ADDR16_HI:
444                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d) >> 16;\n", 
445                                     rel->r_offset - offset, name, addend);
446                             break;
447                         case R_PPC_ADDR16_HA:
448                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = (%s + %d + 0x8000) >> 16;\n", 
449                                     rel->r_offset - offset, name, addend);
450                             break;
451                         case R_PPC_REL24:
452                             /* warning: must be at 32 MB distancy */
453                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = (*(uint32_t *)(gen_code_ptr + %d) & ~0x03fffffc) | ((%s - (long)(gen_code_ptr + %d) + %d) & 0x03fffffc);\n", 
454                                     rel->r_offset - offset, rel->r_offset - offset, name, rel->r_offset - offset, addend);
455                             break;
456                         default:
457                             error("unsupported powerpc relocation (%d)", type);
458                         }
459                     }
460                 }
461             }
462 #elif defined(HOST_S390)
463             {
464                 char name[256];
465                 int type;
466                 int addend;
467                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
468                     if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
469                         sym_name = strtab + symtab[ELFW(R_SYM)(rel->r_info)].st_name;
470                         if (strstart(sym_name, "__op_param", &p)) {
471                             snprintf(name, sizeof(name), "param%s", p);
472                         } else {
473                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
474                         }
475                         type = ELF32_R_TYPE(rel->r_info);
476                         addend = rel->r_addend;
477                         switch(type) {
478                         case R_390_32:
479                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = %s + %d;\n", 
480                                     rel->r_offset - offset, name, addend);
481                             break;
482                         case R_390_16:
483                             fprintf(outfile, "    *(uint16_t *)(gen_code_ptr + %d) = %s + %d;\n", 
484                                     rel->r_offset - offset, name, addend);
485                             break;
486                         case R_390_8:
487                             fprintf(outfile, "    *(uint8_t *)(gen_code_ptr + %d) = %s + %d;\n", 
488                                     rel->r_offset - offset, name, addend);
489                             break;
490                         default:
491                             error("unsupported s390 relocation (%d)", type);
492                         }
493                     }
494                 }
495             }
496 #elif defined(HOST_ALPHA)
497             {
498                 for (i = 0, rel = relocs; i < nb_relocs; i++, rel++) {
499                     if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
500                         int type;
501                         sym_name = strtab + symtab[ELF64_R_SYM(rel->r_info)].st_name;
502                         
503                         type = ELF64_R_TYPE(rel->r_info);
504                         switch (type) {
505                         case R_ALPHA_GPDISP:
506                             /* Instructions to set up the gp can be nopped, since we keep it current
507                                all the time.  FIXME assert that target is really gp  */
508                             fprintf(outfile, "    *(uint32_t *)(gen_code_ptr + %d) = 0x2ffe0000; /* unop */\n",
509                                     rel->r_offset - offset);
510                             break;
511                         case R_ALPHA_LITUSE:
512                             /* jsr to literal hint. Could be used to optimize to bsr. Ignore for
513                                now, since some called functions (libc) need pv to be set up.  */
514                             break;
515                         case R_ALPHA_HINT:
516                             /* Branch target prediction hint. Ignore for now.  Should be already
517                                correct for in-function jumps.  */
518                             break;
519                         case R_ALPHA_LITERAL:
520                             /* Load a literal from the GOT relative to the gp.  Need to patch the
521                                16-bit immediate offset.  */
522                             fprintf(outfile, "    *(int16_t *)(gen_code_ptr + %d) = gp - (long)(&%s);\n",
523                                     rel->r_offset - offset, name);
524                             break;
525                         default:
526                             error("unsupported Alpha relocation (%d)", type);
527                         }
528                     }
529                 }
530             }
531 #elif defined(HOST_IA64)
532             {
533                 char name[256];
534                 int type;
535                 int addend;
536                 for(i = 0, rel = relocs;i < nb_relocs; i++, rel++) {
537                     if (rel->r_offset >= offset && rel->r_offset < offset + copy_size) {
538                         sym_name = strtab + symtab[ELF64_R_SYM(rel->r_info)].st_name;
539                         if (strstart(sym_name, "__op_param", &p)) {
540                             snprintf(name, sizeof(name), "param%s", p);
541                         } else {
542                             snprintf(name, sizeof(name), "(long)(&%s)", sym_name);
543                         }
544                         type = ELF64_R_TYPE(rel->r_info);
545                         addend = rel->r_addend;
546                         switch(type) {
547                         case R_IA64_LTOFF22:
548                             error("must implemnt R_IA64_LTOFF22 relocation");
549                         case R_IA64_PCREL21B:
550                             error("must implemnt R_IA64_PCREL21B relocation");
551                         default:
552                             error("unsupported ia64 relocation (%d)", type);
553                         }
554                     }
555                 }
556             }
557 #else
558 #error unsupported CPU
559 #endif
560         fprintf(outfile, "    gen_code_ptr += %d;\n", copy_size);
561         fprintf(outfile, "}\n");
562         fprintf(outfile, "break;\n\n");
563     } else {
564         fprintf(outfile, "static inline void gen_%s(", name);
565         if (nb_args == 0) {
566             fprintf(outfile, "void");
567         } else {
568             for(i = 0; i < nb_args; i++) {
569                 if (i != 0)
570                     fprintf(outfile, ", ");
571                 fprintf(outfile, "long param%d", i + 1);
572             }
573         }
574         fprintf(outfile, ")\n");
575         fprintf(outfile, "{\n");
576         for(i = 0; i < nb_args; i++) {
577             fprintf(outfile, "    *gen_opparam_ptr++ = param%d;\n", i + 1);
578         }
579         fprintf(outfile, "    *gen_opc_ptr++ = INDEX_%s;\n", name);
580         fprintf(outfile, "}\n\n");
581     }
582 }
583
584 /* load an elf object file */
585 int load_elf(const char *filename, FILE *outfile, int do_print_enum)
586 {
587     int fd;
588     struct elfhdr ehdr;
589     struct elf_shdr *sec, *shdr, *symtab_sec, *strtab_sec, *text_sec;
590     int i, j, nb_syms;
591     ElfW(Sym) *symtab, *sym;
592     char *shstr, *strtab;
593     uint8_t *text;
594     void *relocs;
595     int nb_relocs, reloc_sh_type;
596     
597     fd = open(filename, O_RDONLY);
598     if (fd < 0) 
599         error("can't open file '%s'", filename);
600     
601     /* Read ELF header.  */
602     if (read(fd, &ehdr, sizeof (ehdr)) != sizeof (ehdr))
603         error("unable to read file header");
604
605     /* Check ELF identification.  */
606     if (ehdr.e_ident[EI_MAG0] != ELFMAG0
607      || ehdr.e_ident[EI_MAG1] != ELFMAG1
608      || ehdr.e_ident[EI_MAG2] != ELFMAG2
609      || ehdr.e_ident[EI_MAG3] != ELFMAG3
610      || ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
611         error("bad ELF header");
612     }
613
614     do_swap = elf_must_swap(&ehdr);
615     if (do_swap)
616         elf_swap_ehdr(&ehdr);
617     if (ehdr.e_ident[EI_CLASS] != ELF_CLASS)
618         error("Unsupported ELF class");
619     if (ehdr.e_type != ET_REL)
620         error("ELF object file expected");
621     if (ehdr.e_version != EV_CURRENT)
622         error("Invalid ELF version");
623     if (!elf_check_arch(ehdr.e_machine))
624         error("Unsupported CPU (e_machine=%d)", ehdr.e_machine);
625
626     /* read section headers */
627     shdr = load_data(fd, ehdr.e_shoff, ehdr.e_shnum * sizeof(struct elf_shdr));
628     if (do_swap) {
629         for(i = 0; i < ehdr.e_shnum; i++) {
630             elf_swap_shdr(&shdr[i]);
631         }
632     }
633
634     sec = &shdr[ehdr.e_shstrndx];
635     shstr = load_data(fd, sec->sh_offset, sec->sh_size);
636
637     /* text section */
638
639     text_sec = find_elf_section(shdr, ehdr.e_shnum, shstr, ".text");
640     if (!text_sec)
641         error("could not find .text section");
642     text = load_data(fd, text_sec->sh_offset, text_sec->sh_size);
643
644     /* find text relocations, if any */
645     nb_relocs = 0;
646     relocs = NULL;
647     reloc_sh_type = 0;
648     for(i = 0; i < ehdr.e_shnum; i++) {
649         sec = &shdr[i];
650         if ((sec->sh_type == SHT_REL || sec->sh_type == SHT_RELA) &&
651             sec->sh_info == (text_sec - shdr)) {
652             reloc_sh_type = sec->sh_type;
653             relocs = load_data(fd, sec->sh_offset, sec->sh_size);
654             nb_relocs = sec->sh_size / sec->sh_entsize;
655             if (do_swap) {
656                 if (sec->sh_type == SHT_REL) {
657                     ElfW(Rel) *rel = relocs;
658                     for(j = 0, rel = relocs; j < nb_relocs; j++, rel++) {
659                         swabls(&rel->r_offset);
660                         swabls(&rel->r_info);
661                     }
662                 } else {
663                     ElfW(Rela) *rel = relocs;
664                     for(j = 0, rel = relocs; j < nb_relocs; j++, rel++) {
665                         swabls(&rel->r_offset);
666                         swabls(&rel->r_info);
667                         swabls(&rel->r_addend);
668                     }
669                 }
670             }
671             break;
672         }
673     }
674
675     symtab_sec = find_elf_section(shdr, ehdr.e_shnum, shstr, ".symtab");
676     if (!symtab_sec)
677         error("could not find .symtab section");
678     strtab_sec = &shdr[symtab_sec->sh_link];
679
680     symtab = load_data(fd, symtab_sec->sh_offset, symtab_sec->sh_size);
681     strtab = load_data(fd, strtab_sec->sh_offset, strtab_sec->sh_size);
682     
683     nb_syms = symtab_sec->sh_size / sizeof(ElfW(Sym));
684     if (do_swap) {
685         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
686             swab32s(&sym->st_name);
687             swabls(&sym->st_value);
688             swabls(&sym->st_size);
689             swab16s(&sym->st_shndx);
690         }
691     }
692
693     if (do_print_enum) {
694         fprintf(outfile, "DEF(end, 0)\n");
695         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
696             const char *name, *p;
697             name = strtab + sym->st_name;
698             if (strstart(name, OP_PREFIX, &p)) {
699                 gen_code(name, sym->st_value, sym->st_size, outfile, 
700                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 2);
701             }
702         }
703     } else {
704         /* generate big code generation switch */
705 #ifdef HOST_ALPHA
706         fprintf(outfile, "register long gp asm(\"%%$29\");\n");
707 #endif
708 fprintf(outfile,
709 "int dyngen_code(uint8_t *gen_code_buf,\n"
710 "                const uint16_t *opc_buf, const uint32_t *opparam_buf)\n"
711 "{\n"
712 "    uint8_t *gen_code_ptr;\n"
713 "    const uint16_t *opc_ptr;\n"
714 "    const uint32_t *opparam_ptr;\n"
715 "    gen_code_ptr = gen_code_buf;\n"
716 "    opc_ptr = opc_buf;\n"
717 "    opparam_ptr = opparam_buf;\n"
718 "    for(;;) {\n"
719 "        switch(*opc_ptr++) {\n"
720 );
721
722         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
723             const char *name;
724             name = strtab + sym->st_name;
725             if (strstart(name, OP_PREFIX, NULL)) {
726 #if 0
727                 printf("%4d: %s pos=0x%08x len=%d\n", 
728                        i, name, sym->st_value, sym->st_size);
729 #endif
730                 if (sym->st_shndx != (text_sec - shdr))
731                     error("invalid section for opcode (0x%x)", sym->st_shndx);
732                 gen_code(name, sym->st_value, sym->st_size, outfile, 
733                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 1);
734             }
735         }
736
737 fprintf(outfile,
738 "        default:\n"
739 "            goto the_end;\n"
740 "        }\n"
741 "    }\n"
742 " the_end:\n"
743 );
744
745 /* generate a return */ 
746     switch(ELF_ARCH) {
747     case EM_386:
748         fprintf(outfile, "*gen_code_ptr++ = 0xc3; /* ret */\n");
749         break;
750     case EM_PPC:
751         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x4e800020; /* blr */\n");
752         break;
753     case EM_S390:
754         fprintf(outfile, "*((uint16_t *)gen_code_ptr)++ = 0x07fe; /* br %%r14 */\n");
755         break;
756     case EM_ALPHA:
757         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x6bfa8001; /* ret */\n");
758         break;
759     case EM_IA_64:
760         fprintf(outfile, "*((uint32_t *)gen_code_ptr)++ = 0x00840008; /* br.ret.sptk.many b0;; */\n");
761         break;
762     default:
763         error("unknown ELF architecture");
764     }
765     
766     fprintf(outfile, "return gen_code_ptr -  gen_code_buf;\n");
767     fprintf(outfile, "}\n\n");
768
769 /* generate gen_xxx functions */
770 /* XXX: suppress the use of these functions to simplify code */
771         for(i = 0, sym = symtab; i < nb_syms; i++, sym++) {
772             const char *name;
773             name = strtab + sym->st_name;
774             if (strstart(name, OP_PREFIX, NULL)) {
775                 if (sym->st_shndx != (text_sec - shdr))
776                     error("invalid section for opcode (0x%x)", sym->st_shndx);
777                 gen_code(name, sym->st_value, sym->st_size, outfile, 
778                          text, relocs, nb_relocs, reloc_sh_type, symtab, strtab, 0);
779             }
780         }
781     }
782
783     close(fd);
784     return 0;
785 }
786
787 void usage(void)
788 {
789     printf("dyngen (c) 2003 Fabrice Bellard\n"
790            "usage: dyngen [-o outfile] [-c] objfile\n"
791            "Generate a dynamic code generator from an object file\n"
792            "-c     output enum of operations\n"
793            );
794     exit(1);
795 }
796
797 int main(int argc, char **argv)
798 {
799     int c, do_print_enum;
800     const char *filename, *outfilename;
801     FILE *outfile;
802
803     outfilename = "out.c";
804     do_print_enum = 0;
805     for(;;) {
806         c = getopt(argc, argv, "ho:c");
807         if (c == -1)
808             break;
809         switch(c) {
810         case 'h':
811             usage();
812             break;
813         case 'o':
814             outfilename = optarg;
815             break;
816         case 'c':
817             do_print_enum = 1;
818             break;
819         }
820     }
821     if (optind >= argc)
822         usage();
823     filename = argv[optind];
824     outfile = fopen(outfilename, "w");
825     if (!outfile)
826         error("could not open '%s'", outfilename);
827     load_elf(filename, outfile, do_print_enum);
828     fclose(outfile);
829     return 0;
830 }