1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * syscall_nt.c - checks syscalls with NT set
4  * Copyright (c) 2014-2015 Andrew Lutomirski
5  *
6  * Some obscure user-space code requires the ability to make system calls
7  * with FLAGS.NT set.  Make sure it works.
8  */
9 
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <err.h>
15 #include <sys/syscall.h>
16 
17 #include "helpers.h"
18 
19 static unsigned int nerrs;
20 
21 static void sethandler(int sig, void (*handler)(int, siginfo_t *, void *),
22 		       int flags)
23 {
24 	struct sigaction sa;
25 	memset(&sa, 0, sizeof(sa));
26 	sa.sa_sigaction = handler;
27 	sa.sa_flags = SA_SIGINFO | flags;
28 	sigemptyset(&sa.sa_mask);
29 	if (sigaction(sig, &sa, 0))
30 		err(1, "sigaction");
31 }
32 
33 static void sigtrap(int sig, siginfo_t *si, void *ctx_void)
34 {
35 }
36 
37 static void do_it(unsigned long extraflags)
38 {
39 	unsigned long flags;
40 
41 	set_eflags(get_eflags() | extraflags);
42 	syscall(SYS_getpid);
43 	flags = get_eflags();
44 	set_eflags(X86_EFLAGS_IF | X86_EFLAGS_FIXED);
45 	if ((flags & extraflags) == extraflags) {
46 		printf("[OK]\tThe syscall worked and flags are still set\n");
47 	} else {
48 		printf("[FAIL]\tThe syscall worked but flags were cleared (flags = 0x%lx but expected 0x%lx set)\n",
49 		       flags, extraflags);
50 		nerrs++;
51 	}
52 }
53 
54 int main(void)
55 {
56 	printf("[RUN]\tSet NT and issue a syscall\n");
57 	do_it(X86_EFLAGS_NT);
58 
59 	printf("[RUN]\tSet AC and issue a syscall\n");
60 	do_it(X86_EFLAGS_AC);
61 
62 	printf("[RUN]\tSet NT|AC and issue a syscall\n");
63 	do_it(X86_EFLAGS_NT | X86_EFLAGS_AC);
64 
65 	/*
66 	 * Now try it again with TF set -- TF forces returns via IRET in all
67 	 * cases except non-ptregs-using 64-bit full fast path syscalls.
68 	 */
69 
70 	sethandler(SIGTRAP, sigtrap, 0);
71 
72 	printf("[RUN]\tSet TF and issue a syscall\n");
73 	do_it(X86_EFLAGS_TF);
74 
75 	printf("[RUN]\tSet NT|TF and issue a syscall\n");
76 	do_it(X86_EFLAGS_NT | X86_EFLAGS_TF);
77 
78 	printf("[RUN]\tSet AC|TF and issue a syscall\n");
79 	do_it(X86_EFLAGS_AC | X86_EFLAGS_TF);
80 
81 	printf("[RUN]\tSet NT|AC|TF and issue a syscall\n");
82 	do_it(X86_EFLAGS_NT | X86_EFLAGS_AC | X86_EFLAGS_TF);
83 
84 	/*
85 	 * Now try DF.  This is evil and it's plausible that we will crash
86 	 * glibc, but glibc would have to do something rather surprising
87 	 * for this to happen.
88 	 */
89 	printf("[RUN]\tSet DF and issue a syscall\n");
90 	do_it(X86_EFLAGS_DF);
91 
92 	printf("[RUN]\tSet TF|DF and issue a syscall\n");
93 	do_it(X86_EFLAGS_TF | X86_EFLAGS_DF);
94 
95 	return nerrs == 0 ? 0 : 1;
96 }
97