1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This test covers the anonymous VMA naming functionality through prctl calls
4  */
5 
6 #include <errno.h>
7 #include <sys/prctl.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/mman.h>
11 #include <string.h>
12 
13 #include "../kselftest_harness.h"
14 
15 #define AREA_SIZE 1024
16 
17 #define GOOD_NAME "goodname"
18 #define BAD_NAME "badname\1"
19 
20 #ifndef PR_SET_VMA
21 #define PR_SET_VMA 0x53564d41
22 #define PR_SET_VMA_ANON_NAME 0
23 #endif
24 
25 
26 int rename_vma(unsigned long addr, unsigned long size, char *name)
27 {
28 	int res;
29 
30 	res = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, addr, size, name);
31 	if (res < 0)
32 		return -errno;
33 	return res;
34 }
35 
36 int was_renaming_successful(char *target_name, unsigned long ptr)
37 {
38 	FILE *maps_file;
39 
40 	char line_buf[512], name[128], mode[8];
41 	unsigned long start_addr, end_addr, offset;
42 	unsigned int major_id, minor_id, node_id;
43 
44 	char target_buf[128];
45 	int res = 0, sscanf_res;
46 
47 	// The entry name in maps will be in format [anon:<target_name>]
48 	sprintf(target_buf, "[anon:%s]", target_name);
49 	maps_file = fopen("/proc/self/maps", "r");
50 	if (!maps_file) {
51 		printf("## /proc/self/maps file opening error\n");
52 		return 0;
53 	}
54 
55 	// Parse the maps file to find the entry we renamed
56 	while (fgets(line_buf, sizeof(line_buf), maps_file)) {
57 		sscanf_res = sscanf(line_buf, "%lx-%lx %7s %lx %u:%u %u %s", &start_addr,
58 					&end_addr, mode, &offset, &major_id,
59 					&minor_id, &node_id, name);
60 		if (sscanf_res == EOF) {
61 			res = 0;
62 			printf("## EOF while parsing the maps file\n");
63 			break;
64 		}
65 		if (!strcmp(name, target_buf) && start_addr == ptr) {
66 			res = 1;
67 			break;
68 		}
69 	}
70 	fclose(maps_file);
71 	return res;
72 }
73 
74 FIXTURE(vma) {
75 	void *ptr_anon, *ptr_not_anon;
76 };
77 
78 FIXTURE_SETUP(vma) {
79 	self->ptr_anon = mmap(NULL, AREA_SIZE, PROT_READ | PROT_WRITE,
80 					MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
81 	ASSERT_NE(self->ptr_anon, NULL);
82 	self->ptr_not_anon = mmap(NULL, AREA_SIZE, PROT_READ | PROT_WRITE,
83 					MAP_PRIVATE, 0, 0);
84 	ASSERT_NE(self->ptr_not_anon, NULL);
85 }
86 
87 FIXTURE_TEARDOWN(vma) {
88 	munmap(self->ptr_anon, AREA_SIZE);
89 	munmap(self->ptr_not_anon, AREA_SIZE);
90 }
91 
92 TEST_F(vma, renaming) {
93 	TH_LOG("Try to rename the VMA with correct parameters");
94 	EXPECT_GE(rename_vma((unsigned long)self->ptr_anon, AREA_SIZE, GOOD_NAME), 0);
95 	EXPECT_TRUE(was_renaming_successful(GOOD_NAME, (unsigned long)self->ptr_anon));
96 
97 	TH_LOG("Try to pass invalid name (with non-printable character \\1) to rename the VMA");
98 	EXPECT_EQ(rename_vma((unsigned long)self->ptr_anon, AREA_SIZE, BAD_NAME), -EINVAL);
99 
100 	TH_LOG("Try to rename non-anonynous VMA");
101 	EXPECT_EQ(rename_vma((unsigned long) self->ptr_not_anon, AREA_SIZE, GOOD_NAME), -EINVAL);
102 }
103 
104 TEST_HARNESS_MAIN
105