xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/testsuite/gdb.arch/i386-pkru.c (revision e670fd5c413e99c2f6a37901bb21c537fcd322d2)
1 /* Test program for PKEYS registers.
2 
3    Copyright 2015-2019 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include <stddef.h>
21 #include "x86-cpuid.h"
22 
23 #ifndef NOINLINE
24 #define NOINLINE __attribute__ ((noinline))
25 #endif
26 
27 unsigned int have_pkru (void) NOINLINE;
28 
29 static inline unsigned long
30 rdpkru (void)
31 {
32   unsigned int eax, edx;
33   unsigned int ecx = 0;
34   unsigned int pkru;
35 
36   asm volatile (".byte 0x0f,0x01,0xee\n\t"
37                : "=a" (eax), "=d" (edx)
38                : "c" (ecx));
39   pkru = eax;
40   return pkru;
41 }
42 
43 static inline void
44 wrpkru (unsigned int pkru)
45 {
46   unsigned int eax = pkru;
47   unsigned int ecx = 0;
48   unsigned int edx = 0;
49 
50   asm volatile (".byte 0x0f,0x01,0xef\n\t"
51                : : "a" (eax), "c" (ecx), "d" (edx));
52 }
53 
54 unsigned int NOINLINE
55 have_pkru (void)
56 {
57   unsigned int eax, ebx, ecx, edx;
58 
59   if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
60     return 0;
61 
62   if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
63     {
64       if (__get_cpuid_max (0, NULL) < 7)
65 	return 0;
66 
67       __cpuid_count (7, 0, eax, ebx, ecx, edx);
68 
69       if ((ecx & bit_PKU) == bit_PKU)
70 	return 1;
71     }
72   return 0;
73 }
74 
75 int
76 main (int argc, char **argv)
77 {
78   unsigned int wr_value = 0x12345678;
79   unsigned int rd_value = 0x0;
80 
81   if (have_pkru ())
82     {
83       wrpkru (wr_value);
84       asm ("nop\n\t");	/* break here 1.  */
85 
86       rd_value = rdpkru ();
87       asm ("nop\n\t");	/* break here 2.  */
88     }
89   return 0;
90 }
91