Blob
1 #include <u.h>2 #include <libc.h>3 #include <bio.h>4 #include <mach.h>5 #include "elf.h"8 Mach *mach;10 extern Mach mach386;11 extern Mach machpower;13 static Mach *machs[] =14 {15 &mach386,16 &machpower,17 };19 Mach*20 machbyname(char *name)21 {22 int i;24 for(i=0; i<nelem(machs); i++)25 if(strcmp(machs[i]->name, name) == 0){26 mach = machs[i];27 return machs[i];28 }29 werrstr("machine '%s' not found", name);30 return nil;31 }33 static struct34 {35 ulong magic;36 int (*fn)(int, Fhdr*);37 } cracktab[] = {38 0x7F454C46, crackelf,39 0xFEEDFACE, crackmacho,40 };42 Fhdr*43 crackhdr(char *name, int mode)44 {45 uchar buf[4];46 ulong magic;47 int i, fd;48 Fhdr *hdr;50 if((fd = open(name, mode)) < 0)51 return nil;53 if(seek(fd, 0, 0) < 0 || readn(fd, buf, 4) != 4){54 close(fd);55 return nil;56 }58 hdr = mallocz(sizeof(Fhdr), 1);59 if(hdr == nil){60 close(fd);61 return nil;62 }63 hdr->filename = strdup(name);64 magic = beload4(buf);65 werrstr("magic doesn't match");66 for(i=0; i<nelem(cracktab); i++)67 if(cracktab[i].magic == magic && seek(fd, 0, 0) == 0 && cracktab[i].fn(fd, hdr) >= 0){68 _addhdr(hdr);69 return hdr;70 }71 werrstr("unknown file type: %r");72 free(hdr);73 close(fd);74 return nil;75 }77 void78 uncrackhdr(Fhdr *hdr)79 {80 int i;82 symclose(hdr);83 if(hdr->elf)84 elfclose(hdr->elf);85 if(hdr->fd >= 0)86 close(hdr->fd);87 free(hdr->cmdline);88 free(hdr->prog);89 for(i=0; i<hdr->nthread; i++)90 free(hdr->thread[i].ureg);91 free(hdr->thread);92 free(hdr);93 }95 int96 mapfile(Fhdr *fp, ulong base, Map *map, Regs **regs)97 {98 if(fp == nil){99 werrstr("no file");100 return -1;101 }102 if(map == nil){103 werrstr("no map");104 return -1;105 }106 if(fp->map == 0){107 werrstr("cannot load map for this file type");108 return -1;109 }110 if(regs)111 *regs = nil;112 return fp->map(fp, base, map, regs);113 }115 void116 unmapfile(Fhdr *fp, Map *map)117 {118 int i;120 if(map == nil || fp == nil)121 return;123 for(i=0; i<map->nseg; i++){124 while(i<map->nseg && map->seg[i].fd == fp->fd){125 map->nseg--;126 memmove(&map->seg[i], &map->seg[i+1],127 (map->nseg-i)*sizeof(map->seg[0]));128 }129 }130 }132 Regs*133 coreregs(Fhdr *fp, uint id)134 {135 UregRegs *r;136 int i;138 for(i=0; i<fp->nthread; i++){139 if(fp->thread[i].id == id){140 if((r = mallocz(sizeof *r, 1)) == nil)141 return nil;142 r->r.rw = _uregrw;143 r->ureg = fp->thread[i].ureg;144 return &r->r;145 }146 }147 werrstr("thread not found");148 return nil;149 }