1 // SPDX-License-Identifier: GPL-2.0
3 * ioperm.c - Test case for ioperm(2)
4 * Copyright (c) 2015 Andrew Lutomirski
17 #include <sys/types.h>
25 static void sethandler(int sig
, void (*handler
)(int, siginfo_t
*, void *),
29 memset(&sa
, 0, sizeof(sa
));
30 sa
.sa_sigaction
= handler
;
31 sa
.sa_flags
= SA_SIGINFO
| flags
;
32 sigemptyset(&sa
.sa_mask
);
33 if (sigaction(sig
, &sa
, 0))
38 static void clearhandler(int sig
)
41 memset(&sa
, 0, sizeof(sa
));
42 sa
.sa_handler
= SIG_DFL
;
43 sigemptyset(&sa
.sa_mask
);
44 if (sigaction(sig
, &sa
, 0))
48 static jmp_buf jmpbuf
;
50 static void sigsegv(int sig
, siginfo_t
*si
, void *ctx_void
)
52 siglongjmp(jmpbuf
, 1);
55 static bool try_outb(unsigned short port
)
57 sethandler(SIGSEGV
, sigsegv
, SA_RESETHAND
);
58 if (sigsetjmp(jmpbuf
, 1) != 0) {
61 asm volatile ("outb %%al, %w[port]"
62 : : [port
] "Nd" (port
), "a" (0));
65 clearhandler(SIGSEGV
);
68 static void expect_ok(unsigned short port
)
70 if (!try_outb(port
)) {
71 printf("[FAIL]\toutb to 0x%02hx failed\n", port
);
75 printf("[OK]\toutb to 0x%02hx worked\n", port
);
78 static void expect_gp(unsigned short port
)
81 printf("[FAIL]\toutb to 0x%02hx worked\n", port
);
85 printf("[OK]\toutb to 0x%02hx failed\n", port
);
93 if (sched_setaffinity(0, sizeof(cpuset
), &cpuset
) != 0)
94 err(1, "sched_setaffinity to CPU 0");
100 * Probe for ioperm support. Note that clearing ioperm bits
101 * works even as nonroot.
103 printf("[RUN]\tenable 0x80\n");
104 if (ioperm(0x80, 1, 1) != 0) {
105 printf("[OK]\tioperm(0x80, 1, 1) failed (%d) -- try running as root\n",
112 printf("[RUN]\tdisable 0x80\n");
113 if (ioperm(0x80, 1, 0) != 0) {
114 printf("[FAIL]\tioperm(0x80, 1, 0) failed (%d)", errno
);
120 /* Make sure that fork() preserves ioperm. */
121 if (ioperm(0x80, 1, 1) != 0) {
122 printf("[FAIL]\tioperm(0x80, 1, 0) failed (%d)", errno
);
126 pid_t child
= fork();
131 printf("[RUN]\tchild: check that we inherited permissions\n");
137 if (waitpid(child
, &status
, 0) != child
||
138 !WIFEXITED(status
)) {
139 printf("[FAIL]\tChild died\n");
141 } else if (WEXITSTATUS(status
) != 0) {
142 printf("[FAIL]\tChild failed\n");
145 printf("[OK]\tChild succeeded\n");
149 /* Test the capability checks. */
151 printf("\tDrop privileges\n");
152 if (setresuid(1, 1, 1) != 0) {
153 printf("[WARN]\tDropping privileges failed\n");
157 printf("[RUN]\tdisable 0x80\n");
158 if (ioperm(0x80, 1, 0) != 0) {
159 printf("[FAIL]\tioperm(0x80, 1, 0) failed (%d)", errno
);
162 printf("[OK]\tit worked\n");
164 printf("[RUN]\tenable 0x80 again\n");
165 if (ioperm(0x80, 1, 1) == 0) {
166 printf("[FAIL]\tit succeeded but should have failed.\n");
169 printf("[OK]\tit failed\n");