selftests/x86/ldt_gdt: Run most existing LDT test cases against the GDT as well
[linux-2.6-microblaze.git] / tools / testing / selftests / x86 / ldt_gdt.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ldt_gdt.c - Test cases for LDT and GDT access
4  * Copyright (c) 2015 Andrew Lutomirski
5  */
6
7 #define _GNU_SOURCE
8 #include <err.h>
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <signal.h>
12 #include <setjmp.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <errno.h>
16 #include <unistd.h>
17 #include <sys/syscall.h>
18 #include <asm/ldt.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <stdbool.h>
22 #include <pthread.h>
23 #include <sched.h>
24 #include <linux/futex.h>
25 #include <sys/mman.h>
26 #include <asm/prctl.h>
27 #include <sys/prctl.h>
28
29 #define AR_ACCESSED             (1<<8)
30
31 #define AR_TYPE_RODATA          (0 * (1<<9))
32 #define AR_TYPE_RWDATA          (1 * (1<<9))
33 #define AR_TYPE_RODATA_EXPDOWN  (2 * (1<<9))
34 #define AR_TYPE_RWDATA_EXPDOWN  (3 * (1<<9))
35 #define AR_TYPE_XOCODE          (4 * (1<<9))
36 #define AR_TYPE_XRCODE          (5 * (1<<9))
37 #define AR_TYPE_XOCODE_CONF     (6 * (1<<9))
38 #define AR_TYPE_XRCODE_CONF     (7 * (1<<9))
39
40 #define AR_DPL3                 (3 * (1<<13))
41
42 #define AR_S                    (1 << 12)
43 #define AR_P                    (1 << 15)
44 #define AR_AVL                  (1 << 20)
45 #define AR_L                    (1 << 21)
46 #define AR_DB                   (1 << 22)
47 #define AR_G                    (1 << 23)
48
49 #ifdef __x86_64__
50 # define INT80_CLOBBERS "r8", "r9", "r10", "r11"
51 #else
52 # define INT80_CLOBBERS
53 #endif
54
55 static int nerrs;
56
57 /* Points to an array of 1024 ints, each holding its own index. */
58 static const unsigned int *counter_page;
59 static struct user_desc *low_user_desc;
60 static struct user_desc *low_user_desc_clear;  /* Use to delete GDT entry */
61 static int gdt_entry_num;
62
63 static void check_invalid_segment(uint16_t index, int ldt)
64 {
65         uint32_t has_limit = 0, has_ar = 0, limit, ar;
66         uint32_t selector = (index << 3) | (ldt << 2) | 3;
67
68         asm ("lsl %[selector], %[limit]\n\t"
69              "jnz 1f\n\t"
70              "movl $1, %[has_limit]\n\t"
71              "1:"
72              : [limit] "=r" (limit), [has_limit] "+rm" (has_limit)
73              : [selector] "r" (selector));
74         asm ("larl %[selector], %[ar]\n\t"
75              "jnz 1f\n\t"
76              "movl $1, %[has_ar]\n\t"
77              "1:"
78              : [ar] "=r" (ar), [has_ar] "+rm" (has_ar)
79              : [selector] "r" (selector));
80
81         if (has_limit || has_ar) {
82                 printf("[FAIL]\t%s entry %hu is valid but should be invalid\n",
83                        (ldt ? "LDT" : "GDT"), index);
84                 nerrs++;
85         } else {
86                 printf("[OK]\t%s entry %hu is invalid\n",
87                        (ldt ? "LDT" : "GDT"), index);
88         }
89 }
90
91 static void check_valid_segment(uint16_t index, int ldt,
92                                 uint32_t expected_ar, uint32_t expected_limit,
93                                 bool verbose)
94 {
95         uint32_t has_limit = 0, has_ar = 0, limit, ar;
96         uint32_t selector = (index << 3) | (ldt << 2) | 3;
97
98         asm ("lsl %[selector], %[limit]\n\t"
99              "jnz 1f\n\t"
100              "movl $1, %[has_limit]\n\t"
101              "1:"
102              : [limit] "=r" (limit), [has_limit] "+rm" (has_limit)
103              : [selector] "r" (selector));
104         asm ("larl %[selector], %[ar]\n\t"
105              "jnz 1f\n\t"
106              "movl $1, %[has_ar]\n\t"
107              "1:"
108              : [ar] "=r" (ar), [has_ar] "+rm" (has_ar)
109              : [selector] "r" (selector));
110
111         if (!has_limit || !has_ar) {
112                 printf("[FAIL]\t%s entry %hu is invalid but should be valid\n",
113                        (ldt ? "LDT" : "GDT"), index);
114                 nerrs++;
115                 return;
116         }
117
118         /* The SDM says "bits 19:16 are undefined".  Thanks. */
119         ar &= ~0xF0000;
120
121         /*
122          * NB: Different Linux versions do different things with the
123          * accessed bit in set_thread_area().
124          */
125         if (ar != expected_ar &&
126             (ldt || ar != (expected_ar | AR_ACCESSED))) {
127                 printf("[FAIL]\t%s entry %hu has AR 0x%08X but expected 0x%08X\n",
128                        (ldt ? "LDT" : "GDT"), index, ar, expected_ar);
129                 nerrs++;
130         } else if (limit != expected_limit) {
131                 printf("[FAIL]\t%s entry %hu has limit 0x%08X but expected 0x%08X\n",
132                        (ldt ? "LDT" : "GDT"), index, limit, expected_limit);
133                 nerrs++;
134         } else if (verbose) {
135                 printf("[OK]\t%s entry %hu has AR 0x%08X and limit 0x%08X\n",
136                        (ldt ? "LDT" : "GDT"), index, ar, limit);
137         }
138 }
139
140 static bool install_valid_mode(const struct user_desc *d, uint32_t ar,
141                                bool oldmode, bool ldt)
142 {
143         struct user_desc desc = *d;
144         int ret;
145
146         if (!ldt) {
147 #ifndef __i386__
148                 /* No point testing set_thread_area in a 64-bit build */
149                 return false;
150 #endif
151                 if (!gdt_entry_num)
152                         return false;
153                 desc.entry_number = gdt_entry_num;
154
155                 ret = syscall(SYS_set_thread_area, &desc);
156         } else {
157                 ret = syscall(SYS_modify_ldt, oldmode ? 1 : 0x11,
158                               &desc, sizeof(desc));
159
160                 if (ret < -1)
161                         errno = -ret;
162
163                 if (ret != 0 && errno == ENOSYS) {
164                         printf("[OK]\tmodify_ldt returned -ENOSYS\n");
165                         return false;
166                 }
167         }
168
169         if (ret == 0) {
170                 uint32_t limit = desc.limit;
171                 if (desc.limit_in_pages)
172                         limit = (limit << 12) + 4095;
173                 check_valid_segment(desc.entry_number, ldt, ar, limit, true);
174                 return true;
175         } else {
176                 if (desc.seg_32bit) {
177                         printf("[FAIL]\tUnexpected %s failure %d\n",
178                                ldt ? "modify_ldt" : "set_thread_area",
179                                errno);
180                         nerrs++;
181                         return false;
182                 } else {
183                         printf("[OK]\t%s rejected 16 bit segment\n",
184                                ldt ? "modify_ldt" : "set_thread_area");
185                         return false;
186                 }
187         }
188 }
189
190 static bool install_valid(const struct user_desc *desc, uint32_t ar)
191 {
192         bool ret = install_valid_mode(desc, ar, false, true);
193
194         if (desc->contents <= 1 && desc->seg_32bit &&
195             !desc->seg_not_present) {
196                 /* Should work in the GDT, too. */
197                 install_valid_mode(desc, ar, false, false);
198         }
199
200         return ret;
201 }
202
203 static void install_invalid(const struct user_desc *desc, bool oldmode)
204 {
205         int ret = syscall(SYS_modify_ldt, oldmode ? 1 : 0x11,
206                           desc, sizeof(*desc));
207         if (ret < -1)
208                 errno = -ret;
209         if (ret == 0) {
210                 check_invalid_segment(desc->entry_number, 1);
211         } else if (errno == ENOSYS) {
212                 printf("[OK]\tmodify_ldt returned -ENOSYS\n");
213         } else {
214                 if (desc->seg_32bit) {
215                         printf("[FAIL]\tUnexpected modify_ldt failure %d\n",
216                                errno);
217                         nerrs++;
218                 } else {
219                         printf("[OK]\tmodify_ldt rejected 16 bit segment\n");
220                 }
221         }
222 }
223
224 static int safe_modify_ldt(int func, struct user_desc *ptr,
225                            unsigned long bytecount)
226 {
227         int ret = syscall(SYS_modify_ldt, 0x11, ptr, bytecount);
228         if (ret < -1)
229                 errno = -ret;
230         return ret;
231 }
232
233 static void fail_install(struct user_desc *desc)
234 {
235         if (safe_modify_ldt(0x11, desc, sizeof(*desc)) == 0) {
236                 printf("[FAIL]\tmodify_ldt accepted a bad descriptor\n");
237                 nerrs++;
238         } else if (errno == ENOSYS) {
239                 printf("[OK]\tmodify_ldt returned -ENOSYS\n");
240         } else {
241                 printf("[OK]\tmodify_ldt failure %d\n", errno);
242         }
243 }
244
245 static void do_simple_tests(void)
246 {
247         struct user_desc desc = {
248                 .entry_number    = 0,
249                 .base_addr       = 0,
250                 .limit           = 10,
251                 .seg_32bit       = 1,
252                 .contents        = 2, /* Code, not conforming */
253                 .read_exec_only  = 0,
254                 .limit_in_pages  = 0,
255                 .seg_not_present = 0,
256                 .useable         = 0
257         };
258         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE | AR_S | AR_P | AR_DB);
259
260         desc.limit_in_pages = 1;
261         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
262                       AR_S | AR_P | AR_DB | AR_G);
263
264         check_invalid_segment(1, 1);
265
266         desc.entry_number = 2;
267         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
268                       AR_S | AR_P | AR_DB | AR_G);
269
270         check_invalid_segment(1, 1);
271
272         desc.base_addr = 0xf0000000;
273         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
274                       AR_S | AR_P | AR_DB | AR_G);
275
276         desc.useable = 1;
277         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
278                       AR_S | AR_P | AR_DB | AR_G | AR_AVL);
279
280         desc.seg_not_present = 1;
281         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
282                       AR_S | AR_DB | AR_G | AR_AVL);
283
284         desc.seg_32bit = 0;
285         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
286                       AR_S | AR_G | AR_AVL);
287
288         desc.seg_32bit = 1;
289         desc.contents = 0;
290         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA |
291                       AR_S | AR_DB | AR_G | AR_AVL);
292
293         desc.read_exec_only = 1;
294         install_valid(&desc, AR_DPL3 | AR_TYPE_RODATA |
295                       AR_S | AR_DB | AR_G | AR_AVL);
296
297         desc.contents = 1;
298         install_valid(&desc, AR_DPL3 | AR_TYPE_RODATA_EXPDOWN |
299                       AR_S | AR_DB | AR_G | AR_AVL);
300
301         desc.read_exec_only = 0;
302         desc.limit_in_pages = 0;
303         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA_EXPDOWN |
304                       AR_S | AR_DB | AR_AVL);
305
306         desc.contents = 3;
307         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE_CONF |
308                       AR_S | AR_DB | AR_AVL);
309
310         desc.read_exec_only = 1;
311         install_valid(&desc, AR_DPL3 | AR_TYPE_XOCODE_CONF |
312                       AR_S | AR_DB | AR_AVL);
313
314         desc.read_exec_only = 0;
315         desc.contents = 2;
316         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE |
317                       AR_S | AR_DB | AR_AVL);
318
319         desc.read_exec_only = 1;
320
321 #ifdef __x86_64__
322         desc.lm = 1;
323         install_valid(&desc, AR_DPL3 | AR_TYPE_XOCODE |
324                       AR_S | AR_DB | AR_AVL);
325         desc.lm = 0;
326 #endif
327
328         bool entry1_okay = install_valid(&desc, AR_DPL3 | AR_TYPE_XOCODE |
329                                          AR_S | AR_DB | AR_AVL);
330
331         if (entry1_okay) {
332                 printf("[RUN]\tTest fork\n");
333                 pid_t child = fork();
334                 if (child == 0) {
335                         nerrs = 0;
336                         check_valid_segment(desc.entry_number, 1,
337                                             AR_DPL3 | AR_TYPE_XOCODE |
338                                             AR_S | AR_DB | AR_AVL, desc.limit,
339                                             true);
340                         check_invalid_segment(1, 1);
341                         exit(nerrs ? 1 : 0);
342                 } else {
343                         int status;
344                         if (waitpid(child, &status, 0) != child ||
345                             !WIFEXITED(status)) {
346                                 printf("[FAIL]\tChild died\n");
347                                 nerrs++;
348                         } else if (WEXITSTATUS(status) != 0) {
349                                 printf("[FAIL]\tChild failed\n");
350                                 nerrs++;
351                         } else {
352                                 printf("[OK]\tChild succeeded\n");
353                         }
354                 }
355
356                 printf("[RUN]\tTest size\n");
357                 int i;
358                 for (i = 0; i < 8192; i++) {
359                         desc.entry_number = i;
360                         desc.limit = i;
361                         if (safe_modify_ldt(0x11, &desc, sizeof(desc)) != 0) {
362                                 printf("[FAIL]\tFailed to install entry %d\n", i);
363                                 nerrs++;
364                                 break;
365                         }
366                 }
367                 for (int j = 0; j < i; j++) {
368                         check_valid_segment(j, 1, AR_DPL3 | AR_TYPE_XOCODE |
369                                             AR_S | AR_DB | AR_AVL, j, false);
370                 }
371                 printf("[DONE]\tSize test\n");
372         } else {
373                 printf("[SKIP]\tSkipping fork and size tests because we have no LDT\n");
374         }
375
376         /* Test entry_number too high. */
377         desc.entry_number = 8192;
378         fail_install(&desc);
379
380         /* Test deletion and actions mistakeable for deletion. */
381         memset(&desc, 0, sizeof(desc));
382         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA | AR_S | AR_P);
383
384         desc.seg_not_present = 1;
385         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA | AR_S);
386
387         desc.seg_not_present = 0;
388         desc.read_exec_only = 1;
389         install_valid(&desc, AR_DPL3 | AR_TYPE_RODATA | AR_S | AR_P);
390
391         desc.read_exec_only = 0;
392         desc.seg_not_present = 1;
393         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA | AR_S);
394
395         desc.read_exec_only = 1;
396         desc.limit = 1;
397         install_valid(&desc, AR_DPL3 | AR_TYPE_RODATA | AR_S);
398
399         desc.limit = 0;
400         desc.base_addr = 1;
401         install_valid(&desc, AR_DPL3 | AR_TYPE_RODATA | AR_S);
402
403         desc.base_addr = 0;
404         install_invalid(&desc, false);
405
406         desc.seg_not_present = 0;
407         desc.read_exec_only = 0;
408         desc.seg_32bit = 1;
409         install_valid(&desc, AR_DPL3 | AR_TYPE_RWDATA | AR_S | AR_P | AR_DB);
410         install_invalid(&desc, true);
411 }
412
413 /*
414  * 0: thread is idle
415  * 1: thread armed
416  * 2: thread should clear LDT entry 0
417  * 3: thread should exit
418  */
419 static volatile unsigned int ftx;
420
421 static void *threadproc(void *ctx)
422 {
423         cpu_set_t cpuset;
424         CPU_ZERO(&cpuset);
425         CPU_SET(1, &cpuset);
426         if (sched_setaffinity(0, sizeof(cpuset), &cpuset) != 0)
427                 err(1, "sched_setaffinity to CPU 1");   /* should never fail */
428
429         while (1) {
430                 syscall(SYS_futex, &ftx, FUTEX_WAIT, 0, NULL, NULL, 0);
431                 while (ftx != 2) {
432                         if (ftx >= 3)
433                                 return NULL;
434                 }
435
436                 /* clear LDT entry 0 */
437                 const struct user_desc desc = {};
438                 if (syscall(SYS_modify_ldt, 1, &desc, sizeof(desc)) != 0)
439                         err(1, "modify_ldt");
440
441                 /* If ftx == 2, set it to zero.  If ftx == 100, quit. */
442                 unsigned int x = -2;
443                 asm volatile ("lock xaddl %[x], %[ftx]" :
444                               [x] "+r" (x), [ftx] "+m" (ftx));
445                 if (x != 2)
446                         return NULL;
447         }
448 }
449
450 #ifdef __i386__
451
452 #ifndef SA_RESTORE
453 #define SA_RESTORER 0x04000000
454 #endif
455
456 /*
457  * The UAPI header calls this 'struct sigaction', which conflicts with
458  * glibc.  Sigh.
459  */
460 struct fake_ksigaction {
461         void *handler;  /* the real type is nasty */
462         unsigned long sa_flags;
463         void (*sa_restorer)(void);
464         unsigned char sigset[8];
465 };
466
467 static void fix_sa_restorer(int sig)
468 {
469         struct fake_ksigaction ksa;
470
471         if (syscall(SYS_rt_sigaction, sig, NULL, &ksa, 8) == 0) {
472                 /*
473                  * glibc has a nasty bug: it sometimes writes garbage to
474                  * sa_restorer.  This interacts quite badly with anything
475                  * that fiddles with SS because it can trigger legacy
476                  * stack switching.  Patch it up.  See:
477                  *
478                  * https://sourceware.org/bugzilla/show_bug.cgi?id=21269
479                  */
480                 if (!(ksa.sa_flags & SA_RESTORER) && ksa.sa_restorer) {
481                         ksa.sa_restorer = NULL;
482                         if (syscall(SYS_rt_sigaction, sig, &ksa, NULL,
483                                     sizeof(ksa.sigset)) != 0)
484                                 err(1, "rt_sigaction");
485                 }
486         }
487 }
488 #else
489 static void fix_sa_restorer(int sig)
490 {
491         /* 64-bit glibc works fine. */
492 }
493 #endif
494
495 static void sethandler(int sig, void (*handler)(int, siginfo_t *, void *),
496                        int flags)
497 {
498         struct sigaction sa;
499         memset(&sa, 0, sizeof(sa));
500         sa.sa_sigaction = handler;
501         sa.sa_flags = SA_SIGINFO | flags;
502         sigemptyset(&sa.sa_mask);
503         if (sigaction(sig, &sa, 0))
504                 err(1, "sigaction");
505
506         fix_sa_restorer(sig);
507 }
508
509 static jmp_buf jmpbuf;
510
511 static void sigsegv(int sig, siginfo_t *info, void *ctx_void)
512 {
513         siglongjmp(jmpbuf, 1);
514 }
515
516 static void do_multicpu_tests(void)
517 {
518         cpu_set_t cpuset;
519         pthread_t thread;
520         int failures = 0, iters = 5, i;
521         unsigned short orig_ss;
522
523         CPU_ZERO(&cpuset);
524         CPU_SET(1, &cpuset);
525         if (sched_setaffinity(0, sizeof(cpuset), &cpuset) != 0) {
526                 printf("[SKIP]\tCannot set affinity to CPU 1\n");
527                 return;
528         }
529
530         CPU_ZERO(&cpuset);
531         CPU_SET(0, &cpuset);
532         if (sched_setaffinity(0, sizeof(cpuset), &cpuset) != 0) {
533                 printf("[SKIP]\tCannot set affinity to CPU 0\n");
534                 return;
535         }
536
537         sethandler(SIGSEGV, sigsegv, 0);
538 #ifdef __i386__
539         /* True 32-bit kernels send SIGILL instead of SIGSEGV on IRET faults. */
540         sethandler(SIGILL, sigsegv, 0);
541 #endif
542
543         printf("[RUN]\tCross-CPU LDT invalidation\n");
544
545         if (pthread_create(&thread, 0, threadproc, 0) != 0)
546                 err(1, "pthread_create");
547
548         asm volatile ("mov %%ss, %0" : "=rm" (orig_ss));
549
550         for (i = 0; i < 5; i++) {
551                 if (sigsetjmp(jmpbuf, 1) != 0)
552                         continue;
553
554                 /* Make sure the thread is ready after the last test. */
555                 while (ftx != 0)
556                         ;
557
558                 struct user_desc desc = {
559                         .entry_number    = 0,
560                         .base_addr       = 0,
561                         .limit           = 0xfffff,
562                         .seg_32bit       = 1,
563                         .contents        = 0, /* Data */
564                         .read_exec_only  = 0,
565                         .limit_in_pages  = 1,
566                         .seg_not_present = 0,
567                         .useable         = 0
568                 };
569
570                 if (safe_modify_ldt(0x11, &desc, sizeof(desc)) != 0) {
571                         if (errno != ENOSYS)
572                                 err(1, "modify_ldt");
573                         printf("[SKIP]\tmodify_ldt unavailable\n");
574                         break;
575                 }
576
577                 /* Arm the thread. */
578                 ftx = 1;
579                 syscall(SYS_futex, &ftx, FUTEX_WAKE, 0, NULL, NULL, 0);
580
581                 asm volatile ("mov %0, %%ss" : : "r" (0x7));
582
583                 /* Go! */
584                 ftx = 2;
585
586                 while (ftx != 0)
587                         ;
588
589                 /*
590                  * On success, modify_ldt will segfault us synchronously,
591                  * and we'll escape via siglongjmp.
592                  */
593
594                 failures++;
595                 asm volatile ("mov %0, %%ss" : : "rm" (orig_ss));
596         };
597
598         ftx = 100;  /* Kill the thread. */
599         syscall(SYS_futex, &ftx, FUTEX_WAKE, 0, NULL, NULL, 0);
600
601         if (pthread_join(thread, NULL) != 0)
602                 err(1, "pthread_join");
603
604         if (failures) {
605                 printf("[FAIL]\t%d of %d iterations failed\n", failures, iters);
606                 nerrs++;
607         } else {
608                 printf("[OK]\tAll %d iterations succeeded\n", iters);
609         }
610 }
611
612 static int finish_exec_test(void)
613 {
614         /*
615          * In a sensible world, this would be check_invalid_segment(0, 1);
616          * For better or for worse, though, the LDT is inherited across exec.
617          * We can probably change this safely, but for now we test it.
618          */
619         check_valid_segment(0, 1,
620                             AR_DPL3 | AR_TYPE_XRCODE | AR_S | AR_P | AR_DB,
621                             42, true);
622
623         return nerrs ? 1 : 0;
624 }
625
626 static void do_exec_test(void)
627 {
628         printf("[RUN]\tTest exec\n");
629
630         struct user_desc desc = {
631                 .entry_number    = 0,
632                 .base_addr       = 0,
633                 .limit           = 42,
634                 .seg_32bit       = 1,
635                 .contents        = 2, /* Code, not conforming */
636                 .read_exec_only  = 0,
637                 .limit_in_pages  = 0,
638                 .seg_not_present = 0,
639                 .useable         = 0
640         };
641         install_valid(&desc, AR_DPL3 | AR_TYPE_XRCODE | AR_S | AR_P | AR_DB);
642
643         pid_t child = fork();
644         if (child == 0) {
645                 execl("/proc/self/exe", "ldt_gdt_test_exec", NULL);
646                 printf("[FAIL]\tCould not exec self\n");
647                 exit(1);        /* exec failed */
648         } else {
649                 int status;
650                 if (waitpid(child, &status, 0) != child ||
651                     !WIFEXITED(status)) {
652                         printf("[FAIL]\tChild died\n");
653                         nerrs++;
654                 } else if (WEXITSTATUS(status) != 0) {
655                         printf("[FAIL]\tChild failed\n");
656                         nerrs++;
657                 } else {
658                         printf("[OK]\tChild succeeded\n");
659                 }
660         }
661 }
662
663 static void setup_counter_page(void)
664 {
665         unsigned int *page = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
666                          MAP_ANONYMOUS | MAP_PRIVATE | MAP_32BIT, -1, 0);
667         if (page == MAP_FAILED)
668                 err(1, "mmap");
669
670         for (int i = 0; i < 1024; i++)
671                 page[i] = i;
672         counter_page = page;
673 }
674
675 static int invoke_set_thread_area(void)
676 {
677         int ret;
678         asm volatile ("int $0x80"
679                       : "=a" (ret), "+m" (low_user_desc) :
680                         "a" (243), "b" (low_user_desc)
681                       : INT80_CLOBBERS);
682         return ret;
683 }
684
685 static void setup_low_user_desc(void)
686 {
687         low_user_desc = mmap(NULL, 2 * sizeof(struct user_desc),
688                              PROT_READ | PROT_WRITE,
689                              MAP_ANONYMOUS | MAP_PRIVATE | MAP_32BIT, -1, 0);
690         if (low_user_desc == MAP_FAILED)
691                 err(1, "mmap");
692
693         low_user_desc->entry_number     = -1;
694         low_user_desc->base_addr        = (unsigned long)&counter_page[1];
695         low_user_desc->limit            = 0xfffff;
696         low_user_desc->seg_32bit        = 1;
697         low_user_desc->contents         = 0; /* Data, grow-up*/
698         low_user_desc->read_exec_only   = 0;
699         low_user_desc->limit_in_pages   = 1;
700         low_user_desc->seg_not_present  = 0;
701         low_user_desc->useable          = 0;
702
703         if (invoke_set_thread_area() == 0) {
704                 gdt_entry_num = low_user_desc->entry_number;
705                 printf("[NOTE]\tset_thread_area is available; will use GDT index %d\n", gdt_entry_num);
706         } else {
707                 printf("[NOTE]\tset_thread_area is unavailable\n");
708         }
709
710         low_user_desc_clear = low_user_desc + 1;
711         low_user_desc_clear->entry_number = gdt_entry_num;
712         low_user_desc_clear->read_exec_only = 1;
713         low_user_desc_clear->seg_not_present = 1;
714 }
715
716 static void test_gdt_invalidation(void)
717 {
718         if (!gdt_entry_num)
719                 return; /* 64-bit only system -- we can't use set_thread_area */
720
721         unsigned short prev_sel;
722         unsigned short sel;
723         unsigned int eax;
724         const char *result;
725 #ifdef __x86_64__
726         unsigned long saved_base;
727         unsigned long new_base;
728 #endif
729
730         /* Test DS */
731         invoke_set_thread_area();
732         eax = 243;
733         sel = (gdt_entry_num << 3) | 3;
734         asm volatile ("movw %%ds, %[prev_sel]\n\t"
735                       "movw %[sel], %%ds\n\t"
736 #ifdef __i386__
737                       "pushl %%ebx\n\t"
738 #endif
739                       "movl %[arg1], %%ebx\n\t"
740                       "int $0x80\n\t"   /* Should invalidate ds */
741 #ifdef __i386__
742                       "popl %%ebx\n\t"
743 #endif
744                       "movw %%ds, %[sel]\n\t"
745                       "movw %[prev_sel], %%ds"
746                       : [prev_sel] "=&r" (prev_sel), [sel] "+r" (sel),
747                         "+a" (eax)
748                       : "m" (low_user_desc_clear),
749                         [arg1] "r" ((unsigned int)(unsigned long)low_user_desc_clear)
750                       : INT80_CLOBBERS);
751
752         if (sel != 0) {
753                 result = "FAIL";
754                 nerrs++;
755         } else {
756                 result = "OK";
757         }
758         printf("[%s]\tInvalidate DS with set_thread_area: new DS = 0x%hx\n",
759                result, sel);
760
761         /* Test ES */
762         invoke_set_thread_area();
763         eax = 243;
764         sel = (gdt_entry_num << 3) | 3;
765         asm volatile ("movw %%es, %[prev_sel]\n\t"
766                       "movw %[sel], %%es\n\t"
767 #ifdef __i386__
768                       "pushl %%ebx\n\t"
769 #endif
770                       "movl %[arg1], %%ebx\n\t"
771                       "int $0x80\n\t"   /* Should invalidate es */
772 #ifdef __i386__
773                       "popl %%ebx\n\t"
774 #endif
775                       "movw %%es, %[sel]\n\t"
776                       "movw %[prev_sel], %%es"
777                       : [prev_sel] "=&r" (prev_sel), [sel] "+r" (sel),
778                         "+a" (eax)
779                       : "m" (low_user_desc_clear),
780                         [arg1] "r" ((unsigned int)(unsigned long)low_user_desc_clear)
781                       : INT80_CLOBBERS);
782
783         if (sel != 0) {
784                 result = "FAIL";
785                 nerrs++;
786         } else {
787                 result = "OK";
788         }
789         printf("[%s]\tInvalidate ES with set_thread_area: new ES = 0x%hx\n",
790                result, sel);
791
792         /* Test FS */
793         invoke_set_thread_area();
794         eax = 243;
795         sel = (gdt_entry_num << 3) | 3;
796 #ifdef __x86_64__
797         syscall(SYS_arch_prctl, ARCH_GET_FS, &saved_base);
798 #endif
799         asm volatile ("movw %%fs, %[prev_sel]\n\t"
800                       "movw %[sel], %%fs\n\t"
801 #ifdef __i386__
802                       "pushl %%ebx\n\t"
803 #endif
804                       "movl %[arg1], %%ebx\n\t"
805                       "int $0x80\n\t"   /* Should invalidate fs */
806 #ifdef __i386__
807                       "popl %%ebx\n\t"
808 #endif
809                       "movw %%fs, %[sel]\n\t"
810                       : [prev_sel] "=&r" (prev_sel), [sel] "+r" (sel),
811                         "+a" (eax)
812                       : "m" (low_user_desc_clear),
813                         [arg1] "r" ((unsigned int)(unsigned long)low_user_desc_clear)
814                       : INT80_CLOBBERS);
815
816 #ifdef __x86_64__
817         syscall(SYS_arch_prctl, ARCH_GET_FS, &new_base);
818 #endif
819
820         /* Restore FS/BASE for glibc */
821         asm volatile ("movw %[prev_sel], %%fs" : : [prev_sel] "rm" (prev_sel));
822 #ifdef __x86_64__
823         if (saved_base)
824                 syscall(SYS_arch_prctl, ARCH_SET_FS, saved_base);
825 #endif
826
827         if (sel != 0) {
828                 result = "FAIL";
829                 nerrs++;
830         } else {
831                 result = "OK";
832         }
833         printf("[%s]\tInvalidate FS with set_thread_area: new FS = 0x%hx\n",
834                result, sel);
835
836 #ifdef __x86_64__
837         if (sel == 0 && new_base != 0) {
838                 nerrs++;
839                 printf("[FAIL]\tNew FSBASE was 0x%lx\n", new_base);
840         } else {
841                 printf("[OK]\tNew FSBASE was zero\n");
842         }
843 #endif
844
845         /* Test GS */
846         invoke_set_thread_area();
847         eax = 243;
848         sel = (gdt_entry_num << 3) | 3;
849 #ifdef __x86_64__
850         syscall(SYS_arch_prctl, ARCH_GET_GS, &saved_base);
851 #endif
852         asm volatile ("movw %%gs, %[prev_sel]\n\t"
853                       "movw %[sel], %%gs\n\t"
854 #ifdef __i386__
855                       "pushl %%ebx\n\t"
856 #endif
857                       "movl %[arg1], %%ebx\n\t"
858                       "int $0x80\n\t"   /* Should invalidate gs */
859 #ifdef __i386__
860                       "popl %%ebx\n\t"
861 #endif
862                       "movw %%gs, %[sel]\n\t"
863                       : [prev_sel] "=&r" (prev_sel), [sel] "+r" (sel),
864                         "+a" (eax)
865                       : "m" (low_user_desc_clear),
866                         [arg1] "r" ((unsigned int)(unsigned long)low_user_desc_clear)
867                       : INT80_CLOBBERS);
868
869 #ifdef __x86_64__
870         syscall(SYS_arch_prctl, ARCH_GET_GS, &new_base);
871 #endif
872
873         /* Restore GS/BASE for glibc */
874         asm volatile ("movw %[prev_sel], %%gs" : : [prev_sel] "rm" (prev_sel));
875 #ifdef __x86_64__
876         if (saved_base)
877                 syscall(SYS_arch_prctl, ARCH_SET_GS, saved_base);
878 #endif
879
880         if (sel != 0) {
881                 result = "FAIL";
882                 nerrs++;
883         } else {
884                 result = "OK";
885         }
886         printf("[%s]\tInvalidate GS with set_thread_area: new GS = 0x%hx\n",
887                result, sel);
888
889 #ifdef __x86_64__
890         if (sel == 0 && new_base != 0) {
891                 nerrs++;
892                 printf("[FAIL]\tNew GSBASE was 0x%lx\n", new_base);
893         } else {
894                 printf("[OK]\tNew GSBASE was zero\n");
895         }
896 #endif
897 }
898
899 int main(int argc, char **argv)
900 {
901         if (argc == 1 && !strcmp(argv[0], "ldt_gdt_test_exec"))
902                 return finish_exec_test();
903
904         setup_counter_page();
905         setup_low_user_desc();
906
907         do_simple_tests();
908
909         do_multicpu_tests();
910
911         do_exec_test();
912
913         test_gdt_invalidation();
914
915         return nerrs ? 1 : 0;
916 }