xref: /freebsd/usr.sbin/pmcstat/pmcstat_log.c (revision 6486b015fc84e96725fef22b0e3363351399ae83)
1 /*-
2  * Copyright (c) 2005-2007, Joseph Koshy
3  * Copyright (c) 2007 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by A. Joseph Koshy under
7  * sponsorship from the FreeBSD Foundation and Google, Inc.
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  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 /*
32  * Transform a hwpmc(4) log into human readable form, and into
33  * gprof(1) compatible profiles.
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/endian.h>
41 #include <sys/cpuset.h>
42 #include <sys/gmon.h>
43 #include <sys/imgact_aout.h>
44 #include <sys/imgact_elf.h>
45 #include <sys/mman.h>
46 #include <sys/pmc.h>
47 #include <sys/queue.h>
48 #include <sys/socket.h>
49 #include <sys/stat.h>
50 #include <sys/wait.h>
51 
52 #include <netinet/in.h>
53 
54 #include <assert.h>
55 #include <curses.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <gelf.h>
60 #include <libgen.h>
61 #include <limits.h>
62 #include <netdb.h>
63 #include <pmc.h>
64 #include <pmclog.h>
65 #include <sysexits.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <unistd.h>
71 
72 #include "pmcstat.h"
73 #include "pmcstat_log.h"
74 #include "pmcstat_top.h"
75 
76 #define	PMCSTAT_ALLOCATE		1
77 
78 /*
79  * PUBLIC INTERFACES
80  *
81  * pmcstat_initialize_logging()	initialize this module, called first
82  * pmcstat_shutdown_logging()		orderly shutdown, called last
83  * pmcstat_open_log()			open an eventlog for processing
84  * pmcstat_process_log()		print/convert an event log
85  * pmcstat_display_log()		top mode display for the log
86  * pmcstat_close_log()			finish processing an event log
87  *
88  * IMPLEMENTATION NOTES
89  *
90  * We correlate each 'callchain' or 'sample' entry seen in the event
91  * log back to an executable object in the system. Executable objects
92  * include:
93  * 	- program executables,
94  *	- shared libraries loaded by the runtime loader,
95  *	- dlopen()'ed objects loaded by the program,
96  *	- the runtime loader itself,
97  *	- the kernel and kernel modules.
98  *
99  * Each process that we know about is treated as a set of regions that
100  * map to executable objects.  Processes are described by
101  * 'pmcstat_process' structures.  Executable objects are tracked by
102  * 'pmcstat_image' structures.  The kernel and kernel modules are
103  * common to all processes (they reside at the same virtual addresses
104  * for all processes).  Individual processes can have their text
105  * segments and shared libraries loaded at process-specific locations.
106  *
107  * A given executable object can be in use by multiple processes
108  * (e.g., libc.so) and loaded at a different address in each.
109  * pmcstat_pcmap structures track per-image mappings.
110  *
111  * The sample log could have samples from multiple PMCs; we
112  * generate one 'gmon.out' profile per PMC.
113  *
114  * IMPLEMENTATION OF GMON OUTPUT
115  *
116  * Each executable object gets one 'gmon.out' profile, per PMC in
117  * use.  Creation of 'gmon.out' profiles is done lazily.  The
118  * 'gmon.out' profiles generated for a given sampling PMC are
119  * aggregates of all the samples for that particular executable
120  * object.
121  *
122  * IMPLEMENTATION OF SYSTEM-WIDE CALLGRAPH OUTPUT
123  *
124  * Each active pmcid has its own callgraph structure, described by a
125  * 'struct pmcstat_callgraph'.  Given a process id and a list of pc
126  * values, we map each pc value to a tuple (image, symbol), where
127  * 'image' denotes an executable object and 'symbol' is the closest
128  * symbol that precedes the pc value.  Each pc value in the list is
129  * also given a 'rank' that reflects its depth in the call stack.
130  */
131 
132 struct pmcstat_pmcs pmcstat_pmcs = LIST_HEAD_INITIALIZER(pmcstat_pmcs);
133 
134 /*
135  * All image descriptors are kept in a hash table.
136  */
137 struct pmcstat_image_hash_list pmcstat_image_hash[PMCSTAT_NHASH];
138 
139 /*
140  * All process descriptors are kept in a hash table.
141  */
142 struct pmcstat_process_hash_list pmcstat_process_hash[PMCSTAT_NHASH];
143 
144 struct pmcstat_stats pmcstat_stats; /* statistics */
145 int ps_samples_period; /* samples count between top refresh. */
146 
147 struct pmcstat_process *pmcstat_kernproc; /* kernel 'process' */
148 
149 #include "pmcpl_gprof.h"
150 #include "pmcpl_callgraph.h"
151 #include "pmcpl_annotate.h"
152 #include "pmcpl_calltree.h"
153 
154 struct pmc_plugins  {
155 	const char 	*pl_name;	/* name */
156 
157 	/* configure */
158 	int (*pl_configure)(char *opt);
159 
160 	/* init and shutdown */
161 	int (*pl_init)(void);
162 	void (*pl_shutdown)(FILE *mf);
163 
164 	/* sample processing */
165 	void (*pl_process)(struct pmcstat_process *pp,
166 	    struct pmcstat_pmcrecord *pmcr, uint32_t nsamples,
167 	    uintfptr_t *cc, int usermode, uint32_t cpu);
168 
169 	/* image */
170 	void (*pl_initimage)(struct pmcstat_image *pi);
171 	void (*pl_shutdownimage)(struct pmcstat_image *pi);
172 
173 	/* pmc */
174 	void (*pl_newpmc)(pmcstat_interned_string ps,
175 		struct pmcstat_pmcrecord *pr);
176 
177 	/* top display */
178 	void (*pl_topdisplay)(void);
179 
180 	/* top keypress */
181 	int (*pl_topkeypress)(int c, WINDOW *w);
182 
183 } plugins[] = {
184 	{
185 		.pl_name		= "none",
186 	},
187 	{
188 		.pl_name		= "callgraph",
189 		.pl_init		= pmcpl_cg_init,
190 		.pl_shutdown		= pmcpl_cg_shutdown,
191 		.pl_process		= pmcpl_cg_process,
192 		.pl_topkeypress		= pmcpl_cg_topkeypress,
193 		.pl_topdisplay		= pmcpl_cg_topdisplay
194 	},
195 	{
196 		.pl_name		= "gprof",
197 		.pl_shutdown		= pmcpl_gmon_shutdown,
198 		.pl_process		= pmcpl_gmon_process,
199 		.pl_initimage		= pmcpl_gmon_initimage,
200 		.pl_shutdownimage	= pmcpl_gmon_shutdownimage,
201 		.pl_newpmc		= pmcpl_gmon_newpmc
202 	},
203 	{
204 		.pl_name		= "annotate",
205 		.pl_process		= pmcpl_annotate_process
206 	},
207 	{
208 		.pl_name		= "calltree",
209 		.pl_configure		= pmcpl_ct_configure,
210 		.pl_init		= pmcpl_ct_init,
211 		.pl_shutdown		= pmcpl_ct_shutdown,
212 		.pl_process		= pmcpl_ct_process,
213 		.pl_topkeypress		= pmcpl_ct_topkeypress,
214 		.pl_topdisplay		= pmcpl_ct_topdisplay
215 	},
216 	{
217 		.pl_name		= NULL
218 	}
219 };
220 
221 int pmcstat_mergepmc;
222 
223 int pmcstat_pmcinfilter = 0; /* PMC filter for top mode. */
224 float pmcstat_threshold = 0.5; /* Cost filter for top mode. */
225 
226 /*
227  * Prototypes
228  */
229 
230 static struct pmcstat_image *pmcstat_image_from_path(pmcstat_interned_string
231     _path, int _iskernelmodule);
232 static void pmcstat_image_get_aout_params(struct pmcstat_image *_image);
233 static void pmcstat_image_get_elf_params(struct pmcstat_image *_image);
234 static void	pmcstat_image_link(struct pmcstat_process *_pp,
235     struct pmcstat_image *_i, uintfptr_t _lpc);
236 
237 static void	pmcstat_pmcid_add(pmc_id_t _pmcid,
238     pmcstat_interned_string _name);
239 
240 static void	pmcstat_process_aout_exec(struct pmcstat_process *_pp,
241     struct pmcstat_image *_image, uintfptr_t _entryaddr);
242 static void	pmcstat_process_elf_exec(struct pmcstat_process *_pp,
243     struct pmcstat_image *_image, uintfptr_t _entryaddr);
244 static void	pmcstat_process_exec(struct pmcstat_process *_pp,
245     pmcstat_interned_string _path, uintfptr_t _entryaddr);
246 static struct pmcstat_process *pmcstat_process_lookup(pid_t _pid,
247     int _allocate);
248 static int	pmcstat_string_compute_hash(const char *_string);
249 static void pmcstat_string_initialize(void);
250 static int	pmcstat_string_lookup_hash(pmcstat_interned_string _is);
251 static void pmcstat_string_shutdown(void);
252 static void pmcstat_stats_reset(int _reset_global);
253 
254 /*
255  * A simple implementation of interned strings.  Each interned string
256  * is assigned a unique address, so that subsequent string compares
257  * can be done by a simple pointer comparison instead of using
258  * strcmp().  This speeds up hash table lookups and saves memory if
259  * duplicate strings are the norm.
260  */
261 struct pmcstat_string {
262 	LIST_ENTRY(pmcstat_string)	ps_next;	/* hash link */
263 	int		ps_len;
264 	int		ps_hash;
265 	char		*ps_string;
266 };
267 
268 static LIST_HEAD(,pmcstat_string)	pmcstat_string_hash[PMCSTAT_NHASH];
269 
270 /*
271  * PMC count.
272  */
273 int pmcstat_npmcs;
274 
275 /*
276  * PMC Top mode pause state.
277  */
278 int pmcstat_pause;
279 
280 static void
281 pmcstat_stats_reset(int reset_global)
282 {
283 	struct pmcstat_pmcrecord *pr;
284 
285 	/* Flush PMCs stats. */
286 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
287 		pr->pr_samples = 0;
288 		pr->pr_dubious_frames = 0;
289 	}
290 	ps_samples_period = 0;
291 
292 	/* Flush global stats. */
293 	if (reset_global)
294 		bzero(&pmcstat_stats, sizeof(struct pmcstat_stats));
295 }
296 
297 /*
298  * Compute a 'hash' value for a string.
299  */
300 
301 static int
302 pmcstat_string_compute_hash(const char *s)
303 {
304 	int hash;
305 
306 	for (hash = 0; *s; s++)
307 		hash ^= *s;
308 
309 	return (hash & PMCSTAT_HASH_MASK);
310 }
311 
312 /*
313  * Intern a copy of string 's', and return a pointer to the
314  * interned structure.
315  */
316 
317 pmcstat_interned_string
318 pmcstat_string_intern(const char *s)
319 {
320 	struct pmcstat_string *ps;
321 	const struct pmcstat_string *cps;
322 	int hash, len;
323 
324 	if ((cps = pmcstat_string_lookup(s)) != NULL)
325 		return (cps);
326 
327 	hash = pmcstat_string_compute_hash(s);
328 	len  = strlen(s);
329 
330 	if ((ps = malloc(sizeof(*ps))) == NULL)
331 		err(EX_OSERR, "ERROR: Could not intern string");
332 	ps->ps_len = len;
333 	ps->ps_hash = hash;
334 	ps->ps_string = strdup(s);
335 	LIST_INSERT_HEAD(&pmcstat_string_hash[hash], ps, ps_next);
336 	return ((pmcstat_interned_string) ps);
337 }
338 
339 const char *
340 pmcstat_string_unintern(pmcstat_interned_string str)
341 {
342 	const char *s;
343 
344 	s = ((const struct pmcstat_string *) str)->ps_string;
345 	return (s);
346 }
347 
348 pmcstat_interned_string
349 pmcstat_string_lookup(const char *s)
350 {
351 	struct pmcstat_string *ps;
352 	int hash, len;
353 
354 	hash = pmcstat_string_compute_hash(s);
355 	len = strlen(s);
356 
357 	LIST_FOREACH(ps, &pmcstat_string_hash[hash], ps_next)
358 	    if (ps->ps_len == len && ps->ps_hash == hash &&
359 		strcmp(ps->ps_string, s) == 0)
360 		    return (ps);
361 	return (NULL);
362 }
363 
364 static int
365 pmcstat_string_lookup_hash(pmcstat_interned_string s)
366 {
367 	const struct pmcstat_string *ps;
368 
369 	ps = (const struct pmcstat_string *) s;
370 	return (ps->ps_hash);
371 }
372 
373 /*
374  * Initialize the string interning facility.
375  */
376 
377 static void
378 pmcstat_string_initialize(void)
379 {
380 	int i;
381 
382 	for (i = 0; i < PMCSTAT_NHASH; i++)
383 		LIST_INIT(&pmcstat_string_hash[i]);
384 }
385 
386 /*
387  * Destroy the string table, free'ing up space.
388  */
389 
390 static void
391 pmcstat_string_shutdown(void)
392 {
393 	int i;
394 	struct pmcstat_string *ps, *pstmp;
395 
396 	for (i = 0; i < PMCSTAT_NHASH; i++)
397 		LIST_FOREACH_SAFE(ps, &pmcstat_string_hash[i], ps_next,
398 		    pstmp) {
399 			LIST_REMOVE(ps, ps_next);
400 			free(ps->ps_string);
401 			free(ps);
402 		}
403 }
404 
405 /*
406  * Determine whether a given executable image is an A.OUT object, and
407  * if so, fill in its parameters from the text file.
408  * Sets image->pi_type.
409  */
410 
411 static void
412 pmcstat_image_get_aout_params(struct pmcstat_image *image)
413 {
414 	int fd;
415 	ssize_t nbytes;
416 	struct exec ex;
417 	const char *path;
418 	char buffer[PATH_MAX];
419 
420 	path = pmcstat_string_unintern(image->pi_execpath);
421 	assert(path != NULL);
422 
423 	if (image->pi_iskernelmodule)
424 		errx(EX_SOFTWARE,
425 		    "ERROR: a.out kernel modules are unsupported \"%s\"", path);
426 
427 	(void) snprintf(buffer, sizeof(buffer), "%s%s",
428 	    args.pa_fsroot, path);
429 
430 	if ((fd = open(buffer, O_RDONLY, 0)) < 0 ||
431 	    (nbytes = read(fd, &ex, sizeof(ex))) < 0) {
432 		if (args.pa_verbosity >= 2)
433 			warn("WARNING: Cannot determine type of \"%s\"",
434 			    path);
435 		image->pi_type = PMCSTAT_IMAGE_INDETERMINABLE;
436 		if (fd != -1)
437 			(void) close(fd);
438 		return;
439 	}
440 
441 	(void) close(fd);
442 
443 	if ((unsigned) nbytes != sizeof(ex) ||
444 	    N_BADMAG(ex))
445 		return;
446 
447 	image->pi_type = PMCSTAT_IMAGE_AOUT;
448 
449 	/* TODO: the rest of a.out processing */
450 
451 	return;
452 }
453 
454 /*
455  * Helper function.
456  */
457 
458 static int
459 pmcstat_symbol_compare(const void *a, const void *b)
460 {
461 	const struct pmcstat_symbol *sym1, *sym2;
462 
463 	sym1 = (const struct pmcstat_symbol *) a;
464 	sym2 = (const struct pmcstat_symbol *) b;
465 
466 	if (sym1->ps_end <= sym2->ps_start)
467 		return (-1);
468 	if (sym1->ps_start >= sym2->ps_end)
469 		return (1);
470 	return (0);
471 }
472 
473 /*
474  * Map an address to a symbol in an image.
475  */
476 
477 struct pmcstat_symbol *
478 pmcstat_symbol_search(struct pmcstat_image *image, uintfptr_t addr)
479 {
480 	struct pmcstat_symbol sym;
481 
482 	if (image->pi_symbols == NULL)
483 		return (NULL);
484 
485 	sym.ps_name  = NULL;
486 	sym.ps_start = addr;
487 	sym.ps_end   = addr + 1;
488 
489 	return (bsearch((void *) &sym, image->pi_symbols,
490 		    image->pi_symcount, sizeof(struct pmcstat_symbol),
491 		    pmcstat_symbol_compare));
492 }
493 
494 /*
495  * Add the list of symbols in the given section to the list associated
496  * with the object.
497  */
498 static void
499 pmcstat_image_add_symbols(struct pmcstat_image *image, Elf *e,
500     Elf_Scn *scn, GElf_Shdr *sh)
501 {
502 	int firsttime;
503 	size_t n, newsyms, nshsyms, nfuncsyms;
504 	struct pmcstat_symbol *symptr;
505 	char *fnname;
506 	GElf_Sym sym;
507 	Elf_Data *data;
508 
509 	if ((data = elf_getdata(scn, NULL)) == NULL)
510 		return;
511 
512 	/*
513 	 * Determine the number of functions named in this
514 	 * section.
515 	 */
516 
517 	nshsyms = sh->sh_size / sh->sh_entsize;
518 	for (n = nfuncsyms = 0; n < nshsyms; n++) {
519 		if (gelf_getsym(data, (int) n, &sym) != &sym)
520 			return;
521 		if (GELF_ST_TYPE(sym.st_info) == STT_FUNC)
522 			nfuncsyms++;
523 	}
524 
525 	if (nfuncsyms == 0)
526 		return;
527 
528 	/*
529 	 * Allocate space for the new entries.
530 	 */
531 	firsttime = image->pi_symbols == NULL;
532 	symptr = realloc(image->pi_symbols,
533 	    sizeof(*symptr) * (image->pi_symcount + nfuncsyms));
534 	if (symptr == image->pi_symbols) /* realloc() failed. */
535 		return;
536 	image->pi_symbols = symptr;
537 
538 	/*
539 	 * Append new symbols to the end of the current table.
540 	 */
541 	symptr += image->pi_symcount;
542 
543 	for (n = newsyms = 0; n < nshsyms; n++) {
544 		if (gelf_getsym(data, (int) n, &sym) != &sym)
545 			return;
546 		if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
547 			continue;
548 		if (sym.st_shndx == STN_UNDEF)
549 			continue;
550 
551 		if (!firsttime && pmcstat_symbol_search(image, sym.st_value))
552 			continue; /* We've seen this symbol already. */
553 
554 		if ((fnname = elf_strptr(e, sh->sh_link, sym.st_name))
555 		    == NULL)
556 			continue;
557 
558 		symptr->ps_name  = pmcstat_string_intern(fnname);
559 		symptr->ps_start = sym.st_value - image->pi_vaddr;
560 		symptr->ps_end   = symptr->ps_start + sym.st_size;
561 		symptr++;
562 
563 		newsyms++;
564 	}
565 
566 	image->pi_symcount += newsyms;
567 
568 	assert(newsyms <= nfuncsyms);
569 
570 	/*
571 	 * Return space to the system if there were duplicates.
572 	 */
573 	if (newsyms < nfuncsyms)
574 		image->pi_symbols = realloc(image->pi_symbols,
575 		    sizeof(*symptr) * image->pi_symcount);
576 
577 	/*
578 	 * Keep the list of symbols sorted.
579 	 */
580 	qsort(image->pi_symbols, image->pi_symcount, sizeof(*symptr),
581 	    pmcstat_symbol_compare);
582 
583 	/*
584 	 * Deal with function symbols that have a size of 'zero' by
585 	 * making them extend to the next higher address.  These
586 	 * symbols are usually defined in assembly code.
587 	 */
588 	for (symptr = image->pi_symbols;
589 	     symptr < image->pi_symbols + (image->pi_symcount - 1);
590 	     symptr++)
591 		if (symptr->ps_start == symptr->ps_end)
592 			symptr->ps_end = (symptr+1)->ps_start;
593 }
594 
595 /*
596  * Examine an ELF file to determine the size of its text segment.
597  * Sets image->pi_type if anything conclusive can be determined about
598  * this image.
599  */
600 
601 static void
602 pmcstat_image_get_elf_params(struct pmcstat_image *image)
603 {
604 	int fd;
605 	size_t i, nph, nsh;
606 	const char *path, *elfbase;
607 	char *p, *endp;
608 	uintfptr_t minva, maxva;
609 	Elf *e;
610 	Elf_Scn *scn;
611 	GElf_Ehdr eh;
612 	GElf_Phdr ph;
613 	GElf_Shdr sh;
614 	enum pmcstat_image_type image_type;
615 	char buffer[PATH_MAX];
616 
617 	assert(image->pi_type == PMCSTAT_IMAGE_UNKNOWN);
618 
619 	image->pi_start = minva = ~(uintfptr_t) 0;
620 	image->pi_end = maxva = (uintfptr_t) 0;
621 	image->pi_type = image_type = PMCSTAT_IMAGE_INDETERMINABLE;
622 	image->pi_isdynamic = 0;
623 	image->pi_dynlinkerpath = NULL;
624 	image->pi_vaddr = 0;
625 
626 	path = pmcstat_string_unintern(image->pi_execpath);
627 	assert(path != NULL);
628 
629 	/*
630 	 * Look for kernel modules under FSROOT/KERNELPATH/NAME,
631 	 * and user mode executable objects under FSROOT/PATHNAME.
632 	 */
633 	if (image->pi_iskernelmodule)
634 		(void) snprintf(buffer, sizeof(buffer), "%s%s/%s",
635 		    args.pa_fsroot, args.pa_kernel, path);
636 	else
637 		(void) snprintf(buffer, sizeof(buffer), "%s%s",
638 		    args.pa_fsroot, path);
639 
640 	e = NULL;
641 	if ((fd = open(buffer, O_RDONLY, 0)) < 0 ||
642 	    (e = elf_begin(fd, ELF_C_READ, NULL)) == NULL ||
643 	    (elf_kind(e) != ELF_K_ELF)) {
644 		if (args.pa_verbosity >= 2)
645 			warnx("WARNING: Cannot determine the type of \"%s\".",
646 			    buffer);
647 		goto done;
648 	}
649 
650 	if (gelf_getehdr(e, &eh) != &eh) {
651 		warnx(
652 		    "WARNING: Cannot retrieve the ELF Header for \"%s\": %s.",
653 		    buffer, elf_errmsg(-1));
654 		goto done;
655 	}
656 
657 	if (eh.e_type != ET_EXEC && eh.e_type != ET_DYN &&
658 	    !(image->pi_iskernelmodule && eh.e_type == ET_REL)) {
659 		warnx("WARNING: \"%s\" is of an unsupported ELF type.",
660 		    buffer);
661 		goto done;
662 	}
663 
664 	image_type = eh.e_ident[EI_CLASS] == ELFCLASS32 ?
665 	    PMCSTAT_IMAGE_ELF32 : PMCSTAT_IMAGE_ELF64;
666 
667 	/*
668 	 * Determine the virtual address where an executable would be
669 	 * loaded.  Additionally, for dynamically linked executables,
670 	 * save the pathname to the runtime linker.
671 	 */
672 	if (eh.e_type == ET_EXEC) {
673 		if (elf_getphnum(e, &nph) == 0) {
674 			warnx(
675 "WARNING: Could not determine the number of program headers in \"%s\": %s.",
676 			    buffer,
677 			    elf_errmsg(-1));
678 			goto done;
679 		}
680 		for (i = 0; i < eh.e_phnum; i++) {
681 			if (gelf_getphdr(e, i, &ph) != &ph) {
682 				warnx(
683 "WARNING: Retrieval of PHDR entry #%ju in \"%s\" failed: %s.",
684 				    (uintmax_t) i, buffer, elf_errmsg(-1));
685 				goto done;
686 			}
687 			switch (ph.p_type) {
688 			case PT_DYNAMIC:
689 				image->pi_isdynamic = 1;
690 				break;
691 			case PT_INTERP:
692 				if ((elfbase = elf_rawfile(e, NULL)) == NULL) {
693 					warnx(
694 "WARNING: Cannot retrieve the interpreter for \"%s\": %s.",
695 					    buffer, elf_errmsg(-1));
696 					goto done;
697 				}
698 				image->pi_dynlinkerpath =
699 				    pmcstat_string_intern(elfbase +
700 				        ph.p_offset);
701 				break;
702 			case PT_LOAD:
703 				if ((ph.p_offset & (-ph.p_align)) == 0)
704 					image->pi_vaddr = ph.p_vaddr & (-ph.p_align);
705 				break;
706 			}
707 		}
708 	}
709 
710 	/*
711 	 * Get the min and max VA associated with this ELF object.
712 	 */
713 	if (elf_getshnum(e, &nsh) == 0) {
714 		warnx(
715 "WARNING: Could not determine the number of sections for \"%s\": %s.",
716 		    buffer, elf_errmsg(-1));
717 		goto done;
718 	}
719 
720 	for (i = 0; i < nsh; i++) {
721 		if ((scn = elf_getscn(e, i)) == NULL ||
722 		    gelf_getshdr(scn, &sh) != &sh) {
723 			warnx(
724 "WARNING: Could not retrieve section header #%ju in \"%s\": %s.",
725 			    (uintmax_t) i, buffer, elf_errmsg(-1));
726 			goto done;
727 		}
728 		if (sh.sh_flags & SHF_EXECINSTR) {
729 			minva = min(minva, sh.sh_addr);
730 			maxva = max(maxva, sh.sh_addr + sh.sh_size);
731 		}
732 		if (sh.sh_type == SHT_SYMTAB || sh.sh_type == SHT_DYNSYM)
733 			pmcstat_image_add_symbols(image, e, scn, &sh);
734 	}
735 
736 	image->pi_start = minva;
737 	image->pi_end   = maxva;
738 	image->pi_type  = image_type;
739 	image->pi_fullpath = pmcstat_string_intern(buffer);
740 
741 	/* Build display name
742 	 */
743 	endp = buffer;
744 	for (p = buffer; *p; p++)
745 		if (*p == '/')
746 			endp = p+1;
747 	image->pi_name = pmcstat_string_intern(endp);
748 
749  done:
750 	(void) elf_end(e);
751 	if (fd >= 0)
752 		(void) close(fd);
753 	return;
754 }
755 
756 /*
757  * Given an image descriptor, determine whether it is an ELF, or AOUT.
758  * If no handler claims the image, set its type to 'INDETERMINABLE'.
759  */
760 
761 void
762 pmcstat_image_determine_type(struct pmcstat_image *image)
763 {
764 	assert(image->pi_type == PMCSTAT_IMAGE_UNKNOWN);
765 
766 	/* Try each kind of handler in turn */
767 	if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
768 		pmcstat_image_get_elf_params(image);
769 	if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
770 		pmcstat_image_get_aout_params(image);
771 
772 	/*
773 	 * Otherwise, remember that we tried to determine
774 	 * the object's type and had failed.
775 	 */
776 	if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
777 		image->pi_type = PMCSTAT_IMAGE_INDETERMINABLE;
778 }
779 
780 /*
781  * Locate an image descriptor given an interned path, adding a fresh
782  * descriptor to the cache if necessary.  This function also finds a
783  * suitable name for this image's sample file.
784  *
785  * We defer filling in the file format specific parts of the image
786  * structure till the time we actually see a sample that would fall
787  * into this image.
788  */
789 
790 static struct pmcstat_image *
791 pmcstat_image_from_path(pmcstat_interned_string internedpath,
792     int iskernelmodule)
793 {
794 	int hash;
795 	struct pmcstat_image *pi;
796 
797 	hash = pmcstat_string_lookup_hash(internedpath);
798 
799 	/* First, look for an existing entry. */
800 	LIST_FOREACH(pi, &pmcstat_image_hash[hash], pi_next)
801 	    if (pi->pi_execpath == internedpath &&
802 		  pi->pi_iskernelmodule == iskernelmodule)
803 		    return (pi);
804 
805 	/*
806 	 * Allocate a new entry and place it at the head of the hash
807 	 * and LRU lists.
808 	 */
809 	pi = malloc(sizeof(*pi));
810 	if (pi == NULL)
811 		return (NULL);
812 
813 	pi->pi_type = PMCSTAT_IMAGE_UNKNOWN;
814 	pi->pi_execpath = internedpath;
815 	pi->pi_start = ~0;
816 	pi->pi_end = 0;
817 	pi->pi_entry = 0;
818 	pi->pi_vaddr = 0;
819 	pi->pi_isdynamic = 0;
820 	pi->pi_iskernelmodule = iskernelmodule;
821 	pi->pi_dynlinkerpath = NULL;
822 	pi->pi_symbols = NULL;
823 	pi->pi_symcount = 0;
824 	pi->pi_addr2line = NULL;
825 
826 	if (plugins[args.pa_pplugin].pl_initimage != NULL)
827 		plugins[args.pa_pplugin].pl_initimage(pi);
828 	if (plugins[args.pa_plugin].pl_initimage != NULL)
829 		plugins[args.pa_plugin].pl_initimage(pi);
830 
831 	LIST_INSERT_HEAD(&pmcstat_image_hash[hash], pi, pi_next);
832 
833 	return (pi);
834 }
835 
836 /*
837  * Record the fact that PC values from 'start' to 'end' come from
838  * image 'image'.
839  */
840 
841 static void
842 pmcstat_image_link(struct pmcstat_process *pp, struct pmcstat_image *image,
843     uintfptr_t start)
844 {
845 	struct pmcstat_pcmap *pcm, *pcmnew;
846 	uintfptr_t offset;
847 
848 	assert(image->pi_type != PMCSTAT_IMAGE_UNKNOWN &&
849 	    image->pi_type != PMCSTAT_IMAGE_INDETERMINABLE);
850 
851 	if ((pcmnew = malloc(sizeof(*pcmnew))) == NULL)
852 		err(EX_OSERR, "ERROR: Cannot create a map entry");
853 
854 	/*
855 	 * Adjust the map entry to only cover the text portion
856 	 * of the object.
857 	 */
858 
859 	offset = start - image->pi_vaddr;
860 	pcmnew->ppm_lowpc  = image->pi_start + offset;
861 	pcmnew->ppm_highpc = image->pi_end + offset;
862 	pcmnew->ppm_image  = image;
863 
864 	assert(pcmnew->ppm_lowpc < pcmnew->ppm_highpc);
865 
866 	/* Overlapped mmap()'s are assumed to never occur. */
867 	TAILQ_FOREACH(pcm, &pp->pp_map, ppm_next)
868 	    if (pcm->ppm_lowpc >= pcmnew->ppm_highpc)
869 		    break;
870 
871 	if (pcm == NULL)
872 		TAILQ_INSERT_TAIL(&pp->pp_map, pcmnew, ppm_next);
873 	else
874 		TAILQ_INSERT_BEFORE(pcm, pcmnew, ppm_next);
875 }
876 
877 /*
878  * Unmap images in the range [start..end) associated with process
879  * 'pp'.
880  */
881 
882 static void
883 pmcstat_image_unmap(struct pmcstat_process *pp, uintfptr_t start,
884     uintfptr_t end)
885 {
886 	struct pmcstat_pcmap *pcm, *pcmtmp, *pcmnew;
887 
888 	assert(pp != NULL);
889 	assert(start < end);
890 
891 	/*
892 	 * Cases:
893 	 * - we could have the range completely in the middle of an
894 	 *   existing pcmap; in this case we have to split the pcmap
895 	 *   structure into two (i.e., generate a 'hole').
896 	 * - we could have the range covering multiple pcmaps; these
897 	 *   will have to be removed.
898 	 * - we could have either 'start' or 'end' falling in the
899 	 *   middle of a pcmap; in this case shorten the entry.
900 	 */
901 	TAILQ_FOREACH_SAFE(pcm, &pp->pp_map, ppm_next, pcmtmp) {
902 		assert(pcm->ppm_lowpc < pcm->ppm_highpc);
903 		if (pcm->ppm_highpc <= start)
904 			continue;
905 		if (pcm->ppm_lowpc >= end)
906 			return;
907 		if (pcm->ppm_lowpc >= start && pcm->ppm_highpc <= end) {
908 			/*
909 			 * The current pcmap is completely inside the
910 			 * unmapped range: remove it entirely.
911 			 */
912 			TAILQ_REMOVE(&pp->pp_map, pcm, ppm_next);
913 			free(pcm);
914 		} else if (pcm->ppm_lowpc < start && pcm->ppm_highpc > end) {
915 			/*
916 			 * Split this pcmap into two; curtail the
917 			 * current map to end at [start-1], and start
918 			 * the new one at [end].
919 			 */
920 			if ((pcmnew = malloc(sizeof(*pcmnew))) == NULL)
921 				err(EX_OSERR,
922 				    "ERROR: Cannot split a map entry");
923 
924 			pcmnew->ppm_image = pcm->ppm_image;
925 
926 			pcmnew->ppm_lowpc = end;
927 			pcmnew->ppm_highpc = pcm->ppm_highpc;
928 
929 			pcm->ppm_highpc = start;
930 
931 			TAILQ_INSERT_AFTER(&pp->pp_map, pcm, pcmnew, ppm_next);
932 
933 			return;
934 		} else if (pcm->ppm_lowpc < start && pcm->ppm_highpc <= end)
935 			pcm->ppm_highpc = start;
936 		else if (pcm->ppm_lowpc >= start && pcm->ppm_highpc > end)
937 			pcm->ppm_lowpc = end;
938 		else
939 			assert(0);
940 	}
941 }
942 
943 /*
944  * Resolve file name and line number for the given address.
945  */
946 int
947 pmcstat_image_addr2line(struct pmcstat_image *image, uintfptr_t addr,
948     char *sourcefile, size_t sourcefile_len, unsigned *sourceline,
949     char *funcname, size_t funcname_len)
950 {
951 	static int addr2line_warn = 0;
952 	unsigned l;
953 
954 	char *sep, cmdline[PATH_MAX], imagepath[PATH_MAX];
955 	int fd;
956 
957 	if (image->pi_addr2line == NULL) {
958 		snprintf(imagepath, sizeof(imagepath), "%s%s.symbols",
959 		    args.pa_fsroot,
960 		    pmcstat_string_unintern(image->pi_fullpath));
961 		fd = open(imagepath, O_RDONLY);
962 		if (fd < 0) {
963 			snprintf(imagepath, sizeof(imagepath), "%s%s",
964 			    args.pa_fsroot,
965 			    pmcstat_string_unintern(image->pi_fullpath));
966 		} else
967 			close(fd);
968 		/*
969 		 * New addr2line support recursive inline function with -i
970 		 * but the format does not add a marker when no more entries
971 		 * are available.
972 		 */
973 		snprintf(cmdline, sizeof(cmdline), "addr2line -Cfe \"%s\"",
974 		    imagepath);
975 		image->pi_addr2line = popen(cmdline, "r+");
976 		if (image->pi_addr2line == NULL) {
977 			if (!addr2line_warn) {
978 				addr2line_warn = 1;
979 				warnx(
980 "WARNING: addr2line is needed for source code information."
981 				    );
982 			}
983 			return (0);
984 		}
985 	}
986 
987 	if (feof(image->pi_addr2line) || ferror(image->pi_addr2line)) {
988 		warnx("WARNING: addr2line pipe error");
989 		pclose(image->pi_addr2line);
990 		image->pi_addr2line = NULL;
991 		return (0);
992 	}
993 
994 	fprintf(image->pi_addr2line, "%p\n", (void *)addr);
995 
996 	if (fgets(funcname, funcname_len, image->pi_addr2line) == NULL) {
997 		warnx("WARNING: addr2line function name read error");
998 		return (0);
999 	}
1000 	sep = strchr(funcname, '\n');
1001 	if (sep != NULL)
1002 		*sep = '\0';
1003 
1004 	if (fgets(sourcefile, sourcefile_len, image->pi_addr2line) == NULL) {
1005 		warnx("WARNING: addr2line source file read error");
1006 		return (0);
1007 	}
1008 	sep = strchr(sourcefile, ':');
1009 	if (sep == NULL) {
1010 		warnx("WARNING: addr2line source line separator missing");
1011 		return (0);
1012 	}
1013 	*sep = '\0';
1014 	l = atoi(sep+1);
1015 	if (l == 0)
1016 		return (0);
1017 	*sourceline = l;
1018 	return (1);
1019 }
1020 
1021 /*
1022  * Add a {pmcid,name} mapping.
1023  */
1024 
1025 static void
1026 pmcstat_pmcid_add(pmc_id_t pmcid, pmcstat_interned_string ps)
1027 {
1028 	struct pmcstat_pmcrecord *pr, *prm;
1029 
1030 	/* Replace an existing name for the PMC. */
1031 	prm = NULL;
1032 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1033 		if (pr->pr_pmcid == pmcid) {
1034 			pr->pr_pmcname = ps;
1035 			return;
1036 		} else if (pr->pr_pmcname == ps)
1037 			prm = pr;
1038 
1039 	/*
1040 	 * Otherwise, allocate a new descriptor and call the
1041 	 * plugins hook.
1042 	 */
1043 	if ((pr = malloc(sizeof(*pr))) == NULL)
1044 		err(EX_OSERR, "ERROR: Cannot allocate pmc record");
1045 
1046 	pr->pr_pmcid = pmcid;
1047 	pr->pr_pmcname = ps;
1048 	pr->pr_pmcin = pmcstat_npmcs++;
1049 	pr->pr_samples = 0;
1050 	pr->pr_dubious_frames = 0;
1051 	pr->pr_merge = prm == NULL ? pr : prm;
1052 
1053 	LIST_INSERT_HEAD(&pmcstat_pmcs, pr, pr_next);
1054 
1055 	if (plugins[args.pa_pplugin].pl_newpmc != NULL)
1056 		plugins[args.pa_pplugin].pl_newpmc(ps, pr);
1057 	if (plugins[args.pa_plugin].pl_newpmc != NULL)
1058 		plugins[args.pa_plugin].pl_newpmc(ps, pr);
1059 }
1060 
1061 /*
1062  * Given a pmcid in use, find its human-readable name.
1063  */
1064 
1065 const char *
1066 pmcstat_pmcid_to_name(pmc_id_t pmcid)
1067 {
1068 	struct pmcstat_pmcrecord *pr;
1069 
1070 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1071 	    if (pr->pr_pmcid == pmcid)
1072 		    return (pmcstat_string_unintern(pr->pr_pmcname));
1073 
1074 	return NULL;
1075 }
1076 
1077 /*
1078  * Convert PMC index to name.
1079  */
1080 
1081 const char *
1082 pmcstat_pmcindex_to_name(int pmcin)
1083 {
1084 	struct pmcstat_pmcrecord *pr;
1085 
1086 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1087 		if (pr->pr_pmcin == pmcin)
1088 			return pmcstat_string_unintern(pr->pr_pmcname);
1089 
1090 	return NULL;
1091 }
1092 
1093 /*
1094  * Return PMC record with given index.
1095  */
1096 
1097 struct pmcstat_pmcrecord *
1098 pmcstat_pmcindex_to_pmcr(int pmcin)
1099 {
1100 	struct pmcstat_pmcrecord *pr;
1101 
1102 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1103 		if (pr->pr_pmcin == pmcin)
1104 			return pr;
1105 
1106 	return NULL;
1107 }
1108 
1109 /*
1110  * Get PMC record by id, apply merge policy.
1111  */
1112 
1113 static struct pmcstat_pmcrecord *
1114 pmcstat_lookup_pmcid(pmc_id_t pmcid)
1115 {
1116 	struct pmcstat_pmcrecord *pr;
1117 
1118 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
1119 		if (pr->pr_pmcid == pmcid) {
1120 			if (pmcstat_mergepmc)
1121 				return pr->pr_merge;
1122 			return pr;
1123 		}
1124 	}
1125 
1126 	return NULL;
1127 }
1128 
1129 /*
1130  * Associate an AOUT image with a process.
1131  */
1132 
1133 static void
1134 pmcstat_process_aout_exec(struct pmcstat_process *pp,
1135     struct pmcstat_image *image, uintfptr_t entryaddr)
1136 {
1137 	(void) pp;
1138 	(void) image;
1139 	(void) entryaddr;
1140 	/* TODO Implement a.out handling */
1141 }
1142 
1143 /*
1144  * Associate an ELF image with a process.
1145  */
1146 
1147 static void
1148 pmcstat_process_elf_exec(struct pmcstat_process *pp,
1149     struct pmcstat_image *image, uintfptr_t entryaddr)
1150 {
1151 	uintmax_t libstart;
1152 	struct pmcstat_image *rtldimage;
1153 
1154 	assert(image->pi_type == PMCSTAT_IMAGE_ELF32 ||
1155 	    image->pi_type == PMCSTAT_IMAGE_ELF64);
1156 
1157 	/* Create a map entry for the base executable. */
1158 	pmcstat_image_link(pp, image, image->pi_vaddr);
1159 
1160 	/*
1161 	 * For dynamically linked executables we need to determine
1162 	 * where the dynamic linker was mapped to for this process,
1163 	 * Subsequent executable objects that are mapped in by the
1164 	 * dynamic linker will be tracked by log events of type
1165 	 * PMCLOG_TYPE_MAP_IN.
1166 	 */
1167 
1168 	if (image->pi_isdynamic) {
1169 
1170 		/*
1171 		 * The runtime loader gets loaded just after the maximum
1172 		 * possible heap address.  Like so:
1173 		 *
1174 		 * [  TEXT DATA BSS HEAP -->*RTLD  SHLIBS   <--STACK]
1175 		 * ^					            ^
1176 		 * 0				   VM_MAXUSER_ADDRESS
1177 
1178 		 *
1179 		 * The exact address where the loader gets mapped in
1180 		 * will vary according to the size of the executable
1181 		 * and the limits on the size of the process'es data
1182 		 * segment at the time of exec().  The entry address
1183 		 * recorded at process exec time corresponds to the
1184 		 * 'start' address inside the dynamic linker.  From
1185 		 * this we can figure out the address where the
1186 		 * runtime loader's file object had been mapped to.
1187 		 */
1188 		rtldimage = pmcstat_image_from_path(image->pi_dynlinkerpath, 0);
1189 		if (rtldimage == NULL) {
1190 			warnx("WARNING: Cannot find image for \"%s\".",
1191 			    pmcstat_string_unintern(image->pi_dynlinkerpath));
1192 			pmcstat_stats.ps_exec_errors++;
1193 			return;
1194 		}
1195 
1196 		if (rtldimage->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1197 			pmcstat_image_get_elf_params(rtldimage);
1198 
1199 		if (rtldimage->pi_type != PMCSTAT_IMAGE_ELF32 &&
1200 		    rtldimage->pi_type != PMCSTAT_IMAGE_ELF64) {
1201 			warnx("WARNING: rtld not an ELF object \"%s\".",
1202 			    pmcstat_string_unintern(image->pi_dynlinkerpath));
1203 			return;
1204 		}
1205 
1206 		libstart = entryaddr - rtldimage->pi_entry;
1207 		pmcstat_image_link(pp, rtldimage, libstart);
1208 	}
1209 }
1210 
1211 /*
1212  * Find the process descriptor corresponding to a PID.  If 'allocate'
1213  * is zero, we return a NULL if a pid descriptor could not be found or
1214  * a process descriptor process.  If 'allocate' is non-zero, then we
1215  * will attempt to allocate a fresh process descriptor.  Zombie
1216  * process descriptors are only removed if a fresh allocation for the
1217  * same PID is requested.
1218  */
1219 
1220 static struct pmcstat_process *
1221 pmcstat_process_lookup(pid_t pid, int allocate)
1222 {
1223 	uint32_t hash;
1224 	struct pmcstat_pcmap *ppm, *ppmtmp;
1225 	struct pmcstat_process *pp, *pptmp;
1226 
1227 	hash = (uint32_t) pid & PMCSTAT_HASH_MASK;	/* simplicity wins */
1228 
1229 	LIST_FOREACH_SAFE(pp, &pmcstat_process_hash[hash], pp_next, pptmp)
1230 		if (pp->pp_pid == pid) {
1231 			/* Found a descriptor, check and process zombies */
1232 			if (allocate && pp->pp_isactive == 0) {
1233 				/* remove maps */
1234 				TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next,
1235 				    ppmtmp) {
1236 					TAILQ_REMOVE(&pp->pp_map, ppm,
1237 					    ppm_next);
1238 					free(ppm);
1239 				}
1240 				/* remove process entry */
1241 				LIST_REMOVE(pp, pp_next);
1242 				free(pp);
1243 				break;
1244 			}
1245 			return (pp);
1246 		}
1247 
1248 	if (!allocate)
1249 		return (NULL);
1250 
1251 	if ((pp = malloc(sizeof(*pp))) == NULL)
1252 		err(EX_OSERR, "ERROR: Cannot allocate pid descriptor");
1253 
1254 	pp->pp_pid = pid;
1255 	pp->pp_isactive = 1;
1256 
1257 	TAILQ_INIT(&pp->pp_map);
1258 
1259 	LIST_INSERT_HEAD(&pmcstat_process_hash[hash], pp, pp_next);
1260 	return (pp);
1261 }
1262 
1263 /*
1264  * Associate an image and a process.
1265  */
1266 
1267 static void
1268 pmcstat_process_exec(struct pmcstat_process *pp,
1269     pmcstat_interned_string path, uintfptr_t entryaddr)
1270 {
1271 	struct pmcstat_image *image;
1272 
1273 	if ((image = pmcstat_image_from_path(path, 0)) == NULL) {
1274 		pmcstat_stats.ps_exec_errors++;
1275 		return;
1276 	}
1277 
1278 	if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1279 		pmcstat_image_determine_type(image);
1280 
1281 	assert(image->pi_type != PMCSTAT_IMAGE_UNKNOWN);
1282 
1283 	switch (image->pi_type) {
1284 	case PMCSTAT_IMAGE_ELF32:
1285 	case PMCSTAT_IMAGE_ELF64:
1286 		pmcstat_stats.ps_exec_elf++;
1287 		pmcstat_process_elf_exec(pp, image, entryaddr);
1288 		break;
1289 
1290 	case PMCSTAT_IMAGE_AOUT:
1291 		pmcstat_stats.ps_exec_aout++;
1292 		pmcstat_process_aout_exec(pp, image, entryaddr);
1293 		break;
1294 
1295 	case PMCSTAT_IMAGE_INDETERMINABLE:
1296 		pmcstat_stats.ps_exec_indeterminable++;
1297 		break;
1298 
1299 	default:
1300 		err(EX_SOFTWARE,
1301 		    "ERROR: Unsupported executable type for \"%s\"",
1302 		    pmcstat_string_unintern(path));
1303 	}
1304 }
1305 
1306 
1307 /*
1308  * Find the map entry associated with process 'p' at PC value 'pc'.
1309  */
1310 
1311 struct pmcstat_pcmap *
1312 pmcstat_process_find_map(struct pmcstat_process *p, uintfptr_t pc)
1313 {
1314 	struct pmcstat_pcmap *ppm;
1315 
1316 	TAILQ_FOREACH(ppm, &p->pp_map, ppm_next) {
1317 		if (pc >= ppm->ppm_lowpc && pc < ppm->ppm_highpc)
1318 			return (ppm);
1319 		if (pc < ppm->ppm_lowpc)
1320 			return (NULL);
1321 	}
1322 
1323 	return (NULL);
1324 }
1325 
1326 /*
1327  * Convert a hwpmc(4) log to profile information.  A system-wide
1328  * callgraph is generated if FLAG_DO_CALLGRAPHS is set.  gmon.out
1329  * files usable by gprof(1) are created if FLAG_DO_GPROF is set.
1330  */
1331 static int
1332 pmcstat_analyze_log(void)
1333 {
1334 	uint32_t cpu, cpuflags;
1335 	uintfptr_t pc;
1336 	pid_t pid;
1337 	struct pmcstat_image *image;
1338 	struct pmcstat_process *pp, *ppnew;
1339 	struct pmcstat_pcmap *ppm, *ppmtmp;
1340 	struct pmclog_ev ev;
1341 	struct pmcstat_pmcrecord *pmcr;
1342 	pmcstat_interned_string image_path;
1343 
1344 	assert(args.pa_flags & FLAG_DO_ANALYSIS);
1345 
1346 	if (elf_version(EV_CURRENT) == EV_NONE)
1347 		err(EX_UNAVAILABLE, "Elf library intialization failed");
1348 
1349 	while (pmclog_read(args.pa_logparser, &ev) == 0) {
1350 		assert(ev.pl_state == PMCLOG_OK);
1351 
1352 		switch (ev.pl_type) {
1353 		case PMCLOG_TYPE_INITIALIZE:
1354 			if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
1355 			    PMC_VERSION_MAJOR << 24 && args.pa_verbosity > 0)
1356 				warnx(
1357 "WARNING: Log version 0x%x does not match compiled version 0x%x.",
1358 				    ev.pl_u.pl_i.pl_version, PMC_VERSION_MAJOR);
1359 			break;
1360 
1361 		case PMCLOG_TYPE_MAP_IN:
1362 			/*
1363 			 * Introduce an address range mapping for a
1364 			 * userland process or the kernel (pid == -1).
1365 			 *
1366 			 * We always allocate a process descriptor so
1367 			 * that subsequent samples seen for this
1368 			 * address range are mapped to the current
1369 			 * object being mapped in.
1370 			 */
1371 			pid = ev.pl_u.pl_mi.pl_pid;
1372 			if (pid == -1)
1373 				pp = pmcstat_kernproc;
1374 			else
1375 				pp = pmcstat_process_lookup(pid,
1376 				    PMCSTAT_ALLOCATE);
1377 
1378 			assert(pp != NULL);
1379 
1380 			image_path = pmcstat_string_intern(ev.pl_u.pl_mi.
1381 			    pl_pathname);
1382 			image = pmcstat_image_from_path(image_path, pid == -1);
1383 			if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1384 				pmcstat_image_determine_type(image);
1385 			if (image->pi_type != PMCSTAT_IMAGE_INDETERMINABLE)
1386 				pmcstat_image_link(pp, image,
1387 				    ev.pl_u.pl_mi.pl_start);
1388 			break;
1389 
1390 		case PMCLOG_TYPE_MAP_OUT:
1391 			/*
1392 			 * Remove an address map.
1393 			 */
1394 			pid = ev.pl_u.pl_mo.pl_pid;
1395 			if (pid == -1)
1396 				pp = pmcstat_kernproc;
1397 			else
1398 				pp = pmcstat_process_lookup(pid, 0);
1399 
1400 			if (pp == NULL)	/* unknown process */
1401 				break;
1402 
1403 			pmcstat_image_unmap(pp, ev.pl_u.pl_mo.pl_start,
1404 			    ev.pl_u.pl_mo.pl_end);
1405 			break;
1406 
1407 		case PMCLOG_TYPE_PCSAMPLE:
1408 			/*
1409 			 * Note: the `PCSAMPLE' log entry is not
1410 			 * generated by hpwmc(4) after version 2.
1411 			 */
1412 
1413 			/*
1414 			 * We bring in the gmon file for the image
1415 			 * currently associated with the PMC & pid
1416 			 * pair and increment the appropriate entry
1417 			 * bin inside this.
1418 			 */
1419 			pmcstat_stats.ps_samples_total++;
1420 			ps_samples_period++;
1421 
1422 			pc = ev.pl_u.pl_s.pl_pc;
1423 			pp = pmcstat_process_lookup(ev.pl_u.pl_s.pl_pid,
1424 			    PMCSTAT_ALLOCATE);
1425 
1426 			/* Get PMC record. */
1427 			pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_s.pl_pmcid);
1428 			assert(pmcr != NULL);
1429 			pmcr->pr_samples++;
1430 
1431 			/*
1432 			 * Call the plugins processing
1433 			 * TODO: move pmcstat_process_find_map inside plugins
1434 			 */
1435 
1436 			if (plugins[args.pa_pplugin].pl_process != NULL)
1437 				plugins[args.pa_pplugin].pl_process(
1438 				    pp, pmcr, 1, &pc,
1439 				    pmcstat_process_find_map(pp, pc) != NULL, 0);
1440 			plugins[args.pa_plugin].pl_process(
1441 			    pp, pmcr, 1, &pc,
1442 			    pmcstat_process_find_map(pp, pc) != NULL, 0);
1443 			break;
1444 
1445 		case PMCLOG_TYPE_CALLCHAIN:
1446 			pmcstat_stats.ps_samples_total++;
1447 			ps_samples_period++;
1448 
1449 			cpuflags = ev.pl_u.pl_cc.pl_cpuflags;
1450 			cpu = PMC_CALLCHAIN_CPUFLAGS_TO_CPU(cpuflags);
1451 
1452 			/* Filter on the CPU id. */
1453 			if (!CPU_ISSET(cpu, &(args.pa_cpumask))) {
1454 				pmcstat_stats.ps_samples_skipped++;
1455 				break;
1456 			}
1457 
1458 			pp = pmcstat_process_lookup(ev.pl_u.pl_cc.pl_pid,
1459 			    PMCSTAT_ALLOCATE);
1460 
1461 			/* Get PMC record. */
1462 			pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_cc.pl_pmcid);
1463 			assert(pmcr != NULL);
1464 			pmcr->pr_samples++;
1465 
1466 			/*
1467 			 * Call the plugins processing
1468 			 */
1469 
1470 			if (plugins[args.pa_pplugin].pl_process != NULL)
1471 				plugins[args.pa_pplugin].pl_process(
1472 				    pp, pmcr,
1473 				    ev.pl_u.pl_cc.pl_npc,
1474 				    ev.pl_u.pl_cc.pl_pc,
1475 				    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
1476 				    cpu);
1477 			plugins[args.pa_plugin].pl_process(
1478 			    pp, pmcr,
1479 			    ev.pl_u.pl_cc.pl_npc,
1480 			    ev.pl_u.pl_cc.pl_pc,
1481 			    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
1482 			    cpu);
1483 			break;
1484 
1485 		case PMCLOG_TYPE_PMCALLOCATE:
1486 			/*
1487 			 * Record the association pmc id between this
1488 			 * PMC and its name.
1489 			 */
1490 			pmcstat_pmcid_add(ev.pl_u.pl_a.pl_pmcid,
1491 			    pmcstat_string_intern(ev.pl_u.pl_a.pl_evname));
1492 			break;
1493 
1494 		case PMCLOG_TYPE_PMCALLOCATEDYN:
1495 			/*
1496 			 * Record the association pmc id between this
1497 			 * PMC and its name.
1498 			 */
1499 			pmcstat_pmcid_add(ev.pl_u.pl_ad.pl_pmcid,
1500 			    pmcstat_string_intern(ev.pl_u.pl_ad.pl_evname));
1501 			break;
1502 
1503 		case PMCLOG_TYPE_PROCEXEC:
1504 
1505 			/*
1506 			 * Change the executable image associated with
1507 			 * a process.
1508 			 */
1509 			pp = pmcstat_process_lookup(ev.pl_u.pl_x.pl_pid,
1510 			    PMCSTAT_ALLOCATE);
1511 
1512 			/* delete the current process map */
1513 			TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
1514 				TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
1515 				free(ppm);
1516 			}
1517 
1518 			/* associate this process  image */
1519 			image_path = pmcstat_string_intern(
1520 				ev.pl_u.pl_x.pl_pathname);
1521 			assert(image_path != NULL);
1522 			pmcstat_process_exec(pp, image_path,
1523 			    ev.pl_u.pl_x.pl_entryaddr);
1524 			break;
1525 
1526 		case PMCLOG_TYPE_PROCEXIT:
1527 
1528 			/*
1529 			 * Due to the way the log is generated, the
1530 			 * last few samples corresponding to a process
1531 			 * may appear in the log after the process
1532 			 * exit event is recorded.  Thus we keep the
1533 			 * process' descriptor and associated data
1534 			 * structures around, but mark the process as
1535 			 * having exited.
1536 			 */
1537 			pp = pmcstat_process_lookup(ev.pl_u.pl_e.pl_pid, 0);
1538 			if (pp == NULL)
1539 				break;
1540 			pp->pp_isactive = 0;	/* mark as a zombie */
1541 			break;
1542 
1543 		case PMCLOG_TYPE_SYSEXIT:
1544 			pp = pmcstat_process_lookup(ev.pl_u.pl_se.pl_pid, 0);
1545 			if (pp == NULL)
1546 				break;
1547 			pp->pp_isactive = 0;	/* make a zombie */
1548 			break;
1549 
1550 		case PMCLOG_TYPE_PROCFORK:
1551 
1552 			/*
1553 			 * Allocate a process descriptor for the new
1554 			 * (child) process.
1555 			 */
1556 			ppnew =
1557 			    pmcstat_process_lookup(ev.pl_u.pl_f.pl_newpid,
1558 				PMCSTAT_ALLOCATE);
1559 
1560 			/*
1561 			 * If we had been tracking the parent, clone
1562 			 * its address maps.
1563 			 */
1564 			pp = pmcstat_process_lookup(ev.pl_u.pl_f.pl_oldpid, 0);
1565 			if (pp == NULL)
1566 				break;
1567 			TAILQ_FOREACH(ppm, &pp->pp_map, ppm_next)
1568 			    pmcstat_image_link(ppnew, ppm->ppm_image,
1569 				ppm->ppm_lowpc);
1570 			break;
1571 
1572 		default:	/* other types of entries are not relevant */
1573 			break;
1574 		}
1575 	}
1576 
1577 	if (ev.pl_state == PMCLOG_EOF)
1578 		return (PMCSTAT_FINISHED);
1579 	else if (ev.pl_state == PMCLOG_REQUIRE_DATA)
1580 		return (PMCSTAT_RUNNING);
1581 
1582 	err(EX_DATAERR,
1583 	    "ERROR: event parsing failed (record %jd, offset 0x%jx)",
1584 	    (uintmax_t) ev.pl_count + 1, ev.pl_offset);
1585 }
1586 
1587 /*
1588  * Print log entries as text.
1589  */
1590 
1591 static int
1592 pmcstat_print_log(void)
1593 {
1594 	struct pmclog_ev ev;
1595 	uint32_t npc;
1596 
1597 	while (pmclog_read(args.pa_logparser, &ev) == 0) {
1598 		assert(ev.pl_state == PMCLOG_OK);
1599 		switch (ev.pl_type) {
1600 		case PMCLOG_TYPE_CALLCHAIN:
1601 			PMCSTAT_PRINT_ENTRY("callchain",
1602 			    "%d 0x%x %d %d %c", ev.pl_u.pl_cc.pl_pid,
1603 			    ev.pl_u.pl_cc.pl_pmcid,
1604 			    PMC_CALLCHAIN_CPUFLAGS_TO_CPU(ev.pl_u.pl_cc. \
1605 				pl_cpuflags), ev.pl_u.pl_cc.pl_npc,
1606 			    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(ev.pl_u.pl_cc.\
1607 			        pl_cpuflags) ? 'u' : 's');
1608 			for (npc = 0; npc < ev.pl_u.pl_cc.pl_npc; npc++)
1609 				PMCSTAT_PRINT_ENTRY("...", "%p",
1610 				    (void *) ev.pl_u.pl_cc.pl_pc[npc]);
1611 			break;
1612 		case PMCLOG_TYPE_CLOSELOG:
1613 			PMCSTAT_PRINT_ENTRY("closelog",);
1614 			break;
1615 		case PMCLOG_TYPE_DROPNOTIFY:
1616 			PMCSTAT_PRINT_ENTRY("drop",);
1617 			break;
1618 		case PMCLOG_TYPE_INITIALIZE:
1619 			PMCSTAT_PRINT_ENTRY("initlog","0x%x \"%s\"",
1620 			    ev.pl_u.pl_i.pl_version,
1621 			    pmc_name_of_cputype(ev.pl_u.pl_i.pl_arch));
1622 			if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
1623 			    PMC_VERSION_MAJOR << 24 && args.pa_verbosity > 0)
1624 				warnx(
1625 "WARNING: Log version 0x%x != expected version 0x%x.",
1626 				    ev.pl_u.pl_i.pl_version, PMC_VERSION);
1627 			break;
1628 		case PMCLOG_TYPE_MAP_IN:
1629 			PMCSTAT_PRINT_ENTRY("map-in","%d %p \"%s\"",
1630 			    ev.pl_u.pl_mi.pl_pid,
1631 			    (void *) ev.pl_u.pl_mi.pl_start,
1632 			    ev.pl_u.pl_mi.pl_pathname);
1633 			break;
1634 		case PMCLOG_TYPE_MAP_OUT:
1635 			PMCSTAT_PRINT_ENTRY("map-out","%d %p %p",
1636 			    ev.pl_u.pl_mo.pl_pid,
1637 			    (void *) ev.pl_u.pl_mo.pl_start,
1638 			    (void *) ev.pl_u.pl_mo.pl_end);
1639 			break;
1640 		case PMCLOG_TYPE_PCSAMPLE:
1641 			PMCSTAT_PRINT_ENTRY("sample","0x%x %d %p %c",
1642 			    ev.pl_u.pl_s.pl_pmcid,
1643 			    ev.pl_u.pl_s.pl_pid,
1644 			    (void *) ev.pl_u.pl_s.pl_pc,
1645 			    ev.pl_u.pl_s.pl_usermode ? 'u' : 's');
1646 			break;
1647 		case PMCLOG_TYPE_PMCALLOCATE:
1648 			PMCSTAT_PRINT_ENTRY("allocate","0x%x \"%s\" 0x%x",
1649 			    ev.pl_u.pl_a.pl_pmcid,
1650 			    ev.pl_u.pl_a.pl_evname,
1651 			    ev.pl_u.pl_a.pl_flags);
1652 			break;
1653 		case PMCLOG_TYPE_PMCALLOCATEDYN:
1654 			PMCSTAT_PRINT_ENTRY("allocatedyn","0x%x \"%s\" 0x%x",
1655 			    ev.pl_u.pl_ad.pl_pmcid,
1656 			    ev.pl_u.pl_ad.pl_evname,
1657 			    ev.pl_u.pl_ad.pl_flags);
1658 			break;
1659 		case PMCLOG_TYPE_PMCATTACH:
1660 			PMCSTAT_PRINT_ENTRY("attach","0x%x %d \"%s\"",
1661 			    ev.pl_u.pl_t.pl_pmcid,
1662 			    ev.pl_u.pl_t.pl_pid,
1663 			    ev.pl_u.pl_t.pl_pathname);
1664 			break;
1665 		case PMCLOG_TYPE_PMCDETACH:
1666 			PMCSTAT_PRINT_ENTRY("detach","0x%x %d",
1667 			    ev.pl_u.pl_d.pl_pmcid,
1668 			    ev.pl_u.pl_d.pl_pid);
1669 			break;
1670 		case PMCLOG_TYPE_PROCCSW:
1671 			PMCSTAT_PRINT_ENTRY("cswval","0x%x %d %jd",
1672 			    ev.pl_u.pl_c.pl_pmcid,
1673 			    ev.pl_u.pl_c.pl_pid,
1674 			    ev.pl_u.pl_c.pl_value);
1675 			break;
1676 		case PMCLOG_TYPE_PROCEXEC:
1677 			PMCSTAT_PRINT_ENTRY("exec","0x%x %d %p \"%s\"",
1678 			    ev.pl_u.pl_x.pl_pmcid,
1679 			    ev.pl_u.pl_x.pl_pid,
1680 			    (void *) ev.pl_u.pl_x.pl_entryaddr,
1681 			    ev.pl_u.pl_x.pl_pathname);
1682 			break;
1683 		case PMCLOG_TYPE_PROCEXIT:
1684 			PMCSTAT_PRINT_ENTRY("exitval","0x%x %d %jd",
1685 			    ev.pl_u.pl_e.pl_pmcid,
1686 			    ev.pl_u.pl_e.pl_pid,
1687 			    ev.pl_u.pl_e.pl_value);
1688 			break;
1689 		case PMCLOG_TYPE_PROCFORK:
1690 			PMCSTAT_PRINT_ENTRY("fork","%d %d",
1691 			    ev.pl_u.pl_f.pl_oldpid,
1692 			    ev.pl_u.pl_f.pl_newpid);
1693 			break;
1694 		case PMCLOG_TYPE_USERDATA:
1695 			PMCSTAT_PRINT_ENTRY("userdata","0x%x",
1696 			    ev.pl_u.pl_u.pl_userdata);
1697 			break;
1698 		case PMCLOG_TYPE_SYSEXIT:
1699 			PMCSTAT_PRINT_ENTRY("exit","%d",
1700 			    ev.pl_u.pl_se.pl_pid);
1701 			break;
1702 		default:
1703 			fprintf(args.pa_printfile, "unknown event (type %d).\n",
1704 			    ev.pl_type);
1705 		}
1706 	}
1707 
1708 	if (ev.pl_state == PMCLOG_EOF)
1709 		return (PMCSTAT_FINISHED);
1710 	else if (ev.pl_state ==  PMCLOG_REQUIRE_DATA)
1711 		return (PMCSTAT_RUNNING);
1712 
1713 	errx(EX_DATAERR,
1714 	    "ERROR: event parsing failed (record %jd, offset 0x%jx).",
1715 	    (uintmax_t) ev.pl_count + 1, ev.pl_offset);
1716 	/*NOTREACHED*/
1717 }
1718 
1719 /*
1720  * Public Interfaces.
1721  */
1722 
1723 /*
1724  * Close a logfile, after first flushing all in-module queued data.
1725  */
1726 
1727 int
1728 pmcstat_close_log(void)
1729 {
1730 	/* If a local logfile is configured ask the kernel to stop
1731 	 * and flush data. Kernel will close the file when data is flushed
1732 	 * so keep the status to EXITING.
1733 	 */
1734 	if (args.pa_logfd != -1) {
1735 		if (pmc_close_logfile() < 0)
1736 			err(EX_OSERR, "ERROR: logging failed");
1737 	}
1738 
1739 	return (args.pa_flags & FLAG_HAS_PIPE ? PMCSTAT_EXITING :
1740 	    PMCSTAT_FINISHED);
1741 }
1742 
1743 
1744 
1745 /*
1746  * Open a log file, for reading or writing.
1747  *
1748  * The function returns the fd of a successfully opened log or -1 in
1749  * case of failure.
1750  */
1751 
1752 int
1753 pmcstat_open_log(const char *path, int mode)
1754 {
1755 	int error, fd, cfd;
1756 	size_t hlen;
1757 	const char *p, *errstr;
1758 	struct addrinfo hints, *res, *res0;
1759 	char hostname[MAXHOSTNAMELEN];
1760 
1761 	errstr = NULL;
1762 	fd = -1;
1763 
1764 	/*
1765 	 * If 'path' is "-" then open one of stdin or stdout depending
1766 	 * on the value of 'mode'.
1767 	 *
1768 	 * If 'path' contains a ':' and does not start with a '/' or '.',
1769 	 * and is being opened for writing, treat it as a "host:port"
1770 	 * specification and open a network socket.
1771 	 *
1772 	 * Otherwise, treat 'path' as a file name and open that.
1773 	 */
1774 	if (path[0] == '-' && path[1] == '\0')
1775 		fd = (mode == PMCSTAT_OPEN_FOR_READ) ? 0 : 1;
1776 	else if (path[0] != '/' &&
1777 	    path[0] != '.' && strchr(path, ':') != NULL) {
1778 
1779 		p = strrchr(path, ':');
1780 		hlen = p - path;
1781 		if (p == path || hlen >= sizeof(hostname)) {
1782 			errstr = strerror(EINVAL);
1783 			goto done;
1784 		}
1785 
1786 		assert(hlen < sizeof(hostname));
1787 		(void) strncpy(hostname, path, hlen);
1788 		hostname[hlen] = '\0';
1789 
1790 		(void) memset(&hints, 0, sizeof(hints));
1791 		hints.ai_family = AF_UNSPEC;
1792 		hints.ai_socktype = SOCK_STREAM;
1793 		if ((error = getaddrinfo(hostname, p+1, &hints, &res0)) != 0) {
1794 			errstr = gai_strerror(error);
1795 			goto done;
1796 		}
1797 
1798 		fd = -1;
1799 		for (res = res0; res; res = res->ai_next) {
1800 			if ((fd = socket(res->ai_family, res->ai_socktype,
1801 			    res->ai_protocol)) < 0) {
1802 				errstr = strerror(errno);
1803 				continue;
1804 			}
1805 			if (mode == PMCSTAT_OPEN_FOR_READ) {
1806 				if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {
1807 					errstr = strerror(errno);
1808 					(void) close(fd);
1809 					fd = -1;
1810 					continue;
1811 				}
1812 				listen(fd, 1);
1813 				cfd = accept(fd, NULL, NULL);
1814 				(void) close(fd);
1815 				if (cfd < 0) {
1816 					errstr = strerror(errno);
1817 					fd = -1;
1818 					break;
1819 				}
1820 				fd = cfd;
1821 			} else {
1822 				if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
1823 					errstr = strerror(errno);
1824 					(void) close(fd);
1825 					fd = -1;
1826 					continue;
1827 				}
1828 			}
1829 			errstr = NULL;
1830 			break;
1831 		}
1832 		freeaddrinfo(res0);
1833 
1834 	} else if ((fd = open(path, mode == PMCSTAT_OPEN_FOR_READ ?
1835 		    O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC),
1836 		    S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
1837 			errstr = strerror(errno);
1838 
1839   done:
1840 	if (errstr)
1841 		errx(EX_OSERR, "ERROR: Cannot open \"%s\" for %s: %s.", path,
1842 		    (mode == PMCSTAT_OPEN_FOR_READ ? "reading" : "writing"),
1843 		    errstr);
1844 
1845 	return (fd);
1846 }
1847 
1848 /*
1849  * Process a log file in offline analysis mode.
1850  */
1851 
1852 int
1853 pmcstat_process_log(void)
1854 {
1855 
1856 	/*
1857 	 * If analysis has not been asked for, just print the log to
1858 	 * the current output file.
1859 	 */
1860 	if (args.pa_flags & FLAG_DO_PRINT)
1861 		return (pmcstat_print_log());
1862 	else
1863 		return (pmcstat_analyze_log());
1864 }
1865 
1866 /*
1867  * Refresh top display.
1868  */
1869 
1870 static void
1871 pmcstat_refresh_top(void)
1872 {
1873 	int v_attrs;
1874 	float v;
1875 	char pmcname[40];
1876 	struct pmcstat_pmcrecord *pmcpr;
1877 
1878 	/* If in pause mode do not refresh display. */
1879 	if (pmcstat_pause)
1880 		return;
1881 
1882 	/* Wait until PMC pop in the log. */
1883 	pmcpr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
1884 	if (pmcpr == NULL)
1885 		return;
1886 
1887 	/* Format PMC name. */
1888 	if (pmcstat_mergepmc)
1889 		snprintf(pmcname, sizeof(pmcname), "[%s]",
1890 		    pmcstat_string_unintern(pmcpr->pr_pmcname));
1891 	else
1892 		snprintf(pmcname, sizeof(pmcname), "%s.%d",
1893 		    pmcstat_string_unintern(pmcpr->pr_pmcname),
1894 		    pmcstat_pmcinfilter);
1895 
1896 	/* Format samples count. */
1897 	if (ps_samples_period > 0)
1898 		v = (pmcpr->pr_samples * 100.0) / ps_samples_period;
1899 	else
1900 		v = 0.;
1901 	v_attrs = PMCSTAT_ATTRPERCENT(v);
1902 
1903 	PMCSTAT_PRINTBEGIN();
1904 	PMCSTAT_PRINTW("PMC: %s Samples: %u ",
1905 	    pmcname,
1906 	    pmcpr->pr_samples);
1907 	PMCSTAT_ATTRON(v_attrs);
1908 	PMCSTAT_PRINTW("(%.1f%%) ", v);
1909 	PMCSTAT_ATTROFF(v_attrs);
1910 	PMCSTAT_PRINTW(", %u unresolved\n\n",
1911 	    pmcpr->pr_dubious_frames);
1912 	if (plugins[args.pa_plugin].pl_topdisplay != NULL)
1913 		plugins[args.pa_plugin].pl_topdisplay();
1914 	PMCSTAT_PRINTEND();
1915 }
1916 
1917 /*
1918  * Find the next pmc index to display.
1919  */
1920 
1921 static void
1922 pmcstat_changefilter(void)
1923 {
1924 	int pmcin;
1925 	struct pmcstat_pmcrecord *pmcr;
1926 
1927 	/*
1928 	 * Find the next merge target.
1929 	 */
1930 	if (pmcstat_mergepmc) {
1931 		pmcin = pmcstat_pmcinfilter;
1932 
1933 		do {
1934 			pmcr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
1935 			if (pmcr == NULL || pmcr == pmcr->pr_merge)
1936 				break;
1937 
1938 			pmcstat_pmcinfilter++;
1939 			if (pmcstat_pmcinfilter >= pmcstat_npmcs)
1940 				pmcstat_pmcinfilter = 0;
1941 
1942 		} while (pmcstat_pmcinfilter != pmcin);
1943 	}
1944 }
1945 
1946 /*
1947  * Top mode keypress.
1948  */
1949 
1950 int
1951 pmcstat_keypress_log(void)
1952 {
1953 	int c, ret = 0;
1954 	WINDOW *w;
1955 
1956 	w = newwin(1, 0, 1, 0);
1957 	c = wgetch(w);
1958 	wprintw(w, "Key: %c => ", c);
1959 	switch (c) {
1960 	case 'c':
1961 		wprintw(w, "enter mode 'd' or 'a' => ");
1962 		c = wgetch(w);
1963 		if (c == 'd') {
1964 			args.pa_topmode = PMCSTAT_TOP_DELTA;
1965 			wprintw(w, "switching to delta mode");
1966 		} else {
1967 			args.pa_topmode = PMCSTAT_TOP_ACCUM;
1968 			wprintw(w, "switching to accumulation mode");
1969 		}
1970 		break;
1971 	case 'm':
1972 		pmcstat_mergepmc = !pmcstat_mergepmc;
1973 		/*
1974 		 * Changing merge state require data reset.
1975 		 */
1976 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
1977 			plugins[args.pa_plugin].pl_shutdown(NULL);
1978 		pmcstat_stats_reset(0);
1979 		if (plugins[args.pa_plugin].pl_init != NULL)
1980 			plugins[args.pa_plugin].pl_init();
1981 
1982 		/* Update filter to be on a merge target. */
1983 		pmcstat_changefilter();
1984 		wprintw(w, "merge PMC %s", pmcstat_mergepmc ? "on" : "off");
1985 		break;
1986 	case 'n':
1987 		/* Close current plugin. */
1988 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
1989 			plugins[args.pa_plugin].pl_shutdown(NULL);
1990 
1991 		/* Find next top display available. */
1992 		do {
1993 			args.pa_plugin++;
1994 			if (plugins[args.pa_plugin].pl_name == NULL)
1995 				args.pa_plugin = 0;
1996 		} while (plugins[args.pa_plugin].pl_topdisplay == NULL);
1997 
1998 		/* Open new plugin. */
1999 		pmcstat_stats_reset(0);
2000 		if (plugins[args.pa_plugin].pl_init != NULL)
2001 			plugins[args.pa_plugin].pl_init();
2002 		wprintw(w, "switching to plugin %s",
2003 		    plugins[args.pa_plugin].pl_name);
2004 		break;
2005 	case 'p':
2006 		pmcstat_pmcinfilter++;
2007 		if (pmcstat_pmcinfilter >= pmcstat_npmcs)
2008 			pmcstat_pmcinfilter = 0;
2009 		pmcstat_changefilter();
2010 		wprintw(w, "switching to PMC %s.%d",
2011 		    pmcstat_pmcindex_to_name(pmcstat_pmcinfilter),
2012 		    pmcstat_pmcinfilter);
2013 		break;
2014 	case ' ':
2015 		pmcstat_pause = !pmcstat_pause;
2016 		if (pmcstat_pause)
2017 			wprintw(w, "pause => press space again to continue");
2018 		break;
2019 	case 'q':
2020 		wprintw(w, "exiting...");
2021 		ret = 1;
2022 		break;
2023 	default:
2024 		if (plugins[args.pa_plugin].pl_topkeypress != NULL)
2025 			if (plugins[args.pa_plugin].pl_topkeypress(c, w))
2026 				ret = 1;
2027 	}
2028 
2029 	wrefresh(w);
2030 	delwin(w);
2031 	return ret;
2032 }
2033 
2034 
2035 /*
2036  * Top mode display.
2037  */
2038 
2039 void
2040 pmcstat_display_log(void)
2041 {
2042 
2043 	pmcstat_refresh_top();
2044 
2045 	/* Reset everythings if delta mode. */
2046 	if (args.pa_topmode == PMCSTAT_TOP_DELTA) {
2047 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
2048 			plugins[args.pa_plugin].pl_shutdown(NULL);
2049 		pmcstat_stats_reset(0);
2050 		if (plugins[args.pa_plugin].pl_init != NULL)
2051 			plugins[args.pa_plugin].pl_init();
2052 	}
2053 
2054 }
2055 
2056 /*
2057  * Configure a plugins.
2058  */
2059 
2060 void
2061 pmcstat_pluginconfigure_log(char *opt)
2062 {
2063 
2064 	if (strncmp(opt, "threshold=", 10) == 0) {
2065 		pmcstat_threshold = atof(opt+10);
2066 	} else {
2067 		if (plugins[args.pa_plugin].pl_configure != NULL) {
2068 			if (!plugins[args.pa_plugin].pl_configure(opt))
2069 				err(EX_USAGE,
2070 				    "ERROR: unknown option <%s>.", opt);
2071 		}
2072 	}
2073 }
2074 
2075 /*
2076  * Initialize module.
2077  */
2078 
2079 void
2080 pmcstat_initialize_logging(void)
2081 {
2082 	int i;
2083 
2084 	/* use a convenient format for 'ldd' output */
2085 	if (setenv("LD_TRACE_LOADED_OBJECTS_FMT1","%o \"%p\" %x\n",1) != 0)
2086 		err(EX_OSERR, "ERROR: Cannot setenv");
2087 
2088 	/* Initialize hash tables */
2089 	pmcstat_string_initialize();
2090 	for (i = 0; i < PMCSTAT_NHASH; i++) {
2091 		LIST_INIT(&pmcstat_image_hash[i]);
2092 		LIST_INIT(&pmcstat_process_hash[i]);
2093 	}
2094 
2095 	/*
2096 	 * Create a fake 'process' entry for the kernel with pid -1.
2097 	 * hwpmc(4) will subsequently inform us about where the kernel
2098 	 * and any loaded kernel modules are mapped.
2099 	 */
2100 	if ((pmcstat_kernproc = pmcstat_process_lookup((pid_t) -1,
2101 		 PMCSTAT_ALLOCATE)) == NULL)
2102 		err(EX_OSERR, "ERROR: Cannot initialize logging");
2103 
2104 	/* PMC count. */
2105 	pmcstat_npmcs = 0;
2106 
2107 	/* Merge PMC with same name. */
2108 	pmcstat_mergepmc = args.pa_mergepmc;
2109 
2110 	/*
2111 	 * Initialize plugins
2112 	 */
2113 
2114 	if (plugins[args.pa_pplugin].pl_init != NULL)
2115 		plugins[args.pa_pplugin].pl_init();
2116 	if (plugins[args.pa_plugin].pl_init != NULL)
2117 		plugins[args.pa_plugin].pl_init();
2118 }
2119 
2120 /*
2121  * Shutdown module.
2122  */
2123 
2124 void
2125 pmcstat_shutdown_logging(void)
2126 {
2127 	int i;
2128 	FILE *mf;
2129 	struct pmcstat_image *pi, *pitmp;
2130 	struct pmcstat_process *pp, *pptmp;
2131 	struct pmcstat_pcmap *ppm, *ppmtmp;
2132 
2133 	/* determine where to send the map file */
2134 	mf = NULL;
2135 	if (args.pa_mapfilename != NULL)
2136 		mf = (strcmp(args.pa_mapfilename, "-") == 0) ?
2137 		    args.pa_printfile : fopen(args.pa_mapfilename, "w");
2138 
2139 	if (mf == NULL && args.pa_flags & FLAG_DO_GPROF &&
2140 	    args.pa_verbosity >= 2)
2141 		mf = args.pa_printfile;
2142 
2143 	if (mf)
2144 		(void) fprintf(mf, "MAP:\n");
2145 
2146 	/*
2147 	 * Shutdown the plugins
2148 	 */
2149 
2150 	if (plugins[args.pa_plugin].pl_shutdown != NULL)
2151 		plugins[args.pa_plugin].pl_shutdown(mf);
2152 	if (plugins[args.pa_pplugin].pl_shutdown != NULL)
2153 		plugins[args.pa_pplugin].pl_shutdown(mf);
2154 
2155 	for (i = 0; i < PMCSTAT_NHASH; i++) {
2156 		LIST_FOREACH_SAFE(pi, &pmcstat_image_hash[i], pi_next,
2157 		    pitmp) {
2158 			if (plugins[args.pa_plugin].pl_shutdownimage != NULL)
2159 				plugins[args.pa_plugin].pl_shutdownimage(pi);
2160 			if (plugins[args.pa_pplugin].pl_shutdownimage != NULL)
2161 				plugins[args.pa_pplugin].pl_shutdownimage(pi);
2162 
2163 			free(pi->pi_symbols);
2164 			if (pi->pi_addr2line != NULL)
2165 				pclose(pi->pi_addr2line);
2166 			LIST_REMOVE(pi, pi_next);
2167 			free(pi);
2168 		}
2169 
2170 		LIST_FOREACH_SAFE(pp, &pmcstat_process_hash[i], pp_next,
2171 		    pptmp) {
2172 			TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
2173 				TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
2174 				free(ppm);
2175 			}
2176 			LIST_REMOVE(pp, pp_next);
2177 			free(pp);
2178 		}
2179 	}
2180 
2181 	pmcstat_string_shutdown();
2182 
2183 	/*
2184 	 * Print errors unless -q was specified.  Print all statistics
2185 	 * if verbosity > 1.
2186 	 */
2187 #define	PRINT(N,V) do {							\
2188 		if (pmcstat_stats.ps_##V || args.pa_verbosity >= 2)	\
2189 			(void) fprintf(args.pa_printfile, " %-40s %d\n",\
2190 			    N, pmcstat_stats.ps_##V);			\
2191 	} while (0)
2192 
2193 	if (args.pa_verbosity >= 1 && (args.pa_flags & FLAG_DO_ANALYSIS)) {
2194 		(void) fprintf(args.pa_printfile, "CONVERSION STATISTICS:\n");
2195 		PRINT("#exec/a.out", exec_aout);
2196 		PRINT("#exec/elf", exec_elf);
2197 		PRINT("#exec/unknown", exec_indeterminable);
2198 		PRINT("#exec handling errors", exec_errors);
2199 		PRINT("#samples/total", samples_total);
2200 		PRINT("#samples/unclaimed", samples_unknown_offset);
2201 		PRINT("#samples/unknown-object", samples_indeterminable);
2202 		PRINT("#samples/unknown-function", samples_unknown_function);
2203 		PRINT("#callchain/dubious-frames", callchain_dubious_frames);
2204 	}
2205 
2206 	if (mf)
2207 		(void) fclose(mf);
2208 }
2209