xref: /xnu-10002.61.3/osfmk/ipc/ipc_port.h (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
1 /*
2  * Copyright (c) 2000-2016 Apple Computer, 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  */
62 /*
63  */
64 /*
65  *	File:	ipc/ipc_port.h
66  *	Author:	Rich Draves
67  *	Date:	1989
68  *
69  *	Definitions for ports.
70  */
71 
72 #ifndef _IPC_IPC_PORT_H_
73 #define _IPC_IPC_PORT_H_
74 
75 #ifdef MACH_KERNEL_PRIVATE
76 
77 #include <mach_assert.h>
78 
79 #include <mach/mach_types.h>
80 #include <mach/boolean.h>
81 #include <mach/kern_return.h>
82 #include <mach/port.h>
83 
84 #include <kern/assert.h>
85 #include <kern/kern_types.h>
86 #include <kern/turnstile.h>
87 
88 #include <ipc/ipc_types.h>
89 #include <ipc/ipc_object.h>
90 #include <ipc/ipc_mqueue.h>
91 #include <ipc/ipc_space.h>
92 
93 #include <security/_label.h>
94 
95 #include <ptrauth.h>
96 
97 extern int proc_isinitproc(struct proc *p);
98 
99 struct task_watchport_elem;
100 
101 typedef unsigned int ipc_port_timestamp_t;
102 
103 struct ipc_port_request {
104 	union {
105 		struct ipc_port                *ipr_soright;
106 		struct host_notify_entry       *ipr_hnotify;
107 	};
108 
109 	union {
110 #define IPR_HOST_NOTIFY                         0xfffffffeu
111 		mach_port_name_t                ipr_name;
112 		ipc_port_request_index_t        ipr_next;
113 	};
114 };
115 
116 KALLOC_ARRAY_TYPE_DECL(ipc_port_request_table, struct ipc_port_request);
117 
118 struct ipc_port {
119 	struct ipc_object               ip_object;
120 	union {
121 		/*
122 		 * The waitq_eventmask field is only used on the global queues.
123 		 * We hence repurpose all those bits for our own use.
124 		 *
125 		 * Note: if too many bits are added, compilation will fail
126 		 *       with errors about "negative bitfield sizes"
127 		 */
128 		WAITQ_FLAGS(ip_waitq
129 		    , ip_fullwaiters:1            /* Whether there are senders blocked on a full queue */
130 		    , ip_sprequests:1             /* send-possible requests outstanding */
131 		    , ip_spimportant:1            /* ... at least one is importance donating */
132 		    , ip_impdonation:1            /* port supports importance donation */
133 		    , ip_tempowner:1              /* dont give donations to current receiver */
134 		    , ip_guarded:1                /* port guarded (use context value as guard) */
135 		    , ip_strict_guard:1           /* Strict guarding; Prevents user manipulation of context values directly */
136 		    , ip_specialreply:1           /* port is a special reply port */
137 		    , ip_sync_link_state:3        /* link the port to destination port/ Workloop */
138 		    , ip_sync_bootstrap_checkin:1 /* port part of sync bootstrap checkin, push on thread doing the checkin */
139 		    , ip_immovable_receive:1      /* the receive right cannot be moved out of a space, until it is destroyed */
140 		    , ip_immovable_send:1         /* No send(once) rights to this port can be moved out of a space, never unset */
141 		    , ip_no_grant:1               /* Port wont accept complex messages containing (ool) port descriptors */
142 		    , ip_tg_block_tracking:1      /* Track blocking relationship between thread groups during sync IPC */
143 		    , ip_pinned:1                 /* Can't deallocate the last send right from a space while the bit is set */
144 		    , ip_service_port:1           /* port is a service port */
145 		    , ip_has_watchport:1          /* port has an exec watchport */
146 		    , ip_kernel_iotier_override:2 /* kernel iotier override */
147 		    , ip_kernel_qos_override:3    /* kernel qos override */
148 		    , ip_reply_port_semantics:3   /* reply port defense in depth type */
149 		    );
150 		struct waitq            ip_waitq;
151 	};
152 
153 	struct ipc_mqueue               ip_messages;
154 
155 	/*
156 	 * IMPORTANT: Direct access of unionized fields are highly discouraged.
157 	 * Use accessor functions below and see header doc for possible states.
158 	 */
159 	union {
160 		struct ipc_space       *XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_receiver") ip_receiver;
161 		struct ipc_port        *XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_destination") ip_destination;
162 		ipc_port_timestamp_t    ip_timestamp;
163 	};
164 
165 	/* update ipc_kobject_upgrade_locked() if this union is changed */
166 	union {
167 		uintptr_t               ip_kobject; /* manually PAC-ed, see ipc_kobject_get_raw() */
168 		ipc_importance_task_t   ip_imp_task; /* use accessor ip_get_imp_task() */
169 		struct ipc_port        *ip_sync_inheritor_port;
170 		struct knote           *ip_sync_inheritor_knote;
171 		struct turnstile       *ip_sync_inheritor_ts;
172 	};
173 
174 	/*
175 	 * ip_specialreply:  ip_pid
176 	 * ip_has_watchport: ip_twe
177 	 * else:             ip_pdrequest
178 	 */
179 	union {
180 		int                     ip_pid;
181 		struct task_watchport_elem *XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_twe") ip_twe;
182 		struct ipc_port *XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_pdrequest") ip_pdrequest;
183 	};
184 
185 #define IP_KOBJECT_NSREQUEST_ARMED      ((struct ipc_port *)1)
186 	struct ipc_port                *ip_nsrequest;
187 	ipc_port_request_table_t XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_request") ip_requests;
188 	union {
189 		struct ipc_kmsg *XNU_PTRAUTH_SIGNED_PTR("ipc_port.premsg") ip_premsg;
190 		struct turnstile       *ip_send_turnstile;
191 	};
192 	mach_vm_address_t               ip_context;
193 
194 #if DEVELOPMENT || DEBUG
195 	natural_t                       ip_srp_lost_link : 1;   /* special reply port turnstile link chain broken */
196 	natural_t                       ip_srp_msg_sent : 1;    /* special reply port msg sent */
197 	natural_t                       ip_impcount : 30;       /* number of importance donations in nested queue */
198 #else
199 	natural_t                       ip_impcount;            /* number of importance donations in nested queue */
200 #endif
201 	mach_port_mscount_t             ip_mscount;
202 	mach_port_rights_t              ip_srights;
203 	mach_port_rights_t              ip_sorights;
204 
205 	union {
206 		ipc_kobject_label_t XNU_PTRAUTH_SIGNED_PTR("ipc_port.kolabel") ip_kolabel;
207 		/* Union of service and connection ports' message filtering metadata */
208 		void * XNU_PTRAUTH_SIGNED_PTR("ipc_port.ip_splabel") ip_splabel;
209 	};
210 
211 #if MACH_ASSERT
212 	unsigned long                   ip_timetrack;   /* give an idea of "when" created */
213 	uint32_t                        ip_made_bt;     /* stack trace (btref_t) */
214 	uint32_t                        ip_made_pid;    /* for debugging */
215 #endif  /* MACH_ASSERT */
216 };
217 
218 static inline bool
ip_in_pset(ipc_port_t port)219 ip_in_pset(ipc_port_t port)
220 {
221 	return !circle_queue_empty(&port->ip_waitq.waitq_links);
222 }
223 
224 #define ip_receiver_name        ip_messages.imq_receiver_name
225 #define ip_reply_context        ip_messages.imq_context
226 #define ip_klist                ip_messages.imq_klist
227 
228 #define port_send_turnstile(port)                            \
229 	(IP_PREALLOC(port) ? TURNSTILE_NULL : (port)->ip_send_turnstile)
230 
231 #define set_port_send_turnstile(port, value)                 \
232 MACRO_BEGIN                                                  \
233 if (!IP_PREALLOC(port)) {                                     \
234 	(port)->ip_send_turnstile = (value);           \
235 }                                                         \
236 MACRO_END
237 
238 #define port_send_turnstile_address(port)                    \
239 	(IP_PREALLOC(port) ? NULL : &((port)->ip_send_turnstile))
240 
241 #define port_rcv_turnstile_address(port)   (&(port)->ip_waitq.waitq_ts)
242 
243 extern void __ipc_right_delta_overflow_panic(
244 	ipc_port_t          port,
245 	natural_t          *field,
246 	int                 delta) __abortlike;
247 
248 #define ip_right_delta(port, field, delta)  ({ \
249     ipc_port_t __port = (port);                                  \
250     if (os_add_overflow(__port->field, delta, &__port->field)) { \
251 	__ipc_right_delta_overflow_panic(__port, &__port->field, delta);  \
252     }                                                            \
253 })
254 
255 #define ip_srights_inc(port)  ip_right_delta(port, ip_srights, 1)
256 #define ip_srights_dec(port)  ip_right_delta(port, ip_srights, -1)
257 #define ip_sorights_inc(port) ip_right_delta(port, ip_sorights, 1)
258 #define ip_sorights_dec(port) ip_right_delta(port, ip_sorights, -1)
259 
260 /*
261  * SYNC IPC state flags for special reply port/ rcv right.
262  *
263  * PORT_SYNC_LINK_ANY
264  *    Special reply port is not linked to any other port
265  *    or WL and linkage should be allowed.
266  *
267  * PORT_SYNC_LINK_PORT
268  *    Special reply port is linked to the port and
269  *    ip_sync_inheritor_port contains the inheritor
270  *    port.
271  *
272  * PORT_SYNC_LINK_WORKLOOP_KNOTE
273  *    Special reply port is linked to a WL (via a knote).
274  *    ip_sync_inheritor_knote contains a pointer to the knote
275  *    the port is stashed on.
276  *
277  * PORT_SYNC_LINK_WORKLOOP_STASH
278  *    Special reply port is linked to a WL (via a knote stash).
279  *    ip_sync_inheritor_ts contains a pointer to the turnstile with a +1
280  *    the port is stashed on.
281  *
282  * PORT_SYNC_LINK_NO_LINKAGE
283  *    Message sent to special reply port, do
284  *    not allow any linkages till receive is
285  *    complete.
286  *
287  * PORT_SYNC_LINK_RCV_THREAD
288  *    Receive right copied out as a part of bootstrap check in,
289  *    push on the thread which copied out the port.
290  */
291 #define PORT_SYNC_LINK_ANY              (0)
292 #define PORT_SYNC_LINK_PORT             (0x1)
293 #define PORT_SYNC_LINK_WORKLOOP_KNOTE   (0x2)
294 #define PORT_SYNC_LINK_WORKLOOP_STASH   (0x3)
295 #define PORT_SYNC_LINK_NO_LINKAGE       (0x4)
296 #define PORT_SYNC_LINK_RCV_THREAD       (0x5)
297 
298 #define IP_NULL                         IPC_PORT_NULL
299 #define IP_DEAD                         IPC_PORT_DEAD
300 #define IP_VALID(port)                  IPC_PORT_VALID(port)
301 
302 #define ip_object_to_port(io)           __container_of(io, struct ipc_port, ip_object)
303 #define ip_to_object(port)              (&(port)->ip_object)
304 #define ip_active(port)                 io_active(ip_to_object(port))
305 #define ip_mq_lock_held(port)           io_lock_held(ip_to_object(port))
306 #define ip_mq_lock(port)                io_lock(ip_to_object(port))
307 #define ip_mq_lock_try(port)            io_lock_try(ip_to_object(port))
308 #define ip_mq_lock_held_kdp(port)       io_lock_held_kdp(ip_to_object(port))
309 #define ip_mq_unlock(port)              io_unlock(ip_to_object(port))
310 
311 #define ip_reference(port)              io_reference(ip_to_object(port))
312 #define ip_release(port)                io_release(ip_to_object(port))
313 #define ip_release_safe(port)           io_release_safe(ip_to_object(port))
314 #define ip_release_live(port)           io_release_live(ip_to_object(port))
315 #define ip_validate(port) \
316 	zone_id_require(ZONE_ID_IPC_PORT, sizeof(struct ipc_port), port)
317 
318 #define ip_from_waitq(wq)               __container_of(wq, struct ipc_port, ip_waitq)
319 #define ip_from_mq(mq)                  __container_of(mq, struct ipc_port, ip_messages)
320 
321 #define ip_kotype(port)                 io_kotype(ip_to_object(port))
322 #define ip_is_kobject(port)             io_is_kobject(ip_to_object(port))
323 #define ip_is_control(port) \
324 	(ip_kotype(port) == IKOT_TASK_CONTROL || ip_kotype(port) == IKOT_THREAD_CONTROL)
325 #define ip_is_kolabeled(port)           io_is_kolabeled(ip_to_object(port))
326 
327 #define ip_full_kernel(port)            imq_full_kernel(&(port)->ip_messages)
328 #define ip_full(port)                   imq_full(&(port)->ip_messages)
329 
330 /*
331  * IPC Port flags for reply port defense in depth
332  *
333  * PORT_MARK_REPLY_PORT
334  *   Port is marked as a reply port.
335  *
336  * PORT_ENFORCE_REPLY_PORT_SEMANTICS
337  *   When talking to this port, the local port of mach msg needs to be a reply port.
338  *   Currrently service ports and libxpc connection ports adopt this.
339  *
340  * PORT_MARK_PROVISIONAL_REPLY_PORT
341  *   Port is marked as a provisional reply port with an eventual goal of making it port as PORT_MARK_REPLY_PORT.
342  *
343  * PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS
344  *   Same as PORT_ENFORCE_REPLY_PORT_SEMANTICS above, but does not allow for provisional reply ports.
345  *   Once provisional reply ports no longer exist, this will be removed as "rigidness/strictness" will be irrelavant.
346  *
347  * PORT_ID_PROTECTED_OPT_OUT
348  *   Port is opted out from identity protected enforcement for mach exceptions.
349  */
350 #define PORT_MARK_REPLY_PORT              0x01
351 #define PORT_ENFORCE_REPLY_PORT_SEMANTICS 0x02
352 #define PORT_MARK_PROVISIONAL_REPLY_PORT  0x03
353 #define PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS  0x04
354 #define PORT_ID_PROTECTED_OPT_OUT                 0x05
355 
356 /* ip_reply_port_semantics can be read without a lock as it is never unset after port creation. */
357 #define ip_is_reply_port(port)                          (((port)->ip_reply_port_semantics) == PORT_MARK_REPLY_PORT)
358 #define ip_require_reply_port_semantics(port)           (((port)->ip_reply_port_semantics) == PORT_ENFORCE_REPLY_PORT_SEMANTICS)
359 #define ip_is_provisional_reply_port(port)              (((port)->ip_reply_port_semantics) == PORT_MARK_PROVISIONAL_REPLY_PORT)
360 #define ip_require_rigid_reply_port_semantics(port)     (((port)->ip_reply_port_semantics) == PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS)
361 #define ip_is_id_prot_opted_out(port)                   (((port)->ip_reply_port_semantics) == PORT_ID_PROTECTED_OPT_OUT)
362 
363 #define ip_mark_reply_port(port)                        ((port)->ip_reply_port_semantics = PORT_MARK_REPLY_PORT)
364 #define ip_enforce_reply_port_semantics(port)           ((port)->ip_reply_port_semantics = PORT_ENFORCE_REPLY_PORT_SEMANTICS)
365 #define ip_mark_provisional_reply_port(port)            ((port)->ip_reply_port_semantics = PORT_MARK_PROVISIONAL_REPLY_PORT)
366 #define ip_enforce_rigid_reply_port_semantics(port)     ((port)->ip_reply_port_semantics = PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS)
367 #define ip_mark_id_prot_opt_out(port)                   ((port)->ip_reply_port_semantics = PORT_ID_PROTECTED_OPT_OUT)
368 
369 #define ip_is_immovable_send(port)      ((port)->ip_immovable_send)
370 #define ip_is_pinned(port)              ((port)->ip_pinned)
371 
372 #define ip_is_libxpc_connection_port(port) \
373 	(!ip_is_kolabeled(port) && (!(port)->ip_service_port) && ((port)->ip_splabel != NULL))
374 
375 extern bool ip_violates_rigid_reply_port_semantics(ipc_port_t dest_port, ipc_port_t reply_port,
376     int *reply_port_semantics_violation);
377 
378 extern bool ip_violates_reply_port_semantics(ipc_port_t dest_port, ipc_port_t reply_port,
379     int *reply_port_semantics_violation);
380 
381 /* Rigid Reply Port and Move Reply Port violators */
382 #define REPLY_PORT_SEMANTICS_VIOLATOR    1 /* normal reply port semantics violator */
383 #define RRP_HARDENED_RUNTIME_VIOLATOR    2
384 #define MRP_HARDENED_RUNTIME_VIOLATOR    3
385 #define MRP_3P_VIOLATOR                  4
386 #define RRP_3P_VIOLATOR                  5
387 
388 /* Bits reserved in IO_BITS_PORT_INFO are defined here */
389 
390 /*
391  * JMM - Preallocation flag
392  * This flag indicates that there is a message buffer preallocated for this
393  * port and we should use that when sending (from the kernel) rather than
394  * allocate a new one.  This avoids deadlocks during notification message
395  * sends by critical system threads (which may be needed to free memory and
396  * therefore cannot be blocked waiting for memory themselves).
397  */
398 #define IP_BIT_PREALLOC         0x00008000      /* preallocated mesg */
399 #define IP_PREALLOC(port)       (io_bits(ip_to_object(port)) & IP_BIT_PREALLOC)
400 
401 #define IP_SET_PREALLOC(port, kmsg)                                     \
402 MACRO_BEGIN                                                             \
403 	io_bits_or(ip_to_object(port), IP_BIT_PREALLOC);                \
404 	(port)->ip_premsg = (kmsg);                                     \
405 MACRO_END
406 
407 /*
408  * This flag indicates that the port has opted into message filtering based
409  * on a policy defined in the Sandbox.
410  */
411 #define IP_BIT_FILTER_MSG               0x00001000
412 #define ip_enforce_msg_filtering(port)  ((io_bits(ip_to_object(port)) & IP_BIT_FILTER_MSG) != 0)
413 
414 /*
415  * Use the low bits in the ipr_soright to specify the request type
416  */
417 __enum_decl(ipc_port_request_opts_t, uintptr_t, {
418 	IPR_SOR_SPARM_MASK = 0x01,              /* send-possible armed */
419 	IPR_SOR_SPREQ_MASK = 0x02,              /* send-possible requested */
420 });
421 #define IPR_SOR_SPBIT_MASK      3               /* combo */
422 #define IPR_SOR_SPARMED(sor)    (((uintptr_t)(sor) & IPR_SOR_SPARM_MASK) != 0)
423 #define IPR_SOR_SPREQ(sor)      (((uintptr_t)(sor) & IPR_SOR_SPREQ_MASK) != 0)
424 #define IPR_SOR_PORT(sor)       ((ipc_port_t)((uintptr_t)(sor) & ~IPR_SOR_SPBIT_MASK))
425 #define IPR_SOR_MAKE(p, m)      ((ipc_port_t)((uintptr_t)(p) | (m)))
426 
427 extern lck_grp_t        ipc_lck_grp;
428 extern lck_attr_t       ipc_lck_attr;
429 
430 /*
431  *	Taking the ipc_port_multiple lock grants the privilege
432  *	to lock multiple ports at once.  No ports must locked
433  *	when it is taken.
434  */
435 
436 extern lck_spin_t ipc_port_multiple_lock_data;
437 
438 #define ipc_port_multiple_lock()                                        \
439 	lck_spin_lock_grp(&ipc_port_multiple_lock_data, &ipc_lck_grp)
440 
441 #define ipc_port_multiple_unlock()                                      \
442 	lck_spin_unlock(&ipc_port_multiple_lock_data)
443 
444 /*
445  *	Search for the end of the chain (a port not in transit),
446  *	acquiring locks along the way.
447  */
448 extern boolean_t ipc_port_destination_chain_lock(
449 	ipc_port_t port,
450 	ipc_port_t *base);
451 
452 /*
453  *	The port timestamp facility provides timestamps
454  *	for port destruction.  It is used to serialize
455  *	mach_port_names with port death.
456  */
457 
458 extern ipc_port_timestamp_t ipc_port_timestamp_data;
459 
460 /* Retrieve a port timestamp value */
461 extern ipc_port_timestamp_t ipc_port_timestamp(void);
462 
463 /*
464  *	Compares two timestamps, and returns TRUE if one
465  *	happened before two.  Note that this formulation
466  *	works when the timestamp wraps around at 2^32,
467  *	as long as one and two aren't too far apart.
468  */
469 
470 #define IP_TIMESTAMP_ORDER(one, two)    ((int) ((one) - (two)) < 0)
471 
472 extern void __abortlike __ipc_port_inactive_panic(ipc_port_t port);
473 
474 static inline void
require_ip_active(ipc_port_t port)475 require_ip_active(ipc_port_t port)
476 {
477 	if (!ip_active(port)) {
478 		__ipc_port_inactive_panic(port);
479 	}
480 }
481 
482 /*
483  *  A receive right (port) can be in ONE of the following four states:
484  *
485  *  1) INACTIVE: Dead
486  *  2) IN-SPACE: In a space
487  *  3) IN-TRANSIT: Enqueued in a message
488  *  4) IN-LIMBO
489  *
490  *  If the port is active and ip_receiver_name != MACH_PORT_NULL, we can safely
491  *  deference the union as ip_receiver, which points to the space that holds
492  *  receive right (but doesn't hold a ref for it).
493  *
494  *  If the port is active and ip_receiver_name == MACH_PORT_NULL, we can safely
495  *  deference the union as ip_destination. The port is either IN-LIMBO (ip_destination == IP_NULL)
496  *  or ip_destination points to the destination port and holds a ref for it.
497  *
498  *  If the port is not active, we can safely deference the union as ip_timestamp,
499  *  which contains a timestamp taken when the port was destroyed.
500  *
501  *  If the port is in a space, ip_receiver_name denotes the port name its receive
502  *  right occupies in the receiving space. The only exception, as an optimization trick,
503  *  is task's self port (itk_self), whose ip_receiver_name actually denotes the name
504  *  of mach_task_self() in owning task's space (a send right, with receive right in ipc_space_kernel).
505  */
506 
507 static inline bool
ip_in_a_space(ipc_port_t port)508 ip_in_a_space(ipc_port_t port)
509 {
510 	/* IN-SPACE */
511 	return ip_active(port) && port->ip_receiver_name != MACH_PORT_NULL;
512 }
513 
514 static inline bool
ip_in_space(ipc_port_t port,ipc_space_t space)515 ip_in_space(ipc_port_t port, ipc_space_t space)
516 {
517 	ip_mq_lock_held(port); /* port must be locked, otherwise PAC could fail */
518 	return ip_in_a_space(port) && port->ip_receiver == space;
519 }
520 
521 /* use sparsely when port lock is not possible, just compare raw pointer */
522 static inline bool
ip_in_space_noauth(ipc_port_t port,void * space)523 ip_in_space_noauth(ipc_port_t port, void* space)
524 {
525 	void *__single raw_ptr = ptrauth_strip(*(void **)&port->ip_receiver, ptrauth_key_process_independent_data);
526 	return raw_ptr == space;
527 }
528 
529 static inline bool
ip_in_transit(ipc_port_t port)530 ip_in_transit(ipc_port_t port)
531 {
532 	/* IN-TRANSIT */
533 	ip_mq_lock_held(port); /* port must be locked, otherwise PAC could fail */
534 	return ip_active(port) && !ip_in_a_space(port) && port->ip_destination != IP_NULL;
535 }
536 
537 static inline bool
ip_in_limbo(ipc_port_t port)538 ip_in_limbo(ipc_port_t port)
539 {
540 	/* IN-LIMBO */
541 	ip_mq_lock_held(port); /* port must be locked, otherwise PAC could fail */
542 	return ip_active(port) && !ip_in_a_space(port) && port->ip_destination == IP_NULL;
543 }
544 
545 static inline ipc_space_t
ip_get_receiver(ipc_port_t port)546 ip_get_receiver(ipc_port_t port)
547 {
548 	ip_mq_lock_held(port); /* port must be locked, otherwise PAC could fail */
549 	return ip_in_a_space(port) ? port->ip_receiver : NULL;
550 }
551 
552 static inline void*
ip_get_receiver_ptr_noauth(ipc_port_t port)553 ip_get_receiver_ptr_noauth(ipc_port_t port)
554 {
555 	void *__single raw_ptr = ptrauth_strip(*(void **)&port->ip_receiver, ptrauth_key_process_independent_data);
556 	return raw_ptr;
557 }
558 
559 static inline mach_port_name_t
ip_get_receiver_name(ipc_port_t port)560 ip_get_receiver_name(ipc_port_t port)
561 {
562 	return ip_in_a_space(port) ? port->ip_receiver_name : MACH_PORT_NULL;
563 }
564 
565 static inline ipc_port_t
ip_get_destination(ipc_port_t port)566 ip_get_destination(ipc_port_t port)
567 {
568 	ip_mq_lock_held(port); /* port must be locked, otherwise PAC could fail */
569 	return ip_active(port) && !ip_in_a_space(port) ? port->ip_destination : IP_NULL;
570 }
571 
572 static inline ipc_port_timestamp_t
ip_get_death_time(ipc_port_t port)573 ip_get_death_time(ipc_port_t port)
574 {
575 	assert(!ip_active(port));
576 	return port->ip_timestamp;
577 }
578 
579 static inline ipc_importance_task_t
ip_get_imp_task(ipc_port_t port)580 ip_get_imp_task(ipc_port_t port)
581 {
582 	return (!ip_is_kobject(port) && !port->ip_specialreply && port->ip_tempowner) ? port->ip_imp_task : IIT_NULL;
583 }
584 
585 extern kern_return_t ipc_port_translate_send(
586 	ipc_space_t                     space,
587 	mach_port_name_t                name,
588 	ipc_port_t                     *portp);
589 
590 extern kern_return_t ipc_port_translate_receive(
591 	ipc_space_t                     space,
592 	mach_port_name_t                name,
593 	ipc_port_t                     *portp);
594 
595 /* Allocate a notification request slot */
596 extern kern_return_t ipc_port_request_alloc(
597 	ipc_port_t                      port,
598 	mach_port_name_t                name,
599 	ipc_port_t                      soright,
600 	ipc_port_request_opts_t         options,
601 	ipc_port_request_index_t       *indexp);
602 
603 extern kern_return_t ipc_port_request_hnotify_alloc(
604 	ipc_port_t                      port,
605 	struct host_notify_entry       *hnotify,
606 	ipc_port_request_index_t       *indexp);
607 
608 /* Grow one of a port's tables of notifcation requests */
609 extern kern_return_t ipc_port_request_grow(
610 	ipc_port_t                      port);
611 
612 /* Return the type(s) of notification requests outstanding */
613 extern mach_port_type_t ipc_port_request_type(
614 	ipc_port_t                      port,
615 	mach_port_name_t                name,
616 	ipc_port_request_index_t        index);
617 
618 /* Cancel a notification request and return the send-once right */
619 extern ipc_port_t ipc_port_request_cancel(
620 	ipc_port_t                      port,
621 	mach_port_name_t                name,
622 	ipc_port_request_index_t        index);
623 
624 /* Arm any delayed send-possible notification */
625 extern boolean_t ipc_port_request_sparm(
626 	ipc_port_t                port,
627 	mach_port_name_t          name,
628 	ipc_port_request_index_t  index,
629 	mach_msg_option_t         option,
630 	mach_msg_priority_t       priority);
631 
632 /* Make a no-senders request */
633 extern void ipc_port_nsrequest(
634 	ipc_port_t              port,
635 	mach_port_mscount_t     sync,
636 	ipc_port_t              notify,
637 	ipc_port_t              *previousp);
638 
639 /* Prepare a receive right for transmission/destruction */
640 extern boolean_t ipc_port_clear_receiver(
641 	ipc_port_t              port,
642 	boolean_t               should_destroy,
643 	waitq_link_list_t      *free_l);
644 
645 __options_decl(ipc_port_init_flags_t, uint32_t, {
646 	IPC_PORT_INIT_NONE                              = 0x00000000,
647 	IPC_PORT_INIT_MAKE_SEND_RIGHT                   = 0x00000001,
648 	IPC_PORT_INIT_MESSAGE_QUEUE                     = 0x00000002,
649 	IPC_PORT_INIT_SPECIAL_REPLY                     = 0x00000004,
650 	IPC_PORT_INIT_FILTER_MESSAGE                    = 0x00000008,
651 	IPC_PORT_INIT_TG_BLOCK_TRACKING                 = 0x00000010,
652 	IPC_PORT_INIT_LOCKED                            = 0x00000020,
653 	IPC_PORT_INIT_REPLY                             = 0x00000040,
654 	IPC_PORT_ENFORCE_REPLY_PORT_SEMANTICS           = 0x00000080,
655 	IPC_PORT_INIT_PROVISIONAL_REPLY                 = 0x00000100,
656 	IPC_PORT_INIT_PROVISIONAL_ID_PROT_OPTOUT        = 0x00000200,
657 	IPC_PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS     = 0x00000400,
658 });
659 
660 /* Initialize a newly-allocated port */
661 extern void ipc_port_init(
662 	ipc_port_t              port,
663 	ipc_space_t             space,
664 	ipc_port_init_flags_t   flags,
665 	mach_port_name_t        name);
666 
667 /* Allocate a port */
668 extern kern_return_t ipc_port_alloc(
669 	ipc_space_t             space,
670 	ipc_port_init_flags_t   flags,
671 	mach_port_name_t        *namep,
672 	ipc_port_t              *portp);
673 
674 /* Allocate a port, with a specific name */
675 extern kern_return_t ipc_port_alloc_name(
676 	ipc_space_t             space,
677 	ipc_port_init_flags_t   flags,
678 	mach_port_name_t        name,
679 	ipc_port_t              *portp);
680 
681 /* Attach a label to the port */
682 extern void ipc_port_set_label(
683 	ipc_port_t              port,
684 	ipc_label_t             label);
685 
686 /* Generate dead name notifications */
687 extern void ipc_port_dnnotify(
688 	ipc_port_t              port);
689 
690 /* Generate send-possible notifications */
691 extern void ipc_port_spnotify(
692 	ipc_port_t              port);
693 
694 /* Destroy a port */
695 extern void ipc_port_destroy(
696 	ipc_port_t      port);
697 
698 /* Check if queueing "port" in a message for "dest" would create a circular
699  *  group of ports and messages */
700 extern boolean_t
701 ipc_port_check_circularity(
702 	ipc_port_t      port,
703 	ipc_port_t      dest);
704 
705 #if IMPORTANCE_INHERITANCE
706 
707 enum {
708 	IPID_OPTION_NORMAL       = 0, /* normal boost */
709 	IPID_OPTION_SENDPOSSIBLE = 1, /* send-possible induced boost */
710 };
711 
712 /* link the destination port with special reply port */
713 void
714 ipc_port_link_special_reply_port(
715 	ipc_port_t special_reply_port,
716 	ipc_port_t dest_port,
717 	boolean_t sync_bootstrap_checkin);
718 
719 #define IPC_PORT_ADJUST_SR_NONE                      0
720 #define IPC_PORT_ADJUST_SR_ALLOW_SYNC_LINKAGE        0x1
721 #define IPC_PORT_ADJUST_SR_LINK_WORKLOOP             0x2
722 #define IPC_PORT_ADJUST_UNLINK_THREAD                0x4
723 #define IPC_PORT_ADJUST_SR_RECEIVED_MSG              0x8
724 #define IPC_PORT_ADJUST_SR_ENABLE_EVENT              0x10
725 #define IPC_PORT_ADJUST_RESET_BOOSTRAP_CHECKIN       0x20
726 
727 void
728 ipc_special_reply_port_bits_reset(ipc_port_t special_reply_port);
729 
730 void
731 ipc_special_reply_port_msg_sent(ipc_port_t special_reply_port);
732 
733 void
734 ipc_special_reply_port_msg_sent(ipc_port_t special_reply_port);
735 
736 /* Adjust special reply port linkage */
737 void
738 ipc_port_adjust_special_reply_port_locked(
739 	ipc_port_t special_reply_port,
740 	struct knote *kn,
741 	uint8_t flags,
742 	boolean_t get_turnstile);
743 
744 void
745 ipc_port_adjust_sync_link_state_locked(
746 	ipc_port_t port,
747 	int sync_link_state,
748 	turnstile_inheritor_t inheritor);
749 
750 /* Adjust special reply port linkage */
751 void
752 ipc_port_adjust_special_reply_port(
753 	ipc_port_t special_reply_port,
754 	uint8_t flags);
755 
756 void
757 ipc_port_adjust_port_locked(
758 	ipc_port_t port,
759 	struct knote *kn,
760 	boolean_t sync_bootstrap_checkin);
761 
762 void
763 ipc_port_clear_sync_rcv_thread_boost_locked(
764 	ipc_port_t port);
765 
766 bool
767 ipc_port_has_prdrequest(
768 	ipc_port_t port);
769 
770 kern_return_t
771 ipc_port_add_watchport_elem_locked(
772 	ipc_port_t                 port,
773 	struct task_watchport_elem *watchport_elem,
774 	struct task_watchport_elem **old_elem);
775 
776 kern_return_t
777 ipc_port_clear_watchport_elem_internal_conditional_locked(
778 	ipc_port_t                 port,
779 	struct task_watchport_elem *watchport_elem);
780 
781 kern_return_t
782 ipc_port_replace_watchport_elem_conditional_locked(
783 	ipc_port_t                 port,
784 	struct task_watchport_elem *old_watchport_elem,
785 	struct task_watchport_elem *new_watchport_elem);
786 
787 struct task_watchport_elem *
788 ipc_port_clear_watchport_elem_internal(
789 	ipc_port_t                 port);
790 
791 void
792 ipc_port_send_turnstile_prepare(ipc_port_t port);
793 
794 void
795 ipc_port_send_turnstile_complete(ipc_port_t port);
796 
797 struct waitq *
798 ipc_port_rcv_turnstile_waitq(struct waitq *waitq);
799 
800 /* apply importance delta to port only */
801 extern mach_port_delta_t
802 ipc_port_impcount_delta(
803 	ipc_port_t              port,
804 	mach_port_delta_t       delta,
805 	ipc_port_t              base);
806 
807 /* apply importance delta to port, and return task importance for update */
808 extern boolean_t
809 ipc_port_importance_delta_internal(
810 	ipc_port_t              port,
811 	natural_t               options,
812 	mach_port_delta_t       *deltap,
813 	ipc_importance_task_t   *imp_task);
814 
815 /* Apply an importance delta to a port and reflect change in receiver task */
816 extern boolean_t
817 ipc_port_importance_delta(
818 	ipc_port_t              port,
819 	natural_t               options,
820 	mach_port_delta_t       delta);
821 #endif /* IMPORTANCE_INHERITANCE */
822 
823 /*!
824  * @function ipc_port_make_send_any_locked()
825  *
826  * @brief
827  * Makes a naked send right for a locked and active port.
828  *
829  * @decription
830  * @c ipc_port_make_send_*() should not be used in any generic IPC
831  * plumbing, as this is an operation that subsystem owners need
832  * to be able to synchronize against with the make-send-count
833  * and no-senders notifications.
834  *
835  * It is especially important for kobject types, and in general MIG upcalls
836  * or replies from the kernel should never use MAKE_SEND dispositions,
837  * and prefer COPY_SEND or MOVE_SEND, so that subsystems can control
838  * where that send right comes from.
839  *
840  * This function doesn't perform any validation on the type of port,
841  * this duty is left to the caller.
842  *
843  * @param port          An active and locked port.
844  */
845 extern ipc_port_t ipc_port_make_send_any_locked(
846 	ipc_port_t      port);
847 
848 /*!
849  * @function ipc_port_make_send_any()
850  *
851  * @brief
852  * Makes a naked send right for the specified port.
853  *
854  * @decription
855  * @see ipc_port_make_send_any_locked() for a general warning about
856  * making send rights.
857  *
858  * This function doesn't perform any validation on the type of port,
859  * this duty is left to the caller.
860  *
861  * Using @c ipc_port_make_send_mqueue() or @c ipc_kobject_make_send()
862  * is preferred.
863  *
864  * @param port          The target port.
865  *
866  * @returns
867  * - IP_DEAD            if @c port was dead.
868  * - @c port            if @c port was valid, in which case
869  *                      a naked send right was made.
870  */
871 extern ipc_port_t ipc_port_make_send_any(
872 	ipc_port_t      port) __result_use_check;
873 
874 /*!
875  * @function ipc_port_make_send_mqueue()
876  *
877  * @brief
878  * Makes a naked send right for the specified port.
879  *
880  * @decription
881  * @see ipc_port_make_send_any_locked() for a general warning about
882  * making send rights.
883  *
884  * This function will return IP_NULL if the port wasn't a message queue.
885  *
886  * This avoids confusions where kobject ports are being set in places
887  * where the system expects message queues.
888  *
889  * @param port          The target port.
890  *
891  * @returns
892  * - IP_NULL            if @c port was not a message queue port
893  *                      (IKOT_NONE, or IKOT_TIMER), or @c port was IP_NULL.
894  * - IP_DEAD            if @c port was dead.
895  * - @c port            if @c port was valid, in which case
896  *                      a naked send right was made.
897  */
898 extern ipc_port_t ipc_port_make_send_mqueue(
899 	ipc_port_t      port) __result_use_check;
900 
901 /*!
902  * @function ipc_port_copy_send_any_locked()
903  *
904  * @brief
905  * Copies a naked send right for a locked and active port.
906  *
907  * @decription
908  * This function doesn't perform any validation on the type of port,
909  * this duty is left to the caller.
910  *
911  * @param port          An active and locked port.
912  */
913 extern void ipc_port_copy_send_any_locked(
914 	ipc_port_t      port);
915 
916 /*!
917  * @function ipc_port_make_send_any()
918  *
919  * @brief
920  * Copies a naked send right for the specified port.
921  *
922  * @decription
923  * This function doesn't perform any validation on the type of port,
924  * this duty is left to the caller.
925  *
926  * Using @c ipc_port_copy_send_mqueue() or @c ipc_kobject_copy_send()
927  * is preferred.
928  *
929  * @param port          The target port.
930  *
931  * @returns
932  * - IP_DEAD            if @c port was dead.
933  * - @c port            if @c port was valid, in which case
934  *                      a naked send right was made.
935  */
936 extern ipc_port_t ipc_port_copy_send_any(
937 	ipc_port_t      port) __result_use_check;
938 
939 /*!
940  * @function ipc_port_copy_send_mqueue()
941  *
942  * @brief
943  * Copies a naked send right for the specified port.
944  *
945  * @decription
946  * This function will return IP_NULL if the port wasn't a message queue.
947  *
948  * This avoids confusions where kobject ports are being set in places
949  * where the system expects message queues.
950  *
951  * @param port          The target port.
952  *
953  * @returns
954  * - IP_NULL            if @c port was not a message queue port
955  *                      (IKOT_NONE, or IKOT_TIMER), or @c port was IP_NULL.
956  * - IP_DEAD            if @c port was dead.
957  * - @c port            if @c port was valid, in which case
958  *                      a naked send right was made.
959  */
960 extern ipc_port_t ipc_port_copy_send_mqueue(
961 	ipc_port_t      port) __result_use_check;
962 
963 /* Copyout a naked send right */
964 extern mach_port_name_t ipc_port_copyout_send(
965 	ipc_port_t      sright,
966 	ipc_space_t     space);
967 
968 extern mach_port_name_t ipc_port_copyout_send_pinned(
969 	ipc_port_t      sright,
970 	ipc_space_t     space);
971 
972 extern void ipc_port_thread_group_blocked(
973 	ipc_port_t      port);
974 
975 extern void ipc_port_thread_group_unblocked(void);
976 
977 extern void ipc_port_release_send_and_unlock(
978 	ipc_port_t      port);
979 #endif /* MACH_KERNEL_PRIVATE */
980 
981 #if KERNEL_PRIVATE
982 
983 /* Release a (valid) naked send right */
984 extern void ipc_port_release_send(
985 	ipc_port_t      port);
986 
987 extern void ipc_port_reference(
988 	ipc_port_t port);
989 
990 extern void ipc_port_release(
991 	ipc_port_t port);
992 
993 struct thread_attr_for_ipc_propagation {
994 	union {
995 		struct {
996 			uint64_t tafip_iotier:2,
997 			    tafip_qos:3;
998 		};
999 		uint64_t tafip_value;
1000 	};
1001 	uint64_t tafip_reserved;
1002 };
1003 
1004 extern kern_return_t
1005 ipc_port_propagate_thread_attr(
1006 	ipc_port_t port,
1007 	struct thread_attr_for_ipc_propagation attr);
1008 
1009 extern kern_return_t
1010 ipc_port_reset_thread_attr(ipc_port_t port);
1011 #endif /* KERNEL_PRIVATE */
1012 
1013 #ifdef MACH_KERNEL_PRIVATE
1014 
1015 /* Make a naked send-once right from a locked and active receive right */
1016 extern ipc_port_t ipc_port_make_sonce_locked(
1017 	ipc_port_t      port);
1018 
1019 /* Make a naked send-once right from a receive right */
1020 extern ipc_port_t ipc_port_make_sonce(
1021 	ipc_port_t      port);
1022 
1023 /* Release a naked send-once right */
1024 extern void ipc_port_release_sonce(
1025 	ipc_port_t      port);
1026 
1027 /* Release a naked send-once right */
1028 extern void ipc_port_release_sonce_and_unlock(
1029 	ipc_port_t      port);
1030 
1031 /* Release a naked (in limbo or in transit) receive right */
1032 extern void ipc_port_release_receive(
1033 	ipc_port_t      port);
1034 
1035 /* Finalize the destruction of a port before it gets freed */
1036 extern void ipc_port_finalize(
1037 	ipc_port_t      port);
1038 
1039 /* Get receiver task and its pid (if any) for port. Assumes port is locked. */
1040 extern pid_t ipc_port_get_receiver_task_locked(ipc_port_t port, uintptr_t *task);
1041 
1042 /* Get receiver task and its pid (if any) for port. */
1043 extern pid_t ipc_port_get_receiver_task(ipc_port_t port, uintptr_t *task);
1044 
1045 /* Allocate a port in a special space */
1046 extern ipc_port_t ipc_port_alloc_special(
1047 	ipc_space_t             space,
1048 	ipc_port_init_flags_t   flags);
1049 
1050 /* Deallocate a port in a special space */
1051 extern void ipc_port_dealloc_special_and_unlock(
1052 	ipc_port_t      port,
1053 	ipc_space_t     space);
1054 
1055 /* Deallocate a port in a special space */
1056 extern void ipc_port_dealloc_special(
1057 	ipc_port_t      port,
1058 	ipc_space_t     space);
1059 
1060 extern void ipc_port_recv_update_inheritor(ipc_port_t port,
1061     struct turnstile *turnstile,
1062     turnstile_update_flags_t flags);
1063 
1064 extern void ipc_port_send_update_inheritor(ipc_port_t port,
1065     struct turnstile *turnstile,
1066     turnstile_update_flags_t flags);
1067 
1068 extern int
1069 ipc_special_reply_get_pid_locked(ipc_port_t port);
1070 
1071 #define ipc_port_alloc_reply()          \
1072 	ipc_port_alloc_special(ipc_space_reply, IPC_PORT_INIT_MESSAGE_QUEUE | IPC_PORT_INIT_SPECIAL_REPLY)
1073 #define ipc_port_dealloc_reply(port)    \
1074 	ipc_port_dealloc_special((port), ipc_space_reply)
1075 
1076 #endif /* MACH_KERNEL_PRIVATE */
1077 
1078 #endif  /* _IPC_IPC_PORT_H_ */
1079