xref: /xnu-11215.81.4/bsd/kern/kern_sig.c (revision d4514f0bc1d3f944c22d92e68b646ac3fb40d452)
1 /*
2  * Copyright (c) 1995-2016 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  * Copyright (c) 1982, 1986, 1989, 1991, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  * (c) UNIX System Laboratories, Inc.
32  * All or some portions of this file are derived from material licensed
33  * to the University of California by American Telephone and Telegraph
34  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
35  * the permission of UNIX System Laboratories, Inc.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
66  */
67 /*
68  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
69  * support for mandatory and extensible security protections.  This notice
70  * is included in support of clause 2.2 (b) of the Apple Public License,
71  * Version 2.0.
72  */
73 
74 #define SIGPROP         /* include signal properties table */
75 #include <sys/param.h>
76 #include <sys/resourcevar.h>
77 #include <sys/proc_internal.h>
78 #include <sys/kauth.h>
79 #include <sys/systm.h>
80 #include <sys/timeb.h>
81 #include <sys/times.h>
82 #include <sys/acct.h>
83 #include <sys/file_internal.h>
84 #include <sys/kernel.h>
85 #include <sys/wait.h>
86 #include <sys/signalvar.h>
87 #include <sys/syslog.h>
88 #include <sys/stat.h>
89 #include <sys/lock.h>
90 #include <sys/kdebug.h>
91 #include <sys/reason.h>
92 
93 #include <sys/mount.h>
94 #include <sys/sysproto.h>
95 
96 #include <security/audit/audit.h>
97 
98 #include <kern/cpu_number.h>
99 
100 #include <sys/vm.h>
101 #include <sys/user.h>           /* for coredump */
102 #include <kern/ast.h>           /* for APC support */
103 #include <kern/kalloc.h>
104 #include <kern/task.h>          /* extern void   *get_bsdtask_info(task_t); */
105 #include <kern/thread.h>
106 #include <kern/sched_prim.h>
107 #include <kern/thread_call.h>
108 #include <kern/policy_internal.h>
109 #include <kern/sync_sema.h>
110 
111 #include <vm/vm_shared_region_xnu.h>
112 
113 #include <os/log.h>
114 
115 #include <mach/exception.h>
116 #include <mach/task.h>
117 #include <mach/thread_act.h>
118 #include <libkern/OSAtomic.h>
119 
120 #include <sys/sdt.h>
121 #include <sys/codesign.h>
122 #include <sys/random.h>
123 #include <libkern/section_keywords.h>
124 
125 #if CONFIG_MACF
126 #include <security/mac_framework.h>
127 #endif
128 
129 /*
130  * Missing prototypes that Mach should export
131  *
132  * +++
133  */
134 extern int thread_enable_fpe(thread_t act, int onoff);
135 extern kern_return_t get_signalact(task_t, thread_t *, int);
136 extern unsigned int get_useraddr(void);
137 extern boolean_t task_did_exec(task_t task);
138 extern boolean_t task_is_exec_copy(task_t task);
139 
140 /*
141  * ---
142  */
143 
144 extern void doexception(int exc, mach_exception_code_t code,
145     mach_exception_subcode_t sub);
146 
147 static void stop(proc_t, proc_t);
148 static int cansignal_nomac(proc_t, kauth_cred_t, proc_t, int);
149 int cansignal(proc_t, kauth_cred_t, proc_t, int);
150 int killpg1(proc_t, int, int, int, int);
151 kern_return_t do_bsdexception(int, int, int);
152 void __posix_sem_syscall_return(kern_return_t);
153 char *proc_name_address(void *p);
154 
155 static int      filt_sigattach(struct knote *kn, struct kevent_qos_s *kev);
156 static void     filt_sigdetach(struct knote *kn);
157 static int      filt_signal(struct knote *kn, long hint);
158 static int      filt_signaltouch(struct knote *kn, struct kevent_qos_s *kev);
159 static int      filt_signalprocess(struct knote *kn, struct kevent_qos_s *kev);
160 
161 SECURITY_READ_ONLY_EARLY(struct filterops) sig_filtops = {
162 	.f_attach = filt_sigattach,
163 	.f_detach = filt_sigdetach,
164 	.f_event = filt_signal,
165 	.f_touch = filt_signaltouch,
166 	.f_process = filt_signalprocess,
167 };
168 
169 /* structures  and fns for killpg1 iterartion callback and filters */
170 struct killpg1_filtargs {
171 	bool posix;
172 	proc_t curproc;
173 };
174 
175 struct killpg1_iterargs {
176 	proc_t curproc;
177 	kauth_cred_t uc;
178 	int signum;
179 	int nfound;
180 };
181 
182 static int killpg1_allfilt(proc_t p, void * arg);
183 static int killpg1_callback(proc_t p, void * arg);
184 
185 static int pgsignal_callback(proc_t p, void * arg);
186 static kern_return_t get_signalthread(proc_t, int, thread_t *);
187 
188 
189 /* flags for psignal_internal */
190 #define PSIG_LOCKED     0x1
191 #define PSIG_VFORK      0x2
192 #define PSIG_THREAD     0x4
193 #define PSIG_TRY_THREAD 0x8
194 
195 static os_reason_t build_signal_reason(int signum, const char *procname);
196 static void psignal_internal(proc_t p, task_t task, thread_t thread, int flavor, int signum, os_reason_t signal_reason);
197 
198 /*
199  * NOTE: Source and target may *NOT* overlap! (target is smaller)
200  */
201 static void
sigaltstack_kern_to_user32(struct kern_sigaltstack * in,struct user32_sigaltstack * out)202 sigaltstack_kern_to_user32(struct kern_sigaltstack *in, struct user32_sigaltstack *out)
203 {
204 	out->ss_sp          = CAST_DOWN_EXPLICIT(user32_addr_t, in->ss_sp);
205 	out->ss_size    = CAST_DOWN_EXPLICIT(user32_size_t, in->ss_size);
206 	out->ss_flags   = in->ss_flags;
207 }
208 
209 static void
sigaltstack_kern_to_user64(struct kern_sigaltstack * in,struct user64_sigaltstack * out)210 sigaltstack_kern_to_user64(struct kern_sigaltstack *in, struct user64_sigaltstack *out)
211 {
212 	out->ss_sp          = in->ss_sp;
213 	out->ss_size    = in->ss_size;
214 	out->ss_flags   = in->ss_flags;
215 }
216 
217 /*
218  * NOTE: Source and target may are permitted to overlap! (source is smaller);
219  * this works because we copy fields in order from the end of the struct to
220  * the beginning.
221  */
222 static void
sigaltstack_user32_to_kern(struct user32_sigaltstack * in,struct kern_sigaltstack * out)223 sigaltstack_user32_to_kern(struct user32_sigaltstack *in, struct kern_sigaltstack *out)
224 {
225 	out->ss_flags   = in->ss_flags;
226 	out->ss_size    = in->ss_size;
227 	out->ss_sp              = CAST_USER_ADDR_T(in->ss_sp);
228 }
229 static void
sigaltstack_user64_to_kern(struct user64_sigaltstack * in,struct kern_sigaltstack * out)230 sigaltstack_user64_to_kern(struct user64_sigaltstack *in, struct kern_sigaltstack *out)
231 {
232 	out->ss_flags   = in->ss_flags;
233 	out->ss_size    = (user_size_t)in->ss_size;
234 	out->ss_sp      = (user_addr_t)in->ss_sp;
235 }
236 
237 static void
sigaction_kern_to_user32(struct kern_sigaction * in,struct user32_sigaction * out)238 sigaction_kern_to_user32(struct kern_sigaction *in, struct user32_sigaction *out)
239 {
240 	/* This assumes 32 bit __sa_handler is of type sig_t */
241 	out->__sigaction_u.__sa_handler = CAST_DOWN_EXPLICIT(user32_addr_t, in->__sigaction_u.__sa_handler);
242 	out->sa_mask = in->sa_mask;
243 	out->sa_flags = in->sa_flags;
244 }
245 static void
sigaction_kern_to_user64(struct kern_sigaction * in,struct user64_sigaction * out)246 sigaction_kern_to_user64(struct kern_sigaction *in, struct user64_sigaction *out)
247 {
248 	/* This assumes 32 bit __sa_handler is of type sig_t */
249 	out->__sigaction_u.__sa_handler = in->__sigaction_u.__sa_handler;
250 	out->sa_mask = in->sa_mask;
251 	out->sa_flags = in->sa_flags;
252 }
253 
254 static void
__sigaction_user32_to_kern(struct __user32_sigaction * in,struct __kern_sigaction * out)255 __sigaction_user32_to_kern(struct __user32_sigaction *in, struct __kern_sigaction *out)
256 {
257 	out->__sigaction_u.__sa_handler = CAST_USER_ADDR_T(in->__sigaction_u.__sa_handler);
258 	out->sa_tramp = CAST_USER_ADDR_T(in->sa_tramp);
259 	out->sa_mask = in->sa_mask;
260 	out->sa_flags = in->sa_flags;
261 
262 	kern_return_t kr;
263 	kr = machine_thread_function_pointers_convert_from_user(current_thread(),
264 	    &out->sa_tramp, 1);
265 	assert(kr == KERN_SUCCESS);
266 }
267 
268 static void
__sigaction_user64_to_kern(struct __user64_sigaction * in,struct __kern_sigaction * out)269 __sigaction_user64_to_kern(struct __user64_sigaction *in, struct __kern_sigaction *out)
270 {
271 	out->__sigaction_u.__sa_handler = (user_addr_t)in->__sigaction_u.__sa_handler;
272 	out->sa_tramp = (user_addr_t)in->sa_tramp;
273 	out->sa_mask = in->sa_mask;
274 	out->sa_flags = in->sa_flags;
275 
276 	kern_return_t kr;
277 	kr = machine_thread_function_pointers_convert_from_user(current_thread(),
278 	    &out->sa_tramp, 1);
279 	assert(kr == KERN_SUCCESS);
280 }
281 
282 #if SIGNAL_DEBUG
283 void ram_printf(int);
284 int ram_debug = 0;
285 unsigned int rdebug_proc = 0;
286 void
ram_printf(int x)287 ram_printf(int x)
288 {
289 	printf("x is %d", x);
290 }
291 #endif /* SIGNAL_DEBUG */
292 
293 
294 void
signal_setast(thread_t sig_actthread)295 signal_setast(thread_t sig_actthread)
296 {
297 	act_set_astbsd(sig_actthread);
298 }
299 
300 static int
cansignal_nomac(proc_t src,kauth_cred_t uc_src,proc_t dst,int signum)301 cansignal_nomac(proc_t src, kauth_cred_t uc_src, proc_t dst, int signum)
302 {
303 	/* you can signal yourself */
304 	if (src == dst) {
305 		return 1;
306 	}
307 
308 	/* you can't send the init proc SIGKILL, even if root */
309 	if (signum == SIGKILL && dst == initproc) {
310 		return 0;
311 	}
312 
313 	/* otherwise, root can always signal */
314 	if (kauth_cred_issuser(uc_src)) {
315 		return 1;
316 	}
317 
318 	/* processes in the same session can send SIGCONT to each other */
319 	if (signum == SIGCONT && proc_sessionid(src) == proc_sessionid(dst)) {
320 		return 1;
321 	}
322 
323 #if XNU_TARGET_OS_IOS
324 	// Allow debugging of third party drivers on iOS
325 	if (proc_is_third_party_debuggable_driver(dst)) {
326 		return 1;
327 	}
328 #endif /* XNU_TARGET_OS_IOS */
329 
330 	/* the source process must be authorized to signal the target */
331 	{
332 		int allowed = 0;
333 		kauth_cred_t uc_dst = NOCRED, uc_ref = NOCRED;
334 
335 		uc_dst = uc_ref = kauth_cred_proc_ref(dst);
336 
337 		/*
338 		 * If the real or effective UID of the sender matches the real or saved
339 		 * UID of the target, allow the signal to be sent.
340 		 */
341 		if (kauth_cred_getruid(uc_src) == kauth_cred_getruid(uc_dst) ||
342 		    kauth_cred_getruid(uc_src) == kauth_cred_getsvuid(uc_dst) ||
343 		    kauth_cred_getuid(uc_src) == kauth_cred_getruid(uc_dst) ||
344 		    kauth_cred_getuid(uc_src) == kauth_cred_getsvuid(uc_dst)) {
345 			allowed = 1;
346 		}
347 
348 		if (uc_ref != NOCRED) {
349 			kauth_cred_unref(&uc_ref);
350 			uc_ref = NOCRED;
351 		}
352 
353 		return allowed;
354 	}
355 }
356 
357 /*
358  * Can process `src`, with ucred `uc_src`, send the signal `signum` to process
359  * `dst`?  The ucred is referenced by the caller so internal fileds can be used
360  * safely.
361  */
362 int
cansignal(proc_t src,kauth_cred_t uc_src,proc_t dst,int signum)363 cansignal(proc_t src, kauth_cred_t uc_src, proc_t dst, int signum)
364 {
365 #if CONFIG_MACF
366 	if (mac_proc_check_signal(src, dst, signum)) {
367 		return 0;
368 	}
369 #endif
370 
371 	return cansignal_nomac(src, uc_src, dst, signum);
372 }
373 
374 /*
375  * <rdar://problem/21952708> Some signals can be restricted from being handled,
376  * forcing the default action for that signal. This behavior applies only to
377  * non-root (EUID != 0) processes, and is configured with the "sigrestrict=x"
378  * bootarg:
379  *
380  *   0 (default): Disallow use of restricted signals. Trying to register a handler
381  *		returns ENOTSUP, which userspace may use to take special action (e.g. abort).
382  *   1: As above, but return EINVAL. Restricted signals behave similarly to SIGKILL.
383  *   2: Usual POSIX semantics.
384  */
385 static TUNABLE(unsigned, sigrestrict_arg, "sigrestrict", 0);
386 
387 #if XNU_PLATFORM_WatchOS
388 static int
sigrestrictmask(void)389 sigrestrictmask(void)
390 {
391 	if (kauth_getuid() != 0 && sigrestrict_arg != 2) {
392 		return SIGRESTRICTMASK;
393 	}
394 	return 0;
395 }
396 
397 static int
signal_is_restricted(proc_t p,int signum)398 signal_is_restricted(proc_t p, int signum)
399 {
400 	if (sigmask(signum) & sigrestrictmask()) {
401 		if (sigrestrict_arg == 0 &&
402 		    task_get_apptype(proc_task(p)) == TASK_APPTYPE_APP_DEFAULT) {
403 			return ENOTSUP;
404 		} else {
405 			return EINVAL;
406 		}
407 	}
408 	return 0;
409 }
410 
411 #else
412 
413 static inline int
signal_is_restricted(proc_t p,int signum)414 signal_is_restricted(proc_t p, int signum)
415 {
416 	(void)p;
417 	(void)signum;
418 	return 0;
419 }
420 #endif /* !XNU_PLATFORM_WatchOS */
421 
422 /*
423  * Returns:	0			Success
424  *		EINVAL
425  *	copyout:EFAULT
426  *	copyin:EFAULT
427  *
428  * Notes:	Uses current thread as a parameter to inform PPC to enable
429  *		FPU exceptions via setsigvec(); this operation is not proxy
430  *		safe!
431  */
432 /* ARGSUSED */
433 int
sigaction(proc_t p,struct sigaction_args * uap,__unused int32_t * retval)434 sigaction(proc_t p, struct sigaction_args *uap, __unused int32_t *retval)
435 {
436 	struct kern_sigaction vec;
437 	struct __kern_sigaction __vec;
438 
439 	struct kern_sigaction *sa = &vec;
440 	struct sigacts *ps = &p->p_sigacts;
441 
442 	int signum;
443 	int bit, error = 0;
444 	uint32_t sigreturn_validation = PS_SIGRETURN_VALIDATION_DEFAULT;
445 
446 	signum = uap->signum;
447 	if (signum <= 0 || signum >= NSIG ||
448 	    signum == SIGKILL || signum == SIGSTOP) {
449 		return EINVAL;
450 	}
451 
452 	if (uap->nsa) {
453 		if (IS_64BIT_PROCESS(p)) {
454 			struct __user64_sigaction       __vec64;
455 			error = copyin(uap->nsa, &__vec64, sizeof(__vec64));
456 			__sigaction_user64_to_kern(&__vec64, &__vec);
457 		} else {
458 			struct __user32_sigaction       __vec32;
459 			error = copyin(uap->nsa, &__vec32, sizeof(__vec32));
460 			__sigaction_user32_to_kern(&__vec32, &__vec);
461 		}
462 		if (error) {
463 			return error;
464 		}
465 
466 		sigreturn_validation = (__vec.sa_flags & SA_VALIDATE_SIGRETURN_FROM_SIGTRAMP) ?
467 		    PS_SIGRETURN_VALIDATION_ENABLED : PS_SIGRETURN_VALIDATION_DISABLED;
468 		__vec.sa_flags &= SA_USERSPACE_MASK; /* Only pass on valid sa_flags */
469 
470 		if ((__vec.sa_flags & SA_SIGINFO) || __vec.sa_handler != SIG_DFL) {
471 			if ((error = signal_is_restricted(p, signum))) {
472 				if (error == ENOTSUP) {
473 					printf("%s(%d): denied attempt to register action for signal %d\n",
474 					    proc_name_address(p), proc_pid(p), signum);
475 				}
476 				return error;
477 			}
478 		}
479 	}
480 
481 	if (uap->osa) {
482 		sa->sa_handler = SIGACTION(p, signum);
483 		sa->sa_mask = ps->ps_catchmask[signum];
484 		bit = sigmask(signum);
485 		sa->sa_flags = 0;
486 		if ((ps->ps_sigonstack & bit) != 0) {
487 			sa->sa_flags |= SA_ONSTACK;
488 		}
489 		if ((ps->ps_sigintr & bit) == 0) {
490 			sa->sa_flags |= SA_RESTART;
491 		}
492 		if (ps->ps_siginfo & bit) {
493 			sa->sa_flags |= SA_SIGINFO;
494 		}
495 		if (ps->ps_signodefer & bit) {
496 			sa->sa_flags |= SA_NODEFER;
497 		}
498 		if ((signum == SIGCHLD) && (p->p_flag & P_NOCLDSTOP)) {
499 			sa->sa_flags |= SA_NOCLDSTOP;
500 		}
501 		if ((signum == SIGCHLD) && (p->p_flag & P_NOCLDWAIT)) {
502 			sa->sa_flags |= SA_NOCLDWAIT;
503 		}
504 
505 		if (IS_64BIT_PROCESS(p)) {
506 			struct user64_sigaction vec64 = {};
507 			sigaction_kern_to_user64(sa, &vec64);
508 			error = copyout(&vec64, uap->osa, sizeof(vec64));
509 		} else {
510 			struct user32_sigaction vec32 = {};
511 			sigaction_kern_to_user32(sa, &vec32);
512 			error = copyout(&vec32, uap->osa, sizeof(vec32));
513 		}
514 		if (error) {
515 			return error;
516 		}
517 	}
518 
519 	if (uap->nsa) {
520 		uint32_t old_sigreturn_validation = atomic_load_explicit(
521 			&ps->ps_sigreturn_validation, memory_order_relaxed);
522 		if (old_sigreturn_validation == PS_SIGRETURN_VALIDATION_DEFAULT) {
523 			atomic_compare_exchange_strong_explicit(&ps->ps_sigreturn_validation,
524 			    &old_sigreturn_validation, sigreturn_validation,
525 			    memory_order_relaxed, memory_order_relaxed);
526 		}
527 		error = setsigvec(p, current_thread(), signum, &__vec, FALSE);
528 	}
529 
530 	return error;
531 }
532 
533 /* Routines to manipulate bits on all threads */
534 int
clear_procsiglist(proc_t p,int bit,boolean_t in_signalstart)535 clear_procsiglist(proc_t p, int bit, boolean_t in_signalstart)
536 {
537 	struct uthread * uth;
538 
539 	proc_lock(p);
540 	if (!in_signalstart) {
541 		proc_signalstart(p, 1);
542 	}
543 
544 
545 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
546 		uth->uu_siglist &= ~bit;
547 	}
548 	p->p_siglist &= ~bit;
549 	if (!in_signalstart) {
550 		proc_signalend(p, 1);
551 	}
552 	proc_unlock(p);
553 
554 	return 0;
555 }
556 
557 
558 static int
unblock_procsigmask(proc_t p,int bit)559 unblock_procsigmask(proc_t p, int bit)
560 {
561 	struct uthread * uth;
562 
563 	proc_lock(p);
564 	proc_signalstart(p, 1);
565 
566 
567 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
568 		uth->uu_sigmask &= ~bit;
569 	}
570 	p->p_sigmask &= ~bit;
571 
572 	proc_signalend(p, 1);
573 	proc_unlock(p);
574 	return 0;
575 }
576 
577 static int
block_procsigmask(proc_t p,int bit)578 block_procsigmask(proc_t p, int bit)
579 {
580 	struct uthread * uth;
581 
582 	proc_lock(p);
583 	proc_signalstart(p, 1);
584 
585 
586 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
587 		uth->uu_sigmask |= bit;
588 	}
589 	p->p_sigmask |=  bit;
590 
591 	proc_signalend(p, 1);
592 	proc_unlock(p);
593 	return 0;
594 }
595 
596 int
set_procsigmask(proc_t p,int bit)597 set_procsigmask(proc_t p, int bit)
598 {
599 	struct uthread * uth;
600 
601 	proc_lock(p);
602 	proc_signalstart(p, 1);
603 
604 
605 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
606 		uth->uu_sigmask = bit;
607 	}
608 	p->p_sigmask =  bit;
609 	proc_signalend(p, 1);
610 	proc_unlock(p);
611 
612 	return 0;
613 }
614 
615 /* XXX should be static? */
616 /*
617  * Notes:	The thread parameter is used in the PPC case to select the
618  *		thread on which the floating point exception will be enabled
619  *		or disabled.  We can't simply take current_thread(), since
620  *		this is called from posix_spawn() on the not currently running
621  *		process/thread pair.
622  *
623  *		We mark thread as unused to alow compilation without warning
624  *		on non-PPC platforms.
625  */
626 int
setsigvec(proc_t p,__unused thread_t thread,int signum,struct __kern_sigaction * sa,boolean_t in_sigstart)627 setsigvec(proc_t p, __unused thread_t thread, int signum, struct __kern_sigaction *sa, boolean_t in_sigstart)
628 {
629 	struct sigacts *ps = &p->p_sigacts;
630 	int bit;
631 
632 	assert(signum < NSIG);
633 
634 	if ((signum == SIGKILL || signum == SIGSTOP) &&
635 	    sa->sa_handler != SIG_DFL) {
636 		return EINVAL;
637 	}
638 	bit = sigmask(signum);
639 	/*
640 	 * Change setting atomically.
641 	 */
642 	proc_set_sigact_trampact(p, signum, sa->sa_handler, sa->sa_tramp);
643 	ps->ps_catchmask[signum] = sa->sa_mask & ~sigcantmask;
644 	if (sa->sa_flags & SA_SIGINFO) {
645 		ps->ps_siginfo |= bit;
646 	} else {
647 		ps->ps_siginfo &= ~bit;
648 	}
649 	if ((sa->sa_flags & SA_RESTART) == 0) {
650 		ps->ps_sigintr |= bit;
651 	} else {
652 		ps->ps_sigintr &= ~bit;
653 	}
654 	if (sa->sa_flags & SA_ONSTACK) {
655 		ps->ps_sigonstack |= bit;
656 	} else {
657 		ps->ps_sigonstack &= ~bit;
658 	}
659 	if (sa->sa_flags & SA_RESETHAND) {
660 		ps->ps_sigreset |= bit;
661 	} else {
662 		ps->ps_sigreset &= ~bit;
663 	}
664 	if (sa->sa_flags & SA_NODEFER) {
665 		ps->ps_signodefer |= bit;
666 	} else {
667 		ps->ps_signodefer &= ~bit;
668 	}
669 	if (signum == SIGCHLD) {
670 		if (sa->sa_flags & SA_NOCLDSTOP) {
671 			OSBitOrAtomic(P_NOCLDSTOP, &p->p_flag);
672 		} else {
673 			OSBitAndAtomic(~((uint32_t)P_NOCLDSTOP), &p->p_flag);
674 		}
675 		if ((sa->sa_flags & SA_NOCLDWAIT) || (sa->sa_handler == SIG_IGN)) {
676 			OSBitOrAtomic(P_NOCLDWAIT, &p->p_flag);
677 		} else {
678 			OSBitAndAtomic(~((uint32_t)P_NOCLDWAIT), &p->p_flag);
679 		}
680 	}
681 
682 	/*
683 	 * Set bit in p_sigignore for signals that are set to SIG_IGN,
684 	 * and for signals set to SIG_DFL where the default is to ignore.
685 	 * However, don't put SIGCONT in p_sigignore,
686 	 * as we have to restart the process.
687 	 */
688 	if (sa->sa_handler == SIG_IGN ||
689 	    (sigprop[signum] & SA_IGNORE && sa->sa_handler == SIG_DFL)) {
690 		clear_procsiglist(p, bit, in_sigstart);
691 		if (signum != SIGCONT) {
692 			p->p_sigignore |= bit;  /* easier in psignal */
693 		}
694 		p->p_sigcatch &= ~bit;
695 	} else {
696 		p->p_sigignore &= ~bit;
697 		if (sa->sa_handler == SIG_DFL) {
698 			p->p_sigcatch &= ~bit;
699 		} else {
700 			p->p_sigcatch |= bit;
701 		}
702 	}
703 	return 0;
704 }
705 
706 /*
707  * Initialize signal state for process 0;
708  * set to ignore signals that are ignored by default.
709  */
710 void
siginit(proc_t p)711 siginit(proc_t p)
712 {
713 	int i;
714 
715 	for (i = 1; i < NSIG; i++) {
716 		if (sigprop[i] & SA_IGNORE && i != SIGCONT) {
717 			p->p_sigignore |= sigmask(i);
718 		}
719 	}
720 }
721 
722 /*
723  * Reset signals for an exec of the specified process.
724  */
725 void
execsigs(proc_t p,thread_t thread)726 execsigs(proc_t p, thread_t thread)
727 {
728 	struct sigacts *ps = &p->p_sigacts;
729 	int nc, mask;
730 	struct uthread *ut;
731 
732 	ut = (struct uthread *)get_bsdthread_info(thread);
733 
734 	/*
735 	 * transfer saved signal states from the process
736 	 * back to the current thread.
737 	 *
738 	 * NOTE: We do this without the process locked,
739 	 * because we are guaranteed to be single-threaded
740 	 * by this point in exec and the p_siglist is
741 	 * only accessed by threads inside the process.
742 	 */
743 	ut->uu_siglist |= p->p_siglist;
744 	p->p_siglist = 0;
745 
746 	/*
747 	 * Reset caught signals.  Held signals remain held
748 	 * through p_sigmask (unless they were caught,
749 	 * and are now ignored by default).
750 	 */
751 	proc_reset_sigact(p, p->p_sigcatch);
752 	while (p->p_sigcatch) {
753 		nc = ffs((unsigned int)p->p_sigcatch);
754 		mask = sigmask(nc);
755 		p->p_sigcatch &= ~mask;
756 		if (sigprop[nc] & SA_IGNORE) {
757 			if (nc != SIGCONT) {
758 				p->p_sigignore |= mask;
759 			}
760 			ut->uu_siglist &= ~mask;
761 		}
762 	}
763 
764 	atomic_store_explicit(&ps->ps_sigreturn_validation,
765 	    PS_SIGRETURN_VALIDATION_DEFAULT, memory_order_relaxed);
766 
767 	/*
768 	 * Reset stack state to the user stack.
769 	 * Clear set of signals caught on the signal stack.
770 	 */
771 	/* thread */
772 	ut->uu_sigstk.ss_flags = SA_DISABLE;
773 	ut->uu_sigstk.ss_size = 0;
774 	ut->uu_sigstk.ss_sp = USER_ADDR_NULL;
775 	ut->uu_flag &= ~UT_ALTSTACK;
776 	/* process */
777 	ps->ps_sigonstack = 0;
778 }
779 
780 /*
781  * Manipulate signal mask.
782  * Note that we receive new mask, not pointer,
783  * and return old mask as return value;
784  * the library stub does the rest.
785  */
786 int
sigprocmask(proc_t p,struct sigprocmask_args * uap,__unused int32_t * retval)787 sigprocmask(proc_t p, struct sigprocmask_args *uap, __unused int32_t *retval)
788 {
789 	int error = 0;
790 	sigset_t oldmask, nmask;
791 	user_addr_t omask = uap->omask;
792 	struct uthread *ut;
793 
794 	ut = current_uthread();
795 	oldmask  = ut->uu_sigmask;
796 
797 	if (uap->mask == USER_ADDR_NULL) {
798 		/* just want old mask */
799 		goto out;
800 	}
801 	error = copyin(uap->mask, &nmask, sizeof(sigset_t));
802 	if (error) {
803 		goto out;
804 	}
805 
806 	switch (uap->how) {
807 	case SIG_BLOCK:
808 		block_procsigmask(p, (nmask & ~sigcantmask));
809 		signal_setast(current_thread());
810 		break;
811 
812 	case SIG_UNBLOCK:
813 		unblock_procsigmask(p, (nmask & ~sigcantmask));
814 		signal_setast(current_thread());
815 		break;
816 
817 	case SIG_SETMASK:
818 		set_procsigmask(p, (nmask & ~sigcantmask));
819 		signal_setast(current_thread());
820 		break;
821 
822 	default:
823 		error = EINVAL;
824 		break;
825 	}
826 out:
827 	if (!error && omask != USER_ADDR_NULL) {
828 		copyout(&oldmask, omask, sizeof(sigset_t));
829 	}
830 	return error;
831 }
832 
833 int
sigpending(__unused proc_t p,struct sigpending_args * uap,__unused int32_t * retval)834 sigpending(__unused proc_t p, struct sigpending_args *uap, __unused int32_t *retval)
835 {
836 	struct uthread *ut;
837 	sigset_t pendlist;
838 
839 	ut = current_uthread();
840 	pendlist = ut->uu_siglist;
841 
842 	if (uap->osv) {
843 		copyout(&pendlist, uap->osv, sizeof(sigset_t));
844 	}
845 	return 0;
846 }
847 
848 /*
849  * Suspend process until signal, providing mask to be set
850  * in the meantime.  Note nonstandard calling convention:
851  * libc stub passes mask, not pointer, to save a copyin.
852  */
853 
854 static int
sigcontinue(__unused int error)855 sigcontinue(__unused int error)
856 {
857 //	struct uthread *ut = current_uthread();
858 	unix_syscall_return(EINTR);
859 }
860 
861 int
sigsuspend(proc_t p,struct sigsuspend_args * uap,int32_t * retval)862 sigsuspend(proc_t p, struct sigsuspend_args *uap, int32_t *retval)
863 {
864 	__pthread_testcancel(1);
865 	return sigsuspend_nocancel(p, (struct sigsuspend_nocancel_args *)uap, retval);
866 }
867 
868 int
sigsuspend_nocancel(proc_t p,struct sigsuspend_nocancel_args * uap,__unused int32_t * retval)869 sigsuspend_nocancel(proc_t p, struct sigsuspend_nocancel_args *uap, __unused int32_t *retval)
870 {
871 	struct uthread *ut;
872 
873 	ut = current_uthread();
874 
875 	/*
876 	 * When returning from sigpause, we want
877 	 * the old mask to be restored after the
878 	 * signal handler has finished.  Thus, we
879 	 * save it here and mark the sigacts structure
880 	 * to indicate this.
881 	 */
882 	ut->uu_oldmask = ut->uu_sigmask;
883 	ut->uu_flag |= UT_SAS_OLDMASK;
884 	ut->uu_sigmask = (uap->mask & ~sigcantmask);
885 	(void) tsleep0((caddr_t) p, PPAUSE | PCATCH, "pause", 0, sigcontinue);
886 	/* always return EINTR rather than ERESTART... */
887 	return EINTR;
888 }
889 
890 
891 int
__disable_threadsignal(__unused proc_t p,__unused struct __disable_threadsignal_args * uap,__unused int32_t * retval)892 __disable_threadsignal(__unused proc_t p,
893     __unused struct __disable_threadsignal_args *uap,
894     __unused int32_t *retval)
895 {
896 	struct uthread *uth;
897 
898 	uth = current_uthread();
899 
900 	/* No longer valid to have any signal delivered */
901 	uth->uu_flag |= (UT_NO_SIGMASK | UT_CANCELDISABLE);
902 
903 	return 0;
904 }
905 
906 void
__pthread_testcancel(int presyscall)907 __pthread_testcancel(int presyscall)
908 {
909 	thread_t self = current_thread();
910 	struct uthread * uthread;
911 
912 	uthread = (struct uthread *)get_bsdthread_info(self);
913 
914 
915 	uthread->uu_flag &= ~UT_NOTCANCELPT;
916 
917 	if ((uthread->uu_flag & (UT_CANCELDISABLE | UT_CANCEL | UT_CANCELED)) == UT_CANCEL) {
918 		if (presyscall != 0) {
919 			unix_syscall_return(EINTR);
920 			/* NOTREACHED */
921 		} else {
922 			thread_abort_safely(self);
923 		}
924 	}
925 }
926 
927 
928 
929 int
__pthread_markcancel(__unused proc_t p,struct __pthread_markcancel_args * uap,__unused int32_t * retval)930 __pthread_markcancel(__unused proc_t p,
931     struct __pthread_markcancel_args *uap, __unused int32_t *retval)
932 {
933 	thread_act_t target_act;
934 	int error = 0;
935 	struct uthread *uth;
936 
937 	target_act = (thread_act_t)port_name_to_thread(uap->thread_port,
938 	    PORT_INTRANS_THREAD_IN_CURRENT_TASK);
939 
940 	if (target_act == THR_ACT_NULL) {
941 		return ESRCH;
942 	}
943 
944 	uth = (struct uthread *)get_bsdthread_info(target_act);
945 
946 	if ((uth->uu_flag & (UT_CANCEL | UT_CANCELED)) == 0) {
947 		uth->uu_flag |= (UT_CANCEL | UT_NO_SIGMASK);
948 		if (((uth->uu_flag & UT_NOTCANCELPT) == 0)
949 		    && ((uth->uu_flag & UT_CANCELDISABLE) == 0)) {
950 			thread_abort_safely(target_act);
951 		}
952 	}
953 
954 	thread_deallocate(target_act);
955 	return error;
956 }
957 
958 /* if action =0 ; return the cancellation state ,
959  *      if marked for cancellation, make the thread canceled
960  * if action = 1 ; Enable the cancel handling
961  * if action = 2; Disable the cancel handling
962  */
963 int
__pthread_canceled(__unused proc_t p,struct __pthread_canceled_args * uap,__unused int32_t * retval)964 __pthread_canceled(__unused proc_t p,
965     struct __pthread_canceled_args *uap, __unused int32_t *retval)
966 {
967 	thread_act_t thread;
968 	struct uthread *uth;
969 	int action = uap->action;
970 
971 	thread = current_thread();
972 	uth = (struct uthread *)get_bsdthread_info(thread);
973 
974 	switch (action) {
975 	case 1:
976 		uth->uu_flag &= ~UT_CANCELDISABLE;
977 		return 0;
978 	case 2:
979 		uth->uu_flag |= UT_CANCELDISABLE;
980 		return 0;
981 	case 0:
982 	default:
983 		if ((uth->uu_flag & (UT_CANCELDISABLE | UT_CANCEL | UT_CANCELED)) == UT_CANCEL) {
984 			uth->uu_flag &= ~UT_CANCEL;
985 			uth->uu_flag |= (UT_CANCELED | UT_NO_SIGMASK);
986 			return 0;
987 		}
988 		return EINVAL;
989 	}
990 	return EINVAL;
991 }
992 
993 __attribute__((noreturn))
994 void
__posix_sem_syscall_return(kern_return_t kern_result)995 __posix_sem_syscall_return(kern_return_t kern_result)
996 {
997 	int error = 0;
998 
999 	if (kern_result == KERN_SUCCESS) {
1000 		error = 0;
1001 	} else if (kern_result == KERN_ABORTED) {
1002 		error = EINTR;
1003 	} else if (kern_result == KERN_OPERATION_TIMED_OUT) {
1004 		error = ETIMEDOUT;
1005 	} else {
1006 		error = EINVAL;
1007 	}
1008 	unix_syscall_return(error);
1009 	/* does not return */
1010 }
1011 
1012 /*
1013  * Returns:	0			Success
1014  *		EINTR
1015  *		ETIMEDOUT
1016  *		EINVAL
1017  *      EFAULT if timespec is NULL
1018  */
1019 int
__semwait_signal(proc_t p,struct __semwait_signal_args * uap,int32_t * retval)1020 __semwait_signal(proc_t p, struct __semwait_signal_args *uap,
1021     int32_t *retval)
1022 {
1023 	__pthread_testcancel(0);
1024 	return __semwait_signal_nocancel(p, (struct __semwait_signal_nocancel_args *)uap, retval);
1025 }
1026 
1027 int
__semwait_signal_nocancel(__unused proc_t p,struct __semwait_signal_nocancel_args * uap,__unused int32_t * retval)1028 __semwait_signal_nocancel(__unused proc_t p, struct __semwait_signal_nocancel_args *uap,
1029     __unused int32_t *retval)
1030 {
1031 	kern_return_t kern_result;
1032 	mach_timespec_t then;
1033 	struct timespec now;
1034 	struct user_timespec ts;
1035 	boolean_t truncated_timeout = FALSE;
1036 
1037 	if (uap->timeout) {
1038 		ts.tv_sec = (user_time_t)uap->tv_sec;
1039 		ts.tv_nsec = uap->tv_nsec;
1040 
1041 		if ((ts.tv_sec & 0xFFFFFFFF00000000ULL) != 0) {
1042 			ts.tv_sec = 0xFFFFFFFF;
1043 			ts.tv_nsec = 0;
1044 			truncated_timeout = TRUE;
1045 		}
1046 
1047 		if (uap->relative) {
1048 			then.tv_sec = (unsigned int)ts.tv_sec;
1049 			then.tv_nsec = (clock_res_t)ts.tv_nsec;
1050 		} else {
1051 			nanotime(&now);
1052 
1053 			/* if time has elapsed, set time to null timepsec to bailout rightaway */
1054 			if (now.tv_sec == ts.tv_sec ?
1055 			    now.tv_nsec > ts.tv_nsec :
1056 			    now.tv_sec > ts.tv_sec) {
1057 				then.tv_sec = 0;
1058 				then.tv_nsec = 0;
1059 			} else {
1060 				then.tv_sec = (unsigned int)(ts.tv_sec - now.tv_sec);
1061 				then.tv_nsec = (clock_res_t)(ts.tv_nsec - now.tv_nsec);
1062 				if (then.tv_nsec < 0) {
1063 					then.tv_nsec += NSEC_PER_SEC;
1064 					then.tv_sec--;
1065 				}
1066 			}
1067 		}
1068 
1069 		if (uap->mutex_sem == 0) {
1070 			kern_result = semaphore_timedwait_trap_internal((mach_port_name_t)uap->cond_sem, then.tv_sec, then.tv_nsec, __posix_sem_syscall_return);
1071 		} else {
1072 			kern_result = semaphore_timedwait_signal_trap_internal(uap->cond_sem, uap->mutex_sem, then.tv_sec, then.tv_nsec, __posix_sem_syscall_return);
1073 		}
1074 	} else {
1075 		if (uap->mutex_sem == 0) {
1076 			kern_result = semaphore_wait_trap_internal(uap->cond_sem, __posix_sem_syscall_return);
1077 		} else {
1078 			kern_result = semaphore_wait_signal_trap_internal(uap->cond_sem, uap->mutex_sem, __posix_sem_syscall_return);
1079 		}
1080 	}
1081 
1082 	if (kern_result == KERN_SUCCESS && !truncated_timeout) {
1083 		return 0;
1084 	} else if (kern_result == KERN_SUCCESS && truncated_timeout) {
1085 		return EINTR; /* simulate an exceptional condition because Mach doesn't support a longer timeout */
1086 	} else if (kern_result == KERN_ABORTED) {
1087 		return EINTR;
1088 	} else if (kern_result == KERN_OPERATION_TIMED_OUT) {
1089 		return ETIMEDOUT;
1090 	} else {
1091 		return EINVAL;
1092 	}
1093 }
1094 
1095 
1096 int
__pthread_kill(__unused proc_t p,struct __pthread_kill_args * uap,__unused int32_t * retval)1097 __pthread_kill(__unused proc_t p, struct __pthread_kill_args *uap,
1098     __unused int32_t *retval)
1099 {
1100 	thread_t target_act;
1101 	int error = 0;
1102 	int signum = uap->sig;
1103 	struct uthread *uth;
1104 
1105 	target_act = (thread_t)port_name_to_thread(uap->thread_port,
1106 	    PORT_INTRANS_OPTIONS_NONE);
1107 
1108 	if (target_act == THREAD_NULL) {
1109 		return ESRCH;
1110 	}
1111 	if ((u_int)signum >= NSIG) {
1112 		error = EINVAL;
1113 		goto out;
1114 	}
1115 
1116 	uth = (struct uthread *)get_bsdthread_info(target_act);
1117 
1118 	if (uth->uu_flag & UT_NO_SIGMASK) {
1119 		error = ESRCH;
1120 		goto out;
1121 	}
1122 
1123 	/*
1124 	 * workq threads must have kills enabled through either
1125 	 * BSDTHREAD_CTL_WORKQ_ALLOW_KILL or BSDTHREAD_CTL_WORKQ_ALLOW_SIGMASK
1126 	 */
1127 	if ((thread_get_tag(target_act) & THREAD_TAG_WORKQUEUE) &&
1128 	    !(uth->uu_workq_pthread_kill_allowed || p->p_workq_allow_sigmask)) {
1129 		error = ENOTSUP;
1130 		goto out;
1131 	}
1132 
1133 	if (signum) {
1134 		psignal_uthread(target_act, signum);
1135 	}
1136 out:
1137 	thread_deallocate(target_act);
1138 	return error;
1139 }
1140 
1141 
1142 int
__pthread_sigmask(__unused proc_t p,struct __pthread_sigmask_args * uap,__unused int32_t * retval)1143 __pthread_sigmask(__unused proc_t p, struct __pthread_sigmask_args *uap,
1144     __unused int32_t *retval)
1145 {
1146 	user_addr_t set = uap->set;
1147 	user_addr_t oset = uap->oset;
1148 	sigset_t nset;
1149 	int error = 0;
1150 	struct uthread *ut;
1151 	sigset_t  oldset;
1152 
1153 	ut = current_uthread();
1154 	oldset = ut->uu_sigmask;
1155 
1156 	if (set == USER_ADDR_NULL) {
1157 		/* need only old mask */
1158 		goto out;
1159 	}
1160 
1161 	error = copyin(set, &nset, sizeof(sigset_t));
1162 	if (error) {
1163 		goto out;
1164 	}
1165 
1166 	switch (uap->how) {
1167 	case SIG_BLOCK:
1168 		ut->uu_sigmask |= (nset & ~sigcantmask);
1169 		break;
1170 
1171 	case SIG_UNBLOCK:
1172 		ut->uu_sigmask &= ~(nset);
1173 		signal_setast(current_thread());
1174 		break;
1175 
1176 	case SIG_SETMASK:
1177 		ut->uu_sigmask = (nset & ~sigcantmask);
1178 		signal_setast(current_thread());
1179 		break;
1180 
1181 	default:
1182 		error = EINVAL;
1183 	}
1184 out:
1185 	if (!error && oset != USER_ADDR_NULL) {
1186 		copyout(&oldset, oset, sizeof(sigset_t));
1187 	}
1188 
1189 	return error;
1190 }
1191 
1192 /*
1193  * Returns:	0			Success
1194  *		EINVAL
1195  *	copyin:EFAULT
1196  *	copyout:EFAULT
1197  */
1198 int
__sigwait(proc_t p,struct __sigwait_args * uap,int32_t * retval)1199 __sigwait(proc_t p, struct __sigwait_args *uap, int32_t *retval)
1200 {
1201 	__pthread_testcancel(1);
1202 	return __sigwait_nocancel(p, (struct __sigwait_nocancel_args *)uap, retval);
1203 }
1204 
1205 int
__sigwait_nocancel(proc_t p,struct __sigwait_nocancel_args * uap,__unused int32_t * retval)1206 __sigwait_nocancel(proc_t p, struct __sigwait_nocancel_args *uap, __unused int32_t *retval)
1207 {
1208 	struct uthread *ut;
1209 	struct uthread *uth;
1210 	int error = 0;
1211 	sigset_t mask;
1212 	sigset_t siglist;
1213 	sigset_t sigw = 0;
1214 	int signum;
1215 
1216 	ut = current_uthread();
1217 
1218 	if (uap->set == USER_ADDR_NULL) {
1219 		return EINVAL;
1220 	}
1221 
1222 	error = copyin(uap->set, &mask, sizeof(sigset_t));
1223 	if (error) {
1224 		return error;
1225 	}
1226 
1227 	siglist = (mask & ~sigcantmask);
1228 
1229 	if (siglist == 0) {
1230 		return EINVAL;
1231 	}
1232 
1233 	proc_lock(p);
1234 
1235 	proc_signalstart(p, 1);
1236 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
1237 		if ((sigw = uth->uu_siglist & siglist)) {
1238 			break;
1239 		}
1240 	}
1241 	proc_signalend(p, 1);
1242 
1243 	if (sigw) {
1244 		/* The signal was pending on a thread */
1245 		goto sigwait1;
1246 	}
1247 	/*
1248 	 * When returning from sigwait, we want
1249 	 * the old mask to be restored after the
1250 	 * signal handler has finished.  Thus, we
1251 	 * save it here and mark the sigacts structure
1252 	 * to indicate this.
1253 	 */
1254 	uth = ut;               /* wait for it to be delivered to us */
1255 	ut->uu_oldmask = ut->uu_sigmask;
1256 	ut->uu_flag |= UT_SAS_OLDMASK;
1257 	if (siglist == (sigset_t)0) {
1258 		proc_unlock(p);
1259 		return EINVAL;
1260 	}
1261 	/* SIGKILL and SIGSTOP are not maskable as well */
1262 	ut->uu_sigmask = ~(siglist | sigcantmask);
1263 	ut->uu_sigwait = siglist;
1264 
1265 	/* No Continuations for now */
1266 	error =  msleep((caddr_t)&ut->uu_sigwait, &p->p_mlock, PPAUSE | PCATCH, "pause", 0);
1267 
1268 	if (error == ERESTART) {
1269 		error = 0;
1270 	}
1271 
1272 	sigw = (ut->uu_sigwait & siglist);
1273 	ut->uu_sigmask = ut->uu_oldmask;
1274 	ut->uu_oldmask = 0;
1275 	ut->uu_flag &= ~UT_SAS_OLDMASK;
1276 sigwait1:
1277 	ut->uu_sigwait = 0;
1278 	if (!error) {
1279 		signum = ffs((unsigned int)sigw);
1280 		if (!signum) {
1281 			panic("sigwait with no signal wakeup");
1282 		}
1283 		/* Clear the pending signal in the thread it was delivered */
1284 		uth->uu_siglist &= ~(sigmask(signum));
1285 
1286 #if CONFIG_DTRACE
1287 		DTRACE_PROC2(signal__clear, int, signum, siginfo_t *, &(ut->t_dtrace_siginfo));
1288 #endif
1289 
1290 		proc_unlock(p);
1291 		if (uap->sig != USER_ADDR_NULL) {
1292 			error = copyout(&signum, uap->sig, sizeof(int));
1293 		}
1294 	} else {
1295 		proc_unlock(p);
1296 	}
1297 
1298 	return error;
1299 }
1300 
1301 int
sigaltstack(__unused proc_t p,struct sigaltstack_args * uap,__unused int32_t * retval)1302 sigaltstack(__unused proc_t p, struct sigaltstack_args *uap, __unused int32_t *retval)
1303 {
1304 	struct kern_sigaltstack ss;
1305 	struct kern_sigaltstack *pstk;
1306 	int error;
1307 	struct uthread *uth;
1308 	int onstack;
1309 
1310 	uth = current_uthread();
1311 
1312 	pstk = &uth->uu_sigstk;
1313 	if ((uth->uu_flag & UT_ALTSTACK) == 0) {
1314 		uth->uu_sigstk.ss_flags |= SA_DISABLE;
1315 	}
1316 	onstack = pstk->ss_flags & SA_ONSTACK;
1317 	if (uap->oss) {
1318 		if (IS_64BIT_PROCESS(p)) {
1319 			struct user64_sigaltstack ss64 = {};
1320 			sigaltstack_kern_to_user64(pstk, &ss64);
1321 			error = copyout(&ss64, uap->oss, sizeof(ss64));
1322 		} else {
1323 			struct user32_sigaltstack ss32 = {};
1324 			sigaltstack_kern_to_user32(pstk, &ss32);
1325 			error = copyout(&ss32, uap->oss, sizeof(ss32));
1326 		}
1327 		if (error) {
1328 			return error;
1329 		}
1330 	}
1331 	if (uap->nss == USER_ADDR_NULL) {
1332 		return 0;
1333 	}
1334 	if (IS_64BIT_PROCESS(p)) {
1335 		struct user64_sigaltstack ss64;
1336 		error = copyin(uap->nss, &ss64, sizeof(ss64));
1337 		sigaltstack_user64_to_kern(&ss64, &ss);
1338 	} else {
1339 		struct user32_sigaltstack ss32;
1340 		error = copyin(uap->nss, &ss32, sizeof(ss32));
1341 		sigaltstack_user32_to_kern(&ss32, &ss);
1342 	}
1343 	if (error) {
1344 		return error;
1345 	}
1346 	if ((ss.ss_flags & ~SA_DISABLE) != 0) {
1347 		return EINVAL;
1348 	}
1349 
1350 	if (ss.ss_flags & SA_DISABLE) {
1351 		/* if we are here we are not in the signal handler ;so no need to check */
1352 		if (uth->uu_sigstk.ss_flags & SA_ONSTACK) {
1353 			return EINVAL;
1354 		}
1355 		uth->uu_flag &= ~UT_ALTSTACK;
1356 		uth->uu_sigstk.ss_flags = ss.ss_flags;
1357 		return 0;
1358 	}
1359 	if (onstack) {
1360 		return EPERM;
1361 	}
1362 /* The older stacksize was 8K, enforce that one so no compat problems */
1363 #define OLDMINSIGSTKSZ 8*1024
1364 	if (ss.ss_size < OLDMINSIGSTKSZ) {
1365 		return ENOMEM;
1366 	}
1367 	uth->uu_flag |= UT_ALTSTACK;
1368 	uth->uu_sigstk = ss;
1369 	return 0;
1370 }
1371 
1372 int
kill(proc_t cp,struct kill_args * uap,__unused int32_t * retval)1373 kill(proc_t cp, struct kill_args *uap, __unused int32_t *retval)
1374 {
1375 	proc_t p;
1376 	kauth_cred_t uc = kauth_cred_get();
1377 	int posix = uap->posix;         /* !0 if posix behaviour desired */
1378 
1379 	AUDIT_ARG(pid, uap->pid);
1380 	AUDIT_ARG(signum, uap->signum);
1381 
1382 	if ((u_int)uap->signum >= NSIG) {
1383 		return EINVAL;
1384 	}
1385 	if (uap->pid > 0) {
1386 		/* kill single process */
1387 		if ((p = proc_find(uap->pid)) == NULL) {
1388 			if ((p = pzfind(uap->pid)) != NULL) {
1389 				/*
1390 				 * POSIX 1003.1-2001 requires returning success when killing a
1391 				 * zombie; see Rationale for kill(2).
1392 				 */
1393 				return 0;
1394 			}
1395 			return ESRCH;
1396 		}
1397 		AUDIT_ARG(process, p);
1398 		if (!cansignal(cp, uc, p, uap->signum)) {
1399 			proc_rele(p);
1400 			return EPERM;
1401 		}
1402 		if (uap->signum) {
1403 			psignal(p, uap->signum);
1404 		}
1405 		proc_rele(p);
1406 		return 0;
1407 	}
1408 	switch (uap->pid) {
1409 	case -1: /* broadcast signal */
1410 		return killpg1(cp, uap->signum, 0, 1, posix);
1411 	case 0: /* signal own process group */
1412 		return killpg1(cp, uap->signum, 0, 0, posix);
1413 	default: /* negative explicit process group */
1414 		return killpg1(cp, uap->signum, -(uap->pid), 0, posix);
1415 	}
1416 	/* NOTREACHED */
1417 }
1418 
1419 os_reason_t
build_userspace_exit_reason(uint32_t reason_namespace,uint64_t reason_code,user_addr_t payload,uint32_t payload_size,user_addr_t reason_string,uint64_t reason_flags)1420 build_userspace_exit_reason(uint32_t reason_namespace, uint64_t reason_code, user_addr_t payload, uint32_t payload_size,
1421     user_addr_t reason_string, uint64_t reason_flags)
1422 {
1423 	os_reason_t exit_reason = OS_REASON_NULL;
1424 
1425 	int error = 0;
1426 	int num_items_to_copy = 0;
1427 	uint32_t user_data_to_copy = 0;
1428 	char *reason_user_desc = NULL;
1429 	size_t reason_user_desc_len = 0;
1430 
1431 	exit_reason = os_reason_create(reason_namespace, reason_code);
1432 	if (exit_reason == OS_REASON_NULL) {
1433 		os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: failed to allocate exit reason\n");
1434 		return exit_reason;
1435 	}
1436 
1437 	exit_reason->osr_flags |= OS_REASON_FLAG_FROM_USERSPACE;
1438 
1439 	/*
1440 	 * Only apply flags that are allowed to be passed from userspace.
1441 	 */
1442 	reason_flags = reason_flags & OS_REASON_FLAG_MASK_ALLOWED_FROM_USER;
1443 	exit_reason->osr_flags |= reason_flags;
1444 
1445 	if (!(exit_reason->osr_flags & OS_REASON_FLAG_NO_CRASH_REPORT)) {
1446 		exit_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1447 	}
1448 
1449 	if (payload != USER_ADDR_NULL) {
1450 		if (payload_size == 0) {
1451 			os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: exit reason with namespace %u,"
1452 			    " nonzero payload but zero length\n", reason_namespace);
1453 			exit_reason->osr_flags |= OS_REASON_FLAG_BAD_PARAMS;
1454 			payload = USER_ADDR_NULL;
1455 		} else {
1456 			num_items_to_copy++;
1457 
1458 			if (payload_size > EXIT_REASON_PAYLOAD_MAX_LEN) {
1459 				exit_reason->osr_flags |= OS_REASON_FLAG_PAYLOAD_TRUNCATED;
1460 				payload_size = EXIT_REASON_PAYLOAD_MAX_LEN;
1461 			}
1462 
1463 			user_data_to_copy += payload_size;
1464 		}
1465 	}
1466 
1467 	if (reason_string != USER_ADDR_NULL) {
1468 		reason_user_desc = (char *)kalloc_data(EXIT_REASON_USER_DESC_MAX_LEN, Z_WAITOK);
1469 
1470 		if (reason_user_desc != NULL) {
1471 			error = copyinstr(reason_string, (void *) reason_user_desc,
1472 			    EXIT_REASON_USER_DESC_MAX_LEN, &reason_user_desc_len);
1473 
1474 			if (error == 0) {
1475 				num_items_to_copy++;
1476 				user_data_to_copy += reason_user_desc_len;
1477 			} else if (error == ENAMETOOLONG) {
1478 				num_items_to_copy++;
1479 				reason_user_desc[EXIT_REASON_USER_DESC_MAX_LEN - 1] = '\0';
1480 				user_data_to_copy += reason_user_desc_len;
1481 			} else {
1482 				exit_reason->osr_flags |= OS_REASON_FLAG_FAILED_DATA_COPYIN;
1483 				kfree_data(reason_user_desc, EXIT_REASON_USER_DESC_MAX_LEN);
1484 				reason_user_desc = NULL;
1485 				reason_user_desc_len = 0;
1486 			}
1487 		}
1488 	}
1489 
1490 	if (num_items_to_copy != 0) {
1491 		uint32_t reason_buffer_size_estimate = 0;
1492 		mach_vm_address_t data_addr = 0;
1493 
1494 		reason_buffer_size_estimate = kcdata_estimate_required_buffer_size(num_items_to_copy, user_data_to_copy);
1495 
1496 		error = os_reason_alloc_buffer(exit_reason, reason_buffer_size_estimate);
1497 		if (error != 0) {
1498 			os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: failed to allocate signal reason buffer\n");
1499 			goto out_failed_copyin;
1500 		}
1501 
1502 		if (reason_user_desc != NULL && reason_user_desc_len != 0) {
1503 			if (KERN_SUCCESS == kcdata_get_memory_addr(&exit_reason->osr_kcd_descriptor,
1504 			    EXIT_REASON_USER_DESC,
1505 			    (uint32_t)reason_user_desc_len,
1506 			    &data_addr)) {
1507 				kcdata_memcpy(&exit_reason->osr_kcd_descriptor, (mach_vm_address_t) data_addr,
1508 				    reason_user_desc, (uint32_t)reason_user_desc_len);
1509 			} else {
1510 				os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: failed to allocate space for reason string\n");
1511 				goto out_failed_copyin;
1512 			}
1513 		}
1514 
1515 		if (payload != USER_ADDR_NULL) {
1516 			if (KERN_SUCCESS ==
1517 			    kcdata_get_memory_addr(&exit_reason->osr_kcd_descriptor,
1518 			    EXIT_REASON_USER_PAYLOAD,
1519 			    payload_size,
1520 			    &data_addr)) {
1521 				error = copyin(payload, (void *) data_addr, payload_size);
1522 				if (error) {
1523 					os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: failed to copy in payload data with error %d\n", error);
1524 					goto out_failed_copyin;
1525 				}
1526 			} else {
1527 				os_log(OS_LOG_DEFAULT, "build_userspace_exit_reason: failed to allocate space for payload data\n");
1528 				goto out_failed_copyin;
1529 			}
1530 		}
1531 	}
1532 
1533 	if (reason_user_desc != NULL) {
1534 		kfree_data(reason_user_desc, EXIT_REASON_USER_DESC_MAX_LEN);
1535 		reason_user_desc = NULL;
1536 		reason_user_desc_len = 0;
1537 	}
1538 
1539 	return exit_reason;
1540 
1541 out_failed_copyin:
1542 
1543 	if (reason_user_desc != NULL) {
1544 		kfree_data(reason_user_desc, EXIT_REASON_USER_DESC_MAX_LEN);
1545 		reason_user_desc = NULL;
1546 		reason_user_desc_len = 0;
1547 	}
1548 
1549 	exit_reason->osr_flags |= OS_REASON_FLAG_FAILED_DATA_COPYIN;
1550 	os_reason_alloc_buffer(exit_reason, 0);
1551 	return exit_reason;
1552 }
1553 
1554 static int
terminate_with_payload_internal(struct proc * cur_proc,int target_pid,uint32_t reason_namespace,uint64_t reason_code,user_addr_t payload,uint32_t payload_size,user_addr_t reason_string,uint64_t reason_flags)1555 terminate_with_payload_internal(struct proc *cur_proc, int target_pid, uint32_t reason_namespace,
1556     uint64_t reason_code, user_addr_t payload, uint32_t payload_size,
1557     user_addr_t reason_string, uint64_t reason_flags)
1558 {
1559 	proc_t target_proc = PROC_NULL;
1560 	kauth_cred_t cur_cred = kauth_cred_get();
1561 
1562 	os_reason_t signal_reason = OS_REASON_NULL;
1563 
1564 	AUDIT_ARG(pid, target_pid);
1565 	if ((target_pid <= 0)) {
1566 		return EINVAL;
1567 	}
1568 
1569 	target_proc = proc_find(target_pid);
1570 	if (target_proc == PROC_NULL) {
1571 		return ESRCH;
1572 	}
1573 
1574 	AUDIT_ARG(process, target_proc);
1575 
1576 	if (!cansignal(cur_proc, cur_cred, target_proc, SIGKILL)) {
1577 		proc_rele(target_proc);
1578 		return EPERM;
1579 	}
1580 
1581 	if (target_pid != proc_getpid(cur_proc)) {
1582 		/*
1583 		 * FLAG_ABORT should only be set on terminate_with_reason(getpid()) that
1584 		 * was a fallback from an unsuccessful abort_with_reason(). In that case
1585 		 * caller's pid matches the target one. Otherwise remove the flag.
1586 		 */
1587 		reason_flags &= ~((typeof(reason_flags))OS_REASON_FLAG_ABORT);
1588 	}
1589 
1590 	KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1591 	    proc_getpid(target_proc), reason_namespace,
1592 	    reason_code, 0, 0);
1593 
1594 	signal_reason = build_userspace_exit_reason(reason_namespace, reason_code, payload, payload_size,
1595 	    reason_string, (reason_flags | OS_REASON_FLAG_NO_CRASHED_TID));
1596 
1597 	if (target_pid == proc_getpid(cur_proc)) {
1598 		/*
1599 		 * psignal_thread_with_reason() will pend a SIGKILL on the specified thread or
1600 		 * return if the thread and/or task are already terminating. Either way, the
1601 		 * current thread won't return to userspace.
1602 		 */
1603 		psignal_thread_with_reason(target_proc, current_thread(), SIGKILL, signal_reason);
1604 	} else {
1605 		psignal_with_reason(target_proc, SIGKILL, signal_reason);
1606 	}
1607 
1608 	proc_rele(target_proc);
1609 
1610 	return 0;
1611 }
1612 
1613 int
terminate_with_payload(struct proc * cur_proc,struct terminate_with_payload_args * args,__unused int32_t * retval)1614 terminate_with_payload(struct proc *cur_proc, struct terminate_with_payload_args *args,
1615     __unused int32_t *retval)
1616 {
1617 	return terminate_with_payload_internal(cur_proc, args->pid, args->reason_namespace, args->reason_code, args->payload,
1618 	           args->payload_size, args->reason_string, args->reason_flags);
1619 }
1620 
1621 static int
killpg1_allfilt(proc_t p,void * arg)1622 killpg1_allfilt(proc_t p, void * arg)
1623 {
1624 	struct killpg1_filtargs * kfargp = (struct killpg1_filtargs *)arg;
1625 
1626 	/*
1627 	 * Don't signal initproc, a system process, or the current process if POSIX
1628 	 * isn't specified.
1629 	 */
1630 	return proc_getpid(p) > 1 && !(p->p_flag & P_SYSTEM) &&
1631 	       (kfargp->posix ? true : p != kfargp->curproc);
1632 }
1633 
1634 static int
killpg1_callback(proc_t p,void * arg)1635 killpg1_callback(proc_t p, void *arg)
1636 {
1637 	struct killpg1_iterargs *kargp = (struct killpg1_iterargs *)arg;
1638 	int signum = kargp->signum;
1639 
1640 	if (proc_list_exited(p)) {
1641 		/*
1642 		 * Count zombies as found for the purposes of signalling, since POSIX
1643 		 * 1003.1-2001 sees signalling zombies as successful.  If killpg(2) or
1644 		 * kill(2) with pid -1 only finds zombies that can be signalled, it
1645 		 * shouldn't return ESRCH.  See the Rationale for kill(2).
1646 		 *
1647 		 * Don't call into MAC -- it's not expecting signal checks for exited
1648 		 * processes.
1649 		 */
1650 		if (cansignal_nomac(kargp->curproc, kargp->uc, p, signum)) {
1651 			kargp->nfound++;
1652 		}
1653 	} else if (cansignal(kargp->curproc, kargp->uc, p, signum)) {
1654 		kargp->nfound++;
1655 
1656 		if (signum != 0) {
1657 			psignal(p, signum);
1658 		}
1659 	}
1660 
1661 	return PROC_RETURNED;
1662 }
1663 
1664 /*
1665  * Common code for kill process group/broadcast kill.
1666  */
1667 int
killpg1(proc_t curproc,int signum,int pgid,int all,int posix)1668 killpg1(proc_t curproc, int signum, int pgid, int all, int posix)
1669 {
1670 	kauth_cred_t uc;
1671 	struct pgrp *pgrp;
1672 	int error = 0;
1673 
1674 	uc = kauth_cred_proc_ref(curproc);
1675 	struct killpg1_iterargs karg = {
1676 		.curproc = curproc, .uc = uc, .nfound = 0, .signum = signum
1677 	};
1678 
1679 	if (all) {
1680 		/*
1681 		 * Broadcast to all processes that the user can signal (pid was -1).
1682 		 */
1683 		struct killpg1_filtargs kfarg = {
1684 			.posix = posix, .curproc = curproc
1685 		};
1686 		proc_iterate(PROC_ALLPROCLIST | PROC_ZOMBPROCLIST, killpg1_callback,
1687 		    &karg, killpg1_allfilt, &kfarg);
1688 	} else {
1689 		if (pgid == 0) {
1690 			/*
1691 			 * Send to current the current process' process group.
1692 			 */
1693 			pgrp = proc_pgrp(curproc, NULL);
1694 		} else {
1695 			pgrp = pgrp_find(pgid);
1696 			if (pgrp == NULL) {
1697 				error = ESRCH;
1698 				goto out;
1699 			}
1700 		}
1701 
1702 		pgrp_iterate(pgrp, killpg1_callback, &karg, ^bool (proc_t p) {
1703 			if (p == kernproc || p == initproc) {
1704 			        return false;
1705 			}
1706 			/* XXX shouldn't this allow signalling zombies? */
1707 			return !(p->p_flag & P_SYSTEM) && p->p_stat != SZOMB;
1708 		});
1709 		pgrp_rele(pgrp);
1710 	}
1711 	error = (karg.nfound > 0 ? 0 : (posix ? EPERM : ESRCH));
1712 out:
1713 	kauth_cred_unref(&uc);
1714 	return error;
1715 }
1716 
1717 /*
1718  * Send a signal to a process group.
1719  */
1720 void
gsignal(int pgid,int signum)1721 gsignal(int pgid, int signum)
1722 {
1723 	struct pgrp *pgrp;
1724 
1725 	if (pgid && (pgrp = pgrp_find(pgid))) {
1726 		pgsignal(pgrp, signum, 0);
1727 		pgrp_rele(pgrp);
1728 	}
1729 }
1730 
1731 /*
1732  * Send a signal to a process group.  If checkctty is 1,
1733  * limit to members which have a controlling terminal.
1734  */
1735 
1736 static int
pgsignal_callback(proc_t p,void * arg)1737 pgsignal_callback(proc_t p, void * arg)
1738 {
1739 	int  signum = *(int*)arg;
1740 
1741 	psignal(p, signum);
1742 	return PROC_RETURNED;
1743 }
1744 
1745 void
pgsignal(struct pgrp * pgrp,int signum,int checkctty)1746 pgsignal(struct pgrp *pgrp, int signum, int checkctty)
1747 {
1748 	if (pgrp == PGRP_NULL) {
1749 		return;
1750 	}
1751 
1752 	bool (^filter)(proc_t) = ^bool (proc_t p) {
1753 		return p->p_flag & P_CONTROLT;
1754 	};
1755 
1756 	pgrp_iterate(pgrp, pgsignal_callback, &signum, checkctty ? filter : NULL);
1757 }
1758 
1759 
1760 void
tty_pgsignal_locked(struct tty * tp,int signum,int checkctty)1761 tty_pgsignal_locked(struct tty *tp, int signum, int checkctty)
1762 {
1763 	struct pgrp * pg;
1764 
1765 	pg = tty_pgrp_locked(tp);
1766 	if (pg != PGRP_NULL) {
1767 		tty_unlock(tp);
1768 		pgsignal(pg, signum, checkctty);
1769 		pgrp_rele(pg);
1770 		tty_lock(tp);
1771 	}
1772 }
1773 /*
1774  * Send a signal caused by a trap to a specific thread.
1775  */
1776 void
threadsignal(thread_t sig_actthread,int signum,mach_exception_code_t code,boolean_t set_exitreason)1777 threadsignal(thread_t sig_actthread, int signum, mach_exception_code_t code, boolean_t set_exitreason)
1778 {
1779 	struct uthread *uth;
1780 	struct task * sig_task;
1781 	proc_t p;
1782 	int mask;
1783 
1784 	if ((u_int)signum >= NSIG || signum == 0) {
1785 		return;
1786 	}
1787 
1788 	mask = sigmask(signum);
1789 	if ((mask & threadmask) == 0) {
1790 		return;
1791 	}
1792 	sig_task = get_threadtask(sig_actthread);
1793 	p = (proc_t)(get_bsdtask_info(sig_task));
1794 
1795 	uth = get_bsdthread_info(sig_actthread);
1796 
1797 	proc_lock(p);
1798 	if (!(p->p_lflag & P_LTRACED) && (p->p_sigignore & mask)) {
1799 		proc_unlock(p);
1800 		return;
1801 	}
1802 
1803 	uth->uu_siglist |= mask;
1804 	uth->uu_code = code;
1805 
1806 	/* Attempt to establish whether the signal will be fatal (mirrors logic in psignal_internal()) */
1807 	if (set_exitreason && ((p->p_lflag & P_LTRACED) || (!(uth->uu_sigwait & mask)
1808 	    && !(uth->uu_sigmask & mask) && !(p->p_sigcatch & mask))) &&
1809 	    !(mask & stopsigmask) && !(mask & contsigmask)) {
1810 		if (uth->uu_exit_reason == OS_REASON_NULL) {
1811 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1812 			    proc_getpid(p), OS_REASON_SIGNAL, signum, 0, 0);
1813 
1814 			os_reason_t signal_reason = build_signal_reason(signum, "exc handler");
1815 
1816 			set_thread_exit_reason(sig_actthread, signal_reason, TRUE);
1817 
1818 			/* We dropped/consumed the reference in set_thread_exit_reason() */
1819 			signal_reason = OS_REASON_NULL;
1820 		}
1821 	}
1822 
1823 	proc_unlock(p);
1824 
1825 	/* mark on process as well */
1826 	signal_setast(sig_actthread);
1827 }
1828 
1829 /* Called with proc locked */
1830 static void
set_thread_extra_flags(task_t task,struct uthread * uth,os_reason_t reason)1831 set_thread_extra_flags(task_t task, struct uthread *uth, os_reason_t reason)
1832 {
1833 	extern int vm_shared_region_reslide_restrict;
1834 	boolean_t reslide_shared_region = FALSE;
1835 	boolean_t driver = task_is_driver(task);
1836 	assert(uth != NULL);
1837 	/*
1838 	 * Check whether the userland fault address falls within the shared
1839 	 * region and notify userland if so. To limit the occurrences of shared
1840 	 * cache resliding - and its associated memory tax - only investigate the
1841 	 * fault if it is consequence of accessing unmapped memory (SIGSEGV) or
1842 	 * accessing with incorrect permissions (SIGBUS - KERN_PROTECTION_FAILURE).
1843 	 *
1844 	 * This allows launchd to apply special policies around this fault type.
1845 	 */
1846 	if (reason->osr_namespace == OS_REASON_SIGNAL &&
1847 	    (reason->osr_code == SIGSEGV ||
1848 	    (reason->osr_code == SIGBUS && uth->uu_code == KERN_PROTECTION_FAILURE))) {
1849 		mach_vm_address_t fault_address = uth->uu_subcode;
1850 
1851 		/* Address is in userland, so we hard clear any non-canonical bits to 0 here */
1852 		fault_address = VM_USER_STRIP_PTR(fault_address);
1853 
1854 		if (fault_address >= SHARED_REGION_BASE &&
1855 		    fault_address <= SHARED_REGION_BASE + SHARED_REGION_SIZE) {
1856 			/*
1857 			 * Always report whether the fault happened within the shared cache
1858 			 * region, but only stale the slide if the resliding is extended
1859 			 * to all processes or if the process faulting is a platform one.
1860 			 */
1861 			reason->osr_flags |= OS_REASON_FLAG_SHAREDREGION_FAULT;
1862 
1863 #if __has_feature(ptrauth_calls)
1864 			if (!vm_shared_region_reslide_restrict || task_is_hardened_binary(current_task())) {
1865 				reslide_shared_region = TRUE;
1866 			}
1867 #endif /* __has_feature(ptrauth_calls) */
1868 		}
1869 
1870 		if (driver) {
1871 			/*
1872 			 * Always reslide the DriverKit shared region if the driver faulted.
1873 			 * The memory cost is acceptable because the DriverKit shared cache is small
1874 			 * and there are relatively few driver processes.
1875 			 */
1876 			reslide_shared_region = TRUE;
1877 		}
1878 	}
1879 
1880 	if (reslide_shared_region) {
1881 		vm_shared_region_reslide_stale(driver);
1882 	}
1883 }
1884 
1885 void
set_thread_exit_reason(void * th,void * reason,boolean_t proc_locked)1886 set_thread_exit_reason(void *th, void *reason, boolean_t proc_locked)
1887 {
1888 	struct uthread *targ_uth = get_bsdthread_info(th);
1889 	struct task *targ_task = get_threadtask(th);
1890 	proc_t targ_proc = NULL;
1891 
1892 	os_reason_t exit_reason = (os_reason_t)reason;
1893 
1894 	if (exit_reason == OS_REASON_NULL) {
1895 		return;
1896 	}
1897 
1898 	if (!proc_locked) {
1899 		targ_proc = (proc_t)(get_bsdtask_info(targ_task));
1900 
1901 		proc_lock(targ_proc);
1902 	}
1903 
1904 	set_thread_extra_flags(targ_task, targ_uth, exit_reason);
1905 
1906 	if (targ_uth->uu_exit_reason == OS_REASON_NULL) {
1907 		targ_uth->uu_exit_reason = exit_reason;
1908 	} else {
1909 		/* The caller expects that we drop a reference on the exit reason */
1910 		os_reason_free(exit_reason);
1911 	}
1912 
1913 	if (!proc_locked) {
1914 		assert(targ_proc != NULL);
1915 		proc_unlock(targ_proc);
1916 	}
1917 }
1918 
1919 /*
1920  * get_signalthread
1921  *
1922  * Picks an appropriate thread from a process to target with a signal.
1923  *
1924  * Called with proc locked.
1925  * Returns thread with BSD ast set.
1926  *
1927  * We attempt to deliver a proc-wide signal to the first thread in the task.
1928  * This allows single threaded applications which use signals to
1929  * be able to be linked with multithreaded libraries.
1930  */
1931 static kern_return_t
get_signalthread(proc_t p,int signum,thread_t * thr)1932 get_signalthread(proc_t p, int signum, thread_t * thr)
1933 {
1934 	struct uthread *uth;
1935 	sigset_t mask = sigmask(signum);
1936 	bool skip_wqthreads = true;
1937 
1938 	*thr = THREAD_NULL;
1939 
1940 
1941 again:
1942 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
1943 		if (((uth->uu_flag & UT_NO_SIGMASK) == 0) &&
1944 		    (((uth->uu_sigmask & mask) == 0) || (uth->uu_sigwait & mask))) {
1945 			thread_t th = get_machthread(uth);
1946 			if (skip_wqthreads && (thread_get_tag(th) & THREAD_TAG_WORKQUEUE)) {
1947 				/* Workqueue threads may be parked in the kernel unable to
1948 				 * deliver signals for an extended period of time, so skip them
1949 				 * in favor of pthreads in a first pass. (rdar://50054475). */
1950 			} else if (check_actforsig(proc_task(p), th, 1) == KERN_SUCCESS) {
1951 				*thr = th;
1952 				return KERN_SUCCESS;
1953 			}
1954 		}
1955 	}
1956 	if (skip_wqthreads) {
1957 		skip_wqthreads = false;
1958 		goto again;
1959 	}
1960 	if (get_signalact(proc_task(p), thr, 1) == KERN_SUCCESS) {
1961 		return KERN_SUCCESS;
1962 	}
1963 
1964 	return KERN_FAILURE;
1965 }
1966 
1967 static os_reason_t
build_signal_reason(int signum,const char * procname)1968 build_signal_reason(int signum, const char *procname)
1969 {
1970 	os_reason_t signal_reason = OS_REASON_NULL;
1971 	proc_t sender_proc = current_proc();
1972 	const uint32_t proc_name_length = sizeof(sender_proc->p_name);
1973 	uint32_t reason_buffer_size_estimate = 0;
1974 	const char *default_sender_procname = "unknown";
1975 	mach_vm_address_t data_addr;
1976 	int ret;
1977 
1978 	signal_reason = os_reason_create(OS_REASON_SIGNAL, signum);
1979 	if (signal_reason == OS_REASON_NULL) {
1980 		printf("build_signal_reason: unable to allocate signal reason structure.\n");
1981 		return signal_reason;
1982 	}
1983 
1984 	reason_buffer_size_estimate = kcdata_estimate_required_buffer_size(2, sizeof(sender_proc->p_name) +
1985 	    sizeof(pid_t));
1986 
1987 	ret = os_reason_alloc_buffer_noblock(signal_reason, reason_buffer_size_estimate);
1988 	if (ret != 0) {
1989 		printf("build_signal_reason: unable to allocate signal reason buffer.\n");
1990 		return signal_reason;
1991 	}
1992 
1993 	if (KERN_SUCCESS == kcdata_get_memory_addr(&signal_reason->osr_kcd_descriptor, KCDATA_TYPE_PID,
1994 	    sizeof(pid_t), &data_addr)) {
1995 		pid_t pid = proc_getpid(sender_proc);
1996 		kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &pid, sizeof(pid));
1997 	} else {
1998 		printf("build_signal_reason: exceeded space in signal reason buf, unable to log PID\n");
1999 	}
2000 
2001 	if (KERN_SUCCESS == kcdata_get_memory_addr(&signal_reason->osr_kcd_descriptor, KCDATA_TYPE_PROCNAME,
2002 	    proc_name_length, &data_addr)) {
2003 		if (procname) {
2004 			char truncated_procname[proc_name_length];
2005 			strncpy((char *) &truncated_procname, procname, proc_name_length);
2006 			truncated_procname[proc_name_length - 1] = '\0';
2007 
2008 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, truncated_procname,
2009 			    (uint32_t)strlen((char *) &truncated_procname));
2010 		} else if (*sender_proc->p_name) {
2011 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &sender_proc->p_name,
2012 			    sizeof(sender_proc->p_name));
2013 		} else {
2014 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &default_sender_procname,
2015 			    (uint32_t)strlen(default_sender_procname) + 1);
2016 		}
2017 	} else {
2018 		printf("build_signal_reason: exceeded space in signal reason buf, unable to log procname\n");
2019 	}
2020 
2021 	return signal_reason;
2022 }
2023 
2024 /*
2025  * Send the signal to the process.  If the signal has an action, the action
2026  * is usually performed by the target process rather than the caller; we add
2027  * the signal to the set of pending signals for the process.
2028  *
2029  * Always drops a reference on a signal_reason if one is provided, whether via
2030  * passing it to a thread or deallocating directly.
2031  *
2032  * Exceptions:
2033  *   o When a stop signal is sent to a sleeping process that takes the
2034  *     default action, the process is stopped without awakening it.
2035  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2036  *     regardless of the signal action (eg, blocked or ignored).
2037  *
2038  * Other ignored signals are discarded immediately.
2039  */
2040 static void
psignal_internal(proc_t p,task_t task,thread_t thread,int flavor,int signum,os_reason_t signal_reason)2041 psignal_internal(proc_t p, task_t task, thread_t thread, int flavor, int signum, os_reason_t signal_reason)
2042 {
2043 	int prop;
2044 	user_addr_t action = USER_ADDR_NULL;
2045 	proc_t                  sig_proc;
2046 	thread_t                sig_thread;
2047 	task_t                  sig_task;
2048 	int                     mask;
2049 	struct uthread          *uth;
2050 	kern_return_t           kret;
2051 	uid_t                   r_uid;
2052 	proc_t                  pp;
2053 	kauth_cred_t            my_cred;
2054 	char                    *launchd_exit_reason_desc = NULL;
2055 	boolean_t               update_thread_policy = FALSE;
2056 
2057 	if ((u_int)signum >= NSIG || signum == 0) {
2058 		panic("psignal: bad signal number %d", signum);
2059 	}
2060 
2061 	mask = sigmask(signum);
2062 	prop = sigprop[signum];
2063 
2064 #if SIGNAL_DEBUG
2065 	if (rdebug_proc && (p != PROC_NULL) && (p == rdebug_proc)) {
2066 		ram_printf(3);
2067 	}
2068 #endif /* SIGNAL_DEBUG */
2069 
2070 	/* catch unexpected initproc kills early for easier debuggging */
2071 	if (signum == SIGKILL && p == initproc) {
2072 		if (signal_reason == NULL) {
2073 			panic_plain("unexpected SIGKILL of %s %s (no reason provided)",
2074 			    (p->p_name[0] != '\0' ? p->p_name : "initproc"),
2075 			    ((proc_getcsflags(p) & CS_KILLED) ? "(CS_KILLED)" : ""));
2076 		} else {
2077 			launchd_exit_reason_desc = exit_reason_get_string_desc(signal_reason);
2078 			panic_plain("unexpected SIGKILL of %s %s with reason -- namespace %d code 0x%llx description %." LAUNCHD_PANIC_REASON_STRING_MAXLEN "s",
2079 			    (p->p_name[0] != '\0' ? p->p_name : "initproc"),
2080 			    ((proc_getcsflags(p) & CS_KILLED) ? "(CS_KILLED)" : ""),
2081 			    signal_reason->osr_namespace, signal_reason->osr_code,
2082 			    launchd_exit_reason_desc ? launchd_exit_reason_desc : "none");
2083 		}
2084 	}
2085 
2086 	/*
2087 	 *	We will need the task pointer later.  Grab it now to
2088 	 *	check for a zombie process.  Also don't send signals
2089 	 *	to kernel internal tasks.
2090 	 */
2091 	if (flavor & PSIG_VFORK) {
2092 		sig_task = task;
2093 		sig_thread = thread;
2094 		sig_proc = p;
2095 	} else if (flavor & PSIG_THREAD) {
2096 		sig_task = get_threadtask(thread);
2097 		sig_thread = thread;
2098 		sig_proc = (proc_t)get_bsdtask_info(sig_task);
2099 	} else if (flavor & PSIG_TRY_THREAD) {
2100 		assert((thread == current_thread()) && (p == current_proc()));
2101 		sig_task = proc_task(p);
2102 		sig_thread = thread;
2103 		sig_proc = p;
2104 	} else {
2105 		sig_task = proc_task(p);
2106 		sig_thread = THREAD_NULL;
2107 		sig_proc = p;
2108 	}
2109 
2110 	if ((sig_task == TASK_NULL) || is_kerneltask(sig_task)) {
2111 		os_reason_free(signal_reason);
2112 		return;
2113 	}
2114 
2115 	if ((flavor & (PSIG_VFORK | PSIG_THREAD)) == 0) {
2116 		proc_knote(sig_proc, NOTE_SIGNAL | signum);
2117 	}
2118 
2119 	if ((flavor & PSIG_LOCKED) == 0) {
2120 		proc_signalstart(sig_proc, 0);
2121 	}
2122 
2123 	/* Don't send signals to a process that has ignored them. */
2124 	if (((flavor & PSIG_VFORK) == 0) && ((sig_proc->p_lflag & P_LTRACED) == 0) && (sig_proc->p_sigignore & mask)) {
2125 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2126 		goto sigout_unlocked;
2127 	}
2128 
2129 	/*
2130 	 * The proc_lock prevents the targeted thread from being deallocated
2131 	 * or handling the signal until we're done signaling it.
2132 	 *
2133 	 * Once the proc_lock is dropped, we have no guarantee the thread or uthread exists anymore.
2134 	 *
2135 	 * XXX: What if the thread goes inactive after the thread passes bsd ast point?
2136 	 */
2137 	proc_lock(sig_proc);
2138 
2139 	/*
2140 	 * Don't send signals to a process which has already exited and thus
2141 	 * committed to a particular p_xstat exit code.
2142 	 * Additionally, don't abort the process running 'reboot'.
2143 	 */
2144 	if (ISSET(sig_proc->p_flag, P_REBOOT) || ISSET(sig_proc->p_lflag, P_LEXIT)) {
2145 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2146 		goto sigout_locked;
2147 	}
2148 
2149 	if (flavor & PSIG_VFORK) {
2150 		action = SIG_DFL;
2151 		act_set_astbsd(sig_thread);
2152 		kret = KERN_SUCCESS;
2153 	} else if (flavor & PSIG_TRY_THREAD) {
2154 		uth = get_bsdthread_info(sig_thread);
2155 		if (((uth->uu_flag & UT_NO_SIGMASK) == 0) &&
2156 		    (((uth->uu_sigmask & mask) == 0) || (uth->uu_sigwait & mask)) &&
2157 		    ((kret = check_actforsig(proc_task(sig_proc), sig_thread, 1)) == KERN_SUCCESS)) {
2158 			/* deliver to specified thread */
2159 		} else {
2160 			/* deliver to any willing thread */
2161 			kret = get_signalthread(sig_proc, signum, &sig_thread);
2162 		}
2163 	} else if (flavor & PSIG_THREAD) {
2164 		/* If successful return with ast set */
2165 		kret = check_actforsig(sig_task, sig_thread, 1);
2166 	} else {
2167 		/* If successful return with ast set */
2168 		kret = get_signalthread(sig_proc, signum, &sig_thread);
2169 	}
2170 
2171 	if (kret != KERN_SUCCESS) {
2172 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2173 		proc_unlock(sig_proc);
2174 		goto sigout_unlocked;
2175 	}
2176 
2177 	uth = get_bsdthread_info(sig_thread);
2178 
2179 	/*
2180 	 * If proc is traced, always give parent a chance.
2181 	 */
2182 
2183 	if ((flavor & PSIG_VFORK) == 0) {
2184 		if (sig_proc->p_lflag & P_LTRACED) {
2185 			action = SIG_DFL;
2186 		} else {
2187 			/*
2188 			 * If the signal is being ignored,
2189 			 * then we forget about it immediately.
2190 			 * (Note: we don't set SIGCONT in p_sigignore,
2191 			 * and if it is set to SIG_IGN,
2192 			 * action will be SIG_DFL here.)
2193 			 */
2194 			if (sig_proc->p_sigignore & mask) {
2195 				goto sigout_locked;
2196 			}
2197 
2198 			if (uth->uu_sigwait & mask) {
2199 				action = KERN_SIG_WAIT;
2200 			} else if (uth->uu_sigmask & mask) {
2201 				action = KERN_SIG_HOLD;
2202 			} else if (sig_proc->p_sigcatch & mask) {
2203 				action = KERN_SIG_CATCH;
2204 			} else {
2205 				action = SIG_DFL;
2206 			}
2207 		}
2208 	}
2209 
2210 	/* TODO: p_nice isn't hooked up to the scheduler... */
2211 	if (sig_proc->p_nice > NZERO && action == SIG_DFL && (prop & SA_KILL) &&
2212 	    (sig_proc->p_lflag & P_LTRACED) == 0) {
2213 		sig_proc->p_nice = NZERO;
2214 	}
2215 
2216 	if (prop & SA_CONT) {
2217 		uth->uu_siglist &= ~stopsigmask;
2218 	}
2219 
2220 	if (prop & SA_STOP) {
2221 		struct pgrp *pg;
2222 		/*
2223 		 * If sending a tty stop signal to a member of an orphaned
2224 		 * process group, discard the signal here if the action
2225 		 * is default; don't stop the process below if sleeping,
2226 		 * and don't clear any pending SIGCONT.
2227 		 */
2228 		pg = proc_pgrp(sig_proc, NULL);
2229 		if (prop & SA_TTYSTOP && pg->pg_jobc == 0 &&
2230 		    action == SIG_DFL) {
2231 			pgrp_rele(pg);
2232 			goto sigout_locked;
2233 		}
2234 		pgrp_rele(pg);
2235 		uth->uu_siglist &= ~contsigmask;
2236 	}
2237 
2238 	uth->uu_siglist |= mask;
2239 
2240 	/*
2241 	 * Defer further processing for signals which are held,
2242 	 * except that stopped processes must be continued by SIGCONT.
2243 	 */
2244 	if ((action == KERN_SIG_HOLD) && ((prop & SA_CONT) == 0 || sig_proc->p_stat != SSTOP)) {
2245 		goto sigout_locked;
2246 	}
2247 
2248 	/*
2249 	 *	SIGKILL priority twiddling moved here from above because
2250 	 *	it needs sig_thread.  Could merge it into large switch
2251 	 *	below if we didn't care about priority for tracing
2252 	 *	as SIGKILL's action is always SIG_DFL.
2253 	 *
2254 	 *	TODO: p_nice isn't hooked up to the scheduler...
2255 	 */
2256 	if ((signum == SIGKILL) && (sig_proc->p_nice > NZERO)) {
2257 		sig_proc->p_nice = NZERO;
2258 	}
2259 
2260 	/*
2261 	 *	Process is traced - wake it up (if not already
2262 	 *	stopped) so that it can discover the signal in
2263 	 *	issig() and stop for the parent.
2264 	 */
2265 	if (sig_proc->p_lflag & P_LTRACED) {
2266 		if (sig_proc->p_stat != SSTOP) {
2267 			goto runlocked;
2268 		} else {
2269 			goto sigout_locked;
2270 		}
2271 	}
2272 
2273 	if ((flavor & PSIG_VFORK) != 0) {
2274 		goto runlocked;
2275 	}
2276 
2277 	if (action == KERN_SIG_WAIT) {
2278 #if CONFIG_DTRACE
2279 		/*
2280 		 * DTrace proc signal-clear returns a siginfo_t. Collect the needed info.
2281 		 */
2282 		r_uid = kauth_getruid(); /* per thread credential; protected by our thread context */
2283 
2284 		bzero((caddr_t)&(uth->t_dtrace_siginfo), sizeof(uth->t_dtrace_siginfo));
2285 
2286 		uth->t_dtrace_siginfo.si_signo = signum;
2287 		uth->t_dtrace_siginfo.si_pid = proc_getpid(current_proc());
2288 		uth->t_dtrace_siginfo.si_status = W_EXITCODE(signum, 0);
2289 		uth->t_dtrace_siginfo.si_uid = r_uid;
2290 		uth->t_dtrace_siginfo.si_code = 0;
2291 #endif
2292 		uth->uu_sigwait = mask;
2293 		uth->uu_siglist &= ~mask;
2294 		wakeup(&uth->uu_sigwait);
2295 		/* if it is SIGCONT resume whole process */
2296 		if (prop & SA_CONT) {
2297 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2298 			sig_proc->p_contproc = proc_getpid(current_proc());
2299 			(void) task_resume_internal(sig_task);
2300 		}
2301 		goto sigout_locked;
2302 	}
2303 
2304 	if (action != SIG_DFL) {
2305 		/*
2306 		 *	User wants to catch the signal.
2307 		 *	Wake up the thread, but don't un-suspend it
2308 		 *	(except for SIGCONT).
2309 		 */
2310 		if (prop & SA_CONT) {
2311 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2312 			(void) task_resume_internal(sig_task);
2313 			sig_proc->p_stat = SRUN;
2314 		} else if (sig_proc->p_stat == SSTOP) {
2315 			goto sigout_locked;
2316 		}
2317 		/*
2318 		 * Fill out siginfo structure information to pass to the
2319 		 * signalled process/thread sigaction handler, when it
2320 		 * wakes up.  si_code is 0 because this is an ordinary
2321 		 * signal, not a SIGCHLD, and so si_status is the signal
2322 		 * number itself, instead of the child process exit status.
2323 		 * We shift this left because it will be shifted right before
2324 		 * it is passed to user space.  kind of ugly to use W_EXITCODE
2325 		 * this way, but it beats defining a new macro.
2326 		 *
2327 		 * Note:	Avoid the SIGCHLD recursion case!
2328 		 */
2329 		if (signum != SIGCHLD) {
2330 			r_uid = kauth_getruid();
2331 
2332 			sig_proc->si_pid = proc_getpid(current_proc());
2333 			sig_proc->si_status = W_EXITCODE(signum, 0);
2334 			sig_proc->si_uid = r_uid;
2335 			sig_proc->si_code = 0;
2336 		}
2337 
2338 		goto runlocked;
2339 	} else {
2340 		/*	Default action - varies */
2341 		if (mask & stopsigmask) {
2342 			assert(signal_reason == NULL);
2343 			/*
2344 			 * These are the signals which by default
2345 			 * stop a process.
2346 			 *
2347 			 * Don't clog system with children of init
2348 			 * stopped from the keyboard.
2349 			 */
2350 			if (!(prop & SA_STOP) && sig_proc->p_pptr == initproc) {
2351 				uth->uu_siglist &= ~mask;
2352 				proc_unlock(sig_proc);
2353 				/* siglock still locked, proc_lock not locked */
2354 				psignal_locked(sig_proc, SIGKILL);
2355 				goto sigout_unlocked;
2356 			}
2357 
2358 			/*
2359 			 *	Stop the task
2360 			 *	if task hasn't already been stopped by
2361 			 *	a signal.
2362 			 */
2363 			uth->uu_siglist &= ~mask;
2364 			if (sig_proc->p_stat != SSTOP) {
2365 				sig_proc->p_xstat = signum;
2366 				sig_proc->p_stat = SSTOP;
2367 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &sig_proc->p_flag);
2368 				sig_proc->p_lflag &= ~P_LWAITED;
2369 				proc_signalend(sig_proc, 1);
2370 				proc_unlock(sig_proc);
2371 
2372 				pp = proc_parentholdref(sig_proc);
2373 				proc_signalstart(sig_proc, 0);
2374 				stop(sig_proc, pp);
2375 				if ((pp != PROC_NULL) && ((pp->p_flag & P_NOCLDSTOP) == 0)) {
2376 					my_cred = kauth_cred_proc_ref(sig_proc);
2377 					r_uid = kauth_cred_getruid(my_cred);
2378 					kauth_cred_unref(&my_cred);
2379 
2380 					proc_lock(sig_proc);
2381 					pp->si_pid = proc_getpid(sig_proc);
2382 					/*
2383 					 * POSIX: sigaction for a stopped child
2384 					 * when sent to the parent must set the
2385 					 * child's signal number into si_status.
2386 					 */
2387 					if (signum != SIGSTOP) {
2388 						pp->si_status = WEXITSTATUS(sig_proc->p_xstat);
2389 					} else {
2390 						pp->si_status = W_EXITCODE(signum, signum);
2391 					}
2392 					pp->si_code = CLD_STOPPED;
2393 					pp->si_uid = r_uid;
2394 					proc_unlock(sig_proc);
2395 
2396 					psignal(pp, SIGCHLD);
2397 				}
2398 				if (pp != PROC_NULL) {
2399 					proc_parentdropref(pp, 0);
2400 				}
2401 
2402 				goto sigout_unlocked;
2403 			}
2404 
2405 			goto sigout_locked;
2406 		}
2407 
2408 		DTRACE_PROC3(signal__send, thread_t, sig_thread, proc_t, p, int, signum);
2409 
2410 		switch (signum) {
2411 		/*
2412 		 * Signals ignored by default have been dealt
2413 		 * with already, since their bits are on in
2414 		 * p_sigignore.
2415 		 */
2416 
2417 		case SIGKILL:
2418 			/*
2419 			 * Kill signal always sets process running and
2420 			 * unsuspends it.
2421 			 */
2422 			/*
2423 			 *	Process will be running after 'run'
2424 			 */
2425 			sig_proc->p_stat = SRUN;
2426 			/*
2427 			 * In scenarios where suspend/resume are racing
2428 			 * the signal we are missing AST_BSD by the time
2429 			 * we get here, set again to avoid races. This
2430 			 * was the scenario with spindump enabled shutdowns.
2431 			 * We would need to cover this approp down the line.
2432 			 */
2433 			act_set_astbsd(sig_thread);
2434 			kret = thread_abort(sig_thread);
2435 			update_thread_policy = (kret == KERN_SUCCESS);
2436 
2437 			if (uth->uu_exit_reason == OS_REASON_NULL) {
2438 				if (signal_reason == OS_REASON_NULL) {
2439 					KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2440 					    proc_getpid(sig_proc), OS_REASON_SIGNAL, signum, 0, 0);
2441 
2442 					signal_reason = build_signal_reason(signum, NULL);
2443 				}
2444 
2445 				os_reason_ref(signal_reason);
2446 				set_thread_exit_reason(sig_thread, signal_reason, TRUE);
2447 			}
2448 
2449 			goto sigout_locked;
2450 
2451 		case SIGCONT:
2452 			/*
2453 			 * Let the process run.  If it's sleeping on an
2454 			 * event, it remains so.
2455 			 */
2456 			assert(signal_reason == NULL);
2457 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2458 			sig_proc->p_contproc = proc_getpid(sig_proc);
2459 			sig_proc->p_xstat = signum;
2460 
2461 			(void) task_resume_internal(sig_task);
2462 
2463 			/*
2464 			 * When processing a SIGCONT, we need to check
2465 			 * to see if there are signals pending that
2466 			 * were not delivered because we had been
2467 			 * previously stopped.  If that's the case,
2468 			 * we need to thread_abort_safely() to trigger
2469 			 * interruption of the current system call to
2470 			 * cause their handlers to fire.  If it's only
2471 			 * the SIGCONT, then don't wake up.
2472 			 */
2473 			if (((flavor & (PSIG_VFORK | PSIG_THREAD)) == 0) && (((uth->uu_siglist & ~uth->uu_sigmask) & ~sig_proc->p_sigignore) & ~mask)) {
2474 				uth->uu_siglist &= ~mask;
2475 				sig_proc->p_stat = SRUN;
2476 				goto runlocked;
2477 			}
2478 
2479 			uth->uu_siglist &= ~mask;
2480 			sig_proc->p_stat = SRUN;
2481 			goto sigout_locked;
2482 
2483 		default:
2484 		{
2485 			/*
2486 			 * A signal which has a default action of killing
2487 			 * the process, and for which there is no handler,
2488 			 * needs to act like SIGKILL
2489 			 *
2490 			 * The thread_sstop condition is a remnant of a fix
2491 			 * where PSIG_THREAD exit reasons were not set
2492 			 * correctly (93593933). We keep the behavior with
2493 			 * SSTOP the same as before.
2494 			 */
2495 			const bool default_kill = (action == SIG_DFL) && (prop & SA_KILL);
2496 			const bool thread_sstop = (flavor & PSIG_THREAD) && (sig_proc->p_stat == SSTOP);
2497 
2498 			if (default_kill && !thread_sstop) {
2499 				sig_proc->p_stat = SRUN;
2500 				kret = thread_abort(sig_thread);
2501 				update_thread_policy = (kret == KERN_SUCCESS);
2502 
2503 				if (uth->uu_exit_reason == OS_REASON_NULL) {
2504 					if (signal_reason == OS_REASON_NULL) {
2505 						KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2506 						    proc_getpid(sig_proc), OS_REASON_SIGNAL, signum, 0, 0);
2507 
2508 						signal_reason = build_signal_reason(signum, NULL);
2509 					}
2510 
2511 					os_reason_ref(signal_reason);
2512 					set_thread_exit_reason(sig_thread, signal_reason, TRUE);
2513 				}
2514 
2515 				goto sigout_locked;
2516 			}
2517 
2518 			/*
2519 			 * All other signals wake up the process, but don't
2520 			 * resume it.
2521 			 */
2522 			if (sig_proc->p_stat == SSTOP) {
2523 				goto sigout_locked;
2524 			}
2525 			goto runlocked;
2526 		}
2527 		}
2528 	}
2529 	/*NOTREACHED*/
2530 
2531 runlocked:
2532 	/*
2533 	 * If we're being traced (possibly because someone attached us
2534 	 * while we were stopped), check for a signal from the debugger.
2535 	 */
2536 	if (sig_proc->p_stat == SSTOP) {
2537 		if ((sig_proc->p_lflag & P_LTRACED) != 0 && sig_proc->p_xstat != 0) {
2538 			uth->uu_siglist |= sigmask(sig_proc->p_xstat);
2539 		}
2540 
2541 		if ((flavor & PSIG_VFORK) != 0) {
2542 			sig_proc->p_stat = SRUN;
2543 		}
2544 	} else {
2545 		/*
2546 		 * setrunnable(p) in BSD and
2547 		 * Wake up the thread if it is interruptible.
2548 		 */
2549 		sig_proc->p_stat = SRUN;
2550 		if ((flavor & PSIG_VFORK) == 0) {
2551 			thread_abort_safely(sig_thread);
2552 		}
2553 	}
2554 
2555 sigout_locked:
2556 	if (update_thread_policy) {
2557 		/*
2558 		 * Update the thread policy to heading to terminate, increase priority if
2559 		 * necessary. This needs to be done before we drop the proc lock because the
2560 		 * thread can take the fatal signal once it's dropped.
2561 		 */
2562 		proc_set_thread_policy(sig_thread, TASK_POLICY_ATTRIBUTE, TASK_POLICY_TERMINATED, TASK_POLICY_ENABLE);
2563 	}
2564 
2565 	proc_unlock(sig_proc);
2566 
2567 sigout_unlocked:
2568 	os_reason_free(signal_reason);
2569 	if ((flavor & PSIG_LOCKED) == 0) {
2570 		proc_signalend(sig_proc, 0);
2571 	}
2572 }
2573 
2574 void
psignal(proc_t p,int signum)2575 psignal(proc_t p, int signum)
2576 {
2577 	psignal_internal(p, NULL, NULL, 0, signum, NULL);
2578 }
2579 
2580 void
psignal_with_reason(proc_t p,int signum,struct os_reason * signal_reason)2581 psignal_with_reason(proc_t p, int signum, struct os_reason *signal_reason)
2582 {
2583 	psignal_internal(p, NULL, NULL, 0, signum, signal_reason);
2584 }
2585 
2586 void
psignal_sigkill_with_reason(struct proc * p,struct os_reason * signal_reason)2587 psignal_sigkill_with_reason(struct proc *p, struct os_reason *signal_reason)
2588 {
2589 	psignal_internal(p, NULL, NULL, 0, SIGKILL, signal_reason);
2590 }
2591 
2592 void
psignal_locked(proc_t p,int signum)2593 psignal_locked(proc_t p, int signum)
2594 {
2595 	psignal_internal(p, NULL, NULL, PSIG_LOCKED, signum, NULL);
2596 }
2597 
2598 void
psignal_vfork_with_reason(proc_t p,task_t new_task,thread_t thread,int signum,struct os_reason * signal_reason)2599 psignal_vfork_with_reason(proc_t p, task_t new_task, thread_t thread, int signum, struct os_reason *signal_reason)
2600 {
2601 	psignal_internal(p, new_task, thread, PSIG_VFORK, signum, signal_reason);
2602 }
2603 
2604 void
psignal_vfork(proc_t p,task_t new_task,thread_t thread,int signum)2605 psignal_vfork(proc_t p, task_t new_task, thread_t thread, int signum)
2606 {
2607 	psignal_internal(p, new_task, thread, PSIG_VFORK, signum, NULL);
2608 }
2609 
2610 void
psignal_uthread(thread_t thread,int signum)2611 psignal_uthread(thread_t thread, int signum)
2612 {
2613 	psignal_internal(PROC_NULL, TASK_NULL, thread, PSIG_THREAD, signum, NULL);
2614 }
2615 
2616 /* same as psignal(), but prefer delivery to 'thread' if possible */
2617 void
psignal_try_thread(proc_t p,thread_t thread,int signum)2618 psignal_try_thread(proc_t p, thread_t thread, int signum)
2619 {
2620 	psignal_internal(p, NULL, thread, PSIG_TRY_THREAD, signum, NULL);
2621 }
2622 
2623 void
psignal_try_thread_with_reason(proc_t p,thread_t thread,int signum,struct os_reason * signal_reason)2624 psignal_try_thread_with_reason(proc_t p, thread_t thread, int signum, struct os_reason *signal_reason)
2625 {
2626 	psignal_internal(p, TASK_NULL, thread, PSIG_TRY_THREAD, signum, signal_reason);
2627 }
2628 
2629 void
psignal_thread_with_reason(proc_t p,thread_t thread,int signum,struct os_reason * signal_reason)2630 psignal_thread_with_reason(proc_t p, thread_t thread, int signum, struct os_reason *signal_reason)
2631 {
2632 	psignal_internal(p, TASK_NULL, thread, PSIG_THREAD, signum, signal_reason);
2633 }
2634 
2635 void
psignal_sigkill_try_thread_with_reason(proc_t p,thread_t thread,struct os_reason * signal_reason)2636 psignal_sigkill_try_thread_with_reason(proc_t p, thread_t thread, struct os_reason *signal_reason)
2637 {
2638 	psignal_try_thread_with_reason(p, thread, SIGKILL, signal_reason);
2639 }
2640 
2641 /*
2642  * If the current process has received a signal (should be caught or cause
2643  * termination, should interrupt current syscall), return the signal number.
2644  * Stop signals with default action are processed immediately, then cleared;
2645  * they aren't returned.  This is checked after each entry to the system for
2646  * a syscall or trap (though this can usually be done without calling issignal
2647  * by checking the pending signal masks in the CURSIG macro.) The normal call
2648  * sequence is
2649  *
2650  *	while (signum = CURSIG(curproc))
2651  *		postsig(signum);
2652  */
2653 int
issignal_locked(proc_t p)2654 issignal_locked(proc_t p)
2655 {
2656 	int signum, mask, prop, sigbits;
2657 	thread_t cur_act;
2658 	struct uthread * ut;
2659 	proc_t pp;
2660 	kauth_cred_t my_cred;
2661 	int retval = 0;
2662 	uid_t r_uid;
2663 
2664 	cur_act = current_thread();
2665 
2666 #if SIGNAL_DEBUG
2667 	if (rdebug_proc && (p == rdebug_proc)) {
2668 		ram_printf(3);
2669 	}
2670 #endif /* SIGNAL_DEBUG */
2671 
2672 	/*
2673 	 * Try to grab the signal lock.
2674 	 */
2675 	if (sig_try_locked(p) <= 0) {
2676 		return 0;
2677 	}
2678 
2679 	proc_signalstart(p, 1);
2680 
2681 	ut = get_bsdthread_info(cur_act);
2682 	for (;;) {
2683 		sigbits = ut->uu_siglist & ~ut->uu_sigmask;
2684 
2685 		if (p->p_lflag & P_LPPWAIT) {
2686 			sigbits &= ~stopsigmask;
2687 		}
2688 		if (sigbits == 0) {             /* no signal to send */
2689 			retval = 0;
2690 			goto out;
2691 		}
2692 
2693 		signum = ffs((unsigned int)sigbits);
2694 		mask = sigmask(signum);
2695 		prop = sigprop[signum];
2696 
2697 		/*
2698 		 * We should see pending but ignored signals
2699 		 * only if P_LTRACED was on when they were posted.
2700 		 */
2701 		if (mask & p->p_sigignore && (p->p_lflag & P_LTRACED) == 0) {
2702 			ut->uu_siglist &= ~mask;
2703 			continue;
2704 		}
2705 
2706 		if (p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0) {
2707 			/*
2708 			 * If traced, deliver the signal to the debugger, and wait to be
2709 			 * released.
2710 			 */
2711 			task_t  task;
2712 			p->p_xstat = signum;
2713 
2714 			if (p->p_lflag & P_LSIGEXC) {
2715 				p->sigwait = TRUE;
2716 				p->sigwait_thread = cur_act;
2717 				p->p_stat = SSTOP;
2718 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
2719 				p->p_lflag &= ~P_LWAITED;
2720 				ut->uu_siglist &= ~mask; /* clear the current signal from the pending list */
2721 				proc_signalend(p, 1);
2722 				proc_unlock(p);
2723 				do_bsdexception(EXC_SOFTWARE, EXC_SOFT_SIGNAL, signum);
2724 				proc_lock(p);
2725 				proc_signalstart(p, 1);
2726 			} else {
2727 				proc_unlock(p);
2728 				my_cred = kauth_cred_proc_ref(p);
2729 				r_uid = kauth_cred_getruid(my_cred);
2730 				kauth_cred_unref(&my_cred);
2731 
2732 				/*
2733 				 *	XXX Have to really stop for debuggers;
2734 				 *	XXX stop() doesn't do the right thing.
2735 				 */
2736 				task = proc_task(p);
2737 				task_suspend_internal(task);
2738 
2739 				proc_lock(p);
2740 				p->sigwait = TRUE;
2741 				p->sigwait_thread = cur_act;
2742 				p->p_stat = SSTOP;
2743 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
2744 				p->p_lflag &= ~P_LWAITED;
2745 				ut->uu_siglist &= ~mask;
2746 
2747 				proc_signalend(p, 1);
2748 				proc_unlock(p);
2749 
2750 				pp = proc_parentholdref(p);
2751 				if (pp != PROC_NULL) {
2752 					proc_lock(pp);
2753 					pp->si_pid = proc_getpid(p);
2754 					pp->p_xhighbits = p->p_xhighbits;
2755 					p->p_xhighbits = 0;
2756 					pp->si_status = p->p_xstat;
2757 					pp->si_code = CLD_TRAPPED;
2758 					pp->si_uid = r_uid;
2759 					proc_unlock(pp);
2760 
2761 					psignal(pp, SIGCHLD);
2762 					proc_list_lock();
2763 					wakeup((caddr_t)pp);
2764 					proc_parentdropref(pp, 1);
2765 					proc_list_unlock();
2766 				}
2767 
2768 				assert_wait((caddr_t)&p->sigwait, (THREAD_INTERRUPTIBLE));
2769 				thread_block(THREAD_CONTINUE_NULL);
2770 				proc_lock(p);
2771 				proc_signalstart(p, 1);
2772 			}
2773 
2774 			p->sigwait = FALSE;
2775 			p->sigwait_thread = NULL;
2776 			wakeup((caddr_t)&p->sigwait_thread);
2777 
2778 			if (signum == SIGKILL || ut->uu_siglist & sigmask(SIGKILL)) {
2779 				/*
2780 				 * Deliver a pending sigkill even if it's not the current signal.
2781 				 * Necessary for PT_KILL, which should not be delivered to the
2782 				 * debugger, but we can't differentiate it from any other KILL.
2783 				 */
2784 				signum = SIGKILL;
2785 				goto deliver_sig;
2786 			}
2787 
2788 			/* We may have to quit. */
2789 			if (thread_should_abort(current_thread())) {
2790 				retval = 0;
2791 				goto out;
2792 			}
2793 
2794 			/*
2795 			 * If parent wants us to take the signal,
2796 			 * then it will leave it in p->p_xstat;
2797 			 * otherwise we just look for signals again.
2798 			 */
2799 			signum = p->p_xstat;
2800 			if (signum == 0) {
2801 				continue;
2802 			}
2803 
2804 			/*
2805 			 * Put the new signal into p_siglist.  If the
2806 			 * signal is being masked, look for other signals.
2807 			 */
2808 			mask = sigmask(signum);
2809 			ut->uu_siglist |= mask;
2810 			if (ut->uu_sigmask & mask) {
2811 				continue;
2812 			}
2813 		}
2814 
2815 		/*
2816 		 * Decide whether the signal should be returned.
2817 		 * Return the signal's number, or fall through
2818 		 * to clear it from the pending mask.
2819 		 */
2820 
2821 		switch ((long)SIGACTION(p, signum)) {
2822 		case (long)SIG_DFL:
2823 			/*
2824 			 * If there is a pending stop signal to process
2825 			 * with default action, stop here,
2826 			 * then clear the signal.  However,
2827 			 * if process is member of an orphaned
2828 			 * process group, ignore tty stop signals.
2829 			 */
2830 			if (prop & SA_STOP) {
2831 				struct pgrp * pg;
2832 
2833 				proc_unlock(p);
2834 				pg = proc_pgrp(p, NULL);
2835 				if (p->p_lflag & P_LTRACED ||
2836 				    (pg->pg_jobc == 0 &&
2837 				    prop & SA_TTYSTOP)) {
2838 					proc_lock(p);
2839 					pgrp_rele(pg);
2840 					break; /* ignore signal */
2841 				}
2842 				pgrp_rele(pg);
2843 				if (p->p_stat != SSTOP) {
2844 					proc_lock(p);
2845 					p->p_xstat = signum;
2846 					p->p_stat = SSTOP;
2847 					p->p_lflag &= ~P_LWAITED;
2848 					proc_signalend(p, 1);
2849 					proc_unlock(p);
2850 
2851 					pp = proc_parentholdref(p);
2852 					proc_signalstart(p, 0);
2853 					stop(p, pp);
2854 					if ((pp != PROC_NULL) && ((pp->p_flag & P_NOCLDSTOP) == 0)) {
2855 						my_cred = kauth_cred_proc_ref(p);
2856 						r_uid = kauth_cred_getruid(my_cred);
2857 						kauth_cred_unref(&my_cred);
2858 
2859 						proc_lock(pp);
2860 						pp->si_pid = proc_getpid(p);
2861 						pp->si_status = WEXITSTATUS(p->p_xstat);
2862 						pp->si_code = CLD_STOPPED;
2863 						pp->si_uid = r_uid;
2864 						proc_unlock(pp);
2865 
2866 						psignal(pp, SIGCHLD);
2867 					}
2868 					if (pp != PROC_NULL) {
2869 						proc_parentdropref(pp, 0);
2870 					}
2871 				}
2872 				proc_lock(p);
2873 				break;
2874 			} else if (prop & SA_IGNORE) {
2875 				/*
2876 				 * Except for SIGCONT, shouldn't get here.
2877 				 * Default action is to ignore; drop it.
2878 				 */
2879 				break; /* ignore signal */
2880 			} else {
2881 				goto deliver_sig;
2882 			}
2883 
2884 		case (long)SIG_IGN:
2885 			/*
2886 			 * Masking above should prevent us ever trying
2887 			 * to take action on an ignored signal other
2888 			 * than SIGCONT, unless process is traced.
2889 			 */
2890 			if ((prop & SA_CONT) == 0 &&
2891 			    (p->p_lflag & P_LTRACED) == 0) {
2892 				printf("issignal\n");
2893 			}
2894 			break; /* ignore signal */
2895 
2896 		default:
2897 			/* This signal has an action - deliver it. */
2898 			goto deliver_sig;
2899 		}
2900 
2901 		/* If we dropped through, the signal was ignored - remove it from pending list. */
2902 		ut->uu_siglist &= ~mask;
2903 	} /* for(;;) */
2904 
2905 	/* NOTREACHED */
2906 
2907 deliver_sig:
2908 	ut->uu_siglist &= ~mask;
2909 	retval = signum;
2910 
2911 out:
2912 	proc_signalend(p, 1);
2913 	return retval;
2914 }
2915 
2916 /* called from _sleep */
2917 int
CURSIG(proc_t p)2918 CURSIG(proc_t p)
2919 {
2920 	int signum, mask, prop, sigbits;
2921 	thread_t cur_act;
2922 	struct uthread * ut;
2923 	int retnum = 0;
2924 
2925 
2926 	cur_act = current_thread();
2927 
2928 	ut = get_bsdthread_info(cur_act);
2929 
2930 	if (ut->uu_siglist == 0) {
2931 		return 0;
2932 	}
2933 
2934 	if (((ut->uu_siglist & ~ut->uu_sigmask) == 0) && ((p->p_lflag & P_LTRACED) == 0)) {
2935 		return 0;
2936 	}
2937 
2938 	sigbits = ut->uu_siglist & ~ut->uu_sigmask;
2939 
2940 	for (;;) {
2941 		if (p->p_lflag & P_LPPWAIT) {
2942 			sigbits &= ~stopsigmask;
2943 		}
2944 		if (sigbits == 0) {             /* no signal to send */
2945 			return retnum;
2946 		}
2947 
2948 		signum = ffs((unsigned int)sigbits);
2949 		mask = sigmask(signum);
2950 		prop = sigprop[signum];
2951 		sigbits &= ~mask;               /* take the signal out */
2952 
2953 		/*
2954 		 * We should see pending but ignored signals
2955 		 * only if P_LTRACED was on when they were posted.
2956 		 */
2957 		if (mask & p->p_sigignore && (p->p_lflag & P_LTRACED) == 0) {
2958 			continue;
2959 		}
2960 
2961 		if (p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0) {
2962 			return signum;
2963 		}
2964 
2965 		/*
2966 		 * Decide whether the signal should be returned.
2967 		 * Return the signal's number, or fall through
2968 		 * to clear it from the pending mask.
2969 		 */
2970 
2971 		switch ((long)SIGACTION(p, signum)) {
2972 		case (long)SIG_DFL:
2973 			/*
2974 			 * If there is a pending stop signal to process
2975 			 * with default action, stop here,
2976 			 * then clear the signal.  However,
2977 			 * if process is member of an orphaned
2978 			 * process group, ignore tty stop signals.
2979 			 */
2980 			if (prop & SA_STOP) {
2981 				struct pgrp *pg;
2982 
2983 				pg = proc_pgrp(p, NULL);
2984 
2985 				if (p->p_lflag & P_LTRACED ||
2986 				    (pg->pg_jobc == 0 &&
2987 				    prop & SA_TTYSTOP)) {
2988 					pgrp_rele(pg);
2989 					break;  /* == ignore */
2990 				}
2991 				pgrp_rele(pg);
2992 				retnum = signum;
2993 				break;
2994 			} else if (prop & SA_IGNORE) {
2995 				/*
2996 				 * Except for SIGCONT, shouldn't get here.
2997 				 * Default action is to ignore; drop it.
2998 				 */
2999 				break;          /* == ignore */
3000 			} else {
3001 				return signum;
3002 			}
3003 		/*NOTREACHED*/
3004 
3005 		case (long)SIG_IGN:
3006 			/*
3007 			 * Masking above should prevent us ever trying
3008 			 * to take action on an ignored signal other
3009 			 * than SIGCONT, unless process is traced.
3010 			 */
3011 			if ((prop & SA_CONT) == 0 &&
3012 			    (p->p_lflag & P_LTRACED) == 0) {
3013 				printf("issignal\n");
3014 			}
3015 			break;          /* == ignore */
3016 
3017 		default:
3018 			/*
3019 			 * This signal has an action, let
3020 			 * postsig() process it.
3021 			 */
3022 			return signum;
3023 		}
3024 	}
3025 	/* NOTREACHED */
3026 }
3027 
3028 /*
3029  * Put the argument process into the stopped state and notify the parent
3030  * via wakeup.  Signals are handled elsewhere.  The process must not be
3031  * on the run queue.
3032  */
3033 static void
stop(proc_t p,proc_t parent)3034 stop(proc_t p, proc_t parent)
3035 {
3036 	OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
3037 	if ((parent != PROC_NULL) && (parent->p_stat != SSTOP)) {
3038 		proc_list_lock();
3039 		wakeup((caddr_t)parent);
3040 		proc_list_unlock();
3041 	}
3042 	(void) task_suspend_internal(proc_task(p));
3043 }
3044 
3045 /*
3046  * Take the action for the specified signal
3047  * from the current set of pending signals.
3048  */
3049 void
postsig_locked(int signum)3050 postsig_locked(int signum)
3051 {
3052 	proc_t p = current_proc();
3053 	struct sigacts *ps = &p->p_sigacts;
3054 	user_addr_t catcher;
3055 	uint32_t code;
3056 	int mask, returnmask;
3057 	struct uthread * ut;
3058 	os_reason_t ut_exit_reason = OS_REASON_NULL;
3059 	int coredump_flags = 0;
3060 
3061 #if DIAGNOSTIC
3062 	if (signum == 0) {
3063 		panic("postsig");
3064 	}
3065 #endif
3066 
3067 	/*
3068 	 * Try to grab the signal lock.
3069 	 */
3070 	if (sig_try_locked(p) <= 0) {
3071 		return;
3072 	}
3073 
3074 	proc_signalstart(p, 1);
3075 
3076 	ut = current_uthread();
3077 	mask = sigmask(signum);
3078 	ut->uu_siglist &= ~mask;
3079 	catcher = SIGACTION(p, signum);
3080 	if (catcher == SIG_DFL) {
3081 		/*
3082 		 * Default catcher, where the default is to kill
3083 		 * the process.  (Other cases were ignored above.)
3084 		 */
3085 
3086 		/*
3087 		 * exit_with_reason() below will consume a reference to the thread's exit reason, so we take another
3088 		 * reference so the thread still has one even after we call exit_with_reason(). The thread's reference will
3089 		 * ultimately be destroyed in uthread_cleanup().
3090 		 */
3091 		ut_exit_reason = ut->uu_exit_reason;
3092 		os_reason_ref(ut_exit_reason);
3093 
3094 		p->p_acflag |= AXSIG;
3095 		if (sigprop[signum] & SA_CORE) {
3096 			p->p_sigacts.ps_sig = signum;
3097 			proc_signalend(p, 1);
3098 			proc_unlock(p);
3099 			if (task_is_driver(proc_task(p))) {
3100 				coredump_flags |= COREDUMP_FULLFSYNC;
3101 			}
3102 #if CONFIG_COREDUMP
3103 			if (coredump(p, 0, coredump_flags) == 0) {
3104 				signum |= WCOREFLAG;
3105 			}
3106 #endif
3107 		} else {
3108 			proc_signalend(p, 1);
3109 			proc_unlock(p);
3110 		}
3111 
3112 #if CONFIG_DTRACE
3113 		bzero((caddr_t)&(ut->t_dtrace_siginfo), sizeof(ut->t_dtrace_siginfo));
3114 
3115 		ut->t_dtrace_siginfo.si_signo = signum;
3116 		ut->t_dtrace_siginfo.si_pid = p->si_pid;
3117 		ut->t_dtrace_siginfo.si_uid = p->si_uid;
3118 		ut->t_dtrace_siginfo.si_status = WEXITSTATUS(p->si_status);
3119 
3120 		/* Fire DTrace proc:::fault probe when signal is generated by hardware. */
3121 		switch (signum) {
3122 		case SIGILL: case SIGBUS: case SIGSEGV: case SIGFPE: case SIGTRAP:
3123 			DTRACE_PROC2(fault, int, (int)(ut->uu_code), siginfo_t *, &(ut->t_dtrace_siginfo));
3124 			break;
3125 		default:
3126 			break;
3127 		}
3128 
3129 
3130 		DTRACE_PROC3(signal__handle, int, signum, siginfo_t *, &(ut->t_dtrace_siginfo),
3131 		    void (*)(void), SIG_DFL);
3132 #endif
3133 
3134 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_FRCEXIT) | DBG_FUNC_NONE,
3135 		    proc_getpid(p), W_EXITCODE(0, signum), 3, 0, 0);
3136 
3137 		exit_with_reason(p, W_EXITCODE(0, signum), (int *)NULL, TRUE, TRUE, 0, ut_exit_reason);
3138 
3139 		proc_lock(p);
3140 		return;
3141 	} else {
3142 		/*
3143 		 * If we get here, the signal must be caught.
3144 		 */
3145 #if DIAGNOSTIC
3146 		if (catcher == SIG_IGN || (ut->uu_sigmask & mask)) {
3147 			log(LOG_WARNING,
3148 			    "postsig: processing masked or ignored signal\n");
3149 		}
3150 #endif
3151 
3152 		/*
3153 		 * Set the new mask value and also defer further
3154 		 * occurences of this signal.
3155 		 *
3156 		 * Special case: user has done a sigpause.  Here the
3157 		 * current mask is not of interest, but rather the
3158 		 * mask from before the sigpause is what we want
3159 		 * restored after the signal processing is completed.
3160 		 */
3161 		if (ut->uu_flag & UT_SAS_OLDMASK) {
3162 			returnmask = ut->uu_oldmask;
3163 			ut->uu_flag &= ~UT_SAS_OLDMASK;
3164 			ut->uu_oldmask = 0;
3165 		} else {
3166 			returnmask = ut->uu_sigmask;
3167 		}
3168 		ut->uu_sigmask |= ps->ps_catchmask[signum];
3169 		if ((ps->ps_signodefer & mask) == 0) {
3170 			ut->uu_sigmask |= mask;
3171 		}
3172 		sigset_t siginfo = ps->ps_siginfo;
3173 		if ((signum != SIGILL) && (signum != SIGTRAP) && (ps->ps_sigreset & mask)) {
3174 			if ((signum != SIGCONT) && (sigprop[signum] & SA_IGNORE)) {
3175 				p->p_sigignore |= mask;
3176 			}
3177 			if (SIGACTION(p, signum) != SIG_DFL) {
3178 				proc_set_sigact(p, signum, SIG_DFL);
3179 			}
3180 			ps->ps_siginfo &= ~mask;
3181 			ps->ps_signodefer &= ~mask;
3182 		}
3183 
3184 		if (ps->ps_sig != signum) {
3185 			code = 0;
3186 		} else {
3187 			code = ps->ps_code;
3188 			ps->ps_code = 0;
3189 		}
3190 		OSIncrementAtomicLong(&p->p_stats->p_ru.ru_nsignals);
3191 		sendsig(p, catcher, signum, returnmask, code, siginfo);
3192 	}
3193 	proc_signalend(p, 1);
3194 }
3195 
3196 /*
3197  * Attach a signal knote to the list of knotes for this process.
3198  *
3199  * Signal knotes share the knote list with proc knotes.  This
3200  * could be avoided by using a signal-specific knote list, but
3201  * probably isn't worth the trouble.
3202  */
3203 
3204 static int
filt_sigattach(struct knote * kn,__unused struct kevent_qos_s * kev)3205 filt_sigattach(struct knote *kn, __unused struct kevent_qos_s *kev)
3206 {
3207 	proc_t p = current_proc();  /* can attach only to oneself */
3208 
3209 	proc_klist_lock();
3210 
3211 	kn->kn_proc = p;
3212 	kn->kn_flags |= EV_CLEAR; /* automatically set */
3213 	kn->kn_sdata = 0;         /* incoming data is ignored */
3214 
3215 	KNOTE_ATTACH(&p->p_klist, kn);
3216 
3217 	proc_klist_unlock();
3218 
3219 	/* edge-triggered events can't have fired before we attached */
3220 	return 0;
3221 }
3222 
3223 /*
3224  * remove the knote from the process list, if it hasn't already
3225  * been removed by exit processing.
3226  */
3227 
3228 static void
filt_sigdetach(struct knote * kn)3229 filt_sigdetach(struct knote *kn)
3230 {
3231 	proc_t p;
3232 
3233 	proc_klist_lock();
3234 	p = kn->kn_proc;
3235 	if (p != NULL) {
3236 		kn->kn_proc = NULL;
3237 		KNOTE_DETACH(&p->p_klist, kn);
3238 	}
3239 	proc_klist_unlock();
3240 }
3241 
3242 /*
3243  * Post an event to the signal filter.  Because we share the same list
3244  * as process knotes, we have to filter out and handle only signal events.
3245  *
3246  * We assume that we process fdt_invalidate() before we post the NOTE_EXIT for
3247  * a process during exit.  Therefore, since signal filters can only be
3248  * set up "in-process", we should have already torn down the kqueue
3249  * hosting the EVFILT_SIGNAL knote and should never see NOTE_EXIT.
3250  */
3251 static int
filt_signal(struct knote * kn,long hint)3252 filt_signal(struct knote *kn, long hint)
3253 {
3254 	if (hint & NOTE_SIGNAL) {
3255 		hint &= ~NOTE_SIGNAL;
3256 
3257 		if (kn->kn_id == (unsigned int)hint) {
3258 			kn->kn_hook32++;
3259 		}
3260 	} else if (hint & NOTE_EXIT) {
3261 		panic("filt_signal: detected NOTE_EXIT event");
3262 	}
3263 
3264 	return kn->kn_hook32 != 0;
3265 }
3266 
3267 static int
filt_signaltouch(struct knote * kn,struct kevent_qos_s * kev)3268 filt_signaltouch(struct knote *kn, struct kevent_qos_s *kev)
3269 {
3270 #pragma unused(kev)
3271 
3272 	int res;
3273 
3274 	proc_klist_lock();
3275 
3276 	/*
3277 	 * No data to save - just capture if it is already fired
3278 	 */
3279 	res = (kn->kn_hook32 > 0);
3280 
3281 	proc_klist_unlock();
3282 
3283 	return res;
3284 }
3285 
3286 static int
filt_signalprocess(struct knote * kn,struct kevent_qos_s * kev)3287 filt_signalprocess(struct knote *kn, struct kevent_qos_s *kev)
3288 {
3289 	int res = 0;
3290 
3291 	/*
3292 	 * Snapshot the event data.
3293 	 */
3294 
3295 	proc_klist_lock();
3296 	if (kn->kn_hook32) {
3297 		knote_fill_kevent(kn, kev, kn->kn_hook32);
3298 		kn->kn_hook32 = 0;
3299 		res = 1;
3300 	}
3301 	proc_klist_unlock();
3302 	return res;
3303 }
3304 
3305 void
bsd_ast(thread_t thread)3306 bsd_ast(thread_t thread)
3307 {
3308 	proc_t p = current_proc();
3309 	struct uthread *ut = get_bsdthread_info(thread);
3310 	int     signum;
3311 	static int bsd_init_done = 0;
3312 
3313 	if (p == NULL) {
3314 		return;
3315 	}
3316 
3317 	if (timerisset(&p->p_vtimer_user.it_value)) {
3318 		uint32_t        microsecs;
3319 
3320 		task_vtimer_update(proc_task(p), TASK_VTIMER_USER, &microsecs);
3321 
3322 		if (!itimerdecr(p, &p->p_vtimer_user, microsecs)) {
3323 			if (timerisset(&p->p_vtimer_user.it_value)) {
3324 				task_vtimer_set(proc_task(p), TASK_VTIMER_USER);
3325 			} else {
3326 				task_vtimer_clear(proc_task(p), TASK_VTIMER_USER);
3327 			}
3328 
3329 			psignal_try_thread(p, thread, SIGVTALRM);
3330 		}
3331 	}
3332 
3333 	if (timerisset(&p->p_vtimer_prof.it_value)) {
3334 		uint32_t        microsecs;
3335 
3336 		task_vtimer_update(proc_task(p), TASK_VTIMER_PROF, &microsecs);
3337 
3338 		if (!itimerdecr(p, &p->p_vtimer_prof, microsecs)) {
3339 			if (timerisset(&p->p_vtimer_prof.it_value)) {
3340 				task_vtimer_set(proc_task(p), TASK_VTIMER_PROF);
3341 			} else {
3342 				task_vtimer_clear(proc_task(p), TASK_VTIMER_PROF);
3343 			}
3344 
3345 			psignal_try_thread(p, thread, SIGPROF);
3346 		}
3347 	}
3348 
3349 	if (timerisset(&p->p_rlim_cpu)) {
3350 		struct timeval          tv;
3351 
3352 		task_vtimer_update(proc_task(p), TASK_VTIMER_RLIM, (uint32_t *) &tv.tv_usec);
3353 
3354 		proc_spinlock(p);
3355 		if (p->p_rlim_cpu.tv_sec > 0 || p->p_rlim_cpu.tv_usec > tv.tv_usec) {
3356 			tv.tv_sec = 0;
3357 			timersub(&p->p_rlim_cpu, &tv, &p->p_rlim_cpu);
3358 			proc_spinunlock(p);
3359 		} else {
3360 			timerclear(&p->p_rlim_cpu);
3361 			proc_spinunlock(p);
3362 
3363 			task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
3364 
3365 			psignal_try_thread(p, thread, SIGXCPU);
3366 		}
3367 	}
3368 
3369 #if CONFIG_DTRACE
3370 	if (ut->t_dtrace_sig) {
3371 		uint8_t dt_action_sig = ut->t_dtrace_sig;
3372 		ut->t_dtrace_sig = 0;
3373 		psignal(p, dt_action_sig);
3374 	}
3375 
3376 	if (ut->t_dtrace_stop) {
3377 		ut->t_dtrace_stop = 0;
3378 		proc_lock(p);
3379 		p->p_dtrace_stop = 1;
3380 		proc_unlock(p);
3381 		(void)task_suspend_internal(proc_task(p));
3382 	}
3383 
3384 	if (ut->t_dtrace_resumepid) {
3385 		proc_t resumeproc = proc_find((int)ut->t_dtrace_resumepid);
3386 		ut->t_dtrace_resumepid = 0;
3387 		if (resumeproc != PROC_NULL) {
3388 			proc_lock(resumeproc);
3389 			/* We only act on processes stopped by dtrace */
3390 			if (resumeproc->p_dtrace_stop) {
3391 				resumeproc->p_dtrace_stop = 0;
3392 				proc_unlock(resumeproc);
3393 				task_resume_internal(proc_task(resumeproc));
3394 			} else {
3395 				proc_unlock(resumeproc);
3396 			}
3397 			proc_rele(resumeproc);
3398 		}
3399 	}
3400 
3401 #endif /* CONFIG_DTRACE */
3402 
3403 	proc_lock(p);
3404 	if (CHECK_SIGNALS(p, current_thread(), ut)) {
3405 		while ((signum = issignal_locked(p))) {
3406 			postsig_locked(signum);
3407 		}
3408 	}
3409 	proc_unlock(p);
3410 
3411 	if (!bsd_init_done) {
3412 		bsd_init_done = 1;
3413 		bsdinit_task();
3414 	}
3415 }
3416 
3417 /* ptrace set runnable */
3418 void
pt_setrunnable(proc_t p)3419 pt_setrunnable(proc_t p)
3420 {
3421 	task_t task;
3422 
3423 	task = proc_task(p);
3424 
3425 	if (p->p_lflag & P_LTRACED) {
3426 		proc_lock(p);
3427 		p->p_stat = SRUN;
3428 		proc_unlock(p);
3429 		if (p->sigwait) {
3430 			wakeup((caddr_t)&(p->sigwait));
3431 			if ((p->p_lflag & P_LSIGEXC) == 0) {    // 5878479
3432 				task_release(task);
3433 			}
3434 		}
3435 	}
3436 }
3437 
3438 kern_return_t
do_bsdexception(int exc,int code,int sub)3439 do_bsdexception(
3440 	int exc,
3441 	int code,
3442 	int sub)
3443 {
3444 	mach_exception_data_type_t   codes[EXCEPTION_CODE_MAX];
3445 
3446 	codes[0] = code;
3447 	codes[1] = sub;
3448 	return bsd_exception(exc, codes, 2);
3449 }
3450 
3451 int
proc_pendingsignals(proc_t p,sigset_t mask)3452 proc_pendingsignals(proc_t p, sigset_t mask)
3453 {
3454 	struct uthread * uth;
3455 	sigset_t bits = 0;
3456 
3457 	proc_lock(p);
3458 	/* If the process is in proc exit return no signal info */
3459 	if (p->p_lflag & P_LPEXIT) {
3460 		goto out;
3461 	}
3462 
3463 
3464 	bits = 0;
3465 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
3466 		bits |= (((uth->uu_siglist & ~uth->uu_sigmask) & ~p->p_sigignore) & mask);
3467 	}
3468 out:
3469 	proc_unlock(p);
3470 	return bits;
3471 }
3472 
3473 int
thread_issignal(proc_t p,thread_t th,sigset_t mask)3474 thread_issignal(proc_t p, thread_t th, sigset_t mask)
3475 {
3476 	struct uthread * uth;
3477 	sigset_t  bits = 0;
3478 
3479 	proc_lock(p);
3480 	uth = (struct uthread *)get_bsdthread_info(th);
3481 	if (uth) {
3482 		bits = (((uth->uu_siglist & ~uth->uu_sigmask) & ~p->p_sigignore) & mask);
3483 	}
3484 	proc_unlock(p);
3485 	return bits;
3486 }
3487 
3488 /*
3489  * Allow external reads of the sigprop array.
3490  */
3491 int
hassigprop(int sig,int prop)3492 hassigprop(int sig, int prop)
3493 {
3494 	return sigprop[sig] & prop;
3495 }
3496 
3497 void
pgsigio(pid_t pgid,int sig)3498 pgsigio(pid_t pgid, int sig)
3499 {
3500 	proc_t p = PROC_NULL;
3501 
3502 	if (pgid < 0) {
3503 		gsignal(-(pgid), sig);
3504 	} else if (pgid > 0 && (p = proc_find(pgid)) != 0) {
3505 		psignal(p, sig);
3506 	}
3507 	if (p != PROC_NULL) {
3508 		proc_rele(p);
3509 	}
3510 }
3511 
3512 void
proc_signalstart(proc_t p,int locked)3513 proc_signalstart(proc_t p, int locked)
3514 {
3515 	if (!locked) {
3516 		proc_lock(p);
3517 	}
3518 
3519 	if (p->p_signalholder == current_thread()) {
3520 		panic("proc_signalstart: thread attempting to signal a process for which it holds the signal lock");
3521 	}
3522 
3523 	p->p_sigwaitcnt++;
3524 	while ((p->p_lflag & P_LINSIGNAL) == P_LINSIGNAL) {
3525 		msleep(&p->p_sigmask, &p->p_mlock, 0, "proc_signstart", NULL);
3526 	}
3527 	p->p_sigwaitcnt--;
3528 
3529 	p->p_lflag |= P_LINSIGNAL;
3530 	p->p_signalholder = current_thread();
3531 	if (!locked) {
3532 		proc_unlock(p);
3533 	}
3534 }
3535 
3536 void
proc_signalend(proc_t p,int locked)3537 proc_signalend(proc_t p, int locked)
3538 {
3539 	if (!locked) {
3540 		proc_lock(p);
3541 	}
3542 	p->p_lflag &= ~P_LINSIGNAL;
3543 
3544 	if (p->p_sigwaitcnt > 0) {
3545 		wakeup(&p->p_sigmask);
3546 	}
3547 
3548 	p->p_signalholder = NULL;
3549 	if (!locked) {
3550 		proc_unlock(p);
3551 	}
3552 }
3553 
3554 void
sig_lock_to_exit(proc_t p)3555 sig_lock_to_exit(proc_t p)
3556 {
3557 	thread_t        self = current_thread();
3558 
3559 	p->exit_thread = self;
3560 	proc_unlock(p);
3561 
3562 	task_hold_and_wait(proc_task(p), true);
3563 
3564 	proc_lock(p);
3565 }
3566 
3567 int
sig_try_locked(proc_t p)3568 sig_try_locked(proc_t p)
3569 {
3570 	thread_t        self = current_thread();
3571 
3572 	while (p->sigwait || p->exit_thread) {
3573 		if (p->exit_thread) {
3574 			return 0;
3575 		}
3576 		msleep((caddr_t)&p->sigwait_thread, &p->p_mlock, PCATCH | PDROP, 0, 0);
3577 		if (thread_should_abort(self)) {
3578 			/*
3579 			 * Terminate request - clean up.
3580 			 */
3581 			proc_lock(p);
3582 			return -1;
3583 		}
3584 		proc_lock(p);
3585 	}
3586 	return 1;
3587 }
3588