2 * Copyright (c) 2005-2007, Joseph Koshy
3 * Copyright (c) 2007 The FreeBSD Foundation
6 * Portions of this software were developed by A. Joseph Koshy under
7 * sponsorship from the FreeBSD Foundation and Google, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
32 * Transform a hwpmc(4) log into human readable form, and into
33 * gprof(1) compatible profiles.
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/param.h>
40 #include <sys/endian.h>
41 #include <sys/cpuset.h>
43 #include <sys/imgact_aout.h>
44 #include <sys/imgact_elf.h>
47 #include <sys/queue.h>
48 #include <sys/socket.h>
52 #include <netinet/in.h>
73 #include "pmcstat_log.h"
74 #include "pmcstat_top.h"
76 #define PMCSTAT_ALLOCATE 1
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
88 * IMPLEMENTATION NOTES
90 * We correlate each 'callchain' or 'sample' entry seen in the event
91 * log back to an executable object in the system. Executable objects
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.
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.
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.
111 * The sample log could have samples from multiple PMCs; we
112 * generate one 'gmon.out' profile per PMC.
114 * IMPLEMENTATION OF GMON OUTPUT
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
122 * IMPLEMENTATION OF SYSTEM-WIDE CALLGRAPH OUTPUT
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.
132 struct pmcstat_pmcs pmcstat_pmcs = LIST_HEAD_INITIALIZER(pmcstat_pmcs);
135 * All image descriptors are kept in a hash table.
137 struct pmcstat_image_hash_list pmcstat_image_hash[PMCSTAT_NHASH];
140 * All process descriptors are kept in a hash table.
142 struct pmcstat_process_hash_list pmcstat_process_hash[PMCSTAT_NHASH];
144 struct pmcstat_stats pmcstat_stats; /* statistics */
145 static int ps_samples_period; /* samples count between top refresh. */
147 struct pmcstat_process *pmcstat_kernproc; /* kernel 'process' */
149 #include "pmcpl_gprof.h"
150 #include "pmcpl_callgraph.h"
151 #include "pmcpl_annotate.h"
152 #include "pmcpl_annotate_cg.h"
153 #include "pmcpl_calltree.h"
155 static struct pmc_plugins {
156 const char *pl_name; /* name */
159 int (*pl_configure)(char *opt);
161 /* init and shutdown */
162 int (*pl_init)(void);
163 void (*pl_shutdown)(FILE *mf);
165 /* sample processing */
166 void (*pl_process)(struct pmcstat_process *pp,
167 struct pmcstat_pmcrecord *pmcr, uint32_t nsamples,
168 uintfptr_t *cc, int usermode, uint32_t cpu);
171 void (*pl_initimage)(struct pmcstat_image *pi);
172 void (*pl_shutdownimage)(struct pmcstat_image *pi);
175 void (*pl_newpmc)(pmcstat_interned_string ps,
176 struct pmcstat_pmcrecord *pr);
179 void (*pl_topdisplay)(void);
182 int (*pl_topkeypress)(int c, WINDOW *w);
189 .pl_name = "callgraph",
190 .pl_init = pmcpl_cg_init,
191 .pl_shutdown = pmcpl_cg_shutdown,
192 .pl_process = pmcpl_cg_process,
193 .pl_topkeypress = pmcpl_cg_topkeypress,
194 .pl_topdisplay = pmcpl_cg_topdisplay
198 .pl_shutdown = pmcpl_gmon_shutdown,
199 .pl_process = pmcpl_gmon_process,
200 .pl_initimage = pmcpl_gmon_initimage,
201 .pl_shutdownimage = pmcpl_gmon_shutdownimage,
202 .pl_newpmc = pmcpl_gmon_newpmc
205 .pl_name = "annotate",
206 .pl_process = pmcpl_annotate_process
209 .pl_name = "calltree",
210 .pl_configure = pmcpl_ct_configure,
211 .pl_init = pmcpl_ct_init,
212 .pl_shutdown = pmcpl_ct_shutdown,
213 .pl_process = pmcpl_ct_process,
214 .pl_topkeypress = pmcpl_ct_topkeypress,
215 .pl_topdisplay = pmcpl_ct_topdisplay
218 .pl_name = "annotate_cg",
219 .pl_process = pmcpl_annotate_cg_process
227 static int pmcstat_mergepmc;
229 int pmcstat_pmcinfilter = 0; /* PMC filter for top mode. */
230 float pmcstat_threshold = 0.5; /* Cost filter for top mode. */
236 static struct pmcstat_image *pmcstat_image_from_path(pmcstat_interned_string
237 _path, int _iskernelmodule);
238 static void pmcstat_image_get_aout_params(struct pmcstat_image *_image);
239 static void pmcstat_image_get_elf_params(struct pmcstat_image *_image);
240 static void pmcstat_image_link(struct pmcstat_process *_pp,
241 struct pmcstat_image *_i, uintfptr_t _lpc);
243 static void pmcstat_pmcid_add(pmc_id_t _pmcid,
244 pmcstat_interned_string _name);
246 static void pmcstat_process_aout_exec(struct pmcstat_process *_pp,
247 struct pmcstat_image *_image, uintfptr_t _entryaddr);
248 static void pmcstat_process_elf_exec(struct pmcstat_process *_pp,
249 struct pmcstat_image *_image, uintfptr_t _entryaddr);
250 static void pmcstat_process_exec(struct pmcstat_process *_pp,
251 pmcstat_interned_string _path, uintfptr_t _entryaddr);
252 static struct pmcstat_process *pmcstat_process_lookup(pid_t _pid,
254 static int pmcstat_string_compute_hash(const char *_string);
255 static void pmcstat_string_initialize(void);
256 static int pmcstat_string_lookup_hash(pmcstat_interned_string _is);
257 static void pmcstat_string_shutdown(void);
258 static void pmcstat_stats_reset(int _reset_global);
261 * A simple implementation of interned strings. Each interned string
262 * is assigned a unique address, so that subsequent string compares
263 * can be done by a simple pointer comparison instead of using
264 * strcmp(). This speeds up hash table lookups and saves memory if
265 * duplicate strings are the norm.
267 struct pmcstat_string {
268 LIST_ENTRY(pmcstat_string) ps_next; /* hash link */
274 static LIST_HEAD(,pmcstat_string) pmcstat_string_hash[PMCSTAT_NHASH];
282 * PMC Top mode pause state.
284 static int pmcstat_pause;
287 pmcstat_stats_reset(int reset_global)
289 struct pmcstat_pmcrecord *pr;
291 /* Flush PMCs stats. */
292 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
294 pr->pr_dubious_frames = 0;
296 ps_samples_period = 0;
298 /* Flush global stats. */
300 bzero(&pmcstat_stats, sizeof(struct pmcstat_stats));
304 * Compute a 'hash' value for a string.
308 pmcstat_string_compute_hash(const char *s)
312 for (hash = 2166136261; *s; s++)
313 hash = (hash ^ *s) * 16777619;
315 return (hash & PMCSTAT_HASH_MASK);
319 * Intern a copy of string 's', and return a pointer to the
320 * interned structure.
323 pmcstat_interned_string
324 pmcstat_string_intern(const char *s)
326 struct pmcstat_string *ps;
327 const struct pmcstat_string *cps;
330 if ((cps = pmcstat_string_lookup(s)) != NULL)
333 hash = pmcstat_string_compute_hash(s);
336 if ((ps = malloc(sizeof(*ps))) == NULL)
337 err(EX_OSERR, "ERROR: Could not intern string");
340 ps->ps_string = strdup(s);
341 LIST_INSERT_HEAD(&pmcstat_string_hash[hash], ps, ps_next);
342 return ((pmcstat_interned_string) ps);
346 pmcstat_string_unintern(pmcstat_interned_string str)
350 s = ((const struct pmcstat_string *) str)->ps_string;
354 pmcstat_interned_string
355 pmcstat_string_lookup(const char *s)
357 struct pmcstat_string *ps;
360 hash = pmcstat_string_compute_hash(s);
363 LIST_FOREACH(ps, &pmcstat_string_hash[hash], ps_next)
364 if (ps->ps_len == len && ps->ps_hash == hash &&
365 strcmp(ps->ps_string, s) == 0)
371 pmcstat_string_lookup_hash(pmcstat_interned_string s)
373 const struct pmcstat_string *ps;
375 ps = (const struct pmcstat_string *) s;
376 return (ps->ps_hash);
380 * Initialize the string interning facility.
384 pmcstat_string_initialize(void)
388 for (i = 0; i < PMCSTAT_NHASH; i++)
389 LIST_INIT(&pmcstat_string_hash[i]);
393 * Destroy the string table, free'ing up space.
397 pmcstat_string_shutdown(void)
400 struct pmcstat_string *ps, *pstmp;
402 for (i = 0; i < PMCSTAT_NHASH; i++)
403 LIST_FOREACH_SAFE(ps, &pmcstat_string_hash[i], ps_next,
405 LIST_REMOVE(ps, ps_next);
412 * Determine whether a given executable image is an A.OUT object, and
413 * if so, fill in its parameters from the text file.
414 * Sets image->pi_type.
418 pmcstat_image_get_aout_params(struct pmcstat_image *image)
424 char buffer[PATH_MAX];
426 path = pmcstat_string_unintern(image->pi_execpath);
427 assert(path != NULL);
429 if (image->pi_iskernelmodule)
431 "ERROR: a.out kernel modules are unsupported \"%s\"", path);
433 (void) snprintf(buffer, sizeof(buffer), "%s%s",
434 args.pa_fsroot, path);
436 if ((fd = open(buffer, O_RDONLY, 0)) < 0 ||
437 (nbytes = read(fd, &ex, sizeof(ex))) < 0) {
438 if (args.pa_verbosity >= 2)
439 warn("WARNING: Cannot determine type of \"%s\"",
441 image->pi_type = PMCSTAT_IMAGE_INDETERMINABLE;
449 if ((unsigned) nbytes != sizeof(ex) ||
453 image->pi_type = PMCSTAT_IMAGE_AOUT;
455 /* TODO: the rest of a.out processing */
465 pmcstat_symbol_compare(const void *a, const void *b)
467 const struct pmcstat_symbol *sym1, *sym2;
469 sym1 = (const struct pmcstat_symbol *) a;
470 sym2 = (const struct pmcstat_symbol *) b;
472 if (sym1->ps_end <= sym2->ps_start)
474 if (sym1->ps_start >= sym2->ps_end)
480 * Map an address to a symbol in an image.
483 struct pmcstat_symbol *
484 pmcstat_symbol_search(struct pmcstat_image *image, uintfptr_t addr)
486 struct pmcstat_symbol sym;
488 if (image->pi_symbols == NULL)
493 sym.ps_end = addr + 1;
495 return (bsearch((void *) &sym, image->pi_symbols,
496 image->pi_symcount, sizeof(struct pmcstat_symbol),
497 pmcstat_symbol_compare));
501 * Add the list of symbols in the given section to the list associated
505 pmcstat_image_add_symbols(struct pmcstat_image *image, Elf *e,
506 Elf_Scn *scn, GElf_Shdr *sh)
509 size_t n, newsyms, nshsyms, nfuncsyms;
510 struct pmcstat_symbol *symptr;
515 if ((data = elf_getdata(scn, NULL)) == NULL)
519 * Determine the number of functions named in this
523 nshsyms = sh->sh_size / sh->sh_entsize;
524 for (n = nfuncsyms = 0; n < nshsyms; n++) {
525 if (gelf_getsym(data, (int) n, &sym) != &sym)
527 if (GELF_ST_TYPE(sym.st_info) == STT_FUNC)
535 * Allocate space for the new entries.
537 firsttime = image->pi_symbols == NULL;
538 symptr = realloc(image->pi_symbols,
539 sizeof(*symptr) * (image->pi_symcount + nfuncsyms));
540 if (symptr == image->pi_symbols) /* realloc() failed. */
542 image->pi_symbols = symptr;
545 * Append new symbols to the end of the current table.
547 symptr += image->pi_symcount;
549 for (n = newsyms = 0; n < nshsyms; n++) {
550 if (gelf_getsym(data, (int) n, &sym) != &sym)
552 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
554 if (sym.st_shndx == STN_UNDEF)
557 if (!firsttime && pmcstat_symbol_search(image, sym.st_value))
558 continue; /* We've seen this symbol already. */
560 if ((fnname = elf_strptr(e, sh->sh_link, sym.st_name))
564 /* Remove spurious ARM function name. */
565 if (fnname[0] == '$' &&
566 (fnname[1] == 'a' || fnname[1] == 't' ||
572 symptr->ps_name = pmcstat_string_intern(fnname);
573 symptr->ps_start = sym.st_value - image->pi_vaddr;
574 symptr->ps_end = symptr->ps_start + sym.st_size;
580 image->pi_symcount += newsyms;
581 if (image->pi_symcount == 0)
584 assert(newsyms <= nfuncsyms);
587 * Return space to the system if there were duplicates.
589 if (newsyms < nfuncsyms)
590 image->pi_symbols = realloc(image->pi_symbols,
591 sizeof(*symptr) * image->pi_symcount);
594 * Keep the list of symbols sorted.
596 qsort(image->pi_symbols, image->pi_symcount, sizeof(*symptr),
597 pmcstat_symbol_compare);
600 * Deal with function symbols that have a size of 'zero' by
601 * making them extend to the next higher address. These
602 * symbols are usually defined in assembly code.
604 for (symptr = image->pi_symbols;
605 symptr < image->pi_symbols + (image->pi_symcount - 1);
607 if (symptr->ps_start == symptr->ps_end)
608 symptr->ps_end = (symptr+1)->ps_start;
612 * Examine an ELF file to determine the size of its text segment.
613 * Sets image->pi_type if anything conclusive can be determined about
618 pmcstat_image_get_elf_params(struct pmcstat_image *image)
622 const char *path, *elfbase;
624 uintfptr_t minva, maxva;
630 enum pmcstat_image_type image_type;
631 char buffer[PATH_MAX];
633 assert(image->pi_type == PMCSTAT_IMAGE_UNKNOWN);
635 image->pi_start = minva = ~(uintfptr_t) 0;
636 image->pi_end = maxva = (uintfptr_t) 0;
637 image->pi_type = image_type = PMCSTAT_IMAGE_INDETERMINABLE;
638 image->pi_isdynamic = 0;
639 image->pi_dynlinkerpath = NULL;
642 path = pmcstat_string_unintern(image->pi_execpath);
643 assert(path != NULL);
646 * Look for kernel modules under FSROOT/KERNELPATH/NAME,
647 * and user mode executable objects under FSROOT/PATHNAME.
649 if (image->pi_iskernelmodule)
650 (void) snprintf(buffer, sizeof(buffer), "%s%s/%s",
651 args.pa_fsroot, args.pa_kernel, path);
653 (void) snprintf(buffer, sizeof(buffer), "%s%s",
654 args.pa_fsroot, path);
657 if ((fd = open(buffer, O_RDONLY, 0)) < 0 ||
658 (e = elf_begin(fd, ELF_C_READ, NULL)) == NULL ||
659 (elf_kind(e) != ELF_K_ELF)) {
660 if (args.pa_verbosity >= 2)
661 warnx("WARNING: Cannot determine the type of \"%s\".",
666 if (gelf_getehdr(e, &eh) != &eh) {
668 "WARNING: Cannot retrieve the ELF Header for \"%s\": %s.",
669 buffer, elf_errmsg(-1));
673 if (eh.e_type != ET_EXEC && eh.e_type != ET_DYN &&
674 !(image->pi_iskernelmodule && eh.e_type == ET_REL)) {
675 warnx("WARNING: \"%s\" is of an unsupported ELF type.",
680 image_type = eh.e_ident[EI_CLASS] == ELFCLASS32 ?
681 PMCSTAT_IMAGE_ELF32 : PMCSTAT_IMAGE_ELF64;
684 * Determine the virtual address where an executable would be
685 * loaded. Additionally, for dynamically linked executables,
686 * save the pathname to the runtime linker.
688 if (eh.e_type == ET_EXEC) {
689 if (elf_getphnum(e, &nph) == 0) {
691 "WARNING: Could not determine the number of program headers in \"%s\": %s.",
696 for (i = 0; i < eh.e_phnum; i++) {
697 if (gelf_getphdr(e, i, &ph) != &ph) {
699 "WARNING: Retrieval of PHDR entry #%ju in \"%s\" failed: %s.",
700 (uintmax_t) i, buffer, elf_errmsg(-1));
705 image->pi_isdynamic = 1;
708 if ((elfbase = elf_rawfile(e, NULL)) == NULL) {
710 "WARNING: Cannot retrieve the interpreter for \"%s\": %s.",
711 buffer, elf_errmsg(-1));
714 image->pi_dynlinkerpath =
715 pmcstat_string_intern(elfbase +
719 if ((ph.p_offset & (-ph.p_align)) == 0)
720 image->pi_vaddr = ph.p_vaddr & (-ph.p_align);
727 * Get the min and max VA associated with this ELF object.
729 if (elf_getshnum(e, &nsh) == 0) {
731 "WARNING: Could not determine the number of sections for \"%s\": %s.",
732 buffer, elf_errmsg(-1));
736 for (i = 0; i < nsh; i++) {
737 if ((scn = elf_getscn(e, i)) == NULL ||
738 gelf_getshdr(scn, &sh) != &sh) {
740 "WARNING: Could not retrieve section header #%ju in \"%s\": %s.",
741 (uintmax_t) i, buffer, elf_errmsg(-1));
744 if (sh.sh_flags & SHF_EXECINSTR) {
745 minva = min(minva, sh.sh_addr);
746 maxva = max(maxva, sh.sh_addr + sh.sh_size);
748 if (sh.sh_type == SHT_SYMTAB || sh.sh_type == SHT_DYNSYM)
749 pmcstat_image_add_symbols(image, e, scn, &sh);
752 image->pi_start = minva;
753 image->pi_end = maxva;
754 image->pi_type = image_type;
755 image->pi_fullpath = pmcstat_string_intern(buffer);
757 /* Build display name
760 for (p = buffer; *p; p++)
763 image->pi_name = pmcstat_string_intern(endp);
773 * Given an image descriptor, determine whether it is an ELF, or AOUT.
774 * If no handler claims the image, set its type to 'INDETERMINABLE'.
778 pmcstat_image_determine_type(struct pmcstat_image *image)
780 assert(image->pi_type == PMCSTAT_IMAGE_UNKNOWN);
782 /* Try each kind of handler in turn */
783 if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
784 pmcstat_image_get_elf_params(image);
785 if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
786 pmcstat_image_get_aout_params(image);
789 * Otherwise, remember that we tried to determine
790 * the object's type and had failed.
792 if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
793 image->pi_type = PMCSTAT_IMAGE_INDETERMINABLE;
797 * Locate an image descriptor given an interned path, adding a fresh
798 * descriptor to the cache if necessary. This function also finds a
799 * suitable name for this image's sample file.
801 * We defer filling in the file format specific parts of the image
802 * structure till the time we actually see a sample that would fall
806 static struct pmcstat_image *
807 pmcstat_image_from_path(pmcstat_interned_string internedpath,
811 struct pmcstat_image *pi;
813 hash = pmcstat_string_lookup_hash(internedpath);
815 /* First, look for an existing entry. */
816 LIST_FOREACH(pi, &pmcstat_image_hash[hash], pi_next)
817 if (pi->pi_execpath == internedpath &&
818 pi->pi_iskernelmodule == iskernelmodule)
822 * Allocate a new entry and place it at the head of the hash
825 pi = malloc(sizeof(*pi));
829 pi->pi_type = PMCSTAT_IMAGE_UNKNOWN;
830 pi->pi_execpath = internedpath;
835 pi->pi_isdynamic = 0;
836 pi->pi_iskernelmodule = iskernelmodule;
837 pi->pi_dynlinkerpath = NULL;
838 pi->pi_symbols = NULL;
840 pi->pi_addr2line = NULL;
842 if (plugins[args.pa_pplugin].pl_initimage != NULL)
843 plugins[args.pa_pplugin].pl_initimage(pi);
844 if (plugins[args.pa_plugin].pl_initimage != NULL)
845 plugins[args.pa_plugin].pl_initimage(pi);
847 LIST_INSERT_HEAD(&pmcstat_image_hash[hash], pi, pi_next);
853 * Record the fact that PC values from 'start' to 'end' come from
858 pmcstat_image_link(struct pmcstat_process *pp, struct pmcstat_image *image,
861 struct pmcstat_pcmap *pcm, *pcmnew;
864 assert(image->pi_type != PMCSTAT_IMAGE_UNKNOWN &&
865 image->pi_type != PMCSTAT_IMAGE_INDETERMINABLE);
867 if ((pcmnew = malloc(sizeof(*pcmnew))) == NULL)
868 err(EX_OSERR, "ERROR: Cannot create a map entry");
871 * Adjust the map entry to only cover the text portion
875 offset = start - image->pi_vaddr;
876 pcmnew->ppm_lowpc = image->pi_start + offset;
877 pcmnew->ppm_highpc = image->pi_end + offset;
878 pcmnew->ppm_image = image;
880 assert(pcmnew->ppm_lowpc < pcmnew->ppm_highpc);
882 /* Overlapped mmap()'s are assumed to never occur. */
883 TAILQ_FOREACH(pcm, &pp->pp_map, ppm_next)
884 if (pcm->ppm_lowpc >= pcmnew->ppm_highpc)
888 TAILQ_INSERT_TAIL(&pp->pp_map, pcmnew, ppm_next);
890 TAILQ_INSERT_BEFORE(pcm, pcmnew, ppm_next);
894 * Unmap images in the range [start..end) associated with process
899 pmcstat_image_unmap(struct pmcstat_process *pp, uintfptr_t start,
902 struct pmcstat_pcmap *pcm, *pcmtmp, *pcmnew;
909 * - we could have the range completely in the middle of an
910 * existing pcmap; in this case we have to split the pcmap
911 * structure into two (i.e., generate a 'hole').
912 * - we could have the range covering multiple pcmaps; these
913 * will have to be removed.
914 * - we could have either 'start' or 'end' falling in the
915 * middle of a pcmap; in this case shorten the entry.
917 TAILQ_FOREACH_SAFE(pcm, &pp->pp_map, ppm_next, pcmtmp) {
918 assert(pcm->ppm_lowpc < pcm->ppm_highpc);
919 if (pcm->ppm_highpc <= start)
921 if (pcm->ppm_lowpc >= end)
923 if (pcm->ppm_lowpc >= start && pcm->ppm_highpc <= end) {
925 * The current pcmap is completely inside the
926 * unmapped range: remove it entirely.
928 TAILQ_REMOVE(&pp->pp_map, pcm, ppm_next);
930 } else if (pcm->ppm_lowpc < start && pcm->ppm_highpc > end) {
932 * Split this pcmap into two; curtail the
933 * current map to end at [start-1], and start
934 * the new one at [end].
936 if ((pcmnew = malloc(sizeof(*pcmnew))) == NULL)
938 "ERROR: Cannot split a map entry");
940 pcmnew->ppm_image = pcm->ppm_image;
942 pcmnew->ppm_lowpc = end;
943 pcmnew->ppm_highpc = pcm->ppm_highpc;
945 pcm->ppm_highpc = start;
947 TAILQ_INSERT_AFTER(&pp->pp_map, pcm, pcmnew, ppm_next);
950 } else if (pcm->ppm_lowpc < start && pcm->ppm_highpc <= end)
951 pcm->ppm_highpc = start;
952 else if (pcm->ppm_lowpc >= start && pcm->ppm_highpc > end)
953 pcm->ppm_lowpc = end;
960 * Resolve file name and line number for the given address.
963 pmcstat_image_addr2line(struct pmcstat_image *image, uintfptr_t addr,
964 char *sourcefile, size_t sourcefile_len, unsigned *sourceline,
965 char *funcname, size_t funcname_len)
967 static int addr2line_warn = 0;
970 char *sep, cmdline[PATH_MAX], imagepath[PATH_MAX];
973 if (image->pi_addr2line == NULL) {
974 snprintf(imagepath, sizeof(imagepath), "%s%s.symbols",
976 pmcstat_string_unintern(image->pi_fullpath));
977 fd = open(imagepath, O_RDONLY);
979 snprintf(imagepath, sizeof(imagepath), "%s%s",
981 pmcstat_string_unintern(image->pi_fullpath));
985 * New addr2line support recursive inline function with -i
986 * but the format does not add a marker when no more entries
989 snprintf(cmdline, sizeof(cmdline), "addr2line -Cfe \"%s\"",
991 image->pi_addr2line = popen(cmdline, "r+");
992 if (image->pi_addr2line == NULL) {
993 if (!addr2line_warn) {
996 "WARNING: addr2line is needed for source code information."
1003 if (feof(image->pi_addr2line) || ferror(image->pi_addr2line)) {
1004 warnx("WARNING: addr2line pipe error");
1005 pclose(image->pi_addr2line);
1006 image->pi_addr2line = NULL;
1010 fprintf(image->pi_addr2line, "%p\n", (void *)addr);
1012 if (fgets(funcname, funcname_len, image->pi_addr2line) == NULL) {
1013 warnx("WARNING: addr2line function name read error");
1016 sep = strchr(funcname, '\n');
1020 if (fgets(sourcefile, sourcefile_len, image->pi_addr2line) == NULL) {
1021 warnx("WARNING: addr2line source file read error");
1024 sep = strchr(sourcefile, ':');
1026 warnx("WARNING: addr2line source line separator missing");
1038 * Add a {pmcid,name} mapping.
1042 pmcstat_pmcid_add(pmc_id_t pmcid, pmcstat_interned_string ps)
1044 struct pmcstat_pmcrecord *pr, *prm;
1046 /* Replace an existing name for the PMC. */
1048 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1049 if (pr->pr_pmcid == pmcid) {
1050 pr->pr_pmcname = ps;
1052 } else if (pr->pr_pmcname == ps)
1056 * Otherwise, allocate a new descriptor and call the
1059 if ((pr = malloc(sizeof(*pr))) == NULL)
1060 err(EX_OSERR, "ERROR: Cannot allocate pmc record");
1062 pr->pr_pmcid = pmcid;
1063 pr->pr_pmcname = ps;
1064 pr->pr_pmcin = pmcstat_npmcs++;
1066 pr->pr_dubious_frames = 0;
1067 pr->pr_merge = prm == NULL ? pr : prm;
1069 LIST_INSERT_HEAD(&pmcstat_pmcs, pr, pr_next);
1071 if (plugins[args.pa_pplugin].pl_newpmc != NULL)
1072 plugins[args.pa_pplugin].pl_newpmc(ps, pr);
1073 if (plugins[args.pa_plugin].pl_newpmc != NULL)
1074 plugins[args.pa_plugin].pl_newpmc(ps, pr);
1078 * Given a pmcid in use, find its human-readable name.
1082 pmcstat_pmcid_to_name(pmc_id_t pmcid)
1084 struct pmcstat_pmcrecord *pr;
1086 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1087 if (pr->pr_pmcid == pmcid)
1088 return (pmcstat_string_unintern(pr->pr_pmcname));
1094 * Convert PMC index to name.
1098 pmcstat_pmcindex_to_name(int pmcin)
1100 struct pmcstat_pmcrecord *pr;
1102 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1103 if (pr->pr_pmcin == pmcin)
1104 return pmcstat_string_unintern(pr->pr_pmcname);
1110 * Return PMC record with given index.
1113 struct pmcstat_pmcrecord *
1114 pmcstat_pmcindex_to_pmcr(int pmcin)
1116 struct pmcstat_pmcrecord *pr;
1118 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
1119 if (pr->pr_pmcin == pmcin)
1126 * Get PMC record by id, apply merge policy.
1129 static struct pmcstat_pmcrecord *
1130 pmcstat_lookup_pmcid(pmc_id_t pmcid)
1132 struct pmcstat_pmcrecord *pr;
1134 LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
1135 if (pr->pr_pmcid == pmcid) {
1136 if (pmcstat_mergepmc)
1137 return pr->pr_merge;
1146 * Associate an AOUT image with a process.
1150 pmcstat_process_aout_exec(struct pmcstat_process *pp,
1151 struct pmcstat_image *image, uintfptr_t entryaddr)
1156 /* TODO Implement a.out handling */
1160 * Associate an ELF image with a process.
1164 pmcstat_process_elf_exec(struct pmcstat_process *pp,
1165 struct pmcstat_image *image, uintfptr_t entryaddr)
1168 struct pmcstat_image *rtldimage;
1170 assert(image->pi_type == PMCSTAT_IMAGE_ELF32 ||
1171 image->pi_type == PMCSTAT_IMAGE_ELF64);
1173 /* Create a map entry for the base executable. */
1174 pmcstat_image_link(pp, image, image->pi_vaddr);
1177 * For dynamically linked executables we need to determine
1178 * where the dynamic linker was mapped to for this process,
1179 * Subsequent executable objects that are mapped in by the
1180 * dynamic linker will be tracked by log events of type
1181 * PMCLOG_TYPE_MAP_IN.
1184 if (image->pi_isdynamic) {
1187 * The runtime loader gets loaded just after the maximum
1188 * possible heap address. Like so:
1190 * [ TEXT DATA BSS HEAP -->*RTLD SHLIBS <--STACK]
1192 * 0 VM_MAXUSER_ADDRESS
1195 * The exact address where the loader gets mapped in
1196 * will vary according to the size of the executable
1197 * and the limits on the size of the process'es data
1198 * segment at the time of exec(). The entry address
1199 * recorded at process exec time corresponds to the
1200 * 'start' address inside the dynamic linker. From
1201 * this we can figure out the address where the
1202 * runtime loader's file object had been mapped to.
1204 rtldimage = pmcstat_image_from_path(image->pi_dynlinkerpath, 0);
1205 if (rtldimage == NULL) {
1206 warnx("WARNING: Cannot find image for \"%s\".",
1207 pmcstat_string_unintern(image->pi_dynlinkerpath));
1208 pmcstat_stats.ps_exec_errors++;
1212 if (rtldimage->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1213 pmcstat_image_get_elf_params(rtldimage);
1215 if (rtldimage->pi_type != PMCSTAT_IMAGE_ELF32 &&
1216 rtldimage->pi_type != PMCSTAT_IMAGE_ELF64) {
1217 warnx("WARNING: rtld not an ELF object \"%s\".",
1218 pmcstat_string_unintern(image->pi_dynlinkerpath));
1222 libstart = entryaddr - rtldimage->pi_entry;
1223 pmcstat_image_link(pp, rtldimage, libstart);
1228 * Find the process descriptor corresponding to a PID. If 'allocate'
1229 * is zero, we return a NULL if a pid descriptor could not be found or
1230 * a process descriptor process. If 'allocate' is non-zero, then we
1231 * will attempt to allocate a fresh process descriptor. Zombie
1232 * process descriptors are only removed if a fresh allocation for the
1233 * same PID is requested.
1236 static struct pmcstat_process *
1237 pmcstat_process_lookup(pid_t pid, int allocate)
1240 struct pmcstat_pcmap *ppm, *ppmtmp;
1241 struct pmcstat_process *pp, *pptmp;
1243 hash = (uint32_t) pid & PMCSTAT_HASH_MASK; /* simplicity wins */
1245 LIST_FOREACH_SAFE(pp, &pmcstat_process_hash[hash], pp_next, pptmp)
1246 if (pp->pp_pid == pid) {
1247 /* Found a descriptor, check and process zombies */
1248 if (allocate && pp->pp_isactive == 0) {
1250 TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next,
1252 TAILQ_REMOVE(&pp->pp_map, ppm,
1256 /* remove process entry */
1257 LIST_REMOVE(pp, pp_next);
1267 if ((pp = malloc(sizeof(*pp))) == NULL)
1268 err(EX_OSERR, "ERROR: Cannot allocate pid descriptor");
1271 pp->pp_isactive = 1;
1273 TAILQ_INIT(&pp->pp_map);
1275 LIST_INSERT_HEAD(&pmcstat_process_hash[hash], pp, pp_next);
1280 * Associate an image and a process.
1284 pmcstat_process_exec(struct pmcstat_process *pp,
1285 pmcstat_interned_string path, uintfptr_t entryaddr)
1287 struct pmcstat_image *image;
1289 if ((image = pmcstat_image_from_path(path, 0)) == NULL) {
1290 pmcstat_stats.ps_exec_errors++;
1294 if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1295 pmcstat_image_determine_type(image);
1297 assert(image->pi_type != PMCSTAT_IMAGE_UNKNOWN);
1299 switch (image->pi_type) {
1300 case PMCSTAT_IMAGE_ELF32:
1301 case PMCSTAT_IMAGE_ELF64:
1302 pmcstat_stats.ps_exec_elf++;
1303 pmcstat_process_elf_exec(pp, image, entryaddr);
1306 case PMCSTAT_IMAGE_AOUT:
1307 pmcstat_stats.ps_exec_aout++;
1308 pmcstat_process_aout_exec(pp, image, entryaddr);
1311 case PMCSTAT_IMAGE_INDETERMINABLE:
1312 pmcstat_stats.ps_exec_indeterminable++;
1317 "ERROR: Unsupported executable type for \"%s\"",
1318 pmcstat_string_unintern(path));
1324 * Find the map entry associated with process 'p' at PC value 'pc'.
1327 struct pmcstat_pcmap *
1328 pmcstat_process_find_map(struct pmcstat_process *p, uintfptr_t pc)
1330 struct pmcstat_pcmap *ppm;
1332 TAILQ_FOREACH(ppm, &p->pp_map, ppm_next) {
1333 if (pc >= ppm->ppm_lowpc && pc < ppm->ppm_highpc)
1335 if (pc < ppm->ppm_lowpc)
1343 * Convert a hwpmc(4) log to profile information. A system-wide
1344 * callgraph is generated if FLAG_DO_CALLGRAPHS is set. gmon.out
1345 * files usable by gprof(1) are created if FLAG_DO_GPROF is set.
1348 pmcstat_analyze_log(void)
1350 uint32_t cpu, cpuflags;
1353 struct pmcstat_image *image;
1354 struct pmcstat_process *pp, *ppnew;
1355 struct pmcstat_pcmap *ppm, *ppmtmp;
1356 struct pmclog_ev ev;
1357 struct pmcstat_pmcrecord *pmcr;
1358 pmcstat_interned_string image_path;
1360 assert(args.pa_flags & FLAG_DO_ANALYSIS);
1362 if (elf_version(EV_CURRENT) == EV_NONE)
1363 err(EX_UNAVAILABLE, "Elf library intialization failed");
1365 while (pmclog_read(args.pa_logparser, &ev) == 0) {
1366 assert(ev.pl_state == PMCLOG_OK);
1368 switch (ev.pl_type) {
1369 case PMCLOG_TYPE_INITIALIZE:
1370 if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
1371 PMC_VERSION_MAJOR << 24 && args.pa_verbosity > 0)
1373 "WARNING: Log version 0x%x does not match compiled version 0x%x.",
1374 ev.pl_u.pl_i.pl_version, PMC_VERSION_MAJOR);
1377 case PMCLOG_TYPE_MAP_IN:
1379 * Introduce an address range mapping for a
1380 * userland process or the kernel (pid == -1).
1382 * We always allocate a process descriptor so
1383 * that subsequent samples seen for this
1384 * address range are mapped to the current
1385 * object being mapped in.
1387 pid = ev.pl_u.pl_mi.pl_pid;
1389 pp = pmcstat_kernproc;
1391 pp = pmcstat_process_lookup(pid,
1396 image_path = pmcstat_string_intern(ev.pl_u.pl_mi.
1398 image = pmcstat_image_from_path(image_path, pid == -1);
1399 if (image->pi_type == PMCSTAT_IMAGE_UNKNOWN)
1400 pmcstat_image_determine_type(image);
1401 if (image->pi_type != PMCSTAT_IMAGE_INDETERMINABLE)
1402 pmcstat_image_link(pp, image,
1403 ev.pl_u.pl_mi.pl_start);
1406 case PMCLOG_TYPE_MAP_OUT:
1408 * Remove an address map.
1410 pid = ev.pl_u.pl_mo.pl_pid;
1412 pp = pmcstat_kernproc;
1414 pp = pmcstat_process_lookup(pid, 0);
1416 if (pp == NULL) /* unknown process */
1419 pmcstat_image_unmap(pp, ev.pl_u.pl_mo.pl_start,
1420 ev.pl_u.pl_mo.pl_end);
1423 case PMCLOG_TYPE_PCSAMPLE:
1425 * Note: the `PCSAMPLE' log entry is not
1426 * generated by hpwmc(4) after version 2.
1430 * We bring in the gmon file for the image
1431 * currently associated with the PMC & pid
1432 * pair and increment the appropriate entry
1435 pmcstat_stats.ps_samples_total++;
1436 ps_samples_period++;
1438 pc = ev.pl_u.pl_s.pl_pc;
1439 pp = pmcstat_process_lookup(ev.pl_u.pl_s.pl_pid,
1442 /* Get PMC record. */
1443 pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_s.pl_pmcid);
1444 assert(pmcr != NULL);
1448 * Call the plugins processing
1449 * TODO: move pmcstat_process_find_map inside plugins
1452 if (plugins[args.pa_pplugin].pl_process != NULL)
1453 plugins[args.pa_pplugin].pl_process(
1455 pmcstat_process_find_map(pp, pc) != NULL, 0);
1456 plugins[args.pa_plugin].pl_process(
1458 pmcstat_process_find_map(pp, pc) != NULL, 0);
1461 case PMCLOG_TYPE_CALLCHAIN:
1462 pmcstat_stats.ps_samples_total++;
1463 ps_samples_period++;
1465 cpuflags = ev.pl_u.pl_cc.pl_cpuflags;
1466 cpu = PMC_CALLCHAIN_CPUFLAGS_TO_CPU(cpuflags);
1468 /* Filter on the CPU id. */
1469 if (!CPU_ISSET(cpu, &(args.pa_cpumask))) {
1470 pmcstat_stats.ps_samples_skipped++;
1474 pp = pmcstat_process_lookup(ev.pl_u.pl_cc.pl_pid,
1477 /* Get PMC record. */
1478 pmcr = pmcstat_lookup_pmcid(ev.pl_u.pl_cc.pl_pmcid);
1479 assert(pmcr != NULL);
1483 * Call the plugins processing
1486 if (plugins[args.pa_pplugin].pl_process != NULL)
1487 plugins[args.pa_pplugin].pl_process(
1489 ev.pl_u.pl_cc.pl_npc,
1490 ev.pl_u.pl_cc.pl_pc,
1491 PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
1493 plugins[args.pa_plugin].pl_process(
1495 ev.pl_u.pl_cc.pl_npc,
1496 ev.pl_u.pl_cc.pl_pc,
1497 PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(cpuflags),
1501 case PMCLOG_TYPE_PMCALLOCATE:
1503 * Record the association pmc id between this
1506 pmcstat_pmcid_add(ev.pl_u.pl_a.pl_pmcid,
1507 pmcstat_string_intern(ev.pl_u.pl_a.pl_evname));
1510 case PMCLOG_TYPE_PMCALLOCATEDYN:
1512 * Record the association pmc id between this
1515 pmcstat_pmcid_add(ev.pl_u.pl_ad.pl_pmcid,
1516 pmcstat_string_intern(ev.pl_u.pl_ad.pl_evname));
1519 case PMCLOG_TYPE_PROCEXEC:
1522 * Change the executable image associated with
1525 pp = pmcstat_process_lookup(ev.pl_u.pl_x.pl_pid,
1528 /* delete the current process map */
1529 TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
1530 TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
1534 /* associate this process image */
1535 image_path = pmcstat_string_intern(
1536 ev.pl_u.pl_x.pl_pathname);
1537 assert(image_path != NULL);
1538 pmcstat_process_exec(pp, image_path,
1539 ev.pl_u.pl_x.pl_entryaddr);
1542 case PMCLOG_TYPE_PROCEXIT:
1545 * Due to the way the log is generated, the
1546 * last few samples corresponding to a process
1547 * may appear in the log after the process
1548 * exit event is recorded. Thus we keep the
1549 * process' descriptor and associated data
1550 * structures around, but mark the process as
1553 pp = pmcstat_process_lookup(ev.pl_u.pl_e.pl_pid, 0);
1556 pp->pp_isactive = 0; /* mark as a zombie */
1559 case PMCLOG_TYPE_SYSEXIT:
1560 pp = pmcstat_process_lookup(ev.pl_u.pl_se.pl_pid, 0);
1563 pp->pp_isactive = 0; /* make a zombie */
1566 case PMCLOG_TYPE_PROCFORK:
1569 * Allocate a process descriptor for the new
1573 pmcstat_process_lookup(ev.pl_u.pl_f.pl_newpid,
1577 * If we had been tracking the parent, clone
1580 pp = pmcstat_process_lookup(ev.pl_u.pl_f.pl_oldpid, 0);
1583 TAILQ_FOREACH(ppm, &pp->pp_map, ppm_next)
1584 pmcstat_image_link(ppnew, ppm->ppm_image,
1588 default: /* other types of entries are not relevant */
1593 if (ev.pl_state == PMCLOG_EOF)
1594 return (PMCSTAT_FINISHED);
1595 else if (ev.pl_state == PMCLOG_REQUIRE_DATA)
1596 return (PMCSTAT_RUNNING);
1599 "ERROR: event parsing failed (record %jd, offset 0x%jx)",
1600 (uintmax_t) ev.pl_count + 1, ev.pl_offset);
1604 * Print log entries as text.
1608 pmcstat_print_log(void)
1610 struct pmclog_ev ev;
1613 while (pmclog_read(args.pa_logparser, &ev) == 0) {
1614 assert(ev.pl_state == PMCLOG_OK);
1615 switch (ev.pl_type) {
1616 case PMCLOG_TYPE_CALLCHAIN:
1617 PMCSTAT_PRINT_ENTRY("callchain",
1618 "%d 0x%x %d %d %c", ev.pl_u.pl_cc.pl_pid,
1619 ev.pl_u.pl_cc.pl_pmcid,
1620 PMC_CALLCHAIN_CPUFLAGS_TO_CPU(ev.pl_u.pl_cc. \
1621 pl_cpuflags), ev.pl_u.pl_cc.pl_npc,
1622 PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(ev.pl_u.pl_cc.\
1623 pl_cpuflags) ? 'u' : 's');
1624 for (npc = 0; npc < ev.pl_u.pl_cc.pl_npc; npc++)
1625 PMCSTAT_PRINT_ENTRY("...", "%p",
1626 (void *) ev.pl_u.pl_cc.pl_pc[npc]);
1628 case PMCLOG_TYPE_CLOSELOG:
1629 PMCSTAT_PRINT_ENTRY("closelog",);
1631 case PMCLOG_TYPE_DROPNOTIFY:
1632 PMCSTAT_PRINT_ENTRY("drop",);
1634 case PMCLOG_TYPE_INITIALIZE:
1635 PMCSTAT_PRINT_ENTRY("initlog","0x%x \"%s\"",
1636 ev.pl_u.pl_i.pl_version,
1637 pmc_name_of_cputype(ev.pl_u.pl_i.pl_arch));
1638 if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
1639 PMC_VERSION_MAJOR << 24 && args.pa_verbosity > 0)
1641 "WARNING: Log version 0x%x != expected version 0x%x.",
1642 ev.pl_u.pl_i.pl_version, PMC_VERSION);
1644 case PMCLOG_TYPE_MAP_IN:
1645 PMCSTAT_PRINT_ENTRY("map-in","%d %p \"%s\"",
1646 ev.pl_u.pl_mi.pl_pid,
1647 (void *) ev.pl_u.pl_mi.pl_start,
1648 ev.pl_u.pl_mi.pl_pathname);
1650 case PMCLOG_TYPE_MAP_OUT:
1651 PMCSTAT_PRINT_ENTRY("map-out","%d %p %p",
1652 ev.pl_u.pl_mo.pl_pid,
1653 (void *) ev.pl_u.pl_mo.pl_start,
1654 (void *) ev.pl_u.pl_mo.pl_end);
1656 case PMCLOG_TYPE_PCSAMPLE:
1657 PMCSTAT_PRINT_ENTRY("sample","0x%x %d %p %c",
1658 ev.pl_u.pl_s.pl_pmcid,
1659 ev.pl_u.pl_s.pl_pid,
1660 (void *) ev.pl_u.pl_s.pl_pc,
1661 ev.pl_u.pl_s.pl_usermode ? 'u' : 's');
1663 case PMCLOG_TYPE_PMCALLOCATE:
1664 PMCSTAT_PRINT_ENTRY("allocate","0x%x \"%s\" 0x%x",
1665 ev.pl_u.pl_a.pl_pmcid,
1666 ev.pl_u.pl_a.pl_evname,
1667 ev.pl_u.pl_a.pl_flags);
1669 case PMCLOG_TYPE_PMCALLOCATEDYN:
1670 PMCSTAT_PRINT_ENTRY("allocatedyn","0x%x \"%s\" 0x%x",
1671 ev.pl_u.pl_ad.pl_pmcid,
1672 ev.pl_u.pl_ad.pl_evname,
1673 ev.pl_u.pl_ad.pl_flags);
1675 case PMCLOG_TYPE_PMCATTACH:
1676 PMCSTAT_PRINT_ENTRY("attach","0x%x %d \"%s\"",
1677 ev.pl_u.pl_t.pl_pmcid,
1678 ev.pl_u.pl_t.pl_pid,
1679 ev.pl_u.pl_t.pl_pathname);
1681 case PMCLOG_TYPE_PMCDETACH:
1682 PMCSTAT_PRINT_ENTRY("detach","0x%x %d",
1683 ev.pl_u.pl_d.pl_pmcid,
1684 ev.pl_u.pl_d.pl_pid);
1686 case PMCLOG_TYPE_PROCCSW:
1687 PMCSTAT_PRINT_ENTRY("cswval","0x%x %d %jd",
1688 ev.pl_u.pl_c.pl_pmcid,
1689 ev.pl_u.pl_c.pl_pid,
1690 ev.pl_u.pl_c.pl_value);
1692 case PMCLOG_TYPE_PROCEXEC:
1693 PMCSTAT_PRINT_ENTRY("exec","0x%x %d %p \"%s\"",
1694 ev.pl_u.pl_x.pl_pmcid,
1695 ev.pl_u.pl_x.pl_pid,
1696 (void *) ev.pl_u.pl_x.pl_entryaddr,
1697 ev.pl_u.pl_x.pl_pathname);
1699 case PMCLOG_TYPE_PROCEXIT:
1700 PMCSTAT_PRINT_ENTRY("exitval","0x%x %d %jd",
1701 ev.pl_u.pl_e.pl_pmcid,
1702 ev.pl_u.pl_e.pl_pid,
1703 ev.pl_u.pl_e.pl_value);
1705 case PMCLOG_TYPE_PROCFORK:
1706 PMCSTAT_PRINT_ENTRY("fork","%d %d",
1707 ev.pl_u.pl_f.pl_oldpid,
1708 ev.pl_u.pl_f.pl_newpid);
1710 case PMCLOG_TYPE_USERDATA:
1711 PMCSTAT_PRINT_ENTRY("userdata","0x%x",
1712 ev.pl_u.pl_u.pl_userdata);
1714 case PMCLOG_TYPE_SYSEXIT:
1715 PMCSTAT_PRINT_ENTRY("exit","%d",
1716 ev.pl_u.pl_se.pl_pid);
1719 fprintf(args.pa_printfile, "unknown event (type %d).\n",
1724 if (ev.pl_state == PMCLOG_EOF)
1725 return (PMCSTAT_FINISHED);
1726 else if (ev.pl_state == PMCLOG_REQUIRE_DATA)
1727 return (PMCSTAT_RUNNING);
1730 "ERROR: event parsing failed (record %jd, offset 0x%jx).",
1731 (uintmax_t) ev.pl_count + 1, ev.pl_offset);
1736 * Public Interfaces.
1740 * Close a logfile, after first flushing all in-module queued data.
1744 pmcstat_close_log(void)
1746 /* If a local logfile is configured ask the kernel to stop
1747 * and flush data. Kernel will close the file when data is flushed
1748 * so keep the status to EXITING.
1750 if (args.pa_logfd != -1) {
1751 if (pmc_close_logfile() < 0)
1752 err(EX_OSERR, "ERROR: logging failed");
1755 return (args.pa_flags & FLAG_HAS_PIPE ? PMCSTAT_EXITING :
1762 * Open a log file, for reading or writing.
1764 * The function returns the fd of a successfully opened log or -1 in
1769 pmcstat_open_log(const char *path, int mode)
1773 const char *p, *errstr;
1774 struct addrinfo hints, *res, *res0;
1775 char hostname[MAXHOSTNAMELEN];
1781 * If 'path' is "-" then open one of stdin or stdout depending
1782 * on the value of 'mode'.
1784 * If 'path' contains a ':' and does not start with a '/' or '.',
1785 * and is being opened for writing, treat it as a "host:port"
1786 * specification and open a network socket.
1788 * Otherwise, treat 'path' as a file name and open that.
1790 if (path[0] == '-' && path[1] == '\0')
1791 fd = (mode == PMCSTAT_OPEN_FOR_READ) ? 0 : 1;
1792 else if (path[0] != '/' &&
1793 path[0] != '.' && strchr(path, ':') != NULL) {
1795 p = strrchr(path, ':');
1797 if (p == path || hlen >= sizeof(hostname)) {
1798 errstr = strerror(EINVAL);
1802 assert(hlen < sizeof(hostname));
1803 (void) strncpy(hostname, path, hlen);
1804 hostname[hlen] = '\0';
1806 (void) memset(&hints, 0, sizeof(hints));
1807 hints.ai_family = AF_UNSPEC;
1808 hints.ai_socktype = SOCK_STREAM;
1809 if ((error = getaddrinfo(hostname, p+1, &hints, &res0)) != 0) {
1810 errstr = gai_strerror(error);
1815 for (res = res0; res; res = res->ai_next) {
1816 if ((fd = socket(res->ai_family, res->ai_socktype,
1817 res->ai_protocol)) < 0) {
1818 errstr = strerror(errno);
1821 if (mode == PMCSTAT_OPEN_FOR_READ) {
1822 if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {
1823 errstr = strerror(errno);
1829 cfd = accept(fd, NULL, NULL);
1832 errstr = strerror(errno);
1838 if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
1839 errstr = strerror(errno);
1850 } else if ((fd = open(path, mode == PMCSTAT_OPEN_FOR_READ ?
1851 O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC),
1852 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
1853 errstr = strerror(errno);
1857 errx(EX_OSERR, "ERROR: Cannot open \"%s\" for %s: %s.", path,
1858 (mode == PMCSTAT_OPEN_FOR_READ ? "reading" : "writing"),
1865 * Process a log file in offline analysis mode.
1869 pmcstat_process_log(void)
1873 * If analysis has not been asked for, just print the log to
1874 * the current output file.
1876 if (args.pa_flags & FLAG_DO_PRINT)
1877 return (pmcstat_print_log());
1879 return (pmcstat_analyze_log());
1883 * Refresh top display.
1887 pmcstat_refresh_top(void)
1892 struct pmcstat_pmcrecord *pmcpr;
1894 /* If in pause mode do not refresh display. */
1898 /* Wait until PMC pop in the log. */
1899 pmcpr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
1903 /* Format PMC name. */
1904 if (pmcstat_mergepmc)
1905 snprintf(pmcname, sizeof(pmcname), "[%s]",
1906 pmcstat_string_unintern(pmcpr->pr_pmcname));
1908 snprintf(pmcname, sizeof(pmcname), "%s.%d",
1909 pmcstat_string_unintern(pmcpr->pr_pmcname),
1910 pmcstat_pmcinfilter);
1912 /* Format samples count. */
1913 if (ps_samples_period > 0)
1914 v = (pmcpr->pr_samples * 100.0) / ps_samples_period;
1917 v_attrs = PMCSTAT_ATTRPERCENT(v);
1919 PMCSTAT_PRINTBEGIN();
1920 PMCSTAT_PRINTW("PMC: %s Samples: %u ",
1923 PMCSTAT_ATTRON(v_attrs);
1924 PMCSTAT_PRINTW("(%.1f%%) ", v);
1925 PMCSTAT_ATTROFF(v_attrs);
1926 PMCSTAT_PRINTW(", %u unresolved\n\n",
1927 pmcpr->pr_dubious_frames);
1928 if (plugins[args.pa_plugin].pl_topdisplay != NULL)
1929 plugins[args.pa_plugin].pl_topdisplay();
1934 * Find the next pmc index to display.
1938 pmcstat_changefilter(void)
1941 struct pmcstat_pmcrecord *pmcr;
1944 * Find the next merge target.
1946 if (pmcstat_mergepmc) {
1947 pmcin = pmcstat_pmcinfilter;
1950 pmcr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
1951 if (pmcr == NULL || pmcr == pmcr->pr_merge)
1954 pmcstat_pmcinfilter++;
1955 if (pmcstat_pmcinfilter >= pmcstat_npmcs)
1956 pmcstat_pmcinfilter = 0;
1958 } while (pmcstat_pmcinfilter != pmcin);
1963 * Top mode keypress.
1967 pmcstat_keypress_log(void)
1972 w = newwin(1, 0, 1, 0);
1974 wprintw(w, "Key: %c => ", c);
1977 wprintw(w, "enter mode 'd' or 'a' => ");
1980 args.pa_topmode = PMCSTAT_TOP_DELTA;
1981 wprintw(w, "switching to delta mode");
1983 args.pa_topmode = PMCSTAT_TOP_ACCUM;
1984 wprintw(w, "switching to accumulation mode");
1988 pmcstat_mergepmc = !pmcstat_mergepmc;
1990 * Changing merge state require data reset.
1992 if (plugins[args.pa_plugin].pl_shutdown != NULL)
1993 plugins[args.pa_plugin].pl_shutdown(NULL);
1994 pmcstat_stats_reset(0);
1995 if (plugins[args.pa_plugin].pl_init != NULL)
1996 plugins[args.pa_plugin].pl_init();
1998 /* Update filter to be on a merge target. */
1999 pmcstat_changefilter();
2000 wprintw(w, "merge PMC %s", pmcstat_mergepmc ? "on" : "off");
2003 /* Close current plugin. */
2004 if (plugins[args.pa_plugin].pl_shutdown != NULL)
2005 plugins[args.pa_plugin].pl_shutdown(NULL);
2007 /* Find next top display available. */
2010 if (plugins[args.pa_plugin].pl_name == NULL)
2012 } while (plugins[args.pa_plugin].pl_topdisplay == NULL);
2014 /* Open new plugin. */
2015 pmcstat_stats_reset(0);
2016 if (plugins[args.pa_plugin].pl_init != NULL)
2017 plugins[args.pa_plugin].pl_init();
2018 wprintw(w, "switching to plugin %s",
2019 plugins[args.pa_plugin].pl_name);
2022 pmcstat_pmcinfilter++;
2023 if (pmcstat_pmcinfilter >= pmcstat_npmcs)
2024 pmcstat_pmcinfilter = 0;
2025 pmcstat_changefilter();
2026 wprintw(w, "switching to PMC %s.%d",
2027 pmcstat_pmcindex_to_name(pmcstat_pmcinfilter),
2028 pmcstat_pmcinfilter);
2031 pmcstat_pause = !pmcstat_pause;
2033 wprintw(w, "pause => press space again to continue");
2036 wprintw(w, "exiting...");
2040 if (plugins[args.pa_plugin].pl_topkeypress != NULL)
2041 if (plugins[args.pa_plugin].pl_topkeypress(c, w))
2056 pmcstat_display_log(void)
2059 pmcstat_refresh_top();
2061 /* Reset everythings if delta mode. */
2062 if (args.pa_topmode == PMCSTAT_TOP_DELTA) {
2063 if (plugins[args.pa_plugin].pl_shutdown != NULL)
2064 plugins[args.pa_plugin].pl_shutdown(NULL);
2065 pmcstat_stats_reset(0);
2066 if (plugins[args.pa_plugin].pl_init != NULL)
2067 plugins[args.pa_plugin].pl_init();
2073 * Configure a plugins.
2077 pmcstat_pluginconfigure_log(char *opt)
2080 if (strncmp(opt, "threshold=", 10) == 0) {
2081 pmcstat_threshold = atof(opt+10);
2083 if (plugins[args.pa_plugin].pl_configure != NULL) {
2084 if (!plugins[args.pa_plugin].pl_configure(opt))
2086 "ERROR: unknown option <%s>.", opt);
2092 * Initialize module.
2096 pmcstat_initialize_logging(void)
2100 /* use a convenient format for 'ldd' output */
2101 if (setenv("LD_TRACE_LOADED_OBJECTS_FMT1","%o \"%p\" %x\n",1) != 0)
2102 err(EX_OSERR, "ERROR: Cannot setenv");
2104 /* Initialize hash tables */
2105 pmcstat_string_initialize();
2106 for (i = 0; i < PMCSTAT_NHASH; i++) {
2107 LIST_INIT(&pmcstat_image_hash[i]);
2108 LIST_INIT(&pmcstat_process_hash[i]);
2112 * Create a fake 'process' entry for the kernel with pid -1.
2113 * hwpmc(4) will subsequently inform us about where the kernel
2114 * and any loaded kernel modules are mapped.
2116 if ((pmcstat_kernproc = pmcstat_process_lookup((pid_t) -1,
2117 PMCSTAT_ALLOCATE)) == NULL)
2118 err(EX_OSERR, "ERROR: Cannot initialize logging");
2123 /* Merge PMC with same name. */
2124 pmcstat_mergepmc = args.pa_mergepmc;
2127 * Initialize plugins
2130 if (plugins[args.pa_pplugin].pl_init != NULL)
2131 plugins[args.pa_pplugin].pl_init();
2132 if (plugins[args.pa_plugin].pl_init != NULL)
2133 plugins[args.pa_plugin].pl_init();
2141 pmcstat_shutdown_logging(void)
2145 struct pmcstat_image *pi, *pitmp;
2146 struct pmcstat_process *pp, *pptmp;
2147 struct pmcstat_pcmap *ppm, *ppmtmp;
2149 /* determine where to send the map file */
2151 if (args.pa_mapfilename != NULL)
2152 mf = (strcmp(args.pa_mapfilename, "-") == 0) ?
2153 args.pa_printfile : fopen(args.pa_mapfilename, "w");
2155 if (mf == NULL && args.pa_flags & FLAG_DO_GPROF &&
2156 args.pa_verbosity >= 2)
2157 mf = args.pa_printfile;
2160 (void) fprintf(mf, "MAP:\n");
2163 * Shutdown the plugins
2166 if (plugins[args.pa_plugin].pl_shutdown != NULL)
2167 plugins[args.pa_plugin].pl_shutdown(mf);
2168 if (plugins[args.pa_pplugin].pl_shutdown != NULL)
2169 plugins[args.pa_pplugin].pl_shutdown(mf);
2171 for (i = 0; i < PMCSTAT_NHASH; i++) {
2172 LIST_FOREACH_SAFE(pi, &pmcstat_image_hash[i], pi_next,
2174 if (plugins[args.pa_plugin].pl_shutdownimage != NULL)
2175 plugins[args.pa_plugin].pl_shutdownimage(pi);
2176 if (plugins[args.pa_pplugin].pl_shutdownimage != NULL)
2177 plugins[args.pa_pplugin].pl_shutdownimage(pi);
2179 free(pi->pi_symbols);
2180 if (pi->pi_addr2line != NULL)
2181 pclose(pi->pi_addr2line);
2182 LIST_REMOVE(pi, pi_next);
2186 LIST_FOREACH_SAFE(pp, &pmcstat_process_hash[i], pp_next,
2188 TAILQ_FOREACH_SAFE(ppm, &pp->pp_map, ppm_next, ppmtmp) {
2189 TAILQ_REMOVE(&pp->pp_map, ppm, ppm_next);
2192 LIST_REMOVE(pp, pp_next);
2197 pmcstat_string_shutdown();
2200 * Print errors unless -q was specified. Print all statistics
2203 #define PRINT(N,V) do { \
2204 if (pmcstat_stats.ps_##V || args.pa_verbosity >= 2) \
2205 (void) fprintf(args.pa_printfile, " %-40s %d\n",\
2206 N, pmcstat_stats.ps_##V); \
2209 if (args.pa_verbosity >= 1 && (args.pa_flags & FLAG_DO_ANALYSIS)) {
2210 (void) fprintf(args.pa_printfile, "CONVERSION STATISTICS:\n");
2211 PRINT("#exec/a.out", exec_aout);
2212 PRINT("#exec/elf", exec_elf);
2213 PRINT("#exec/unknown", exec_indeterminable);
2214 PRINT("#exec handling errors", exec_errors);
2215 PRINT("#samples/total", samples_total);
2216 PRINT("#samples/unclaimed", samples_unknown_offset);
2217 PRINT("#samples/unknown-object", samples_indeterminable);
2218 PRINT("#samples/unknown-function", samples_unknown_function);
2219 PRINT("#callchain/dubious-frames", callchain_dubious_frames);