1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1983, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#ifndef lint
33static const char copyright[] =
34"@(#) Copyright (c) 1983, 1993\n\
35	The Regents of the University of California.  All rights reserved.\n";
36#endif /* not lint */
37
38#if 0
39#ifndef lint
40static char sccsid[] = "@(#)gprof.c	8.1 (Berkeley) 6/6/93";
41#endif /* not lint */
42#endif
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD$");
46
47#include <err.h>
48#include <limits.h>
49#include <stdint.h>
50#include <string.h>
51
52#define	EXTERN
53#include "gprof.h"
54
55static int valcmp(const void *, const void *);
56
57static struct gmonhdr	gmonhdr;
58static int lflag;
59static int Lflag;
60
61int
62main(int argc, char **argv)
63{
64    char	**sp;
65    nltype	**timesortnlp;
66    char	**defaultEs;
67
68    --argc;
69    argv++;
70    debug = 0;
71    bflag = TRUE;
72    while ( *argv != 0 && **argv == '-' ) {
73	(*argv)++;
74	switch ( **argv ) {
75	case 'a':
76	    aflag = TRUE;
77	    break;
78	case 'b':
79	    bflag = FALSE;
80	    break;
81	case 'C':
82	    Cflag = TRUE;
83	    cyclethreshold = atoi( *++argv );
84	    break;
85	case 'd':
86	    dflag = TRUE;
87	    setlinebuf(stdout);
88	    debug |= atoi( *++argv );
89	    debug |= ANYDEBUG;
90#	    ifdef DEBUG
91		printf("[main] debug = %d\n", debug);
92#	    else /* not DEBUG */
93		printf("gprof: -d ignored\n");
94#	    endif /* DEBUG */
95	    break;
96	case 'E':
97	    ++argv;
98	    addlist( Elist , *argv );
99	    Eflag = TRUE;
100	    addlist( elist , *argv );
101	    eflag = TRUE;
102	    break;
103	case 'e':
104	    addlist( elist , *++argv );
105	    eflag = TRUE;
106	    break;
107	case 'F':
108	    ++argv;
109	    addlist( Flist , *argv );
110	    Fflag = TRUE;
111	    addlist( flist , *argv );
112	    fflag = TRUE;
113	    break;
114	case 'f':
115	    addlist( flist , *++argv );
116	    fflag = TRUE;
117	    break;
118	case 'k':
119	    addlist( kfromlist , *++argv );
120	    addlist( ktolist , *++argv );
121	    kflag = TRUE;
122	    break;
123	case 'K':
124	    Kflag = TRUE;
125	    break;
126	case 'l':
127	    lflag = 1;
128	    Lflag = 0;
129	    break;
130	case 'L':
131	    Lflag = 1;
132	    lflag = 0;
133	    break;
134	case 's':
135	    sflag = TRUE;
136	    break;
137	case 'u':
138	    uflag = TRUE;
139	    break;
140	case 'z':
141	    zflag = TRUE;
142	    break;
143	}
144	argv++;
145    }
146    if ( *argv != 0 ) {
147	a_outname  = *argv;
148	argv++;
149    } else {
150	a_outname  = A_OUTNAME;
151    }
152    if ( *argv != 0 ) {
153	gmonname = *argv;
154	argv++;
155    } else {
156	gmonname = (char *) malloc(strlen(a_outname)+6);
157	strcpy(gmonname, a_outname);
158	strcat(gmonname, ".gmon");
159    }
160	/*
161	 *	get information from the executable file.
162	 */
163    if ((Kflag && kernel_getnfile(a_outname, &defaultEs) == -1) ||
164      (!Kflag && elf_getnfile(a_outname, &defaultEs) == -1
165#ifdef WITH_AOUT
166      && aout_getnfile(a_outname, &defaultEs) == -1
167#endif
168      ))
169	errx(1, "%s: bad format", a_outname);
170	/*
171	 *	sort symbol table.
172	 */
173    qsort(nl, nname, sizeof(nltype), valcmp);
174	/*
175	 *	turn off default functions
176	 */
177    for ( sp = defaultEs ; *sp ; sp++ ) {
178	Eflag = TRUE;
179	addlist( Elist , *sp );
180	eflag = TRUE;
181	addlist( elist , *sp );
182    }
183	/*
184	 *	get information about mon.out file(s).
185	 */
186    do	{
187	getpfile( gmonname );
188	if ( *argv != 0 ) {
189	    gmonname = *argv;
190	}
191    } while ( *argv++ != 0 );
192	/*
193	 *	how many ticks per second?
194	 *	if we can't tell, report time in ticks.
195	 */
196    if (hz == 0) {
197	hz = 1;
198	fprintf(stderr, "time is in ticks, not seconds\n");
199    }
200	/*
201	 *	dump out a gmon.sum file if requested
202	 */
203    if ( sflag ) {
204	dumpsum( GMONSUM );
205    }
206	/*
207	 *	assign samples to procedures
208	 */
209    asgnsamples();
210	/*
211	 *	assemble the dynamic profile
212	 */
213    timesortnlp = doarcs();
214	/*
215	 *	print the dynamic profile
216	 */
217    if(!lflag) {
218	    printgprof( timesortnlp );
219    }
220	/*
221	 *	print the flat profile
222	 */
223    if(!Lflag) {
224	    printprof();
225    }
226	/*
227	 *	print the index
228	 */
229    printindex();
230    exit(0);
231}
232
233    /*
234     *	information from a gmon.out file is in two parts:
235     *	an array of sampling hits within pc ranges,
236     *	and the arcs.
237     */
238void
239getpfile(char *filename)
240{
241    FILE		*pfile;
242    struct rawarc	arc;
243
244    pfile = openpfile(filename);
245    readsamples(pfile);
246	/*
247	 *	the rest of the file consists of
248	 *	a bunch of <from,self,count> tuples.
249	 */
250    while ( fread( &arc , sizeof arc , 1 , pfile ) == 1 ) {
251#	ifdef DEBUG
252	    if ( debug & SAMPLEDEBUG ) {
253		printf( "[getpfile] frompc 0x%lx selfpc 0x%lx count %ld\n" ,
254			arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
255	    }
256#	endif /* DEBUG */
257	    /*
258	     *	add this arc
259	     */
260	tally( &arc );
261    }
262    fclose(pfile);
263}
264
265FILE *
266openpfile(char *filename)
267{
268    struct gmonhdr	tmp;
269    FILE		*pfile;
270    int			size;
271    int			rate;
272
273    if((pfile = fopen(filename, "r")) == NULL)
274	err(1, "%s", filename);
275    fread(&tmp, sizeof(struct gmonhdr), 1, pfile);
276    if ( s_highpc != 0 && ( tmp.lpc != gmonhdr.lpc ||
277	 tmp.hpc != gmonhdr.hpc || tmp.ncnt != gmonhdr.ncnt ) )
278	errx(1, "%s: incompatible with first gmon file", filename);
279    gmonhdr = tmp;
280    if ( gmonhdr.version == GMONVERSION ) {
281	rate = gmonhdr.profrate;
282	size = sizeof(struct gmonhdr);
283    } else {
284	fseek(pfile, sizeof(struct ophdr), SEEK_SET);
285	size = sizeof(struct ophdr);
286	gmonhdr.profrate = rate = hertz();
287	gmonhdr.version = GMONVERSION;
288    }
289    if (hz == 0) {
290	hz = rate;
291    } else if (hz != rate)
292	errx(0, "%s: profile clock rate (%d) %s (%ld) in first gmon file",
293	    filename, rate, "incompatible with clock rate", hz);
294    if ( gmonhdr.histcounter_type == 0 ) {
295	/* Historical case.  The type was u_short (2 bytes in practice). */
296	histcounter_type = 16;
297	histcounter_size = 2;
298    } else {
299	histcounter_type = gmonhdr.histcounter_type;
300	histcounter_size = abs(histcounter_type) / CHAR_BIT;
301    }
302    s_lowpc = (unsigned long) gmonhdr.lpc;
303    s_highpc = (unsigned long) gmonhdr.hpc;
304    lowpc = (unsigned long)gmonhdr.lpc / HISTORICAL_SCALE_2;
305    highpc = (unsigned long)gmonhdr.hpc / HISTORICAL_SCALE_2;
306    sampbytes = gmonhdr.ncnt - size;
307    nsamples = sampbytes / histcounter_size;
308#   ifdef DEBUG
309	if ( debug & SAMPLEDEBUG ) {
310	    printf( "[openpfile] hdr.lpc 0x%lx hdr.hpc 0x%lx hdr.ncnt %d\n",
311		gmonhdr.lpc , gmonhdr.hpc , gmonhdr.ncnt );
312	    printf( "[openpfile]   s_lowpc 0x%lx   s_highpc 0x%lx\n" ,
313		s_lowpc , s_highpc );
314	    printf( "[openpfile]     lowpc 0x%lx     highpc 0x%lx\n" ,
315		lowpc , highpc );
316	    printf( "[openpfile] sampbytes %d nsamples %d\n" ,
317		sampbytes , nsamples );
318	    printf( "[openpfile] sample rate %ld\n" , hz );
319	}
320#   endif /* DEBUG */
321    return(pfile);
322}
323
324void
325tally(struct rawarc *rawp)
326{
327    nltype		*parentp;
328    nltype		*childp;
329
330    parentp = nllookup( rawp -> raw_frompc );
331    childp = nllookup( rawp -> raw_selfpc );
332    if ( parentp == 0 || childp == 0 )
333	return;
334    if ( kflag
335	 && onlist( kfromlist , parentp -> name )
336	 && onlist( ktolist , childp -> name ) ) {
337	return;
338    }
339    childp -> ncall += rawp -> raw_count;
340#   ifdef DEBUG
341	if ( debug & TALLYDEBUG ) {
342	    printf( "[tally] arc from %s to %s traversed %ld times\n" ,
343		    parentp -> name , childp -> name , rawp -> raw_count );
344	}
345#   endif /* DEBUG */
346    addarc( parentp , childp , rawp -> raw_count );
347}
348
349/*
350 * dump out the gmon.sum file
351 */
352void
353dumpsum(const char *sumfile)
354{
355    register nltype *nlp;
356    register arctype *arcp;
357    struct rawarc arc;
358    FILE *sfile;
359
360    if ( ( sfile = fopen ( sumfile , "w" ) ) == NULL )
361	err( 1 , "%s" , sumfile );
362    /*
363     * dump the header; use the last header read in
364     */
365    if ( fwrite( &gmonhdr , sizeof gmonhdr , 1 , sfile ) != 1 )
366	err( 1 , "%s" , sumfile );
367    /*
368     * dump the samples
369     */
370    if (fwrite(samples, histcounter_size, nsamples, sfile) != nsamples)
371	err( 1 , "%s" , sumfile );
372    /*
373     * dump the normalized raw arc information
374     */
375    for ( nlp = nl ; nlp < npe ; nlp++ ) {
376	for ( arcp = nlp -> children ; arcp ; arcp = arcp -> arc_childlist ) {
377	    arc.raw_frompc = arcp -> arc_parentp -> value;
378	    arc.raw_selfpc = arcp -> arc_childp -> value;
379	    arc.raw_count = arcp -> arc_count;
380	    if ( fwrite ( &arc , sizeof arc , 1 , sfile ) != 1 )
381		err( 1 , "%s" , sumfile );
382#	    ifdef DEBUG
383		if ( debug & SAMPLEDEBUG ) {
384		    printf( "[dumpsum] frompc 0x%lx selfpc 0x%lx count %ld\n" ,
385			    arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
386		}
387#	    endif /* DEBUG */
388	}
389    }
390    fclose( sfile );
391}
392
393static int
394valcmp(const void *v1, const void *v2)
395{
396    const nltype *p1 = (const nltype *)v1;
397    const nltype *p2 = (const nltype *)v2;
398
399    if ( p1 -> value < p2 -> value ) {
400	return LESSTHAN;
401    }
402    if ( p1 -> value > p2 -> value ) {
403	return GREATERTHAN;
404    }
405    return EQUALTO;
406}
407
408void
409readsamples(FILE *pfile)
410{
411    int		i;
412    intmax_t	sample;
413
414    if (samples == 0) {
415	samples = (double *) calloc(nsamples, sizeof(double));
416	if (samples == NULL)
417	    errx(0, "no room for %d sample pc's", nsamples);
418    }
419    for (i = 0; i < nsamples; i++) {
420	fread(&sample, histcounter_size, 1, pfile);
421	if (feof(pfile))
422		break;
423	switch ( histcounter_type ) {
424	case -8:
425	    samples[i] += *(int8_t *)&sample;
426	    break;
427	case 8:
428	    samples[i] += *(u_int8_t *)&sample;
429	    break;
430	case -16:
431	    samples[i] += *(int16_t *)&sample;
432	    break;
433	case 16:
434	    samples[i] += *(u_int16_t *)&sample;
435	    break;
436	case -32:
437	    samples[i] += *(int32_t *)&sample;
438	    break;
439	case 32:
440	    samples[i] += *(u_int32_t *)&sample;
441	    break;
442	case -64:
443	    samples[i] += *(int64_t *)&sample;
444	    break;
445	case 64:
446	    samples[i] += *(u_int64_t *)&sample;
447	    break;
448	default:
449	    err(1, "unsupported histogram counter type %d", histcounter_type);
450	}
451    }
452    if (i != nsamples)
453	errx(1, "unexpected EOF after reading %d/%d samples", --i , nsamples );
454}
455
456/*
457 *	Assign samples to the procedures to which they belong.
458 *
459 *	There are three cases as to where pcl and pch can be
460 *	with respect to the routine entry addresses svalue0 and svalue1
461 *	as shown in the following diagram.  overlap computes the
462 *	distance between the arrows, the fraction of the sample
463 *	that is to be credited to the routine which starts at svalue0.
464 *
465 *	    svalue0                                         svalue1
466 *	       |                                               |
467 *	       v                                               v
468 *
469 *	       +-----------------------------------------------+
470 *	       |					       |
471 *	  |  ->|    |<-		->|         |<-		->|    |<-  |
472 *	  |         |		  |         |		  |         |
473 *	  +---------+		  +---------+		  +---------+
474 *
475 *	  ^         ^		  ^         ^		  ^         ^
476 *	  |         |		  |         |		  |         |
477 *	 pcl       pch		 pcl       pch		 pcl       pch
478 *
479 *	For the vax we assert that samples will never fall in the first
480 *	two bytes of any routine, since that is the entry mask,
481 *	thus we give call alignentries() to adjust the entry points if
482 *	the entry mask falls in one bucket but the code for the routine
483 *	doesn't start until the next bucket.  In conjunction with the
484 *	alignment of routine addresses, this should allow us to have
485 *	only one sample for every four bytes of text space and never
486 *	have any overlap (the two end cases, above).
487 */
488void
489asgnsamples(void)
490{
491    register int	j;
492    double		ccnt;
493    double		thetime;
494    unsigned long	pcl, pch;
495    register int	i;
496    unsigned long	overlap;
497    unsigned long	svalue0, svalue1;
498
499    /* read samples and assign to namelist symbols */
500    scale = highpc - lowpc;
501    scale /= nsamples;
502    alignentries();
503    for (i = 0, j = 1; i < nsamples; i++) {
504	ccnt = samples[i];
505	if (ccnt == 0)
506		continue;
507	pcl = lowpc + (unsigned long)(scale * i);
508	pch = lowpc + (unsigned long)(scale * (i + 1));
509	thetime = ccnt;
510#	ifdef DEBUG
511	    if ( debug & SAMPLEDEBUG ) {
512		printf( "[asgnsamples] pcl 0x%lx pch 0x%lx ccnt %.0f\n" ,
513			pcl , pch , ccnt );
514	    }
515#	endif /* DEBUG */
516	totime += thetime;
517	for (j = j - 1; j < nname; j++) {
518	    svalue0 = nl[j].svalue;
519	    svalue1 = nl[j+1].svalue;
520		/*
521		 *	if high end of tick is below entry address,
522		 *	go for next tick.
523		 */
524	    if (pch < svalue0)
525		    break;
526		/*
527		 *	if low end of tick into next routine,
528		 *	go for next routine.
529		 */
530	    if (pcl >= svalue1)
531		    continue;
532	    overlap = min(pch, svalue1) - max(pcl, svalue0);
533	    if (overlap > 0) {
534#		ifdef DEBUG
535		    if (debug & SAMPLEDEBUG) {
536			printf("[asgnsamples] (0x%lx->0x%lx-0x%lx) %s gets %f ticks %lu overlap\n",
537				nl[j].value / HISTORICAL_SCALE_2,
538				svalue0, svalue1, nl[j].name,
539				overlap * thetime / scale, overlap);
540		    }
541#		endif /* DEBUG */
542		nl[j].time += overlap * thetime / scale;
543	    }
544	}
545    }
546#   ifdef DEBUG
547	if (debug & SAMPLEDEBUG) {
548	    printf("[asgnsamples] totime %f\n", totime);
549	}
550#   endif /* DEBUG */
551}
552
553
554unsigned long
555min(unsigned long a, unsigned long b)
556{
557    if (a<b)
558	return(a);
559    return(b);
560}
561
562unsigned long
563max(unsigned long a, unsigned long b)
564{
565    if (a>b)
566	return(a);
567    return(b);
568}
569
570    /*
571     *	calculate scaled entry point addresses (to save time in asgnsamples),
572     *	and possibly push the scaled entry points over the entry mask,
573     *	if it turns out that the entry point is in one bucket and the code
574     *	for a routine is in the next bucket.
575     */
576void
577alignentries(void)
578{
579    register struct nl	*nlp;
580    unsigned long	bucket_of_entry;
581    unsigned long	bucket_of_code;
582
583    for (nlp = nl; nlp < npe; nlp++) {
584	nlp -> svalue = nlp -> value / HISTORICAL_SCALE_2;
585	bucket_of_entry = (nlp->svalue - lowpc) / scale;
586	bucket_of_code = (nlp->svalue + OFFSET_OF_CODE / HISTORICAL_SCALE_2 -
587	  lowpc) / scale;
588	if (bucket_of_entry < bucket_of_code) {
589#	    ifdef DEBUG
590		if (debug & SAMPLEDEBUG) {
591		    printf("[alignentries] pushing svalue 0x%lx to 0x%lx\n",
592			    nlp->svalue,
593			    nlp->svalue + OFFSET_OF_CODE / HISTORICAL_SCALE_2);
594		}
595#	    endif /* DEBUG */
596	    nlp->svalue += OFFSET_OF_CODE / HISTORICAL_SCALE_2;
597	}
598    }
599}
600