]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - tools/testing/selftests/x86/protection_keys.c
Linux 4.14-rc6
[mirror_ubuntu-focal-kernel.git] / tools / testing / selftests / x86 / protection_keys.c
CommitLineData
5f23f6d0
DH
1/*
2 * Tests x86 Memory Protection Keys (see Documentation/x86/protection-keys.txt)
3 *
4 * There are examples in here of:
5 * * how to set protection keys on memory
6 * * how to set/clear bits in PKRU (the rights register)
7 * * how to handle SEGV_PKRU signals and extract pkey-relevant
8 * information from the siginfo
9 *
10 * Things to add:
11 * make sure KSM and KSM COW breaking works
12 * prefault pages in at malloc, or not
13 * protect MPX bounds tables with protection keys?
14 * make sure VMA splitting/merging is working correctly
15 * OOMs can destroy mm->mmap (see exit_mmap()), so make sure it is immune to pkeys
16 * look for pkey "leaks" where it is still set on a VMA but "freed" back to the kernel
17 * do a plain mprotect() to a mprotect_pkey() area and make sure the pkey sticks
18 *
19 * Compile like this:
20 * gcc -o protection_keys -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
21 * gcc -m32 -o protection_keys_32 -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
22 */
23#define _GNU_SOURCE
24#include <errno.h>
25#include <linux/futex.h>
26#include <sys/time.h>
27#include <sys/syscall.h>
28#include <string.h>
29#include <stdio.h>
30#include <stdint.h>
31#include <stdbool.h>
32#include <signal.h>
33#include <assert.h>
34#include <stdlib.h>
35#include <ucontext.h>
36#include <sys/mman.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39#include <sys/stat.h>
40#include <fcntl.h>
41#include <unistd.h>
42#include <sys/ptrace.h>
43#include <setjmp.h>
44
45#include "pkey-helpers.h"
46
47int iteration_nr = 1;
48int test_nr;
49
50unsigned int shadow_pkru;
51
52#define HPAGE_SIZE (1UL<<21)
53#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
54#define ALIGN_UP(x, align_to) (((x) + ((align_to)-1)) & ~((align_to)-1))
55#define ALIGN_DOWN(x, align_to) ((x) & ~((align_to)-1))
56#define ALIGN_PTR_UP(p, ptr_align_to) ((typeof(p))ALIGN_UP((unsigned long)(p), ptr_align_to))
57#define ALIGN_PTR_DOWN(p, ptr_align_to) ((typeof(p))ALIGN_DOWN((unsigned long)(p), ptr_align_to))
58#define __stringify_1(x...) #x
59#define __stringify(x...) __stringify_1(x)
60
61#define PTR_ERR_ENOTSUP ((void *)-ENOTSUP)
62
63int dprint_in_signal;
64char dprint_in_signal_buffer[DPRINT_IN_SIGNAL_BUF_SIZE];
65
66extern void abort_hooks(void);
67#define pkey_assert(condition) do { \
68 if (!(condition)) { \
69 dprintf0("assert() at %s::%d test_nr: %d iteration: %d\n", \
70 __FILE__, __LINE__, \
71 test_nr, iteration_nr); \
72 dprintf0("errno at assert: %d", errno); \
73 abort_hooks(); \
74 assert(condition); \
75 } \
76} while (0)
77#define raw_assert(cond) assert(cond)
78
79void cat_into_file(char *str, char *file)
80{
81 int fd = open(file, O_RDWR);
82 int ret;
83
84 dprintf2("%s(): writing '%s' to '%s'\n", __func__, str, file);
85 /*
86 * these need to be raw because they are called under
87 * pkey_assert()
88 */
89 raw_assert(fd >= 0);
90 ret = write(fd, str, strlen(str));
91 if (ret != strlen(str)) {
92 perror("write to file failed");
93 fprintf(stderr, "filename: '%s' str: '%s'\n", file, str);
94 raw_assert(0);
95 }
96 close(fd);
97}
98
99#if CONTROL_TRACING > 0
100static int warned_tracing;
101int tracing_root_ok(void)
102{
103 if (geteuid() != 0) {
104 if (!warned_tracing)
105 fprintf(stderr, "WARNING: not run as root, "
106 "can not do tracing control\n");
107 warned_tracing = 1;
108 return 0;
109 }
110 return 1;
111}
112#endif
113
114void tracing_on(void)
115{
116#if CONTROL_TRACING > 0
117#define TRACEDIR "/sys/kernel/debug/tracing"
118 char pidstr[32];
119
120 if (!tracing_root_ok())
121 return;
122
123 sprintf(pidstr, "%d", getpid());
124 cat_into_file("0", TRACEDIR "/tracing_on");
125 cat_into_file("\n", TRACEDIR "/trace");
126 if (1) {
127 cat_into_file("function_graph", TRACEDIR "/current_tracer");
128 cat_into_file("1", TRACEDIR "/options/funcgraph-proc");
129 } else {
130 cat_into_file("nop", TRACEDIR "/current_tracer");
131 }
132 cat_into_file(pidstr, TRACEDIR "/set_ftrace_pid");
133 cat_into_file("1", TRACEDIR "/tracing_on");
134 dprintf1("enabled tracing\n");
135#endif
136}
137
138void tracing_off(void)
139{
140#if CONTROL_TRACING > 0
141 if (!tracing_root_ok())
142 return;
143 cat_into_file("0", "/sys/kernel/debug/tracing/tracing_on");
144#endif
145}
146
147void abort_hooks(void)
148{
149 fprintf(stderr, "running %s()...\n", __func__);
150 tracing_off();
151#ifdef SLEEP_ON_ABORT
152 sleep(SLEEP_ON_ABORT);
153#endif
154}
155
156static inline void __page_o_noops(void)
157{
158 /* 8-bytes of instruction * 512 bytes = 1 page */
159 asm(".rept 512 ; nopl 0x7eeeeeee(%eax) ; .endr");
160}
161
162/*
163 * This attempts to have roughly a page of instructions followed by a few
164 * instructions that do a write, and another page of instructions. That
165 * way, we are pretty sure that the write is in the second page of
166 * instructions and has at least a page of padding behind it.
167 *
168 * *That* lets us be sure to madvise() away the write instruction, which
169 * will then fault, which makes sure that the fault code handles
170 * execute-only memory properly.
171 */
172__attribute__((__aligned__(PAGE_SIZE)))
173void lots_o_noops_around_write(int *write_to_me)
174{
175 dprintf3("running %s()\n", __func__);
176 __page_o_noops();
177 /* Assume this happens in the second page of instructions: */
178 *write_to_me = __LINE__;
179 /* pad out by another page: */
180 __page_o_noops();
181 dprintf3("%s() done\n", __func__);
182}
183
184/* Define some kernel-like types */
185#define u8 uint8_t
186#define u16 uint16_t
187#define u32 uint32_t
188#define u64 uint64_t
189
190#ifdef __i386__
191#define SYS_mprotect_key 380
192#define SYS_pkey_alloc 381
193#define SYS_pkey_free 382
194#define REG_IP_IDX REG_EIP
2195bff0 195#define si_pkey_offset 0x14
5f23f6d0
DH
196#else
197#define SYS_mprotect_key 329
198#define SYS_pkey_alloc 330
199#define SYS_pkey_free 331
200#define REG_IP_IDX REG_RIP
201#define si_pkey_offset 0x20
202#endif
203
204void dump_mem(void *dumpme, int len_bytes)
205{
206 char *c = (void *)dumpme;
207 int i;
208
209 for (i = 0; i < len_bytes; i += sizeof(u64)) {
210 u64 *ptr = (u64 *)(c + i);
211 dprintf1("dump[%03d][@%p]: %016jx\n", i, ptr, *ptr);
212 }
213}
214
d12fe87e
EB
215#define SEGV_BNDERR 3 /* failed address bound checks */
216#define SEGV_PKUERR 4
5f23f6d0
DH
217
218static char *si_code_str(int si_code)
219{
d12fe87e 220 if (si_code == SEGV_MAPERR)
5f23f6d0 221 return "SEGV_MAPERR";
d12fe87e 222 if (si_code == SEGV_ACCERR)
5f23f6d0 223 return "SEGV_ACCERR";
d12fe87e 224 if (si_code == SEGV_BNDERR)
5f23f6d0 225 return "SEGV_BNDERR";
d12fe87e 226 if (si_code == SEGV_PKUERR)
5f23f6d0
DH
227 return "SEGV_PKUERR";
228 return "UNKNOWN";
229}
230
231int pkru_faults;
232int last_si_pkey = -1;
233void signal_handler(int signum, siginfo_t *si, void *vucontext)
234{
235 ucontext_t *uctxt = vucontext;
236 int trapno;
237 unsigned long ip;
238 char *fpregs;
239 u32 *pkru_ptr;
240 u64 si_pkey;
241 u32 *si_pkey_ptr;
242 int pkru_offset;
243 fpregset_t fpregset;
244
245 dprint_in_signal = 1;
246 dprintf1(">>>>===============SIGSEGV============================\n");
247 dprintf1("%s()::%d, pkru: 0x%x shadow: %x\n", __func__, __LINE__,
248 __rdpkru(), shadow_pkru);
249
250 trapno = uctxt->uc_mcontext.gregs[REG_TRAPNO];
251 ip = uctxt->uc_mcontext.gregs[REG_IP_IDX];
252 fpregset = uctxt->uc_mcontext.fpregs;
253 fpregs = (void *)fpregset;
254
255 dprintf2("%s() trapno: %d ip: 0x%lx info->si_code: %s/%d\n", __func__,
256 trapno, ip, si_code_str(si->si_code), si->si_code);
257#ifdef __i386__
258 /*
259 * 32-bit has some extra padding so that userspace can tell whether
260 * the XSTATE header is present in addition to the "legacy" FPU
261 * state. We just assume that it is here.
262 */
263 fpregs += 0x70;
264#endif
265 pkru_offset = pkru_xstate_offset();
266 pkru_ptr = (void *)(&fpregs[pkru_offset]);
267
268 dprintf1("siginfo: %p\n", si);
269 dprintf1(" fpregs: %p\n", fpregs);
270 /*
271 * If we got a PKRU fault, we *HAVE* to have at least one bit set in
272 * here.
273 */
274 dprintf1("pkru_xstate_offset: %d\n", pkru_xstate_offset());
275 if (DEBUG_LEVEL > 4)
276 dump_mem(pkru_ptr - 128, 256);
277 pkey_assert(*pkru_ptr);
278
279 si_pkey_ptr = (u32 *)(((u8 *)si) + si_pkey_offset);
280 dprintf1("si_pkey_ptr: %p\n", si_pkey_ptr);
281 dump_mem(si_pkey_ptr - 8, 24);
282 si_pkey = *si_pkey_ptr;
283 pkey_assert(si_pkey < NR_PKEYS);
284 last_si_pkey = si_pkey;
285
286 if ((si->si_code == SEGV_MAPERR) ||
287 (si->si_code == SEGV_ACCERR) ||
288 (si->si_code == SEGV_BNDERR)) {
289 printf("non-PK si_code, exiting...\n");
290 exit(4);
291 }
292
293 dprintf1("signal pkru from xsave: %08x\n", *pkru_ptr);
294 /* need __rdpkru() version so we do not do shadow_pkru checking */
295 dprintf1("signal pkru from pkru: %08x\n", __rdpkru());
296 dprintf1("si_pkey from siginfo: %jx\n", si_pkey);
297 *(u64 *)pkru_ptr = 0x00000000;
298 dprintf1("WARNING: set PRKU=0 to allow faulting instruction to continue\n");
299 pkru_faults++;
300 dprintf1("<<<<==================================================\n");
301 return;
302 if (trapno == 14) {
303 fprintf(stderr,
304 "ERROR: In signal handler, page fault, trapno = %d, ip = %016lx\n",
305 trapno, ip);
306 fprintf(stderr, "si_addr %p\n", si->si_addr);
307 fprintf(stderr, "REG_ERR: %lx\n",
308 (unsigned long)uctxt->uc_mcontext.gregs[REG_ERR]);
309 exit(1);
310 } else {
311 fprintf(stderr, "unexpected trap %d! at 0x%lx\n", trapno, ip);
312 fprintf(stderr, "si_addr %p\n", si->si_addr);
313 fprintf(stderr, "REG_ERR: %lx\n",
314 (unsigned long)uctxt->uc_mcontext.gregs[REG_ERR]);
315 exit(2);
316 }
317 dprint_in_signal = 0;
318}
319
320int wait_all_children(void)
321{
322 int status;
323 return waitpid(-1, &status, 0);
324}
325
326void sig_chld(int x)
327{
328 dprint_in_signal = 1;
329 dprintf2("[%d] SIGCHLD: %d\n", getpid(), x);
330 dprint_in_signal = 0;
331}
332
333void setup_sigsegv_handler(void)
334{
335 int r, rs;
336 struct sigaction newact;
337 struct sigaction oldact;
338
339 /* #PF is mapped to sigsegv */
340 int signum = SIGSEGV;
341
342 newact.sa_handler = 0;
343 newact.sa_sigaction = signal_handler;
344
345 /*sigset_t - signals to block while in the handler */
346 /* get the old signal mask. */
347 rs = sigprocmask(SIG_SETMASK, 0, &newact.sa_mask);
348 pkey_assert(rs == 0);
349
350 /* call sa_sigaction, not sa_handler*/
351 newact.sa_flags = SA_SIGINFO;
352
353 newact.sa_restorer = 0; /* void(*)(), obsolete */
354 r = sigaction(signum, &newact, &oldact);
355 r = sigaction(SIGALRM, &newact, &oldact);
356 pkey_assert(r == 0);
357}
358
359void setup_handlers(void)
360{
361 signal(SIGCHLD, &sig_chld);
362 setup_sigsegv_handler();
363}
364
365pid_t fork_lazy_child(void)
366{
367 pid_t forkret;
368
369 forkret = fork();
370 pkey_assert(forkret >= 0);
371 dprintf3("[%d] fork() ret: %d\n", getpid(), forkret);
372
373 if (!forkret) {
374 /* in the child */
375 while (1) {
376 dprintf1("child sleeping...\n");
377 sleep(30);
378 }
379 }
380 return forkret;
381}
382
383void davecmp(void *_a, void *_b, int len)
384{
385 int i;
386 unsigned long *a = _a;
387 unsigned long *b = _b;
388
389 for (i = 0; i < len / sizeof(*a); i++) {
390 if (a[i] == b[i])
391 continue;
392
393 dprintf3("[%3d]: a: %016lx b: %016lx\n", i, a[i], b[i]);
394 }
395}
396
397void dumpit(char *f)
398{
399 int fd = open(f, O_RDONLY);
400 char buf[100];
401 int nr_read;
402
403 dprintf2("maps fd: %d\n", fd);
404 do {
405 nr_read = read(fd, &buf[0], sizeof(buf));
406 write(1, buf, nr_read);
407 } while (nr_read > 0);
408 close(fd);
409}
410
411#define PKEY_DISABLE_ACCESS 0x1
412#define PKEY_DISABLE_WRITE 0x2
413
414u32 pkey_get(int pkey, unsigned long flags)
415{
416 u32 mask = (PKEY_DISABLE_ACCESS|PKEY_DISABLE_WRITE);
417 u32 pkru = __rdpkru();
418 u32 shifted_pkru;
419 u32 masked_pkru;
420
421 dprintf1("%s(pkey=%d, flags=%lx) = %x / %d\n",
422 __func__, pkey, flags, 0, 0);
423 dprintf2("%s() raw pkru: %x\n", __func__, pkru);
424
425 shifted_pkru = (pkru >> (pkey * PKRU_BITS_PER_PKEY));
426 dprintf2("%s() shifted_pkru: %x\n", __func__, shifted_pkru);
427 masked_pkru = shifted_pkru & mask;
428 dprintf2("%s() masked pkru: %x\n", __func__, masked_pkru);
429 /*
430 * shift down the relevant bits to the lowest two, then
431 * mask off all the other high bits.
432 */
433 return masked_pkru;
434}
435
436int pkey_set(int pkey, unsigned long rights, unsigned long flags)
437{
438 u32 mask = (PKEY_DISABLE_ACCESS|PKEY_DISABLE_WRITE);
439 u32 old_pkru = __rdpkru();
440 u32 new_pkru;
441
442 /* make sure that 'rights' only contains the bits we expect: */
443 assert(!(rights & ~mask));
444
445 /* copy old pkru */
446 new_pkru = old_pkru;
447 /* mask out bits from pkey in old value: */
448 new_pkru &= ~(mask << (pkey * PKRU_BITS_PER_PKEY));
449 /* OR in new bits for pkey: */
450 new_pkru |= (rights << (pkey * PKRU_BITS_PER_PKEY));
451
452 __wrpkru(new_pkru);
453
454 dprintf3("%s(pkey=%d, rights=%lx, flags=%lx) = %x pkru now: %x old_pkru: %x\n",
455 __func__, pkey, rights, flags, 0, __rdpkru(), old_pkru);
456 return 0;
457}
458
459void pkey_disable_set(int pkey, int flags)
460{
461 unsigned long syscall_flags = 0;
462 int ret;
463 int pkey_rights;
16846c2d 464 u32 orig_pkru = rdpkru();
5f23f6d0
DH
465
466 dprintf1("START->%s(%d, 0x%x)\n", __func__,
467 pkey, flags);
468 pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
469
470 pkey_rights = pkey_get(pkey, syscall_flags);
471
472 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
473 pkey, pkey, pkey_rights);
474 pkey_assert(pkey_rights >= 0);
475
476 pkey_rights |= flags;
477
478 ret = pkey_set(pkey, pkey_rights, syscall_flags);
479 assert(!ret);
480 /*pkru and flags have the same format */
481 shadow_pkru |= flags << (pkey * 2);
482 dprintf1("%s(%d) shadow: 0x%x\n", __func__, pkey, shadow_pkru);
483
484 pkey_assert(ret >= 0);
485
486 pkey_rights = pkey_get(pkey, syscall_flags);
487 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
488 pkey, pkey, pkey_rights);
489
490 dprintf1("%s(%d) pkru: 0x%x\n", __func__, pkey, rdpkru());
491 if (flags)
492 pkey_assert(rdpkru() > orig_pkru);
493 dprintf1("END<---%s(%d, 0x%x)\n", __func__,
494 pkey, flags);
495}
496
497void pkey_disable_clear(int pkey, int flags)
498{
499 unsigned long syscall_flags = 0;
500 int ret;
501 int pkey_rights = pkey_get(pkey, syscall_flags);
502 u32 orig_pkru = rdpkru();
503
504 pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
505
506 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
507 pkey, pkey, pkey_rights);
508 pkey_assert(pkey_rights >= 0);
509
510 pkey_rights |= flags;
511
512 ret = pkey_set(pkey, pkey_rights, 0);
513 /* pkru and flags have the same format */
514 shadow_pkru &= ~(flags << (pkey * 2));
515 pkey_assert(ret >= 0);
516
517 pkey_rights = pkey_get(pkey, syscall_flags);
518 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
519 pkey, pkey, pkey_rights);
520
521 dprintf1("%s(%d) pkru: 0x%x\n", __func__, pkey, rdpkru());
522 if (flags)
523 assert(rdpkru() > orig_pkru);
524}
525
526void pkey_write_allow(int pkey)
527{
528 pkey_disable_clear(pkey, PKEY_DISABLE_WRITE);
529}
530void pkey_write_deny(int pkey)
531{
532 pkey_disable_set(pkey, PKEY_DISABLE_WRITE);
533}
534void pkey_access_allow(int pkey)
535{
536 pkey_disable_clear(pkey, PKEY_DISABLE_ACCESS);
537}
538void pkey_access_deny(int pkey)
539{
540 pkey_disable_set(pkey, PKEY_DISABLE_ACCESS);
541}
542
543int sys_mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
544 unsigned long pkey)
545{
546 int sret;
547
548 dprintf2("%s(0x%p, %zx, prot=%lx, pkey=%lx)\n", __func__,
549 ptr, size, orig_prot, pkey);
550
551 errno = 0;
552 sret = syscall(SYS_mprotect_key, ptr, size, orig_prot, pkey);
553 if (errno) {
554 dprintf2("SYS_mprotect_key sret: %d\n", sret);
555 dprintf2("SYS_mprotect_key prot: 0x%lx\n", orig_prot);
556 dprintf2("SYS_mprotect_key failed, errno: %d\n", errno);
557 if (DEBUG_LEVEL >= 2)
558 perror("SYS_mprotect_pkey");
559 }
560 return sret;
561}
562
563int sys_pkey_alloc(unsigned long flags, unsigned long init_val)
564{
565 int ret = syscall(SYS_pkey_alloc, flags, init_val);
566 dprintf1("%s(flags=%lx, init_val=%lx) syscall ret: %d errno: %d\n",
567 __func__, flags, init_val, ret, errno);
568 return ret;
569}
570
571int alloc_pkey(void)
572{
573 int ret;
574 unsigned long init_val = 0x0;
575
576 dprintf1("alloc_pkey()::%d, pkru: 0x%x shadow: %x\n",
577 __LINE__, __rdpkru(), shadow_pkru);
578 ret = sys_pkey_alloc(0, init_val);
579 /*
580 * pkey_alloc() sets PKRU, so we need to reflect it in
581 * shadow_pkru:
582 */
583 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
584 __LINE__, ret, __rdpkru(), shadow_pkru);
585 if (ret) {
586 /* clear both the bits: */
587 shadow_pkru &= ~(0x3 << (ret * 2));
588 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
589 __LINE__, ret, __rdpkru(), shadow_pkru);
590 /*
591 * move the new state in from init_val
592 * (remember, we cheated and init_val == pkru format)
593 */
594 shadow_pkru |= (init_val << (ret * 2));
595 }
596 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
597 __LINE__, ret, __rdpkru(), shadow_pkru);
598 dprintf1("alloc_pkey()::%d errno: %d\n", __LINE__, errno);
599 /* for shadow checking: */
600 rdpkru();
601 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
602 __LINE__, ret, __rdpkru(), shadow_pkru);
603 return ret;
604}
605
606int sys_pkey_free(unsigned long pkey)
607{
608 int ret = syscall(SYS_pkey_free, pkey);
609 dprintf1("%s(pkey=%ld) syscall ret: %d\n", __func__, pkey, ret);
610 return ret;
611}
612
613/*
614 * I had a bug where pkey bits could be set by mprotect() but
615 * not cleared. This ensures we get lots of random bit sets
616 * and clears on the vma and pte pkey bits.
617 */
618int alloc_random_pkey(void)
619{
620 int max_nr_pkey_allocs;
621 int ret;
622 int i;
623 int alloced_pkeys[NR_PKEYS];
624 int nr_alloced = 0;
625 int random_index;
626 memset(alloced_pkeys, 0, sizeof(alloced_pkeys));
627
628 /* allocate every possible key and make a note of which ones we got */
629 max_nr_pkey_allocs = NR_PKEYS;
630 max_nr_pkey_allocs = 1;
631 for (i = 0; i < max_nr_pkey_allocs; i++) {
632 int new_pkey = alloc_pkey();
633 if (new_pkey < 0)
634 break;
635 alloced_pkeys[nr_alloced++] = new_pkey;
636 }
637
638 pkey_assert(nr_alloced > 0);
639 /* select a random one out of the allocated ones */
640 random_index = rand() % nr_alloced;
641 ret = alloced_pkeys[random_index];
642 /* now zero it out so we don't free it next */
643 alloced_pkeys[random_index] = 0;
644
645 /* go through the allocated ones that we did not want and free them */
646 for (i = 0; i < nr_alloced; i++) {
647 int free_ret;
648 if (!alloced_pkeys[i])
649 continue;
650 free_ret = sys_pkey_free(alloced_pkeys[i]);
651 pkey_assert(!free_ret);
652 }
653 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
654 __LINE__, ret, __rdpkru(), shadow_pkru);
655 return ret;
656}
657
658int mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
659 unsigned long pkey)
660{
661 int nr_iterations = random() % 100;
662 int ret;
663
664 while (0) {
665 int rpkey = alloc_random_pkey();
666 ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
667 dprintf1("sys_mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
668 ptr, size, orig_prot, pkey, ret);
669 if (nr_iterations-- < 0)
670 break;
671
672 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
673 __LINE__, ret, __rdpkru(), shadow_pkru);
674 sys_pkey_free(rpkey);
675 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
676 __LINE__, ret, __rdpkru(), shadow_pkru);
677 }
678 pkey_assert(pkey < NR_PKEYS);
679
680 ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
681 dprintf1("mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
682 ptr, size, orig_prot, pkey, ret);
683 pkey_assert(!ret);
684 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
685 __LINE__, ret, __rdpkru(), shadow_pkru);
686 return ret;
687}
688
689struct pkey_malloc_record {
690 void *ptr;
691 long size;
692};
693struct pkey_malloc_record *pkey_malloc_records;
694long nr_pkey_malloc_records;
695void record_pkey_malloc(void *ptr, long size)
696{
697 long i;
698 struct pkey_malloc_record *rec = NULL;
699
700 for (i = 0; i < nr_pkey_malloc_records; i++) {
701 rec = &pkey_malloc_records[i];
702 /* find a free record */
703 if (rec)
704 break;
705 }
706 if (!rec) {
707 /* every record is full */
708 size_t old_nr_records = nr_pkey_malloc_records;
709 size_t new_nr_records = (nr_pkey_malloc_records * 2 + 1);
710 size_t new_size = new_nr_records * sizeof(struct pkey_malloc_record);
711 dprintf2("new_nr_records: %zd\n", new_nr_records);
712 dprintf2("new_size: %zd\n", new_size);
713 pkey_malloc_records = realloc(pkey_malloc_records, new_size);
714 pkey_assert(pkey_malloc_records != NULL);
715 rec = &pkey_malloc_records[nr_pkey_malloc_records];
716 /*
717 * realloc() does not initialize memory, so zero it from
718 * the first new record all the way to the end.
719 */
720 for (i = 0; i < new_nr_records - old_nr_records; i++)
721 memset(rec + i, 0, sizeof(*rec));
722 }
723 dprintf3("filling malloc record[%d/%p]: {%p, %ld}\n",
724 (int)(rec - pkey_malloc_records), rec, ptr, size);
725 rec->ptr = ptr;
726 rec->size = size;
727 nr_pkey_malloc_records++;
728}
729
730void free_pkey_malloc(void *ptr)
731{
732 long i;
733 int ret;
734 dprintf3("%s(%p)\n", __func__, ptr);
735 for (i = 0; i < nr_pkey_malloc_records; i++) {
736 struct pkey_malloc_record *rec = &pkey_malloc_records[i];
737 dprintf4("looking for ptr %p at record[%ld/%p]: {%p, %ld}\n",
738 ptr, i, rec, rec->ptr, rec->size);
739 if ((ptr < rec->ptr) ||
740 (ptr >= rec->ptr + rec->size))
741 continue;
742
743 dprintf3("found ptr %p at record[%ld/%p]: {%p, %ld}\n",
744 ptr, i, rec, rec->ptr, rec->size);
745 nr_pkey_malloc_records--;
746 ret = munmap(rec->ptr, rec->size);
747 dprintf3("munmap ret: %d\n", ret);
748 pkey_assert(!ret);
749 dprintf3("clearing rec->ptr, rec: %p\n", rec);
750 rec->ptr = NULL;
751 dprintf3("done clearing rec->ptr, rec: %p\n", rec);
752 return;
753 }
754 pkey_assert(false);
755}
756
757
758void *malloc_pkey_with_mprotect(long size, int prot, u16 pkey)
759{
760 void *ptr;
761 int ret;
762
763 rdpkru();
764 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
765 size, prot, pkey);
766 pkey_assert(pkey < NR_PKEYS);
767 ptr = mmap(NULL, size, prot, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
768 pkey_assert(ptr != (void *)-1);
769 ret = mprotect_pkey((void *)ptr, PAGE_SIZE, prot, pkey);
770 pkey_assert(!ret);
771 record_pkey_malloc(ptr, size);
772 rdpkru();
773
774 dprintf1("%s() for pkey %d @ %p\n", __func__, pkey, ptr);
775 return ptr;
776}
777
778void *malloc_pkey_anon_huge(long size, int prot, u16 pkey)
779{
780 int ret;
781 void *ptr;
782
783 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
784 size, prot, pkey);
785 /*
786 * Guarantee we can fit at least one huge page in the resulting
787 * allocation by allocating space for 2:
788 */
789 size = ALIGN_UP(size, HPAGE_SIZE * 2);
790 ptr = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
791 pkey_assert(ptr != (void *)-1);
792 record_pkey_malloc(ptr, size);
793 mprotect_pkey(ptr, size, prot, pkey);
794
795 dprintf1("unaligned ptr: %p\n", ptr);
796 ptr = ALIGN_PTR_UP(ptr, HPAGE_SIZE);
797 dprintf1(" aligned ptr: %p\n", ptr);
798 ret = madvise(ptr, HPAGE_SIZE, MADV_HUGEPAGE);
799 dprintf1("MADV_HUGEPAGE ret: %d\n", ret);
800 ret = madvise(ptr, HPAGE_SIZE, MADV_WILLNEED);
801 dprintf1("MADV_WILLNEED ret: %d\n", ret);
802 memset(ptr, 0, HPAGE_SIZE);
803
804 dprintf1("mmap()'d thp for pkey %d @ %p\n", pkey, ptr);
805 return ptr;
806}
807
808int hugetlb_setup_ok;
809#define GET_NR_HUGE_PAGES 10
810void setup_hugetlbfs(void)
811{
812 int err;
813 int fd;
5f23f6d0
DH
814 char buf[] = "123";
815
816 if (geteuid() != 0) {
817 fprintf(stderr, "WARNING: not run as root, can not do hugetlb test\n");
818 return;
819 }
820
821 cat_into_file(__stringify(GET_NR_HUGE_PAGES), "/proc/sys/vm/nr_hugepages");
822
823 /*
824 * Now go make sure that we got the pages and that they
825 * are 2M pages. Someone might have made 1G the default.
826 */
827 fd = open("/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages", O_RDONLY);
828 if (fd < 0) {
829 perror("opening sysfs 2M hugetlb config");
830 return;
831 }
832
833 /* -1 to guarantee leaving the trailing \0 */
834 err = read(fd, buf, sizeof(buf)-1);
835 close(fd);
836 if (err <= 0) {
837 perror("reading sysfs 2M hugetlb config");
838 return;
839 }
840
841 if (atoi(buf) != GET_NR_HUGE_PAGES) {
842 fprintf(stderr, "could not confirm 2M pages, got: '%s' expected %d\n",
843 buf, GET_NR_HUGE_PAGES);
844 return;
845 }
846
847 hugetlb_setup_ok = 1;
848}
849
850void *malloc_pkey_hugetlb(long size, int prot, u16 pkey)
851{
852 void *ptr;
853 int flags = MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB;
854
855 if (!hugetlb_setup_ok)
856 return PTR_ERR_ENOTSUP;
857
858 dprintf1("doing %s(%ld, %x, %x)\n", __func__, size, prot, pkey);
859 size = ALIGN_UP(size, HPAGE_SIZE * 2);
860 pkey_assert(pkey < NR_PKEYS);
861 ptr = mmap(NULL, size, PROT_NONE, flags, -1, 0);
862 pkey_assert(ptr != (void *)-1);
863 mprotect_pkey(ptr, size, prot, pkey);
864
865 record_pkey_malloc(ptr, size);
866
867 dprintf1("mmap()'d hugetlbfs for pkey %d @ %p\n", pkey, ptr);
868 return ptr;
869}
870
871void *malloc_pkey_mmap_dax(long size, int prot, u16 pkey)
872{
873 void *ptr;
874 int fd;
875
876 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
877 size, prot, pkey);
878 pkey_assert(pkey < NR_PKEYS);
879 fd = open("/dax/foo", O_RDWR);
880 pkey_assert(fd >= 0);
881
882 ptr = mmap(0, size, prot, MAP_SHARED, fd, 0);
883 pkey_assert(ptr != (void *)-1);
884
885 mprotect_pkey(ptr, size, prot, pkey);
886
887 record_pkey_malloc(ptr, size);
888
889 dprintf1("mmap()'d for pkey %d @ %p\n", pkey, ptr);
890 close(fd);
891 return ptr;
892}
893
894void *(*pkey_malloc[])(long size, int prot, u16 pkey) = {
895
896 malloc_pkey_with_mprotect,
897 malloc_pkey_anon_huge,
898 malloc_pkey_hugetlb
899/* can not do direct with the pkey_mprotect() API:
900 malloc_pkey_mmap_direct,
901 malloc_pkey_mmap_dax,
902*/
903};
904
905void *malloc_pkey(long size, int prot, u16 pkey)
906{
907 void *ret;
908 static int malloc_type;
909 int nr_malloc_types = ARRAY_SIZE(pkey_malloc);
910
911 pkey_assert(pkey < NR_PKEYS);
912
913 while (1) {
914 pkey_assert(malloc_type < nr_malloc_types);
915
916 ret = pkey_malloc[malloc_type](size, prot, pkey);
917 pkey_assert(ret != (void *)-1);
918
919 malloc_type++;
920 if (malloc_type >= nr_malloc_types)
921 malloc_type = (random()%nr_malloc_types);
922
923 /* try again if the malloc_type we tried is unsupported */
924 if (ret == PTR_ERR_ENOTSUP)
925 continue;
926
927 break;
928 }
929
930 dprintf3("%s(%ld, prot=%x, pkey=%x) returning: %p\n", __func__,
931 size, prot, pkey, ret);
932 return ret;
933}
934
935int last_pkru_faults;
936void expected_pk_fault(int pkey)
937{
938 dprintf2("%s(): last_pkru_faults: %d pkru_faults: %d\n",
939 __func__, last_pkru_faults, pkru_faults);
940 dprintf2("%s(%d): last_si_pkey: %d\n", __func__, pkey, last_si_pkey);
941 pkey_assert(last_pkru_faults + 1 == pkru_faults);
942 pkey_assert(last_si_pkey == pkey);
943 /*
944 * The signal handler shold have cleared out PKRU to let the
945 * test program continue. We now have to restore it.
946 */
947 if (__rdpkru() != 0)
948 pkey_assert(0);
949
950 __wrpkru(shadow_pkru);
951 dprintf1("%s() set PKRU=%x to restore state after signal nuked it\n",
952 __func__, shadow_pkru);
953 last_pkru_faults = pkru_faults;
954 last_si_pkey = -1;
955}
956
957void do_not_expect_pk_fault(void)
958{
959 pkey_assert(last_pkru_faults == pkru_faults);
960}
961
962int test_fds[10] = { -1 };
963int nr_test_fds;
964void __save_test_fd(int fd)
965{
966 pkey_assert(fd >= 0);
967 pkey_assert(nr_test_fds < ARRAY_SIZE(test_fds));
968 test_fds[nr_test_fds] = fd;
969 nr_test_fds++;
970}
971
972int get_test_read_fd(void)
973{
974 int test_fd = open("/etc/passwd", O_RDONLY);
975 __save_test_fd(test_fd);
976 return test_fd;
977}
978
979void close_test_fds(void)
980{
981 int i;
982
983 for (i = 0; i < nr_test_fds; i++) {
984 if (test_fds[i] < 0)
985 continue;
986 close(test_fds[i]);
987 test_fds[i] = -1;
988 }
989 nr_test_fds = 0;
990}
991
992#define barrier() __asm__ __volatile__("": : :"memory")
993__attribute__((noinline)) int read_ptr(int *ptr)
994{
995 /*
996 * Keep GCC from optimizing this away somehow
997 */
998 barrier();
999 return *ptr;
1000}
1001
1002void test_read_of_write_disabled_region(int *ptr, u16 pkey)
1003{
1004 int ptr_contents;
1005
1006 dprintf1("disabling write access to PKEY[1], doing read\n");
1007 pkey_write_deny(pkey);
1008 ptr_contents = read_ptr(ptr);
1009 dprintf1("*ptr: %d\n", ptr_contents);
1010 dprintf1("\n");
1011}
1012void test_read_of_access_disabled_region(int *ptr, u16 pkey)
1013{
1014 int ptr_contents;
1015
1016 dprintf1("disabling access to PKEY[%02d], doing read @ %p\n", pkey, ptr);
1017 rdpkru();
1018 pkey_access_deny(pkey);
1019 ptr_contents = read_ptr(ptr);
1020 dprintf1("*ptr: %d\n", ptr_contents);
1021 expected_pk_fault(pkey);
1022}
1023void test_write_of_write_disabled_region(int *ptr, u16 pkey)
1024{
1025 dprintf1("disabling write access to PKEY[%02d], doing write\n", pkey);
1026 pkey_write_deny(pkey);
1027 *ptr = __LINE__;
1028 expected_pk_fault(pkey);
1029}
1030void test_write_of_access_disabled_region(int *ptr, u16 pkey)
1031{
1032 dprintf1("disabling access to PKEY[%02d], doing write\n", pkey);
1033 pkey_access_deny(pkey);
1034 *ptr = __LINE__;
1035 expected_pk_fault(pkey);
1036}
1037void test_kernel_write_of_access_disabled_region(int *ptr, u16 pkey)
1038{
1039 int ret;
1040 int test_fd = get_test_read_fd();
1041
1042 dprintf1("disabling access to PKEY[%02d], "
1043 "having kernel read() to buffer\n", pkey);
1044 pkey_access_deny(pkey);
1045 ret = read(test_fd, ptr, 1);
1046 dprintf1("read ret: %d\n", ret);
1047 pkey_assert(ret);
1048}
1049void test_kernel_write_of_write_disabled_region(int *ptr, u16 pkey)
1050{
1051 int ret;
1052 int test_fd = get_test_read_fd();
1053
1054 pkey_write_deny(pkey);
1055 ret = read(test_fd, ptr, 100);
1056 dprintf1("read ret: %d\n", ret);
1057 if (ret < 0 && (DEBUG_LEVEL > 0))
1058 perror("verbose read result (OK for this to be bad)");
1059 pkey_assert(ret);
1060}
1061
1062void test_kernel_gup_of_access_disabled_region(int *ptr, u16 pkey)
1063{
1064 int pipe_ret, vmsplice_ret;
1065 struct iovec iov;
1066 int pipe_fds[2];
1067
1068 pipe_ret = pipe(pipe_fds);
1069
1070 pkey_assert(pipe_ret == 0);
1071 dprintf1("disabling access to PKEY[%02d], "
1072 "having kernel vmsplice from buffer\n", pkey);
1073 pkey_access_deny(pkey);
1074 iov.iov_base = ptr;
1075 iov.iov_len = PAGE_SIZE;
1076 vmsplice_ret = vmsplice(pipe_fds[1], &iov, 1, SPLICE_F_GIFT);
1077 dprintf1("vmsplice() ret: %d\n", vmsplice_ret);
1078 pkey_assert(vmsplice_ret == -1);
1079
1080 close(pipe_fds[0]);
1081 close(pipe_fds[1]);
1082}
1083
1084void test_kernel_gup_write_to_write_disabled_region(int *ptr, u16 pkey)
1085{
1086 int ignored = 0xdada;
1087 int futex_ret;
1088 int some_int = __LINE__;
1089
1090 dprintf1("disabling write to PKEY[%02d], "
1091 "doing futex gunk in buffer\n", pkey);
1092 *ptr = some_int;
1093 pkey_write_deny(pkey);
1094 futex_ret = syscall(SYS_futex, ptr, FUTEX_WAIT, some_int-1, NULL,
1095 &ignored, ignored);
1096 if (DEBUG_LEVEL > 0)
1097 perror("futex");
1098 dprintf1("futex() ret: %d\n", futex_ret);
1099}
1100
1101/* Assumes that all pkeys other than 'pkey' are unallocated */
1102void test_pkey_syscalls_on_non_allocated_pkey(int *ptr, u16 pkey)
1103{
1104 int err;
1105 int i;
1106
1107 /* Note: 0 is the default pkey, so don't mess with it */
1108 for (i = 1; i < NR_PKEYS; i++) {
1109 if (pkey == i)
1110 continue;
1111
1112 dprintf1("trying get/set/free to non-allocated pkey: %2d\n", i);
1113 err = sys_pkey_free(i);
1114 pkey_assert(err);
1115
5f23f6d0
DH
1116 err = sys_pkey_free(i);
1117 pkey_assert(err);
1118
1119 err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, i);
1120 pkey_assert(err);
1121 }
1122}
1123
1124/* Assumes that all pkeys other than 'pkey' are unallocated */
1125void test_pkey_syscalls_bad_args(int *ptr, u16 pkey)
1126{
1127 int err;
5f23f6d0
DH
1128 int bad_pkey = NR_PKEYS+99;
1129
5f23f6d0
DH
1130 /* pass a known-invalid pkey in: */
1131 err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, bad_pkey);
1132 pkey_assert(err);
1133}
1134
1135/* Assumes that all pkeys other than 'pkey' are unallocated */
1136void test_pkey_alloc_exhaust(int *ptr, u16 pkey)
1137{
5f23f6d0
DH
1138 int err;
1139 int allocated_pkeys[NR_PKEYS] = {0};
1140 int nr_allocated_pkeys = 0;
1141 int i;
1142
1143 for (i = 0; i < NR_PKEYS*2; i++) {
1144 int new_pkey;
1145 dprintf1("%s() alloc loop: %d\n", __func__, i);
1146 new_pkey = alloc_pkey();
1147 dprintf4("%s()::%d, err: %d pkru: 0x%x shadow: 0x%x\n", __func__,
1148 __LINE__, err, __rdpkru(), shadow_pkru);
1149 rdpkru(); /* for shadow checking */
1150 dprintf2("%s() errno: %d ENOSPC: %d\n", __func__, errno, ENOSPC);
1151 if ((new_pkey == -1) && (errno == ENOSPC)) {
1152 dprintf2("%s() failed to allocate pkey after %d tries\n",
1153 __func__, nr_allocated_pkeys);
1154 break;
1155 }
1156 pkey_assert(nr_allocated_pkeys < NR_PKEYS);
1157 allocated_pkeys[nr_allocated_pkeys++] = new_pkey;
1158 }
1159
1160 dprintf3("%s()::%d\n", __func__, __LINE__);
1161
1162 /*
1163 * ensure it did not reach the end of the loop without
1164 * failure:
1165 */
1166 pkey_assert(i < NR_PKEYS*2);
1167
1168 /*
1169 * There are 16 pkeys supported in hardware. One is taken
1170 * up for the default (0) and another can be taken up by
1171 * an execute-only mapping. Ensure that we can allocate
1172 * at least 14 (16-2).
1173 */
1174 pkey_assert(i >= NR_PKEYS-2);
1175
1176 for (i = 0; i < nr_allocated_pkeys; i++) {
1177 err = sys_pkey_free(allocated_pkeys[i]);
1178 pkey_assert(!err);
1179 rdpkru(); /* for shadow checking */
1180 }
1181}
1182
1183void test_ptrace_of_child(int *ptr, u16 pkey)
1184{
1185 __attribute__((__unused__)) int peek_result;
1186 pid_t child_pid;
1187 void *ignored = 0;
1188 long ret;
1189 int status;
1190 /*
1191 * This is the "control" for our little expermient. Make sure
1192 * we can always access it when ptracing.
1193 */
1194 int *plain_ptr_unaligned = malloc(HPAGE_SIZE);
1195 int *plain_ptr = ALIGN_PTR_UP(plain_ptr_unaligned, PAGE_SIZE);
1196
1197 /*
1198 * Fork a child which is an exact copy of this process, of course.
1199 * That means we can do all of our tests via ptrace() and then plain
1200 * memory access and ensure they work differently.
1201 */
1202 child_pid = fork_lazy_child();
1203 dprintf1("[%d] child pid: %d\n", getpid(), child_pid);
1204
1205 ret = ptrace(PTRACE_ATTACH, child_pid, ignored, ignored);
1206 if (ret)
1207 perror("attach");
1208 dprintf1("[%d] attach ret: %ld %d\n", getpid(), ret, __LINE__);
1209 pkey_assert(ret != -1);
1210 ret = waitpid(child_pid, &status, WUNTRACED);
1211 if ((ret != child_pid) || !(WIFSTOPPED(status))) {
1212 fprintf(stderr, "weird waitpid result %ld stat %x\n",
1213 ret, status);
1214 pkey_assert(0);
1215 }
1216 dprintf2("waitpid ret: %ld\n", ret);
1217 dprintf2("waitpid status: %d\n", status);
1218
1219 pkey_access_deny(pkey);
1220 pkey_write_deny(pkey);
1221
1222 /* Write access, untested for now:
1223 ret = ptrace(PTRACE_POKEDATA, child_pid, peek_at, data);
1224 pkey_assert(ret != -1);
1225 dprintf1("poke at %p: %ld\n", peek_at, ret);
1226 */
1227
1228 /*
1229 * Try to access the pkey-protected "ptr" via ptrace:
1230 */
1231 ret = ptrace(PTRACE_PEEKDATA, child_pid, ptr, ignored);
1232 /* expect it to work, without an error: */
1233 pkey_assert(ret != -1);
1234 /* Now access from the current task, and expect an exception: */
1235 peek_result = read_ptr(ptr);
1236 expected_pk_fault(pkey);
1237
1238 /*
1239 * Try to access the NON-pkey-protected "plain_ptr" via ptrace:
1240 */
1241 ret = ptrace(PTRACE_PEEKDATA, child_pid, plain_ptr, ignored);
1242 /* expect it to work, without an error: */
1243 pkey_assert(ret != -1);
1244 /* Now access from the current task, and expect NO exception: */
1245 peek_result = read_ptr(plain_ptr);
1246 do_not_expect_pk_fault();
1247
1248 ret = ptrace(PTRACE_DETACH, child_pid, ignored, 0);
1249 pkey_assert(ret != -1);
1250
1251 ret = kill(child_pid, SIGKILL);
1252 pkey_assert(ret != -1);
1253
1254 wait(&status);
1255
1256 free(plain_ptr_unaligned);
1257}
1258
1259void test_executing_on_unreadable_memory(int *ptr, u16 pkey)
1260{
1261 void *p1;
1262 int scratch;
1263 int ptr_contents;
1264 int ret;
1265
1266 p1 = ALIGN_PTR_UP(&lots_o_noops_around_write, PAGE_SIZE);
1267 dprintf3("&lots_o_noops: %p\n", &lots_o_noops_around_write);
1268 /* lots_o_noops_around_write should be page-aligned already */
1269 assert(p1 == &lots_o_noops_around_write);
1270
1271 /* Point 'p1' at the *second* page of the function: */
1272 p1 += PAGE_SIZE;
1273
1274 madvise(p1, PAGE_SIZE, MADV_DONTNEED);
1275 lots_o_noops_around_write(&scratch);
1276 ptr_contents = read_ptr(p1);
1277 dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
1278
1279 ret = mprotect_pkey(p1, PAGE_SIZE, PROT_EXEC, (u64)pkey);
1280 pkey_assert(!ret);
1281 pkey_access_deny(pkey);
1282
1283 dprintf2("pkru: %x\n", rdpkru());
1284
1285 /*
1286 * Make sure this is an *instruction* fault
1287 */
1288 madvise(p1, PAGE_SIZE, MADV_DONTNEED);
1289 lots_o_noops_around_write(&scratch);
1290 do_not_expect_pk_fault();
1291 ptr_contents = read_ptr(p1);
1292 dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
1293 expected_pk_fault(pkey);
1294}
1295
1296void test_mprotect_pkey_on_unsupported_cpu(int *ptr, u16 pkey)
1297{
1298 int size = PAGE_SIZE;
1299 int sret;
1300
1301 if (cpu_has_pku()) {
1302 dprintf1("SKIP: %s: no CPU support\n", __func__);
1303 return;
1304 }
1305
1306 sret = syscall(SYS_mprotect_key, ptr, size, PROT_READ, pkey);
1307 pkey_assert(sret < 0);
1308}
1309
1310void (*pkey_tests[])(int *ptr, u16 pkey) = {
1311 test_read_of_write_disabled_region,
1312 test_read_of_access_disabled_region,
1313 test_write_of_write_disabled_region,
1314 test_write_of_access_disabled_region,
1315 test_kernel_write_of_access_disabled_region,
1316 test_kernel_write_of_write_disabled_region,
1317 test_kernel_gup_of_access_disabled_region,
1318 test_kernel_gup_write_to_write_disabled_region,
1319 test_executing_on_unreadable_memory,
1320 test_ptrace_of_child,
1321 test_pkey_syscalls_on_non_allocated_pkey,
1322 test_pkey_syscalls_bad_args,
1323 test_pkey_alloc_exhaust,
1324};
1325
1326void run_tests_once(void)
1327{
1328 int *ptr;
1329 int prot = PROT_READ|PROT_WRITE;
1330
1331 for (test_nr = 0; test_nr < ARRAY_SIZE(pkey_tests); test_nr++) {
1332 int pkey;
1333 int orig_pkru_faults = pkru_faults;
1334
1335 dprintf1("======================\n");
1336 dprintf1("test %d preparing...\n", test_nr);
1337
1338 tracing_on();
1339 pkey = alloc_random_pkey();
1340 dprintf1("test %d starting with pkey: %d\n", test_nr, pkey);
1341 ptr = malloc_pkey(PAGE_SIZE, prot, pkey);
1342 dprintf1("test %d starting...\n", test_nr);
1343 pkey_tests[test_nr](ptr, pkey);
1344 dprintf1("freeing test memory: %p\n", ptr);
1345 free_pkey_malloc(ptr);
1346 sys_pkey_free(pkey);
1347
1348 dprintf1("pkru_faults: %d\n", pkru_faults);
1349 dprintf1("orig_pkru_faults: %d\n", orig_pkru_faults);
1350
1351 tracing_off();
1352 close_test_fds();
1353
7738789f 1354 printf("test %2d PASSED (iteration %d)\n", test_nr, iteration_nr);
5f23f6d0
DH
1355 dprintf1("======================\n\n");
1356 }
1357 iteration_nr++;
1358}
1359
1360void pkey_setup_shadow(void)
1361{
1362 shadow_pkru = __rdpkru();
1363}
1364
1365int main(void)
1366{
1367 int nr_iterations = 22;
1368
1369 setup_handlers();
1370
1371 printf("has pku: %d\n", cpu_has_pku());
1372
1373 if (!cpu_has_pku()) {
1374 int size = PAGE_SIZE;
1375 int *ptr;
1376
1377 printf("running PKEY tests for unsupported CPU/OS\n");
1378
1379 ptr = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1380 assert(ptr != (void *)-1);
1381 test_mprotect_pkey_on_unsupported_cpu(ptr, 1);
1382 exit(0);
1383 }
1384
1385 pkey_setup_shadow();
1386 printf("startup pkru: %x\n", rdpkru());
1387 setup_hugetlbfs();
1388
1389 while (nr_iterations-- > 0)
1390 run_tests_once();
1391
1392 printf("done (all tests OK)\n");
1393 return 0;
1394}