1 /*-
2  * Copyright (c) 2003-2008 Joseph Koshy
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/types.h>
31 #include <sys/cpuset.h>
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/pmc.h>
36 
37 #include <assert.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <limits.h>
43 #include <netdb.h>
44 #include <pmc.h>
45 #include <pmclog.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <strings.h>
50 #include <sysexits.h>
51 #include <unistd.h>
52 
53 #include "libpmcstat.h"
54 
55 /*
56  * Get PMC record by id, apply merge policy.
57  */
58 
59 static struct pmcstat_pmcrecord *
60 pmcstat_lookup_pmcid(pmc_id_t pmcid, int pmcstat_mergepmc)
61 {
62 	struct pmcstat_pmcrecord *pr;
63 
64 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
65 		if (pr->pr_pmcid == pmcid) {
66 			if (pmcstat_mergepmc)
67 				return pr->pr_merge;
68 			return pr;
69 		}
70 	}
71 
72 	return NULL;
73 }
74 
75 /*
76  * Add a {pmcid,name} mapping.
77  */
78 
79 static void
80 pmcstat_pmcid_add(pmc_id_t pmcid, pmcstat_interned_string ps,
81     struct pmcstat_args *args, struct pmc_plugins *plugins,
82     int *pmcstat_npmcs)
83 {
84 	struct pmcstat_pmcrecord *pr, *prm;
85 
86 	/* Replace an existing name for the PMC. */
87 	prm = NULL;
88 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
89 		if (pr->pr_pmcid == pmcid) {
90 			pr->pr_pmcname = ps;
91 			return;
92 		} else if (pr->pr_pmcname == ps)
93 			prm = pr;
94 
95 	/*
96 	 * Otherwise, allocate a new descriptor and call the
97 	 * plugins hook.
98 	 */
99 	if ((pr = malloc(sizeof(*pr))) == NULL)
100 		err(EX_OSERR, "ERROR: Cannot allocate pmc record");
101 
102 	pr->pr_pmcid = pmcid;
103 	pr->pr_pmcname = ps;
104 	pr->pr_pmcin = (*pmcstat_npmcs)++;
105 	pr->pr_samples = 0;
106 	pr->pr_dubious_frames = 0;
107 	pr->pr_merge = prm == NULL ? pr : prm;
108 
109 	LIST_INSERT_HEAD(&pmcstat_pmcs, pr, pr_next);
110 
111 	if (plugins[args->pa_pplugin].pl_newpmc != NULL)
112 		plugins[args->pa_pplugin].pl_newpmc(ps, pr);
113 	if (plugins[args->pa_plugin].pl_newpmc != NULL)
114 		plugins[args->pa_plugin].pl_newpmc(ps, pr);
115 }
116 
117 /*
118  * Unmap images in the range [start..end) associated with process
119  * 'pp'.
120  */
121 
122 static void
123 pmcstat_image_unmap(struct pmcstat_process *pp, uintfptr_t start,
124     uintfptr_t end)
125 {
126 	struct pmcstat_pcmap *pcm, *pcmtmp, *pcmnew;
127 
128 	assert(pp != NULL);
129 	assert(start < end);
130 
131 	/*
132 	 * Cases:
133 	 * - we could have the range completely in the middle of an
134 	 *   existing pcmap; in this case we have to split the pcmap
135 	 *   structure into two (i.e., generate a 'hole').
136 	 * - we could have the range covering multiple pcmaps; these
137 	 *   will have to be removed.
138 	 * - we could have either 'start' or 'end' falling in the
139 	 *   middle of a pcmap; in this case shorten the entry.
140 	 */
141 	TAILQ_FOREACH_SAFE(pcm, &pp->pp_map, ppm_next, pcmtmp) {
142 		assert(pcm->ppm_lowpc < pcm->ppm_highpc);
143 		if (pcm->ppm_highpc <= start)
144 			continue;
145 		if (pcm->ppm_lowpc >= end)
146 			return;
147 		if (pcm->ppm_lowpc >= start && pcm->ppm_highpc <= end) {
148 			/*
149 			 * The current pcmap is completely inside the
150 			 * unmapped range: remove it entirely.
151 			 */
152 			TAILQ_REMOVE(&pp->pp_map, pcm, ppm_next);
153 			free(pcm);
154 		} else if (pcm->ppm_lowpc < start && pcm->ppm_highpc > end) {
155 			/*
156 			 * Split this pcmap into two; curtail the
157 			 * current map to end at [start-1], and start
158 			 * the new one at [end].
159 			 */
160 			if ((pcmnew = malloc(sizeof(*pcmnew))) == NULL)
161 				err(EX_OSERR,
162 				    "ERROR: Cannot split a map entry");
163 
164 			pcmnew->ppm_image = pcm->ppm_image;
165 
166 			pcmnew->ppm_lowpc = end;
167 			pcmnew->ppm_highpc = pcm->ppm_highpc;
168 
169 			pcm->ppm_highpc = start;
170 
171 			TAILQ_INSERT_AFTER(&pp->pp_map, pcm, pcmnew, ppm_next);
172 
173 			return;
174 		} else if (pcm->ppm_lowpc < start && pcm->ppm_highpc <= end)
175 			pcm->ppm_highpc = start;
176 		else if (pcm->ppm_lowpc >= start && pcm->ppm_highpc > end)
177 			pcm->ppm_lowpc = end;
178 		else
179 			assert(0);
180 	}
181 }
182 
183 /*
184  * Convert a hwpmc(4) log to profile information.  A system-wide
185  * callgraph is generated if FLAG_DO_CALLGRAPHS is set.  gmon.out
186  * files usable by gprof(1) are created if FLAG_DO_GPROF is set.
187  */
188 int
189 pmcstat_analyze_log(struct pmcstat_args *args,
190     struct pmc_plugins *plugins,
191     struct pmcstat_stats *pmcstat_stats,
192     struct pmcstat_process *pmcstat_kernproc,
193     int pmcstat_mergepmc,
194     int *pmcstat_npmcs,
195     int *ps_samples_period)
196 {
197 	uint32_t cpu, cpuflags;
198 	uintfptr_t pc;
199 	pid_t pid;
200 	struct pmcstat_image *image;
201 	struct pmcstat_process *pp, *ppnew;
202 	struct pmcstat_pcmap *ppm, *ppmtmp;
203 	struct pmclog_ev ev;
204 	struct pmcstat_pmcrecord *pmcr;
205 	pmcstat_interned_string image_path;
206 
207 	assert(args->pa_flags & FLAG_DO_ANALYSIS);
208 
209 	if (elf_version(EV_CURRENT) == EV_NONE)
210 		err(EX_UNAVAILABLE, "Elf library initialization failed");
211 
212 	while (pmclog_read(args->pa_logparser, &ev) == 0) {
213 		assert(ev.pl_state == PMCLOG_OK);
214 
215 		switch (ev.pl_type) {
216 		case PMCLOG_TYPE_INITIALIZE:
217 			if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
218 			    PMC_VERSION_MAJOR << 24 && args->pa_verbosity > 0)
219 				warnx(
220 "WARNING: Log version 0x%x does not match compiled version 0x%x.",
221 				    ev.pl_u.pl_i.pl_version, PMC_VERSION_MAJOR);
222 			break;
223 
224 		case PMCLOG_TYPE_MAP_IN:
225 			/*
226 			 * Introduce an address range mapping for a
227 			 * userland process or the kernel (pid == -1).
228 			 *
229 			 * We always allocate a process descriptor so
230 			 * that subsequent samples seen for this
231 			 * address range are mapped to the current
232 			 * object being mapped in.
233 			 */
234 			pid = ev.pl_u.pl_mi.pl_pid;
235 			if (pid == -1)
236 				pp = pmcstat_kernproc;
237 			else
238 				pp = pmcstat_process_lookup(pid,
239 				    PMCSTAT_ALLOCATE);
240 
241 			assert(pp != NULL);
242 
243 			image_path = pmcstat_string_intern(ev.pl_u.pl_mi.
244 			    pl_pathname);
245 			image = pmcstat_image_from_path(image_path, pid == -1,
246 			    args, plugins);
247 			if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
248 				pmcstat_image_determine_type(image, args);
249 			if (image->pi_type != PMCSTAT_IMAGE_INDETERMINABLE)
250 				pmcstat_image_link(pp, image,
251 				    ev.pl_u.pl_mi.pl_start);
252 			break;
253 
254 		case PMCLOG_TYPE_MAP_OUT:
255 			/*
256 			 * Remove an address map.
257 			 */
258 			pid = ev.pl_u.pl_mo.pl_pid;
259 			if (pid == -1)
260 				pp = pmcstat_kernproc;
261 			else
262 				pp = pmcstat_process_lookup(pid, 0);
263 
264 			if (pp == NULL)	/* unknown process */
265 				break;
266 
267 			pmcstat_image_unmap(pp, ev.pl_u.pl_mo.pl_start,
268 			    ev.pl_u.pl_mo.pl_end);
269 			break;
270 
271 		case PMCLOG_TYPE_PCSAMPLE:
272 			/*
273 			 * Note: the `PCSAMPLE' log entry is not
274 			 * generated by hpwmc(4) after version 2.
275 			 */
276 
277 			/*
278 			 * We bring in the gmon file for the image
279 			 * currently associated with the PMC & pid
280 			 * pair and increment the appropriate entry
281 			 * bin inside this.
282 			 */
283 			pmcstat_stats->ps_samples_total++;
284 			*ps_samples_period += 1;
285 
286 			pc = ev.pl_u.pl_s.pl_pc;
287 			pp = pmcstat_process_lookup(ev.pl_u.pl_s.pl_pid,
288 			    PMCSTAT_ALLOCATE);
289 
290 			/* Get PMC record. */
291 			pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_s.pl_pmcid, pmcstat_mergepmc);
292 			assert(pmcr != NULL);
293 			pmcr->pr_samples++;
294 
295 			/*
296 			 * Call the plugins processing
297 			 * TODO: move pmcstat_process_find_map inside plugins
298 			 */
299 
300 			if (plugins[args->pa_pplugin].pl_process != NULL)
301 				plugins[args->pa_pplugin].pl_process(
302 				    pp, pmcr, 1, &pc,
303 				    pmcstat_process_find_map(pp, pc) != NULL, 0);
304 			plugins[args->pa_plugin].pl_process(
305 			    pp, pmcr, 1, &pc,
306 			    pmcstat_process_find_map(pp, pc) != NULL, 0);
307 			break;
308 
309 		case PMCLOG_TYPE_CALLCHAIN:
310 			pmcstat_stats->ps_samples_total++;
311 			*ps_samples_period += 1;
312 
313 			cpuflags = ev.pl_u.pl_cc.pl_cpuflags;
314 			cpu = PMC_CALLCHAIN_CPUFLAGS_TO_CPU(cpuflags);
315 
316 			if ((args->pa_flags & FLAG_FILTER_THREAD_ID) &&
317 				args->pa_tid != ev.pl_u.pl_cc.pl_tid) {
318 				pmcstat_stats->ps_samples_skipped++;
319 				break;
320 			}
321 			/* Filter on the CPU id. */
322 			if (!CPU_ISSET(cpu, &(args->pa_cpumask))) {
323 				pmcstat_stats->ps_samples_skipped++;
324 				break;
325 			}
326 
327 			pp = pmcstat_process_lookup(ev.pl_u.pl_cc.pl_pid,
328 			    PMCSTAT_ALLOCATE);
329 
330 			/* Get PMC record. */
331 			pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_cc.pl_pmcid, pmcstat_mergepmc);
332 			assert(pmcr != NULL);
333 			pmcr->pr_samples++;
334 
335 			/*
336 			 * Call the plugins processing
337 			 */
338 
339 			if (plugins[args->pa_pplugin].pl_process != NULL)
340 				plugins[args->pa_pplugin].pl_process(
341 				    pp, pmcr,
342 				    ev.pl_u.pl_cc.pl_npc,
343 				    ev.pl_u.pl_cc.pl_pc,
344 				    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
345 				    cpu);
346 			plugins[args->pa_plugin].pl_process(
347 			    pp, pmcr,
348 			    ev.pl_u.pl_cc.pl_npc,
349 			    ev.pl_u.pl_cc.pl_pc,
350 			    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
351 			    cpu);
352 			break;
353 
354 		case PMCLOG_TYPE_PMCALLOCATE:
355 			/*
356 			 * Record the association pmc id between this
357 			 * PMC and its name.
358 			 */
359 			pmcstat_pmcid_add(ev.pl_u.pl_a.pl_pmcid,
360 			    pmcstat_string_intern(ev.pl_u.pl_a.pl_evname),
361 			    args, plugins, pmcstat_npmcs);
362 			break;
363 
364 		case PMCLOG_TYPE_PMCALLOCATEDYN:
365 			/*
366 			 * Record the association pmc id between this
367 			 * PMC and its name.
368 			 */
369 			pmcstat_pmcid_add(ev.pl_u.pl_ad.pl_pmcid,
370 			    pmcstat_string_intern(ev.pl_u.pl_ad.pl_evname),
371 			    args, plugins, pmcstat_npmcs);
372 			break;
373 
374 		case PMCLOG_TYPE_PROCEXEC:
375 			/*
376 			 * Change the executable image associated with
377 			 * a process.
378 			 */
379 			pp = pmcstat_process_lookup(ev.pl_u.pl_x.pl_pid,
380 			    PMCSTAT_ALLOCATE);
381 
382 			/* delete the current process map */
383 			TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
384 				TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
385 				free(ppm);
386 			}
387 
388 			/*
389 			 * Associate this process image.
390 			 */
391 			image_path = pmcstat_string_intern(
392 				ev.pl_u.pl_x.pl_pathname);
393 			assert(image_path != NULL);
394 			pmcstat_process_exec(pp, image_path,
395 			    ev.pl_u.pl_x.pl_entryaddr, args,
396 			    plugins, pmcstat_stats);
397 			break;
398 
399 		case PMCLOG_TYPE_PROCEXIT:
400 
401 			/*
402 			 * Due to the way the log is generated, the
403 			 * last few samples corresponding to a process
404 			 * may appear in the log after the process
405 			 * exit event is recorded.  Thus we keep the
406 			 * process' descriptor and associated data
407 			 * structures around, but mark the process as
408 			 * having exited.
409 			 */
410 			pp = pmcstat_process_lookup(ev.pl_u.pl_e.pl_pid, 0);
411 			if (pp == NULL)
412 				break;
413 			pp->pp_isactive = 0;	/* mark as a zombie */
414 			break;
415 
416 		case PMCLOG_TYPE_SYSEXIT:
417 			pp = pmcstat_process_lookup(ev.pl_u.pl_se.pl_pid, 0);
418 			if (pp == NULL)
419 				break;
420 			pp->pp_isactive = 0;	/* make a zombie */
421 			break;
422 
423 		case PMCLOG_TYPE_PROCFORK:
424 
425 			/*
426 			 * Allocate a process descriptor for the new
427 			 * (child) process.
428 			 */
429 			ppnew =
430 			    pmcstat_process_lookup(ev.pl_u.pl_f.pl_newpid,
431 				PMCSTAT_ALLOCATE);
432 
433 			/*
434 			 * If we had been tracking the parent, clone
435 			 * its address maps.
436 			 */
437 			pp = pmcstat_process_lookup(ev.pl_u.pl_f.pl_oldpid, 0);
438 			if (pp == NULL)
439 				break;
440 			TAILQ_FOREACH(ppm, &pp->pp_map, ppm_next)
441 			    pmcstat_image_link(ppnew, ppm->ppm_image,
442 				ppm->ppm_lowpc);
443 			break;
444 
445 		default:	/* other types of entries are not relevant */
446 			break;
447 		}
448 	}
449 
450 	if (ev.pl_state == PMCLOG_EOF)
451 		return (PMCSTAT_FINISHED);
452 	else if (ev.pl_state == PMCLOG_REQUIRE_DATA)
453 		return (PMCSTAT_RUNNING);
454 
455 	err(EX_DATAERR,
456 	    "ERROR: event parsing failed (record %jd, offset 0x%jx)",
457 	    (uintmax_t) ev.pl_count + 1, ev.pl_offset);
458 }
459 
460 /*
461  * Open a log file, for reading or writing.
462  *
463  * The function returns the fd of a successfully opened log or -1 in
464  * case of failure.
465  */
466 
467 int
468 pmcstat_open_log(const char *path, int mode)
469 {
470 	int error, fd, cfd;
471 	size_t hlen;
472 	const char *p, *errstr;
473 	struct addrinfo hints, *res, *res0;
474 	char hostname[MAXHOSTNAMELEN];
475 
476 	errstr = NULL;
477 	fd = -1;
478 
479 	/*
480 	 * If 'path' is "-" then open one of stdin or stdout depending
481 	 * on the value of 'mode'.
482 	 *
483 	 * If 'path' contains a ':' and does not start with a '/' or '.',
484 	 * and is being opened for writing, treat it as a "host:port"
485 	 * specification and open a network socket.
486 	 *
487 	 * Otherwise, treat 'path' as a file name and open that.
488 	 */
489 	if (path[0] == '-' && path[1] == '\0')
490 		fd = (mode == PMCSTAT_OPEN_FOR_READ) ? 0 : 1;
491 	else if (path[0] != '/' &&
492 	    path[0] != '.' && strchr(path, ':') != NULL) {
493 
494 		p = strrchr(path, ':');
495 		hlen = p - path;
496 		if (p == path || hlen >= sizeof(hostname)) {
497 			errstr = strerror(EINVAL);
498 			goto done;
499 		}
500 
501 		assert(hlen < sizeof(hostname));
502 		(void) strncpy(hostname, path, hlen);
503 		hostname[hlen] = '\0';
504 
505 		(void) memset(&hints, 0, sizeof(hints));
506 		hints.ai_family = AF_UNSPEC;
507 		hints.ai_socktype = SOCK_STREAM;
508 		if ((error = getaddrinfo(hostname, p+1, &hints, &res0)) != 0) {
509 			errstr = gai_strerror(error);
510 			goto done;
511 		}
512 
513 		fd = -1;
514 		for (res = res0; res; res = res->ai_next) {
515 			if ((fd = socket(res->ai_family, res->ai_socktype,
516 			    res->ai_protocol)) < 0) {
517 				errstr = strerror(errno);
518 				continue;
519 			}
520 			if (mode == PMCSTAT_OPEN_FOR_READ) {
521 				if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {
522 					errstr = strerror(errno);
523 					(void) close(fd);
524 					fd = -1;
525 					continue;
526 				}
527 				listen(fd, 1);
528 				cfd = accept(fd, NULL, NULL);
529 				(void) close(fd);
530 				if (cfd < 0) {
531 					errstr = strerror(errno);
532 					fd = -1;
533 					break;
534 				}
535 				fd = cfd;
536 			} else {
537 				if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
538 					errstr = strerror(errno);
539 					(void) close(fd);
540 					fd = -1;
541 					continue;
542 				}
543 			}
544 			errstr = NULL;
545 			break;
546 		}
547 		freeaddrinfo(res0);
548 
549 	} else if ((fd = open(path, mode == PMCSTAT_OPEN_FOR_READ ?
550 		    O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC),
551 		    S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
552 			errstr = strerror(errno);
553 
554   done:
555 	if (errstr)
556 		errx(EX_OSERR, "ERROR: Cannot open \"%s\" for %s: %s.", path,
557 		    (mode == PMCSTAT_OPEN_FOR_READ ? "reading" : "writing"),
558 		    errstr);
559 
560 	return (fd);
561 }
562 
563 /*
564  * Close a logfile, after first flushing all in-module queued data.
565  */
566 
567 int
568 pmcstat_close_log(struct pmcstat_args *args)
569 {
570 	/* If a local logfile is configured ask the kernel to stop
571 	 * and flush data. Kernel will close the file when data is flushed
572 	 * so keep the status to EXITING.
573 	 */
574 	if (args->pa_logfd != -1) {
575 		if (pmc_close_logfile() < 0)
576 			err(EX_OSERR, "ERROR: logging failed");
577 	}
578 
579 	return (args->pa_flags & FLAG_HAS_PIPE ? PMCSTAT_EXITING :
580 	    PMCSTAT_FINISHED);
581 }
582 
583 /*
584  * Initialize module.
585  */
586 
587 void
588 pmcstat_initialize_logging(struct pmcstat_process **pmcstat_kernproc,
589     struct pmcstat_args *args, struct pmc_plugins *plugins,
590     int *pmcstat_npmcs, int *pmcstat_mergepmc)
591 {
592 	struct pmcstat_process *pmcstat_kp;
593 	int i;
594 
595 	/* use a convenient format for 'ldd' output */
596 	if (setenv("LD_TRACE_LOADED_OBJECTS_FMT1","%o \"%p\" %x\n",1) != 0)
597 		err(EX_OSERR, "ERROR: Cannot setenv");
598 
599 	/* Initialize hash tables */
600 	pmcstat_string_initialize();
601 	for (i = 0; i < PMCSTAT_NHASH; i++) {
602 		LIST_INIT(&pmcstat_image_hash[i]);
603 		LIST_INIT(&pmcstat_process_hash[i]);
604 	}
605 
606 	/*
607 	 * Create a fake 'process' entry for the kernel with pid -1.
608 	 * hwpmc(4) will subsequently inform us about where the kernel
609 	 * and any loaded kernel modules are mapped.
610 	 */
611 	if ((pmcstat_kp = pmcstat_process_lookup((pid_t) -1,
612 	    PMCSTAT_ALLOCATE)) == NULL)
613 		err(EX_OSERR, "ERROR: Cannot initialize logging");
614 
615 	*pmcstat_kernproc = pmcstat_kp;
616 
617 	/* PMC count. */
618 	*pmcstat_npmcs = 0;
619 
620 	/* Merge PMC with same name. */
621 	*pmcstat_mergepmc = args->pa_mergepmc;
622 
623 	/*
624 	 * Initialize plugins
625 	 */
626 
627 	if (plugins[args->pa_pplugin].pl_init != NULL)
628 		plugins[args->pa_pplugin].pl_init();
629 	if (plugins[args->pa_plugin].pl_init != NULL)
630 		plugins[args->pa_plugin].pl_init();
631 }
632 
633 /*
634  * Shutdown module.
635  */
636 
637 void
638 pmcstat_shutdown_logging(struct pmcstat_args *args,
639     struct pmc_plugins *plugins,
640     struct pmcstat_stats *pmcstat_stats)
641 {
642 	struct pmcstat_image *pi, *pitmp;
643 	struct pmcstat_process *pp, *pptmp;
644 	struct pmcstat_pcmap *ppm, *ppmtmp;
645 	FILE *mf;
646 	int i;
647 
648 	/* determine where to send the map file */
649 	mf = NULL;
650 	if (args->pa_mapfilename != NULL)
651 		mf = (strcmp(args->pa_mapfilename, "-") == 0) ?
652 		    args->pa_printfile : fopen(args->pa_mapfilename, "w");
653 
654 	if (mf == NULL && args->pa_flags & FLAG_DO_GPROF &&
655 	    args->pa_verbosity >= 2)
656 		mf = args->pa_printfile;
657 
658 	if (mf)
659 		(void) fprintf(mf, "MAP:\n");
660 
661 	/*
662 	 * Shutdown the plugins
663 	 */
664 
665 	if (plugins[args->pa_plugin].pl_shutdown != NULL)
666 		plugins[args->pa_plugin].pl_shutdown(mf);
667 	if (plugins[args->pa_pplugin].pl_shutdown != NULL)
668 		plugins[args->pa_pplugin].pl_shutdown(mf);
669 
670 	for (i = 0; i < PMCSTAT_NHASH; i++) {
671 		LIST_FOREACH_SAFE(pi, &pmcstat_image_hash[i], pi_next,
672 		    pitmp) {
673 			if (plugins[args->pa_plugin].pl_shutdownimage != NULL)
674 				plugins[args->pa_plugin].pl_shutdownimage(pi);
675 			if (plugins[args->pa_pplugin].pl_shutdownimage != NULL)
676 				plugins[args->pa_pplugin].pl_shutdownimage(pi);
677 
678 			free(pi->pi_symbols);
679 			if (pi->pi_addr2line != NULL)
680 				pclose(pi->pi_addr2line);
681 			LIST_REMOVE(pi, pi_next);
682 			free(pi);
683 		}
684 
685 		LIST_FOREACH_SAFE(pp, &pmcstat_process_hash[i], pp_next,
686 		    pptmp) {
687 			TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
688 				TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
689 				free(ppm);
690 			}
691 			LIST_REMOVE(pp, pp_next);
692 			free(pp);
693 		}
694 	}
695 
696 	pmcstat_string_shutdown();
697 
698 	/*
699 	 * Print errors unless -q was specified.  Print all statistics
700 	 * if verbosity > 1.
701 	 */
702 #define	PRINT(N,V) do {							\
703 		if (pmcstat_stats->ps_##V || args->pa_verbosity >= 2)	\
704 			(void) fprintf(args->pa_printfile, " %-40s %d\n",\
705 			    N, pmcstat_stats->ps_##V);			\
706 	} while (0)
707 
708 	if (args->pa_verbosity >= 1 && (args->pa_flags & FLAG_DO_ANALYSIS)) {
709 		(void) fprintf(args->pa_printfile, "CONVERSION STATISTICS:\n");
710 		PRINT("#exec/a.out", exec_aout);
711 		PRINT("#exec/elf", exec_elf);
712 		PRINT("#exec/unknown", exec_indeterminable);
713 		PRINT("#exec handling errors", exec_errors);
714 		PRINT("#samples/total", samples_total);
715 		PRINT("#samples/unclaimed", samples_unknown_offset);
716 		PRINT("#samples/unknown-object", samples_indeterminable);
717 		PRINT("#samples/unknown-function", samples_unknown_function);
718 		PRINT("#callchain/dubious-frames", callchain_dubious_frames);
719 	}
720 
721 	if (mf)
722 		(void) fclose(mf);
723 }
724