xref: /xnu-12377.81.4/osfmk/ipc/ipc_kmsg.c (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 2000-2020 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  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  * NOTICE: This file was modified by McAfee Research in 2004 to introduce
58  * support for mandatory and extensible security protections.  This notice
59  * is included in support of clause 2.2 (b) of the Apple Public License,
60  * Version 2.0.
61  * Copyright (c) 2005 SPARTA, Inc.
62  */
63 /*
64  */
65 /*
66  *	File:	ipc/ipc_kmsg.c
67  *	Author:	Rich Draves
68  *	Date:	1989
69  *
70  *	Operations on kernel messages.
71  */
72 
73 #include <mach/mach_types.h>
74 #include <mach/boolean.h>
75 #include <mach/kern_return.h>
76 #include <mach/message.h>
77 #include <mach/port.h>
78 #include <mach/vm_map.h>
79 #include <mach/mach_vm.h>
80 #include <mach/vm_statistics.h>
81 
82 #include <kern/kern_types.h>
83 #include <kern/assert.h>
84 #include <kern/debug.h>
85 #include <kern/ipc_kobject.h>
86 #include <kern/kalloc.h>
87 #include <kern/zalloc.h>
88 #include <kern/processor.h>
89 #include <kern/thread.h>
90 #include <kern/thread_group.h>
91 #include <kern/sched_prim.h>
92 #include <kern/misc_protos.h>
93 #include <kern/cpu_data.h>
94 #include <kern/policy_internal.h>
95 #include <kern/mach_filter.h>
96 
97 #include <pthread/priority_private.h>
98 
99 #include <machine/limits.h>
100 
101 #include <vm/vm_map_xnu.h>
102 #include <vm/vm_object_xnu.h>
103 #include <vm/vm_kern_xnu.h>
104 #include <vm/vm_protos.h>
105 
106 #include <ipc/port.h>
107 #include <ipc/ipc_types.h>
108 #include <ipc/ipc_entry.h>
109 #include <ipc/ipc_kmsg.h>
110 #include <ipc/ipc_notify.h>
111 #include <ipc/ipc_object.h>
112 #include <ipc/ipc_space.h>
113 #include <ipc/ipc_policy.h>
114 #include <ipc/ipc_port.h>
115 #include <ipc/ipc_right.h>
116 #include <ipc/ipc_hash.h>
117 #include <ipc/ipc_importance.h>
118 #include <ipc/ipc_service_port.h>
119 
120 #include <os/overflow.h>
121 
122 #include <security/mac_mach_internal.h>
123 
124 #include <device/device_server.h>
125 
126 #include <string.h>
127 
128 #include <sys/kdebug.h>
129 
130 #include <ptrauth.h>
131 #if __has_feature(ptrauth_calls)
132 #include <libkern/ptrauth_utils.h>
133 #endif
134 
135 
136 /*
137  * In kernel, complex mach msg have a simpler representation than userspace:
138  *
139  * <header>
140  * <desc-count>
141  * <descriptors> * desc-count
142  * <body>
143  *
144  * And the descriptors are of type `mach_msg_kdescriptor_t`,
145  * that is large enough to accommodate for any possible representation.
146  *
147  * The `type` field of any descriptor is always at the same offset,
148  * and the smallest possible descriptor is of size USER_DESC_SIZE_MIN.
149  *
150  * Note:
151  * - KERN_DESC_SIZE is 16 on all kernels
152  * - USER_DESC_SIZE_MIN is 12 on all kernels
153  */
154 
155 #define KERNEL_DESC_SIZE        sizeof(mach_msg_kdescriptor_t)
156 #define USER_DESC_SIZE_MIN      sizeof(mach_msg_type_descriptor_t)
157 #define USER_DESC_SIZE_MAX      KERNEL_DESC_SIZE
158 #define USER_DESC_MAX_DELTA     (KERNEL_DESC_SIZE - USER_DESC_SIZE_MIN)
159 #define USER_HEADER_SIZE_DELTA  (sizeof(mach_msg_header_t) - sizeof(mach_msg_user_header_t))
160 
161 
162 #define mach_validate_desc_type(t, size) \
163 	static_assert(sizeof(t) == (size))
164 
165 mach_validate_desc_type(mach_msg_descriptor_t, KERNEL_DESC_SIZE);
166 mach_validate_desc_type(mach_msg_kdescriptor_t, KERNEL_DESC_SIZE);
167 mach_validate_desc_type(mach_msg_port_descriptor_t, KERNEL_DESC_SIZE);
168 mach_validate_desc_type(mach_msg_ool_descriptor_t, KERNEL_DESC_SIZE);
169 mach_validate_desc_type(mach_msg_ool_ports_descriptor_t, KERNEL_DESC_SIZE);
170 mach_validate_desc_type(mach_msg_guarded_port_descriptor_t, KERNEL_DESC_SIZE);
171 
172 extern vm_map_t         ipc_kernel_copy_map;
173 extern const vm_size_t  msg_ool_size_small;
174 
175 /* zone for cached ipc_kmsg_t structures */
176 ZONE_DEFINE_ID(ZONE_ID_IPC_KMSG, "ipc kmsgs", struct ipc_kmsg,
177     ZC_CACHING | ZC_ZFREE_CLEARMEM);
178 #define ikm_require(kmsg) \
179 	zone_id_require(ZONE_ID_IPC_KMSG, sizeof(struct ipc_kmsg), kmsg)
180 #define ikm_require_aligned(kmsg) \
181 	zone_id_require_aligned(ZONE_ID_IPC_KMSG, kmsg)
182 
183 KALLOC_TYPE_VAR_DEFINE(KT_IPC_KMSG_KDATA_OOL,
184     mach_msg_base_t, mach_msg_kdescriptor_t, KT_DEFAULT);
185 
186 
187 #pragma mark ipc_kmsg layout and accessors
188 
189 /* Whether header, body, content and trailer occupy contiguous memory space */
190 static inline bool
ikm_is_linear(ipc_kmsg_t kmsg)191 ikm_is_linear(ipc_kmsg_t kmsg)
192 {
193 	return kmsg->ikm_type == IKM_TYPE_ALL_INLINED ||
194 	       kmsg->ikm_type == IKM_TYPE_KDATA_OOL;
195 }
196 
197 /* Size of kmsg header (plus body and descriptors for complex messages) */
198 __attribute__((always_inline, overloadable))
199 static mach_msg_size_t
ikm_kdata_size(mach_msg_size_t dsc_count,bool complex)200 ikm_kdata_size(
201 	mach_msg_size_t dsc_count,
202 	bool            complex)
203 {
204 	if (complex) {
205 		return sizeof(mach_msg_kbase_t) + dsc_count * KERNEL_DESC_SIZE;
206 	} else {
207 		return sizeof(mach_msg_header_t);
208 	}
209 }
210 
211 __attribute__((always_inline, overloadable))
212 static mach_msg_size_t
ikm_kdata_size(mach_msg_header_t * hdr)213 ikm_kdata_size(
214 	mach_msg_header_t *hdr)
215 {
216 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
217 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
218 
219 		return ikm_kdata_size(kbase->msgb_dsc_count, true);
220 	}
221 	return ikm_kdata_size(0, false);
222 }
223 
224 /*
225  * Returns start address of user data for kmsg.
226  *
227  * Caller is responsible for checking the size of udata buffer before attempting
228  * to write to the address returned.
229  *
230  * Condition:
231  *   1. kmsg descriptors must have been validated and expanded, or is a message
232  *      originated from kernel.
233  *   2. ikm_header() content may or may not be populated
234  */
235 void *
ikm_udata(ipc_kmsg_t kmsg,mach_msg_size_t dsc_count,bool complex)236 ikm_udata(
237 	ipc_kmsg_t      kmsg,
238 	mach_msg_size_t dsc_count,
239 	bool            complex)
240 {
241 	if (ikm_is_linear(kmsg)) {
242 		mach_msg_header_t *hdr = ikm_header(kmsg);
243 
244 		return (char *)hdr + ikm_kdata_size(dsc_count, complex);
245 	}
246 	return kmsg->ikm_udata;
247 }
248 
249 /*
250  * Returns start address of user data for kmsg, given a populated kmsg.
251  *
252  * Caller is responsible for checking the size of udata buffer before attempting
253  * to write to the address returned.
254  *
255  * Condition:
256  *   kmsg must have a populated header.
257  */
258 void *
ikm_udata_from_header(ipc_kmsg_t kmsg)259 ikm_udata_from_header(ipc_kmsg_t kmsg)
260 {
261 	if (ikm_is_linear(kmsg)) {
262 		mach_msg_header_t *hdr = ikm_header(kmsg);
263 
264 		return (char *)hdr + ikm_kdata_size(hdr);
265 	}
266 	return kmsg->ikm_udata;
267 }
268 
269 #if (DEVELOPMENT || DEBUG)
270 /* Returns end of kdata buffer (may contain extra space) */
271 vm_offset_t
ikm_kdata_end(ipc_kmsg_t kmsg)272 ikm_kdata_end(ipc_kmsg_t kmsg)
273 {
274 	switch (kmsg->ikm_type) {
275 	case IKM_TYPE_ALL_INLINED:
276 		return (vm_offset_t)kmsg->ikm_big_data + IKM_BIG_MSG_SIZE;
277 	case IKM_TYPE_UDATA_OOL:
278 		return (vm_offset_t)kmsg->ikm_small_data + IKM_SMALL_MSG_SIZE;
279 	default:
280 		return (vm_offset_t)kmsg->ikm_kdata + kmsg->ikm_kdata_size;
281 	}
282 }
283 #endif
284 
285 /*
286  * Returns message header address.
287  */
288 inline mach_msg_header_t *
ikm_header(ipc_kmsg_t kmsg)289 ikm_header(
290 	ipc_kmsg_t         kmsg)
291 {
292 	switch (kmsg->ikm_type) {
293 	case IKM_TYPE_ALL_INLINED:
294 		return (mach_msg_header_t *)kmsg->ikm_big_data;
295 	case IKM_TYPE_UDATA_OOL:
296 		return (mach_msg_header_t *)kmsg->ikm_small_data;
297 	default:
298 		return (mach_msg_header_t *)kmsg->ikm_kdata;
299 	}
300 }
301 
302 static inline mach_msg_aux_header_t *
ikm_aux_header(ipc_kmsg_t kmsg)303 ikm_aux_header(
304 	ipc_kmsg_t         kmsg)
305 {
306 	if (!kmsg->ikm_aux_size) {
307 		return NULL;
308 	}
309 
310 	assert(kmsg->ikm_aux_size >= sizeof(mach_msg_aux_header_t));
311 
312 	if (kmsg->ikm_type == IKM_TYPE_ALL_INLINED) {
313 		return (mach_msg_aux_header_t *)((vm_offset_t)(kmsg + 1) -
314 		       kmsg->ikm_aux_size);
315 	} else {
316 		assert(kmsg->ikm_type != IKM_TYPE_KDATA_OOL);
317 		return (mach_msg_aux_header_t *)((vm_offset_t)kmsg->ikm_udata +
318 		       kmsg->ikm_udata_size - kmsg->ikm_aux_size);
319 	}
320 }
321 
322 /*!
323  * @brief
324  * Returns the size of a user descriptor for a given type
325  */
326 static inline mach_msg_size_t
ikm_user_desc_size(mach_msg_descriptor_type_t type,bool is_task_64bit)327 ikm_user_desc_size(mach_msg_descriptor_type_t type, bool is_task_64bit)
328 {
329 	/*
330 	 * User descriptors come in two sizes:
331 	 * - USER_DESC_SIZE_MIN (12)
332 	 * - USER_DESC_SIZE_MAX (16)
333 	 *
334 	 * Ideally this function would be implemented as a "switch",
335 	 * unfortunately this produces terrible codegen, so we instead write
336 	 * the optimal code by hand with tons of static asserts.
337 	 *
338 	 * As of now there are only two cases:
339 	 * - port descriptors are always 12 bytes
340 	 * - other descriptors are 12 bytes on 32bits, and 16 on 64bits.
341 	 *
342 	 * If one of the static asserts break because you are adding a new
343 	 * descriptor type, make sure to update this function properly.
344 	 */
345 	static_assert(MACH_MSG_DESCRIPTOR_MAX == MACH_MSG_GUARDED_PORT_DESCRIPTOR);
346 
347 	if (type == MACH_MSG_PORT_DESCRIPTOR) {
348 		mach_validate_desc_type(mach_msg_user_port_descriptor_t, USER_DESC_SIZE_MIN);
349 		return USER_DESC_SIZE_MIN;
350 	}
351 	if (is_task_64bit) {
352 		mach_validate_desc_type(mach_msg_ool_descriptor64_t, USER_DESC_SIZE_MAX);
353 		mach_validate_desc_type(mach_msg_ool_ports_descriptor64_t, USER_DESC_SIZE_MAX);
354 		mach_validate_desc_type(mach_msg_guarded_port_descriptor64_t, USER_DESC_SIZE_MAX);
355 		return USER_DESC_SIZE_MAX;
356 	} else {
357 		mach_validate_desc_type(mach_msg_ool_descriptor32_t, USER_DESC_SIZE_MIN);
358 		mach_validate_desc_type(mach_msg_ool_ports_descriptor32_t, USER_DESC_SIZE_MIN);
359 		mach_validate_desc_type(mach_msg_guarded_port_descriptor32_t, USER_DESC_SIZE_MIN);
360 		return USER_DESC_SIZE_MIN;
361 	}
362 }
363 
364 __abortlike
365 static void
__ipc_kmsg_descriptor_invalid_type_panic(const mach_msg_kdescriptor_t * kdesc)366 __ipc_kmsg_descriptor_invalid_type_panic(
367 	const mach_msg_kdescriptor_t *kdesc)
368 {
369 	panic("Invalid descriptor type (%p: %d)",
370 	    kdesc, mach_msg_kdescriptor_type(kdesc));
371 }
372 
373 mach_msg_trailer_size_t
ipc_kmsg_trailer_size(mach_msg_option64_t option,vm_map_t map __unused)374 ipc_kmsg_trailer_size(mach_msg_option64_t option, vm_map_t map __unused)
375 {
376 	return REQUESTED_TRAILER_SIZE(map->max_offset > VM_MAX_ADDRESS, option);
377 }
378 
379 
380 /*
381  * Get the trailer address of kmsg.
382  */
383 mach_msg_max_trailer_t *
ipc_kmsg_get_trailer(ipc_kmsg_t kmsg)384 ipc_kmsg_get_trailer(
385 	ipc_kmsg_t              kmsg)
386 {
387 	mach_msg_header_t *hdr = ikm_header(kmsg);
388 	mach_msg_size_t    trailer_pos = hdr->msgh_size;
389 	vm_offset_t        base;
390 
391 	if (ikm_is_linear(kmsg)) {
392 		base = (vm_offset_t)hdr;
393 	} else {
394 		base = (vm_offset_t)kmsg->ikm_udata;
395 		trailer_pos -= ikm_kdata_size(hdr);
396 	}
397 
398 	return (mach_msg_max_trailer_t *)(base + trailer_pos);
399 }
400 
401 void
ipc_kmsg_set_voucher_port(ipc_kmsg_t kmsg,ipc_port_t voucher_port,mach_msg_type_name_t type)402 ipc_kmsg_set_voucher_port(
403 	ipc_kmsg_t           kmsg,
404 	ipc_port_t           voucher_port,
405 	mach_msg_type_name_t type)
406 {
407 	if (IP_VALID(voucher_port)) {
408 		assert(ip_type(voucher_port) == IKOT_VOUCHER);
409 	}
410 	kmsg->ikm_voucher_port = voucher_port;
411 	kmsg->ikm_voucher_type = type;
412 }
413 
414 ipc_port_t
ipc_kmsg_get_voucher_port(ipc_kmsg_t kmsg)415 ipc_kmsg_get_voucher_port(ipc_kmsg_t kmsg)
416 {
417 	return kmsg->ikm_voucher_port;
418 }
419 
420 void
ipc_kmsg_clear_voucher_port(ipc_kmsg_t kmsg)421 ipc_kmsg_clear_voucher_port(ipc_kmsg_t kmsg)
422 {
423 	kmsg->ikm_voucher_port = IP_NULL;
424 	kmsg->ikm_voucher_type = MACH_MSGH_BITS_ZERO;
425 }
426 
427 /*
428  * Caller has a reference to the kmsg and the mqueue lock held.
429  *
430  * As such, we can safely return a pointer to the thread group in the kmsg and
431  * not an additional reference. It is up to the caller to decide to take an
432  * additional reference on the thread group while still holding the mqueue lock,
433  * if needed.
434  */
435 #if CONFIG_PREADOPT_TG
436 struct thread_group *
ipc_kmsg_get_thread_group(ipc_kmsg_t kmsg)437 ipc_kmsg_get_thread_group(ipc_kmsg_t kmsg)
438 {
439 	struct thread_group *tg = NULL;
440 	kern_return_t __assert_only kr;
441 
442 	ipc_voucher_t voucher = convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg));
443 	kr = bank_get_preadopt_thread_group(voucher, &tg);
444 	ipc_voucher_release(voucher);
445 
446 	return tg;
447 }
448 #endif
449 
450 #pragma mark ipc_kmsg signing
451 
452 __abortlike
453 static void
__ikm_signature_check_panic(ipc_kmsg_t kmsg,uint32_t sig)454 __ikm_signature_check_panic(ipc_kmsg_t kmsg, uint32_t sig)
455 {
456 	mach_msg_header_t *hdr = ikm_header(kmsg);
457 
458 	panic("IPC kmsg header signature mismatch: "
459 	    "kmsg=%p, hdr=%p, id=%d, sig=0x%08x (expected 0x%08x)",
460 	    kmsg, hdr, hdr->msgh_id, sig, kmsg->ikm_signature);
461 }
462 
463 static uint32_t
__ipc_kmsg_sign(ipc_kmsg_t kmsg,mach_msg_max_trailer_t * trailer,mach_msg_size_t * dsc_count)464 __ipc_kmsg_sign(
465 	ipc_kmsg_t              kmsg,
466 	mach_msg_max_trailer_t *trailer,
467 	mach_msg_size_t        *dsc_count)
468 {
469 	uint32_t           signature = 0;
470 	mach_msg_header_t *hdr  = ikm_header(kmsg);
471 	mach_msg_base_t    base;
472 
473 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
474 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
475 
476 		/*
477 		 * the "atomic" load will also be volatile which prevents the
478 		 * compiler from re-fetching that value after optimization.
479 		 */
480 		base.header = kbase->msgb_header;
481 		base.body.msgh_descriptor_count =
482 		    os_atomic_load(&kbase->msgb_dsc_count, relaxed);
483 	} else {
484 		base.header = *hdr;
485 		base.body.msgh_descriptor_count = 0;
486 	}
487 
488 	/* compute sig of a copy of the header with all varying bits masked off */
489 	base.header.msgh_bits &= MACH_MSGH_BITS_USER;
490 	base.header.msgh_bits &= ~MACH_MSGH_BITS_VOUCHER_MASK;
491 
492 #if __has_feature(ptrauth_calls)
493 	{
494 		uintptr_t data = (uintptr_t)kmsg;
495 
496 		data &= ~(0xffffLL << 48); /* clear upper 16 bits */
497 		data |= OS_PTRAUTH_DISCRIMINATOR("kmsg.ikm_signature") << 48;
498 
499 		data  = ptrauth_utils_sign_blob_generic(&base, sizeof(base), data, 0);
500 		data  = ptrauth_utils_sign_blob_generic(trailer,
501 		    MAX_TRAILER_SIZE, data, PTRAUTH_ADDR_DIVERSIFY);
502 		signature = (uint32_t)(data >> 32);
503 	}
504 #else
505 	(void)kmsg;
506 	(void)trailer;
507 #endif
508 
509 	if (dsc_count) {
510 		*dsc_count = base.body.msgh_descriptor_count;
511 	}
512 	return signature;
513 }
514 
515 static void
ipc_kmsg_sign(ipc_kmsg_t kmsg,mach_msg_max_trailer_t * trailer)516 ipc_kmsg_sign(ipc_kmsg_t kmsg, mach_msg_max_trailer_t *trailer)
517 {
518 	kmsg->ikm_signature = __ipc_kmsg_sign(kmsg, trailer, NULL);
519 }
520 
521 /*
522  *	Routine:	ipc_kmsg_init_trailer_and_sign
523  *	Purpose:
524  *		Initiailizes a trailer in a message safely,
525  *		and sign its header and trailer.
526  */
527 static void
ipc_kmsg_init_trailer_and_sign(ipc_kmsg_t kmsg,task_t sender)528 ipc_kmsg_init_trailer_and_sign(
529 	ipc_kmsg_t          kmsg,
530 	task_t              sender)
531 {
532 	static const mach_msg_max_trailer_t KERNEL_TRAILER_TEMPLATE = {
533 		.msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0,
534 		.msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE,
535 		.msgh_sender = KERNEL_SECURITY_TOKEN_VALUE,
536 		.msgh_audit = KERNEL_AUDIT_TOKEN_VALUE
537 	};
538 
539 	mach_msg_max_trailer_t *trailer = ipc_kmsg_get_trailer(kmsg);
540 
541 	if (sender == TASK_NULL) {
542 		memcpy(trailer, &KERNEL_TRAILER_TEMPLATE, sizeof(*trailer));
543 	} else {
544 		bzero(trailer, sizeof(*trailer));
545 		trailer->msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0;
546 		trailer->msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE;
547 		trailer->msgh_sender = *task_get_sec_token(sender);
548 		trailer->msgh_audit = *task_get_audit_token(sender);
549 	}
550 
551 	ipc_kmsg_sign(kmsg, trailer);
552 }
553 
554 /*
555  * Purpose:
556  *       Validate kmsg signature.
557  */
558 mach_msg_size_t
ipc_kmsg_validate_signature(ipc_kmsg_t kmsg)559 ipc_kmsg_validate_signature(
560 	ipc_kmsg_t kmsg)
561 {
562 	uint32_t         sig;
563 	mach_msg_size_t  dsc_count;
564 
565 	ikm_require_aligned(kmsg);
566 	sig = __ipc_kmsg_sign(kmsg, ipc_kmsg_get_trailer(kmsg), &dsc_count);
567 	if (sig != kmsg->ikm_signature) {
568 		__ikm_signature_check_panic(kmsg, sig);
569 	}
570 
571 	return dsc_count;
572 }
573 
574 void
ipc_kmsg_sign_descriptors(mach_msg_kdescriptor_t * kdesc,mach_msg_size_t dsc_count)575 ipc_kmsg_sign_descriptors(
576 	mach_msg_kdescriptor_t *kdesc,
577 	mach_msg_size_t         dsc_count)
578 {
579 #if __has_feature(ptrauth_calls)
580 	for (mach_msg_size_t i = 0; i < dsc_count; i++, kdesc++) {
581 		switch (mach_msg_kdescriptor_type(kdesc)) {
582 		case MACH_MSG_PORT_DESCRIPTOR:
583 			kdesc->kdesc_port.name =
584 			    kdesc->kdesc_port.kext_name;
585 			break;
586 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
587 		case MACH_MSG_OOL_DESCRIPTOR:
588 			kdesc->kdesc_memory.address =
589 			    kdesc->kdesc_memory.kext_address;
590 			break;
591 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
592 			mach_msg_ool_ports_descriptor_t *dsc = &kdesc->kdesc_port_array;
593 			ipc_port_t          *ports = dsc->kext_address;
594 			mach_port_array_t    array = dsc->kext_address;
595 
596 			for (mach_msg_size_t j = 0; j < dsc->count; j++) {
597 				array[j].port = ports[j];
598 			}
599 			dsc->address = array;
600 			break;
601 		}
602 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
603 			kdesc->kdesc_guarded_port.name =
604 			    kdesc->kdesc_guarded_port.kext_name;
605 			break;
606 		default:
607 			__ipc_kmsg_descriptor_invalid_type_panic(kdesc);
608 		}
609 	}
610 #else
611 #pragma unused(kdesc, dsc_count)
612 #endif /* __has_feature(ptrauth_calls) */
613 }
614 
615 static void
ipc_kmsg_relocate_descriptors(mach_msg_kdescriptor_t * dst_dsc,const mach_msg_kdescriptor_t * src_dsc,mach_msg_size_t dsc_count)616 ipc_kmsg_relocate_descriptors(
617 	mach_msg_kdescriptor_t *dst_dsc,
618 	const mach_msg_kdescriptor_t *src_dsc,
619 	mach_msg_size_t         dsc_count)
620 {
621 #if __has_feature(ptrauth_calls)
622 	for (mach_msg_size_t i = 0; i < dsc_count; i++, dst_dsc++, src_dsc++) {
623 		switch (mach_msg_kdescriptor_type(src_dsc)) {
624 		case MACH_MSG_PORT_DESCRIPTOR:
625 			dst_dsc->kdesc_port.name =
626 			    src_dsc->kdesc_port.name;
627 			break;
628 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
629 		case MACH_MSG_OOL_DESCRIPTOR:
630 			dst_dsc->kdesc_memory.address =
631 			    src_dsc->kdesc_memory.address;
632 			break;
633 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
634 			dst_dsc->kdesc_port_array.address =
635 			    src_dsc->kdesc_port_array.address;
636 			break;
637 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
638 			dst_dsc->kdesc_guarded_port.name =
639 			    src_dsc->kdesc_guarded_port.name;
640 			break;
641 		default:
642 			__ipc_kmsg_descriptor_invalid_type_panic(src_dsc);
643 		}
644 	}
645 #else
646 #pragma unused(dst_dsc, src_dsc, dsc_count)
647 #endif /* __has_feature(ptrauth_calls) */
648 }
649 
650 static void
ipc_kmsg_strip_descriptors(mach_msg_kdescriptor_t * dst_dsc,const mach_msg_kdescriptor_t * src_dsc,mach_msg_size_t dsc_count)651 ipc_kmsg_strip_descriptors(
652 	mach_msg_kdescriptor_t *dst_dsc,
653 	const mach_msg_kdescriptor_t *src_dsc,
654 	mach_msg_size_t         dsc_count)
655 {
656 #if __has_feature(ptrauth_calls)
657 	for (mach_msg_size_t i = 0; i < dsc_count; i++, dst_dsc++, src_dsc++) {
658 		switch (mach_msg_kdescriptor_type(src_dsc)) {
659 		case MACH_MSG_PORT_DESCRIPTOR:
660 			dst_dsc->kdesc_port.kext_name =
661 			    src_dsc->kdesc_port.name;
662 			break;
663 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
664 		case MACH_MSG_OOL_DESCRIPTOR:
665 			dst_dsc->kdesc_memory.kext_address =
666 			    src_dsc->kdesc_memory.address;
667 			break;
668 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
669 			mach_msg_ool_ports_descriptor_t *dsc = &dst_dsc->kdesc_port_array;
670 			ipc_port_t          *ports = dsc->address;
671 			mach_port_array_t    array = dsc->address;
672 
673 			for (mach_msg_size_t j = 0; j < dsc->count; j++) {
674 				ports[j] = array[j].port;
675 			}
676 			dsc->kext_address = array;
677 			break;
678 		}
679 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
680 			dst_dsc->kdesc_guarded_port.kext_name =
681 			    src_dsc->kdesc_guarded_port.name;
682 			break;
683 		default:
684 			__ipc_kmsg_descriptor_invalid_type_panic(src_dsc);
685 		}
686 	}
687 #else
688 #pragma unused(dst_dsc, src_dsc, dsc_count)
689 #endif /* __has_feature(ptrauth_calls) */
690 }
691 
692 
693 #pragma mark ipc_kmsg alloc/clean/free
694 
695 static inline void *
ikm_alloc_kdata_ool(size_t size,zalloc_flags_t flags)696 ikm_alloc_kdata_ool(size_t size, zalloc_flags_t flags)
697 {
698 	return kalloc_type_var_impl(KT_IPC_KMSG_KDATA_OOL,
699 	           size, flags, NULL);
700 }
701 
702 static inline void
ikm_free_kdata_ool(void * ptr,size_t size)703 ikm_free_kdata_ool(void *ptr, size_t size)
704 {
705 	kfree_type_var_impl(KT_IPC_KMSG_KDATA_OOL, ptr, size);
706 }
707 
708 /*
709  *	Routine:	ipc_kmsg_alloc
710  *	Purpose:
711  *		Allocate a kernel message structure.  If the
712  *		message is scalar and all the data resides inline, that is best.
713  *      Otherwise, allocate out of line buffers to fit the message and
714  *      the optional auxiliary data.
715  *
716  *	Conditions:
717  *		Nothing locked.
718  *
719  *      kmsg_size doesn't take the trailer or descriptor
720  *		inflation into account, but already accounts for the mach
721  *		message header expansion.
722  */
723 ipc_kmsg_t
ipc_kmsg_alloc(mach_msg_size_t kmsg_size,mach_msg_size_t aux_size,mach_msg_size_t desc_count,ipc_kmsg_alloc_flags_t flags)724 ipc_kmsg_alloc(
725 	mach_msg_size_t         kmsg_size,
726 	mach_msg_size_t         aux_size,
727 	mach_msg_size_t         desc_count,
728 	ipc_kmsg_alloc_flags_t  flags)
729 {
730 	mach_msg_size_t max_kmsg_size, max_delta, max_kdata_size,
731 	    max_udata_size, max_kmsg_and_aux_size;
732 	ipc_kmsg_t kmsg;
733 
734 	void *msg_kdata = NULL, *msg_udata = NULL;
735 	zalloc_flags_t alloc_flags = Z_WAITOK;
736 	ipc_kmsg_type_t kmsg_type;
737 
738 	/*
739 	 * In kernel descriptors, are of the same size (KERNEL_DESC_SIZE),
740 	 * but in userspace, depending on 64-bitness, descriptors might be
741 	 * smaller.
742 	 *
743 	 * When handling a userspace message however, we know how many
744 	 * descriptors have been declared, and we pad for the maximum expansion.
745 	 *
746 	 * During descriptor expansion, message header stays at the same place
747 	 * while everything after it gets shifted to higher address.
748 	 */
749 	if (flags & IPC_KMSG_ALLOC_KERNEL) {
750 		assert(aux_size == 0);
751 		max_delta = 0;
752 	} else if (os_mul_and_add_overflow(desc_count, USER_DESC_MAX_DELTA,
753 	    USER_HEADER_SIZE_DELTA, &max_delta)) {
754 		return IKM_NULL;
755 	}
756 
757 	if (os_add3_overflow(kmsg_size, MAX_TRAILER_SIZE, max_delta, &max_kmsg_size)) {
758 		return IKM_NULL;
759 	}
760 	if (os_add_overflow(max_kmsg_size, aux_size, &max_kmsg_and_aux_size)) {
761 		return IKM_NULL;
762 	}
763 
764 	/* First, determine the layout of the kmsg to allocate */
765 	if (max_kmsg_and_aux_size <= IKM_BIG_MSG_SIZE) {
766 		kmsg_type = IKM_TYPE_ALL_INLINED;
767 		max_udata_size = 0;
768 		max_kdata_size = 0;
769 	} else if (flags & IPC_KMSG_ALLOC_ALL_INLINE) {
770 		panic("size too large for the fast kmsg zone (%d)", kmsg_size);
771 	} else if (flags & IPC_KMSG_ALLOC_LINEAR) {
772 		/*
773 		 * Caller sets MACH64_SEND_KOBJECT_CALL or MACH64_SEND_ANY, or that
774 		 * the call originates from kernel, or it's a mach_msg() call.
775 		 * In any case, message does not carry aux data.
776 		 * We have validated mach_msg2() call options in mach_msg2_trap().
777 		 */
778 		if (aux_size != 0) {
779 			panic("non-zero aux size for kmsg type IKM_TYPE_KDATA_OOL.");
780 		}
781 		kmsg_type = IKM_TYPE_KDATA_OOL;
782 		max_udata_size = 0;
783 		max_kdata_size = max_kmsg_size;
784 	} else {
785 		mach_msg_size_t min_kdata_size;
786 
787 		/*
788 		 * If message can be splitted from the middle, IOW does not need to
789 		 * occupy contiguous memory space, sequester (header + descriptors)
790 		 * from (content + trailer + aux) for memory security.
791 		 */
792 		assert(max_kmsg_and_aux_size > IKM_BIG_MSG_SIZE);
793 
794 		/*
795 		 * max_kdata_size: Maximum combined size of header plus (optional) descriptors.
796 		 * This is _base_ size + descriptor count * kernel descriptor size.
797 		 */
798 		if (os_mul_and_add_overflow(desc_count, KERNEL_DESC_SIZE,
799 		    sizeof(mach_msg_base_t), &max_kdata_size)) {
800 			return IKM_NULL;
801 		}
802 
803 		/*
804 		 * min_kdata_size: Minimum combined size of header plus (optional) descriptors.
805 		 * This is _header_ size + descriptor count * minimal descriptor size.
806 		 */
807 		mach_msg_size_t min_size = (flags & IPC_KMSG_ALLOC_KERNEL) ?
808 		    KERNEL_DESC_SIZE : USER_DESC_SIZE_MIN;
809 		if (os_mul_and_add_overflow(desc_count, min_size,
810 		    sizeof(mach_msg_header_t), &min_kdata_size)) {
811 			return IKM_NULL;
812 		}
813 
814 		/*
815 		 * max_udata_size: Maximum combined size of message content, trailer and aux.
816 		 * This is total kmsg and aux size (already accounts for max trailer size) minus
817 		 * _minimum_ (header + descs) size.
818 		 */
819 		if (os_sub_overflow(max_kmsg_and_aux_size, min_kdata_size, &max_udata_size)) {
820 			return IKM_NULL;
821 		}
822 
823 		if (max_kdata_size <= IKM_SMALL_MSG_SIZE) {
824 			kmsg_type = IKM_TYPE_UDATA_OOL;
825 		} else {
826 			kmsg_type = IKM_TYPE_ALL_OOL;
827 		}
828 	}
829 
830 	if (flags & IPC_KMSG_ALLOC_ZERO) {
831 		alloc_flags |= Z_ZERO;
832 	}
833 	if (flags & IPC_KMSG_ALLOC_NOFAIL) {
834 		alloc_flags |= Z_NOFAIL;
835 	}
836 
837 	/* Then, allocate memory for both udata and kdata if needed, as well as kmsg */
838 	if (max_udata_size > 0) {
839 		msg_udata = kalloc_data(max_udata_size, alloc_flags);
840 		if (__improbable(msg_udata == NULL)) {
841 			return IKM_NULL;
842 		}
843 	}
844 
845 	if (kmsg_type == IKM_TYPE_ALL_OOL || kmsg_type == IKM_TYPE_KDATA_OOL) {
846 		if (kmsg_type == IKM_TYPE_ALL_OOL) {
847 			msg_kdata = kalloc_type(mach_msg_base_t, mach_msg_kdescriptor_t,
848 			    desc_count, alloc_flags | Z_SPRAYQTN);
849 		} else {
850 			msg_kdata = ikm_alloc_kdata_ool(max_kdata_size, alloc_flags);
851 		}
852 
853 		if (__improbable(msg_kdata == NULL)) {
854 			kfree_data(msg_udata, max_udata_size);
855 			return IKM_NULL;
856 		}
857 	}
858 
859 	static_assert(IPC_KMSG_MAX_AUX_DATA_SPACE <= UINT16_MAX,
860 	    "casting aux_size won't truncate");
861 
862 	kmsg = zalloc_id(ZONE_ID_IPC_KMSG, Z_WAITOK | Z_ZERO | Z_NOFAIL);
863 	kmsg->ikm_type = kmsg_type;
864 	kmsg->ikm_aux_size = (uint16_t)aux_size;
865 
866 	if (flags & IPC_KMSG_ALLOC_USE_KEEP_ALIVE) {
867 		assert(kmsg_type == IKM_TYPE_ALL_INLINED);
868 		kmsg->ikm_keep_alive = IKM_KEEP_ALIVE_OWNED;
869 	}
870 
871 	/* Finally, set up pointers properly */
872 	if (kmsg_type == IKM_TYPE_ALL_INLINED) {
873 		assert(msg_udata == NULL && msg_kdata == NULL);
874 	} else {
875 		if (kmsg_type == IKM_TYPE_UDATA_OOL) {
876 			kmsg->ikm_kdata = kmsg->ikm_small_data;
877 		} else {
878 			kmsg->ikm_kdata = msg_kdata;
879 		}
880 		kmsg->ikm_udata = msg_udata;
881 		kmsg->ikm_kdata_size = max_kdata_size;
882 		kmsg->ikm_udata_size = max_udata_size;
883 	}
884 
885 	return kmsg;
886 }
887 
888 /* re-export for IOKit's c++ */
889 extern ipc_kmsg_t ipc_kmsg_alloc_uext_reply(mach_msg_size_t);
890 
891 ipc_kmsg_t
ipc_kmsg_alloc_uext_reply(mach_msg_size_t size)892 ipc_kmsg_alloc_uext_reply(
893 	mach_msg_size_t         size)
894 {
895 	return ipc_kmsg_alloc(size, 0, 0, IPC_KMSG_ALLOC_KERNEL | IPC_KMSG_ALLOC_LINEAR |
896 	           IPC_KMSG_ALLOC_ZERO | IPC_KMSG_ALLOC_NOFAIL);
897 }
898 
899 /*
900  *	Routine:	ipc_kmsg_keep_alive_try_reusing()
901  *	Purpose:
902  *		Attempt to mark a preallocated message in-use.
903  *		Returns true on success, false on failure.
904  */
905 bool
ipc_kmsg_keep_alive_try_reusing(ipc_kmsg_t kmsg)906 ipc_kmsg_keep_alive_try_reusing(ipc_kmsg_t kmsg)
907 {
908 	uintptr_t v;
909 
910 	v = os_atomic_or_orig(&kmsg->ikm_keep_alive,
911 	    IKM_KEEP_ALIVE_IN_USE, relaxed);
912 
913 	/* if the message isn't owned, it can't use keep-alive */
914 	ipc_release_assert(v & IKM_KEEP_ALIVE_OWNED);
915 
916 	return (v & IKM_KEEP_ALIVE_IN_USE) == 0;
917 }
918 
919 /*
920  *	Routine:	ipc_kmsg_keep_alive_done_using
921  *	Purpose:
922  *		Marks an ipc kmsg as no longer in flight.
923  *		Returns true if the message is also no longer owned.
924  */
925 static bool
ipc_kmsg_keep_alive_done_using(ipc_kmsg_t kmsg)926 ipc_kmsg_keep_alive_done_using(ipc_kmsg_t kmsg)
927 {
928 	uintptr_t v = os_atomic_load(&kmsg->ikm_keep_alive, relaxed);
929 
930 	if (v == IKM_KEEP_ALIVE_NONE) {
931 		/* fastpath for most messages not using the facility */
932 		return true;
933 	}
934 
935 	v = os_atomic_andnot_orig(&kmsg->ikm_keep_alive,
936 	    IKM_KEEP_ALIVE_IN_USE, release);
937 
938 	/* if the message wasn't in-use, something is wrong */
939 	ipc_release_assert(v & IKM_KEEP_ALIVE_IN_USE);
940 
941 	if (v & IKM_KEEP_ALIVE_OWNED) {
942 		return false;
943 	}
944 	os_atomic_thread_fence(acquire);
945 	return true;
946 }
947 
948 /*
949  *	Routine:	ipc_kmsg_keep_alive_abandon()
950  *	Purpose:
951  *		Abandons a message that was marked as OWNED
952  *		as part of allocating it with IPC_KMSG_ALLOC_USE_KEEP_ALIVE.
953  */
954 void
ipc_kmsg_keep_alive_abandon(ipc_kmsg_t kmsg)955 ipc_kmsg_keep_alive_abandon(
956 	ipc_kmsg_t              kmsg)
957 {
958 	uintptr_t v;
959 
960 	v = os_atomic_andnot_orig(&kmsg->ikm_keep_alive,
961 	    IKM_KEEP_ALIVE_OWNED, release);
962 
963 	/* if the message wasn't owned, something is wrong */
964 	ipc_release_assert(v & IKM_KEEP_ALIVE_OWNED);
965 
966 	if ((v & IKM_KEEP_ALIVE_IN_USE) == 0) {
967 		os_atomic_thread_fence(acquire);
968 		ipc_kmsg_free(kmsg);
969 	}
970 }
971 
972 /*
973  *	Routine:	ipc_kmsg_free_allocations
974  *	Purpose:
975  *		Free external allocations of a kmsg.
976  *	Conditions:
977  *		Nothing locked.
978  */
979 static void
ipc_kmsg_free_allocations(ipc_kmsg_t kmsg)980 ipc_kmsg_free_allocations(
981 	ipc_kmsg_t              kmsg)
982 {
983 	mach_msg_size_t dsc_count = 0;
984 
985 	switch (kmsg->ikm_type) {
986 	case IKM_TYPE_ALL_INLINED:
987 		break;
988 	case IKM_TYPE_UDATA_OOL:
989 		kfree_data(kmsg->ikm_udata, kmsg->ikm_udata_size);
990 		/* kdata is inlined, udata freed */
991 		break;
992 	case IKM_TYPE_KDATA_OOL:
993 		ikm_free_kdata_ool(kmsg->ikm_kdata, kmsg->ikm_kdata_size);
994 		/* kdata freed, no udata */
995 		break;
996 	case IKM_TYPE_ALL_OOL:
997 		dsc_count = (kmsg->ikm_kdata_size - sizeof(mach_msg_base_t)) /
998 		    KERNEL_DESC_SIZE;
999 		kfree_type(mach_msg_base_t, mach_msg_kdescriptor_t, dsc_count,
1000 		    kmsg->ikm_kdata);
1001 		/* kdata freed */
1002 		kfree_data(kmsg->ikm_udata, kmsg->ikm_udata_size);
1003 		/* udata freed */
1004 		break;
1005 	default:
1006 		panic("strange kmsg type");
1007 	}
1008 	kmsg->ikm_type = IKM_TYPE_ALL_INLINED;
1009 
1010 	/* leave nothing dangling or causing out of bounds */
1011 	kmsg->ikm_udata = NULL;
1012 	kmsg->ikm_kdata = NULL;
1013 	kmsg->ikm_udata_size = 0;
1014 	kmsg->ikm_kdata_size = 0;
1015 	kmsg->ikm_aux_size = 0;
1016 }
1017 
1018 /*
1019  *	Routine:	ipc_kmsg_free
1020  *	Purpose:
1021  *		Free a kernel message (and udata) buffer.
1022  *	Conditions:
1023  *		Nothing locked.
1024  */
1025 void
ipc_kmsg_free(ipc_kmsg_t kmsg)1026 ipc_kmsg_free(
1027 	ipc_kmsg_t      kmsg)
1028 {
1029 	assert(!IP_VALID(ipc_kmsg_get_voucher_port(kmsg)));
1030 
1031 	KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_FREE) | DBG_FUNC_NONE,
1032 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
1033 	    0, 0, 0, 0);
1034 
1035 	/*
1036 	 * Check to see if an mk_timer asked for this message to stay
1037 	 * alive.
1038 	 */
1039 	if (kmsg->ikm_type == IKM_TYPE_ALL_INLINED &&
1040 	    !ipc_kmsg_keep_alive_done_using(kmsg)) {
1041 		return;
1042 	}
1043 
1044 	ipc_kmsg_free_allocations(kmsg);
1045 	zfree_id(ZONE_ID_IPC_KMSG, kmsg);
1046 	/* kmsg struct freed */
1047 }
1048 
1049 /*
1050  *	Routine:	ipc_kmsg_clean_header
1051  *	Purpose:
1052  *		Cleans the header of a kmsg.
1053  *	Conditions:
1054  *		Nothing locked.
1055  */
1056 static void
ipc_kmsg_clean_header(ipc_kmsg_t kmsg)1057 ipc_kmsg_clean_header(
1058 	ipc_kmsg_t              kmsg)
1059 {
1060 	ipc_port_t port;
1061 	mach_msg_header_t *hdr = ikm_header(kmsg);
1062 	mach_msg_bits_t mbits = hdr->msgh_bits;
1063 
1064 	/* deal with importance chain while we still have dest and voucher references */
1065 	ipc_importance_clean(kmsg);
1066 
1067 	port = hdr->msgh_remote_port;
1068 	if (IP_VALID(port)) {
1069 		ipc_object_destroy_dest(port, MACH_MSGH_BITS_REMOTE(mbits));
1070 	}
1071 
1072 	port = hdr->msgh_local_port;
1073 	if (IP_VALID(port)) {
1074 		ipc_object_destroy(port, MACH_MSGH_BITS_LOCAL(mbits));
1075 	}
1076 
1077 	port = ipc_kmsg_get_voucher_port(kmsg);
1078 	if (IP_VALID(port)) {
1079 		assert(MACH_MSGH_BITS_VOUCHER(mbits) == MACH_MSG_TYPE_MOVE_SEND);
1080 		ipc_object_destroy(port, MACH_MSG_TYPE_PORT_SEND);
1081 		ipc_kmsg_clear_voucher_port(kmsg);
1082 	}
1083 }
1084 
1085 /*
1086  *	Routine:	ipc_kmsg_clean_descriptors
1087  *	Purpose:
1088  *		Cleans the body of a kernel message.
1089  *		Releases all rights, references, and memory.
1090  *
1091  *	Conditions:
1092  *		No locks held.
1093  */
1094 void
ipc_kmsg_clean_descriptors(mach_msg_kdescriptor_t * kdesc __counted_by (number),mach_msg_type_number_t number)1095 ipc_kmsg_clean_descriptors(
1096 	mach_msg_kdescriptor_t *kdesc __counted_by(number),
1097 	mach_msg_type_number_t  number)
1098 {
1099 	for (mach_msg_type_number_t i = 0; i < number; i++, kdesc++) {
1100 		switch (mach_msg_kdescriptor_type(kdesc)) {
1101 		case MACH_MSG_PORT_DESCRIPTOR: {
1102 			mach_msg_port_descriptor_t *dsc = &kdesc->kdesc_port;
1103 
1104 			/*
1105 			 * Destroy port rights carried in the message
1106 			 */
1107 			if (IP_VALID(dsc->name)) {
1108 				ipc_object_destroy(dsc->name, dsc->disposition);
1109 				dsc->name = IP_NULL;
1110 			}
1111 			break;
1112 		}
1113 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
1114 		case MACH_MSG_OOL_DESCRIPTOR: {
1115 			mach_msg_ool_descriptor_t *dsc = &kdesc->kdesc_memory;
1116 			vm_map_copy_t copy = dsc->address;
1117 
1118 			/*
1119 			 * Destroy memory carried in the message
1120 			 */
1121 			if (copy) {
1122 				vm_map_copy_discard(copy);
1123 				dsc->address = NULL;
1124 			} else {
1125 				assert(dsc->size == 0);
1126 			}
1127 			break;
1128 		}
1129 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
1130 			mach_msg_ool_ports_descriptor_t *dsc = &kdesc->kdesc_port_array;
1131 			mach_port_array_t array = dsc->address;
1132 
1133 			for (mach_msg_size_t j = 0; j < dsc->count; j++) {
1134 				ipc_port_t port = array[j].port;
1135 
1136 				if (IP_VALID(port)) {
1137 					ipc_object_destroy(port, dsc->disposition);
1138 				}
1139 			}
1140 			if (array) {
1141 				mach_port_array_free(array, dsc->count);
1142 				dsc->address = NULL;
1143 			} else {
1144 				assert(dsc->count == 0);
1145 			}
1146 			break;
1147 		}
1148 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR: {
1149 			mach_msg_guarded_port_descriptor_t *dsc = &kdesc->kdesc_guarded_port;
1150 
1151 			/*
1152 			 * Destroy port rights carried in the message
1153 			 */
1154 			if (IP_VALID(dsc->name)) {
1155 				ipc_object_destroy(dsc->name, dsc->disposition);
1156 				dsc->name = IP_NULL;
1157 			}
1158 			break;
1159 		}
1160 		default:
1161 			__ipc_kmsg_descriptor_invalid_type_panic(kdesc);
1162 		}
1163 	}
1164 }
1165 
1166 /*
1167  *	Routine:	ipc_kmsg_clean
1168  *	Purpose:
1169  *		Cleans a kernel message.  Releases all rights,
1170  *		references, and memory held by the message.
1171  *	Conditions:
1172  *		No locks held.
1173  */
1174 
1175 static void
ipc_kmsg_clean(ipc_kmsg_t kmsg,mach_msg_size_t dsc_count)1176 ipc_kmsg_clean(ipc_kmsg_t kmsg, mach_msg_size_t dsc_count)
1177 {
1178 	ipc_kmsg_clean_header(kmsg);
1179 
1180 	if (dsc_count) {
1181 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(ikm_header(kmsg));
1182 
1183 		ipc_kmsg_clean_descriptors(kbase->msgb_dsc_array, dsc_count);
1184 	}
1185 }
1186 
1187 
1188 #pragma mark ipc_kmsg enqueue/destroy, qos, priority, voucher, ...
1189 
1190 /* we can't include the BSD <sys/persona.h> header here... */
1191 #ifndef PERSONA_ID_NONE
1192 #define PERSONA_ID_NONE ((uint32_t)-1)
1193 #endif
1194 
1195 /*
1196  *	Routine:	ipc_kmsg_enqueue_qos
1197  *	Purpose:
1198  *		Enqueue a kmsg, propagating qos
1199  *		overrides towards the head of the queue.
1200  *
1201  *	Returns:
1202  *		whether the head of the queue had
1203  *		it's override-qos adjusted because
1204  *		of this insertion.
1205  */
1206 
1207 bool
ipc_kmsg_enqueue_qos(ipc_kmsg_queue_t queue,ipc_kmsg_t kmsg)1208 ipc_kmsg_enqueue_qos(
1209 	ipc_kmsg_queue_t        queue,
1210 	ipc_kmsg_t              kmsg)
1211 {
1212 	mach_msg_qos_t qos_ovr = kmsg->ikm_qos_override;
1213 	ipc_kmsg_t     prev;
1214 
1215 	if (ipc_kmsg_enqueue(queue, kmsg)) {
1216 		return true;
1217 	}
1218 
1219 	/* apply QoS overrides towards the head */
1220 	prev = ipc_kmsg_queue_element(kmsg->ikm_link.prev);
1221 	while (prev != kmsg) {
1222 		if (qos_ovr <= prev->ikm_qos_override) {
1223 			return false;
1224 		}
1225 		prev->ikm_qos_override = qos_ovr;
1226 		prev = ipc_kmsg_queue_element(prev->ikm_link.prev);
1227 	}
1228 
1229 	return true;
1230 }
1231 
1232 /*
1233  *	Routine:	ipc_kmsg_override_qos
1234  *	Purpose:
1235  *		Update the override for a given kmsg already
1236  *		enqueued, propagating qos override adjustments
1237  *		towards	the head of the queue.
1238  *
1239  *	Returns:
1240  *		whether the head of the queue had
1241  *		it's override-qos adjusted because
1242  *		of this insertion.
1243  */
1244 
1245 bool
ipc_kmsg_override_qos(ipc_kmsg_queue_t queue,ipc_kmsg_t kmsg,mach_msg_qos_t qos_ovr)1246 ipc_kmsg_override_qos(
1247 	ipc_kmsg_queue_t    queue,
1248 	ipc_kmsg_t          kmsg,
1249 	mach_msg_qos_t      qos_ovr)
1250 {
1251 	ipc_kmsg_t first = ipc_kmsg_queue_first(queue);
1252 	ipc_kmsg_t cur = kmsg;
1253 
1254 	/* apply QoS overrides towards the head */
1255 	while (qos_ovr > cur->ikm_qos_override) {
1256 		cur->ikm_qos_override = qos_ovr;
1257 		if (cur == first) {
1258 			return true;
1259 		}
1260 		cur = ipc_kmsg_queue_element(cur->ikm_link.prev);
1261 	}
1262 
1263 	return false;
1264 }
1265 
1266 /*
1267  *	Routine:	ipc_kmsg_destroy
1268  *	Purpose:
1269  *		Destroys a kernel message.  Releases all rights,
1270  *		references, and memory held by the message.
1271  *		Frees the message.
1272  *	Conditions:
1273  *		No locks held.
1274  */
1275 
1276 void
ipc_kmsg_destroy(ipc_kmsg_t kmsg,ipc_kmsg_destroy_flags_t flags)1277 ipc_kmsg_destroy(
1278 	ipc_kmsg_t                     kmsg,
1279 	ipc_kmsg_destroy_flags_t       flags)
1280 {
1281 	/* sign the msg if it has not been signed */
1282 	boolean_t sign_msg = (flags & IPC_KMSG_DESTROY_NOT_SIGNED);
1283 	mach_msg_header_t *hdr = ikm_header(kmsg);
1284 
1285 	if (flags & IPC_KMSG_DESTROY_SKIP_REMOTE) {
1286 		hdr->msgh_remote_port = MACH_PORT_NULL;
1287 		/* re-sign the msg since content changed */
1288 		sign_msg = true;
1289 	}
1290 
1291 	if (flags & IPC_KMSG_DESTROY_SKIP_LOCAL) {
1292 		hdr->msgh_local_port = MACH_PORT_NULL;
1293 		/* re-sign the msg since content changed */
1294 		sign_msg = true;
1295 	}
1296 
1297 	if (sign_msg) {
1298 		ipc_kmsg_sign(kmsg, ipc_kmsg_get_trailer(kmsg));
1299 	}
1300 
1301 	/*
1302 	 *	Destroying a message can cause more messages to be destroyed.
1303 	 *	Curtail recursion by putting messages on the deferred
1304 	 *	destruction queue.  If this was the first message on the
1305 	 *	queue, this instance must process the full queue.
1306 	 */
1307 	if (ipc_kmsg_delayed_destroy(kmsg)) {
1308 		ipc_kmsg_reap_delayed();
1309 	}
1310 }
1311 
1312 /*
1313  *	Routine:	ipc_kmsg_delayed_destroy
1314  *	Purpose:
1315  *		Enqueues a kernel message for deferred destruction.
1316  *	Returns:
1317  *		Boolean indicator that the caller is responsible to reap
1318  *		deferred messages.
1319  */
1320 
1321 bool
ipc_kmsg_delayed_destroy(ipc_kmsg_t kmsg)1322 ipc_kmsg_delayed_destroy(
1323 	ipc_kmsg_t kmsg)
1324 {
1325 	return ipc_kmsg_enqueue(&current_thread()->ith_messages, kmsg);
1326 }
1327 
1328 /*
1329  *	Routine:	ipc_kmsg_delayed_destroy_queue
1330  *	Purpose:
1331  *		Enqueues a queue of kernel messages for deferred destruction.
1332  *	Returns:
1333  *		Boolean indicator that the caller is responsible to reap
1334  *		deferred messages.
1335  */
1336 
1337 bool
ipc_kmsg_delayed_destroy_queue(ipc_kmsg_queue_t queue)1338 ipc_kmsg_delayed_destroy_queue(
1339 	ipc_kmsg_queue_t        queue)
1340 {
1341 	return circle_queue_concat_tail(&current_thread()->ith_messages, queue);
1342 }
1343 
1344 /*
1345  *	Routine:	ipc_kmsg_reap_delayed
1346  *	Purpose:
1347  *		Destroys messages from the per-thread
1348  *		deferred reaping queue.
1349  *	Conditions:
1350  *		No locks held. kmsgs on queue must be signed.
1351  */
1352 
1353 void
ipc_kmsg_reap_delayed(void)1354 ipc_kmsg_reap_delayed(void)
1355 {
1356 	ipc_kmsg_queue_t queue = &(current_thread()->ith_messages);
1357 	ipc_kmsg_t kmsg;
1358 
1359 	/*
1360 	 * must leave kmsg in queue while cleaning it to assure
1361 	 * no nested calls recurse into here.
1362 	 */
1363 	while ((kmsg = ipc_kmsg_queue_first(queue)) != IKM_NULL) {
1364 		/*
1365 		 * Kmsgs queued for delayed destruction either come from
1366 		 * ipc_kmsg_destroy() or ipc_kmsg_delayed_destroy_queue(),
1367 		 * where we handover all kmsgs enqueued on port to destruction
1368 		 * queue in O(1). In either case, all kmsgs must have been
1369 		 * signed.
1370 		 *
1371 		 * For each unreceived msg, validate its signature before freeing.
1372 		 */
1373 		ipc_kmsg_clean(kmsg, ipc_kmsg_validate_signature(kmsg));
1374 		ipc_kmsg_rmqueue(queue, kmsg);
1375 		ipc_kmsg_free(kmsg);
1376 	}
1377 }
1378 
1379 static pthread_priority_compact_t
ipc_get_current_thread_priority(void)1380 ipc_get_current_thread_priority(void)
1381 {
1382 	thread_t thread = current_thread();
1383 	thread_qos_t qos;
1384 	int relpri;
1385 
1386 	qos = thread_get_requested_qos(thread, &relpri);
1387 	if (!qos) {
1388 		qos = thread_user_promotion_qos_for_pri(thread->base_pri);
1389 		relpri = 0;
1390 	}
1391 	return _pthread_priority_make_from_thread_qos(qos, relpri, 0);
1392 }
1393 
1394 static kern_return_t
ipc_kmsg_set_qos(ipc_kmsg_t kmsg,mach_msg_option64_t options,mach_msg_priority_t priority)1395 ipc_kmsg_set_qos(
1396 	ipc_kmsg_t kmsg,
1397 	mach_msg_option64_t options,
1398 	mach_msg_priority_t priority)
1399 {
1400 	kern_return_t kr;
1401 	mach_msg_header_t *hdr = ikm_header(kmsg);
1402 	ipc_port_t special_reply_port = hdr->msgh_local_port;
1403 	ipc_port_t dest_port = hdr->msgh_remote_port;
1404 
1405 	if ((options & MACH_SEND_OVERRIDE) &&
1406 	    !mach_msg_priority_is_pthread_priority(priority)) {
1407 		mach_msg_qos_t qos = mach_msg_priority_qos(priority);
1408 		int relpri = mach_msg_priority_relpri(priority);
1409 		mach_msg_qos_t ovr = mach_msg_priority_overide_qos(priority);
1410 
1411 		kmsg->ikm_ppriority = _pthread_priority_make_from_thread_qos(qos, relpri, 0);
1412 		kmsg->ikm_qos_override = MAX(qos, ovr);
1413 	} else {
1414 #if CONFIG_VOUCHER_DEPRECATED
1415 		kr = ipc_get_pthpriority_from_kmsg_voucher(kmsg, &kmsg->ikm_ppriority);
1416 #else
1417 		kr = KERN_FAILURE;
1418 #endif /* CONFIG_VOUCHER_DEPRECATED */
1419 		if (kr != KERN_SUCCESS) {
1420 			if (options & MACH_SEND_PROPAGATE_QOS) {
1421 				kmsg->ikm_ppriority = ipc_get_current_thread_priority();
1422 			} else {
1423 				kmsg->ikm_ppriority = MACH_MSG_PRIORITY_UNSPECIFIED;
1424 			}
1425 		}
1426 
1427 		if (options & MACH_SEND_OVERRIDE) {
1428 			mach_msg_qos_t qos = _pthread_priority_thread_qos(kmsg->ikm_ppriority);
1429 			mach_msg_qos_t ovr = _pthread_priority_thread_qos(priority);
1430 			kmsg->ikm_qos_override = MAX(qos, ovr);
1431 		} else {
1432 			kmsg->ikm_qos_override = _pthread_priority_thread_qos(kmsg->ikm_ppriority);
1433 		}
1434 	}
1435 
1436 	kr = KERN_SUCCESS;
1437 
1438 	if (IP_VALID(special_reply_port) &&
1439 	    ip_is_special_reply_port(special_reply_port) &&
1440 	    !ip_is_kobject(dest_port) &&
1441 	    MACH_MSGH_BITS_LOCAL(hdr->msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE) {
1442 		boolean_t sync_bootstrap_checkin = !!(options & MACH_SEND_SYNC_BOOTSTRAP_CHECKIN);
1443 		/*
1444 		 * Link the destination port to special reply port and make sure that
1445 		 * dest port has a send turnstile, else allocate one.
1446 		 */
1447 		ipc_port_link_special_reply_port(special_reply_port, dest_port, sync_bootstrap_checkin);
1448 	}
1449 	return kr;
1450 }
1451 
1452 static kern_return_t
ipc_kmsg_set_qos_kernel(ipc_kmsg_t kmsg)1453 ipc_kmsg_set_qos_kernel(
1454 	ipc_kmsg_t kmsg)
1455 {
1456 	ipc_port_t dest_port = ikm_header(kmsg)->msgh_remote_port;
1457 	kmsg->ikm_qos_override = dest_port->ip_kernel_qos_override;
1458 	kmsg->ikm_ppriority = _pthread_priority_make_from_thread_qos(kmsg->ikm_qos_override, 0, 0);
1459 	return KERN_SUCCESS;
1460 }
1461 
1462 /*
1463  *	Routine:	ipc_kmsg_link_reply_context_locked
1464  *	Purpose:
1465  *		Link any required context from the sending voucher
1466  *		to the reply port. The ipc_kmsg_copyin_from_user function will
1467  *		enforce that the sender calls mach_msg in this context.
1468  *	Conditions:
1469  *		reply port is locked
1470  */
1471 static void
ipc_kmsg_link_reply_context_locked(ipc_port_t reply_port,ipc_port_t voucher_port)1472 ipc_kmsg_link_reply_context_locked(
1473 	ipc_port_t reply_port,
1474 	ipc_port_t voucher_port)
1475 {
1476 	kern_return_t __assert_only kr;
1477 	uint32_t persona_id = 0;
1478 	ipc_voucher_t voucher;
1479 
1480 	ip_mq_lock_held(reply_port);
1481 
1482 	if (!ip_active(reply_port)) {
1483 		return;
1484 	}
1485 
1486 	voucher = convert_port_to_voucher(voucher_port);
1487 
1488 	kr = bank_get_bank_ledger_thread_group_and_persona(voucher, NULL, NULL, &persona_id);
1489 	assert(kr == KERN_SUCCESS);
1490 	ipc_voucher_release(voucher);
1491 
1492 	if (persona_id == 0 || persona_id == PERSONA_ID_NONE) {
1493 		/* there was no persona context to record */
1494 		return;
1495 	}
1496 
1497 	/*
1498 	 * Set the persona_id as the context on the reply port.
1499 	 * This will force the thread that replies to have adopted a voucher
1500 	 * with a matching persona.
1501 	 */
1502 	reply_port->ip_reply_context = persona_id;
1503 
1504 	return;
1505 }
1506 
1507 /*
1508  *	Routine:	ipc_kmsg_validate_reply_context_locked
1509  *	Purpose:
1510  *		Validate that the current thread is running in the context
1511  *		required by the destination port.
1512  *	Conditions:
1513  *		dest_port is locked
1514  *	Returns:
1515  *		MACH_MSG_SUCCESS on success.
1516  *		On error, an EXC_GUARD exception is also raised.
1517  *		This function *always* resets the port reply context.
1518  */
1519 static mach_msg_return_t
ipc_kmsg_validate_reply_context_locked(mach_msg_option64_t option,ipc_port_t dest_port,ipc_voucher_t voucher,mach_port_name_t voucher_name)1520 ipc_kmsg_validate_reply_context_locked(
1521 	mach_msg_option64_t option,
1522 	ipc_port_t dest_port,
1523 	ipc_voucher_t voucher,
1524 	mach_port_name_t voucher_name)
1525 {
1526 	uint32_t dest_ctx = dest_port->ip_reply_context;
1527 	dest_port->ip_reply_context = 0;
1528 
1529 	if (!ip_active(dest_port)) {
1530 		return MACH_MSG_SUCCESS;
1531 	}
1532 
1533 	if (voucher == IPC_VOUCHER_NULL || !MACH_PORT_VALID(voucher_name)) {
1534 		if ((option & MACH_SEND_KERNEL) == 0) {
1535 			mach_port_guard_exception(voucher_name,
1536 			    MPG_PAYLOAD(MPG_FLAGS_STRICT_REPLY_INVALID_VOUCHER, dest_ctx),
1537 			    kGUARD_EXC_STRICT_REPLY);
1538 		}
1539 		return MACH_SEND_INVALID_CONTEXT;
1540 	}
1541 
1542 	kern_return_t __assert_only kr;
1543 	uint32_t persona_id = 0;
1544 	kr = bank_get_bank_ledger_thread_group_and_persona(voucher, NULL, NULL, &persona_id);
1545 	assert(kr == KERN_SUCCESS);
1546 
1547 	if (dest_ctx != persona_id) {
1548 		if ((option & MACH_SEND_KERNEL) == 0) {
1549 			mach_port_guard_exception(voucher_name,
1550 			    MPG_PAYLOAD(MPG_FLAGS_STRICT_REPLY_MISMATCHED_PERSONA,
1551 			    persona_id, dest_ctx),
1552 			    kGUARD_EXC_STRICT_REPLY);
1553 		}
1554 		return MACH_SEND_INVALID_CONTEXT;
1555 	}
1556 
1557 	return MACH_MSG_SUCCESS;
1558 }
1559 
1560 
1561 #pragma mark ipc_kmsg copyin and inflate (from user)
1562 /*!
1563  * @defgroup IPC kmsg copyin and inflate functions
1564  * @{
1565  *
1566  * IPC kmsg inflate
1567  * ~~~~~~~~~~~~~~~~
1568  *
1569  * This is the operation that turns the user representation of a message,
1570  * into a message in kernel representation, without any rights.
1571  *
1572  * This is driven by @c ipc_kmsg_get_and_inflate_from_user() which will:
1573  * - convert the message header into kernel layout (mach_msg_header_t),
1574  * - convert the descriptors into kernel layout,
1575  * - copy the body bytes.
1576  *
1577  *
1578  * IPC (right) copyin
1579  * ~~~~~~~~~~~~~~~~~~
1580  *
1581  * This is the operation that turns the userspace port names and VM addresses
1582  * in to actual IPC ports and vm_map_copy_t objects.
1583  *
1584  * This is done on an IPC kmsg in "kernel representation" and just replace
1585  * userspace scalar values with kernel pointers in place.
1586  *
1587  * @c ipc_kmsg_copyin_from_user() is the function that drives the entire
1588  * inflate and copyin logic, applying various filtering at each stage.
1589  */
1590 
1591 
1592 /*
1593  * Macros to help inflate descriptors in place.
1594  *
1595  * the `addr` parameters must be of type `char *` so that the compiler
1596  * must assume these addresses alias (and they do).
1597  */
1598 #define ikm_udsc_type(addr)         __IGNORE_WCASTALIGN(((const mach_msg_type_descriptor_t *)(addr))->type)
1599 #define ikm_udsc_get(dst, addr)     __IGNORE_WCASTALIGN(*(dst) = *(const typeof(*(dst)) *)(addr))
1600 #define ikm_kdsc_zero(addr, type)   ((type *)memset(addr, 0, sizeof(type)))
1601 
1602 typedef struct {
1603 	mach_msg_header_t      *msg;
1604 
1605 	mach_port_name_t        dest_name;
1606 	mach_msg_type_name_t    dest_type;
1607 	ipc_port_t              dest_port;
1608 	ipc_copyin_cleanup_t    dest_cleanup;
1609 
1610 	mach_port_name_t        reply_name;
1611 	mach_msg_type_name_t    reply_type;
1612 	ipc_port_t              reply_port;
1613 	ipc_copyin_cleanup_t    reply_cleanup;
1614 	ipc_entry_bits_t        reply_bits; /* for debugging purpose */
1615 
1616 	mach_port_name_t        voucher_name;
1617 	mach_msg_type_name_t    voucher_type;
1618 	ipc_port_t              voucher_port;
1619 	ipc_copyin_cleanup_t    voucher_cleanup;
1620 
1621 	ipc_table_index_t       dest_request;
1622 } ikm_copyinhdr_state_t;
1623 
1624 /*
1625  *     Routine:        ipc_kmsg_copyin_header_validate
1626  *     Purpose:
1627  *             Perform various preflights on an IPC kmsg
1628  *     Conditions:
1629  *             Nothing locked.
1630  */
1631 static mach_msg_return_t
ipc_kmsg_copyin_header_validate(ipc_kmsg_t kmsg,__unused mach_msg_option64_t options,ikm_copyinhdr_state_t * st)1632 ipc_kmsg_copyin_header_validate(
1633 	ipc_kmsg_t              kmsg,
1634 	__unused mach_msg_option64_t options,
1635 	ikm_copyinhdr_state_t  *st)
1636 {
1637 	mach_msg_header_t *msg = ikm_header(kmsg);
1638 
1639 	if (msg->msgh_bits & ~MACH_MSGH_BITS_USER) {
1640 		return MACH_SEND_INVALID_HEADER;
1641 	}
1642 
1643 	st->msg = msg;
1644 
1645 	/*
1646 	 *	Validate the reply port and its disposition.
1647 	 */
1648 	st->reply_name = CAST_MACH_PORT_TO_NAME(msg->msgh_local_port);
1649 	st->reply_type = MACH_MSGH_BITS_LOCAL(msg->msgh_bits);
1650 	if (st->reply_type == MACH_MSG_TYPE_NONE) {
1651 		if (st->reply_name != MACH_PORT_NULL) {
1652 			return MACH_SEND_INVALID_HEADER;
1653 		}
1654 	} else if (!MACH_MSG_TYPE_PORT_ANY_SEND(st->reply_type)) {
1655 		return MACH_SEND_INVALID_HEADER;
1656 	}
1657 
1658 	/*
1659 	 *	Validate the voucher and its disposition.
1660 	 *
1661 	 *      The validation is a little nuanced for backward compatbility
1662 	 *      reasons: once upon a time, the "msgh_voucher_port" field was
1663 	 *      reserved, and some clients were expecting it to round-trip.
1664 	 *
1665 	 *      However, for that case, the voucher_type would always be 0
1666 	 *      (because the MACH_MSGH_BITS_USER mask check would reject non
1667 	 *      zero bits), so when it is, we're careful to have the
1668 	 *      msgh_voucher_port value round trip unmodified.
1669 	 */
1670 	st->voucher_name = MACH_PORT_NULL;
1671 	st->voucher_type = MACH_MSGH_BITS_VOUCHER(msg->msgh_bits);
1672 	switch (st->voucher_type) {
1673 	case MACH_MSG_TYPE_NONE:
1674 		break;
1675 	case MACH_MSG_TYPE_MOVE_SEND:
1676 	case MACH_MSG_TYPE_COPY_SEND:
1677 		st->voucher_name = msg->msgh_voucher_port;
1678 		if (st->voucher_name != MACH_PORT_DEAD) {
1679 			break;
1680 		}
1681 		OS_FALLTHROUGH;
1682 	default:
1683 		return MACH_SEND_INVALID_VOUCHER;
1684 	}
1685 
1686 	/*
1687 	 *	Validate the destination and its disposition.
1688 	 */
1689 	st->dest_name = CAST_MACH_PORT_TO_NAME(msg->msgh_remote_port);
1690 	st->dest_type = MACH_MSGH_BITS_REMOTE(msg->msgh_bits);
1691 
1692 	if (!MACH_MSG_TYPE_PORT_ANY_SEND(st->dest_type)) {
1693 		return MACH_SEND_INVALID_HEADER;
1694 	}
1695 
1696 	if (!MACH_PORT_VALID(st->dest_name)) {
1697 		return MACH_SEND_INVALID_DEST;
1698 	}
1699 
1700 	if (st->dest_name == st->voucher_name) {
1701 		/*
1702 		 * If the voucher and destination are the same,
1703 		 * then the disposition for the destination
1704 		 * must be a valid disposition for a voucher!
1705 		 */
1706 		if (st->dest_type != MACH_MSG_TYPE_MOVE_SEND &&
1707 		    st->dest_type != MACH_MSG_TYPE_COPY_SEND) {
1708 			return MACH_SEND_INVALID_DEST;
1709 		}
1710 	}
1711 
1712 	if (st->dest_name == st->reply_name) {
1713 		/*
1714 		 * If the destination and reply port are the same,
1715 		 * no disposition can be a move-send-once.
1716 		 */
1717 		if (st->dest_type == MACH_MSG_TYPE_MOVE_SEND_ONCE ||
1718 		    st->reply_type == MACH_MSG_TYPE_MOVE_SEND_ONCE) {
1719 			return MACH_SEND_INVALID_DEST;
1720 		}
1721 	}
1722 
1723 	if (MACH_PORT_VALID(st->reply_name) && st->reply_name == st->voucher_name) {
1724 		/* Special case where the voucher name == reply name */
1725 		st->reply_bits = -1;
1726 		return MACH_SEND_INVALID_REPLY;
1727 	}
1728 
1729 	return MACH_MSG_SUCCESS;
1730 }
1731 
1732 /*
1733  *     Routine:        ipc_kmsg_copyin_header_cleanup
1734  *     Purpose:
1735  *             Cleans up the state used for an IPC kmsg header copyin
1736  *     Conditions:
1737  *             Nothing locked.
1738  */
1739 static void
ipc_kmsg_copyin_header_cleanup(ikm_copyinhdr_state_t * st)1740 ipc_kmsg_copyin_header_cleanup(ikm_copyinhdr_state_t *st)
1741 {
1742 	/* the caller must take care of these */
1743 	assert(st->dest_port == IP_NULL);
1744 	assert(st->reply_port == IP_NULL);
1745 	assert(st->voucher_port == IP_NULL);
1746 
1747 	ipc_right_copyin_cleanup_destroy(&st->dest_cleanup, st->dest_name);
1748 	ipc_right_copyin_cleanup_destroy(&st->reply_cleanup, st->reply_name);
1749 	ipc_right_copyin_cleanup_destroy(&st->voucher_cleanup, st->voucher_name);
1750 }
1751 
1752 static inline mach_msg_type_name_t
ipc_kmsg_copyin_dest_disposition(ikm_copyinhdr_state_t * st,ipc_object_copyin_flags_t * xtra)1753 ipc_kmsg_copyin_dest_disposition(
1754 	ikm_copyinhdr_state_t  *st,
1755 	ipc_object_copyin_flags_t *xtra)
1756 {
1757 	mach_msg_type_name_t disp1;
1758 	mach_msg_type_name_t disp2;
1759 
1760 	if (st->dest_name == st->voucher_name) {
1761 		/*
1762 		 *	Do the joint copyin of the dest disposition and
1763 		 *	voucher disposition from the one entry/port.
1764 		 *
1765 		 *	We already validated that the voucher copyin would
1766 		 *	succeed (above), and that the destination port
1767 		 *	disposition is valid for a voucher.
1768 		 */
1769 
1770 		disp1 = st->dest_type;
1771 		disp2 = st->voucher_type;
1772 	} else if (st->dest_name == st->reply_name) {
1773 		/*
1774 		 *	Destination and reply ports are the same!
1775 		 *	This is very similar to the case where the
1776 		 *	destination and voucher ports were the same.
1777 		 *
1778 		 *	ipc_kmsg_copyin_header_validate() tells us that
1779 		 *	neither dest_type nor reply_type is a move-send-once.
1780 		 *
1781 		 *	We need to consider any pair of these:
1782 		 *	{make-send, make-send-once, move-send, copy-send}
1783 		 *
1784 		 *	1. If any is a make-send, then it means one of the
1785 		 *	   dispositions requires a receive right:
1786 		 *
1787 		 *	   If the destination port disposition needs
1788 		 *	   a receive right, its copyin succeeding
1789 		 *	   means the receive right is there.
1790 		 *
1791 		 *	   If the reply port disposition needs a receive
1792 		 *	   right, then it was validated by
1793 		 *	   ipc_right_copyin_check_reply() and we know the
1794 		 *	   receive right is there too.
1795 		 *
1796 		 *	   Hence the port is not in danger of dying
1797 		 *	   while we hold the space lock, we can go
1798 		 *	   one at a time.
1799 		 *
1800 		 *	2. otherwise, we do the joint copyin dance.
1801 		 */
1802 
1803 		if ((st->dest_type == MACH_MSG_TYPE_MAKE_SEND) ||
1804 		    (st->dest_type == MACH_MSG_TYPE_MAKE_SEND_ONCE) ||
1805 		    (st->reply_type == MACH_MSG_TYPE_MAKE_SEND) ||
1806 		    (st->reply_type == MACH_MSG_TYPE_MAKE_SEND_ONCE)) {
1807 			*xtra = IPC_OBJECT_COPYIN_FLAGS_NONE;
1808 			return st->dest_type;
1809 		}
1810 
1811 		disp1 = st->dest_type;
1812 		disp2 = st->reply_type;
1813 	} else {
1814 		/*
1815 		 *	Handle destination and reply independently, as
1816 		 *	they are independent entries (even if the entries
1817 		 *	refer to the same port).
1818 		 *
1819 		 *	This can be the tough case to make atomic.
1820 		 *
1821 		 *	The difficult problem is serializing with port death.
1822 		 *	The bad case is when dest_port dies after its copyin,
1823 		 *	reply_port dies before its copyin, and dest_port dies before
1824 		 *	reply_port.  Then the copyins operated as if dest_port was
1825 		 *	alive and reply_port was dead, which shouldn't have happened
1826 		 *	because they died in the other order.
1827 		 *
1828 		 *	Note that it is easy for a user task to tell if
1829 		 *	a copyin happened before or after a port died.
1830 		 *	If a port dies before copyin, a dead-name notification
1831 		 *	is generated and the dead name's urefs are incremented,
1832 		 *	and if the copyin happens first, a port-deleted
1833 		 *	notification is generated.
1834 		 *
1835 		 *	Even so, avoiding that potentially detectable race is too
1836 		 *	expensive - and no known code cares about it.  So, we just
1837 		 *	do the expedient thing and copy them in one after the other.
1838 		 */
1839 
1840 		*xtra = IPC_OBJECT_COPYIN_FLAGS_NONE;
1841 		return st->dest_type;
1842 	}
1843 
1844 	if (disp1 == MACH_MSG_TYPE_MOVE_SEND && disp2 == MACH_MSG_TYPE_MOVE_SEND) {
1845 		*xtra |= IPC_OBJECT_COPYIN_FLAGS_DEST_EXTRA_MOVE;
1846 		return MACH_MSG_TYPE_MOVE_SEND;
1847 	}
1848 
1849 	if (disp1 == MACH_MSG_TYPE_MOVE_SEND && disp2 == MACH_MSG_TYPE_COPY_SEND) {
1850 		*xtra |= IPC_OBJECT_COPYIN_FLAGS_DEST_EXTRA_COPY;
1851 		return MACH_MSG_TYPE_MOVE_SEND;
1852 	}
1853 	if (disp1 == MACH_MSG_TYPE_COPY_SEND && disp2 == MACH_MSG_TYPE_MOVE_SEND) {
1854 		*xtra |= IPC_OBJECT_COPYIN_FLAGS_DEST_EXTRA_COPY;
1855 		return MACH_MSG_TYPE_MOVE_SEND;
1856 	}
1857 
1858 	if (disp1 == MACH_MSG_TYPE_COPY_SEND && disp2 == MACH_MSG_TYPE_COPY_SEND) {
1859 		*xtra |= IPC_OBJECT_COPYIN_FLAGS_DEST_EXTRA_COPY;
1860 		return MACH_MSG_TYPE_COPY_SEND;
1861 	}
1862 
1863 	ipc_unreachable("not a pair of copy/move-send");
1864 }
1865 
1866 /*
1867  *	Routine:	ipc_kmsg_copyin_header_rights
1868  *	Purpose:
1869  *		Core implementation of ipc_kmsg_copyin_header()
1870  *
1871  *	Conditions:
1872  *		Nothing locked.
1873  *		Returns with the destination port locked on success.
1874  */
1875 static mach_msg_return_t
ipc_kmsg_copyin_header_rights(ipc_space_t space,ikm_copyinhdr_state_t * st)1876 ipc_kmsg_copyin_header_rights(
1877 	ipc_space_t             space,
1878 	ikm_copyinhdr_state_t  *st)
1879 {
1880 	ipc_entry_t dest_entry = IE_NULL;
1881 	ipc_entry_t reply_entry = IE_NULL;
1882 	ipc_entry_t voucher_entry = IE_NULL;
1883 	mach_msg_type_name_t dest_type;
1884 	ipc_object_copyin_flags_t dest_xtra;
1885 	kern_return_t kr = KERN_SUCCESS;
1886 
1887 	is_write_lock(space);
1888 	if (__improbable(!is_active(space))) {
1889 		is_write_unlock(space);
1890 		return MACH_SEND_INVALID_DEST;
1891 	}
1892 
1893 	/* space locked and active */
1894 
1895 	/*
1896 	 *      Step 1: lookup the various entries
1897 	 *
1898 	 *      Validate that copyins of the voucher and reply ports
1899 	 *      will always succeed.
1900 	 *
1901 	 *      Once we haved copied in the destination port,
1902 	 *      we can't back out.
1903 	 */
1904 
1905 	if (st->voucher_name != MACH_PORT_NULL) {
1906 		voucher_entry = ipc_entry_lookup(space, st->voucher_name);
1907 
1908 		if (voucher_entry == IE_NULL ||
1909 		    (voucher_entry->ie_bits & MACH_PORT_TYPE_SEND) == 0 ||
1910 		    ip_type(voucher_entry->ie_port) != IKOT_VOUCHER) {
1911 			is_write_unlock(space);
1912 			return MACH_SEND_INVALID_VOUCHER;
1913 		}
1914 	}
1915 
1916 	if (st->dest_name == st->voucher_name) {
1917 		dest_entry = voucher_entry;
1918 	} else {
1919 		dest_entry = ipc_entry_lookup(space, st->dest_name);
1920 	}
1921 	if (__improbable(dest_entry == IE_NULL ||
1922 	    (dest_entry->ie_bits & MACH_PORT_TYPE_PORT_RIGHTS) == 0)) {
1923 		is_write_unlock(space);
1924 		return MACH_SEND_INVALID_DEST;
1925 	}
1926 
1927 	if (MACH_PORT_VALID(st->reply_name)) {
1928 		assert(st->reply_name != st->voucher_name);
1929 		if (st->reply_name == st->dest_name) {
1930 			reply_entry = dest_entry;
1931 		} else {
1932 			reply_entry = ipc_entry_lookup(space, st->reply_name);
1933 		}
1934 		if (reply_entry != IE_NULL) {
1935 			st->reply_bits = reply_entry->ie_bits;
1936 		}
1937 		if (__improbable(reply_entry == IE_NULL ||
1938 		    (reply_entry->ie_bits & MACH_PORT_TYPE_PORT_RIGHTS) == 0)) {
1939 			is_write_unlock(space);
1940 			return MACH_SEND_INVALID_REPLY;
1941 		}
1942 
1943 		if (__improbable(!ipc_right_copyin_check_reply(space,
1944 		    st->reply_name, reply_entry, st->reply_type))) {
1945 			is_write_unlock(space);
1946 			return MACH_SEND_INVALID_REPLY;
1947 		}
1948 	}
1949 
1950 
1951 	/*
1952 	 *      Step 2: copyin the destination port
1953 	 *
1954 	 *      Handle combinations as required in order to respect
1955 	 *      atomicity with respect to MOVE_{SEND,SEND_ONCE,RECEIVE}
1956 	 *      (COPY/MAKE disposition cause no such headaches).
1957 	 */
1958 
1959 	dest_type = ipc_kmsg_copyin_dest_disposition(st, &dest_xtra);
1960 
1961 	kr = ipc_right_copyin(space, st->dest_name, dest_type,
1962 	    IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND |
1963 	    dest_xtra, IPC_COPYIN_KMSG_DESTINATION, dest_entry,
1964 	    &st->dest_port, &st->dest_cleanup, NULL);
1965 	if (kr == KERN_SUCCESS) {
1966 		assert(IP_VALID(st->dest_port));
1967 		assert(!IP_VALID(st->dest_cleanup.icc_release_port));
1968 	} else {
1969 		ipc_space_unlock(space);
1970 		return MACH_SEND_INVALID_DEST;
1971 	}
1972 
1973 	/*
1974 	 *      Step 3: copyin the voucher and reply ports if needed.
1975 	 */
1976 	if (st->voucher_name == st->dest_name && dest_xtra) {
1977 		st->voucher_port = st->dest_port;
1978 	} else if (st->voucher_name) {
1979 		kr = ipc_right_copyin(space, st->voucher_name, st->voucher_type,
1980 		    IPC_OBJECT_COPYIN_FLAGS_NONE, IPC_COPYIN_KMSG_VOUCHER, voucher_entry,
1981 		    &st->voucher_port, &st->voucher_cleanup, NULL);
1982 
1983 		ipc_release_assert(kr == KERN_SUCCESS);
1984 		assert(IP_VALID(st->voucher_port));
1985 	}
1986 
1987 	if (st->reply_name == st->dest_name && dest_xtra) {
1988 		st->reply_port = st->dest_port;
1989 	} else if (MACH_PORT_VALID(st->reply_name)) {
1990 		kr = ipc_right_copyin(space, st->reply_name, st->reply_type,
1991 		    IPC_OBJECT_COPYIN_FLAGS_DEADOK, IPC_COPYIN_KMSG_REPLY, reply_entry,
1992 		    &st->reply_port, &st->reply_cleanup, NULL);
1993 
1994 		/*
1995 		 * ipc_right_copyin_check_reply() succeding means the
1996 		 * copyin above should work.
1997 		 */
1998 		ipc_release_assert(kr == KERN_SUCCESS);
1999 	} else {
2000 		/* convert invalid name to equivalent ipc_object type */
2001 		st->reply_port = CAST_MACH_NAME_TO_PORT(st->reply_name);
2002 	}
2003 
2004 
2005 	/*
2006 	 *      Step 4: wrap up
2007 	 *
2008 	 *      unlock the space, lock the dest port.
2009 	 *      capture the destination entry "ie_request"
2010 	 */
2011 
2012 	ip_mq_lock(st->dest_port);
2013 
2014 	st->dest_request = dest_entry->ie_request;
2015 
2016 	is_write_unlock(space);
2017 
2018 	return kr;
2019 }
2020 
2021 /*
2022  *	Routine:	ipc_kmsg_copyin_header
2023  *	Purpose:
2024  *		"Copy-in" port rights in the header of a message.
2025  *		Operates atomically; if it doesn't succeed the
2026  *		message header and the space are left untouched.
2027  *		If it does succeed the remote/local port fields
2028  *		contain object pointers instead of port names,
2029  *		and the bits field is updated.  The destination port
2030  *		will be a valid port pointer.
2031  *
2032  *	Conditions:
2033  *		Nothing locked. May add MACH64_SEND_ALWAYS option.
2034  *	Returns:
2035  *		MACH_MSG_SUCCESS	Successful copyin.
2036  *		MACH_SEND_INVALID_HEADER
2037  *			Illegal value in the message header bits.
2038  *		MACH_SEND_INVALID_DEST	The space is dead.
2039  *		MACH_SEND_INVALID_DEST	Can't copyin destination port.
2040  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
2041  *		MACH_SEND_INVALID_REPLY	Can't copyin reply port.
2042  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
2043  */
2044 static mach_msg_return_t
ipc_kmsg_copyin_header(ipc_kmsg_t kmsg,ipc_space_t space,mach_msg_priority_t priority,mach_msg_option64_t * option64p)2045 ipc_kmsg_copyin_header(
2046 	ipc_kmsg_t              kmsg,
2047 	ipc_space_t             space,
2048 	mach_msg_priority_t     priority,
2049 	mach_msg_option64_t     *option64p)
2050 {
2051 	mach_msg_option64_t options = *option64p;
2052 	ikm_copyinhdr_state_t st = { };
2053 	bool needboost = false;
2054 	kern_return_t kr;
2055 
2056 	kr = ipc_kmsg_copyin_header_validate(kmsg, options, &st);
2057 	if (kr == KERN_SUCCESS) {
2058 		kr = ipc_kmsg_copyin_header_rights(space, &st);
2059 	}
2060 
2061 	if (__improbable(kr != KERN_SUCCESS)) {
2062 		if (kr == MACH_SEND_INVALID_VOUCHER) {
2063 			mach_port_guard_exception(st.voucher_name, st.voucher_type,
2064 			    kGUARD_EXC_SEND_INVALID_VOUCHER);
2065 		}
2066 		if (kr == MACH_SEND_INVALID_REPLY) {
2067 			mach_port_guard_exception(st.reply_name,
2068 			    MPG_PAYLOAD(MPG_FLAGS_NONE, st.reply_bits, st.reply_type),
2069 			    kGUARD_EXC_SEND_INVALID_REPLY);
2070 		}
2071 		ipc_kmsg_copyin_header_cleanup(&st);
2072 		return kr;
2073 	}
2074 
2075 	/*
2076 	 *  Point of no return: past this point, the send won't fail,
2077 	 *  the message will be swallowed instead
2078 	 *
2079 	 *  The destination port is locked and active.
2080 	 */
2081 	ip_mq_lock_held(st.dest_port);
2082 
2083 	if (IP_VALID(st.voucher_port)) {
2084 		/*
2085 		 * No room to store voucher port in in-kernel msg header,
2086 		 * so we store it back in the kmsg itself.
2087 		 *
2088 		 * Store original voucher type there as well before the bits
2089 		 * are set to the post-copyin type.
2090 		 */
2091 		ipc_kmsg_set_voucher_port(kmsg, st.voucher_port, st.voucher_type);
2092 		st.voucher_port = IP_NULL; /* transfered to the kmsg */
2093 		st.voucher_type = MACH_MSG_TYPE_MOVE_SEND;
2094 	}
2095 	st.dest_type = ipc_object_copyin_type(st.dest_type);
2096 	st.reply_type = ipc_object_copyin_type(st.reply_type);
2097 
2098 	if (!ip_active(st.dest_port) ||
2099 	    (ip_is_kobject(st.dest_port) &&
2100 	    ip_in_space(st.dest_port, ipc_space_kernel))) {
2101 		/*
2102 		 * If the dest port died, or is a kobject AND its receive right
2103 		 * belongs to kernel, allow copyin of immovable send rights
2104 		 * in the message body (port descriptor) to succeed since
2105 		 * those send rights are simply "moved" or "copied" into kernel.
2106 		 *
2107 		 * See: ipc_object_copyin().
2108 		 */
2109 		kmsg->ikm_flags |= IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND;
2110 	}
2111 
2112 	/*
2113 	 * JMM - Without rdar://problem/6275821, this is the last place we can
2114 	 * re-arm the send-possible notifications.  It may trigger unexpectedly
2115 	 * early (send may NOT have failed), but better than missing.  We assure
2116 	 * we won't miss by forcing MACH_SEND_ALWAYS if we got past arming.
2117 	 */
2118 	if (((options & MACH64_SEND_NOTIFY) != 0) &&
2119 	    st.dest_type != MACH_MSG_TYPE_PORT_SEND_ONCE &&
2120 	    st.dest_request != IE_REQ_NONE &&
2121 	    ip_active(st.dest_port) &&
2122 	    !ip_in_space(st.dest_port, ipc_space_kernel)) {
2123 		/* st.dest_port could be in-transit, or in an ipc space */
2124 		if (ip_full(st.dest_port)) {
2125 			needboost = ipc_port_request_sparm(st.dest_port,
2126 			    st.dest_name, st.dest_request, options, priority);
2127 		} else {
2128 			*option64p |= MACH64_SEND_ALWAYS;
2129 		}
2130 	}
2131 
2132 	/*
2133 	 * If our request is the first boosting send-possible
2134 	 * notification this cycle, push the boost down the
2135 	 * destination port.
2136 	 */
2137 	if (!needboost) {
2138 		ip_mq_unlock(st.dest_port);
2139 #if IMPORTANCE_INHERITANCE
2140 	} else if (!ipc_port_importance_delta(st.dest_port,
2141 	    IPID_OPTION_SENDPOSSIBLE, 1)) {
2142 		ip_mq_unlock(st.dest_port);
2143 #endif /* IMPORTANCE_INHERITANCE */
2144 	}
2145 
2146 	/* st.dest_port is unlocked */
2147 
2148 	st.msg->msgh_bits = MACH_MSGH_BITS_SET(st.dest_type, st.reply_type,
2149 	    st.voucher_type, st.msg->msgh_bits);
2150 	st.msg->msgh_remote_port = st.dest_port;
2151 	st.msg->msgh_local_port = st.reply_port;
2152 	st.dest_port = st.reply_port = IP_NULL; /* transferred to the message */
2153 
2154 	/*
2155 	 * capture the qos value(s) for the kmsg qos,
2156 	 * and apply any override before we enqueue the kmsg.
2157 	 */
2158 	ipc_kmsg_set_qos(kmsg, options, priority);
2159 
2160 	/* then sign the header and trailer as soon as possible */
2161 	ipc_kmsg_init_trailer_and_sign(kmsg, current_task());
2162 
2163 	ipc_kmsg_copyin_header_cleanup(&st);
2164 
2165 	return MACH_MSG_SUCCESS;
2166 }
2167 
2168 
2169 static mach_msg_return_t
ipc_kmsg_inflate_port_descriptor(char * kdesc_addr,const char * udesc_addr,mach_msg_send_uctx_t * send_uctx)2170 ipc_kmsg_inflate_port_descriptor(
2171 	char                   *kdesc_addr,
2172 	const char             *udesc_addr,
2173 	mach_msg_send_uctx_t   *send_uctx)
2174 {
2175 	mach_msg_user_port_descriptor_t udesc;
2176 	mach_msg_port_descriptor_t *kdesc;
2177 
2178 	ikm_udsc_get(&udesc, udesc_addr);
2179 	if (os_add_overflow(send_uctx->send_dsc_port_count, 1,
2180 	    &send_uctx->send_dsc_port_count)) {
2181 		return MACH_SEND_TOO_LARGE;
2182 	}
2183 
2184 	kdesc = ikm_kdsc_zero(kdesc_addr, mach_msg_port_descriptor_t);
2185 	kdesc->u_name      = CAST_MACH_NAME_TO_PORT(udesc.name);
2186 	kdesc->disposition = udesc.disposition;
2187 	kdesc->type        = udesc.type;
2188 	return MACH_MSG_SUCCESS;
2189 }
2190 
2191 static mach_msg_return_t
ipc_kmsg_copyin_port_descriptor(mach_msg_port_descriptor_t * dsc,ipc_space_t space,ipc_port_t dest_port,ipc_kmsg_t kmsg)2192 ipc_kmsg_copyin_port_descriptor(
2193 	mach_msg_port_descriptor_t *dsc,
2194 	ipc_space_t             space,
2195 	ipc_port_t              dest_port,
2196 	ipc_kmsg_t              kmsg)
2197 {
2198 	mach_msg_type_name_t user_disp = dsc->disposition;
2199 	mach_port_name_t     name = CAST_MACH_PORT_TO_NAME(dsc->u_name);
2200 	mach_msg_type_name_t result_disp;
2201 	ipc_port_t           port;
2202 	kern_return_t        kr;
2203 
2204 	result_disp = ipc_object_copyin_type(user_disp);
2205 	if (MACH_PORT_VALID(name)) {
2206 		kr = ipc_object_copyin(space, name, user_disp, kmsg->ikm_flags,
2207 		    IPC_COPYIN_KMSG_PORT_DESCRIPTOR, NULL, &port);
2208 		if (kr != KERN_SUCCESS) {
2209 			if (kr == KERN_INVALID_RIGHT) {
2210 				mach_port_guard_exception(name,
2211 				    MPG_PAYLOAD(MPG_FLAGS_SEND_INVALID_RIGHT_PORT, user_disp),
2212 				    kGUARD_EXC_SEND_INVALID_RIGHT);
2213 			}
2214 			return MACH_SEND_INVALID_RIGHT;
2215 		}
2216 
2217 		if (result_disp == MACH_MSG_TYPE_PORT_RECEIVE &&
2218 		    ipc_port_check_circularity(port, dest_port)) {
2219 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
2220 		}
2221 		dsc->name = port;
2222 	} else {
2223 		dsc->name = CAST_MACH_NAME_TO_PORT(name);
2224 	}
2225 
2226 	dsc->disposition = result_disp;
2227 	return MACH_MSG_SUCCESS;
2228 }
2229 
2230 
2231 static mach_msg_return_t
ipc_kmsg_inflate_ool_descriptor(char * kdesc_addr,const char * udesc_addr,mach_msg_send_uctx_t * send_uctx,bool isU64)2232 ipc_kmsg_inflate_ool_descriptor(
2233 	char                   *kdesc_addr,
2234 	const char             *udesc_addr,
2235 	mach_msg_send_uctx_t   *send_uctx,
2236 	bool                    isU64)
2237 {
2238 	mach_msg_ool_descriptor64_t udesc;
2239 	mach_msg_ool_descriptor_t *kdesc;
2240 
2241 	if (isU64) {
2242 		ikm_udsc_get(&udesc, udesc_addr);
2243 	} else {
2244 		mach_msg_ool_descriptor32_t udesc32;
2245 
2246 		ikm_udsc_get(&udesc32, udesc_addr);
2247 		udesc = (mach_msg_ool_descriptor64_t){
2248 			.address     = udesc32.address,
2249 			.size        = udesc32.size,
2250 			.deallocate  = udesc32.deallocate,
2251 			.copy        = udesc32.copy,
2252 			.type        = udesc32.type,
2253 		};
2254 	}
2255 
2256 	switch (udesc.copy) {
2257 	case MACH_MSG_PHYSICAL_COPY:
2258 	case MACH_MSG_VIRTUAL_COPY:
2259 		break;
2260 	default:
2261 		return MACH_SEND_INVALID_TYPE;
2262 	}
2263 
2264 	if (udesc.size > msg_ool_size_small &&
2265 	    udesc.copy == MACH_MSG_PHYSICAL_COPY &&
2266 	    !udesc.deallocate) {
2267 		vm_size_t size;
2268 
2269 		if (round_page_overflow(udesc.size, &size) ||
2270 		    os_add_overflow(send_uctx->send_dsc_vm_size, size,
2271 		    &send_uctx->send_dsc_vm_size)) {
2272 			return MACH_MSG_VM_KERNEL;
2273 		}
2274 	}
2275 
2276 	kdesc = ikm_kdsc_zero(kdesc_addr, mach_msg_ool_descriptor_t);
2277 	kdesc->u_address  = udesc.address;
2278 	kdesc->size       = udesc.size;
2279 	kdesc->deallocate = udesc.deallocate;
2280 	kdesc->copy       = udesc.copy;
2281 	kdesc->type       = udesc.type;
2282 	return MACH_MSG_SUCCESS;
2283 }
2284 
2285 static mach_msg_return_t
ipc_kmsg_copyin_ool_descriptor(mach_msg_ool_descriptor_t * dsc,mach_vm_address_t * paddr,vm_size_t * space_needed,vm_map_t map)2286 ipc_kmsg_copyin_ool_descriptor(
2287 	mach_msg_ool_descriptor_t *dsc,
2288 	mach_vm_address_t      *paddr,
2289 	vm_size_t              *space_needed,
2290 	vm_map_t                map)
2291 {
2292 	mach_vm_size_t length = dsc->size;
2293 	vm_map_copy_t  copy = VM_MAP_COPY_NULL;
2294 
2295 	if (length == 0) {
2296 		/* nothing to do */
2297 	} else if (length > msg_ool_size_small &&
2298 	    (dsc->copy == MACH_MSG_PHYSICAL_COPY) && !dsc->deallocate) {
2299 		mach_vm_size_t    length_aligned = round_page(length);
2300 		mach_vm_address_t addr = *paddr;
2301 
2302 		/*
2303 		 * If the request is a physical copy and the source
2304 		 * is not being deallocated, then allocate space
2305 		 * in the kernel's pageable ipc copy map and copy
2306 		 * the data in.  The semantics guarantee that the
2307 		 * data will have been physically copied before
2308 		 * the send operation terminates.  Thus if the data
2309 		 * is not being deallocated, we must be prepared
2310 		 * to page if the region is sufficiently large.
2311 		 */
2312 		if (mach_copyin(dsc->u_address, (char *)addr, length)) {
2313 			return MACH_SEND_INVALID_MEMORY;
2314 		}
2315 
2316 		/*
2317 		 * The kernel ipc copy map is marked no_zero_fill.
2318 		 * If the transfer is not a page multiple, we need
2319 		 * to zero fill the balance.
2320 		 */
2321 		if (!page_aligned(length)) {
2322 			bzero((char *)addr + length, length_aligned - length);
2323 		}
2324 
2325 		if (vm_map_copyin(ipc_kernel_copy_map, addr, length,
2326 		    true, &copy) != KERN_SUCCESS) {
2327 			return MACH_MSG_VM_KERNEL;
2328 		}
2329 
2330 		*paddr        += length_aligned;
2331 		*space_needed -= length_aligned;
2332 	} else {
2333 		/*
2334 		 * Make a vm_map_copy_t of the of the data.  If the
2335 		 * data is small, this will do an optimized physical
2336 		 * copy.  Otherwise, it will do a virtual copy.
2337 		 *
2338 		 * NOTE: A virtual copy is OK if the original is being
2339 		 * deallocted, even if a physical copy was requested.
2340 		 */
2341 		switch (vm_map_copyin(map, dsc->u_address, length,
2342 		    dsc->deallocate, &copy)) {
2343 		case KERN_SUCCESS:
2344 			break;
2345 		case KERN_RESOURCE_SHORTAGE:
2346 			return MACH_MSG_VM_KERNEL;
2347 		default:
2348 			return MACH_SEND_INVALID_MEMORY;
2349 		}
2350 	}
2351 
2352 	dsc->address = copy;
2353 	return MACH_MSG_SUCCESS;
2354 }
2355 
2356 
2357 static mach_msg_return_t
ipc_kmsg_inflate_ool_ports_descriptor(char * kdesc_addr,const char * udesc_addr,mach_msg_send_uctx_t * send_uctx,bool isU64)2358 ipc_kmsg_inflate_ool_ports_descriptor(
2359 	char                   *kdesc_addr,
2360 	const char             *udesc_addr,
2361 	mach_msg_send_uctx_t   *send_uctx,
2362 	bool                    isU64)
2363 {
2364 	mach_msg_ool_ports_descriptor64_t udesc;
2365 	mach_msg_ool_ports_descriptor_t *kdesc;
2366 
2367 	if (isU64) {
2368 		ikm_udsc_get(&udesc, udesc_addr);
2369 	} else {
2370 		mach_msg_ool_ports_descriptor32_t udesc32;
2371 
2372 		ikm_udsc_get(&udesc32, udesc_addr);
2373 		udesc = (mach_msg_ool_ports_descriptor64_t){
2374 			.address     = udesc32.address,
2375 			.deallocate  = udesc32.deallocate,
2376 			.copy        = udesc32.copy,
2377 			.disposition = udesc32.disposition,
2378 			.type        = udesc32.type,
2379 			.count       = udesc32.count,
2380 		};
2381 	}
2382 
2383 	if (os_add_overflow(send_uctx->send_dsc_port_count, udesc.count,
2384 	    &send_uctx->send_dsc_port_count)) {
2385 		return MACH_SEND_TOO_LARGE;
2386 	}
2387 
2388 	kdesc = ikm_kdsc_zero(kdesc_addr, mach_msg_ool_ports_descriptor_t);
2389 	kdesc->u_address   = udesc.address;
2390 	kdesc->deallocate  = udesc.deallocate;
2391 	kdesc->copy        = udesc.copy;
2392 	kdesc->disposition = udesc.disposition;
2393 	kdesc->type        = udesc.type;
2394 	kdesc->count       = udesc.count;
2395 	return MACH_MSG_SUCCESS;
2396 }
2397 
2398 static mach_msg_return_t
ipc_kmsg_copyin_ool_ports_descriptor(mach_msg_ool_ports_descriptor_t * dsc,vm_map_t map,ipc_space_t space,ipc_port_t dest_port,ipc_kmsg_t kmsg,mach_msg_option64_t options)2399 ipc_kmsg_copyin_ool_ports_descriptor(
2400 	mach_msg_ool_ports_descriptor_t *dsc,
2401 	vm_map_t                map,
2402 	ipc_space_t             space,
2403 	ipc_port_t              dest_port,
2404 	ipc_kmsg_t              kmsg,
2405 	mach_msg_option64_t     options)
2406 {
2407 	mach_msg_type_name_t user_disp = dsc->disposition;
2408 	mach_msg_size_t      count = dsc->count;
2409 	mach_msg_type_name_t result_disp;
2410 	mach_port_array_t    array = NULL;
2411 	mach_port_name_t    *names;
2412 	mach_vm_size_t       names_size;
2413 	ipc_space_policy_t   current_policy;
2414 
2415 	result_disp = ipc_object_copyin_type(user_disp);
2416 	names_size  = count * sizeof(mach_port_name_t);
2417 
2418 	/*
2419 	 * For enhanced v2 binaries, we restrict sending OOL
2420 	 * port array with any disposition besdies COPY_SEND.
2421 	 */
2422 	current_policy = ipc_convert_msg_options_to_space(options);
2423 	if (ool_port_array_enforced &&
2424 	    ipc_should_apply_policy(current_policy, IPC_POLICY_ENHANCED_V2) &&
2425 	    (user_disp != MACH_MSG_TYPE_COPY_SEND)) {
2426 		mach_port_guard_exception(current_policy,
2427 		    MPG_PAYLOAD(MPG_FLAGS_INVALID_OPTIONS_OOL_DISP, user_disp),
2428 		    kGUARD_EXC_DESCRIPTOR_VIOLATION);
2429 
2430 		return MACH_SEND_INVALID_OPTIONS;
2431 	}
2432 
2433 	if (count) {
2434 		array = mach_port_array_alloc(count, Z_WAITOK | Z_SPRAYQTN);
2435 		if (array == NULL) {
2436 			return MACH_SEND_NO_BUFFER;
2437 		}
2438 
2439 		/* use the end of the array to store names we will copy in */
2440 		names = (mach_port_name_t *)(array + count) - count;
2441 
2442 		if (mach_copyin(dsc->u_address, names, names_size)) {
2443 			mach_port_array_free(array, count);
2444 			return MACH_SEND_INVALID_MEMORY;
2445 		}
2446 	}
2447 
2448 	if (dsc->deallocate) {
2449 		(void)mach_vm_deallocate(map, dsc->u_address, names_size);
2450 	}
2451 
2452 	for (mach_msg_size_t i = 0; i < count; i++) {
2453 		mach_port_name_t name = names[i];
2454 		ipc_port_t       port;
2455 		kern_return_t    kr;
2456 
2457 		if (!MACH_PORT_VALID(name)) {
2458 			array[i].port = CAST_MACH_NAME_TO_PORT(name);
2459 			continue;
2460 		}
2461 
2462 		kr = ipc_object_copyin(space, name, user_disp, kmsg->ikm_flags,
2463 		    IPC_COPYIN_KMSG_OOL_PORT_ARRAY_DESCRIPTOR, NULL, &port);
2464 
2465 		if (kr != KERN_SUCCESS) {
2466 			for (mach_msg_size_t j = 0; j < i; j++) {
2467 				port = array[j].port;
2468 				if (IP_VALID(port)) {
2469 					ipc_object_destroy(port, result_disp);
2470 				}
2471 			}
2472 			mach_port_array_free(array, count);
2473 
2474 			if (kr == KERN_INVALID_RIGHT) {
2475 				mach_port_guard_exception(name,
2476 				    MPG_PAYLOAD(MPG_FLAGS_SEND_INVALID_RIGHT_OOL_PORT, user_disp),
2477 				    kGUARD_EXC_SEND_INVALID_RIGHT);
2478 			}
2479 			return MACH_SEND_INVALID_RIGHT;
2480 		}
2481 
2482 		if (result_disp == MACH_MSG_TYPE_PORT_RECEIVE &&
2483 		    ipc_port_check_circularity(port, dest_port)) {
2484 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
2485 		}
2486 
2487 		array[i].port = port;
2488 	}
2489 
2490 	dsc->disposition = result_disp;
2491 	dsc->address     = array;
2492 	return MACH_MSG_SUCCESS;
2493 }
2494 
2495 
2496 static mach_msg_return_t
ipc_kmsg_inflate_guarded_port_descriptor(char * kdesc_addr,const char * udesc_addr,mach_msg_send_uctx_t * send_uctx,bool isU64)2497 ipc_kmsg_inflate_guarded_port_descriptor(
2498 	char                   *kdesc_addr,
2499 	const char             *udesc_addr,
2500 	mach_msg_send_uctx_t   *send_uctx,
2501 	bool                    isU64)
2502 {
2503 	mach_msg_guarded_port_descriptor64_t udesc;
2504 	mach_msg_guarded_port_descriptor_t *kdesc;
2505 
2506 	if (isU64) {
2507 		ikm_udsc_get(&udesc, udesc_addr);
2508 	} else {
2509 		mach_msg_guarded_port_descriptor32_t udesc32;
2510 
2511 		ikm_udsc_get(&udesc32, udesc_addr);
2512 		udesc = (mach_msg_guarded_port_descriptor64_t){
2513 			.context     = udesc32.context,
2514 			.flags       = udesc32.flags,
2515 			.disposition = udesc32.disposition,
2516 			.type        = udesc32.type,
2517 			.name        = udesc32.name,
2518 		};
2519 	}
2520 
2521 	if (os_add_overflow(send_uctx->send_dsc_port_count, 1,
2522 	    &send_uctx->send_dsc_port_count)) {
2523 		return MACH_SEND_TOO_LARGE;
2524 	}
2525 
2526 	/* Only MACH_MSG_TYPE_MOVE_RECEIVE is supported for now */
2527 	if (udesc.disposition != MACH_MSG_TYPE_MOVE_RECEIVE) {
2528 		return MACH_SEND_INVALID_TYPE;
2529 	}
2530 
2531 	if (!udesc.flags ||
2532 	    ((udesc.flags & ~MACH_MSG_GUARD_FLAGS_MASK) != 0) ||
2533 	    ((udesc.flags & MACH_MSG_GUARD_FLAGS_UNGUARDED_ON_SEND) && (udesc.context != 0))) {
2534 		return MACH_SEND_INVALID_TYPE;
2535 	}
2536 
2537 	kdesc = ikm_kdsc_zero(kdesc_addr, mach_msg_guarded_port_descriptor_t);
2538 	kdesc->u_context   = udesc.context;
2539 	kdesc->flags       = udesc.flags;
2540 	kdesc->disposition = udesc.disposition;
2541 	kdesc->type        = udesc.type;
2542 	kdesc->u_name      = udesc.name;
2543 	return MACH_MSG_SUCCESS;
2544 }
2545 
2546 static mach_msg_return_t
ipc_kmsg_copyin_guarded_port_descriptor(mach_msg_guarded_port_descriptor_t * dsc,ipc_space_t space,ipc_port_t dest_port,ipc_kmsg_t kmsg)2547 ipc_kmsg_copyin_guarded_port_descriptor(
2548 	mach_msg_guarded_port_descriptor_t *dsc,
2549 	ipc_space_t             space,
2550 	ipc_port_t              dest_port,
2551 	ipc_kmsg_t              kmsg)
2552 {
2553 	mach_msg_type_name_t   user_disp = dsc->disposition;
2554 	mach_port_name_t       name = dsc->u_name;
2555 	mach_msg_type_name_t   result_disp;
2556 	ipc_port_t             port;
2557 	kern_return_t          kr;
2558 
2559 	result_disp = ipc_object_copyin_type(user_disp);
2560 	if (MACH_PORT_VALID(name)) {
2561 		kr = ipc_object_copyin(space, name, user_disp, kmsg->ikm_flags,
2562 		    IPC_COPYIN_KMSG_GUARDED_PORT_DESCRIPTOR, dsc, &port);
2563 		if (kr != KERN_SUCCESS) {
2564 			if (kr == KERN_INVALID_RIGHT) {
2565 				mach_port_guard_exception(name,
2566 				    MPG_PAYLOAD(MPG_FLAGS_SEND_INVALID_RIGHT_GUARDED, user_disp),
2567 				    kGUARD_EXC_SEND_INVALID_RIGHT);
2568 			}
2569 			return MACH_SEND_INVALID_RIGHT;
2570 		}
2571 
2572 		if (result_disp == MACH_MSG_TYPE_PORT_RECEIVE &&
2573 		    ipc_port_check_circularity(port, dest_port)) {
2574 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
2575 		}
2576 		dsc->name = port;
2577 	} else {
2578 		dsc->name = CAST_MACH_NAME_TO_PORT(name);
2579 	}
2580 
2581 	/* dsc->flags were possibly modified by ipc_object_copyin() */
2582 	dsc->disposition = result_disp;
2583 	dsc->u_name      = 0;
2584 	return MACH_MSG_SUCCESS;
2585 }
2586 
2587 
2588 static mach_msg_return_t
ipc_kmsg_inflate_descriptor(char * kdesc,const char * udesc,mach_msg_send_uctx_t * send_uctx,bool isU64)2589 ipc_kmsg_inflate_descriptor(
2590 	char                   *kdesc,
2591 	const char             *udesc,
2592 	mach_msg_send_uctx_t   *send_uctx,
2593 	bool                    isU64)
2594 {
2595 	switch (ikm_udsc_type(udesc)) {
2596 	case MACH_MSG_PORT_DESCRIPTOR:
2597 		return ipc_kmsg_inflate_port_descriptor(kdesc, udesc, send_uctx);
2598 	case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
2599 	case MACH_MSG_OOL_DESCRIPTOR:
2600 		return ipc_kmsg_inflate_ool_descriptor(kdesc, udesc, send_uctx, isU64);
2601 	case MACH_MSG_OOL_PORTS_DESCRIPTOR:
2602 		return ipc_kmsg_inflate_ool_ports_descriptor(kdesc, udesc, send_uctx, isU64);
2603 	case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
2604 		return ipc_kmsg_inflate_guarded_port_descriptor(kdesc, udesc, send_uctx, isU64);
2605 	default:
2606 		/* verified by ipc_kmsg_measure_descriptors_from_user() */
2607 		__builtin_unreachable();
2608 	}
2609 }
2610 
2611 static mach_msg_return_t
ipc_kmsg_inflate_descriptors(char * const descs,mach_msg_send_uctx_t * send_uctx,bool isU64)2612 ipc_kmsg_inflate_descriptors(
2613 	char             *const descs,
2614 	mach_msg_send_uctx_t   *send_uctx,
2615 	bool                    isU64)
2616 {
2617 	const mach_msg_size_t   desc_count = send_uctx->send_dsc_count;
2618 	const mach_msg_size_t   desc_ksize = desc_count * KERNEL_DESC_SIZE;
2619 	const mach_msg_size_t   desc_usize = send_uctx->send_dsc_usize;
2620 	char                   *kdesc      = descs;
2621 	char                   *udesc      = descs;
2622 	mach_msg_return_t       mr         = MACH_MSG_SUCCESS;
2623 
2624 	if (__probable(desc_count <= 64)) {
2625 		/*
2626 		 * If there are less than 64 descriptors, then we can use
2627 		 * the udesc_mask to know by how much to shift data,
2628 		 * and inflate right to left.
2629 		 */
2630 		kdesc += desc_ksize;
2631 		udesc += desc_usize;
2632 
2633 		for (uint64_t bit = 1ull << (desc_count - 1); bit; bit >>= 1) {
2634 			kdesc -= KERNEL_DESC_SIZE;
2635 			if (send_uctx->send_dsc_mask & bit) {
2636 				udesc -= USER_DESC_SIZE_MAX;
2637 			} else {
2638 				udesc -= USER_DESC_SIZE_MIN;
2639 			}
2640 			mr = ipc_kmsg_inflate_descriptor(kdesc, udesc,
2641 			    send_uctx, isU64);
2642 			if (mr != MACH_MSG_SUCCESS) {
2643 				return mr;
2644 			}
2645 		}
2646 	} else {
2647 		/*
2648 		 * Else, move all descriptors at the end of the buffer,
2649 		 * and inflate them left to right.
2650 		 */
2651 
2652 		udesc += desc_ksize - desc_usize;
2653 		memmove(udesc, kdesc, desc_usize);
2654 
2655 		for (mach_msg_size_t i = 0; i < desc_count; i++) {
2656 			mach_msg_size_t dsize;
2657 
2658 			dsize = ikm_user_desc_size(ikm_udsc_type(udesc), isU64);
2659 			mr = ipc_kmsg_inflate_descriptor(kdesc, udesc,
2660 			    send_uctx, isU64);
2661 			if (mr != MACH_MSG_SUCCESS) {
2662 				return mr;
2663 			}
2664 			udesc += dsize;
2665 			kdesc += KERNEL_DESC_SIZE;
2666 		}
2667 	}
2668 
2669 	return MACH_MSG_SUCCESS;
2670 }
2671 
2672 static inline bool
ipc_kmsg_user_desc_type_is_valid(mach_msg_descriptor_type_t type,mach_msg_option64_t options)2673 ipc_kmsg_user_desc_type_is_valid(
2674 	mach_msg_descriptor_type_t type,
2675 	mach_msg_option64_t        options)
2676 {
2677 	switch (type) {
2678 	case MACH_MSG_PORT_DESCRIPTOR:
2679 	case MACH_MSG_OOL_DESCRIPTOR:
2680 	case MACH_MSG_OOL_PORTS_DESCRIPTOR:
2681 		return true;
2682 	case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
2683 	case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
2684 		/*
2685 		 * only allow port and memory descriptors for kobjects and
2686 		 * driverkit.
2687 		 */
2688 		return !(options & (MACH64_SEND_KOBJECT_CALL | MACH64_SEND_DK_CALL));
2689 	default:
2690 		return false;
2691 	}
2692 }
2693 
2694 /*!
2695  * @brief
2696  * Quickly validate and measure the layout of user descriptors.
2697  *
2698  * @description
2699  * This function fills:
2700  * - the send_dsc_usize field with the size of user descriptors,
2701  * - the send_dsc_mask field representing which of the first 64
2702  *   first descriptors whose size is 12 (bit is 0) or 16 (bit is 1).
2703  *
2704  * @param addr          the address of where user descriptors start.
2705  * @param size          the size of the data to parse (descriptors might
2706  *                      be less, but can't be more).
2707  * @param send_uctx     the context used for this MACH_SEND_MSG operation.
2708  * @param options       the options for this MACH_SEND_MSG operation.
2709  * @param isU64         whether the current user task is 64 bit.
2710  * @returns
2711  * - MACH_MSG_SUCCESS   if parsing was successful.
2712  * - MACH_SEND_MSG_TOO_SMALL
2713  *                      if there wasn't enough data to parse
2714  *                      send_dsc_count descriptors
2715  * - MACH_SEND_INVALID_TYPE
2716  *                      if descriptors types parsed aren't valid
2717  *                      or allowed by policy.
2718  */
2719 __result_use_check
2720 static mach_msg_return_t
ipc_kmsg_measure_descriptors_from_user(vm_address_t addr,mach_msg_size_t size,mach_msg_send_uctx_t * send_uctx,mach_msg_option64_t options,bool isU64)2721 ipc_kmsg_measure_descriptors_from_user(
2722 	vm_address_t            addr,
2723 	mach_msg_size_t         size,
2724 	mach_msg_send_uctx_t   *send_uctx,
2725 	mach_msg_option64_t     options,
2726 	bool                    isU64)
2727 {
2728 	mach_msg_size_t dcnt = send_uctx->send_dsc_count;
2729 	mach_msg_size_t dpos = 0;
2730 	uint64_t        mask = 0;
2731 	uint64_t        bit  = 1;
2732 
2733 	for (mach_msg_size_t i = 0; i < dcnt; i++, bit <<= 1) {
2734 		mach_msg_descriptor_type_t dtype;
2735 		mach_msg_size_t dsize;
2736 
2737 		if (dpos + USER_DESC_SIZE_MIN > size) {
2738 			return MACH_SEND_MSG_TOO_SMALL;
2739 		}
2740 		dtype = ikm_udsc_type(addr + dpos);
2741 		if (!ipc_kmsg_user_desc_type_is_valid(dtype, options)) {
2742 			return MACH_SEND_INVALID_TYPE;
2743 		}
2744 
2745 		if (dtype == MACH_MSG_OOL_PORTS_DESCRIPTOR) {
2746 			/*
2747 			 * No need to check for int overflow here, since due to kmsg
2748 			 * restrictions and sanitization, it's not possible to have
2749 			 * more than 2**32-1 arrays.
2750 			 */
2751 			send_uctx->send_dsc_port_arrays_count++;
2752 		}
2753 
2754 		dsize = ikm_user_desc_size(dtype, isU64);
2755 		if (dsize == USER_DESC_SIZE_MAX) {
2756 			mask |= bit;
2757 		}
2758 		dpos += dsize;
2759 		if (dpos > size) {
2760 			return MACH_SEND_MSG_TOO_SMALL;
2761 		}
2762 	}
2763 
2764 	send_uctx->send_dsc_usize = dpos;
2765 	send_uctx->send_dsc_mask  = mask;
2766 	return MACH_MSG_SUCCESS;
2767 }
2768 
2769 /*
2770  *	Routine:	ipc_kmsg_copyin_body
2771  *	Purpose:
2772  *		"Copy-in" port rights and out-of-line memory
2773  *		in the message body.
2774  *
2775  *		In all failure cases, the message is left holding
2776  *		no rights or memory.  However, the message buffer
2777  *		is not deallocated.  If successful, the message
2778  *		contains a valid destination port.
2779  *	Conditions:
2780  *		Nothing locked.
2781  *	Returns:
2782  *		MACH_MSG_SUCCESS	Successful copyin.
2783  *		MACH_SEND_INVALID_MEMORY	Can't grab out-of-line memory.
2784  *		MACH_SEND_INVALID_RIGHT	Can't copyin port right in body.
2785  *		MACH_SEND_INVALID_TYPE	Bad type specification.
2786  *		MACH_SEND_MSG_TOO_SMALL	Body is too small for types/data.
2787  *		MACH_SEND_INVALID_RT_OOL_SIZE OOL Buffer too large for RT
2788  *		MACH_MSG_INVALID_RT_DESCRIPTOR Dealloc and RT are incompatible
2789  */
2790 
2791 static mach_msg_return_t
ipc_kmsg_copyin_body(ipc_kmsg_t kmsg,mach_msg_send_uctx_t * send_uctx,ipc_space_t space,vm_map_t map,mach_msg_option64_t options)2792 ipc_kmsg_copyin_body(
2793 	ipc_kmsg_t              kmsg,
2794 	mach_msg_send_uctx_t   *send_uctx,
2795 	ipc_space_t             space,
2796 	vm_map_t                map,
2797 	mach_msg_option64_t     options)
2798 {
2799 	mach_msg_type_number_t  dsc_count = send_uctx->send_dsc_count;
2800 	vm_size_t               psize = send_uctx->send_dsc_vm_size;
2801 	mach_vm_address_t       paddr = 0;
2802 	mach_msg_header_t      *hdr   = ikm_header(kmsg);
2803 	mach_msg_kbase_t       *kbase = mach_msg_header_to_kbase(hdr);
2804 	ipc_port_t              dest_port = hdr->msgh_remote_port;
2805 
2806 	assert(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX);
2807 
2808 	/*
2809 	 * Allocate space in the pageable kernel ipc copy map for all the
2810 	 * ool data that is to be physically copied.  Map is marked wait for
2811 	 * space.
2812 	 */
2813 	if (psize) {
2814 		kern_return_t kr;
2815 
2816 		kr  = mach_vm_allocate_kernel(ipc_kernel_copy_map, &paddr, psize,
2817 		    VM_MAP_KERNEL_FLAGS_ANYWHERE(.vm_tag = VM_KERN_MEMORY_IPC));
2818 		if (kr != KERN_SUCCESS) {
2819 			ipc_kmsg_clean_header(kmsg);
2820 			return MACH_MSG_VM_KERNEL;
2821 		}
2822 	}
2823 
2824 	for (mach_msg_size_t copied_in_dscs = 0; copied_in_dscs < dsc_count; copied_in_dscs++) {
2825 		mach_msg_kdescriptor_t *kdesc = &kbase->msgb_dsc_array[copied_in_dscs];
2826 		mach_msg_return_t mr;
2827 
2828 		switch (mach_msg_kdescriptor_type(kdesc)) {
2829 		case MACH_MSG_PORT_DESCRIPTOR:
2830 			mr = ipc_kmsg_copyin_port_descriptor(&kdesc->kdesc_port,
2831 			    space, dest_port, kmsg);
2832 			break;
2833 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
2834 		case MACH_MSG_OOL_DESCRIPTOR:
2835 			mr = ipc_kmsg_copyin_ool_descriptor(&kdesc->kdesc_memory,
2836 			    &paddr, &psize, map);
2837 			break;
2838 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
2839 			mr = ipc_kmsg_copyin_ool_ports_descriptor(&kdesc->kdesc_port_array,
2840 			    map, space, dest_port, kmsg, options);
2841 			break;
2842 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
2843 			mr = ipc_kmsg_copyin_guarded_port_descriptor(&kdesc->kdesc_guarded_port,
2844 			    space, dest_port, kmsg);
2845 			break;
2846 		default:
2847 			__builtin_unreachable();
2848 		}
2849 
2850 		if (MACH_MSG_SUCCESS != mr) {
2851 			/* clean from start of message descriptors to copied_in_dscs */
2852 			ipc_kmsg_clean_header(kmsg);
2853 			ipc_kmsg_clean_descriptors(kbase->msgb_dsc_array,
2854 			    copied_in_dscs);
2855 			if (psize) {
2856 				kmem_free(ipc_kernel_copy_map, paddr, psize);
2857 			}
2858 			return mr;
2859 		}
2860 	}
2861 
2862 	assert(psize == 0);
2863 	return MACH_MSG_SUCCESS;
2864 }
2865 
2866 /*
2867  *	Routine:	ipc_kmsg_get_and_inflate_from_user()
2868  *	Purpose:
2869  *		Copies in user message (and aux) to the allocated
2870  *		kernel message buffer, and expands header and descriptor
2871  *		into "kernel" format.
2872  *
2873  *	Conditions:
2874  *		msg up to sizeof(mach_msg_user_header_t) has been previously
2875  *		copied in, and number of descriptors has been made known.
2876  *
2877  *		if send_aux_size is not 0, mach_msg_validate_data_vectors()
2878  *		guarantees that aux_size must be larger than
2879  *		mach_msg_aux_header_t.
2880  */
2881 static mach_msg_return_t
ipc_kmsg_get_and_inflate_from_user(ipc_kmsg_t kmsg,mach_msg_send_uctx_t * send_uctx,mach_msg_header_t * khdr,vm_map_t map,mach_msg_option64_t options)2882 ipc_kmsg_get_and_inflate_from_user(
2883 	ipc_kmsg_t              kmsg,
2884 	mach_msg_send_uctx_t   *send_uctx,
2885 	mach_msg_header_t      *khdr,
2886 	vm_map_t                map,
2887 	mach_msg_option64_t     options)
2888 {
2889 	bool                    isU64 = (map->max_offset > VM_MAX_ADDRESS);
2890 	mach_msg_user_header_t *uhdr  = &send_uctx->send_header;
2891 	char                   *kdesc = (char *)khdr; /* where descriptors start */
2892 	char                   *kbody = NULL;         /* where the body starts   */
2893 	mach_msg_size_t         upos  = 0;            /* copyin cursor so far    */
2894 	mach_msg_size_t         usize = send_uctx->send_msg_size;
2895 	mach_msg_return_t       mr    = MACH_MSG_SUCCESS;
2896 
2897 	/*
2898 	 * Step 1: inflate the header in kernel representation
2899 	 *
2900 	 * Notable steps:
2901 	 * - the msgh_bits are normalized
2902 	 * - the msgh_size is incorrect until we measure descriptors
2903 	 */
2904 	*khdr = (mach_msg_header_t){
2905 		.msgh_bits         = uhdr->msgh_bits & MACH_MSGH_BITS_USER,
2906 		.msgh_size         = usize + USER_HEADER_SIZE_DELTA,
2907 		.msgh_remote_port  = CAST_MACH_NAME_TO_PORT(uhdr->msgh_remote_port),
2908 		.msgh_local_port   = CAST_MACH_NAME_TO_PORT(uhdr->msgh_local_port),
2909 		.msgh_voucher_port = uhdr->msgh_voucher_port,
2910 		.msgh_id           = uhdr->msgh_id,
2911 	};
2912 
2913 	if (uhdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
2914 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(khdr);
2915 
2916 		kbase->msgb_dsc_count = send_uctx->send_dsc_count;
2917 		kdesc = (char *)(kbase + 1);
2918 		upos  = sizeof(mach_msg_user_base_t);
2919 	} else {
2920 		kdesc = (char *)(khdr + 1);
2921 		upos  = sizeof(mach_msg_user_header_t);
2922 	}
2923 	if (ikm_is_linear(kmsg)) {
2924 		kbody = (char *)kdesc +
2925 		    send_uctx->send_dsc_count * KERNEL_DESC_SIZE;
2926 	} else {
2927 		kbody = kmsg->ikm_udata;
2928 	}
2929 
2930 	/*
2931 	 * Step 2: inflate descriptors in kernel representation
2932 	 *
2933 	 * Notable steps:
2934 	 * - for linear messages we will copy the entire body too at once.
2935 	 * - the msgh_size will be updated for the inflated size of descriptors.
2936 	 */
2937 	if (send_uctx->send_dsc_count) {
2938 		mach_msg_size_t desc_count = send_uctx->send_dsc_count;
2939 		mach_msg_size_t desc_ksize = desc_count * KERNEL_DESC_SIZE;
2940 		mach_msg_size_t copyin_size;
2941 
2942 		/*
2943 		 * If kmsg is linear, copy in all data in the buffer.
2944 		 * Otherwise, first copyin until the end of descriptors
2945 		 * or the message, whichever comes first.
2946 		 */
2947 		if (ikm_is_linear(kmsg)) {
2948 			copyin_size = usize - upos;
2949 		} else {
2950 			copyin_size = MIN(desc_ksize, usize - upos);
2951 		}
2952 		assert((vm_offset_t)kdesc + copyin_size <= ikm_kdata_end(kmsg));
2953 
2954 		if (copyinmsg(send_uctx->send_msg_addr + upos, kdesc, copyin_size)) {
2955 			return MACH_SEND_INVALID_DATA;
2956 		}
2957 		upos += copyin_size;
2958 
2959 		/*
2960 		 * pre-validate and measure the descriptors user claims
2961 		 * to have by checking their size and type.
2962 		 */
2963 		mr = ipc_kmsg_measure_descriptors_from_user((vm_address_t)kdesc,
2964 		    copyin_size, send_uctx, options, isU64);
2965 		if (mr != MACH_MSG_SUCCESS) {
2966 			return mr;
2967 		}
2968 		khdr->msgh_size += desc_ksize - send_uctx->send_dsc_usize;
2969 
2970 		/*
2971 		 * If the descriptors user size is smaller than their
2972 		 * kernel size, we copied in some piece of body that we need to
2973 		 * relocate, and we need to inflate descriptors.
2974 		 */
2975 		if (send_uctx->send_dsc_usize != desc_ksize) {
2976 			memmove(kbody, kdesc + send_uctx->send_dsc_usize,
2977 			    copyin_size - send_uctx->send_dsc_usize);
2978 			kbody += copyin_size - send_uctx->send_dsc_usize;
2979 		}
2980 
2981 		mr = ipc_kmsg_inflate_descriptors(kdesc, send_uctx,
2982 		    map->max_offset > VM_MAX_ADDRESS);
2983 		if (mr != MACH_MSG_SUCCESS) {
2984 			return mr;
2985 		}
2986 	}
2987 
2988 	/*
2989 	 * Step 3: copy pure user data remaining.
2990 	 */
2991 	if (upos < usize &&
2992 	    copyinmsg(send_uctx->send_msg_addr + upos, kbody, usize - upos)) {
2993 		return MACH_SEND_INVALID_DATA;
2994 	}
2995 	kbody += usize - upos;
2996 
2997 	/*
2998 	 * Step 4: copy auxiliary data if any
2999 	 */
3000 	if (send_uctx->send_aux_size) {
3001 		mach_msg_aux_header_t *aux_hdr  = ikm_aux_header(kmsg);
3002 		mach_msg_size_t        aux_size = send_uctx->send_aux_size;
3003 
3004 		assert((vm_offset_t)kbody <= (vm_offset_t)aux_hdr);
3005 		assert(aux_size >= sizeof(aux_hdr[0]));
3006 
3007 		/* initialize aux data header */
3008 		aux_hdr->msgdh_size = send_uctx->send_aux_size;
3009 		aux_hdr->msgdh_reserved = 0;
3010 
3011 		/* copyin aux data after the header */
3012 		if (aux_size > sizeof(aux_hdr[0]) &&
3013 		    copyinmsg(send_uctx->send_aux_addr + sizeof(*aux_hdr),
3014 		    aux_hdr + 1, aux_size - sizeof(*aux_hdr))) {
3015 			return MACH_SEND_INVALID_DATA;
3016 		}
3017 	}
3018 
3019 	return MACH_MSG_SUCCESS;
3020 }
3021 
3022 /*
3023  *	Routine:	ipc_kmsg_copyin_from_user
3024  *	Purpose:
3025  *		"Copy-in" port rights and out-of-line memory
3026  *		in the message.
3027  *
3028  *		In all failure cases, the message is left holding
3029  *		no rights or memory.  However, the message buffer
3030  *		is not deallocated.  If successful, the message
3031  *		contains a valid destination port.
3032  *	Conditions:
3033  *		Nothing locked.
3034  *	Returns:
3035  *		MACH_MSG_SUCCESS	Successful copyin.
3036  *		MACH_SEND_INVALID_HEADER Illegal value in the message header bits.
3037  *		MACH_SEND_INVALID_DEST	Can't copyin destination port.
3038  *		MACH_SEND_INVALID_REPLY	Can't copyin reply port.
3039  *		MACH_SEND_INVALID_MEMORY	Can't grab out-of-line memory.
3040  *		MACH_SEND_INVALID_RIGHT	Can't copyin port right in body.
3041  *		MACH_SEND_INVALID_TYPE	Bad type specification.
3042  *		MACH_SEND_MSG_TOO_SMALL	Body is too small for types/data.
3043  */
3044 
3045 mach_msg_return_t
ipc_kmsg_copyin_from_user(ipc_kmsg_t kmsg,mach_msg_send_uctx_t * send_uctx,ipc_space_t space,vm_map_t map,mach_msg_priority_t priority,mach_msg_option64_t * option64p)3046 ipc_kmsg_copyin_from_user(
3047 	ipc_kmsg_t              kmsg,
3048 	mach_msg_send_uctx_t   *send_uctx,
3049 	ipc_space_t             space,
3050 	vm_map_t                map,
3051 	mach_msg_priority_t     priority,
3052 	mach_msg_option64_t    *option64p)
3053 {
3054 	mach_msg_option64_t options = *option64p;
3055 	mach_msg_header_t  *hdr = ikm_header(kmsg);
3056 	mach_msg_return_t   mr;
3057 
3058 	mr = ipc_validate_kmsg_header_schema_from_user(&send_uctx->send_header,
3059 	    send_uctx->send_dsc_count, options);
3060 	if (mr != MACH_MSG_SUCCESS) {
3061 		return mr;
3062 	}
3063 
3064 	mr = ipc_kmsg_get_and_inflate_from_user(kmsg, send_uctx,
3065 	    hdr, map, options);
3066 	if (mr != MACH_MSG_SUCCESS) {
3067 		return mr;
3068 	}
3069 
3070 	mr = ipc_validate_kmsg_schema_from_user(hdr, send_uctx, options);
3071 	if (mr != MACH_MSG_SUCCESS) {
3072 		return mr;
3073 	}
3074 
3075 	/* copyin_header may add MACH64_SEND_ALWAYS option */
3076 	mr = ipc_kmsg_copyin_header(kmsg, space, priority, option64p);
3077 	if (mr != MACH_MSG_SUCCESS) {
3078 		return mr;
3079 	}
3080 	options = *option64p;
3081 
3082 	mr = ipc_validate_kmsg_header_from_user(hdr, send_uctx, options);
3083 	if (mr != MACH_MSG_SUCCESS) {
3084 		/* no descriptors have been copied in yet */
3085 		ipc_kmsg_clean_header(kmsg);
3086 		return mr;
3087 	}
3088 
3089 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_SEND) | DBG_FUNC_NONE,
3090 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
3091 	    (uintptr_t)hdr->msgh_bits,
3092 	    (uintptr_t)hdr->msgh_id,
3093 	    VM_KERNEL_ADDRPERM((uintptr_t)unsafe_convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg))),
3094 	    0);
3095 
3096 	DEBUG_KPRINT_SYSCALL_IPC("ipc_kmsg_copyin_from_user header:\n%.8x\n%.8x\n%p\n%p\n%p\n%.8x\n",
3097 	    hdr->msgh_size,
3098 	    hdr->msgh_bits,
3099 	    hdr->msgh_remote_port,
3100 	    hdr->msgh_local_port,
3101 	    ipc_kmsg_get_voucher_port(kmsg),
3102 	    hdr->msgh_id);
3103 
3104 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
3105 		mr = ipc_kmsg_copyin_body(kmsg, send_uctx, space, map, options);
3106 	}
3107 
3108 	return mr;
3109 }
3110 
3111 /** @} */
3112 #pragma mark ipc_kmsg copyout and deflate (to user)
3113 /*!
3114  * @defgroup IPC kmsg copyout and deflate functions
3115  * @{
3116  *
3117  * IPC (right) copyout
3118  * ~~~~~~~~~~~~~~~~~~~
3119  *
3120  * This is the operation that turns kernel objects like IPC ports or
3121  * vm_map_copy_t and turns them into port names or userspace VM addresses.
3122  *
3123  * This is done on an IPC kmsg in "kernel representation" and just replace
3124  * kernel pointers with scalar values only meaningful to userspace in place.
3125  *
3126  * There are several copyout machineries that will drive this operation:
3127  * - @c ipc_kmsg_copyout() for the regular case,
3128  * - @c ipc_kmsg_copyout_pseudo() for pseud-receive,
3129  * - @c ipc_kmsg_copyout_dest_to_user() for receive error cases
3130  *   where the actual message is destroyed and a minimal message
3131  *   is received instead.
3132  *
3133  * Copied out messages do not hold any "right" in the "kdata" part of the
3134  * message anymore.
3135  *
3136  *
3137  * IPC kmsg deflate
3138  * ~~~~~~~~~~~~~~~~
3139  *
3140  * This is the operation that turns a message in kernel representation,
3141  * but with rights copied out, into user representation.
3142  *
3143  * This is driven by @c ipc_kmsg_deflate() which will:
3144  * - convert the message header into user layout (mach_msg_user_header_t),
3145  * - convert the descriptors into user layout,
3146  * - generate receive time parts of the trailer and convert it to user layout.
3147  *
3148  * This operation mangles the payload of the kmsg, making most of the kmsg
3149  * functions have undefined behavior. The only valid things to do with
3150  * a deflated message is to copy the bytes back to userspace and destroy
3151  * the message with @c ipc_kmsg_free().
3152  *
3153  *
3154  * Note that deflation will maintain the position of the pure data bodies
3155  * trailers and auxiliary data payloads. The deflation causes the header
3156  * desscriptors to contract by moving the start of the message rather
3157  * than by shortening it.
3158  *
3159  * As a result, it means that deflation works left-to-right (end toward start),
3160  * starting with the trailer, then descriptors and header last.
3161  * (@see @c ipc_kmsg_deflate() and @c ipc_kmsg_deflate_descriptors()).
3162  *
3163  *
3164  * IPC kmsg "put"
3165  * ~~~~~~~~~~~~~~
3166  *
3167  * This denotes the operation that copies the paylaod of an IPC kmsg into the
3168  * provided buffer, ending with the IPC kmsg being freed.
3169  *
3170  * There are two possible variants of this operation:
3171  *
3172  * - @c ipc_kmsg_put_to_kernel() which uses a kernel provided buffer,
3173  *   and performs no transformation. It is used for kernel upcall replies
3174  *   (see kernel_mach_msg_rpc()).
3175  *
3176  * - @c ipc_kmsg_put_to_user() which uses a user provided buffer.
3177  *   The message will undergo copyout and deflation before the put to user
3178  *   actually happens. This is used by the user mach_msg() receive paths.
3179  */
3180 
3181 /*!
3182  * @typedef ikm_deflate_context_t
3183  *
3184  * @brief
3185  * Data structure holding the various parameters during a deflate operation.
3186  *
3187  * @field dctx_uhdr             the pointer to the start of the user header
3188  * @field dctx_udata            the pointer to the pure data parts or NULL
3189  * @field dctx_trailer          the pointer to the trailer,
3190  *                              or NULL if doing a pseudo-receive.
3191  * @field dctx_aux_hdr          the pointer to the auxiliary data or NULL.
3192  *
3193  * @field dctx_uhdr_size        the number of bytes to copyout from dctx_uhdr.
3194  * @field dctx_udata_size       the number of bytes to copyout from dctx_udata,
3195  *                              or 0 if dctx_udata is NULL.
3196  * @field dctx_trailer_size     the size of the trailer,
3197  *                              or 0 if dctx_trailer is NULL.
3198  * @field dctx_aux_size         the size of the auxiliary data payload,
3199  *                              or 0 if dctx_aux_hdr is NULL.
3200  * @field dctx_isU64            whether the user process receiving the message
3201  *                              is 32 or 64bits.
3202  */
3203 typedef struct {
3204 	char                   *dctx_uhdr;
3205 	char                   *dctx_udata;
3206 	mach_msg_max_trailer_t *dctx_trailer;
3207 	mach_msg_aux_header_t  *dctx_aux_hdr;
3208 	mach_msg_size_t         dctx_uhdr_size;
3209 	mach_msg_size_t         dctx_udata_size;
3210 	mach_msg_size_t         dctx_trailer_size;
3211 	mach_msg_size_t         dctx_aux_size;
3212 	bool                    dctx_isU64;
3213 } ikm_deflate_context_t;
3214 
3215 #define ipc_kmsg_deflate_put(udesc_end, value) \
3216 	memcpy((udesc_end) - sizeof(*(value)), (value), sizeof(*(value)))
3217 
3218 /*
3219  *	Routine:	ipc_kmsg_copyout_header
3220  *	Purpose:
3221  *		"Copy-out" port rights in the header of a message.
3222  *		Operates atomically; if it doesn't succeed the
3223  *		message header and the space are left untouched.
3224  *		If it does succeed the remote/local port fields
3225  *		contain port names instead of object pointers,
3226  *		and the bits field is updated.
3227  *	Conditions:
3228  *		Nothing locked.
3229  *	Returns:
3230  *		MACH_MSG_SUCCESS	Copied out port rights.
3231  *		MACH_RCV_INVALID_NOTIFY
3232  *			Notify is non-null and doesn't name a receive right.
3233  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
3234  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
3235  *			The space is dead.
3236  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
3237  *			No room in space for another name.
3238  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
3239  *			Couldn't allocate memory for the reply port.
3240  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
3241  *			Couldn't allocate memory for the dead-name request.
3242  */
3243 static mach_msg_return_t
ipc_kmsg_copyout_header(ipc_kmsg_t kmsg,mach_msg_header_t * msg,ipc_space_t space,mach_msg_option64_t option)3244 ipc_kmsg_copyout_header(
3245 	ipc_kmsg_t              kmsg,
3246 	mach_msg_header_t      *msg,
3247 	ipc_space_t             space,
3248 	mach_msg_option64_t     option)
3249 {
3250 	mach_msg_bits_t mbits = msg->msgh_bits;
3251 	ipc_port_t dest = msg->msgh_remote_port;
3252 
3253 	mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
3254 	mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
3255 	mach_msg_type_name_t voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
3256 	ipc_port_t reply = msg->msgh_local_port;
3257 	ipc_port_t release_reply_port = IP_NULL;
3258 	mach_port_name_t dest_name, reply_name;
3259 
3260 	ipc_port_t voucher = ipc_kmsg_get_voucher_port(kmsg);
3261 	uintptr_t voucher_addr = 0;
3262 	ipc_port_t release_voucher_port = IP_NULL;
3263 	mach_port_name_t voucher_name;
3264 
3265 	uint32_t entries_held = 0;
3266 	boolean_t need_write_lock = FALSE;
3267 	kern_return_t kr;
3268 
3269 	assert(IP_VALID(dest));
3270 
3271 	/*
3272 	 * While we still hold a reference on the received-from port,
3273 	 * process all send-possible notfications we received along with
3274 	 * the message.
3275 	 */
3276 	ipc_port_spnotify(dest);
3277 
3278 	/*
3279 	 * Reserve any potentially needed entries in the target space.
3280 	 * We'll free any unused before unlocking the space.
3281 	 */
3282 	if (IP_VALID(reply)) {
3283 		entries_held++;
3284 		need_write_lock = TRUE;
3285 	}
3286 	if (IP_VALID(voucher)) {
3287 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
3288 
3289 		if ((option & MACH_RCV_VOUCHER) != 0) {
3290 			entries_held++;
3291 		}
3292 		need_write_lock = TRUE;
3293 		voucher_addr = unsafe_convert_port_to_voucher(voucher);
3294 	}
3295 
3296 	if (need_write_lock) {
3297 handle_reply_again:
3298 		is_write_lock(space);
3299 
3300 		while (entries_held) {
3301 			if (!is_active(space)) {
3302 				is_write_unlock(space);
3303 				return MACH_RCV_HEADER_ERROR |
3304 				       MACH_MSG_IPC_SPACE;
3305 			}
3306 
3307 			kr = ipc_entries_hold(space, entries_held);
3308 			if (KERN_SUCCESS == kr) {
3309 				break;
3310 			}
3311 
3312 			kr = ipc_entry_grow_table(space, ITS_SIZE_NONE);
3313 			if (KERN_SUCCESS != kr) {
3314 				return MACH_RCV_HEADER_ERROR |
3315 				       MACH_MSG_IPC_SPACE;
3316 			}
3317 			/* space was unlocked and relocked - retry */
3318 		}
3319 
3320 		/* Handle reply port. */
3321 		if (IP_VALID(reply)) {
3322 			ipc_port_t reply_subst = IP_NULL;
3323 			ipc_object_label_t label;
3324 			ipc_entry_t entry;
3325 
3326 			label = ip_mq_lock_check_aligned(reply);
3327 
3328 			/* Is the reply port still active and allowed to be copied out? */
3329 			if (!io_state_active(label.io_state) ||
3330 			    !ip_label_check_or_substitute(space, reply, &label,
3331 			    reply_type, &reply_subst)) {
3332 				/* clear the context value */
3333 				reply->ip_reply_context = 0;
3334 				ip_mq_unlock_label_put(reply, &label);
3335 
3336 				assert(reply_subst == IP_NULL);
3337 				release_reply_port = reply;
3338 				reply = IP_DEAD;
3339 				reply_name = MACH_PORT_DEAD;
3340 				goto done_with_reply;
3341 			}
3342 
3343 			/* is the kolabel requesting a substitution */
3344 			if (reply_subst != IP_NULL) {
3345 				/*
3346 				 * port is unlocked, its right consumed
3347 				 * space is unlocked
3348 				 */
3349 				/* control ports need to be immovable and don't belong here */
3350 				release_assert(!ip_is_tt_control_port(reply_subst));
3351 				assert(reply_type == MACH_MSG_TYPE_PORT_SEND);
3352 				msg->msgh_local_port = reply = reply_subst;
3353 				goto handle_reply_again;
3354 			}
3355 
3356 
3357 			/* Is there already an entry we can use? */
3358 			if ((reply_type != MACH_MSG_TYPE_PORT_SEND_ONCE) &&
3359 			    ipc_right_reverse(space, reply, &reply_name, &entry)) {
3360 				assert(entry->ie_bits & MACH_PORT_TYPE_SEND_RECEIVE);
3361 			} else {
3362 				/* claim a held entry for the reply port */
3363 				assert(entries_held > 0);
3364 				entries_held--;
3365 				ipc_entry_claim(space, ip_to_object(reply),
3366 				    &reply_name, &entry);
3367 			}
3368 
3369 			/* space and reply port are locked and active */
3370 			ip_reference(reply);         /* hold onto the reply port */
3371 
3372 			/*
3373 			 * If the receiver would like to enforce strict reply
3374 			 * semantics, and the message looks like it expects a reply,
3375 			 * and contains a voucher, then link the context in the
3376 			 * voucher with the reply port so that the next message sent
3377 			 * to the reply port must come from a thread that has a
3378 			 * matching context (voucher).
3379 			 */
3380 			if (enforce_strict_reply && MACH_RCV_WITH_STRICT_REPLY(option) && IP_VALID(voucher)) {
3381 				ipc_kmsg_link_reply_context_locked(reply, voucher);
3382 			} else {
3383 				/*
3384 				 * if the receive did not choose to participate
3385 				 * in the strict reply/RPC, then don't enforce
3386 				 * anything (as this could lead to booby-trapped
3387 				 * messages that kill the server).
3388 				 */
3389 				reply->ip_reply_context = 0;
3390 			}
3391 
3392 			ip_label_put(reply, &label);
3393 			ipc_right_copyout_any_send(space, reply, reply_type,
3394 			    IPC_OBJECT_COPYOUT_FLAGS_NONE, reply_name, entry);
3395 			kr = KERN_SUCCESS;
3396 			/* reply port is unlocked */
3397 		} else {
3398 			reply_name = CAST_MACH_PORT_TO_NAME(reply);
3399 		}
3400 
3401 done_with_reply:
3402 
3403 		/* Handle voucher port. */
3404 		if (voucher_type != MACH_MSGH_BITS_ZERO) {
3405 			assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
3406 
3407 			if (!IP_VALID(voucher)) {
3408 				if ((option & MACH_RCV_VOUCHER) == 0) {
3409 					voucher_type = MACH_MSGH_BITS_ZERO;
3410 				}
3411 				voucher_name = MACH_PORT_NULL;
3412 				goto done_with_voucher;
3413 			}
3414 
3415 #if CONFIG_PREADOPT_TG
3416 			struct knote *kn = current_thread()->ith_knote;
3417 			if (kn == ITH_KNOTE_NULL || kn == ITH_KNOTE_PSEUDO) {
3418 				/*
3419 				 * We are not in this path of voucher copyout because of
3420 				 * kevent - we cannot expect a voucher preadopt happening on
3421 				 * this thread for this message later on
3422 				 */
3423 				KDBG_DEBUG(MACHDBG_CODE(DBG_MACH_THREAD_GROUP, MACH_THREAD_GROUP_PREADOPT_NA),
3424 				    thread_tid(current_thread()), 0, 0, 0);
3425 			}
3426 #endif
3427 
3428 			/* clear voucher from its hiding place back in the kmsg */
3429 			ipc_kmsg_clear_voucher_port(kmsg);
3430 
3431 			if ((option & MACH_RCV_VOUCHER) != 0) {
3432 				ipc_object_label_t label;
3433 				ipc_entry_t entry;
3434 
3435 				label = ip_mq_lock_check_aligned(voucher);
3436 				ipc_release_assert(label.io_type == IKOT_VOUCHER);
3437 
3438 				if (ipc_right_reverse(space, voucher,
3439 				    &voucher_name, &entry)) {
3440 					assert(entry->ie_bits & MACH_PORT_TYPE_SEND);
3441 				} else {
3442 					assert(entries_held > 0);
3443 					entries_held--;
3444 					ipc_entry_claim(space, ip_to_object(voucher), &voucher_name, &entry);
3445 				}
3446 				/* space is locked and active */
3447 
3448 				assert(label.io_type == IKOT_VOUCHER);
3449 				ip_label_put(voucher, &label);
3450 				ipc_right_copyout_any_send(space, voucher,
3451 				    MACH_MSG_TYPE_MOVE_SEND,
3452 				    IPC_OBJECT_COPYOUT_FLAGS_NONE,
3453 				    voucher_name, entry);
3454 				/* voucher port is unlocked */
3455 			} else {
3456 				voucher_type = MACH_MSGH_BITS_ZERO;
3457 				release_voucher_port = voucher;
3458 				voucher_name = MACH_PORT_NULL;
3459 			}
3460 		} else {
3461 			voucher_name = msg->msgh_voucher_port;
3462 		}
3463 
3464 done_with_voucher:
3465 
3466 		ip_mq_lock(dest);
3467 		is_write_unlock(space);
3468 	} else {
3469 		/*
3470 		 *	No reply or voucher port!  This is an easy case.
3471 		 *
3472 		 *	We only need to check that the space is still
3473 		 *	active once we locked the destination:
3474 		 *
3475 		 *	- if the space holds a receive right for `dest`,
3476 		 *	  then holding the port lock means we can't fail
3477 		 *	  to notice if the space went dead because
3478 		 *	  the is_write_unlock() will pair with
3479 		 *	  os_atomic_barrier_before_lock_acquire() + ip_mq_lock().
3480 		 *
3481 		 *	- if this space doesn't hold a receive right
3482 		 *	  for `dest`, then `dest->ip_receiver` points
3483 		 *	  elsewhere, and ipc_object_copyout_dest() will
3484 		 *	  handle this situation, and failing to notice
3485 		 *	  that the space was dead is accetable.
3486 		 */
3487 
3488 		os_atomic_barrier_before_lock_acquire();
3489 		ip_mq_lock(dest);
3490 		if (!is_active(space)) {
3491 			ip_mq_unlock(dest);
3492 			return MACH_RCV_HEADER_ERROR | MACH_MSG_IPC_SPACE;
3493 		}
3494 
3495 		reply_name = CAST_MACH_PORT_TO_NAME(reply);
3496 
3497 		if (voucher_type != MACH_MSGH_BITS_ZERO) {
3498 			assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
3499 			if ((option & MACH_RCV_VOUCHER) == 0) {
3500 				voucher_type = MACH_MSGH_BITS_ZERO;
3501 			}
3502 			voucher_name = MACH_PORT_NULL;
3503 		} else {
3504 			voucher_name = msg->msgh_voucher_port;
3505 		}
3506 	}
3507 
3508 	/*
3509 	 *	At this point, the space is unlocked and the destination
3510 	 *	port is locked.
3511 	 *	reply_name is taken care of; we still need dest_name.
3512 	 *	We still hold a ref for reply (if it is valid).
3513 	 *
3514 	 *	If the space holds receive rights for the destination,
3515 	 *	we return its name for the right.  Otherwise the task
3516 	 *	managed to destroy or give away the receive right between
3517 	 *	receiving the message and this copyout.  If the destination
3518 	 *	is dead, return MACH_PORT_DEAD, and if the receive right
3519 	 *	exists somewhere else (another space, in transit)
3520 	 *	return MACH_PORT_NULL.
3521 	 *
3522 	 *	Making this copyout operation atomic with the previous
3523 	 *	copyout of the reply port is a bit tricky.  If there was
3524 	 *	no real reply port (it wasn't IP_VALID) then this isn't
3525 	 *	an issue.  If the reply port was dead at copyout time,
3526 	 *	then we are OK, because if dest is dead we serialize
3527 	 *	after the death of both ports and if dest is alive
3528 	 *	we serialize after reply died but before dest's (later) death.
3529 	 *	So assume reply was alive when we copied it out.  If dest
3530 	 *	is alive, then we are OK because we serialize before
3531 	 *	the ports' deaths.  So assume dest is dead when we look at it.
3532 	 *	If reply dies/died after dest, then we are OK because
3533 	 *	we serialize after dest died but before reply dies.
3534 	 *	So the hard case is when reply is alive at copyout,
3535 	 *	dest is dead at copyout, and reply died before dest died.
3536 	 *	In this case pretend that dest is still alive, so
3537 	 *	we serialize while both ports are alive.
3538 	 *
3539 	 *	Because the space lock is held across the copyout of reply
3540 	 *	and locking dest, the receive right for dest can't move
3541 	 *	in or out of the space while the copyouts happen, so
3542 	 *	that isn't an atomicity problem.  In the last hard case
3543 	 *	above, this implies that when dest is dead that the
3544 	 *	space couldn't have had receive rights for dest at
3545 	 *	the time reply was copied-out, so when we pretend
3546 	 *	that dest is still alive, we can return MACH_PORT_NULL.
3547 	 *
3548 	 *	If dest == reply, then we have to make it look like
3549 	 *	either both copyouts happened before the port died,
3550 	 *	or both happened after the port died.  This special
3551 	 *	case works naturally if the timestamp comparison
3552 	 *	is done correctly.
3553 	 */
3554 
3555 	if (ip_active(dest)) {
3556 		ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
3557 		/* dest is unlocked */
3558 	} else {
3559 		ipc_port_timestamp_t timestamp;
3560 
3561 		timestamp = ip_get_death_time(dest);
3562 		ip_mq_unlock(dest);
3563 		ip_release(dest);
3564 
3565 		if (IP_VALID(reply)) {
3566 			ip_mq_lock(reply);
3567 			if (ip_active(reply) ||
3568 			    IP_TIMESTAMP_ORDER(timestamp,
3569 			    ip_get_death_time(reply))) {
3570 				dest_name = MACH_PORT_DEAD;
3571 			} else {
3572 				dest_name = MACH_PORT_NULL;
3573 			}
3574 			ip_mq_unlock(reply);
3575 		} else {
3576 			dest_name = MACH_PORT_DEAD;
3577 		}
3578 	}
3579 
3580 	if (IP_VALID(reply)) {
3581 		ip_release(reply);
3582 	}
3583 
3584 	if (IP_VALID(release_reply_port)) {
3585 		if (reply_type == MACH_MSG_TYPE_PORT_SEND_ONCE) {
3586 			ipc_port_release_sonce(release_reply_port);
3587 		} else {
3588 			ipc_port_release_send(release_reply_port);
3589 		}
3590 	}
3591 
3592 	if ((option & MACH_RCV_VOUCHER) != 0) {
3593 		KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_RECV) | DBG_FUNC_NONE,
3594 		    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
3595 		    (uintptr_t)msg->msgh_bits,
3596 		    (uintptr_t)msg->msgh_id,
3597 		    VM_KERNEL_ADDRPERM(voucher_addr), 0);
3598 	} else {
3599 		KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_RECV_VOUCHER_REFUSED) | DBG_FUNC_NONE,
3600 		    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
3601 		    (uintptr_t)msg->msgh_bits,
3602 		    (uintptr_t)msg->msgh_id,
3603 		    VM_KERNEL_ADDRPERM(voucher_addr), 0);
3604 	}
3605 
3606 	if (IP_VALID(release_voucher_port)) {
3607 		ipc_port_release_send(release_voucher_port);
3608 	}
3609 
3610 	msg->msgh_bits = MACH_MSGH_BITS_SET(reply_type, dest_type,
3611 	    voucher_type, mbits);
3612 	msg->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
3613 	msg->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
3614 	msg->msgh_voucher_port = voucher_name;
3615 
3616 	return MACH_MSG_SUCCESS;
3617 }
3618 
3619 /*
3620  *	Routine:	ipc_kmsg_copyout_port
3621  *	Purpose:
3622  *		Copy-out a port right.  Always returns a name,
3623  *		even for unsuccessful return codes.  Always
3624  *		consumes the supplied port.
3625  *	Conditions:
3626  *		Nothing locked.
3627  *	Returns:
3628  *		MACH_MSG_SUCCESS	The space acquired the right
3629  *			(name is valid) or the port is dead (MACH_PORT_DEAD).
3630  *		MACH_MSG_IPC_SPACE	No room in space for the right,
3631  *			or the space is dead.  (Name is MACH_PORT_NULL.)
3632  *		MACH_MSG_IPC_KERNEL	Kernel resource shortage.
3633  *			(Name is MACH_PORT_NULL.)
3634  */
3635 static mach_msg_return_t
ipc_kmsg_copyout_port(ipc_space_t space,ipc_port_t port,mach_msg_type_name_t msgt_name,mach_msg_guarded_port_descriptor_t * gdesc,mach_port_name_t * namep)3636 ipc_kmsg_copyout_port(
3637 	ipc_space_t             space,
3638 	ipc_port_t              port,
3639 	mach_msg_type_name_t    msgt_name,
3640 	mach_msg_guarded_port_descriptor_t *gdesc,
3641 	mach_port_name_t       *namep)
3642 {
3643 	kern_return_t kr;
3644 
3645 	if (!IP_VALID(port)) {
3646 		*namep = CAST_MACH_PORT_TO_NAME(port);
3647 		return MACH_MSG_SUCCESS;
3648 	}
3649 
3650 	kr = ipc_object_copyout(space, port, msgt_name,
3651 	    IPC_OBJECT_COPYOUT_FLAGS_NONE, gdesc, namep);
3652 	if (kr != KERN_SUCCESS) {
3653 		if (kr == KERN_INVALID_CAPABILITY) {
3654 			*namep = MACH_PORT_DEAD;
3655 		} else {
3656 			*namep = MACH_PORT_NULL;
3657 
3658 			if (kr == KERN_RESOURCE_SHORTAGE) {
3659 				return MACH_MSG_IPC_KERNEL;
3660 			} else {
3661 				return MACH_MSG_IPC_SPACE;
3662 			}
3663 		}
3664 	}
3665 
3666 	return MACH_MSG_SUCCESS;
3667 }
3668 
3669 /*
3670  *	Routine:	ipc_kmsg_copyout_reply_port
3671  *	Purpose:
3672  *      Kernel swallows the send-once right associated with reply port.
3673  *      Always returns a name, even for unsuccessful return codes.
3674  *      Returns
3675  *          MACH_MSG_SUCCESS Returns name of receive right for reply port.
3676  *              Name is valid if the space acquired the right and msgt_name would be changed from MOVE_SO to MAKE_SO.
3677  *              Name is MACH_PORT_DEAD if the port is dead.
3678  *              Name is MACH_PORT_NULL if its entry could not be found in task's ipc space.
3679  *          MACH_MSG_IPC_SPACE
3680  *              The space is dead.  (Name is MACH_PORT_NULL.)
3681  *	Conditions:
3682  *      Nothing locked.
3683  */
3684 static mach_msg_return_t
ipc_kmsg_copyout_reply_port(ipc_space_t space,ipc_port_t port,mach_msg_type_name_t * msgt_name,mach_port_name_t * namep)3685 ipc_kmsg_copyout_reply_port(
3686 	ipc_space_t             space,
3687 	ipc_port_t              port,
3688 	mach_msg_type_name_t   *msgt_name,
3689 	mach_port_name_t       *namep)
3690 {
3691 	ipc_entry_t entry;
3692 	kern_return_t kr;
3693 
3694 	if (!IP_VALID(port)) {
3695 		*namep = CAST_MACH_PORT_TO_NAME(port);
3696 		return MACH_MSG_SUCCESS;
3697 	}
3698 
3699 	assert(ip_is_reply_port(port));
3700 	assert(*msgt_name == MACH_MSG_TYPE_PORT_SEND_ONCE);
3701 
3702 	is_write_lock(space);
3703 
3704 	if (!is_active(space)) {
3705 		ipc_port_release_sonce(port);
3706 		is_write_unlock(space);
3707 		*namep = MACH_PORT_NULL;
3708 		return MACH_MSG_IPC_SPACE;
3709 	}
3710 
3711 	ip_mq_lock(port);
3712 
3713 	if (!ip_active(port)) {
3714 		*namep = MACH_PORT_DEAD;
3715 		kr = MACH_MSG_SUCCESS;
3716 		goto out;
3717 	}
3718 
3719 	/* space is locked and active. port is locked and active. */
3720 	if (!ipc_right_reverse(space, port, namep, &entry)) {
3721 		*namep = MACH_PORT_NULL;
3722 		kr = MACH_MSG_SUCCESS;
3723 		goto out;
3724 	}
3725 
3726 	assert(entry->ie_bits & MACH_PORT_TYPE_RECEIVE);
3727 
3728 	*msgt_name = MACH_MSG_TYPE_MAKE_SEND_ONCE;
3729 	ipc_port_release_sonce_and_unlock(port);
3730 	/* port is unlocked. */
3731 
3732 	is_write_unlock(space);
3733 
3734 	return MACH_MSG_SUCCESS;
3735 
3736 out:
3737 
3738 	/* space and object are locked. */
3739 	ipc_port_release_sonce_and_unlock(port);
3740 
3741 	is_write_unlock(space);
3742 
3743 	return kr;
3744 }
3745 
3746 
3747 static mach_msg_return_t
ipc_kmsg_copyout_port_descriptor(mach_msg_port_descriptor_t * dsc,ipc_space_t space)3748 ipc_kmsg_copyout_port_descriptor(
3749 	mach_msg_port_descriptor_t *dsc,
3750 	ipc_space_t             space)
3751 {
3752 	mach_port_name_t  name;
3753 	mach_msg_return_t mr;
3754 
3755 	/* Copyout port right carried in the message */
3756 	mr = ipc_kmsg_copyout_port(space, dsc->name, dsc->disposition,
3757 	    NULL, &name);
3758 	dsc->u_name = CAST_MACH_NAME_TO_PORT(name);
3759 	return mr;
3760 }
3761 
3762 static char *
ipc_kmsg_deflate_port_descriptor(char * udesc_end,const mach_msg_port_descriptor_t * kdesc)3763 ipc_kmsg_deflate_port_descriptor(
3764 	char                   *udesc_end,
3765 	const mach_msg_port_descriptor_t *kdesc)
3766 {
3767 	mach_msg_user_port_descriptor_t udesc = {
3768 		.name        = CAST_MACH_PORT_TO_NAME(kdesc->u_name),
3769 		.disposition = kdesc->disposition,
3770 		.type        = kdesc->type,
3771 	};
3772 
3773 	return ipc_kmsg_deflate_put(udesc_end, &udesc);
3774 }
3775 
3776 static mach_msg_return_t
ipc_kmsg_copyout_ool_descriptor(mach_msg_ool_descriptor_t * dsc,vm_map_t map)3777 ipc_kmsg_copyout_ool_descriptor(
3778 	mach_msg_ool_descriptor_t  *dsc,
3779 	vm_map_t                    map)
3780 {
3781 	vm_map_copy_t               copy = dsc->address;
3782 	vm_map_size_t               size = dsc->size;
3783 	vm_map_address_t            rcv_addr;
3784 	boolean_t                   misaligned = FALSE;
3785 	mach_msg_return_t           mr  = MACH_MSG_SUCCESS;
3786 
3787 	if (copy != VM_MAP_COPY_NULL) {
3788 		kern_return_t kr;
3789 
3790 		rcv_addr = 0;
3791 		if (vm_map_copy_validate_size(map, copy, &size) == FALSE) {
3792 			panic("Inconsistent OOL/copyout size on %p: expected %d, got %lld @%p",
3793 			    dsc, dsc->size, (unsigned long long)copy->size, copy);
3794 		}
3795 
3796 		if ((copy->type == VM_MAP_COPY_ENTRY_LIST) &&
3797 		    (trunc_page(copy->offset) != copy->offset ||
3798 		    round_page(dsc->size) != dsc->size)) {
3799 			misaligned = TRUE;
3800 		}
3801 
3802 		if (misaligned) {
3803 			mach_vm_offset_t rounded_addr;
3804 			vm_map_size_t   rounded_size;
3805 			vm_map_offset_t effective_page_mask, effective_page_size;
3806 
3807 			effective_page_mask = VM_MAP_PAGE_MASK(map);
3808 			effective_page_size = effective_page_mask + 1;
3809 
3810 			rounded_size = vm_map_round_page(copy->offset + size, effective_page_mask) - vm_map_trunc_page(copy->offset, effective_page_mask);
3811 
3812 			kr = mach_vm_allocate_kernel(map, &rounded_addr, rounded_size,
3813 			    VM_MAP_KERNEL_FLAGS_ANYWHERE(.vm_tag = VM_MEMORY_MACH_MSG));
3814 
3815 			if (kr == KERN_SUCCESS) {
3816 				/*
3817 				 * vm_map_copy_overwrite does a full copy
3818 				 * if size is too small to optimize.
3819 				 * So we tried skipping the offset adjustment
3820 				 * if we fail the 'size' test.
3821 				 *
3822 				 * if (size >= VM_MAP_COPY_OVERWRITE_OPTIMIZATION_THRESHOLD_PAGES * effective_page_size)
3823 				 *
3824 				 * This resulted in leaked memory especially on the
3825 				 * older watches (16k user - 4k kernel) because we
3826 				 * would do a physical copy into the start of this
3827 				 * rounded range but could leak part of it
3828 				 * on deallocation if the 'size' being deallocated
3829 				 * does not cover the full range. So instead we do
3830 				 * the misalignment adjustment always so that on
3831 				 * deallocation we will remove the full range.
3832 				 */
3833 				if ((rounded_addr & effective_page_mask) !=
3834 				    (copy->offset & effective_page_mask)) {
3835 					/*
3836 					 * Need similar mis-alignment of source and destination...
3837 					 */
3838 					rounded_addr += (copy->offset & effective_page_mask);
3839 
3840 					assert((rounded_addr & effective_page_mask) == (copy->offset & effective_page_mask));
3841 				}
3842 				rcv_addr = rounded_addr;
3843 
3844 				kr = vm_map_copy_overwrite(map, rcv_addr, copy, size,
3845 #if HAS_MTE
3846 				    FALSE,
3847 #endif
3848 				    FALSE);
3849 			}
3850 		} else {
3851 			kr = vm_map_copyout_size(map, &rcv_addr, copy, size);
3852 		}
3853 		if (kr != KERN_SUCCESS) {
3854 			if (kr == KERN_RESOURCE_SHORTAGE) {
3855 				mr = MACH_MSG_VM_KERNEL;
3856 			} else {
3857 				mr = MACH_MSG_VM_SPACE;
3858 			}
3859 			vm_map_copy_discard(copy);
3860 			rcv_addr = 0;
3861 			size = 0;
3862 		}
3863 	} else {
3864 		rcv_addr = 0;
3865 		size = 0;
3866 	}
3867 
3868 	dsc->u_address = rcv_addr;
3869 	dsc->size      = size;
3870 	return mr;
3871 }
3872 
3873 static char *
ipc_kmsg_deflate_memory_descriptor(char * udesc_end,const mach_msg_ool_descriptor_t * kdesc,bool isU64)3874 ipc_kmsg_deflate_memory_descriptor(
3875 	char                   *udesc_end,
3876 	const mach_msg_ool_descriptor_t *kdesc,
3877 	bool                    isU64)
3878 {
3879 	bool deallocate = (kdesc->copy == MACH_MSG_VIRTUAL_COPY);
3880 
3881 	if (isU64) {
3882 		mach_msg_ool_descriptor64_t udesc = {
3883 			.address     = kdesc->u_address,
3884 			.size        = kdesc->size,
3885 			.deallocate  = deallocate,
3886 			.copy        = kdesc->copy,
3887 			.type        = kdesc->type,
3888 		};
3889 
3890 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
3891 	} else {
3892 		mach_msg_ool_descriptor32_t udesc = {
3893 			.address     = (uint32_t)kdesc->u_address,
3894 			.size        = kdesc->size,
3895 			.deallocate  = deallocate,
3896 			.copy        = kdesc->copy,
3897 			.type        = kdesc->type,
3898 		};
3899 
3900 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
3901 	}
3902 }
3903 
3904 
3905 static mach_msg_return_t
ipc_kmsg_copyout_ool_ports_descriptor(mach_msg_kdescriptor_t * kdesc,vm_map_t map,ipc_space_t space)3906 ipc_kmsg_copyout_ool_ports_descriptor(
3907 	mach_msg_kdescriptor_t *kdesc,
3908 	vm_map_t                map,
3909 	ipc_space_t             space)
3910 {
3911 	mach_msg_ool_ports_descriptor_t *dsc = &kdesc->kdesc_port_array;
3912 	mach_msg_type_name_t    disp  = dsc->disposition;
3913 	mach_msg_type_number_t  count = dsc->count;
3914 	mach_port_array_t       array = dsc->address;
3915 	mach_port_name_t       *names = dsc->address;
3916 
3917 	vm_size_t               names_length = count * sizeof(mach_port_name_t);
3918 	mach_vm_offset_t        rcv_addr = 0;
3919 	mach_msg_return_t       mr = MACH_MSG_SUCCESS;
3920 
3921 	if (count != 0 && array != NULL) {
3922 		kern_return_t kr;
3923 		vm_tag_t tag;
3924 
3925 		/*
3926 		 * Dynamically allocate the region
3927 		 */
3928 		if (vm_kernel_map_is_kernel(map)) {
3929 			tag = VM_KERN_MEMORY_IPC;
3930 		} else {
3931 			tag = VM_MEMORY_MACH_MSG;
3932 		}
3933 
3934 		kr = mach_vm_allocate_kernel(map, &rcv_addr, names_length,
3935 		    VM_MAP_KERNEL_FLAGS_ANYWHERE(.vm_tag = tag));
3936 
3937 		/*
3938 		 * Handle the port rights and copy out the names
3939 		 * for those rights out to user-space.
3940 		 */
3941 		if (kr == MACH_MSG_SUCCESS) {
3942 			for (mach_msg_size_t i = 0; i < count; i++) {
3943 				mr |= ipc_kmsg_copyout_port(space,
3944 				    array[i].port, disp, NULL, &names[i]);
3945 			}
3946 			if (copyoutmap(map, names, rcv_addr, names_length)) {
3947 				mr |= MACH_MSG_VM_SPACE;
3948 			}
3949 			mach_port_array_free(array, count);
3950 		} else {
3951 			ipc_kmsg_clean_descriptors(kdesc, 1);
3952 			if (kr == KERN_RESOURCE_SHORTAGE) {
3953 				mr = MACH_MSG_VM_KERNEL;
3954 			} else {
3955 				mr = MACH_MSG_VM_SPACE;
3956 			}
3957 			rcv_addr = 0;
3958 		}
3959 	}
3960 
3961 	dsc->u_address = rcv_addr;
3962 	return mr;
3963 }
3964 
3965 static char *
ipc_kmsg_deflate_port_array_descriptor(char * udesc_end,const mach_msg_ool_ports_descriptor_t * kdesc,bool isU64)3966 ipc_kmsg_deflate_port_array_descriptor(
3967 	char                   *udesc_end,
3968 	const mach_msg_ool_ports_descriptor_t *kdesc,
3969 	bool                    isU64)
3970 {
3971 	if (isU64) {
3972 		mach_msg_ool_ports_descriptor64_t udesc = {
3973 			.address     = kdesc->u_address,
3974 			.count       = kdesc->count,
3975 			.deallocate  = true,
3976 			.copy        = MACH_MSG_VIRTUAL_COPY,
3977 			.disposition = kdesc->disposition,
3978 			.type        = kdesc->type,
3979 		};
3980 
3981 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
3982 	} else {
3983 		mach_msg_ool_ports_descriptor32_t udesc = {
3984 			.address     = (uint32_t)kdesc->u_address,
3985 			.count       = kdesc->count,
3986 			.deallocate  = true,
3987 			.copy        = MACH_MSG_VIRTUAL_COPY,
3988 			.disposition = kdesc->disposition,
3989 			.type        = kdesc->type,
3990 		};
3991 
3992 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
3993 	}
3994 }
3995 
3996 
3997 static mach_msg_return_t
ipc_kmsg_copyout_guarded_port_descriptor(mach_msg_guarded_port_descriptor_t * dsc,ipc_space_t space,mach_msg_option64_t option)3998 ipc_kmsg_copyout_guarded_port_descriptor(
3999 	mach_msg_guarded_port_descriptor_t *dsc,
4000 	ipc_space_t             space,
4001 	mach_msg_option64_t     option)
4002 {
4003 	mach_port_t             port    = dsc->name;
4004 	mach_msg_type_name_t    disp    = dsc->disposition;
4005 	mach_msg_return_t       mr      = MACH_MSG_SUCCESS;
4006 
4007 	/* Currently kernel_task doesnt support receiving guarded port descriptors */
4008 	struct knote *kn = current_thread()->ith_knote;
4009 	if ((kn != ITH_KNOTE_PSEUDO) && ((option & MACH_RCV_GUARDED_DESC) == 0)) {
4010 #if DEVELOPMENT || DEBUG
4011 		/*
4012 		 * Simulated crash needed for debugging, notifies the receiver to opt into receiving
4013 		 * guarded descriptors.
4014 		 */
4015 		mach_port_guard_exception(current_thread()->ith_receiver_name,
4016 		    0, kGUARD_EXC_RCV_GUARDED_DESC);
4017 #endif
4018 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_DESTROY_GUARDED_DESC),
4019 		    current_thread()->ith_receiver_name,
4020 		    VM_KERNEL_ADDRPERM(port), disp, dsc->flags);
4021 
4022 		ipc_object_destroy(port, disp);
4023 		dsc->u_context = 0;
4024 		dsc->u_name    = MACH_PORT_NULL;
4025 	} else {
4026 		mr = ipc_kmsg_copyout_port(space, port, disp, dsc,
4027 		    &dsc->u_name);
4028 	}
4029 
4030 	return mr;
4031 }
4032 
4033 static char *
ipc_kmsg_deflate_guarded_port_descriptor(char * udesc_end,const mach_msg_guarded_port_descriptor_t * kdesc,bool isU64)4034 ipc_kmsg_deflate_guarded_port_descriptor(
4035 	char                   *udesc_end,
4036 	const mach_msg_guarded_port_descriptor_t *kdesc,
4037 	bool                    isU64)
4038 {
4039 	if (isU64) {
4040 		mach_msg_guarded_port_descriptor64_t udesc = {
4041 			.context     = kdesc->u_context,
4042 			.flags       = kdesc->flags,
4043 			.disposition = kdesc->disposition,
4044 			.type        = kdesc->type,
4045 			.name        = kdesc->u_name,
4046 		};
4047 
4048 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
4049 	} else {
4050 		mach_msg_guarded_port_descriptor32_t udesc = {
4051 			.context     = (uint32_t)kdesc->u_context,
4052 			.flags       = kdesc->flags,
4053 			.disposition = kdesc->disposition,
4054 			.type        = kdesc->type,
4055 			.name        = kdesc->u_name,
4056 		};
4057 
4058 		return ipc_kmsg_deflate_put(udesc_end, &udesc);
4059 	}
4060 }
4061 
4062 
4063 /*
4064  *	Routine:	ipc_kmsg_copyout_descriptors
4065  *	Purpose:
4066  *		"Copy-out" port rights and out-of-line memory
4067  *		in the body of a message.
4068  *
4069  *		The error codes are a combination of special bits.
4070  *		The copyout proceeds despite errors.
4071  *	Conditions:
4072  *		Nothing locked.
4073  *	Returns:
4074  *		MACH_MSG_SUCCESS	Successful copyout.
4075  *		MACH_MSG_IPC_SPACE	No room for port right in name space.
4076  *		MACH_MSG_VM_SPACE	No room for memory in address space.
4077  *		MACH_MSG_IPC_KERNEL	Resource shortage handling port right.
4078  *		MACH_MSG_VM_KERNEL	Resource shortage handling memory.
4079  *		MACH_MSG_INVALID_RT_DESCRIPTOR Descriptor incompatible with RT
4080  */
4081 
4082 static mach_msg_return_t
ipc_kmsg_copyout_descriptors(mach_msg_kdescriptor_t * kdesc,mach_msg_size_t dsc_count,ipc_space_t space,vm_map_t map,mach_msg_option64_t option)4083 ipc_kmsg_copyout_descriptors(
4084 	mach_msg_kdescriptor_t *kdesc,
4085 	mach_msg_size_t         dsc_count,
4086 	ipc_space_t             space,
4087 	vm_map_t                map,
4088 	mach_msg_option64_t     option)
4089 {
4090 	mach_msg_return_t mr = MACH_MSG_SUCCESS;
4091 
4092 	assert(current_task() != kernel_task);
4093 
4094 	for (mach_msg_size_t i = 0; i < dsc_count; i++, kdesc++) {
4095 		switch (mach_msg_kdescriptor_type(kdesc)) {
4096 		case MACH_MSG_PORT_DESCRIPTOR:
4097 			mr |= ipc_kmsg_copyout_port_descriptor(&kdesc->kdesc_port,
4098 			    space);
4099 			break;
4100 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
4101 		case MACH_MSG_OOL_DESCRIPTOR:
4102 			mr |= ipc_kmsg_copyout_ool_descriptor(&kdesc->kdesc_memory,
4103 			    map);
4104 			break;
4105 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
4106 			mr |= ipc_kmsg_copyout_ool_ports_descriptor(kdesc,
4107 			    map, space);
4108 			break;
4109 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
4110 			mr |= ipc_kmsg_copyout_guarded_port_descriptor(&kdesc->kdesc_guarded_port,
4111 			    space, option);
4112 			break;
4113 		default:
4114 			__ipc_kmsg_descriptor_invalid_type_panic(kdesc);
4115 		}
4116 	}
4117 
4118 	if (mr != MACH_MSG_SUCCESS) {
4119 		mr |= MACH_RCV_BODY_ERROR;
4120 	}
4121 	return mr;
4122 }
4123 
4124 static void
ipc_kmsg_deflate_descriptors(ikm_deflate_context_t * dctx,mach_msg_kdescriptor_t * desc_array,mach_msg_size_t desc_count)4125 ipc_kmsg_deflate_descriptors(
4126 	ikm_deflate_context_t  *dctx,
4127 	mach_msg_kdescriptor_t *desc_array,
4128 	mach_msg_size_t         desc_count)
4129 {
4130 	char           *udesc = (char *)(desc_array + desc_count);
4131 	mach_msg_body_t body  = {
4132 		.msgh_descriptor_count = desc_count,
4133 	};
4134 
4135 	for (mach_msg_size_t i = desc_count; i-- > 0;) {
4136 		const mach_msg_kdescriptor_t *kdesc = &desc_array[i];
4137 
4138 		switch (mach_msg_kdescriptor_type(kdesc)) {
4139 		case MACH_MSG_PORT_DESCRIPTOR:
4140 			udesc = ipc_kmsg_deflate_port_descriptor(udesc,
4141 			    &kdesc->kdesc_port);
4142 			break;
4143 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
4144 		case MACH_MSG_OOL_DESCRIPTOR:
4145 			udesc = ipc_kmsg_deflate_memory_descriptor(udesc,
4146 			    &kdesc->kdesc_memory, dctx->dctx_isU64);
4147 			break;
4148 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
4149 			udesc = ipc_kmsg_deflate_port_array_descriptor(udesc,
4150 			    &kdesc->kdesc_port_array, dctx->dctx_isU64);
4151 			break;
4152 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
4153 			udesc = ipc_kmsg_deflate_guarded_port_descriptor(udesc,
4154 			    &kdesc->kdesc_guarded_port, dctx->dctx_isU64);
4155 			break;
4156 		default:
4157 			__ipc_kmsg_descriptor_invalid_type_panic(kdesc);
4158 		}
4159 	}
4160 
4161 	/* adjust the context with how much the descriptors contracted */
4162 	dctx->dctx_uhdr      += udesc - (char *)desc_array;
4163 	dctx->dctx_uhdr_size -= udesc - (char *)desc_array;
4164 
4165 	/* update the descriptor count right before the array */
4166 	udesc = ipc_kmsg_deflate_put(udesc, &body);
4167 }
4168 
4169 static mach_msg_size_t
ipc_kmsg_descriptors_copyout_size(mach_msg_kdescriptor_t * kdesc,mach_msg_size_t count,vm_map_t map)4170 ipc_kmsg_descriptors_copyout_size(
4171 	mach_msg_kdescriptor_t *kdesc,
4172 	mach_msg_size_t         count,
4173 	vm_map_t                map)
4174 {
4175 	bool isU64 = (map->max_offset > VM_MAX_ADDRESS);
4176 	mach_msg_size_t size = 0;
4177 
4178 	for (mach_msg_size_t i = 0; i < count; i++) {
4179 		size += ikm_user_desc_size(kdesc[i].kdesc_header.type, isU64);
4180 	}
4181 
4182 	return size;
4183 }
4184 
4185 /*
4186  *	Routine:	ipc_kmsg_copyout_size
4187  *	Purpose:
4188  *		Compute the size of the message as copied out to the given
4189  *		map. If the destination map's pointers are a different size
4190  *		than the kernel's, we have to allow for expansion/
4191  *		contraction of the descriptors as appropriate.
4192  *	Conditions:
4193  *		Nothing locked.
4194  *	Returns:
4195  *		size of the message as it would be received.
4196  */
4197 
4198 mach_msg_size_t
ipc_kmsg_copyout_size(ipc_kmsg_t kmsg,vm_map_t map)4199 ipc_kmsg_copyout_size(
4200 	ipc_kmsg_t              kmsg,
4201 	vm_map_t                map)
4202 {
4203 	mach_msg_header_t *hdr   = ikm_header(kmsg);
4204 	mach_msg_size_t    size  = hdr->msgh_size - USER_HEADER_SIZE_DELTA;
4205 
4206 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
4207 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
4208 
4209 		size -= KERNEL_DESC_SIZE * kbase->msgb_dsc_count;
4210 		size += ipc_kmsg_descriptors_copyout_size(kbase->msgb_dsc_array,
4211 		    kbase->msgb_dsc_count, map);
4212 	}
4213 
4214 	return size;
4215 }
4216 
4217 /*
4218  *	Routine:	ipc_kmsg_copyout
4219  *	Purpose:
4220  *		"Copy-out" port rights and out-of-line memory
4221  *		in the message.
4222  *	Conditions:
4223  *		Nothing locked.
4224  *	Returns:
4225  *		MACH_MSG_SUCCESS	Copied out all rights and memory.
4226  *		MACH_RCV_HEADER_ERROR + special bits
4227  *			Rights and memory in the message are intact.
4228  *		MACH_RCV_BODY_ERROR + special bits
4229  *			The message header was successfully copied out.
4230  *			As much of the body was handled as possible.
4231  */
4232 
4233 mach_msg_return_t
ipc_kmsg_copyout(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map,mach_msg_option64_t option)4234 ipc_kmsg_copyout(
4235 	ipc_kmsg_t              kmsg,
4236 	ipc_space_t             space,
4237 	vm_map_t                map,
4238 	mach_msg_option64_t     option)
4239 {
4240 	mach_msg_header_t *hdr = ikm_header(kmsg);
4241 	mach_msg_size_t    dsc_count;
4242 	mach_msg_return_t  mr;
4243 
4244 	dsc_count = ipc_kmsg_validate_signature(kmsg);
4245 
4246 	mr = ipc_kmsg_copyout_header(kmsg, hdr, space, option);
4247 	if (mr != MACH_MSG_SUCCESS) {
4248 		return mr;
4249 	}
4250 
4251 	if (dsc_count) {
4252 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
4253 
4254 		mr = ipc_kmsg_copyout_descriptors(kbase->msgb_dsc_array,
4255 		    dsc_count, space, map, option);
4256 	}
4257 
4258 	return mr;
4259 }
4260 
4261 /*
4262  *	Routine:	ipc_kmsg_copyout_pseudo
4263  *	Purpose:
4264  *		Does a pseudo-copyout of the message.
4265  *		This is like a regular copyout, except
4266  *		that the ports in the header are handled
4267  *		as if they are in the body.  They aren't reversed.
4268  *
4269  *		The error codes are a combination of special bits.
4270  *		The copyout proceeds despite errors.
4271  *	Conditions:
4272  *		Nothing locked.
4273  *	Returns:
4274  *		MACH_MSG_SUCCESS	Successful copyout.
4275  *		MACH_MSG_IPC_SPACE	No room for port right in name space.
4276  *		MACH_MSG_VM_SPACE	No room for memory in address space.
4277  *		MACH_MSG_IPC_KERNEL	Resource shortage handling port right.
4278  *		MACH_MSG_VM_KERNEL	Resource shortage handling memory.
4279  */
4280 
4281 mach_msg_return_t
ipc_kmsg_copyout_pseudo(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map)4282 ipc_kmsg_copyout_pseudo(
4283 	ipc_kmsg_t              kmsg,
4284 	ipc_space_t             space,
4285 	vm_map_t                map)
4286 {
4287 	mach_msg_header_t *hdr = ikm_header(kmsg);
4288 	mach_msg_bits_t mbits = hdr->msgh_bits;
4289 	ipc_port_t dest = hdr->msgh_remote_port;
4290 	ipc_port_t reply = hdr->msgh_local_port;
4291 	ipc_port_t voucher = ipc_kmsg_get_voucher_port(kmsg);
4292 	mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
4293 	mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
4294 	mach_msg_type_name_t voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
4295 	mach_port_name_t voucher_name = hdr->msgh_voucher_port;
4296 	mach_port_name_t dest_name, reply_name;
4297 	mach_msg_return_t mr;
4298 	mach_msg_size_t dsc_count;
4299 
4300 	/* Set ith_knote to ITH_KNOTE_PSEUDO */
4301 	current_thread()->ith_knote = ITH_KNOTE_PSEUDO;
4302 
4303 	dsc_count = ipc_kmsg_validate_signature(kmsg);
4304 
4305 	assert(IP_VALID(dest));
4306 
4307 #if 0
4308 	/*
4309 	 * If we did this here, it looks like we wouldn't need the undo logic
4310 	 * at the end of ipc_kmsg_send() in the error cases.  Not sure which
4311 	 * would be more elegant to keep.
4312 	 */
4313 	ipc_importance_clean(kmsg);
4314 #else
4315 	/* just assert it is already clean */
4316 	ipc_importance_assert_clean(kmsg);
4317 #endif
4318 
4319 	mr = ipc_kmsg_copyout_port(space, dest, dest_type, NULL, &dest_name);
4320 
4321 	if (!IP_VALID(reply)) {
4322 		reply_name = CAST_MACH_PORT_TO_NAME(reply);
4323 	} else if (ip_is_reply_port(reply)) {
4324 		mach_msg_return_t reply_mr;
4325 		reply_mr = ipc_kmsg_copyout_reply_port(space, reply, &reply_type, &reply_name);
4326 		mr = mr | reply_mr;
4327 		if (reply_mr == MACH_MSG_SUCCESS) {
4328 			mbits = MACH_MSGH_BITS_SET(dest_type, reply_type, voucher_type, MACH_MSGH_BITS_OTHER(mbits));
4329 		}
4330 	} else {
4331 		mr = mr | ipc_kmsg_copyout_port(space, reply, reply_type, NULL, &reply_name);
4332 	}
4333 
4334 	hdr->msgh_bits = mbits & MACH_MSGH_BITS_USER;
4335 	hdr->msgh_remote_port = CAST_MACH_NAME_TO_PORT(dest_name);
4336 	hdr->msgh_local_port = CAST_MACH_NAME_TO_PORT(reply_name);
4337 
4338 	/* restore the voucher:
4339 	 * If it was copied in via move-send, have to put back a voucher send right.
4340 	 *
4341 	 * If it was copied in via copy-send, the header still contains the old voucher name.
4342 	 * Restore the type and discard the copied-in/pre-processed voucher.
4343 	 */
4344 	if (IP_VALID(voucher)) {
4345 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
4346 		if (kmsg->ikm_voucher_type == MACH_MSG_TYPE_MOVE_SEND) {
4347 			mr |= ipc_kmsg_copyout_port(space, voucher, voucher_type, NULL, &voucher_name);
4348 			hdr->msgh_voucher_port = voucher_name;
4349 		} else {
4350 			assert(kmsg->ikm_voucher_type == MACH_MSG_TYPE_COPY_SEND);
4351 			hdr->msgh_bits = MACH_MSGH_BITS_SET(dest_type, reply_type, MACH_MSG_TYPE_COPY_SEND,
4352 			    MACH_MSGH_BITS_OTHER(hdr->msgh_bits));
4353 			ipc_object_destroy(voucher, voucher_type);
4354 		}
4355 		ipc_kmsg_clear_voucher_port(kmsg);
4356 	}
4357 
4358 	if (dsc_count) {
4359 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
4360 
4361 		/* rdar://120614480 this MACH64_MSG_OPTION_NONE is wrong */
4362 		mr |= ipc_kmsg_copyout_descriptors(kbase->msgb_dsc_array,
4363 		    dsc_count, space, map, MACH64_MSG_OPTION_NONE);
4364 	}
4365 
4366 	current_thread()->ith_knote = ITH_KNOTE_NULL;
4367 
4368 	return mr;
4369 }
4370 
4371 /*
4372  *	Routine:	ipc_kmsg_copyout_dest_to_user
4373  *	Purpose:
4374  *		Copies out the destination port in the message.
4375  *		Destroys all other rights and memory in the message.
4376  *		Transforms the message into a bare header with trailer.
4377  *	Conditions:
4378  *		Nothing locked.
4379  */
4380 
4381 void
ipc_kmsg_copyout_dest_to_user(ipc_kmsg_t kmsg,ipc_space_t space)4382 ipc_kmsg_copyout_dest_to_user(
4383 	ipc_kmsg_t      kmsg,
4384 	ipc_space_t     space)
4385 {
4386 	mach_msg_bits_t mbits;
4387 	ipc_port_t dest;
4388 	ipc_port_t reply;
4389 	ipc_port_t voucher;
4390 	mach_msg_type_name_t dest_type;
4391 	mach_msg_type_name_t reply_type;
4392 	mach_msg_type_name_t voucher_type;
4393 	mach_port_name_t dest_name, reply_name, voucher_name;
4394 	mach_msg_header_t *hdr;
4395 	mach_msg_id_t msg_id;
4396 	mach_msg_size_t aux_size;
4397 	mach_msg_size_t dsc_count;
4398 
4399 	dsc_count = ipc_kmsg_validate_signature(kmsg);
4400 
4401 	hdr = ikm_header(kmsg);
4402 	mbits = hdr->msgh_bits;
4403 	dest = hdr->msgh_remote_port;
4404 	reply = hdr->msgh_local_port;
4405 	voucher = ipc_kmsg_get_voucher_port(kmsg);
4406 	voucher_name = hdr->msgh_voucher_port;
4407 	msg_id = hdr->msgh_id;
4408 	dest_type = MACH_MSGH_BITS_REMOTE(mbits);
4409 	reply_type = MACH_MSGH_BITS_LOCAL(mbits);
4410 	voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
4411 	aux_size = kmsg->ikm_aux_size;
4412 
4413 	assert(IP_VALID(dest));
4414 
4415 	ipc_importance_assert_clean(kmsg);
4416 
4417 	ip_mq_lock(dest);
4418 	if (ip_active(dest)) {
4419 		ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
4420 		/* dest is unlocked */
4421 	} else {
4422 		ip_mq_unlock(dest);
4423 		ip_release(dest);
4424 		dest_name = MACH_PORT_DEAD;
4425 	}
4426 
4427 	if (IP_VALID(reply)) {
4428 		ipc_object_destroy(reply, reply_type);
4429 		reply_name = MACH_PORT_NULL;
4430 	} else {
4431 		reply_name = CAST_MACH_PORT_TO_NAME(reply);
4432 	}
4433 
4434 	if (IP_VALID(voucher)) {
4435 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
4436 		ipc_object_destroy(voucher, voucher_type);
4437 		ipc_kmsg_clear_voucher_port(kmsg);
4438 		voucher_name = MACH_PORT_NULL;
4439 	}
4440 
4441 	if (mbits & MACH_MSGH_BITS_COMPLEX) {
4442 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
4443 
4444 		ipc_kmsg_clean_descriptors(kbase->msgb_dsc_array, dsc_count);
4445 	}
4446 
4447 	ipc_kmsg_free_allocations(kmsg);
4448 
4449 	/* and now reconstruct a message anew */
4450 
4451 	mbits = MACH_MSGH_BITS_SET(reply_type, dest_type, voucher_type, mbits);
4452 	*ikm_header(kmsg) = (mach_msg_header_t){
4453 		.msgh_bits         = mbits,
4454 		.msgh_size         = sizeof(mach_msg_header_t),
4455 		.msgh_local_port   = CAST_MACH_NAME_TO_PORT(dest_name),
4456 		.msgh_remote_port  = CAST_MACH_NAME_TO_PORT(reply_name),
4457 		.msgh_voucher_port = voucher_name,
4458 		.msgh_id           = msg_id,
4459 	};
4460 	ipc_kmsg_init_trailer_and_sign(kmsg, TASK_NULL);
4461 
4462 	/* put a minimal aux header if there was one */
4463 	if (aux_size) {
4464 		kmsg->ikm_aux_size = sizeof(mach_msg_aux_header_t);
4465 		*ikm_aux_header(kmsg) = (mach_msg_aux_header_t){
4466 			.msgdh_size = sizeof(mach_msg_aux_header_t),
4467 		};
4468 	}
4469 }
4470 
4471 /*
4472  *	Routine:	ipc_kmsg_copyout_dest_to_kernel
4473  *	Purpose:
4474  *		Copies out the destination and reply ports in the message.
4475  *		Leaves all other rights and memory in the message alone.
4476  *	Conditions:
4477  *		Nothing locked.
4478  *
4479  *	Derived from ipc_kmsg_copyout_dest_to_user.
4480  *	Use by mach_msg_rpc_from_kernel (which used to use copyout_dest).
4481  *	We really do want to save rights and memory.
4482  */
4483 
4484 void
ipc_kmsg_copyout_dest_to_kernel(ipc_kmsg_t kmsg,ipc_space_t space)4485 ipc_kmsg_copyout_dest_to_kernel(
4486 	ipc_kmsg_t      kmsg,
4487 	ipc_space_t     space)
4488 {
4489 	ipc_port_t dest;
4490 	mach_port_t reply;
4491 	mach_msg_type_name_t dest_type;
4492 	mach_msg_type_name_t reply_type;
4493 	mach_port_name_t dest_name;
4494 	mach_msg_header_t *hdr;
4495 
4496 	(void)ipc_kmsg_validate_signature(kmsg);
4497 
4498 	hdr = ikm_header(kmsg);
4499 	dest = hdr->msgh_remote_port;
4500 	reply = hdr->msgh_local_port;
4501 	dest_type = MACH_MSGH_BITS_REMOTE(hdr->msgh_bits);
4502 	reply_type = MACH_MSGH_BITS_LOCAL(hdr->msgh_bits);
4503 
4504 	assert(IP_VALID(dest));
4505 
4506 	ip_mq_lock(dest);
4507 	if (ip_active(dest)) {
4508 		ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
4509 		/* dest is unlocked */
4510 	} else {
4511 		ip_mq_unlock(dest);
4512 		ip_release(dest);
4513 		dest_name = MACH_PORT_DEAD;
4514 	}
4515 
4516 	/*
4517 	 * While MIG kernel users don't receive vouchers, the
4518 	 * msgh_voucher_port field is intended to be round-tripped through the
4519 	 * kernel if there is no voucher disposition set. Here we check for a
4520 	 * non-zero voucher disposition, and consume the voucher send right as
4521 	 * there is no possible way to specify MACH_RCV_VOUCHER semantics.
4522 	 */
4523 	mach_msg_type_name_t voucher_type;
4524 	voucher_type = MACH_MSGH_BITS_VOUCHER(hdr->msgh_bits);
4525 	if (voucher_type != MACH_MSGH_BITS_ZERO) {
4526 		ipc_port_t voucher = ipc_kmsg_get_voucher_port(kmsg);
4527 
4528 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
4529 		/*
4530 		 * someone managed to send this kernel routine a message with
4531 		 * a voucher in it. Cleanup the reference in
4532 		 * kmsg->ikm_voucher.
4533 		 */
4534 		if (IP_VALID(voucher)) {
4535 			ipc_port_release_send(voucher);
4536 		}
4537 		hdr->msgh_voucher_port = 0;
4538 		ipc_kmsg_clear_voucher_port(kmsg);
4539 	}
4540 
4541 	hdr->msgh_bits =
4542 	    (MACH_MSGH_BITS_OTHER(hdr->msgh_bits) |
4543 	    MACH_MSGH_BITS(reply_type, dest_type));
4544 	hdr->msgh_local_port =  CAST_MACH_NAME_TO_PORT(dest_name);
4545 	hdr->msgh_remote_port = reply;
4546 }
4547 
4548 static void
ipc_kmsg_deflate_header(ikm_deflate_context_t * dctx,mach_msg_header_t * hdr)4549 ipc_kmsg_deflate_header(
4550 	ikm_deflate_context_t  *dctx,
4551 	mach_msg_header_t      *hdr)
4552 {
4553 	mach_msg_user_header_t uhdr = {
4554 		.msgh_bits         = hdr->msgh_bits,
4555 		.msgh_size         = dctx->dctx_uhdr_size + dctx->dctx_udata_size,
4556 		.msgh_remote_port  = CAST_MACH_PORT_TO_NAME(hdr->msgh_remote_port),
4557 		.msgh_local_port   = CAST_MACH_PORT_TO_NAME(hdr->msgh_local_port),
4558 		.msgh_voucher_port = hdr->msgh_voucher_port,
4559 		.msgh_id           = hdr->msgh_id,
4560 	};
4561 
4562 	/* the header will contract, take it into account */
4563 	dctx->dctx_uhdr      += USER_HEADER_SIZE_DELTA;
4564 	dctx->dctx_uhdr_size -= USER_HEADER_SIZE_DELTA;
4565 	uhdr.msgh_size       -= USER_HEADER_SIZE_DELTA;
4566 	memcpy(dctx->dctx_uhdr, &uhdr, sizeof(uhdr));
4567 }
4568 
4569 static void
ipc_kmsg_deflate_trailer(ikm_deflate_context_t * dctx,mach_msg_recv_result_t * msgr)4570 ipc_kmsg_deflate_trailer(
4571 	ikm_deflate_context_t  *dctx,
4572 	mach_msg_recv_result_t *msgr)
4573 {
4574 	mach_msg_max_trailer_t   *trailer = dctx->dctx_trailer;
4575 #ifdef __arm64__
4576 	mach_msg_max_trailer32_t *out32  = (mach_msg_max_trailer32_t *)trailer;
4577 	mach_msg_max_trailer64_t *out64  = (mach_msg_max_trailer64_t *)trailer;
4578 #else
4579 	mach_msg_max_trailer_t   *out32  = trailer;
4580 	mach_msg_max_trailer_t   *out64  = trailer;
4581 #endif /* __arm64__ */
4582 
4583 #define trailer_assert_same_field(field) \
4584 	static_assert(offsetof(typeof(*out32), field) == \
4585 	    offsetof(typeof(*out64), field)); \
4586 	static_assert(sizeof(out32->field) == sizeof(out64->field))
4587 
4588 	/*
4589 	 * These fields have been set by ipc_kmsg_init_trailer_and_sign(),
4590 	 * but alias in both 32 and 64 bit forms and need no munging:
4591 	 *
4592 	 *   msgh_trailer_type, msgh_trailer_size, msgh_sender, msgh_audit
4593 	 *
4594 	 * Update the size with the user requested one,
4595 	 * and update the message seqno.
4596 	 *
4597 	 * These cover:
4598 	 * - mach_msg_trailer_t           (msgh_trailer_type + msgh_trailer_size)
4599 	 * - mach_msg_seqno_trailer_t     (the above + msgh_seqno)
4600 	 * - mach_msg_security_trailer_t  (the above + msgh_sender)
4601 	 * - mach_msg_audit_trailer_t     (the above + msgh_audit)
4602 	 */
4603 	trailer_assert_same_field(msgh_trailer_type);
4604 	trailer_assert_same_field(msgh_trailer_size);
4605 	trailer_assert_same_field(msgh_seqno);
4606 	trailer_assert_same_field(msgh_sender);
4607 	trailer_assert_same_field(msgh_audit);
4608 
4609 	trailer->msgh_trailer_size = dctx->dctx_trailer_size;
4610 	trailer->msgh_seqno        = msgr->msgr_seqno;
4611 
4612 	/*
4613 	 * Lastly update fields that are 32bit versus 64bit dependent,
4614 	 * which are all after msgh_context (including this field).
4615 	 *
4616 	 * These cover:
4617 	 * - mach_msg_context_trailer_t   (the above + msgh_context)
4618 	 * - mach_msg_mac_trailer_t       (the above + msg_ad + msgh_labels)
4619 	 */
4620 
4621 	bzero((char *)trailer + sizeof(mach_msg_audit_trailer_t),
4622 	    MAX_TRAILER_SIZE - sizeof(mach_msg_audit_trailer_t));
4623 
4624 	if (dctx->dctx_isU64) {
4625 		out64->msgh_context = msgr->msgr_context;
4626 	} else {
4627 		out32->msgh_context = (typeof(out32->msgh_context))msgr->msgr_context;
4628 	}
4629 #undef trailer_assert_same_field
4630 }
4631 
4632 static ikm_deflate_context_t
ipc_kmsg_deflate(ipc_kmsg_t kmsg,mach_msg_recv_result_t * msgr,mach_msg_option64_t options,vm_map_t map)4633 ipc_kmsg_deflate(
4634 	ipc_kmsg_t              kmsg,     /* scalar or vector */
4635 	mach_msg_recv_result_t *msgr,
4636 	mach_msg_option64_t     options,
4637 	vm_map_t                map)
4638 {
4639 	mach_msg_header_t      *hdr  = ikm_header(kmsg);
4640 	ikm_deflate_context_t   dctx = {
4641 		.dctx_uhdr       = (char *)hdr,
4642 		.dctx_uhdr_size  = hdr->msgh_size,
4643 
4644 		.dctx_aux_hdr    = ikm_aux_header(kmsg),
4645 		.dctx_aux_size   = kmsg->ikm_aux_size,
4646 
4647 		.dctx_isU64      = (map->max_offset > VM_MAX_ADDRESS),
4648 	};
4649 
4650 	/*
4651 	 * If we aren't pseudo-receiving, deflate the trailer
4652 	 * before where it is is mangled beyond recognition.
4653 	 */
4654 	if (msgr->msgr_recv_name != MSGR_PSEUDO_RECEIVE) {
4655 		dctx.dctx_trailer      = ipc_kmsg_get_trailer(kmsg);
4656 		dctx.dctx_trailer_size = ipc_kmsg_trailer_size(options, map);
4657 	}
4658 
4659 	/*
4660 	 * If the message isn't linear,
4661 	 * split into uhdr=header+descriptors and udata=body+trailer
4662 	 */
4663 	if (!ikm_is_linear(kmsg)) {
4664 		mach_msg_size_t kdata_size = ikm_kdata_size(hdr);
4665 
4666 		dctx.dctx_udata_size = dctx.dctx_uhdr_size - kdata_size;
4667 		if (dctx.dctx_udata_size || dctx.dctx_trailer_size) {
4668 			dctx.dctx_udata      = kmsg->ikm_udata;
4669 			dctx.dctx_uhdr_size  = kdata_size;
4670 		}
4671 	}
4672 
4673 	/*
4674 	 * /!\ past this point, very few ipc_kmsg methods are allowed /!\
4675 	 *
4676 	 * The kmsg layout will be mangled in order to copy the bytes out,
4677 	 * and once that is done, destroying the message is the only thing
4678 	 * allowed.
4679 	 */
4680 
4681 	if (msgr->msgr_recv_name != MSGR_PSEUDO_RECEIVE) {
4682 		ipc_kmsg_deflate_trailer(&dctx, msgr);
4683 	}
4684 
4685 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
4686 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
4687 
4688 		ipc_kmsg_deflate_descriptors(&dctx,
4689 		    kbase->msgb_dsc_array, kbase->msgb_dsc_count);
4690 	}
4691 
4692 	ipc_kmsg_deflate_header(&dctx, hdr);
4693 
4694 	return dctx;
4695 }
4696 
4697 
4698 /*
4699  *	Routine:	ipc_kmsg_put_to_user
4700  *	Purpose:
4701  *		Copies a scalar or vector message buffer to a user message.
4702  *		Frees the message buffer.
4703  *
4704  *		1. If user has allocated space for aux data,
4705  *		   mach_msg_validate_data_vectors() guarantees that
4706  *		   recv_aux_addr is non-zero, and recv_aux_size
4707  *		   is at least sizeof(mach_msg_aux_header_t).
4708  *
4709  *		   In case the kmsg is a scalar or a vector without auxiliary
4710  *		   data, copy out an empty aux header to recv_aux_addr
4711  *		   which serves as EOF.
4712  *
4713  *		2. If the user has not allocated space for aux data,
4714  *		   silently drop the aux payload on reception.
4715  *
4716  *		3. If MACH64_RCV_LINEAR_VECTOR is set, use recv_msg_addr as
4717  *		   the combined buffer for message proper and aux data.
4718  *		   recv_aux_addr and recv_aux_size must be passed as
4719  *		   zeros and are ignored.
4720  *
4721  *	Conditions:
4722  *		Nothing locked. kmsg is freed upon return.
4723  *
4724  *	Returns:
4725  *		MACH_RCV_INVALID_DATA    Couldn't copy to user message.
4726  *		the incoming "mr"        Copied data out of message buffer.
4727  */
4728 mach_msg_return_t
ipc_kmsg_put_to_user(ipc_kmsg_t kmsg,mach_msg_recv_bufs_t * recv_bufs,mach_msg_recv_result_t * msgr,mach_msg_option64_t options,vm_map_t map,mach_msg_return_t mr)4729 ipc_kmsg_put_to_user(
4730 	ipc_kmsg_t              kmsg,     /* scalar or vector */
4731 	mach_msg_recv_bufs_t   *recv_bufs,
4732 	mach_msg_recv_result_t *msgr,
4733 	mach_msg_option64_t     options,
4734 	vm_map_t                map,
4735 	mach_msg_return_t       mr)
4736 {
4737 	mach_msg_aux_header_t   eof_aux = { .msgdh_size = 0 };
4738 	mach_vm_address_t       msg_rcv_addr = recv_bufs->recv_msg_addr;
4739 	mach_vm_address_t       aux_rcv_addr = recv_bufs->recv_aux_addr;
4740 	mach_msg_size_t         usize = 0;
4741 	ikm_deflate_context_t   dctx;
4742 
4743 	/*
4744 	 * After this, the kmsg() is mangled beyond recognition,
4745 	 * and calling things like ikm_header() etc.. will have
4746 	 * undefined behavior.
4747 	 */
4748 	dctx = ipc_kmsg_deflate(kmsg, msgr, options, map);
4749 
4750 	msgr->msgr_msg_size     = dctx.dctx_uhdr_size + dctx.dctx_udata_size;
4751 	msgr->msgr_trailer_size = dctx.dctx_trailer_size;
4752 	msgr->msgr_aux_size     = dctx.dctx_aux_size;
4753 
4754 	usize = msgr->msgr_msg_size + msgr->msgr_trailer_size;
4755 
4756 	/*
4757 	 * Validate our parameters, and compute the actual copy out addresses
4758 	 */
4759 
4760 	if (options & MACH64_RCV_LINEAR_VECTOR) {
4761 		assert(options & MACH64_MSG_VECTOR);
4762 
4763 		if (usize + dctx.dctx_aux_size > recv_bufs->recv_msg_size) {
4764 			mr = MACH_RCV_INVALID_DATA;
4765 			goto out;
4766 		}
4767 		if (options & MACH64_RCV_STACK) {
4768 			msg_rcv_addr += recv_bufs->recv_msg_size -
4769 			    (usize + dctx.dctx_aux_size);
4770 		}
4771 		aux_rcv_addr = msg_rcv_addr + usize;
4772 	} else {
4773 		assert(!(options & MACH64_RCV_STACK));
4774 
4775 		if (msgr->msgr_msg_size > recv_bufs->recv_msg_size) {
4776 			mr = MACH_RCV_INVALID_DATA;
4777 			goto out;
4778 		}
4779 
4780 		/*
4781 		 * (81193887) some clients stomp their own stack due to mis-sized
4782 		 * combined send/receives where the receive buffer didn't account
4783 		 * for the trailer size.
4784 		 *
4785 		 * At the very least, avoid smashing their stack
4786 		 */
4787 		if (usize > recv_bufs->recv_msg_size) {
4788 			dctx.dctx_trailer_size -= recv_bufs->recv_msg_size - usize;
4789 			usize = recv_bufs->recv_msg_size;
4790 		}
4791 
4792 		/*
4793 		 * If user has a buffer for aux data, at least copy out
4794 		 * an empty header which serves as an EOF.
4795 		 *
4796 		 * We don't need to do so for linear vector because
4797 		 * it's used in kevent context and we will return
4798 		 * msgr_aux_size as 0 on ext[3] to signify empty aux data.
4799 		 *
4800 		 * See: filt_machportprocess().
4801 		 */
4802 		if (aux_rcv_addr && !dctx.dctx_aux_hdr) {
4803 			dctx.dctx_aux_hdr  = &eof_aux;
4804 			dctx.dctx_aux_size = sizeof(eof_aux);
4805 			msgr->msgr_aux_size  = sizeof(eof_aux);
4806 		}
4807 
4808 		/*
4809 		 * If a receiver tries to receive a message with an aux vector,
4810 		 * but didn't provide one, we silently drop it for backward
4811 		 * compatibility reasons.
4812 		 */
4813 		if (dctx.dctx_aux_size > recv_bufs->recv_aux_size) {
4814 			dctx.dctx_aux_hdr  = NULL;
4815 			dctx.dctx_aux_size = 0;
4816 			msgr->msgr_aux_size  = 0;
4817 			aux_rcv_addr         = 0;
4818 		}
4819 	}
4820 
4821 
4822 	/*
4823 	 * Now that we measured twice, time to copyout all pieces.
4824 	 */
4825 
4826 	if (dctx.dctx_udata) {
4827 		mach_msg_size_t uhdr_size = dctx.dctx_uhdr_size;
4828 
4829 		if (copyoutmsg(dctx.dctx_uhdr, msg_rcv_addr, uhdr_size) ||
4830 		    copyoutmsg(dctx.dctx_udata, msg_rcv_addr + uhdr_size,
4831 		    usize - uhdr_size)) {
4832 			mr = MACH_RCV_INVALID_DATA;
4833 			goto out;
4834 		}
4835 	} else {
4836 		if (copyoutmsg(dctx.dctx_uhdr, msg_rcv_addr, usize)) {
4837 			mr = MACH_RCV_INVALID_DATA;
4838 			goto out;
4839 		}
4840 	}
4841 
4842 	if (dctx.dctx_aux_size &&
4843 	    copyoutmsg(dctx.dctx_aux_hdr, aux_rcv_addr, dctx.dctx_aux_size)) {
4844 		mr = MACH_RCV_INVALID_DATA;
4845 		goto out;
4846 	}
4847 
4848 out:
4849 	if (mr == MACH_RCV_INVALID_DATA) {
4850 		msgr->msgr_msg_size     = 0;
4851 		msgr->msgr_trailer_size = 0;
4852 		msgr->msgr_aux_size     = 0;
4853 	}
4854 
4855 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_LINK) | DBG_FUNC_NONE,
4856 	    recv_bufs->recv_msg_addr, VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
4857 	    /* this is on the receive/copyout path */ 1, 0, 0);
4858 
4859 	ipc_kmsg_free(kmsg);
4860 
4861 	return mr;
4862 }
4863 
4864 /** @} */
4865 #pragma mark ipc_kmsg kernel interfaces (get/put, copyin_from_kernel, send)
4866 
4867 /*
4868  *	Routine:	ipc_kmsg_get_from_kernel
4869  *	Purpose:
4870  *		Allocates a new kernel message buffer.
4871  *		Copies a kernel message to the message buffer.
4872  *		Only resource errors are allowed.
4873  *	Conditions:
4874  *		Nothing locked.
4875  *		Ports in header are ipc_port_t.
4876  *	Returns:
4877  *		MACH_MSG_SUCCESS	Acquired a message buffer.
4878  *		MACH_SEND_NO_BUFFER	Couldn't allocate a message buffer.
4879  */
4880 
4881 mach_msg_return_t
ipc_kmsg_get_from_kernel(mach_msg_header_t * msg,mach_msg_size_t size,mach_msg_option64_t options,ipc_kmsg_t * kmsgp)4882 ipc_kmsg_get_from_kernel(
4883 	mach_msg_header_t      *msg,
4884 	mach_msg_size_t         size,
4885 	mach_msg_option64_t     options,
4886 	ipc_kmsg_t             *kmsgp)
4887 {
4888 	mach_msg_kbase_t  *src_base;
4889 	ipc_kmsg_t         kmsg;
4890 	mach_msg_header_t *hdr;
4891 	mach_msg_size_t    desc_count, kdata_sz;
4892 
4893 	assert(size >= sizeof(mach_msg_header_t));
4894 	assert((size & 3) == 0);
4895 
4896 	if (msg->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
4897 		src_base   = mach_msg_header_to_kbase(msg);
4898 		desc_count = src_base->msgb_dsc_count;
4899 		kdata_sz   = ikm_kdata_size(desc_count, true);
4900 	} else {
4901 		desc_count = 0;
4902 		kdata_sz   = ikm_kdata_size(desc_count, false);
4903 	}
4904 
4905 	assert(size >= kdata_sz);
4906 	if (size < kdata_sz) {
4907 		return MACH_SEND_TOO_LARGE;
4908 	}
4909 
4910 	kmsg = ipc_kmsg_alloc(size, 0, desc_count, IPC_KMSG_ALLOC_KERNEL);
4911 	/* kmsg can be non-linear */
4912 
4913 	if (kmsg == IKM_NULL) {
4914 		return MACH_SEND_NO_BUFFER;
4915 	}
4916 
4917 	hdr = ikm_header(kmsg);
4918 	if (ikm_is_linear(kmsg)) {
4919 		memcpy(hdr, msg, size);
4920 	} else {
4921 		memcpy(hdr, msg, kdata_sz);
4922 		memcpy(kmsg->ikm_udata, (char *)msg + kdata_sz, size - kdata_sz);
4923 	}
4924 	hdr->msgh_size = size;
4925 
4926 	if (desc_count) {
4927 		mach_msg_kbase_t *dst_base = mach_msg_header_to_kbase(hdr);
4928 
4929 		if (options & MACH64_POLICY_KERNEL_EXTENSION) {
4930 			ipc_kmsg_sign_descriptors(dst_base->msgb_dsc_array,
4931 			    desc_count);
4932 		} else {
4933 			ipc_kmsg_relocate_descriptors(dst_base->msgb_dsc_array,
4934 			    src_base->msgb_dsc_array, desc_count);
4935 		}
4936 	}
4937 
4938 	*kmsgp = kmsg;
4939 	return MACH_MSG_SUCCESS;
4940 }
4941 
4942 static void
ipc_kmsg_copyin_port_from_kernel(mach_msg_header_t * hdr,ipc_port_t port,ipc_port_t remote,mach_msg_type_name_t disp)4943 ipc_kmsg_copyin_port_from_kernel(
4944 	mach_msg_header_t      *hdr,
4945 	ipc_port_t              port,
4946 	ipc_port_t              remote,
4947 	mach_msg_type_name_t    disp)
4948 {
4949 	ipc_object_copyin_from_kernel(port, disp);
4950 	/*
4951 	 * avoid circularity when the destination is also
4952 	 * the kernel.  This check should be changed into an
4953 	 * assert when the new kobject model is in place since
4954 	 * ports will not be used in kernel to kernel chats
4955 	 */
4956 
4957 	/* do not lock remote port, use raw pointer comparison */
4958 	if (!ip_in_space_noauth(remote, ipc_space_kernel)) {
4959 		/* remote port could be dead, in-transit or in an ipc space */
4960 		if (disp == MACH_MSG_TYPE_MOVE_RECEIVE &&
4961 		    ipc_port_check_circularity(port, remote)) {
4962 			hdr->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
4963 		}
4964 	}
4965 }
4966 
4967 /*
4968  *	Routine:	ipc_kmsg_copyin_from_kernel
4969  *	Purpose:
4970  *		"Copy-in" port rights and out-of-line memory
4971  *		in a message sent from the kernel.
4972  *
4973  *		Because the message comes from the kernel,
4974  *		the implementation assumes there are no errors
4975  *		or peculiarities in the message.
4976  *	Conditions:
4977  *		Nothing locked.
4978  */
4979 
4980 mach_msg_return_t
ipc_kmsg_copyin_from_kernel(ipc_kmsg_t kmsg)4981 ipc_kmsg_copyin_from_kernel(
4982 	ipc_kmsg_t      kmsg)
4983 {
4984 	mach_msg_header_t   *hdr = ikm_header(kmsg);
4985 	mach_msg_bits_t      bits = hdr->msgh_bits;
4986 	mach_msg_type_name_t rname = MACH_MSGH_BITS_REMOTE(bits);
4987 	mach_msg_type_name_t lname = MACH_MSGH_BITS_LOCAL(bits);
4988 	mach_msg_type_name_t vname = MACH_MSGH_BITS_VOUCHER(bits);
4989 	ipc_port_t           remote = hdr->msgh_remote_port;
4990 	ipc_port_t           local = hdr->msgh_local_port;
4991 	ipc_port_t           voucher = ipc_kmsg_get_voucher_port(kmsg);
4992 
4993 	/* translate the destination and reply ports */
4994 	if (!IP_VALID(remote)) {
4995 		return MACH_SEND_INVALID_DEST;
4996 	}
4997 
4998 	ipc_object_copyin_from_kernel(remote, rname);
4999 	if (IP_VALID(local)) {
5000 		ipc_object_copyin_from_kernel(local, lname);
5001 	}
5002 
5003 	if (IP_VALID(voucher)) {
5004 		ipc_object_copyin_from_kernel(voucher, vname);
5005 	}
5006 
5007 	/*
5008 	 *	The common case is a complex message with no reply port,
5009 	 *	because that is what the memory_object interface uses.
5010 	 */
5011 
5012 	if (bits == (MACH_MSGH_BITS_COMPLEX |
5013 	    MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0))) {
5014 		bits = (MACH_MSGH_BITS_COMPLEX |
5015 		    MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, 0));
5016 
5017 		hdr->msgh_bits = bits;
5018 	} else {
5019 		bits = (MACH_MSGH_BITS_OTHER(bits) |
5020 		    MACH_MSGH_BITS_SET_PORTS(ipc_object_copyin_type(rname),
5021 		    ipc_object_copyin_type(lname), ipc_object_copyin_type(vname)));
5022 
5023 		hdr->msgh_bits = bits;
5024 	}
5025 
5026 	ipc_kmsg_set_qos_kernel(kmsg);
5027 
5028 	/* Add trailer and signature to the message */
5029 	ipc_kmsg_init_trailer_and_sign(kmsg, TASK_NULL);
5030 
5031 	if (bits & MACH_MSGH_BITS_COMPLEX) {
5032 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(hdr);
5033 		mach_msg_size_t   count = kbase->msgb_dsc_count;
5034 		mach_msg_kdescriptor_t *kdesc = kbase->msgb_dsc_array;
5035 
5036 		for (mach_msg_size_t i = 0; i < count; i++) {
5037 			switch (mach_msg_kdescriptor_type(&kdesc[i])) {
5038 			case MACH_MSG_PORT_DESCRIPTOR: {
5039 				mach_msg_port_descriptor_t *dsc = &kdesc[i].kdesc_port;
5040 				mach_msg_type_name_t disp = dsc->disposition;
5041 				ipc_port_t           port = dsc->name;
5042 
5043 				dsc->disposition = ipc_object_copyin_type(disp);
5044 				if (IP_VALID(port)) {
5045 					ipc_kmsg_copyin_port_from_kernel(hdr,
5046 					    port, remote, disp);
5047 				}
5048 				break;
5049 			}
5050 			case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
5051 			case MACH_MSG_OOL_DESCRIPTOR: {
5052 				/*
5053 				 * The sender should supply ready-made memory, i.e.
5054 				 * a vm_map_copy_t, so we don't need to do anything.
5055 				 */
5056 				break;
5057 			}
5058 			case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
5059 				mach_msg_ool_ports_descriptor_t *dsc = &kdesc[i].kdesc_port_array;
5060 				mach_msg_type_name_t disp  = dsc->disposition;
5061 				mach_port_array_t    array = dsc->address;
5062 
5063 				dsc->disposition = ipc_object_copyin_type(disp);
5064 
5065 				for (mach_msg_size_t j = 0; j < dsc->count; j++) {
5066 					ipc_port_t port = array[j].port;
5067 
5068 					if (IP_VALID(port)) {
5069 						ipc_kmsg_copyin_port_from_kernel(hdr,
5070 						    port, remote, disp);
5071 					}
5072 				}
5073 				break;
5074 			}
5075 			case MACH_MSG_GUARDED_PORT_DESCRIPTOR: {
5076 				mach_msg_guarded_port_descriptor_t *dsc = &kdesc[i].kdesc_guarded_port;
5077 				mach_msg_type_name_t disp = dsc->disposition;
5078 				ipc_port_t           port = dsc->name;
5079 
5080 				dsc->disposition = ipc_object_copyin_type(disp);
5081 				assert(dsc->flags == 0);
5082 
5083 				if (IP_VALID(port)) {
5084 					ipc_kmsg_copyin_port_from_kernel(hdr,
5085 					    port, remote, disp);
5086 				}
5087 				break;
5088 			}
5089 			default:
5090 				__ipc_kmsg_descriptor_invalid_type_panic(kdesc);
5091 			}
5092 		}
5093 	}
5094 
5095 	return MACH_MSG_SUCCESS;
5096 }
5097 
5098 /*
5099  *	Routine:	ipc_kmsg_send
5100  *	Purpose:
5101  *		Send a message.  The message holds a reference
5102  *		for the destination port in the msgh_remote_port field.
5103  *
5104  *		If unsuccessful, the caller still has possession of
5105  *		the message and must do something with it.  If successful,
5106  *		the message is queued, given to a receiver, destroyed,
5107  *		or handled directly by the kernel via mach_msg.
5108  *	Conditions:
5109  *		Nothing locked.
5110  *	Returns:
5111  *		MACH_MSG_SUCCESS	       The message was accepted.
5112  *		MACH_SEND_TIMED_OUT	       Caller still has message.
5113  *		MACH_SEND_INTERRUPTED	   Caller still has message.
5114  *		MACH_SEND_INVALID_DEST	   Caller still has message.
5115  *      MACH_SEND_INVALID_OPTIONS  Caller still has message.
5116  */
5117 mach_msg_return_t
ipc_kmsg_send(ipc_kmsg_t kmsg,mach_msg_option64_t options,mach_msg_timeout_t send_timeout)5118 ipc_kmsg_send(
5119 	ipc_kmsg_t              kmsg,
5120 	mach_msg_option64_t     options,
5121 	mach_msg_timeout_t      send_timeout)
5122 {
5123 	ipc_port_t port;
5124 	thread_t th = current_thread();
5125 	mach_msg_return_t error = MACH_MSG_SUCCESS;
5126 	boolean_t kernel_reply = FALSE;
5127 	mach_msg_header_t *hdr;
5128 
5129 	/* Check if honor qlimit flag is set on thread. */
5130 	if ((th->options & TH_OPT_HONOR_QLIMIT) == TH_OPT_HONOR_QLIMIT) {
5131 		/* Remove the MACH_SEND_ALWAYS flag to honor queue limit. */
5132 		options &= (~MACH64_SEND_ALWAYS);
5133 		/* Add the timeout flag since the message queue might be full. */
5134 		options |= MACH64_SEND_TIMEOUT;
5135 		th->options &= (~TH_OPT_HONOR_QLIMIT);
5136 	}
5137 
5138 #if IMPORTANCE_INHERITANCE
5139 	bool did_importance = false;
5140 #if IMPORTANCE_TRACE
5141 	mach_msg_id_t imp_msgh_id = -1;
5142 	int           sender_pid  = -1;
5143 #endif /* IMPORTANCE_TRACE */
5144 #endif /* IMPORTANCE_INHERITANCE */
5145 
5146 	hdr = ikm_header(kmsg);
5147 	/* don't allow the creation of a circular loop */
5148 	if (hdr->msgh_bits & MACH_MSGH_BITS_CIRCULAR) {
5149 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_ALL);
5150 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_MSGH_BITS_CIRCULAR);
5151 		return MACH_MSG_SUCCESS;
5152 	}
5153 
5154 	ipc_voucher_send_preprocessing(kmsg);
5155 
5156 	port = hdr->msgh_remote_port;
5157 	assert(IP_VALID(port));
5158 	ip_mq_lock(port);
5159 
5160 	/*
5161 	 * If the destination has been guarded with a reply context, and the
5162 	 * sender is consuming a send-once right, then assume this is a reply
5163 	 * to an RPC and we need to validate that this sender is currently in
5164 	 * the correct context.
5165 	 */
5166 	if (enforce_strict_reply && port->ip_reply_context != 0 &&
5167 	    ((options & MACH64_SEND_KERNEL) == 0) &&
5168 	    MACH_MSGH_BITS_REMOTE(hdr->msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE) {
5169 		error = ipc_kmsg_validate_reply_context_locked(options,
5170 		    port, th->ith_voucher, th->ith_voucher_name);
5171 		if (error != MACH_MSG_SUCCESS) {
5172 			ip_mq_unlock(port);
5173 			return error;
5174 		}
5175 	}
5176 
5177 #if IMPORTANCE_INHERITANCE
5178 retry:
5179 #endif /* IMPORTANCE_INHERITANCE */
5180 	/*
5181 	 *	Can't deliver to a dead port.
5182 	 *	However, we can pretend it got sent
5183 	 *	and was then immediately destroyed.
5184 	 */
5185 	if (!ip_active(port)) {
5186 		ip_mq_unlock(port);
5187 		if (did_importance) {
5188 			/*
5189 			 * We're going to pretend we delivered this message
5190 			 * successfully, and just eat the kmsg. However, the
5191 			 * kmsg is actually visible via the importance_task!
5192 			 * We need to cleanup this linkage before we destroy
5193 			 * the message, and more importantly before we set the
5194 			 * msgh_remote_port to NULL. See: 34302571
5195 			 */
5196 			ipc_importance_clean(kmsg);
5197 		}
5198 		ip_release(port);  /* JMM - Future: release right, not just ref */
5199 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
5200 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_SEND_INVALID_DEST);
5201 		return MACH_MSG_SUCCESS;
5202 	}
5203 
5204 	if (ip_in_space(port, ipc_space_kernel)) {
5205 		port->ip_messages.imq_seqno++;
5206 		ip_mq_unlock(port);
5207 
5208 		counter_inc(&current_task()->messages_sent);
5209 
5210 		/*
5211 		 * Call the server routine, and get the reply message to send.
5212 		 */
5213 		kmsg = ipc_kobject_server(port, kmsg, options);
5214 		if (kmsg == IKM_NULL) {
5215 			return MACH_MSG_SUCCESS;
5216 		}
5217 		/* reload hdr since kmsg changed */
5218 		hdr = ikm_header(kmsg);
5219 
5220 		ipc_kmsg_init_trailer_and_sign(kmsg, TASK_NULL);
5221 
5222 		/* restart the KMSG_INFO tracing for the reply message */
5223 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_START);
5224 		port = hdr->msgh_remote_port;
5225 		assert(IP_VALID(port));
5226 		ip_mq_lock(port);
5227 		/* fall thru with reply - same options */
5228 		kernel_reply = TRUE;
5229 		if (!ip_active(port)) {
5230 			error = MACH_SEND_INVALID_DEST;
5231 		}
5232 	}
5233 
5234 #if IMPORTANCE_INHERITANCE
5235 	/*
5236 	 * Need to see if this message needs importance donation and/or
5237 	 * propagation.  That routine can drop the port lock temporarily.
5238 	 * If it does we'll have to revalidate the destination.
5239 	 */
5240 	if (!did_importance) {
5241 		did_importance = true;
5242 		if (ipc_importance_send(kmsg, options)) {
5243 			goto retry;
5244 		}
5245 	}
5246 #endif /* IMPORTANCE_INHERITANCE */
5247 
5248 	if (error != MACH_MSG_SUCCESS) {
5249 		ip_mq_unlock(port);
5250 	} else {
5251 		/*
5252 		 * We have a valid message and a valid reference on the port.
5253 		 * call mqueue_send() on its message queue.
5254 		 */
5255 		ipc_special_reply_port_msg_sent(port);
5256 
5257 		error = ipc_mqueue_send_locked(&port->ip_messages, kmsg,
5258 		    options, send_timeout);
5259 		/* port unlocked */
5260 	}
5261 
5262 #if IMPORTANCE_INHERITANCE
5263 	if (did_importance) {
5264 		__unused int importance_cleared = 0;
5265 		switch (error) {
5266 		case MACH_SEND_TIMED_OUT:
5267 		case MACH_SEND_NO_BUFFER:
5268 		case MACH_SEND_INTERRUPTED:
5269 		case MACH_SEND_INVALID_DEST:
5270 			/*
5271 			 * We still have the kmsg and its
5272 			 * reference on the port.  But we
5273 			 * have to back out the importance
5274 			 * boost.
5275 			 *
5276 			 * The port could have changed hands,
5277 			 * be inflight to another destination,
5278 			 * etc...  But in those cases our
5279 			 * back-out will find the new owner
5280 			 * (and all the operations that
5281 			 * transferred the right should have
5282 			 * applied their own boost adjustments
5283 			 * to the old owner(s)).
5284 			 */
5285 			importance_cleared = 1;
5286 			ipc_importance_clean(kmsg);
5287 			break;
5288 
5289 		case MACH_MSG_SUCCESS:
5290 		default:
5291 			break;
5292 		}
5293 #if IMPORTANCE_TRACE
5294 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, (IMPORTANCE_CODE(IMP_MSG, IMP_MSG_SEND)) | DBG_FUNC_END,
5295 		    task_pid(current_task()), sender_pid, imp_msgh_id, importance_cleared, 0);
5296 #endif /* IMPORTANCE_TRACE */
5297 	}
5298 #endif /* IMPORTANCE_INHERITANCE */
5299 
5300 	/*
5301 	 * If the port has been destroyed while we wait, treat the message
5302 	 * as a successful delivery (like we do for an inactive port).
5303 	 */
5304 	if (error == MACH_SEND_INVALID_DEST) {
5305 		ip_release(port); /* JMM - Future: release right, not just ref */
5306 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
5307 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_SEND_INVALID_DEST);
5308 		return MACH_MSG_SUCCESS;
5309 	}
5310 
5311 	if (error != MACH_MSG_SUCCESS && kernel_reply) {
5312 		/*
5313 		 * Kernel reply messages that fail can't be allowed to
5314 		 * pseudo-receive on error conditions. We need to just treat
5315 		 * the message as a successful delivery.
5316 		 */
5317 		ip_release(port); /* JMM - Future: release right, not just ref */
5318 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
5319 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, error);
5320 		return MACH_MSG_SUCCESS;
5321 	}
5322 	return error;
5323 }
5324 
5325 /*
5326  *	Routine:	ipc_kmsg_put_to_kernel
5327  *	Purpose:
5328  *		Copies a message buffer to a kernel message.
5329  *		Frees the message buffer.
5330  *		No errors allowed.
5331  *	Conditions:
5332  *		Nothing locked.
5333  */
5334 void
ipc_kmsg_put_to_kernel(mach_msg_header_t * msg,mach_msg_option64_t options,ipc_kmsg_t kmsg,mach_msg_size_t rcv_size)5335 ipc_kmsg_put_to_kernel(
5336 	mach_msg_header_t      *msg,
5337 	mach_msg_option64_t     options,
5338 	ipc_kmsg_t              kmsg,
5339 	mach_msg_size_t         rcv_size) /* includes trailer size */
5340 {
5341 	mach_msg_header_t *hdr = ikm_header(kmsg);
5342 	mach_msg_kbase_t  *src_base;
5343 	mach_msg_size_t    desc_count, kdata_sz;
5344 
5345 	assert(kmsg->ikm_aux_size == 0);
5346 	assert(rcv_size >= hdr->msgh_size);
5347 
5348 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
5349 		src_base   = mach_msg_header_to_kbase(hdr);
5350 		desc_count = src_base->msgb_dsc_count;
5351 		kdata_sz   = ikm_kdata_size(desc_count, true);
5352 	} else {
5353 		desc_count = 0;
5354 		kdata_sz   = ikm_kdata_size(desc_count, false);
5355 	}
5356 
5357 	if (ikm_is_linear(kmsg)) {
5358 		memcpy(msg, hdr, rcv_size);
5359 	} else {
5360 		memcpy(msg, hdr, kdata_sz);
5361 		memcpy((char *)msg + kdata_sz,
5362 		    kmsg->ikm_udata, rcv_size - kdata_sz);
5363 	}
5364 
5365 	if (desc_count) {
5366 		mach_msg_kbase_t *dst_base = mach_msg_header_to_kbase(msg);
5367 
5368 		if (options & MACH64_POLICY_KERNEL_EXTENSION) {
5369 			ipc_kmsg_strip_descriptors(dst_base->msgb_dsc_array,
5370 			    src_base->msgb_dsc_array, desc_count);
5371 		} else {
5372 			ipc_kmsg_relocate_descriptors(dst_base->msgb_dsc_array,
5373 			    src_base->msgb_dsc_array, desc_count);
5374 		}
5375 	}
5376 
5377 	ipc_kmsg_free(kmsg);
5378 }
5379 
5380 /** @} */
5381 #pragma mark ipc_kmsg tracing
5382 
5383 #define KMSG_TRACE_FLAG_TRACED     0x000001
5384 #define KMSG_TRACE_FLAG_COMPLEX    0x000002
5385 #define KMSG_TRACE_FLAG_OOLMEM     0x000004
5386 #define KMSG_TRACE_FLAG_VCPY       0x000008
5387 #define KMSG_TRACE_FLAG_PCPY       0x000010
5388 #define KMSG_TRACE_FLAG_SND64      0x000020
5389 #define KMSG_TRACE_FLAG_RAISEIMP   0x000040
5390 #define KMSG_TRACE_FLAG_APP_SRC    0x000080
5391 #define KMSG_TRACE_FLAG_APP_DST    0x000100
5392 #define KMSG_TRACE_FLAG_DAEMON_SRC 0x000200
5393 #define KMSG_TRACE_FLAG_DAEMON_DST 0x000400
5394 #define KMSG_TRACE_FLAG_DST_NDFLTQ 0x000800
5395 #define KMSG_TRACE_FLAG_SRC_NDFLTQ 0x001000
5396 #define KMSG_TRACE_FLAG_DST_SONCE  0x002000
5397 #define KMSG_TRACE_FLAG_SRC_SONCE  0x004000
5398 #define KMSG_TRACE_FLAG_CHECKIN    0x008000
5399 #define KMSG_TRACE_FLAG_ONEWAY     0x010000
5400 #define KMSG_TRACE_FLAG_IOKIT      0x020000
5401 #define KMSG_TRACE_FLAG_SNDRCV     0x040000
5402 #define KMSG_TRACE_FLAG_DSTQFULL   0x080000
5403 #define KMSG_TRACE_FLAG_VOUCHER    0x100000
5404 #define KMSG_TRACE_FLAG_TIMER      0x200000
5405 #define KMSG_TRACE_FLAG_SEMA       0x400000
5406 #define KMSG_TRACE_FLAG_DTMPOWNER  0x800000
5407 #define KMSG_TRACE_FLAG_GUARDED_DESC 0x1000000
5408 
5409 #define KMSG_TRACE_FLAGS_MASK      0x1ffffff
5410 #define KMSG_TRACE_FLAGS_SHIFT     8
5411 
5412 #define KMSG_TRACE_ID_SHIFT        32
5413 
5414 #define KMSG_TRACE_PORTS_MASK      0xff
5415 #define KMSG_TRACE_PORTS_SHIFT     0
5416 
5417 #if (KDEBUG_LEVEL >= KDEBUG_LEVEL_STANDARD)
5418 
5419 void
ipc_kmsg_trace_send(ipc_kmsg_t kmsg,mach_msg_option64_t option)5420 ipc_kmsg_trace_send(ipc_kmsg_t kmsg, mach_msg_option64_t option)
5421 {
5422 	task_t send_task = TASK_NULL;
5423 	ipc_port_t dst_port, src_port;
5424 	boolean_t is_task_64bit;
5425 	mach_msg_header_t *msg;
5426 	mach_msg_trailer_t *trailer;
5427 
5428 	int dest_type = 0;
5429 	uint32_t msg_size = 0;
5430 	uint64_t msg_flags = KMSG_TRACE_FLAG_TRACED;
5431 	uint32_t num_ports = 0;
5432 	uint32_t send_pid, dst_pid;
5433 
5434 	/*
5435 	 * check to see not only if ktracing is enabled, but if we will
5436 	 * _actually_ emit the KMSG_INFO tracepoint. This saves us a
5437 	 * significant amount of processing (and a port lock hold) in
5438 	 * the non-tracing case.
5439 	 */
5440 	if (__probable((kdebug_enable & KDEBUG_TRACE) == 0)) {
5441 		return;
5442 	}
5443 	if (!kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO))) {
5444 		return;
5445 	}
5446 
5447 	msg = ikm_header(kmsg);
5448 
5449 	dst_port = msg->msgh_remote_port;
5450 	if (!IPC_PORT_VALID(dst_port)) {
5451 		return;
5452 	}
5453 
5454 	/*
5455 	 * Message properties / options
5456 	 */
5457 	if ((option & (MACH_SEND_MSG | MACH_RCV_MSG)) == (MACH_SEND_MSG | MACH_RCV_MSG)) {
5458 		msg_flags |= KMSG_TRACE_FLAG_SNDRCV;
5459 	}
5460 
5461 	if (msg->msgh_id >= is_iokit_subsystem.start &&
5462 	    msg->msgh_id < is_iokit_subsystem.end + 100) {
5463 		msg_flags |= KMSG_TRACE_FLAG_IOKIT;
5464 	}
5465 	/* magic XPC checkin message id (XPC_MESSAGE_ID_CHECKIN) from libxpc */
5466 	else if (msg->msgh_id == 0x77303074u /* w00t */) {
5467 		msg_flags |= KMSG_TRACE_FLAG_CHECKIN;
5468 	}
5469 
5470 	if (msg->msgh_bits & MACH_MSGH_BITS_RAISEIMP) {
5471 		msg_flags |= KMSG_TRACE_FLAG_RAISEIMP;
5472 	}
5473 
5474 	if (unsafe_convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg))) {
5475 		msg_flags |= KMSG_TRACE_FLAG_VOUCHER;
5476 	}
5477 
5478 	/*
5479 	 * Sending task / port
5480 	 */
5481 	send_task = current_task();
5482 	send_pid = task_pid(send_task);
5483 
5484 	if (send_pid != 0) {
5485 		if (task_is_daemon(send_task)) {
5486 			msg_flags |= KMSG_TRACE_FLAG_DAEMON_SRC;
5487 		} else if (task_is_app(send_task)) {
5488 			msg_flags |= KMSG_TRACE_FLAG_APP_SRC;
5489 		}
5490 	}
5491 
5492 	is_task_64bit = (send_task->map->max_offset > VM_MAX_ADDRESS);
5493 	if (is_task_64bit) {
5494 		msg_flags |= KMSG_TRACE_FLAG_SND64;
5495 	}
5496 
5497 	src_port = msg->msgh_local_port;
5498 	if (src_port) {
5499 		if (src_port->ip_messages.imq_qlimit != MACH_PORT_QLIMIT_DEFAULT) {
5500 			msg_flags |= KMSG_TRACE_FLAG_SRC_NDFLTQ;
5501 		}
5502 		switch (MACH_MSGH_BITS_LOCAL(msg->msgh_bits)) {
5503 		case MACH_MSG_TYPE_MOVE_SEND_ONCE:
5504 			msg_flags |= KMSG_TRACE_FLAG_SRC_SONCE;
5505 			break;
5506 		default:
5507 			break;
5508 		}
5509 	} else {
5510 		msg_flags |= KMSG_TRACE_FLAG_ONEWAY;
5511 	}
5512 
5513 
5514 	/*
5515 	 * Destination task / port
5516 	 */
5517 	ip_mq_lock(dst_port);
5518 	if (!ip_active(dst_port)) {
5519 		/* dst port is being torn down */
5520 		dst_pid = (uint32_t)0xfffffff0;
5521 	} else if (dst_port->ip_tempowner) {
5522 		msg_flags |= KMSG_TRACE_FLAG_DTMPOWNER;
5523 		if (IIT_NULL != ip_get_imp_task(dst_port)) {
5524 			dst_pid = task_pid(dst_port->ip_imp_task->iit_task);
5525 		} else {
5526 			dst_pid = (uint32_t)0xfffffff1;
5527 		}
5528 	} else if (!ip_in_a_space(dst_port)) {
5529 		/* dst_port is otherwise in-transit */
5530 		dst_pid = (uint32_t)0xfffffff2;
5531 	} else {
5532 		if (ip_in_space(dst_port, ipc_space_kernel)) {
5533 			dst_pid = 0;
5534 		} else {
5535 			ipc_space_t dst_space;
5536 			dst_space = ip_get_receiver(dst_port);
5537 			if (dst_space && is_active(dst_space)) {
5538 				dst_pid = task_pid(dst_space->is_task);
5539 				if (task_is_daemon(dst_space->is_task)) {
5540 					msg_flags |= KMSG_TRACE_FLAG_DAEMON_DST;
5541 				} else if (task_is_app(dst_space->is_task)) {
5542 					msg_flags |= KMSG_TRACE_FLAG_APP_DST;
5543 				}
5544 			} else {
5545 				/* receiving task is being torn down */
5546 				dst_pid = (uint32_t)0xfffffff3;
5547 			}
5548 		}
5549 	}
5550 
5551 	if (dst_port->ip_messages.imq_qlimit != MACH_PORT_QLIMIT_DEFAULT) {
5552 		msg_flags |= KMSG_TRACE_FLAG_DST_NDFLTQ;
5553 	}
5554 	if (imq_full(&dst_port->ip_messages)) {
5555 		msg_flags |= KMSG_TRACE_FLAG_DSTQFULL;
5556 	}
5557 
5558 	dest_type = ip_type(dst_port);
5559 
5560 	ip_mq_unlock(dst_port);
5561 
5562 	switch (dest_type) {
5563 	case IKOT_SEMAPHORE:
5564 		msg_flags |= KMSG_TRACE_FLAG_SEMA;
5565 		break;
5566 	case IOT_TIMER_PORT:
5567 	case IKOT_CLOCK:
5568 		msg_flags |= KMSG_TRACE_FLAG_TIMER;
5569 		break;
5570 	case IKOT_MAIN_DEVICE:
5571 	case IKOT_IOKIT_CONNECT:
5572 	case IKOT_IOKIT_OBJECT:
5573 	case IKOT_IOKIT_IDENT:
5574 	case IKOT_UEXT_OBJECT:
5575 		msg_flags |= KMSG_TRACE_FLAG_IOKIT;
5576 		break;
5577 	default:
5578 		break;
5579 	}
5580 
5581 	switch (MACH_MSGH_BITS_REMOTE(msg->msgh_bits)) {
5582 	case MACH_MSG_TYPE_PORT_SEND_ONCE:
5583 		msg_flags |= KMSG_TRACE_FLAG_DST_SONCE;
5584 		break;
5585 	default:
5586 		break;
5587 	}
5588 
5589 
5590 	/*
5591 	 * Message size / content
5592 	 */
5593 	msg_size = msg->msgh_size - sizeof(mach_msg_header_t);
5594 
5595 	if (msg->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
5596 		mach_msg_kbase_t *kbase = mach_msg_header_to_kbase(msg);
5597 		mach_msg_kdescriptor_t *kdesc;
5598 		mach_msg_descriptor_type_t dtype;
5599 
5600 		msg_flags |= KMSG_TRACE_FLAG_COMPLEX;
5601 
5602 		for (mach_msg_size_t i = 0; i < kbase->msgb_dsc_count; i++) {
5603 			kdesc = &kbase->msgb_dsc_array[i];
5604 			dtype = mach_msg_kdescriptor_type(kdesc);
5605 
5606 			switch (dtype) {
5607 			case MACH_MSG_PORT_DESCRIPTOR:
5608 				num_ports++;
5609 				break;
5610 			case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
5611 			case MACH_MSG_OOL_DESCRIPTOR: {
5612 				mach_msg_ool_descriptor_t *dsc = &kdesc->kdesc_memory;
5613 
5614 				msg_flags |= KMSG_TRACE_FLAG_OOLMEM;
5615 				msg_size += dsc->size;
5616 				if (dsc->size > msg_ool_size_small &&
5617 				    (dsc->copy == MACH_MSG_PHYSICAL_COPY) &&
5618 				    !dsc->deallocate) {
5619 					msg_flags |= KMSG_TRACE_FLAG_PCPY;
5620 				} else if (dsc->size <= msg_ool_size_small) {
5621 					msg_flags |= KMSG_TRACE_FLAG_PCPY;
5622 				} else {
5623 					msg_flags |= KMSG_TRACE_FLAG_VCPY;
5624 				}
5625 			} break;
5626 			case MACH_MSG_OOL_PORTS_DESCRIPTOR:
5627 				num_ports += kdesc->kdesc_port_array.count;
5628 				break;
5629 			case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
5630 				num_ports++;
5631 				msg_flags |= KMSG_TRACE_FLAG_GUARDED_DESC;
5632 				break;
5633 			default:
5634 				break;
5635 			}
5636 			msg_size -= ikm_user_desc_size(dtype, is_task_64bit);
5637 		}
5638 	}
5639 
5640 	/*
5641 	 * Trailer contents
5642 	 */
5643 	trailer = (mach_msg_trailer_t *)ipc_kmsg_get_trailer(kmsg);
5644 	if (trailer->msgh_trailer_size <= sizeof(mach_msg_security_trailer_t)) {
5645 		mach_msg_security_trailer_t *strailer;
5646 		strailer = (mach_msg_security_trailer_t *)trailer;
5647 		/*
5648 		 * verify the sender PID: replies from the kernel often look
5649 		 * like self-talk because the sending port is not reset.
5650 		 */
5651 		if (memcmp(&strailer->msgh_sender,
5652 		    &KERNEL_SECURITY_TOKEN,
5653 		    sizeof(KERNEL_SECURITY_TOKEN)) == 0) {
5654 			send_pid = 0;
5655 			msg_flags &= ~(KMSG_TRACE_FLAG_APP_SRC | KMSG_TRACE_FLAG_DAEMON_SRC);
5656 		}
5657 	}
5658 
5659 	KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END,
5660 	    (uintptr_t)send_pid,
5661 	    (uintptr_t)dst_pid,
5662 	    (uintptr_t)(((uint64_t)msg->msgh_id << KMSG_TRACE_ID_SHIFT) | msg_size),
5663 	    (uintptr_t)(
5664 		    ((msg_flags & KMSG_TRACE_FLAGS_MASK) << KMSG_TRACE_FLAGS_SHIFT) |
5665 		    ((num_ports & KMSG_TRACE_PORTS_MASK) << KMSG_TRACE_PORTS_SHIFT)
5666 		    )
5667 	    );
5668 }
5669 
5670 #endif
5671