1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Corrupt the XSTATE header in a signal frame
4  *
5  * Based on analysis and a test case from Thomas Gleixner.
6  */
7 
8 #define _GNU_SOURCE
9 
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <sched.h>
14 #include <signal.h>
15 #include <err.h>
16 #include <unistd.h>
17 #include <stdint.h>
18 #include <sys/wait.h>
19 
20 #include "../kselftest.h" /* For __cpuid_count() */
21 #include "helpers.h"
22 
xsave_enabled(void)23 static inline int xsave_enabled(void)
24 {
25 	unsigned int eax, ebx, ecx, edx;
26 
27 	__cpuid_count(0x1, 0x0, eax, ebx, ecx, edx);
28 
29 	/* Is CR4.OSXSAVE enabled ? */
30 	return ecx & (1U << 27);
31 }
32 
sigusr1(int sig,siginfo_t * info,void * uc_void)33 static void sigusr1(int sig, siginfo_t *info, void *uc_void)
34 {
35 	ucontext_t *uc = uc_void;
36 	uint8_t *fpstate = (uint8_t *)uc->uc_mcontext.fpregs;
37 	uint64_t *xfeatures = (uint64_t *)(fpstate + 512);
38 
39 	printf("\tWreck XSTATE header\n");
40 	/* Wreck the first reserved bytes in the header */
41 	*(xfeatures + 2) = 0xfffffff;
42 }
43 
sigsegv(int sig,siginfo_t * info,void * uc_void)44 static void sigsegv(int sig, siginfo_t *info, void *uc_void)
45 {
46 	printf("\tGot SIGSEGV\n");
47 }
48 
main(void)49 int main(void)
50 {
51 	cpu_set_t set;
52 
53 	sethandler(SIGUSR1, sigusr1, 0);
54 	sethandler(SIGSEGV, sigsegv, 0);
55 
56 	if (!xsave_enabled()) {
57 		printf("[SKIP] CR4.OSXSAVE disabled.\n");
58 		return 0;
59 	}
60 
61 	CPU_ZERO(&set);
62 	CPU_SET(0, &set);
63 
64 	/*
65 	 * Enforce that the child runs on the same CPU
66 	 * which in turn forces a schedule.
67 	 */
68 	sched_setaffinity(getpid(), sizeof(set), &set);
69 
70 	printf("[RUN]\tSend ourselves a signal\n");
71 	raise(SIGUSR1);
72 
73 	printf("[OK]\tBack from the signal.  Now schedule.\n");
74 	pid_t child = fork();
75 	if (child < 0)
76 		err(1, "fork");
77 	if (child == 0)
78 		return 0;
79 	if (child)
80 		waitpid(child, NULL, 0);
81 	printf("[OK]\tBack in the main thread.\n");
82 
83 	/*
84 	 * We could try to confirm that extended state is still preserved
85 	 * when we schedule.  For now, the only indication of failure is
86 	 * a warning in the kernel logs.
87 	 */
88 
89 	return 0;
90 }
91