xref: /xnu-12377.1.9/tests/vm/corpse_owned_vmobjects.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 2024 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #include <signal.h>
30 #include <spawn.h>
31 #include <stdlib.h>
32 #include <sys/sysctl.h>
33 #include <sys/ptrace.h>
34 #include <sys/types.h>
35 #include <mach/mach.h>
36 #include <excserver.h>
37 #include <sys/mman.h>
38 #include <kern/exc_resource.h>
39 #include <TargetConditionals.h>
40 #include <mach/vm_page_size.h>
41 #include <sys/spawn_internal.h>
42 #include <mach/mach_vm.h>
43 
44 #include <darwintest.h>
45 #include <dispatch/dispatch.h>
46 #include <mach-o/dyld.h>
47 
48 /* internal */
49 #include <spawn_private.h>
50 #include <sys/kern_memorystatus.h>
51 
52 #define TEST_MEMLIMIT_MB 10
53 #define SEM_TIMEOUT dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC)
54 #define OWNED_VMOBJECTS_SYSCTL "vm.get_owned_vmobjects"
55 
56 T_GLOBAL_META(
57 	T_META_NAMESPACE("xnu.memorystatus"),
58 	T_META_RADAR_COMPONENT_NAME("xnu"),
59 	T_META_OWNER("aaron_j_sonin"),
60 	T_META_RADAR_COMPONENT_VERSION("VM"));
61 
62 /* Globals */
63 static dispatch_semaphore_t sync_sema;
64 static pid_t child_pid;
65 static bool caught_crash = false, caught_corpse = false;
66 mach_port_t exception_port;
67 
68 /* Exception  */
69 kern_return_t
catch_mach_exception_raise_state(mach_port_t exception_port,exception_type_t exception,const mach_exception_data_t code,mach_msg_type_number_t code_count,int * flavor,const thread_state_t old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count)70 catch_mach_exception_raise_state(mach_port_t exception_port,
71     exception_type_t exception,
72     const mach_exception_data_t code,
73     mach_msg_type_number_t code_count,
74     int * flavor,
75     const thread_state_t old_state,
76     mach_msg_type_number_t old_state_count,
77     thread_state_t new_state,
78     mach_msg_type_number_t * new_state_count)
79 {
80 #pragma unused(exception_port, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
81 	T_FAIL("Unsupported catch_mach_exception_raise_state");
82 	return KERN_NOT_SUPPORTED;
83 }
84 
85 kern_return_t
catch_mach_exception_raise_state_identity(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t code_count,int * flavor,thread_state_t old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count)86 catch_mach_exception_raise_state_identity(mach_port_t exception_port,
87     mach_port_t thread,
88     mach_port_t task,
89     exception_type_t exception,
90     mach_exception_data_t code,
91     mach_msg_type_number_t code_count,
92     int * flavor,
93     thread_state_t old_state,
94     mach_msg_type_number_t old_state_count,
95     thread_state_t new_state,
96     mach_msg_type_number_t * new_state_count)
97 {
98 #pragma unused(exception_port, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
99 	T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
100 	return KERN_NOT_SUPPORTED;
101 }
102 
103 kern_return_t
catch_mach_exception_raise_state_identity_protected(mach_port_t exception_port,uint64_t thread_id,mach_port_t task_id_token,exception_type_t exception,mach_exception_data_t codes,mach_msg_type_number_t codeCnt,int * flavor,thread_state_t old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count)104 catch_mach_exception_raise_state_identity_protected(
105 	mach_port_t exception_port,
106 	uint64_t thread_id,
107 	mach_port_t task_id_token,
108 	exception_type_t exception,
109 	mach_exception_data_t codes,
110 	mach_msg_type_number_t codeCnt,
111 	int * flavor,
112 	thread_state_t old_state,
113 	mach_msg_type_number_t old_state_count,
114 	thread_state_t new_state,
115 	mach_msg_type_number_t * new_state_count)
116 {
117 #pragma unused(exception_port, thread_id, task_id_token, exception, codes, codeCnt, flavor, old_state, old_state_count, new_state, new_state_count)
118 	T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
119 	return KERN_NOT_SUPPORTED;
120 }
121 
122 kern_return_t
catch_mach_exception_raise_identity_protected(mach_port_t exception_port,uint64_t thread_id,mach_port_t task_id_token,exception_type_t exception,mach_exception_data_t codes,mach_msg_type_number_t codeCnt)123 catch_mach_exception_raise_identity_protected(
124 	mach_port_t               exception_port,
125 	uint64_t                  thread_id,
126 	mach_port_t               task_id_token,
127 	exception_type_t          exception,
128 	mach_exception_data_t     codes,
129 	mach_msg_type_number_t    codeCnt)
130 {
131 #pragma unused(exception_port, thread_id, task_id_token, exception, codes, codeCnt)
132 	T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
133 	return KERN_NOT_SUPPORTED;
134 }
135 
136 void
verify_owned_vmobjects(task_t task)137 verify_owned_vmobjects(task_t task)
138 {
139 	int ret;
140 	size_t owned_vmobjects_len;
141 
142 	ret = sysctlbyname(OWNED_VMOBJECTS_SYSCTL, NULL, &owned_vmobjects_len, &task, sizeof(task));
143 	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl " OWNED_VMOBJECTS_SYSCTL);
144 	T_EXPECT_GT((int) owned_vmobjects_len, 0, "owned vmobjects list is populated on %s", (task == mach_task_self()) ? "self" : "corpse");
145 }
146 
147 kern_return_t
catch_mach_exception_raise(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t code_count)148 catch_mach_exception_raise(mach_port_t exception_port,
149     mach_port_t thread,
150     mach_port_t task,
151     exception_type_t exception,
152     mach_exception_data_t code,
153     mach_msg_type_number_t code_count)
154 {
155 #pragma unused(thread, task, code, code_count)
156 	T_QUIET; T_EXPECT_TRUE((exception == EXC_CRASH) || (exception == EXC_CORPSE_NOTIFY), "catch_mach_exception_raise() catches EXC_CRASH or EXC_CORPSE_NOTIFY");
157 	if (exception == EXC_CRASH) {
158 		caught_crash = true;
159 		return KERN_SUCCESS;
160 	} else if (exception == EXC_CORPSE_NOTIFY) {
161 		caught_corpse = true;
162 		verify_owned_vmobjects(task);
163 		dispatch_semaphore_signal(sync_sema);
164 		return KERN_SUCCESS;
165 	}
166 	return KERN_NOT_SUPPORTED;
167 }
168 
169 /*
170  * Background process that will allocate enough memory to push
171  * itself over the threshold, hopefully triggering EXC_RESOURCE.
172  */
173 T_HELPER_DECL(i_eat_memory_for_breakfast, "") {
174 	int ret, j, num_pages = 0;
175 	unsigned char *buf;
176 
177 	if (argc == 1) {
178 		num_pages = atoi(argv[0]);
179 	} else {
180 		T_FAIL("No arguments passed to memory eater");
181 	}
182 
183 	/* Allocate a purgeable buffer that will show up in owned vmobjects */
184 	mach_vm_address_t addr = 0;
185 	ret = mach_vm_allocate(mach_task_self(), &addr, vm_page_size, VM_FLAGS_ANYWHERE | VM_FLAGS_PURGABLE);
186 	T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "allocate purgeable buffer");
187 	T_QUIET; T_ASSERT_NE((int) addr, 0, "purgeable buffer not null");
188 	verify_owned_vmobjects(mach_task_self());
189 
190 	/* Allocate and touch all our pages */
191 	T_LOG("Allocating %d pages...", num_pages);
192 	buf = mmap(NULL, vm_page_size * num_pages, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
193 	T_QUIET; T_ASSERT_POSIX_SUCCESS(buf, "mmap");
194 	for (j = 0; j < num_pages; j++) {
195 		((volatile unsigned char *)buf)[j * vm_page_size] = 1;
196 	}
197 
198 	exit(0);
199 }
200 
201 static void
kill_child(void)202 kill_child(void)
203 {
204 	int ret = kill(child_pid, SIGKILL);
205 	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kill");
206 }
207 
208 static pid_t
launch_child(int num_pages)209 launch_child(int num_pages)
210 {
211 	extern char **environ;
212 	int ret;
213 	char testpath[PATH_MAX];
214 	posix_spawnattr_t spawn_attrs;
215 
216 	uint32_t testpath_buf_size = PATH_MAX;
217 	char num_pages_str[32] = {0};
218 	char *argv[5] = {testpath, "-n", "i_eat_memory_for_breakfast", num_pages_str, NULL};
219 
220 	T_LOG("Spawning child process...");
221 
222 	/* Fork so we can keep the exception port. */
223 	if ((child_pid = fork()) == 0) {
224 		ret = posix_spawnattr_init(&spawn_attrs);
225 		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "posix_spawnattr_init");
226 		ret = posix_spawnattr_setjetsam_ext(&spawn_attrs, POSIX_SPAWN_JETSAM_MEMLIMIT_FATAL, JETSAM_PRIORITY_FOREGROUND, TEST_MEMLIMIT_MB, TEST_MEMLIMIT_MB);
227 		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "posix_spawnattr_setjetsam_ext");
228 		ret = posix_spawnattr_setflags(&spawn_attrs, POSIX_SPAWN_SETEXEC);
229 		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "posix_spawnattr_setflags");
230 		ret = snprintf(num_pages_str, sizeof(num_pages_str), "%d", num_pages);
231 		T_QUIET; T_ASSERT_LE((size_t) ret, sizeof(num_pages_str), "Don't allocate too many pages.");
232 		ret = _NSGetExecutablePath(testpath, &testpath_buf_size);
233 		T_QUIET; T_ASSERT_EQ(ret, 0, "_NSGetExecutablePath");
234 		ret = posix_spawn(&child_pid, argv[0], NULL, &spawn_attrs, argv, environ);
235 		T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawn");
236 	}
237 
238 	T_ATEND(kill_child);
239 
240 	return child_pid;
241 }
242 
243 void*
exc_thread(void * arg)244 exc_thread(void *arg)
245 {
246 #pragma unused(arg)
247 	kern_return_t kr;
248 
249 	while (1) {
250 		kr = mach_msg_server(mach_exc_server, MACH_MSG_SIZE_RELIABLE, exception_port, 0);
251 		T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_msg_server");
252 	}
253 }
254 
255 T_DECL(corpse_owned_vmobjects, "vm.get_owned_vmobjects sysctl on corpses",
256     T_META_ASROOT(true),
257     T_META_BOOTARGS_SET("memstat_no_task_limit_increase=1"),
258     T_META_TAG_VM_PREFERRED
259     )
260 {
261 	int ret;
262 	pthread_t handle_thread;
263 	task_t task;
264 
265 	T_SETUPBEGIN;
266 
267 	sync_sema = dispatch_semaphore_create(0);
268 
269 	task = mach_task_self();
270 	T_QUIET; T_ASSERT_NE(task, MACH_PORT_NULL, "mach_task_self");
271 
272 	/* Allocate a port for receiving EXC_CRASH and EXC_CORPSE_NOTIFY */
273 	ret = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &exception_port);
274 	T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "mach_port_allocate");
275 	ret = mach_port_insert_right(task, exception_port, exception_port, MACH_MSG_TYPE_MAKE_SEND);
276 	T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "mach_port_insert_right");
277 	ret = task_set_exception_ports(task, EXC_MASK_CRASH | EXC_MASK_CORPSE_NOTIFY, exception_port, EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, 0);
278 	T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "task_set_exception_ports");
279 
280 	T_SETUPEND;
281 
282 	/* Spawn exception handling thread */
283 	ret = pthread_create(&handle_thread, NULL, exc_thread, 0);
284 
285 	/* Spawn child to eat memory and trigger EXC_RESOURCE */
286 	launch_child((TEST_MEMLIMIT_MB * (1 << 20)) / vm_page_size);
287 
288 	/* We should receive an exception */
289 	dispatch_semaphore_wait(sync_sema, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC));
290 	T_QUIET; T_EXPECT_EQ(caught_crash, true, "Caught EXC_CRASH");
291 	T_QUIET; T_EXPECT_EQ(caught_corpse, true, "Caught EXC_CORPSE_NOTIFY");
292 }
293