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 <stdlib.h>
30 #include <unistd.h>
31 #include <stdbool.h>
32 #include <pthread.h>
33 #include <darwintest.h>
34 #include <kern/exc_guard.h>
35 #include <mach/task_info.h>
36
37 #include "exc_helpers.h"
38 #include "exc_guard_helper.h"
39 #include "test_utils.h"
40
41 /* Convenience macro for compile-time array size */
42 #define countof(array) \
43 _Pragma("clang diagnostic push") \
44 _Pragma("clang diagnostic error \"-Wsizeof-pointer-div\"") \
45 (sizeof(array)/sizeof((array)[0])) \
46 _Pragma("clang diagnostic pop")
47
48 /*
49 * Global data shared between the code running the block and the exception handler.
50 * Ideally this would be thread-local data in the thread running the block,
51 * but the exception handler runs on a different thread and can't see it.
52 */
53 static pthread_mutex_t exc_guard_helper_mutex = PTHREAD_MUTEX_INITIALIZER;
54 static mach_port_t exc_guard_helper_exc_port = MACH_PORT_NULL;
55
56 static pthread_mutex_t exc_guard_helper_request_mutex = PTHREAD_MUTEX_INITIALIZER;
57 static exc_guard_helper_info_t exc_guard_helper_reply;
58 static struct {
59 mach_port_t thread;
60 unsigned int guard_type;
61 } exc_guard_helper_request;
62
63 static const char *
name_for_guard_type(unsigned guard_type)64 name_for_guard_type(unsigned guard_type)
65 {
66 static const char *names[] = {
67 [GUARD_TYPE_NONE] = "GUARD_TYPE_NONE",
68 [GUARD_TYPE_MACH_PORT] = "GUARD_TYPE_MACH_PORT",
69 [GUARD_TYPE_FD] = "GUARD_TYPE_FD",
70 [GUARD_TYPE_USER] = "GUARD_TYPE_USER",
71 [GUARD_TYPE_VN] = "GUARD_TYPE_VN",
72 [GUARD_TYPE_VIRT_MEMORY] = "GUARD_TYPE_VIRT_MEMORY",
73 [GUARD_TYPE_REJECTED_SC] = "GUARD_TYPE_REJECTED_SC",
74 };
75 const char *result = NULL;
76 if (guard_type < countof(names)) {
77 result = names[guard_type];
78 }
79 if (result == NULL) {
80 result = "unknown";
81 }
82 return result;
83 }
84
85 static size_t
exc_guard_helper_exception_handler(__unused mach_port_t task,mach_port_t thread,exception_type_t exception,mach_exception_data_t codes,__unused uint64_t exception_pc)86 exc_guard_helper_exception_handler(
87 __unused mach_port_t task,
88 mach_port_t thread,
89 exception_type_t exception,
90 mach_exception_data_t codes,
91 __unused uint64_t exception_pc)
92 {
93 T_QUIET; T_ASSERT_EQ(exception, EXC_GUARD, "exception type");
94 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_lock(&exc_guard_helper_request_mutex), "lock");
95
96 if (thread != exc_guard_helper_request.thread) {
97 /* reject, nobody is waiting for exceptions */
98 if (verbose_exc_helper) {
99 T_LOG("exc_guard_helper caught an exception but nobody is waiting for it");
100 }
101 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "unlock");
102 return 0;
103 }
104
105 unsigned int exc_guard_type = EXC_GUARD_DECODE_GUARD_TYPE(codes[0]);
106 uint32_t exc_guard_flavor = EXC_GUARD_DECODE_GUARD_FLAVOR(codes[0]);
107 uint32_t exc_guard_target = EXC_GUARD_DECODE_GUARD_TARGET(codes[0]);
108 uint64_t exc_guard_payload = codes[1];
109
110 if (exc_guard_helper_request.guard_type == exc_guard_type) {
111 /* okay, exception matches caller's requested guard type */
112 } else {
113 /* reject, exception's guard type is not of the requested type */
114 if (verbose_exc_helper) {
115 T_LOG("exc_guard_helper exception is not of the "
116 "desired guard type (expected %u, got %u)",
117 exc_guard_helper_request.guard_type, exc_guard_type);
118 }
119 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "unlock");
120 return 0;
121 }
122
123 if (++exc_guard_helper_reply.catch_count == 1) {
124 /* save the details of the first caught exception */
125 exc_guard_helper_reply.guard_type = exc_guard_type;
126 exc_guard_helper_reply.guard_flavor = exc_guard_flavor;
127 exc_guard_helper_reply.guard_target = exc_guard_target;
128 exc_guard_helper_reply.guard_payload = exc_guard_payload;
129 }
130
131 if (verbose_exc_helper) {
132 T_LOG("exc_guard_helper caught EXC_GUARD type %u (%s), flavor %u, "
133 "target %u, payload 0x%llx (catch #%u in the block)",
134 exc_guard_type, name_for_guard_type(exc_guard_type),
135 exc_guard_flavor, exc_guard_target, exc_guard_payload,
136 exc_guard_helper_reply.catch_count);
137 }
138
139 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "unlock");
140 return 0;
141 }
142
143 /*
144 * Set up our exception handlers if they are not already configured.
145 * exc_guard_helper_mutex must be held by the caller.
146 */
147 static void
initialize_exception_handlers(void)148 initialize_exception_handlers(void)
149 {
150 if (exc_guard_helper_exc_port == MACH_PORT_NULL) {
151 exc_guard_helper_exc_port = create_exception_port(EXC_MASK_GUARD);
152 T_QUIET; T_ASSERT_NE(exc_guard_helper_exc_port, MACH_PORT_NULL, "exception port");
153 repeat_exception_handler(exc_guard_helper_exc_port, exc_guard_helper_exception_handler);
154 if (verbose_exc_helper) {
155 T_LOG("exc_guard_helper exception handlers installed");
156 }
157 }
158 }
159
160 void
exc_guard_helper_init(void)161 exc_guard_helper_init(void)
162 {
163 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_lock(&exc_guard_helper_mutex), "lock");
164 initialize_exception_handlers();
165 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_mutex), "unlock");
166 }
167
168
169 /*
170 * Return EXC_GUARD behavior flags that enable guard_type (non-fatal)
171 * and leave all other behaviors in old_behavior unchanged.
172 */
173 static task_exc_guard_behavior_t
configure_exc_guard_of_type(unsigned int guard_type,task_exc_guard_behavior_t old_behavior)174 configure_exc_guard_of_type(
175 unsigned int guard_type,
176 task_exc_guard_behavior_t old_behavior)
177 {
178 /*
179 * Behavior flags for all known EXC_GUARD types.
180 * These flags are defined in mach/task_info.h.
181 * Some guard types cannot be configured and do not have these flags.
182 */
183 static const struct {
184 task_exc_guard_behavior_t set;
185 task_exc_guard_behavior_t clear;
186 } behavior_flags[] = {
187 [GUARD_TYPE_VIRT_MEMORY] = {
188 .clear = TASK_EXC_GUARD_VM_ALL,
189 .set = TASK_EXC_GUARD_VM_DELIVER,
190 },
191 [GUARD_TYPE_MACH_PORT] = {
192 .clear = TASK_EXC_GUARD_MP_ALL,
193 .set = TASK_EXC_GUARD_MP_DELIVER,
194 },
195 };
196
197 /* Reject guard types not present in behavior_flags[]. */
198 if (guard_type >= countof(behavior_flags)) {
199 goto unimplemented_guard_type;
200 }
201 if (behavior_flags[guard_type].set == 0 &&
202 behavior_flags[guard_type].clear == 0) {
203 goto unimplemented_guard_type;
204 }
205
206 /* Set and clear behavior flags for the requested guard type(s). */
207 task_exc_guard_behavior_t new_behavior = old_behavior;
208 new_behavior &= ~behavior_flags[guard_type].clear;
209 new_behavior |= behavior_flags[guard_type].set;
210 return new_behavior;
211
212 unimplemented_guard_type:
213 /*
214 * No behavior_flags[] entry for this EXC_GUARD guard type.
215 * If task_set_exc_guard_behavior() can configure your new
216 * guard type then add it to behavior_flags[] above.
217 */
218 T_FAIL("guard type %u (%s) is unimplemented in exc_guard_helper",
219 guard_type, name_for_guard_type(guard_type));
220 T_END;
221 }
222
223 task_exc_guard_behavior_t
enable_exc_guard_of_type(unsigned int guard_type)224 enable_exc_guard_of_type(unsigned int guard_type)
225 {
226 kern_return_t kr;
227 task_exc_guard_behavior_t old_behavior, new_behavior;
228
229 kr = task_get_exc_guard_behavior(mach_task_self(), &old_behavior);
230 T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "exc_guard_helper calling task_get_exc_guard_behavior");
231
232 new_behavior = configure_exc_guard_of_type(guard_type, old_behavior);
233
234 kr = task_set_exc_guard_behavior(mach_task_self(), new_behavior);
235 T_QUIET; T_ASSERT_MACH_SUCCESS(kr,
236 "exc_guard_helper calling task_set_exc_guard_behavior to enable guard type %u %s",
237 guard_type, name_for_guard_type(guard_type));
238
239 return old_behavior;
240 }
241
242 bool
block_raised_exc_guard_of_type(unsigned int guard_type,exc_guard_helper_info_t * const out_exc_info,exc_guard_helper_block_t block)243 block_raised_exc_guard_of_type(
244 unsigned int guard_type,
245 exc_guard_helper_info_t * const out_exc_info,
246 exc_guard_helper_block_t block)
247 {
248 if (process_is_translated() && guard_type == GUARD_TYPE_VIRT_MEMORY) {
249 T_FAIL("block_raised_exc_guard_of_type(GUARD_TYPE_VIRT_MEMORY) "
250 "does not work on translation/Rosetta (rdar://142438840)");
251 }
252
253 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_lock(&exc_guard_helper_mutex), "lock");
254 initialize_exception_handlers();
255
256 /* lock the request and reply structs against the exception handler */
257 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_lock(&exc_guard_helper_request_mutex), "lock");
258
259 /* prepare the global request and reply struct contents */
260 memset(&exc_guard_helper_request, 0, sizeof(exc_guard_helper_request));
261 memset(&exc_guard_helper_reply, 0, sizeof(exc_guard_helper_reply));
262 exc_guard_helper_request.thread = mach_thread_self();
263 exc_guard_helper_request.guard_type = guard_type;
264
265 /* unlock the request and reply structs so the exception handler can use them */
266 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "unlock");
267
268 /* run the caller's block */
269 if (verbose_exc_helper) {
270 T_LOG("exc_guard_helper calling a block");
271 }
272 block();
273 if (verbose_exc_helper) {
274 T_LOG("exc_guard_helper finished a block, %u exception%s caught",
275 exc_guard_helper_reply.catch_count,
276 exc_guard_helper_reply.catch_count == 1 ? "" : "s");
277 }
278
279 /* lock the request and reply structs again */
280 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "lock");
281
282 /* read the reply from the exception handler */
283 bool result = exc_guard_helper_reply.catch_count > 0;
284 memcpy(out_exc_info, &exc_guard_helper_reply, sizeof(exc_guard_helper_reply));
285
286 /* clear the request and reply before unlocking everything */
287 memset(&exc_guard_helper_request, 0, sizeof(exc_guard_helper_request));
288 memset(&exc_guard_helper_reply, 0, sizeof(exc_guard_helper_reply));
289 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_request_mutex), "unlock");
290
291 T_QUIET; T_ASSERT_POSIX_ZERO(pthread_mutex_unlock(&exc_guard_helper_mutex), "unlock");
292
293 return result;
294 }
295
296 bool
block_raised_exc_guard_of_type_ignoring_translated(unsigned int guard_type,exc_guard_helper_info_t * const out_exc_info,exc_guard_helper_block_t block)297 block_raised_exc_guard_of_type_ignoring_translated(
298 unsigned int guard_type,
299 exc_guard_helper_info_t * const out_exc_info,
300 exc_guard_helper_block_t block)
301 {
302 if (process_is_translated() && guard_type == GUARD_TYPE_VIRT_MEMORY) {
303 /* Rosetta can't recover from guard exceptions of GUARD_TYPE_VIRT_MEMORY */
304 T_LOG("note: exc_guard_helper calling a block with no exception "
305 "handler due to translation/Rosetta (rdar://142438840)");
306 block();
307 memset(out_exc_info, 0, sizeof(*out_exc_info));
308 return false;
309 }
310
311 return block_raised_exc_guard_of_type(guard_type, out_exc_info, block);
312 }
313