2 * Tests x86 Memory Protection Keys (see Documentation/x86/protection-keys.txt)
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
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
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
25 #include <linux/futex.h>
27 #include <sys/syscall.h>
37 #include <sys/types.h>
42 #include <sys/ptrace.h>
45 #include "pkey-helpers.h"
50 unsigned int shadow_pkru
;
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)
61 #define PTR_ERR_ENOTSUP ((void *)-ENOTSUP)
64 char dprint_in_signal_buffer
[DPRINT_IN_SIGNAL_BUF_SIZE
];
66 extern void abort_hooks(void);
67 #define pkey_assert(condition) do { \
69 dprintf0("assert() at %s::%d test_nr: %d iteration: %d\n", \
71 test_nr, iteration_nr); \
72 dprintf0("errno at assert: %d", errno); \
77 #define raw_assert(cond) assert(cond)
79 void cat_into_file(char *str
, char *file
)
81 int fd
= open(file
, O_RDWR
);
84 dprintf2("%s(): writing '%s' to '%s'\n", __func__
, str
, file
);
86 * these need to be raw because they are called under
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
);
99 #if CONTROL_TRACING > 0
100 static int warned_tracing
;
101 int tracing_root_ok(void)
103 if (geteuid() != 0) {
105 fprintf(stderr
, "WARNING: not run as root, "
106 "can not do tracing control\n");
114 void tracing_on(void)
116 #if CONTROL_TRACING > 0
117 #define TRACEDIR "/sys/kernel/debug/tracing"
120 if (!tracing_root_ok())
123 sprintf(pidstr
, "%d", getpid());
124 cat_into_file("0", TRACEDIR
"/tracing_on");
125 cat_into_file("\n", TRACEDIR
"/trace");
127 cat_into_file("function_graph", TRACEDIR
"/current_tracer");
128 cat_into_file("1", TRACEDIR
"/options/funcgraph-proc");
130 cat_into_file("nop", TRACEDIR
"/current_tracer");
132 cat_into_file(pidstr
, TRACEDIR
"/set_ftrace_pid");
133 cat_into_file("1", TRACEDIR
"/tracing_on");
134 dprintf1("enabled tracing\n");
138 void tracing_off(void)
140 #if CONTROL_TRACING > 0
141 if (!tracing_root_ok())
143 cat_into_file("0", "/sys/kernel/debug/tracing/tracing_on");
147 void abort_hooks(void)
149 fprintf(stderr
, "running %s()...\n", __func__
);
151 #ifdef SLEEP_ON_ABORT
152 sleep(SLEEP_ON_ABORT
);
156 static inline void __page_o_noops(void)
158 /* 8-bytes of instruction * 512 bytes = 1 page */
159 asm(".rept 512 ; nopl 0x7eeeeeee(%eax) ; .endr");
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.
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.
172 __attribute__((__aligned__(PAGE_SIZE
)))
173 void lots_o_noops_around_write(int *write_to_me
)
175 dprintf3("running %s()\n", __func__
);
177 /* Assume this happens in the second page of instructions: */
178 *write_to_me
= __LINE__
;
179 /* pad out by another page: */
181 dprintf3("%s() done\n", __func__
);
184 /* Define some kernel-like types */
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
195 #define si_pkey_offset 0x14
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
204 void dump_mem(void *dumpme
, int len_bytes
)
206 char *c
= (void *)dumpme
;
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
);
215 #define SEGV_BNDERR 3 /* failed address bound checks */
216 #define SEGV_PKUERR 4
218 static char *si_code_str(int si_code
)
220 if (si_code
== SEGV_MAPERR
)
221 return "SEGV_MAPERR";
222 if (si_code
== SEGV_ACCERR
)
223 return "SEGV_ACCERR";
224 if (si_code
== SEGV_BNDERR
)
225 return "SEGV_BNDERR";
226 if (si_code
== SEGV_PKUERR
)
227 return "SEGV_PKUERR";
232 int last_si_pkey
= -1;
233 void signal_handler(int signum
, siginfo_t
*si
, void *vucontext
)
235 ucontext_t
*uctxt
= vucontext
;
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
);
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
;
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
);
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.
265 pkru_offset
= pkru_xstate_offset();
266 pkru_ptr
= (void *)(&fpregs
[pkru_offset
]);
268 dprintf1("siginfo: %p\n", si
);
269 dprintf1(" fpregs: %p\n", fpregs
);
271 * If we got a PKRU fault, we *HAVE* to have at least one bit set in
274 dprintf1("pkru_xstate_offset: %d\n", pkru_xstate_offset());
276 dump_mem(pkru_ptr
- 128, 256);
277 pkey_assert(*pkru_ptr
);
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
;
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");
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");
300 dprintf1("<<<<==================================================\n");
304 "ERROR: In signal handler, page fault, trapno = %d, ip = %016lx\n",
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
]);
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
]);
317 dprint_in_signal
= 0;
320 int wait_all_children(void)
323 return waitpid(-1, &status
, 0);
328 dprint_in_signal
= 1;
329 dprintf2("[%d] SIGCHLD: %d\n", getpid(), x
);
330 dprint_in_signal
= 0;
333 void setup_sigsegv_handler(void)
336 struct sigaction newact
;
337 struct sigaction oldact
;
339 /* #PF is mapped to sigsegv */
340 int signum
= SIGSEGV
;
342 newact
.sa_handler
= 0;
343 newact
.sa_sigaction
= signal_handler
;
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);
350 /* call sa_sigaction, not sa_handler*/
351 newact
.sa_flags
= SA_SIGINFO
;
353 newact
.sa_restorer
= 0; /* void(*)(), obsolete */
354 r
= sigaction(signum
, &newact
, &oldact
);
355 r
= sigaction(SIGALRM
, &newact
, &oldact
);
359 void setup_handlers(void)
361 signal(SIGCHLD
, &sig_chld
);
362 setup_sigsegv_handler();
365 pid_t
fork_lazy_child(void)
370 pkey_assert(forkret
>= 0);
371 dprintf3("[%d] fork() ret: %d\n", getpid(), forkret
);
376 dprintf1("child sleeping...\n");
383 void davecmp(void *_a
, void *_b
, int len
)
386 unsigned long *a
= _a
;
387 unsigned long *b
= _b
;
389 for (i
= 0; i
< len
/ sizeof(*a
); i
++) {
393 dprintf3("[%3d]: a: %016lx b: %016lx\n", i
, a
[i
], b
[i
]);
399 int fd
= open(f
, O_RDONLY
);
403 dprintf2("maps fd: %d\n", fd
);
405 nr_read
= read(fd
, &buf
[0], sizeof(buf
));
406 write(1, buf
, nr_read
);
407 } while (nr_read
> 0);
411 #define PKEY_DISABLE_ACCESS 0x1
412 #define PKEY_DISABLE_WRITE 0x2
414 u32
pkey_get(int pkey
, unsigned long flags
)
416 u32 mask
= (PKEY_DISABLE_ACCESS
|PKEY_DISABLE_WRITE
);
417 u32 pkru
= __rdpkru();
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
);
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
);
430 * shift down the relevant bits to the lowest two, then
431 * mask off all the other high bits.
436 int pkey_set(int pkey
, unsigned long rights
, unsigned long flags
)
438 u32 mask
= (PKEY_DISABLE_ACCESS
|PKEY_DISABLE_WRITE
);
439 u32 old_pkru
= __rdpkru();
442 /* make sure that 'rights' only contains the bits we expect: */
443 assert(!(rights
& ~mask
));
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
));
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
);
459 void pkey_disable_set(int pkey
, int flags
)
461 unsigned long syscall_flags
= 0;
464 u32 orig_pkru
= rdpkru();
466 dprintf1("START->%s(%d, 0x%x)\n", __func__
,
468 pkey_assert(flags
& (PKEY_DISABLE_ACCESS
| PKEY_DISABLE_WRITE
));
470 pkey_rights
= pkey_get(pkey
, syscall_flags
);
472 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__
,
473 pkey
, pkey
, pkey_rights
);
474 pkey_assert(pkey_rights
>= 0);
476 pkey_rights
|= flags
;
478 ret
= pkey_set(pkey
, pkey_rights
, syscall_flags
);
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
);
484 pkey_assert(ret
>= 0);
486 pkey_rights
= pkey_get(pkey
, syscall_flags
);
487 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__
,
488 pkey
, pkey
, pkey_rights
);
490 dprintf1("%s(%d) pkru: 0x%x\n", __func__
, pkey
, rdpkru());
492 pkey_assert(rdpkru() > orig_pkru
);
493 dprintf1("END<---%s(%d, 0x%x)\n", __func__
,
497 void pkey_disable_clear(int pkey
, int flags
)
499 unsigned long syscall_flags
= 0;
501 int pkey_rights
= pkey_get(pkey
, syscall_flags
);
502 u32 orig_pkru
= rdpkru();
504 pkey_assert(flags
& (PKEY_DISABLE_ACCESS
| PKEY_DISABLE_WRITE
));
506 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__
,
507 pkey
, pkey
, pkey_rights
);
508 pkey_assert(pkey_rights
>= 0);
510 pkey_rights
|= flags
;
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);
517 pkey_rights
= pkey_get(pkey
, syscall_flags
);
518 dprintf1("%s(%d) pkey_get(%d): %x\n", __func__
,
519 pkey
, pkey
, pkey_rights
);
521 dprintf1("%s(%d) pkru: 0x%x\n", __func__
, pkey
, rdpkru());
523 assert(rdpkru() > orig_pkru
);
526 void pkey_write_allow(int pkey
)
528 pkey_disable_clear(pkey
, PKEY_DISABLE_WRITE
);
530 void pkey_write_deny(int pkey
)
532 pkey_disable_set(pkey
, PKEY_DISABLE_WRITE
);
534 void pkey_access_allow(int pkey
)
536 pkey_disable_clear(pkey
, PKEY_DISABLE_ACCESS
);
538 void pkey_access_deny(int pkey
)
540 pkey_disable_set(pkey
, PKEY_DISABLE_ACCESS
);
543 int sys_mprotect_pkey(void *ptr
, size_t size
, unsigned long orig_prot
,
548 dprintf2("%s(0x%p, %zx, prot=%lx, pkey=%lx)\n", __func__
,
549 ptr
, size
, orig_prot
, pkey
);
552 sret
= syscall(SYS_mprotect_key
, ptr
, size
, orig_prot
, pkey
);
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");
563 int sys_pkey_alloc(unsigned long flags
, unsigned long init_val
)
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
);
574 unsigned long init_val
= 0x0;
576 dprintf1("alloc_pkey()::%d, pkru: 0x%x shadow: %x\n",
577 __LINE__
, __rdpkru(), shadow_pkru
);
578 ret
= sys_pkey_alloc(0, init_val
);
580 * pkey_alloc() sets PKRU, so we need to reflect it in
583 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
584 __LINE__
, ret
, __rdpkru(), shadow_pkru
);
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
);
591 * move the new state in from init_val
592 * (remember, we cheated and init_val == pkru format)
594 shadow_pkru
|= (init_val
<< (ret
* 2));
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: */
601 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
602 __LINE__
, ret
, __rdpkru(), shadow_pkru
);
606 int sys_pkey_free(unsigned long pkey
)
608 int ret
= syscall(SYS_pkey_free
, pkey
);
609 dprintf1("%s(pkey=%ld) syscall ret: %d\n", __func__
, pkey
, ret
);
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.
618 int alloc_random_pkey(void)
620 int max_nr_pkey_allocs
;
623 int alloced_pkeys
[NR_PKEYS
];
626 memset(alloced_pkeys
, 0, sizeof(alloced_pkeys
));
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();
635 alloced_pkeys
[nr_alloced
++] = new_pkey
;
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;
645 /* go through the allocated ones that we did not want and free them */
646 for (i
= 0; i
< nr_alloced
; i
++) {
648 if (!alloced_pkeys
[i
])
650 free_ret
= sys_pkey_free(alloced_pkeys
[i
]);
651 pkey_assert(!free_ret
);
653 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__
,
654 __LINE__
, ret
, __rdpkru(), shadow_pkru
);
658 int mprotect_pkey(void *ptr
, size_t size
, unsigned long orig_prot
,
661 int nr_iterations
= random() % 100;
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)
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
);
678 pkey_assert(pkey
< NR_PKEYS
);
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
);
684 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__
,
685 __LINE__
, ret
, __rdpkru(), shadow_pkru
);
689 struct pkey_malloc_record
{
693 struct pkey_malloc_record
*pkey_malloc_records
;
694 long nr_pkey_malloc_records
;
695 void record_pkey_malloc(void *ptr
, long size
)
698 struct pkey_malloc_record
*rec
= NULL
;
700 for (i
= 0; i
< nr_pkey_malloc_records
; i
++) {
701 rec
= &pkey_malloc_records
[i
];
702 /* find a free record */
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
];
717 * realloc() does not initialize memory, so zero it from
718 * the first new record all the way to the end.
720 for (i
= 0; i
< new_nr_records
- old_nr_records
; i
++)
721 memset(rec
+ i
, 0, sizeof(*rec
));
723 dprintf3("filling malloc record[%d/%p]: {%p, %ld}\n",
724 (int)(rec
- pkey_malloc_records
), rec
, ptr
, size
);
727 nr_pkey_malloc_records
++;
730 void free_pkey_malloc(void *ptr
)
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
))
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
);
749 dprintf3("clearing rec->ptr, rec: %p\n", rec
);
751 dprintf3("done clearing rec->ptr, rec: %p\n", rec
);
758 void *malloc_pkey_with_mprotect(long size
, int prot
, u16 pkey
)
764 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__
,
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
);
771 record_pkey_malloc(ptr
, size
);
774 dprintf1("%s() for pkey %d @ %p\n", __func__
, pkey
, ptr
);
778 void *malloc_pkey_anon_huge(long size
, int prot
, u16 pkey
)
783 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__
,
786 * Guarantee we can fit at least one huge page in the resulting
787 * allocation by allocating space for 2:
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
);
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
);
804 dprintf1("mmap()'d thp for pkey %d @ %p\n", pkey
, ptr
);
808 int hugetlb_setup_ok
;
809 #define GET_NR_HUGE_PAGES 10
810 void setup_hugetlbfs(void)
816 if (geteuid() != 0) {
817 fprintf(stderr
, "WARNING: not run as root, can not do hugetlb test\n");
821 cat_into_file(__stringify(GET_NR_HUGE_PAGES
), "/proc/sys/vm/nr_hugepages");
824 * Now go make sure that we got the pages and that they
825 * are 2M pages. Someone might have made 1G the default.
827 fd
= open("/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages", O_RDONLY
);
829 perror("opening sysfs 2M hugetlb config");
833 /* -1 to guarantee leaving the trailing \0 */
834 err
= read(fd
, buf
, sizeof(buf
)-1);
837 perror("reading sysfs 2M hugetlb config");
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
);
847 hugetlb_setup_ok
= 1;
850 void *malloc_pkey_hugetlb(long size
, int prot
, u16 pkey
)
853 int flags
= MAP_ANONYMOUS
|MAP_PRIVATE
|MAP_HUGETLB
;
855 if (!hugetlb_setup_ok
)
856 return PTR_ERR_ENOTSUP
;
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
);
865 record_pkey_malloc(ptr
, size
);
867 dprintf1("mmap()'d hugetlbfs for pkey %d @ %p\n", pkey
, ptr
);
871 void *malloc_pkey_mmap_dax(long size
, int prot
, u16 pkey
)
876 dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__
,
878 pkey_assert(pkey
< NR_PKEYS
);
879 fd
= open("/dax/foo", O_RDWR
);
880 pkey_assert(fd
>= 0);
882 ptr
= mmap(0, size
, prot
, MAP_SHARED
, fd
, 0);
883 pkey_assert(ptr
!= (void *)-1);
885 mprotect_pkey(ptr
, size
, prot
, pkey
);
887 record_pkey_malloc(ptr
, size
);
889 dprintf1("mmap()'d for pkey %d @ %p\n", pkey
, ptr
);
894 void *(*pkey_malloc
[])(long size
, int prot
, u16 pkey
) = {
896 malloc_pkey_with_mprotect
,
897 malloc_pkey_anon_huge
,
899 /* can not do direct with the pkey_mprotect() API:
900 malloc_pkey_mmap_direct,
901 malloc_pkey_mmap_dax,
905 void *malloc_pkey(long size
, int prot
, u16 pkey
)
908 static int malloc_type
;
909 int nr_malloc_types
= ARRAY_SIZE(pkey_malloc
);
911 pkey_assert(pkey
< NR_PKEYS
);
914 pkey_assert(malloc_type
< nr_malloc_types
);
916 ret
= pkey_malloc
[malloc_type
](size
, prot
, pkey
);
917 pkey_assert(ret
!= (void *)-1);
920 if (malloc_type
>= nr_malloc_types
)
921 malloc_type
= (random()%nr_malloc_types
);
923 /* try again if the malloc_type we tried is unsupported */
924 if (ret
== PTR_ERR_ENOTSUP
)
930 dprintf3("%s(%ld, prot=%x, pkey=%x) returning: %p\n", __func__
,
931 size
, prot
, pkey
, ret
);
935 int last_pkru_faults
;
936 void expected_pk_fault(int pkey
)
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
);
944 * The signal handler shold have cleared out PKRU to let the
945 * test program continue. We now have to restore it.
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
;
957 void do_not_expect_pk_fault(void)
959 pkey_assert(last_pkru_faults
== pkru_faults
);
962 int test_fds
[10] = { -1 };
964 void __save_test_fd(int fd
)
966 pkey_assert(fd
>= 0);
967 pkey_assert(nr_test_fds
< ARRAY_SIZE(test_fds
));
968 test_fds
[nr_test_fds
] = fd
;
972 int get_test_read_fd(void)
974 int test_fd
= open("/etc/passwd", O_RDONLY
);
975 __save_test_fd(test_fd
);
979 void close_test_fds(void)
983 for (i
= 0; i
< nr_test_fds
; i
++) {
992 #define barrier() __asm__ __volatile__("": : :"memory")
993 __attribute__((noinline
)) int read_ptr(int *ptr
)
996 * Keep GCC from optimizing this away somehow
1002 void test_read_of_write_disabled_region(int *ptr
, u16 pkey
)
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
);
1012 void test_read_of_access_disabled_region(int *ptr
, u16 pkey
)
1016 dprintf1("disabling access to PKEY[%02d], doing read @ %p\n", pkey
, ptr
);
1018 pkey_access_deny(pkey
);
1019 ptr_contents
= read_ptr(ptr
);
1020 dprintf1("*ptr: %d\n", ptr_contents
);
1021 expected_pk_fault(pkey
);
1023 void test_write_of_write_disabled_region(int *ptr
, u16 pkey
)
1025 dprintf1("disabling write access to PKEY[%02d], doing write\n", pkey
);
1026 pkey_write_deny(pkey
);
1028 expected_pk_fault(pkey
);
1030 void test_write_of_access_disabled_region(int *ptr
, u16 pkey
)
1032 dprintf1("disabling access to PKEY[%02d], doing write\n", pkey
);
1033 pkey_access_deny(pkey
);
1035 expected_pk_fault(pkey
);
1037 void test_kernel_write_of_access_disabled_region(int *ptr
, u16 pkey
)
1040 int test_fd
= get_test_read_fd();
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
);
1049 void test_kernel_write_of_write_disabled_region(int *ptr
, u16 pkey
)
1052 int test_fd
= get_test_read_fd();
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)");
1062 void test_kernel_gup_of_access_disabled_region(int *ptr
, u16 pkey
)
1064 int pipe_ret
, vmsplice_ret
;
1068 pipe_ret
= pipe(pipe_fds
);
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
);
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);
1084 void test_kernel_gup_write_to_write_disabled_region(int *ptr
, u16 pkey
)
1086 int ignored
= 0xdada;
1088 int some_int
= __LINE__
;
1090 dprintf1("disabling write to PKEY[%02d], "
1091 "doing futex gunk in buffer\n", pkey
);
1093 pkey_write_deny(pkey
);
1094 futex_ret
= syscall(SYS_futex
, ptr
, FUTEX_WAIT
, some_int
-1, NULL
,
1096 if (DEBUG_LEVEL
> 0)
1098 dprintf1("futex() ret: %d\n", futex_ret
);
1101 /* Assumes that all pkeys other than 'pkey' are unallocated */
1102 void test_pkey_syscalls_on_non_allocated_pkey(int *ptr
, u16 pkey
)
1107 /* Note: 0 is the default pkey, so don't mess with it */
1108 for (i
= 1; i
< NR_PKEYS
; i
++) {
1112 dprintf1("trying get/set/free to non-allocated pkey: %2d\n", i
);
1113 err
= sys_pkey_free(i
);
1116 err
= sys_pkey_free(i
);
1119 err
= sys_mprotect_pkey(ptr
, PAGE_SIZE
, PROT_READ
, i
);
1124 /* Assumes that all pkeys other than 'pkey' are unallocated */
1125 void test_pkey_syscalls_bad_args(int *ptr
, u16 pkey
)
1128 int bad_pkey
= NR_PKEYS
+99;
1130 /* pass a known-invalid pkey in: */
1131 err
= sys_mprotect_pkey(ptr
, PAGE_SIZE
, PROT_READ
, bad_pkey
);
1135 /* Assumes that all pkeys other than 'pkey' are unallocated */
1136 void test_pkey_alloc_exhaust(int *ptr
, u16 pkey
)
1139 int allocated_pkeys
[NR_PKEYS
] = {0};
1140 int nr_allocated_pkeys
= 0;
1143 for (i
= 0; i
< NR_PKEYS
*2; i
++) {
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
);
1156 pkey_assert(nr_allocated_pkeys
< NR_PKEYS
);
1157 allocated_pkeys
[nr_allocated_pkeys
++] = new_pkey
;
1160 dprintf3("%s()::%d\n", __func__
, __LINE__
);
1163 * ensure it did not reach the end of the loop without
1166 pkey_assert(i
< NR_PKEYS
*2);
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).
1174 pkey_assert(i
>= NR_PKEYS
-2);
1176 for (i
= 0; i
< nr_allocated_pkeys
; i
++) {
1177 err
= sys_pkey_free(allocated_pkeys
[i
]);
1179 rdpkru(); /* for shadow checking */
1183 void test_ptrace_of_child(int *ptr
, u16 pkey
)
1185 __attribute__((__unused__
)) int peek_result
;
1191 * This is the "control" for our little expermient. Make sure
1192 * we can always access it when ptracing.
1194 int *plain_ptr_unaligned
= malloc(HPAGE_SIZE
);
1195 int *plain_ptr
= ALIGN_PTR_UP(plain_ptr_unaligned
, PAGE_SIZE
);
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.
1202 child_pid
= fork_lazy_child();
1203 dprintf1("[%d] child pid: %d\n", getpid(), child_pid
);
1205 ret
= ptrace(PTRACE_ATTACH
, child_pid
, ignored
, ignored
);
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",
1216 dprintf2("waitpid ret: %ld\n", ret
);
1217 dprintf2("waitpid status: %d\n", status
);
1219 pkey_access_deny(pkey
);
1220 pkey_write_deny(pkey
);
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);
1229 * Try to access the pkey-protected "ptr" via ptrace:
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
);
1239 * Try to access the NON-pkey-protected "plain_ptr" via ptrace:
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();
1248 ret
= ptrace(PTRACE_DETACH
, child_pid
, ignored
, 0);
1249 pkey_assert(ret
!= -1);
1251 ret
= kill(child_pid
, SIGKILL
);
1252 pkey_assert(ret
!= -1);
1256 free(plain_ptr_unaligned
);
1259 void test_executing_on_unreadable_memory(int *ptr
, u16 pkey
)
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
);
1271 /* Point 'p1' at the *second* page of the function: */
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
);
1279 ret
= mprotect_pkey(p1
, PAGE_SIZE
, PROT_EXEC
, (u64
)pkey
);
1281 pkey_access_deny(pkey
);
1283 dprintf2("pkru: %x\n", rdpkru());
1286 * Make sure this is an *instruction* fault
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
);
1296 void test_mprotect_pkey_on_unsupported_cpu(int *ptr
, u16 pkey
)
1298 int size
= PAGE_SIZE
;
1301 if (cpu_has_pku()) {
1302 dprintf1("SKIP: %s: no CPU support\n", __func__
);
1306 sret
= syscall(SYS_mprotect_key
, ptr
, size
, PROT_READ
, pkey
);
1307 pkey_assert(sret
< 0);
1310 void (*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
,
1326 void run_tests_once(void)
1329 int prot
= PROT_READ
|PROT_WRITE
;
1331 for (test_nr
= 0; test_nr
< ARRAY_SIZE(pkey_tests
); test_nr
++) {
1333 int orig_pkru_faults
= pkru_faults
;
1335 dprintf1("======================\n");
1336 dprintf1("test %d preparing...\n", test_nr
);
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
);
1348 dprintf1("pkru_faults: %d\n", pkru_faults
);
1349 dprintf1("orig_pkru_faults: %d\n", orig_pkru_faults
);
1354 printf("test %2d PASSED (iteration %d)\n", test_nr
, iteration_nr
);
1355 dprintf1("======================\n\n");
1360 void pkey_setup_shadow(void)
1362 shadow_pkru
= __rdpkru();
1367 int nr_iterations
= 22;
1371 printf("has pku: %d\n", cpu_has_pku());
1373 if (!cpu_has_pku()) {
1374 int size
= PAGE_SIZE
;
1377 printf("running PKEY tests for unsupported CPU/OS\n");
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);
1385 pkey_setup_shadow();
1386 printf("startup pkru: %x\n", rdpkru());
1389 while (nr_iterations
-- > 0)
1392 printf("done (all tests OK)\n");