xref: /xnu-11215/tests/text_corruption.c (revision aca3beaa)
1 #include <unistd.h>
2 #include <stdio.h>
3 
4 #include <darwintest.h>
5 #include <darwintest_utils.h>
6 
7 T_GLOBAL_META(
8 /*
9  * We're going to corrupt shared library text, so don't
10  * run with other tests.
11  */
12 	T_META_RUN_CONCURRENTLY(false),
13 	T_META_REQUIRES_SYSCTL_NE("kern.page_protection_type", 2)
14 	);
15 
16 /*
17  * No system(3c) on watchOS, so provide our own.
18  * returns -1 if fails to run
19  * returns 0 if process exits normally.
20  * returns +n if process exits due to signal N
21  */
22 static int
my_system(const char * command)23 my_system(const char *command)
24 {
25 	pid_t pid;
26 	int status = 0;
27 	int signal = 0;
28 	int err;
29 	const char *argv[] = {
30 		"/bin/sh",
31 		"-c",
32 		command,
33 		NULL
34 	};
35 
36 	if (dt_launch_tool(&pid, (char **)(void *)argv, FALSE, NULL, NULL)) {
37 		return -1;
38 	}
39 
40 	err = dt_waitpid(pid, &status, &signal, 30);
41 	if (err) {
42 		return 0;
43 	}
44 
45 	return signal;
46 }
47 
48 
49 /*
50  * The tests are run in the following order:
51  *
52  * - call foo
53  * - corrupt foo, then call foo
54  * - call foo
55  *
56  * - call atan
57  * - corrupt atan, then call atan
58  * - call atan
59  *
60  * The first and last of each should exit normally. The middle one should exit with SIGILL.
61  *
62  * atan() was picked as a shared region function that isn't likely used by any normal daemons.
63  */
64 T_DECL(text_corruption_recovery, "test detection/recovery of text corruption",
65     T_META_IGNORECRASHES(".*text_corruption_helper.*"),
66     T_META_ASROOT(true))
67 {
68 	int ret;
69 
70 	ret = my_system("./text_corruption_helper foo");
71 	T_QUIET; T_ASSERT_EQ(ret, 0, "First call of foo");
72 
73 	ret = my_system("./text_corruption_helper Xfoo");
74 	T_QUIET; T_ASSERT_EQ(ret, SIGILL, "Call of corrupted foo");
75 
76 	ret = my_system("./text_corruption_helper foo");
77 	T_QUIET; T_ASSERT_EQ(ret, 0, "Fixed call of foo");
78 
79 	ret = my_system("./text_corruption_helper atan");
80 	T_QUIET; T_ASSERT_EQ(ret, 0, "First call of atan");
81 
82 	ret = my_system("./text_corruption_helper Xatan");
83 	T_QUIET; T_ASSERT_EQ(ret, SIGILL, "Call of corrupted atan");
84 
85 	ret = my_system("./text_corruption_helper atan");
86 	T_QUIET; T_ASSERT_EQ(ret, 0, "Fixed call of atan");
87 }
88