xref: /freebsd/sys/kern/sys_procdesc.c (revision 2bacbbecb165dd761ea7ec2fc35630db61508cdf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009, 2016 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * This software was developed at the University of Cambridge Computer
8  * Laboratory with support from a grant from Google, Inc.
9  *
10  * Portions of this software were developed by BAE Systems, the University of
11  * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
12  * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
13  * Computing (TC) research program.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 /*-
38  * FreeBSD process descriptor facility.
39  *
40  * Some processes are represented by a file descriptor, which will be used in
41  * preference to signaling and pids for the purposes of process management,
42  * and is, in effect, a form of capability.  When a process descriptor is
43  * used with a process, it ceases to be visible to certain traditional UNIX
44  * process facilities, such as waitpid(2).
45  *
46  * Some semantics:
47  *
48  * - At most one process descriptor will exist for any process, although
49  *   references to that descriptor may be held from many processes (or even
50  *   be in flight between processes over a local domain socket).
51  * - Last close on the process descriptor will terminate the process using
52  *   SIGKILL and reparent it to init so that there's a process to reap it
53  *   when it's done exiting.
54  * - If the process exits before the descriptor is closed, it will not
55  *   generate SIGCHLD on termination, or be picked up by waitpid().
56  * - The pdkill(2) system call may be used to deliver a signal to the process
57  *   using its process descriptor.
58  *
59  * Open questions:
60  *
61  * - Will we want to add a pidtoprocdesc(2) system call to allow process
62  *   descriptors to be created for processes without pdfork(2)?
63  */
64 
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/event.h>
68 #include <sys/fcntl.h>
69 #include <sys/file.h>
70 #include <sys/filedesc.h>
71 #include <sys/imgact.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/mutex.h>
75 #include <sys/poll.h>
76 #include <sys/proc.h>
77 #include <sys/procdesc.h>
78 #include <sys/resourcevar.h>
79 #include <sys/stat.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysproto.h>
82 #include <sys/sysctl.h>
83 #include <sys/systm.h>
84 #include <sys/ucred.h>
85 #include <sys/user.h>
86 
87 #include <security/audit/audit.h>
88 
89 #include <vm/uma.h>
90 
91 FEATURE(process_descriptors, "Process Descriptors");
92 
93 MALLOC_DEFINE(M_PROCDESC, "procdesc", "process descriptors");
94 
95 static fo_poll_t	procdesc_poll;
96 static fo_kqfilter_t	procdesc_kqfilter;
97 static fo_stat_t	procdesc_stat;
98 static fo_close_t	procdesc_close;
99 static fo_fill_kinfo_t	procdesc_fill_kinfo;
100 static fo_cmp_t		procdesc_cmp;
101 
102 static const struct fileops procdesc_ops = {
103 	.fo_read = invfo_rdwr,
104 	.fo_write = invfo_rdwr,
105 	.fo_truncate = invfo_truncate,
106 	.fo_ioctl = invfo_ioctl,
107 	.fo_poll = procdesc_poll,
108 	.fo_kqfilter = procdesc_kqfilter,
109 	.fo_stat = procdesc_stat,
110 	.fo_close = procdesc_close,
111 	.fo_chmod = invfo_chmod,
112 	.fo_chown = invfo_chown,
113 	.fo_sendfile = invfo_sendfile,
114 	.fo_fill_kinfo = procdesc_fill_kinfo,
115 	.fo_cmp = procdesc_cmp,
116 	.fo_flags = DFLAG_PASSABLE,
117 };
118 
119 /*
120  * Function to be used by procstat(1) sysctls when returning procdesc
121  * information.
122  */
123 pid_t
124 procdesc_pid(struct file *fp_procdesc)
125 {
126 	struct procdesc *pd;
127 
128 	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
129 	   ("procdesc_pid: !procdesc"));
130 
131 	pd = fp_procdesc->f_data;
132 	return (pd->pd_pid);
133 }
134 
135 /*
136  * Retrieve the PID associated with a process descriptor.
137  */
138 int
139 kern_pdgetpid(struct thread *td, int fd, const cap_rights_t *rightsp,
140     pid_t *pidp)
141 {
142 	struct file *fp;
143 	int error;
144 
145 	error = fget_procdesc(td, fd, rightsp, &fp, NULL, NULL);
146 	if (error == 0)
147 		*pidp = procdesc_pid(fp);
148 	if (fp != NULL)
149 		fdrop(fp, td);
150 	return (error);
151 }
152 
153 /*
154  * System call to return the pid of a process given its process descriptor.
155  */
156 int
157 sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
158 {
159 	pid_t pid;
160 	int error;
161 
162 	AUDIT_ARG_FD(uap->fd);
163 	error = kern_pdgetpid(td, uap->fd, &cap_pdgetpid_rights, &pid);
164 	if (error == 0)
165 		error = copyout(&pid, uap->pidp, sizeof(pid));
166 	return (error);
167 }
168 
169 static struct procdesc *
170 procdesc_alloc(int flags)
171 {
172 	struct procdesc *pd;
173 
174 	pd = malloc(sizeof(*pd), M_PROCDESC, M_WAITOK | M_ZERO);
175 	pd->pd_flags = 0;
176 	pd->pd_pid = -1;
177 	PROCDESC_LOCK_INIT(pd);
178 	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
179 
180 	/*
181 	 * Process descriptors start out with two references: one from their
182 	 * struct file, and the other from their struct proc.
183 	 */
184 	refcount_init(&pd->pd_refcount, 2);
185 	pd->pd_fpcount = 1;
186 
187 	return (pd);
188 }
189 
190 /*
191  * When a new process is forked by pdfork(), a file descriptor is allocated
192  * by the fork code first, then the process is forked, and then we get a
193  * chance to set up the process descriptor.  Failure is not permitted at this
194  * point, so procdesc_new() must succeed.
195  */
196 void
197 procdesc_new(struct proc *p, int flags)
198 {
199 	struct procdesc *pd;
200 
201 	pd = procdesc_alloc(flags);
202 	pd->pd_proc = p;
203 	pd->pd_pid = p->p_pid;
204 	MPASS(p->p_procdesc == NULL);
205 	p->p_procdesc = pd;
206 }
207 
208 static int
209 pdtofdflags(int flags)
210 {
211 	int fflags;
212 
213 	fflags = 0;
214 	if (flags & PD_CLOEXEC)
215 		fflags |= O_CLOEXEC;
216 	return (fflags);
217 }
218 
219 /*
220  * Create a new process decriptor for the process that refers to it.
221  */
222 int
223 procdesc_falloc(struct thread *td, struct file **resultfp, int *resultfd,
224     int flags, struct filecaps *fcaps)
225 {
226 	int error;
227 
228 	error = falloc_caps(td, resultfp, resultfd, pdtofdflags(flags), fcaps);
229 	if (error == 0 && (flags & PD_DAEMON) != 0)
230 		(*resultfp)->f_pdflags |= F_PD_NOKILL;
231 	return (error);
232 }
233 
234 /*
235  * Initialize a file with a process descriptor.
236  */
237 void
238 procdesc_finit(struct procdesc *pdp, struct file *fp)
239 {
240 
241 	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
242 }
243 
244 static void
245 procdesc_destroy(struct procdesc *pd)
246 {
247 	knlist_destroy(&pd->pd_selinfo.si_note);
248 	PROCDESC_LOCK_DESTROY(pd);
249 	free(pd, M_PROCDESC);
250 }
251 
252 static void
253 procdesc_free(struct procdesc *pd)
254 {
255 
256 	/*
257 	 * When the last reference is released, we assert that the descriptor
258 	 * has been closed, but not that the process has exited, as we will
259 	 * detach the descriptor before the process dies if the descript is
260 	 * closed, as we can't wait synchronously.
261 	 */
262 	if (refcount_release(&pd->pd_refcount)) {
263 		KASSERT(pd->pd_proc == NULL,
264 		    ("procdesc_free: pd_proc != NULL"));
265 		KASSERT(pd->pd_fpcount == 0,
266 		    ("procdesc_free: not closed %p %d", pd, pd->pd_fpcount));
267 
268 		if (pd->pd_pid != -1)
269 			proc_id_clear(PROC_ID_PID, pd->pd_pid);
270 
271 		seldrain(&pd->pd_selinfo);
272 		procdesc_destroy(pd);
273 	}
274 }
275 
276 /*
277  * procdesc_exit() - notify a process descriptor that its process is exiting.
278  * We use the proctree_lock to ensure that process exit either happens
279  * strictly before or strictly after a concurrent call to procdesc_close().
280  */
281 void
282 procdesc_exit(struct proc *p)
283 {
284 	struct procdesc *pd;
285 
286 	sx_assert(&proctree_lock, SA_XLOCKED);
287 	PROC_LOCK_ASSERT(p, MA_OWNED);
288 	MPASS((p->p_flag & P_WEXIT) != 0);
289 
290 	pd = p->p_procdesc;
291 	if (pd == NULL)
292 		return;
293 
294 	PROCDESC_LOCK(pd);
295 	KASSERT(pd->pd_fpcount > 0, ("%s: closed procdesc %p", __func__, pd));
296 
297 	pd->pd_flags |= PDF_EXITED;
298 	pd->pd_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
299 
300 	selwakeup(&pd->pd_selinfo);
301 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT | NOTE_PDSIGCHLD);
302 	PROCDESC_UNLOCK(pd);
303 
304 	/* Wakeup all waiters for this procdesc' process exit. */
305 	wakeup(&p->p_procdesc);
306 }
307 
308 void
309 procdesc_jobstate(struct proc *p)
310 {
311 	struct procdesc *pd;
312 
313 	PROC_LOCK_ASSERT(p, MA_OWNED);
314 	pd = p->p_procdesc;
315 	if (pd == NULL)
316 		return;
317 
318 	PROCDESC_LOCK(pd);
319 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_PDSIGCHLD);
320 	PROCDESC_UNLOCK(pd);
321 	wakeup(&p->p_procdesc);
322 }
323 
324 void
325 procdesc_fork(struct proc *p, pid_t child_pid)
326 {
327 	struct procdesc *pd;
328 
329 	PROC_LOCK(p);
330 	pd = p->p_procdesc;
331 	if (pd != NULL) {
332 		PROCDESC_LOCK(pd);
333 		pd->pd_last_child = child_pid;
334 		KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_FORK);
335 		PROCDESC_UNLOCK(pd);
336 	}
337 	PROC_UNLOCK(p);
338 }
339 
340 /*
341  * When a process descriptor is reaped, perhaps as a result of close(), release
342  * the process's reference on the process descriptor.
343  */
344 void
345 procdesc_reap(struct proc *p)
346 {
347 	struct procdesc *pd;
348 
349 	sx_assert(&proctree_lock, SA_XLOCKED);
350 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
351 
352 	pd = p->p_procdesc;
353 	pd->pd_proc = NULL;
354 	p->p_procdesc = NULL;
355 	procdesc_free(pd);
356 }
357 
358 static void
359 procdesc_close_tail(struct file *fp, struct proc *p)
360 {
361 	if ((fp->f_pdflags & F_PD_NOKILL) == 0)
362 		kern_psignal(p, SIGKILL);
363 	PROC_UNLOCK(p);
364 	sx_xunlock(&proctree_lock);
365 }
366 
367 /*
368  * procdesc_close() - last close on a process descriptor.  If the process is
369  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
370  * its reaper clean up the mess; if not, we have to clean up the zombie
371  * ourselves.
372  */
373 static int
374 procdesc_close(struct file *fp, struct thread *td)
375 {
376 	struct procdesc *pd;
377 	struct proc *p;
378 
379 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
380 
381 	pd = fp->f_data;
382 	fp->f_ops = &badfileops;
383 	fp->f_data = NULL;
384 
385 	sx_xlock(&proctree_lock);
386 	PROCDESC_LOCK(pd);
387 	MPASS(pd->pd_fpcount > 0);
388 	pd->pd_fpcount--;
389 	PROCDESC_UNLOCK(pd);
390 	p = pd->pd_proc;
391 	if (p == NULL) {
392 		/*
393 		 * This is the case where process' exit status was already
394 		 * collected and procdesc_reap() was already called.
395 		 */
396 		sx_xunlock(&proctree_lock);
397 	} else {
398 		PROC_LOCK(p);
399 		AUDIT_ARG_PROCESS(p);
400 		if (p->p_state == PRS_ZOMBIE) {
401 			/*
402 			 * If the process is already dead and just awaiting
403 			 * reaping, do that now.  This will release the
404 			 * process's reference to the process descriptor when it
405 			 * calls back into procdesc_reap().
406 			 */
407 			proc_reap(curthread, p, NULL, 0);
408 		} else if (pd->pd_fpcount == 0) /* last procdesc */ {
409 			/*
410 			 * If the process is not yet dead, we need to kill it,
411 			 * but we can't wait around synchronously for it to go
412 			 * away, as that path leads to madness (and deadlocks).
413 			 * First, detach the process from its descriptor so that
414 			 * its exit status will be reported normally.
415 			 */
416 			pd->pd_proc = NULL;
417 			p->p_procdesc = NULL;
418 			pd->pd_pid = -1;
419 			procdesc_free(pd);
420 
421 			/* Failed finstall() should not cause reaping. */
422 			if ((fp->f_pdflags & F_PD_NOFINSTALL) == 0) {
423 				/*
424 				 * Next, reparent it to its reaper
425 				 * (usually init(8)) so that there's
426 				 * someone to pick up the pieces;
427 				 * finally, terminate with prejudice.
428 				 */
429 				p->p_sigparent = SIGCHLD;
430 				if ((p->p_flag & P_TRACED) == 0) {
431 					proc_reparent(p, p->p_reaper, true);
432 				} else {
433 					proc_clear_orphan(p);
434 					p->p_oppid = p->p_reaper->p_pid;
435 					proc_add_orphan(p, p->p_reaper);
436 				}
437 			}
438 			procdesc_close_tail(fp, p);
439 		} else {
440 			procdesc_close_tail(fp, p);
441 		}
442 	}
443 
444 	/*
445 	 * Release the file descriptor's reference on the process descriptor.
446 	 */
447 	procdesc_free(pd);
448 	return (0);
449 }
450 
451 static int
452 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
453     struct thread *td)
454 {
455 	struct procdesc *pd;
456 	int revents;
457 
458 	revents = 0;
459 	pd = fp->f_data;
460 	PROCDESC_LOCK(pd);
461 	if (pd->pd_flags & PDF_EXITED)
462 		revents |= POLLHUP;
463 	else
464 		selrecord(td, &pd->pd_selinfo);
465 	PROCDESC_UNLOCK(pd);
466 	return (revents);
467 }
468 
469 static void
470 procdesc_kqops_detach(struct knote *kn)
471 {
472 	struct procdesc *pd;
473 
474 	pd = kn->kn_fp->f_data;
475 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
476 }
477 
478 static int
479 procdesc_kqops_event(struct knote *kn, long hint)
480 {
481 	struct procdesc *pd;
482 	struct proc *p;
483 	u_int event;
484 
485 	pd = kn->kn_fp->f_data;
486 	if (hint == 0) {
487 		/*
488 		 * Initial test after registration.  Generate notes in
489 		 * case the process already terminated before
490 		 * registration, or is stopped, or traced, with an event
491 		 * pending.
492 		 */
493 		p = pd->pd_proc;
494 		if ((pd->pd_flags & PDF_EXITED) != 0)
495 			event = NOTE_EXIT | NOTE_PDSIGCHLD;
496 		else if ((atomic_load_int(&p->p_flag) & (P_STOPPED_SIG |
497 		    P_STOPPED_TRACE)) != 0)
498 			event = NOTE_PDSIGCHLD;
499 		else
500 			event = 0;
501 	} else {
502 		/* Mask off extra data. */
503 		event = (u_int)hint & NOTE_PCTRLMASK;
504 	}
505 
506 	/* If the user is interested in this event, record it. */
507 	if ((kn->kn_sfflags & event) != 0)
508 		kn->kn_fflags |= kn->kn_sfflags & event;
509 
510 	/* Report exit status */
511 	if ((kn->kn_fflags & NOTE_EXIT) != 0)
512 		kn->kn_data = pd->pd_xstat;
513 
514 	/* Process is gone, so flag the event as finished. */
515 	if ((event & NOTE_REAP) != 0 ||
516 	    ((event & NOTE_EXIT) != 0 && (kn->kn_sfflags & NOTE_REAP) == 0)) {
517 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
518 		if (kn->kn_fflags == 0)
519 			kn->kn_flags |= EV_DROP;
520 		return (1);
521 	}
522 
523 	if ((kn->kn_fflags & NOTE_FORK) != 0)
524 		kn->kn_data = pd->pd_last_child;
525 
526 	return (kn->kn_fflags != 0);
527 }
528 
529 static const struct filterops procdesc_kqops = {
530 	.f_isfd = 1,
531 	.f_detach = procdesc_kqops_detach,
532 	.f_event = procdesc_kqops_event,
533 	.f_copy = knote_triv_copy,
534 };
535 
536 static int
537 procdesc_kqfilter(struct file *fp, struct knote *kn)
538 {
539 	struct procdesc *pd;
540 
541 	pd = fp->f_data;
542 	switch (kn->kn_filter) {
543 	case EVFILT_PROCDESC:
544 		kn->kn_fop = &procdesc_kqops;
545 		kn->kn_flags |= EV_CLEAR;
546 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
547 		return (0);
548 	default:
549 		return (EINVAL);
550 	}
551 }
552 
553 static int
554 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
555 {
556 	struct procdesc *pd;
557 	struct timeval pstart, boottime;
558 
559 	/*
560 	 * XXXRW: Perhaps we should cache some more information from the
561 	 * process so that we can return it reliably here even after it has
562 	 * died.  For example, caching its credential data.
563 	 */
564 	bzero(sb, sizeof(*sb));
565 	pd = fp->f_data;
566 	sx_slock(&proctree_lock);
567 	if (pd->pd_proc != NULL) {
568 		PROC_LOCK(pd->pd_proc);
569 		AUDIT_ARG_PROCESS(pd->pd_proc);
570 
571 		/* Set birth and [acm] times to process start time. */
572 		pstart = pd->pd_proc->p_stats->p_start;
573 		getboottime(&boottime);
574 		timevaladd(&pstart, &boottime);
575 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
576 		sb->st_atim = sb->st_birthtim;
577 		sb->st_ctim = sb->st_birthtim;
578 		sb->st_mtim = sb->st_birthtim;
579 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
580 			sb->st_mode = S_IFREG | S_IRWXU;
581 		else
582 			sb->st_mode = S_IFREG;
583 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
584 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
585 		PROC_UNLOCK(pd->pd_proc);
586 	} else
587 		sb->st_mode = S_IFREG;
588 	sx_sunlock(&proctree_lock);
589 	return (0);
590 }
591 
592 static int
593 procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
594     struct filedesc *fdp)
595 {
596 	struct procdesc *pdp;
597 
598 	kif->kf_type = KF_TYPE_PROCDESC;
599 	pdp = fp->f_data;
600 	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
601 	return (0);
602 }
603 
604 static int
605 procdesc_cmp(struct file *fp1, struct file *fp2, struct thread *td)
606 {
607 	struct procdesc *pdp1, *pdp2;
608 
609 	if (fp2->f_type != DTYPE_PROCDESC)
610 		return (3);
611 	pdp1 = fp1->f_data;
612 	pdp2 = fp2->f_data;
613 	return (kcmp_cmp((uintptr_t)pdp1->pd_pid, (uintptr_t)pdp2->pd_pid));
614 }
615 
616 static int
617 pdopenpid1(struct thread *td, pid_t pid, struct procdesc **pdf, struct file *fp)
618 {
619 	struct proc *p;
620 	struct procdesc *pd;
621 	int error;
622 
623 	sx_assert(&proctree_lock, SX_XLOCKED);
624 
625 	error = pget(pid, PGET_NOTID | PGET_CANDEBUG, &p);
626 	if (error != 0)
627 		return (error);
628 	if ((p->p_flag & (P_SYSTEM | P_WEXIT)) != 0) {
629 		PROC_UNLOCK(p);
630 		return (EBUSY);
631 	}
632 	pd = p->p_procdesc;
633 	if (pd != NULL) {
634 		refcount_acquire(&pd->pd_refcount);
635 		PROCDESC_LOCK(pd);
636 		MPASS(pd->pd_fpcount > 0);
637 		pd->pd_fpcount++;
638 		PROCDESC_UNLOCK(pd);
639 	} else {
640 		pd = *pdf;
641 		*pdf = NULL;
642 		pd->pd_proc = p;
643 		pd->pd_pid = p->p_pid;
644 		p->p_procdesc = pd;
645 	}
646 	procdesc_finit(pd, fp);
647 	PROC_UNLOCK(p);
648 	return (0);
649 }
650 
651 static int
652 kern_pdopenpid(struct thread *td, pid_t pid, int flags)
653 {
654 	struct file *fp;
655 	struct procdesc *pdf;
656 	int error, fd, fflags;
657 
658 	error = falloc_noinstall(td, &fp);
659 	if (error != 0)
660 		return (error);
661 	fflags = pdtofdflags(flags);
662 	pdf = procdesc_alloc(flags);
663 	if ((flags & PD_DAEMON) != 0)
664 		fp->f_pdflags |= F_PD_NOKILL;
665 
666 	sx_xlock(&proctree_lock);
667 	error = pdopenpid1(td, pid, &pdf, fp);
668 	sx_xunlock(&proctree_lock);
669 
670 	if (error == 0) {
671 		error = finstall(td, fp, &fd, fflags, NULL);
672 		if (error == 0) {
673 			td->td_retval[0] = fd;
674 		} else {
675 			/*
676 			 * Not killing the target process if cannot
677 			 * return file descriptor to userspace.
678 			 */
679 			fp->f_pdflags |= F_PD_NOKILL | F_PD_NOFINSTALL;
680 		}
681 	}
682 	fdrop(fp, td);
683 
684 	if (pdf != NULL) {
685 		MPASS(pdf->pd_refcount == 2);
686 		MPASS(pdf->pd_fpcount == 1);
687 		MPASS(pdf->pd_proc == NULL);
688 		MPASS(pdf->pd_pid == -1);
689 		procdesc_destroy(pdf);
690 	}
691 	return (error);
692 }
693 
694 int
695 sys_pdopenpid(struct thread *td, struct pdopenpid_args *args)
696 {
697 	AUDIT_ARG_PID(args->pid);
698 	AUDIT_ARG_FFLAGS(args->flags);
699 
700 	if ((args->flags & ~(PD_ALLOWED_AT_FORK)) != 0)
701 		return (EINVAL);
702 	return (kern_pdopenpid(td, args->pid, args->flags));
703 }
704 
705 /*
706  * Get the file/process descriptor/process from the procdesc file
707  * descriptor.  The process descriptor and process returns are
708  * optional.  If requested to return the process, the proctree lock
709  * must be held, and the process will be returned locked.
710  *
711  * The caller must fdrop(*pfp) if *pfp != NULL, regardless of the
712  * error returned, after the proctree_lock is unlocked.
713  * procdesc_close() takes the proctree_lock.
714  */
715 int
716 fget_procdesc(struct thread *td, int pdfd, const cap_rights_t *cap_rights,
717     struct file **pfp, struct procdesc **pdp, struct proc **pp)
718 {
719 	struct file *fp;
720 	struct procdesc *pd;
721 	struct proc *p;
722 	int error;
723 
724 	if (pp != NULL)
725 		sx_assert(&proctree_lock, SX_LOCKED);
726 
727 	*pfp = NULL;
728 	error = fget(td, pdfd, cap_rights, &fp);
729 	if (error != 0)
730 		return (error);
731 	*pfp = fp;
732 	if (fp->f_type != DTYPE_PROCDESC)
733 		return (EINVAL);
734 	pd = fp->f_data;
735 	if (pp != NULL) {
736 		p = pd->pd_proc;
737 		if (p == NULL) {
738 			return (ESRCH);
739 		} else {
740 			*pp = p;
741 			PROC_LOCK(p);
742 		}
743 	}
744 	if (pdp != NULL)
745 		*pdp = pd;
746 	return (0);
747 }
748 
749 static int
750 kern_pddupfd(struct thread *td, int pdfd, int fd, int flags)
751 {
752 	struct proc *p;
753 	struct file *fp, *pfp;
754 	struct filecaps fcaps;
755 	uint8_t fd_flags;
756 	int error, fdr;
757 
758 	sx_slock(&proctree_lock);
759 	error = fget_procdesc(td, pdfd, &cap_pddupfd_rights, &pfp, NULL, &p);
760 	if (error == 0) {
761 		if ((p->p_flag & P_WEXIT) != 0) {
762 			error = ESRCH;
763 			PROC_UNLOCK(p);
764 		} else {
765 			_PHOLD(p);
766 		}
767 	}
768 	sx_sunlock(&proctree_lock);
769 	if (error != 0)
770 		goto out;
771 	AUDIT_ARG_PROCESS(p);
772 	PROC_LOCK_ASSERT(p, MA_OWNED);
773 
774 	/*
775 	 * Block the target process from entering execve().
776 	 * We need to ensure that the p_candebug() predicate
777 	 * is stable until the fget_remote() call ends even
778 	 * after the process lock is dropped.  For that, the
779 	 * process must not change uid/suid.
780 	 */
781 	execve_block_wait(td, p);
782 	error = p_candebug(td, p);
783 
784 	if (error == 0) {
785 		PROC_UNLOCK(p);
786 		error = fget_remote(td, p, fd, &fcaps, &fd_flags, &fp);
787 		if (error == 0) {
788 			if ((fp->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
789 				error = EOPNOTSUPP;
790 			} else {
791 				error = finstall_refed(td, fp, &fdr, O_CLOEXEC |
792 				    ((fd_flags & FD_RESOLVE_BENEATH) != 0 ?
793 				    O_RESOLVE_BENEATH : 0), &fcaps);
794 			}
795 			if (error != 0) {
796 				fdrop(fp, td);
797 				filecaps_free(&fcaps);
798 			} else {
799 				td->td_retval[0] = fdr;
800 			}
801 		}
802 		PROC_LOCK(p);
803 	}
804 	execve_unblock(td, p);
805 	_PRELE(p);
806 	PROC_UNLOCK(p);
807 out:
808 	if (pfp != NULL)
809 		fdrop(pfp, td);
810 	return (error);
811 }
812 
813 int
814 sys_pddupfd(struct thread *td, struct pddupfd_args *args)
815 {
816 	if (args->flags != 0)
817 		return (EINVAL);
818 	return (kern_pddupfd(td, args->pd, args->fd, args->flags));
819 }
820