-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmemdump.c
58 lines (48 loc) · 1.21 KB
/
memdump.c
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
// SPDX-License-Identifier: MIT
// Copyright (C) J. Neuschäfer
/*
* memdump - dump a memory range to stdout
* Usage: memdump START_ADDRESS SIZE
*/
#include <fcntl.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#define PAGE 4096ul /* an assumption that will hopefully not bite me. */
#define PAGE_MASK (PAGE - 1)
int main(int argc, char **argv) {
if (argc != 3) {
printf("Usage: memscan START_ADDRESS SIZE\n");
return EXIT_FAILURE;
}
off_t base = strtoul(argv[1], NULL, 0);
size_t size = strtoul(argv[2], NULL, 0);
if (size == 0) {
printf("Size is zero. Exiting.\n");
exit(EXIT_FAILURE);
}
if ((base & PAGE_MASK) || (size & PAGE_MASK)) {
printf("Base or size not 4k-aligned. Exiting.\n");
exit(EXIT_FAILURE);
}
int fd = open("/dev/mem", O_RDONLY);
if (fd < 0) {
perror("Failed to open /dev/mem");
exit(EXIT_FAILURE);
}
void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, base);
if (map == MAP_FAILED) {
perror("Failed to map /dev/mem");
exit(EXIT_FAILURE);
}
close(fd);
fwrite(map, 1, size, stdout);
fflush(stdout);
return EXIT_SUCCESS;
}