+ if (exit_reason == OS_REASON_NULL) {
+ kr = KERN_RESOURCE_SHORTAGE;
+ } else {
+ kr = task_violated_guard(code, reason_code, exit_reason);
+ }
+ os_reason_free(exit_reason);
+ } else {
+ /*
+ * We use SIGABRT (rather than calling exit directly from here) so that
+ * the debugger can catch abort_with_{reason,payload} calls.
+ */
+ psignal_try_thread_with_reason(p, current_thread(), SIGABRT, exit_reason);
+ }
+
+ switch (kr) {
+ case KERN_SUCCESS:
+ return 0;
+ case KERN_NOT_SUPPORTED:
+ return ENOTSUP;
+ case KERN_INVALID_ARGUMENT:
+ return EINVAL;
+ case KERN_RESOURCE_SHORTAGE:
+ default:
+ return EBUSY;
+ }
+}
+
+int
+abort_with_payload(struct proc *cur_proc, struct abort_with_payload_args *args,
+ __unused void *retval)
+{
+ abort_with_payload_internal(cur_proc, args->reason_namespace,
+ args->reason_code, args->payload, args->payload_size,
+ args->reason_string, args->reason_flags, 0);
+
+ return 0;
+}
+
+int
+os_fault_with_payload(struct proc *cur_proc,
+ struct os_fault_with_payload_args *args, __unused int *retval)
+{
+ return abort_with_payload_internal(cur_proc, args->reason_namespace,
+ args->reason_code, args->payload, args->payload_size,
+ args->reason_string, args->reason_flags, OS_REASON_IFLAG_USER_FAULT);
+}
+
+
+/*
+ * exit --
+ * Death of process.
+ */
+__attribute__((noreturn))
+void
+exit(proc_t p, struct exit_args *uap, int *retval)
+{
+ p->p_xhighbits = ((uint32_t)(uap->rval) & 0xFF000000) >> 24;
+ exit1(p, W_EXITCODE((uint32_t)uap->rval, 0), retval);
+
+ thread_exception_return();
+ /* NOTREACHED */
+ while (TRUE) {
+ thread_block(THREAD_CONTINUE_NULL);
+ }
+ /* NOTREACHED */
+}
+
+/*
+ * Exit: deallocate address space and other resources, change proc state
+ * to zombie, and unlink proc from allproc and parent's lists. Save exit
+ * status and rusage for wait(). Check for child processes and orphan them.
+ */
+int
+exit1(proc_t p, int rv, int *retval)
+{
+ return exit1_internal(p, rv, retval, TRUE, TRUE, 0);
+}
+
+int
+exit1_internal(proc_t p, int rv, int *retval, boolean_t thread_can_terminate, boolean_t perf_notify,
+ int jetsam_flags)
+{
+ return exit_with_reason(p, rv, retval, thread_can_terminate, perf_notify, jetsam_flags, OS_REASON_NULL);
+}
+
+/*
+ * NOTE: exit_with_reason drops a reference on the passed exit_reason
+ */
+int
+exit_with_reason(proc_t p, int rv, int *retval, boolean_t thread_can_terminate, boolean_t perf_notify,
+ int jetsam_flags, struct os_reason *exit_reason)
+{
+ thread_t self = current_thread();
+ struct task *task = p->task;
+ struct uthread *ut;
+ int error = 0;
+
+ /*
+ * If a thread in this task has already
+ * called exit(), then halt any others
+ * right here.
+ */
+
+ ut = get_bsdthread_info(self);
+ if ((p == current_proc()) &&
+ (ut->uu_flag & UT_VFORK)) {
+ os_reason_free(exit_reason);
+ if (!thread_can_terminate) {
+ return EINVAL;
+ }
+
+ vfork_exit(p, rv);
+ vfork_return(p, retval, p->p_pid);
+ unix_syscall_return(0);
+ /* NOT REACHED */
+ }
+
+ /*
+ * The parameter list of audit_syscall_exit() was augmented to
+ * take the Darwin syscall number as the first parameter,
+ * which is currently required by mac_audit_postselect().
+ */
+
+ /*
+ * The BSM token contains two components: an exit status as passed
+ * to exit(), and a return value to indicate what sort of exit it
+ * was. The exit status is WEXITSTATUS(rv), but it's not clear
+ * what the return value is.
+ */
+ AUDIT_ARG(exit, WEXITSTATUS(rv), 0);
+ /*
+ * TODO: what to audit here when jetsam calls exit and the uthread,
+ * 'ut' does not belong to the proc, 'p'.
+ */
+ AUDIT_SYSCALL_EXIT(SYS_exit, p, ut, 0); /* Exit is always successfull */
+
+ DTRACE_PROC1(exit, int, CLD_EXITED);
+
+ /* mark process is going to exit and pull out of DBG/disk throttle */
+ /* TODO: This should be done after becoming exit thread */
+ proc_set_task_policy(p->task, TASK_POLICY_ATTRIBUTE,
+ TASK_POLICY_TERMINATED, TASK_POLICY_ENABLE);
+
+ proc_lock(p);
+ error = proc_transstart(p, 1, (jetsam_flags ? 1 : 0));
+ if (error == EDEADLK) {
+ /*
+ * If proc_transstart() returns EDEADLK, then another thread
+ * is either exec'ing or exiting. Return an error and allow
+ * the other thread to continue.
+ */
+ proc_unlock(p);
+ os_reason_free(exit_reason);
+ if (current_proc() == p) {
+ if (p->exit_thread == self) {
+ printf("exit_thread failed to exit, leaving process %s[%d] in unkillable limbo\n",
+ p->p_comm, p->p_pid);
+ }
+
+ if (thread_can_terminate) {
+ thread_exception_return();
+ }
+ }
+
+ return error;
+ }
+
+ while (p->exit_thread != self) {
+ if (sig_try_locked(p) <= 0) {
+ proc_transend(p, 1);
+ os_reason_free(exit_reason);
+
+ if (get_threadtask(self) != task) {
+ proc_unlock(p);
+ return 0;
+ }
+ proc_unlock(p);
+
+ thread_terminate(self);
+ if (!thread_can_terminate) {
+ return 0;
+ }
+
+ thread_exception_return();
+ /* NOTREACHED */
+ }
+ sig_lock_to_exit(p);
+ }
+
+ if (exit_reason != OS_REASON_NULL) {
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_COMMIT) | DBG_FUNC_NONE,
+ p->p_pid, exit_reason->osr_namespace,
+ exit_reason->osr_code, 0, 0);
+ }
+
+ assert(p->p_exit_reason == OS_REASON_NULL);
+ p->p_exit_reason = exit_reason;
+
+ p->p_lflag |= P_LEXIT;
+ p->p_xstat = rv;
+ p->p_lflag |= jetsam_flags;
+
+ proc_transend(p, 1);
+ proc_unlock(p);
+
+ proc_prepareexit(p, rv, perf_notify);
+
+ /* Last thread to terminate will call proc_exit() */
+ task_terminate_internal(task);
+
+ return 0;
+}
+
+#if CONFIG_MEMORYSTATUS
+/*
+ * Remove this process from jetsam bands for freezing or exiting. Note this will block, if the process
+ * is currently being frozen.
+ * The proc_list_lock is held by the caller.
+ * NB: If the process should be ineligible for future freezing or jetsaming the caller should first set
+ * the p_listflag P_LIST_EXITED bit.
+ */
+static void
+proc_memorystatus_remove(proc_t p)
+{
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+ while (memorystatus_remove(p) == EAGAIN) {
+ os_log(OS_LOG_DEFAULT, "memorystatus_remove: Process[%d] tried to exit while being frozen. Blocking exit until freeze completes.", p->p_pid);
+ msleep(&p->p_memstat_state, proc_list_mlock, PWAIT, "proc_memorystatus_remove", NULL);
+ }
+}
+#endif
+
+void
+proc_prepareexit(proc_t p, int rv, boolean_t perf_notify)
+{
+ mach_exception_data_type_t code = 0, subcode = 0;
+
+ struct uthread *ut;
+ thread_t self = current_thread();
+ ut = get_bsdthread_info(self);
+ struct rusage_superset *rup;
+ int kr = 0;
+ int create_corpse = FALSE;
+
+ if (p == initproc) {
+ launchd_crashed_panic(p, rv);
+ /* NOTREACHED */
+ }
+
+ /*
+ * Generate a corefile/crashlog if:
+ * The process doesn't have an exit reason that indicates no crash report should be created
+ * AND any of the following are true:
+ * - The process was terminated due to a fatal signal that generates a core
+ * - The process was killed due to a code signing violation
+ * - The process has an exit reason that indicates we should generate a crash report
+ *
+ * The first condition is necessary because abort_with_reason()/payload() use SIGABRT
+ * (which normally triggers a core) but may indicate that no crash report should be created.
+ */
+ if (!(PROC_HAS_EXITREASON(p) && (PROC_EXITREASON_FLAGS(p) & OS_REASON_FLAG_NO_CRASH_REPORT)) &&
+ (hassigprop(WTERMSIG(rv), SA_CORE) || ((p->p_csflags & CS_KILLED) != 0) ||
+ (PROC_HAS_EXITREASON(p) && (PROC_EXITREASON_FLAGS(p) &
+ OS_REASON_FLAG_GENERATE_CRASH_REPORT)))) {
+ /*
+ * Workaround for processes checking up on PT_DENY_ATTACH:
+ * should be backed out post-Leopard (details in 5431025).
+ */
+ if ((SIGSEGV == WTERMSIG(rv)) &&
+ (p->p_pptr->p_lflag & P_LNOATTACH)) {
+ goto skipcheck;
+ }
+
+ /*
+ * Crash Reporter looks for the signal value, original exception
+ * type, and low 20 bits of the original code in code[0]
+ * (8, 4, and 20 bits respectively). code[1] is unmodified.
+ */
+ code = ((WTERMSIG(rv) & 0xff) << 24) |
+ ((ut->uu_exception & 0x0f) << 20) |
+ ((int)ut->uu_code & 0xfffff);
+ subcode = ut->uu_subcode;
+
+ kr = task_exception_notify(EXC_CRASH, code, subcode);
+
+ /* Nobody handled EXC_CRASH?? remember to make corpse */
+ if (kr != 0) {
+ create_corpse = TRUE;
+ }
+ }
+
+skipcheck:
+ /* Notify the perf server? */
+ if (perf_notify) {
+ (void)sys_perf_notify(self, p->p_pid);
+ }
+
+
+ /* stash the usage into corpse data if making_corpse == true */
+ if (create_corpse == TRUE) {
+ kr = task_mark_corpse(p->task);
+ if (kr != KERN_SUCCESS) {
+ if (kr == KERN_NO_SPACE) {
+ printf("Process[%d] has no vm space for corpse info.\n", p->p_pid);
+ } else if (kr == KERN_NOT_SUPPORTED) {
+ printf("Process[%d] was destined to be corpse. But corpse is disabled by config.\n", p->p_pid);
+ } else {
+ printf("Process[%d] crashed: %s. Too many corpses being created.\n", p->p_pid, p->p_comm);
+ }
+ create_corpse = FALSE;
+ }
+ }
+
+ /*
+ * Before this process becomes a zombie, stash resource usage
+ * stats in the proc for external observers to query
+ * via proc_pid_rusage().
+ *
+ * If the zombie allocation fails, just punt the stats.
+ */
+ rup = zalloc(zombie_zone);
+ gather_rusage_info(p, &rup->ri, RUSAGE_INFO_CURRENT);
+ rup->ri.ri_phys_footprint = 0;
+ rup->ri.ri_proc_exit_abstime = mach_absolute_time();
+ /*
+ * Make the rusage_info visible to external observers
+ * only after it has been completely filled in.
+ */
+ p->p_ru = rup;
+
+ if (create_corpse) {
+ int est_knotes = 0, num_knotes = 0;
+ uint64_t *buffer = NULL;
+ uint32_t buf_size = 0;
+
+ /* Get all the udata pointers from kqueue */
+ est_knotes = kevent_proc_copy_uptrs(p, NULL, 0);
+ if (est_knotes > 0) {
+ buf_size = (uint32_t)((est_knotes + 32) * sizeof(uint64_t));
+ buffer = kheap_alloc(KHEAP_TEMP, buf_size, Z_WAITOK);
+ num_knotes = kevent_proc_copy_uptrs(p, buffer, buf_size);
+ if (num_knotes > est_knotes + 32) {
+ num_knotes = est_knotes + 32;
+ }
+ }
+
+ /* Update the code, subcode based on exit reason */
+ proc_update_corpse_exception_codes(p, &code, &subcode);
+ populate_corpse_crashinfo(p, p->task, rup,
+ code, subcode, buffer, num_knotes, NULL);
+ if (buffer != NULL) {
+ kheap_free(KHEAP_TEMP, buffer, buf_size);
+ }
+ }
+ /*
+ * Remove proc from allproc queue and from pidhash chain.
+ * Need to do this before we do anything that can block.
+ * Not doing causes things like mount() find this on allproc
+ * in partially cleaned state.
+ */
+
+ proc_list_lock();
+
+#if CONFIG_MEMORYSTATUS
+ proc_memorystatus_remove(p);
+#endif
+
+ LIST_REMOVE(p, p_list);
+ LIST_INSERT_HEAD(&zombproc, p, p_list); /* Place onto zombproc. */
+ /* will not be visible via proc_find */
+ p->p_listflag |= P_LIST_EXITED;
+
+ proc_list_unlock();
+
+#ifdef PGINPROF
+ vmsizmon();
+#endif
+ /*
+ * If parent is waiting for us to exit or exec,
+ * P_LPPWAIT is set; we will wakeup the parent below.
+ */
+ proc_lock(p);
+ p->p_lflag &= ~(P_LTRACED | P_LPPWAIT);
+ p->p_sigignore = ~(sigcantmask);
+ ut->uu_siglist = 0;
+ proc_unlock(p);
+}
+
+void
+proc_exit(proc_t p)
+{
+ proc_t q;
+ proc_t pp;
+ struct task *task = p->task;
+ vnode_t tvp = NULLVP;
+ struct pgrp * pg;
+ struct session *sessp;
+ struct uthread * uth;
+ pid_t pid;
+ int exitval;
+ int knote_hint;
+
+ uth = current_uthread();
+
+ proc_lock(p);
+ proc_transstart(p, 1, 0);
+ if (!(p->p_lflag & P_LEXIT)) {
+ /*
+ * This can happen if a thread_terminate() occurs
+ * in a single-threaded process.
+ */
+ p->p_lflag |= P_LEXIT;
+ proc_transend(p, 1);
+ proc_unlock(p);
+ proc_prepareexit(p, 0, TRUE);
+ (void) task_terminate_internal(task);
+ proc_lock(p);
+ } else {
+ proc_transend(p, 1);
+ }
+
+ p->p_lflag |= P_LPEXIT;
+
+ /*
+ * Other kernel threads may be in the middle of signalling this process.
+ * Wait for those threads to wrap it up before making the process
+ * disappear on them.
+ */
+ if ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 0)) {
+ p->p_sigwaitcnt++;
+ while ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 1)) {
+ msleep(&p->p_sigmask, &p->p_mlock, PWAIT, "proc_sigdrain", NULL);
+ }
+ p->p_sigwaitcnt--;
+ }
+
+ proc_unlock(p);
+ pid = p->p_pid;
+ exitval = p->p_xstat;
+ KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
+ BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_START,
+ pid, exitval, 0, 0, 0);
+
+#if CONFIG_DTRACE
+ dtrace_proc_exit(p);
+#endif
+
+ /*
+ * need to cancel async IO requests that can be cancelled and wait for those
+ * already active. MAY BLOCK!
+ */
+
+ proc_refdrain(p);
+
+ /* if any pending cpu limits action, clear it */
+ task_clear_cpuusage(p->task, TRUE);
+
+ workq_mark_exiting(p);
+
+ _aio_exit( p );
+
+ /*
+ * Close open files and release open-file table.
+ * This may block!
+ */
+ fdfree(p);
+
+ /*
+ * Once all the knotes, kqueues & workloops are destroyed, get rid of the
+ * workqueue.
+ */
+ workq_exit(p);
+
+ if (uth->uu_lowpri_window) {
+ /*
+ * task is marked as a low priority I/O type
+ * and the I/O we issued while in flushing files on close
+ * collided with normal I/O operations...
+ * no need to throttle this thread since its going away
+ * but we do need to update our bookeeping w/r to throttled threads
+ */
+ throttle_lowpri_io(0);
+ }
+
+ if (p->p_lflag & P_LNSPACE_RESOLVER) {
+ /*
+ * The namespace resolver is exiting; there may be
+ * outstanding materialization requests to clean up.
+ */
+ nspace_resolver_exited(p);
+ }
+
+#if SYSV_SHM
+ /* Close ref SYSV Shared memory*/
+ if (p->vm_shm) {
+ shmexit(p);
+ }
+#endif
+#if SYSV_SEM
+ /* Release SYSV semaphores */
+ semexit(p);
+#endif
+
+#if PSYNCH
+ pth_proc_hashdelete(p);
+#endif /* PSYNCH */
+
+ sessp = proc_session(p);
+ if (SESS_LEADER(p, sessp)) {
+ if (sessp->s_ttyvp != NULLVP) {
+ struct vnode *ttyvp;
+ int ttyvid;
+ int cttyflag = 0;
+ struct vfs_context context;
+ struct tty *tp;
+
+ /*
+ * Controlling process.
+ * Signal foreground pgrp,
+ * drain controlling terminal
+ * and revoke access to controlling terminal.
+ */
+ session_lock(sessp);
+ tp = SESSION_TP(sessp);
+ if ((tp != TTY_NULL) && (tp->t_session == sessp)) {
+ session_unlock(sessp);
+
+ tty_pgsignal(tp, SIGHUP, 1);
+
+ session_lock(sessp);
+ tp = SESSION_TP(sessp);
+ }
+ cttyflag = sessp->s_flags & S_CTTYREF;
+ sessp->s_flags &= ~S_CTTYREF;
+ ttyvp = sessp->s_ttyvp;
+ ttyvid = sessp->s_ttyvid;
+ sessp->s_ttyvp = NULLVP;
+ sessp->s_ttyvid = 0;
+ sessp->s_ttyp = TTY_NULL;
+ sessp->s_ttypgrpid = NO_PID;
+ session_unlock(sessp);
+
+ if ((ttyvp != NULLVP) && (vnode_getwithvid(ttyvp, ttyvid) == 0)) {
+ if (tp != TTY_NULL) {
+ tty_lock(tp);
+ (void) ttywait(tp);
+ tty_unlock(tp);
+ }
+
+ context.vc_thread = NULL;
+ context.vc_ucred = kauth_cred_proc_ref(p);
+ VNOP_REVOKE(ttyvp, REVOKEALL, &context);
+ if (cttyflag) {
+ /*
+ * Release the extra usecount taken in cttyopen.
+ * usecount should be released after VNOP_REVOKE is called.
+ * This usecount was taken to ensure that
+ * the VNOP_REVOKE results in a close to
+ * the tty since cttyclose is a no-op.
+ */
+ vnode_rele(ttyvp);
+ }
+ vnode_put(ttyvp);
+ kauth_cred_unref(&context.vc_ucred);
+ ttyvp = NULLVP;
+ }
+ if (tp) {
+ ttyfree(tp);
+ }
+ }
+ session_lock(sessp);
+ sessp->s_leader = NULL;
+ session_unlock(sessp);
+ }
+ session_rele(sessp);
+
+ pg = proc_pgrp(p);
+ fixjobc(p, pg, 0);
+ pg_rele(pg);
+
+ /*
+ * Change RLIMIT_FSIZE for accounting/debugging. proc_limitsetcur_internal() will COW the current plimit
+ * before making changes if the current plimit is shared. The COW'ed plimit will be freed
+ * below by calling proc_limitdrop().
+ */
+ proc_limitsetcur_internal(p, RLIMIT_FSIZE, RLIM_INFINITY);
+
+ (void)acct_process(p);
+
+ proc_list_lock();
+
+ if ((p->p_listflag & P_LIST_EXITCOUNT) == P_LIST_EXITCOUNT) {
+ p->p_listflag &= ~P_LIST_EXITCOUNT;
+ proc_shutdown_exitcount--;
+ if (proc_shutdown_exitcount == 0) {
+ wakeup(&proc_shutdown_exitcount);
+ }
+ }
+
+ /* wait till parentrefs are dropped and grant no more */
+ proc_childdrainstart(p);
+ while ((q = p->p_children.lh_first) != NULL) {
+ int reparentedtoinit = (q->p_listflag & P_LIST_DEADPARENT) ? 1 : 0;
+ if (q->p_stat == SZOMB) {
+ if (p != q->p_pptr) {
+ panic("parent child linkage broken");
+ }
+ /* check for sysctl zomb lookup */
+ while ((q->p_listflag & P_LIST_WAITING) == P_LIST_WAITING) {
+ msleep(&q->p_stat, proc_list_mlock, PWAIT, "waitcoll", 0);
+ }
+ q->p_listflag |= P_LIST_WAITING;
+ /*
+ * This is a named reference and it is not granted
+ * if the reap is already in progress. So we get
+ * the reference here exclusively and their can be
+ * no waiters. So there is no need for a wakeup
+ * after we are done. Also the reap frees the structure
+ * and the proc struct cannot be used for wakeups as well.
+ * It is safe to use q here as this is system reap
+ */
+ (void)reap_child_locked(p, q, 1, reparentedtoinit, 1, 0);
+ } else {
+ /*
+ * Traced processes are killed
+ * since their existence means someone is messing up.
+ */
+ if (q->p_lflag & P_LTRACED) {
+ struct proc *opp;
+
+ /*
+ * Take a reference on the child process to
+ * ensure it doesn't exit and disappear between
+ * the time we drop the list_lock and attempt
+ * to acquire its proc_lock.
+ */
+ if (proc_ref_locked(q) != q) {
+ continue;
+ }
+
+ proc_list_unlock();
+
+ opp = proc_find(q->p_oppid);
+ if (opp != PROC_NULL) {
+ proc_list_lock();
+ q->p_oppid = 0;
+ proc_list_unlock();
+ proc_reparentlocked(q, opp, 0, 0);
+ proc_rele(opp);
+ } else {
+ /* original parent exited while traced */
+ proc_list_lock();
+ q->p_listflag |= P_LIST_DEADPARENT;
+ q->p_oppid = 0;
+ proc_list_unlock();
+ proc_reparentlocked(q, initproc, 0, 0);
+ }
+
+ proc_lock(q);
+ q->p_lflag &= ~P_LTRACED;
+
+ if (q->sigwait_thread) {
+ thread_t thread = q->sigwait_thread;
+
+ proc_unlock(q);
+ /*
+ * The sigwait_thread could be stopped at a
+ * breakpoint. Wake it up to kill.
+ * Need to do this as it could be a thread which is not
+ * the first thread in the task. So any attempts to kill
+ * the process would result into a deadlock on q->sigwait.
+ */
+ thread_resume(thread);
+ clear_wait(thread, THREAD_INTERRUPTED);
+ threadsignal(thread, SIGKILL, 0, TRUE);
+ } else {
+ proc_unlock(q);
+ }
+
+ psignal(q, SIGKILL);
+ proc_list_lock();
+ proc_rele_locked(q);
+ } else {
+ q->p_listflag |= P_LIST_DEADPARENT;
+ proc_reparentlocked(q, initproc, 0, 1);
+ }
+ }
+ }
+
+ proc_childdrainend(p);
+ proc_list_unlock();
+
+#if CONFIG_MACF
+ /*
+ * Notify MAC policies that proc is dead.
+ * This should be replaced with proper label management
+ * (rdar://problem/32126399).
+ */
+ mac_proc_notify_exit(p);
+#endif
+
+ /*
+ * Release reference to text vnode
+ */
+ tvp = p->p_textvp;
+ p->p_textvp = NULL;
+ if (tvp != NULLVP) {
+ vnode_rele(tvp);
+ }
+
+ /*
+ * Save exit status and final rusage info, adding in child rusage
+ * info and self times. If we were unable to allocate a zombie
+ * structure, this information is lost.
+ */
+ if (p->p_ru != NULL) {
+ calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime, NULL);
+ p->p_ru->ru = p->p_stats->p_ru;
+
+ ruadd(&(p->p_ru->ru), &p->p_stats->p_cru);
+ }
+
+ /*
+ * Free up profiling buffers.
+ */
+ {
+ struct uprof *p0 = &p->p_stats->p_prof, *p1, *pn;
+
+ p1 = p0->pr_next;
+ p0->pr_next = NULL;
+ p0->pr_scale = 0;
+
+ for (; p1 != NULL; p1 = pn) {
+ pn = p1->pr_next;
+ kfree(p1, sizeof *p1);
+ }
+ }
+
+ proc_free_realitimer(p);
+
+ /*
+ * Other substructures are freed from wait().
+ */
+ zfree(proc_stats_zone, p->p_stats);
+ p->p_stats = NULL;
+
+ zfree(proc_sigacts_zone, p->p_sigacts);
+ p->p_sigacts = NULL;
+
+ proc_limitdrop(p);
+
+ /*
+ * Finish up by terminating the task
+ * and halt this thread (only if a
+ * member of the task exiting).
+ */
+ p->task = TASK_NULL;
+ set_bsdtask_info(task, NULL);
+
+ knote_hint = NOTE_EXIT | (p->p_xstat & 0xffff);
+ proc_knote(p, knote_hint);
+
+ /* mark the thread as the one that is doing proc_exit
+ * no need to hold proc lock in uthread_free
+ */
+ uth->uu_flag |= UT_PROCEXIT;
+ /*
+ * Notify parent that we're gone.
+ */
+ pp = proc_parent(p);
+ if (pp->p_flag & P_NOCLDWAIT) {
+ if (p->p_ru != NULL) {
+ proc_lock(pp);
+#if 3839178
+ /*
+ * If the parent is ignoring SIGCHLD, then POSIX requires
+ * us to not add the resource usage to the parent process -
+ * we are only going to hand it off to init to get reaped.
+ * We should contest the standard in this case on the basis
+ * of RLIMIT_CPU.
+ */
+#else /* !3839178 */
+ /*
+ * Add child resource usage to parent before giving
+ * zombie to init. If we were unable to allocate a
+ * zombie structure, this information is lost.
+ */
+ ruadd(&pp->p_stats->p_cru, &p->p_ru->ru);
+#endif /* !3839178 */
+ update_rusage_info_child(&pp->p_stats->ri_child, &p->p_ru->ri);
+ proc_unlock(pp);
+ }
+
+ /* kernel can reap this one, no need to move it to launchd */
+ proc_list_lock();
+ p->p_listflag |= P_LIST_DEADPARENT;
+ proc_list_unlock();
+ }
+ if ((p->p_listflag & P_LIST_DEADPARENT) == 0 || p->p_oppid) {
+ if (pp != initproc) {
+ proc_lock(pp);
+ pp->si_pid = p->p_pid;
+ pp->p_xhighbits = p->p_xhighbits;
+ p->p_xhighbits = 0;
+ pp->si_status = p->p_xstat;
+ pp->si_code = CLD_EXITED;
+ /*
+ * p_ucred usage is safe as it is an exiting process
+ * and reference is dropped in reap
+ */
+ pp->si_uid = kauth_cred_getruid(p->p_ucred);
+ proc_unlock(pp);
+ }
+ /* mark as a zombie */
+ /* No need to take proc lock as all refs are drained and
+ * no one except parent (reaping ) can look at this.
+ * The write is to an int and is coherent. Also parent is
+ * keyed off of list lock for reaping
+ */
+ DTRACE_PROC2(exited, proc_t, p, int, exitval);
+ KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
+ BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_END,
+ pid, exitval, 0, 0, 0);
+ p->p_stat = SZOMB;
+ /*
+ * The current process can be reaped so, no one
+ * can depend on this
+ */
+
+ psignal(pp, SIGCHLD);
+
+ /* and now wakeup the parent */
+ proc_list_lock();
+ wakeup((caddr_t)pp);
+ proc_list_unlock();
+ } else {
+ /* should be fine as parent proc would be initproc */
+ /* mark as a zombie */
+ /* No need to take proc lock as all refs are drained and
+ * no one except parent (reaping ) can look at this.
+ * The write is to an int and is coherent. Also parent is
+ * keyed off of list lock for reaping
+ */
+ DTRACE_PROC2(exited, proc_t, p, int, exitval);
+ proc_list_lock();
+ KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
+ BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_END,
+ pid, exitval, 0, 0, 0);
+ /* check for sysctl zomb lookup */
+ while ((p->p_listflag & P_LIST_WAITING) == P_LIST_WAITING) {
+ msleep(&p->p_stat, proc_list_mlock, PWAIT, "waitcoll", 0);
+ }
+ /* safe to use p as this is a system reap */
+ p->p_stat = SZOMB;
+ p->p_listflag |= P_LIST_WAITING;
+
+ /*
+ * This is a named reference and it is not granted
+ * if the reap is already in progress. So we get
+ * the reference here exclusively and their can be
+ * no waiters. So there is no need for a wakeup
+ * after we are done. AlsO the reap frees the structure
+ * and the proc struct cannot be used for wakeups as well.
+ * It is safe to use p here as this is system reap
+ */
+ (void)reap_child_locked(pp, p, 1, 0, 1, 1);
+ /* list lock dropped by reap_child_locked */
+ }
+ if (uth->uu_lowpri_window) {
+ /*
+ * task is marked as a low priority I/O type and we've
+ * somehow picked up another throttle during exit processing...
+ * no need to throttle this thread since its going away
+ * but we do need to update our bookeeping w/r to throttled threads
+ */
+ throttle_lowpri_io(0);
+ }
+
+ proc_rele(pp);
+}
+
+
+/*
+ * reap_child_locked
+ *
+ * Description: Given a process from which all status information needed
+ * has already been extracted, if the process is a ptrace
+ * attach process, detach it and give it back to its real
+ * parent, else recover all resources remaining associated
+ * with it.
+ *
+ * Parameters: proc_t parent Parent of process being reaped
+ * proc_t child Process to reap
+ *
+ * Returns: 0 Process was not reaped because it
+ * came from an attach
+ * 1 Process was reaped
+ */
+static int
+reap_child_locked(proc_t parent, proc_t child, int deadparent, int reparentedtoinit, int locked, int droplock)
+{
+ proc_t trace_parent = PROC_NULL; /* Traced parent process, if tracing */
+
+ if (locked == 1) {
+ proc_list_unlock();
+ }
+
+ /*
+ * If we got the child via a ptrace 'attach',
+ * we need to give it back to the old parent.
+ *
+ * Exception: someone who has been reparented to launchd before being
+ * ptraced can simply be reaped, refer to radar 5677288
+ * p_oppid -> ptraced
+ * trace_parent == initproc -> away from launchd
+ * reparentedtoinit -> came to launchd by reparenting
+ */
+ if (child->p_oppid) {
+ int knote_hint;
+ pid_t oppid;
+
+ proc_lock(child);
+ oppid = child->p_oppid;
+ child->p_oppid = 0;
+ knote_hint = NOTE_EXIT | (child->p_xstat & 0xffff);
+ proc_unlock(child);
+
+ if ((trace_parent = proc_find(oppid))
+ && !((trace_parent == initproc) && reparentedtoinit)) {
+ if (trace_parent != initproc) {
+ /*
+ * proc internal fileds and p_ucred usage safe
+ * here as child is dead and is not reaped or
+ * reparented yet
+ */
+ proc_lock(trace_parent);
+ trace_parent->si_pid = child->p_pid;
+ trace_parent->si_status = child->p_xstat;
+ trace_parent->si_code = CLD_CONTINUED;
+ trace_parent->si_uid = kauth_cred_getruid(child->p_ucred);
+ proc_unlock(trace_parent);
+ }
+ proc_reparentlocked(child, trace_parent, 1, 0);
+
+ /* resend knote to original parent (and others) after reparenting */
+ proc_knote(child, knote_hint);
+
+ psignal(trace_parent, SIGCHLD);
+ proc_list_lock();
+ wakeup((caddr_t)trace_parent);
+ child->p_listflag &= ~P_LIST_WAITING;
+ wakeup(&child->p_stat);
+ proc_list_unlock();
+ proc_rele(trace_parent);
+ if ((locked == 1) && (droplock == 0)) {
+ proc_list_lock();
+ }
+ return 0;
+ }
+
+ /*
+ * If we can't reparent (e.g. the original parent exited while child was being debugged, or
+ * original parent is the same as the debugger currently exiting), we still need to satisfy
+ * the knote lifecycle for other observers on the system. While the debugger was attached,
+ * the NOTE_EXIT would not have been broadcast during initial child termination.
+ */
+ proc_knote(child, knote_hint);
+
+ if (trace_parent != PROC_NULL) {
+ proc_rele(trace_parent);
+ }
+ }
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ proc_knote(child, NOTE_REAP);
+#pragma clang diagnostic pop
+
+ proc_knote_drain(child);
+
+ child->p_xstat = 0;
+ if (child->p_ru) {
+ proc_lock(parent);
+#if 3839178
+ /*
+ * If the parent is ignoring SIGCHLD, then POSIX requires
+ * us to not add the resource usage to the parent process -
+ * we are only going to hand it off to init to get reaped.
+ * We should contest the standard in this case on the basis
+ * of RLIMIT_CPU.
+ */
+ if (!(parent->p_flag & P_NOCLDWAIT))
+#endif /* 3839178 */
+ ruadd(&parent->p_stats->p_cru, &child->p_ru->ru);
+ update_rusage_info_child(&parent->p_stats->ri_child, &child->p_ru->ri);
+ proc_unlock(parent);
+ zfree(zombie_zone, child->p_ru);
+ child->p_ru = NULL;
+ } else {
+ printf("Warning : lost p_ru for %s\n", child->p_comm);
+ }
+
+ AUDIT_SESSION_PROCEXIT(child);
+
+ /*
+ * Decrement the count of procs running with this uid.
+ * p_ucred usage is safe here as it is an exited process.
+ * and refernce is dropped after these calls down below
+ * (locking protection is provided by list lock held in chgproccnt)
+ */
+#if CONFIG_PERSONAS
+ /*
+ * persona_proc_drop calls chgproccnt(-1) on the persona uid,
+ * and (+1) on the child->p_ucred uid
+ */
+ persona_proc_drop(child);
+#endif
+ (void)chgproccnt(kauth_cred_getruid(child->p_ucred), -1);
+
+ os_reason_free(child->p_exit_reason);
+
+ /*
+ * Finally finished with old proc entry.
+ * Unlink it from its process group and free it.
+ */
+ leavepgrp(child);
+
+ proc_list_lock();
+ LIST_REMOVE(child, p_list); /* off zombproc */
+ parent->p_childrencnt--;
+ LIST_REMOVE(child, p_sibling);
+ /* If there are no more children wakeup parent */
+ if ((deadparent != 0) && (LIST_EMPTY(&parent->p_children))) {
+ wakeup((caddr_t)parent); /* with list lock held */
+ }
+ child->p_listflag &= ~P_LIST_WAITING;
+ wakeup(&child->p_stat);
+
+ /* Take it out of process hash */
+ LIST_REMOVE(child, p_hash);
+ child->p_listflag &= ~P_LIST_INHASH;
+ proc_checkdeadrefs(child);
+ nprocs--;
+
+ if (deadparent) {
+ /*
+ * If a child zombie is being reaped because its parent
+ * is exiting, make sure we update the list flag
+ */
+ child->p_listflag |= P_LIST_DEADPARENT;
+ }
+
+ proc_list_unlock();
+
+ /*
+ * Free up credentials.
+ */
+ if (IS_VALID_CRED(child->p_ucred)) {
+ kauth_cred_t tmp_ucred = child->p_ucred;
+ kauth_cred_unref(&tmp_ucred);
+ child->p_ucred = NOCRED;
+ }
+
+ lck_mtx_destroy(&child->p_mlock, proc_mlock_grp);
+ lck_mtx_destroy(&child->p_ucred_mlock, proc_ucred_mlock_grp);
+ lck_mtx_destroy(&child->p_fdmlock, proc_fdmlock_grp);
+#if CONFIG_DTRACE
+ lck_mtx_destroy(&child->p_dtrace_sprlock, proc_lck_grp);
+#endif
+ lck_spin_destroy(&child->p_slock, proc_slock_grp);
+
+ zfree(proc_zone, child);
+ if ((locked == 1) && (droplock == 0)) {
+ proc_list_lock();
+ }
+
+ return 1;
+}
+
+
+int
+wait1continue(int result)
+{
+ proc_t p;
+ thread_t thread;
+ uthread_t uth;
+ struct _wait4_data *wait4_data;
+ struct wait4_nocancel_args *uap;
+ int *retval;
+
+ if (result) {
+ return result;
+ }
+
+ p = current_proc();
+ thread = current_thread();
+ uth = (struct uthread *)get_bsdthread_info(thread);
+
+ wait4_data = &uth->uu_save.uus_wait4_data;
+ uap = wait4_data->args;
+ retval = wait4_data->retval;
+ return wait4_nocancel(p, uap, retval);
+}
+
+int
+wait4(proc_t q, struct wait4_args *uap, int32_t *retval)
+{
+ __pthread_testcancel(1);
+ return wait4_nocancel(q, (struct wait4_nocancel_args *)uap, retval);
+}
+
+int
+wait4_nocancel(proc_t q, struct wait4_nocancel_args *uap, int32_t *retval)
+{
+ int nfound;
+ int sibling_count;
+ proc_t p;
+ int status, error;
+ uthread_t uth;
+ struct _wait4_data *wait4_data;
+
+ AUDIT_ARG(pid, uap->pid);
+
+ if (uap->pid == 0) {
+ uap->pid = -q->p_pgrpid;
+ }
+
+loop:
+ proc_list_lock();
+loop1:
+ nfound = 0;
+ sibling_count = 0;
+
+ PCHILDREN_FOREACH(q, p) {
+ if (p->p_sibling.le_next != 0) {
+ sibling_count++;
+ }
+ if (uap->pid != WAIT_ANY &&
+ p->p_pid != uap->pid &&
+ p->p_pgrpid != -(uap->pid)) {
+ continue;
+ }
+
+ nfound++;
+
+ /* XXX This is racy because we don't get the lock!!!! */
+
+ if (p->p_listflag & P_LIST_WAITING) {
+ /* we're not using a continuation here but we still need to stash
+ * the args for stackshot. */
+ uth = current_uthread();
+ wait4_data = &uth->uu_save.uus_wait4_data;
+ wait4_data->args = uap;
+ thread_set_pending_block_hint(current_thread(), kThreadWaitOnProcess);
+
+ (void)msleep(&p->p_stat, proc_list_mlock, PWAIT, "waitcoll", 0);
+ goto loop1;
+ }
+ p->p_listflag |= P_LIST_WAITING; /* only allow single thread to wait() */
+
+
+ if (p->p_stat == SZOMB) {
+ int reparentedtoinit = (p->p_listflag & P_LIST_DEADPARENT) ? 1 : 0;
+
+ proc_list_unlock();
+#if CONFIG_MACF
+ if ((error = mac_proc_check_wait(q, p)) != 0) {
+ goto out;
+ }
+#endif
+ retval[0] = p->p_pid;
+ if (uap->status) {
+ /* Legacy apps expect only 8 bits of status */
+ status = 0xffff & p->p_xstat; /* convert to int */
+ error = copyout((caddr_t)&status,
+ uap->status,
+ sizeof(status));
+ if (error) {
+ goto out;
+ }
+ }
+ if (uap->rusage) {
+ if (p->p_ru == NULL) {
+ error = ENOMEM;
+ } else {
+ if (IS_64BIT_PROCESS(q)) {
+ struct user64_rusage my_rusage = {};
+ munge_user64_rusage(&p->p_ru->ru, &my_rusage);
+ error = copyout((caddr_t)&my_rusage,
+ uap->rusage,
+ sizeof(my_rusage));
+ } else {
+ struct user32_rusage my_rusage = {};
+ munge_user32_rusage(&p->p_ru->ru, &my_rusage);
+ error = copyout((caddr_t)&my_rusage,
+ uap->rusage,
+ sizeof(my_rusage));
+ }
+ }
+ /* information unavailable? */
+ if (error) {
+ goto out;
+ }
+ }
+
+ /* Conformance change for 6577252.
+ * When SIGCHLD is blocked and wait() returns because the status
+ * of a child process is available and there are no other
+ * children processes, then any pending SIGCHLD signal is cleared.
+ */
+ if (sibling_count == 0) {
+ int mask = sigmask(SIGCHLD);
+ uth = current_uthread();
+
+ if ((uth->uu_sigmask & mask) != 0) {
+ /* we are blocking SIGCHLD signals. clear any pending SIGCHLD.
+ * This locking looks funny but it is protecting access to the
+ * thread via p_uthlist.
+ */
+ proc_lock(q);
+ uth->uu_siglist &= ~mask; /* clear pending signal */
+ proc_unlock(q);
+ }
+ }
+
+ /* Clean up */
+ (void)reap_child_locked(q, p, 0, reparentedtoinit, 0, 0);
+
+ return 0;
+ }
+ if (p->p_stat == SSTOP && (p->p_lflag & P_LWAITED) == 0 &&
+ (p->p_lflag & P_LTRACED || uap->options & WUNTRACED)) {
+ proc_list_unlock();
+#if CONFIG_MACF
+ if ((error = mac_proc_check_wait(q, p)) != 0) {
+ goto out;
+ }
+#endif
+ proc_lock(p);
+ p->p_lflag |= P_LWAITED;
+ proc_unlock(p);
+ retval[0] = p->p_pid;
+ if (uap->status) {
+ status = W_STOPCODE(p->p_xstat);
+ error = copyout((caddr_t)&status,
+ uap->status,
+ sizeof(status));
+ } else {
+ error = 0;
+ }
+ goto out;
+ }
+ /*
+ * If we are waiting for continued processses, and this
+ * process was continued
+ */
+ if ((uap->options & WCONTINUED) &&
+ (p->p_flag & P_CONTINUED)) {
+ proc_list_unlock();
+#if CONFIG_MACF
+ if ((error = mac_proc_check_wait(q, p)) != 0) {
+ goto out;
+ }
+#endif