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