xref: /freebsd/sys/kern/kern_ktrace.c (revision 245157fd8a382c3989075789ee98582665f3b31d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2005 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "opt_ktrace.h"
35 
36 #define	EXTERR_CATEGORY	EXTERR_KTRACE
37 #include <sys/systm.h>
38 #include <sys/capsicum.h>
39 #include <sys/exterrvar.h>
40 #include <sys/fcntl.h>
41 #include <sys/kernel.h>
42 #include <sys/kthread.h>
43 #include <sys/ktrace.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/namei.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/socket.h>
53 #include <sys/stat.h>
54 #include <sys/sx.h>
55 #include <sys/sysctl.h>
56 #include <sys/sysent.h>
57 #include <sys/syslog.h>
58 #include <sys/sysproto.h>
59 #include <sys/unistd.h>
60 #include <sys/vnode.h>
61 
62 #include <security/mac/mac_framework.h>
63 
64 /*
65  * The ktrace facility allows the tracing of certain key events in user space
66  * processes, such as system calls, signal delivery, context switches, and
67  * user generated events using utrace(2).  It works by streaming event
68  * records and data to a vnode associated with the process using the
69  * ktrace(2) system call.  In general, records can be written directly from
70  * the context that generates the event.  One important exception to this is
71  * during a context switch, where sleeping is not permitted.  To handle this
72  * case, trace events are generated using in-kernel ktr_request records, and
73  * then delivered to disk at a convenient moment -- either immediately, the
74  * next traceable event, at system call return, or at process exit.
75  *
76  * When dealing with multiple threads or processes writing to the same event
77  * log, ordering guarantees are weak: specifically, if an event has multiple
78  * records (i.e., system call enter and return), they may be interlaced with
79  * records from another event.  Process and thread ID information is provided
80  * in the record, and user applications can de-interlace events if required.
81  */
82 
83 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
84 
85 #ifdef KTRACE
86 
87 FEATURE(ktrace, "Kernel support for system-call tracing");
88 
89 #ifndef KTRACE_REQUEST_POOL
90 #define	KTRACE_REQUEST_POOL	100
91 #endif
92 
93 struct ktr_request {
94 	struct	ktr_header ktr_header;
95 	void	*ktr_buffer;
96 	union {
97 		struct	ktr_proc_ctor ktr_proc_ctor;
98 		struct	ktr_cap_fail ktr_cap_fail;
99 		struct	ktr_syscall ktr_syscall;
100 		struct	ktr_sysret ktr_sysret;
101 		struct	ktr_genio ktr_genio;
102 		struct	ktr_psig ktr_psig;
103 		struct	ktr_csw ktr_csw;
104 		struct	ktr_fault ktr_fault;
105 		struct	ktr_faultend ktr_faultend;
106 		struct  ktr_struct_array ktr_struct_array;
107 		struct	ktr_exterr ktr_exterr;
108 	} ktr_data;
109 	STAILQ_ENTRY(ktr_request) ktr_list;
110 };
111 
112 static const int data_lengths[] = {
113 	[KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
114 	[KTR_SYSRET] = sizeof(struct ktr_sysret),
115 	[KTR_NAMEI] = 0,
116 	[KTR_GENIO] = sizeof(struct ktr_genio),
117 	[KTR_PSIG] = sizeof(struct ktr_psig),
118 	[KTR_CSW] = sizeof(struct ktr_csw),
119 	[KTR_USER] = 0,
120 	[KTR_STRUCT] = 0,
121 	[KTR_SYSCTL] = 0,
122 	[KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
123 	[KTR_PROCDTOR] = 0,
124 	[KTR_CAPFAIL] = sizeof(struct ktr_cap_fail),
125 	[KTR_FAULT] = sizeof(struct ktr_fault),
126 	[KTR_FAULTEND] = sizeof(struct ktr_faultend),
127 	[KTR_STRUCT_ARRAY] = sizeof(struct ktr_struct_array),
128 	[KTR_ARGS] = 0,
129 	[KTR_ENVS] = 0,
130 	[KTR_EXTERR] = sizeof(struct ktr_exterr),
131 };
132 
133 static STAILQ_HEAD(, ktr_request) ktr_free;
134 
135 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
136     "KTRACE options");
137 
138 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
139 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
140 
141 u_int ktr_geniosize = PAGE_SIZE;
142 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RWTUN, &ktr_geniosize,
143     0, "Maximum size of genio event payload");
144 
145 /*
146  * Allow to not to send signal to traced process, in which context the
147  * ktr record is written.  The limit is applied from the process that
148  * set up ktrace, so killing the traced process is not completely fair.
149  */
150 int ktr_filesize_limit_signal = 0;
151 SYSCTL_INT(_kern_ktrace, OID_AUTO, filesize_limit_signal, CTLFLAG_RWTUN,
152     &ktr_filesize_limit_signal, 0,
153     "Send SIGXFSZ to the traced process when the log size limit is exceeded");
154 
155 static int print_message = 1;
156 static struct mtx ktrace_mtx;
157 static struct sx ktrace_sx;
158 
159 struct ktr_io_params {
160 	struct vnode	*vp;
161 	struct ucred	*cr;
162 	off_t		lim;
163 	u_int		refs;
164 };
165 
166 static void ktrace_init(void *dummy);
167 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
168 static u_int ktrace_resize_pool(u_int oldsize, u_int newsize);
169 static struct ktr_request *ktr_getrequest_entered(struct thread *td, int type);
170 static struct ktr_request *ktr_getrequest(int type);
171 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
172 static struct ktr_io_params *ktr_freeproc(struct proc *p);
173 static void ktr_freerequest(struct ktr_request *req);
174 static void ktr_freerequest_locked(struct ktr_request *req);
175 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
176 static int ktrcanset(struct thread *,struct proc *);
177 static int ktrsetchildren(struct thread *, struct proc *, int, int,
178     struct ktr_io_params *);
179 static int ktrops(struct thread *, struct proc *, int, int,
180     struct ktr_io_params *);
181 static void ktrprocctor_entered(struct thread *, struct proc *);
182 
183 /*
184  * ktrace itself generates events, such as context switches, which we do not
185  * wish to trace.  Maintain a flag, TDP_INKTRACE, on each thread to determine
186  * whether or not it is in a region where tracing of events should be
187  * suppressed.
188  */
189 static void
ktrace_enter(struct thread * td)190 ktrace_enter(struct thread *td)
191 {
192 
193 	KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
194 	td->td_pflags |= TDP_INKTRACE;
195 }
196 
197 static void
ktrace_exit(struct thread * td)198 ktrace_exit(struct thread *td)
199 {
200 
201 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
202 	td->td_pflags &= ~TDP_INKTRACE;
203 }
204 
205 static void
ktrace_assert(struct thread * td)206 ktrace_assert(struct thread *td)
207 {
208 
209 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
210 }
211 
212 static void
ast_ktrace(struct thread * td,int tda __unused)213 ast_ktrace(struct thread *td, int tda __unused)
214 {
215 	KTRUSERRET(td);
216 }
217 
218 static void
ktrace_init(void * dummy)219 ktrace_init(void *dummy)
220 {
221 	struct ktr_request *req;
222 	int i;
223 
224 	mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
225 	sx_init(&ktrace_sx, "ktrace_sx");
226 	STAILQ_INIT(&ktr_free);
227 	for (i = 0; i < ktr_requestpool; i++) {
228 		req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK |
229 		    M_ZERO);
230 		STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
231 	}
232 	ast_register(TDA_KTRACE, ASTR_ASTF_REQUIRED, 0, ast_ktrace);
233 }
234 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
235 
236 static int
sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)237 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
238 {
239 	struct thread *td;
240 	u_int newsize, oldsize, wantsize;
241 	int error;
242 
243 	/* Handle easy read-only case first to avoid warnings from GCC. */
244 	if (!req->newptr) {
245 		oldsize = ktr_requestpool;
246 		return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
247 	}
248 
249 	error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
250 	if (error)
251 		return (error);
252 	td = curthread;
253 	ktrace_enter(td);
254 	oldsize = ktr_requestpool;
255 	newsize = ktrace_resize_pool(oldsize, wantsize);
256 	ktrace_exit(td);
257 	error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
258 	if (error)
259 		return (error);
260 	if (wantsize > oldsize && newsize < wantsize)
261 		return (ENOSPC);
262 	return (0);
263 }
264 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool,
265     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &ktr_requestpool, 0,
266     sysctl_kern_ktrace_request_pool, "IU",
267     "Pool buffer size for ktrace(1)");
268 
269 static u_int
ktrace_resize_pool(u_int oldsize,u_int newsize)270 ktrace_resize_pool(u_int oldsize, u_int newsize)
271 {
272 	STAILQ_HEAD(, ktr_request) ktr_new;
273 	struct ktr_request *req;
274 	int bound;
275 
276 	print_message = 1;
277 	bound = newsize - oldsize;
278 	if (bound == 0)
279 		return (ktr_requestpool);
280 	if (bound < 0) {
281 		mtx_lock(&ktrace_mtx);
282 		/* Shrink pool down to newsize if possible. */
283 		while (bound++ < 0) {
284 			req = STAILQ_FIRST(&ktr_free);
285 			if (req == NULL)
286 				break;
287 			STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
288 			ktr_requestpool--;
289 			free(req, M_KTRACE);
290 		}
291 	} else {
292 		/* Grow pool up to newsize. */
293 		STAILQ_INIT(&ktr_new);
294 		while (bound-- > 0) {
295 			req = malloc(sizeof(struct ktr_request), M_KTRACE,
296 			    M_WAITOK | M_ZERO);
297 			STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
298 		}
299 		mtx_lock(&ktrace_mtx);
300 		STAILQ_CONCAT(&ktr_free, &ktr_new);
301 		ktr_requestpool += (newsize - oldsize);
302 	}
303 	mtx_unlock(&ktrace_mtx);
304 	return (ktr_requestpool);
305 }
306 
307 /* ktr_getrequest() assumes that ktr_comm[] is the same size as td_name[]. */
308 CTASSERT(sizeof(((struct ktr_header *)NULL)->ktr_comm) ==
309     (sizeof((struct thread *)NULL)->td_name));
310 
311 static struct ktr_request *
ktr_getrequest_entered(struct thread * td,int type)312 ktr_getrequest_entered(struct thread *td, int type)
313 {
314 	struct ktr_request *req;
315 	struct proc *p = td->td_proc;
316 	int pm;
317 
318 	mtx_lock(&ktrace_mtx);
319 	if (!KTRCHECK(td, type)) {
320 		mtx_unlock(&ktrace_mtx);
321 		return (NULL);
322 	}
323 	req = STAILQ_FIRST(&ktr_free);
324 	if (req != NULL) {
325 		STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
326 		req->ktr_header.ktr_type = type;
327 		if (p->p_traceflag & KTRFAC_DROP) {
328 			req->ktr_header.ktr_type |= KTR_DROP;
329 			p->p_traceflag &= ~KTRFAC_DROP;
330 		}
331 		mtx_unlock(&ktrace_mtx);
332 		nanotime(&req->ktr_header.ktr_time);
333 		req->ktr_header.ktr_type |= KTR_VERSIONED;
334 		req->ktr_header.ktr_pid = p->p_pid;
335 		req->ktr_header.ktr_tid = td->td_tid;
336 		req->ktr_header.ktr_cpu = PCPU_GET(cpuid);
337 		req->ktr_header.ktr_version = KTR_VERSION1;
338 		bcopy(td->td_name, req->ktr_header.ktr_comm,
339 		    sizeof(req->ktr_header.ktr_comm));
340 		req->ktr_buffer = NULL;
341 		req->ktr_header.ktr_len = 0;
342 	} else {
343 		p->p_traceflag |= KTRFAC_DROP;
344 		pm = print_message;
345 		print_message = 0;
346 		mtx_unlock(&ktrace_mtx);
347 		if (pm)
348 			printf("Out of ktrace request objects.\n");
349 	}
350 	return (req);
351 }
352 
353 static struct ktr_request *
ktr_getrequest(int type)354 ktr_getrequest(int type)
355 {
356 	struct thread *td = curthread;
357 	struct ktr_request *req;
358 
359 	ktrace_enter(td);
360 	req = ktr_getrequest_entered(td, type);
361 	if (req == NULL)
362 		ktrace_exit(td);
363 
364 	return (req);
365 }
366 
367 /*
368  * Some trace generation environments don't permit direct access to VFS,
369  * such as during a context switch where sleeping is not allowed.  Under these
370  * circumstances, queue a request to the thread to be written asynchronously
371  * later.
372  */
373 static void
ktr_enqueuerequest(struct thread * td,struct ktr_request * req)374 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
375 {
376 	bool sched_ast;
377 
378 	mtx_lock(&ktrace_mtx);
379 	sched_ast = td->td_proc->p_ktrioparms != NULL;
380 	if (sched_ast)
381 		STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
382 	else
383 		ktr_freerequest_locked(req);
384 	mtx_unlock(&ktrace_mtx);
385 	if (sched_ast)
386 		ast_sched(td, TDA_KTRACE);
387 }
388 
389 /*
390  * Drain any pending ktrace records from the per-thread queue to disk.  This
391  * is used both internally before committing other records, and also on
392  * system call return.  We drain all the ones we can find at the time when
393  * drain is requested, but don't keep draining after that as those events
394  * may be approximately "after" the current event.
395  */
396 static void
ktr_drain(struct thread * td)397 ktr_drain(struct thread *td)
398 {
399 	struct ktr_request *queued_req;
400 	STAILQ_HEAD(, ktr_request) local_queue;
401 
402 	ktrace_assert(td);
403 	sx_assert(&ktrace_sx, SX_XLOCKED);
404 
405 	STAILQ_INIT(&local_queue);
406 
407 	if (!STAILQ_EMPTY_ATOMIC(&td->td_proc->p_ktr)) {
408 		mtx_lock(&ktrace_mtx);
409 		STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
410 		mtx_unlock(&ktrace_mtx);
411 
412 		while ((queued_req = STAILQ_FIRST(&local_queue))) {
413 			STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
414 			ktr_writerequest(td, queued_req);
415 			ktr_freerequest(queued_req);
416 		}
417 	}
418 }
419 
420 /*
421  * Submit a trace record for immediate commit to disk -- to be used only
422  * where entering VFS is OK.  First drain any pending records that may have
423  * been cached in the thread.
424  */
425 static void
ktr_submitrequest(struct thread * td,struct ktr_request * req)426 ktr_submitrequest(struct thread *td, struct ktr_request *req)
427 {
428 
429 	ktrace_assert(td);
430 
431 	sx_xlock(&ktrace_sx);
432 	ktr_drain(td);
433 	ktr_writerequest(td, req);
434 	ktr_freerequest(req);
435 	sx_xunlock(&ktrace_sx);
436 	ktrace_exit(td);
437 }
438 
439 static void
ktr_freerequest(struct ktr_request * req)440 ktr_freerequest(struct ktr_request *req)
441 {
442 
443 	mtx_lock(&ktrace_mtx);
444 	ktr_freerequest_locked(req);
445 	mtx_unlock(&ktrace_mtx);
446 }
447 
448 static void
ktr_freerequest_locked(struct ktr_request * req)449 ktr_freerequest_locked(struct ktr_request *req)
450 {
451 
452 	mtx_assert(&ktrace_mtx, MA_OWNED);
453 	if (req->ktr_buffer != NULL)
454 		free(req->ktr_buffer, M_KTRACE);
455 	STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
456 }
457 
458 static void
ktr_io_params_ref(struct ktr_io_params * kiop)459 ktr_io_params_ref(struct ktr_io_params *kiop)
460 {
461 	mtx_assert(&ktrace_mtx, MA_OWNED);
462 	kiop->refs++;
463 }
464 
465 static struct ktr_io_params *
ktr_io_params_rele(struct ktr_io_params * kiop)466 ktr_io_params_rele(struct ktr_io_params *kiop)
467 {
468 	mtx_assert(&ktrace_mtx, MA_OWNED);
469 	if (kiop == NULL)
470 		return (NULL);
471 	KASSERT(kiop->refs > 0, ("kiop ref == 0 %p", kiop));
472 	return (--(kiop->refs) == 0 ? kiop : NULL);
473 }
474 
475 void
ktr_io_params_free(struct ktr_io_params * kiop)476 ktr_io_params_free(struct ktr_io_params *kiop)
477 {
478 	if (kiop == NULL)
479 		return;
480 
481 	MPASS(kiop->refs == 0);
482 	vn_close(kiop->vp, FWRITE, kiop->cr, curthread);
483 	crfree(kiop->cr);
484 	free(kiop, M_KTRACE);
485 }
486 
487 static struct ktr_io_params *
ktr_io_params_alloc(struct thread * td,struct vnode * vp)488 ktr_io_params_alloc(struct thread *td, struct vnode *vp)
489 {
490 	struct ktr_io_params *res;
491 
492 	res = malloc(sizeof(struct ktr_io_params), M_KTRACE, M_WAITOK);
493 	res->vp = vp;
494 	res->cr = crhold(td->td_ucred);
495 	res->lim = lim_cur(td, RLIMIT_FSIZE);
496 	res->refs = 1;
497 	return (res);
498 }
499 
500 /*
501  * Disable tracing for a process and release all associated resources.
502  * The caller is responsible for releasing a reference on the returned
503  * vnode and credentials.
504  */
505 static struct ktr_io_params *
ktr_freeproc(struct proc * p)506 ktr_freeproc(struct proc *p)
507 {
508 	struct ktr_io_params *kiop;
509 	struct ktr_request *req;
510 
511 	PROC_LOCK_ASSERT(p, MA_OWNED);
512 	mtx_assert(&ktrace_mtx, MA_OWNED);
513 	kiop = ktr_io_params_rele(p->p_ktrioparms);
514 	p->p_ktrioparms = NULL;
515 	p->p_traceflag = 0;
516 	while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
517 		STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
518 		ktr_freerequest_locked(req);
519 	}
520 	return (kiop);
521 }
522 
523 struct vnode *
ktr_get_tracevp(struct proc * p,bool ref)524 ktr_get_tracevp(struct proc *p, bool ref)
525 {
526 	struct vnode *vp;
527 
528 	PROC_LOCK_ASSERT(p, MA_OWNED);
529 
530 	if (p->p_ktrioparms != NULL) {
531 		vp = p->p_ktrioparms->vp;
532 		if (ref)
533 			vrefact(vp);
534 	} else {
535 		vp = NULL;
536 	}
537 	return (vp);
538 }
539 
540 void
ktrsyscall(int code,int narg,syscallarg_t args[])541 ktrsyscall(int code, int narg, syscallarg_t args[])
542 {
543 	struct ktr_request *req;
544 	struct ktr_syscall *ktp;
545 	size_t buflen;
546 	char *buf = NULL;
547 
548 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
549 		return;
550 
551 	buflen = sizeof(register_t) * narg;
552 	if (buflen > 0) {
553 		buf = malloc(buflen, M_KTRACE, M_WAITOK);
554 		bcopy(args, buf, buflen);
555 	}
556 	req = ktr_getrequest(KTR_SYSCALL);
557 	if (req == NULL) {
558 		if (buf != NULL)
559 			free(buf, M_KTRACE);
560 		return;
561 	}
562 	ktp = &req->ktr_data.ktr_syscall;
563 	ktp->ktr_code = code;
564 	ktp->ktr_narg = narg;
565 	if (buflen > 0) {
566 		req->ktr_header.ktr_len = buflen;
567 		req->ktr_buffer = buf;
568 	}
569 	ktr_submitrequest(curthread, req);
570 }
571 
572 void
ktrdata(int type,const void * data,size_t len)573 ktrdata(int type, const void *data, size_t len)
574 {
575         struct ktr_request *req;
576         void *buf;
577 
578         if ((req = ktr_getrequest(type)) == NULL)
579                 return;
580         buf = malloc(len, M_KTRACE, M_WAITOK);
581         bcopy(data, buf, len);
582         req->ktr_header.ktr_len = len;
583         req->ktr_buffer = buf;
584         ktr_submitrequest(curthread, req);
585 }
586 
587 void
ktrsysret(int code,int error,register_t retval)588 ktrsysret(int code, int error, register_t retval)
589 {
590 	struct ktr_request *req;
591 	struct ktr_sysret *ktp;
592 
593 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
594 		return;
595 
596 	req = ktr_getrequest(KTR_SYSRET);
597 	if (req == NULL)
598 		return;
599 	ktp = &req->ktr_data.ktr_sysret;
600 	ktp->ktr_code = code;
601 	ktp->ktr_error = error;
602 	ktp->ktr_retval = ((error == 0) ? retval: 0);		/* what about val2 ? */
603 	ktr_submitrequest(curthread, req);
604 }
605 
606 /*
607  * When a setuid process execs, disable tracing.
608  *
609  * XXX: We toss any pending asynchronous records.
610  */
611 struct ktr_io_params *
ktrprocexec(struct proc * p)612 ktrprocexec(struct proc *p)
613 {
614 	struct ktr_io_params *kiop;
615 
616 	PROC_LOCK_ASSERT(p, MA_OWNED);
617 
618 	kiop = p->p_ktrioparms;
619 	if (kiop == NULL || priv_check_cred(kiop->cr, PRIV_DEBUG_DIFFCRED) == 0)
620 		return (NULL);
621 
622 	mtx_lock(&ktrace_mtx);
623 	kiop = ktr_freeproc(p);
624 	mtx_unlock(&ktrace_mtx);
625 	return (kiop);
626 }
627 
628 /*
629  * When a process exits, drain per-process asynchronous trace records
630  * and disable tracing.
631  */
632 void
ktrprocexit(struct thread * td)633 ktrprocexit(struct thread *td)
634 {
635 	struct ktr_request *req;
636 	struct proc *p;
637 	struct ktr_io_params *kiop;
638 
639 	p = td->td_proc;
640 	if (p->p_traceflag == 0)
641 		return;
642 
643 	ktrace_enter(td);
644 	req = ktr_getrequest_entered(td, KTR_PROCDTOR);
645 	if (req != NULL)
646 		ktr_enqueuerequest(td, req);
647 	sx_xlock(&ktrace_sx);
648 	ktr_drain(td);
649 	sx_xunlock(&ktrace_sx);
650 	PROC_LOCK(p);
651 	mtx_lock(&ktrace_mtx);
652 	kiop = ktr_freeproc(p);
653 	mtx_unlock(&ktrace_mtx);
654 	PROC_UNLOCK(p);
655 	ktr_io_params_free(kiop);
656 	ktrace_exit(td);
657 }
658 
659 static void
ktrprocctor_entered(struct thread * td,struct proc * p)660 ktrprocctor_entered(struct thread *td, struct proc *p)
661 {
662 	struct ktr_proc_ctor *ktp;
663 	struct ktr_request *req;
664 	struct thread *td2;
665 
666 	ktrace_assert(td);
667 	td2 = FIRST_THREAD_IN_PROC(p);
668 	req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
669 	if (req == NULL)
670 		return;
671 	ktp = &req->ktr_data.ktr_proc_ctor;
672 	ktp->sv_flags = p->p_sysent->sv_flags;
673 	ktr_enqueuerequest(td2, req);
674 }
675 
676 void
ktrprocctor(struct proc * p)677 ktrprocctor(struct proc *p)
678 {
679 	struct thread *td = curthread;
680 
681 	if ((p->p_traceflag & KTRFAC_MASK) == 0)
682 		return;
683 
684 	ktrace_enter(td);
685 	ktrprocctor_entered(td, p);
686 	ktrace_exit(td);
687 }
688 
689 /*
690  * When a process forks, enable tracing in the new process if needed.
691  */
692 void
ktrprocfork(struct proc * p1,struct proc * p2)693 ktrprocfork(struct proc *p1, struct proc *p2)
694 {
695 
696 	MPASS(p2->p_ktrioparms == NULL);
697 	MPASS(p2->p_traceflag == 0);
698 
699 	if (p1->p_traceflag == 0)
700 		return;
701 
702 	PROC_LOCK(p1);
703 	mtx_lock(&ktrace_mtx);
704 	if (p1->p_traceflag & KTRFAC_INHERIT) {
705 		p2->p_traceflag = p1->p_traceflag;
706 		if ((p2->p_ktrioparms = p1->p_ktrioparms) != NULL)
707 			p1->p_ktrioparms->refs++;
708 	}
709 	mtx_unlock(&ktrace_mtx);
710 	PROC_UNLOCK(p1);
711 
712 	ktrprocctor(p2);
713 }
714 
715 /*
716  * When a thread returns, drain any asynchronous records generated by the
717  * system call.
718  */
719 void
ktruserret(struct thread * td)720 ktruserret(struct thread *td)
721 {
722 
723 	ktrace_enter(td);
724 	sx_xlock(&ktrace_sx);
725 	ktr_drain(td);
726 	sx_xunlock(&ktrace_sx);
727 	ktrace_exit(td);
728 }
729 
730 void
ktrnamei(const char * path)731 ktrnamei(const char *path)
732 {
733 	struct ktr_request *req;
734 	int namelen;
735 	char *buf = NULL;
736 
737 	namelen = strlen(path);
738 	if (namelen > 0) {
739 		buf = malloc(namelen, M_KTRACE, M_WAITOK);
740 		bcopy(path, buf, namelen);
741 	}
742 	req = ktr_getrequest(KTR_NAMEI);
743 	if (req == NULL) {
744 		if (buf != NULL)
745 			free(buf, M_KTRACE);
746 		return;
747 	}
748 	if (namelen > 0) {
749 		req->ktr_header.ktr_len = namelen;
750 		req->ktr_buffer = buf;
751 	}
752 	ktr_submitrequest(curthread, req);
753 }
754 
755 void
ktrsysctl(int * name,u_int namelen)756 ktrsysctl(int *name, u_int namelen)
757 {
758 	struct ktr_request *req;
759 	u_int mib[CTL_MAXNAME + 2];
760 	char *mibname;
761 	size_t mibnamelen;
762 	int error;
763 
764 	/* Lookup name of mib. */
765 	KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
766 	mib[0] = 0;
767 	mib[1] = 1;
768 	bcopy(name, mib + 2, namelen * sizeof(*name));
769 	mibnamelen = 128;
770 	mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
771 	error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
772 	    NULL, 0, &mibnamelen, 0);
773 	if (error) {
774 		free(mibname, M_KTRACE);
775 		return;
776 	}
777 	req = ktr_getrequest(KTR_SYSCTL);
778 	if (req == NULL) {
779 		free(mibname, M_KTRACE);
780 		return;
781 	}
782 	req->ktr_header.ktr_len = mibnamelen;
783 	req->ktr_buffer = mibname;
784 	ktr_submitrequest(curthread, req);
785 }
786 
787 void
ktrgenio(int fd,enum uio_rw rw,struct uio * uio,int error)788 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
789 {
790 	struct ktr_request *req;
791 	struct ktr_genio *ktg;
792 	int datalen;
793 	char *buf;
794 
795 	if (error != 0 && (rw == UIO_READ || error == EFAULT)) {
796 		freeuio(uio);
797 		return;
798 	}
799 	uio->uio_offset = 0;
800 	uio->uio_rw = UIO_WRITE;
801 	datalen = MIN(uio->uio_resid, ktr_geniosize);
802 	buf = malloc(datalen, M_KTRACE, M_WAITOK);
803 	error = uiomove(buf, datalen, uio);
804 	freeuio(uio);
805 	if (error) {
806 		free(buf, M_KTRACE);
807 		return;
808 	}
809 	req = ktr_getrequest(KTR_GENIO);
810 	if (req == NULL) {
811 		free(buf, M_KTRACE);
812 		return;
813 	}
814 	ktg = &req->ktr_data.ktr_genio;
815 	ktg->ktr_fd = fd;
816 	ktg->ktr_rw = rw;
817 	req->ktr_header.ktr_len = datalen;
818 	req->ktr_buffer = buf;
819 	ktr_submitrequest(curthread, req);
820 }
821 
822 void
ktrpsig(int sig,sig_t action,sigset_t * mask,int code)823 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
824 {
825 	struct thread *td = curthread;
826 	struct ktr_request *req;
827 	struct ktr_psig	*kp;
828 
829 	req = ktr_getrequest(KTR_PSIG);
830 	if (req == NULL)
831 		return;
832 	kp = &req->ktr_data.ktr_psig;
833 	kp->signo = (char)sig;
834 	kp->action = action;
835 	kp->mask = *mask;
836 	kp->code = code;
837 	ktr_enqueuerequest(td, req);
838 	ktrace_exit(td);
839 }
840 
841 static void
ktrcsw_impl(int out,int user,const char * wmesg,const struct timespec * tv)842 ktrcsw_impl(int out, int user, const char *wmesg, const struct timespec *tv)
843 {
844 	struct thread *td = curthread;
845 	struct ktr_request *req;
846 	struct ktr_csw *kc;
847 
848 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
849 		return;
850 
851 	req = ktr_getrequest(KTR_CSW);
852 	if (req == NULL)
853 		return;
854 	kc = &req->ktr_data.ktr_csw;
855 	kc->out = out;
856 	kc->user = user;
857 	if (tv != NULL)
858 		req->ktr_header.ktr_time = *tv;
859 	if (wmesg != NULL)
860 		strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
861 	else
862 		bzero(kc->wmesg, sizeof(kc->wmesg));
863 	ktr_enqueuerequest(td, req);
864 	ktrace_exit(td);
865 }
866 
867 void
ktrcsw(int out,int user,const char * wmesg)868 ktrcsw(int out, int user, const char *wmesg)
869 {
870 	ktrcsw_impl(out, user, wmesg, NULL);
871 }
872 
873 void
ktrcsw_out(const struct timespec * tv,const char * wmesg)874 ktrcsw_out(const struct timespec *tv, const char *wmesg)
875 {
876 	ktrcsw_impl(1, 0, wmesg, tv);
877 }
878 
879 void
ktrstruct(const char * name,const void * data,size_t datalen)880 ktrstruct(const char *name, const void *data, size_t datalen)
881 {
882 	struct ktr_request *req;
883 	char *buf;
884 	size_t buflen, namelen;
885 
886 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
887 		return;
888 
889 	if (data == NULL)
890 		datalen = 0;
891 	namelen = strlen(name) + 1;
892 	buflen = namelen + datalen;
893 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
894 	strcpy(buf, name);
895 	bcopy(data, buf + namelen, datalen);
896 	if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
897 		free(buf, M_KTRACE);
898 		return;
899 	}
900 	req->ktr_buffer = buf;
901 	req->ktr_header.ktr_len = buflen;
902 	ktr_submitrequest(curthread, req);
903 }
904 
905 void
ktrstruct_error(const char * name,const void * data,size_t datalen,int error)906 ktrstruct_error(const char *name, const void *data, size_t datalen, int error)
907 {
908 
909 	if (error == 0)
910 		ktrstruct(name, data, datalen);
911 }
912 
913 void
ktrstructarray(const char * name,enum uio_seg seg,const void * data,int num_items,size_t struct_size)914 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
915     int num_items, size_t struct_size)
916 {
917 	struct ktr_request *req;
918 	struct ktr_struct_array *ksa;
919 	char *buf;
920 	size_t buflen, datalen, namelen;
921 	int max_items;
922 
923 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
924 		return;
925 	if (num_items < 0)
926 		return;
927 
928 	/* Trim array length to genio size. */
929 	max_items = ktr_geniosize / struct_size;
930 	if (num_items > max_items) {
931 		if (max_items == 0)
932 			num_items = 1;
933 		else
934 			num_items = max_items;
935 	}
936 	datalen = num_items * struct_size;
937 
938 	if (data == NULL)
939 		datalen = 0;
940 
941 	namelen = strlen(name) + 1;
942 	buflen = namelen + datalen;
943 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
944 	strcpy(buf, name);
945 	if (seg == UIO_SYSSPACE)
946 		bcopy(data, buf + namelen, datalen);
947 	else {
948 		if (copyin(data, buf + namelen, datalen) != 0) {
949 			free(buf, M_KTRACE);
950 			return;
951 		}
952 	}
953 	if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
954 		free(buf, M_KTRACE);
955 		return;
956 	}
957 	ksa = &req->ktr_data.ktr_struct_array;
958 	ksa->struct_size = struct_size;
959 	req->ktr_buffer = buf;
960 	req->ktr_header.ktr_len = buflen;
961 	ktr_submitrequest(curthread, req);
962 }
963 
964 void
ktrcapfail(enum ktr_cap_violation type,const void * data)965 ktrcapfail(enum ktr_cap_violation type, const void *data)
966 {
967 	struct thread *td = curthread;
968 	struct ktr_request *req;
969 	struct ktr_cap_fail *kcf;
970 	union ktr_cap_data *kcd;
971 
972 	if (__predict_false(td->td_pflags & TDP_INKTRACE))
973 		return;
974 	if (type != CAPFAIL_SYSCALL &&
975 	    (td->td_sa.callp->sy_flags & SYF_CAPENABLED) == 0)
976 		return;
977 
978 	req = ktr_getrequest(KTR_CAPFAIL);
979 	if (req == NULL)
980 		return;
981 	kcf = &req->ktr_data.ktr_cap_fail;
982 	kcf->cap_type = type;
983 	kcf->cap_code = td->td_sa.code;
984 	kcf->cap_svflags = td->td_proc->p_sysent->sv_flags;
985 	if (data != NULL) {
986 		kcd = &kcf->cap_data;
987 		switch (type) {
988 		case CAPFAIL_NOTCAPABLE:
989 		case CAPFAIL_INCREASE:
990 			kcd->cap_needed = *(const cap_rights_t *)data;
991 			kcd->cap_held = *((const cap_rights_t *)data + 1);
992 			break;
993 		case CAPFAIL_SYSCALL:
994 		case CAPFAIL_SIGNAL:
995 		case CAPFAIL_PROTO:
996 			kcd->cap_int = *(const int *)data;
997 			break;
998 		case CAPFAIL_SOCKADDR: {
999 			size_t len;
1000 
1001 			len = MIN(((const struct sockaddr *)data)->sa_len,
1002 			    sizeof(kcd->cap_sockaddr));
1003 			memset(&kcd->cap_sockaddr, 0,
1004 			    sizeof(kcd->cap_sockaddr));
1005 			memcpy(&kcd->cap_sockaddr, data, len);
1006 			break;
1007 		}
1008 		case CAPFAIL_NAMEI:
1009 			strlcpy(kcd->cap_path, data, MAXPATHLEN);
1010 			break;
1011 		case CAPFAIL_CPUSET:
1012 		default:
1013 			break;
1014 		}
1015 	}
1016 	ktr_enqueuerequest(td, req);
1017 	ktrace_exit(td);
1018 }
1019 
1020 void
ktrfault(vm_offset_t vaddr,int type)1021 ktrfault(vm_offset_t vaddr, int type)
1022 {
1023 	struct thread *td = curthread;
1024 	struct ktr_request *req;
1025 	struct ktr_fault *kf;
1026 
1027 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
1028 		return;
1029 
1030 	req = ktr_getrequest(KTR_FAULT);
1031 	if (req == NULL)
1032 		return;
1033 	kf = &req->ktr_data.ktr_fault;
1034 	kf->vaddr = vaddr;
1035 	kf->type = type;
1036 	ktr_enqueuerequest(td, req);
1037 	ktrace_exit(td);
1038 }
1039 
1040 void
ktrfaultend(int result)1041 ktrfaultend(int result)
1042 {
1043 	struct thread *td = curthread;
1044 	struct ktr_request *req;
1045 	struct ktr_faultend *kf;
1046 
1047 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
1048 		return;
1049 
1050 	req = ktr_getrequest(KTR_FAULTEND);
1051 	if (req == NULL)
1052 		return;
1053 	kf = &req->ktr_data.ktr_faultend;
1054 	kf->result = result;
1055 	ktr_enqueuerequest(td, req);
1056 	ktrace_exit(td);
1057 }
1058 
1059 void
ktrexterr(struct thread * td)1060 ktrexterr(struct thread *td)
1061 {
1062 	struct ktr_request *req;
1063 	struct ktr_exterr *ktre;
1064 
1065 	if (!KTRPOINT(td, KTR_EXTERR))
1066 		return;
1067 
1068 	req = ktr_getrequest(KTR_EXTERR);
1069 	if (req == NULL)
1070 		return;
1071 	ktre = &req->ktr_data.ktr_exterr;
1072 	if (exterr_to_ue(td, &ktre->ue) == 0)
1073 		ktr_enqueuerequest(td, req);
1074 	else
1075 		ktr_freerequest(req);
1076 	ktrace_exit(td);
1077 }
1078 #endif /* KTRACE */
1079 
1080 #ifndef KTRACE
1081 void
ktrexterr(struct thread * td __unused)1082 ktrexterr(struct thread *td __unused)
1083 {
1084 }
1085 #endif
1086 
1087 /* Interface and common routines */
1088 
1089 #ifndef _SYS_SYSPROTO_H_
1090 struct ktrace_args {
1091 	char	*fname;
1092 	int	ops;
1093 	int	facs;
1094 	int	pid;
1095 };
1096 #endif
1097 /* ARGSUSED */
1098 int
sys_ktrace(struct thread * td,struct ktrace_args * uap)1099 sys_ktrace(struct thread *td, struct ktrace_args *uap)
1100 {
1101 #ifdef KTRACE
1102 	struct vnode *vp = NULL;
1103 	struct proc *p;
1104 	struct pgrp *pg;
1105 	int facs = uap->facs & ~KTRFAC_ROOT;
1106 	int ops = KTROP(uap->ops);
1107 	int descend = uap->ops & KTRFLAG_DESCEND;
1108 	int ret = 0;
1109 	int flags, error = 0;
1110 	struct nameidata nd;
1111 	struct ktr_io_params *kiop, *old_kiop;
1112 
1113 	/*
1114 	 * Need something to (un)trace.
1115 	 */
1116 	if (ops != KTROP_CLEARFILE && facs == 0)
1117 		return (EINVAL);
1118 
1119 	kiop = NULL;
1120 	if (ops != KTROP_CLEAR) {
1121 		/*
1122 		 * an operation which requires a file argument.
1123 		 */
1124 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname);
1125 		flags = FREAD | FWRITE | O_NOFOLLOW;
1126 		error = vn_open(&nd, &flags, 0, NULL);
1127 		if (error)
1128 			return (error);
1129 		NDFREE_PNBUF(&nd);
1130 		vp = nd.ni_vp;
1131 		VOP_UNLOCK(vp);
1132 		if (vp->v_type != VREG) {
1133 			(void)vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
1134 			return (EACCES);
1135 		}
1136 		kiop = ktr_io_params_alloc(td, vp);
1137 	}
1138 
1139 	/*
1140 	 * Clear all uses of the tracefile.
1141 	 */
1142 	ktrace_enter(td);
1143 	if (ops == KTROP_CLEARFILE) {
1144 restart:
1145 		sx_slock(&allproc_lock);
1146 		FOREACH_PROC_IN_SYSTEM(p) {
1147 			old_kiop = NULL;
1148 			PROC_LOCK(p);
1149 			if (p->p_ktrioparms != NULL &&
1150 			    p->p_ktrioparms->vp == vp) {
1151 				if (ktrcanset(td, p)) {
1152 					mtx_lock(&ktrace_mtx);
1153 					old_kiop = ktr_freeproc(p);
1154 					mtx_unlock(&ktrace_mtx);
1155 				} else
1156 					error = EPERM;
1157 			}
1158 			PROC_UNLOCK(p);
1159 			if (old_kiop != NULL) {
1160 				sx_sunlock(&allproc_lock);
1161 				ktr_io_params_free(old_kiop);
1162 				goto restart;
1163 			}
1164 		}
1165 		sx_sunlock(&allproc_lock);
1166 		goto done;
1167 	}
1168 	/*
1169 	 * do it
1170 	 */
1171 	sx_slock(&proctree_lock);
1172 	if (uap->pid < 0) {
1173 		/*
1174 		 * by process group
1175 		 */
1176 		pg = pgfind(-uap->pid);
1177 		if (pg == NULL) {
1178 			sx_sunlock(&proctree_lock);
1179 			error = ESRCH;
1180 			goto done;
1181 		}
1182 
1183 		/*
1184 		 * ktrops() may call vrele(). Lock pg_members
1185 		 * by the proctree_lock rather than pg_mtx.
1186 		 */
1187 		PGRP_UNLOCK(pg);
1188 		if (LIST_EMPTY(&pg->pg_members)) {
1189 			sx_sunlock(&proctree_lock);
1190 			error = ESRCH;
1191 			goto done;
1192 		}
1193 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1194 			PROC_LOCK(p);
1195 			if (descend)
1196 				ret |= ktrsetchildren(td, p, ops, facs, kiop);
1197 			else
1198 				ret |= ktrops(td, p, ops, facs, kiop);
1199 		}
1200 	} else {
1201 		/*
1202 		 * by pid
1203 		 */
1204 		p = pfind(uap->pid);
1205 		if (p == NULL) {
1206 			error = ESRCH;
1207 			sx_sunlock(&proctree_lock);
1208 			goto done;
1209 		}
1210 		if (descend)
1211 			ret |= ktrsetchildren(td, p, ops, facs, kiop);
1212 		else
1213 			ret |= ktrops(td, p, ops, facs, kiop);
1214 	}
1215 	sx_sunlock(&proctree_lock);
1216 	if (!ret)
1217 		error = EPERM;
1218 done:
1219 	if (kiop != NULL) {
1220 		mtx_lock(&ktrace_mtx);
1221 		kiop = ktr_io_params_rele(kiop);
1222 		mtx_unlock(&ktrace_mtx);
1223 		ktr_io_params_free(kiop);
1224 	}
1225 	ktrace_exit(td);
1226 	return (error);
1227 #else /* !KTRACE */
1228 	return (ENOSYS);
1229 #endif /* KTRACE */
1230 }
1231 
1232 /* ARGSUSED */
1233 int
sys_utrace(struct thread * td,struct utrace_args * uap)1234 sys_utrace(struct thread *td, struct utrace_args *uap)
1235 {
1236 
1237 #ifdef KTRACE
1238 	struct ktr_request *req;
1239 	void *cp;
1240 	int error;
1241 
1242 	if (!KTRPOINT(td, KTR_USER))
1243 		return (0);
1244 	if (uap->len > KTR_USER_MAXLEN)
1245 		return (EINVAL);
1246 	cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1247 	error = copyin(uap->addr, cp, uap->len);
1248 	if (error) {
1249 		free(cp, M_KTRACE);
1250 		return (error);
1251 	}
1252 	req = ktr_getrequest(KTR_USER);
1253 	if (req == NULL) {
1254 		free(cp, M_KTRACE);
1255 		return (ENOMEM);
1256 	}
1257 	req->ktr_buffer = cp;
1258 	req->ktr_header.ktr_len = uap->len;
1259 	ktr_submitrequest(td, req);
1260 	return (0);
1261 #else /* !KTRACE */
1262 	return (ENOSYS);
1263 #endif /* KTRACE */
1264 }
1265 
1266 #ifdef KTRACE
1267 static int
ktrops(struct thread * td,struct proc * p,int ops,int facs,struct ktr_io_params * new_kiop)1268 ktrops(struct thread *td, struct proc *p, int ops, int facs,
1269     struct ktr_io_params *new_kiop)
1270 {
1271 	struct ktr_io_params *old_kiop;
1272 
1273 	PROC_LOCK_ASSERT(p, MA_OWNED);
1274 	if (!ktrcanset(td, p)) {
1275 		PROC_UNLOCK(p);
1276 		return (0);
1277 	}
1278 	if ((ops == KTROP_SET && p->p_state == PRS_NEW) ||
1279 	    p_cansee(td, p) != 0) {
1280 		/*
1281 		 * Disallow setting trace points if the process is being born.
1282 		 * This avoids races with trace point inheritance in
1283 		 * ktrprocfork().
1284 		 */
1285 		PROC_UNLOCK(p);
1286 		return (0);
1287 	}
1288 	if ((p->p_flag & P_WEXIT) != 0) {
1289 		/*
1290 		 * There's nothing to do if the process is exiting, but avoid
1291 		 * signaling an error.
1292 		 */
1293 		PROC_UNLOCK(p);
1294 		return (1);
1295 	}
1296 	old_kiop = NULL;
1297 	mtx_lock(&ktrace_mtx);
1298 	if (ops == KTROP_SET) {
1299 		if (p->p_ktrioparms != NULL &&
1300 		    p->p_ktrioparms->vp != new_kiop->vp) {
1301 			/* if trace file already in use, relinquish below */
1302 			old_kiop = ktr_io_params_rele(p->p_ktrioparms);
1303 			p->p_ktrioparms = NULL;
1304 		}
1305 		if (p->p_ktrioparms == NULL) {
1306 			p->p_ktrioparms = new_kiop;
1307 			ktr_io_params_ref(new_kiop);
1308 		}
1309 		p->p_traceflag |= facs;
1310 		if (priv_check(td, PRIV_KTRACE) == 0)
1311 			p->p_traceflag |= KTRFAC_ROOT;
1312 	} else {
1313 		/* KTROP_CLEAR */
1314 		if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1315 			/* no more tracing */
1316 			old_kiop = ktr_freeproc(p);
1317 	}
1318 	mtx_unlock(&ktrace_mtx);
1319 	if ((p->p_traceflag & KTRFAC_MASK) != 0)
1320 		ktrprocctor_entered(td, p);
1321 	PROC_UNLOCK(p);
1322 	ktr_io_params_free(old_kiop);
1323 
1324 	return (1);
1325 }
1326 
1327 static int
ktrsetchildren(struct thread * td,struct proc * top,int ops,int facs,struct ktr_io_params * new_kiop)1328 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1329     struct ktr_io_params *new_kiop)
1330 {
1331 	struct proc *p;
1332 	int ret = 0;
1333 
1334 	p = top;
1335 	PROC_LOCK_ASSERT(p, MA_OWNED);
1336 	sx_assert(&proctree_lock, SX_LOCKED);
1337 	for (;;) {
1338 		ret |= ktrops(td, p, ops, facs, new_kiop);
1339 		/*
1340 		 * If this process has children, descend to them next,
1341 		 * otherwise do any siblings, and if done with this level,
1342 		 * follow back up the tree (but not past top).
1343 		 */
1344 		if (!LIST_EMPTY(&p->p_children))
1345 			p = LIST_FIRST(&p->p_children);
1346 		else for (;;) {
1347 			if (p == top)
1348 				return (ret);
1349 			if (LIST_NEXT(p, p_sibling)) {
1350 				p = LIST_NEXT(p, p_sibling);
1351 				break;
1352 			}
1353 			p = p->p_pptr;
1354 		}
1355 		PROC_LOCK(p);
1356 	}
1357 	/*NOTREACHED*/
1358 }
1359 
1360 static void
ktr_writerequest(struct thread * td,struct ktr_request * req)1361 ktr_writerequest(struct thread *td, struct ktr_request *req)
1362 {
1363 	struct ktr_io_params *kiop, *kiop1;
1364 	struct ktr_header *kth;
1365 	struct vnode *vp;
1366 	struct proc *p;
1367 	struct ucred *cred;
1368 	struct uio auio;
1369 	struct iovec aiov[3];
1370 	struct mount *mp;
1371 	off_t lim;
1372 	int datalen, buflen;
1373 	int error;
1374 
1375 	p = td->td_proc;
1376 
1377 	/*
1378 	 * We reference the kiop for use in I/O in case ktrace is
1379 	 * disabled on the process as we write out the request.
1380 	 */
1381 	mtx_lock(&ktrace_mtx);
1382 	kiop = p->p_ktrioparms;
1383 
1384 	/*
1385 	 * If kiop is NULL, it has been cleared out from under this
1386 	 * request, so just drop it.
1387 	 */
1388 	if (kiop == NULL) {
1389 		mtx_unlock(&ktrace_mtx);
1390 		return;
1391 	}
1392 
1393 	ktr_io_params_ref(kiop);
1394 	vp = kiop->vp;
1395 	cred = kiop->cr;
1396 	lim = kiop->lim;
1397 
1398 	KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1399 	mtx_unlock(&ktrace_mtx);
1400 
1401 	kth = &req->ktr_header;
1402 	KASSERT(((u_short)kth->ktr_type & ~KTR_TYPE) < nitems(data_lengths),
1403 	    ("data_lengths array overflow"));
1404 	datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_TYPE];
1405 	buflen = kth->ktr_len;
1406 	auio.uio_iov = &aiov[0];
1407 	auio.uio_offset = 0;
1408 	auio.uio_segflg = UIO_SYSSPACE;
1409 	auio.uio_rw = UIO_WRITE;
1410 	aiov[0].iov_base = (caddr_t)kth;
1411 	aiov[0].iov_len = sizeof(struct ktr_header);
1412 	auio.uio_resid = sizeof(struct ktr_header);
1413 	auio.uio_iovcnt = 1;
1414 	auio.uio_td = td;
1415 	if (datalen != 0) {
1416 		aiov[1].iov_base = (caddr_t)&req->ktr_data;
1417 		aiov[1].iov_len = datalen;
1418 		auio.uio_resid += datalen;
1419 		auio.uio_iovcnt++;
1420 		kth->ktr_len += datalen;
1421 	}
1422 	if (buflen != 0) {
1423 		KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1424 		aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1425 		aiov[auio.uio_iovcnt].iov_len = buflen;
1426 		auio.uio_resid += buflen;
1427 		auio.uio_iovcnt++;
1428 	}
1429 
1430 	vn_start_write(vp, &mp, V_WAIT);
1431 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1432 	td->td_ktr_io_lim = lim;
1433 #ifdef MAC
1434 	error = mac_vnode_check_write(cred, NOCRED, vp);
1435 	if (error == 0)
1436 #endif
1437 		error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1438 	VOP_UNLOCK(vp);
1439 	vn_finished_write(mp);
1440 	if (error == 0) {
1441 		mtx_lock(&ktrace_mtx);
1442 		kiop = ktr_io_params_rele(kiop);
1443 		mtx_unlock(&ktrace_mtx);
1444 		ktr_io_params_free(kiop);
1445 		return;
1446 	}
1447 
1448 	/*
1449 	 * If error encountered, give up tracing on this vnode on this
1450 	 * process.  Other processes might still be suitable for
1451 	 * writes to this vnode.
1452 	 */
1453 	log(LOG_NOTICE,
1454 	    "ktrace write failed, errno %d, tracing stopped for pid %d\n",
1455 	    error, p->p_pid);
1456 
1457 	kiop1 = NULL;
1458 	PROC_LOCK(p);
1459 	mtx_lock(&ktrace_mtx);
1460 	if (p->p_ktrioparms != NULL && p->p_ktrioparms->vp == vp)
1461 		kiop1 = ktr_freeproc(p);
1462 	kiop = ktr_io_params_rele(kiop);
1463 	mtx_unlock(&ktrace_mtx);
1464 	PROC_UNLOCK(p);
1465 	ktr_io_params_free(kiop1);
1466 	ktr_io_params_free(kiop);
1467 }
1468 
1469 /*
1470  * Return true if caller has permission to set the ktracing state
1471  * of target.  Essentially, the target can't possess any
1472  * more permissions than the caller.  KTRFAC_ROOT signifies that
1473  * root previously set the tracing status on the target process, and
1474  * so, only root may further change it.
1475  */
1476 static int
ktrcanset(struct thread * td,struct proc * targetp)1477 ktrcanset(struct thread *td, struct proc *targetp)
1478 {
1479 
1480 	PROC_LOCK_ASSERT(targetp, MA_OWNED);
1481 	if (targetp->p_traceflag & KTRFAC_ROOT &&
1482 	    priv_check(td, PRIV_KTRACE))
1483 		return (0);
1484 
1485 	if (p_candebug(td, targetp) != 0)
1486 		return (0);
1487 
1488 	return (1);
1489 }
1490 
1491 #endif /* KTRACE */
1492