Skip to contentSkip to conversation

selftests, x86, pkeys: test with random, unallocated protection keys

PATCH In review Dave Hansen 2 participants 2 messages Feb 24, 2017

Subsystems (2)
lore
Share & tools
lore

Dave Hansen

author maintainer
#0 lore raw

PATCH v2 1/1 selftests, x86, pkeys: test with random, unallocated protection keys

Changes from v1:
* Also generate random negative numbers for protection key

--
From: Dave Hansen <[email protected]>

The kernel pkeys code had a minor bug where it did some large shifts to an integer which is undefined behavior in C. It didn't cause any real harm, but it is screwy behavior that the kernel should have rejected.

Add a test case for this.

---

 b/tools/testing/selftests/x86/protection_keys.c |   25 ++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
tools/testing/selftests/x86/protection_keys.c renamed from tools/testing/selftests/x86/protection_keys.c~pkeys-better-selftests-of-random-pkey +25 -0
diff -puN tools/testing/selftests/x86/protection_keys.c~pkeys-better-selftests-of-random-pkey tools/testing/selftests/x86/protection_keys.c
@@ -1123,6 +1123,30 @@ void test_pkey_syscalls_on_non_allocated
 }
 
 /* Assumes that all pkeys other than 'pkey' are unallocated */
+void test_pkey_syscalls_on_non_allocated_random_pkey(int *ptr, u16 pkey)
+{
+	int err;
+	int nr_tests = 0;
+
+	while (nr_tests < 1000) {
+		int test_pkey = rand() - RAND_MAX/2;
+
+		/* do not test with the pkey we know is good */
+		if (pkey == test_pkey)
+			continue;
+
+		dprintf1("trying free/mprotect bad pkey: %2d\n", test_pkey);
+		err = sys_pkey_free(test_pkey);
+		pkey_assert(err);
+
+		err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, test_pkey);
+		pkey_assert(err);
+
+		nr_tests++;
+	}
+}
+
+/* Assumes that all pkeys other than 'pkey' are unallocated */
 void test_pkey_syscalls_bad_args(int *ptr, u16 pkey)
 {
 	int err;
@@ -1320,6 +1344,7 @@ void (*pkey_tests[])(int *ptr, u16 pkey)
 	test_executing_on_unreadable_memory,
 	test_ptrace_of_child,
 	test_pkey_syscalls_on_non_allocated_pkey,
+	test_pkey_syscalls_on_non_allocated_random_pkey,
 	test_pkey_syscalls_bad_args,
 	test_pkey_alloc_exhaust,
 };

_

Acked-by on v2 1/1
#1 lore raw
Quoted 8 lines · Dave Hansen

Changes from v1:
* Also generate random negative numbers for protection key

--
From: Dave Hansen <[email protected]>

Quoted 8 lines

The kernel pkeys code had a minor bug where it did some large shifts to an integer which is undefined behavior in C. It didn't cause any real harm, but it is screwy behavior that the kernel should have rejected.

Add a test case for this.

Signature · 1 line
 Kirill A. Shutemov