Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <mach.h>
5 #include "elf.h"
7 static struct
8 {
9 ulong magic;
10 int (*fn)(int, Fhdr*);
11 } cracktab[] = {
12 0x7F454C46, crackelf,
13 0xFEEDFACE, crackmacho,
14 };
16 Fhdr*
17 crackhdr(char *name, int mode)
18 {
19 uchar buf[4];
20 ulong magic;
21 int i, fd;
22 Fhdr *hdr;
24 if((fd = open(name, mode)) < 0)
25 return nil;
27 if(seek(fd, 0, 0) < 0 || readn(fd, buf, 4) != 4){
28 close(fd);
29 return nil;
30 }
32 hdr = mallocz(sizeof(Fhdr), 1);
33 if(hdr == nil){
34 close(fd);
35 return nil;
36 }
37 hdr->filename = strdup(name);
38 magic = beload4(buf);
39 werrstr("magic doesn't match");
40 for(i=0; i<nelem(cracktab); i++)
41 if(cracktab[i].magic == magic && seek(fd, 0, 0) == 0 && cracktab[i].fn(fd, hdr) >= 0){
42 _addhdr(hdr);
43 return hdr;
44 }
45 werrstr("unknown file type: %r");
46 free(hdr);
47 close(fd);
48 return nil;
49 }
51 void
52 uncrackhdr(Fhdr *hdr)
53 {
54 int i;
56 symclose(hdr);
57 if(hdr->elf)
58 elfclose(hdr->elf);
59 if(hdr->fd >= 0)
60 close(hdr->fd);
61 free(hdr->cmdline);
62 free(hdr->prog);
63 for(i=0; i<hdr->nthread; i++)
64 free(hdr->thread[i].ureg);
65 free(hdr->thread);
66 free(hdr);
67 }
69 int
70 mapfile(Fhdr *fp, ulong base, Map *map, Regs **regs)
71 {
72 if(fp == nil){
73 werrstr("no file");
74 return -1;
75 }
76 if(map == nil){
77 werrstr("no map");
78 return -1;
79 }
80 if(fp->map == 0){
81 werrstr("cannot load map for this file type");
82 return -1;
83 }
84 if(regs)
85 *regs = nil;
86 return fp->map(fp, base, map, regs);
87 }
89 void
90 unmapfile(Fhdr *fp, Map *map)
91 {
92 int i;
94 if(map == nil || fp == nil)
95 return;
97 for(i=0; i<map->nseg; i++){
98 while(i<map->nseg && map->seg[i].fd == fp->fd){
99 map->nseg--;
100 memmove(&map->seg[i], &map->seg[i+1],
101 (map->nseg-i)*sizeof(map->seg[0]));
106 Regs*
107 coreregs(Fhdr *fp, uint id)
109 UregRegs *r;
110 int i;
112 for(i=0; i<fp->nthread; i++){
113 if(fp->thread[i].id == id){
114 if((r = mallocz(sizeof *r, 1)) == nil)
115 return nil;
116 r->r.rw = _uregrw;
117 r->ureg = fp->thread[i].ureg;
118 return &r->r;
121 werrstr("thread not found");
122 return nil;