xref: /plan9-contrib/sys/src/libmach/map.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 /*
2  * file map routines
3  */
4 #include <u.h>
5 #include <libc.h>
6 #include <bio.h>
7 #include <mach.h>
8 
9 static int	reloc(Map*, ulong, long*);
10 
11 Map *
12 newmap(Map *map, int fd, int n)
13 {
14 	int size;
15 
16 	size = sizeof(Map)+(n-1)*sizeof(struct segment);
17 	if (map == 0)
18 		map = malloc(size);
19 	else
20 		map = realloc(map, size);
21 	if (map == 0) {
22 		werrstr("out of memory: %r");
23 		return 0;
24 	}
25 	memset(map, 0, size);
26 	map->fd = fd;
27 	map->nsegs = n;
28 	return map;
29 }
30 
31 int
32 setmap(Map *map, ulong b, ulong e, ulong f, char *name)
33 {
34 	int i;
35 
36 	if (map == 0)
37 		return 0;
38 	for (i = 0; i < map->nsegs; i++)
39 		if (!map->seg[i].inuse)
40 			break;
41 	if (i >= map->nsegs)
42 		return 0;
43 	map->seg[i].b = b;
44 	map->seg[i].e = e;
45 	map->seg[i].f = f;
46 	map->seg[i].inuse = 1;
47 	map->seg[i].name = name;
48 	return 1;
49 }
50 
51 int
52 findseg(Map *map, char *name)
53 {
54 	int i;
55 
56 	if (!map)
57 		return -1;
58 	for (i = 0; i < map->nsegs; i++)
59 		if (map->seg[i].inuse && !strcmp(map->seg[i].name, name))
60 			return i;
61 	return -1;
62 }
63 
64 void
65 unusemap(Map *map, int i)
66 {
67 	if (map != 0 && 0 <= i && i < map->nsegs)
68 		map->seg[i].inuse = 0;
69 }
70 
71 Map *
72 loadmap(Map *map, int fd, Fhdr *fp)
73 {
74 	map = newmap(map, fd, 2);
75 	if (map == 0)
76 		return 0;
77 	map->seg[0].b = fp->txtaddr;
78 	map->seg[0].e = fp->txtaddr+fp->txtsz;
79 	map->seg[0].f = fp->txtoff;
80 	map->seg[0].inuse = 1;
81 	map->seg[0].name = "text";
82 	map->seg[1].b = fp->dataddr;
83 	map->seg[1].e = fp->dataddr+fp->datsz;
84 	map->seg[1].f = fp->datoff;
85 	map->seg[1].inuse = 1;
86 	map->seg[1].name = "data";
87 	return map;
88 }
89