xref: /xnu-10002.61.3/tests/vm/test_vm_no_pager.m (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
1#include <errno.h>
2#include <fcntl.h>
3#include <kern/kcdata.h>
4#include <mach/kern_return.h>
5#include <signal.h>
6#include <stdbool.h>
7#include <stdarg.h>
8#include <stdint.h>
9#include <stdlib.h>
10#include <string.h>
11#include <stdio.h>
12#include <unistd.h>
13
14#include <sys/fsctl.h>
15#include <sys/stat.h>
16#include <sys/mman.h>
17#include <sys/sysctl.h>
18
19#include <mach/mach.h>
20#include <excserver.h>
21#include <dispatch/dispatch.h>
22#import <Foundation/Foundation.h>
23#import <System/corpses/task_corpse.h>
24#include <kdd.h>
25#include <kern/kern_cdata.h>
26#include <sys/reason.h>
27
28#include <darwintest.h>
29#include <darwintest_utils.h>
30
31T_GLOBAL_META(
32	T_META_OWNER("y_feigelson"),
33	T_META_NAMESPACE("xnu.vm"),
34	T_META_RADAR_COMPONENT_NAME("xnu"),
35	T_META_RADAR_COMPONENT_VERSION("VM"));
36
37static int verbose = 0;
38
39// KDBG_TRIAGE_VM_OBJECT_NO_PAGER_FORCED_UNMOUNT
40#define FORCED_UNMOUNT_ERROR "Object has no pager because the backing vnode was force unmounted"
41// KDBG_TRIAGE_VM_OBJECT_NO_PAGER_UNGRAFT
42#define UNGRAFTED_ERROR "Object has no pager because the backing vnode was ungrafted"
43
44static dispatch_semaphore_t sync_sema;
45static char* current_expected_triage_string;
46
47/* Use darwintests' launch and waitpid */
48static int
49my_system(const char *command, const char *arg)
50{
51	pid_t pid;
52	int ret;
53	const char *argv[] = {
54		command,
55		arg,
56		verbose ? "-v" : "",
57		NULL
58	};
59
60	dt_launch_tool(&pid, (char **)(void *)argv, FALSE, NULL, NULL);
61	// Status and signal will be empty since we took over exception handling
62	dt_waitpid(pid, NULL, NULL, 100);
63
64	return 0;
65}
66
67static int
68system_corpse_limit_reached(void)
69{
70	size_t output_size;
71	int total_corpse_count;
72	int ret;
73
74	output_size = sizeof(total_corpse_count);
75
76	ret = sysctlbyname("kern.total_corpses_count", &total_corpse_count, &output_size, NULL, 0);
77	if (ret != 0) {
78		T_LOG("sysctlbyname kern.total_corpses_count returned error: %d", ret);
79		return TRUE;
80	}
81
82	T_LOG("System corpse count is %d", total_corpse_count);
83
84	/* Abort the test if total_corpse_count is greater than equal to 4 */
85	// TODOyfeig check this out
86	if (total_corpse_count >= 4) {
87		return TRUE;
88	}
89
90	return FALSE;
91}
92
93/* Iterate corpse kcdata and verify `current_expected_triage_string` is found */
94void
95verify_corpse_data(mach_port_t task, mach_vm_address_t corpse_addr, size_t corpse_size)
96{
97	void * result                   = NULL;
98	mach_vm_address_t start_address;
99	mach_vm_address_t end_address;;
100	uint8_t * local_start;
101	uint64_t local_len;
102	kern_return_t r;
103
104	uint32_t t                          = 0;
105	uint32_t s                          = 0;
106	uint64_t f                          = 0;
107	uint64_t crashed_thread_id_reported = 0;
108	void * d                            = NULL;
109	int i                               = 0;
110	kern_return_t kret                  = KERN_SUCCESS;
111	task_crashinfo_item_t corpse_data   = NULL;
112
113	T_LOG("Verifiyng corpse data");
114	start_address = trunc_page((size_t)corpse_addr);
115	end_address  = round_page(corpse_addr + corpse_size);
116	r = task_map_corpse_info_64(mach_task_self(), task, (mach_vm_address_t *)&local_start, &local_len);
117	corpse_addr = (mach_vm_address_t)local_start;
118	start_address = (mach_vm_address_t)local_start;
119	corpse_size = local_len;
120	if (r == KERN_SUCCESS) {
121		corpse_data = malloc(corpse_size);
122		if (corpse_data) {
123			void * src = &local_start[(mach_vm_address_t)corpse_addr - start_address];
124			memcpy(corpse_data, src, corpse_size);
125		} else {
126			T_FAIL("Failed to malloc for corpse data");
127			return;
128		}
129		vm_deallocate(mach_task_self(), (uintptr_t)local_start, local_len);
130	}
131
132	kcdata_iter_t iter = kcdata_iter(corpse_data, corpse_size);
133	KCDataType * kcd_type = NULL;
134
135	KCDATA_ITER_FOREACH(iter)
136	{
137		i++;
138		t        = kcdata_iter_type(iter);
139		s        = kcdata_iter_size(iter);
140		f        = kcdata_iter_flags(iter);
141		d        = kcdata_iter_payload(iter);
142		kcd_type = getKCDataTypeForID(t);
143
144		if (t == TASK_CRASHINFO_KERNEL_TRIAGE_INFO_V1) {
145			struct kernel_triage_info_v1 kt = *(struct kernel_triage_info_v1 *) d;
146
147			for (char* str_iter = &kt; str_iter < (char*)&kt + sizeof(struct kernel_triage_info_v1); str_iter += MAX_TRIAGE_STRING_LEN) {
148				if (strlen(str_iter) && strstr(str_iter, current_expected_triage_string)) {
149					free(corpse_data);
150					T_PASS("Found expected crash triage string in corpse kcdata:\n`%s`", kt.triage_string1);
151					return;
152				}
153			}
154		}
155	}
156
157	free(corpse_data);
158	if (KCDATA_ITER_FOREACH_FAILED(iter)) {
159		T_FAIL("kcdata iteration failed");
160	}
161
162	T_FAIL("Didn't find expected crash string.\nExpected: `%s`", current_expected_triage_string);
163}
164
165/* Mach exception handler routines */
166kern_return_t
167catch_mach_exception_raise(mach_port_t exception_port,
168                           mach_port_t thread,
169                           mach_port_t task,
170                           exception_type_t exception,
171                           mach_exception_data_t code,
172                           mach_msg_type_number_t codeCnt)
173{
174	if (exception == EXC_CORPSE_NOTIFY) {
175		T_LOG("successfully caught EXC_CORPSE_NOTIFY %d code[0] = 0x%016llx at 0x%016llx", exception, code[0], code[1]);
176		verify_corpse_data(task, (mach_vm_address_t)code[0], (size_t)code[1]);
177		dispatch_semaphore_signal(sync_sema);
178		return KERN_SUCCESS;
179	}
180
181	T_LOG("caught %d %s(%d) at 0x%016llx returning KERN_FAILURE", exception, mach_error_string((int)code[0]), (int)code[0],
182	       code[1]);
183	return KERN_FAILURE;
184}
185
186kern_return_t
187catch_mach_exception_raise_state(mach_port_t exception_port,
188                                 exception_type_t exception,
189                                 const mach_exception_data_t code,
190                                 mach_msg_type_number_t codeCnt,
191                                 int * flavor,
192                                 const thread_state_t old_state,
193                                 mach_msg_type_number_t old_stateCnt,
194                                 thread_state_t new_state,
195                                 mach_msg_type_number_t * new_stateCnt)
196{
197	return KERN_NOT_SUPPORTED;
198}
199
200kern_return_t
201catch_mach_exception_raise_state_identity(mach_port_t exception_port,
202                                          mach_port_t thread,
203                                          mach_port_t task,
204                                          exception_type_t exception,
205                                          mach_exception_data_t code,
206                                          mach_msg_type_number_t codeCnt,
207                                          int * flavor,
208                                          thread_state_t old_state,
209                                          mach_msg_type_number_t old_stateCnt,
210                                          thread_state_t new_state,
211                                          mach_msg_type_number_t * new_stateCnt)
212{
213	return KERN_NOT_SUPPORTED;
214}
215
216kern_return_t
217catch_mach_exception_raise_identity_protected(
218	__unused mach_port_t      exception_port,
219	uint64_t                  thread_id,
220	mach_port_t               task_id_token,
221	exception_type_t          exception,
222	mach_exception_data_t     code,
223	mach_msg_type_number_t    codeCnt)
224{
225	return KERN_NOT_SUPPORTED;
226}
227
228
229/*
230 * Setup exception handling port for EXC_CORPSE_NOTIFY.
231 * Runs mach_msg_server once for receiving exception messages from kernel
232 */
233static void *
234setup_mach_server(void * arg __unused)
235{
236	kern_return_t kret;
237	mach_port_t exception_port;
238
239	kret = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &exception_port);
240	T_EXPECT_MACH_SUCCESS(kret, "mach_port_allocate: %s (%d)", mach_error_string(kret), kret);
241
242	kret = mach_port_insert_right(mach_task_self(), exception_port, exception_port, MACH_MSG_TYPE_MAKE_SEND);
243	T_EXPECT_MACH_SUCCESS(kret, "mach_port_insert_right: %s (%d)", mach_error_string(kret), kret);
244
245	kret = task_set_exception_ports(mach_task_self(), EXC_MASK_CORPSE_NOTIFY, exception_port,
246	                                EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, 0);
247	T_EXPECT_MACH_SUCCESS(kret, "task_set_exception_ports: %s (%d)", mach_error_string(kret), kret);
248
249	dispatch_semaphore_signal(sync_sema);
250
251	kret = mach_msg_server(mach_exc_server, MACH_MSG_SIZE_RELIABLE, exception_port, 0);
252	T_EXPECT_MACH_SUCCESS(kret, "mach_msg_server: %s (%d)", mach_error_string(kret), kret);
253
254	return NULL;
255}
256
257static void
258parse_args(int argc, char** argv)
259{
260	char c;
261	opterr = 0;
262    optind = 0;
263
264    while ((c = getopt(argc, argv, "v")) != -1) {
265        switch (c) {
266        case 'v':
267            verbose = 1;
268            break;
269        }
270    }
271}
272
273/* Perform necessary setup prior to running crash program */
274static void
275setup_for_crash()
276{
277	T_SETUPBEGIN;
278
279	int ret;
280	pthread_t handle_thread;
281
282	ret = system_corpse_limit_reached();
283	if (ret) {
284		T_SKIP("Too many processes already crashing, can't test corpses. Aborting test.");
285		return;
286	}
287
288	sync_sema = dispatch_semaphore_create(0);
289
290	ret = pthread_create(&handle_thread, NULL, setup_mach_server, NULL);
291	T_QUIET; T_EXPECT_EQ(ret, 0, "pthread_create failed");
292
293	T_SETUPEND;
294}
295
296/* Run the helper with the chosen test number */
297static void
298run_test(const char* test_num, int argc, char** argv)
299{
300	parse_args(argc, argv); // TODOyfeig is there really no global setup in darwintests?
301	setup_for_crash();
302
303	dispatch_semaphore_wait(sync_sema, DISPATCH_TIME_FOREVER); // Wait for exception handler setup
304	my_system("./test_vm_no_pager_helper", test_num);
305	dispatch_semaphore_wait(sync_sema, DISPATCH_TIME_FOREVER); // Wait for corpse kcdata processing
306}
307
308
309/* Test Declarations  */
310T_DECL(vm_no_pager_force_unmount, "test correct detection and propagation of reason for not having a pager (forced unmount)",
311	T_META_IGNORECRASHES(".*test_vm_no_pager.*"),
312	T_META_ASROOT(true))
313{
314	current_expected_triage_string = FORCED_UNMOUNT_ERROR;
315	run_test("1", argc, argv);
316}
317
318T_DECL(vm_no_pager_ungraft, "test correct detection and propagation of reason for not having a pager (ungraft)",
319    T_META_IGNORECRASHES(".*test_vm_no_pager.*"),
320    T_META_ASROOT(true))
321{
322	current_expected_triage_string = UNGRAFTED_ERROR;
323	run_test("2", argc, argv);
324}
325