Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / libvpx / source / libvpx / build / make / obj_int_extract.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16
17 #include "vpx_config.h"
18 #include "vpx/vpx_integer.h"
19
20 typedef enum {
21   OUTPUT_FMT_PLAIN,
22   OUTPUT_FMT_RVDS,
23   OUTPUT_FMT_GAS,
24   OUTPUT_FMT_C_HEADER,
25 } output_fmt_t;
26
27 int log_msg(const char *fmt, ...) {
28   int res;
29   va_list ap;
30   va_start(ap, fmt);
31   res = vfprintf(stderr, fmt, ap);
32   va_end(ap);
33   return res;
34 }
35
36 #if defined(__GNUC__) && __GNUC__
37 #if defined(__MACH__)
38
39 #include <mach-o/loader.h>
40 #include <mach-o/nlist.h>
41
42 int print_macho_equ(output_fmt_t mode, uint8_t* name, int val) {
43   switch (mode) {
44     case OUTPUT_FMT_RVDS:
45       printf("%-40s EQU %5d\n", name, val);
46       return 0;
47     case OUTPUT_FMT_GAS:
48       printf(".set %-40s, %5d\n", name, val);
49       return 0;
50     case OUTPUT_FMT_C_HEADER:
51       printf("#define %-40s %5d\n", name, val);
52       return 0;
53     default:
54       log_msg("Unsupported mode: %d", mode);
55       return 1;
56   }
57 }
58
59 int parse_macho(uint8_t *base_buf, size_t sz, output_fmt_t mode) {
60   int i, j;
61   struct mach_header header;
62   uint8_t *buf = base_buf;
63   int base_data_section = 0;
64   int bits = 0;
65
66   /* We can read in mach_header for 32 and 64 bit architectures
67    * because it's identical to mach_header_64 except for the last
68    * element (uint32_t reserved), which we don't use. Then, when
69    * we know which architecture we're looking at, increment buf
70    * appropriately.
71    */
72   memcpy(&header, buf, sizeof(struct mach_header));
73
74   if (header.magic == MH_MAGIC) {
75     if (header.cputype == CPU_TYPE_ARM
76         || header.cputype == CPU_TYPE_X86) {
77       bits = 32;
78       buf += sizeof(struct mach_header);
79     } else {
80       log_msg("Bad cputype for object file. Currently only tested for CPU_TYPE_[ARM|X86].\n");
81       goto bail;
82     }
83   } else if (header.magic == MH_MAGIC_64) {
84     if (header.cputype == CPU_TYPE_X86_64) {
85       bits = 64;
86       buf += sizeof(struct mach_header_64);
87     } else {
88       log_msg("Bad cputype for object file. Currently only tested for CPU_TYPE_X86_64.\n");
89       goto bail;
90     }
91   } else {
92     log_msg("Bad magic number for object file. 0x%x or 0x%x expected, 0x%x found.\n",
93             MH_MAGIC, MH_MAGIC_64, header.magic);
94     goto bail;
95   }
96
97   if (header.filetype != MH_OBJECT) {
98     log_msg("Bad filetype for object file. Currently only tested for MH_OBJECT.\n");
99     goto bail;
100   }
101
102   for (i = 0; i < header.ncmds; i++) {
103     struct load_command lc;
104
105     memcpy(&lc, buf, sizeof(struct load_command));
106
107     if (lc.cmd == LC_SEGMENT) {
108       uint8_t *seg_buf = buf;
109       struct section s;
110       struct segment_command seg_c;
111
112       memcpy(&seg_c, seg_buf, sizeof(struct segment_command));
113       seg_buf += sizeof(struct segment_command);
114
115       /* Although each section is given it's own offset, nlist.n_value
116        * references the offset of the first section. This isn't
117        * apparent without debug information because the offset of the
118        * data section is the same as the first section. However, with
119        * debug sections mixed in, the offset of the debug section
120        * increases but n_value still references the first section.
121        */
122       if (seg_c.nsects < 1) {
123         log_msg("Not enough sections\n");
124         goto bail;
125       }
126
127       memcpy(&s, seg_buf, sizeof(struct section));
128       base_data_section = s.offset;
129     } else if (lc.cmd == LC_SEGMENT_64) {
130       uint8_t *seg_buf = buf;
131       struct section_64 s;
132       struct segment_command_64 seg_c;
133
134       memcpy(&seg_c, seg_buf, sizeof(struct segment_command_64));
135       seg_buf += sizeof(struct segment_command_64);
136
137       /* Explanation in LG_SEGMENT */
138       if (seg_c.nsects < 1) {
139         log_msg("Not enough sections\n");
140         goto bail;
141       }
142
143       memcpy(&s, seg_buf, sizeof(struct section_64));
144       base_data_section = s.offset;
145     } else if (lc.cmd == LC_SYMTAB) {
146       if (base_data_section != 0) {
147         struct symtab_command sc;
148         uint8_t *sym_buf = base_buf;
149         uint8_t *str_buf = base_buf;
150
151         memcpy(&sc, buf, sizeof(struct symtab_command));
152
153         if (sc.cmdsize != sizeof(struct symtab_command)) {
154           log_msg("Can't find symbol table!\n");
155           goto bail;
156         }
157
158         sym_buf += sc.symoff;
159         str_buf += sc.stroff;
160
161         for (j = 0; j < sc.nsyms; j++) {
162           /* Location of string is cacluated each time from the
163            * start of the string buffer.  On darwin the symbols
164            * are prefixed by "_", so we bump the pointer by 1.
165            * The target value is defined as an int in *_asm_*_offsets.c,
166            * which is 4 bytes on all targets we currently use.
167            */
168           if (bits == 32) {
169             struct nlist nl;
170             int val;
171
172             memcpy(&nl, sym_buf, sizeof(struct nlist));
173             sym_buf += sizeof(struct nlist);
174
175             memcpy(&val, base_buf + base_data_section + nl.n_value,
176                    sizeof(val));
177             print_macho_equ(mode, str_buf + nl.n_un.n_strx + 1, val);
178           } else { /* if (bits == 64) */
179             struct nlist_64 nl;
180             int val;
181
182             memcpy(&nl, sym_buf, sizeof(struct nlist_64));
183             sym_buf += sizeof(struct nlist_64);
184
185             memcpy(&val, base_buf + base_data_section + nl.n_value,
186                    sizeof(val));
187             print_macho_equ(mode, str_buf + nl.n_un.n_strx + 1, val);
188           }
189         }
190       }
191     }
192
193     buf += lc.cmdsize;
194   }
195
196   return 0;
197 bail:
198   return 1;
199
200 }
201
202 #elif defined(__ELF__)
203 #include "elf.h"
204
205 #define COPY_STRUCT(dst, buf, ofst, sz) do {\
206     if(ofst + sizeof((*(dst))) > sz) goto bail;\
207     memcpy(dst, buf+ofst, sizeof((*(dst))));\
208   } while(0)
209
210 #define ENDIAN_ASSIGN(val, memb) do {\
211     if(!elf->le_data) {log_msg("Big Endian data not supported yet!\n");goto bail;}\
212     (val) = (memb);\
213   } while(0)
214
215 #define ENDIAN_ASSIGN_IN_PLACE(memb) do {\
216     ENDIAN_ASSIGN(memb, memb);\
217   } while(0)
218
219 typedef struct {
220   uint8_t      *buf; /* Buffer containing ELF data */
221   size_t        sz;  /* Buffer size */
222   int           le_data; /* Data is little-endian */
223   unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
224   int           bits; /* 32 or 64 */
225   Elf32_Ehdr    hdr32;
226   Elf64_Ehdr    hdr64;
227 } elf_obj_t;
228
229 int parse_elf_header(elf_obj_t *elf) {
230   int res;
231   /* Verify ELF Magic numbers */
232   COPY_STRUCT(&elf->e_ident, elf->buf, 0, elf->sz);
233   res = elf->e_ident[EI_MAG0] == ELFMAG0;
234   res &= elf->e_ident[EI_MAG1] == ELFMAG1;
235   res &= elf->e_ident[EI_MAG2] == ELFMAG2;
236   res &= elf->e_ident[EI_MAG3] == ELFMAG3;
237   res &= elf->e_ident[EI_CLASS] == ELFCLASS32
238          || elf->e_ident[EI_CLASS] == ELFCLASS64;
239   res &= elf->e_ident[EI_DATA] == ELFDATA2LSB;
240
241   if (!res) goto bail;
242
243   elf->le_data = elf->e_ident[EI_DATA] == ELFDATA2LSB;
244
245   /* Read in relevant values */
246   if (elf->e_ident[EI_CLASS] == ELFCLASS32) {
247     elf->bits = 32;
248     COPY_STRUCT(&elf->hdr32, elf->buf, 0, elf->sz);
249
250     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_type);
251     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_machine);
252     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_version);
253     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_entry);
254     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_phoff);
255     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_shoff);
256     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_flags);
257     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_ehsize);
258     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_phentsize);
259     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_phnum);
260     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_shentsize);
261     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_shnum);
262     ENDIAN_ASSIGN_IN_PLACE(elf->hdr32.e_shstrndx);
263   } else { /* if (elf->e_ident[EI_CLASS] == ELFCLASS64) */
264     elf->bits = 64;
265     COPY_STRUCT(&elf->hdr64, elf->buf, 0, elf->sz);
266
267     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_type);
268     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_machine);
269     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_version);
270     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_entry);
271     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_phoff);
272     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_shoff);
273     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_flags);
274     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_ehsize);
275     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_phentsize);
276     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_phnum);
277     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_shentsize);
278     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_shnum);
279     ENDIAN_ASSIGN_IN_PLACE(elf->hdr64.e_shstrndx);
280   }
281
282   return 0;
283 bail:
284   log_msg("Failed to parse ELF file header");
285   return 1;
286 }
287
288 int parse_elf_section(elf_obj_t *elf, int idx, Elf32_Shdr *hdr32, Elf64_Shdr *hdr64) {
289   if (hdr32) {
290     if (idx >= elf->hdr32.e_shnum)
291       goto bail;
292
293     COPY_STRUCT(hdr32, elf->buf, elf->hdr32.e_shoff + idx * elf->hdr32.e_shentsize,
294                 elf->sz);
295     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_name);
296     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_type);
297     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_flags);
298     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_addr);
299     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_offset);
300     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_size);
301     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_link);
302     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_info);
303     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_addralign);
304     ENDIAN_ASSIGN_IN_PLACE(hdr32->sh_entsize);
305   } else { /* if (hdr64) */
306     if (idx >= elf->hdr64.e_shnum)
307       goto bail;
308
309     COPY_STRUCT(hdr64, elf->buf, elf->hdr64.e_shoff + idx * elf->hdr64.e_shentsize,
310                 elf->sz);
311     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_name);
312     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_type);
313     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_flags);
314     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_addr);
315     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_offset);
316     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_size);
317     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_link);
318     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_info);
319     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_addralign);
320     ENDIAN_ASSIGN_IN_PLACE(hdr64->sh_entsize);
321   }
322
323   return 0;
324 bail:
325   return 1;
326 }
327
328 const char *parse_elf_string_table(elf_obj_t *elf, int s_idx, int idx) {
329   if (elf->bits == 32) {
330     Elf32_Shdr shdr;
331
332     if (parse_elf_section(elf, s_idx, &shdr, NULL)) {
333       log_msg("Failed to parse ELF string table: section %d, index %d\n",
334               s_idx, idx);
335       return "";
336     }
337
338     return (char *)(elf->buf + shdr.sh_offset + idx);
339   } else { /* if (elf->bits == 64) */
340     Elf64_Shdr shdr;
341
342     if (parse_elf_section(elf, s_idx, NULL, &shdr)) {
343       log_msg("Failed to parse ELF string table: section %d, index %d\n",
344               s_idx, idx);
345       return "";
346     }
347
348     return (char *)(elf->buf + shdr.sh_offset + idx);
349   }
350 }
351
352 int parse_elf_symbol(elf_obj_t *elf, unsigned int ofst, Elf32_Sym *sym32, Elf64_Sym *sym64) {
353   if (sym32) {
354     COPY_STRUCT(sym32, elf->buf, ofst, elf->sz);
355     ENDIAN_ASSIGN_IN_PLACE(sym32->st_name);
356     ENDIAN_ASSIGN_IN_PLACE(sym32->st_value);
357     ENDIAN_ASSIGN_IN_PLACE(sym32->st_size);
358     ENDIAN_ASSIGN_IN_PLACE(sym32->st_info);
359     ENDIAN_ASSIGN_IN_PLACE(sym32->st_other);
360     ENDIAN_ASSIGN_IN_PLACE(sym32->st_shndx);
361   } else { /* if (sym64) */
362     COPY_STRUCT(sym64, elf->buf, ofst, elf->sz);
363     ENDIAN_ASSIGN_IN_PLACE(sym64->st_name);
364     ENDIAN_ASSIGN_IN_PLACE(sym64->st_value);
365     ENDIAN_ASSIGN_IN_PLACE(sym64->st_size);
366     ENDIAN_ASSIGN_IN_PLACE(sym64->st_info);
367     ENDIAN_ASSIGN_IN_PLACE(sym64->st_other);
368     ENDIAN_ASSIGN_IN_PLACE(sym64->st_shndx);
369   }
370   return 0;
371 bail:
372   return 1;
373 }
374
375 int parse_elf(uint8_t *buf, size_t sz, output_fmt_t mode) {
376   elf_obj_t    elf;
377   unsigned int ofst;
378   int          i;
379   Elf32_Off    strtab_off32;
380   Elf64_Off    strtab_off64; /* save String Table offset for later use */
381
382   memset(&elf, 0, sizeof(elf));
383   elf.buf = buf;
384   elf.sz = sz;
385
386   /* Parse Header */
387   if (parse_elf_header(&elf))
388     goto bail;
389
390   if (elf.bits == 32) {
391     Elf32_Shdr shdr;
392     for (i = 0; i < elf.hdr32.e_shnum; i++) {
393       parse_elf_section(&elf, i, &shdr, NULL);
394
395       if (shdr.sh_type == SHT_STRTAB) {
396         char strtsb_name[128];
397
398         strcpy(strtsb_name, (char *)(elf.buf + shdr.sh_offset + shdr.sh_name));
399
400         if (!(strcmp(strtsb_name, ".shstrtab"))) {
401           /* log_msg("found section: %s\n", strtsb_name); */
402           strtab_off32 = shdr.sh_offset;
403           break;
404         }
405       }
406     }
407   } else { /* if (elf.bits == 64) */
408     Elf64_Shdr shdr;
409     for (i = 0; i < elf.hdr64.e_shnum; i++) {
410       parse_elf_section(&elf, i, NULL, &shdr);
411
412       if (shdr.sh_type == SHT_STRTAB) {
413         char strtsb_name[128];
414
415         strcpy(strtsb_name, (char *)(elf.buf + shdr.sh_offset + shdr.sh_name));
416
417         if (!(strcmp(strtsb_name, ".shstrtab"))) {
418           /* log_msg("found section: %s\n", strtsb_name); */
419           strtab_off64 = shdr.sh_offset;
420           break;
421         }
422       }
423     }
424   }
425
426   /* Parse all Symbol Tables */
427   if (elf.bits == 32) {
428     Elf32_Shdr shdr;
429     for (i = 0; i < elf.hdr32.e_shnum; i++) {
430       parse_elf_section(&elf, i, &shdr, NULL);
431
432       if (shdr.sh_type == SHT_SYMTAB) {
433         for (ofst = shdr.sh_offset;
434              ofst < shdr.sh_offset + shdr.sh_size;
435              ofst += shdr.sh_entsize) {
436           Elf32_Sym sym;
437
438           parse_elf_symbol(&elf, ofst, &sym, NULL);
439
440           /* For all OBJECTS (data objects), extract the value from the
441            * proper data segment.
442            */
443           /* if (ELF32_ST_TYPE(sym.st_info) == STT_OBJECT && sym.st_name)
444               log_msg("found data object %s\n",
445                       parse_elf_string_table(&elf,
446                                              shdr.sh_link,
447                                              sym.st_name));
448            */
449
450           if (ELF32_ST_TYPE(sym.st_info) == STT_OBJECT
451               && sym.st_size == 4) {
452             Elf32_Shdr dhdr;
453             int val = 0;
454             char section_name[128];
455
456             parse_elf_section(&elf, sym.st_shndx, &dhdr, NULL);
457
458             /* For explanition - refer to _MSC_VER version of code */
459             strcpy(section_name, (char *)(elf.buf + strtab_off32 + dhdr.sh_name));
460             /* log_msg("Section_name: %s, Section_type: %d\n", section_name, dhdr.sh_type); */
461
462             if (strcmp(section_name, ".bss")) {
463               if (sizeof(val) != sym.st_size) {
464                 /* The target value is declared as an int in
465                  * *_asm_*_offsets.c, which is 4 bytes on all
466                  * targets we currently use. Complain loudly if
467                  * this is not true.
468                  */
469                 log_msg("Symbol size is wrong\n");
470                 goto bail;
471               }
472
473               memcpy(&val,
474                      elf.buf + dhdr.sh_offset + sym.st_value,
475                      sym.st_size);
476             }
477
478             if (!elf.le_data) {
479               log_msg("Big Endian data not supported yet!\n");
480               goto bail;
481             }
482
483             switch (mode) {
484               case OUTPUT_FMT_RVDS:
485                 printf("%-40s EQU %5d\n",
486                        parse_elf_string_table(&elf,
487                                               shdr.sh_link,
488                                               sym.st_name),
489                        val);
490                 break;
491               case OUTPUT_FMT_GAS:
492                 printf(".equ %-40s, %5d\n",
493                        parse_elf_string_table(&elf,
494                                               shdr.sh_link,
495                                               sym.st_name),
496                        val);
497                 break;
498               case OUTPUT_FMT_C_HEADER:
499                 printf("#define %-40s %5d\n",
500                        parse_elf_string_table(&elf,
501                                               shdr.sh_link,
502                                               sym.st_name),
503                        val);
504                 break;
505               default:
506                 printf("%s = %d\n",
507                        parse_elf_string_table(&elf,
508                                               shdr.sh_link,
509                                               sym.st_name),
510                        val);
511             }
512           }
513         }
514       }
515     }
516   } else { /* if (elf.bits == 64) */
517     Elf64_Shdr shdr;
518     for (i = 0; i < elf.hdr64.e_shnum; i++) {
519       parse_elf_section(&elf, i, NULL, &shdr);
520
521       if (shdr.sh_type == SHT_SYMTAB) {
522         for (ofst = shdr.sh_offset;
523              ofst < shdr.sh_offset + shdr.sh_size;
524              ofst += shdr.sh_entsize) {
525           Elf64_Sym sym;
526
527           parse_elf_symbol(&elf, ofst, NULL, &sym);
528
529           /* For all OBJECTS (data objects), extract the value from the
530            * proper data segment.
531            */
532           /* if (ELF64_ST_TYPE(sym.st_info) == STT_OBJECT && sym.st_name)
533               log_msg("found data object %s\n",
534                       parse_elf_string_table(&elf,
535                                              shdr.sh_link,
536                                              sym.st_name));
537            */
538
539           if (ELF64_ST_TYPE(sym.st_info) == STT_OBJECT
540               && sym.st_size == 4) {
541             Elf64_Shdr dhdr;
542             int val = 0;
543             char section_name[128];
544
545             parse_elf_section(&elf, sym.st_shndx, NULL, &dhdr);
546
547             /* For explanition - refer to _MSC_VER version of code */
548             strcpy(section_name, (char *)(elf.buf + strtab_off64 + dhdr.sh_name));
549             /* log_msg("Section_name: %s, Section_type: %d\n", section_name, dhdr.sh_type); */
550
551             if ((strcmp(section_name, ".bss"))) {
552               if (sizeof(val) != sym.st_size) {
553                 /* The target value is declared as an int in
554                  * *_asm_*_offsets.c, which is 4 bytes on all
555                  * targets we currently use. Complain loudly if
556                  * this is not true.
557                  */
558                 log_msg("Symbol size is wrong\n");
559                 goto bail;
560               }
561
562               memcpy(&val,
563                      elf.buf + dhdr.sh_offset + sym.st_value,
564                      sym.st_size);
565             }
566
567             if (!elf.le_data) {
568               log_msg("Big Endian data not supported yet!\n");
569               goto bail;
570             }
571
572             switch (mode) {
573               case OUTPUT_FMT_RVDS:
574                 printf("%-40s EQU %5d\n",
575                        parse_elf_string_table(&elf,
576                                               shdr.sh_link,
577                                               sym.st_name),
578                        val);
579                 break;
580               case OUTPUT_FMT_GAS:
581                 printf(".equ %-40s, %5d\n",
582                        parse_elf_string_table(&elf,
583                                               shdr.sh_link,
584                                               sym.st_name),
585                        val);
586                 break;
587               default:
588                 printf("%s = %d\n",
589                        parse_elf_string_table(&elf,
590                                               shdr.sh_link,
591                                               sym.st_name),
592                        val);
593             }
594           }
595         }
596       }
597     }
598   }
599
600   if (mode == OUTPUT_FMT_RVDS)
601     printf("    END\n");
602
603   return 0;
604 bail:
605   log_msg("Parse error: File does not appear to be valid ELF32 or ELF64\n");
606   return 1;
607 }
608
609 #endif
610 #endif /* defined(__GNUC__) && __GNUC__ */
611
612
613 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__)
614 /*  See "Microsoft Portable Executable and Common Object File Format Specification"
615     for reference.
616 */
617 #define get_le32(x) ((*(x)) | (*(x+1)) << 8 |(*(x+2)) << 16 | (*(x+3)) << 24 )
618 #define get_le16(x) ((*(x)) | (*(x+1)) << 8)
619
620 int parse_coff(uint8_t *buf, size_t sz) {
621   unsigned int nsections, symtab_ptr, symtab_sz, strtab_ptr;
622   unsigned int sectionrawdata_ptr;
623   unsigned int i;
624   uint8_t *ptr;
625   uint32_t symoffset;
626
627   char **sectionlist;  // this array holds all section names in their correct order.
628   // it is used to check if the symbol is in .bss or .rdata section.
629
630   nsections = get_le16(buf + 2);
631   symtab_ptr = get_le32(buf + 8);
632   symtab_sz = get_le32(buf + 12);
633   strtab_ptr = symtab_ptr + symtab_sz * 18;
634
635   if (nsections > 96) {
636     log_msg("Too many sections\n");
637     return 1;
638   }
639
640   sectionlist = malloc(nsections * sizeof(sectionlist));
641
642   if (sectionlist == NULL) {
643     log_msg("Allocating first level of section list failed\n");
644     return 1;
645   }
646
647   // log_msg("COFF: Found %u symbols in %u sections.\n", symtab_sz, nsections);
648
649   /*
650   The size of optional header is always zero for an obj file. So, the section header
651   follows the file header immediately.
652   */
653
654   ptr = buf + 20;     // section header
655
656   for (i = 0; i < nsections; i++) {
657     char sectionname[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
658     strncpy(sectionname, ptr, 8);
659     // log_msg("COFF: Parsing section %s\n",sectionname);
660
661     sectionlist[i] = malloc(strlen(sectionname) + 1);
662
663     if (sectionlist[i] == NULL) {
664       log_msg("Allocating storage for %s failed\n", sectionname);
665       goto bail;
666     }
667     strcpy(sectionlist[i], sectionname);
668
669     // check if it's .rdata and is not a COMDAT section.
670     if (!strcmp(sectionname, ".rdata") &&
671         (get_le32(ptr + 36) & 0x1000) == 0) {
672       sectionrawdata_ptr = get_le32(ptr + 20);
673     }
674
675     ptr += 40;
676   }
677
678   // log_msg("COFF: Symbol table at offset %u\n", symtab_ptr);
679   // log_msg("COFF: raw data pointer ofset for section .rdata is %u\n", sectionrawdata_ptr);
680
681   /*  The compiler puts the data with non-zero offset in .rdata section, but puts the data with
682       zero offset in .bss section. So, if the data in in .bss section, set offset=0.
683       Note from Wiki: In an object module compiled from C, the bss section contains
684       the local variables (but not functions) that were declared with the static keyword,
685       except for those with non-zero initial values. (In C, static variables are initialized
686       to zero by default.) It also contains the non-local (both extern and static) variables
687       that are also initialized to zero (either explicitly or by default).
688       */
689   // move to symbol table
690   /* COFF symbol table:
691       offset      field
692       0           Name(*)
693       8           Value
694       12          SectionNumber
695       14          Type
696       16          StorageClass
697       17          NumberOfAuxSymbols
698       */
699   ptr = buf + symtab_ptr;
700
701   for (i = 0; i < symtab_sz; i++) {
702     int16_t section = get_le16(ptr + 12); // section number
703
704     if (section > 0 && ptr[16] == 2) {
705       // if(section > 0 && ptr[16] == 3 && get_le32(ptr+8)) {
706
707       if (get_le32(ptr)) {
708         char name[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
709         strncpy(name, ptr, 8);
710         // log_msg("COFF: Parsing symbol %s\n",name);
711         /* The 64bit Windows compiler doesn't prefix with an _.
712          * Check what's there, and bump if necessary
713          */
714         if (name[0] == '_')
715           printf("%-40s EQU ", name + 1);
716         else
717           printf("%-40s EQU ", name);
718       } else {
719         // log_msg("COFF: Parsing symbol %s\n",
720         //        buf + strtab_ptr + get_le32(ptr+4));
721         if ((buf + strtab_ptr + get_le32(ptr + 4))[0] == '_')
722           printf("%-40s EQU ",
723                  buf + strtab_ptr + get_le32(ptr + 4) + 1);
724         else
725           printf("%-40s EQU ", buf + strtab_ptr + get_le32(ptr + 4));
726       }
727
728       if (!(strcmp(sectionlist[section - 1], ".bss"))) {
729         symoffset = 0;
730       } else {
731         symoffset = get_le32(buf + sectionrawdata_ptr + get_le32(ptr + 8));
732       }
733
734       // log_msg("      Section: %d\n",section);
735       // log_msg("      Class:   %d\n",ptr[16]);
736       // log_msg("      Address: %u\n",get_le32(ptr+8));
737       // log_msg("      Offset: %u\n", symoffset);
738
739       printf("%5d\n", symoffset);
740     }
741
742     ptr += 18;
743   }
744
745   printf("    END\n");
746
747   for (i = 0; i < nsections; i++) {
748     free(sectionlist[i]);
749   }
750
751   free(sectionlist);
752
753   return 0;
754 bail:
755
756   for (i = 0; i < nsections; i++) {
757     free(sectionlist[i]);
758   }
759
760   free(sectionlist);
761
762   return 1;
763 }
764 #endif /* defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__) */
765
766 int main(int argc, char **argv) {
767   output_fmt_t mode = OUTPUT_FMT_PLAIN;
768   const char *f;
769   uint8_t *file_buf;
770   int res;
771   FILE *fp;
772   long int file_size;
773
774   if (argc < 2 || argc > 3) {
775     fprintf(stderr, "Usage: %s [output format] <obj file>\n\n", argv[0]);
776     fprintf(stderr, "  <obj file>\tobject file to parse\n");
777     fprintf(stderr, "Output Formats:\n");
778     fprintf(stderr, "  gas  - compatible with GNU assembler\n");
779     fprintf(stderr, "  rvds - compatible with armasm\n");
780     fprintf(stderr, "  cheader - c/c++ header file\n");
781     goto bail;
782   }
783
784   f = argv[2];
785
786   if (!strcmp(argv[1], "rvds"))
787     mode = OUTPUT_FMT_RVDS;
788   else if (!strcmp(argv[1], "gas"))
789     mode = OUTPUT_FMT_GAS;
790   else if (!strcmp(argv[1], "cheader"))
791     mode = OUTPUT_FMT_C_HEADER;
792   else
793     f = argv[1];
794
795   fp = fopen(f, "rb");
796
797   if (!fp) {
798     perror("Unable to open file");
799     goto bail;
800   }
801
802   if (fseek(fp, 0, SEEK_END)) {
803     perror("stat");
804     goto bail;
805   }
806
807   file_size = ftell(fp);
808   file_buf = malloc(file_size);
809
810   if (!file_buf) {
811     perror("malloc");
812     goto bail;
813   }
814
815   rewind(fp);
816
817   if (fread(file_buf, sizeof(char), file_size, fp) != file_size) {
818     perror("read");
819     goto bail;
820   }
821
822   if (fclose(fp)) {
823     perror("close");
824     goto bail;
825   }
826
827 #if defined(__GNUC__) && __GNUC__
828 #if defined(__MACH__)
829   res = parse_macho(file_buf, file_size, mode);
830 #elif defined(__ELF__)
831   res = parse_elf(file_buf, file_size, mode);
832 #endif
833 #endif
834 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__)
835   res = parse_coff(file_buf, file_size);
836 #endif
837
838   free(file_buf);
839
840   if (!res)
841     return EXIT_SUCCESS;
842
843 bail:
844   return EXIT_FAILURE;
845 }