xref: /xnu-8792.61.2/osfmk/ipc/ipc_kmsg.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
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 
74 #include <mach/mach_types.h>
75 #include <mach/boolean.h>
76 #include <mach/kern_return.h>
77 #include <mach/message.h>
78 #include <mach/port.h>
79 #include <mach/vm_map.h>
80 #include <mach/mach_vm.h>
81 #include <mach/vm_statistics.h>
82 
83 #include <kern/kern_types.h>
84 #include <kern/assert.h>
85 #include <kern/debug.h>
86 #include <kern/ipc_kobject.h>
87 #include <kern/kalloc.h>
88 #include <kern/zalloc.h>
89 #include <kern/processor.h>
90 #include <kern/thread.h>
91 #include <kern/thread_group.h>
92 #include <kern/sched_prim.h>
93 #include <kern/misc_protos.h>
94 #include <kern/cpu_data.h>
95 #include <kern/policy_internal.h>
96 #include <kern/mach_filter.h>
97 
98 #include <pthread/priority_private.h>
99 
100 #include <machine/limits.h>
101 
102 #include <vm/vm_map.h>
103 #include <vm/vm_object.h>
104 #include <vm/vm_kern.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_port.h>
114 #include <ipc/ipc_right.h>
115 #include <ipc/ipc_hash.h>
116 #include <ipc/ipc_importance.h>
117 #include <ipc/ipc_service_port.h>
118 #include <libkern/coreanalytics/coreanalytics.h>
119 
120 #if MACH_FLIPC
121 #include <kern/mach_node.h>
122 #include <ipc/flipc.h>
123 #endif
124 
125 #include <os/overflow.h>
126 
127 #include <security/mac_mach_internal.h>
128 
129 #include <device/device_server.h>
130 
131 #include <string.h>
132 
133 #if DEBUG
134 #define DEBUG_MSGS_K64 1
135 #endif
136 
137 #include <sys/kdebug.h>
138 #include <libkern/OSAtomic.h>
139 
140 #include <libkern/crypto/sha2.h>
141 
142 #include <ptrauth.h>
143 #if __has_feature(ptrauth_calls)
144 #include <libkern/ptrauth_utils.h>
145 #endif
146 
147 #if CONFIG_CSR
148 #include <sys/csr.h>
149 #endif
150 
151 /*
152  * In kernel, complex mach msg have a simpler representation than userspace:
153  *
154  * <header>
155  * <desc-count>
156  * <descriptors> * desc-count
157  * <body>
158  *
159  * And the descriptors are of a fake type `mach_msg_descriptor_t`,
160  * that is large enough to accommodate for any possible representation.
161  *
162  * The `type` field of any desciptor is always at the same offset,
163  * and the smallest possible descriptor is of size MACH_MSG_DESC_MIN_SIZE.
164  *
165  * Note:
166  * - KERN_DESC_SIZE is 16 on all kernels
167  * - MACH_MSG_DESC_MIN_SIZE is 12 on all kernels
168  */
169 
170 #define KERNEL_DESC_SIZE             sizeof(mach_msg_descriptor_t)
171 #define MACH_MSG_DESC_MIN_SIZE       sizeof(mach_msg_type_descriptor_t)
172 
173 #define USER_HEADER_SIZE_DELTA \
174 	((mach_msg_size_t)(sizeof(mach_msg_header_t) - sizeof(mach_msg_user_header_t)))
175 
176 #define USER_DESC_MAX_DELTA \
177 	(KERNEL_DESC_SIZE - MACH_MSG_DESC_MIN_SIZE)
178 
179 #define mach_validate_desc_type(t) \
180 	static_assert(MACH_MSG_DESC_MIN_SIZE <= sizeof(t) && \
181 	sizeof(t) <= sizeof(mach_msg_descriptor_t))
182 
183 mach_validate_desc_type(mach_msg_descriptor_t);
184 mach_validate_desc_type(mach_msg_port_descriptor_t);
185 mach_validate_desc_type(mach_msg_user_port_descriptor_t);
186 mach_validate_desc_type(mach_msg_type_descriptor_t);
187 mach_validate_desc_type(mach_msg_ool_descriptor32_t);
188 mach_validate_desc_type(mach_msg_ool_descriptor64_t);
189 mach_validate_desc_type(mach_msg_ool_ports_descriptor32_t);
190 mach_validate_desc_type(mach_msg_ool_ports_descriptor64_t);
191 mach_validate_desc_type(mach_msg_guarded_port_descriptor32_t);
192 mach_validate_desc_type(mach_msg_guarded_port_descriptor64_t);
193 
194 extern char *proc_name_address(struct proc *p);
195 
196 /*
197  * As CA framework replies on successfully allocating zalloc memory,
198  * we maintain a small buffer that gets flushed when full. This helps us avoid taking spinlocks when working with CA.
199  */
200 #define REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE         2
201 
202 struct reply_port_semantics_violations_rb_entry {
203 	char        proc_name[CA_PROCNAME_LEN];
204 };
205 struct reply_port_semantics_violations_rb_entry reply_port_semantics_violations_rb[REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE];
206 static uint8_t reply_port_semantics_violations_rb_index = 0;
207 
208 LCK_GRP_DECLARE(reply_port_telemetry_lock_grp, "reply_port_telemetry_lock_grp");
209 LCK_SPIN_DECLARE(reply_port_telemetry_lock, &reply_port_telemetry_lock_grp);
210 
211 /* Telemetry: report back the process name violating reply port semantics */
212 CA_EVENT(reply_port_semantics_violations,
213     CA_STATIC_STRING(CA_PROCNAME_LEN), proc_name);
214 
215 
216 /* Routine: flush_reply_port_semantics_violations_telemetry
217  * Conditions:
218  *              Assumes the reply_port_telemetry_lock is held.
219  *              Unlocks it before returning.
220  */
221 static void
flush_reply_port_semantics_violations_telemetry()222 flush_reply_port_semantics_violations_telemetry()
223 {
224 	struct reply_port_semantics_violations_rb_entry local_rb[REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE];
225 	uint8_t local_rb_index = 0;
226 
227 	if (__improbable(reply_port_semantics_violations_rb_index > REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE)) {
228 		panic("Invalid reply port semantics violations buffer index %d > %d",
229 		    reply_port_semantics_violations_rb_index, REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE);
230 	}
231 
232 	/*
233 	 * We operate on local copy of telemetry buffer because CA framework relies on successfully
234 	 * allocating zalloc memory. It can not do that if we are accessing the shared buffer
235 	 * with spin locks held.
236 	 */
237 	while (local_rb_index != reply_port_semantics_violations_rb_index) {
238 		local_rb[local_rb_index] = reply_port_semantics_violations_rb[local_rb_index];
239 		local_rb_index++;
240 	}
241 
242 	lck_spin_unlock(&reply_port_telemetry_lock);
243 
244 	while (local_rb_index > 0) {
245 		struct reply_port_semantics_violations_rb_entry *entry = &local_rb[--local_rb_index];
246 
247 		ca_event_t ca_event = CA_EVENT_ALLOCATE_FLAGS(reply_port_semantics_violations, Z_NOWAIT);
248 		if (ca_event) {
249 			CA_EVENT_TYPE(reply_port_semantics_violations) * event = ca_event->data;
250 			strlcpy(event->proc_name, entry->proc_name, CA_PROCNAME_LEN);
251 			CA_EVENT_SEND(ca_event);
252 		}
253 	}
254 
255 	/*
256 	 * Finally call out the buffer as empty. This is also a sort of rate limiting mechanisms for the events.
257 	 * Events will get dropped until the buffer is not fully flushed.
258 	 */
259 	lck_spin_lock(&reply_port_telemetry_lock);
260 	reply_port_semantics_violations_rb_index = 0;
261 }
262 
263 static void
stash_reply_port_semantics_violations_telemetry()264 stash_reply_port_semantics_violations_telemetry()
265 {
266 	struct reply_port_semantics_violations_rb_entry *entry;
267 
268 	lck_spin_lock(&reply_port_telemetry_lock);
269 
270 	if (reply_port_semantics_violations_rb_index == REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE) {
271 		/* Dropping the event since buffer is full. */
272 		lck_spin_unlock(&reply_port_telemetry_lock);
273 		return;
274 	}
275 
276 	task_t task = current_task_early();
277 	if (task) {
278 		char *proc_name = (char *) "unknown";
279 #ifdef MACH_BSD
280 		proc_name = proc_name_address(get_bsdtask_info(task));
281 #endif /* MACH_BSD */
282 		entry = &reply_port_semantics_violations_rb[reply_port_semantics_violations_rb_index++];
283 		strlcpy(entry->proc_name, proc_name, CA_PROCNAME_LEN);
284 	}
285 
286 	if (reply_port_semantics_violations_rb_index == REPLY_PORT_SEMANTICS_VIOLATIONS_RB_SIZE) {
287 		flush_reply_port_semantics_violations_telemetry();
288 	}
289 
290 	lck_spin_unlock(&reply_port_telemetry_lock);
291 }
292 
293 /* Update following two helpers if new descriptor type is added */
294 static_assert(MACH_MSG_DESCRIPTOR_MAX == MACH_MSG_GUARDED_PORT_DESCRIPTOR);
295 
296 static inline mach_msg_size_t
ikm_user_desc_size(mach_msg_descriptor_type_t type,bool is_task_64bit)297 ikm_user_desc_size(
298 	mach_msg_descriptor_type_t type,
299 	bool                       is_task_64bit)
300 {
301 	if (is_task_64bit) {
302 		switch (type) {
303 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
304 		case MACH_MSG_OOL_DESCRIPTOR:
305 			return sizeof(mach_msg_ool_descriptor64_t);
306 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
307 			return sizeof(mach_msg_ool_ports_descriptor64_t);
308 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
309 			return sizeof(mach_msg_guarded_port_descriptor64_t);
310 		default: /* MACH_MSG_PORT_DESCRIPTOR */
311 			return sizeof(mach_msg_user_port_descriptor_t);
312 		}
313 	} else {
314 		switch (type) {
315 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
316 		case MACH_MSG_OOL_DESCRIPTOR:
317 			return sizeof(mach_msg_ool_descriptor32_t);
318 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
319 			return sizeof(mach_msg_ool_ports_descriptor32_t);
320 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
321 			return sizeof(mach_msg_guarded_port_descriptor32_t);
322 		default: /* MACH_MSG_PORT_DESCRIPTOR */
323 			return sizeof(mach_msg_user_port_descriptor_t);
324 		}
325 	}
326 }
327 
328 static inline bool
ikm_user_desc_type_valid(mach_msg_descriptor_type_t type)329 ikm_user_desc_type_valid(
330 	mach_msg_descriptor_type_t type)
331 {
332 	return type <= MACH_MSG_DESCRIPTOR_MAX;
333 }
334 
335 /*
336  * Measure the total descriptor size in a kmsg.
337  *
338  * Condition:
339  *     Descriptors must have valid type and message is well-formed.
340  *     See ikm_check_descriptors().
341  */
342 static mach_msg_size_t
ikm_total_desc_size(ipc_kmsg_t kmsg,vm_map_t map,mach_msg_size_t body_adj,mach_msg_size_t header_adj,bool user_descs)343 ikm_total_desc_size(
344 	ipc_kmsg_t      kmsg,
345 	vm_map_t        map,
346 	mach_msg_size_t body_adj,    /* gap formed during copyout_body memmove */
347 	mach_msg_size_t header_adj,  /* gap formed during put_to_user */
348 	bool            user_descs)  /* are descriptors user sized */
349 {
350 	mach_msg_size_t total = 0;
351 	bool is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
352 	mach_msg_size_t hdr_size = sizeof(mach_msg_header_t) - header_adj;
353 	/*
354 	 * hdr can be of type (mach_msg_user_header_t *) or (mach_msg_header_t *).
355 	 * following code relies on the fact that both structs share the same
356 	 * first two fields. (msgh_bits and msgh_size)
357 	 */
358 	static_assert(offsetof(mach_msg_user_header_t, msgh_bits) ==
359 	    offsetof(mach_msg_header_t, msgh_bits));
360 	static_assert(offsetof(mach_msg_user_header_t, msgh_size) ==
361 	    offsetof(mach_msg_header_t, msgh_size));
362 
363 	mach_msg_header_t *hdr = (mach_msg_header_t *)((vm_offset_t)ikm_header(kmsg) + header_adj);
364 
365 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
366 		mach_msg_body_t *body;
367 		mach_msg_type_number_t dsc_count;
368 		mach_msg_size_t dsize;
369 		mach_msg_descriptor_t *daddr;
370 
371 		body = (mach_msg_body_t *)((vm_offset_t)hdr + hdr_size);
372 		dsc_count = body->msgh_descriptor_count;
373 
374 		if (!user_descs) {
375 			return dsc_count * KERNEL_DESC_SIZE;
376 		}
377 
378 		daddr = (mach_msg_descriptor_t *)((vm_offset_t)(body + 1) + body_adj);
379 		for (uint32_t i = 0; i < dsc_count; i++) {
380 			dsize = ikm_user_desc_size(daddr->type.type, is_task_64bit);
381 			daddr = (mach_msg_descriptor_t *)((vm_offset_t)daddr + dsize);
382 			total += dsize;
383 		}
384 	}
385 
386 	return total;
387 }
388 
389 /* Pre-validate descriptors and message size during copyin */
390 __result_use_check
391 static mach_msg_return_t
ikm_check_descriptors(ipc_kmsg_t kmsg,vm_map_t map,mach_msg_size_t copied_in)392 ikm_check_descriptors(
393 	ipc_kmsg_t      kmsg, /* a complex message */
394 	vm_map_t        map,
395 	mach_msg_size_t copied_in)
396 {
397 	mach_msg_body_t *body;
398 	mach_msg_type_number_t dsc_count;
399 	mach_msg_size_t dsize;
400 	vm_offset_t end;
401 	mach_msg_descriptor_t *daddr;
402 
403 	bool is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
404 	mach_msg_size_t hdr_size = sizeof(mach_msg_header_t);
405 	mach_msg_size_t base_size = sizeof(mach_msg_base_t);
406 	mach_msg_header_t *hdr = ikm_header(kmsg);
407 
408 	assert(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX);
409 
410 	body = (mach_msg_body_t *)((vm_offset_t)hdr + hdr_size);
411 	dsc_count = body->msgh_descriptor_count;
412 	daddr = (mach_msg_descriptor_t *)(vm_offset_t)(body + 1);
413 	/* Maximum possible descriptor end address */
414 	end = (vm_offset_t)hdr + base_size + copied_in;
415 
416 	for (uint32_t i = 0; i < dsc_count; i++) {
417 		if ((vm_offset_t)daddr + MACH_MSG_DESC_MIN_SIZE > end) {
418 			return MACH_SEND_MSG_TOO_SMALL;
419 		}
420 		/* Now we can access daddr->type safely */
421 		if (!ikm_user_desc_type_valid(daddr->type.type)) {
422 			return MACH_SEND_INVALID_TYPE;
423 		}
424 		dsize = ikm_user_desc_size(daddr->type.type, is_task_64bit);
425 
426 		if ((vm_offset_t)daddr + dsize > end) {
427 			return MACH_SEND_MSG_TOO_SMALL;
428 		}
429 		daddr = (mach_msg_descriptor_t *)((vm_offset_t)daddr + dsize);
430 	}
431 
432 	return MACH_MSG_SUCCESS;
433 }
434 
435 /* Measure the size of user data content carried in kmsg. */
436 static mach_msg_size_t
ikm_content_size(ipc_kmsg_t kmsg,vm_map_t map,mach_msg_size_t header_adj,bool user_descs)437 ikm_content_size(
438 	ipc_kmsg_t      kmsg,
439 	vm_map_t        map,
440 	mach_msg_size_t header_adj,  /* gap formed during put_to_user */
441 	bool            user_descs)  /* are descriptors user sized */
442 {
443 	mach_msg_size_t hdr_size = sizeof(mach_msg_header_t) - header_adj;
444 	mach_msg_size_t base_size = hdr_size + sizeof(mach_msg_body_t);
445 	/*
446 	 * hdr can be of type (mach_msg_user_header_t *) or (mach_msg_header_t *).
447 	 * following code relies on the fact that both structs share the same
448 	 * first two fields. (msgh_bits and msgh_size)
449 	 */
450 	mach_msg_header_t *hdr = (mach_msg_header_t *)((vm_offset_t)ikm_header(kmsg) + header_adj);
451 
452 	assert(hdr->msgh_size >= hdr_size);
453 	if (hdr->msgh_size <= hdr_size) {
454 		return 0;
455 	}
456 
457 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
458 		assert(hdr->msgh_size >= base_size +
459 		    ikm_total_desc_size(kmsg, map, 0, header_adj, user_descs));
460 		return hdr->msgh_size - base_size -
461 		       ikm_total_desc_size(kmsg, map, 0, header_adj, user_descs);
462 	} else {
463 		assert(hdr->msgh_size > hdr_size);
464 		return hdr->msgh_size - hdr_size;
465 	}
466 }
467 
468 /* Size of kmsg header (plus body and descriptors for complex messages) */
469 static mach_msg_size_t
ikm_kdata_size(ipc_kmsg_t kmsg,vm_map_t map,mach_msg_size_t header_adj,bool user_descs)470 ikm_kdata_size(
471 	ipc_kmsg_t      kmsg,
472 	vm_map_t        map,
473 	mach_msg_size_t header_adj,
474 	bool            user_descs)
475 {
476 	mach_msg_size_t content_size = ikm_content_size(kmsg, map, header_adj, user_descs);
477 	/*
478 	 * hdr can be of type (mach_msg_user_header_t *) or (mach_msg_header_t *).
479 	 * following code relies on the fact that both structs share the same
480 	 * first two fields. (msgh_bits and msgh_size)
481 	 */
482 	mach_msg_header_t *hdr = (mach_msg_header_t *)((vm_offset_t)ikm_header(kmsg) + header_adj);
483 
484 	assert(hdr->msgh_size > content_size);
485 	return hdr->msgh_size - content_size;
486 }
487 
488 #if __has_feature(ptrauth_calls)
489 typedef uintptr_t ikm_sig_scratch_t;
490 
491 static void
ikm_init_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)492 ikm_init_sig(
493 	__unused ipc_kmsg_t kmsg,
494 	ikm_sig_scratch_t *scratchp)
495 {
496 	*scratchp = OS_PTRAUTH_DISCRIMINATOR("kmsg.ikm_signature");
497 }
498 
499 static void
ikm_chunk_sig(ipc_kmsg_t kmsg,void * data,size_t len,ikm_sig_scratch_t * scratchp)500 ikm_chunk_sig(
501 	ipc_kmsg_t kmsg,
502 	void *data,
503 	size_t len,
504 	ikm_sig_scratch_t *scratchp)
505 {
506 	int ptrauth_flags;
507 	void *trailerp;
508 
509 	/*
510 	 * if we happen to be doing the trailer chunk,
511 	 * diversify with the ptrauth-ed trailer pointer -
512 	 * as that is unchanging for the kmsg
513 	 */
514 	trailerp = (void *)ipc_kmsg_get_trailer(kmsg, false);
515 
516 	ptrauth_flags = (data == trailerp) ? PTRAUTH_ADDR_DIVERSIFY : 0;
517 	*scratchp = ptrauth_utils_sign_blob_generic(data, len, *scratchp, ptrauth_flags);
518 }
519 
520 static uintptr_t
ikm_finalize_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)521 ikm_finalize_sig(
522 	__unused ipc_kmsg_t kmsg,
523 	ikm_sig_scratch_t *scratchp)
524 {
525 	return *scratchp;
526 }
527 
528 #elif defined(CRYPTO_SHA2) && !defined(__x86_64__)
529 
530 typedef SHA256_CTX ikm_sig_scratch_t;
531 
532 static void
ikm_init_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)533 ikm_init_sig(
534 	__unused ipc_kmsg_t kmsg,
535 	ikm_sig_scratch_t *scratchp)
536 {
537 	SHA256_Init(scratchp);
538 	SHA256_Update(scratchp, &vm_kernel_addrhash_salt_ext, sizeof(uint64_t));
539 }
540 
541 static void
ikm_chunk_sig(__unused ipc_kmsg_t kmsg,void * data,size_t len,ikm_sig_scratch_t * scratchp)542 ikm_chunk_sig(
543 	__unused ipc_kmsg_t kmsg,
544 	void *data,
545 	size_t len,
546 	ikm_sig_scratch_t *scratchp)
547 {
548 	SHA256_Update(scratchp, data, len);
549 }
550 
551 static uintptr_t
ikm_finalize_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)552 ikm_finalize_sig(
553 	__unused ipc_kmsg_t kmsg,
554 	ikm_sig_scratch_t *scratchp)
555 {
556 	uintptr_t sha_digest[SHA256_DIGEST_LENGTH / sizeof(uintptr_t)];
557 
558 	SHA256_Final((uint8_t *)sha_digest, scratchp);
559 
560 	/*
561 	 * Only use one uintptr_t sized part of result for space and compat reasons.
562 	 * Truncation is better than XOR'ing the chunks together in hopes of higher
563 	 * entropy - because of its lower risk of collisions.
564 	 */
565 	return *sha_digest;
566 }
567 
568 #else
569 /* Stubbed out implementation (for __x86_64__ for now) */
570 
571 typedef uintptr_t ikm_sig_scratch_t;
572 
573 static void
ikm_init_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)574 ikm_init_sig(
575 	__unused ipc_kmsg_t kmsg,
576 	ikm_sig_scratch_t *scratchp)
577 {
578 	*scratchp = 0;
579 }
580 
581 static void
ikm_chunk_sig(__unused ipc_kmsg_t kmsg,__unused void * data,__unused size_t len,__unused ikm_sig_scratch_t * scratchp)582 ikm_chunk_sig(
583 	__unused ipc_kmsg_t kmsg,
584 	__unused void *data,
585 	__unused size_t len,
586 	__unused ikm_sig_scratch_t *scratchp)
587 {
588 	return;
589 }
590 
591 static uintptr_t
ikm_finalize_sig(__unused ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)592 ikm_finalize_sig(
593 	__unused ipc_kmsg_t kmsg,
594 	ikm_sig_scratch_t *scratchp)
595 {
596 	return *scratchp;
597 }
598 
599 #endif
600 
601 static void
ikm_header_sig(ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)602 ikm_header_sig(
603 	ipc_kmsg_t kmsg,
604 	ikm_sig_scratch_t *scratchp)
605 {
606 	mach_msg_size_t dsc_count;
607 	mach_msg_base_t base;
608 	boolean_t complex;
609 
610 	mach_msg_header_t *hdr = ikm_header(kmsg);
611 	/* take a snapshot of the message header/body-count */
612 	base.header = *hdr;
613 	complex = ((base.header.msgh_bits & MACH_MSGH_BITS_COMPLEX) != 0);
614 	if (complex) {
615 		dsc_count = ((mach_msg_body_t *)(hdr + 1))->msgh_descriptor_count;
616 	} else {
617 		dsc_count = 0;
618 	}
619 	base.body.msgh_descriptor_count = dsc_count;
620 
621 	/* compute sig of a copy of the header with all varying bits masked off */
622 	base.header.msgh_bits &= MACH_MSGH_BITS_USER;
623 	base.header.msgh_bits &= ~MACH_MSGH_BITS_VOUCHER_MASK;
624 	ikm_chunk_sig(kmsg, &base, sizeof(mach_msg_base_t), scratchp);
625 }
626 
627 static void
ikm_trailer_sig(ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)628 ikm_trailer_sig(
629 	ipc_kmsg_t kmsg,
630 	ikm_sig_scratch_t *scratchp)
631 {
632 	mach_msg_max_trailer_t *trailerp;
633 
634 	/* Add sig of the trailer contents */
635 	trailerp = ipc_kmsg_get_trailer(kmsg, false);
636 	ikm_chunk_sig(kmsg, trailerp, sizeof(*trailerp), scratchp);
637 }
638 
639 /* Compute the signature for the body bits of a message */
640 static void
ikm_body_sig(ipc_kmsg_t kmsg,ikm_sig_scratch_t * scratchp)641 ikm_body_sig(
642 	ipc_kmsg_t        kmsg,
643 	ikm_sig_scratch_t *scratchp)
644 {
645 	mach_msg_descriptor_t *kern_dsc;
646 	mach_msg_size_t dsc_count;
647 	mach_msg_body_t *body;
648 	mach_msg_size_t i;
649 
650 	mach_msg_header_t *hdr = ikm_header(kmsg);
651 
652 	if ((hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) == 0) {
653 		return;
654 	}
655 	body = (mach_msg_body_t *) (hdr + 1);
656 	dsc_count = body->msgh_descriptor_count;
657 
658 	if (dsc_count == 0) {
659 		return;
660 	}
661 
662 	kern_dsc = (mach_msg_descriptor_t *) (body + 1);
663 
664 	/* Compute the signature for the whole descriptor array */
665 	ikm_chunk_sig(kmsg, kern_dsc, sizeof(*kern_dsc) * dsc_count, scratchp);
666 
667 	/* look for descriptor contents that need a signature */
668 	for (i = 0; i < dsc_count; i++) {
669 		switch (kern_dsc[i].type.type) {
670 		case MACH_MSG_PORT_DESCRIPTOR:
671 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
672 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
673 		case MACH_MSG_OOL_DESCRIPTOR:
674 			break;
675 
676 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
677 			mach_msg_ool_ports_descriptor_t *ports_dsc;
678 
679 			/* Compute sig for the port/object pointers */
680 			ports_dsc = (mach_msg_ool_ports_descriptor_t *)&kern_dsc[i];
681 			ikm_chunk_sig(kmsg, ports_dsc->address, ports_dsc->count * sizeof(ipc_object_t), scratchp);
682 			break;
683 		}
684 		default: {
685 			panic("ipc_kmsg_body_sig: invalid message descriptor");
686 		}
687 		}
688 	}
689 }
690 
691 static void
ikm_sign(ipc_kmsg_t kmsg)692 ikm_sign(ipc_kmsg_t kmsg)
693 {
694 	ikm_sig_scratch_t scratch;
695 	uintptr_t sig;
696 
697 	zone_require(ipc_kmsg_zone, kmsg);
698 
699 	ikm_init_sig(kmsg, &scratch);
700 
701 	/* First sign header and trailer and store a partial sig */
702 	ikm_header_sig(kmsg, &scratch);
703 	ikm_trailer_sig(kmsg, &scratch);
704 
705 #if __has_feature(ptrauth_calls)
706 	/*
707 	 * On PAC devices lower 32 bits of the signature generated by G Key are
708 	 * always zeros. Use that space to store header + trailer partial sig.
709 	 *
710 	 * See: ptrauth_utils_sign_blob_generic()
711 	 */
712 	kmsg->ikm_sig_partial = (uint32_t)(ikm_finalize_sig(kmsg, &scratch) >> 32);
713 #endif
714 
715 	/* Then sign body, which may be large: ~ BigO(# descriptors) */
716 	ikm_body_sig(kmsg, &scratch);
717 
718 	sig = ikm_finalize_sig(kmsg, &scratch);
719 #if __has_feature(ptrauth_calls)
720 	kmsg->ikm_sig_full = (uint32_t)(sig >> 32);
721 #else
722 	kmsg->ikm_signature = sig;
723 #endif
724 }
725 
726 unsigned int ikm_signature_failures;
727 unsigned int ikm_signature_failure_id;
728 #if (DEVELOPMENT || DEBUG)
729 unsigned int ikm_signature_panic_disable;
730 unsigned int ikm_signature_header_failures;
731 unsigned int ikm_signature_trailer_failures;
732 #endif
733 
734 /*
735  * Purpose:
736  *       Validate kmsg signature.
737  *       partial:  Only validate header + trailer.
738  *
739  * Condition:
740  *       On non-PAC devices, `partial` must be set to false.
741  */
742 static void
ikm_validate_sig_internal(ipc_kmsg_t kmsg,bool partial)743 ikm_validate_sig_internal(
744 	ipc_kmsg_t kmsg,
745 	bool       partial)
746 {
747 	ikm_sig_scratch_t scratch;
748 	uintptr_t expected;
749 	uintptr_t sig;
750 	char *str;
751 
752 	zone_require(ipc_kmsg_zone, kmsg);
753 
754 	ikm_init_sig(kmsg, &scratch);
755 
756 	ikm_header_sig(kmsg, &scratch);
757 
758 	ikm_trailer_sig(kmsg, &scratch);
759 
760 	if (partial) {
761 #if __has_feature(ptrauth_calls)
762 		/* Do partial evaluation of header + trailer signature */
763 		sig = ikm_finalize_sig(kmsg, &scratch);
764 		expected = (uintptr_t)kmsg->ikm_sig_partial << 32;
765 		if (sig != expected) {
766 #if (DEVELOPMENT || DEBUG)
767 			ikm_signature_trailer_failures++;
768 #endif
769 			str = "header trailer";
770 			goto failure;
771 		}
772 		return;
773 #else
774 		panic("Partial kmsg signature validation only supported on PAC devices.");
775 #endif
776 	}
777 
778 	ikm_body_sig(kmsg, &scratch);
779 	sig = ikm_finalize_sig(kmsg, &scratch);
780 
781 #if __has_feature(ptrauth_calls)
782 	expected = (uintptr_t)kmsg->ikm_sig_full << 32;
783 #else
784 	expected = kmsg->ikm_signature;
785 #endif
786 
787 	if (sig != expected) {
788 		ikm_signature_failures++;
789 		str = "full";
790 
791 #if __has_feature(ptrauth_calls)
792 		failure:
793 #endif
794 		{
795 			mach_msg_id_t id = ikm_header(kmsg)->msgh_id;
796 
797 			ikm_signature_failure_id = id;
798 #if (DEVELOPMENT || DEBUG)
799 			if (ikm_signature_panic_disable) {
800 				return;
801 			}
802 #endif
803 			panic("ikm_validate_sig: %s signature mismatch: kmsg=0x%p, id=%d, sig=0x%zx (expected 0x%zx)",
804 			    str, kmsg, id, sig, expected);
805 		}
806 	}
807 }
808 
809 static void
ikm_validate_sig(ipc_kmsg_t kmsg)810 ikm_validate_sig(
811 	ipc_kmsg_t kmsg)
812 {
813 	ikm_validate_sig_internal(kmsg, false);
814 }
815 
816 /*
817  * Purpose:
818  *       Validate kmsg signature. [Exported in header]
819  *       partial:  Only validate header + trailer.
820  *
821  * Condition:
822  *       On non-PAC devices, `partial` must be set to false.
823  */
824 void
ipc_kmsg_validate_sig(ipc_kmsg_t kmsg,bool partial)825 ipc_kmsg_validate_sig(
826 	ipc_kmsg_t kmsg,
827 	bool       partial)
828 {
829 	ikm_validate_sig_internal(kmsg, partial);
830 }
831 
832 #if DEBUG_MSGS_K64
833 extern void ipc_pset_print64(
834 	ipc_pset_t      pset);
835 
836 extern void     ipc_kmsg_print64(
837 	ipc_kmsg_t      kmsg,
838 	const char      *str);
839 
840 extern void     ipc_msg_print64(
841 	mach_msg_header_t       *msgh);
842 
843 extern ipc_port_t ipc_name_to_data64(
844 	task_t                  task,
845 	mach_port_name_t        name);
846 
847 /*
848  * Forward declarations
849  */
850 void ipc_msg_print_untyped64(
851 	mach_msg_body_t         *body);
852 
853 const char * ipc_type_name64(
854 	int             type_name,
855 	boolean_t       received);
856 
857 void ipc_print_type_name64(
858 	int     type_name);
859 
860 const char *
861 msgh_bit_decode64(
862 	mach_msg_bits_t bit);
863 
864 const char *
865 mm_copy_options_string64(
866 	mach_msg_copy_options_t option);
867 
868 void db_print_msg_uid64(mach_msg_header_t *);
869 
870 static void
ipc_msg_body_print64(void * body,int size)871 ipc_msg_body_print64(void *body, int size)
872 {
873 	uint32_t        *word = (uint32_t *) body;
874 	uint32_t        *end  = (uint32_t *)(((uintptr_t) body) + size
875 	    - sizeof(mach_msg_header_t));
876 	int             i;
877 
878 	kprintf("  body(%p-%p):\n    %p: ", body, end, word);
879 	for (;;) {
880 		for (i = 0; i < 8; i++, word++) {
881 			if (word >= end) {
882 				kprintf("\n");
883 				return;
884 			}
885 			kprintf("%08x ", *word);
886 		}
887 		kprintf("\n    %p: ", word);
888 	}
889 }
890 
891 
892 const char *
ipc_type_name64(int type_name,boolean_t received)893 ipc_type_name64(
894 	int             type_name,
895 	boolean_t       received)
896 {
897 	switch (type_name) {
898 	case MACH_MSG_TYPE_PORT_NAME:
899 		return "port_name";
900 
901 	case MACH_MSG_TYPE_MOVE_RECEIVE:
902 		if (received) {
903 			return "port_receive";
904 		} else {
905 			return "move_receive";
906 		}
907 
908 	case MACH_MSG_TYPE_MOVE_SEND:
909 		if (received) {
910 			return "port_send";
911 		} else {
912 			return "move_send";
913 		}
914 
915 	case MACH_MSG_TYPE_MOVE_SEND_ONCE:
916 		if (received) {
917 			return "port_send_once";
918 		} else {
919 			return "move_send_once";
920 		}
921 
922 	case MACH_MSG_TYPE_COPY_SEND:
923 		return "copy_send";
924 
925 	case MACH_MSG_TYPE_MAKE_SEND:
926 		return "make_send";
927 
928 	case MACH_MSG_TYPE_MAKE_SEND_ONCE:
929 		return "make_send_once";
930 
931 	default:
932 		return (char *) 0;
933 	}
934 }
935 
936 void
ipc_print_type_name64(int type_name)937 ipc_print_type_name64(
938 	int     type_name)
939 {
940 	const char *name = ipc_type_name64(type_name, TRUE);
941 	if (name) {
942 		kprintf("%s", name);
943 	} else {
944 		kprintf("type%d", type_name);
945 	}
946 }
947 
948 /*
949  * ipc_kmsg_print64	[ debug ]
950  */
951 void
ipc_kmsg_print64(ipc_kmsg_t kmsg,const char * str)952 ipc_kmsg_print64(
953 	ipc_kmsg_t      kmsg,
954 	const char      *str)
955 {
956 	kprintf("%s kmsg=%p:\n", str, kmsg);
957 	kprintf("  next=%p, prev=%p",
958 	    kmsg->ikm_link.next,
959 	    kmsg->ikm_link.prev);
960 	kprintf("\n");
961 	ipc_msg_print64(ikm_header(kmsg));
962 }
963 
964 const char *
msgh_bit_decode64(mach_msg_bits_t bit)965 msgh_bit_decode64(
966 	mach_msg_bits_t bit)
967 {
968 	switch (bit) {
969 	case MACH_MSGH_BITS_COMPLEX:        return "complex";
970 	case MACH_MSGH_BITS_CIRCULAR:       return "circular";
971 	default:                            return (char *) 0;
972 	}
973 }
974 
975 /*
976  * ipc_msg_print64	[ debug ]
977  */
978 void
ipc_msg_print64(mach_msg_header_t * msgh)979 ipc_msg_print64(
980 	mach_msg_header_t       *msgh)
981 {
982 	mach_msg_bits_t mbits;
983 	unsigned int    bit, i;
984 	const char      *bit_name;
985 	int             needs_comma;
986 
987 	mbits = msgh->msgh_bits;
988 	kprintf("  msgh_bits=0x%x: l=0x%x,r=0x%x\n",
989 	    mbits,
990 	    MACH_MSGH_BITS_LOCAL(msgh->msgh_bits),
991 	    MACH_MSGH_BITS_REMOTE(msgh->msgh_bits));
992 
993 	mbits = MACH_MSGH_BITS_OTHER(mbits) & MACH_MSGH_BITS_USED;
994 	kprintf("  decoded bits:  ");
995 	needs_comma = 0;
996 	for (i = 0, bit = 1; i < sizeof(mbits) * 8; ++i, bit <<= 1) {
997 		if ((mbits & bit) == 0) {
998 			continue;
999 		}
1000 		bit_name = msgh_bit_decode64((mach_msg_bits_t)bit);
1001 		if (bit_name) {
1002 			kprintf("%s%s", needs_comma ? "," : "", bit_name);
1003 		} else {
1004 			kprintf("%sunknown(0x%x),", needs_comma ? "," : "", bit);
1005 		}
1006 		++needs_comma;
1007 	}
1008 	if (msgh->msgh_bits & ~MACH_MSGH_BITS_USED) {
1009 		kprintf("%sunused=0x%x,", needs_comma ? "," : "",
1010 		    msgh->msgh_bits & ~MACH_MSGH_BITS_USED);
1011 	}
1012 	kprintf("\n");
1013 
1014 	needs_comma = 1;
1015 	if (msgh->msgh_remote_port) {
1016 		kprintf("  remote=%p(", msgh->msgh_remote_port);
1017 		ipc_print_type_name64(MACH_MSGH_BITS_REMOTE(msgh->msgh_bits));
1018 		kprintf(")");
1019 	} else {
1020 		kprintf("  remote=null");
1021 	}
1022 
1023 	if (msgh->msgh_local_port) {
1024 		kprintf("%slocal=%p(", needs_comma ? "," : "",
1025 		    msgh->msgh_local_port);
1026 		ipc_print_type_name64(MACH_MSGH_BITS_LOCAL(msgh->msgh_bits));
1027 		kprintf(")\n");
1028 	} else {
1029 		kprintf("local=null\n");
1030 	}
1031 
1032 	kprintf("  msgh_id=%d, size=%d\n",
1033 	    msgh->msgh_id,
1034 	    msgh->msgh_size);
1035 
1036 	if (mbits & MACH_MSGH_BITS_COMPLEX) {
1037 		ipc_msg_print_untyped64((mach_msg_body_t *) (msgh + 1));
1038 	}
1039 
1040 	ipc_msg_body_print64((void *)(msgh + 1), msgh->msgh_size);
1041 }
1042 
1043 
1044 const char *
mm_copy_options_string64(mach_msg_copy_options_t option)1045 mm_copy_options_string64(
1046 	mach_msg_copy_options_t option)
1047 {
1048 	const char      *name;
1049 
1050 	switch (option) {
1051 	case MACH_MSG_PHYSICAL_COPY:
1052 		name = "PHYSICAL";
1053 		break;
1054 	case MACH_MSG_VIRTUAL_COPY:
1055 		name = "VIRTUAL";
1056 		break;
1057 	case MACH_MSG_OVERWRITE:
1058 		name = "OVERWRITE(DEPRECATED)";
1059 		break;
1060 	case MACH_MSG_ALLOCATE:
1061 		name = "ALLOCATE";
1062 		break;
1063 	case MACH_MSG_KALLOC_COPY_T:
1064 		name = "KALLOC_COPY_T";
1065 		break;
1066 	default:
1067 		name = "unknown";
1068 		break;
1069 	}
1070 	return name;
1071 }
1072 
1073 void
ipc_msg_print_untyped64(mach_msg_body_t * body)1074 ipc_msg_print_untyped64(
1075 	mach_msg_body_t         *body)
1076 {
1077 	mach_msg_descriptor_t       *saddr, *send;
1078 	mach_msg_descriptor_type_t  type;
1079 
1080 	kprintf("  %d descriptors: \n", body->msgh_descriptor_count);
1081 
1082 	saddr = (mach_msg_descriptor_t *) (body + 1);
1083 	send = saddr + body->msgh_descriptor_count;
1084 
1085 	for (; saddr < send; saddr++) {
1086 		type = saddr->type.type;
1087 
1088 		switch (type) {
1089 		case MACH_MSG_PORT_DESCRIPTOR: {
1090 			mach_msg_port_descriptor_t *dsc;
1091 
1092 			dsc = &saddr->port;
1093 			kprintf("    PORT name = %p disp = ", dsc->name);
1094 			ipc_print_type_name64(dsc->disposition);
1095 			kprintf("\n");
1096 			break;
1097 		}
1098 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
1099 		case MACH_MSG_OOL_DESCRIPTOR: {
1100 			mach_msg_ool_descriptor_t *dsc;
1101 
1102 			dsc = (mach_msg_ool_descriptor_t *) &saddr->out_of_line;
1103 			kprintf("    OOL%s addr = %p size = 0x%x copy = %s %s\n",
1104 			    type == MACH_MSG_OOL_DESCRIPTOR ? "" : " VOLATILE",
1105 			    dsc->address, dsc->size,
1106 			    mm_copy_options_string64(dsc->copy),
1107 			    dsc->deallocate ? "DEALLOC" : "");
1108 			break;
1109 		}
1110 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
1111 			mach_msg_ool_ports_descriptor_t *dsc;
1112 
1113 			dsc = (mach_msg_ool_ports_descriptor_t *) &saddr->ool_ports;
1114 
1115 			kprintf("    OOL_PORTS addr = %p count = 0x%x ",
1116 			    dsc->address, dsc->count);
1117 			kprintf("disp = ");
1118 			ipc_print_type_name64(dsc->disposition);
1119 			kprintf(" copy = %s %s\n",
1120 			    mm_copy_options_string64(dsc->copy),
1121 			    dsc->deallocate ? "DEALLOC" : "");
1122 			break;
1123 		}
1124 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR: {
1125 			mach_msg_guarded_port_descriptor_t *dsc;
1126 
1127 			dsc = (mach_msg_guarded_port_descriptor_t *)&saddr->guarded_port;
1128 			kprintf("    GUARDED_PORT name = %p flags = 0x%x disp = ", dsc->name, dsc->flags);
1129 			ipc_print_type_name64(dsc->disposition);
1130 			kprintf("\n");
1131 			break;
1132 		}
1133 		default: {
1134 			kprintf("    UNKNOWN DESCRIPTOR 0x%x\n", type);
1135 			break;
1136 		}
1137 		}
1138 	}
1139 }
1140 
1141 #define DEBUG_IPC_KMSG_PRINT(kmsg, string)       \
1142 	__unreachable_ok_push   \
1143 	if (DEBUG_KPRINT_SYSCALL_PREDICATE(DEBUG_KPRINT_SYSCALL_IPC_MASK)) {    \
1144 	        ipc_kmsg_print64(kmsg, string); \
1145 	}       \
1146 	__unreachable_ok_pop
1147 
1148 #define DEBUG_IPC_MSG_BODY_PRINT(body, size)     \
1149 	__unreachable_ok_push   \
1150 	if (DEBUG_KPRINT_SYSCALL_PREDICATE(DEBUG_KPRINT_SYSCALL_IPC_MASK)) {    \
1151 	        ipc_msg_body_print64(body,size);\
1152 	}       \
1153 	__unreachable_ok_pop
1154 #else /* !DEBUG_MSGS_K64 */
1155 #define DEBUG_IPC_KMSG_PRINT(kmsg, string)
1156 #define DEBUG_IPC_MSG_BODY_PRINT(body, size)
1157 #endif  /* !DEBUG_MSGS_K64 */
1158 
1159 extern vm_map_t         ipc_kernel_copy_map;
1160 extern vm_size_t        ipc_kmsg_max_space;
1161 extern const vm_size_t  ipc_kmsg_max_vm_space;
1162 extern const vm_size_t  msg_ool_size_small;
1163 
1164 #define MSG_OOL_SIZE_SMALL      msg_ool_size_small
1165 
1166 #define KMSG_TRACE_FLAG_TRACED     0x000001
1167 #define KMSG_TRACE_FLAG_COMPLEX    0x000002
1168 #define KMSG_TRACE_FLAG_OOLMEM     0x000004
1169 #define KMSG_TRACE_FLAG_VCPY       0x000008
1170 #define KMSG_TRACE_FLAG_PCPY       0x000010
1171 #define KMSG_TRACE_FLAG_SND64      0x000020
1172 #define KMSG_TRACE_FLAG_RAISEIMP   0x000040
1173 #define KMSG_TRACE_FLAG_APP_SRC    0x000080
1174 #define KMSG_TRACE_FLAG_APP_DST    0x000100
1175 #define KMSG_TRACE_FLAG_DAEMON_SRC 0x000200
1176 #define KMSG_TRACE_FLAG_DAEMON_DST 0x000400
1177 #define KMSG_TRACE_FLAG_DST_NDFLTQ 0x000800
1178 #define KMSG_TRACE_FLAG_SRC_NDFLTQ 0x001000
1179 #define KMSG_TRACE_FLAG_DST_SONCE  0x002000
1180 #define KMSG_TRACE_FLAG_SRC_SONCE  0x004000
1181 #define KMSG_TRACE_FLAG_CHECKIN    0x008000
1182 #define KMSG_TRACE_FLAG_ONEWAY     0x010000
1183 #define KMSG_TRACE_FLAG_IOKIT      0x020000
1184 #define KMSG_TRACE_FLAG_SNDRCV     0x040000
1185 #define KMSG_TRACE_FLAG_DSTQFULL   0x080000
1186 #define KMSG_TRACE_FLAG_VOUCHER    0x100000
1187 #define KMSG_TRACE_FLAG_TIMER      0x200000
1188 #define KMSG_TRACE_FLAG_SEMA       0x400000
1189 #define KMSG_TRACE_FLAG_DTMPOWNER  0x800000
1190 #define KMSG_TRACE_FLAG_GUARDED_DESC 0x1000000
1191 
1192 #define KMSG_TRACE_FLAGS_MASK      0x1ffffff
1193 #define KMSG_TRACE_FLAGS_SHIFT     8
1194 
1195 #define KMSG_TRACE_PORTS_MASK      0xff
1196 #define KMSG_TRACE_PORTS_SHIFT     0
1197 
1198 #if (KDEBUG_LEVEL >= KDEBUG_LEVEL_STANDARD)
1199 #include <stdint.h>
1200 
1201 void
ipc_kmsg_trace_send(ipc_kmsg_t kmsg,mach_msg_option_t option)1202 ipc_kmsg_trace_send(ipc_kmsg_t kmsg,
1203     mach_msg_option_t option)
1204 {
1205 	task_t send_task = TASK_NULL;
1206 	ipc_port_t dst_port, src_port;
1207 	boolean_t is_task_64bit;
1208 	mach_msg_header_t *msg;
1209 	mach_msg_trailer_t *trailer;
1210 
1211 	int kotype = 0;
1212 	uint32_t msg_size = 0;
1213 	uint64_t msg_flags = KMSG_TRACE_FLAG_TRACED;
1214 	uint32_t num_ports = 0;
1215 	uint32_t send_pid, dst_pid;
1216 
1217 	/*
1218 	 * check to see not only if ktracing is enabled, but if we will
1219 	 * _actually_ emit the KMSG_INFO tracepoint. This saves us a
1220 	 * significant amount of processing (and a port lock hold) in
1221 	 * the non-tracing case.
1222 	 */
1223 	if (__probable((kdebug_enable & KDEBUG_TRACE) == 0)) {
1224 		return;
1225 	}
1226 	if (!kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO))) {
1227 		return;
1228 	}
1229 
1230 	msg = ikm_header(kmsg);
1231 
1232 	dst_port = msg->msgh_remote_port;
1233 	if (!IPC_PORT_VALID(dst_port)) {
1234 		return;
1235 	}
1236 
1237 	/*
1238 	 * Message properties / options
1239 	 */
1240 	if ((option & (MACH_SEND_MSG | MACH_RCV_MSG)) == (MACH_SEND_MSG | MACH_RCV_MSG)) {
1241 		msg_flags |= KMSG_TRACE_FLAG_SNDRCV;
1242 	}
1243 
1244 	if (msg->msgh_id >= is_iokit_subsystem.start &&
1245 	    msg->msgh_id < is_iokit_subsystem.end + 100) {
1246 		msg_flags |= KMSG_TRACE_FLAG_IOKIT;
1247 	}
1248 	/* magic XPC checkin message id (XPC_MESSAGE_ID_CHECKIN) from libxpc */
1249 	else if (msg->msgh_id == 0x77303074u /* w00t */) {
1250 		msg_flags |= KMSG_TRACE_FLAG_CHECKIN;
1251 	}
1252 
1253 	if (msg->msgh_bits & MACH_MSGH_BITS_RAISEIMP) {
1254 		msg_flags |= KMSG_TRACE_FLAG_RAISEIMP;
1255 	}
1256 
1257 	if (unsafe_convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg))) {
1258 		msg_flags |= KMSG_TRACE_FLAG_VOUCHER;
1259 	}
1260 
1261 	/*
1262 	 * Sending task / port
1263 	 */
1264 	send_task = current_task();
1265 	send_pid = task_pid(send_task);
1266 
1267 	if (send_pid != 0) {
1268 		if (task_is_daemon(send_task)) {
1269 			msg_flags |= KMSG_TRACE_FLAG_DAEMON_SRC;
1270 		} else if (task_is_app(send_task)) {
1271 			msg_flags |= KMSG_TRACE_FLAG_APP_SRC;
1272 		}
1273 	}
1274 
1275 	is_task_64bit = (send_task->map->max_offset > VM_MAX_ADDRESS);
1276 	if (is_task_64bit) {
1277 		msg_flags |= KMSG_TRACE_FLAG_SND64;
1278 	}
1279 
1280 	src_port = msg->msgh_local_port;
1281 	if (src_port) {
1282 		if (src_port->ip_messages.imq_qlimit != MACH_PORT_QLIMIT_DEFAULT) {
1283 			msg_flags |= KMSG_TRACE_FLAG_SRC_NDFLTQ;
1284 		}
1285 		switch (MACH_MSGH_BITS_LOCAL(msg->msgh_bits)) {
1286 		case MACH_MSG_TYPE_MOVE_SEND_ONCE:
1287 			msg_flags |= KMSG_TRACE_FLAG_SRC_SONCE;
1288 			break;
1289 		default:
1290 			break;
1291 		}
1292 	} else {
1293 		msg_flags |= KMSG_TRACE_FLAG_ONEWAY;
1294 	}
1295 
1296 
1297 	/*
1298 	 * Destination task / port
1299 	 */
1300 	ip_mq_lock(dst_port);
1301 	if (!ip_active(dst_port)) {
1302 		/* dst port is being torn down */
1303 		dst_pid = (uint32_t)0xfffffff0;
1304 	} else if (dst_port->ip_tempowner) {
1305 		msg_flags |= KMSG_TRACE_FLAG_DTMPOWNER;
1306 		if (IIT_NULL != ip_get_imp_task(dst_port)) {
1307 			dst_pid = task_pid(dst_port->ip_imp_task->iit_task);
1308 		} else {
1309 			dst_pid = (uint32_t)0xfffffff1;
1310 		}
1311 	} else if (!ip_in_a_space(dst_port)) {
1312 		/* dst_port is otherwise in-transit */
1313 		dst_pid = (uint32_t)0xfffffff2;
1314 	} else {
1315 		if (ip_in_space(dst_port, ipc_space_kernel)) {
1316 			dst_pid = 0;
1317 		} else {
1318 			ipc_space_t dst_space;
1319 			dst_space = ip_get_receiver(dst_port);
1320 			if (dst_space && is_active(dst_space)) {
1321 				dst_pid = task_pid(dst_space->is_task);
1322 				if (task_is_daemon(dst_space->is_task)) {
1323 					msg_flags |= KMSG_TRACE_FLAG_DAEMON_DST;
1324 				} else if (task_is_app(dst_space->is_task)) {
1325 					msg_flags |= KMSG_TRACE_FLAG_APP_DST;
1326 				}
1327 			} else {
1328 				/* receiving task is being torn down */
1329 				dst_pid = (uint32_t)0xfffffff3;
1330 			}
1331 		}
1332 	}
1333 
1334 	if (dst_port->ip_messages.imq_qlimit != MACH_PORT_QLIMIT_DEFAULT) {
1335 		msg_flags |= KMSG_TRACE_FLAG_DST_NDFLTQ;
1336 	}
1337 	if (imq_full(&dst_port->ip_messages)) {
1338 		msg_flags |= KMSG_TRACE_FLAG_DSTQFULL;
1339 	}
1340 
1341 	kotype = ip_kotype(dst_port);
1342 
1343 	ip_mq_unlock(dst_port);
1344 
1345 	switch (kotype) {
1346 	case IKOT_SEMAPHORE:
1347 		msg_flags |= KMSG_TRACE_FLAG_SEMA;
1348 		break;
1349 	case IKOT_TIMER:
1350 	case IKOT_CLOCK:
1351 		msg_flags |= KMSG_TRACE_FLAG_TIMER;
1352 		break;
1353 	case IKOT_MAIN_DEVICE:
1354 	case IKOT_IOKIT_CONNECT:
1355 	case IKOT_IOKIT_OBJECT:
1356 	case IKOT_IOKIT_IDENT:
1357 	case IKOT_UEXT_OBJECT:
1358 		msg_flags |= KMSG_TRACE_FLAG_IOKIT;
1359 		break;
1360 	default:
1361 		break;
1362 	}
1363 
1364 	switch (MACH_MSGH_BITS_REMOTE(msg->msgh_bits)) {
1365 	case MACH_MSG_TYPE_PORT_SEND_ONCE:
1366 		msg_flags |= KMSG_TRACE_FLAG_DST_SONCE;
1367 		break;
1368 	default:
1369 		break;
1370 	}
1371 
1372 
1373 	/*
1374 	 * Message size / content
1375 	 */
1376 	msg_size = msg->msgh_size - sizeof(mach_msg_header_t);
1377 
1378 	if (msg->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
1379 		mach_msg_body_t *msg_body;
1380 		mach_msg_descriptor_t *kern_dsc;
1381 		mach_msg_size_t dsc_count;
1382 
1383 		msg_flags |= KMSG_TRACE_FLAG_COMPLEX;
1384 
1385 		msg_body = (mach_msg_body_t *)(msg + 1);
1386 		dsc_count = msg_body->msgh_descriptor_count;
1387 		kern_dsc = (mach_msg_descriptor_t *)(msg_body + 1);
1388 
1389 		for (mach_msg_size_t i = 0; i < dsc_count; i++) {
1390 			switch (kern_dsc[i].type.type) {
1391 			case MACH_MSG_PORT_DESCRIPTOR:
1392 				num_ports++;
1393 				break;
1394 			case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
1395 			case MACH_MSG_OOL_DESCRIPTOR: {
1396 				mach_msg_ool_descriptor_t *dsc;
1397 				dsc = (mach_msg_ool_descriptor_t *)&kern_dsc[i];
1398 				msg_flags |= KMSG_TRACE_FLAG_OOLMEM;
1399 				msg_size += dsc->size;
1400 				if (dsc->size > MSG_OOL_SIZE_SMALL &&
1401 				    (dsc->copy == MACH_MSG_PHYSICAL_COPY) &&
1402 				    !dsc->deallocate) {
1403 					msg_flags |= KMSG_TRACE_FLAG_PCPY;
1404 				} else if (dsc->size <= MSG_OOL_SIZE_SMALL) {
1405 					msg_flags |= KMSG_TRACE_FLAG_PCPY;
1406 				} else {
1407 					msg_flags |= KMSG_TRACE_FLAG_VCPY;
1408 				}
1409 			} break;
1410 			case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
1411 				mach_msg_ool_ports_descriptor_t *dsc;
1412 				dsc = (mach_msg_ool_ports_descriptor_t *)&kern_dsc[i];
1413 				num_ports += dsc->count;
1414 			} break;
1415 			case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
1416 				num_ports++;
1417 				msg_flags |= KMSG_TRACE_FLAG_GUARDED_DESC;
1418 				break;
1419 			default:
1420 				break;
1421 			}
1422 			msg_size -= ikm_user_desc_size(kern_dsc[i].type.type, is_task_64bit);
1423 		}
1424 	}
1425 
1426 	/*
1427 	 * Trailer contents
1428 	 */
1429 	trailer = (mach_msg_trailer_t *)ipc_kmsg_get_trailer(kmsg, false);
1430 	if (trailer->msgh_trailer_size <= sizeof(mach_msg_security_trailer_t)) {
1431 		mach_msg_security_trailer_t *strailer;
1432 		strailer = (mach_msg_security_trailer_t *)trailer;
1433 		/*
1434 		 * verify the sender PID: replies from the kernel often look
1435 		 * like self-talk because the sending port is not reset.
1436 		 */
1437 		if (memcmp(&strailer->msgh_sender,
1438 		    &KERNEL_SECURITY_TOKEN,
1439 		    sizeof(KERNEL_SECURITY_TOKEN)) == 0) {
1440 			send_pid = 0;
1441 			msg_flags &= ~(KMSG_TRACE_FLAG_APP_SRC | KMSG_TRACE_FLAG_DAEMON_SRC);
1442 		}
1443 	}
1444 
1445 	KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END,
1446 	    (uintptr_t)send_pid,
1447 	    (uintptr_t)dst_pid,
1448 	    (uintptr_t)msg_size,
1449 	    (uintptr_t)(
1450 		    ((msg_flags & KMSG_TRACE_FLAGS_MASK) << KMSG_TRACE_FLAGS_SHIFT) |
1451 		    ((num_ports & KMSG_TRACE_PORTS_MASK) << KMSG_TRACE_PORTS_SHIFT)
1452 		    )
1453 	    );
1454 }
1455 #endif
1456 
1457 /* zone for cached ipc_kmsg_t structures */
1458 ZONE_DEFINE(ipc_kmsg_zone, "ipc kmsgs", IKM_SAVED_KMSG_SIZE,
1459     ZC_CACHING | ZC_ZFREE_CLEARMEM);
1460 static TUNABLE(bool, enforce_strict_reply, "ipc_strict_reply", false);
1461 
1462 /*
1463  * Forward declarations
1464  */
1465 
1466 static void ipc_kmsg_clean(
1467 	ipc_kmsg_t      kmsg);
1468 
1469 static void
1470 ipc_kmsg_link_reply_context_locked(
1471 	ipc_port_t reply_port,
1472 	ipc_port_t voucher_port);
1473 
1474 static kern_return_t
1475 ipc_kmsg_validate_reply_port_locked(
1476 	ipc_port_t reply_port,
1477 	mach_msg_option_t options);
1478 
1479 static mach_msg_return_t
1480 ipc_kmsg_validate_reply_context_locked(
1481 	mach_msg_option_t option,
1482 	ipc_port_t dest_port,
1483 	ipc_voucher_t voucher,
1484 	mach_port_name_t voucher_name);
1485 
1486 /* we can't include the BSD <sys/persona.h> header here... */
1487 #ifndef PERSONA_ID_NONE
1488 #define PERSONA_ID_NONE ((uint32_t)-1)
1489 #endif
1490 
1491 static inline void *
ikm_inline_data(ipc_kmsg_t kmsg)1492 ikm_inline_data(
1493 	ipc_kmsg_t         kmsg)
1494 {
1495 	return (void *)(kmsg + 1);
1496 }
1497 
1498 /* Whether header, body, content and trailer occupy contiguous memory space */
1499 static inline bool
ikm_is_linear(ipc_kmsg_t kmsg)1500 ikm_is_linear(ipc_kmsg_t kmsg)
1501 {
1502 	return kmsg->ikm_type == IKM_TYPE_ALL_INLINED ||
1503 	       kmsg->ikm_type == IKM_TYPE_KDATA_OOL;
1504 }
1505 
1506 static inline bool
ikm_header_inlined(ipc_kmsg_t kmsg)1507 ikm_header_inlined(ipc_kmsg_t kmsg)
1508 {
1509 	/* ikm_type must not be reordered */
1510 	static_assert(IKM_TYPE_UDATA_OOL == 1);
1511 	static_assert(IKM_TYPE_ALL_INLINED == 0);
1512 	return kmsg->ikm_type <= IKM_TYPE_UDATA_OOL;
1513 }
1514 
1515 /*
1516  * Returns start address of user data for kmsg.
1517  *
1518  * Condition:
1519  *   1. kmsg descriptors must have been validated and expanded, or is a message
1520  *      originated from kernel.
1521  *   2. ikm_header() content may or may not be populated
1522  */
1523 void *
ikm_udata(ipc_kmsg_t kmsg,mach_msg_size_t desc_count,bool complex)1524 ikm_udata(
1525 	ipc_kmsg_t      kmsg,
1526 	mach_msg_size_t desc_count,
1527 	bool            complex)
1528 {
1529 	if (!ikm_is_linear(kmsg)) {
1530 		return kmsg->ikm_udata;
1531 	} else if (complex) {
1532 		return (void *)((vm_offset_t)ikm_header(kmsg) + sizeof(mach_msg_base_t) +
1533 		       desc_count * KERNEL_DESC_SIZE);
1534 	} else {
1535 		return (void *)((vm_offset_t)ikm_header(kmsg) + sizeof(mach_msg_header_t));
1536 	}
1537 }
1538 
1539 #if (DEVELOPMENT || DEBUG)
1540 /* Returns end of kdata buffer (may contain extra space) */
1541 static vm_offset_t
ikm_kdata_end(ipc_kmsg_t kmsg)1542 ikm_kdata_end(ipc_kmsg_t kmsg)
1543 {
1544 	if (ikm_header_inlined(kmsg)) {
1545 		/* round up to total kmsg buffer size */
1546 		return (vm_offset_t)kmsg + IKM_SAVED_KMSG_SIZE;
1547 	} else if (ikm_is_linear(kmsg)) {
1548 		/* round up to total kmsg buffer size */
1549 		ipc_kmsg_vector_t *vec = ikm_inline_data(kmsg);
1550 		return (vm_offset_t)vec->kmsgv_data + vec->kmsgv_size;
1551 	} else {
1552 		assert(kmsg->ikm_type == IKM_TYPE_ALL_OOL);
1553 		ipc_kmsg_vector_t *vec = ikm_inline_data(kmsg);
1554 		return (vm_offset_t)vec->kmsgv_data + sizeof(mach_msg_base_t) +
1555 		       vec->kmsgv_size * KERNEL_DESC_SIZE;
1556 	}
1557 }
1558 
1559 /* Returns end of udata buffer (may contain extra space) */
1560 static vm_offset_t
ikm_udata_end(ipc_kmsg_t kmsg)1561 ikm_udata_end(ipc_kmsg_t kmsg)
1562 {
1563 	assert(kmsg->ikm_type != IKM_TYPE_ALL_INLINED);
1564 	assert(kmsg->ikm_udata != NULL);
1565 
1566 	return (vm_offset_t)kmsg->ikm_udata + kmsg->ikm_udata_size;
1567 }
1568 #endif
1569 
1570 /*
1571  * Returns message header address.
1572  *
1573  * /!\ WARNING /!\
1574  * Need to shift the return value after call to ipc_kmsg_convert_header_to_user().
1575  */
1576 inline mach_msg_header_t *
ikm_header(ipc_kmsg_t kmsg)1577 ikm_header(
1578 	ipc_kmsg_t         kmsg)
1579 {
1580 	return ikm_header_inlined(kmsg) ? (mach_msg_header_t *)ikm_inline_data(kmsg) :
1581 	       (mach_msg_header_t *)(((ipc_kmsg_vector_t *)ikm_inline_data(kmsg))->kmsgv_data);
1582 }
1583 
1584 static inline mach_msg_aux_header_t *
ikm_aux_header(ipc_kmsg_t kmsg)1585 ikm_aux_header(
1586 	ipc_kmsg_t         kmsg)
1587 {
1588 	if (!kmsg->ikm_aux_size) {
1589 		return NULL;
1590 	}
1591 
1592 	assert(kmsg->ikm_aux_size >= sizeof(mach_msg_aux_header_t));
1593 
1594 	if (kmsg->ikm_type == IKM_TYPE_ALL_INLINED) {
1595 		return (mach_msg_aux_header_t *)((vm_offset_t)kmsg + IKM_SAVED_KMSG_SIZE -
1596 		       kmsg->ikm_aux_size);
1597 	} else {
1598 		assert(kmsg->ikm_type != IKM_TYPE_KDATA_OOL);
1599 		return (mach_msg_aux_header_t *)((vm_offset_t)kmsg->ikm_udata +
1600 		       kmsg->ikm_udata_size - kmsg->ikm_aux_size);
1601 	}
1602 }
1603 
1604 /* Return real size of kmsg aux data */
1605 inline mach_msg_size_t
ipc_kmsg_aux_data_size(ipc_kmsg_t kmsg)1606 ipc_kmsg_aux_data_size(
1607 	ipc_kmsg_t         kmsg)
1608 {
1609 	mach_msg_aux_header_t *aux;
1610 
1611 	aux = ikm_aux_header(kmsg);
1612 	if (aux == NULL) {
1613 		return 0;
1614 	}
1615 
1616 #if (DEVELOPMENT || DEBUG)
1617 	if (kmsg->ikm_type == IKM_TYPE_ALL_INLINED) {
1618 		assert((vm_offset_t)aux + aux->msgdh_size <= (vm_offset_t)kmsg + IKM_SAVED_KMSG_SIZE);
1619 	} else {
1620 		assert((vm_offset_t)aux + aux->msgdh_size <= ikm_udata_end(kmsg));
1621 	}
1622 
1623 	assert3u(aux->msgdh_size, <=, kmsg->ikm_aux_size);
1624 	assert3u(aux->msgdh_size, >=, sizeof(mach_msg_aux_header_t));
1625 #endif
1626 
1627 	return aux->msgdh_size;
1628 }
1629 
1630 void
ipc_kmsg_set_aux_data_header(ipc_kmsg_t kmsg,mach_msg_aux_header_t * new_hdr)1631 ipc_kmsg_set_aux_data_header(
1632 	ipc_kmsg_t            kmsg,
1633 	mach_msg_aux_header_t *new_hdr)
1634 {
1635 	mach_msg_aux_header_t *cur_hdr;
1636 
1637 	assert3u(new_hdr->msgdh_size, >=, sizeof(mach_msg_aux_header_t));
1638 
1639 	cur_hdr = ikm_aux_header(kmsg);
1640 	if (cur_hdr == NULL) {
1641 		return;
1642 	}
1643 
1644 	/*
1645 	 * New header size must not exceed the space allocated for aux.
1646 	 */
1647 	assert3u(kmsg->ikm_aux_size, >=, new_hdr->msgdh_size);
1648 	assert3u(kmsg->ikm_aux_size, >=, sizeof(mach_msg_aux_header_t));
1649 
1650 	*cur_hdr = *new_hdr;
1651 }
1652 
1653 /*
1654  *	Routine:	ipc_kmsg_alloc
1655  *	Purpose:
1656  *		Allocate a kernel message structure.  If the
1657  *		message is scalar and all the data resides inline, that is best.
1658  *      Otherwise, allocate out of line buffers to fit the message and
1659  *      the optional auxiliary data.
1660  *
1661  *	Conditions:
1662  *		Nothing locked.
1663  *
1664  *      kmsg_size doesn't take the trailer or descriptor
1665  *		inflation into account, but already accounts for the mach
1666  *		message header expansion.
1667  */
1668 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)1669 ipc_kmsg_alloc(
1670 	mach_msg_size_t         kmsg_size,
1671 	mach_msg_size_t         aux_size,
1672 	mach_msg_size_t         desc_count,
1673 	ipc_kmsg_alloc_flags_t  flags)
1674 {
1675 	mach_msg_size_t max_kmsg_size, max_delta, max_kdata_size,
1676 	    min_kdata_size, max_udata_size, max_kmsg_and_aux_size;
1677 	ipc_kmsg_t kmsg;
1678 
1679 	void *msg_data = NULL, *user_data = NULL;
1680 	zalloc_flags_t alloc_flags = Z_WAITOK;
1681 	ipc_kmsg_type_t kmsg_type;
1682 	ipc_kmsg_vector_t *vec;
1683 
1684 	/*
1685 	 * In kernel descriptors, are of the same size (KERNEL_DESC_SIZE),
1686 	 * but in userspace, depending on 64-bitness, descriptors might be
1687 	 * smaller.
1688 	 *
1689 	 * When handling a userspace message however, we know how many
1690 	 * descriptors have been declared, and we pad for the maximum expansion.
1691 	 *
1692 	 * During descriptor expansion, message header stays at the same place
1693 	 * while everything after it gets shifted to higher address.
1694 	 */
1695 	if (flags & IPC_KMSG_ALLOC_KERNEL) {
1696 		assert(aux_size == 0);
1697 		max_delta = 0;
1698 	} else if (os_mul_overflow(desc_count, USER_DESC_MAX_DELTA, &max_delta)) {
1699 		return IKM_NULL;
1700 	}
1701 
1702 	if (os_add3_overflow(kmsg_size, MAX_TRAILER_SIZE, max_delta, &max_kmsg_size)) {
1703 		return IKM_NULL;
1704 	}
1705 	if (os_add_overflow(max_kmsg_size, aux_size, &max_kmsg_and_aux_size)) {
1706 		return IKM_NULL;
1707 	}
1708 
1709 	if (flags & IPC_KMSG_ALLOC_ZERO) {
1710 		alloc_flags |= Z_ZERO;
1711 	}
1712 	if (flags & IPC_KMSG_ALLOC_NOFAIL) {
1713 		alloc_flags |= Z_NOFAIL;
1714 	}
1715 
1716 	/* First, determine the layout of the kmsg to allocate */
1717 	if (max_kmsg_and_aux_size <= IKM_SAVED_MSG_SIZE) {
1718 		kmsg_type = IKM_TYPE_ALL_INLINED;
1719 		max_udata_size = 0;
1720 		max_kdata_size = 0;
1721 	} else if (flags & IPC_KMSG_ALLOC_SAVED) {
1722 		panic("size too large for the fast kmsg zone (%d)", kmsg_size);
1723 	} else if (flags & IPC_KMSG_ALLOC_LINEAR) {
1724 		kmsg_type = IKM_TYPE_KDATA_OOL;
1725 		/*
1726 		 * Caller sets MACH64_SEND_KOBJECT_CALL or MACH64_SEND_ANY, or that
1727 		 * the call originates from kernel, or it's a mach_msg() call.
1728 		 * In any case, message does not carry aux data.
1729 		 * We have validated mach_msg2() call options in mach_msg2_trap().
1730 		 */
1731 		if (aux_size != 0) {
1732 			panic("non-zero aux size for kmsg type IKM_TYPE_KDATA_OOL.");
1733 		}
1734 		max_udata_size = aux_size;
1735 		max_kdata_size = max_kmsg_size;
1736 	} else {
1737 		/*
1738 		 * If message can be splitted from the middle, IOW does not need to
1739 		 * occupy contiguous memory space, sequester (header + descriptors)
1740 		 * from (content + trailer + aux) for memory security.
1741 		 */
1742 		assert(max_kmsg_and_aux_size > IKM_SAVED_MSG_SIZE);
1743 
1744 		/*
1745 		 * max_kdata_size: Maximum combined size of header plus (optional) descriptors.
1746 		 * This is _base_ size + descriptor count * kernel descriptor size.
1747 		 */
1748 		if (os_mul_and_add_overflow(desc_count, KERNEL_DESC_SIZE,
1749 		    sizeof(mach_msg_base_t), &max_kdata_size)) {
1750 			return IKM_NULL;
1751 		}
1752 
1753 		/*
1754 		 * min_kdata_size: Minimum combined size of header plus (optional) descriptors.
1755 		 * This is _header_ size + descriptor count * minimal descriptor size.
1756 		 */
1757 		mach_msg_size_t min_size = (flags & IPC_KMSG_ALLOC_KERNEL) ?
1758 		    KERNEL_DESC_SIZE : MACH_MSG_DESC_MIN_SIZE;
1759 		if (os_mul_and_add_overflow(desc_count, min_size,
1760 		    sizeof(mach_msg_header_t), &min_kdata_size)) {
1761 			return IKM_NULL;
1762 		}
1763 
1764 		/*
1765 		 * max_udata_size: Maximum combined size of message content, trailer and aux.
1766 		 * This is total kmsg and aux size (already accounts for max trailer size) minus
1767 		 * _minimum_ (header + descs) size.
1768 		 */
1769 		if (os_sub_overflow(max_kmsg_and_aux_size, min_kdata_size, &max_udata_size)) {
1770 			return IKM_NULL;
1771 		}
1772 
1773 		if (max_kdata_size <= IKM_SAVED_MSG_SIZE) {
1774 			max_kdata_size = 0; /* no need to allocate kdata */
1775 			kmsg_type = IKM_TYPE_UDATA_OOL;
1776 		} else {
1777 			kmsg_type = IKM_TYPE_ALL_OOL;
1778 		}
1779 	}
1780 
1781 	/* Then, allocate memory for both udata and kdata if needed, as well as kmsg */
1782 	if (max_udata_size > 0) {
1783 		user_data = kalloc_data(max_udata_size, alloc_flags);
1784 		if (user_data == NULL) {
1785 			return IKM_NULL;
1786 		}
1787 	}
1788 
1789 	if (max_kdata_size > 0) {
1790 		if (kmsg_type == IKM_TYPE_ALL_OOL) {
1791 			msg_data = kalloc_type(mach_msg_base_t, mach_msg_descriptor_t, desc_count, alloc_flags);
1792 		} else {
1793 			assert(kmsg_type == IKM_TYPE_KDATA_OOL);
1794 			msg_data = kalloc_data(max_kdata_size, alloc_flags);
1795 		}
1796 
1797 		if (__improbable(msg_data == NULL)) {
1798 			kfree_data(user_data, max_udata_size);
1799 			return IKM_NULL;
1800 		}
1801 	}
1802 
1803 	kmsg = zalloc_flags(ipc_kmsg_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1804 	kmsg->ikm_type = kmsg_type;
1805 	kmsg->ikm_aux_size = aux_size;
1806 
1807 	/* Finally, set up pointers properly */
1808 	if (user_data) {
1809 		assert(kmsg_type != IKM_TYPE_ALL_INLINED);
1810 		kmsg->ikm_udata = user_data;
1811 		kmsg->ikm_udata_size = max_udata_size; /* buffer size */
1812 	}
1813 	if (msg_data) {
1814 		assert(kmsg_type == IKM_TYPE_ALL_OOL || kmsg_type == IKM_TYPE_KDATA_OOL);
1815 		vec = (ipc_kmsg_vector_t *)ikm_inline_data(kmsg);
1816 		vec->kmsgv_data = msg_data;
1817 		vec->kmsgv_size = (kmsg_type == IKM_TYPE_ALL_OOL) ?
1818 		    desc_count :     /* save descriptor count on kmsgv_size */
1819 		    max_kdata_size;  /* buffer size */
1820 	}
1821 
1822 	/* inline kmsg space at least can fit a vector */
1823 	static_assert(IKM_SAVED_MSG_SIZE > sizeof(ipc_kmsg_vector_t));
1824 
1825 	return kmsg;
1826 }
1827 
1828 /* re-export for IOKit's c++ */
1829 extern ipc_kmsg_t ipc_kmsg_alloc_uext_reply(mach_msg_size_t);
1830 
1831 ipc_kmsg_t
ipc_kmsg_alloc_uext_reply(mach_msg_size_t size)1832 ipc_kmsg_alloc_uext_reply(
1833 	mach_msg_size_t         size)
1834 {
1835 	return ipc_kmsg_alloc(size, 0, 0, IPC_KMSG_ALLOC_KERNEL | IPC_KMSG_ALLOC_LINEAR |
1836 	           IPC_KMSG_ALLOC_ZERO | IPC_KMSG_ALLOC_NOFAIL);
1837 }
1838 
1839 
1840 /*
1841  *	Routine:	ipc_kmsg_free
1842  *	Purpose:
1843  *		Free a kernel message (and udata) buffer.  If the kmg is preallocated
1844  *		to a port, just "put it back (marked unused)."  We have to
1845  *		do this with the port locked. The port may have its hold
1846  *		on our message released.  In that case, we have to just
1847  *		revert the message to a traditional one and free it normally.
1848  *	Conditions:
1849  *		Nothing locked.
1850  */
1851 void
ipc_kmsg_free(ipc_kmsg_t kmsg)1852 ipc_kmsg_free(
1853 	ipc_kmsg_t      kmsg)
1854 {
1855 	mach_msg_size_t msg_buf_size = 0, udata_buf_size = 0, dsc_count = 0;
1856 	void *msg_buf = NULL, *udata_buf = NULL;
1857 	ipc_kmsg_vector_t *vec = NULL;
1858 	ipc_port_t inuse_port = IP_NULL;
1859 	mach_msg_header_t *hdr;
1860 
1861 	assert(!IP_VALID(ipc_kmsg_get_voucher_port(kmsg)));
1862 
1863 	KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_FREE) | DBG_FUNC_NONE,
1864 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
1865 	    0, 0, 0, 0);
1866 
1867 	switch (kmsg->ikm_type) {
1868 	case IKM_TYPE_ALL_INLINED:
1869 	case IKM_TYPE_UDATA_OOL:
1870 		msg_buf = ikm_inline_data(kmsg);
1871 		msg_buf_size = IKM_SAVED_MSG_SIZE;
1872 		break;
1873 	case IKM_TYPE_KDATA_OOL:
1874 		vec = ikm_inline_data(kmsg);
1875 		msg_buf = vec->kmsgv_data;
1876 		msg_buf_size = vec->kmsgv_size;
1877 		break;
1878 	case IKM_TYPE_ALL_OOL:
1879 		vec = ikm_inline_data(kmsg);
1880 		msg_buf = vec->kmsgv_data;
1881 		dsc_count = vec->kmsgv_size;
1882 		msg_buf_size = sizeof(mach_msg_base_t) + dsc_count * KERNEL_DESC_SIZE;
1883 		break;
1884 	default:
1885 		panic("strange kmsg type");
1886 	}
1887 
1888 	hdr = ikm_header(kmsg);
1889 	if ((void *)hdr < msg_buf ||
1890 	    (void *)hdr >= (void *)((uintptr_t)msg_buf + msg_buf_size)) {
1891 		panic("ipc_kmsg_free: invalid kmsg (%p) header", kmsg);
1892 	}
1893 
1894 	if (kmsg->ikm_type != IKM_TYPE_ALL_INLINED) {
1895 		udata_buf = kmsg->ikm_udata;
1896 		udata_buf_size = kmsg->ikm_udata_size;
1897 	}
1898 
1899 	switch (kmsg->ikm_type) {
1900 	case IKM_TYPE_ALL_INLINED:
1901 		/*
1902 		 * Check to see if the message is bound to the port.
1903 		 * If so, mark it not in use.
1904 		 */
1905 		inuse_port = ikm_prealloc_inuse_port(kmsg);
1906 		if (inuse_port != IP_NULL) {
1907 			ip_mq_lock(inuse_port);
1908 			ikm_prealloc_clear_inuse(kmsg);
1909 			assert(inuse_port->ip_premsg == kmsg);
1910 			assert(IP_PREALLOC(inuse_port));
1911 			ip_mq_unlock(inuse_port);
1912 			ip_release(inuse_port); /* May be last reference */
1913 			return;
1914 		}
1915 		/* all data inlined, nothing to do */
1916 		break;
1917 	case IKM_TYPE_UDATA_OOL:
1918 		assert(udata_buf != NULL);
1919 		kfree_data(udata_buf, udata_buf_size);
1920 		/* kdata is inlined, udata freed */
1921 		break;
1922 	case IKM_TYPE_KDATA_OOL:
1923 		kfree_data(msg_buf, msg_buf_size);
1924 		assert(udata_buf == NULL);
1925 		assert(udata_buf_size == 0);
1926 		/* kdata freed, no udata */
1927 		break;
1928 	case IKM_TYPE_ALL_OOL:
1929 		kfree_type(mach_msg_base_t, mach_msg_descriptor_t, dsc_count, msg_buf);
1930 		/* kdata freed */
1931 		assert(udata_buf != NULL);
1932 		kfree_data(udata_buf, udata_buf_size);
1933 		/* udata freed */
1934 		break;
1935 	default:
1936 		panic("strange kmsg type");
1937 	}
1938 
1939 	zfree(ipc_kmsg_zone, kmsg);
1940 	/* kmsg struct freed */
1941 }
1942 
1943 
1944 /*
1945  *	Routine:	ipc_kmsg_enqueue_qos
1946  *	Purpose:
1947  *		Enqueue a kmsg, propagating qos
1948  *		overrides towards the head of the queue.
1949  *
1950  *	Returns:
1951  *		whether the head of the queue had
1952  *		it's override-qos adjusted because
1953  *		of this insertion.
1954  */
1955 
1956 bool
ipc_kmsg_enqueue_qos(ipc_kmsg_queue_t queue,ipc_kmsg_t kmsg)1957 ipc_kmsg_enqueue_qos(
1958 	ipc_kmsg_queue_t        queue,
1959 	ipc_kmsg_t              kmsg)
1960 {
1961 	mach_msg_qos_t qos_ovr = kmsg->ikm_qos_override;
1962 	ipc_kmsg_t     prev;
1963 
1964 	if (ipc_kmsg_enqueue(queue, kmsg)) {
1965 		return true;
1966 	}
1967 
1968 	/* apply QoS overrides towards the head */
1969 	prev = ipc_kmsg_queue_element(kmsg->ikm_link.prev);
1970 	while (prev != kmsg) {
1971 		if (qos_ovr <= prev->ikm_qos_override) {
1972 			return false;
1973 		}
1974 		prev->ikm_qos_override = qos_ovr;
1975 		prev = ipc_kmsg_queue_element(prev->ikm_link.prev);
1976 	}
1977 
1978 	return true;
1979 }
1980 
1981 /*
1982  *	Routine:	ipc_kmsg_override_qos
1983  *	Purpose:
1984  *		Update the override for a given kmsg already
1985  *		enqueued, propagating qos override adjustments
1986  *		towards	the head of the queue.
1987  *
1988  *	Returns:
1989  *		whether the head of the queue had
1990  *		it's override-qos adjusted because
1991  *		of this insertion.
1992  */
1993 
1994 bool
ipc_kmsg_override_qos(ipc_kmsg_queue_t queue,ipc_kmsg_t kmsg,mach_msg_qos_t qos_ovr)1995 ipc_kmsg_override_qos(
1996 	ipc_kmsg_queue_t    queue,
1997 	ipc_kmsg_t          kmsg,
1998 	mach_msg_qos_t      qos_ovr)
1999 {
2000 	ipc_kmsg_t first = ipc_kmsg_queue_first(queue);
2001 	ipc_kmsg_t cur = kmsg;
2002 
2003 	/* apply QoS overrides towards the head */
2004 	while (qos_ovr > cur->ikm_qos_override) {
2005 		cur->ikm_qos_override = qos_ovr;
2006 		if (cur == first) {
2007 			return true;
2008 		}
2009 		cur = ipc_kmsg_queue_element(cur->ikm_link.prev);
2010 	}
2011 
2012 	return false;
2013 }
2014 
2015 /*
2016  *	Routine:	ipc_kmsg_destroy
2017  *	Purpose:
2018  *		Destroys a kernel message.  Releases all rights,
2019  *		references, and memory held by the message.
2020  *		Frees the message.
2021  *	Conditions:
2022  *		No locks held.
2023  */
2024 
2025 void
ipc_kmsg_destroy(ipc_kmsg_t kmsg,ipc_kmsg_destroy_flags_t flags)2026 ipc_kmsg_destroy(
2027 	ipc_kmsg_t                     kmsg,
2028 	ipc_kmsg_destroy_flags_t       flags)
2029 {
2030 	/* sign the msg if it has not been signed */
2031 	boolean_t sign_msg = (flags & IPC_KMSG_DESTROY_NOT_SIGNED);
2032 	mach_msg_header_t *hdr = ikm_header(kmsg);
2033 
2034 	if (flags & IPC_KMSG_DESTROY_SKIP_REMOTE) {
2035 		hdr->msgh_remote_port = MACH_PORT_NULL;
2036 		/* re-sign the msg since content changed */
2037 		sign_msg = true;
2038 	}
2039 
2040 	if (flags & IPC_KMSG_DESTROY_SKIP_LOCAL) {
2041 		hdr->msgh_local_port = MACH_PORT_NULL;
2042 		/* re-sign the msg since content changed */
2043 		sign_msg = true;
2044 	}
2045 
2046 	if (sign_msg) {
2047 		ikm_sign(kmsg);
2048 	}
2049 
2050 	/*
2051 	 *	Destroying a message can cause more messages to be destroyed.
2052 	 *	Curtail recursion by putting messages on the deferred
2053 	 *	destruction queue.  If this was the first message on the
2054 	 *	queue, this instance must process the full queue.
2055 	 */
2056 	if (ipc_kmsg_delayed_destroy(kmsg)) {
2057 		ipc_kmsg_reap_delayed();
2058 	}
2059 }
2060 
2061 /*
2062  *	Routine:	ipc_kmsg_delayed_destroy
2063  *	Purpose:
2064  *		Enqueues a kernel message for deferred destruction.
2065  *	Returns:
2066  *		Boolean indicator that the caller is responsible to reap
2067  *		deferred messages.
2068  */
2069 
2070 bool
ipc_kmsg_delayed_destroy(ipc_kmsg_t kmsg)2071 ipc_kmsg_delayed_destroy(
2072 	ipc_kmsg_t kmsg)
2073 {
2074 	return ipc_kmsg_enqueue(&current_thread()->ith_messages, kmsg);
2075 }
2076 
2077 /*
2078  *	Routine:	ipc_kmsg_delayed_destroy_queue
2079  *	Purpose:
2080  *		Enqueues a queue of kernel messages for deferred destruction.
2081  *	Returns:
2082  *		Boolean indicator that the caller is responsible to reap
2083  *		deferred messages.
2084  */
2085 
2086 bool
ipc_kmsg_delayed_destroy_queue(ipc_kmsg_queue_t queue)2087 ipc_kmsg_delayed_destroy_queue(
2088 	ipc_kmsg_queue_t        queue)
2089 {
2090 	return circle_queue_concat_tail(&current_thread()->ith_messages, queue);
2091 }
2092 
2093 /*
2094  *	Routine:	ipc_kmsg_reap_delayed
2095  *	Purpose:
2096  *		Destroys messages from the per-thread
2097  *		deferred reaping queue.
2098  *	Conditions:
2099  *		No locks held. kmsgs on queue must be signed.
2100  */
2101 
2102 void
ipc_kmsg_reap_delayed(void)2103 ipc_kmsg_reap_delayed(void)
2104 {
2105 	ipc_kmsg_queue_t queue = &(current_thread()->ith_messages);
2106 	ipc_kmsg_t kmsg;
2107 
2108 	/*
2109 	 * must leave kmsg in queue while cleaning it to assure
2110 	 * no nested calls recurse into here.
2111 	 */
2112 	while ((kmsg = ipc_kmsg_queue_first(queue)) != IKM_NULL) {
2113 		/*
2114 		 * Kmsgs queued for delayed destruction either come from
2115 		 * ipc_kmsg_destroy() or ipc_kmsg_delayed_destroy_queue(),
2116 		 * where we handover all kmsgs enqueued on port to destruction
2117 		 * queue in O(1). In either case, all kmsgs must have been
2118 		 * signed.
2119 		 *
2120 		 * For each unreceived msg, validate its signature before freeing.
2121 		 */
2122 		ikm_validate_sig(kmsg);
2123 
2124 		ipc_kmsg_clean(kmsg);
2125 		ipc_kmsg_rmqueue(queue, kmsg);
2126 		ipc_kmsg_free(kmsg);
2127 	}
2128 }
2129 
2130 /*
2131  *	Routine:	ipc_kmsg_clean_body
2132  *	Purpose:
2133  *		Cleans the body of a kernel message.
2134  *		Releases all rights, references, and memory.
2135  *
2136  *	Conditions:
2137  *		No locks held.
2138  */
2139 static void
ipc_kmsg_clean_body(__unused ipc_kmsg_t kmsg,mach_msg_type_number_t number,mach_msg_descriptor_t * saddr)2140 ipc_kmsg_clean_body(
2141 	__unused ipc_kmsg_t     kmsg,
2142 	mach_msg_type_number_t  number,
2143 	mach_msg_descriptor_t   *saddr)
2144 {
2145 	mach_msg_type_number_t      i;
2146 
2147 	if (number == 0) {
2148 		return;
2149 	}
2150 
2151 	for (i = 0; i < number; i++, saddr++) {
2152 		switch (saddr->type.type) {
2153 		case MACH_MSG_PORT_DESCRIPTOR: {
2154 			mach_msg_port_descriptor_t *dsc;
2155 
2156 			dsc = &saddr->port;
2157 
2158 			/*
2159 			 * Destroy port rights carried in the message
2160 			 */
2161 			if (!IP_VALID(dsc->name)) {
2162 				continue;
2163 			}
2164 			ipc_object_destroy(ip_to_object(dsc->name), dsc->disposition);
2165 			break;
2166 		}
2167 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
2168 		case MACH_MSG_OOL_DESCRIPTOR: {
2169 			mach_msg_ool_descriptor_t *dsc;
2170 
2171 			dsc = (mach_msg_ool_descriptor_t *)&saddr->out_of_line;
2172 
2173 			/*
2174 			 * Destroy memory carried in the message
2175 			 */
2176 			if (dsc->size == 0) {
2177 				assert(dsc->address == (void *) 0);
2178 			} else {
2179 				vm_map_copy_discard((vm_map_copy_t) dsc->address);
2180 			}
2181 			break;
2182 		}
2183 		case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
2184 			ipc_object_t                    *objects;
2185 			mach_msg_type_number_t          j;
2186 			mach_msg_ool_ports_descriptor_t *dsc;
2187 
2188 			dsc = (mach_msg_ool_ports_descriptor_t  *)&saddr->ool_ports;
2189 			objects = (ipc_object_t *) dsc->address;
2190 
2191 			if (dsc->count == 0) {
2192 				break;
2193 			}
2194 
2195 			assert(objects != (ipc_object_t *) 0);
2196 
2197 			/* destroy port rights carried in the message */
2198 
2199 			for (j = 0; j < dsc->count; j++) {
2200 				ipc_object_t object = objects[j];
2201 
2202 				if (!IO_VALID(object)) {
2203 					continue;
2204 				}
2205 
2206 				ipc_object_destroy(object, dsc->disposition);
2207 			}
2208 
2209 			/* destroy memory carried in the message */
2210 
2211 			assert(dsc->count != 0);
2212 
2213 			kfree_type(mach_port_t, dsc->count, dsc->address);
2214 			break;
2215 		}
2216 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR: {
2217 			mach_msg_guarded_port_descriptor_t *dsc = (typeof(dsc)) & saddr->guarded_port;
2218 
2219 			/*
2220 			 * Destroy port rights carried in the message
2221 			 */
2222 			if (!IP_VALID(dsc->name)) {
2223 				continue;
2224 			}
2225 			ipc_object_destroy(ip_to_object(dsc->name), dsc->disposition);
2226 			break;
2227 		}
2228 		default:
2229 			panic("invalid descriptor type: (%p: %d)",
2230 			    saddr, saddr->type.type);
2231 		}
2232 	}
2233 }
2234 
2235 /*
2236  *	Routine:	ipc_kmsg_clean_partial
2237  *	Purpose:
2238  *		Cleans a partially-acquired kernel message.
2239  *		number is the index of the type descriptor
2240  *		in the body of the message that contained the error.
2241  *		If dolast, the memory and port rights in this last
2242  *		type spec are also cleaned.  In that case, number
2243  *		specifies the number of port rights to clean.
2244  *	Conditions:
2245  *		Nothing locked.
2246  */
2247 
2248 static void
ipc_kmsg_clean_partial(ipc_kmsg_t kmsg,mach_msg_type_number_t number,mach_msg_descriptor_t * desc,vm_offset_t paddr,vm_size_t length)2249 ipc_kmsg_clean_partial(
2250 	ipc_kmsg_t              kmsg,
2251 	mach_msg_type_number_t  number,
2252 	mach_msg_descriptor_t   *desc,
2253 	vm_offset_t             paddr,
2254 	vm_size_t               length)
2255 {
2256 	ipc_object_t object;
2257 	mach_msg_header_t *hdr = ikm_header(kmsg);
2258 	mach_msg_bits_t mbits = hdr->msgh_bits;
2259 
2260 	/* deal with importance chain while we still have dest and voucher references */
2261 	ipc_importance_clean(kmsg);
2262 
2263 	object = ip_to_object(hdr->msgh_remote_port);
2264 	assert(IO_VALID(object));
2265 	ipc_object_destroy_dest(object, MACH_MSGH_BITS_REMOTE(mbits));
2266 
2267 	object = ip_to_object(hdr->msgh_local_port);
2268 	if (IO_VALID(object)) {
2269 		ipc_object_destroy(object, MACH_MSGH_BITS_LOCAL(mbits));
2270 	}
2271 
2272 	object = ip_to_object(ipc_kmsg_get_voucher_port(kmsg));
2273 	if (IO_VALID(object)) {
2274 		assert(MACH_MSGH_BITS_VOUCHER(mbits) == MACH_MSG_TYPE_MOVE_SEND);
2275 		ipc_object_destroy(object, MACH_MSG_TYPE_PORT_SEND);
2276 		ipc_kmsg_clear_voucher_port(kmsg);
2277 	}
2278 
2279 	if (paddr) {
2280 		kmem_free(ipc_kernel_copy_map, paddr, length);
2281 	}
2282 
2283 	ipc_kmsg_clean_body(kmsg, number, desc);
2284 }
2285 
2286 /*
2287  *	Routine:	ipc_kmsg_clean
2288  *	Purpose:
2289  *		Cleans a kernel message.  Releases all rights,
2290  *		references, and memory held by the message.
2291  *	Conditions:
2292  *		No locks held.
2293  */
2294 
2295 static void
ipc_kmsg_clean(ipc_kmsg_t kmsg)2296 ipc_kmsg_clean(
2297 	ipc_kmsg_t      kmsg)
2298 {
2299 	ipc_object_t object;
2300 	mach_msg_bits_t mbits;
2301 	mach_msg_header_t *hdr;
2302 
2303 	/* deal with importance chain while we still have dest and voucher references */
2304 	ipc_importance_clean(kmsg);
2305 
2306 	hdr = ikm_header(kmsg);
2307 	mbits = hdr->msgh_bits;
2308 	object = ip_to_object(hdr->msgh_remote_port);
2309 	if (IO_VALID(object)) {
2310 		ipc_object_destroy_dest(object, MACH_MSGH_BITS_REMOTE(mbits));
2311 	}
2312 
2313 	object = ip_to_object(hdr->msgh_local_port);
2314 	if (IO_VALID(object)) {
2315 		ipc_object_destroy(object, MACH_MSGH_BITS_LOCAL(mbits));
2316 	}
2317 
2318 	object = ip_to_object(ipc_kmsg_get_voucher_port(kmsg));
2319 	if (IO_VALID(object)) {
2320 		assert(MACH_MSGH_BITS_VOUCHER(mbits) == MACH_MSG_TYPE_MOVE_SEND);
2321 		ipc_object_destroy(object, MACH_MSG_TYPE_PORT_SEND);
2322 		ipc_kmsg_clear_voucher_port(kmsg);
2323 	}
2324 
2325 	if (mbits & MACH_MSGH_BITS_COMPLEX) {
2326 		mach_msg_body_t *body;
2327 
2328 		body = (mach_msg_body_t *) (hdr + 1);
2329 		ipc_kmsg_clean_body(kmsg, body->msgh_descriptor_count,
2330 		    (mach_msg_descriptor_t *)(body + 1));
2331 	}
2332 }
2333 
2334 /*
2335  *	Routine:	ipc_kmsg_set_prealloc
2336  *	Purpose:
2337  *		Assign a kmsg as a preallocated message buffer to a port.
2338  *	Conditions:
2339  *		port locked.
2340  */
2341 void
ipc_kmsg_set_prealloc(ipc_kmsg_t kmsg,ipc_port_t port)2342 ipc_kmsg_set_prealloc(
2343 	ipc_kmsg_t              kmsg,
2344 	ipc_port_t              port)
2345 {
2346 	assert(kmsg->ikm_prealloc == IP_NULL);
2347 	assert(kmsg->ikm_type == IKM_TYPE_ALL_INLINED);
2348 	kmsg->ikm_prealloc = IP_NULL;
2349 
2350 	IP_SET_PREALLOC(port, kmsg);
2351 }
2352 
2353 /*
2354  *	Routine:	ipc_kmsg_too_large
2355  *	Purpose:
2356  *		Return true if kmsg is too large to be received:
2357  *
2358  *      If MACH64_RCV_LINEAR_VECTOR:
2359  *          - combined message buffer is not large enough
2360  *            to fit both the message (plus trailer) and
2361  *            auxiliary data.
2362  *      Otherwise:
2363  *          - message buffer is not large enough
2364  *          - auxiliary buffer is not large enough:
2365  *			  (1) kmsg is a vector with aux, but user expects
2366  *                a scalar kmsg (ith_max_asize is 0)
2367  *            (2) kmsg is a vector with aux, but user aux
2368  *                buffer is not large enough.
2369  */
2370 bool
ipc_kmsg_too_large(mach_msg_size_t msg_size,mach_msg_size_t aux_size,mach_msg_option64_t option64,mach_msg_size_t max_msg_size,mach_msg_size_t max_aux_size,thread_t receiver)2371 ipc_kmsg_too_large(
2372 	mach_msg_size_t     msg_size,
2373 	mach_msg_size_t     aux_size,
2374 	mach_msg_option64_t option64,
2375 	mach_msg_size_t     max_msg_size,
2376 	mach_msg_size_t     max_aux_size,
2377 	thread_t            receiver)
2378 {
2379 	mach_msg_size_t tsize = REQUESTED_TRAILER_SIZE(thread_is_64bit_addr(receiver),
2380 	    receiver->ith_option);
2381 
2382 	if (max_aux_size != 0) {
2383 		assert(option64 & MACH64_MSG_VECTOR);
2384 	}
2385 
2386 	if (option64 & MACH64_RCV_LINEAR_VECTOR) {
2387 		assert(receiver->ith_max_asize == 0);
2388 		assert(receiver->ith_aux_addr == 0);
2389 		assert(option64 & MACH64_MSG_VECTOR);
2390 
2391 		if (max_msg_size < msg_size + tsize + aux_size) {
2392 			return true;
2393 		}
2394 	} else {
2395 		if (max_msg_size < msg_size + tsize) {
2396 			return true;
2397 		}
2398 
2399 		/*
2400 		 * only return too large if MACH64_MSG_VECTOR.
2401 		 *
2402 		 * silently drop aux data when receiver is not expecting it for compat
2403 		 * reasons.
2404 		 */
2405 		if ((option64 & MACH64_MSG_VECTOR) && max_aux_size < aux_size) {
2406 			return true;
2407 		}
2408 	}
2409 
2410 	return false;
2411 }
2412 
2413 /*
2414  *	Routine:	ipc_kmsg_get_body_and_aux_from_user
2415  *	Purpose:
2416  *		Copies in user message (and aux) to allocated kernel message buffer.
2417  *	Conditions:
2418  *		msg_addr and msg_size must be valid. aux_addr and aux_size can
2419  *      be NULL if kmsg is not vectorized, or vector kmsg does not carry
2420  *      auxiliary data.
2421  *
2422  *      msg up to sizeof(mach_msg_user_header_t) has been previously copied in,
2423  *      and number of descriptors has been made known.
2424  *
2425  *      kmsg_size already accounts for message header expansion.
2426  *
2427  *      if aux_size is not 0, mach_msg_validate_data_vectors() guarantees that
2428  *      aux_size must be larger than mach_msg_aux_header_t.
2429  */
2430 static mach_msg_return_t
ipc_kmsg_get_body_and_aux_from_user(ipc_kmsg_t kmsg,mach_vm_address_t msg_addr,mach_msg_size_t kmsg_size,mach_vm_address_t aux_addr,mach_msg_size_t aux_size,mach_msg_size_t desc_count,mach_msg_user_header_t user_header)2431 ipc_kmsg_get_body_and_aux_from_user(
2432 	ipc_kmsg_t             kmsg,
2433 	mach_vm_address_t      msg_addr,
2434 	mach_msg_size_t        kmsg_size,
2435 	mach_vm_address_t      aux_addr,      /* Nullable */
2436 	mach_msg_size_t        aux_size,      /* Nullable */
2437 	mach_msg_size_t        desc_count,
2438 	mach_msg_user_header_t user_header)
2439 {
2440 	mach_msg_header_t *hdr     = ikm_header(kmsg);
2441 	hdr->msgh_size             = kmsg_size;
2442 	hdr->msgh_bits             = user_header.msgh_bits;
2443 	hdr->msgh_remote_port      = CAST_MACH_NAME_TO_PORT(user_header.msgh_remote_port);
2444 	hdr->msgh_local_port       = CAST_MACH_NAME_TO_PORT(user_header.msgh_local_port);
2445 	hdr->msgh_voucher_port     = user_header.msgh_voucher_port;
2446 	hdr->msgh_id               = user_header.msgh_id;
2447 
2448 	if (user_header.msgh_bits & MACH_MSGH_BITS_COMPLEX) {
2449 		mach_msg_base_t *kbase = (mach_msg_base_t *)hdr;
2450 
2451 		assert(kmsg_size >= sizeof(mach_msg_base_t));
2452 		kbase->body.msgh_descriptor_count = desc_count;
2453 
2454 		/* copy in the rest of the message, after user_base */
2455 		if (kmsg_size > sizeof(mach_msg_base_t)) {
2456 			/*
2457 			 * if kmsg is linear, just copyin the remaining msg after base
2458 			 * and we are done. Otherwise, first copyin until the end of descriptors
2459 			 * or the message, whichever comes first.
2460 			 */
2461 			mach_msg_size_t copyin_size = kmsg_size - sizeof(mach_msg_base_t);
2462 			if (!ikm_is_linear(kmsg) && (desc_count * KERNEL_DESC_SIZE < copyin_size)) {
2463 				copyin_size = desc_count * KERNEL_DESC_SIZE;
2464 			}
2465 
2466 			assert((vm_offset_t)hdr + sizeof(mach_msg_base_t) +
2467 			    copyin_size <= ikm_kdata_end(kmsg));
2468 
2469 			if (copyinmsg(msg_addr + sizeof(mach_msg_user_base_t),
2470 			    (char *)hdr + sizeof(mach_msg_base_t),
2471 			    copyin_size)) {
2472 				return MACH_SEND_INVALID_DATA;
2473 			}
2474 
2475 			/*
2476 			 * next, pre-validate the descriptors user claims to have by checking
2477 			 * their size and type, instead of doing it at body copyin time.
2478 			 */
2479 			mach_msg_return_t mr = ikm_check_descriptors(kmsg, current_map(), copyin_size);
2480 			if (mr != MACH_MSG_SUCCESS) {
2481 				return mr;
2482 			}
2483 
2484 			/*
2485 			 * for non-linear kmsg, since we have copied in all data that can
2486 			 * possibly be a descriptor and pre-validated them, we can now measure
2487 			 * the actual descriptor size and copyin the remaining user data
2488 			 * following the descriptors, if there is any.
2489 			 */
2490 			if (!ikm_is_linear(kmsg)) {
2491 				mach_msg_size_t dsc_size = ikm_total_desc_size(kmsg, current_map(), 0, 0, true);
2492 				assert(desc_count * KERNEL_DESC_SIZE >= dsc_size);
2493 
2494 				/* if there is user data after descriptors, copy it into data heap */
2495 				if (kmsg_size > sizeof(mach_msg_base_t) + dsc_size) {
2496 					copyin_size = kmsg_size - sizeof(mach_msg_base_t) - dsc_size;
2497 
2498 					assert(kmsg->ikm_udata != NULL);
2499 					assert((vm_offset_t)kmsg->ikm_udata + copyin_size <= ikm_udata_end(kmsg));
2500 					if (copyinmsg(msg_addr + sizeof(mach_msg_user_base_t) + dsc_size,
2501 					    (char *)kmsg->ikm_udata,
2502 					    copyin_size)) {
2503 						return MACH_SEND_INVALID_DATA;
2504 					}
2505 				}
2506 
2507 				/* finally, nil out the extra user data we copied into kdata */
2508 				if (desc_count * KERNEL_DESC_SIZE > dsc_size) {
2509 					bzero((void *)((vm_offset_t)hdr + sizeof(mach_msg_base_t) + dsc_size),
2510 					    desc_count * KERNEL_DESC_SIZE - dsc_size);
2511 				}
2512 			}
2513 		}
2514 	} else {
2515 		assert(desc_count == 0);
2516 		/* copy in the rest of the message, after user_header */
2517 		if (kmsg_size > sizeof(mach_msg_header_t)) {
2518 			char *msg_content = ikm_is_linear(kmsg) ?
2519 			    (char *)hdr + sizeof(mach_msg_header_t) :
2520 			    (char *)kmsg->ikm_udata;
2521 
2522 			if (ikm_is_linear(kmsg)) {
2523 				assert((vm_offset_t)hdr + kmsg_size <= ikm_kdata_end(kmsg));
2524 			} else {
2525 				assert((vm_offset_t)kmsg->ikm_udata + kmsg_size - sizeof(mach_msg_header_t) <= ikm_udata_end(kmsg));
2526 			}
2527 
2528 			if (copyinmsg(msg_addr + sizeof(mach_msg_user_header_t), msg_content,
2529 			    kmsg_size - sizeof(mach_msg_header_t))) {
2530 				return MACH_SEND_INVALID_DATA;
2531 			}
2532 		}
2533 	}
2534 
2535 	if (aux_size > 0) {
2536 		assert(aux_addr != 0);
2537 		mach_msg_aux_header_t *aux_header = ikm_aux_header(kmsg);
2538 
2539 		assert(kmsg->ikm_aux_size == aux_size);
2540 		assert(aux_header != NULL);
2541 
2542 		/* initialize aux data header */
2543 		aux_header->msgdh_size = aux_size;
2544 		aux_header->msgdh_reserved = 0;
2545 
2546 		/* copyin aux data after the header */
2547 		assert(aux_size >= sizeof(mach_msg_aux_header_t));
2548 		if (aux_size > sizeof(mach_msg_aux_header_t)) {
2549 			if (kmsg->ikm_type != IKM_TYPE_ALL_INLINED) {
2550 				assert((vm_offset_t)aux_header + aux_size <= ikm_udata_end(kmsg));
2551 			} else {
2552 				assert((vm_offset_t)aux_header + aux_size <= ikm_kdata_end(kmsg));
2553 			}
2554 			if (copyinmsg(aux_addr + sizeof(mach_msg_aux_header_t),
2555 			    (char *)aux_header + sizeof(mach_msg_aux_header_t),
2556 			    aux_size - sizeof(mach_msg_aux_header_t))) {
2557 				return MACH_SEND_INVALID_DATA;
2558 			}
2559 		}
2560 	}
2561 
2562 	return MACH_MSG_SUCCESS;
2563 }
2564 
2565 /*
2566  *	Routine:	ipc_kmsg_get_from_user
2567  *	Purpose:
2568  *		Allocates a scalar or vector kernel message buffer.
2569  *		Copies user message (and optional aux data) to the message buffer.
2570  *  Conditions:
2571  *      user_msg_size must have been bound checked. aux_{addr, size} are
2572  *      0 if not MACH64_MSG_VECTOR.
2573  *  Returns:
2574  *      Produces a kmsg reference on success.
2575  *
2576  *		MACH_MSG_SUCCESS	Acquired a message buffer.
2577  *		MACH_SEND_MSG_TOO_SMALL	Message smaller than a header.
2578  *		MACH_SEND_MSG_TOO_SMALL	Message size not long-word multiple.
2579  *		MACH_SEND_TOO_LARGE	Message too large to ever be sent.
2580  *		MACH_SEND_NO_BUFFER	Couldn't allocate a message buffer.
2581  *		MACH_SEND_INVALID_DATA	Couldn't copy message data.
2582  */
2583 mach_msg_return_t
ipc_kmsg_get_from_user(mach_vm_address_t msg_addr,mach_msg_size_t user_msg_size,mach_vm_address_t aux_addr,mach_msg_size_t aux_size,mach_msg_user_header_t user_header,mach_msg_size_t desc_count,mach_msg_option64_t option64,ipc_kmsg_t * kmsgp)2584 ipc_kmsg_get_from_user(
2585 	mach_vm_address_t      msg_addr,
2586 	mach_msg_size_t        user_msg_size,
2587 	mach_vm_address_t      aux_addr,
2588 	mach_msg_size_t        aux_size,
2589 	mach_msg_user_header_t user_header,
2590 	mach_msg_size_t        desc_count,
2591 	mach_msg_option64_t    option64,
2592 	ipc_kmsg_t             *kmsgp)
2593 {
2594 	mach_msg_size_t kmsg_size = 0;
2595 	ipc_kmsg_alloc_flags_t flags = IPC_KMSG_ALLOC_USER;
2596 	ipc_kmsg_t kmsg;
2597 	kern_return_t kr;
2598 
2599 	kmsg_size = user_msg_size + USER_HEADER_SIZE_DELTA;
2600 
2601 	if (aux_size == 0) {
2602 		assert(aux_addr == 0);
2603 	} else {
2604 		assert(aux_size >= sizeof(mach_msg_aux_header_t));
2605 	}
2606 
2607 	if (!(option64 & MACH64_MSG_VECTOR)) {
2608 		assert(aux_addr == 0);
2609 		assert(aux_size == 0);
2610 	}
2611 
2612 	/*
2613 	 * If not a mach_msg2() call to a message queue, allocate a linear kmsg.
2614 	 *
2615 	 * This is equivalent to making the following cases always linear:
2616 	 *     - mach_msg_trap() calls.
2617 	 *     - mach_msg2_trap() to kobject ports.
2618 	 *     - mach_msg2_trap() from old simulators.
2619 	 */
2620 	if (!(option64 & MACH64_SEND_MQ_CALL)) {
2621 		flags |= IPC_KMSG_ALLOC_LINEAR;
2622 	}
2623 
2624 	kmsg = ipc_kmsg_alloc(kmsg_size, aux_size, desc_count, flags);
2625 	/* can fail if msg size is too large */
2626 	if (kmsg == IKM_NULL) {
2627 		return MACH_SEND_NO_BUFFER;
2628 	}
2629 
2630 	kr = ipc_kmsg_get_body_and_aux_from_user(kmsg, msg_addr, kmsg_size,
2631 	    aux_addr, aux_size, desc_count, user_header);
2632 	if (kr != MACH_MSG_SUCCESS) {
2633 		ipc_kmsg_free(kmsg);
2634 		return kr;
2635 	}
2636 
2637 	*kmsgp = kmsg;
2638 	return MACH_MSG_SUCCESS;
2639 }
2640 
2641 /*
2642  *	Routine:	ipc_kmsg_get_from_kernel
2643  *	Purpose:
2644  *		First checks for a preallocated message
2645  *		reserved for kernel clients.  If not found or size is too large -
2646  *		allocates a new kernel message buffer.
2647  *		Copies a kernel message to the message buffer.
2648  *		Only resource errors are allowed.
2649  *	Conditions:
2650  *		Nothing locked.
2651  *		Ports in header are ipc_port_t.
2652  *	Returns:
2653  *		MACH_MSG_SUCCESS	Acquired a message buffer.
2654  *		MACH_SEND_NO_BUFFER	Couldn't allocate a message buffer.
2655  */
2656 
2657 mach_msg_return_t
ipc_kmsg_get_from_kernel(mach_msg_header_t * msg,mach_msg_size_t size,ipc_kmsg_t * kmsgp)2658 ipc_kmsg_get_from_kernel(
2659 	mach_msg_header_t       *msg,
2660 	mach_msg_size_t         size, /* can be larger than prealloc space */
2661 	ipc_kmsg_t              *kmsgp)
2662 {
2663 	ipc_kmsg_t        kmsg;
2664 	mach_msg_header_t *hdr;
2665 	void              *udata;
2666 
2667 	ipc_port_t        dest_port;
2668 	bool              complex;
2669 	mach_msg_size_t   desc_count, kdata_sz;
2670 
2671 	assert(size >= sizeof(mach_msg_header_t));
2672 	assert((size & 3) == 0);
2673 
2674 	dest_port = msg->msgh_remote_port; /* Nullable */
2675 	complex = (msg->msgh_bits & MACH_MSGH_BITS_COMPLEX);
2676 
2677 	/*
2678 	 * See if the port has a pre-allocated kmsg for kernel
2679 	 * clients.  These are set up for those kernel clients
2680 	 * which cannot afford to wait.
2681 	 */
2682 	if (IP_VALID(dest_port) && IP_PREALLOC(dest_port)) {
2683 		ip_mq_lock(dest_port);
2684 
2685 		if (!ip_active(dest_port)) {
2686 			ip_mq_unlock(dest_port);
2687 			return MACH_SEND_NO_BUFFER;
2688 		}
2689 
2690 		assert(IP_PREALLOC(dest_port));
2691 		kmsg = dest_port->ip_premsg;
2692 
2693 		if (ikm_prealloc_inuse(kmsg)) {
2694 			ip_mq_unlock(dest_port);
2695 			return MACH_SEND_NO_BUFFER;
2696 		}
2697 
2698 		assert(kmsg->ikm_type == IKM_TYPE_ALL_INLINED);
2699 		assert(kmsg->ikm_aux_size == 0);
2700 
2701 		if (size + MAX_TRAILER_SIZE > IKM_SAVED_MSG_SIZE) {
2702 			ip_mq_unlock(dest_port);
2703 			return MACH_SEND_TOO_LARGE;
2704 		}
2705 		ikm_prealloc_set_inuse(kmsg, dest_port);
2706 
2707 		ip_mq_unlock(dest_port);
2708 	} else {
2709 		desc_count = 0;
2710 		kdata_sz = sizeof(mach_msg_header_t);
2711 
2712 		if (complex) {
2713 			desc_count = ((mach_msg_base_t *)msg)->body.msgh_descriptor_count;
2714 			kdata_sz = sizeof(mach_msg_base_t) + desc_count * KERNEL_DESC_SIZE;
2715 			assert(size >= kdata_sz);
2716 		}
2717 
2718 		kmsg = ipc_kmsg_alloc(size, 0, desc_count, IPC_KMSG_ALLOC_KERNEL);
2719 		/* kmsg can be non-linear */
2720 	}
2721 
2722 	if (kmsg == IKM_NULL) {
2723 		return MACH_SEND_NO_BUFFER;
2724 	}
2725 
2726 	hdr = ikm_header(kmsg);
2727 	if (ikm_is_linear(kmsg)) {
2728 		memcpy(hdr, msg, size);
2729 	} else {
2730 		/* copy kdata to kernel allocation chunk */
2731 		memcpy(hdr, msg, kdata_sz);
2732 		/* copy udata to user allocation chunk */
2733 		udata = ikm_udata(kmsg, desc_count, complex);
2734 		memcpy(udata, (char *)msg + kdata_sz, size - kdata_sz);
2735 	}
2736 	hdr->msgh_size = size;
2737 
2738 	*kmsgp = kmsg;
2739 	return MACH_MSG_SUCCESS;
2740 }
2741 
2742 /*
2743  *	Routine:	ipc_kmsg_send
2744  *	Purpose:
2745  *		Send a message.  The message holds a reference
2746  *		for the destination port in the msgh_remote_port field.
2747  *
2748  *		If unsuccessful, the caller still has possession of
2749  *		the message and must do something with it.  If successful,
2750  *		the message is queued, given to a receiver, destroyed,
2751  *		or handled directly by the kernel via mach_msg.
2752  *	Conditions:
2753  *		Nothing locked.
2754  *	Returns:
2755  *		MACH_MSG_SUCCESS	       The message was accepted.
2756  *		MACH_SEND_TIMED_OUT	       Caller still has message.
2757  *		MACH_SEND_INTERRUPTED	   Caller still has message.
2758  *		MACH_SEND_INVALID_DEST	   Caller still has message.
2759  *      MACH_SEND_INVALID_OPTIONS  Caller still has message.
2760  */
2761 mach_msg_return_t
ipc_kmsg_send(ipc_kmsg_t kmsg,mach_msg_option64_t option64,mach_msg_timeout_t send_timeout)2762 ipc_kmsg_send(
2763 	ipc_kmsg_t              kmsg,
2764 	mach_msg_option64_t     option64,
2765 	mach_msg_timeout_t      send_timeout)
2766 {
2767 	ipc_port_t port;
2768 	thread_t th = current_thread();
2769 	mach_msg_return_t error = MACH_MSG_SUCCESS;
2770 	boolean_t kernel_reply = FALSE;
2771 	mach_msg_header_t *hdr;
2772 
2773 	/* Check if honor qlimit flag is set on thread. */
2774 	if ((th->options & TH_OPT_HONOR_QLIMIT) == TH_OPT_HONOR_QLIMIT) {
2775 		/* Remove the MACH_SEND_ALWAYS flag to honor queue limit. */
2776 		option64 &= (~MACH64_SEND_ALWAYS);
2777 		/* Add the timeout flag since the message queue might be full. */
2778 		option64 |= MACH64_SEND_TIMEOUT;
2779 		th->options &= (~TH_OPT_HONOR_QLIMIT);
2780 	}
2781 
2782 #if IMPORTANCE_INHERITANCE
2783 	bool did_importance = false;
2784 #if IMPORTANCE_TRACE
2785 	mach_msg_id_t imp_msgh_id = -1;
2786 	int           sender_pid  = -1;
2787 #endif /* IMPORTANCE_TRACE */
2788 #endif /* IMPORTANCE_INHERITANCE */
2789 
2790 	hdr = ikm_header(kmsg);
2791 	/* don't allow the creation of a circular loop */
2792 	if (hdr->msgh_bits & MACH_MSGH_BITS_CIRCULAR) {
2793 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_ALL);
2794 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_MSGH_BITS_CIRCULAR);
2795 		return MACH_MSG_SUCCESS;
2796 	}
2797 
2798 	ipc_voucher_send_preprocessing(kmsg);
2799 
2800 	port = hdr->msgh_remote_port;
2801 	assert(IP_VALID(port));
2802 	ip_mq_lock(port);
2803 
2804 	if (option64 & MACH64_MACH_MSG2) {
2805 		/*
2806 		 * This is a _user_ message via mach_msg2_trap()。
2807 		 *
2808 		 * To curb kobject port/message queue confusion and improve control flow
2809 		 * integrity, mach_msg2_trap() invocations mandate the use of either
2810 		 * MACH64_SEND_KOBJECT_CALL or MACH64_SEND_MQ_CALL and that the flag
2811 		 * matches the underlying port type. (unless the call is from a simulator,
2812 		 * since old simulators keep using mach_msg() in all cases indiscriminatingly.)
2813 		 *
2814 		 * Since:
2815 		 *     (1) We make sure to always pass either MACH64_SEND_MQ_CALL or
2816 		 *         MACH64_SEND_KOBJECT_CALL bit at all sites outside simulators
2817 		 *         (checked by mach_msg2_trap());
2818 		 *     (2) We checked in mach_msg2_trap() that _exactly_ one of the three bits is set.
2819 		 *
2820 		 * CFI check cannot be bypassed by simply setting MACH64_SEND_ANY.
2821 		 */
2822 #if XNU_TARGET_OS_OSX
2823 		if (option64 & MACH64_SEND_ANY) {
2824 			goto cfi_passed;
2825 		}
2826 #endif /* XNU_TARGET_OS_OSX */
2827 
2828 		if (ip_is_kobject(port)) {
2829 			natural_t kotype = ip_kotype(port);
2830 
2831 			if (__improbable(kotype == IKOT_TIMER)) {
2832 				/*
2833 				 * For bincompat, let's still allow user messages to timer port, but
2834 				 * force MACH64_SEND_MQ_CALL flag for memory segregation.
2835 				 */
2836 				if (__improbable(!(option64 & MACH64_SEND_MQ_CALL))) {
2837 					ip_mq_unlock(port);
2838 					mach_port_guard_exception(0, 0, 0, kGUARD_EXC_INVALID_OPTIONS);
2839 					return MACH_SEND_INVALID_OPTIONS;
2840 				}
2841 			} else {
2842 				/* Otherwise, caller must set MACH64_SEND_KOBJECT_CALL. */
2843 				if (__improbable(!(option64 & MACH64_SEND_KOBJECT_CALL))) {
2844 					ip_mq_unlock(port);
2845 					mach_port_guard_exception(0, 0, 0, kGUARD_EXC_INVALID_OPTIONS);
2846 					return MACH_SEND_INVALID_OPTIONS;
2847 				}
2848 			}
2849 		}
2850 
2851 #if CONFIG_CSR
2852 		if (csr_check(CSR_ALLOW_KERNEL_DEBUGGER) == 0) {
2853 			/*
2854 			 * Allow MACH64_SEND_KOBJECT_CALL flag to message queues when SIP
2855 			 * is off (for Mach-on-Mach emulation). The other direction is still
2856 			 * not allowed (MIG KernelServer assumes a linear kmsg).
2857 			 */
2858 			goto cfi_passed;
2859 		}
2860 #endif /* CONFIG_CSR */
2861 
2862 		/* If destination is a message queue, caller must set MACH64_SEND_MQ_CALL */
2863 		if (__improbable((!ip_is_kobject(port) &&
2864 		    !(option64 & MACH64_SEND_MQ_CALL)))) {
2865 			ip_mq_unlock(port);
2866 			mach_port_guard_exception(0, 0, 0, kGUARD_EXC_INVALID_OPTIONS);
2867 			return MACH_SEND_INVALID_OPTIONS;
2868 		}
2869 	}
2870 
2871 #if (XNU_TARGET_OS_OSX || CONFIG_CSR)
2872 cfi_passed:
2873 #endif /* XNU_TARGET_OS_OSX || CONFIG_CSR */
2874 
2875 	/*
2876 	 * If the destination has been guarded with a reply context, and the
2877 	 * sender is consuming a send-once right, then assume this is a reply
2878 	 * to an RPC and we need to validate that this sender is currently in
2879 	 * the correct context.
2880 	 */
2881 	if (enforce_strict_reply && port->ip_reply_context != 0 &&
2882 	    ((option64 & MACH64_SEND_KERNEL) == 0) &&
2883 	    MACH_MSGH_BITS_REMOTE(hdr->msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE) {
2884 		error = ipc_kmsg_validate_reply_context_locked((mach_msg_option_t)option64,
2885 		    port, th->ith_voucher, th->ith_voucher_name);
2886 		if (error != MACH_MSG_SUCCESS) {
2887 			ip_mq_unlock(port);
2888 			return error;
2889 		}
2890 	}
2891 
2892 #if IMPORTANCE_INHERITANCE
2893 retry:
2894 #endif /* IMPORTANCE_INHERITANCE */
2895 	/*
2896 	 *	Can't deliver to a dead port.
2897 	 *	However, we can pretend it got sent
2898 	 *	and was then immediately destroyed.
2899 	 */
2900 	if (!ip_active(port)) {
2901 		ip_mq_unlock(port);
2902 #if MACH_FLIPC
2903 		if (MACH_NODE_VALID(kmsg->ikm_node) && FPORT_VALID(port->ip_messages.imq_fport)) {
2904 			flipc_msg_ack(kmsg->ikm_node, &port->ip_messages, FALSE);
2905 		}
2906 #endif
2907 		if (did_importance) {
2908 			/*
2909 			 * We're going to pretend we delivered this message
2910 			 * successfully, and just eat the kmsg. However, the
2911 			 * kmsg is actually visible via the importance_task!
2912 			 * We need to cleanup this linkage before we destroy
2913 			 * the message, and more importantly before we set the
2914 			 * msgh_remote_port to NULL. See: 34302571
2915 			 */
2916 			ipc_importance_clean(kmsg);
2917 		}
2918 		ip_release(port);  /* JMM - Future: release right, not just ref */
2919 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
2920 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_SEND_INVALID_DEST);
2921 		return MACH_MSG_SUCCESS;
2922 	}
2923 
2924 	if (ip_in_space(port, ipc_space_kernel)) {
2925 		require_ip_active(port);
2926 		port->ip_messages.imq_seqno++;
2927 		ip_mq_unlock(port);
2928 
2929 		counter_inc(&current_task()->messages_sent);
2930 
2931 		/*
2932 		 * Call the server routine, and get the reply message to send.
2933 		 */
2934 		kmsg = ipc_kobject_server(port, kmsg, (mach_msg_option_t)option64);
2935 		if (kmsg == IKM_NULL) {
2936 			return MACH_MSG_SUCCESS;
2937 		}
2938 		/* reload hdr since kmsg changed */
2939 		hdr = ikm_header(kmsg);
2940 
2941 		/* sign the reply message */
2942 		ipc_kmsg_init_trailer(kmsg, TASK_NULL);
2943 		ikm_sign(kmsg);
2944 
2945 		/* restart the KMSG_INFO tracing for the reply message */
2946 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_START);
2947 		port = hdr->msgh_remote_port;
2948 		assert(IP_VALID(port));
2949 		ip_mq_lock(port);
2950 		/* fall thru with reply - same options */
2951 		kernel_reply = TRUE;
2952 		if (!ip_active(port)) {
2953 			error = MACH_SEND_INVALID_DEST;
2954 		}
2955 	}
2956 
2957 #if IMPORTANCE_INHERITANCE
2958 	/*
2959 	 * Need to see if this message needs importance donation and/or
2960 	 * propagation.  That routine can drop the port lock temporarily.
2961 	 * If it does we'll have to revalidate the destination.
2962 	 */
2963 	if (!did_importance) {
2964 		did_importance = true;
2965 		if (ipc_importance_send(kmsg, (mach_msg_option_t)option64)) {
2966 			goto retry;
2967 		}
2968 	}
2969 #endif /* IMPORTANCE_INHERITANCE */
2970 
2971 	if (error != MACH_MSG_SUCCESS) {
2972 		ip_mq_unlock(port);
2973 	} else {
2974 		/*
2975 		 * We have a valid message and a valid reference on the port.
2976 		 * call mqueue_send() on its message queue.
2977 		 */
2978 		ipc_special_reply_port_msg_sent(port);
2979 
2980 		error = ipc_mqueue_send_locked(&port->ip_messages, kmsg,
2981 		    (mach_msg_option_t)option64, send_timeout);
2982 		/* port unlocked */
2983 	}
2984 
2985 #if IMPORTANCE_INHERITANCE
2986 	if (did_importance) {
2987 		__unused int importance_cleared = 0;
2988 		switch (error) {
2989 		case MACH_SEND_TIMED_OUT:
2990 		case MACH_SEND_NO_BUFFER:
2991 		case MACH_SEND_INTERRUPTED:
2992 		case MACH_SEND_INVALID_DEST:
2993 			/*
2994 			 * We still have the kmsg and its
2995 			 * reference on the port.  But we
2996 			 * have to back out the importance
2997 			 * boost.
2998 			 *
2999 			 * The port could have changed hands,
3000 			 * be inflight to another destination,
3001 			 * etc...  But in those cases our
3002 			 * back-out will find the new owner
3003 			 * (and all the operations that
3004 			 * transferred the right should have
3005 			 * applied their own boost adjustments
3006 			 * to the old owner(s)).
3007 			 */
3008 			importance_cleared = 1;
3009 			ipc_importance_clean(kmsg);
3010 			break;
3011 
3012 		case MACH_MSG_SUCCESS:
3013 		default:
3014 			break;
3015 		}
3016 #if IMPORTANCE_TRACE
3017 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, (IMPORTANCE_CODE(IMP_MSG, IMP_MSG_SEND)) | DBG_FUNC_END,
3018 		    task_pid(current_task()), sender_pid, imp_msgh_id, importance_cleared, 0);
3019 #endif /* IMPORTANCE_TRACE */
3020 	}
3021 #endif /* IMPORTANCE_INHERITANCE */
3022 
3023 	/*
3024 	 * If the port has been destroyed while we wait, treat the message
3025 	 * as a successful delivery (like we do for an inactive port).
3026 	 */
3027 	if (error == MACH_SEND_INVALID_DEST) {
3028 #if MACH_FLIPC
3029 		if (MACH_NODE_VALID(kmsg->ikm_node) && FPORT_VALID(port->ip_messages.imq_fport)) {
3030 			flipc_msg_ack(kmsg->ikm_node, &port->ip_messages, FALSE);
3031 		}
3032 #endif
3033 		ip_release(port); /* JMM - Future: release right, not just ref */
3034 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
3035 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, MACH_SEND_INVALID_DEST);
3036 		return MACH_MSG_SUCCESS;
3037 	}
3038 
3039 	if (error != MACH_MSG_SUCCESS && kernel_reply) {
3040 		/*
3041 		 * Kernel reply messages that fail can't be allowed to
3042 		 * pseudo-receive on error conditions. We need to just treat
3043 		 * the message as a successful delivery.
3044 		 */
3045 #if MACH_FLIPC
3046 		if (MACH_NODE_VALID(kmsg->ikm_node) && FPORT_VALID(port->ip_messages.imq_fport)) {
3047 			flipc_msg_ack(kmsg->ikm_node, &port->ip_messages, FALSE);
3048 		}
3049 #endif
3050 		ip_release(port); /* JMM - Future: release right, not just ref */
3051 		ipc_kmsg_destroy(kmsg, IPC_KMSG_DESTROY_SKIP_REMOTE);
3052 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_INFO) | DBG_FUNC_END, error);
3053 		return MACH_MSG_SUCCESS;
3054 	}
3055 	return error;
3056 }
3057 
3058 /*
3059  *	Routine:	ipc_kmsg_convert_header_to_user
3060  *	Purpose:
3061  *		Convert a kmsg header back to user header.
3062  */
3063 static mach_msg_user_header_t *
ipc_kmsg_convert_header_to_user(ipc_kmsg_t kmsg)3064 ipc_kmsg_convert_header_to_user(
3065 	ipc_kmsg_t              kmsg)
3066 {
3067 	assert(current_task() != kernel_task);
3068 	mach_msg_header_t *hdr = ikm_header(kmsg);
3069 
3070 	/* user_header is kernel header shifted in place */
3071 	mach_msg_user_header_t *user_header =
3072 	    (mach_msg_user_header_t *)((vm_offset_t)(hdr) + USER_HEADER_SIZE_DELTA);
3073 
3074 	mach_msg_bits_t         bits            = hdr->msgh_bits;
3075 	mach_msg_size_t         kmsg_size       = hdr->msgh_size;
3076 	mach_port_name_t        remote_port     = CAST_MACH_PORT_TO_NAME(hdr->msgh_remote_port);
3077 	mach_port_name_t        local_port      = CAST_MACH_PORT_TO_NAME(hdr->msgh_local_port);
3078 	mach_port_name_t        voucher_port    = hdr->msgh_voucher_port;
3079 	mach_msg_id_t           id              = hdr->msgh_id;
3080 
3081 	user_header->msgh_id                    = id;
3082 	user_header->msgh_local_port            = local_port;
3083 	user_header->msgh_remote_port           = remote_port;
3084 	user_header->msgh_voucher_port          = voucher_port;
3085 	user_header->msgh_size                  = kmsg_size - USER_HEADER_SIZE_DELTA;
3086 	user_header->msgh_bits                  = bits;
3087 
3088 	return user_header;
3089 }
3090 
3091 /*
3092  *	Routine:	ipc_kmsg_put_vector_to_user
3093  *	Purpose:
3094  *		Copies a scalar or vector message buffer to a user message.
3095  *		Frees the message buffer.
3096  *	Conditions:
3097  *		Nothing locked. kmsg is freed upon return.
3098  *
3099  *      1. If user has allocated space for aux data, mach_msg_validate_data_vectors
3100  *      guarantees that rcv_aux_addr is non-zero, and max_aux_size must be at least
3101  *      sizeof(mach_msg_aux_header_t). In case the kmsg is a scalar or a vector
3102  *      without auxiliary data, copy out an empty aux header to rcv_aux_addr which
3103  *      serves as EOF.
3104  *
3105  *      2. If kmsg is a vector without aux, copy out the message as if it's scalar
3106  *
3107  *      3. If an aux buffer is provided by user, max_aux_size must be large enough
3108  *      to at least fit the minimum aux header built by msg_receive_error().
3109  *
3110  *      4. If MACH64_RCV_LINEAR_VECTOR is set, use rcv_msg_addr as the combined
3111  *      buffer for message proper and aux data. rcv_aux_addr and max_aux_size
3112  *      must be passed as zeros and are ignored.
3113  *
3114  *  Returns:
3115  *		MACH_MSG_SUCCESS	    Copied data out of message buffer.
3116  *		MACH_RCV_INVALID_DATA	Couldn't copy to user message.
3117  */
3118 static mach_msg_return_t
ipc_kmsg_put_vector_to_user(ipc_kmsg_t kmsg,mach_msg_option64_t option64,mach_vm_address_t rcv_msg_addr,mach_msg_size_t max_msg_size,mach_vm_address_t rcv_aux_addr,mach_msg_size_t max_aux_size,mach_msg_size_t trailer_size,mach_msg_size_t * msg_sizep,mach_msg_size_t * aux_sizep)3119 ipc_kmsg_put_vector_to_user(
3120 	ipc_kmsg_t              kmsg,     /* scalar or vector */
3121 	mach_msg_option64_t     option64,
3122 	mach_vm_address_t       rcv_msg_addr,
3123 	mach_msg_size_t         max_msg_size,
3124 	mach_vm_address_t       rcv_aux_addr,    /* Nullable */
3125 	mach_msg_size_t         max_aux_size,    /* Nullable */
3126 	mach_msg_size_t         trailer_size,
3127 	mach_msg_size_t         *msg_sizep,  /* size of msg copied out */
3128 	mach_msg_size_t         *aux_sizep)  /* size of aux copied out */
3129 {
3130 	mach_msg_size_t cpout_msg_size, cpout_aux_size;
3131 	mach_msg_user_header_t *user_hdr;
3132 	mach_msg_return_t mr = MACH_MSG_SUCCESS;
3133 
3134 	DEBUG_IPC_KMSG_PRINT(kmsg, "ipc_kmsg_put_vector_to_user()");
3135 
3136 	assert(option64 & MACH64_MSG_VECTOR);
3137 	user_hdr = ipc_kmsg_convert_header_to_user(kmsg);
3138 	/* ikm_header->msgh_size is now user msg size */
3139 
3140 	/* msg and aux size might be updated by msg_receive_error() */
3141 	cpout_msg_size = user_hdr->msgh_size + trailer_size;
3142 	cpout_aux_size = ipc_kmsg_aux_data_size(kmsg);
3143 
3144 	/*
3145 	 * For ipc_kmsg_put_scalar_to_user() we try to receive up to
3146 	 * msg buffer size for backward-compatibility. (See below).
3147 	 *
3148 	 * For mach_msg2(), we just error out here.
3149 	 */
3150 	if (option64 & MACH64_RCV_LINEAR_VECTOR) {
3151 		if (cpout_msg_size + cpout_aux_size > max_msg_size) {
3152 			mr = MACH_RCV_INVALID_DATA;
3153 			cpout_msg_size = 0;
3154 			cpout_aux_size = 0;
3155 			goto failed;
3156 		}
3157 		assert(rcv_aux_addr == 0);
3158 		assert(max_aux_size == 0);
3159 
3160 		if (option64 & MACH64_RCV_STACK) {
3161 			rcv_msg_addr += max_msg_size - cpout_msg_size - cpout_aux_size;
3162 		}
3163 		rcv_aux_addr = rcv_msg_addr + cpout_msg_size;
3164 		max_aux_size = cpout_aux_size;
3165 	} else {
3166 		/*
3167 		 * (81193887) some clients stomp their own stack due to mis-sized
3168 		 * combined send/receives where the receive buffer didn't account
3169 		 * for the trailer size.
3170 		 *
3171 		 * At the very least, avoid smashing their stack.
3172 		 */
3173 		if (cpout_msg_size > max_msg_size) {
3174 			cpout_msg_size = max_msg_size;
3175 
3176 			/* just copy out the partial message for compatibility */
3177 			cpout_aux_size = 0;
3178 			goto copyout_msg;
3179 		}
3180 
3181 		if (cpout_aux_size > max_aux_size) {
3182 			/*
3183 			 * mach_msg_validate_data_vectors() guarantees
3184 			 * that max_aux_size is at least what msg_receive_error() builds
3185 			 * during MACH_RCV_TOO_LARGE, if an aux buffer is provided.
3186 			 *
3187 			 * So this can only happen if caller is trying to receive a vector
3188 			 * kmsg with aux, but did not provide aux buffer. And we must be
3189 			 * coming from msg_receive_error().
3190 			 */
3191 			assert(rcv_aux_addr == 0);
3192 
3193 			/* just copy out the minimal message header and trailer */
3194 			cpout_aux_size = 0;
3195 			goto copyout_msg;
3196 		}
3197 	}
3198 
3199 	/*
3200 	 * at this point, we are certain that receiver has enough space for both msg
3201 	 * proper and aux data.
3202 	 */
3203 	assert(max_aux_size >= cpout_aux_size);
3204 	if (option64 & MACH64_RCV_LINEAR_VECTOR) {
3205 		assert(max_msg_size >= cpout_msg_size + cpout_aux_size);
3206 	} else {
3207 		assert(max_msg_size >= cpout_msg_size);
3208 	}
3209 
3210 	/* receive the aux data to user space */
3211 	if (cpout_aux_size) {
3212 		mach_msg_aux_header_t *aux_header;
3213 
3214 		if ((aux_header = ikm_aux_header(kmsg)) != NULL) {
3215 			/* user expecting aux data, and kmsg has it */
3216 			assert(rcv_aux_addr != 0);
3217 			if (copyoutmsg((const char *)aux_header, rcv_aux_addr, cpout_aux_size)) {
3218 				mr = MACH_RCV_INVALID_DATA;
3219 				cpout_aux_size = 0;
3220 				cpout_msg_size = 0;
3221 				goto failed;
3222 			}
3223 			/* success, copy out the msg next */
3224 			goto copyout_msg;
3225 		}
3226 	}
3227 
3228 	/* we only reach here if have not copied out any aux data */
3229 	if (!(option64 & MACH64_RCV_LINEAR_VECTOR) && rcv_aux_addr != 0) {
3230 		/*
3231 		 * If user has a buffer for aux data, at least copy out an empty header
3232 		 * which serves as an EOF. We don't need to do so for linear vector
3233 		 * because it's used in kevent context and we will return cpout_aux_size
3234 		 * as 0 on ext[3] to signify empty aux data.
3235 		 *
3236 		 * See: filt_machportprocess().
3237 		 */
3238 		mach_msg_aux_header_t header = {.msgdh_size = 0};
3239 		cpout_aux_size = sizeof(header);
3240 		assert(max_aux_size >= cpout_aux_size);
3241 		if (copyoutmsg((const char *)&header, rcv_aux_addr, cpout_aux_size)) {
3242 			mr = MACH_RCV_INVALID_DATA;
3243 			cpout_aux_size = 0;
3244 			cpout_msg_size = 0;
3245 			goto failed;
3246 		}
3247 	}
3248 
3249 copyout_msg:
3250 	/* receive the message proper to user space */
3251 	if (ikm_is_linear(kmsg)) {
3252 		if (copyoutmsg((const char *)user_hdr, rcv_msg_addr, cpout_msg_size)) {
3253 			mr = MACH_RCV_INVALID_DATA;
3254 			cpout_msg_size = 0;
3255 			goto failed;
3256 		}
3257 	} else {
3258 		mach_msg_size_t kdata_size = ikm_kdata_size(kmsg, current_map(),
3259 		    USER_HEADER_SIZE_DELTA, true);
3260 		mach_msg_size_t udata_size = ikm_content_size(kmsg, current_map(),
3261 		    USER_HEADER_SIZE_DELTA, true) + trailer_size;
3262 
3263 		mach_msg_size_t kdata_copyout_size = MIN(kdata_size, cpout_msg_size);
3264 		mach_msg_size_t udata_copyout_size = MIN(udata_size, cpout_msg_size - kdata_copyout_size);
3265 
3266 		/* First copy out kdata */
3267 		if (copyoutmsg((const char *)user_hdr, rcv_msg_addr, kdata_copyout_size)) {
3268 			mr = MACH_RCV_INVALID_DATA;
3269 			cpout_msg_size = 0;
3270 			goto failed;
3271 		}
3272 
3273 		/* Then copy out udata */
3274 		if (copyoutmsg((const char *)kmsg->ikm_udata, rcv_msg_addr + kdata_copyout_size,
3275 		    udata_copyout_size)) {
3276 			mr = MACH_RCV_INVALID_DATA;
3277 			cpout_msg_size = 0;
3278 			goto failed;
3279 		}
3280 	}
3281 
3282 	/* at this point, we have copied out the message proper */
3283 	assert(cpout_msg_size > 0);
3284 
3285 failed:
3286 
3287 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_LINK) | DBG_FUNC_NONE,
3288 	    (rcv_msg_addr >= VM_MIN_KERNEL_AND_KEXT_ADDRESS ||
3289 	    rcv_msg_addr + cpout_msg_size >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) ? (uintptr_t)0 : (uintptr_t)rcv_msg_addr,
3290 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
3291 	    1, /* this is on the receive/copyout path */
3292 	    0, 0);
3293 
3294 	ipc_kmsg_free(kmsg);
3295 
3296 	if (msg_sizep) {
3297 		*msg_sizep = cpout_msg_size;
3298 	}
3299 
3300 	if (aux_sizep) {
3301 		*aux_sizep = cpout_aux_size;
3302 	}
3303 
3304 	return mr;
3305 }
3306 
3307 /*
3308  *	Routine:	ipc_kmsg_put_scalar_to_user
3309  *	Purpose:
3310  *		Copies a scalar message buffer to a user message.
3311  *		Frees the message buffer.
3312  *	Conditions:
3313  *		Nothing locked. kmsg is freed upon return.
3314  *
3315  *	Returns:
3316  *		MACH_MSG_SUCCESS	    Copied data out of message buffer.
3317  *		MACH_RCV_INVALID_DATA	Couldn't copy to user message.
3318  */
3319 static mach_msg_return_t
ipc_kmsg_put_scalar_to_user(ipc_kmsg_t kmsg,__unused mach_msg_option64_t option64,mach_vm_address_t rcv_addr,mach_msg_size_t rcv_size,mach_msg_size_t trailer_size,mach_msg_size_t * sizep)3320 ipc_kmsg_put_scalar_to_user(
3321 	ipc_kmsg_t              kmsg,
3322 	__unused mach_msg_option64_t     option64,
3323 	mach_vm_address_t       rcv_addr,
3324 	mach_msg_size_t         rcv_size,
3325 	mach_msg_size_t         trailer_size,
3326 	mach_msg_size_t         *sizep)  /* size of msg copied out */
3327 {
3328 	mach_msg_size_t copyout_size;
3329 	mach_msg_user_header_t *user_hdr;
3330 	mach_msg_return_t mr = MACH_MSG_SUCCESS;
3331 
3332 	DEBUG_IPC_KMSG_PRINT(kmsg, "ipc_kmsg_put_scalar_to_user()");
3333 
3334 	assert(!(option64 & MACH64_MSG_VECTOR));
3335 	/* stack-based receive must be vectorized */
3336 	assert(!(option64 & MACH64_RCV_STACK));
3337 	/*
3338 	 * We will reach here in one of the following cases, kmsg size
3339 	 * may have been updated by msg_receive_error();
3340 	 *
3341 	 *	1. kmsg is scalar: OK to copy out as scalar
3342 	 *  2. kmsg is vector without aux: OK to copy out as scalar
3343 	 *  3. kmsg is vector with aux: silently dropping aux data
3344 	 */
3345 	user_hdr = ipc_kmsg_convert_header_to_user(kmsg);
3346 	/* ikm_header->msgh_size is now user msg size */
3347 
3348 	copyout_size = user_hdr->msgh_size + trailer_size;
3349 
3350 	/*
3351 	 * (81193887) some clients stomp their own stack due to mis-sized
3352 	 * combined send/receives where the receive buffer didn't account
3353 	 * for the trailer size.
3354 	 *
3355 	 * At the very least, avoid smashing their stack.
3356 	 */
3357 	if (copyout_size > rcv_size) {
3358 		copyout_size = rcv_size;
3359 	}
3360 
3361 	if (ikm_is_linear(kmsg)) {
3362 		if (copyoutmsg((const char *)user_hdr, rcv_addr, copyout_size)) {
3363 			mr = MACH_RCV_INVALID_DATA;
3364 			copyout_size = 0;
3365 		}
3366 	} else {
3367 		mach_msg_size_t kdata_size = ikm_kdata_size(kmsg, current_map(),
3368 		    USER_HEADER_SIZE_DELTA, true);
3369 		mach_msg_size_t udata_size = ikm_content_size(kmsg, current_map(),
3370 		    USER_HEADER_SIZE_DELTA, true) + trailer_size;
3371 
3372 		mach_msg_size_t kdata_copyout_size = MIN(kdata_size, copyout_size);
3373 		mach_msg_size_t udata_copyout_size = MIN(udata_size, copyout_size - kdata_copyout_size);
3374 
3375 		/* First copy out kdata */
3376 		if (copyoutmsg((const char *)user_hdr, rcv_addr, kdata_copyout_size)) {
3377 			mr = MACH_RCV_INVALID_DATA;
3378 			copyout_size = 0;
3379 		}
3380 
3381 		/* Then copy out udata */
3382 		if (copyoutmsg((const char *)kmsg->ikm_udata, rcv_addr + kdata_copyout_size,
3383 		    udata_copyout_size)) {
3384 			mr = MACH_RCV_INVALID_DATA;
3385 			copyout_size = 0;
3386 		}
3387 	}
3388 
3389 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_KMSG_LINK) | DBG_FUNC_NONE,
3390 	    (rcv_addr >= VM_MIN_KERNEL_AND_KEXT_ADDRESS ||
3391 	    rcv_addr + copyout_size >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) ? (uintptr_t)0 : (uintptr_t)rcv_addr,
3392 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
3393 	    1, /* this is on the receive/copyout path */
3394 	    0, 0);
3395 
3396 	ipc_kmsg_free(kmsg);
3397 
3398 	if (sizep) {
3399 		*sizep = copyout_size;
3400 	}
3401 	return mr;
3402 }
3403 
3404 /*
3405  *	Routine:	ipc_kmsg_put_to_user
3406  *	Purpose:
3407  *		Copies a scalar or vector message buffer to a user message.
3408  *		Frees the message buffer.
3409  *      See comments above ipc_kmsg_put_{scalar, vector}_to_user().
3410  *	Conditions:
3411  *		Nothing locked. kmsg is freed upon return.
3412  *
3413  *	Returns:
3414  *		MACH_MSG_SUCCESS	    Copied data out of message buffer.
3415  *		MACH_RCV_INVALID_DATA	Couldn't copy to user message.
3416  */
3417 mach_msg_return_t
ipc_kmsg_put_to_user(ipc_kmsg_t kmsg,mach_msg_option64_t option64,mach_vm_address_t rcv_msg_addr,mach_msg_size_t max_msg_size,mach_vm_address_t rcv_aux_addr,mach_msg_size_t max_aux_size,mach_msg_size_t trailer_size,mach_msg_size_t * msg_sizep,mach_msg_size_t * aux_sizep)3418 ipc_kmsg_put_to_user(
3419 	ipc_kmsg_t              kmsg,     /* scalar or vector */
3420 	mach_msg_option64_t     option64,
3421 	mach_vm_address_t       rcv_msg_addr,
3422 	mach_msg_size_t         max_msg_size,
3423 	mach_vm_address_t       rcv_aux_addr,    /* Nullable */
3424 	mach_msg_size_t         max_aux_size,    /* Nullable */
3425 	mach_msg_size_t         trailer_size,
3426 	mach_msg_size_t         *msg_sizep,  /* size of msg copied out */
3427 	mach_msg_size_t         *aux_sizep)  /* size of aux copied out */
3428 {
3429 	mach_msg_return_t mr;
3430 
3431 	if (option64 & MACH64_MSG_VECTOR) {
3432 		mr = ipc_kmsg_put_vector_to_user(kmsg, option64, rcv_msg_addr,
3433 		    max_msg_size, rcv_aux_addr, max_aux_size, trailer_size,
3434 		    msg_sizep, aux_sizep);
3435 	} else {
3436 		mr = ipc_kmsg_put_scalar_to_user(kmsg, option64, rcv_msg_addr,
3437 		    max_msg_size, trailer_size, msg_sizep);
3438 		if (mr == MACH_MSG_SUCCESS && aux_sizep != NULL) {
3439 			*aux_sizep = 0;
3440 		}
3441 	}
3442 
3443 	/*
3444 	 * During message copyout, MACH_RCV_INVALID_DATA takes precedence
3445 	 * over all other errors. Other error code will be treated as
3446 	 * MACH_MSG_SUCCESS by mach_msg_receive_results().
3447 	 *
3448 	 * See: msg_receive_error().
3449 	 */
3450 	assert(mr == MACH_RCV_INVALID_DATA || mr == MACH_MSG_SUCCESS);
3451 	return mr;
3452 }
3453 
3454 /*
3455  *	Routine:	ipc_kmsg_put_to_kernel
3456  *	Purpose:
3457  *		Copies a message buffer to a kernel message.
3458  *		Frees the message buffer.
3459  *		No errors allowed.
3460  *	Conditions:
3461  *		Nothing locked.
3462  */
3463 
3464 void
ipc_kmsg_put_to_kernel(mach_msg_header_t * msg,ipc_kmsg_t kmsg,mach_msg_size_t rcv_size)3465 ipc_kmsg_put_to_kernel(
3466 	mach_msg_header_t       *msg,
3467 	ipc_kmsg_t              kmsg,
3468 	mach_msg_size_t         rcv_size) /* includes trailer size */
3469 {
3470 	mach_msg_header_t *hdr = ikm_header(kmsg);
3471 
3472 	assert(kmsg->ikm_aux_size == 0);
3473 	assert(rcv_size >= hdr->msgh_size);
3474 
3475 	if (ikm_is_linear(kmsg)) {
3476 		(void)memcpy((void *)msg, (const void *)hdr, rcv_size);
3477 	} else {
3478 		mach_msg_size_t kdata_size = ikm_kdata_size(kmsg, current_map(), 0, false);
3479 
3480 		/* First memcpy kdata */
3481 		assert(rcv_size >= kdata_size);
3482 		(void)memcpy((void *)msg, (const void *)hdr, kdata_size);
3483 
3484 		/* Fill the remaining space with udata */
3485 		(void)memcpy((void *)((vm_offset_t)msg + kdata_size),
3486 		    (const void *)kmsg->ikm_udata, rcv_size - kdata_size);
3487 	}
3488 
3489 	ipc_kmsg_free(kmsg);
3490 }
3491 
3492 static pthread_priority_compact_t
ipc_get_current_thread_priority(void)3493 ipc_get_current_thread_priority(void)
3494 {
3495 	thread_t thread = current_thread();
3496 	thread_qos_t qos;
3497 	int relpri;
3498 
3499 	qos = thread_get_requested_qos(thread, &relpri);
3500 	if (!qos) {
3501 		qos = thread_user_promotion_qos_for_pri(thread->base_pri);
3502 		relpri = 0;
3503 	}
3504 	return _pthread_priority_make_from_thread_qos(qos, relpri, 0);
3505 }
3506 
3507 static kern_return_t
ipc_kmsg_set_qos(ipc_kmsg_t kmsg,mach_msg_option_t options,mach_msg_priority_t priority)3508 ipc_kmsg_set_qos(
3509 	ipc_kmsg_t kmsg,
3510 	mach_msg_option_t options,
3511 	mach_msg_priority_t priority)
3512 {
3513 	kern_return_t kr;
3514 	mach_msg_header_t *hdr = ikm_header(kmsg);
3515 	ipc_port_t special_reply_port = hdr->msgh_local_port;
3516 	ipc_port_t dest_port = hdr->msgh_remote_port;
3517 
3518 	if ((options & MACH_SEND_OVERRIDE) &&
3519 	    !mach_msg_priority_is_pthread_priority(priority)) {
3520 		mach_msg_qos_t qos = mach_msg_priority_qos(priority);
3521 		int relpri = mach_msg_priority_relpri(priority);
3522 		mach_msg_qos_t ovr = mach_msg_priority_overide_qos(priority);
3523 
3524 		kmsg->ikm_ppriority = _pthread_priority_make_from_thread_qos(qos, relpri, 0);
3525 		kmsg->ikm_qos_override = MAX(qos, ovr);
3526 	} else {
3527 #if CONFIG_VOUCHER_DEPRECATED
3528 		kr = ipc_get_pthpriority_from_kmsg_voucher(kmsg, &kmsg->ikm_ppriority);
3529 #else
3530 		kr = KERN_FAILURE;
3531 #endif /* CONFIG_VOUCHER_DEPRECATED */
3532 		if (kr != KERN_SUCCESS) {
3533 			if (options & MACH_SEND_PROPAGATE_QOS) {
3534 				kmsg->ikm_ppriority = ipc_get_current_thread_priority();
3535 			} else {
3536 				kmsg->ikm_ppriority = MACH_MSG_PRIORITY_UNSPECIFIED;
3537 			}
3538 		}
3539 
3540 		if (options & MACH_SEND_OVERRIDE) {
3541 			mach_msg_qos_t qos = _pthread_priority_thread_qos(kmsg->ikm_ppriority);
3542 			mach_msg_qos_t ovr = _pthread_priority_thread_qos(priority);
3543 			kmsg->ikm_qos_override = MAX(qos, ovr);
3544 		} else {
3545 			kmsg->ikm_qos_override = _pthread_priority_thread_qos(kmsg->ikm_ppriority);
3546 		}
3547 	}
3548 
3549 	kr = KERN_SUCCESS;
3550 
3551 	if (IP_VALID(special_reply_port) &&
3552 	    special_reply_port->ip_specialreply &&
3553 	    !ip_is_kobject(dest_port) &&
3554 	    MACH_MSGH_BITS_LOCAL(hdr->msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE) {
3555 		boolean_t sync_bootstrap_checkin = !!(options & MACH_SEND_SYNC_BOOTSTRAP_CHECKIN);
3556 		/*
3557 		 * Link the destination port to special reply port and make sure that
3558 		 * dest port has a send turnstile, else allocate one.
3559 		 */
3560 		ipc_port_link_special_reply_port(special_reply_port, dest_port, sync_bootstrap_checkin);
3561 	}
3562 	return kr;
3563 }
3564 
3565 static kern_return_t
ipc_kmsg_set_qos_kernel(ipc_kmsg_t kmsg)3566 ipc_kmsg_set_qos_kernel(
3567 	ipc_kmsg_t kmsg)
3568 {
3569 	ipc_port_t dest_port = ikm_header(kmsg)->msgh_remote_port;
3570 	kmsg->ikm_qos_override = dest_port->ip_kernel_qos_override;
3571 	kmsg->ikm_ppriority = _pthread_priority_make_from_thread_qos(kmsg->ikm_qos_override, 0, 0);
3572 	return KERN_SUCCESS;
3573 }
3574 
3575 /*
3576  *	Routine:	ipc_kmsg_link_reply_context_locked
3577  *	Purpose:
3578  *		Link any required context from the sending voucher
3579  *		to the reply port. The ipc_kmsg_copyin_from_user function will
3580  *		enforce that the sender calls mach_msg in this context.
3581  *	Conditions:
3582  *		reply port is locked
3583  */
3584 static void
ipc_kmsg_link_reply_context_locked(ipc_port_t reply_port,ipc_port_t voucher_port)3585 ipc_kmsg_link_reply_context_locked(
3586 	ipc_port_t reply_port,
3587 	ipc_port_t voucher_port)
3588 {
3589 	kern_return_t __assert_only kr;
3590 	uint32_t persona_id = 0;
3591 	ipc_voucher_t voucher;
3592 
3593 	ip_mq_lock_held(reply_port);
3594 
3595 	if (!ip_active(reply_port)) {
3596 		return;
3597 	}
3598 
3599 	voucher = convert_port_to_voucher(voucher_port);
3600 
3601 	kr = bank_get_bank_ledger_thread_group_and_persona(voucher, NULL, NULL, &persona_id);
3602 	assert(kr == KERN_SUCCESS);
3603 	ipc_voucher_release(voucher);
3604 
3605 	if (persona_id == 0 || persona_id == PERSONA_ID_NONE) {
3606 		/* there was no persona context to record */
3607 		return;
3608 	}
3609 
3610 	/*
3611 	 * Set the persona_id as the context on the reply port.
3612 	 * This will force the thread that replies to have adopted a voucher
3613 	 * with a matching persona.
3614 	 */
3615 	reply_port->ip_reply_context = persona_id;
3616 
3617 	return;
3618 }
3619 
3620 static kern_return_t
ipc_kmsg_validate_reply_port_locked(ipc_port_t reply_port,mach_msg_option_t options)3621 ipc_kmsg_validate_reply_port_locked(ipc_port_t reply_port, mach_msg_option_t options)
3622 {
3623 	ip_mq_lock_held(reply_port);
3624 
3625 	if (!ip_active(reply_port)) {
3626 		/*
3627 		 * Ideally, we would enforce that the reply receive right is
3628 		 * active, but asynchronous XPC cancellation destroys the
3629 		 * receive right, so we just have to return success here.
3630 		 */
3631 		return KERN_SUCCESS;
3632 	}
3633 
3634 	if (options & MACH_SEND_MSG) {
3635 		/*
3636 		 * If the rely port is active, then it should not be
3637 		 * in-transit, and the receive right should be in the caller's
3638 		 * IPC space.
3639 		 */
3640 		if (!ip_in_space(reply_port, current_task()->itk_space)) {
3641 			return KERN_INVALID_CAPABILITY;
3642 		}
3643 
3644 		/*
3645 		 * A port used as a reply port in an RPC should have exactly 1
3646 		 * extant send-once right which we either just made or are
3647 		 * moving as part of the IPC.
3648 		 */
3649 		if (reply_port->ip_sorights != 1) {
3650 			return KERN_INVALID_CAPABILITY;
3651 		}
3652 		/*
3653 		 * XPC uses an extra send-right to keep the name of the reply
3654 		 * right around through cancellation.  That makes it harder to
3655 		 * enforce a particular semantic kere, so for now, we say that
3656 		 * you can have a maximum of 1 send right (in addition to your
3657 		 * send once right). In the future, it would be great to lock
3658 		 * this down even further.
3659 		 */
3660 		if (reply_port->ip_srights > 1) {
3661 			return KERN_INVALID_CAPABILITY;
3662 		}
3663 
3664 		/*
3665 		 * The sender can also specify that the receive right should
3666 		 * be immovable. Note that this check only applies to
3667 		 * send-only operations. Combined send/receive or rcv-only
3668 		 * operations can specify an immovable receive right by
3669 		 * opt-ing into guarded descriptors (MACH_RCV_GUARDED_DESC)
3670 		 * and using the MACH_MSG_STRICT_REPLY options flag.
3671 		 */
3672 		if (MACH_SEND_REPLY_IS_IMMOVABLE(options)) {
3673 			if (!reply_port->ip_immovable_receive) {
3674 				return KERN_INVALID_CAPABILITY;
3675 			}
3676 		}
3677 	}
3678 
3679 	/*
3680 	 * don't enforce this yet: need a better way of indicating the
3681 	 * receiver wants this...
3682 	 */
3683 #if 0
3684 	if (MACH_RCV_WITH_IMMOVABLE_REPLY(options)) {
3685 		if (!reply_port->ip_immovable_receive) {
3686 			return KERN_INVALID_CAPABILITY;
3687 		}
3688 	}
3689 #endif /* 0  */
3690 
3691 	return KERN_SUCCESS;
3692 }
3693 
3694 /*
3695  *	Routine:	ipc_kmsg_validate_reply_context_locked
3696  *	Purpose:
3697  *		Validate that the current thread is running in the context
3698  *		required by the destination port.
3699  *	Conditions:
3700  *		dest_port is locked
3701  *	Returns:
3702  *		MACH_MSG_SUCCESS on success.
3703  *		On error, an EXC_GUARD exception is also raised.
3704  *		This function *always* resets the port reply context.
3705  */
3706 static mach_msg_return_t
ipc_kmsg_validate_reply_context_locked(mach_msg_option_t option,ipc_port_t dest_port,ipc_voucher_t voucher,mach_port_name_t voucher_name)3707 ipc_kmsg_validate_reply_context_locked(
3708 	mach_msg_option_t option,
3709 	ipc_port_t dest_port,
3710 	ipc_voucher_t voucher,
3711 	mach_port_name_t voucher_name)
3712 {
3713 	uint32_t dest_ctx = dest_port->ip_reply_context;
3714 	dest_port->ip_reply_context = 0;
3715 
3716 	if (!ip_active(dest_port)) {
3717 		return MACH_MSG_SUCCESS;
3718 	}
3719 
3720 	if (voucher == IPC_VOUCHER_NULL || !MACH_PORT_VALID(voucher_name)) {
3721 		if ((option & MACH_SEND_KERNEL) == 0) {
3722 			mach_port_guard_exception(voucher_name, 0,
3723 			    (MPG_FLAGS_STRICT_REPLY_INVALID_VOUCHER | dest_ctx),
3724 			    kGUARD_EXC_STRICT_REPLY);
3725 		}
3726 		return MACH_SEND_INVALID_CONTEXT;
3727 	}
3728 
3729 	kern_return_t __assert_only kr;
3730 	uint32_t persona_id = 0;
3731 	kr = bank_get_bank_ledger_thread_group_and_persona(voucher, NULL, NULL, &persona_id);
3732 	assert(kr == KERN_SUCCESS);
3733 
3734 	if (dest_ctx != persona_id) {
3735 		if ((option & MACH_SEND_KERNEL) == 0) {
3736 			mach_port_guard_exception(voucher_name, 0,
3737 			    (MPG_FLAGS_STRICT_REPLY_MISMATCHED_PERSONA | ((((uint64_t)persona_id << 32) & MPG_FLAGS_STRICT_REPLY_MASK) | dest_ctx)),
3738 			    kGUARD_EXC_STRICT_REPLY);
3739 		}
3740 		return MACH_SEND_INVALID_CONTEXT;
3741 	}
3742 
3743 	return MACH_MSG_SUCCESS;
3744 }
3745 
3746 /*
3747  *	Routine:	ipc_kmsg_copyin_header
3748  *	Purpose:
3749  *		"Copy-in" port rights in the header of a message.
3750  *		Operates atomically; if it doesn't succeed the
3751  *		message header and the space are left untouched.
3752  *		If it does succeed the remote/local port fields
3753  *		contain object pointers instead of port names,
3754  *		and the bits field is updated.  The destination port
3755  *		will be a valid port pointer.
3756  *
3757  *	Conditions:
3758  *		Nothing locked. May add MACH64_SEND_ALWAYS option.
3759  *	Returns:
3760  *		MACH_MSG_SUCCESS	Successful copyin.
3761  *		MACH_SEND_INVALID_HEADER
3762  *			Illegal value in the message header bits.
3763  *		MACH_SEND_INVALID_DEST	The space is dead.
3764  *		MACH_SEND_INVALID_DEST	Can't copyin destination port.
3765  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
3766  *		MACH_SEND_INVALID_REPLY	Can't copyin reply port.
3767  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
3768  */
3769 
3770 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)3771 ipc_kmsg_copyin_header(
3772 	ipc_kmsg_t              kmsg,
3773 	ipc_space_t             space,
3774 	mach_msg_priority_t     priority,
3775 	mach_msg_option64_t     *option64p)
3776 {
3777 	mach_msg_header_t *msg = ikm_header(kmsg);
3778 	mach_msg_bits_t mbits = msg->msgh_bits & MACH_MSGH_BITS_USER;
3779 	mach_port_name_t dest_name = CAST_MACH_PORT_TO_NAME(msg->msgh_remote_port);
3780 	mach_port_name_t reply_name = CAST_MACH_PORT_TO_NAME(msg->msgh_local_port);
3781 	mach_port_name_t voucher_name = MACH_PORT_NULL;
3782 	kern_return_t kr;
3783 
3784 	mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
3785 	mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
3786 	mach_msg_type_name_t voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
3787 	ipc_object_t dest_port = IO_NULL;
3788 	ipc_object_t reply_port = IO_NULL;
3789 	ipc_port_t dest_soright = IP_NULL;
3790 	ipc_port_t dport = IP_NULL;
3791 	ipc_port_t reply_soright = IP_NULL;
3792 	ipc_port_t voucher_soright = IP_NULL;
3793 	ipc_port_t release_port = IP_NULL;
3794 	ipc_port_t voucher_port = IP_NULL;
3795 	ipc_port_t voucher_release_port = IP_NULL;
3796 	ipc_entry_t dest_entry = IE_NULL;
3797 	ipc_entry_t reply_entry = IE_NULL;
3798 	ipc_entry_t voucher_entry = IE_NULL;
3799 	ipc_object_copyin_flags_t dest_flags = IPC_OBJECT_COPYIN_FLAGS_ALLOW_REPLY_MAKE_SEND_ONCE | IPC_OBJECT_COPYIN_FLAGS_ALLOW_REPLY_MOVE_SEND_ONCE;
3800 	ipc_object_copyin_flags_t reply_flags = IPC_OBJECT_COPYIN_FLAGS_ALLOW_REPLY_MAKE_SEND_ONCE;
3801 	boolean_t reply_port_semantics_violation = FALSE;
3802 
3803 	int assertcnt = 0;
3804 	mach_msg_option_t option32 = (mach_msg_option_t)*option64p;
3805 #if IMPORTANCE_INHERITANCE
3806 	boolean_t needboost = FALSE;
3807 #endif /* IMPORTANCE_INHERITANCE */
3808 
3809 	if ((mbits != msg->msgh_bits) ||
3810 	    (!MACH_MSG_TYPE_PORT_ANY_SEND(dest_type)) ||
3811 	    ((reply_type == 0) ?
3812 	    (reply_name != MACH_PORT_NULL) :
3813 	    !MACH_MSG_TYPE_PORT_ANY_SEND(reply_type))) {
3814 		return MACH_SEND_INVALID_HEADER;
3815 	}
3816 
3817 	if (!MACH_PORT_VALID(dest_name)) {
3818 		return MACH_SEND_INVALID_DEST;
3819 	}
3820 
3821 	is_write_lock(space);
3822 	if (!is_active(space)) {
3823 		is_write_unlock(space);
3824 		return MACH_SEND_INVALID_DEST;
3825 	}
3826 	/* space locked and active */
3827 
3828 	/*
3829 	 *	If there is a voucher specified, make sure the disposition is
3830 	 *	valid and the entry actually refers to a voucher port.  Don't
3831 	 *	actually copy in until we validate destination and reply.
3832 	 */
3833 	if (voucher_type != MACH_MSGH_BITS_ZERO) {
3834 		voucher_name = msg->msgh_voucher_port;
3835 
3836 		if (voucher_name == MACH_PORT_DEAD ||
3837 		    (voucher_type != MACH_MSG_TYPE_MOVE_SEND &&
3838 		    voucher_type != MACH_MSG_TYPE_COPY_SEND)) {
3839 			is_write_unlock(space);
3840 			if ((option32 & MACH_SEND_KERNEL) == 0) {
3841 				mach_port_guard_exception(voucher_name, 0, 0, kGUARD_EXC_SEND_INVALID_VOUCHER);
3842 			}
3843 			return MACH_SEND_INVALID_VOUCHER;
3844 		}
3845 
3846 		if (voucher_name != MACH_PORT_NULL) {
3847 			voucher_entry = ipc_entry_lookup(space, voucher_name);
3848 			if (voucher_entry == IE_NULL ||
3849 			    (voucher_entry->ie_bits & MACH_PORT_TYPE_SEND) == 0 ||
3850 			    io_kotype(voucher_entry->ie_object) != IKOT_VOUCHER) {
3851 				is_write_unlock(space);
3852 				if ((option32 & MACH_SEND_KERNEL) == 0) {
3853 					mach_port_guard_exception(voucher_name, 0, 0, kGUARD_EXC_SEND_INVALID_VOUCHER);
3854 				}
3855 				return MACH_SEND_INVALID_VOUCHER;
3856 			}
3857 		} else {
3858 			voucher_type = MACH_MSG_TYPE_MOVE_SEND;
3859 		}
3860 	}
3861 
3862 	if (enforce_strict_reply && MACH_SEND_WITH_STRICT_REPLY(option32) &&
3863 	    (!MACH_PORT_VALID(reply_name) ||
3864 	    ((reply_type != MACH_MSG_TYPE_MAKE_SEND_ONCE) && (reply_type != MACH_MSG_TYPE_MOVE_SEND_ONCE))
3865 	    )) {
3866 		/*
3867 		 * The caller cannot enforce a reply context with an invalid
3868 		 * reply port name, or a non-send_once reply disposition.
3869 		 */
3870 		is_write_unlock(space);
3871 		if ((option32 & MACH_SEND_KERNEL) == 0) {
3872 			mach_port_guard_exception(reply_name, 0,
3873 			    (MPG_FLAGS_STRICT_REPLY_INVALID_REPLY_DISP | reply_type),
3874 			    kGUARD_EXC_STRICT_REPLY);
3875 		}
3876 		return MACH_SEND_INVALID_REPLY;
3877 	}
3878 
3879 	/*
3880 	 *	Handle combinations of validating destination and reply; along
3881 	 *	with copying in destination, reply, and voucher in an atomic way.
3882 	 */
3883 
3884 	if (dest_name == voucher_name) {
3885 		/*
3886 		 *	If the destination name is the same as the voucher name,
3887 		 *	the voucher_entry must already be known.  Either that or
3888 		 *	the destination name is MACH_PORT_NULL (i.e. invalid).
3889 		 */
3890 		dest_entry = voucher_entry;
3891 		if (dest_entry == IE_NULL) {
3892 			goto invalid_dest;
3893 		}
3894 
3895 		/*
3896 		 *	Make sure a future copyin of the reply port will succeed.
3897 		 *	Once we start copying in the dest/voucher pair, we can't
3898 		 *	back out.
3899 		 */
3900 		if (MACH_PORT_VALID(reply_name)) {
3901 			assert(reply_type != 0); /* because reply_name not null */
3902 
3903 			/* It is just WRONG if dest, voucher, and reply are all the same. */
3904 			if (voucher_name == reply_name) {
3905 				goto invalid_reply;
3906 			}
3907 			reply_entry = ipc_entry_lookup(space, reply_name);
3908 			if (reply_entry == IE_NULL) {
3909 				goto invalid_reply;
3910 			}
3911 			assert(dest_entry != reply_entry); /* names are not equal */
3912 			if (!ipc_right_copyin_check_reply(space, reply_name, reply_entry, reply_type, dest_entry, &reply_port_semantics_violation)) {
3913 				goto invalid_reply;
3914 			}
3915 		}
3916 
3917 		/*
3918 		 *	Do the joint copyin of the dest disposition and
3919 		 *	voucher disposition from the one entry/port.  We
3920 		 *	already validated that the voucher copyin would
3921 		 *	succeed (above).  So, any failure in combining
3922 		 *	the copyins can be blamed on the destination.
3923 		 */
3924 		kr = ipc_right_copyin_two(space, dest_name, dest_entry,
3925 		    dest_type, voucher_type, IPC_OBJECT_COPYIN_FLAGS_NONE, IPC_OBJECT_COPYIN_FLAGS_NONE,
3926 		    &dest_port, &dest_soright, &release_port);
3927 		if (kr != KERN_SUCCESS) {
3928 			assert(kr != KERN_INVALID_CAPABILITY);
3929 			goto invalid_dest;
3930 		}
3931 		voucher_port = ip_object_to_port(dest_port);
3932 
3933 		/*
3934 		 * could not have been one of these dispositions,
3935 		 * validated the port was a true kernel voucher port above,
3936 		 * AND was successfully able to copyin both dest and voucher.
3937 		 */
3938 		assert(dest_type != MACH_MSG_TYPE_MAKE_SEND);
3939 		assert(dest_type != MACH_MSG_TYPE_MAKE_SEND_ONCE);
3940 		assert(dest_type != MACH_MSG_TYPE_MOVE_SEND_ONCE);
3941 
3942 		/*
3943 		 *	Perform the delayed reply right copyin (guaranteed success).
3944 		 */
3945 		if (reply_entry != IE_NULL) {
3946 			kr = ipc_right_copyin(space, reply_name, reply_entry,
3947 			    reply_type, IPC_OBJECT_COPYIN_FLAGS_DEADOK | reply_flags,
3948 			    &reply_port, &reply_soright,
3949 			    &release_port, &assertcnt, 0, NULL);
3950 			assert(assertcnt == 0);
3951 			assert(kr == KERN_SUCCESS);
3952 		}
3953 	} else {
3954 		if (dest_name == reply_name) {
3955 			/*
3956 			 *	Destination and reply ports are the same!
3957 			 *	This is very similar to the case where the
3958 			 *	destination and voucher ports were the same
3959 			 *	(except the reply port disposition is not
3960 			 *	previously validated).
3961 			 */
3962 			dest_entry = ipc_entry_lookup(space, dest_name);
3963 			if (dest_entry == IE_NULL) {
3964 				goto invalid_dest;
3965 			}
3966 
3967 			reply_entry = dest_entry;
3968 			assert(reply_type != 0); /* because name not null */
3969 
3970 			/*
3971 			 *	Pre-validate that the reply right can be copied in by itself.
3972 			 *  Fail if reply port is marked as immovable send.
3973 			 */
3974 			if (!ipc_right_copyin_check_reply(space, reply_name, reply_entry, reply_type, dest_entry, &reply_port_semantics_violation)) {
3975 				goto invalid_reply;
3976 			}
3977 
3978 			/*
3979 			 *	Do the joint copyin of the dest disposition and
3980 			 *	reply disposition from the one entry/port.
3981 			 */
3982 			kr = ipc_right_copyin_two(space, dest_name, dest_entry, dest_type, reply_type,
3983 			    dest_flags, reply_flags, &dest_port, &dest_soright, &release_port);
3984 			if (kr == KERN_INVALID_CAPABILITY) {
3985 				goto invalid_reply;
3986 			} else if (kr != KERN_SUCCESS) {
3987 				goto invalid_dest;
3988 			}
3989 			reply_port = dest_port;
3990 		} else {
3991 			/*
3992 			 *	Handle destination and reply independently, as
3993 			 *	they are independent entries (even if the entries
3994 			 *	refer to the same port).
3995 			 *
3996 			 *	This can be the tough case to make atomic.
3997 			 *
3998 			 *	The difficult problem is serializing with port death.
3999 			 *	The bad case is when dest_port dies after its copyin,
4000 			 *	reply_port dies before its copyin, and dest_port dies before
4001 			 *	reply_port.  Then the copyins operated as if dest_port was
4002 			 *	alive and reply_port was dead, which shouldn't have happened
4003 			 *	because they died in the other order.
4004 			 *
4005 			 *	Note that it is easy for a user task to tell if
4006 			 *	a copyin happened before or after a port died.
4007 			 *	If a port dies before copyin, a dead-name notification
4008 			 *	is generated and the dead name's urefs are incremented,
4009 			 *	and if the copyin happens first, a port-deleted
4010 			 *	notification is generated.
4011 			 *
4012 			 *	Even so, avoiding that potentially detectable race is too
4013 			 *	expensive - and no known code cares about it.  So, we just
4014 			 *	do the expedient thing and copy them in one after the other.
4015 			 */
4016 
4017 			dest_entry = ipc_entry_lookup(space, dest_name);
4018 			if (dest_entry == IE_NULL) {
4019 				goto invalid_dest;
4020 			}
4021 			assert(dest_entry != voucher_entry);
4022 
4023 			/*
4024 			 *	Make sure reply port entry is valid before dest copyin.
4025 			 */
4026 			if (MACH_PORT_VALID(reply_name)) {
4027 				if (reply_name == voucher_name) {
4028 					goto invalid_reply;
4029 				}
4030 				reply_entry = ipc_entry_lookup(space, reply_name);
4031 				if (reply_entry == IE_NULL) {
4032 					goto invalid_reply;
4033 				}
4034 				assert(dest_entry != reply_entry); /* names are not equal */
4035 				assert(reply_type != 0); /* because reply_name not null */
4036 
4037 				if (!ipc_right_copyin_check_reply(space, reply_name, reply_entry, reply_type, dest_entry, &reply_port_semantics_violation)) {
4038 					goto invalid_reply;
4039 				}
4040 			}
4041 
4042 			/*
4043 			 *	copyin the destination.
4044 			 */
4045 			kr = ipc_right_copyin(space, dest_name, dest_entry, dest_type,
4046 			    (IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND | IPC_OBJECT_COPYIN_FLAGS_ALLOW_DEAD_SEND_ONCE | dest_flags),
4047 			    &dest_port, &dest_soright,
4048 			    &release_port, &assertcnt, 0, NULL);
4049 			assert(assertcnt == 0);
4050 			if (kr != KERN_SUCCESS) {
4051 				goto invalid_dest;
4052 			}
4053 			assert(IO_VALID(dest_port));
4054 			assert(!IP_VALID(release_port));
4055 
4056 			/*
4057 			 *	Copyin the pre-validated reply right.
4058 			 *	It's OK if the reply right has gone dead in the meantime.
4059 			 */
4060 			if (MACH_PORT_VALID(reply_name)) {
4061 				kr = ipc_right_copyin(space, reply_name, reply_entry,
4062 				    reply_type, IPC_OBJECT_COPYIN_FLAGS_DEADOK | reply_flags,
4063 				    &reply_port, &reply_soright,
4064 				    &release_port, &assertcnt, 0, NULL);
4065 				assert(assertcnt == 0);
4066 				assert(kr == KERN_SUCCESS);
4067 			} else {
4068 				/* convert invalid name to equivalent ipc_object type */
4069 				reply_port = ip_to_object(CAST_MACH_NAME_TO_PORT(reply_name));
4070 			}
4071 		}
4072 
4073 		/*
4074 		 * Finally can copyin the voucher right now that dest and reply
4075 		 * are fully copied in (guaranteed success).
4076 		 */
4077 		if (IE_NULL != voucher_entry) {
4078 			kr = ipc_right_copyin(space, voucher_name, voucher_entry,
4079 			    voucher_type, IPC_OBJECT_COPYIN_FLAGS_NONE,
4080 			    (ipc_object_t *)&voucher_port,
4081 			    &voucher_soright,
4082 			    &voucher_release_port,
4083 			    &assertcnt, 0, NULL);
4084 			assert(assertcnt == 0);
4085 			assert(KERN_SUCCESS == kr);
4086 			assert(IP_VALID(voucher_port));
4087 			require_ip_active(voucher_port);
4088 		}
4089 	}
4090 
4091 	dest_type = ipc_object_copyin_type(dest_type);
4092 	reply_type = ipc_object_copyin_type(reply_type);
4093 
4094 	dport = ip_object_to_port(dest_port);
4095 	/*
4096 	 *	If the dest port died, or is a kobject AND its receive right belongs to kernel,
4097 	 *  allow copyin of immovable send rights in the message body (port descriptor) to
4098 	 *  succeed since those send rights are simply "moved" or "copied" into kernel.
4099 	 *
4100 	 *  See: ipc_object_copyin().
4101 	 */
4102 
4103 	ip_mq_lock(dport);
4104 
4105 	if (!ip_active(dport) || (ip_is_kobject(dport) &&
4106 	    ip_in_space(dport, ipc_space_kernel))) {
4107 		assert(ip_kotype(dport) != IKOT_TIMER);
4108 		kmsg->ikm_flags |= IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND;
4109 	}
4110 
4111 	/*
4112 	 * JMM - Without rdar://problem/6275821, this is the last place we can
4113 	 * re-arm the send-possible notifications.  It may trigger unexpectedly
4114 	 * early (send may NOT have failed), but better than missing.  We assure
4115 	 * we won't miss by forcing MACH_SEND_ALWAYS if we got past arming.
4116 	 */
4117 	if (((option32 & MACH_SEND_NOTIFY) != 0) &&
4118 	    dest_type != MACH_MSG_TYPE_PORT_SEND_ONCE &&
4119 	    dest_entry != IE_NULL && dest_entry->ie_request != IE_REQ_NONE) {
4120 		/* dport still locked from above */
4121 		if (ip_active(dport) && !ip_in_space(dport, ipc_space_kernel)) {
4122 			/* dport could be in-transit, or in an ipc space */
4123 			if (ip_full(dport)) {
4124 #if IMPORTANCE_INHERITANCE
4125 				needboost = ipc_port_request_sparm(dport, dest_name,
4126 				    dest_entry->ie_request,
4127 				    option32,
4128 				    priority);
4129 				if (needboost == FALSE) {
4130 					ip_mq_unlock(dport);
4131 				}
4132 #else
4133 				ipc_port_request_sparm(dport, dest_name,
4134 				    dest_entry->ie_request,
4135 				    option32,
4136 				    priority);
4137 				ip_mq_unlock(dport);
4138 #endif /* IMPORTANCE_INHERITANCE */
4139 			} else {
4140 				*option64p |= MACH64_SEND_ALWAYS;
4141 				ip_mq_unlock(dport);
4142 			}
4143 		} else {
4144 			ip_mq_unlock(dport);
4145 		}
4146 	} else {
4147 		ip_mq_unlock(dport);
4148 	}
4149 	/* dport is unlocked, unless needboost == TRUE */
4150 
4151 	is_write_unlock(space);
4152 
4153 #if IMPORTANCE_INHERITANCE
4154 	/*
4155 	 * If our request is the first boosting send-possible
4156 	 * notification this cycle, push the boost down the
4157 	 * destination port.
4158 	 */
4159 	if (needboost == TRUE) {
4160 		/* dport still locked from above */
4161 		if (ipc_port_importance_delta(dport, IPID_OPTION_SENDPOSSIBLE, 1) == FALSE) {
4162 			ip_mq_unlock(dport);
4163 		}
4164 	}
4165 #endif /* IMPORTANCE_INHERITANCE */
4166 
4167 	/* dport is unlocked */
4168 
4169 	if (dest_soright != IP_NULL) {
4170 		ipc_notify_port_deleted(dest_soright, dest_name);
4171 	}
4172 	if (reply_soright != IP_NULL) {
4173 		ipc_notify_port_deleted(reply_soright, reply_name);
4174 	}
4175 	if (voucher_soright != IP_NULL) {
4176 		ipc_notify_port_deleted(voucher_soright, voucher_name);
4177 	}
4178 
4179 	/*
4180 	 * No room to store voucher port in in-kernel msg header,
4181 	 * so we store it back in the kmsg itself. Store original voucher
4182 	 * type there as well, but set the bits to the post-copyin type.
4183 	 */
4184 	if (IP_VALID(voucher_port)) {
4185 		ipc_kmsg_set_voucher_port(kmsg, voucher_port, voucher_type);
4186 		voucher_type = MACH_MSG_TYPE_MOVE_SEND;
4187 	}
4188 
4189 	msg->msgh_bits = MACH_MSGH_BITS_SET(dest_type, reply_type, voucher_type, mbits);
4190 	msg->msgh_remote_port = ip_object_to_port(dest_port);
4191 	msg->msgh_local_port = ip_object_to_port(reply_port);
4192 
4193 	/*
4194 	 * capture the qos value(s) for the kmsg qos,
4195 	 * and apply any override before we enqueue the kmsg.
4196 	 */
4197 	ipc_kmsg_set_qos(kmsg, option32, priority);
4198 
4199 	if (release_port != IP_NULL) {
4200 		ip_release(release_port);
4201 	}
4202 
4203 	if (voucher_release_port != IP_NULL) {
4204 		ip_release(voucher_release_port);
4205 	}
4206 
4207 	if (enforce_strict_reply && MACH_SEND_WITH_STRICT_REPLY(option32) &&
4208 	    IP_VALID(msg->msgh_local_port)) {
4209 		/*
4210 		 * We've already validated that the reply disposition is a
4211 		 * [make/move] send-once. Ideally, we should enforce that the
4212 		 * reply port is also not dead, but XPC asynchronous
4213 		 * cancellation can make the reply port dead before we
4214 		 * actually make it to the mach_msg send.
4215 		 *
4216 		 * Here, we ensure that if we have a non-dead reply port, then
4217 		 * the reply port's receive right should not be in-transit,
4218 		 * and should live in the caller's IPC space.
4219 		 */
4220 		ipc_port_t rport = msg->msgh_local_port;
4221 		ip_mq_lock(rport);
4222 		kr = ipc_kmsg_validate_reply_port_locked(rport, option32);
4223 		ip_mq_unlock(rport);
4224 		if (kr != KERN_SUCCESS) {
4225 			/*
4226 			 * no descriptors have been copied in yet, but the
4227 			 * full header has been copied in: clean it up
4228 			 */
4229 			ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
4230 			if ((option32 & MACH_SEND_KERNEL) == 0) {
4231 				mach_port_guard_exception(reply_name, 0,
4232 				    (MPG_FLAGS_STRICT_REPLY_INVALID_REPLY_PORT | kr),
4233 				    kGUARD_EXC_STRICT_REPLY);
4234 			}
4235 			return MACH_SEND_INVALID_REPLY;
4236 		}
4237 	}
4238 
4239 	if (reply_port_semantics_violation) {
4240 		/* Currently rate limiting it to sucess paths only. */
4241 		stash_reply_port_semantics_violations_telemetry();
4242 	}
4243 	return MACH_MSG_SUCCESS;
4244 
4245 invalid_reply:
4246 	is_write_unlock(space);
4247 
4248 	if (release_port != IP_NULL) {
4249 		ip_release(release_port);
4250 	}
4251 
4252 	assert(voucher_port == IP_NULL);
4253 	assert(voucher_soright == IP_NULL);
4254 
4255 	if ((option32 & MACH_SEND_KERNEL) == 0) {
4256 		mach_port_guard_exception(reply_name, 0, 0, kGUARD_EXC_SEND_INVALID_REPLY);
4257 	}
4258 	return MACH_SEND_INVALID_REPLY;
4259 
4260 invalid_dest:
4261 	is_write_unlock(space);
4262 
4263 	if (release_port != IP_NULL) {
4264 		ip_release(release_port);
4265 	}
4266 
4267 	if (reply_soright != IP_NULL) {
4268 		ipc_notify_port_deleted(reply_soright, reply_name);
4269 	}
4270 
4271 	assert(voucher_port == IP_NULL);
4272 	assert(voucher_soright == IP_NULL);
4273 
4274 	return MACH_SEND_INVALID_DEST;
4275 }
4276 
4277 static mach_msg_descriptor_t *
ipc_kmsg_copyin_port_descriptor(mach_msg_port_descriptor_t * dsc,mach_msg_user_port_descriptor_t * user_dsc_in,ipc_space_t space,ipc_object_t dest,ipc_kmsg_t kmsg,mach_msg_option_t options,mach_msg_return_t * mr)4278 ipc_kmsg_copyin_port_descriptor(
4279 	mach_msg_port_descriptor_t *dsc,
4280 	mach_msg_user_port_descriptor_t *user_dsc_in,
4281 	ipc_space_t space,
4282 	ipc_object_t dest,
4283 	ipc_kmsg_t kmsg,
4284 	mach_msg_option_t options,
4285 	mach_msg_return_t *mr)
4286 {
4287 	mach_msg_user_port_descriptor_t user_dsc = *user_dsc_in;
4288 	mach_msg_type_name_t        user_disp;
4289 	mach_msg_type_name_t        result_disp;
4290 	mach_port_name_t            name;
4291 	ipc_object_t                object;
4292 
4293 	user_disp = user_dsc.disposition;
4294 	result_disp = ipc_object_copyin_type(user_disp);
4295 
4296 	name = (mach_port_name_t)user_dsc.name;
4297 	if (MACH_PORT_VALID(name)) {
4298 		kern_return_t kr = ipc_object_copyin(space, name, user_disp, &object, 0, NULL, kmsg->ikm_flags);
4299 		if (kr != KERN_SUCCESS) {
4300 			if (((options & MACH_SEND_KERNEL) == 0) && (kr == KERN_INVALID_RIGHT)) {
4301 				mach_port_guard_exception(name, 0, 0, kGUARD_EXC_SEND_INVALID_RIGHT);
4302 			}
4303 			*mr = MACH_SEND_INVALID_RIGHT;
4304 			return NULL;
4305 		}
4306 
4307 		if ((result_disp == MACH_MSG_TYPE_PORT_RECEIVE) &&
4308 		    ipc_port_check_circularity(ip_object_to_port(object),
4309 		    ip_object_to_port(dest))) {
4310 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
4311 		}
4312 		dsc->name = ip_object_to_port(object);
4313 	} else {
4314 		dsc->name = CAST_MACH_NAME_TO_PORT(name);
4315 	}
4316 	dsc->disposition = result_disp;
4317 	dsc->type = MACH_MSG_PORT_DESCRIPTOR;
4318 
4319 	dsc->pad_end = 0;         // debug, unnecessary
4320 
4321 	return (mach_msg_descriptor_t *)(user_dsc_in + 1);
4322 }
4323 
4324 static mach_msg_descriptor_t *
ipc_kmsg_copyin_ool_descriptor(mach_msg_ool_descriptor_t * dsc,mach_msg_descriptor_t * user_dsc,int is_64bit,mach_vm_address_t * paddr,vm_map_copy_t * copy,vm_size_t * space_needed,vm_map_t map,mach_msg_return_t * mr)4325 ipc_kmsg_copyin_ool_descriptor(
4326 	mach_msg_ool_descriptor_t *dsc,
4327 	mach_msg_descriptor_t *user_dsc,
4328 	int is_64bit,
4329 	mach_vm_address_t *paddr,
4330 	vm_map_copy_t *copy,
4331 	vm_size_t *space_needed,
4332 	vm_map_t map,
4333 	mach_msg_return_t *mr)
4334 {
4335 	vm_size_t                           length;
4336 	boolean_t                           dealloc;
4337 	mach_msg_copy_options_t             copy_options;
4338 	mach_vm_offset_t            addr;
4339 	mach_msg_descriptor_type_t  dsc_type;
4340 
4341 	if (is_64bit) {
4342 		mach_msg_ool_descriptor64_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
4343 
4344 		addr = (mach_vm_offset_t) user_ool_dsc->address;
4345 		length = user_ool_dsc->size;
4346 		dealloc = user_ool_dsc->deallocate;
4347 		copy_options = user_ool_dsc->copy;
4348 		dsc_type = user_ool_dsc->type;
4349 
4350 		user_dsc = (typeof(user_dsc))(user_ool_dsc + 1);
4351 	} else {
4352 		mach_msg_ool_descriptor32_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
4353 
4354 		addr = CAST_USER_ADDR_T(user_ool_dsc->address);
4355 		dealloc = user_ool_dsc->deallocate;
4356 		copy_options = user_ool_dsc->copy;
4357 		dsc_type = user_ool_dsc->type;
4358 		length = user_ool_dsc->size;
4359 
4360 		user_dsc = (typeof(user_dsc))(user_ool_dsc + 1);
4361 	}
4362 
4363 	dsc->size = (mach_msg_size_t)length;
4364 	dsc->deallocate = dealloc;
4365 	dsc->copy = copy_options;
4366 	dsc->type = dsc_type;
4367 
4368 	if (length == 0) {
4369 		dsc->address = NULL;
4370 	} else if (length > MSG_OOL_SIZE_SMALL &&
4371 	    (copy_options == MACH_MSG_PHYSICAL_COPY) && !dealloc) {
4372 		/*
4373 		 * If the request is a physical copy and the source
4374 		 * is not being deallocated, then allocate space
4375 		 * in the kernel's pageable ipc copy map and copy
4376 		 * the data in.  The semantics guarantee that the
4377 		 * data will have been physically copied before
4378 		 * the send operation terminates.  Thus if the data
4379 		 * is not being deallocated, we must be prepared
4380 		 * to page if the region is sufficiently large.
4381 		 */
4382 		if (copyin(addr, (char *)*paddr, length)) {
4383 			*mr = MACH_SEND_INVALID_MEMORY;
4384 			return NULL;
4385 		}
4386 
4387 		/*
4388 		 * The kernel ipc copy map is marked no_zero_fill.
4389 		 * If the transfer is not a page multiple, we need
4390 		 * to zero fill the balance.
4391 		 */
4392 		if (!page_aligned(length)) {
4393 			(void) memset((void *) (*paddr + length), 0,
4394 			    round_page(length) - length);
4395 		}
4396 		if (vm_map_copyin(ipc_kernel_copy_map, (vm_map_address_t)*paddr,
4397 		    (vm_map_size_t)length, TRUE, copy) != KERN_SUCCESS) {
4398 			*mr = MACH_MSG_VM_KERNEL;
4399 			return NULL;
4400 		}
4401 		dsc->address = (void *)*copy;
4402 		*paddr += round_page(length);
4403 		*space_needed -= round_page(length);
4404 	} else {
4405 		/*
4406 		 * Make a vm_map_copy_t of the of the data.  If the
4407 		 * data is small, this will do an optimized physical
4408 		 * copy.  Otherwise, it will do a virtual copy.
4409 		 *
4410 		 * NOTE: A virtual copy is OK if the original is being
4411 		 * deallocted, even if a physical copy was requested.
4412 		 */
4413 		kern_return_t kr = vm_map_copyin(map, addr,
4414 		    (vm_map_size_t)length, dealloc, copy);
4415 		if (kr != KERN_SUCCESS) {
4416 			*mr = (kr == KERN_RESOURCE_SHORTAGE) ?
4417 			    MACH_MSG_VM_KERNEL :
4418 			    MACH_SEND_INVALID_MEMORY;
4419 			return NULL;
4420 		}
4421 		dsc->address = (void *)*copy;
4422 	}
4423 
4424 	return user_dsc;
4425 }
4426 
4427 static mach_msg_descriptor_t *
ipc_kmsg_copyin_ool_ports_descriptor(mach_msg_ool_ports_descriptor_t * dsc,mach_msg_descriptor_t * user_dsc,int is_64bit,vm_map_t map,ipc_space_t space,ipc_object_t dest,ipc_kmsg_t kmsg,mach_msg_option_t options,mach_msg_return_t * mr)4428 ipc_kmsg_copyin_ool_ports_descriptor(
4429 	mach_msg_ool_ports_descriptor_t *dsc,
4430 	mach_msg_descriptor_t *user_dsc,
4431 	int is_64bit,
4432 	vm_map_t map,
4433 	ipc_space_t space,
4434 	ipc_object_t dest,
4435 	ipc_kmsg_t kmsg,
4436 	mach_msg_option_t options,
4437 	mach_msg_return_t *mr)
4438 {
4439 	void *data;
4440 	ipc_object_t *objects;
4441 	unsigned int i;
4442 	mach_vm_offset_t addr;
4443 	mach_msg_type_name_t user_disp;
4444 	mach_msg_type_name_t result_disp;
4445 	mach_msg_type_number_t count;
4446 	mach_msg_copy_options_t copy_option;
4447 	boolean_t deallocate;
4448 	mach_msg_descriptor_type_t type;
4449 	vm_size_t ports_length, names_length;
4450 
4451 	if (is_64bit) {
4452 		mach_msg_ool_ports_descriptor64_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
4453 
4454 		addr = (mach_vm_offset_t)user_ool_dsc->address;
4455 		count = user_ool_dsc->count;
4456 		deallocate = user_ool_dsc->deallocate;
4457 		copy_option = user_ool_dsc->copy;
4458 		user_disp = user_ool_dsc->disposition;
4459 		type = user_ool_dsc->type;
4460 
4461 		user_dsc = (typeof(user_dsc))(user_ool_dsc + 1);
4462 	} else {
4463 		mach_msg_ool_ports_descriptor32_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
4464 
4465 		addr = CAST_USER_ADDR_T(user_ool_dsc->address);
4466 		count = user_ool_dsc->count;
4467 		deallocate = user_ool_dsc->deallocate;
4468 		copy_option = user_ool_dsc->copy;
4469 		user_disp = user_ool_dsc->disposition;
4470 		type = user_ool_dsc->type;
4471 
4472 		user_dsc = (typeof(user_dsc))(user_ool_dsc + 1);
4473 	}
4474 
4475 	dsc->deallocate = deallocate;
4476 	dsc->copy = copy_option;
4477 	dsc->type = type;
4478 	dsc->count = count;
4479 	dsc->address = NULL; /* for now */
4480 
4481 	result_disp = ipc_object_copyin_type(user_disp);
4482 	dsc->disposition = result_disp;
4483 
4484 	/* We always do a 'physical copy', but you have to specify something valid */
4485 	if (copy_option != MACH_MSG_PHYSICAL_COPY &&
4486 	    copy_option != MACH_MSG_VIRTUAL_COPY) {
4487 		*mr = MACH_SEND_INVALID_TYPE;
4488 		return NULL;
4489 	}
4490 
4491 	/* calculate length of data in bytes, rounding up */
4492 
4493 	if (os_mul_overflow(count, sizeof(mach_port_t), &ports_length)) {
4494 		*mr = MACH_SEND_TOO_LARGE;
4495 		return NULL;
4496 	}
4497 
4498 	if (os_mul_overflow(count, sizeof(mach_port_name_t), &names_length)) {
4499 		*mr = MACH_SEND_TOO_LARGE;
4500 		return NULL;
4501 	}
4502 
4503 	if (ports_length == 0) {
4504 		return user_dsc;
4505 	}
4506 
4507 	data = kalloc_type(mach_port_t, count, Z_WAITOK);
4508 
4509 	if (data == NULL) {
4510 		*mr = MACH_SEND_NO_BUFFER;
4511 		return NULL;
4512 	}
4513 
4514 #ifdef __LP64__
4515 	mach_port_name_t *names = &((mach_port_name_t *)data)[count];
4516 #else
4517 	mach_port_name_t *names = ((mach_port_name_t *)data);
4518 #endif
4519 
4520 	if (copyinmap(map, addr, names, names_length) != KERN_SUCCESS) {
4521 		kfree_type(mach_port_t, count, data);
4522 		*mr = MACH_SEND_INVALID_MEMORY;
4523 		return NULL;
4524 	}
4525 
4526 	if (deallocate) {
4527 		(void) mach_vm_deallocate(map, addr, (mach_vm_size_t)names_length);
4528 	}
4529 
4530 	objects = (ipc_object_t *) data;
4531 	dsc->address = data;
4532 
4533 	for (i = 0; i < count; i++) {
4534 		mach_port_name_t name = names[i];
4535 		ipc_object_t object;
4536 
4537 		if (!MACH_PORT_VALID(name)) {
4538 			objects[i] = ip_to_object(CAST_MACH_NAME_TO_PORT(name));
4539 			continue;
4540 		}
4541 
4542 		kern_return_t kr = ipc_object_copyin(space, name, user_disp, &object, 0, NULL, kmsg->ikm_flags);
4543 
4544 		if (kr != KERN_SUCCESS) {
4545 			unsigned int j;
4546 
4547 			for (j = 0; j < i; j++) {
4548 				object = objects[j];
4549 				if (IPC_OBJECT_VALID(object)) {
4550 					ipc_object_destroy(object, result_disp);
4551 				}
4552 			}
4553 			kfree_type(mach_port_t, count, data);
4554 			dsc->address = NULL;
4555 			if (((options & MACH_SEND_KERNEL) == 0) && (kr == KERN_INVALID_RIGHT)) {
4556 				mach_port_guard_exception(name, 0, 0, kGUARD_EXC_SEND_INVALID_RIGHT);
4557 			}
4558 			*mr = MACH_SEND_INVALID_RIGHT;
4559 			return NULL;
4560 		}
4561 
4562 		if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
4563 		    ipc_port_check_circularity(ip_object_to_port(object),
4564 		    ip_object_to_port(dest))) {
4565 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
4566 		}
4567 
4568 		objects[i] = object;
4569 	}
4570 
4571 	return user_dsc;
4572 }
4573 
4574 static mach_msg_descriptor_t *
ipc_kmsg_copyin_guarded_port_descriptor(mach_msg_guarded_port_descriptor_t * dsc,mach_msg_descriptor_t * user_addr,int is_64bit,ipc_space_t space,ipc_object_t dest,ipc_kmsg_t kmsg,mach_msg_option_t options,mach_msg_return_t * mr)4575 ipc_kmsg_copyin_guarded_port_descriptor(
4576 	mach_msg_guarded_port_descriptor_t *dsc,
4577 	mach_msg_descriptor_t *user_addr,
4578 	int is_64bit,
4579 	ipc_space_t space,
4580 	ipc_object_t dest,
4581 	ipc_kmsg_t kmsg,
4582 	mach_msg_option_t options,
4583 	mach_msg_return_t *mr)
4584 {
4585 	mach_msg_descriptor_t       *user_dsc;
4586 	mach_msg_type_name_t        disp;
4587 	mach_msg_type_name_t        result_disp;
4588 	mach_port_name_t            name;
4589 	mach_msg_guard_flags_t      guard_flags;
4590 	ipc_object_t                object;
4591 	mach_port_context_t         context;
4592 
4593 	if (!is_64bit) {
4594 		mach_msg_guarded_port_descriptor32_t *user_gp_dsc = (typeof(user_gp_dsc))user_addr;
4595 		name = user_gp_dsc->name;
4596 		guard_flags = user_gp_dsc->flags;
4597 		disp = user_gp_dsc->disposition;
4598 		context = user_gp_dsc->context;
4599 		user_dsc = (mach_msg_descriptor_t *)(user_gp_dsc + 1);
4600 	} else {
4601 		mach_msg_guarded_port_descriptor64_t *user_gp_dsc = (typeof(user_gp_dsc))user_addr;
4602 		name = user_gp_dsc->name;
4603 		guard_flags = user_gp_dsc->flags;
4604 		disp = user_gp_dsc->disposition;
4605 		context = user_gp_dsc->context;
4606 		user_dsc = (mach_msg_descriptor_t *)(user_gp_dsc + 1);
4607 	}
4608 
4609 	guard_flags &= MACH_MSG_GUARD_FLAGS_MASK;
4610 	result_disp = ipc_object_copyin_type(disp);
4611 
4612 	if (MACH_PORT_VALID(name)) {
4613 		kern_return_t kr = ipc_object_copyin(space, name, disp, &object, context, &guard_flags, kmsg->ikm_flags);
4614 		if (kr != KERN_SUCCESS) {
4615 			if (((options & MACH_SEND_KERNEL) == 0) && (kr == KERN_INVALID_RIGHT)) {
4616 				mach_port_guard_exception(name, 0, 0, kGUARD_EXC_SEND_INVALID_RIGHT);
4617 			}
4618 			*mr = MACH_SEND_INVALID_RIGHT;
4619 			return NULL;
4620 		}
4621 
4622 		if ((result_disp == MACH_MSG_TYPE_PORT_RECEIVE) &&
4623 		    ipc_port_check_circularity(ip_object_to_port(object),
4624 		    ip_object_to_port(dest))) {
4625 			ikm_header(kmsg)->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
4626 		}
4627 		dsc->name = ip_object_to_port(object);
4628 	} else {
4629 		dsc->name = CAST_MACH_NAME_TO_PORT(name);
4630 	}
4631 	dsc->flags = guard_flags;
4632 	dsc->disposition = result_disp;
4633 	dsc->type = MACH_MSG_GUARDED_PORT_DESCRIPTOR;
4634 
4635 #if __LP64__
4636 	dsc->pad_end = 0;         // debug, unnecessary
4637 #endif
4638 
4639 	return user_dsc;
4640 }
4641 
4642 
4643 /*
4644  *	Routine:	ipc_kmsg_copyin_body
4645  *	Purpose:
4646  *		"Copy-in" port rights and out-of-line memory
4647  *		in the message body.
4648  *
4649  *		In all failure cases, the message is left holding
4650  *		no rights or memory.  However, the message buffer
4651  *		is not deallocated.  If successful, the message
4652  *		contains a valid destination port.
4653  *	Conditions:
4654  *		Nothing locked.
4655  *	Returns:
4656  *		MACH_MSG_SUCCESS	Successful copyin.
4657  *		MACH_SEND_INVALID_MEMORY	Can't grab out-of-line memory.
4658  *		MACH_SEND_INVALID_RIGHT	Can't copyin port right in body.
4659  *		MACH_SEND_INVALID_TYPE	Bad type specification.
4660  *		MACH_SEND_MSG_TOO_SMALL	Body is too small for types/data.
4661  *		MACH_SEND_INVALID_RT_OOL_SIZE OOL Buffer too large for RT
4662  *		MACH_MSG_INVALID_RT_DESCRIPTOR Dealloc and RT are incompatible
4663  *		MACH_SEND_NO_GRANT_DEST	Dest port doesn't accept ports in body
4664  */
4665 
4666 static mach_msg_return_t
ipc_kmsg_copyin_body(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map,mach_msg_option_t options)4667 ipc_kmsg_copyin_body(
4668 	ipc_kmsg_t      kmsg,
4669 	ipc_space_t     space,
4670 	vm_map_t        map,
4671 	mach_msg_option_t options)
4672 {
4673 	ipc_object_t                dest;
4674 	mach_msg_body_t             *body;
4675 	mach_msg_descriptor_t       *daddr;
4676 	mach_msg_descriptor_t       *user_addr, *kern_addr;
4677 	mach_msg_type_number_t      dsc_count;
4678 	boolean_t                   is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
4679 	boolean_t                   contains_port_desc = FALSE;
4680 	vm_size_t                   space_needed = 0;
4681 	mach_vm_address_t           paddr = 0;
4682 	__assert_only vm_offset_t   end;
4683 	vm_map_copy_t               copy = VM_MAP_COPY_NULL;
4684 	mach_msg_return_t           mr = MACH_MSG_SUCCESS;
4685 	mach_msg_header_t           *hdr = ikm_header(kmsg);
4686 
4687 	ipc_port_t                  remote_port = hdr->msgh_remote_port;
4688 
4689 	vm_size_t           descriptor_size = 0;
4690 
4691 	mach_msg_type_number_t total_ool_port_count = 0;
4692 	mach_msg_guard_flags_t guard_flags = 0;
4693 	mach_port_context_t context;
4694 	mach_msg_type_name_t disp;
4695 
4696 	/*
4697 	 * Determine if the target is a kernel port.
4698 	 */
4699 	dest = ip_to_object(remote_port);
4700 	body = (mach_msg_body_t *) (hdr + 1);
4701 	daddr = (mach_msg_descriptor_t *) (body + 1);
4702 
4703 	dsc_count = body->msgh_descriptor_count;
4704 	if (dsc_count == 0) {
4705 		return MACH_MSG_SUCCESS;
4706 	}
4707 
4708 	assert(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX);
4709 	end = (vm_offset_t)hdr + sizeof(mach_msg_base_t) +
4710 	    dsc_count * KERNEL_DESC_SIZE;
4711 
4712 	/*
4713 	 * Make an initial pass to determine kernal VM space requirements for
4714 	 * physical copies and possible contraction of the descriptors from
4715 	 * processes with pointers larger than the kernel's.
4716 	 */
4717 	for (mach_msg_type_number_t i = 0; i < dsc_count; i++) {
4718 		mach_msg_size_t dsize;
4719 		mach_msg_size_t size;
4720 		mach_msg_type_number_t ool_port_count = 0;
4721 
4722 		dsize = ikm_user_desc_size(daddr->type.type, is_task_64bit);
4723 		/* descriptor size check has been hoisted to ikm_check_descriptors() */
4724 		assert((vm_offset_t)daddr + dsize <= end);
4725 
4726 		switch (daddr->type.type) {
4727 		case MACH_MSG_OOL_DESCRIPTOR:
4728 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
4729 			size = (is_task_64bit) ?
4730 			    ((mach_msg_ool_descriptor64_t *)daddr)->size :
4731 			    daddr->out_of_line.size;
4732 
4733 			if (daddr->out_of_line.copy != MACH_MSG_PHYSICAL_COPY &&
4734 			    daddr->out_of_line.copy != MACH_MSG_VIRTUAL_COPY) {
4735 				/*
4736 				 * Invalid copy option
4737 				 */
4738 				mr = MACH_SEND_INVALID_TYPE;
4739 				goto clean_message;
4740 			}
4741 
4742 			if (size > MSG_OOL_SIZE_SMALL &&
4743 			    (daddr->out_of_line.copy == MACH_MSG_PHYSICAL_COPY) &&
4744 			    !(daddr->out_of_line.deallocate)) {
4745 				/*
4746 				 * Out-of-line memory descriptor, accumulate kernel
4747 				 * memory requirements
4748 				 */
4749 				if (space_needed + round_page(size) <= space_needed) {
4750 					/* Overflow dectected */
4751 					mr = MACH_MSG_VM_KERNEL;
4752 					goto clean_message;
4753 				}
4754 
4755 				space_needed += round_page(size);
4756 				if (space_needed > ipc_kmsg_max_vm_space) {
4757 					/* Per message kernel memory limit exceeded */
4758 					mr = MACH_MSG_VM_KERNEL;
4759 					goto clean_message;
4760 				}
4761 			}
4762 			break;
4763 		case MACH_MSG_PORT_DESCRIPTOR:
4764 			if (os_add_overflow(total_ool_port_count, 1, &total_ool_port_count)) {
4765 				/* Overflow detected */
4766 				mr = MACH_SEND_TOO_LARGE;
4767 				goto clean_message;
4768 			}
4769 			contains_port_desc = TRUE;
4770 			break;
4771 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
4772 			ool_port_count = (is_task_64bit) ?
4773 			    ((mach_msg_ool_ports_descriptor64_t *)daddr)->count :
4774 			    daddr->ool_ports.count;
4775 
4776 			if (os_add_overflow(total_ool_port_count, ool_port_count, &total_ool_port_count)) {
4777 				/* Overflow detected */
4778 				mr = MACH_SEND_TOO_LARGE;
4779 				goto clean_message;
4780 			}
4781 
4782 			if (ool_port_count > (ipc_kmsg_max_vm_space / sizeof(mach_port_t))) {
4783 				/* Per message kernel memory limit exceeded */
4784 				mr = MACH_SEND_TOO_LARGE;
4785 				goto clean_message;
4786 			}
4787 			contains_port_desc = TRUE;
4788 			break;
4789 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
4790 			guard_flags = (is_task_64bit) ?
4791 			    ((mach_msg_guarded_port_descriptor64_t *)daddr)->flags :
4792 			    ((mach_msg_guarded_port_descriptor32_t *)daddr)->flags;
4793 			context = (is_task_64bit) ?
4794 			    ((mach_msg_guarded_port_descriptor64_t *)daddr)->context :
4795 			    ((mach_msg_guarded_port_descriptor32_t *)daddr)->context;
4796 			disp = (is_task_64bit) ?
4797 			    ((mach_msg_guarded_port_descriptor64_t *)daddr)->disposition :
4798 			    ((mach_msg_guarded_port_descriptor32_t *)daddr)->disposition;
4799 
4800 			/* Only MACH_MSG_TYPE_MOVE_RECEIVE is supported for now */
4801 			if (!guard_flags || ((guard_flags & ~MACH_MSG_GUARD_FLAGS_MASK) != 0) ||
4802 			    ((guard_flags & MACH_MSG_GUARD_FLAGS_UNGUARDED_ON_SEND) && (context != 0)) ||
4803 			    (disp != MACH_MSG_TYPE_MOVE_RECEIVE)) {
4804 				/*
4805 				 * Invalid guard flags, context or disposition
4806 				 */
4807 				mr = MACH_SEND_INVALID_TYPE;
4808 				goto clean_message;
4809 			}
4810 			if (os_add_overflow(total_ool_port_count, 1, &total_ool_port_count)) {
4811 				/* Overflow detected */
4812 				mr = MACH_SEND_TOO_LARGE;
4813 				goto clean_message;
4814 			}
4815 			contains_port_desc = TRUE;
4816 			break;
4817 		default:
4818 			/* descriptor type check has been hoisted to ikm_check_descriptors() */
4819 			panic("invalid descriptor type");
4820 		}
4821 
4822 		descriptor_size += dsize;
4823 		daddr = (typeof(daddr))((vm_offset_t)daddr + dsize);
4824 	}
4825 
4826 	/* Sending more than 16383 rights in one message seems crazy */
4827 	if (total_ool_port_count >= (MACH_PORT_UREFS_MAX / 4)) {
4828 		mr = MACH_SEND_TOO_LARGE;
4829 		goto clean_message;
4830 	}
4831 
4832 	/*
4833 	 * Check if dest is a no-grant port; Since this bit is set only on
4834 	 * port construction and cannot be unset later, we can peek at the
4835 	 * bit without paying the cost of locking the port.
4836 	 */
4837 	if (contains_port_desc && remote_port->ip_no_grant) {
4838 		mr = MACH_SEND_NO_GRANT_DEST;
4839 		goto clean_message;
4840 	}
4841 
4842 	/*
4843 	 * Allocate space in the pageable kernel ipc copy map for all the
4844 	 * ool data that is to be physically copied.  Map is marked wait for
4845 	 * space.
4846 	 */
4847 	if (space_needed) {
4848 		if (mach_vm_allocate_kernel(ipc_kernel_copy_map, &paddr, space_needed,
4849 		    VM_FLAGS_ANYWHERE, VM_KERN_MEMORY_IPC) != KERN_SUCCESS) {
4850 			mr = MACH_MSG_VM_KERNEL;
4851 			goto clean_message;
4852 		}
4853 	}
4854 
4855 	/* kern_addr = just after base as it was copied in */
4856 	kern_addr = (mach_msg_descriptor_t *)((vm_offset_t)hdr +
4857 	    sizeof(mach_msg_base_t));
4858 
4859 	/*
4860 	 * Shift memory after mach_msg_base_t to make room for dsc_count * 16bytes
4861 	 * of descriptors on 64 bit kernels
4862 	 */
4863 	vm_offset_t dsc_adjust = KERNEL_DESC_SIZE * dsc_count - descriptor_size;
4864 
4865 	if (descriptor_size != KERNEL_DESC_SIZE * dsc_count) {
4866 		if (ikm_is_linear(kmsg)) {
4867 			memmove((char *)(((vm_offset_t)hdr) + sizeof(mach_msg_base_t) + dsc_adjust),
4868 			    (void *)((vm_offset_t)hdr + sizeof(mach_msg_base_t)),
4869 			    hdr->msgh_size - sizeof(mach_msg_base_t));
4870 		} else {
4871 			/* just memmove the descriptors following the header */
4872 			memmove((char *)(((vm_offset_t)hdr) + sizeof(mach_msg_base_t) + dsc_adjust),
4873 			    (void *)((vm_offset_t)hdr + sizeof(mach_msg_base_t)),
4874 			    ikm_total_desc_size(kmsg, current_map(), 0, 0, true));
4875 		}
4876 
4877 		/* Update the message size for the larger in-kernel representation */
4878 		hdr->msgh_size += (mach_msg_size_t)dsc_adjust;
4879 	}
4880 
4881 
4882 	/* user_addr = just after base after it has been (conditionally) moved */
4883 	user_addr = (mach_msg_descriptor_t *)((vm_offset_t)hdr +
4884 	    sizeof(mach_msg_base_t) + dsc_adjust);
4885 
4886 	/*
4887 	 * Receive right of a libxpc connection port is moved as a part of kmsg's body
4888 	 * 1. from a client to a service during connection etsablishment.
4889 	 * 2. back to the client on service's death or port deallocation.
4890 	 *
4891 	 * Any other attempt to move this receive right is not allowed.
4892 	 */
4893 	kmsg->ikm_flags |= IPC_OBJECT_COPYIN_FLAGS_ALLOW_CONN_IMMOVABLE_RECEIVE;
4894 
4895 	/* handle the OOL regions and port descriptors. */
4896 	for (mach_msg_type_number_t copied_in_dscs = 0;
4897 	    copied_in_dscs < dsc_count; copied_in_dscs++) {
4898 		switch (user_addr->type.type) {
4899 		case MACH_MSG_PORT_DESCRIPTOR:
4900 			user_addr = ipc_kmsg_copyin_port_descriptor((mach_msg_port_descriptor_t *)kern_addr,
4901 			    (mach_msg_user_port_descriptor_t *)user_addr, space, dest, kmsg, options, &mr);
4902 			kern_addr++;
4903 			break;
4904 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
4905 		case MACH_MSG_OOL_DESCRIPTOR:
4906 			user_addr = ipc_kmsg_copyin_ool_descriptor((mach_msg_ool_descriptor_t *)kern_addr,
4907 			    user_addr, is_task_64bit, &paddr, &copy, &space_needed, map, &mr);
4908 			kern_addr++;
4909 			break;
4910 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
4911 			user_addr = ipc_kmsg_copyin_ool_ports_descriptor((mach_msg_ool_ports_descriptor_t *)kern_addr,
4912 			    user_addr, is_task_64bit, map, space, dest, kmsg, options, &mr);
4913 			kern_addr++;
4914 			break;
4915 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
4916 			user_addr = ipc_kmsg_copyin_guarded_port_descriptor((mach_msg_guarded_port_descriptor_t *)kern_addr,
4917 			    user_addr, is_task_64bit, space, dest, kmsg, options, &mr);
4918 			kern_addr++;
4919 			break;
4920 		default:
4921 			panic("invalid descriptor type %d", user_addr->type.type);
4922 		}
4923 
4924 		if (MACH_MSG_SUCCESS != mr) {
4925 			/* clean from start of message descriptors to copied_in_dscs */
4926 			ipc_kmsg_clean_partial(kmsg, copied_in_dscs,
4927 			    (mach_msg_descriptor_t *)((mach_msg_base_t *)hdr + 1),
4928 			    paddr, space_needed);
4929 			goto out;
4930 		}
4931 	} /* End of loop */
4932 
4933 out:
4934 	return mr;
4935 
4936 clean_message:
4937 	/* no descriptors have been copied in yet */
4938 	ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
4939 	return mr;
4940 }
4941 
4942 #define MACH_BOOTSTRAP_PORT_MSG_ID_MASK ((1ul << 24) - 1)
4943 
4944 /*
4945  *	Routine:	ipc_kmsg_copyin_from_user
4946  *	Purpose:
4947  *		"Copy-in" port rights and out-of-line memory
4948  *		in the message.
4949  *
4950  *		In all failure cases, the message is left holding
4951  *		no rights or memory.  However, the message buffer
4952  *		is not deallocated.  If successful, the message
4953  *		contains a valid destination port.
4954  *	Conditions:
4955  *		Nothing locked.
4956  *	Returns:
4957  *		MACH_MSG_SUCCESS	Successful copyin.
4958  *		MACH_SEND_INVALID_HEADER Illegal value in the message header bits.
4959  *		MACH_SEND_INVALID_DEST	Can't copyin destination port.
4960  *		MACH_SEND_INVALID_REPLY	Can't copyin reply port.
4961  *		MACH_SEND_INVALID_MEMORY	Can't grab out-of-line memory.
4962  *		MACH_SEND_INVALID_RIGHT	Can't copyin port right in body.
4963  *		MACH_SEND_INVALID_TYPE	Bad type specification.
4964  *		MACH_SEND_MSG_TOO_SMALL	Body is too small for types/data.
4965  */
4966 
4967 mach_msg_return_t
ipc_kmsg_copyin_from_user(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map,mach_msg_priority_t priority,mach_msg_option64_t * option64p,bool filter_nonfatal)4968 ipc_kmsg_copyin_from_user(
4969 	ipc_kmsg_t              kmsg,
4970 	ipc_space_t             space,
4971 	vm_map_t                map,
4972 	mach_msg_priority_t     priority,
4973 	mach_msg_option64_t     *option64p,
4974 	bool                    filter_nonfatal)
4975 {
4976 	mach_msg_return_t           mr;
4977 	mach_msg_header_t           *hdr = ikm_header(kmsg);
4978 	mach_port_name_t dest_name = CAST_MACH_PORT_TO_NAME(hdr->msgh_remote_port);
4979 
4980 	hdr->msgh_bits &= MACH_MSGH_BITS_USER;
4981 
4982 	mr = ipc_kmsg_copyin_header(kmsg, space, priority, option64p);
4983 	/* copyin_header may add MACH64_SEND_ALWAYS option */
4984 
4985 	if (mr != MACH_MSG_SUCCESS) {
4986 		return mr;
4987 	}
4988 
4989 	/* Get the message filter policy if the task and port support filtering */
4990 	mach_msg_filter_id fid = 0;
4991 	mach_port_t remote_port = hdr->msgh_remote_port;
4992 	mach_msg_id_t msg_id = hdr->msgh_id;
4993 	void * sblabel = NULL;
4994 
4995 	if (mach_msg_filter_at_least(MACH_MSG_FILTER_CALLBACKS_VERSION_1) &&
4996 	    task_get_filter_msg_flag(current_task()) &&
4997 	    ip_enforce_msg_filtering(remote_port)) {
4998 		ip_mq_lock(remote_port);
4999 		if (ip_active(remote_port)) {
5000 			if (remote_port->ip_service_port) {
5001 				ipc_service_port_label_t label = remote_port->ip_splabel;
5002 				sblabel = label->ispl_sblabel;
5003 				if (label && ipc_service_port_label_is_bootstrap_port(label)) {
5004 					/*
5005 					 * Mask the top byte for messages sent to launchd's bootstrap port.
5006 					 * Filter any messages with domain 0 (as they correspond to MIG
5007 					 * based messages)
5008 					 */
5009 					unsigned msg_protocol = msg_id & ~MACH_BOOTSTRAP_PORT_MSG_ID_MASK;
5010 					if (!msg_protocol) {
5011 						ip_mq_unlock(remote_port);
5012 						goto filtered_msg;
5013 					}
5014 					msg_id = msg_id & MACH_BOOTSTRAP_PORT_MSG_ID_MASK;
5015 				}
5016 			} else {
5017 				assert(!ip_is_kolabeled(remote_port));
5018 				/* Connection ports can also have send-side message filters */
5019 				sblabel = remote_port->ip_splabel;
5020 			}
5021 			if (sblabel) {
5022 				mach_msg_filter_retain_sblabel_callback(sblabel);
5023 			}
5024 		}
5025 		ip_mq_unlock(remote_port);
5026 
5027 		if (sblabel && !mach_msg_fetch_filter_policy(sblabel, msg_id, &fid)) {
5028 			goto filtered_msg;
5029 		}
5030 	}
5031 
5032 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_SEND) | DBG_FUNC_NONE,
5033 	    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
5034 	    (uintptr_t)hdr->msgh_bits,
5035 	    (uintptr_t)hdr->msgh_id,
5036 	    VM_KERNEL_ADDRPERM((uintptr_t)unsafe_convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg))),
5037 	    0);
5038 
5039 	DEBUG_KPRINT_SYSCALL_IPC("ipc_kmsg_copyin_from_user header:\n%.8x\n%.8x\n%p\n%p\n%p\n%.8x\n",
5040 	    hdr->msgh_size,
5041 	    hdr->msgh_bits,
5042 	    hdr->msgh_remote_port,
5043 	    hdr->msgh_local_port,
5044 	    ipc_kmsg_get_voucher_port(kmsg),
5045 	    hdr->msgh_id);
5046 
5047 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
5048 		mr = ipc_kmsg_copyin_body(kmsg, space, map, (mach_msg_option_t)*option64p);
5049 	}
5050 
5051 	/* Sign the message contents */
5052 	if (mr == MACH_MSG_SUCCESS) {
5053 		ipc_kmsg_init_trailer(kmsg, current_task());
5054 		ikm_sign(kmsg);
5055 	}
5056 
5057 	return mr;
5058 
5059 filtered_msg:
5060 	if (!filter_nonfatal) {
5061 		mach_port_guard_exception(dest_name, 0, 0, kGUARD_EXC_MSG_FILTERED);
5062 	}
5063 	/* no descriptors have been copied in yet */
5064 	ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
5065 	return MACH_SEND_MSG_FILTERED;
5066 }
5067 
5068 /*
5069  *	Routine:	ipc_kmsg_copyin_from_kernel
5070  *	Purpose:
5071  *		"Copy-in" port rights and out-of-line memory
5072  *		in a message sent from the kernel.
5073  *
5074  *		Because the message comes from the kernel,
5075  *		the implementation assumes there are no errors
5076  *		or peculiarities in the message.
5077  *	Conditions:
5078  *		Nothing locked.
5079  */
5080 
5081 mach_msg_return_t
ipc_kmsg_copyin_from_kernel(ipc_kmsg_t kmsg)5082 ipc_kmsg_copyin_from_kernel(
5083 	ipc_kmsg_t      kmsg)
5084 {
5085 	mach_msg_header_t *hdr = ikm_header(kmsg);
5086 	mach_msg_bits_t bits = hdr->msgh_bits;
5087 	mach_msg_type_name_t rname = MACH_MSGH_BITS_REMOTE(bits);
5088 	mach_msg_type_name_t lname = MACH_MSGH_BITS_LOCAL(bits);
5089 	mach_msg_type_name_t vname = MACH_MSGH_BITS_VOUCHER(bits);
5090 	ipc_object_t remote = ip_to_object(hdr->msgh_remote_port);
5091 	ipc_object_t local = ip_to_object(hdr->msgh_local_port);
5092 	ipc_object_t voucher = ip_to_object(ipc_kmsg_get_voucher_port(kmsg));
5093 	ipc_port_t dest = hdr->msgh_remote_port;
5094 
5095 	/* translate the destination and reply ports */
5096 	if (!IO_VALID(remote)) {
5097 		return MACH_SEND_INVALID_DEST;
5098 	}
5099 
5100 	ipc_object_copyin_from_kernel(remote, rname);
5101 	if (IO_VALID(local)) {
5102 		ipc_object_copyin_from_kernel(local, lname);
5103 	}
5104 
5105 	if (IO_VALID(voucher)) {
5106 		ipc_object_copyin_from_kernel(voucher, vname);
5107 	}
5108 
5109 	/*
5110 	 *	The common case is a complex message with no reply port,
5111 	 *	because that is what the memory_object interface uses.
5112 	 */
5113 
5114 	if (bits == (MACH_MSGH_BITS_COMPLEX |
5115 	    MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0))) {
5116 		bits = (MACH_MSGH_BITS_COMPLEX |
5117 		    MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, 0));
5118 
5119 		hdr->msgh_bits = bits;
5120 	} else {
5121 		bits = (MACH_MSGH_BITS_OTHER(bits) |
5122 		    MACH_MSGH_BITS_SET_PORTS(ipc_object_copyin_type(rname),
5123 		    ipc_object_copyin_type(lname), ipc_object_copyin_type(vname)));
5124 
5125 		hdr->msgh_bits = bits;
5126 	}
5127 
5128 	ipc_kmsg_set_qos_kernel(kmsg);
5129 
5130 	if (bits & MACH_MSGH_BITS_COMPLEX) {
5131 		/*
5132 		 * Check if the remote port accepts ports in the body.
5133 		 */
5134 		if (dest->ip_no_grant) {
5135 			mach_msg_descriptor_t   *saddr;
5136 			mach_msg_body_t         *body;
5137 			mach_msg_type_number_t  i, count;
5138 
5139 			body = (mach_msg_body_t *) (hdr + 1);
5140 			saddr = (mach_msg_descriptor_t *) (body + 1);
5141 			count = body->msgh_descriptor_count;
5142 
5143 			for (i = 0; i < count; i++, saddr++) {
5144 				switch (saddr->type.type) {
5145 				case MACH_MSG_PORT_DESCRIPTOR:
5146 				case MACH_MSG_OOL_PORTS_DESCRIPTOR:
5147 				case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
5148 					/* no descriptors have been copied in yet */
5149 					ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
5150 					return MACH_SEND_NO_GRANT_DEST;
5151 				}
5152 			}
5153 		}
5154 
5155 		mach_msg_descriptor_t   *saddr;
5156 		mach_msg_body_t         *body;
5157 		mach_msg_type_number_t  i, count;
5158 
5159 		body = (mach_msg_body_t *) (hdr + 1);
5160 		saddr = (mach_msg_descriptor_t *) (body + 1);
5161 		count = body->msgh_descriptor_count;
5162 
5163 		for (i = 0; i < count; i++, saddr++) {
5164 			switch (saddr->type.type) {
5165 			case MACH_MSG_PORT_DESCRIPTOR: {
5166 				mach_msg_type_name_t        name;
5167 				ipc_object_t                object;
5168 				mach_msg_port_descriptor_t  *dsc;
5169 
5170 				dsc = &saddr->port;
5171 
5172 				/* this is really the type SEND, SEND_ONCE, etc. */
5173 				name = dsc->disposition;
5174 				object = ip_to_object(dsc->name);
5175 				dsc->disposition = ipc_object_copyin_type(name);
5176 
5177 				if (!IO_VALID(object)) {
5178 					break;
5179 				}
5180 
5181 				ipc_object_copyin_from_kernel(object, name);
5182 
5183 				/* CDY avoid circularity when the destination is also */
5184 				/* the kernel.  This check should be changed into an  */
5185 				/* assert when the new kobject model is in place since*/
5186 				/* ports will not be used in kernel to kernel chats   */
5187 
5188 				/* do not lock remote port, use raw pointer comparison */
5189 				if (!ip_in_space_noauth(ip_object_to_port(remote), ipc_space_kernel)) {
5190 					/* remote port could be dead, in-transit or in an ipc space */
5191 					if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
5192 					    ipc_port_check_circularity(ip_object_to_port(object),
5193 					    ip_object_to_port(remote))) {
5194 						hdr->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
5195 					}
5196 				}
5197 				break;
5198 			}
5199 			case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
5200 			case MACH_MSG_OOL_DESCRIPTOR: {
5201 				/*
5202 				 * The sender should supply ready-made memory, i.e.
5203 				 * a vm_map_copy_t, so we don't need to do anything.
5204 				 */
5205 				break;
5206 			}
5207 			case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
5208 				ipc_object_t                        *objects;
5209 				unsigned int                        j;
5210 				mach_msg_type_name_t                name;
5211 				mach_msg_ool_ports_descriptor_t     *dsc;
5212 
5213 				dsc = (mach_msg_ool_ports_descriptor_t *)&saddr->ool_ports;
5214 
5215 				/* this is really the type SEND, SEND_ONCE, etc. */
5216 				name = dsc->disposition;
5217 				dsc->disposition = ipc_object_copyin_type(name);
5218 
5219 				objects = (ipc_object_t *) dsc->address;
5220 
5221 				for (j = 0; j < dsc->count; j++) {
5222 					ipc_object_t object = objects[j];
5223 
5224 					if (!IO_VALID(object)) {
5225 						continue;
5226 					}
5227 
5228 					ipc_object_copyin_from_kernel(object, name);
5229 
5230 					if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
5231 					    ipc_port_check_circularity(ip_object_to_port(object),
5232 					    ip_object_to_port(remote))) {
5233 						hdr->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
5234 					}
5235 				}
5236 				break;
5237 			}
5238 			case MACH_MSG_GUARDED_PORT_DESCRIPTOR: {
5239 				mach_msg_guarded_port_descriptor_t *dsc = (typeof(dsc)) & saddr->guarded_port;
5240 				mach_msg_type_name_t disp = dsc->disposition;
5241 				ipc_object_t object = ip_to_object(dsc->name);
5242 				dsc->disposition = ipc_object_copyin_type(disp);
5243 				assert(dsc->flags == 0);
5244 
5245 				if (!IO_VALID(object)) {
5246 					break;
5247 				}
5248 
5249 				ipc_object_copyin_from_kernel(object, disp);
5250 				/*
5251 				 * avoid circularity when the destination is also
5252 				 * the kernel.  This check should be changed into an
5253 				 * assert when the new kobject model is in place since
5254 				 * ports will not be used in kernel to kernel chats
5255 				 */
5256 
5257 				/* do not lock remote port, use raw pointer comparison */
5258 				if (!ip_in_space_noauth(ip_object_to_port(remote), ipc_space_kernel)) {
5259 					/* remote port could be dead, in-transit or in an ipc space */
5260 					if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
5261 					    ipc_port_check_circularity(ip_object_to_port(object),
5262 					    ip_object_to_port(remote))) {
5263 						hdr->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
5264 					}
5265 				}
5266 				break;
5267 			}
5268 			default: {
5269 #if     MACH_ASSERT
5270 				panic("ipc_kmsg_copyin_from_kernel:  bad descriptor");
5271 #endif  /* MACH_ASSERT */
5272 			}
5273 			}
5274 		}
5275 	}
5276 
5277 	/* Add trailer and signature to the message */
5278 	ipc_kmsg_init_trailer(kmsg, TASK_NULL);
5279 	ikm_sign(kmsg);
5280 
5281 	return MACH_MSG_SUCCESS;
5282 }
5283 
5284 /*
5285  *	Routine:	ipc_kmsg_copyout_header
5286  *	Purpose:
5287  *		"Copy-out" port rights in the header of a message.
5288  *		Operates atomically; if it doesn't succeed the
5289  *		message header and the space are left untouched.
5290  *		If it does succeed the remote/local port fields
5291  *		contain port names instead of object pointers,
5292  *		and the bits field is updated.
5293  *	Conditions:
5294  *		Nothing locked.
5295  *	Returns:
5296  *		MACH_MSG_SUCCESS	Copied out port rights.
5297  *		MACH_RCV_INVALID_NOTIFY
5298  *			Notify is non-null and doesn't name a receive right.
5299  *			(Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
5300  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
5301  *			The space is dead.
5302  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
5303  *			No room in space for another name.
5304  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
5305  *			Couldn't allocate memory for the reply port.
5306  *		MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
5307  *			Couldn't allocate memory for the dead-name request.
5308  */
5309 
5310 static mach_msg_return_t
ipc_kmsg_copyout_header(ipc_kmsg_t kmsg,ipc_space_t space,mach_msg_option_t option)5311 ipc_kmsg_copyout_header(
5312 	ipc_kmsg_t              kmsg,
5313 	ipc_space_t             space,
5314 	mach_msg_option_t       option)
5315 {
5316 	mach_msg_header_t *msg = ikm_header(kmsg);
5317 	mach_msg_bits_t mbits = msg->msgh_bits;
5318 	ipc_port_t dest = msg->msgh_remote_port;
5319 
5320 	assert(IP_VALID(dest));
5321 
5322 	/*
5323 	 * While we still hold a reference on the received-from port,
5324 	 * process all send-possible notfications we received along with
5325 	 * the message.
5326 	 */
5327 	ipc_port_spnotify(dest);
5328 
5329 	{
5330 		mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
5331 		mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
5332 		mach_msg_type_name_t voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
5333 		ipc_port_t reply = msg->msgh_local_port;
5334 		ipc_port_t release_reply_port = IP_NULL;
5335 		mach_port_name_t dest_name, reply_name;
5336 
5337 		ipc_port_t voucher = ipc_kmsg_get_voucher_port(kmsg);
5338 		uintptr_t voucher_addr = 0;
5339 		ipc_port_t release_voucher_port = IP_NULL;
5340 		mach_port_name_t voucher_name;
5341 
5342 		uint32_t entries_held = 0;
5343 		boolean_t need_write_lock = FALSE;
5344 		ipc_object_copyout_flags_t reply_copyout_options = IPC_OBJECT_COPYOUT_FLAGS_NONE;
5345 		kern_return_t kr;
5346 
5347 		/*
5348 		 * Reserve any potentially needed entries in the target space.
5349 		 * We'll free any unused before unlocking the space.
5350 		 */
5351 		if (IP_VALID(reply)) {
5352 			entries_held++;
5353 			need_write_lock = TRUE;
5354 		}
5355 		if (IP_VALID(voucher)) {
5356 			assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
5357 
5358 			if ((option & MACH_RCV_VOUCHER) != 0) {
5359 				entries_held++;
5360 			}
5361 			need_write_lock = TRUE;
5362 			voucher_addr = unsafe_convert_port_to_voucher(voucher);
5363 		}
5364 
5365 		if (need_write_lock) {
5366 handle_reply_again:
5367 			is_write_lock(space);
5368 
5369 			while (entries_held) {
5370 				if (!is_active(space)) {
5371 					is_write_unlock(space);
5372 					return MACH_RCV_HEADER_ERROR |
5373 					       MACH_MSG_IPC_SPACE;
5374 				}
5375 
5376 				kr = ipc_entries_hold(space, entries_held);
5377 				if (KERN_SUCCESS == kr) {
5378 					break;
5379 				}
5380 
5381 				kr = ipc_entry_grow_table(space, ITS_SIZE_NONE);
5382 				if (KERN_SUCCESS != kr) {
5383 					return MACH_RCV_HEADER_ERROR |
5384 					       MACH_MSG_IPC_SPACE;
5385 				}
5386 				/* space was unlocked and relocked - retry */
5387 			}
5388 
5389 			/* Handle reply port. */
5390 			if (IP_VALID(reply)) {
5391 				ipc_port_t reply_subst = IP_NULL;
5392 				ipc_entry_t entry;
5393 
5394 				ip_mq_lock(reply);
5395 
5396 				/* Is the reply port still active and allowed to be copied out? */
5397 				if (!ip_active(reply) ||
5398 				    !ip_label_check(space, reply, reply_type,
5399 				    &reply_copyout_options, &reply_subst)) {
5400 					/* clear the context value */
5401 					reply->ip_reply_context = 0;
5402 					ip_mq_unlock(reply);
5403 
5404 					assert(reply_subst == IP_NULL);
5405 					release_reply_port = reply;
5406 					reply = IP_DEAD;
5407 					reply_name = MACH_PORT_DEAD;
5408 					goto done_with_reply;
5409 				}
5410 
5411 				/* is the kolabel requesting a substitution */
5412 				if (reply_subst != IP_NULL) {
5413 					/*
5414 					 * port is unlocked, its right consumed
5415 					 * space is unlocked
5416 					 */
5417 					assert(reply_type == MACH_MSG_TYPE_PORT_SEND);
5418 					msg->msgh_local_port = reply = reply_subst;
5419 					goto handle_reply_again;
5420 				}
5421 
5422 
5423 				/* Is there already an entry we can use? */
5424 				if ((reply_type != MACH_MSG_TYPE_PORT_SEND_ONCE) &&
5425 				    ipc_right_reverse(space, ip_to_object(reply), &reply_name, &entry)) {
5426 					assert(entry->ie_bits & MACH_PORT_TYPE_SEND_RECEIVE);
5427 				} else {
5428 					/* claim a held entry for the reply port */
5429 					assert(entries_held > 0);
5430 					entries_held--;
5431 					ipc_entry_claim(space, ip_to_object(reply),
5432 					    &reply_name, &entry);
5433 				}
5434 
5435 				/* space and reply port are locked and active */
5436 				ip_reference(reply);         /* hold onto the reply port */
5437 
5438 				/*
5439 				 * If the receiver would like to enforce strict reply
5440 				 * semantics, and the message looks like it expects a reply,
5441 				 * and contains a voucher, then link the context in the
5442 				 * voucher with the reply port so that the next message sent
5443 				 * to the reply port must come from a thread that has a
5444 				 * matching context (voucher).
5445 				 */
5446 				if (enforce_strict_reply && MACH_RCV_WITH_STRICT_REPLY(option) && IP_VALID(voucher)) {
5447 					if (ipc_kmsg_validate_reply_port_locked(reply, option) != KERN_SUCCESS) {
5448 						/* if the receiver isn't happy with the reply port: fail the receive. */
5449 						assert(!ip_is_pinned(reply));
5450 						ipc_entry_dealloc(space, ip_to_object(reply),
5451 						    reply_name, entry);
5452 						ip_mq_unlock(reply);
5453 						is_write_unlock(space);
5454 						ip_release(reply);
5455 						return MACH_RCV_INVALID_REPLY;
5456 					}
5457 					ipc_kmsg_link_reply_context_locked(reply, voucher);
5458 				} else {
5459 					/*
5460 					 * if the receive did not choose to participate
5461 					 * in the strict reply/RPC, then don't enforce
5462 					 * anything (as this could lead to booby-trapped
5463 					 * messages that kill the server).
5464 					 */
5465 					reply->ip_reply_context = 0;
5466 				}
5467 
5468 				kr = ipc_right_copyout(space, reply_name, entry,
5469 				    reply_type, IPC_OBJECT_COPYOUT_FLAGS_NONE, NULL, NULL,
5470 				    ip_to_object(reply));
5471 				assert(kr == KERN_SUCCESS);
5472 				/* reply port is unlocked */
5473 			} else {
5474 				reply_name = CAST_MACH_PORT_TO_NAME(reply);
5475 			}
5476 
5477 done_with_reply:
5478 
5479 			/* Handle voucher port. */
5480 			if (voucher_type != MACH_MSGH_BITS_ZERO) {
5481 				assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
5482 
5483 				if (!IP_VALID(voucher)) {
5484 					if ((option & MACH_RCV_VOUCHER) == 0) {
5485 						voucher_type = MACH_MSGH_BITS_ZERO;
5486 					}
5487 					voucher_name = MACH_PORT_NULL;
5488 					goto done_with_voucher;
5489 				}
5490 
5491 #if CONFIG_PREADOPT_TG
5492 				struct knote *kn = current_thread()->ith_knote;
5493 				if (kn == ITH_KNOTE_NULL || kn == ITH_KNOTE_PSEUDO) {
5494 					/*
5495 					 * We are not in this path of voucher copyout because of
5496 					 * kevent - we cannot expect a voucher preadopt happening on
5497 					 * this thread for this message later on
5498 					 */
5499 					KDBG_DEBUG(MACHDBG_CODE(DBG_MACH_THREAD_GROUP, MACH_THREAD_GROUP_PREADOPT_NA),
5500 					    thread_tid(current_thread()), 0, 0, 0);
5501 				}
5502 #endif
5503 
5504 				/* clear voucher from its hiding place back in the kmsg */
5505 				ipc_kmsg_clear_voucher_port(kmsg);
5506 
5507 				if ((option & MACH_RCV_VOUCHER) != 0) {
5508 					ipc_entry_t entry;
5509 
5510 					ip_mq_lock(voucher);
5511 
5512 					if (ipc_right_reverse(space, ip_to_object(voucher),
5513 					    &voucher_name, &entry)) {
5514 						assert(entry->ie_bits & MACH_PORT_TYPE_SEND);
5515 					} else {
5516 						assert(entries_held > 0);
5517 						entries_held--;
5518 						ipc_entry_claim(space, ip_to_object(voucher), &voucher_name, &entry);
5519 					}
5520 					/* space is locked and active */
5521 
5522 					assert(ip_kotype(voucher) == IKOT_VOUCHER);
5523 					kr = ipc_right_copyout(space, voucher_name, entry,
5524 					    MACH_MSG_TYPE_MOVE_SEND, IPC_OBJECT_COPYOUT_FLAGS_NONE,
5525 					    NULL, NULL, ip_to_object(voucher));
5526 					/* voucher port is unlocked */
5527 				} else {
5528 					voucher_type = MACH_MSGH_BITS_ZERO;
5529 					release_voucher_port = voucher;
5530 					voucher_name = MACH_PORT_NULL;
5531 				}
5532 			} else {
5533 				voucher_name = msg->msgh_voucher_port;
5534 			}
5535 
5536 done_with_voucher:
5537 
5538 			ip_mq_lock(dest);
5539 			is_write_unlock(space);
5540 		} else {
5541 			/*
5542 			 *	No reply or voucher port!  This is an easy case.
5543 			 *
5544 			 *	We only need to check that the space is still
5545 			 *	active once we locked the destination:
5546 			 *
5547 			 *	- if the space holds a receive right for `dest`,
5548 			 *	  then holding the port lock means we can't fail
5549 			 *	  to notice if the space went dead because
5550 			 *	  the is_write_unlock() will pair with
5551 			 *	  os_atomic_barrier_before_lock_acquire() + ip_mq_lock().
5552 			 *
5553 			 *	- if this space doesn't hold a receive right
5554 			 *	  for `dest`, then `dest->ip_receiver` points
5555 			 *	  elsewhere, and ipc_object_copyout_dest() will
5556 			 *	  handle this situation, and failing to notice
5557 			 *	  that the space was dead is accetable.
5558 			 */
5559 
5560 			os_atomic_barrier_before_lock_acquire();
5561 			ip_mq_lock(dest);
5562 			if (!is_active(space)) {
5563 				ip_mq_unlock(dest);
5564 				return MACH_RCV_HEADER_ERROR | MACH_MSG_IPC_SPACE;
5565 			}
5566 
5567 			reply_name = CAST_MACH_PORT_TO_NAME(reply);
5568 
5569 			if (voucher_type != MACH_MSGH_BITS_ZERO) {
5570 				assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
5571 				if ((option & MACH_RCV_VOUCHER) == 0) {
5572 					voucher_type = MACH_MSGH_BITS_ZERO;
5573 				}
5574 				voucher_name = MACH_PORT_NULL;
5575 			} else {
5576 				voucher_name = msg->msgh_voucher_port;
5577 			}
5578 		}
5579 
5580 		/*
5581 		 *	At this point, the space is unlocked and the destination
5582 		 *	port is locked.
5583 		 *	reply_name is taken care of; we still need dest_name.
5584 		 *	We still hold a ref for reply (if it is valid).
5585 		 *
5586 		 *	If the space holds receive rights for the destination,
5587 		 *	we return its name for the right.  Otherwise the task
5588 		 *	managed to destroy or give away the receive right between
5589 		 *	receiving the message and this copyout.  If the destination
5590 		 *	is dead, return MACH_PORT_DEAD, and if the receive right
5591 		 *	exists somewhere else (another space, in transit)
5592 		 *	return MACH_PORT_NULL.
5593 		 *
5594 		 *	Making this copyout operation atomic with the previous
5595 		 *	copyout of the reply port is a bit tricky.  If there was
5596 		 *	no real reply port (it wasn't IP_VALID) then this isn't
5597 		 *	an issue.  If the reply port was dead at copyout time,
5598 		 *	then we are OK, because if dest is dead we serialize
5599 		 *	after the death of both ports and if dest is alive
5600 		 *	we serialize after reply died but before dest's (later) death.
5601 		 *	So assume reply was alive when we copied it out.  If dest
5602 		 *	is alive, then we are OK because we serialize before
5603 		 *	the ports' deaths.  So assume dest is dead when we look at it.
5604 		 *	If reply dies/died after dest, then we are OK because
5605 		 *	we serialize after dest died but before reply dies.
5606 		 *	So the hard case is when reply is alive at copyout,
5607 		 *	dest is dead at copyout, and reply died before dest died.
5608 		 *	In this case pretend that dest is still alive, so
5609 		 *	we serialize while both ports are alive.
5610 		 *
5611 		 *	Because the space lock is held across the copyout of reply
5612 		 *	and locking dest, the receive right for dest can't move
5613 		 *	in or out of the space while the copyouts happen, so
5614 		 *	that isn't an atomicity problem.  In the last hard case
5615 		 *	above, this implies that when dest is dead that the
5616 		 *	space couldn't have had receive rights for dest at
5617 		 *	the time reply was copied-out, so when we pretend
5618 		 *	that dest is still alive, we can return MACH_PORT_NULL.
5619 		 *
5620 		 *	If dest == reply, then we have to make it look like
5621 		 *	either both copyouts happened before the port died,
5622 		 *	or both happened after the port died.  This special
5623 		 *	case works naturally if the timestamp comparison
5624 		 *	is done correctly.
5625 		 */
5626 
5627 		if (ip_active(dest)) {
5628 			ipc_object_copyout_dest(space, ip_to_object(dest),
5629 			    dest_type, &dest_name);
5630 			/* dest is unlocked */
5631 		} else {
5632 			ipc_port_timestamp_t timestamp;
5633 
5634 			timestamp = ip_get_death_time(dest);
5635 			ip_mq_unlock(dest);
5636 			ip_release(dest);
5637 
5638 			if (IP_VALID(reply)) {
5639 				ip_mq_lock(reply);
5640 				if (ip_active(reply) ||
5641 				    IP_TIMESTAMP_ORDER(timestamp,
5642 				    ip_get_death_time(reply))) {
5643 					dest_name = MACH_PORT_DEAD;
5644 				} else {
5645 					dest_name = MACH_PORT_NULL;
5646 				}
5647 				ip_mq_unlock(reply);
5648 			} else {
5649 				dest_name = MACH_PORT_DEAD;
5650 			}
5651 		}
5652 
5653 		if (IP_VALID(reply)) {
5654 			ip_release(reply);
5655 		}
5656 
5657 		if (IP_VALID(release_reply_port)) {
5658 			if (reply_type == MACH_MSG_TYPE_PORT_SEND_ONCE) {
5659 				ipc_port_release_sonce(release_reply_port);
5660 			} else {
5661 				ipc_port_release_send(release_reply_port);
5662 			}
5663 		}
5664 
5665 		if ((option & MACH_RCV_VOUCHER) != 0) {
5666 			KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_RECV) | DBG_FUNC_NONE,
5667 			    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
5668 			    (uintptr_t)msg->msgh_bits,
5669 			    (uintptr_t)msg->msgh_id,
5670 			    VM_KERNEL_ADDRPERM(voucher_addr), 0);
5671 		} else {
5672 			KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_MSG_RECV_VOUCHER_REFUSED) | DBG_FUNC_NONE,
5673 			    VM_KERNEL_ADDRPERM((uintptr_t)kmsg),
5674 			    (uintptr_t)msg->msgh_bits,
5675 			    (uintptr_t)msg->msgh_id,
5676 			    VM_KERNEL_ADDRPERM(voucher_addr), 0);
5677 		}
5678 
5679 		if (IP_VALID(release_voucher_port)) {
5680 			ipc_port_release_send(release_voucher_port);
5681 		}
5682 
5683 		msg->msgh_bits = MACH_MSGH_BITS_SET(reply_type, dest_type,
5684 		    voucher_type, mbits);
5685 		msg->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
5686 		msg->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
5687 		msg->msgh_voucher_port = voucher_name;
5688 	}
5689 
5690 	return MACH_MSG_SUCCESS;
5691 }
5692 
5693 /*
5694  *	Routine:	ipc_kmsg_copyout_object
5695  *	Purpose:
5696  *		Copy-out a port right.  Always returns a name,
5697  *		even for unsuccessful return codes.  Always
5698  *		consumes the supplied object.
5699  *	Conditions:
5700  *		Nothing locked.
5701  *	Returns:
5702  *		MACH_MSG_SUCCESS	The space acquired the right
5703  *			(name is valid) or the object is dead (MACH_PORT_DEAD).
5704  *		MACH_MSG_IPC_SPACE	No room in space for the right,
5705  *			or the space is dead.  (Name is MACH_PORT_NULL.)
5706  *		MACH_MSG_IPC_KERNEL	Kernel resource shortage.
5707  *			(Name is MACH_PORT_NULL.)
5708  */
5709 static mach_msg_return_t
ipc_kmsg_copyout_object(ipc_space_t space,ipc_object_t object,mach_msg_type_name_t msgt_name,mach_port_context_t * context,mach_msg_guard_flags_t * guard_flags,mach_port_name_t * namep)5710 ipc_kmsg_copyout_object(
5711 	ipc_space_t             space,
5712 	ipc_object_t            object,
5713 	mach_msg_type_name_t    msgt_name,
5714 	mach_port_context_t     *context,
5715 	mach_msg_guard_flags_t  *guard_flags,
5716 	mach_port_name_t        *namep)
5717 {
5718 	kern_return_t kr;
5719 
5720 	if (!IO_VALID(object)) {
5721 		*namep = CAST_MACH_PORT_TO_NAME(object);
5722 		return MACH_MSG_SUCCESS;
5723 	}
5724 
5725 	kr = ipc_object_copyout(space, object, msgt_name, IPC_OBJECT_COPYOUT_FLAGS_NONE,
5726 	    context, guard_flags, namep);
5727 	if (kr != KERN_SUCCESS) {
5728 		if (kr == KERN_INVALID_CAPABILITY) {
5729 			*namep = MACH_PORT_DEAD;
5730 		} else {
5731 			*namep = MACH_PORT_NULL;
5732 
5733 			if (kr == KERN_RESOURCE_SHORTAGE) {
5734 				return MACH_MSG_IPC_KERNEL;
5735 			} else {
5736 				return MACH_MSG_IPC_SPACE;
5737 			}
5738 		}
5739 	}
5740 
5741 	return MACH_MSG_SUCCESS;
5742 }
5743 
5744 /*
5745  *	Routine:	ipc_kmsg_copyout_reply_object
5746  *	Purpose:
5747  *      Kernel swallows the send-once right associated with reply port.
5748  *      Always returns a name, even for unsuccessful return codes.
5749  *      Returns
5750  *          MACH_MSG_SUCCESS Returns name of receive right for reply port.
5751  *              Name is valid if the space acquired the right and msgt_name would be changed from MOVE_SO to MAKE_SO.
5752  *              Name is MACH_PORT_DEAD if the object is dead.
5753  *              Name is MACH_PORT_NULL if its entry could not be found in task's ipc space.
5754  *          MACH_MSG_IPC_SPACE
5755  *              The space is dead.  (Name is MACH_PORT_NULL.)
5756  *	Conditions:
5757  *      Nothing locked.
5758  */
5759 static mach_msg_return_t
ipc_kmsg_copyout_reply_object(ipc_space_t space,ipc_object_t object,mach_msg_type_name_t * msgt_name,mach_port_name_t * namep)5760 ipc_kmsg_copyout_reply_object(
5761 	ipc_space_t             space,
5762 	ipc_object_t            object,
5763 	mach_msg_type_name_t    *msgt_name,
5764 	mach_port_name_t        *namep)
5765 {
5766 	ipc_port_t port;
5767 	ipc_entry_t entry;
5768 	kern_return_t kr;
5769 
5770 	if (!IO_VALID(object)) {
5771 		*namep = CAST_MACH_PORT_TO_NAME(object);
5772 		return MACH_MSG_SUCCESS;
5773 	}
5774 
5775 	port = ip_object_to_port(object);
5776 
5777 	assert(ip_is_reply_port(port));
5778 	assert(*msgt_name == MACH_MSG_TYPE_PORT_SEND_ONCE);
5779 
5780 	is_write_lock(space);
5781 
5782 	if (!is_active(space)) {
5783 		ipc_port_release_sonce(port);
5784 		is_write_unlock(space);
5785 		*namep = MACH_PORT_NULL;
5786 		return MACH_MSG_IPC_SPACE;
5787 	}
5788 
5789 	io_lock(object);
5790 
5791 	if (!io_active(object)) {
5792 		*namep = MACH_PORT_DEAD;
5793 		kr = MACH_MSG_SUCCESS;
5794 		goto out;
5795 	}
5796 
5797 	/* space is locked and active. object is locked and active. */
5798 	if (!ipc_right_reverse(space, object, namep, &entry)) {
5799 		*namep = MACH_PORT_NULL;
5800 		kr = MACH_MSG_SUCCESS;
5801 		goto out;
5802 	}
5803 
5804 	assert(entry->ie_bits & MACH_PORT_TYPE_RECEIVE);
5805 
5806 	*msgt_name = MACH_MSG_TYPE_MAKE_SEND_ONCE;
5807 	ipc_port_release_sonce_and_unlock(port);
5808 	/* object is unlocked. */
5809 
5810 	is_write_unlock(space);
5811 
5812 	return MACH_MSG_SUCCESS;
5813 
5814 out:
5815 
5816 	/* space and object are locked. */
5817 	ipc_port_release_sonce_and_unlock(port);
5818 
5819 	is_write_unlock(space);
5820 
5821 	return kr;
5822 }
5823 
5824 static mach_msg_descriptor_t *
ipc_kmsg_copyout_port_descriptor(mach_msg_descriptor_t * dsc,mach_msg_descriptor_t * dest_dsc,ipc_space_t space,kern_return_t * mr)5825 ipc_kmsg_copyout_port_descriptor(
5826 	mach_msg_descriptor_t   *dsc,
5827 	mach_msg_descriptor_t   *dest_dsc,
5828 	ipc_space_t             space,
5829 	kern_return_t           *mr)
5830 {
5831 	mach_msg_user_port_descriptor_t *user_dsc;
5832 	mach_port_t             port;
5833 	mach_port_name_t        name;
5834 	mach_msg_type_name_t    disp;
5835 
5836 	/* Copyout port right carried in the message */
5837 	port = dsc->port.name;
5838 	disp = dsc->port.disposition;
5839 	*mr |= ipc_kmsg_copyout_object(space,
5840 	    ip_to_object(port), disp, NULL, NULL, &name);
5841 
5842 	// point to the start of this port descriptor
5843 	user_dsc = ((mach_msg_user_port_descriptor_t *)dest_dsc - 1);
5844 	bzero((void *)user_dsc, sizeof(*user_dsc));
5845 	user_dsc->name = CAST_MACH_PORT_TO_NAME(name);
5846 	user_dsc->disposition = disp;
5847 	user_dsc->type = MACH_MSG_PORT_DESCRIPTOR;
5848 
5849 	return (mach_msg_descriptor_t *)user_dsc;
5850 }
5851 
5852 static mach_msg_descriptor_t *
ipc_kmsg_copyout_ool_descriptor(mach_msg_ool_descriptor_t * dsc,mach_msg_descriptor_t * user_dsc,int is_64bit,vm_map_t map,mach_msg_return_t * mr)5853 ipc_kmsg_copyout_ool_descriptor(
5854 	mach_msg_ool_descriptor_t   *dsc,
5855 	mach_msg_descriptor_t       *user_dsc,
5856 	int                         is_64bit,
5857 	vm_map_t                    map,
5858 	mach_msg_return_t           *mr)
5859 {
5860 	vm_map_copy_t               copy;
5861 	vm_map_address_t            rcv_addr;
5862 	mach_msg_copy_options_t     copy_options;
5863 	vm_map_size_t               size;
5864 	mach_msg_descriptor_type_t  dsc_type;
5865 	boolean_t                   misaligned = FALSE;
5866 
5867 	copy = (vm_map_copy_t)dsc->address;
5868 	size = (vm_map_size_t)dsc->size;
5869 	copy_options = dsc->copy;
5870 	assert(copy_options != MACH_MSG_KALLOC_COPY_T);
5871 	dsc_type = dsc->type;
5872 
5873 	if (copy != VM_MAP_COPY_NULL) {
5874 		kern_return_t kr;
5875 
5876 		rcv_addr = 0;
5877 		if (vm_map_copy_validate_size(map, copy, &size) == FALSE) {
5878 			panic("Inconsistent OOL/copyout size on %p: expected %d, got %lld @%p",
5879 			    dsc, dsc->size, (unsigned long long)copy->size, copy);
5880 		}
5881 
5882 		if ((copy->type == VM_MAP_COPY_ENTRY_LIST) &&
5883 		    (trunc_page(copy->offset) != copy->offset ||
5884 		    round_page(dsc->size) != dsc->size)) {
5885 			misaligned = TRUE;
5886 		}
5887 
5888 		if (misaligned) {
5889 			mach_vm_offset_t rounded_addr;
5890 			vm_map_size_t   rounded_size;
5891 			vm_map_offset_t effective_page_mask, effective_page_size;
5892 
5893 			effective_page_mask = VM_MAP_PAGE_MASK(map);
5894 			effective_page_size = effective_page_mask + 1;
5895 
5896 			rounded_size = vm_map_round_page(copy->offset + size, effective_page_mask) - vm_map_trunc_page(copy->offset, effective_page_mask);
5897 
5898 			kr = mach_vm_allocate_kernel(map, &rounded_addr,
5899 			    rounded_size, VM_FLAGS_ANYWHERE, VM_KERN_MEMORY_IPC);
5900 
5901 			if (kr == KERN_SUCCESS) {
5902 				/*
5903 				 * vm_map_copy_overwrite does a full copy
5904 				 * if size is too small to optimize.
5905 				 * So we tried skipping the offset adjustment
5906 				 * if we fail the 'size' test.
5907 				 *
5908 				 * if (size >= VM_MAP_COPY_OVERWRITE_OPTIMIZATION_THRESHOLD_PAGES * effective_page_size) {
5909 				 *
5910 				 * This resulted in leaked memory especially on the
5911 				 * older watches (16k user - 4k kernel) because we
5912 				 * would do a physical copy into the start of this
5913 				 * rounded range but could leak part of it
5914 				 * on deallocation if the 'size' being deallocated
5915 				 * does not cover the full range. So instead we do
5916 				 * the misalignment adjustment always so that on
5917 				 * deallocation we will remove the full range.
5918 				 */
5919 				if ((rounded_addr & effective_page_mask) !=
5920 				    (copy->offset & effective_page_mask)) {
5921 					/*
5922 					 * Need similar mis-alignment of source and destination...
5923 					 */
5924 					rounded_addr += (copy->offset & effective_page_mask);
5925 
5926 					assert((rounded_addr & effective_page_mask) == (copy->offset & effective_page_mask));
5927 				}
5928 				rcv_addr = rounded_addr;
5929 
5930 				kr = vm_map_copy_overwrite(map, rcv_addr, copy, size, FALSE);
5931 			}
5932 		} else {
5933 			kr = vm_map_copyout_size(map, &rcv_addr, copy, size);
5934 		}
5935 		if (kr != KERN_SUCCESS) {
5936 			if (kr == KERN_RESOURCE_SHORTAGE) {
5937 				*mr |= MACH_MSG_VM_KERNEL;
5938 			} else {
5939 				*mr |= MACH_MSG_VM_SPACE;
5940 			}
5941 			vm_map_copy_discard(copy);
5942 			rcv_addr = 0;
5943 			size = 0;
5944 		}
5945 	} else {
5946 		rcv_addr = 0;
5947 		size = 0;
5948 	}
5949 
5950 	/*
5951 	 * Now update the descriptor as the user would see it.
5952 	 * This may require expanding the descriptor to the user
5953 	 * visible size.  There is already space allocated for
5954 	 * this in what naddr points to.
5955 	 */
5956 	if (is_64bit) {
5957 		mach_msg_ool_descriptor64_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
5958 		user_ool_dsc--;
5959 		bzero((void *)user_ool_dsc, sizeof(*user_ool_dsc));
5960 
5961 		user_ool_dsc->address = rcv_addr;
5962 		user_ool_dsc->deallocate = (copy_options == MACH_MSG_VIRTUAL_COPY) ?
5963 		    TRUE : FALSE;
5964 		user_ool_dsc->copy = copy_options;
5965 		user_ool_dsc->type = dsc_type;
5966 		user_ool_dsc->size = (mach_msg_size_t)size;
5967 
5968 		user_dsc = (typeof(user_dsc))user_ool_dsc;
5969 	} else {
5970 		mach_msg_ool_descriptor32_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
5971 		user_ool_dsc--;
5972 		bzero((void *)user_ool_dsc, sizeof(*user_ool_dsc));
5973 
5974 		user_ool_dsc->address = CAST_DOWN_EXPLICIT(uint32_t, rcv_addr);
5975 		user_ool_dsc->size = (mach_msg_size_t)size;
5976 		user_ool_dsc->deallocate = (copy_options == MACH_MSG_VIRTUAL_COPY) ?
5977 		    TRUE : FALSE;
5978 		user_ool_dsc->copy = copy_options;
5979 		user_ool_dsc->type = dsc_type;
5980 
5981 		user_dsc = (typeof(user_dsc))user_ool_dsc;
5982 	}
5983 	return user_dsc;
5984 }
5985 
5986 static mach_msg_descriptor_t *
ipc_kmsg_copyout_ool_ports_descriptor(mach_msg_ool_ports_descriptor_t * dsc,mach_msg_descriptor_t * user_dsc,int is_64bit,vm_map_t map,ipc_space_t space,ipc_kmsg_t kmsg,mach_msg_return_t * mr)5987 ipc_kmsg_copyout_ool_ports_descriptor(mach_msg_ool_ports_descriptor_t *dsc,
5988     mach_msg_descriptor_t *user_dsc,
5989     int is_64bit,
5990     vm_map_t map,
5991     ipc_space_t space,
5992     ipc_kmsg_t kmsg,
5993     mach_msg_return_t *mr)
5994 {
5995 	mach_vm_offset_t        rcv_addr = 0;
5996 	mach_msg_type_name_t    disp;
5997 	mach_msg_type_number_t  count, i;
5998 	vm_size_t               ports_length, names_length;
5999 	mach_msg_copy_options_t copy_options = MACH_MSG_VIRTUAL_COPY;
6000 
6001 	count = dsc->count;
6002 	disp = dsc->disposition;
6003 	ports_length = count * sizeof(mach_port_t);
6004 	names_length = count * sizeof(mach_port_name_t);
6005 
6006 	if (ports_length != 0 && dsc->address != 0) {
6007 		if (copy_options == MACH_MSG_VIRTUAL_COPY) {
6008 			/*
6009 			 * Dynamically allocate the region
6010 			 */
6011 			vm_tag_t tag;
6012 			if (vm_kernel_map_is_kernel(map)) {
6013 				tag = VM_KERN_MEMORY_IPC;
6014 			} else {
6015 				tag = VM_MEMORY_MACH_MSG;
6016 			}
6017 
6018 			kern_return_t kr;
6019 			if ((kr = mach_vm_allocate_kernel(map, &rcv_addr,
6020 			    (mach_vm_size_t)names_length,
6021 			    VM_FLAGS_ANYWHERE, tag)) != KERN_SUCCESS) {
6022 				ipc_kmsg_clean_body(kmsg, 1, (mach_msg_descriptor_t *)dsc);
6023 				rcv_addr = 0;
6024 
6025 				if (kr == KERN_RESOURCE_SHORTAGE) {
6026 					*mr |= MACH_MSG_VM_KERNEL;
6027 				} else {
6028 					*mr |= MACH_MSG_VM_SPACE;
6029 				}
6030 			}
6031 		}
6032 
6033 		/*
6034 		 * Handle the port rights and copy out the names
6035 		 * for those rights out to user-space.
6036 		 */
6037 		if (rcv_addr != 0) {
6038 			ipc_object_t *objects = (ipc_object_t *) dsc->address;
6039 			mach_port_name_t *names = (mach_port_name_t *) dsc->address;
6040 
6041 			/* copyout port rights carried in the message */
6042 
6043 			for (i = 0; i < count; i++) {
6044 				ipc_object_t object = objects[i];
6045 
6046 				*mr |= ipc_kmsg_copyout_object(space, object,
6047 				    disp, NULL, NULL, &names[i]);
6048 			}
6049 
6050 			/* copyout to memory allocated above */
6051 			void *data = dsc->address;
6052 			if (copyoutmap(map, data, rcv_addr, names_length) != KERN_SUCCESS) {
6053 				*mr |= MACH_MSG_VM_SPACE;
6054 			}
6055 			kfree_type(mach_port_t, count, data);
6056 		}
6057 	} else {
6058 		rcv_addr = 0;
6059 	}
6060 
6061 	/*
6062 	 * Now update the descriptor based on the information
6063 	 * calculated above.
6064 	 */
6065 	if (is_64bit) {
6066 		mach_msg_ool_ports_descriptor64_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
6067 		user_ool_dsc--;
6068 		bzero((void *)user_ool_dsc, sizeof(*user_ool_dsc));
6069 
6070 		user_ool_dsc->address = rcv_addr;
6071 		user_ool_dsc->deallocate = (copy_options == MACH_MSG_VIRTUAL_COPY) ?
6072 		    TRUE : FALSE;
6073 		user_ool_dsc->copy = copy_options;
6074 		user_ool_dsc->disposition = disp;
6075 		user_ool_dsc->type = MACH_MSG_OOL_PORTS_DESCRIPTOR;
6076 		user_ool_dsc->count = count;
6077 
6078 		user_dsc = (typeof(user_dsc))user_ool_dsc;
6079 	} else {
6080 		mach_msg_ool_ports_descriptor32_t *user_ool_dsc = (typeof(user_ool_dsc))user_dsc;
6081 		user_ool_dsc--;
6082 		bzero((void *)user_ool_dsc, sizeof(*user_ool_dsc));
6083 
6084 		user_ool_dsc->address = CAST_DOWN_EXPLICIT(uint32_t, rcv_addr);
6085 		user_ool_dsc->count = count;
6086 		user_ool_dsc->deallocate = (copy_options == MACH_MSG_VIRTUAL_COPY) ?
6087 		    TRUE : FALSE;
6088 		user_ool_dsc->copy = copy_options;
6089 		user_ool_dsc->disposition = disp;
6090 		user_ool_dsc->type = MACH_MSG_OOL_PORTS_DESCRIPTOR;
6091 
6092 		user_dsc = (typeof(user_dsc))user_ool_dsc;
6093 	}
6094 	return user_dsc;
6095 }
6096 
6097 static mach_msg_descriptor_t *
ipc_kmsg_copyout_guarded_port_descriptor(mach_msg_guarded_port_descriptor_t * dsc,mach_msg_descriptor_t * dest_dsc,int is_64bit,__unused ipc_kmsg_t kmsg,ipc_space_t space,mach_msg_option_t option,kern_return_t * mr)6098 ipc_kmsg_copyout_guarded_port_descriptor(
6099 	mach_msg_guarded_port_descriptor_t *dsc,
6100 	mach_msg_descriptor_t *dest_dsc,
6101 	int is_64bit,
6102 	__unused ipc_kmsg_t  kmsg,
6103 	ipc_space_t space,
6104 	mach_msg_option_t option,
6105 	kern_return_t *mr)
6106 {
6107 	mach_port_t                 port;
6108 	mach_port_name_t            name = MACH_PORT_NULL;
6109 	mach_msg_type_name_t        disp;
6110 	mach_msg_guard_flags_t      guard_flags;
6111 	mach_port_context_t         context;
6112 
6113 	/* Copyout port right carried in the message */
6114 	port = dsc->name;
6115 	disp = dsc->disposition;
6116 	guard_flags = dsc->flags;
6117 	context = 0;
6118 
6119 	/* Currently kernel_task doesnt support receiving guarded port descriptors */
6120 	struct knote *kn = current_thread()->ith_knote;
6121 	if ((kn != ITH_KNOTE_PSEUDO) && ((option & MACH_RCV_GUARDED_DESC) == 0)) {
6122 #if DEVELOPMENT || DEBUG
6123 		/*
6124 		 * Simulated crash needed for debugging, notifies the receiver to opt into receiving
6125 		 * guarded descriptors.
6126 		 */
6127 		mach_port_guard_exception(current_thread()->ith_receiver_name,
6128 		    0, 0, kGUARD_EXC_RCV_GUARDED_DESC);
6129 #endif
6130 		KDBG(MACHDBG_CODE(DBG_MACH_IPC, MACH_IPC_DESTROY_GUARDED_DESC), current_thread()->ith_receiver_name,
6131 		    VM_KERNEL_ADDRPERM(port), disp, guard_flags);
6132 		ipc_object_destroy(ip_to_object(port), disp);
6133 		mach_msg_user_port_descriptor_t *user_dsc = (typeof(user_dsc))dest_dsc;
6134 		user_dsc--;         // point to the start of this port descriptor
6135 		bzero((void *)user_dsc, sizeof(*user_dsc));
6136 		user_dsc->name = name;
6137 		user_dsc->disposition = disp;
6138 		user_dsc->type = MACH_MSG_PORT_DESCRIPTOR;
6139 		dest_dsc = (typeof(dest_dsc))user_dsc;
6140 	} else {
6141 		*mr |= ipc_kmsg_copyout_object(space,
6142 		    ip_to_object(port), disp, &context, &guard_flags, &name);
6143 
6144 		if (!is_64bit) {
6145 			mach_msg_guarded_port_descriptor32_t *user_dsc = (typeof(user_dsc))dest_dsc;
6146 			user_dsc--;         // point to the start of this port descriptor
6147 			bzero((void *)user_dsc, sizeof(*user_dsc));
6148 			user_dsc->name = name;
6149 			user_dsc->flags = guard_flags;
6150 			user_dsc->disposition = disp;
6151 			user_dsc->type = MACH_MSG_GUARDED_PORT_DESCRIPTOR;
6152 			user_dsc->context = CAST_DOWN_EXPLICIT(uint32_t, context);
6153 			dest_dsc = (typeof(dest_dsc))user_dsc;
6154 		} else {
6155 			mach_msg_guarded_port_descriptor64_t *user_dsc = (typeof(user_dsc))dest_dsc;
6156 			user_dsc--;         // point to the start of this port descriptor
6157 			bzero((void *)user_dsc, sizeof(*user_dsc));
6158 			user_dsc->name = name;
6159 			user_dsc->flags = guard_flags;
6160 			user_dsc->disposition = disp;
6161 			user_dsc->type = MACH_MSG_GUARDED_PORT_DESCRIPTOR;
6162 			user_dsc->context = context;
6163 			dest_dsc = (typeof(dest_dsc))user_dsc;
6164 		}
6165 	}
6166 
6167 	return (mach_msg_descriptor_t *)dest_dsc;
6168 }
6169 
6170 
6171 /*
6172  *	Routine:	ipc_kmsg_copyout_body
6173  *	Purpose:
6174  *		"Copy-out" port rights and out-of-line memory
6175  *		in the body of a message.
6176  *
6177  *		The error codes are a combination of special bits.
6178  *		The copyout proceeds despite errors.
6179  *	Conditions:
6180  *		Nothing locked.
6181  *	Returns:
6182  *		MACH_MSG_SUCCESS	Successful copyout.
6183  *		MACH_MSG_IPC_SPACE	No room for port right in name space.
6184  *		MACH_MSG_VM_SPACE	No room for memory in address space.
6185  *		MACH_MSG_IPC_KERNEL	Resource shortage handling port right.
6186  *		MACH_MSG_VM_KERNEL	Resource shortage handling memory.
6187  *		MACH_MSG_INVALID_RT_DESCRIPTOR Descriptor incompatible with RT
6188  */
6189 
6190 static mach_msg_return_t
ipc_kmsg_copyout_body(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map,mach_msg_option_t option)6191 ipc_kmsg_copyout_body(
6192 	ipc_kmsg_t              kmsg,
6193 	ipc_space_t             space,
6194 	vm_map_t                map,
6195 	mach_msg_option_t       option)
6196 {
6197 	mach_msg_body_t             *body;
6198 	mach_msg_descriptor_t       *kern_dsc, *user_dsc;
6199 	mach_msg_type_number_t      dsc_count;
6200 	mach_msg_return_t           mr = MACH_MSG_SUCCESS;
6201 	boolean_t                   is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
6202 	mach_msg_header_t           *hdr = ikm_header(kmsg);
6203 
6204 	body = (mach_msg_body_t *) (hdr + 1);
6205 	dsc_count = body->msgh_descriptor_count;
6206 	kern_dsc = (mach_msg_descriptor_t *) (body + 1);
6207 	/* Point user_dsc just after the end of all the descriptors */
6208 	user_dsc = &kern_dsc[dsc_count];
6209 
6210 	assert(current_task() != kernel_task);
6211 
6212 	/* Now process the descriptors - in reverse order */
6213 	for (mach_msg_type_number_t i = dsc_count; i-- > 0;) {
6214 		switch (kern_dsc[i].type.type) {
6215 		case MACH_MSG_PORT_DESCRIPTOR:
6216 			user_dsc = ipc_kmsg_copyout_port_descriptor(&kern_dsc[i],
6217 			    user_dsc, space, &mr);
6218 			break;
6219 		case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
6220 		case MACH_MSG_OOL_DESCRIPTOR:
6221 			user_dsc = ipc_kmsg_copyout_ool_descriptor(
6222 				(mach_msg_ool_descriptor_t *)&kern_dsc[i],
6223 				user_dsc, is_task_64bit, map, &mr);
6224 			break;
6225 		case MACH_MSG_OOL_PORTS_DESCRIPTOR:
6226 			user_dsc = ipc_kmsg_copyout_ool_ports_descriptor(
6227 				(mach_msg_ool_ports_descriptor_t *)&kern_dsc[i],
6228 				user_dsc, is_task_64bit, map, space, kmsg, &mr);
6229 			break;
6230 		case MACH_MSG_GUARDED_PORT_DESCRIPTOR:
6231 			user_dsc = ipc_kmsg_copyout_guarded_port_descriptor(
6232 				(mach_msg_guarded_port_descriptor_t *)&kern_dsc[i],
6233 				user_dsc, is_task_64bit, kmsg, space, option, &mr);
6234 			break;
6235 		default:
6236 			panic("untyped IPC copyout body: invalid message descriptor");
6237 		}
6238 	}
6239 
6240 	assert((vm_offset_t)kern_dsc == (vm_offset_t)hdr + sizeof(mach_msg_base_t));
6241 
6242 	if (user_dsc != kern_dsc) {
6243 		vm_offset_t dsc_adjust = (vm_offset_t)user_dsc - (vm_offset_t)kern_dsc;
6244 		/* update the message size for the smaller user representation */
6245 		hdr->msgh_size -= (mach_msg_size_t)dsc_adjust;
6246 
6247 		if (ikm_is_linear(kmsg)) {
6248 			/* trailer has been initialized during send - memmove it too. */
6249 			memmove((char *)kern_dsc,
6250 			    user_dsc, hdr->msgh_size - sizeof(mach_msg_base_t) + MAX_TRAILER_SIZE);
6251 		} else {
6252 			/* just memmove the descriptors following the header */
6253 			memmove((char *)kern_dsc,
6254 			    user_dsc, ikm_total_desc_size(kmsg, current_map(), dsc_adjust, 0, true));
6255 		}
6256 	}
6257 
6258 	return mr;
6259 }
6260 
6261 /*
6262  *	Routine:	ipc_kmsg_copyout_size
6263  *	Purpose:
6264  *		Compute the size of the message as copied out to the given
6265  *		map. If the destination map's pointers are a different size
6266  *		than the kernel's, we have to allow for expansion/
6267  *		contraction of the descriptors as appropriate.
6268  *	Conditions:
6269  *		Nothing locked.
6270  *	Returns:
6271  *		size of the message as it would be received.
6272  */
6273 
6274 mach_msg_size_t
ipc_kmsg_copyout_size(ipc_kmsg_t kmsg,vm_map_t map)6275 ipc_kmsg_copyout_size(
6276 	ipc_kmsg_t              kmsg,
6277 	vm_map_t                map)
6278 {
6279 	mach_msg_size_t         send_size;
6280 	mach_msg_header_t       *hdr;
6281 
6282 	hdr = ikm_header(kmsg);
6283 	send_size = hdr->msgh_size - USER_HEADER_SIZE_DELTA;
6284 
6285 	boolean_t is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
6286 
6287 	if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
6288 		mach_msg_body_t *body;
6289 		mach_msg_descriptor_t *saddr, *eaddr;
6290 
6291 		body = (mach_msg_body_t *) (hdr + 1);
6292 		saddr = (mach_msg_descriptor_t *) (body + 1);
6293 		eaddr = saddr + body->msgh_descriptor_count;
6294 
6295 		send_size -= KERNEL_DESC_SIZE * body->msgh_descriptor_count;
6296 		for (; saddr < eaddr; saddr++) {
6297 			send_size += ikm_user_desc_size(saddr->type.type, is_task_64bit);
6298 		}
6299 	}
6300 	return send_size;
6301 }
6302 
6303 /*
6304  *	Routine:	ipc_kmsg_copyout
6305  *	Purpose:
6306  *		"Copy-out" port rights and out-of-line memory
6307  *		in the message.
6308  *	Conditions:
6309  *		Nothing locked.
6310  *	Returns:
6311  *		MACH_MSG_SUCCESS	Copied out all rights and memory.
6312  *		MACH_RCV_HEADER_ERROR + special bits
6313  *			Rights and memory in the message are intact.
6314  *		MACH_RCV_BODY_ERROR + special bits
6315  *			The message header was successfully copied out.
6316  *			As much of the body was handled as possible.
6317  */
6318 
6319 mach_msg_return_t
ipc_kmsg_copyout(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map,mach_msg_option_t option)6320 ipc_kmsg_copyout(
6321 	ipc_kmsg_t              kmsg,
6322 	ipc_space_t             space,
6323 	vm_map_t                map,
6324 	mach_msg_option_t      option)
6325 {
6326 	mach_msg_return_t mr;
6327 
6328 	ikm_validate_sig(kmsg);
6329 
6330 	mr = ipc_kmsg_copyout_header(kmsg, space, option);
6331 	if (mr != MACH_MSG_SUCCESS) {
6332 		return mr;
6333 	}
6334 
6335 	if (ikm_header(kmsg)->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
6336 		mr = ipc_kmsg_copyout_body(kmsg, space, map, option);
6337 
6338 		if (mr != MACH_MSG_SUCCESS) {
6339 			mr |= MACH_RCV_BODY_ERROR;
6340 		}
6341 	}
6342 
6343 	return mr;
6344 }
6345 
6346 /*
6347  *	Routine:	ipc_kmsg_copyout_pseudo
6348  *	Purpose:
6349  *		Does a pseudo-copyout of the message.
6350  *		This is like a regular copyout, except
6351  *		that the ports in the header are handled
6352  *		as if they are in the body.  They aren't reversed.
6353  *
6354  *		The error codes are a combination of special bits.
6355  *		The copyout proceeds despite errors.
6356  *	Conditions:
6357  *		Nothing locked.
6358  *	Returns:
6359  *		MACH_MSG_SUCCESS	Successful copyout.
6360  *		MACH_MSG_IPC_SPACE	No room for port right in name space.
6361  *		MACH_MSG_VM_SPACE	No room for memory in address space.
6362  *		MACH_MSG_IPC_KERNEL	Resource shortage handling port right.
6363  *		MACH_MSG_VM_KERNEL	Resource shortage handling memory.
6364  */
6365 
6366 mach_msg_return_t
ipc_kmsg_copyout_pseudo(ipc_kmsg_t kmsg,ipc_space_t space,vm_map_t map)6367 ipc_kmsg_copyout_pseudo(
6368 	ipc_kmsg_t              kmsg,
6369 	ipc_space_t             space,
6370 	vm_map_t                map)
6371 {
6372 	mach_msg_header_t *hdr = ikm_header(kmsg);
6373 	mach_msg_bits_t mbits = hdr->msgh_bits;
6374 	ipc_object_t dest = ip_to_object(hdr->msgh_remote_port);
6375 	ipc_object_t reply = ip_to_object(hdr->msgh_local_port);
6376 	ipc_object_t voucher = ip_to_object(ipc_kmsg_get_voucher_port(kmsg));
6377 	mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
6378 	mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
6379 	mach_msg_type_name_t voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
6380 	mach_port_name_t voucher_name = hdr->msgh_voucher_port;
6381 	mach_port_name_t dest_name, reply_name;
6382 	mach_msg_return_t mr;
6383 
6384 	/* Set ith_knote to ITH_KNOTE_PSEUDO */
6385 	current_thread()->ith_knote = ITH_KNOTE_PSEUDO;
6386 
6387 	ikm_validate_sig(kmsg);
6388 
6389 	assert(IO_VALID(dest));
6390 
6391 #if 0
6392 	/*
6393 	 * If we did this here, it looks like we wouldn't need the undo logic
6394 	 * at the end of ipc_kmsg_send() in the error cases.  Not sure which
6395 	 * would be more elegant to keep.
6396 	 */
6397 	ipc_importance_clean(kmsg);
6398 #else
6399 	/* just assert it is already clean */
6400 	ipc_importance_assert_clean(kmsg);
6401 #endif
6402 
6403 	mr = ipc_kmsg_copyout_object(space, dest, dest_type, NULL, NULL, &dest_name);
6404 
6405 	if (!IO_VALID(reply)) {
6406 		reply_name = CAST_MACH_PORT_TO_NAME(reply);
6407 	} else if (ip_is_reply_port(ip_object_to_port(reply))) {
6408 		mach_msg_return_t reply_mr;
6409 		reply_mr = ipc_kmsg_copyout_reply_object(space, reply, &reply_type, &reply_name);
6410 		mr = mr | reply_mr;
6411 		if (reply_mr == MACH_MSG_SUCCESS) {
6412 			mbits = MACH_MSGH_BITS_SET(dest_type, reply_type, voucher_type, MACH_MSGH_BITS_OTHER(mbits));
6413 		}
6414 	} else {
6415 		mr = mr | ipc_kmsg_copyout_object(space, reply, reply_type, NULL, NULL, &reply_name);
6416 	}
6417 
6418 	hdr->msgh_bits = mbits & MACH_MSGH_BITS_USER;
6419 	hdr->msgh_remote_port = CAST_MACH_NAME_TO_PORT(dest_name);
6420 	hdr->msgh_local_port = CAST_MACH_NAME_TO_PORT(reply_name);
6421 
6422 	/* restore the voucher:
6423 	 * If it was copied in via move-send, have to put back a voucher send right.
6424 	 *
6425 	 * If it was copied in via copy-send, the header still contains the old voucher name.
6426 	 * Restore the type and discard the copied-in/pre-processed voucher.
6427 	 */
6428 	if (IO_VALID(voucher)) {
6429 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
6430 		if (kmsg->ikm_voucher_type == MACH_MSG_TYPE_MOVE_SEND) {
6431 			mr |= ipc_kmsg_copyout_object(space, voucher, voucher_type, NULL, NULL, &voucher_name);
6432 			hdr->msgh_voucher_port = voucher_name;
6433 		} else {
6434 			assert(kmsg->ikm_voucher_type == MACH_MSG_TYPE_COPY_SEND);
6435 			hdr->msgh_bits = MACH_MSGH_BITS_SET(dest_type, reply_type, MACH_MSG_TYPE_COPY_SEND,
6436 			    MACH_MSGH_BITS_OTHER(hdr->msgh_bits));
6437 			ipc_object_destroy(voucher, voucher_type);
6438 		}
6439 		ipc_kmsg_clear_voucher_port(kmsg);
6440 	}
6441 
6442 	if (mbits & MACH_MSGH_BITS_COMPLEX) {
6443 		mr |= ipc_kmsg_copyout_body(kmsg, space, map, 0);
6444 	}
6445 
6446 	current_thread()->ith_knote = ITH_KNOTE_NULL;
6447 
6448 	return mr;
6449 }
6450 
6451 /*
6452  *	Routine:	ipc_kmsg_copyout_dest_to_user
6453  *	Purpose:
6454  *		Copies out the destination port in the message.
6455  *		Destroys all other rights and memory in the message.
6456  *	Conditions:
6457  *		Nothing locked.
6458  */
6459 
6460 void
ipc_kmsg_copyout_dest_to_user(ipc_kmsg_t kmsg,ipc_space_t space)6461 ipc_kmsg_copyout_dest_to_user(
6462 	ipc_kmsg_t      kmsg,
6463 	ipc_space_t     space)
6464 {
6465 	mach_msg_bits_t mbits;
6466 	ipc_object_t dest;
6467 	ipc_object_t reply;
6468 	ipc_object_t voucher;
6469 	mach_msg_type_name_t dest_type;
6470 	mach_msg_type_name_t reply_type;
6471 	mach_msg_type_name_t voucher_type;
6472 	mach_port_name_t dest_name, reply_name, voucher_name;
6473 	mach_msg_header_t *hdr;
6474 
6475 	ikm_validate_sig(kmsg);
6476 
6477 	hdr = ikm_header(kmsg);
6478 	mbits = hdr->msgh_bits;
6479 	dest = ip_to_object(hdr->msgh_remote_port);
6480 	reply = ip_to_object(hdr->msgh_local_port);
6481 	voucher = ip_to_object(ipc_kmsg_get_voucher_port(kmsg));
6482 	voucher_name = hdr->msgh_voucher_port;
6483 	dest_type = MACH_MSGH_BITS_REMOTE(mbits);
6484 	reply_type = MACH_MSGH_BITS_LOCAL(mbits);
6485 	voucher_type = MACH_MSGH_BITS_VOUCHER(mbits);
6486 
6487 	assert(IO_VALID(dest));
6488 
6489 	ipc_importance_assert_clean(kmsg);
6490 
6491 	io_lock(dest);
6492 	if (io_active(dest)) {
6493 		ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
6494 		/* dest is unlocked */
6495 	} else {
6496 		io_unlock(dest);
6497 		io_release(dest);
6498 		dest_name = MACH_PORT_DEAD;
6499 	}
6500 
6501 	if (IO_VALID(reply)) {
6502 		ipc_object_destroy(reply, reply_type);
6503 		reply_name = MACH_PORT_NULL;
6504 	} else {
6505 		reply_name = CAST_MACH_PORT_TO_NAME(reply);
6506 	}
6507 
6508 	if (IO_VALID(voucher)) {
6509 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
6510 		ipc_object_destroy(voucher, voucher_type);
6511 		ipc_kmsg_clear_voucher_port(kmsg);
6512 		voucher_name = MACH_PORT_NULL;
6513 	}
6514 
6515 	hdr->msgh_bits = MACH_MSGH_BITS_SET(reply_type, dest_type,
6516 	    voucher_type, mbits);
6517 	hdr->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
6518 	hdr->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
6519 	hdr->msgh_voucher_port = voucher_name;
6520 
6521 	if (mbits & MACH_MSGH_BITS_COMPLEX) {
6522 		mach_msg_body_t *body;
6523 
6524 		body = (mach_msg_body_t *) (hdr + 1);
6525 		ipc_kmsg_clean_body(kmsg, body->msgh_descriptor_count,
6526 		    (mach_msg_descriptor_t *)(body + 1));
6527 	}
6528 }
6529 
6530 /*
6531  *	Routine:	ipc_kmsg_copyout_dest_to_kernel
6532  *	Purpose:
6533  *		Copies out the destination and reply ports in the message.
6534  *		Leaves all other rights and memory in the message alone.
6535  *	Conditions:
6536  *		Nothing locked.
6537  *
6538  *	Derived from ipc_kmsg_copyout_dest_to_user.
6539  *	Use by mach_msg_rpc_from_kernel (which used to use copyout_dest).
6540  *	We really do want to save rights and memory.
6541  */
6542 
6543 void
ipc_kmsg_copyout_dest_to_kernel(ipc_kmsg_t kmsg,ipc_space_t space)6544 ipc_kmsg_copyout_dest_to_kernel(
6545 	ipc_kmsg_t      kmsg,
6546 	ipc_space_t     space)
6547 {
6548 	ipc_object_t dest;
6549 	mach_port_t reply;
6550 	mach_msg_type_name_t dest_type;
6551 	mach_msg_type_name_t reply_type;
6552 	mach_port_name_t dest_name;
6553 	mach_msg_header_t *hdr;
6554 
6555 	ikm_validate_sig(kmsg);
6556 
6557 	hdr = ikm_header(kmsg);
6558 	dest = ip_to_object(hdr->msgh_remote_port);
6559 	reply = hdr->msgh_local_port;
6560 	dest_type = MACH_MSGH_BITS_REMOTE(hdr->msgh_bits);
6561 	reply_type = MACH_MSGH_BITS_LOCAL(hdr->msgh_bits);
6562 
6563 	assert(IO_VALID(dest));
6564 
6565 	io_lock(dest);
6566 	if (io_active(dest)) {
6567 		ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
6568 		/* dest is unlocked */
6569 	} else {
6570 		io_unlock(dest);
6571 		io_release(dest);
6572 		dest_name = MACH_PORT_DEAD;
6573 	}
6574 
6575 	/*
6576 	 * While MIG kernel users don't receive vouchers, the
6577 	 * msgh_voucher_port field is intended to be round-tripped through the
6578 	 * kernel if there is no voucher disposition set. Here we check for a
6579 	 * non-zero voucher disposition, and consume the voucher send right as
6580 	 * there is no possible way to specify MACH_RCV_VOUCHER semantics.
6581 	 */
6582 	mach_msg_type_name_t voucher_type;
6583 	voucher_type = MACH_MSGH_BITS_VOUCHER(hdr->msgh_bits);
6584 	if (voucher_type != MACH_MSGH_BITS_ZERO) {
6585 		ipc_port_t voucher = ipc_kmsg_get_voucher_port(kmsg);
6586 
6587 		assert(voucher_type == MACH_MSG_TYPE_MOVE_SEND);
6588 		/*
6589 		 * someone managed to send this kernel routine a message with
6590 		 * a voucher in it. Cleanup the reference in
6591 		 * kmsg->ikm_voucher.
6592 		 */
6593 		if (IP_VALID(voucher)) {
6594 			ipc_port_release_send(voucher);
6595 		}
6596 		hdr->msgh_voucher_port = 0;
6597 		ipc_kmsg_clear_voucher_port(kmsg);
6598 	}
6599 
6600 	hdr->msgh_bits =
6601 	    (MACH_MSGH_BITS_OTHER(hdr->msgh_bits) |
6602 	    MACH_MSGH_BITS(reply_type, dest_type));
6603 	hdr->msgh_local_port =  CAST_MACH_NAME_TO_PORT(dest_name);
6604 	hdr->msgh_remote_port = reply;
6605 }
6606 
6607 /*
6608  * Caller has a reference to the kmsg and the mqueue lock held.
6609  *
6610  * As such, we can safely return a pointer to the thread group in the kmsg and
6611  * not an additional reference. It is up to the caller to decide to take an
6612  * additional reference on the thread group while still holding the mqueue lock,
6613  * if needed.
6614  */
6615 #if CONFIG_PREADOPT_TG
6616 struct thread_group *
ipc_kmsg_get_thread_group(ipc_kmsg_t kmsg)6617 ipc_kmsg_get_thread_group(ipc_kmsg_t kmsg)
6618 {
6619 	struct thread_group *tg = NULL;
6620 	kern_return_t __assert_only kr;
6621 
6622 	ipc_voucher_t voucher = convert_port_to_voucher(ipc_kmsg_get_voucher_port(kmsg));
6623 	kr = bank_get_preadopt_thread_group(voucher, &tg);
6624 	ipc_voucher_release(voucher);
6625 
6626 	return tg;
6627 }
6628 #endif
6629 
6630 #ifdef __arm64__
6631 /*
6632  * Just sets those parts of the trailer that aren't set up at allocation time.
6633  */
6634 static void
ipc_kmsg_munge_trailer(mach_msg_max_trailer_t * in,void * _out,boolean_t is64bit)6635 ipc_kmsg_munge_trailer(mach_msg_max_trailer_t *in, void *_out, boolean_t is64bit)
6636 {
6637 	if (is64bit) {
6638 		mach_msg_max_trailer64_t *out = (mach_msg_max_trailer64_t*)_out;
6639 		out->msgh_seqno = in->msgh_seqno;
6640 		out->msgh_context = in->msgh_context;
6641 		out->msgh_trailer_size = in->msgh_trailer_size;
6642 		out->msgh_ad = in->msgh_ad;
6643 	} else {
6644 		mach_msg_max_trailer32_t *out = (mach_msg_max_trailer32_t*)_out;
6645 		out->msgh_seqno = in->msgh_seqno;
6646 		out->msgh_context = (mach_port_context32_t)in->msgh_context;
6647 		out->msgh_trailer_size = in->msgh_trailer_size;
6648 		out->msgh_ad = in->msgh_ad;
6649 	}
6650 }
6651 #endif /* __arm64__ */
6652 
6653 mach_msg_trailer_size_t
ipc_kmsg_trailer_size(mach_msg_option_t option,__unused thread_t thread)6654 ipc_kmsg_trailer_size(
6655 	mach_msg_option_t option,
6656 	__unused thread_t thread)
6657 {
6658 	if (!(option & MACH_RCV_TRAILER_MASK)) {
6659 		return MACH_MSG_TRAILER_MINIMUM_SIZE;
6660 	} else {
6661 		return REQUESTED_TRAILER_SIZE(thread_is_64bit_addr(thread), option);
6662 	}
6663 }
6664 
6665 /*
6666  *	Routine:	ipc_kmsg_init_trailer
6667  *	Purpose:
6668  *		Initiailizes a trailer in a message safely.
6669  */
6670 void
ipc_kmsg_init_trailer(ipc_kmsg_t kmsg,task_t sender)6671 ipc_kmsg_init_trailer(
6672 	ipc_kmsg_t          kmsg,
6673 	task_t              sender)
6674 {
6675 	static const mach_msg_max_trailer_t KERNEL_TRAILER_TEMPLATE = {
6676 		.msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0,
6677 		.msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE,
6678 		.msgh_sender = KERNEL_SECURITY_TOKEN_VALUE,
6679 		.msgh_audit = KERNEL_AUDIT_TOKEN_VALUE
6680 	};
6681 
6682 	mach_msg_max_trailer_t *trailer;
6683 
6684 	/*
6685 	 * I reserve for the trailer the largest space (MAX_TRAILER_SIZE)
6686 	 * However, the internal size field of the trailer (msgh_trailer_size)
6687 	 * is initialized to the minimum (sizeof(mach_msg_trailer_t)), to optimize
6688 	 * the cases where no implicit data is requested.
6689 	 */
6690 	trailer = ipc_kmsg_get_trailer(kmsg, false);
6691 	if (sender == TASK_NULL) {
6692 		memcpy(trailer, &KERNEL_TRAILER_TEMPLATE, sizeof(*trailer));
6693 	} else {
6694 		bzero(trailer, sizeof(*trailer));
6695 		trailer->msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0;
6696 		trailer->msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE;
6697 		trailer->msgh_sender = *task_get_sec_token(sender);
6698 		trailer->msgh_audit = *task_get_audit_token(sender);
6699 	}
6700 }
6701 
6702 
6703 void
ipc_kmsg_add_trailer(ipc_kmsg_t kmsg,ipc_space_t space __unused,mach_msg_option_t option,__unused thread_t thread,mach_port_seqno_t seqno,boolean_t minimal_trailer,mach_vm_offset_t context)6704 ipc_kmsg_add_trailer(ipc_kmsg_t kmsg, ipc_space_t space __unused,
6705     mach_msg_option_t option, __unused thread_t thread,
6706     mach_port_seqno_t seqno, boolean_t minimal_trailer,
6707     mach_vm_offset_t context)
6708 {
6709 	mach_msg_max_trailer_t *trailer;
6710 
6711 #ifdef __arm64__
6712 	mach_msg_max_trailer_t tmp_trailer; /* This accommodates U64, and we'll munge */
6713 
6714 	/*
6715 	 * If we are building a minimal_trailer, that means we have not attempted to
6716 	 * copy out message body (which converts descriptors to user sizes) because
6717 	 * we are coming from msg_receive_error().
6718 	 *
6719 	 * Adjust trailer calculation accordingly.
6720 	 */
6721 	void *real_trailer_out = (void*)ipc_kmsg_get_trailer(kmsg, !minimal_trailer);
6722 
6723 	/*
6724 	 * Populate scratch with initial values set up at message allocation time.
6725 	 * After, we reinterpret the space in the message as the right type
6726 	 * of trailer for the address space in question.
6727 	 */
6728 	bcopy(real_trailer_out, &tmp_trailer, MAX_TRAILER_SIZE);
6729 	trailer = &tmp_trailer;
6730 #else /* __arm64__ */
6731 	(void)thread;
6732 	trailer = ipc_kmsg_get_trailer(kmsg, !minimal_trailer);
6733 #endif /* __arm64__ */
6734 
6735 	if (!(option & MACH_RCV_TRAILER_MASK)) {
6736 		return;
6737 	}
6738 
6739 	trailer->msgh_seqno = seqno;
6740 	trailer->msgh_context = context;
6741 	trailer->msgh_trailer_size = REQUESTED_TRAILER_SIZE(thread_is_64bit_addr(thread), option);
6742 
6743 	if (minimal_trailer) {
6744 		goto done;
6745 	}
6746 
6747 	if (GET_RCV_ELEMENTS(option) >= MACH_RCV_TRAILER_AV) {
6748 		trailer->msgh_ad = 0;
6749 	}
6750 
6751 	/*
6752 	 * The ipc_kmsg_t holds a reference to the label of a label
6753 	 * handle, not the port. We must get a reference to the port
6754 	 * and a send right to copyout to the receiver.
6755 	 */
6756 
6757 	if (option & MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_LABELS)) {
6758 		trailer->msgh_labels.sender = 0;
6759 	}
6760 
6761 done:
6762 #ifdef __arm64__
6763 	ipc_kmsg_munge_trailer(trailer, real_trailer_out, thread_is_64bit_addr(thread));
6764 #endif /* __arm64__ */
6765 	return;
6766 }
6767 
6768 /*
6769  * Get the trailer address of kmsg.
6770  *
6771  *     - body_copied_out: Whether ipc_kmsg_copyout_body() has been called.
6772  *     If true, descriptors in kmsg has been converted to user size.
6773  *
6774  * /!\ WARNING /!\
6775  *     Should not be used after ipc_kmsg_convert_header_to_user() is called.
6776  */
6777 mach_msg_max_trailer_t *
ipc_kmsg_get_trailer(ipc_kmsg_t kmsg,bool body_copied_out)6778 ipc_kmsg_get_trailer(
6779 	ipc_kmsg_t              kmsg,
6780 	bool                    body_copied_out) /* is kmsg body copyout attempted */
6781 {
6782 	mach_msg_header_t *hdr = ikm_header(kmsg);
6783 
6784 	if (ikm_is_linear(kmsg)) {
6785 		return (mach_msg_max_trailer_t *)((vm_offset_t)hdr +
6786 		       mach_round_msg(hdr->msgh_size));
6787 	} else {
6788 		assert(kmsg->ikm_udata != NULL);
6789 		return (mach_msg_max_trailer_t *)((vm_offset_t)kmsg->ikm_udata +
6790 		       ikm_content_size(kmsg, current_map(), 0, body_copied_out));
6791 	}
6792 }
6793 
6794 void
ipc_kmsg_set_voucher_port(ipc_kmsg_t kmsg,ipc_port_t voucher_port,mach_msg_type_name_t type)6795 ipc_kmsg_set_voucher_port(
6796 	ipc_kmsg_t           kmsg,
6797 	ipc_port_t           voucher_port,
6798 	mach_msg_type_name_t type)
6799 {
6800 	if (IP_VALID(voucher_port)) {
6801 		assert(ip_kotype(voucher_port) == IKOT_VOUCHER);
6802 	}
6803 	kmsg->ikm_voucher_port = voucher_port;
6804 	kmsg->ikm_voucher_type = type;
6805 }
6806 
6807 ipc_port_t
ipc_kmsg_get_voucher_port(ipc_kmsg_t kmsg)6808 ipc_kmsg_get_voucher_port(ipc_kmsg_t kmsg)
6809 {
6810 	return kmsg->ikm_voucher_port;
6811 }
6812 
6813 void
ipc_kmsg_clear_voucher_port(ipc_kmsg_t kmsg)6814 ipc_kmsg_clear_voucher_port(ipc_kmsg_t kmsg)
6815 {
6816 	kmsg->ikm_voucher_port = IP_NULL;
6817 	kmsg->ikm_voucher_type = MACH_MSGH_BITS_ZERO;
6818 }
6819