scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

elfprobe.c (1017B)


      1 #include <stdio.h>
      2 
      3 #include <scc/mach.h>
      4 #include <scc/elf/elftypes.h>
      5 #include <scc/elf/elfhdr.h>
      6 #include <scc/elf.h>
      7 
      8 #include "../libmach.h"
      9 #include "fun.h"
     10 
     11 int
     12 elfprobe(unsigned char *buf, char **name)
     13 {
     14 	int arch, data, endian;
     15 	struct elfhdr32 hdr;
     16 	struct arch *ap;
     17 
     18 	data = buf[EI_DATA];
     19 	endian = (data == ELFDATA2LSB) ? LITTLE_ENDIAN : BIG_ENDIAN;
     20 	arch = (buf[EI_CLASS] == ELFCLASS32) ? ARCHUNK32 : ARCHUNK64;
     21 
     22 	unpack(endian,
     23 	       buf,
     24 	       "'16sss",
     25 	       hdr.e_ident,
     26 	       &hdr.e_type,
     27 	       &hdr.e_machine,
     28 	       &hdr.e_version);
     29 
     30 	if (!IS_ELF(hdr)
     31 	||  buf[EI_VERSION] != EV_CURRENT
     32 	||  hdr.e_version != EV_CURRENT
     33 	||  buf[EI_CLASS] != ELFCLASS32 && buf[EI_CLASS] != ELFCLASS64
     34 	||  (data != ELFDATA2LSB && data != ELFDATA2MSB)) {
     35 		return -1;
     36 	}
     37 
     38 	for (ap = elfarchs; ap->name; ap++) {
     39 		if (ap->mach == hdr.e_machine &&  ap->endian == data) {
     40 			if (name)
     41 				*name = ap->name;
     42 			return ap->type;
     43 		}
     44 	}
     45 
     46 	if  (name)
     47 		*name = "elf-unknown";
     48 
     49 	return OBJ(ELF, arch, endian);
     50 }