protection_keys.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Tests Memory Protection Keys (see Documentation/core-api/protection-keys.rst)
  4. *
  5. * There are examples in here of:
  6. * * how to set protection keys on memory
  7. * * how to set/clear bits in pkey registers (the rights register)
  8. * * how to handle SEGV_PKUERR signals and extract pkey-relevant
  9. * information from the siginfo
  10. *
  11. * Things to add:
  12. * make sure KSM and KSM COW breaking works
  13. * prefault pages in at malloc, or not
  14. * protect MPX bounds tables with protection keys?
  15. * make sure VMA splitting/merging is working correctly
  16. * OOMs can destroy mm->mmap (see exit_mmap()), so make sure it is immune to pkeys
  17. * look for pkey "leaks" where it is still set on a VMA but "freed" back to the kernel
  18. * do a plain mprotect() to a mprotect_pkey() area and make sure the pkey sticks
  19. *
  20. * Compile like this:
  21. * gcc -mxsave -o protection_keys -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
  22. * gcc -mxsave -m32 -o protection_keys_32 -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
  23. */
  24. #define _GNU_SOURCE
  25. #define __SANE_USERSPACE_TYPES__
  26. #include <errno.h>
  27. #include <linux/elf.h>
  28. #include <linux/futex.h>
  29. #include <time.h>
  30. #include <sys/time.h>
  31. #include <sys/syscall.h>
  32. #include <string.h>
  33. #include <stdio.h>
  34. #include <stdint.h>
  35. #include <stdbool.h>
  36. #include <signal.h>
  37. #include <assert.h>
  38. #include <stdlib.h>
  39. #include <ucontext.h>
  40. #include <sys/mman.h>
  41. #include <sys/types.h>
  42. #include <sys/wait.h>
  43. #include <sys/stat.h>
  44. #include <fcntl.h>
  45. #include <unistd.h>
  46. #include <sys/ptrace.h>
  47. #include <setjmp.h>
  48. #include "pkey-helpers.h"
  49. int iteration_nr = 1;
  50. int test_nr;
  51. u64 shadow_pkey_reg;
  52. int dprint_in_signal;
  53. char dprint_in_signal_buffer[DPRINT_IN_SIGNAL_BUF_SIZE];
  54. void cat_into_file(char *str, char *file)
  55. {
  56. int fd = open(file, O_RDWR);
  57. int ret;
  58. dprintf2("%s(): writing '%s' to '%s'\n", __func__, str, file);
  59. /*
  60. * these need to be raw because they are called under
  61. * pkey_assert()
  62. */
  63. if (fd < 0) {
  64. fprintf(stderr, "error opening '%s'\n", str);
  65. perror("error: ");
  66. exit(__LINE__);
  67. }
  68. ret = write(fd, str, strlen(str));
  69. if (ret != strlen(str)) {
  70. perror("write to file failed");
  71. fprintf(stderr, "filename: '%s' str: '%s'\n", file, str);
  72. exit(__LINE__);
  73. }
  74. close(fd);
  75. }
  76. #if CONTROL_TRACING > 0
  77. static int warned_tracing;
  78. int tracing_root_ok(void)
  79. {
  80. if (geteuid() != 0) {
  81. if (!warned_tracing)
  82. fprintf(stderr, "WARNING: not run as root, "
  83. "can not do tracing control\n");
  84. warned_tracing = 1;
  85. return 0;
  86. }
  87. return 1;
  88. }
  89. #endif
  90. void tracing_on(void)
  91. {
  92. #if CONTROL_TRACING > 0
  93. #define TRACEDIR "/sys/kernel/tracing"
  94. char pidstr[32];
  95. if (!tracing_root_ok())
  96. return;
  97. sprintf(pidstr, "%d", getpid());
  98. cat_into_file("0", TRACEDIR "/tracing_on");
  99. cat_into_file("\n", TRACEDIR "/trace");
  100. if (1) {
  101. cat_into_file("function_graph", TRACEDIR "/current_tracer");
  102. cat_into_file("1", TRACEDIR "/options/funcgraph-proc");
  103. } else {
  104. cat_into_file("nop", TRACEDIR "/current_tracer");
  105. }
  106. cat_into_file(pidstr, TRACEDIR "/set_ftrace_pid");
  107. cat_into_file("1", TRACEDIR "/tracing_on");
  108. dprintf1("enabled tracing\n");
  109. #endif
  110. }
  111. void tracing_off(void)
  112. {
  113. #if CONTROL_TRACING > 0
  114. if (!tracing_root_ok())
  115. return;
  116. cat_into_file("0", "/sys/kernel/tracing/tracing_on");
  117. #endif
  118. }
  119. void abort_hooks(void)
  120. {
  121. fprintf(stderr, "running %s()...\n", __func__);
  122. tracing_off();
  123. #ifdef SLEEP_ON_ABORT
  124. sleep(SLEEP_ON_ABORT);
  125. #endif
  126. }
  127. /*
  128. * This attempts to have roughly a page of instructions followed by a few
  129. * instructions that do a write, and another page of instructions. That
  130. * way, we are pretty sure that the write is in the second page of
  131. * instructions and has at least a page of padding behind it.
  132. *
  133. * *That* lets us be sure to madvise() away the write instruction, which
  134. * will then fault, which makes sure that the fault code handles
  135. * execute-only memory properly.
  136. */
  137. #if defined(__powerpc64__) || defined(__aarch64__)
  138. /* This way, both 4K and 64K alignment are maintained */
  139. __attribute__((__aligned__(65536)))
  140. #else
  141. __attribute__((__aligned__(PAGE_SIZE)))
  142. #endif
  143. void lots_o_noops_around_write(int *write_to_me)
  144. {
  145. dprintf3("running %s()\n", __func__);
  146. __page_o_noops();
  147. /* Assume this happens in the second page of instructions: */
  148. *write_to_me = __LINE__;
  149. /* pad out by another page: */
  150. __page_o_noops();
  151. dprintf3("%s() done\n", __func__);
  152. }
  153. void dump_mem(void *dumpme, int len_bytes)
  154. {
  155. char *c = (void *)dumpme;
  156. int i;
  157. for (i = 0; i < len_bytes; i += sizeof(u64)) {
  158. u64 *ptr = (u64 *)(c + i);
  159. dprintf1("dump[%03d][@%p]: %016llx\n", i, ptr, *ptr);
  160. }
  161. }
  162. static u32 hw_pkey_get(int pkey, unsigned long flags)
  163. {
  164. u64 pkey_reg = __read_pkey_reg();
  165. dprintf1("%s(pkey=%d, flags=%lx) = %x / %d\n",
  166. __func__, pkey, flags, 0, 0);
  167. dprintf2("%s() raw pkey_reg: %016llx\n", __func__, pkey_reg);
  168. return (u32) get_pkey_bits(pkey_reg, pkey);
  169. }
  170. static int hw_pkey_set(int pkey, unsigned long rights, unsigned long flags)
  171. {
  172. u32 mask = (PKEY_DISABLE_ACCESS|PKEY_DISABLE_WRITE);
  173. u64 old_pkey_reg = __read_pkey_reg();
  174. u64 new_pkey_reg;
  175. /* make sure that 'rights' only contains the bits we expect: */
  176. assert(!(rights & ~mask));
  177. /* modify bits accordingly in old pkey_reg and assign it */
  178. new_pkey_reg = set_pkey_bits(old_pkey_reg, pkey, rights);
  179. __write_pkey_reg(new_pkey_reg);
  180. dprintf3("%s(pkey=%d, rights=%lx, flags=%lx) = %x"
  181. " pkey_reg now: %016llx old_pkey_reg: %016llx\n",
  182. __func__, pkey, rights, flags, 0, __read_pkey_reg(),
  183. old_pkey_reg);
  184. return 0;
  185. }
  186. void pkey_disable_set(int pkey, int flags)
  187. {
  188. unsigned long syscall_flags = 0;
  189. int ret;
  190. int pkey_rights;
  191. dprintf1("START->%s(%d, 0x%x)\n", __func__,
  192. pkey, flags);
  193. pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
  194. pkey_rights = hw_pkey_get(pkey, syscall_flags);
  195. dprintf1("%s(%d) hw_pkey_get(%d): %x\n", __func__,
  196. pkey, pkey, pkey_rights);
  197. pkey_assert(pkey_rights >= 0);
  198. pkey_rights |= flags;
  199. ret = hw_pkey_set(pkey, pkey_rights, syscall_flags);
  200. assert(!ret);
  201. /* pkey_reg and flags have the same format */
  202. shadow_pkey_reg = set_pkey_bits(shadow_pkey_reg, pkey, pkey_rights);
  203. dprintf1("%s(%d) shadow: 0x%016llx\n",
  204. __func__, pkey, shadow_pkey_reg);
  205. pkey_assert(ret >= 0);
  206. pkey_rights = hw_pkey_get(pkey, syscall_flags);
  207. dprintf1("%s(%d) hw_pkey_get(%d): %x\n", __func__,
  208. pkey, pkey, pkey_rights);
  209. dprintf1("%s(%d) pkey_reg: 0x%016llx\n",
  210. __func__, pkey, read_pkey_reg());
  211. dprintf1("END<---%s(%d, 0x%x)\n", __func__,
  212. pkey, flags);
  213. }
  214. void pkey_disable_clear(int pkey, int flags)
  215. {
  216. unsigned long syscall_flags = 0;
  217. int ret;
  218. int pkey_rights = hw_pkey_get(pkey, syscall_flags);
  219. pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
  220. dprintf1("%s(%d) hw_pkey_get(%d): %x\n", __func__,
  221. pkey, pkey, pkey_rights);
  222. pkey_assert(pkey_rights >= 0);
  223. pkey_rights &= ~flags;
  224. ret = hw_pkey_set(pkey, pkey_rights, 0);
  225. shadow_pkey_reg = set_pkey_bits(shadow_pkey_reg, pkey, pkey_rights);
  226. pkey_assert(ret >= 0);
  227. pkey_rights = hw_pkey_get(pkey, syscall_flags);
  228. dprintf1("%s(%d) hw_pkey_get(%d): %x\n", __func__,
  229. pkey, pkey, pkey_rights);
  230. dprintf1("%s(%d) pkey_reg: 0x%016llx\n", __func__,
  231. pkey, read_pkey_reg());
  232. }
  233. void pkey_write_allow(int pkey)
  234. {
  235. pkey_disable_clear(pkey, PKEY_DISABLE_WRITE);
  236. }
  237. void pkey_write_deny(int pkey)
  238. {
  239. pkey_disable_set(pkey, PKEY_DISABLE_WRITE);
  240. }
  241. void pkey_access_allow(int pkey)
  242. {
  243. pkey_disable_clear(pkey, PKEY_DISABLE_ACCESS);
  244. }
  245. void pkey_access_deny(int pkey)
  246. {
  247. pkey_disable_set(pkey, PKEY_DISABLE_ACCESS);
  248. }
  249. static char *si_code_str(int si_code)
  250. {
  251. if (si_code == SEGV_MAPERR)
  252. return "SEGV_MAPERR";
  253. if (si_code == SEGV_ACCERR)
  254. return "SEGV_ACCERR";
  255. if (si_code == SEGV_BNDERR)
  256. return "SEGV_BNDERR";
  257. if (si_code == SEGV_PKUERR)
  258. return "SEGV_PKUERR";
  259. return "UNKNOWN";
  260. }
  261. int pkey_faults;
  262. int last_si_pkey = -1;
  263. void signal_handler(int signum, siginfo_t *si, void *vucontext)
  264. {
  265. ucontext_t *uctxt = vucontext;
  266. int trapno;
  267. unsigned long ip;
  268. #ifdef MCONTEXT_FPREGS
  269. char *fpregs;
  270. #endif
  271. #if defined(__i386__) || defined(__x86_64__) /* arch */
  272. u32 *pkey_reg_ptr;
  273. int pkey_reg_offset;
  274. #endif /* arch */
  275. u64 siginfo_pkey;
  276. u32 *si_pkey_ptr;
  277. dprint_in_signal = 1;
  278. dprintf1(">>>>===============SIGSEGV============================\n");
  279. dprintf1("%s()::%d, pkey_reg: 0x%016llx shadow: %016llx\n",
  280. __func__, __LINE__,
  281. __read_pkey_reg(), shadow_pkey_reg);
  282. trapno = MCONTEXT_TRAPNO(uctxt->uc_mcontext);
  283. ip = MCONTEXT_IP(uctxt->uc_mcontext);
  284. #ifdef MCONTEXT_FPREGS
  285. fpregs = (char *) uctxt->uc_mcontext.fpregs;
  286. #endif
  287. dprintf2("%s() trapno: %d ip: 0x%016lx info->si_code: %s/%d\n",
  288. __func__, trapno, ip, si_code_str(si->si_code),
  289. si->si_code);
  290. #if defined(__i386__) || defined(__x86_64__) /* arch */
  291. #ifdef __i386__
  292. /*
  293. * 32-bit has some extra padding so that userspace can tell whether
  294. * the XSTATE header is present in addition to the "legacy" FPU
  295. * state. We just assume that it is here.
  296. */
  297. fpregs += 0x70;
  298. #endif /* i386 */
  299. pkey_reg_offset = pkey_reg_xstate_offset();
  300. pkey_reg_ptr = (void *)(&fpregs[pkey_reg_offset]);
  301. /*
  302. * If we got a PKEY fault, we *HAVE* to have at least one bit set in
  303. * here.
  304. */
  305. dprintf1("pkey_reg_xstate_offset: %d\n", pkey_reg_xstate_offset());
  306. if (DEBUG_LEVEL > 4)
  307. dump_mem(pkey_reg_ptr - 128, 256);
  308. pkey_assert(*pkey_reg_ptr);
  309. #endif /* arch */
  310. dprintf1("siginfo: %p\n", si);
  311. #ifdef MCONTEXT_FPREGS
  312. dprintf1(" fpregs: %p\n", fpregs);
  313. #endif
  314. if ((si->si_code == SEGV_MAPERR) ||
  315. (si->si_code == SEGV_ACCERR) ||
  316. (si->si_code == SEGV_BNDERR)) {
  317. printf("non-PK si_code, exiting...\n");
  318. exit(4);
  319. }
  320. si_pkey_ptr = siginfo_get_pkey_ptr(si);
  321. dprintf1("si_pkey_ptr: %p\n", si_pkey_ptr);
  322. dump_mem((u8 *)si_pkey_ptr - 8, 24);
  323. siginfo_pkey = *si_pkey_ptr;
  324. pkey_assert(siginfo_pkey < NR_PKEYS);
  325. last_si_pkey = siginfo_pkey;
  326. /*
  327. * need __read_pkey_reg() version so we do not do shadow_pkey_reg
  328. * checking
  329. */
  330. dprintf1("signal pkey_reg from pkey_reg: %016llx\n",
  331. __read_pkey_reg());
  332. dprintf1("pkey from siginfo: %016llx\n", siginfo_pkey);
  333. #if defined(__i386__) || defined(__x86_64__) /* arch */
  334. dprintf1("signal pkey_reg from xsave: %08x\n", *pkey_reg_ptr);
  335. *(u64 *)pkey_reg_ptr = 0x00000000;
  336. dprintf1("WARNING: set PKEY_REG=0 to allow faulting instruction to continue\n");
  337. #elif defined(__powerpc64__) /* arch */
  338. /* restore access and let the faulting instruction continue */
  339. pkey_access_allow(siginfo_pkey);
  340. #elif defined(__aarch64__)
  341. aarch64_write_signal_pkey(uctxt, PKEY_ALLOW_ALL);
  342. #endif /* arch */
  343. pkey_faults++;
  344. dprintf1("<<<<==================================================\n");
  345. dprint_in_signal = 0;
  346. }
  347. int wait_all_children(void)
  348. {
  349. int status;
  350. return waitpid(-1, &status, 0);
  351. }
  352. void sig_chld(int x)
  353. {
  354. dprint_in_signal = 1;
  355. dprintf2("[%d] SIGCHLD: %d\n", getpid(), x);
  356. dprint_in_signal = 0;
  357. }
  358. void setup_sigsegv_handler(void)
  359. {
  360. int r, rs;
  361. struct sigaction newact;
  362. struct sigaction oldact;
  363. /* #PF is mapped to sigsegv */
  364. int signum = SIGSEGV;
  365. newact.sa_handler = 0;
  366. newact.sa_sigaction = signal_handler;
  367. /*sigset_t - signals to block while in the handler */
  368. /* get the old signal mask. */
  369. rs = sigprocmask(SIG_SETMASK, 0, &newact.sa_mask);
  370. pkey_assert(rs == 0);
  371. /* call sa_sigaction, not sa_handler*/
  372. newact.sa_flags = SA_SIGINFO;
  373. newact.sa_restorer = 0; /* void(*)(), obsolete */
  374. r = sigaction(signum, &newact, &oldact);
  375. r = sigaction(SIGALRM, &newact, &oldact);
  376. pkey_assert(r == 0);
  377. }
  378. void setup_handlers(void)
  379. {
  380. signal(SIGCHLD, &sig_chld);
  381. setup_sigsegv_handler();
  382. }
  383. pid_t fork_lazy_child(void)
  384. {
  385. pid_t forkret;
  386. forkret = fork();
  387. pkey_assert(forkret >= 0);
  388. dprintf3("[%d] fork() ret: %d\n", getpid(), forkret);
  389. if (!forkret) {
  390. /* in the child */
  391. while (1) {
  392. dprintf1("child sleeping...\n");
  393. sleep(30);
  394. }
  395. }
  396. return forkret;
  397. }
  398. int sys_mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
  399. unsigned long pkey)
  400. {
  401. int sret;
  402. dprintf2("%s(0x%p, %zx, prot=%lx, pkey=%lx)\n", __func__,
  403. ptr, size, orig_prot, pkey);
  404. errno = 0;
  405. sret = syscall(__NR_pkey_mprotect, ptr, size, orig_prot, pkey);
  406. if (errno) {
  407. dprintf2("SYS_mprotect_key sret: %d\n", sret);
  408. dprintf2("SYS_mprotect_key prot: 0x%lx\n", orig_prot);
  409. dprintf2("SYS_mprotect_key failed, errno: %d\n", errno);
  410. if (DEBUG_LEVEL >= 2)
  411. perror("SYS_mprotect_pkey");
  412. }
  413. return sret;
  414. }
  415. int sys_pkey_alloc(unsigned long flags, unsigned long init_val)
  416. {
  417. int ret = syscall(SYS_pkey_alloc, flags, init_val);
  418. dprintf1("%s(flags=%lx, init_val=%lx) syscall ret: %d errno: %d\n",
  419. __func__, flags, init_val, ret, errno);
  420. return ret;
  421. }
  422. int alloc_pkey(void)
  423. {
  424. int ret;
  425. unsigned long init_val = 0x0;
  426. dprintf1("%s()::%d, pkey_reg: 0x%016llx shadow: %016llx\n",
  427. __func__, __LINE__, __read_pkey_reg(), shadow_pkey_reg);
  428. ret = sys_pkey_alloc(0, init_val);
  429. /*
  430. * pkey_alloc() sets PKEY register, so we need to reflect it in
  431. * shadow_pkey_reg:
  432. */
  433. dprintf4("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  434. " shadow: 0x%016llx\n",
  435. __func__, __LINE__, ret, __read_pkey_reg(),
  436. shadow_pkey_reg);
  437. if (ret > 0) {
  438. /* clear both the bits: */
  439. shadow_pkey_reg = set_pkey_bits(shadow_pkey_reg, ret,
  440. ~PKEY_MASK);
  441. dprintf4("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  442. " shadow: 0x%016llx\n",
  443. __func__,
  444. __LINE__, ret, __read_pkey_reg(),
  445. shadow_pkey_reg);
  446. /*
  447. * move the new state in from init_val
  448. * (remember, we cheated and init_val == pkey_reg format)
  449. */
  450. shadow_pkey_reg = set_pkey_bits(shadow_pkey_reg, ret,
  451. init_val);
  452. }
  453. dprintf4("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  454. " shadow: 0x%016llx\n",
  455. __func__, __LINE__, ret, __read_pkey_reg(),
  456. shadow_pkey_reg);
  457. dprintf1("%s()::%d errno: %d\n", __func__, __LINE__, errno);
  458. /* for shadow checking: */
  459. read_pkey_reg();
  460. dprintf4("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  461. " shadow: 0x%016llx\n",
  462. __func__, __LINE__, ret, __read_pkey_reg(),
  463. shadow_pkey_reg);
  464. return ret;
  465. }
  466. int sys_pkey_free(unsigned long pkey)
  467. {
  468. int ret = syscall(SYS_pkey_free, pkey);
  469. dprintf1("%s(pkey=%ld) syscall ret: %d\n", __func__, pkey, ret);
  470. return ret;
  471. }
  472. /*
  473. * I had a bug where pkey bits could be set by mprotect() but
  474. * not cleared. This ensures we get lots of random bit sets
  475. * and clears on the vma and pte pkey bits.
  476. */
  477. int alloc_random_pkey(void)
  478. {
  479. int max_nr_pkey_allocs;
  480. int ret;
  481. int i;
  482. int alloced_pkeys[NR_PKEYS];
  483. int nr_alloced = 0;
  484. int random_index;
  485. memset(alloced_pkeys, 0, sizeof(alloced_pkeys));
  486. /* allocate every possible key and make a note of which ones we got */
  487. max_nr_pkey_allocs = NR_PKEYS;
  488. for (i = 0; i < max_nr_pkey_allocs; i++) {
  489. int new_pkey = alloc_pkey();
  490. if (new_pkey < 0)
  491. break;
  492. alloced_pkeys[nr_alloced++] = new_pkey;
  493. }
  494. pkey_assert(nr_alloced > 0);
  495. /* select a random one out of the allocated ones */
  496. random_index = rand() % nr_alloced;
  497. ret = alloced_pkeys[random_index];
  498. /* now zero it out so we don't free it next */
  499. alloced_pkeys[random_index] = 0;
  500. /* go through the allocated ones that we did not want and free them */
  501. for (i = 0; i < nr_alloced; i++) {
  502. int free_ret;
  503. if (!alloced_pkeys[i])
  504. continue;
  505. free_ret = sys_pkey_free(alloced_pkeys[i]);
  506. pkey_assert(!free_ret);
  507. }
  508. dprintf1("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  509. " shadow: 0x%016llx\n", __func__,
  510. __LINE__, ret, __read_pkey_reg(), shadow_pkey_reg);
  511. return ret;
  512. }
  513. int mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
  514. unsigned long pkey)
  515. {
  516. int nr_iterations = random() % 100;
  517. int ret;
  518. while (0) {
  519. int rpkey = alloc_random_pkey();
  520. ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
  521. dprintf1("sys_mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
  522. ptr, size, orig_prot, pkey, ret);
  523. if (nr_iterations-- < 0)
  524. break;
  525. dprintf1("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  526. " shadow: 0x%016llx\n",
  527. __func__, __LINE__, ret, __read_pkey_reg(),
  528. shadow_pkey_reg);
  529. sys_pkey_free(rpkey);
  530. dprintf1("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  531. " shadow: 0x%016llx\n",
  532. __func__, __LINE__, ret, __read_pkey_reg(),
  533. shadow_pkey_reg);
  534. }
  535. pkey_assert(pkey < NR_PKEYS);
  536. ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
  537. dprintf1("mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
  538. ptr, size, orig_prot, pkey, ret);
  539. pkey_assert(!ret);
  540. dprintf1("%s()::%d, ret: %d pkey_reg: 0x%016llx"
  541. " shadow: 0x%016llx\n", __func__,
  542. __LINE__, ret, __read_pkey_reg(), shadow_pkey_reg);
  543. return ret;
  544. }
  545. struct pkey_malloc_record {
  546. void *ptr;
  547. long size;
  548. int prot;
  549. };
  550. struct pkey_malloc_record *pkey_malloc_records;
  551. struct pkey_malloc_record *pkey_last_malloc_record;
  552. long nr_pkey_malloc_records;
  553. void record_pkey_malloc(void *ptr, long size, int prot)
  554. {
  555. long i;
  556. struct pkey_malloc_record *rec = NULL;
  557. for (i = 0; i < nr_pkey_malloc_records; i++) {
  558. rec = &pkey_malloc_records[i];
  559. /* find a free record */
  560. if (rec)
  561. break;
  562. }
  563. if (!rec) {
  564. /* every record is full */
  565. size_t old_nr_records = nr_pkey_malloc_records;
  566. size_t new_nr_records = (nr_pkey_malloc_records * 2 + 1);
  567. size_t new_size = new_nr_records * sizeof(struct pkey_malloc_record);
  568. dprintf2("new_nr_records: %zd\n", new_nr_records);
  569. dprintf2("new_size: %zd\n", new_size);
  570. pkey_malloc_records = realloc(pkey_malloc_records, new_size);
  571. pkey_assert(pkey_malloc_records != NULL);
  572. rec = &pkey_malloc_records[nr_pkey_malloc_records];
  573. /*
  574. * realloc() does not initialize memory, so zero it from
  575. * the first new record all the way to the end.
  576. */
  577. for (i = 0; i < new_nr_records - old_nr_records; i++)
  578. memset(rec + i, 0, sizeof(*rec));
  579. }
  580. dprintf3("filling malloc record[%d/%p]: {%p, %ld}\n",
  581. (int)(rec - pkey_malloc_records), rec, ptr, size);
  582. rec->ptr = ptr;
  583. rec->size = size;
  584. rec->prot = prot;
  585. pkey_last_malloc_record = rec;
  586. nr_pkey_malloc_records++;
  587. }
  588. void free_pkey_malloc(void *ptr)
  589. {
  590. long i;
  591. int ret;
  592. dprintf3("%s(%p)\n", __func__, ptr);
  593. for (i = 0; i < nr_pkey_malloc_records; i++) {
  594. struct pkey_malloc_record *rec = &pkey_malloc_records[i];
  595. dprintf4("looking for ptr %p at record[%ld/%p]: {%p, %ld}\n",
  596. ptr, i, rec, rec->ptr, rec->size);
  597. if ((ptr < rec->ptr) ||
  598. (ptr >= rec->ptr + rec->size))
  599. continue;
  600. dprintf3("found ptr %p at record[%ld/%p]: {%p, %ld}\n",
  601. ptr, i, rec, rec->ptr, rec->size);
  602. nr_pkey_malloc_records--;
  603. ret = munmap(rec->ptr, rec->size);
  604. dprintf3("munmap ret: %d\n", ret);
  605. pkey_assert(!ret);
  606. dprintf3("clearing rec->ptr, rec: %p\n", rec);
  607. rec->ptr = NULL;
  608. dprintf3("done clearing rec->ptr, rec: %p\n", rec);
  609. return;
  610. }
  611. pkey_assert(false);
  612. }
  613. void *malloc_pkey_with_mprotect(long size, int prot, u16 pkey)
  614. {
  615. void *ptr;
  616. int ret;
  617. read_pkey_reg();
  618. dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
  619. size, prot, pkey);
  620. pkey_assert(pkey < NR_PKEYS);
  621. ptr = mmap(NULL, size, prot, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  622. pkey_assert(ptr != (void *)-1);
  623. ret = mprotect_pkey((void *)ptr, PAGE_SIZE, prot, pkey);
  624. pkey_assert(!ret);
  625. record_pkey_malloc(ptr, size, prot);
  626. read_pkey_reg();
  627. dprintf1("%s() for pkey %d @ %p\n", __func__, pkey, ptr);
  628. return ptr;
  629. }
  630. void *malloc_pkey_anon_huge(long size, int prot, u16 pkey)
  631. {
  632. int ret;
  633. void *ptr;
  634. dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
  635. size, prot, pkey);
  636. /*
  637. * Guarantee we can fit at least one huge page in the resulting
  638. * allocation by allocating space for 2:
  639. */
  640. size = ALIGN_UP(size, HPAGE_SIZE * 2);
  641. ptr = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  642. pkey_assert(ptr != (void *)-1);
  643. record_pkey_malloc(ptr, size, prot);
  644. mprotect_pkey(ptr, size, prot, pkey);
  645. dprintf1("unaligned ptr: %p\n", ptr);
  646. ptr = ALIGN_PTR_UP(ptr, HPAGE_SIZE);
  647. dprintf1(" aligned ptr: %p\n", ptr);
  648. ret = madvise(ptr, HPAGE_SIZE, MADV_HUGEPAGE);
  649. dprintf1("MADV_HUGEPAGE ret: %d\n", ret);
  650. ret = madvise(ptr, HPAGE_SIZE, MADV_WILLNEED);
  651. dprintf1("MADV_WILLNEED ret: %d\n", ret);
  652. memset(ptr, 0, HPAGE_SIZE);
  653. dprintf1("mmap()'d thp for pkey %d @ %p\n", pkey, ptr);
  654. return ptr;
  655. }
  656. int hugetlb_setup_ok;
  657. #define SYSFS_FMT_NR_HUGE_PAGES "/sys/kernel/mm/hugepages/hugepages-%ldkB/nr_hugepages"
  658. #define GET_NR_HUGE_PAGES 10
  659. void setup_hugetlbfs(void)
  660. {
  661. int err;
  662. int fd;
  663. char buf[256];
  664. long hpagesz_kb;
  665. long hpagesz_mb;
  666. if (geteuid() != 0) {
  667. fprintf(stderr, "WARNING: not run as root, can not do hugetlb test\n");
  668. return;
  669. }
  670. cat_into_file(__stringify(GET_NR_HUGE_PAGES), "/proc/sys/vm/nr_hugepages");
  671. /*
  672. * Now go make sure that we got the pages and that they
  673. * are PMD-level pages. Someone might have made PUD-level
  674. * pages the default.
  675. */
  676. hpagesz_kb = HPAGE_SIZE / 1024;
  677. hpagesz_mb = hpagesz_kb / 1024;
  678. sprintf(buf, SYSFS_FMT_NR_HUGE_PAGES, hpagesz_kb);
  679. fd = open(buf, O_RDONLY);
  680. if (fd < 0) {
  681. fprintf(stderr, "opening sysfs %ldM hugetlb config: %s\n",
  682. hpagesz_mb, strerror(errno));
  683. return;
  684. }
  685. /* -1 to guarantee leaving the trailing \0 */
  686. err = read(fd, buf, sizeof(buf)-1);
  687. close(fd);
  688. if (err <= 0) {
  689. fprintf(stderr, "reading sysfs %ldM hugetlb config: %s\n",
  690. hpagesz_mb, strerror(errno));
  691. return;
  692. }
  693. if (atoi(buf) != GET_NR_HUGE_PAGES) {
  694. fprintf(stderr, "could not confirm %ldM pages, got: '%s' expected %d\n",
  695. hpagesz_mb, buf, GET_NR_HUGE_PAGES);
  696. return;
  697. }
  698. hugetlb_setup_ok = 1;
  699. }
  700. void *malloc_pkey_hugetlb(long size, int prot, u16 pkey)
  701. {
  702. void *ptr;
  703. int flags = MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB;
  704. if (!hugetlb_setup_ok)
  705. return PTR_ERR_ENOTSUP;
  706. dprintf1("doing %s(%ld, %x, %x)\n", __func__, size, prot, pkey);
  707. size = ALIGN_UP(size, HPAGE_SIZE * 2);
  708. pkey_assert(pkey < NR_PKEYS);
  709. ptr = mmap(NULL, size, PROT_NONE, flags, -1, 0);
  710. pkey_assert(ptr != (void *)-1);
  711. mprotect_pkey(ptr, size, prot, pkey);
  712. record_pkey_malloc(ptr, size, prot);
  713. dprintf1("mmap()'d hugetlbfs for pkey %d @ %p\n", pkey, ptr);
  714. return ptr;
  715. }
  716. void *malloc_pkey_mmap_dax(long size, int prot, u16 pkey)
  717. {
  718. void *ptr;
  719. int fd;
  720. dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
  721. size, prot, pkey);
  722. pkey_assert(pkey < NR_PKEYS);
  723. fd = open("/dax/foo", O_RDWR);
  724. pkey_assert(fd >= 0);
  725. ptr = mmap(0, size, prot, MAP_SHARED, fd, 0);
  726. pkey_assert(ptr != (void *)-1);
  727. mprotect_pkey(ptr, size, prot, pkey);
  728. record_pkey_malloc(ptr, size, prot);
  729. dprintf1("mmap()'d for pkey %d @ %p\n", pkey, ptr);
  730. close(fd);
  731. return ptr;
  732. }
  733. void *(*pkey_malloc[])(long size, int prot, u16 pkey) = {
  734. malloc_pkey_with_mprotect,
  735. malloc_pkey_with_mprotect_subpage,
  736. malloc_pkey_anon_huge,
  737. malloc_pkey_hugetlb
  738. /* can not do direct with the pkey_mprotect() API:
  739. malloc_pkey_mmap_direct,
  740. malloc_pkey_mmap_dax,
  741. */
  742. };
  743. void *malloc_pkey(long size, int prot, u16 pkey)
  744. {
  745. void *ret;
  746. static int malloc_type;
  747. int nr_malloc_types = ARRAY_SIZE(pkey_malloc);
  748. pkey_assert(pkey < NR_PKEYS);
  749. while (1) {
  750. pkey_assert(malloc_type < nr_malloc_types);
  751. ret = pkey_malloc[malloc_type](size, prot, pkey);
  752. pkey_assert(ret != (void *)-1);
  753. malloc_type++;
  754. if (malloc_type >= nr_malloc_types)
  755. malloc_type = (random()%nr_malloc_types);
  756. /* try again if the malloc_type we tried is unsupported */
  757. if (ret == PTR_ERR_ENOTSUP)
  758. continue;
  759. break;
  760. }
  761. dprintf3("%s(%ld, prot=%x, pkey=%x) returning: %p\n", __func__,
  762. size, prot, pkey, ret);
  763. return ret;
  764. }
  765. int last_pkey_faults;
  766. #define UNKNOWN_PKEY -2
  767. void expected_pkey_fault(int pkey)
  768. {
  769. dprintf2("%s(): last_pkey_faults: %d pkey_faults: %d\n",
  770. __func__, last_pkey_faults, pkey_faults);
  771. dprintf2("%s(%d): last_si_pkey: %d\n", __func__, pkey, last_si_pkey);
  772. pkey_assert(last_pkey_faults + 1 == pkey_faults);
  773. /*
  774. * For exec-only memory, we do not know the pkey in
  775. * advance, so skip this check.
  776. */
  777. if (pkey != UNKNOWN_PKEY)
  778. pkey_assert(last_si_pkey == pkey);
  779. #if defined(__i386__) || defined(__x86_64__) /* arch */
  780. /*
  781. * The signal handler shold have cleared out PKEY register to let the
  782. * test program continue. We now have to restore it.
  783. */
  784. if (__read_pkey_reg() != 0)
  785. #elif defined(__aarch64__)
  786. if (__read_pkey_reg() != PKEY_ALLOW_ALL)
  787. #else
  788. if (__read_pkey_reg() != shadow_pkey_reg)
  789. #endif /* arch */
  790. pkey_assert(0);
  791. __write_pkey_reg(shadow_pkey_reg);
  792. dprintf1("%s() set pkey_reg=%016llx to restore state after signal "
  793. "nuked it\n", __func__, shadow_pkey_reg);
  794. last_pkey_faults = pkey_faults;
  795. last_si_pkey = -1;
  796. }
  797. #define do_not_expect_pkey_fault(msg) do { \
  798. if (last_pkey_faults != pkey_faults) \
  799. dprintf0("unexpected PKey fault: %s\n", msg); \
  800. pkey_assert(last_pkey_faults == pkey_faults); \
  801. } while (0)
  802. int test_fds[10] = { -1 };
  803. int nr_test_fds;
  804. void __save_test_fd(int fd)
  805. {
  806. pkey_assert(fd >= 0);
  807. pkey_assert(nr_test_fds < ARRAY_SIZE(test_fds));
  808. test_fds[nr_test_fds] = fd;
  809. nr_test_fds++;
  810. }
  811. int get_test_read_fd(void)
  812. {
  813. int test_fd = open("/etc/passwd", O_RDONLY);
  814. __save_test_fd(test_fd);
  815. return test_fd;
  816. }
  817. void close_test_fds(void)
  818. {
  819. int i;
  820. for (i = 0; i < nr_test_fds; i++) {
  821. if (test_fds[i] < 0)
  822. continue;
  823. close(test_fds[i]);
  824. test_fds[i] = -1;
  825. }
  826. nr_test_fds = 0;
  827. }
  828. void test_pkey_alloc_free_attach_pkey0(int *ptr, u16 pkey)
  829. {
  830. int i, err;
  831. int max_nr_pkey_allocs;
  832. int alloced_pkeys[NR_PKEYS];
  833. int nr_alloced = 0;
  834. long size;
  835. pkey_assert(pkey_last_malloc_record);
  836. size = pkey_last_malloc_record->size;
  837. /*
  838. * This is a bit of a hack. But mprotect() requires
  839. * huge-page-aligned sizes when operating on hugetlbfs.
  840. * So, make sure that we use something that's a multiple
  841. * of a huge page when we can.
  842. */
  843. if (size >= HPAGE_SIZE)
  844. size = HPAGE_SIZE;
  845. /* allocate every possible key and make sure key-0 never got allocated */
  846. max_nr_pkey_allocs = NR_PKEYS;
  847. for (i = 0; i < max_nr_pkey_allocs; i++) {
  848. int new_pkey = alloc_pkey();
  849. pkey_assert(new_pkey != 0);
  850. if (new_pkey < 0)
  851. break;
  852. alloced_pkeys[nr_alloced++] = new_pkey;
  853. }
  854. /* free all the allocated keys */
  855. for (i = 0; i < nr_alloced; i++) {
  856. int free_ret;
  857. if (!alloced_pkeys[i])
  858. continue;
  859. free_ret = sys_pkey_free(alloced_pkeys[i]);
  860. pkey_assert(!free_ret);
  861. }
  862. /* attach key-0 in various modes */
  863. err = sys_mprotect_pkey(ptr, size, PROT_READ, 0);
  864. pkey_assert(!err);
  865. err = sys_mprotect_pkey(ptr, size, PROT_WRITE, 0);
  866. pkey_assert(!err);
  867. err = sys_mprotect_pkey(ptr, size, PROT_EXEC, 0);
  868. pkey_assert(!err);
  869. err = sys_mprotect_pkey(ptr, size, PROT_READ|PROT_WRITE, 0);
  870. pkey_assert(!err);
  871. err = sys_mprotect_pkey(ptr, size, PROT_READ|PROT_WRITE|PROT_EXEC, 0);
  872. pkey_assert(!err);
  873. }
  874. void test_read_of_write_disabled_region(int *ptr, u16 pkey)
  875. {
  876. int ptr_contents;
  877. dprintf1("disabling write access to PKEY[1], doing read\n");
  878. pkey_write_deny(pkey);
  879. ptr_contents = read_ptr(ptr);
  880. dprintf1("*ptr: %d\n", ptr_contents);
  881. dprintf1("\n");
  882. }
  883. void test_read_of_access_disabled_region(int *ptr, u16 pkey)
  884. {
  885. int ptr_contents;
  886. dprintf1("disabling access to PKEY[%02d], doing read @ %p\n", pkey, ptr);
  887. read_pkey_reg();
  888. pkey_access_deny(pkey);
  889. ptr_contents = read_ptr(ptr);
  890. dprintf1("*ptr: %d\n", ptr_contents);
  891. expected_pkey_fault(pkey);
  892. }
  893. void test_read_of_access_disabled_region_with_page_already_mapped(int *ptr,
  894. u16 pkey)
  895. {
  896. int ptr_contents;
  897. dprintf1("disabling access to PKEY[%02d], doing read @ %p\n",
  898. pkey, ptr);
  899. ptr_contents = read_ptr(ptr);
  900. dprintf1("reading ptr before disabling the read : %d\n",
  901. ptr_contents);
  902. read_pkey_reg();
  903. pkey_access_deny(pkey);
  904. ptr_contents = read_ptr(ptr);
  905. dprintf1("*ptr: %d\n", ptr_contents);
  906. expected_pkey_fault(pkey);
  907. }
  908. void test_write_of_write_disabled_region_with_page_already_mapped(int *ptr,
  909. u16 pkey)
  910. {
  911. *ptr = __LINE__;
  912. dprintf1("disabling write access; after accessing the page, "
  913. "to PKEY[%02d], doing write\n", pkey);
  914. pkey_write_deny(pkey);
  915. *ptr = __LINE__;
  916. expected_pkey_fault(pkey);
  917. }
  918. void test_write_of_write_disabled_region(int *ptr, u16 pkey)
  919. {
  920. dprintf1("disabling write access to PKEY[%02d], doing write\n", pkey);
  921. pkey_write_deny(pkey);
  922. *ptr = __LINE__;
  923. expected_pkey_fault(pkey);
  924. }
  925. void test_write_of_access_disabled_region(int *ptr, u16 pkey)
  926. {
  927. dprintf1("disabling access to PKEY[%02d], doing write\n", pkey);
  928. pkey_access_deny(pkey);
  929. *ptr = __LINE__;
  930. expected_pkey_fault(pkey);
  931. }
  932. void test_write_of_access_disabled_region_with_page_already_mapped(int *ptr,
  933. u16 pkey)
  934. {
  935. *ptr = __LINE__;
  936. dprintf1("disabling access; after accessing the page, "
  937. " to PKEY[%02d], doing write\n", pkey);
  938. pkey_access_deny(pkey);
  939. *ptr = __LINE__;
  940. expected_pkey_fault(pkey);
  941. }
  942. void test_kernel_write_of_access_disabled_region(int *ptr, u16 pkey)
  943. {
  944. int ret;
  945. int test_fd = get_test_read_fd();
  946. dprintf1("disabling access to PKEY[%02d], "
  947. "having kernel read() to buffer\n", pkey);
  948. pkey_access_deny(pkey);
  949. ret = read(test_fd, ptr, 1);
  950. dprintf1("read ret: %d\n", ret);
  951. pkey_assert(ret);
  952. }
  953. void test_kernel_write_of_write_disabled_region(int *ptr, u16 pkey)
  954. {
  955. int ret;
  956. int test_fd = get_test_read_fd();
  957. pkey_write_deny(pkey);
  958. ret = read(test_fd, ptr, 100);
  959. dprintf1("read ret: %d\n", ret);
  960. if (ret < 0 && (DEBUG_LEVEL > 0))
  961. perror("verbose read result (OK for this to be bad)");
  962. pkey_assert(ret);
  963. }
  964. void test_kernel_gup_of_access_disabled_region(int *ptr, u16 pkey)
  965. {
  966. int pipe_ret, vmsplice_ret;
  967. struct iovec iov;
  968. int pipe_fds[2];
  969. pipe_ret = pipe(pipe_fds);
  970. pkey_assert(pipe_ret == 0);
  971. dprintf1("disabling access to PKEY[%02d], "
  972. "having kernel vmsplice from buffer\n", pkey);
  973. pkey_access_deny(pkey);
  974. iov.iov_base = ptr;
  975. iov.iov_len = PAGE_SIZE;
  976. vmsplice_ret = vmsplice(pipe_fds[1], &iov, 1, SPLICE_F_GIFT);
  977. dprintf1("vmsplice() ret: %d\n", vmsplice_ret);
  978. pkey_assert(vmsplice_ret == -1);
  979. close(pipe_fds[0]);
  980. close(pipe_fds[1]);
  981. }
  982. void test_kernel_gup_write_to_write_disabled_region(int *ptr, u16 pkey)
  983. {
  984. int ignored = 0xdada;
  985. int futex_ret;
  986. int some_int = __LINE__;
  987. dprintf1("disabling write to PKEY[%02d], "
  988. "doing futex gunk in buffer\n", pkey);
  989. *ptr = some_int;
  990. pkey_write_deny(pkey);
  991. futex_ret = syscall(SYS_futex, ptr, FUTEX_WAIT, some_int-1, NULL,
  992. &ignored, ignored);
  993. if (DEBUG_LEVEL > 0)
  994. perror("futex");
  995. dprintf1("futex() ret: %d\n", futex_ret);
  996. }
  997. /* Assumes that all pkeys other than 'pkey' are unallocated */
  998. void test_pkey_syscalls_on_non_allocated_pkey(int *ptr, u16 pkey)
  999. {
  1000. int err;
  1001. int i;
  1002. /* Note: 0 is the default pkey, so don't mess with it */
  1003. for (i = 1; i < NR_PKEYS; i++) {
  1004. if (pkey == i)
  1005. continue;
  1006. dprintf1("trying get/set/free to non-allocated pkey: %2d\n", i);
  1007. err = sys_pkey_free(i);
  1008. pkey_assert(err);
  1009. err = sys_pkey_free(i);
  1010. pkey_assert(err);
  1011. err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, i);
  1012. pkey_assert(err);
  1013. }
  1014. }
  1015. /* Assumes that all pkeys other than 'pkey' are unallocated */
  1016. void test_pkey_syscalls_bad_args(int *ptr, u16 pkey)
  1017. {
  1018. int err;
  1019. int bad_pkey = NR_PKEYS+99;
  1020. /* pass a known-invalid pkey in: */
  1021. err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, bad_pkey);
  1022. pkey_assert(err);
  1023. }
  1024. void become_child(void)
  1025. {
  1026. pid_t forkret;
  1027. forkret = fork();
  1028. pkey_assert(forkret >= 0);
  1029. dprintf3("[%d] fork() ret: %d\n", getpid(), forkret);
  1030. if (!forkret) {
  1031. /* in the child */
  1032. return;
  1033. }
  1034. exit(0);
  1035. }
  1036. /* Assumes that all pkeys other than 'pkey' are unallocated */
  1037. void test_pkey_alloc_exhaust(int *ptr, u16 pkey)
  1038. {
  1039. int err;
  1040. int allocated_pkeys[NR_PKEYS] = {0};
  1041. int nr_allocated_pkeys = 0;
  1042. int i;
  1043. for (i = 0; i < NR_PKEYS*3; i++) {
  1044. int new_pkey;
  1045. dprintf1("%s() alloc loop: %d\n", __func__, i);
  1046. new_pkey = alloc_pkey();
  1047. dprintf4("%s()::%d, err: %d pkey_reg: 0x%016llx"
  1048. " shadow: 0x%016llx\n",
  1049. __func__, __LINE__, err, __read_pkey_reg(),
  1050. shadow_pkey_reg);
  1051. read_pkey_reg(); /* for shadow checking */
  1052. dprintf2("%s() errno: %d ENOSPC: %d\n", __func__, errno, ENOSPC);
  1053. if ((new_pkey == -1) && (errno == ENOSPC)) {
  1054. dprintf2("%s() failed to allocate pkey after %d tries\n",
  1055. __func__, nr_allocated_pkeys);
  1056. } else {
  1057. /*
  1058. * Ensure the number of successes never
  1059. * exceeds the number of keys supported
  1060. * in the hardware.
  1061. */
  1062. pkey_assert(nr_allocated_pkeys < NR_PKEYS);
  1063. allocated_pkeys[nr_allocated_pkeys++] = new_pkey;
  1064. }
  1065. /*
  1066. * Make sure that allocation state is properly
  1067. * preserved across fork().
  1068. */
  1069. if (i == NR_PKEYS*2)
  1070. become_child();
  1071. }
  1072. dprintf3("%s()::%d\n", __func__, __LINE__);
  1073. /*
  1074. * On x86:
  1075. * There are 16 pkeys supported in hardware. Three are
  1076. * allocated by the time we get here:
  1077. * 1. The default key (0)
  1078. * 2. One possibly consumed by an execute-only mapping.
  1079. * 3. One allocated by the test code and passed in via
  1080. * 'pkey' to this function.
  1081. * Ensure that we can allocate at least another 13 (16-3).
  1082. *
  1083. * On powerpc:
  1084. * There are either 5, 28, 29 or 32 pkeys supported in
  1085. * hardware depending on the page size (4K or 64K) and
  1086. * platform (powernv or powervm). Four are allocated by
  1087. * the time we get here. These include pkey-0, pkey-1,
  1088. * exec-only pkey and the one allocated by the test code.
  1089. * Ensure that we can allocate the remaining.
  1090. */
  1091. pkey_assert(i >= (NR_PKEYS - get_arch_reserved_keys() - 1));
  1092. for (i = 0; i < nr_allocated_pkeys; i++) {
  1093. err = sys_pkey_free(allocated_pkeys[i]);
  1094. pkey_assert(!err);
  1095. read_pkey_reg(); /* for shadow checking */
  1096. }
  1097. }
  1098. void arch_force_pkey_reg_init(void)
  1099. {
  1100. #if defined(__i386__) || defined(__x86_64__) /* arch */
  1101. u64 *buf;
  1102. /*
  1103. * All keys should be allocated and set to allow reads and
  1104. * writes, so the register should be all 0. If not, just
  1105. * skip the test.
  1106. */
  1107. if (read_pkey_reg())
  1108. return;
  1109. /*
  1110. * Just allocate an absurd about of memory rather than
  1111. * doing the XSAVE size enumeration dance.
  1112. */
  1113. buf = mmap(NULL, 1*MB, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  1114. /* These __builtins require compiling with -mxsave */
  1115. /* XSAVE to build a valid buffer: */
  1116. __builtin_ia32_xsave(buf, XSTATE_PKEY);
  1117. /* Clear XSTATE_BV[PKRU]: */
  1118. buf[XSTATE_BV_OFFSET/sizeof(u64)] &= ~XSTATE_PKEY;
  1119. /* XRSTOR will likely get PKRU back to the init state: */
  1120. __builtin_ia32_xrstor(buf, XSTATE_PKEY);
  1121. munmap(buf, 1*MB);
  1122. #endif
  1123. }
  1124. /*
  1125. * This is mostly useless on ppc for now. But it will not
  1126. * hurt anything and should give some better coverage as
  1127. * a long-running test that continually checks the pkey
  1128. * register.
  1129. */
  1130. void test_pkey_init_state(int *ptr, u16 pkey)
  1131. {
  1132. int err;
  1133. int allocated_pkeys[NR_PKEYS] = {0};
  1134. int nr_allocated_pkeys = 0;
  1135. int i;
  1136. for (i = 0; i < NR_PKEYS; i++) {
  1137. int new_pkey = alloc_pkey();
  1138. if (new_pkey < 0)
  1139. continue;
  1140. allocated_pkeys[nr_allocated_pkeys++] = new_pkey;
  1141. }
  1142. dprintf3("%s()::%d\n", __func__, __LINE__);
  1143. arch_force_pkey_reg_init();
  1144. /*
  1145. * Loop for a bit, hoping to get exercise the kernel
  1146. * context switch code.
  1147. */
  1148. for (i = 0; i < 1000000; i++)
  1149. read_pkey_reg();
  1150. for (i = 0; i < nr_allocated_pkeys; i++) {
  1151. err = sys_pkey_free(allocated_pkeys[i]);
  1152. pkey_assert(!err);
  1153. read_pkey_reg(); /* for shadow checking */
  1154. }
  1155. }
  1156. /*
  1157. * pkey 0 is special. It is allocated by default, so you do not
  1158. * have to call pkey_alloc() to use it first. Make sure that it
  1159. * is usable.
  1160. */
  1161. void test_mprotect_with_pkey_0(int *ptr, u16 pkey)
  1162. {
  1163. long size;
  1164. int prot;
  1165. assert(pkey_last_malloc_record);
  1166. size = pkey_last_malloc_record->size;
  1167. /*
  1168. * This is a bit of a hack. But mprotect() requires
  1169. * huge-page-aligned sizes when operating on hugetlbfs.
  1170. * So, make sure that we use something that's a multiple
  1171. * of a huge page when we can.
  1172. */
  1173. if (size >= HPAGE_SIZE)
  1174. size = HPAGE_SIZE;
  1175. prot = pkey_last_malloc_record->prot;
  1176. /* Use pkey 0 */
  1177. mprotect_pkey(ptr, size, prot, 0);
  1178. /* Make sure that we can set it back to the original pkey. */
  1179. mprotect_pkey(ptr, size, prot, pkey);
  1180. }
  1181. void test_ptrace_of_child(int *ptr, u16 pkey)
  1182. {
  1183. __attribute__((__unused__)) int peek_result;
  1184. pid_t child_pid;
  1185. void *ignored = 0;
  1186. long ret;
  1187. int status;
  1188. /*
  1189. * This is the "control" for our little expermient. Make sure
  1190. * we can always access it when ptracing.
  1191. */
  1192. int *plain_ptr_unaligned = malloc(HPAGE_SIZE);
  1193. int *plain_ptr = ALIGN_PTR_UP(plain_ptr_unaligned, PAGE_SIZE);
  1194. /*
  1195. * Fork a child which is an exact copy of this process, of course.
  1196. * That means we can do all of our tests via ptrace() and then plain
  1197. * memory access and ensure they work differently.
  1198. */
  1199. child_pid = fork_lazy_child();
  1200. dprintf1("[%d] child pid: %d\n", getpid(), child_pid);
  1201. ret = ptrace(PTRACE_ATTACH, child_pid, ignored, ignored);
  1202. if (ret)
  1203. perror("attach");
  1204. dprintf1("[%d] attach ret: %ld %d\n", getpid(), ret, __LINE__);
  1205. pkey_assert(ret != -1);
  1206. ret = waitpid(child_pid, &status, WUNTRACED);
  1207. if ((ret != child_pid) || !(WIFSTOPPED(status))) {
  1208. fprintf(stderr, "weird waitpid result %ld stat %x\n",
  1209. ret, status);
  1210. pkey_assert(0);
  1211. }
  1212. dprintf2("waitpid ret: %ld\n", ret);
  1213. dprintf2("waitpid status: %d\n", status);
  1214. pkey_access_deny(pkey);
  1215. pkey_write_deny(pkey);
  1216. /* Write access, untested for now:
  1217. ret = ptrace(PTRACE_POKEDATA, child_pid, peek_at, data);
  1218. pkey_assert(ret != -1);
  1219. dprintf1("poke at %p: %ld\n", peek_at, ret);
  1220. */
  1221. /*
  1222. * Try to access the pkey-protected "ptr" via ptrace:
  1223. */
  1224. ret = ptrace(PTRACE_PEEKDATA, child_pid, ptr, ignored);
  1225. /* expect it to work, without an error: */
  1226. pkey_assert(ret != -1);
  1227. /* Now access from the current task, and expect an exception: */
  1228. peek_result = read_ptr(ptr);
  1229. expected_pkey_fault(pkey);
  1230. /*
  1231. * Try to access the NON-pkey-protected "plain_ptr" via ptrace:
  1232. */
  1233. ret = ptrace(PTRACE_PEEKDATA, child_pid, plain_ptr, ignored);
  1234. /* expect it to work, without an error: */
  1235. pkey_assert(ret != -1);
  1236. /* Now access from the current task, and expect NO exception: */
  1237. peek_result = read_ptr(plain_ptr);
  1238. do_not_expect_pkey_fault("read plain pointer after ptrace");
  1239. ret = ptrace(PTRACE_DETACH, child_pid, ignored, 0);
  1240. pkey_assert(ret != -1);
  1241. ret = kill(child_pid, SIGKILL);
  1242. pkey_assert(ret != -1);
  1243. wait(&status);
  1244. free(plain_ptr_unaligned);
  1245. }
  1246. void *get_pointer_to_instructions(void)
  1247. {
  1248. void *p1;
  1249. p1 = ALIGN_PTR_UP(&lots_o_noops_around_write, PAGE_SIZE);
  1250. dprintf3("&lots_o_noops: %p\n", &lots_o_noops_around_write);
  1251. /* lots_o_noops_around_write should be page-aligned already */
  1252. assert(p1 == &lots_o_noops_around_write);
  1253. /* Point 'p1' at the *second* page of the function: */
  1254. p1 += PAGE_SIZE;
  1255. /*
  1256. * Try to ensure we fault this in on next touch to ensure
  1257. * we get an instruction fault as opposed to a data one
  1258. */
  1259. madvise(p1, PAGE_SIZE, MADV_DONTNEED);
  1260. return p1;
  1261. }
  1262. void test_executing_on_unreadable_memory(int *ptr, u16 pkey)
  1263. {
  1264. void *p1;
  1265. int scratch;
  1266. int ptr_contents;
  1267. int ret;
  1268. p1 = get_pointer_to_instructions();
  1269. lots_o_noops_around_write(&scratch);
  1270. ptr_contents = read_ptr(p1);
  1271. dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
  1272. ret = mprotect_pkey(p1, PAGE_SIZE, PROT_EXEC, (u64)pkey);
  1273. pkey_assert(!ret);
  1274. pkey_access_deny(pkey);
  1275. dprintf2("pkey_reg: %016llx\n", read_pkey_reg());
  1276. /*
  1277. * Make sure this is an *instruction* fault
  1278. */
  1279. madvise(p1, PAGE_SIZE, MADV_DONTNEED);
  1280. lots_o_noops_around_write(&scratch);
  1281. do_not_expect_pkey_fault("executing on PROT_EXEC memory");
  1282. expect_fault_on_read_execonly_key(p1, pkey);
  1283. // Reset back to PROT_EXEC | PROT_READ for architectures that support
  1284. // non-PKEY execute-only permissions.
  1285. ret = mprotect_pkey(p1, PAGE_SIZE, PROT_EXEC | PROT_READ, (u64)pkey);
  1286. pkey_assert(!ret);
  1287. }
  1288. void test_implicit_mprotect_exec_only_memory(int *ptr, u16 pkey)
  1289. {
  1290. void *p1;
  1291. int scratch;
  1292. int ptr_contents;
  1293. int ret;
  1294. dprintf1("%s() start\n", __func__);
  1295. p1 = get_pointer_to_instructions();
  1296. lots_o_noops_around_write(&scratch);
  1297. ptr_contents = read_ptr(p1);
  1298. dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
  1299. /* Use a *normal* mprotect(), not mprotect_pkey(): */
  1300. ret = mprotect(p1, PAGE_SIZE, PROT_EXEC);
  1301. pkey_assert(!ret);
  1302. /*
  1303. * Reset the shadow, assuming that the above mprotect()
  1304. * correctly changed PKRU, but to an unknown value since
  1305. * the actual allocated pkey is unknown.
  1306. */
  1307. shadow_pkey_reg = __read_pkey_reg();
  1308. dprintf2("pkey_reg: %016llx\n", read_pkey_reg());
  1309. /* Make sure this is an *instruction* fault */
  1310. madvise(p1, PAGE_SIZE, MADV_DONTNEED);
  1311. lots_o_noops_around_write(&scratch);
  1312. do_not_expect_pkey_fault("executing on PROT_EXEC memory");
  1313. expect_fault_on_read_execonly_key(p1, UNKNOWN_PKEY);
  1314. /*
  1315. * Put the memory back to non-PROT_EXEC. Should clear the
  1316. * exec-only pkey off the VMA and allow it to be readable
  1317. * again. Go to PROT_NONE first to check for a kernel bug
  1318. * that did not clear the pkey when doing PROT_NONE.
  1319. */
  1320. ret = mprotect(p1, PAGE_SIZE, PROT_NONE);
  1321. pkey_assert(!ret);
  1322. ret = mprotect(p1, PAGE_SIZE, PROT_READ|PROT_EXEC);
  1323. pkey_assert(!ret);
  1324. ptr_contents = read_ptr(p1);
  1325. do_not_expect_pkey_fault("plain read on recently PROT_EXEC area");
  1326. }
  1327. #if defined(__i386__) || defined(__x86_64__)
  1328. void test_ptrace_modifies_pkru(int *ptr, u16 pkey)
  1329. {
  1330. u32 new_pkru;
  1331. pid_t child;
  1332. int status, ret;
  1333. int pkey_offset = pkey_reg_xstate_offset();
  1334. size_t xsave_size = cpu_max_xsave_size();
  1335. void *xsave;
  1336. u32 *pkey_register;
  1337. u64 *xstate_bv;
  1338. struct iovec iov;
  1339. new_pkru = ~read_pkey_reg();
  1340. /* Don't make PROT_EXEC mappings inaccessible */
  1341. new_pkru &= ~3;
  1342. child = fork();
  1343. pkey_assert(child >= 0);
  1344. dprintf3("[%d] fork() ret: %d\n", getpid(), child);
  1345. if (!child) {
  1346. ptrace(PTRACE_TRACEME, 0, 0, 0);
  1347. /* Stop and allow the tracer to modify PKRU directly */
  1348. raise(SIGSTOP);
  1349. /*
  1350. * need __read_pkey_reg() version so we do not do shadow_pkey_reg
  1351. * checking
  1352. */
  1353. if (__read_pkey_reg() != new_pkru)
  1354. exit(1);
  1355. /* Stop and allow the tracer to clear XSTATE_BV for PKRU */
  1356. raise(SIGSTOP);
  1357. if (__read_pkey_reg() != 0)
  1358. exit(1);
  1359. /* Stop and allow the tracer to examine PKRU */
  1360. raise(SIGSTOP);
  1361. exit(0);
  1362. }
  1363. pkey_assert(child == waitpid(child, &status, 0));
  1364. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1365. pkey_assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  1366. xsave = (void *)malloc(xsave_size);
  1367. pkey_assert(xsave > 0);
  1368. /* Modify the PKRU register directly */
  1369. iov.iov_base = xsave;
  1370. iov.iov_len = xsave_size;
  1371. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1372. pkey_assert(ret == 0);
  1373. pkey_register = (u32 *)(xsave + pkey_offset);
  1374. pkey_assert(*pkey_register == read_pkey_reg());
  1375. *pkey_register = new_pkru;
  1376. ret = ptrace(PTRACE_SETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1377. pkey_assert(ret == 0);
  1378. /* Test that the modification is visible in ptrace before any execution */
  1379. memset(xsave, 0xCC, xsave_size);
  1380. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1381. pkey_assert(ret == 0);
  1382. pkey_assert(*pkey_register == new_pkru);
  1383. /* Execute the tracee */
  1384. ret = ptrace(PTRACE_CONT, child, 0, 0);
  1385. pkey_assert(ret == 0);
  1386. /* Test that the tracee saw the PKRU value change */
  1387. pkey_assert(child == waitpid(child, &status, 0));
  1388. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1389. pkey_assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  1390. /* Test that the modification is visible in ptrace after execution */
  1391. memset(xsave, 0xCC, xsave_size);
  1392. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1393. pkey_assert(ret == 0);
  1394. pkey_assert(*pkey_register == new_pkru);
  1395. /* Clear the PKRU bit from XSTATE_BV */
  1396. xstate_bv = (u64 *)(xsave + 512);
  1397. *xstate_bv &= ~(1 << 9);
  1398. ret = ptrace(PTRACE_SETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1399. pkey_assert(ret == 0);
  1400. /* Test that the modification is visible in ptrace before any execution */
  1401. memset(xsave, 0xCC, xsave_size);
  1402. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1403. pkey_assert(ret == 0);
  1404. pkey_assert(*pkey_register == 0);
  1405. ret = ptrace(PTRACE_CONT, child, 0, 0);
  1406. pkey_assert(ret == 0);
  1407. /* Test that the tracee saw the PKRU value go to 0 */
  1408. pkey_assert(child == waitpid(child, &status, 0));
  1409. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1410. pkey_assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  1411. /* Test that the modification is visible in ptrace after execution */
  1412. memset(xsave, 0xCC, xsave_size);
  1413. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_X86_XSTATE, &iov);
  1414. pkey_assert(ret == 0);
  1415. pkey_assert(*pkey_register == 0);
  1416. ret = ptrace(PTRACE_CONT, child, 0, 0);
  1417. pkey_assert(ret == 0);
  1418. pkey_assert(child == waitpid(child, &status, 0));
  1419. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1420. pkey_assert(WIFEXITED(status));
  1421. pkey_assert(WEXITSTATUS(status) == 0);
  1422. free(xsave);
  1423. }
  1424. #endif
  1425. #if defined(__aarch64__)
  1426. void test_ptrace_modifies_pkru(int *ptr, u16 pkey)
  1427. {
  1428. pid_t child;
  1429. int status, ret;
  1430. struct iovec iov;
  1431. u64 trace_pkey;
  1432. /* Just a random pkey value.. */
  1433. u64 new_pkey = (POE_X << PKEY_BITS_PER_PKEY * 2) |
  1434. (POE_NONE << PKEY_BITS_PER_PKEY) |
  1435. POE_RWX;
  1436. child = fork();
  1437. pkey_assert(child >= 0);
  1438. dprintf3("[%d] fork() ret: %d\n", getpid(), child);
  1439. if (!child) {
  1440. ptrace(PTRACE_TRACEME, 0, 0, 0);
  1441. /* Stop and allow the tracer to modify PKRU directly */
  1442. raise(SIGSTOP);
  1443. /*
  1444. * need __read_pkey_reg() version so we do not do shadow_pkey_reg
  1445. * checking
  1446. */
  1447. if (__read_pkey_reg() != new_pkey)
  1448. exit(1);
  1449. raise(SIGSTOP);
  1450. exit(0);
  1451. }
  1452. pkey_assert(child == waitpid(child, &status, 0));
  1453. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1454. pkey_assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  1455. iov.iov_base = &trace_pkey;
  1456. iov.iov_len = 8;
  1457. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_ARM_POE, &iov);
  1458. pkey_assert(ret == 0);
  1459. pkey_assert(trace_pkey == read_pkey_reg());
  1460. trace_pkey = new_pkey;
  1461. ret = ptrace(PTRACE_SETREGSET, child, (void *)NT_ARM_POE, &iov);
  1462. pkey_assert(ret == 0);
  1463. /* Test that the modification is visible in ptrace before any execution */
  1464. memset(&trace_pkey, 0, sizeof(trace_pkey));
  1465. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_ARM_POE, &iov);
  1466. pkey_assert(ret == 0);
  1467. pkey_assert(trace_pkey == new_pkey);
  1468. /* Execute the tracee */
  1469. ret = ptrace(PTRACE_CONT, child, 0, 0);
  1470. pkey_assert(ret == 0);
  1471. /* Test that the tracee saw the PKRU value change */
  1472. pkey_assert(child == waitpid(child, &status, 0));
  1473. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1474. pkey_assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  1475. /* Test that the modification is visible in ptrace after execution */
  1476. memset(&trace_pkey, 0, sizeof(trace_pkey));
  1477. ret = ptrace(PTRACE_GETREGSET, child, (void *)NT_ARM_POE, &iov);
  1478. pkey_assert(ret == 0);
  1479. pkey_assert(trace_pkey == new_pkey);
  1480. ret = ptrace(PTRACE_CONT, child, 0, 0);
  1481. pkey_assert(ret == 0);
  1482. pkey_assert(child == waitpid(child, &status, 0));
  1483. dprintf3("[%d] waitpid(%d) status: %x\n", getpid(), child, status);
  1484. pkey_assert(WIFEXITED(status));
  1485. pkey_assert(WEXITSTATUS(status) == 0);
  1486. }
  1487. #endif
  1488. void test_mprotect_pkey_on_unsupported_cpu(int *ptr, u16 pkey)
  1489. {
  1490. int size = PAGE_SIZE;
  1491. int sret;
  1492. if (cpu_has_pkeys()) {
  1493. dprintf1("SKIP: %s: no CPU support\n", __func__);
  1494. return;
  1495. }
  1496. sret = syscall(__NR_pkey_mprotect, ptr, size, PROT_READ, pkey);
  1497. pkey_assert(sret < 0);
  1498. }
  1499. void (*pkey_tests[])(int *ptr, u16 pkey) = {
  1500. test_read_of_write_disabled_region,
  1501. test_read_of_access_disabled_region,
  1502. test_read_of_access_disabled_region_with_page_already_mapped,
  1503. test_write_of_write_disabled_region,
  1504. test_write_of_write_disabled_region_with_page_already_mapped,
  1505. test_write_of_access_disabled_region,
  1506. test_write_of_access_disabled_region_with_page_already_mapped,
  1507. test_kernel_write_of_access_disabled_region,
  1508. test_kernel_write_of_write_disabled_region,
  1509. test_kernel_gup_of_access_disabled_region,
  1510. test_kernel_gup_write_to_write_disabled_region,
  1511. test_executing_on_unreadable_memory,
  1512. test_implicit_mprotect_exec_only_memory,
  1513. test_mprotect_with_pkey_0,
  1514. test_ptrace_of_child,
  1515. test_pkey_init_state,
  1516. test_pkey_syscalls_on_non_allocated_pkey,
  1517. test_pkey_syscalls_bad_args,
  1518. test_pkey_alloc_exhaust,
  1519. test_pkey_alloc_free_attach_pkey0,
  1520. #if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
  1521. test_ptrace_modifies_pkru,
  1522. #endif
  1523. };
  1524. void run_tests_once(void)
  1525. {
  1526. int *ptr;
  1527. int prot = PROT_READ|PROT_WRITE;
  1528. for (test_nr = 0; test_nr < ARRAY_SIZE(pkey_tests); test_nr++) {
  1529. int pkey;
  1530. int orig_pkey_faults = pkey_faults;
  1531. dprintf1("======================\n");
  1532. dprintf1("test %d preparing...\n", test_nr);
  1533. tracing_on();
  1534. pkey = alloc_random_pkey();
  1535. dprintf1("test %d starting with pkey: %d\n", test_nr, pkey);
  1536. ptr = malloc_pkey(PAGE_SIZE, prot, pkey);
  1537. dprintf1("test %d starting...\n", test_nr);
  1538. pkey_tests[test_nr](ptr, pkey);
  1539. dprintf1("freeing test memory: %p\n", ptr);
  1540. free_pkey_malloc(ptr);
  1541. sys_pkey_free(pkey);
  1542. dprintf1("pkey_faults: %d\n", pkey_faults);
  1543. dprintf1("orig_pkey_faults: %d\n", orig_pkey_faults);
  1544. tracing_off();
  1545. close_test_fds();
  1546. printf("test %2d PASSED (iteration %d)\n", test_nr, iteration_nr);
  1547. dprintf1("======================\n\n");
  1548. }
  1549. iteration_nr++;
  1550. }
  1551. void pkey_setup_shadow(void)
  1552. {
  1553. shadow_pkey_reg = __read_pkey_reg();
  1554. }
  1555. int main(void)
  1556. {
  1557. int nr_iterations = 22;
  1558. int pkeys_supported = is_pkeys_supported();
  1559. srand((unsigned int)time(NULL));
  1560. setup_handlers();
  1561. printf("has pkeys: %d\n", pkeys_supported);
  1562. if (!pkeys_supported) {
  1563. int size = PAGE_SIZE;
  1564. int *ptr;
  1565. printf("running PKEY tests for unsupported CPU/OS\n");
  1566. ptr = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  1567. assert(ptr != (void *)-1);
  1568. test_mprotect_pkey_on_unsupported_cpu(ptr, 1);
  1569. exit(0);
  1570. }
  1571. pkey_setup_shadow();
  1572. printf("startup pkey_reg: %016llx\n", read_pkey_reg());
  1573. setup_hugetlbfs();
  1574. while (nr_iterations-- > 0)
  1575. run_tests_once();
  1576. printf("done (all tests OK)\n");
  1577. return 0;
  1578. }