summaryrefslogtreecommitdiff
path: root/procfs.c
blob: e3bfb2ce234a311679e5e354cd483f3819b012ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "procfs.h"

int procfs_open(pid_t pid) {
	char path[2048];
	sprintf(path, "/proc/%d/mem", pid);
	return open(path, O_RDWR);
}

ssize_t procfs_maps(pid_t pid, struct procfs_map **maps) {
	char path[2048];
	sprintf(path, "/proc/%d/maps", pid);
	FILE *f = fopen(path, "r");
	if (!f) return -1;

	int n = 0;
	int capacity = 2;
	*maps = calloc(capacity, sizeof(**maps));
	if (!*maps) return -1;
	while (1) {
		void *base, *max;
		int matches = fscanf(f, "%p-%p", &base, &max);
		if (matches == EOF) goto eof;
		if (matches < 2) goto err;
		int c;
		while ((c = getc(f)) != '\n')
			if (c == EOF) goto eof;
		n++;
		if (n > capacity) {
			capacity <<= 1;
			struct procfs_map *r = reallocarray(*maps, capacity, sizeof(*r));
			if (!r) goto err;
			*maps = r;
		}
		(*maps)[n - 1].base = (uintptr_t) base;
		(*maps)[n - 1].max = (uintptr_t) max;
	}
eof:
	if (ferror(f)) goto err;
	if (n == 0) free(*maps);
	return n;
err:
	free(*maps);
	return -1;
}

int read_page(int fd, uintptr_t index, uint8_t *data) {
	if (lseek(fd, index * PAGE_SIZE, SEEK_SET) == -1) 
		return -1;
	size_t n = 0;
	while (n < PAGE_SIZE) {
		ssize_t result = read(fd, data + n, PAGE_SIZE - n);
		if (result == -1) return -1;
		n += result;
	}
	return 0;
}