1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <syscall.h>
3 #include <errno.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 
7 #ifndef MLOCK_ONFAULT
8 #define MLOCK_ONFAULT 1
9 #endif
10 
11 #ifndef MCL_ONFAULT
12 #define MCL_ONFAULT (MCL_FUTURE << 1)
13 #endif
14 
15 static int mlock2_(void *start, size_t len, int flags)
16 {
17 #ifdef __NR_mlock2
18 	return syscall(__NR_mlock2, start, len, flags);
19 #else
20 	errno = ENOSYS;
21 	return -1;
22 #endif
23 }
24 
25 static FILE *seek_to_smaps_entry(unsigned long addr)
26 {
27 	FILE *file;
28 	char *line = NULL;
29 	size_t size = 0;
30 	unsigned long start, end;
31 	char perms[5];
32 	unsigned long offset;
33 	char dev[32];
34 	unsigned long inode;
35 	char path[BUFSIZ];
36 
37 	file = fopen("/proc/self/smaps", "r");
38 	if (!file) {
39 		perror("fopen smaps");
40 		_exit(1);
41 	}
42 
43 	while (getline(&line, &size, file) > 0) {
44 		if (sscanf(line, "%lx-%lx %s %lx %s %lu %s\n",
45 			   &start, &end, perms, &offset, dev, &inode, path) < 6)
46 			goto next;
47 
48 		if (start <= addr && addr < end)
49 			goto out;
50 
51 next:
52 		free(line);
53 		line = NULL;
54 		size = 0;
55 	}
56 
57 	fclose(file);
58 	file = NULL;
59 
60 out:
61 	free(line);
62 	return file;
63 }
64