xref: /freebsd/sys/kern/sys_process.c (revision 8bd5e2f15cc9756e7d6b7feb43ec47f18a38e2bf)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1994, Sean Eric Fagan
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Sean Eric Fagan.
18  * 4. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/ktr.h>
40 #include <sys/limits.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/reg.h>
44 #include <sys/syscallsubr.h>
45 #include <sys/sysent.h>
46 #include <sys/sysproto.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/vnode.h>
50 #include <sys/ptrace.h>
51 #include <sys/rwlock.h>
52 #include <sys/sx.h>
53 #include <sys/malloc.h>
54 #include <sys/signalvar.h>
55 #include <sys/caprights.h>
56 #include <sys/filedesc.h>
57 
58 #include <security/audit/audit.h>
59 
60 #include <vm/vm.h>
61 #include <vm/pmap.h>
62 #include <vm/vm_extern.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_kern.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_page.h>
67 #include <vm/vm_param.h>
68 
69 #ifdef COMPAT_FREEBSD32
70 #include <sys/procfs.h>
71 #endif
72 
73 /* Assert it's safe to unlock a process, e.g. to allocate working memory */
74 #define	PROC_ASSERT_TRACEREQ(p)	MPASS(((p)->p_flag2 & P2_PTRACEREQ) != 0)
75 
76 /*
77  * Functions implemented using PROC_ACTION():
78  *
79  * proc_read_regs(proc, regs)
80  *	Get the current user-visible register set from the process
81  *	and copy it into the regs structure (<machine/reg.h>).
82  *	The process is stopped at the time read_regs is called.
83  *
84  * proc_write_regs(proc, regs)
85  *	Update the current register set from the passed in regs
86  *	structure.  Take care to avoid clobbering special CPU
87  *	registers or privileged bits in the PSL.
88  *	Depending on the architecture this may have fix-up work to do,
89  *	especially if the IAR or PCW are modified.
90  *	The process is stopped at the time write_regs is called.
91  *
92  * proc_read_fpregs, proc_write_fpregs
93  *	deal with the floating point register set, otherwise as above.
94  *
95  * proc_read_dbregs, proc_write_dbregs
96  *	deal with the processor debug register set, otherwise as above.
97  *
98  * proc_sstep(proc)
99  *	Arrange for the process to trap after executing a single instruction.
100  */
101 
102 #define	PROC_ACTION(action) do {					\
103 	int error;							\
104 									\
105 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);			\
106 	if ((td->td_proc->p_flag & P_INMEM) == 0)			\
107 		error = EIO;						\
108 	else								\
109 		error = (action);					\
110 	return (error);							\
111 } while (0)
112 
113 int
114 proc_read_regs(struct thread *td, struct reg *regs)
115 {
116 
117 	PROC_ACTION(fill_regs(td, regs));
118 }
119 
120 int
121 proc_write_regs(struct thread *td, struct reg *regs)
122 {
123 
124 	PROC_ACTION(set_regs(td, regs));
125 }
126 
127 int
128 proc_read_dbregs(struct thread *td, struct dbreg *dbregs)
129 {
130 
131 	PROC_ACTION(fill_dbregs(td, dbregs));
132 }
133 
134 int
135 proc_write_dbregs(struct thread *td, struct dbreg *dbregs)
136 {
137 
138 	PROC_ACTION(set_dbregs(td, dbregs));
139 }
140 
141 /*
142  * Ptrace doesn't support fpregs at all, and there are no security holes
143  * or translations for fpregs, so we can just copy them.
144  */
145 int
146 proc_read_fpregs(struct thread *td, struct fpreg *fpregs)
147 {
148 
149 	PROC_ACTION(fill_fpregs(td, fpregs));
150 }
151 
152 int
153 proc_write_fpregs(struct thread *td, struct fpreg *fpregs)
154 {
155 
156 	PROC_ACTION(set_fpregs(td, fpregs));
157 }
158 
159 static struct regset *
160 proc_find_regset(struct thread *td, int note)
161 {
162 	struct regset **regsetp, **regset_end, *regset;
163 	struct sysentvec *sv;
164 
165 	sv = td->td_proc->p_sysent;
166 	regsetp = sv->sv_regset_begin;
167 	if (regsetp == NULL)
168 		return (NULL);
169 	regset_end = sv->sv_regset_end;
170 	MPASS(regset_end != NULL);
171 	for (; regsetp < regset_end; regsetp++) {
172 		regset = *regsetp;
173 		if (regset->note != note)
174 			continue;
175 
176 		return (regset);
177 	}
178 
179 	return (NULL);
180 }
181 
182 static int
183 proc_read_regset(struct thread *td, int note, struct iovec *iov)
184 {
185 	struct regset *regset;
186 	struct proc *p;
187 	void *buf;
188 	size_t size;
189 	int error;
190 
191 	regset = proc_find_regset(td, note);
192 	if (regset == NULL)
193 		return (EINVAL);
194 
195 	if (iov->iov_base == NULL) {
196 		iov->iov_len = regset->size;
197 		if (iov->iov_len == 0)
198 			return (EINVAL);
199 
200 		return (0);
201 	}
202 
203 	/* The length is wrong, return an error */
204 	if (iov->iov_len != regset->size)
205 		return (EINVAL);
206 
207 	if (regset->get == NULL)
208 		return (EINVAL);
209 
210 	error = 0;
211 	size = regset->size;
212 	p = td->td_proc;
213 
214 	/* Drop the proc lock while allocating the temp buffer */
215 	PROC_ASSERT_TRACEREQ(p);
216 	PROC_UNLOCK(p);
217 	buf = malloc(size, M_TEMP, M_WAITOK);
218 	PROC_LOCK(p);
219 
220 	if (!regset->get(regset, td, buf, &size)) {
221 		error = EINVAL;
222 	} else {
223 		KASSERT(size == regset->size,
224 		    ("%s: Getter function changed the size", __func__));
225 
226 		iov->iov_len = size;
227 		PROC_UNLOCK(p);
228 		error = copyout(buf, iov->iov_base, size);
229 		PROC_LOCK(p);
230 	}
231 
232 	free(buf, M_TEMP);
233 
234 	return (error);
235 }
236 
237 static int
238 proc_write_regset(struct thread *td, int note, struct iovec *iov)
239 {
240 	struct regset *regset;
241 	struct proc *p;
242 	void *buf;
243 	size_t size;
244 	int error;
245 
246 	regset = proc_find_regset(td, note);
247 	if (regset == NULL)
248 		return (EINVAL);
249 
250 	/* The length is wrong, return an error */
251 	if (iov->iov_len != regset->size)
252 		return (EINVAL);
253 
254 	if (regset->set == NULL)
255 		return (EINVAL);
256 
257 	size = regset->size;
258 	p = td->td_proc;
259 
260 	/* Drop the proc lock while allocating the temp buffer */
261 	PROC_ASSERT_TRACEREQ(p);
262 	PROC_UNLOCK(p);
263 	buf = malloc(size, M_TEMP, M_WAITOK);
264 	error = copyin(iov->iov_base, buf, size);
265 	PROC_LOCK(p);
266 
267 	if (error == 0) {
268 		if (!regset->set(regset, td, buf, size)) {
269 			error = EINVAL;
270 		}
271 	}
272 
273 	free(buf, M_TEMP);
274 
275 	return (error);
276 }
277 
278 #ifdef COMPAT_FREEBSD32
279 /* For 32 bit binaries, we need to expose the 32 bit regs layouts. */
280 int
281 proc_read_regs32(struct thread *td, struct reg32 *regs32)
282 {
283 
284 	PROC_ACTION(fill_regs32(td, regs32));
285 }
286 
287 int
288 proc_write_regs32(struct thread *td, struct reg32 *regs32)
289 {
290 
291 	PROC_ACTION(set_regs32(td, regs32));
292 }
293 
294 int
295 proc_read_dbregs32(struct thread *td, struct dbreg32 *dbregs32)
296 {
297 
298 	PROC_ACTION(fill_dbregs32(td, dbregs32));
299 }
300 
301 int
302 proc_write_dbregs32(struct thread *td, struct dbreg32 *dbregs32)
303 {
304 
305 	PROC_ACTION(set_dbregs32(td, dbregs32));
306 }
307 
308 int
309 proc_read_fpregs32(struct thread *td, struct fpreg32 *fpregs32)
310 {
311 
312 	PROC_ACTION(fill_fpregs32(td, fpregs32));
313 }
314 
315 int
316 proc_write_fpregs32(struct thread *td, struct fpreg32 *fpregs32)
317 {
318 
319 	PROC_ACTION(set_fpregs32(td, fpregs32));
320 }
321 #endif
322 
323 int
324 proc_sstep(struct thread *td)
325 {
326 
327 	PROC_ACTION(ptrace_single_step(td));
328 }
329 
330 int
331 proc_rwmem(struct proc *p, struct uio *uio)
332 {
333 	vm_map_t map;
334 	vm_offset_t pageno;		/* page number */
335 	vm_prot_t reqprot;
336 	int error, fault_flags, page_offset, writing;
337 
338 	/*
339 	 * Assert that someone has locked this vmspace.  (Should be
340 	 * curthread but we can't assert that.)  This keeps the process
341 	 * from exiting out from under us until this operation completes.
342 	 */
343 	PROC_ASSERT_HELD(p);
344 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
345 
346 	/*
347 	 * The map we want...
348 	 */
349 	map = &p->p_vmspace->vm_map;
350 
351 	/*
352 	 * If we are writing, then we request vm_fault() to create a private
353 	 * copy of each page.  Since these copies will not be writeable by the
354 	 * process, we must explicity request that they be dirtied.
355 	 */
356 	writing = uio->uio_rw == UIO_WRITE;
357 	reqprot = writing ? VM_PROT_COPY | VM_PROT_READ : VM_PROT_READ;
358 	fault_flags = writing ? VM_FAULT_DIRTY : VM_FAULT_NORMAL;
359 
360 	/*
361 	 * Only map in one page at a time.  We don't have to, but it
362 	 * makes things easier.  This way is trivial - right?
363 	 */
364 	do {
365 		vm_offset_t uva;
366 		u_int len;
367 		vm_page_t m;
368 
369 		uva = (vm_offset_t)uio->uio_offset;
370 
371 		/*
372 		 * Get the page number of this segment.
373 		 */
374 		pageno = trunc_page(uva);
375 		page_offset = uva - pageno;
376 
377 		/*
378 		 * How many bytes to copy
379 		 */
380 		len = min(PAGE_SIZE - page_offset, uio->uio_resid);
381 
382 		/*
383 		 * Fault and hold the page on behalf of the process.
384 		 */
385 		error = vm_fault(map, pageno, reqprot, fault_flags, &m);
386 		if (error != KERN_SUCCESS) {
387 			if (error == KERN_RESOURCE_SHORTAGE)
388 				error = ENOMEM;
389 			else
390 				error = EFAULT;
391 			break;
392 		}
393 
394 		/*
395 		 * Now do the i/o move.
396 		 */
397 		error = uiomove_fromphys(&m, page_offset, len, uio);
398 
399 		/* Make the I-cache coherent for breakpoints. */
400 		if (writing && error == 0) {
401 			vm_map_lock_read(map);
402 			if (vm_map_check_protection(map, pageno, pageno +
403 			    PAGE_SIZE, VM_PROT_EXECUTE))
404 				vm_sync_icache(map, uva, len);
405 			vm_map_unlock_read(map);
406 		}
407 
408 		/*
409 		 * Release the page.
410 		 */
411 		vm_page_unwire(m, PQ_ACTIVE);
412 
413 	} while (error == 0 && uio->uio_resid > 0);
414 
415 	return (error);
416 }
417 
418 static ssize_t
419 proc_iop(struct thread *td, struct proc *p, vm_offset_t va, void *buf,
420     size_t len, enum uio_rw rw)
421 {
422 	struct iovec iov;
423 	struct uio uio;
424 	ssize_t slen;
425 
426 	MPASS(len < SSIZE_MAX);
427 	slen = (ssize_t)len;
428 
429 	iov.iov_base = (caddr_t)buf;
430 	iov.iov_len = len;
431 	uio.uio_iov = &iov;
432 	uio.uio_iovcnt = 1;
433 	uio.uio_offset = va;
434 	uio.uio_resid = slen;
435 	uio.uio_segflg = UIO_SYSSPACE;
436 	uio.uio_rw = rw;
437 	uio.uio_td = td;
438 	proc_rwmem(p, &uio);
439 	if (uio.uio_resid == slen)
440 		return (-1);
441 	return (slen - uio.uio_resid);
442 }
443 
444 ssize_t
445 proc_readmem(struct thread *td, struct proc *p, vm_offset_t va, void *buf,
446     size_t len)
447 {
448 
449 	return (proc_iop(td, p, va, buf, len, UIO_READ));
450 }
451 
452 ssize_t
453 proc_writemem(struct thread *td, struct proc *p, vm_offset_t va, void *buf,
454     size_t len)
455 {
456 
457 	return (proc_iop(td, p, va, buf, len, UIO_WRITE));
458 }
459 
460 static int
461 ptrace_vm_entry(struct thread *td, struct proc *p, struct ptrace_vm_entry *pve)
462 {
463 	struct vattr vattr;
464 	vm_map_t map;
465 	vm_map_entry_t entry;
466 	vm_object_t obj, tobj, lobj;
467 	struct vmspace *vm;
468 	struct vnode *vp;
469 	char *freepath, *fullpath;
470 	u_int pathlen;
471 	int error, index;
472 
473 	error = 0;
474 	obj = NULL;
475 
476 	vm = vmspace_acquire_ref(p);
477 	map = &vm->vm_map;
478 	vm_map_lock_read(map);
479 
480 	do {
481 		KASSERT((map->header.eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
482 		    ("Submap in map header"));
483 		index = 0;
484 		VM_MAP_ENTRY_FOREACH(entry, map) {
485 			if (index >= pve->pve_entry &&
486 			    (entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
487 				break;
488 			index++;
489 		}
490 		if (index < pve->pve_entry) {
491 			error = EINVAL;
492 			break;
493 		}
494 		if (entry == &map->header) {
495 			error = ENOENT;
496 			break;
497 		}
498 
499 		/* We got an entry. */
500 		pve->pve_entry = index + 1;
501 		pve->pve_timestamp = map->timestamp;
502 		pve->pve_start = entry->start;
503 		pve->pve_end = entry->end - 1;
504 		pve->pve_offset = entry->offset;
505 		pve->pve_prot = entry->protection;
506 
507 		/* Backing object's path needed? */
508 		if (pve->pve_pathlen == 0)
509 			break;
510 
511 		pathlen = pve->pve_pathlen;
512 		pve->pve_pathlen = 0;
513 
514 		obj = entry->object.vm_object;
515 		if (obj != NULL)
516 			VM_OBJECT_RLOCK(obj);
517 	} while (0);
518 
519 	vm_map_unlock_read(map);
520 
521 	pve->pve_fsid = VNOVAL;
522 	pve->pve_fileid = VNOVAL;
523 
524 	if (error == 0 && obj != NULL) {
525 		lobj = obj;
526 		for (tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
527 			if (tobj != obj)
528 				VM_OBJECT_RLOCK(tobj);
529 			if (lobj != obj)
530 				VM_OBJECT_RUNLOCK(lobj);
531 			lobj = tobj;
532 			pve->pve_offset += tobj->backing_object_offset;
533 		}
534 		vp = vm_object_vnode(lobj);
535 		if (vp != NULL)
536 			vref(vp);
537 		if (lobj != obj)
538 			VM_OBJECT_RUNLOCK(lobj);
539 		VM_OBJECT_RUNLOCK(obj);
540 
541 		if (vp != NULL) {
542 			freepath = NULL;
543 			fullpath = NULL;
544 			vn_fullpath(vp, &fullpath, &freepath);
545 			vn_lock(vp, LK_SHARED | LK_RETRY);
546 			if (VOP_GETATTR(vp, &vattr, td->td_ucred) == 0) {
547 				pve->pve_fileid = vattr.va_fileid;
548 				pve->pve_fsid = vattr.va_fsid;
549 			}
550 			vput(vp);
551 
552 			if (fullpath != NULL) {
553 				pve->pve_pathlen = strlen(fullpath) + 1;
554 				if (pve->pve_pathlen <= pathlen) {
555 					error = copyout(fullpath, pve->pve_path,
556 					    pve->pve_pathlen);
557 				} else
558 					error = ENAMETOOLONG;
559 			}
560 			if (freepath != NULL)
561 				free(freepath, M_TEMP);
562 		}
563 	}
564 	vmspace_free(vm);
565 	if (error == 0)
566 		CTR3(KTR_PTRACE, "PT_VM_ENTRY: pid %d, entry %d, start %p",
567 		    p->p_pid, pve->pve_entry, pve->pve_start);
568 
569 	return (error);
570 }
571 
572 /*
573  * Process debugging system call.
574  */
575 #ifndef _SYS_SYSPROTO_H_
576 struct ptrace_args {
577 	int	req;
578 	pid_t	pid;
579 	caddr_t	addr;
580 	int	data;
581 };
582 #endif
583 
584 int
585 sys_ptrace(struct thread *td, struct ptrace_args *uap)
586 {
587 	/*
588 	 * XXX this obfuscation is to reduce stack usage, but the register
589 	 * structs may be too large to put on the stack anyway.
590 	 */
591 	union {
592 		struct ptrace_io_desc piod;
593 		struct ptrace_lwpinfo pl;
594 		struct ptrace_vm_entry pve;
595 		struct ptrace_coredump pc;
596 		struct dbreg dbreg;
597 		struct fpreg fpreg;
598 		struct reg reg;
599 		struct iovec vec;
600 		char args[sizeof(td->td_sa.args)];
601 		struct ptrace_sc_ret psr;
602 		int ptevents;
603 	} r;
604 	void *addr;
605 	int error;
606 
607 	if (!allow_ptrace)
608 		return (ENOSYS);
609 	error = 0;
610 
611 	AUDIT_ARG_PID(uap->pid);
612 	AUDIT_ARG_CMD(uap->req);
613 	AUDIT_ARG_VALUE(uap->data);
614 	addr = &r;
615 	switch (uap->req) {
616 	case PT_GET_EVENT_MASK:
617 	case PT_LWPINFO:
618 	case PT_GET_SC_ARGS:
619 	case PT_GET_SC_RET:
620 		break;
621 	case PT_GETREGS:
622 		bzero(&r.reg, sizeof(r.reg));
623 		break;
624 	case PT_GETFPREGS:
625 		bzero(&r.fpreg, sizeof(r.fpreg));
626 		break;
627 	case PT_GETDBREGS:
628 		bzero(&r.dbreg, sizeof(r.dbreg));
629 		break;
630 	case PT_SETREGSET:
631 		error = copyin(uap->addr, &r.vec, sizeof(r.vec));
632 		break;
633 	case PT_GETREGSET:
634 		error = copyin(uap->addr, &r.vec, sizeof(r.vec));
635 		break;
636 	case PT_SETREGS:
637 		error = copyin(uap->addr, &r.reg, sizeof(r.reg));
638 		break;
639 	case PT_SETFPREGS:
640 		error = copyin(uap->addr, &r.fpreg, sizeof(r.fpreg));
641 		break;
642 	case PT_SETDBREGS:
643 		error = copyin(uap->addr, &r.dbreg, sizeof(r.dbreg));
644 		break;
645 	case PT_SET_EVENT_MASK:
646 		if (uap->data != sizeof(r.ptevents))
647 			error = EINVAL;
648 		else
649 			error = copyin(uap->addr, &r.ptevents, uap->data);
650 		break;
651 	case PT_IO:
652 		error = copyin(uap->addr, &r.piod, sizeof(r.piod));
653 		break;
654 	case PT_VM_ENTRY:
655 		error = copyin(uap->addr, &r.pve, sizeof(r.pve));
656 		break;
657 	case PT_COREDUMP:
658 		if (uap->data != sizeof(r.pc))
659 			error = EINVAL;
660 		else
661 			error = copyin(uap->addr, &r.pc, uap->data);
662 		break;
663 	default:
664 		addr = uap->addr;
665 		break;
666 	}
667 	if (error)
668 		return (error);
669 
670 	error = kern_ptrace(td, uap->req, uap->pid, addr, uap->data);
671 	if (error)
672 		return (error);
673 
674 	switch (uap->req) {
675 	case PT_VM_ENTRY:
676 		error = copyout(&r.pve, uap->addr, sizeof(r.pve));
677 		break;
678 	case PT_IO:
679 		error = copyout(&r.piod, uap->addr, sizeof(r.piod));
680 		break;
681 	case PT_GETREGS:
682 		error = copyout(&r.reg, uap->addr, sizeof(r.reg));
683 		break;
684 	case PT_GETFPREGS:
685 		error = copyout(&r.fpreg, uap->addr, sizeof(r.fpreg));
686 		break;
687 	case PT_GETDBREGS:
688 		error = copyout(&r.dbreg, uap->addr, sizeof(r.dbreg));
689 		break;
690 	case PT_GETREGSET:
691 		error = copyout(&r.vec, uap->addr, sizeof(r.vec));
692 		break;
693 	case PT_GET_EVENT_MASK:
694 		/* NB: The size in uap->data is validated in kern_ptrace(). */
695 		error = copyout(&r.ptevents, uap->addr, uap->data);
696 		break;
697 	case PT_LWPINFO:
698 		/* NB: The size in uap->data is validated in kern_ptrace(). */
699 		error = copyout(&r.pl, uap->addr, uap->data);
700 		break;
701 	case PT_GET_SC_ARGS:
702 		error = copyout(r.args, uap->addr, MIN(uap->data,
703 		    sizeof(r.args)));
704 		break;
705 	case PT_GET_SC_RET:
706 		error = copyout(&r.psr, uap->addr, MIN(uap->data,
707 		    sizeof(r.psr)));
708 		break;
709 	}
710 
711 	return (error);
712 }
713 
714 #ifdef COMPAT_FREEBSD32
715 /*
716  *   PROC_READ(regs, td2, addr);
717  * becomes either:
718  *   proc_read_regs(td2, addr);
719  * or
720  *   proc_read_regs32(td2, addr);
721  * .. except this is done at runtime.  There is an additional
722  * complication in that PROC_WRITE disallows 32 bit consumers
723  * from writing to 64 bit address space targets.
724  */
725 #define	PROC_READ(w, t, a)	wrap32 ? \
726 	proc_read_ ## w ## 32(t, a) : \
727 	proc_read_ ## w (t, a)
728 #define	PROC_WRITE(w, t, a)	wrap32 ? \
729 	(safe ? proc_write_ ## w ## 32(t, a) : EINVAL ) : \
730 	proc_write_ ## w (t, a)
731 #else
732 #define	PROC_READ(w, t, a)	proc_read_ ## w (t, a)
733 #define	PROC_WRITE(w, t, a)	proc_write_ ## w (t, a)
734 #endif
735 
736 void
737 proc_set_traced(struct proc *p, bool stop)
738 {
739 
740 	sx_assert(&proctree_lock, SX_XLOCKED);
741 	PROC_LOCK_ASSERT(p, MA_OWNED);
742 	p->p_flag |= P_TRACED;
743 	if (stop)
744 		p->p_flag2 |= P2_PTRACE_FSTP;
745 	p->p_ptevents = PTRACE_DEFAULT;
746 }
747 
748 void
749 ptrace_unsuspend(struct proc *p)
750 {
751 	PROC_LOCK_ASSERT(p, MA_OWNED);
752 
753 	PROC_SLOCK(p);
754 	p->p_flag &= ~(P_STOPPED_TRACE | P_STOPPED_SIG | P_WAITED);
755 	thread_unsuspend(p);
756 	PROC_SUNLOCK(p);
757 	itimer_proc_continue(p);
758 	kqtimer_proc_continue(p);
759 }
760 
761 static int
762 proc_can_ptrace(struct thread *td, struct proc *p)
763 {
764 	int error;
765 
766 	PROC_LOCK_ASSERT(p, MA_OWNED);
767 
768 	if ((p->p_flag & P_WEXIT) != 0)
769 		return (ESRCH);
770 
771 	if ((error = p_cansee(td, p)) != 0)
772 		return (error);
773 	if ((error = p_candebug(td, p)) != 0)
774 		return (error);
775 
776 	/* not being traced... */
777 	if ((p->p_flag & P_TRACED) == 0)
778 		return (EPERM);
779 
780 	/* not being traced by YOU */
781 	if (p->p_pptr != td->td_proc)
782 		return (EBUSY);
783 
784 	/* not currently stopped */
785 	if ((p->p_flag & P_STOPPED_TRACE) == 0 ||
786 	    p->p_suspcount != p->p_numthreads  ||
787 	    (p->p_flag & P_WAITED) == 0)
788 		return (EBUSY);
789 
790 	return (0);
791 }
792 
793 static struct thread *
794 ptrace_sel_coredump_thread(struct proc *p)
795 {
796 	struct thread *td2;
797 
798 	PROC_LOCK_ASSERT(p, MA_OWNED);
799 	MPASS((p->p_flag & P_STOPPED_TRACE) != 0);
800 
801 	FOREACH_THREAD_IN_PROC(p, td2) {
802 		if ((td2->td_dbgflags & TDB_SSWITCH) != 0)
803 			return (td2);
804 	}
805 	return (NULL);
806 }
807 
808 int
809 kern_ptrace(struct thread *td, int req, pid_t pid, void *addr, int data)
810 {
811 	struct iovec iov;
812 	struct uio uio;
813 	struct proc *curp, *p, *pp;
814 	struct thread *td2 = NULL, *td3;
815 	struct ptrace_io_desc *piod = NULL;
816 	struct ptrace_lwpinfo *pl;
817 	struct ptrace_sc_ret *psr;
818 	struct file *fp;
819 	struct ptrace_coredump *pc;
820 	struct thr_coredump_req *tcq;
821 	int error, num, tmp;
822 	lwpid_t tid = 0, *buf;
823 #ifdef COMPAT_FREEBSD32
824 	int wrap32 = 0, safe = 0;
825 #endif
826 	bool proctree_locked, p2_req_set;
827 
828 	curp = td->td_proc;
829 	proctree_locked = false;
830 	p2_req_set = false;
831 
832 	/* Lock proctree before locking the process. */
833 	switch (req) {
834 	case PT_TRACE_ME:
835 	case PT_ATTACH:
836 	case PT_STEP:
837 	case PT_CONTINUE:
838 	case PT_TO_SCE:
839 	case PT_TO_SCX:
840 	case PT_SYSCALL:
841 	case PT_FOLLOW_FORK:
842 	case PT_LWP_EVENTS:
843 	case PT_GET_EVENT_MASK:
844 	case PT_SET_EVENT_MASK:
845 	case PT_DETACH:
846 	case PT_GET_SC_ARGS:
847 		sx_xlock(&proctree_lock);
848 		proctree_locked = true;
849 		break;
850 	default:
851 		break;
852 	}
853 
854 	if (req == PT_TRACE_ME) {
855 		p = td->td_proc;
856 		PROC_LOCK(p);
857 	} else {
858 		if (pid <= PID_MAX) {
859 			if ((p = pfind(pid)) == NULL) {
860 				if (proctree_locked)
861 					sx_xunlock(&proctree_lock);
862 				return (ESRCH);
863 			}
864 		} else {
865 			td2 = tdfind(pid, -1);
866 			if (td2 == NULL) {
867 				if (proctree_locked)
868 					sx_xunlock(&proctree_lock);
869 				return (ESRCH);
870 			}
871 			p = td2->td_proc;
872 			tid = pid;
873 			pid = p->p_pid;
874 		}
875 	}
876 	AUDIT_ARG_PROCESS(p);
877 
878 	if ((p->p_flag & P_WEXIT) != 0) {
879 		error = ESRCH;
880 		goto fail;
881 	}
882 	if ((error = p_cansee(td, p)) != 0)
883 		goto fail;
884 
885 	if ((error = p_candebug(td, p)) != 0)
886 		goto fail;
887 
888 	/*
889 	 * System processes can't be debugged.
890 	 */
891 	if ((p->p_flag & P_SYSTEM) != 0) {
892 		error = EINVAL;
893 		goto fail;
894 	}
895 
896 	if (tid == 0) {
897 		if ((p->p_flag & P_STOPPED_TRACE) != 0) {
898 			KASSERT(p->p_xthread != NULL, ("NULL p_xthread"));
899 			td2 = p->p_xthread;
900 		} else {
901 			td2 = FIRST_THREAD_IN_PROC(p);
902 		}
903 		tid = td2->td_tid;
904 	}
905 
906 #ifdef COMPAT_FREEBSD32
907 	/*
908 	 * Test if we're a 32 bit client and what the target is.
909 	 * Set the wrap controls accordingly.
910 	 */
911 	if (SV_CURPROC_FLAG(SV_ILP32)) {
912 		if (SV_PROC_FLAG(td2->td_proc, SV_ILP32))
913 			safe = 1;
914 		wrap32 = 1;
915 	}
916 #endif
917 	/*
918 	 * Permissions check
919 	 */
920 	switch (req) {
921 	case PT_TRACE_ME:
922 		/*
923 		 * Always legal, when there is a parent process which
924 		 * could trace us.  Otherwise, reject.
925 		 */
926 		if ((p->p_flag & P_TRACED) != 0) {
927 			error = EBUSY;
928 			goto fail;
929 		}
930 		if (p->p_pptr == initproc) {
931 			error = EPERM;
932 			goto fail;
933 		}
934 		break;
935 
936 	case PT_ATTACH:
937 		/* Self */
938 		if (p == td->td_proc) {
939 			error = EINVAL;
940 			goto fail;
941 		}
942 
943 		/* Already traced */
944 		if (p->p_flag & P_TRACED) {
945 			error = EBUSY;
946 			goto fail;
947 		}
948 
949 		/* Can't trace an ancestor if you're being traced. */
950 		if (curp->p_flag & P_TRACED) {
951 			for (pp = curp->p_pptr; pp != NULL; pp = pp->p_pptr) {
952 				if (pp == p) {
953 					error = EINVAL;
954 					goto fail;
955 				}
956 			}
957 		}
958 
959 		/* OK */
960 		break;
961 
962 	case PT_CLEARSTEP:
963 		/* Allow thread to clear single step for itself */
964 		if (td->td_tid == tid)
965 			break;
966 
967 		/* FALLTHROUGH */
968 	default:
969 		/*
970 		 * Check for ptrace eligibility before waiting for
971 		 * holds to drain.
972 		 */
973 		error = proc_can_ptrace(td, p);
974 		if (error != 0)
975 			goto fail;
976 
977 		/*
978 		 * Block parallel ptrace requests.  Most important, do
979 		 * not allow other thread in debugger to continue the
980 		 * debuggee until coredump finished.
981 		 */
982 		while ((p->p_flag2 & P2_PTRACEREQ) != 0) {
983 			if (proctree_locked)
984 				sx_xunlock(&proctree_lock);
985 			error = msleep(&p->p_flag2, &p->p_mtx, PPAUSE | PCATCH |
986 			    (proctree_locked ? PDROP : 0), "pptrace", 0);
987 			if (proctree_locked) {
988 				sx_xlock(&proctree_lock);
989 				PROC_LOCK(p);
990 			}
991 			if (error == 0 && td2->td_proc != p)
992 				error = ESRCH;
993 			if (error == 0)
994 				error = proc_can_ptrace(td, p);
995 			if (error != 0)
996 				goto fail;
997 		}
998 
999 		/* Ok */
1000 		break;
1001 	}
1002 
1003 	/*
1004 	 * Keep this process around and request parallel ptrace()
1005 	 * request to wait until we finish this request.
1006 	 */
1007 	MPASS((p->p_flag2 & P2_PTRACEREQ) == 0);
1008 	p->p_flag2 |= P2_PTRACEREQ;
1009 	p2_req_set = true;
1010 	_PHOLD(p);
1011 
1012 	/*
1013 	 * Actually do the requests
1014 	 */
1015 
1016 	td->td_retval[0] = 0;
1017 
1018 	switch (req) {
1019 	case PT_TRACE_ME:
1020 		/* set my trace flag and "owner" so it can read/write me */
1021 		proc_set_traced(p, false);
1022 		if (p->p_flag & P_PPWAIT)
1023 			p->p_flag |= P_PPTRACE;
1024 		CTR1(KTR_PTRACE, "PT_TRACE_ME: pid %d", p->p_pid);
1025 		break;
1026 
1027 	case PT_ATTACH:
1028 		/* security check done above */
1029 		/*
1030 		 * It would be nice if the tracing relationship was separate
1031 		 * from the parent relationship but that would require
1032 		 * another set of links in the proc struct or for "wait"
1033 		 * to scan the entire proc table.  To make life easier,
1034 		 * we just re-parent the process we're trying to trace.
1035 		 * The old parent is remembered so we can put things back
1036 		 * on a "detach".
1037 		 */
1038 		proc_set_traced(p, true);
1039 		proc_reparent(p, td->td_proc, false);
1040 		CTR2(KTR_PTRACE, "PT_ATTACH: pid %d, oppid %d", p->p_pid,
1041 		    p->p_oppid);
1042 
1043 		sx_xunlock(&proctree_lock);
1044 		proctree_locked = false;
1045 		MPASS(p->p_xthread == NULL);
1046 		MPASS((p->p_flag & P_STOPPED_TRACE) == 0);
1047 
1048 		/*
1049 		 * If already stopped due to a stop signal, clear the
1050 		 * existing stop before triggering a traced SIGSTOP.
1051 		 */
1052 		if ((p->p_flag & P_STOPPED_SIG) != 0) {
1053 			PROC_SLOCK(p);
1054 			p->p_flag &= ~(P_STOPPED_SIG | P_WAITED);
1055 			thread_unsuspend(p);
1056 			PROC_SUNLOCK(p);
1057 		}
1058 
1059 		kern_psignal(p, SIGSTOP);
1060 		break;
1061 
1062 	case PT_CLEARSTEP:
1063 		CTR2(KTR_PTRACE, "PT_CLEARSTEP: tid %d (pid %d)", td2->td_tid,
1064 		    p->p_pid);
1065 		error = ptrace_clear_single_step(td2);
1066 		break;
1067 
1068 	case PT_SETSTEP:
1069 		CTR2(KTR_PTRACE, "PT_SETSTEP: tid %d (pid %d)", td2->td_tid,
1070 		    p->p_pid);
1071 		error = ptrace_single_step(td2);
1072 		break;
1073 
1074 	case PT_SUSPEND:
1075 		CTR2(KTR_PTRACE, "PT_SUSPEND: tid %d (pid %d)", td2->td_tid,
1076 		    p->p_pid);
1077 		td2->td_dbgflags |= TDB_SUSPEND;
1078 		thread_lock(td2);
1079 		td2->td_flags |= TDF_NEEDSUSPCHK;
1080 		thread_unlock(td2);
1081 		break;
1082 
1083 	case PT_RESUME:
1084 		CTR2(KTR_PTRACE, "PT_RESUME: tid %d (pid %d)", td2->td_tid,
1085 		    p->p_pid);
1086 		td2->td_dbgflags &= ~TDB_SUSPEND;
1087 		break;
1088 
1089 	case PT_FOLLOW_FORK:
1090 		CTR3(KTR_PTRACE, "PT_FOLLOW_FORK: pid %d %s -> %s", p->p_pid,
1091 		    p->p_ptevents & PTRACE_FORK ? "enabled" : "disabled",
1092 		    data ? "enabled" : "disabled");
1093 		if (data)
1094 			p->p_ptevents |= PTRACE_FORK;
1095 		else
1096 			p->p_ptevents &= ~PTRACE_FORK;
1097 		break;
1098 
1099 	case PT_LWP_EVENTS:
1100 		CTR3(KTR_PTRACE, "PT_LWP_EVENTS: pid %d %s -> %s", p->p_pid,
1101 		    p->p_ptevents & PTRACE_LWP ? "enabled" : "disabled",
1102 		    data ? "enabled" : "disabled");
1103 		if (data)
1104 			p->p_ptevents |= PTRACE_LWP;
1105 		else
1106 			p->p_ptevents &= ~PTRACE_LWP;
1107 		break;
1108 
1109 	case PT_GET_EVENT_MASK:
1110 		if (data != sizeof(p->p_ptevents)) {
1111 			error = EINVAL;
1112 			break;
1113 		}
1114 		CTR2(KTR_PTRACE, "PT_GET_EVENT_MASK: pid %d mask %#x", p->p_pid,
1115 		    p->p_ptevents);
1116 		*(int *)addr = p->p_ptevents;
1117 		break;
1118 
1119 	case PT_SET_EVENT_MASK:
1120 		if (data != sizeof(p->p_ptevents)) {
1121 			error = EINVAL;
1122 			break;
1123 		}
1124 		tmp = *(int *)addr;
1125 		if ((tmp & ~(PTRACE_EXEC | PTRACE_SCE | PTRACE_SCX |
1126 		    PTRACE_FORK | PTRACE_LWP | PTRACE_VFORK)) != 0) {
1127 			error = EINVAL;
1128 			break;
1129 		}
1130 		CTR3(KTR_PTRACE, "PT_SET_EVENT_MASK: pid %d mask %#x -> %#x",
1131 		    p->p_pid, p->p_ptevents, tmp);
1132 		p->p_ptevents = tmp;
1133 		break;
1134 
1135 	case PT_GET_SC_ARGS:
1136 		CTR1(KTR_PTRACE, "PT_GET_SC_ARGS: pid %d", p->p_pid);
1137 		if ((td2->td_dbgflags & (TDB_SCE | TDB_SCX)) == 0
1138 #ifdef COMPAT_FREEBSD32
1139 		    || (wrap32 && !safe)
1140 #endif
1141 		    ) {
1142 			error = EINVAL;
1143 			break;
1144 		}
1145 		bzero(addr, sizeof(td2->td_sa.args));
1146 		/* See the explanation in linux_ptrace_get_syscall_info(). */
1147 		bcopy(td2->td_sa.args, addr, SV_PROC_ABI(td->td_proc) ==
1148 		    SV_ABI_LINUX ? sizeof(td2->td_sa.args) :
1149 		    td2->td_sa.callp->sy_narg * sizeof(register_t));
1150 		break;
1151 
1152 	case PT_GET_SC_RET:
1153 		if ((td2->td_dbgflags & (TDB_SCX)) == 0
1154 #ifdef COMPAT_FREEBSD32
1155 		    || (wrap32 && !safe)
1156 #endif
1157 		    ) {
1158 			error = EINVAL;
1159 			break;
1160 		}
1161 		psr = addr;
1162 		bzero(psr, sizeof(*psr));
1163 		psr->sr_error = td2->td_errno;
1164 		if (psr->sr_error == 0) {
1165 			psr->sr_retval[0] = td2->td_retval[0];
1166 			psr->sr_retval[1] = td2->td_retval[1];
1167 		}
1168 		CTR4(KTR_PTRACE,
1169 		    "PT_GET_SC_RET: pid %d error %d retval %#lx,%#lx",
1170 		    p->p_pid, psr->sr_error, psr->sr_retval[0],
1171 		    psr->sr_retval[1]);
1172 		break;
1173 
1174 	case PT_STEP:
1175 	case PT_CONTINUE:
1176 	case PT_TO_SCE:
1177 	case PT_TO_SCX:
1178 	case PT_SYSCALL:
1179 	case PT_DETACH:
1180 		/* Zero means do not send any signal */
1181 		if (data < 0 || data > _SIG_MAXSIG) {
1182 			error = EINVAL;
1183 			break;
1184 		}
1185 
1186 		switch (req) {
1187 		case PT_STEP:
1188 			CTR3(KTR_PTRACE, "PT_STEP: tid %d (pid %d), sig = %d",
1189 			    td2->td_tid, p->p_pid, data);
1190 			error = ptrace_single_step(td2);
1191 			if (error)
1192 				goto out;
1193 			break;
1194 		case PT_CONTINUE:
1195 		case PT_TO_SCE:
1196 		case PT_TO_SCX:
1197 		case PT_SYSCALL:
1198 			if (addr != (void *)1) {
1199 				error = ptrace_set_pc(td2,
1200 				    (u_long)(uintfptr_t)addr);
1201 				if (error)
1202 					goto out;
1203 			}
1204 			switch (req) {
1205 			case PT_TO_SCE:
1206 				p->p_ptevents |= PTRACE_SCE;
1207 				CTR4(KTR_PTRACE,
1208 		    "PT_TO_SCE: pid %d, events = %#x, PC = %#lx, sig = %d",
1209 				    p->p_pid, p->p_ptevents,
1210 				    (u_long)(uintfptr_t)addr, data);
1211 				break;
1212 			case PT_TO_SCX:
1213 				p->p_ptevents |= PTRACE_SCX;
1214 				CTR4(KTR_PTRACE,
1215 		    "PT_TO_SCX: pid %d, events = %#x, PC = %#lx, sig = %d",
1216 				    p->p_pid, p->p_ptevents,
1217 				    (u_long)(uintfptr_t)addr, data);
1218 				break;
1219 			case PT_SYSCALL:
1220 				p->p_ptevents |= PTRACE_SYSCALL;
1221 				CTR4(KTR_PTRACE,
1222 		    "PT_SYSCALL: pid %d, events = %#x, PC = %#lx, sig = %d",
1223 				    p->p_pid, p->p_ptevents,
1224 				    (u_long)(uintfptr_t)addr, data);
1225 				break;
1226 			case PT_CONTINUE:
1227 				CTR3(KTR_PTRACE,
1228 				    "PT_CONTINUE: pid %d, PC = %#lx, sig = %d",
1229 				    p->p_pid, (u_long)(uintfptr_t)addr, data);
1230 				break;
1231 			}
1232 			break;
1233 		case PT_DETACH:
1234 			/*
1235 			 * Clear P_TRACED before reparenting
1236 			 * a detached process back to its original
1237 			 * parent.  Otherwise the debugee will be set
1238 			 * as an orphan of the debugger.
1239 			 */
1240 			p->p_flag &= ~(P_TRACED | P_WAITED);
1241 
1242 			/*
1243 			 * Reset the process parent.
1244 			 */
1245 			if (p->p_oppid != p->p_pptr->p_pid) {
1246 				PROC_LOCK(p->p_pptr);
1247 				sigqueue_take(p->p_ksi);
1248 				PROC_UNLOCK(p->p_pptr);
1249 
1250 				pp = proc_realparent(p);
1251 				proc_reparent(p, pp, false);
1252 				if (pp == initproc)
1253 					p->p_sigparent = SIGCHLD;
1254 				CTR3(KTR_PTRACE,
1255 			    "PT_DETACH: pid %d reparented to pid %d, sig %d",
1256 				    p->p_pid, pp->p_pid, data);
1257 			} else {
1258 				CTR2(KTR_PTRACE, "PT_DETACH: pid %d, sig %d",
1259 				    p->p_pid, data);
1260 			}
1261 
1262 			p->p_ptevents = 0;
1263 			FOREACH_THREAD_IN_PROC(p, td3) {
1264 				if ((td3->td_dbgflags & TDB_FSTP) != 0) {
1265 					sigqueue_delete(&td3->td_sigqueue,
1266 					    SIGSTOP);
1267 				}
1268 				td3->td_dbgflags &= ~(TDB_XSIG | TDB_FSTP |
1269 				    TDB_SUSPEND);
1270 			}
1271 
1272 			if ((p->p_flag2 & P2_PTRACE_FSTP) != 0) {
1273 				sigqueue_delete(&p->p_sigqueue, SIGSTOP);
1274 				p->p_flag2 &= ~P2_PTRACE_FSTP;
1275 			}
1276 
1277 			/* should we send SIGCHLD? */
1278 			/* childproc_continued(p); */
1279 			break;
1280 		}
1281 
1282 		sx_xunlock(&proctree_lock);
1283 		proctree_locked = false;
1284 
1285 	sendsig:
1286 		MPASS(!proctree_locked);
1287 
1288 		/*
1289 		 * Clear the pending event for the thread that just
1290 		 * reported its event (p_xthread).  This may not be
1291 		 * the thread passed to PT_CONTINUE, PT_STEP, etc. if
1292 		 * the debugger is resuming a different thread.
1293 		 *
1294 		 * Deliver any pending signal via the reporting thread.
1295 		 */
1296 		MPASS(p->p_xthread != NULL);
1297 		p->p_xthread->td_dbgflags &= ~TDB_XSIG;
1298 		p->p_xthread->td_xsig = data;
1299 		p->p_xthread = NULL;
1300 		p->p_xsig = data;
1301 
1302 		/*
1303 		 * P_WKILLED is insurance that a PT_KILL/SIGKILL
1304 		 * always works immediately, even if another thread is
1305 		 * unsuspended first and attempts to handle a
1306 		 * different signal or if the POSIX.1b style signal
1307 		 * queue cannot accommodate any new signals.
1308 		 */
1309 		if (data == SIGKILL)
1310 			proc_wkilled(p);
1311 
1312 		/*
1313 		 * Unsuspend all threads.  To leave a thread
1314 		 * suspended, use PT_SUSPEND to suspend it before
1315 		 * continuing the process.
1316 		 */
1317 		ptrace_unsuspend(p);
1318 		break;
1319 
1320 	case PT_WRITE_I:
1321 	case PT_WRITE_D:
1322 		td2->td_dbgflags |= TDB_USERWR;
1323 		PROC_UNLOCK(p);
1324 		error = 0;
1325 		if (proc_writemem(td, p, (off_t)(uintptr_t)addr, &data,
1326 		    sizeof(int)) != sizeof(int))
1327 			error = ENOMEM;
1328 		else
1329 			CTR3(KTR_PTRACE, "PT_WRITE: pid %d: %p <= %#x",
1330 			    p->p_pid, addr, data);
1331 		PROC_LOCK(p);
1332 		break;
1333 
1334 	case PT_READ_I:
1335 	case PT_READ_D:
1336 		PROC_UNLOCK(p);
1337 		error = tmp = 0;
1338 		if (proc_readmem(td, p, (off_t)(uintptr_t)addr, &tmp,
1339 		    sizeof(int)) != sizeof(int))
1340 			error = ENOMEM;
1341 		else
1342 			CTR3(KTR_PTRACE, "PT_READ: pid %d: %p >= %#x",
1343 			    p->p_pid, addr, tmp);
1344 		td->td_retval[0] = tmp;
1345 		PROC_LOCK(p);
1346 		break;
1347 
1348 	case PT_IO:
1349 		piod = addr;
1350 		iov.iov_base = piod->piod_addr;
1351 		iov.iov_len = piod->piod_len;
1352 		uio.uio_offset = (off_t)(uintptr_t)piod->piod_offs;
1353 		uio.uio_resid = piod->piod_len;
1354 		uio.uio_iov = &iov;
1355 		uio.uio_iovcnt = 1;
1356 		uio.uio_segflg = UIO_USERSPACE;
1357 		uio.uio_td = td;
1358 		switch (piod->piod_op) {
1359 		case PIOD_READ_D:
1360 		case PIOD_READ_I:
1361 			CTR3(KTR_PTRACE, "PT_IO: pid %d: READ (%p, %#x)",
1362 			    p->p_pid, (uintptr_t)uio.uio_offset, uio.uio_resid);
1363 			uio.uio_rw = UIO_READ;
1364 			break;
1365 		case PIOD_WRITE_D:
1366 		case PIOD_WRITE_I:
1367 			CTR3(KTR_PTRACE, "PT_IO: pid %d: WRITE (%p, %#x)",
1368 			    p->p_pid, (uintptr_t)uio.uio_offset, uio.uio_resid);
1369 			td2->td_dbgflags |= TDB_USERWR;
1370 			uio.uio_rw = UIO_WRITE;
1371 			break;
1372 		default:
1373 			error = EINVAL;
1374 			goto out;
1375 		}
1376 		PROC_UNLOCK(p);
1377 		error = proc_rwmem(p, &uio);
1378 		piod->piod_len -= uio.uio_resid;
1379 		PROC_LOCK(p);
1380 		break;
1381 
1382 	case PT_KILL:
1383 		CTR1(KTR_PTRACE, "PT_KILL: pid %d", p->p_pid);
1384 		data = SIGKILL;
1385 		goto sendsig;	/* in PT_CONTINUE above */
1386 
1387 	case PT_SETREGS:
1388 		CTR2(KTR_PTRACE, "PT_SETREGS: tid %d (pid %d)", td2->td_tid,
1389 		    p->p_pid);
1390 		td2->td_dbgflags |= TDB_USERWR;
1391 		error = PROC_WRITE(regs, td2, addr);
1392 		break;
1393 
1394 	case PT_GETREGS:
1395 		CTR2(KTR_PTRACE, "PT_GETREGS: tid %d (pid %d)", td2->td_tid,
1396 		    p->p_pid);
1397 		error = PROC_READ(regs, td2, addr);
1398 		break;
1399 
1400 	case PT_SETFPREGS:
1401 		CTR2(KTR_PTRACE, "PT_SETFPREGS: tid %d (pid %d)", td2->td_tid,
1402 		    p->p_pid);
1403 		td2->td_dbgflags |= TDB_USERWR;
1404 		error = PROC_WRITE(fpregs, td2, addr);
1405 		break;
1406 
1407 	case PT_GETFPREGS:
1408 		CTR2(KTR_PTRACE, "PT_GETFPREGS: tid %d (pid %d)", td2->td_tid,
1409 		    p->p_pid);
1410 		error = PROC_READ(fpregs, td2, addr);
1411 		break;
1412 
1413 	case PT_SETDBREGS:
1414 		CTR2(KTR_PTRACE, "PT_SETDBREGS: tid %d (pid %d)", td2->td_tid,
1415 		    p->p_pid);
1416 		td2->td_dbgflags |= TDB_USERWR;
1417 		error = PROC_WRITE(dbregs, td2, addr);
1418 		break;
1419 
1420 	case PT_GETDBREGS:
1421 		CTR2(KTR_PTRACE, "PT_GETDBREGS: tid %d (pid %d)", td2->td_tid,
1422 		    p->p_pid);
1423 		error = PROC_READ(dbregs, td2, addr);
1424 		break;
1425 
1426 	case PT_SETREGSET:
1427 		CTR2(KTR_PTRACE, "PT_SETREGSET: tid %d (pid %d)", td2->td_tid,
1428 		    p->p_pid);
1429 		error = proc_write_regset(td2, data, addr);
1430 		break;
1431 
1432 	case PT_GETREGSET:
1433 		CTR2(KTR_PTRACE, "PT_GETREGSET: tid %d (pid %d)", td2->td_tid,
1434 		    p->p_pid);
1435 		error = proc_read_regset(td2, data, addr);
1436 		break;
1437 
1438 	case PT_LWPINFO:
1439 		if (data <= 0 || data > sizeof(*pl)) {
1440 			error = EINVAL;
1441 			break;
1442 		}
1443 		pl = addr;
1444 		bzero(pl, sizeof(*pl));
1445 		pl->pl_lwpid = td2->td_tid;
1446 		pl->pl_event = PL_EVENT_NONE;
1447 		pl->pl_flags = 0;
1448 		if (td2->td_dbgflags & TDB_XSIG) {
1449 			pl->pl_event = PL_EVENT_SIGNAL;
1450 			if (td2->td_si.si_signo != 0 &&
1451 			    data >= offsetof(struct ptrace_lwpinfo, pl_siginfo)
1452 			    + sizeof(pl->pl_siginfo)){
1453 				pl->pl_flags |= PL_FLAG_SI;
1454 				pl->pl_siginfo = td2->td_si;
1455 			}
1456 		}
1457 		if (td2->td_dbgflags & TDB_SCE)
1458 			pl->pl_flags |= PL_FLAG_SCE;
1459 		else if (td2->td_dbgflags & TDB_SCX)
1460 			pl->pl_flags |= PL_FLAG_SCX;
1461 		if (td2->td_dbgflags & TDB_EXEC)
1462 			pl->pl_flags |= PL_FLAG_EXEC;
1463 		if (td2->td_dbgflags & TDB_FORK) {
1464 			pl->pl_flags |= PL_FLAG_FORKED;
1465 			pl->pl_child_pid = td2->td_dbg_forked;
1466 			if (td2->td_dbgflags & TDB_VFORK)
1467 				pl->pl_flags |= PL_FLAG_VFORKED;
1468 		} else if ((td2->td_dbgflags & (TDB_SCX | TDB_VFORK)) ==
1469 		    TDB_VFORK)
1470 			pl->pl_flags |= PL_FLAG_VFORK_DONE;
1471 		if (td2->td_dbgflags & TDB_CHILD)
1472 			pl->pl_flags |= PL_FLAG_CHILD;
1473 		if (td2->td_dbgflags & TDB_BORN)
1474 			pl->pl_flags |= PL_FLAG_BORN;
1475 		if (td2->td_dbgflags & TDB_EXIT)
1476 			pl->pl_flags |= PL_FLAG_EXITED;
1477 		pl->pl_sigmask = td2->td_sigmask;
1478 		pl->pl_siglist = td2->td_siglist;
1479 		strcpy(pl->pl_tdname, td2->td_name);
1480 		if ((td2->td_dbgflags & (TDB_SCE | TDB_SCX)) != 0) {
1481 			pl->pl_syscall_code = td2->td_sa.code;
1482 			pl->pl_syscall_narg = td2->td_sa.callp->sy_narg;
1483 		} else {
1484 			pl->pl_syscall_code = 0;
1485 			pl->pl_syscall_narg = 0;
1486 		}
1487 		CTR6(KTR_PTRACE,
1488     "PT_LWPINFO: tid %d (pid %d) event %d flags %#x child pid %d syscall %d",
1489 		    td2->td_tid, p->p_pid, pl->pl_event, pl->pl_flags,
1490 		    pl->pl_child_pid, pl->pl_syscall_code);
1491 		break;
1492 
1493 	case PT_GETNUMLWPS:
1494 		CTR2(KTR_PTRACE, "PT_GETNUMLWPS: pid %d: %d threads", p->p_pid,
1495 		    p->p_numthreads);
1496 		td->td_retval[0] = p->p_numthreads;
1497 		break;
1498 
1499 	case PT_GETLWPLIST:
1500 		CTR3(KTR_PTRACE, "PT_GETLWPLIST: pid %d: data %d, actual %d",
1501 		    p->p_pid, data, p->p_numthreads);
1502 		if (data <= 0) {
1503 			error = EINVAL;
1504 			break;
1505 		}
1506 		num = imin(p->p_numthreads, data);
1507 		PROC_UNLOCK(p);
1508 		buf = malloc(num * sizeof(lwpid_t), M_TEMP, M_WAITOK);
1509 		tmp = 0;
1510 		PROC_LOCK(p);
1511 		FOREACH_THREAD_IN_PROC(p, td2) {
1512 			if (tmp >= num)
1513 				break;
1514 			buf[tmp++] = td2->td_tid;
1515 		}
1516 		PROC_UNLOCK(p);
1517 		error = copyout(buf, addr, tmp * sizeof(lwpid_t));
1518 		free(buf, M_TEMP);
1519 		if (!error)
1520 			td->td_retval[0] = tmp;
1521 		PROC_LOCK(p);
1522 		break;
1523 
1524 	case PT_VM_TIMESTAMP:
1525 		CTR2(KTR_PTRACE, "PT_VM_TIMESTAMP: pid %d: timestamp %d",
1526 		    p->p_pid, p->p_vmspace->vm_map.timestamp);
1527 		td->td_retval[0] = p->p_vmspace->vm_map.timestamp;
1528 		break;
1529 
1530 	case PT_VM_ENTRY:
1531 		PROC_UNLOCK(p);
1532 		error = ptrace_vm_entry(td, p, addr);
1533 		PROC_LOCK(p);
1534 		break;
1535 
1536 	case PT_COREDUMP:
1537 		pc = addr;
1538 		CTR2(KTR_PTRACE, "PT_COREDUMP: pid %d, fd %d",
1539 		    p->p_pid, pc->pc_fd);
1540 
1541 		if ((pc->pc_flags & ~(PC_COMPRESS | PC_ALL)) != 0) {
1542 			error = EINVAL;
1543 			break;
1544 		}
1545 		PROC_UNLOCK(p);
1546 
1547 		tcq = malloc(sizeof(*tcq), M_TEMP, M_WAITOK | M_ZERO);
1548 		fp = NULL;
1549 		error = fget_write(td, pc->pc_fd, &cap_write_rights, &fp);
1550 		if (error != 0)
1551 			goto coredump_cleanup_nofp;
1552 		if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VREG) {
1553 			error = EPIPE;
1554 			goto coredump_cleanup;
1555 		}
1556 
1557 		PROC_LOCK(p);
1558 		error = proc_can_ptrace(td, p);
1559 		if (error != 0)
1560 			goto coredump_cleanup_locked;
1561 
1562 		td2 = ptrace_sel_coredump_thread(p);
1563 		if (td2 == NULL) {
1564 			error = EBUSY;
1565 			goto coredump_cleanup_locked;
1566 		}
1567 		KASSERT((td2->td_dbgflags & TDB_COREDUMPRQ) == 0,
1568 		    ("proc %d tid %d req coredump", p->p_pid, td2->td_tid));
1569 
1570 		tcq->tc_vp = fp->f_vnode;
1571 		tcq->tc_limit = pc->pc_limit == 0 ? OFF_MAX : pc->pc_limit;
1572 		tcq->tc_flags = SVC_PT_COREDUMP;
1573 		if ((pc->pc_flags & PC_COMPRESS) == 0)
1574 			tcq->tc_flags |= SVC_NOCOMPRESS;
1575 		if ((pc->pc_flags & PC_ALL) != 0)
1576 			tcq->tc_flags |= SVC_ALL;
1577 		td2->td_coredump = tcq;
1578 		td2->td_dbgflags |= TDB_COREDUMPRQ;
1579 		thread_run_flash(td2);
1580 		while ((td2->td_dbgflags & TDB_COREDUMPRQ) != 0)
1581 			msleep(p, &p->p_mtx, PPAUSE, "crdmp", 0);
1582 		error = tcq->tc_error;
1583 coredump_cleanup_locked:
1584 		PROC_UNLOCK(p);
1585 coredump_cleanup:
1586 		fdrop(fp, td);
1587 coredump_cleanup_nofp:
1588 		free(tcq, M_TEMP);
1589 		PROC_LOCK(p);
1590 		break;
1591 
1592 	default:
1593 #ifdef __HAVE_PTRACE_MACHDEP
1594 		if (req >= PT_FIRSTMACH) {
1595 			PROC_UNLOCK(p);
1596 			error = cpu_ptrace(td2, req, addr, data);
1597 			PROC_LOCK(p);
1598 		} else
1599 #endif
1600 			/* Unknown request. */
1601 			error = EINVAL;
1602 		break;
1603 	}
1604 out:
1605 	/* Drop our hold on this process now that the request has completed. */
1606 	_PRELE(p);
1607 fail:
1608 	if (p2_req_set) {
1609 		if ((p->p_flag2 & P2_PTRACEREQ) != 0)
1610 			wakeup(&p->p_flag2);
1611 		p->p_flag2 &= ~P2_PTRACEREQ;
1612 	}
1613 	PROC_UNLOCK(p);
1614 	if (proctree_locked)
1615 		sx_xunlock(&proctree_lock);
1616 	return (error);
1617 }
1618 #undef PROC_READ
1619 #undef PROC_WRITE
1620