1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2018, Matthew Macy
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/cpuset.h>
32 #include <sys/event.h>
33 #include <sys/queue.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <sys/time.h>
38 #include <sys/ttycom.h>
39 #include <sys/user.h>
40 #include <sys/wait.h>
41 
42 #include <assert.h>
43 #include <curses.h>
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <getopt.h>
48 #include <kvm.h>
49 #include <libgen.h>
50 #include <limits.h>
51 #include <locale.h>
52 #include <math.h>
53 #include <pmc.h>
54 #include <pmclog.h>
55 #include <regex.h>
56 #include <signal.h>
57 #include <stdarg.h>
58 #include <stdint.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <stddef.h>
62 #include <string.h>
63 #include <sysexits.h>
64 #include <unistd.h>
65 
66 #include <libpmcstat.h>
67 #include "cmd_pmc.h"
68 
69 #include <string>
70 #include <unordered_map>
71 
72 #include <pmcformat.h>
73 
74 using	namespace std;
75 using	std::unordered_map;
76 typedef unordered_map < int ,string > idmap;
77 typedef pair < int ,string > identry;
78 
79 #define LIST_MAX 64
80 static struct option longopts[] = {
81 	{"lwps", required_argument, NULL, 't'},
82 	{"pids", required_argument, NULL, 'p'},
83 	{"threads", required_argument, NULL, 'T'},
84 	{"processes", required_argument, NULL, 'P'},
85 	{"events", required_argument, NULL, 'e'},
86 	{NULL, 0, NULL, 0}
87 };
88 
89 static void __dead2
usage(void)90 usage(void)
91 {
92 	errx(EX_USAGE,
93 	    "\t filter log file\n"
94 	    "\t -e <events>, --events <events> -- comma-delimited list of events to filter on\n"
95 	    "\t -p <pids>, --pids <pids> -- comma-delimited list of pids to filter on\n"
96 	    "\t -P <processes>, --processes <processes> -- comma-delimited list of process names to filter on\n"
97 	    "\t -t <lwps>, --lwps <lwps> -- comma-delimited list of lwps to filter on\n"
98 	    "\t -T <threads>, --threads <threads> -- comma-delimited list of thread names to filter on\n"
99 	    "\t -x -- toggle inclusive filtering\n"
100 	    );
101 }
102 
103 
104 static void
parse_intlist(char * strlist,uint32_t * intlist,int * pcount,int (* fn)(const char *))105 parse_intlist(char *strlist, uint32_t *intlist, int *pcount, int (*fn) (const char *))
106 {
107 	char *token;
108 	int count, tokenval;
109 
110 	count = 0;
111 	while ((token = strsep(&strlist, ",")) != NULL &&
112 	    count < LIST_MAX) {
113 		if ((tokenval = fn(token)) < 0)
114 			errx(EX_USAGE, "ERROR: %s not usable value", token);
115 		intlist[count++] = tokenval;
116 	}
117 	*pcount = count;
118 }
119 
120 static void
parse_events(char * strlist,uint32_t intlist[LIST_MAX],int * pcount,char * cpuid)121 parse_events(char *strlist, uint32_t intlist[LIST_MAX], int *pcount, char *cpuid)
122 {
123 	char *token;
124 	int count, tokenval;
125 
126 	count = 0;
127 	while ((token = strsep(&strlist, ",")) != NULL &&
128 	    count < LIST_MAX) {
129 		if ((tokenval = pmc_pmu_idx_get_by_event(cpuid, token)) < 0)
130 			errx(EX_USAGE, "ERROR: %s not usable value", token);
131 		intlist[count++] = tokenval;
132 	}
133 	*pcount = count;
134 }
135 
136 static void
parse_names(char * strlist,char * namelist[LIST_MAX],int * pcount)137 parse_names(char *strlist, char *namelist[LIST_MAX], int *pcount)
138 {
139 	char *token;
140 	int count;
141 
142 	count = 0;
143 	while ((token = strsep(&strlist, ",")) != NULL &&
144 	    count < LIST_MAX) {
145 		namelist[count++] = token;
146 	}
147 	*pcount = count;
148 }
149 
150 
151 struct pmcid_ent {
152 	uint32_t pe_pmcid;
153 	uint32_t pe_idx;
154 };
155 #define	_PMCLOG_TO_HEADER(T,L)						\
156 	((PMCLOG_HEADER_MAGIC << 24) |					\
157 	 (PMCLOG_TYPE_ ## T << 16)   |					\
158 	 ((L) & 0xFFFF))
159 
160 static bool
pmc_find_name(idmap & map,uint32_t id,char * list[LIST_MAX],int count)161 pmc_find_name(idmap & map, uint32_t id, char *list[LIST_MAX], int count)
162 {
163 	int i;
164 
165 	auto kvpair = map.find(id);
166 	if (kvpair == map.end()) {
167 		printf("unknown id: %d\n", id);
168 		return (false);
169 	}
170 	auto p = list;
171 	for (i = 0; i < count; i++, p++) {
172 		if (strstr(kvpair->second.c_str(), *p) != NULL)
173 			return (true);
174 	}
175 	return (false);
176 }
177 
178 static void
pmc_log_event(int fd,struct pmclog_ev * ev,bool json)179 pmc_log_event(int fd, struct pmclog_ev *ev, bool json)
180 {
181 	string ret;
182 	int len;
183 	const void *buf;
184 
185 	if (json) {
186 		ret = event_to_json(ev);
187 		buf = ret.c_str();
188 		len = ret.size();
189 	} else {
190 		len = ev->pl_len;
191 		buf = ev->pl_data;
192 	}
193 	if (write(fd, buf, len) != (ssize_t)len)
194 		errx(EX_OSERR, "ERROR: failed output write");
195 }
196 
197 static void
pmc_filter_handler(uint32_t * lwplist,int lwpcount,uint32_t * pidlist,int pidcount,char * events,char * processes,char * threads,bool exclusive,bool json,int infd,int outfd)198 pmc_filter_handler(uint32_t *lwplist, int lwpcount, uint32_t *pidlist, int pidcount,
199     char *events, char *processes, char *threads, bool exclusive, bool json, int infd,
200     int outfd)
201 {
202 	struct pmclog_ev ev;
203 	struct pmclog_parse_state *ps;
204 	struct pmcid_ent *pe;
205 	uint32_t eventlist[LIST_MAX];
206 	char cpuid[PMC_CPUID_LEN];
207 	char *proclist[LIST_MAX];
208 	char *threadlist[LIST_MAX];
209 	int i, pmccount, eventcount;
210 	int proccount, threadcount;
211 	uint32_t idx;
212 	idmap pidmap, tidmap;
213 
214 	if ((ps = static_cast < struct pmclog_parse_state *>(pmclog_open(infd)))== NULL)
215 		errx(EX_OSERR, "ERROR: Cannot allocate pmclog parse state: %s\n", strerror(errno));
216 
217 	threadcount = proccount = eventcount = pmccount = 0;
218 	if (processes)
219 		parse_names(processes, proclist, &proccount);
220 	if (threads)
221 		parse_names(threads, threadlist, &threadcount);
222 	while (pmclog_read(ps, &ev) == 0) {
223 		if (ev.pl_type == PMCLOG_TYPE_INITIALIZE)
224 			memcpy(cpuid, ev.pl_u.pl_i.pl_cpuid, PMC_CPUID_LEN);
225 		if (ev.pl_type == PMCLOG_TYPE_PMCALLOCATE)
226 			pmccount++;
227 	}
228 	if (events)
229 		parse_events(events, eventlist, &eventcount, cpuid);
230 	lseek(infd, 0, SEEK_SET);
231 	pmclog_close(ps);
232 	if ((ps = static_cast < struct pmclog_parse_state *>(pmclog_open(infd)))== NULL)
233 		errx(EX_OSERR, "ERROR: Cannot allocate pmclog parse state: %s\n", strerror(errno));
234 	if ((pe = (struct pmcid_ent *) malloc(sizeof(*pe) * pmccount)) == NULL)
235 		errx(EX_OSERR, "ERROR: failed to allocate pmcid map");
236 	i = 0;
237 	while (pmclog_read(ps, &ev) == 0 && i < pmccount) {
238 		if (ev.pl_type == PMCLOG_TYPE_PMCALLOCATE) {
239 			pe[i].pe_pmcid = ev.pl_u.pl_a.pl_pmcid;
240 			pe[i].pe_idx = ev.pl_u.pl_a.pl_event;
241 			i++;
242 		}
243 	}
244 	lseek(infd, 0, SEEK_SET);
245 	pmclog_close(ps);
246 	if ((ps = static_cast < struct pmclog_parse_state *>(pmclog_open(infd)))== NULL)
247 		errx(EX_OSERR, "ERROR: Cannot allocate pmclog parse state: %s\n", strerror(errno));
248 	while (pmclog_read(ps, &ev) == 0) {
249 		if (ev.pl_type == PMCLOG_TYPE_THR_CREATE)
250 			tidmap[ev.pl_u.pl_tc.pl_tid] = ev.pl_u.pl_tc.pl_tdname;
251 		if (ev.pl_type == PMCLOG_TYPE_PROC_CREATE)
252 			pidmap[ev.pl_u.pl_pc.pl_pid] = ev.pl_u.pl_pc.pl_pcomm;
253 		if (ev.pl_type != PMCLOG_TYPE_CALLCHAIN) {
254 			pmc_log_event(outfd, &ev, json);
255 			continue;
256 		}
257 		if (pidcount) {
258 			for (i = 0; i < pidcount; i++)
259 				if (pidlist[i] == ev.pl_u.pl_cc.pl_pid)
260 					break;
261 			if ((i == pidcount) == exclusive)
262 				continue;
263 		}
264 		if (lwpcount) {
265 			for (i = 0; i < lwpcount; i++)
266 				if (lwplist[i] == ev.pl_u.pl_cc.pl_tid)
267 					break;
268 			if ((i == lwpcount) == exclusive)
269 				continue;
270 		}
271 		if (eventcount) {
272 			for (i = 0; i < pmccount; i++) {
273 				if (pe[i].pe_pmcid == ev.pl_u.pl_cc.pl_pmcid)
274 					break;
275 			}
276 			if (i == pmccount)
277 				errx(EX_USAGE, "ERROR: unallocated pmcid: %d\n",
278 				    ev.pl_u.pl_cc.pl_pmcid);
279 
280 			idx = pe[i].pe_idx;
281 			for (i = 0; i < eventcount; i++) {
282 				if (idx == eventlist[i])
283 					break;
284 			}
285 			if ((i == eventcount) == exclusive)
286 				continue;
287 		}
288 		if (proccount &&
289 		    pmc_find_name(pidmap, ev.pl_u.pl_cc.pl_pid, proclist, proccount) == exclusive)
290 			continue;
291 		if (threadcount &&
292 		    pmc_find_name(tidmap, ev.pl_u.pl_cc.pl_tid, threadlist, threadcount) == exclusive)
293 			continue;
294 		pmc_log_event(outfd, &ev, json);
295 	}
296 }
297 
298 int
cmd_pmc_filter(int argc,char ** argv)299 cmd_pmc_filter(int argc, char **argv)
300 {
301 	char *lwps, *pids, *events, *processes, *threads;
302 	uint32_t lwplist[LIST_MAX];
303 	uint32_t pidlist[LIST_MAX];
304 	int option, lwpcount, pidcount;
305 	int prelogfd, postlogfd;
306 	bool exclusive, json;
307 
308 	threads = processes = lwps = pids = events = NULL;
309 	lwpcount = pidcount = 0;
310 	json = exclusive = false;
311 	while ((option = getopt_long(argc, argv, "e:jp:t:xP:T:", longopts, NULL)) != -1) {
312 		switch (option) {
313 		case 'e':
314 			events = strdup(optarg);
315 			break;
316 		case 'j':
317 			json = true;
318 			break;
319 		case 'p':
320 			pids = strdup(optarg);
321 			break;
322 		case 'P':
323 			processes = strdup(optarg);
324 			break;
325 		case 't':
326 			lwps = strdup(optarg);
327 			break;
328 		case 'T':
329 			threads = strdup(optarg);
330 			break;
331 		case 'x':
332 			exclusive = !exclusive;
333 			break;
334 		case '?':
335 		default:
336 			usage();
337 		}
338 	}
339 	argc -= optind;
340 	argv += optind;
341 	if (argc != 2)
342 		usage();
343 
344 	if (lwps)
345 		parse_intlist(lwps, lwplist, &lwpcount, atoi);
346 	if (pids)
347 		parse_intlist(pids, pidlist, &pidcount, atoi);
348 	if ((prelogfd = open(argv[0], O_RDONLY,
349 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
350 		errx(EX_OSERR, "ERROR: Cannot open \"%s\" for reading: %s.", argv[0],
351 		    strerror(errno));
352 	if ((postlogfd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC,
353 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
354 		errx(EX_OSERR, "ERROR: Cannot open \"%s\" for writing: %s.", argv[1],
355 		    strerror(errno));
356 
357 	pmc_filter_handler(lwplist, lwpcount, pidlist, pidcount, events,
358 	    processes, threads, exclusive, json, prelogfd, postlogfd);
359 	return (0);
360 }
361