xref: /xnu-10002.61.3/bsd/kern/kern_sig.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
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. To limit the occurrences of shared
1834 	 * cache resliding - and its associated memory tax - only investigate the
1835 	 * fault if it is consequence of accessing unmapped memory (SIGSEGV) or
1836 	 * accessing with incorrect permissions (SIGBUS - KERN_PROTECTION_FAILURE).
1837 	 *
1838 	 * This allows launchd to apply special policies around this fault type.
1839 	 */
1840 	if (reason->osr_namespace == OS_REASON_SIGNAL &&
1841 	    (reason->osr_code == SIGSEGV ||
1842 	    (reason->osr_code == SIGBUS && uth->uu_code == KERN_PROTECTION_FAILURE))) {
1843 		mach_vm_address_t fault_address = uth->uu_subcode;
1844 
1845 		/* Address is in userland, so we hard clear any non-canonical bits to 0 here */
1846 		fault_address = VM_USER_STRIP_PTR(fault_address);
1847 
1848 		if (fault_address >= SHARED_REGION_BASE &&
1849 		    fault_address <= SHARED_REGION_BASE + SHARED_REGION_SIZE) {
1850 			/*
1851 			 * Always report whether the fault happened within the shared cache
1852 			 * region, but only stale the slide if the resliding is extended
1853 			 * to all processes or if the process faulting is a platform one.
1854 			 */
1855 			reason->osr_flags |= OS_REASON_FLAG_SHAREDREGION_FAULT;
1856 
1857 #if __has_feature(ptrauth_calls)
1858 			if (!vm_shared_region_reslide_restrict || csproc_get_platform_binary(current_proc())) {
1859 				reslide_shared_region = TRUE;
1860 			}
1861 #endif /* __has_feature(ptrauth_calls) */
1862 		}
1863 
1864 		if (driver) {
1865 			/*
1866 			 * Always reslide the DriverKit shared region if the driver faulted.
1867 			 * The memory cost is acceptable because the DriverKit shared cache is small
1868 			 * and there are relatively few driver processes.
1869 			 */
1870 			reslide_shared_region = TRUE;
1871 		}
1872 	}
1873 
1874 	if (reslide_shared_region) {
1875 		vm_shared_region_reslide_stale(driver);
1876 	}
1877 }
1878 
1879 void
set_thread_exit_reason(void * th,void * reason,boolean_t proc_locked)1880 set_thread_exit_reason(void *th, void *reason, boolean_t proc_locked)
1881 {
1882 	struct uthread *targ_uth = get_bsdthread_info(th);
1883 	struct task *targ_task = get_threadtask(th);
1884 	proc_t targ_proc = NULL;
1885 
1886 	os_reason_t exit_reason = (os_reason_t)reason;
1887 
1888 	if (exit_reason == OS_REASON_NULL) {
1889 		return;
1890 	}
1891 
1892 	if (!proc_locked) {
1893 		targ_proc = (proc_t)(get_bsdtask_info(targ_task));
1894 
1895 		proc_lock(targ_proc);
1896 	}
1897 
1898 	set_thread_extra_flags(targ_task, targ_uth, exit_reason);
1899 
1900 	if (targ_uth->uu_exit_reason == OS_REASON_NULL) {
1901 		targ_uth->uu_exit_reason = exit_reason;
1902 	} else {
1903 		/* The caller expects that we drop a reference on the exit reason */
1904 		os_reason_free(exit_reason);
1905 	}
1906 
1907 	if (!proc_locked) {
1908 		assert(targ_proc != NULL);
1909 		proc_unlock(targ_proc);
1910 	}
1911 }
1912 
1913 /*
1914  * get_signalthread
1915  *
1916  * Picks an appropriate thread from a process to target with a signal.
1917  *
1918  * Called with proc locked.
1919  * Returns thread with BSD ast set.
1920  *
1921  * We attempt to deliver a proc-wide signal to the first thread in the task.
1922  * This allows single threaded applications which use signals to
1923  * be able to be linked with multithreaded libraries.
1924  */
1925 static kern_return_t
get_signalthread(proc_t p,int signum,thread_t * thr)1926 get_signalthread(proc_t p, int signum, thread_t * thr)
1927 {
1928 	struct uthread *uth;
1929 	sigset_t mask = sigmask(signum);
1930 	bool skip_wqthreads = true;
1931 
1932 	*thr = THREAD_NULL;
1933 
1934 
1935 again:
1936 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
1937 		if (((uth->uu_flag & UT_NO_SIGMASK) == 0) &&
1938 		    (((uth->uu_sigmask & mask) == 0) || (uth->uu_sigwait & mask))) {
1939 			thread_t th = get_machthread(uth);
1940 			if (skip_wqthreads && (thread_get_tag(th) & THREAD_TAG_WORKQUEUE)) {
1941 				/* Workqueue threads may be parked in the kernel unable to
1942 				 * deliver signals for an extended period of time, so skip them
1943 				 * in favor of pthreads in a first pass. (rdar://50054475). */
1944 			} else if (check_actforsig(proc_task(p), th, 1) == KERN_SUCCESS) {
1945 				*thr = th;
1946 				return KERN_SUCCESS;
1947 			}
1948 		}
1949 	}
1950 	if (skip_wqthreads) {
1951 		skip_wqthreads = false;
1952 		goto again;
1953 	}
1954 	if (get_signalact(proc_task(p), thr, 1) == KERN_SUCCESS) {
1955 		return KERN_SUCCESS;
1956 	}
1957 
1958 	return KERN_FAILURE;
1959 }
1960 
1961 static os_reason_t
build_signal_reason(int signum,const char * procname)1962 build_signal_reason(int signum, const char *procname)
1963 {
1964 	os_reason_t signal_reason = OS_REASON_NULL;
1965 	proc_t sender_proc = current_proc();
1966 	uint32_t reason_buffer_size_estimate = 0, proc_name_length = 0;
1967 	const char *default_sender_procname = "unknown";
1968 	mach_vm_address_t data_addr;
1969 	int ret;
1970 
1971 	signal_reason = os_reason_create(OS_REASON_SIGNAL, signum);
1972 	if (signal_reason == OS_REASON_NULL) {
1973 		printf("build_signal_reason: unable to allocate signal reason structure.\n");
1974 		return signal_reason;
1975 	}
1976 
1977 	reason_buffer_size_estimate = kcdata_estimate_required_buffer_size(2, sizeof(sender_proc->p_name) +
1978 	    sizeof(pid_t));
1979 
1980 	ret = os_reason_alloc_buffer_noblock(signal_reason, reason_buffer_size_estimate);
1981 	if (ret != 0) {
1982 		printf("build_signal_reason: unable to allocate signal reason buffer.\n");
1983 		return signal_reason;
1984 	}
1985 
1986 	if (KERN_SUCCESS == kcdata_get_memory_addr(&signal_reason->osr_kcd_descriptor, KCDATA_TYPE_PID,
1987 	    sizeof(pid_t), &data_addr)) {
1988 		pid_t pid = proc_getpid(sender_proc);
1989 		kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &pid, sizeof(pid));
1990 	} else {
1991 		printf("build_signal_reason: exceeded space in signal reason buf, unable to log PID\n");
1992 	}
1993 
1994 	proc_name_length = sizeof(sender_proc->p_name);
1995 	if (KERN_SUCCESS == kcdata_get_memory_addr(&signal_reason->osr_kcd_descriptor, KCDATA_TYPE_PROCNAME,
1996 	    proc_name_length, &data_addr)) {
1997 		if (procname) {
1998 			char truncated_procname[proc_name_length];
1999 			strncpy((char *) &truncated_procname, procname, proc_name_length);
2000 			truncated_procname[proc_name_length - 1] = '\0';
2001 
2002 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, truncated_procname,
2003 			    (uint32_t)strlen((char *) &truncated_procname));
2004 		} else if (*sender_proc->p_name) {
2005 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &sender_proc->p_name,
2006 			    sizeof(sender_proc->p_name));
2007 		} else {
2008 			kcdata_memcpy(&signal_reason->osr_kcd_descriptor, data_addr, &default_sender_procname,
2009 			    (uint32_t)strlen(default_sender_procname) + 1);
2010 		}
2011 	} else {
2012 		printf("build_signal_reason: exceeded space in signal reason buf, unable to log procname\n");
2013 	}
2014 
2015 	return signal_reason;
2016 }
2017 
2018 /*
2019  * Send the signal to the process.  If the signal has an action, the action
2020  * is usually performed by the target process rather than the caller; we add
2021  * the signal to the set of pending signals for the process.
2022  *
2023  * Always drops a reference on a signal_reason if one is provided, whether via
2024  * passing it to a thread or deallocating directly.
2025  *
2026  * Exceptions:
2027  *   o When a stop signal is sent to a sleeping process that takes the
2028  *     default action, the process is stopped without awakening it.
2029  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2030  *     regardless of the signal action (eg, blocked or ignored).
2031  *
2032  * Other ignored signals are discarded immediately.
2033  */
2034 static void
psignal_internal(proc_t p,task_t task,thread_t thread,int flavor,int signum,os_reason_t signal_reason)2035 psignal_internal(proc_t p, task_t task, thread_t thread, int flavor, int signum, os_reason_t signal_reason)
2036 {
2037 	int prop;
2038 	user_addr_t action = USER_ADDR_NULL;
2039 	proc_t                  sig_proc;
2040 	thread_t                sig_thread;
2041 	task_t                  sig_task;
2042 	int                     mask;
2043 	struct uthread          *uth;
2044 	kern_return_t           kret;
2045 	uid_t                   r_uid;
2046 	proc_t                  pp;
2047 	kauth_cred_t            my_cred;
2048 	char                    *launchd_exit_reason_desc = NULL;
2049 	boolean_t               update_thread_policy = FALSE;
2050 
2051 	if ((u_int)signum >= NSIG || signum == 0) {
2052 		panic("psignal: bad signal number %d", signum);
2053 	}
2054 
2055 	mask = sigmask(signum);
2056 	prop = sigprop[signum];
2057 
2058 #if SIGNAL_DEBUG
2059 	if (rdebug_proc && (p != PROC_NULL) && (p == rdebug_proc)) {
2060 		ram_printf(3);
2061 	}
2062 #endif /* SIGNAL_DEBUG */
2063 
2064 	/* catch unexpected initproc kills early for easier debuggging */
2065 	if (signum == SIGKILL && p == initproc) {
2066 		if (signal_reason == NULL) {
2067 			panic_plain("unexpected SIGKILL of %s %s (no reason provided)",
2068 			    (p->p_name[0] != '\0' ? p->p_name : "initproc"),
2069 			    ((proc_getcsflags(p) & CS_KILLED) ? "(CS_KILLED)" : ""));
2070 		} else {
2071 			launchd_exit_reason_desc = exit_reason_get_string_desc(signal_reason);
2072 			panic_plain("unexpected SIGKILL of %s %s with reason -- namespace %d code 0x%llx description %." LAUNCHD_PANIC_REASON_STRING_MAXLEN "s",
2073 			    (p->p_name[0] != '\0' ? p->p_name : "initproc"),
2074 			    ((proc_getcsflags(p) & CS_KILLED) ? "(CS_KILLED)" : ""),
2075 			    signal_reason->osr_namespace, signal_reason->osr_code,
2076 			    launchd_exit_reason_desc ? launchd_exit_reason_desc : "none");
2077 		}
2078 	}
2079 
2080 	/*
2081 	 *	We will need the task pointer later.  Grab it now to
2082 	 *	check for a zombie process.  Also don't send signals
2083 	 *	to kernel internal tasks.
2084 	 */
2085 	if (flavor & PSIG_VFORK) {
2086 		sig_task = task;
2087 		sig_thread = thread;
2088 		sig_proc = p;
2089 	} else if (flavor & PSIG_THREAD) {
2090 		sig_task = get_threadtask(thread);
2091 		sig_thread = thread;
2092 		sig_proc = (proc_t)get_bsdtask_info(sig_task);
2093 	} else if (flavor & PSIG_TRY_THREAD) {
2094 		assert((thread == current_thread()) && (p == current_proc()));
2095 		sig_task = proc_task(p);
2096 		sig_thread = thread;
2097 		sig_proc = p;
2098 	} else {
2099 		sig_task = proc_task(p);
2100 		sig_thread = THREAD_NULL;
2101 		sig_proc = p;
2102 	}
2103 
2104 	if ((sig_task == TASK_NULL) || is_kerneltask(sig_task)) {
2105 		os_reason_free(signal_reason);
2106 		return;
2107 	}
2108 
2109 	if ((flavor & (PSIG_VFORK | PSIG_THREAD)) == 0) {
2110 		proc_knote(sig_proc, NOTE_SIGNAL | signum);
2111 	}
2112 
2113 	if ((flavor & PSIG_LOCKED) == 0) {
2114 		proc_signalstart(sig_proc, 0);
2115 	}
2116 
2117 	/* Don't send signals to a process that has ignored them. */
2118 	if (((flavor & PSIG_VFORK) == 0) && ((sig_proc->p_lflag & P_LTRACED) == 0) && (sig_proc->p_sigignore & mask)) {
2119 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2120 		goto sigout_unlocked;
2121 	}
2122 
2123 	/*
2124 	 * The proc_lock prevents the targeted thread from being deallocated
2125 	 * or handling the signal until we're done signaling it.
2126 	 *
2127 	 * Once the proc_lock is dropped, we have no guarantee the thread or uthread exists anymore.
2128 	 *
2129 	 * XXX: What if the thread goes inactive after the thread passes bsd ast point?
2130 	 */
2131 	proc_lock(sig_proc);
2132 
2133 	/*
2134 	 * Don't send signals to a process which has already exited and thus
2135 	 * committed to a particular p_xstat exit code.
2136 	 * Additionally, don't abort the process running 'reboot'.
2137 	 */
2138 	if (ISSET(sig_proc->p_flag, P_REBOOT) || ISSET(sig_proc->p_lflag, P_LEXIT)) {
2139 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2140 		goto sigout_locked;
2141 	}
2142 
2143 	if (flavor & PSIG_VFORK) {
2144 		action = SIG_DFL;
2145 		act_set_astbsd(sig_thread);
2146 		kret = KERN_SUCCESS;
2147 	} else if (flavor & PSIG_TRY_THREAD) {
2148 		uth = get_bsdthread_info(sig_thread);
2149 		if (((uth->uu_flag & UT_NO_SIGMASK) == 0) &&
2150 		    (((uth->uu_sigmask & mask) == 0) || (uth->uu_sigwait & mask)) &&
2151 		    ((kret = check_actforsig(proc_task(sig_proc), sig_thread, 1)) == KERN_SUCCESS)) {
2152 			/* deliver to specified thread */
2153 		} else {
2154 			/* deliver to any willing thread */
2155 			kret = get_signalthread(sig_proc, signum, &sig_thread);
2156 		}
2157 	} else if (flavor & PSIG_THREAD) {
2158 		/* If successful return with ast set */
2159 		kret = check_actforsig(sig_task, sig_thread, 1);
2160 	} else {
2161 		/* If successful return with ast set */
2162 		kret = get_signalthread(sig_proc, signum, &sig_thread);
2163 	}
2164 
2165 	if (kret != KERN_SUCCESS) {
2166 		DTRACE_PROC3(signal__discard, thread_t, sig_thread, proc_t, sig_proc, int, signum);
2167 		proc_unlock(sig_proc);
2168 		goto sigout_unlocked;
2169 	}
2170 
2171 	uth = get_bsdthread_info(sig_thread);
2172 
2173 	/*
2174 	 * If proc is traced, always give parent a chance.
2175 	 */
2176 
2177 	if ((flavor & PSIG_VFORK) == 0) {
2178 		if (sig_proc->p_lflag & P_LTRACED) {
2179 			action = SIG_DFL;
2180 		} else {
2181 			/*
2182 			 * If the signal is being ignored,
2183 			 * then we forget about it immediately.
2184 			 * (Note: we don't set SIGCONT in p_sigignore,
2185 			 * and if it is set to SIG_IGN,
2186 			 * action will be SIG_DFL here.)
2187 			 */
2188 			if (sig_proc->p_sigignore & mask) {
2189 				goto sigout_locked;
2190 			}
2191 
2192 			if (uth->uu_sigwait & mask) {
2193 				action = KERN_SIG_WAIT;
2194 			} else if (uth->uu_sigmask & mask) {
2195 				action = KERN_SIG_HOLD;
2196 			} else if (sig_proc->p_sigcatch & mask) {
2197 				action = KERN_SIG_CATCH;
2198 			} else {
2199 				action = SIG_DFL;
2200 			}
2201 		}
2202 	}
2203 
2204 	/* TODO: p_nice isn't hooked up to the scheduler... */
2205 	if (sig_proc->p_nice > NZERO && action == SIG_DFL && (prop & SA_KILL) &&
2206 	    (sig_proc->p_lflag & P_LTRACED) == 0) {
2207 		sig_proc->p_nice = NZERO;
2208 	}
2209 
2210 	if (prop & SA_CONT) {
2211 		uth->uu_siglist &= ~stopsigmask;
2212 	}
2213 
2214 	if (prop & SA_STOP) {
2215 		struct pgrp *pg;
2216 		/*
2217 		 * If sending a tty stop signal to a member of an orphaned
2218 		 * process group, discard the signal here if the action
2219 		 * is default; don't stop the process below if sleeping,
2220 		 * and don't clear any pending SIGCONT.
2221 		 */
2222 		pg = proc_pgrp(sig_proc, NULL);
2223 		if (prop & SA_TTYSTOP && pg->pg_jobc == 0 &&
2224 		    action == SIG_DFL) {
2225 			pgrp_rele(pg);
2226 			goto sigout_locked;
2227 		}
2228 		pgrp_rele(pg);
2229 		uth->uu_siglist &= ~contsigmask;
2230 	}
2231 
2232 	uth->uu_siglist |= mask;
2233 
2234 	/*
2235 	 * Defer further processing for signals which are held,
2236 	 * except that stopped processes must be continued by SIGCONT.
2237 	 */
2238 	if ((action == KERN_SIG_HOLD) && ((prop & SA_CONT) == 0 || sig_proc->p_stat != SSTOP)) {
2239 		goto sigout_locked;
2240 	}
2241 
2242 	/*
2243 	 *	SIGKILL priority twiddling moved here from above because
2244 	 *	it needs sig_thread.  Could merge it into large switch
2245 	 *	below if we didn't care about priority for tracing
2246 	 *	as SIGKILL's action is always SIG_DFL.
2247 	 *
2248 	 *	TODO: p_nice isn't hooked up to the scheduler...
2249 	 */
2250 	if ((signum == SIGKILL) && (sig_proc->p_nice > NZERO)) {
2251 		sig_proc->p_nice = NZERO;
2252 	}
2253 
2254 	/*
2255 	 *	Process is traced - wake it up (if not already
2256 	 *	stopped) so that it can discover the signal in
2257 	 *	issig() and stop for the parent.
2258 	 */
2259 	if (sig_proc->p_lflag & P_LTRACED) {
2260 		if (sig_proc->p_stat != SSTOP) {
2261 			goto runlocked;
2262 		} else {
2263 			goto sigout_locked;
2264 		}
2265 	}
2266 
2267 	if ((flavor & PSIG_VFORK) != 0) {
2268 		goto runlocked;
2269 	}
2270 
2271 	if (action == KERN_SIG_WAIT) {
2272 #if CONFIG_DTRACE
2273 		/*
2274 		 * DTrace proc signal-clear returns a siginfo_t. Collect the needed info.
2275 		 */
2276 		r_uid = kauth_getruid(); /* per thread credential; protected by our thread context */
2277 
2278 		bzero((caddr_t)&(uth->t_dtrace_siginfo), sizeof(uth->t_dtrace_siginfo));
2279 
2280 		uth->t_dtrace_siginfo.si_signo = signum;
2281 		uth->t_dtrace_siginfo.si_pid = proc_getpid(current_proc());
2282 		uth->t_dtrace_siginfo.si_status = W_EXITCODE(signum, 0);
2283 		uth->t_dtrace_siginfo.si_uid = r_uid;
2284 		uth->t_dtrace_siginfo.si_code = 0;
2285 #endif
2286 		uth->uu_sigwait = mask;
2287 		uth->uu_siglist &= ~mask;
2288 		wakeup(&uth->uu_sigwait);
2289 		/* if it is SIGCONT resume whole process */
2290 		if (prop & SA_CONT) {
2291 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2292 			sig_proc->p_contproc = proc_getpid(current_proc());
2293 			(void) task_resume_internal(sig_task);
2294 		}
2295 		goto sigout_locked;
2296 	}
2297 
2298 	if (action != SIG_DFL) {
2299 		/*
2300 		 *	User wants to catch the signal.
2301 		 *	Wake up the thread, but don't un-suspend it
2302 		 *	(except for SIGCONT).
2303 		 */
2304 		if (prop & SA_CONT) {
2305 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2306 			(void) task_resume_internal(sig_task);
2307 			sig_proc->p_stat = SRUN;
2308 		} else if (sig_proc->p_stat == SSTOP) {
2309 			goto sigout_locked;
2310 		}
2311 		/*
2312 		 * Fill out siginfo structure information to pass to the
2313 		 * signalled process/thread sigaction handler, when it
2314 		 * wakes up.  si_code is 0 because this is an ordinary
2315 		 * signal, not a SIGCHLD, and so si_status is the signal
2316 		 * number itself, instead of the child process exit status.
2317 		 * We shift this left because it will be shifted right before
2318 		 * it is passed to user space.  kind of ugly to use W_EXITCODE
2319 		 * this way, but it beats defining a new macro.
2320 		 *
2321 		 * Note:	Avoid the SIGCHLD recursion case!
2322 		 */
2323 		if (signum != SIGCHLD) {
2324 			r_uid = kauth_getruid();
2325 
2326 			sig_proc->si_pid = proc_getpid(current_proc());
2327 			sig_proc->si_status = W_EXITCODE(signum, 0);
2328 			sig_proc->si_uid = r_uid;
2329 			sig_proc->si_code = 0;
2330 		}
2331 
2332 		goto runlocked;
2333 	} else {
2334 		/*	Default action - varies */
2335 		if (mask & stopsigmask) {
2336 			assert(signal_reason == NULL);
2337 			/*
2338 			 * These are the signals which by default
2339 			 * stop a process.
2340 			 *
2341 			 * Don't clog system with children of init
2342 			 * stopped from the keyboard.
2343 			 */
2344 			if (!(prop & SA_STOP) && sig_proc->p_pptr == initproc) {
2345 				uth->uu_siglist &= ~mask;
2346 				proc_unlock(sig_proc);
2347 				/* siglock still locked, proc_lock not locked */
2348 				psignal_locked(sig_proc, SIGKILL);
2349 				goto sigout_unlocked;
2350 			}
2351 
2352 			/*
2353 			 *	Stop the task
2354 			 *	if task hasn't already been stopped by
2355 			 *	a signal.
2356 			 */
2357 			uth->uu_siglist &= ~mask;
2358 			if (sig_proc->p_stat != SSTOP) {
2359 				sig_proc->p_xstat = signum;
2360 				sig_proc->p_stat = SSTOP;
2361 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &sig_proc->p_flag);
2362 				sig_proc->p_lflag &= ~P_LWAITED;
2363 				proc_signalend(sig_proc, 1);
2364 				proc_unlock(sig_proc);
2365 
2366 				pp = proc_parentholdref(sig_proc);
2367 				proc_signalstart(sig_proc, 0);
2368 				stop(sig_proc, pp);
2369 				if ((pp != PROC_NULL) && ((pp->p_flag & P_NOCLDSTOP) == 0)) {
2370 					my_cred = kauth_cred_proc_ref(sig_proc);
2371 					r_uid = kauth_cred_getruid(my_cred);
2372 					kauth_cred_unref(&my_cred);
2373 
2374 					proc_lock(sig_proc);
2375 					pp->si_pid = proc_getpid(sig_proc);
2376 					/*
2377 					 * POSIX: sigaction for a stopped child
2378 					 * when sent to the parent must set the
2379 					 * child's signal number into si_status.
2380 					 */
2381 					if (signum != SIGSTOP) {
2382 						pp->si_status = WEXITSTATUS(sig_proc->p_xstat);
2383 					} else {
2384 						pp->si_status = W_EXITCODE(signum, signum);
2385 					}
2386 					pp->si_code = CLD_STOPPED;
2387 					pp->si_uid = r_uid;
2388 					proc_unlock(sig_proc);
2389 
2390 					psignal(pp, SIGCHLD);
2391 				}
2392 				if (pp != PROC_NULL) {
2393 					proc_parentdropref(pp, 0);
2394 				}
2395 
2396 				goto sigout_unlocked;
2397 			}
2398 
2399 			goto sigout_locked;
2400 		}
2401 
2402 		DTRACE_PROC3(signal__send, thread_t, sig_thread, proc_t, p, int, signum);
2403 
2404 		switch (signum) {
2405 		/*
2406 		 * Signals ignored by default have been dealt
2407 		 * with already, since their bits are on in
2408 		 * p_sigignore.
2409 		 */
2410 
2411 		case SIGKILL:
2412 			/*
2413 			 * Kill signal always sets process running and
2414 			 * unsuspends it.
2415 			 */
2416 			/*
2417 			 *	Process will be running after 'run'
2418 			 */
2419 			sig_proc->p_stat = SRUN;
2420 			/*
2421 			 * In scenarios where suspend/resume are racing
2422 			 * the signal we are missing AST_BSD by the time
2423 			 * we get here, set again to avoid races. This
2424 			 * was the scenario with spindump enabled shutdowns.
2425 			 * We would need to cover this approp down the line.
2426 			 */
2427 			act_set_astbsd(sig_thread);
2428 			kret = thread_abort(sig_thread);
2429 			update_thread_policy = (kret == KERN_SUCCESS);
2430 
2431 			if (uth->uu_exit_reason == OS_REASON_NULL) {
2432 				if (signal_reason == OS_REASON_NULL) {
2433 					KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2434 					    proc_getpid(sig_proc), OS_REASON_SIGNAL, signum, 0, 0);
2435 
2436 					signal_reason = build_signal_reason(signum, NULL);
2437 				}
2438 
2439 				os_reason_ref(signal_reason);
2440 				set_thread_exit_reason(sig_thread, signal_reason, TRUE);
2441 			}
2442 
2443 			goto sigout_locked;
2444 
2445 		case SIGCONT:
2446 			/*
2447 			 * Let the process run.  If it's sleeping on an
2448 			 * event, it remains so.
2449 			 */
2450 			assert(signal_reason == NULL);
2451 			OSBitOrAtomic(P_CONTINUED, &sig_proc->p_flag);
2452 			sig_proc->p_contproc = proc_getpid(sig_proc);
2453 			sig_proc->p_xstat = signum;
2454 
2455 			(void) task_resume_internal(sig_task);
2456 
2457 			/*
2458 			 * When processing a SIGCONT, we need to check
2459 			 * to see if there are signals pending that
2460 			 * were not delivered because we had been
2461 			 * previously stopped.  If that's the case,
2462 			 * we need to thread_abort_safely() to trigger
2463 			 * interruption of the current system call to
2464 			 * cause their handlers to fire.  If it's only
2465 			 * the SIGCONT, then don't wake up.
2466 			 */
2467 			if (((flavor & (PSIG_VFORK | PSIG_THREAD)) == 0) && (((uth->uu_siglist & ~uth->uu_sigmask) & ~sig_proc->p_sigignore) & ~mask)) {
2468 				uth->uu_siglist &= ~mask;
2469 				sig_proc->p_stat = SRUN;
2470 				goto runlocked;
2471 			}
2472 
2473 			uth->uu_siglist &= ~mask;
2474 			sig_proc->p_stat = SRUN;
2475 			goto sigout_locked;
2476 
2477 		default:
2478 		{
2479 			/*
2480 			 * A signal which has a default action of killing
2481 			 * the process, and for which there is no handler,
2482 			 * needs to act like SIGKILL
2483 			 *
2484 			 * The thread_sstop condition is a remnant of a fix
2485 			 * where PSIG_THREAD exit reasons were not set
2486 			 * correctly (93593933). We keep the behavior with
2487 			 * SSTOP the same as before.
2488 			 */
2489 			const bool default_kill = (action == SIG_DFL) && (prop & SA_KILL);
2490 			const bool thread_sstop = (flavor & PSIG_THREAD) && (sig_proc->p_stat == SSTOP);
2491 
2492 			if (default_kill && !thread_sstop) {
2493 				sig_proc->p_stat = SRUN;
2494 				kret = thread_abort(sig_thread);
2495 				update_thread_policy = (kret == KERN_SUCCESS);
2496 
2497 				if (uth->uu_exit_reason == OS_REASON_NULL) {
2498 					if (signal_reason == OS_REASON_NULL) {
2499 						KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2500 						    proc_getpid(sig_proc), OS_REASON_SIGNAL, signum, 0, 0);
2501 
2502 						signal_reason = build_signal_reason(signum, NULL);
2503 					}
2504 
2505 					os_reason_ref(signal_reason);
2506 					set_thread_exit_reason(sig_thread, signal_reason, TRUE);
2507 				}
2508 
2509 				goto sigout_locked;
2510 			}
2511 
2512 			/*
2513 			 * All other signals wake up the process, but don't
2514 			 * resume it.
2515 			 */
2516 			if (sig_proc->p_stat == SSTOP) {
2517 				goto sigout_locked;
2518 			}
2519 			goto runlocked;
2520 		}
2521 		}
2522 	}
2523 	/*NOTREACHED*/
2524 
2525 runlocked:
2526 	/*
2527 	 * If we're being traced (possibly because someone attached us
2528 	 * while we were stopped), check for a signal from the debugger.
2529 	 */
2530 	if (sig_proc->p_stat == SSTOP) {
2531 		if ((sig_proc->p_lflag & P_LTRACED) != 0 && sig_proc->p_xstat != 0) {
2532 			uth->uu_siglist |= sigmask(sig_proc->p_xstat);
2533 		}
2534 
2535 		if ((flavor & PSIG_VFORK) != 0) {
2536 			sig_proc->p_stat = SRUN;
2537 		}
2538 	} else {
2539 		/*
2540 		 * setrunnable(p) in BSD and
2541 		 * Wake up the thread if it is interruptible.
2542 		 */
2543 		sig_proc->p_stat = SRUN;
2544 		if ((flavor & PSIG_VFORK) == 0) {
2545 			thread_abort_safely(sig_thread);
2546 		}
2547 	}
2548 
2549 sigout_locked:
2550 	if (update_thread_policy) {
2551 		/*
2552 		 * Update the thread policy to heading to terminate, increase priority if
2553 		 * necessary. This needs to be done before we drop the proc lock because the
2554 		 * thread can take the fatal signal once it's dropped.
2555 		 */
2556 		proc_set_thread_policy(sig_thread, TASK_POLICY_ATTRIBUTE, TASK_POLICY_TERMINATED, TASK_POLICY_ENABLE);
2557 	}
2558 
2559 	proc_unlock(sig_proc);
2560 
2561 sigout_unlocked:
2562 	os_reason_free(signal_reason);
2563 	if ((flavor & PSIG_LOCKED) == 0) {
2564 		proc_signalend(sig_proc, 0);
2565 	}
2566 }
2567 
2568 void
psignal(proc_t p,int signum)2569 psignal(proc_t p, int signum)
2570 {
2571 	psignal_internal(p, NULL, NULL, 0, signum, NULL);
2572 }
2573 
2574 void
psignal_with_reason(proc_t p,int signum,struct os_reason * signal_reason)2575 psignal_with_reason(proc_t p, int signum, struct os_reason *signal_reason)
2576 {
2577 	psignal_internal(p, NULL, NULL, 0, signum, signal_reason);
2578 }
2579 
2580 void
psignal_sigkill_with_reason(struct proc * p,struct os_reason * signal_reason)2581 psignal_sigkill_with_reason(struct proc *p, struct os_reason *signal_reason)
2582 {
2583 	psignal_internal(p, NULL, NULL, 0, SIGKILL, signal_reason);
2584 }
2585 
2586 void
psignal_locked(proc_t p,int signum)2587 psignal_locked(proc_t p, int signum)
2588 {
2589 	psignal_internal(p, NULL, NULL, PSIG_LOCKED, signum, NULL);
2590 }
2591 
2592 void
psignal_vfork_with_reason(proc_t p,task_t new_task,thread_t thread,int signum,struct os_reason * signal_reason)2593 psignal_vfork_with_reason(proc_t p, task_t new_task, thread_t thread, int signum, struct os_reason *signal_reason)
2594 {
2595 	psignal_internal(p, new_task, thread, PSIG_VFORK, signum, signal_reason);
2596 }
2597 
2598 void
psignal_vfork(proc_t p,task_t new_task,thread_t thread,int signum)2599 psignal_vfork(proc_t p, task_t new_task, thread_t thread, int signum)
2600 {
2601 	psignal_internal(p, new_task, thread, PSIG_VFORK, signum, NULL);
2602 }
2603 
2604 void
psignal_uthread(thread_t thread,int signum)2605 psignal_uthread(thread_t thread, int signum)
2606 {
2607 	psignal_internal(PROC_NULL, TASK_NULL, thread, PSIG_THREAD, signum, NULL);
2608 }
2609 
2610 /* same as psignal(), but prefer delivery to 'thread' if possible */
2611 void
psignal_try_thread(proc_t p,thread_t thread,int signum)2612 psignal_try_thread(proc_t p, thread_t thread, int signum)
2613 {
2614 	psignal_internal(p, NULL, thread, PSIG_TRY_THREAD, signum, NULL);
2615 }
2616 
2617 void
psignal_try_thread_with_reason(proc_t p,thread_t thread,int signum,struct os_reason * signal_reason)2618 psignal_try_thread_with_reason(proc_t p, thread_t thread, int signum, struct os_reason *signal_reason)
2619 {
2620 	psignal_internal(p, TASK_NULL, thread, PSIG_TRY_THREAD, signum, signal_reason);
2621 }
2622 
2623 void
psignal_thread_with_reason(proc_t p,thread_t thread,int signum,struct os_reason * signal_reason)2624 psignal_thread_with_reason(proc_t p, thread_t thread, int signum, struct os_reason *signal_reason)
2625 {
2626 	psignal_internal(p, TASK_NULL, thread, PSIG_THREAD, signum, signal_reason);
2627 }
2628 
2629 /*
2630  * If the current process has received a signal (should be caught or cause
2631  * termination, should interrupt current syscall), return the signal number.
2632  * Stop signals with default action are processed immediately, then cleared;
2633  * they aren't returned.  This is checked after each entry to the system for
2634  * a syscall or trap (though this can usually be done without calling issignal
2635  * by checking the pending signal masks in the CURSIG macro.) The normal call
2636  * sequence is
2637  *
2638  *	while (signum = CURSIG(curproc))
2639  *		postsig(signum);
2640  */
2641 int
issignal_locked(proc_t p)2642 issignal_locked(proc_t p)
2643 {
2644 	int signum, mask, prop, sigbits;
2645 	thread_t cur_act;
2646 	struct uthread * ut;
2647 	proc_t pp;
2648 	kauth_cred_t my_cred;
2649 	int retval = 0;
2650 	uid_t r_uid;
2651 
2652 	cur_act = current_thread();
2653 
2654 #if SIGNAL_DEBUG
2655 	if (rdebug_proc && (p == rdebug_proc)) {
2656 		ram_printf(3);
2657 	}
2658 #endif /* SIGNAL_DEBUG */
2659 
2660 	/*
2661 	 * Try to grab the signal lock.
2662 	 */
2663 	if (sig_try_locked(p) <= 0) {
2664 		return 0;
2665 	}
2666 
2667 	proc_signalstart(p, 1);
2668 
2669 	ut = get_bsdthread_info(cur_act);
2670 	for (;;) {
2671 		sigbits = ut->uu_siglist & ~ut->uu_sigmask;
2672 
2673 		if (p->p_lflag & P_LPPWAIT) {
2674 			sigbits &= ~stopsigmask;
2675 		}
2676 		if (sigbits == 0) {             /* no signal to send */
2677 			retval = 0;
2678 			goto out;
2679 		}
2680 
2681 		signum = ffs((unsigned int)sigbits);
2682 		mask = sigmask(signum);
2683 		prop = sigprop[signum];
2684 
2685 		/*
2686 		 * We should see pending but ignored signals
2687 		 * only if P_LTRACED was on when they were posted.
2688 		 */
2689 		if (mask & p->p_sigignore && (p->p_lflag & P_LTRACED) == 0) {
2690 			ut->uu_siglist &= ~mask;
2691 			continue;
2692 		}
2693 
2694 		if (p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0) {
2695 			/*
2696 			 * If traced, deliver the signal to the debugger, and wait to be
2697 			 * released.
2698 			 */
2699 			task_t  task;
2700 			p->p_xstat = signum;
2701 
2702 			if (p->p_lflag & P_LSIGEXC) {
2703 				p->sigwait = TRUE;
2704 				p->sigwait_thread = cur_act;
2705 				p->p_stat = SSTOP;
2706 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
2707 				p->p_lflag &= ~P_LWAITED;
2708 				ut->uu_siglist &= ~mask; /* clear the current signal from the pending list */
2709 				proc_signalend(p, 1);
2710 				proc_unlock(p);
2711 				do_bsdexception(EXC_SOFTWARE, EXC_SOFT_SIGNAL, signum);
2712 				proc_lock(p);
2713 				proc_signalstart(p, 1);
2714 			} else {
2715 				proc_unlock(p);
2716 				my_cred = kauth_cred_proc_ref(p);
2717 				r_uid = kauth_cred_getruid(my_cred);
2718 				kauth_cred_unref(&my_cred);
2719 
2720 				/*
2721 				 *	XXX Have to really stop for debuggers;
2722 				 *	XXX stop() doesn't do the right thing.
2723 				 */
2724 				task = proc_task(p);
2725 				task_suspend_internal(task);
2726 
2727 				proc_lock(p);
2728 				p->sigwait = TRUE;
2729 				p->sigwait_thread = cur_act;
2730 				p->p_stat = SSTOP;
2731 				OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
2732 				p->p_lflag &= ~P_LWAITED;
2733 				ut->uu_siglist &= ~mask;
2734 
2735 				proc_signalend(p, 1);
2736 				proc_unlock(p);
2737 
2738 				pp = proc_parentholdref(p);
2739 				if (pp != PROC_NULL) {
2740 					proc_lock(pp);
2741 					pp->si_pid = proc_getpid(p);
2742 					pp->p_xhighbits = p->p_xhighbits;
2743 					p->p_xhighbits = 0;
2744 					pp->si_status = p->p_xstat;
2745 					pp->si_code = CLD_TRAPPED;
2746 					pp->si_uid = r_uid;
2747 					proc_unlock(pp);
2748 
2749 					psignal(pp, SIGCHLD);
2750 					proc_list_lock();
2751 					wakeup((caddr_t)pp);
2752 					proc_parentdropref(pp, 1);
2753 					proc_list_unlock();
2754 				}
2755 
2756 				assert_wait((caddr_t)&p->sigwait, (THREAD_INTERRUPTIBLE));
2757 				thread_block(THREAD_CONTINUE_NULL);
2758 				proc_lock(p);
2759 				proc_signalstart(p, 1);
2760 			}
2761 
2762 			p->sigwait = FALSE;
2763 			p->sigwait_thread = NULL;
2764 			wakeup((caddr_t)&p->sigwait_thread);
2765 
2766 			if (signum == SIGKILL || ut->uu_siglist & sigmask(SIGKILL)) {
2767 				/*
2768 				 * Deliver a pending sigkill even if it's not the current signal.
2769 				 * Necessary for PT_KILL, which should not be delivered to the
2770 				 * debugger, but we can't differentiate it from any other KILL.
2771 				 */
2772 				signum = SIGKILL;
2773 				goto deliver_sig;
2774 			}
2775 
2776 			/* We may have to quit. */
2777 			if (thread_should_abort(current_thread())) {
2778 				retval = 0;
2779 				goto out;
2780 			}
2781 
2782 			/*
2783 			 * If parent wants us to take the signal,
2784 			 * then it will leave it in p->p_xstat;
2785 			 * otherwise we just look for signals again.
2786 			 */
2787 			signum = p->p_xstat;
2788 			if (signum == 0) {
2789 				continue;
2790 			}
2791 
2792 			/*
2793 			 * Put the new signal into p_siglist.  If the
2794 			 * signal is being masked, look for other signals.
2795 			 */
2796 			mask = sigmask(signum);
2797 			ut->uu_siglist |= mask;
2798 			if (ut->uu_sigmask & mask) {
2799 				continue;
2800 			}
2801 		}
2802 
2803 		/*
2804 		 * Decide whether the signal should be returned.
2805 		 * Return the signal's number, or fall through
2806 		 * to clear it from the pending mask.
2807 		 */
2808 
2809 		switch ((long)SIGACTION(p, signum)) {
2810 		case (long)SIG_DFL:
2811 			/*
2812 			 * If there is a pending stop signal to process
2813 			 * with default action, stop here,
2814 			 * then clear the signal.  However,
2815 			 * if process is member of an orphaned
2816 			 * process group, ignore tty stop signals.
2817 			 */
2818 			if (prop & SA_STOP) {
2819 				struct pgrp * pg;
2820 
2821 				proc_unlock(p);
2822 				pg = proc_pgrp(p, NULL);
2823 				if (p->p_lflag & P_LTRACED ||
2824 				    (pg->pg_jobc == 0 &&
2825 				    prop & SA_TTYSTOP)) {
2826 					proc_lock(p);
2827 					pgrp_rele(pg);
2828 					break; /* ignore signal */
2829 				}
2830 				pgrp_rele(pg);
2831 				if (p->p_stat != SSTOP) {
2832 					proc_lock(p);
2833 					p->p_xstat = signum;
2834 					p->p_stat = SSTOP;
2835 					p->p_lflag &= ~P_LWAITED;
2836 					proc_signalend(p, 1);
2837 					proc_unlock(p);
2838 
2839 					pp = proc_parentholdref(p);
2840 					proc_signalstart(p, 0);
2841 					stop(p, pp);
2842 					if ((pp != PROC_NULL) && ((pp->p_flag & P_NOCLDSTOP) == 0)) {
2843 						my_cred = kauth_cred_proc_ref(p);
2844 						r_uid = kauth_cred_getruid(my_cred);
2845 						kauth_cred_unref(&my_cred);
2846 
2847 						proc_lock(pp);
2848 						pp->si_pid = proc_getpid(p);
2849 						pp->si_status = WEXITSTATUS(p->p_xstat);
2850 						pp->si_code = CLD_STOPPED;
2851 						pp->si_uid = r_uid;
2852 						proc_unlock(pp);
2853 
2854 						psignal(pp, SIGCHLD);
2855 					}
2856 					if (pp != PROC_NULL) {
2857 						proc_parentdropref(pp, 0);
2858 					}
2859 				}
2860 				proc_lock(p);
2861 				break;
2862 			} else if (prop & SA_IGNORE) {
2863 				/*
2864 				 * Except for SIGCONT, shouldn't get here.
2865 				 * Default action is to ignore; drop it.
2866 				 */
2867 				break; /* ignore signal */
2868 			} else {
2869 				goto deliver_sig;
2870 			}
2871 
2872 		case (long)SIG_IGN:
2873 			/*
2874 			 * Masking above should prevent us ever trying
2875 			 * to take action on an ignored signal other
2876 			 * than SIGCONT, unless process is traced.
2877 			 */
2878 			if ((prop & SA_CONT) == 0 &&
2879 			    (p->p_lflag & P_LTRACED) == 0) {
2880 				printf("issignal\n");
2881 			}
2882 			break; /* ignore signal */
2883 
2884 		default:
2885 			/* This signal has an action - deliver it. */
2886 			goto deliver_sig;
2887 		}
2888 
2889 		/* If we dropped through, the signal was ignored - remove it from pending list. */
2890 		ut->uu_siglist &= ~mask;
2891 	} /* for(;;) */
2892 
2893 	/* NOTREACHED */
2894 
2895 deliver_sig:
2896 	ut->uu_siglist &= ~mask;
2897 	retval = signum;
2898 
2899 out:
2900 	proc_signalend(p, 1);
2901 	return retval;
2902 }
2903 
2904 /* called from _sleep */
2905 int
CURSIG(proc_t p)2906 CURSIG(proc_t p)
2907 {
2908 	int signum, mask, prop, sigbits;
2909 	thread_t cur_act;
2910 	struct uthread * ut;
2911 	int retnum = 0;
2912 
2913 
2914 	cur_act = current_thread();
2915 
2916 	ut = get_bsdthread_info(cur_act);
2917 
2918 	if (ut->uu_siglist == 0) {
2919 		return 0;
2920 	}
2921 
2922 	if (((ut->uu_siglist & ~ut->uu_sigmask) == 0) && ((p->p_lflag & P_LTRACED) == 0)) {
2923 		return 0;
2924 	}
2925 
2926 	sigbits = ut->uu_siglist & ~ut->uu_sigmask;
2927 
2928 	for (;;) {
2929 		if (p->p_lflag & P_LPPWAIT) {
2930 			sigbits &= ~stopsigmask;
2931 		}
2932 		if (sigbits == 0) {             /* no signal to send */
2933 			return retnum;
2934 		}
2935 
2936 		signum = ffs((unsigned int)sigbits);
2937 		mask = sigmask(signum);
2938 		prop = sigprop[signum];
2939 		sigbits &= ~mask;               /* take the signal out */
2940 
2941 		/*
2942 		 * We should see pending but ignored signals
2943 		 * only if P_LTRACED was on when they were posted.
2944 		 */
2945 		if (mask & p->p_sigignore && (p->p_lflag & P_LTRACED) == 0) {
2946 			continue;
2947 		}
2948 
2949 		if (p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0) {
2950 			return signum;
2951 		}
2952 
2953 		/*
2954 		 * Decide whether the signal should be returned.
2955 		 * Return the signal's number, or fall through
2956 		 * to clear it from the pending mask.
2957 		 */
2958 
2959 		switch ((long)SIGACTION(p, signum)) {
2960 		case (long)SIG_DFL:
2961 			/*
2962 			 * If there is a pending stop signal to process
2963 			 * with default action, stop here,
2964 			 * then clear the signal.  However,
2965 			 * if process is member of an orphaned
2966 			 * process group, ignore tty stop signals.
2967 			 */
2968 			if (prop & SA_STOP) {
2969 				struct pgrp *pg;
2970 
2971 				pg = proc_pgrp(p, NULL);
2972 
2973 				if (p->p_lflag & P_LTRACED ||
2974 				    (pg->pg_jobc == 0 &&
2975 				    prop & SA_TTYSTOP)) {
2976 					pgrp_rele(pg);
2977 					break;  /* == ignore */
2978 				}
2979 				pgrp_rele(pg);
2980 				retnum = signum;
2981 				break;
2982 			} else if (prop & SA_IGNORE) {
2983 				/*
2984 				 * Except for SIGCONT, shouldn't get here.
2985 				 * Default action is to ignore; drop it.
2986 				 */
2987 				break;          /* == ignore */
2988 			} else {
2989 				return signum;
2990 			}
2991 		/*NOTREACHED*/
2992 
2993 		case (long)SIG_IGN:
2994 			/*
2995 			 * Masking above should prevent us ever trying
2996 			 * to take action on an ignored signal other
2997 			 * than SIGCONT, unless process is traced.
2998 			 */
2999 			if ((prop & SA_CONT) == 0 &&
3000 			    (p->p_lflag & P_LTRACED) == 0) {
3001 				printf("issignal\n");
3002 			}
3003 			break;          /* == ignore */
3004 
3005 		default:
3006 			/*
3007 			 * This signal has an action, let
3008 			 * postsig() process it.
3009 			 */
3010 			return signum;
3011 		}
3012 	}
3013 	/* NOTREACHED */
3014 }
3015 
3016 /*
3017  * Put the argument process into the stopped state and notify the parent
3018  * via wakeup.  Signals are handled elsewhere.  The process must not be
3019  * on the run queue.
3020  */
3021 static void
stop(proc_t p,proc_t parent)3022 stop(proc_t p, proc_t parent)
3023 {
3024 	OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
3025 	if ((parent != PROC_NULL) && (parent->p_stat != SSTOP)) {
3026 		proc_list_lock();
3027 		wakeup((caddr_t)parent);
3028 		proc_list_unlock();
3029 	}
3030 	(void) task_suspend_internal(proc_task(p));
3031 }
3032 
3033 /*
3034  * Take the action for the specified signal
3035  * from the current set of pending signals.
3036  */
3037 void
postsig_locked(int signum)3038 postsig_locked(int signum)
3039 {
3040 	proc_t p = current_proc();
3041 	struct sigacts *ps = &p->p_sigacts;
3042 	user_addr_t catcher;
3043 	uint32_t code;
3044 	int mask, returnmask;
3045 	struct uthread * ut;
3046 	os_reason_t ut_exit_reason = OS_REASON_NULL;
3047 	int coredump_flags = 0;
3048 
3049 #if DIAGNOSTIC
3050 	if (signum == 0) {
3051 		panic("postsig");
3052 	}
3053 	/*
3054 	 *	This must be called on master cpu
3055 	 */
3056 	if (cpu_number() != master_cpu) {
3057 		panic("psig not on master");
3058 	}
3059 #endif
3060 
3061 	/*
3062 	 * Try to grab the signal lock.
3063 	 */
3064 	if (sig_try_locked(p) <= 0) {
3065 		return;
3066 	}
3067 
3068 	proc_signalstart(p, 1);
3069 
3070 	ut = current_uthread();
3071 	mask = sigmask(signum);
3072 	ut->uu_siglist &= ~mask;
3073 	catcher = SIGACTION(p, signum);
3074 	if (catcher == SIG_DFL) {
3075 		/*
3076 		 * Default catcher, where the default is to kill
3077 		 * the process.  (Other cases were ignored above.)
3078 		 */
3079 
3080 		/*
3081 		 * exit_with_reason() below will consume a reference to the thread's exit reason, so we take another
3082 		 * reference so the thread still has one even after we call exit_with_reason(). The thread's reference will
3083 		 * ultimately be destroyed in uthread_cleanup().
3084 		 */
3085 		ut_exit_reason = ut->uu_exit_reason;
3086 		os_reason_ref(ut_exit_reason);
3087 
3088 		p->p_acflag |= AXSIG;
3089 		if (sigprop[signum] & SA_CORE) {
3090 			p->p_sigacts.ps_sig = signum;
3091 			proc_signalend(p, 1);
3092 			proc_unlock(p);
3093 			if (task_is_driver(proc_task(p))) {
3094 				coredump_flags |= COREDUMP_FULLFSYNC;
3095 			}
3096 #if CONFIG_COREDUMP
3097 			if (coredump(p, 0, coredump_flags) == 0) {
3098 				signum |= WCOREFLAG;
3099 			}
3100 #endif
3101 		} else {
3102 			proc_signalend(p, 1);
3103 			proc_unlock(p);
3104 		}
3105 
3106 #if CONFIG_DTRACE
3107 		bzero((caddr_t)&(ut->t_dtrace_siginfo), sizeof(ut->t_dtrace_siginfo));
3108 
3109 		ut->t_dtrace_siginfo.si_signo = signum;
3110 		ut->t_dtrace_siginfo.si_pid = p->si_pid;
3111 		ut->t_dtrace_siginfo.si_uid = p->si_uid;
3112 		ut->t_dtrace_siginfo.si_status = WEXITSTATUS(p->si_status);
3113 
3114 		/* Fire DTrace proc:::fault probe when signal is generated by hardware. */
3115 		switch (signum) {
3116 		case SIGILL: case SIGBUS: case SIGSEGV: case SIGFPE: case SIGTRAP:
3117 			DTRACE_PROC2(fault, int, (int)(ut->uu_code), siginfo_t *, &(ut->t_dtrace_siginfo));
3118 			break;
3119 		default:
3120 			break;
3121 		}
3122 
3123 
3124 		DTRACE_PROC3(signal__handle, int, signum, siginfo_t *, &(ut->t_dtrace_siginfo),
3125 		    void (*)(void), SIG_DFL);
3126 #endif
3127 
3128 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_FRCEXIT) | DBG_FUNC_NONE,
3129 		    proc_getpid(p), W_EXITCODE(0, signum), 3, 0, 0);
3130 
3131 		exit_with_reason(p, W_EXITCODE(0, signum), (int *)NULL, TRUE, TRUE, 0, ut_exit_reason);
3132 
3133 		proc_lock(p);
3134 		return;
3135 	} else {
3136 		/*
3137 		 * If we get here, the signal must be caught.
3138 		 */
3139 #if DIAGNOSTIC
3140 		if (catcher == SIG_IGN || (ut->uu_sigmask & mask)) {
3141 			log(LOG_WARNING,
3142 			    "postsig: processing masked or ignored signal\n");
3143 		}
3144 #endif
3145 
3146 		/*
3147 		 * Set the new mask value and also defer further
3148 		 * occurences of this signal.
3149 		 *
3150 		 * Special case: user has done a sigpause.  Here the
3151 		 * current mask is not of interest, but rather the
3152 		 * mask from before the sigpause is what we want
3153 		 * restored after the signal processing is completed.
3154 		 */
3155 		if (ut->uu_flag & UT_SAS_OLDMASK) {
3156 			returnmask = ut->uu_oldmask;
3157 			ut->uu_flag &= ~UT_SAS_OLDMASK;
3158 			ut->uu_oldmask = 0;
3159 		} else {
3160 			returnmask = ut->uu_sigmask;
3161 		}
3162 		ut->uu_sigmask |= ps->ps_catchmask[signum];
3163 		if ((ps->ps_signodefer & mask) == 0) {
3164 			ut->uu_sigmask |= mask;
3165 		}
3166 		sigset_t siginfo = ps->ps_siginfo;
3167 		if ((signum != SIGILL) && (signum != SIGTRAP) && (ps->ps_sigreset & mask)) {
3168 			if ((signum != SIGCONT) && (sigprop[signum] & SA_IGNORE)) {
3169 				p->p_sigignore |= mask;
3170 			}
3171 			if (SIGACTION(p, signum) != SIG_DFL) {
3172 				proc_set_sigact(p, signum, SIG_DFL);
3173 			}
3174 			ps->ps_siginfo &= ~mask;
3175 			ps->ps_signodefer &= ~mask;
3176 		}
3177 
3178 		if (ps->ps_sig != signum) {
3179 			code = 0;
3180 		} else {
3181 			code = ps->ps_code;
3182 			ps->ps_code = 0;
3183 		}
3184 		OSIncrementAtomicLong(&p->p_stats->p_ru.ru_nsignals);
3185 		sendsig(p, catcher, signum, returnmask, code, siginfo);
3186 	}
3187 	proc_signalend(p, 1);
3188 }
3189 
3190 /*
3191  * Attach a signal knote to the list of knotes for this process.
3192  *
3193  * Signal knotes share the knote list with proc knotes.  This
3194  * could be avoided by using a signal-specific knote list, but
3195  * probably isn't worth the trouble.
3196  */
3197 
3198 static int
filt_sigattach(struct knote * kn,__unused struct kevent_qos_s * kev)3199 filt_sigattach(struct knote *kn, __unused struct kevent_qos_s *kev)
3200 {
3201 	proc_t p = current_proc();  /* can attach only to oneself */
3202 
3203 	proc_klist_lock();
3204 
3205 	kn->kn_proc = p;
3206 	kn->kn_flags |= EV_CLEAR; /* automatically set */
3207 	kn->kn_sdata = 0;         /* incoming data is ignored */
3208 
3209 	KNOTE_ATTACH(&p->p_klist, kn);
3210 
3211 	proc_klist_unlock();
3212 
3213 	/* edge-triggered events can't have fired before we attached */
3214 	return 0;
3215 }
3216 
3217 /*
3218  * remove the knote from the process list, if it hasn't already
3219  * been removed by exit processing.
3220  */
3221 
3222 static void
filt_sigdetach(struct knote * kn)3223 filt_sigdetach(struct knote *kn)
3224 {
3225 	proc_t p;
3226 
3227 	proc_klist_lock();
3228 	p = kn->kn_proc;
3229 	if (p != NULL) {
3230 		kn->kn_proc = NULL;
3231 		KNOTE_DETACH(&p->p_klist, kn);
3232 	}
3233 	proc_klist_unlock();
3234 }
3235 
3236 /*
3237  * Post an event to the signal filter.  Because we share the same list
3238  * as process knotes, we have to filter out and handle only signal events.
3239  *
3240  * We assume that we process fdt_invalidate() before we post the NOTE_EXIT for
3241  * a process during exit.  Therefore, since signal filters can only be
3242  * set up "in-process", we should have already torn down the kqueue
3243  * hosting the EVFILT_SIGNAL knote and should never see NOTE_EXIT.
3244  */
3245 static int
filt_signal(struct knote * kn,long hint)3246 filt_signal(struct knote *kn, long hint)
3247 {
3248 	if (hint & NOTE_SIGNAL) {
3249 		hint &= ~NOTE_SIGNAL;
3250 
3251 		if (kn->kn_id == (unsigned int)hint) {
3252 			kn->kn_hook32++;
3253 		}
3254 	} else if (hint & NOTE_EXIT) {
3255 		panic("filt_signal: detected NOTE_EXIT event");
3256 	}
3257 
3258 	return kn->kn_hook32 != 0;
3259 }
3260 
3261 static int
filt_signaltouch(struct knote * kn,struct kevent_qos_s * kev)3262 filt_signaltouch(struct knote *kn, struct kevent_qos_s *kev)
3263 {
3264 #pragma unused(kev)
3265 
3266 	int res;
3267 
3268 	proc_klist_lock();
3269 
3270 	/*
3271 	 * No data to save - just capture if it is already fired
3272 	 */
3273 	res = (kn->kn_hook32 > 0);
3274 
3275 	proc_klist_unlock();
3276 
3277 	return res;
3278 }
3279 
3280 static int
filt_signalprocess(struct knote * kn,struct kevent_qos_s * kev)3281 filt_signalprocess(struct knote *kn, struct kevent_qos_s *kev)
3282 {
3283 	int res = 0;
3284 
3285 	/*
3286 	 * Snapshot the event data.
3287 	 */
3288 
3289 	proc_klist_lock();
3290 	if (kn->kn_hook32) {
3291 		knote_fill_kevent(kn, kev, kn->kn_hook32);
3292 		kn->kn_hook32 = 0;
3293 		res = 1;
3294 	}
3295 	proc_klist_unlock();
3296 	return res;
3297 }
3298 
3299 void
bsd_ast(thread_t thread)3300 bsd_ast(thread_t thread)
3301 {
3302 	proc_t p = current_proc();
3303 	struct uthread *ut = get_bsdthread_info(thread);
3304 	int     signum;
3305 	static int bsd_init_done = 0;
3306 
3307 	if (p == NULL) {
3308 		return;
3309 	}
3310 
3311 	if (timerisset(&p->p_vtimer_user.it_value)) {
3312 		uint32_t        microsecs;
3313 
3314 		task_vtimer_update(proc_task(p), TASK_VTIMER_USER, &microsecs);
3315 
3316 		if (!itimerdecr(p, &p->p_vtimer_user, microsecs)) {
3317 			if (timerisset(&p->p_vtimer_user.it_value)) {
3318 				task_vtimer_set(proc_task(p), TASK_VTIMER_USER);
3319 			} else {
3320 				task_vtimer_clear(proc_task(p), TASK_VTIMER_USER);
3321 			}
3322 
3323 			psignal_try_thread(p, thread, SIGVTALRM);
3324 		}
3325 	}
3326 
3327 	if (timerisset(&p->p_vtimer_prof.it_value)) {
3328 		uint32_t        microsecs;
3329 
3330 		task_vtimer_update(proc_task(p), TASK_VTIMER_PROF, &microsecs);
3331 
3332 		if (!itimerdecr(p, &p->p_vtimer_prof, microsecs)) {
3333 			if (timerisset(&p->p_vtimer_prof.it_value)) {
3334 				task_vtimer_set(proc_task(p), TASK_VTIMER_PROF);
3335 			} else {
3336 				task_vtimer_clear(proc_task(p), TASK_VTIMER_PROF);
3337 			}
3338 
3339 			psignal_try_thread(p, thread, SIGPROF);
3340 		}
3341 	}
3342 
3343 	if (timerisset(&p->p_rlim_cpu)) {
3344 		struct timeval          tv;
3345 
3346 		task_vtimer_update(proc_task(p), TASK_VTIMER_RLIM, (uint32_t *) &tv.tv_usec);
3347 
3348 		proc_spinlock(p);
3349 		if (p->p_rlim_cpu.tv_sec > 0 || p->p_rlim_cpu.tv_usec > tv.tv_usec) {
3350 			tv.tv_sec = 0;
3351 			timersub(&p->p_rlim_cpu, &tv, &p->p_rlim_cpu);
3352 			proc_spinunlock(p);
3353 		} else {
3354 			timerclear(&p->p_rlim_cpu);
3355 			proc_spinunlock(p);
3356 
3357 			task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
3358 
3359 			psignal_try_thread(p, thread, SIGXCPU);
3360 		}
3361 	}
3362 
3363 #if CONFIG_DTRACE
3364 	if (ut->t_dtrace_sig) {
3365 		uint8_t dt_action_sig = ut->t_dtrace_sig;
3366 		ut->t_dtrace_sig = 0;
3367 		psignal(p, dt_action_sig);
3368 	}
3369 
3370 	if (ut->t_dtrace_stop) {
3371 		ut->t_dtrace_stop = 0;
3372 		proc_lock(p);
3373 		p->p_dtrace_stop = 1;
3374 		proc_unlock(p);
3375 		(void)task_suspend_internal(proc_task(p));
3376 	}
3377 
3378 	if (ut->t_dtrace_resumepid) {
3379 		proc_t resumeproc = proc_find((int)ut->t_dtrace_resumepid);
3380 		ut->t_dtrace_resumepid = 0;
3381 		if (resumeproc != PROC_NULL) {
3382 			proc_lock(resumeproc);
3383 			/* We only act on processes stopped by dtrace */
3384 			if (resumeproc->p_dtrace_stop) {
3385 				resumeproc->p_dtrace_stop = 0;
3386 				proc_unlock(resumeproc);
3387 				task_resume_internal(proc_task(resumeproc));
3388 			} else {
3389 				proc_unlock(resumeproc);
3390 			}
3391 			proc_rele(resumeproc);
3392 		}
3393 	}
3394 
3395 #endif /* CONFIG_DTRACE */
3396 
3397 	proc_lock(p);
3398 	if (CHECK_SIGNALS(p, current_thread(), ut)) {
3399 		while ((signum = issignal_locked(p))) {
3400 			postsig_locked(signum);
3401 		}
3402 	}
3403 	proc_unlock(p);
3404 
3405 	if (!bsd_init_done) {
3406 		bsd_init_done = 1;
3407 		bsdinit_task();
3408 	}
3409 }
3410 
3411 /* ptrace set runnable */
3412 void
pt_setrunnable(proc_t p)3413 pt_setrunnable(proc_t p)
3414 {
3415 	task_t task;
3416 
3417 	task = proc_task(p);
3418 
3419 	if (p->p_lflag & P_LTRACED) {
3420 		proc_lock(p);
3421 		p->p_stat = SRUN;
3422 		proc_unlock(p);
3423 		if (p->sigwait) {
3424 			wakeup((caddr_t)&(p->sigwait));
3425 			if ((p->p_lflag & P_LSIGEXC) == 0) {    // 5878479
3426 				task_release(task);
3427 			}
3428 		}
3429 	}
3430 }
3431 
3432 kern_return_t
do_bsdexception(int exc,int code,int sub)3433 do_bsdexception(
3434 	int exc,
3435 	int code,
3436 	int sub)
3437 {
3438 	mach_exception_data_type_t   codes[EXCEPTION_CODE_MAX];
3439 
3440 	codes[0] = code;
3441 	codes[1] = sub;
3442 	return bsd_exception(exc, codes, 2);
3443 }
3444 
3445 int
proc_pendingsignals(proc_t p,sigset_t mask)3446 proc_pendingsignals(proc_t p, sigset_t mask)
3447 {
3448 	struct uthread * uth;
3449 	sigset_t bits = 0;
3450 
3451 	proc_lock(p);
3452 	/* If the process is in proc exit return no signal info */
3453 	if (p->p_lflag & P_LPEXIT) {
3454 		goto out;
3455 	}
3456 
3457 
3458 	bits = 0;
3459 	TAILQ_FOREACH(uth, &p->p_uthlist, uu_list) {
3460 		bits |= (((uth->uu_siglist & ~uth->uu_sigmask) & ~p->p_sigignore) & mask);
3461 	}
3462 out:
3463 	proc_unlock(p);
3464 	return bits;
3465 }
3466 
3467 int
thread_issignal(proc_t p,thread_t th,sigset_t mask)3468 thread_issignal(proc_t p, thread_t th, sigset_t mask)
3469 {
3470 	struct uthread * uth;
3471 	sigset_t  bits = 0;
3472 
3473 	proc_lock(p);
3474 	uth = (struct uthread *)get_bsdthread_info(th);
3475 	if (uth) {
3476 		bits = (((uth->uu_siglist & ~uth->uu_sigmask) & ~p->p_sigignore) & mask);
3477 	}
3478 	proc_unlock(p);
3479 	return bits;
3480 }
3481 
3482 /*
3483  * Allow external reads of the sigprop array.
3484  */
3485 int
hassigprop(int sig,int prop)3486 hassigprop(int sig, int prop)
3487 {
3488 	return sigprop[sig] & prop;
3489 }
3490 
3491 void
pgsigio(pid_t pgid,int sig)3492 pgsigio(pid_t pgid, int sig)
3493 {
3494 	proc_t p = PROC_NULL;
3495 
3496 	if (pgid < 0) {
3497 		gsignal(-(pgid), sig);
3498 	} else if (pgid > 0 && (p = proc_find(pgid)) != 0) {
3499 		psignal(p, sig);
3500 	}
3501 	if (p != PROC_NULL) {
3502 		proc_rele(p);
3503 	}
3504 }
3505 
3506 void
proc_signalstart(proc_t p,int locked)3507 proc_signalstart(proc_t p, int locked)
3508 {
3509 	if (!locked) {
3510 		proc_lock(p);
3511 	}
3512 
3513 	if (p->p_signalholder == current_thread()) {
3514 		panic("proc_signalstart: thread attempting to signal a process for which it holds the signal lock");
3515 	}
3516 
3517 	p->p_sigwaitcnt++;
3518 	while ((p->p_lflag & P_LINSIGNAL) == P_LINSIGNAL) {
3519 		msleep(&p->p_sigmask, &p->p_mlock, 0, "proc_signstart", NULL);
3520 	}
3521 	p->p_sigwaitcnt--;
3522 
3523 	p->p_lflag |= P_LINSIGNAL;
3524 	p->p_signalholder = current_thread();
3525 	if (!locked) {
3526 		proc_unlock(p);
3527 	}
3528 }
3529 
3530 void
proc_signalend(proc_t p,int locked)3531 proc_signalend(proc_t p, int locked)
3532 {
3533 	if (!locked) {
3534 		proc_lock(p);
3535 	}
3536 	p->p_lflag &= ~P_LINSIGNAL;
3537 
3538 	if (p->p_sigwaitcnt > 0) {
3539 		wakeup(&p->p_sigmask);
3540 	}
3541 
3542 	p->p_signalholder = NULL;
3543 	if (!locked) {
3544 		proc_unlock(p);
3545 	}
3546 }
3547 
3548 void
sig_lock_to_exit(proc_t p)3549 sig_lock_to_exit(proc_t p)
3550 {
3551 	thread_t        self = current_thread();
3552 
3553 	p->exit_thread = self;
3554 	proc_unlock(p);
3555 
3556 	task_hold(proc_task(p));
3557 	task_wait(proc_task(p), FALSE);
3558 
3559 	proc_lock(p);
3560 }
3561 
3562 int
sig_try_locked(proc_t p)3563 sig_try_locked(proc_t p)
3564 {
3565 	thread_t        self = current_thread();
3566 
3567 	while (p->sigwait || p->exit_thread) {
3568 		if (p->exit_thread) {
3569 			return 0;
3570 		}
3571 		msleep((caddr_t)&p->sigwait_thread, &p->p_mlock, PCATCH | PDROP, 0, 0);
3572 		if (thread_should_abort(self)) {
3573 			/*
3574 			 * Terminate request - clean up.
3575 			 */
3576 			proc_lock(p);
3577 			return -1;
3578 		}
3579 		proc_lock(p);
3580 	}
3581 	return 1;
3582 }
3583