2 * sysret_ss_attrs.c - test that syscalls return valid hidden SS attributes
3 * Copyright (c) 2015 Andrew Lutomirski
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms and conditions of the GNU General Public License,
7 * version 2, as published by the Free Software Foundation.
9 * This program is distributed in the hope it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * On AMD CPUs, SYSRET can return with a valid SS descriptor with with
15 * the hidden attributes set to an unusable state. Make sure the kernel
16 * doesn't let this happen.
31 static void *threadproc(void *ctx
)
34 * Do our best to cause sleeps on this CPU to exit the kernel and
35 * re-enter with SS = 0.
44 extern unsigned long call32_from_64(void *stack
, void (*function
)(void));
46 asm (".pushsection .text\n\t"
53 extern void test_ss(void);
59 * Start a busy-looping thread on the same CPU we're on.
60 * For simplicity, just stick everything to CPU 0. This will
61 * fail in some containers, but that's probably okay.
66 if (sched_setaffinity(0, sizeof(cpuset
), &cpuset
) != 0)
67 printf("[WARN]\tsched_setaffinity failed\n");
70 if (pthread_create(&thread
, 0, threadproc
, 0) != 0)
71 err(1, "pthread_create");
74 unsigned char *stack32
= mmap(NULL
, 4096, PROT_READ
| PROT_WRITE
,
75 MAP_32BIT
| MAP_ANONYMOUS
| MAP_PRIVATE
,
77 if (stack32
== MAP_FAILED
)
81 printf("[RUN]\tSyscalls followed by SS validation\n");
83 for (int i
= 0; i
< 1000; i
++) {
85 * Go to sleep and return using sysret (if we're 64-bit
86 * or we're 32-bit on AMD on a 64-bit kernel). On AMD CPUs,
87 * SYSRET doesn't fix up the cached SS descriptor, so the
88 * kernel needs some kind of workaround to make sure that we
89 * end the system call with a valid stack segment. This
90 * can be a confusing failure because the SS *selector*
91 * is the same regardless.
97 * On 32-bit, just doing a syscall through glibc is enough
98 * to cause a crash if our cached SS descriptor is invalid.
99 * On 64-bit, it's not, so try extra hard.
101 call32_from_64(stack32
+ 4088, test_ss
);
105 printf("[OK]\tWe survived\n");
108 munmap(stack32
, 4096);