blob: 54c4ccec9f928d5dd9557f346cfb0e53836dc9e8 [file] [log] [blame]
nethercotec9f36922004-02-14 16:40:02 +00001
2/*--------------------------------------------------------------------*/
3/*--- Massif: a heap profiling skin. ms_main.c ---*/
4/*--------------------------------------------------------------------*/
5
6/*
7 This file is part of Massif, a Valgrind skin for profiling memory
8 usage of programs.
9
10 Copyright (C) 2003 Nicholas Nethercote
11 njn25@cam.ac.uk
12
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation; either version 2 of the
16 License, or (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26 02111-1307, USA.
27
28 The GNU General Public License is contained in the file COPYING.
29*/
30
31// Memory profiler. Produces a graph, gives lots of information about
32// allocation contexts, in terms of space.time values (ie. area under the
33// graph). Allocation context information is hierarchical, and can thus
34// be inspected step-wise to an appropriate depth. See comments on data
35// structures below for more info on how things work.
36
37#include "vg_skin.h"
38//#include "vg_profile.c"
39
40#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
41
42/*------------------------------------------------------------*/
43/*--- Overview of operation ---*/
44/*------------------------------------------------------------*/
45
46// Heap blocks are tracked, and the amount of space allocated by various
47// contexts (ie. lines of code, more or less) is also tracked.
48// Periodically, a census is taken, and the amount of space used, at that
49// point, by the most significant (highly allocating) contexts is recorded.
50// Census start off frequently, but are scaled back as the program goes on,
51// so that there are always a good number of them. At the end, overall
52// spacetimes for different contexts (of differing levels of precision) is
53// calculated, the graph is printed, and the text giving spacetimes for the
54// increasingly precise contexts is given.
55//
56// Measures the following:
57// - heap blocks
58// - heap admin bytes
59// - stack(s)
60// - code (code segments loaded at startup, and loaded with mmap)
61// - data (data segments loaded at startup, and loaded/created with mmap,
62// and brk()d segments)
63
64/*------------------------------------------------------------*/
65/*--- Main types ---*/
66/*------------------------------------------------------------*/
67
68// An XPt represents an "execution point", ie. a code address. Each XPt is
69// part of a tree of XPts (an "execution tree", or "XTree"). Each
70// top-to-bottom path through an XTree gives an execution context ("XCon"),
71// and is equivalent to a traditional Valgrind ExeContext.
72//
73// The XPt at the top of an XTree (but below "alloc_xpt") is called a
74// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
75// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
76// bottom-XPTs in that XTree.
77//
78// All XCons have the same top-XPt, "alloc_xpt", which represents all
79// allocation functions like malloc(). It's a bit of a fake XPt, though,
80// and is only used because it makes some of the code simpler.
81//
82// XTrees are bi-directional.
83//
84// > parent < Example: if child1() calls parent() and child2()
85// / | \ also calls parent(), and parent() calls malloc(),
86// | / \ | the XTree will look like this.
87// | v v |
88// child1 child2
89
90typedef struct _XPt XPt;
91
92struct _XPt {
93 Addr eip; // code address
94
95 // Bottom-XPts: space for the precise context.
96 // Other XPts: space of all the descendent bottom-XPts.
97 // Nb: this value goes up and down as the program executes.
98 UInt curr_space;
99
100 // An approximate space.time calculation used along the way for selecting
101 // which contexts to include at each census point.
102 // !!! top-XPTs only !!!
103 ULong spacetime;
104
105 // spacetime2 is an exact space.time calculation done at the end, and
106 // used in the results.
107 // Note that it is *doubled*, to avoid rounding errors.
108 // !!! not used for 'alloc_xpt' !!!
109 ULong spacetime2;
110
111 // n_children and max_children are integers; a very big program might
112 // have more than 65536 allocation points (Konqueror startup has 1800).
113 XPt* parent; // pointer to parent XPt
114 UInt n_children; // number of children
115 UInt max_children; // capacity of children array
116 XPt** children; // pointers to children XPts
117};
118
119// Each census snapshots the most significant XTrees, each XTree having a
120// top-XPt as its root. The 'curr_space' element for each XPt is recorded
121// in the snapshot. The snapshot contains all the XTree's XPts, not in a
122// tree structure, but flattened into an array. This flat snapshot is used
123// at the end for computing spacetime2 for each XPt.
124//
125// Graph resolution, x-axis: no point having more than about 200 census
126// x-points; you can't see them on the graph. Therefore:
127//
128// - do a census every 1 ms for first 200 --> 200, all (200 ms)
129// - halve (drop half of them) --> 100, every 2nd (200 ms)
130// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
131// - halve --> 100, every 4th (400 ms)
132// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
133// - etc.
134//
135// This isn't exactly right, because we actually drop (N/2)-1 when halving,
136// but it shows the basic idea.
137
138#define MAX_N_CENSI 200 // Keep it even, for simplicity
139
140// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
141// bands, rest get lumped into OTHERS. I only print the top N
142// (cumulative-so-far space-time) at each point. N should be a bit bigger
143// than 19 in case the cumulative space-time doesn't fit with the eventual
144// space-time computed by hp2ps (but it should be close if the samples are
145// evenly spread, since hp2ps does an approximate per-band space-time
146// calculation that just sums the totals; ie. it assumes all samples are
147// the same distance apart).
148
149#define MAX_SNAPSHOTS 32
150
151typedef
152 struct {
153 XPt* xpt;
154 UInt space;
155 }
156 XPtSnapshot;
157
158// An XTree snapshot is stored as an array of of XPt snapshots.
159typedef XPtSnapshot* XTreeSnapshot;
160
161typedef
162 struct {
163 Int ms_time; // Int: must allow -1
164 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
165 UInt others_space;
166 UInt heap_admin_space;
167 UInt stacks_space;
168 }
169 Census;
170
171// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
172// which is a foothold into the XCon at which it was allocated. From
173// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
174// decremented (at deallocation).
175//
176// Nb: first two fields must match core's VgHashNode.
177typedef
178 struct _HP_Chunk {
179 struct _HP_Chunk* next;
180 Addr data; // Ptr to actual block
181 UInt size; // Size requested
182 XPt* where; // Where allocated; bottom-XPt
183 }
184 HP_Chunk;
185
186/*------------------------------------------------------------*/
187/*--- Profiling events ---*/
188/*------------------------------------------------------------*/
189
190typedef
191 enum {
192 VgpGetXPt = VgpFini+1,
193 VgpGetXPtSearch,
194 VgpCensus,
195 VgpCensusHeap,
196 VgpCensusSnapshot,
197 VgpCensusTreeSize,
198 VgpUpdateXCon,
199 VgpCalcSpacetime2,
200 VgpPrintHp,
201 VgpPrintXPts,
202 }
203 VgpSkinCC;
204
205/*------------------------------------------------------------*/
206/*--- Statistics ---*/
207/*------------------------------------------------------------*/
208
209// Konqueror startup, to give an idea of the numbers involved with a biggish
210// program, with default depth:
211//
212// depth=3 depth=40
213// - 310,000 allocations
214// - 300,000 frees
215// - 15,000 XPts 800,000 XPts
216// - 1,800 top-XPts
217
218static UInt n_xpts = 0;
219static UInt n_bot_xpts = 0;
220static UInt n_allocs = 0;
221static UInt n_zero_allocs = 0;
222static UInt n_frees = 0;
223static UInt n_children_reallocs = 0;
224static UInt n_snapshot_frees = 0;
225
226static UInt n_halvings = 0;
227static UInt n_real_censi = 0;
228static UInt n_fake_censi = 0;
229static UInt n_attempted_censi = 0;
230
231/*------------------------------------------------------------*/
232/*--- Globals ---*/
233/*------------------------------------------------------------*/
234
235#define FILENAME_LEN 256
236
237#define SPRINTF(zz_buf, fmt, args...) \
238 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
239 VG_(write)(fd, (void*)zz_buf, len); \
240 } while (0)
241
242#define BUF_LEN 1024 // general purpose
243static Char buf [BUF_LEN];
244static Char buf2[BUF_LEN];
245static Char buf3[BUF_LEN];
246
247static UInt sigstacks_space = 0; // Current signal stacks space sum
248
249static VgHashTable malloc_list = NULL; // HP_Chunks
250
251static UInt n_heap_blocks = 0;
252
253
254#define MAX_ALLOC_FNS 32 // includes the builtin ones
255
256// First six filled in, rest should be zeroed. argc/argv-style vector.
257static UInt n_alloc_fns = 8;
258static Char* alloc_fns[MAX_ALLOC_FNS] = {
259 "malloc",
260 "operator new(unsigned)",
261 "operator new[](unsigned)",
262 "__builtin_new",
263 "__builtin_vec_new",
264 "calloc",
265 "realloc",
266 "my_malloc", // from vg_libpthread.c
267};
268
269
270/*------------------------------------------------------------*/
271/*--- Command line args ---*/
272/*------------------------------------------------------------*/
273
274#define MAX_DEPTH 50
275
276typedef
277 enum {
278 XText, XHTML,
279 }
280 XFormat;
281
282static Bool clo_heap = True;
283static UInt clo_heap_admin = 8;
284static Bool clo_stacks = True;
285static Bool clo_depth = 3;
286static XFormat clo_format = XText;
287
288Bool SK_(process_cmd_line_option)(Char* arg)
289{
290 if (VG_CLO_STREQ(arg, "--heap=yes"))
291 clo_heap = True;
292 else if (VG_CLO_STREQ(arg, "--heap=no"))
293 clo_heap = False;
294
295 else if (VG_CLO_STREQN(13, arg, "--heap-admin=")) {
296 clo_heap_admin = (Int)VG_(atoll)(&arg[13]);
297 if (clo_heap_admin > 100) {
298 VG_(message)(Vg_UserMsg,
299 "Admin size for heap blocks too large");
300 VG_(bad_option)(arg);
301 }
302 }
303
304 else if (VG_CLO_STREQ(arg, "--stacks=yes"))
305 clo_stacks = True;
306 else if (VG_CLO_STREQ(arg, "--stacks=no"))
307 clo_stacks = False;
308
309 else if (VG_CLO_STREQN(8, arg, "--depth=")) {
310 clo_depth = (Int)VG_(atoll)(&arg[8]);
311 if (clo_depth < 1) clo_depth = 1;
312 if (clo_depth >= MAX_DEPTH) clo_depth = MAX_DEPTH;
313 }
314
315 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
316 alloc_fns[n_alloc_fns] = & arg[11];
317 n_alloc_fns++;
318 if (n_alloc_fns >= MAX_ALLOC_FNS) {
319 VG_(printf)("Too many alloc functions specified, sorry");
320 VG_(bad_option)(arg);
321 }
322 }
323
324 else if (VG_CLO_STREQ(arg, "--format=text"))
325 clo_format = XText;
326 else if (VG_CLO_STREQ(arg, "--format=html"))
327 clo_format = XHTML;
328
329 else
330 return VG_(replacement_malloc_process_cmd_line_option)(arg);
331
332 return True;
333}
334
335void SK_(print_usage)(void)
336{
337 VG_(printf)(
338" --heap=no|yes profile heap blocks [yes]\n"
339" --heap-admin=<number> average admin bytes per heap block [8]\n"
340" --stacks=no|yes profile stack(s) [yes]\n"
341" --depth=<number> depth of contexts [3]\n"
342" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
343" --format=text|html format of textual output [text]\n"
344 );
345 VG_(replacement_malloc_print_usage)();
346}
347
348void SK_(print_debug_usage)(void)
349{
350 VG_(replacement_malloc_print_debug_usage)();
351}
352
353/*------------------------------------------------------------*/
354/*--- Execution contexts ---*/
355/*------------------------------------------------------------*/
356
357// Fake XPt representing all allocation functions like malloc(). Acts as
358// parent node to all top-XPts.
359static XPt* alloc_xpt;
360
361// Cheap allocation for blocks that never need to be freed. Saves about 10%
362// for Konqueror startup with --depth=40.
363static void* perm_malloc(UInt n_bytes)
364{
365 static Addr hp = 0; // current heap pointer
366 static Addr hp_lim = 0; // maximum usable byte in current block
367
368 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
369
370 if (hp + n_bytes > hp_lim) {
371 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
372 hp_lim = hp + SUPERBLOCK_SIZE - 1;
373 }
374
375 hp += n_bytes;
376
377 return (void*)(hp - n_bytes);
378}
379
380
381
382static XPt* new_XPt(Addr eip, XPt* parent, Bool is_bottom)
383{
384 XPt* xpt = perm_malloc(sizeof(XPt));
385 xpt->eip = eip;
386
387 xpt->curr_space = 0;
388 xpt->spacetime = 0;
389 xpt->spacetime2 = 0;
390
391 xpt->parent = parent;
392 sk_assert(parent == NULL || 0xffffffff != parent->eip);
393
394 xpt->n_children = 0;
395
396 // If a bottom-XPt, don't allocate space for children. This can be 50%
397 // or more, although it tends to drop as --depth increases (eg. 10% for
398 // konqueror with --depth=20).
399 if ( is_bottom ) {
400 xpt->max_children = 0;
401 xpt->children = NULL;
402 n_bot_xpts++;
403 } else {
404 xpt->max_children = 4;
405 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
406 }
407
408 // Update statistics
409 n_xpts++;
410
411 return xpt;
412}
413
414static Bool is_alloc_fn(Addr eip)
415{
416 Int i;
417
418 if ( VG_(get_fnname)(eip, buf, BUF_LEN) ) {
419 for (i = 0; i < n_alloc_fns; i++) {
420 if (VG_STREQ(buf, alloc_fns[i]))
421 return True;
422 }
423 }
424 return False;
425}
426
427// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
428// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
429// to ensure this in certain cases. See comments below.
430static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
431{
432 // Static to minimise stack size. +1 for added 0xffffffff %eip.
433 static Addr eips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
434
435 XPt* xpt = alloc_xpt;
436 UInt n_eips, L, A, B, nC;
437 UInt overestimate;
438 Bool reached_bottom;
439
440 VGP_PUSHCC(VgpGetXPt);
441
442 // Want at least clo_depth non-alloc-fn entries in the snapshot.
443 // However, because we have 1 or more (an unknown number, at this point)
444 // alloc-fns ignored, we overestimate the size needed for the stack
445 // snapshot. Then, if necessary, we repeatedly increase the size until
446 // it is enough.
447 overestimate = 2;
448 while (True) {
449 n_eips = VG_(stack_snapshot)( tid, eips, clo_depth + overestimate );
450
451 // Now we add a dummy "unknown" %eip at the end. This is only used if we
452 // run out of %eips before hitting clo_depth. It's done to ensure the
453 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
454 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
455 // the parent's spacetime wouldn't be equal to the total of the
456 // childrens' spacetimes).
457 eips[ n_eips++ ] = 0xffffffff;
458
459 // Skip over alloc functions in eips[].
460 for (L = 0; is_alloc_fn(eips[L]) && L < n_eips; L++) { }
461
462 // Must be at least one alloc function, unless client used
463 // MALLOCLIKE_BLOCK
464 if (!custom_malloc) sk_assert(L > 0);
465
466 // Should be at least one non-alloc function. If not, try again.
467 if (L == n_eips) {
468 overestimate += 2;
469 if (overestimate > MAX_ALLOC_FNS)
470 VG_(skin_panic)("No stk snapshot big enough to find non-alloc fns");
471 } else {
472 break;
473 }
474 }
475 A = L;
476 B = n_eips - 1;
477 reached_bottom = False;
478
479 // By this point, the eips we care about are in eips[A]..eips[B]
480
481 // Now do the search/insertion of the XCon. 'L' is the loop counter,
482 // being the index into eips[].
483 while (True) {
484 // Look for %eip in xpt's children.
485 // XXX: linear search, ugh -- about 10% of time for konqueror startup
486 // XXX: tried cacheing last result, only hit about 4% for konqueror
487 // Nb: this search hits about 98% of the time for konqueror
488 VGP_PUSHCC(VgpGetXPtSearch);
489
490 // If we've searched/added deep enough, or run out of EIPs, this is
491 // the bottom XPt.
492 if (L - A + 1 == clo_depth || L == B)
493 reached_bottom = True;
494
495 nC = 0;
496 while (True) {
497 if (nC == xpt->n_children) {
498 // not found, insert new XPt
499 sk_assert(xpt->max_children != 0);
500 sk_assert(xpt->n_children <= xpt->max_children);
501 // Expand 'children' if necessary
502 if (xpt->n_children == xpt->max_children) {
503 xpt->max_children *= 2;
504 xpt->children = VG_(realloc)( xpt->children,
505 xpt->max_children * sizeof(XPt*) );
506 n_children_reallocs++;
507 }
508 // Make new XPt for %eip, insert in list
509 xpt->children[ xpt->n_children++ ] =
510 new_XPt(eips[L], xpt, reached_bottom);
511 break;
512 }
513 if (eips[L] == xpt->children[nC]->eip) break; // found the %eip
514 nC++; // keep looking
515 }
516 VGP_POPCC(VgpGetXPtSearch);
517
518 // Return found/built bottom-XPt.
519 if (reached_bottom) {
520 sk_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
521 VGP_POPCC(VgpGetXPt);
522 return xpt->children[nC];
523 }
524
525 // Descend to next level in XTree, the newly found/built non-bottom-XPt
526 xpt = xpt->children[nC];
527 L++;
528 }
529}
530
531// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
532static void update_XCon(XPt* xpt, Int space_delta)
533{
534 VGP_PUSHCC(VgpUpdateXCon);
535
536 sk_assert(True == clo_heap);
537 sk_assert(0 != space_delta);
538 sk_assert(NULL != xpt);
539 sk_assert(0 == xpt->n_children); // must be bottom-XPt
540
541 while (xpt != alloc_xpt) {
542 if (space_delta < 0) sk_assert(xpt->curr_space >= -space_delta);
543 xpt->curr_space += space_delta;
544 xpt = xpt->parent;
545 }
546 if (space_delta < 0) sk_assert(alloc_xpt->curr_space >= -space_delta);
547 alloc_xpt->curr_space += space_delta;
548
549 VGP_POPCC(VgpUpdateXCon);
550}
551
552// Actually want a reverse sort, biggest to smallest
553static Int XPt_cmp_spacetime(void* n1, void* n2)
554{
555 XPt* xpt1 = *(XPt**)n1;
556 XPt* xpt2 = *(XPt**)n2;
557 return (xpt1->spacetime < xpt2->spacetime ? 1 : -1);
558}
559
560static Int XPt_cmp_spacetime2(void* n1, void* n2)
561{
562 XPt* xpt1 = *(XPt**)n1;
563 XPt* xpt2 = *(XPt**)n2;
564 return (xpt1->spacetime2 < xpt2->spacetime2 ? 1 : -1);
565}
566
567
568/*------------------------------------------------------------*/
569/*--- A generic Queue ---*/
570/*------------------------------------------------------------*/
571
572typedef
573 struct {
574 UInt head; // Index of first entry
575 UInt tail; // Index of final+1 entry, ie. next free slot
576 UInt max_elems;
577 void** elems;
578 }
579 Queue;
580
581static Queue* construct_queue(UInt size)
582{
583 UInt i;
584 Queue* q = VG_(malloc)(sizeof(Queue));
585 q->head = 0;
586 q->tail = 0;
587 q->max_elems = size;
588 q->elems = VG_(malloc)(size * sizeof(void*));
589 for (i = 0; i < size; i++)
590 q->elems[i] = NULL;
591
592 return q;
593}
594
595static void destruct_queue(Queue* q)
596{
597 VG_(free)(q->elems);
598 VG_(free)(q);
599}
600
601static void shuffle(Queue* dest_q, void** old_elems)
602{
603 UInt i, j;
604 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
605 dest_q->elems[i] = old_elems[j];
606 dest_q->head = 0;
607 dest_q->tail = i;
608 for ( ; i < dest_q->max_elems; i++)
609 dest_q->elems[i] = NULL; // paranoia
610}
611
612// Shuffles elements down. If not enough slots free, increase size. (We
613// don't wait until we've completely run out of space, because there could
614// be lots of shuffling just before that point which would be slow.)
615static void adjust(Queue* q)
616{
617 void** old_elems;
618
619 sk_assert(q->tail == q->max_elems);
620 if (q->head < 10) {
621 old_elems = q->elems;
622 q->max_elems *= 2;
623 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
624 shuffle(q, old_elems);
625 VG_(free)(old_elems);
626 } else {
627 shuffle(q, q->elems);
628 }
629}
630
631static void enqueue(Queue* q, void* elem)
632{
633 if (q->tail == q->max_elems)
634 adjust(q);
635 q->elems[q->tail++] = elem;
636}
637
638static Bool is_empty_queue(Queue* q)
639{
640 return (q->head == q->tail);
641}
642
643static void* dequeue(Queue* q)
644{
645 if (is_empty_queue(q))
646 return NULL; // Queue empty
647 else
648 return q->elems[q->head++];
649}
650
651/*------------------------------------------------------------*/
652/*--- malloc() et al replacement wrappers ---*/
653/*------------------------------------------------------------*/
654
655static __inline__
656void add_HP_Chunk(HP_Chunk* hc)
657{
658 n_heap_blocks++;
659 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
660}
661
662static __inline__
663HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
664{
665 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UInt)p,
666 (VgHashNode***)prev_chunks_next_ptr );
667}
668
669static __inline__
670void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
671{
672 sk_assert(n_heap_blocks > 0);
673 n_heap_blocks--;
674 *prev_chunks_next_ptr = hc->next;
675}
676
677// Forward declaration
678static void hp_census(void);
679
680static __inline__
681void new_block_meta ( void* p, Int size, Bool custom_malloc )
682{
683 HP_Chunk* hc;
684
685 VGP_PUSHCC(VgpCliMalloc);
686
687 if (0 == size) n_zero_allocs++;
688
689 // Make new HP_Chunk node, add to malloclist
690 hc = VG_(malloc)(sizeof(HP_Chunk));
691 hc->size = size;
692 hc->data = (Addr)p;
693
694 if (clo_heap) {
695 hc->where = get_XCon( VG_(get_current_or_recent_tid)(), custom_malloc );
696 if (size != 0)
697 update_XCon(hc->where, size);
698 } else {
699 hc->where = NULL; // paranoia
700 }
701
702 add_HP_Chunk( hc );
703
704 hp_census(); // do a census!
705
706 VGP_POPCC(VgpCliMalloc);
707}
708
709static __inline__
710void* new_block ( Int size, UInt align, Bool is_zeroed )
711{
712 void* p;
713
714 if (size < 0) return NULL;
715
716 VGP_PUSHCC(VgpCliMalloc);
717
718 // Update statistics
719 n_allocs++;
720
721 p = VG_(cli_malloc)( align, size );
722 if (is_zeroed) VG_(memset)(p, 0, size);
723 new_block_meta(p, size, /*custom_malloc*/False);
724
725 VGP_POPCC(VgpCliMalloc);
726 return p;
727}
728
729static __inline__
730void die_block ( void* p, Bool custom_free )
731{
732 HP_Chunk* hc;
733 HP_Chunk** remove_handle;
734
735 VGP_PUSHCC(VgpCliMalloc);
736
737 // Update statistics
738 n_frees++;
739
740 hc = get_HP_Chunk ( p, &remove_handle );
741 if (hc == NULL)
742 return; // must have been a bogus free(), or p==NULL
743
744 sk_assert(hc->data == (Addr)p);
745
746 if (clo_heap && hc->size != 0)
747 update_XCon(hc->where, -hc->size);
748
749 // Actually free the heap block
750 if (!custom_free)
751 VG_(cli_free)( p );
752
753 // Remove HP_Chunk from malloclist, destroy
754 remove_HP_Chunk(hc, remove_handle);
755
756 hp_census(); // do a census!
757
758 VG_(free)( hc );
759 VGP_POPCC(VgpCliMalloc);
760}
761
762
763void* SK_(malloc) ( Int n )
764{
765 return new_block( n, VG_(clo_alignment), /*is_zeroed*/False );
766}
767
768void* SK_(__builtin_new) ( Int n )
769{
770 return new_block( n, VG_(clo_alignment), /*is_zeroed*/False );
771}
772
773void* SK_(__builtin_vec_new) ( Int n )
774{
775 return new_block( n, VG_(clo_alignment), /*is_zeroed*/False );
776}
777
778void* SK_(calloc) ( Int m, Int size )
779{
780 return new_block( m*size, VG_(clo_alignment), /*is_zeroed*/True );
781}
782
783void SK_(free) ( void* p )
784{
785 die_block( p, /*custom_free*/False );
786}
787
788void SK_(__builtin_delete) ( void* p )
789{
790 die_block( p, /*custom_free*/False);
791}
792
793void SK_(__builtin_vec_delete) ( void* p )
794{
795 die_block( p, /*custom_free*/False );
796}
797
798void* SK_(realloc) ( void* p_old, Int new_size )
799{
800 HP_Chunk* hc;
801 HP_Chunk** remove_handle;
802 Int i;
803 void* p_new;
804 UInt old_size;
805 XPt *old_where, *new_where;
806
807 VGP_PUSHCC(VgpCliMalloc);
808
809 // First try and find the block.
810 hc = get_HP_Chunk ( p_old, &remove_handle );
811 if (hc == NULL) {
812 VGP_POPCC(VgpCliMalloc);
813 return NULL; // must have been a bogus free()
814 }
815
816 sk_assert(hc->data == (Addr)p_old);
817 old_size = hc->size;
818
819 if (new_size <= old_size) {
820 // new size is smaller or same; block not moved
821 p_new = p_old;
822
823 } else {
824 // new size is bigger; make new block, copy shared contents, free old
825 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
826
827 for (i = 0; i < old_size; i++)
828 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
829
830 VG_(cli_free)(p_old);
831 }
832
833 old_where = hc->where;
834 new_where = get_XCon( VG_(get_current_or_recent_tid)(),
835 /*custom_malloc*/False);
836
837 // Update HP_Chunk
838 hc->data = (Addr)p_new;
839 hc->size = new_size;
840 hc->where = new_where;
841
842 // Update XPt curr_space fields
843 if (clo_heap) {
844 if (0 != old_size) update_XCon(old_where, -old_size);
845 if (0 != new_size) update_XCon(new_where, new_size);
846 }
847
848 // If block has moved, have to remove and reinsert in the malloclist
849 // (since the updated 'data' field is the hash lookup key).
850 if (p_new != p_old) {
851 remove_HP_Chunk(hc, remove_handle);
852 add_HP_Chunk(hc);
853 }
854
855 VGP_POPCC(VgpCliMalloc);
856 return p_new;
857}
858
859
860/*------------------------------------------------------------*/
861/*--- Taking a census ---*/
862/*------------------------------------------------------------*/
863
864static Census censi[MAX_N_CENSI];
865static UInt curr_census = 0;
866
867// Must return False so that all stacks are traversed
868static UInt count_stack_size_counter;
869static Bool count_stack_size( Addr stack_min, Addr stack_max )
870{
871 count_stack_size_counter += (stack_max - stack_min);
872 return False;
873}
874
875static UInt get_xtree_size(XPt* xpt, UInt ix)
876{
877 UInt i;
878
879// VG_(printf)("%4d ", xpt->curr_space);
880
881 // If this one has size zero, all the children will be size zero too, so
882 // nothing interesting to record.
883// if (0 != xpt->curr_space || 0 == ix) {
884 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002 || 0 == ix) {
885 ix++;
886
887 // Count all (non-zero) descendent XPts
888 for (i = 0; i < xpt->n_children; i++)
889 ix = get_xtree_size(xpt->children[i], ix);
890 }
891 return ix;
892}
893
894static
895UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
896{
897 UInt i;
898
899 // Snapshot this XPt, if non-zero space, or the first one
900// if (0 != xpt->curr_space || 0 == ix) {
901 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002 || 0 == ix) {
902 xtree_snapshot[ix].xpt = xpt;
903 xtree_snapshot[ix].space = xpt->curr_space;
904 ix++;
905
906 // Snapshot all (non-zero) descendent XPts
907 for (i = 0; i < xpt->n_children; i++)
908 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
909 }
910 return ix;
911}
912
913static UInt ms_interval;
914static UInt do_every_nth_census = 30;
915
916// Weed out half the censi; we choose those that represent the smallest
917// time-spans, because that loses the least information.
918//
919// Algorithm for N censi: We find the census representing the smallest
920// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
921// (It's (N/2)-1 because we never remove the first and last censi.)
922// We have to do this one census at a time, rather than finding the (N/2)-1
923// smallest censi in one hit, because when a census is removed, it's
924// neighbours immediately cover greater timespans. So it's N^2, but N only
925// equals 200, and this is only done every 100 censi, which is not too often.
926static void halve_censi(void)
927{
928 Int i, jp, j, jn, k;
929 Census* min_census;
930
931 n_halvings++;
932 if (VG_(clo_verbosity) > 1)
933 VG_(message)(Vg_UserMsg, "Halving censi...");
934
935 // Sets j to the index of the first not-yet-removed census at or after i
936 #define FIND_CENSUS(i, j) \
937 for (j = i; -1 == censi[j].ms_time; j++) { }
938
939 for (i = 2; i < MAX_N_CENSI; i += 2) {
940 // Find the censi representing the smallest timespan. The timespan
941 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
942 // censi A and B. We don't consider the first and last censi for
943 // removal.
944 Int min_span = 0x7fffffff;
945 Int min_j = 0;
946
947 // Initial triple: (prev, curr, next) == (jp, j, jn)
948 jp = 0;
949 FIND_CENSUS(1, j);
950 FIND_CENSUS(j+1, jn);
951 while (jn < MAX_N_CENSI) {
952 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
953 sk_assert(timespan >= 0);
954 if (timespan < min_span) {
955 min_span = timespan;
956 min_j = j;
957 }
958 // Move on to next triple
959 jp = j;
960 j = jn;
961 FIND_CENSUS(jn+1, jn);
962 }
963 // We've found the least important census, now remove it
964 min_census = & censi[ min_j ];
965 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
966 n_snapshot_frees++;
967 VG_(free)(min_census->xtree_snapshots[k]);
968 min_census->xtree_snapshots[k] = NULL;
969 }
970 min_census->ms_time = -1;
971 }
972
973 // Slide down the remaining censi over the removed ones. The '<=' is
974 // because we are removing on (N/2)-1, rather than N/2.
975 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
976 FIND_CENSUS(j, j);
977 if (i != j) {
978 censi[i] = censi[j];
979 }
980 }
981 curr_census = i;
982
983 // Double intervals
984 ms_interval *= 2;
985 do_every_nth_census *= 2;
986
987 if (VG_(clo_verbosity) > 1)
988 VG_(message)(Vg_UserMsg, "...done");
989}
990
991// Take a census. Census time seems to be insignificant (usually <= 0 ms,
992// almost always <= 1ms) so don't have to worry about subtracting it from
993// running time in any way.
994//
995// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
996// 50ms!
997static void hp_census(void)
998{
999 static UInt ms_prev_census = 0;
1000 static UInt ms_next_census = 0; // zero allows startup census
1001
1002 Int ms_time, ms_time_since_prev;
1003 Int i, K;
1004 Census* census;
1005
1006 VGP_PUSHCC(VgpCensus);
1007
1008 // Only do a census if it's time
1009 ms_time = VG_(read_millisecond_timer)();
1010 ms_time_since_prev = ms_time - ms_prev_census;
1011 if (ms_time < ms_next_census) {
1012 n_fake_censi++;
1013 VGP_POPCC(VgpCensus);
1014 return;
1015 }
1016 n_real_censi++;
1017
1018 census = & censi[curr_census];
1019
1020 census->ms_time = ms_time;
1021
1022 // Heap: snapshot the K most significant XTrees -------------------
1023 if (clo_heap) {
1024 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1025 ? alloc_xpt->n_children
1026 : MAX_SNAPSHOTS); // max out
1027
1028 // Update .spacetime field (approximatively) for all top-XPts.
1029 // We *do not* do it for any non-top-XPTs.
1030 for (i = 0; i < alloc_xpt->n_children; i++) {
1031 XPt* top_XPt = alloc_xpt->children[i];
1032 top_XPt->spacetime += top_XPt->curr_space * ms_time_since_prev;
1033 }
1034 // Sort top-XPts by spacetime2 field.
1035 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
1036 XPt_cmp_spacetime);
1037
1038 VGP_PUSHCC(VgpCensusHeap);
1039
1040 // For each significant top-level XPt, record space info about its
1041 // entire XTree, in a single census entry.
1042 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1043 // snapshot, take similar amounts of time (measured with the
1044 // millesecond counter).
1045 for (i = 0; i < K; i++) {
1046 UInt xtree_size, xtree_size2;
1047// VG_(printf)("%7u ", alloc_xpt->children[i]->spacetime);
1048 // Count how many XPts are in the XTree; make array of that size
1049 // (+1 for zero termination, which calloc() does for us).
1050 VGP_PUSHCC(VgpCensusTreeSize);
1051 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1052 VGP_POPCC(VgpCensusTreeSize);
1053 census->xtree_snapshots[i] =
1054 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
1055 if (VG_(clo_verbosity) > 1)
1056 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1057 (xtree_size+1) * sizeof(XPtSnapshot));
1058
1059 // Take space-snapshot: copy 'curr_space' for every XPt in the
1060 // XTree into the snapshot array, along with pointers to the XPts.
1061 // (Except for ones with curr_space==0, which wouldn't contribute
1062 // to the final spacetime2 calculation anyway; excluding them
1063 // saves a lot of memory and up to 40% time with big --depth valus.
1064 VGP_PUSHCC(VgpCensusSnapshot);
1065 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1066 census->xtree_snapshots[i], 0);
1067 sk_assert(xtree_size == xtree_size2);
1068 VGP_POPCC(VgpCensusSnapshot);
1069 }
1070// VG_(printf)("\n\n");
1071 // Zero-terminate 'xtree_snapshot' array
1072 census->xtree_snapshots[i] = NULL;
1073
1074 VGP_POPCC(VgpCensusHeap);
1075
1076 //VG_(printf)("printed %d censi\n", K);
1077
1078 // Lump the rest into a single "others" entry.
1079 census->others_space = 0;
1080 for (i = K; i < alloc_xpt->n_children; i++) {
1081 census->others_space += alloc_xpt->children[i]->curr_space;
1082 }
1083 }
1084
1085 // Heap admin -------------------------------------------------------
1086 if (clo_heap_admin > 0)
1087 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1088
1089 // Stack(s) ---------------------------------------------------------
1090 if (clo_stacks) {
1091 count_stack_size_counter = sigstacks_space;
1092 // slightly abusing this function
1093 VG_(first_matching_thread_stack)( count_stack_size );
1094 census->stacks_space = count_stack_size_counter;
1095 i++;
1096 }
1097
1098 // Finish, update interval if necessary -----------------------------
1099 curr_census++;
1100 census = NULL; // don't use again now that curr_census changed
1101
1102 // Halve the entries, if our census table is full
1103 if (MAX_N_CENSI == curr_census) {
1104 halve_censi();
1105 }
1106
1107 // Take time for next census from now, rather than when this census
1108 // should have happened. Because, if there's a big gap due to a kernel
1109 // operation, there's no point doing catch-up censi every BB for a while
1110 // -- that would just give N censi at almost the same time.
1111 if (VG_(clo_verbosity) > 1) {
1112 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1113 VG_(read_millisecond_timer)() - ms_time );
1114 }
1115 ms_prev_census = ms_time;
1116 ms_next_census = ms_time + ms_interval;
1117 //ms_next_census += ms_interval;
1118
1119 //VG_(printf)("Next: %d ms\n", ms_next_census);
1120
1121 VGP_POPCC(VgpCensus);
1122}
1123
1124/*------------------------------------------------------------*/
1125/*--- Tracked events ---*/
1126/*------------------------------------------------------------*/
1127
1128static void new_mem_stack_signal(Addr a, UInt len)
1129{
1130 sigstacks_space += len;
1131}
1132
1133static void die_mem_stack_signal(Addr a, UInt len)
1134{
1135 sk_assert(sigstacks_space >= len);
1136 sigstacks_space -= len;
1137}
1138
1139/*------------------------------------------------------------*/
1140/*--- Client Requests ---*/
1141/*------------------------------------------------------------*/
1142
1143Bool SK_(handle_client_request) ( ThreadId tid, UInt* argv, UInt* ret )
1144{
1145 switch (argv[0]) {
1146 case VG_USERREQ__MALLOCLIKE_BLOCK: {
1147 void* p = (void*)argv[1];
1148 UInt sizeB = argv[2];
1149 *ret = 0;
1150 new_block_meta( p, sizeB, /*custom_malloc*/True );
1151 return True;
1152 }
1153 case VG_USERREQ__FREELIKE_BLOCK: {
1154 void* p = (void*)argv[1];
1155 *ret = 0;
1156 die_block( p, /*custom_free*/True );
1157 return True;
1158 }
1159 default:
1160 *ret = 0;
1161 return False;
1162 }
1163}
1164
1165/*------------------------------------------------------------*/
1166/*--- Initialisation ---*/
1167/*------------------------------------------------------------*/
1168
1169// Current directory at startup.
1170static Char* base_dir;
1171
1172UInt VG_(vg_malloc_redzone_szB) = 0;
1173
1174void SK_(pre_clo_init)()
1175{
1176 VG_(details_name) ("Massif");
1177 VG_(details_version) ("0.0.3");
1178 VG_(details_description) ("a space profiler");
1179 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1180 VG_(details_bug_reports_to) ("njn25@cam.ac.uk");
1181
1182 // Needs
1183 VG_(needs_libc_freeres)();
1184 VG_(needs_command_line_options)();
1185 VG_(needs_client_requests) ();
1186
1187 // Events to track
1188 VG_(init_new_mem_stack_signal) ( new_mem_stack_signal );
1189 VG_(init_die_mem_stack_signal) ( die_mem_stack_signal );
1190
1191 // Profiling events
1192 VGP_(register_profile_event)(VgpGetXPt, "get-XPt");
1193 VGP_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1194 VGP_(register_profile_event)(VgpCensus, "census");
1195 VGP_(register_profile_event)(VgpCensusHeap, "census-heap");
1196 VGP_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1197 VGP_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1198 VGP_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1199 VGP_(register_profile_event)(VgpCalcSpacetime2, "calc-spacetime2");
1200 VGP_(register_profile_event)(VgpPrintHp, "print-hp");
1201 VGP_(register_profile_event)(VgpPrintXPts, "print-XPts");
1202
1203 // HP_Chunks
1204 malloc_list = VG_(HT_construct)();
1205
1206 // Dummy node at top of the context structure.
1207 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1208
1209 sk_assert( VG_(getcwd_alloc)(&base_dir) );
1210}
1211
1212void SK_(post_clo_init)(void)
1213{
1214 ms_interval = 1;
1215
1216 // Do an initial sample for t = 0
1217 hp_census();
1218}
1219
1220/*------------------------------------------------------------*/
1221/*--- Instrumentation ---*/
1222/*------------------------------------------------------------*/
1223
1224UCodeBlock* SK_(instrument)(UCodeBlock* cb_in, Addr orig_addr)
1225{
1226 return cb_in;
1227}
1228
1229/*------------------------------------------------------------*/
1230/*--- Spacetime recomputation ---*/
1231/*------------------------------------------------------------*/
1232
1233// Although we've been calculating spacetime along the way, because the
1234// earlier calculations were done at a finer timescale, the .spacetime field
1235// might not agree with what hp2ps sees, because we've thrown away some of
1236// the information. So recompute it at the scale that hp2ps sees, so we can
1237// confidently determine which contexts hp2ps will choose for displaying as
1238// distinct bands. This recomputation only happens to the significant ones
1239// that get printed in the .hp file, so it's cheap.
1240//
1241// The spacetime calculation:
1242// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1243// where
1244// a[N] is the space at census N
1245// d(A,B) is the time interval between censi A and B
1246// and
1247// d(A,B) + d(B,C) == d(A,C)
1248//
1249// Key point: we can calculate the area for a census without knowing the
1250// previous or subsequent censi's space; because any over/underestimates
1251// for this census will be reversed in the next, balancing out. This is
1252// important, as getting the previous/next census entry for a particular
1253// AP is a pain with this data structure, but getting the prev/next
1254// census time is easy.
1255//
1256// Each heap calculation gets added to its context's spacetime2 field.
1257// The ULong* values are all running totals, hence the use of "+=" everywhere.
1258
1259// This does the calculations for a single census.
1260static void calc_spacetime2b(Census* census, UInt d_t1_t2,
1261 ULong* twice_heap_ST,
1262 ULong* twice_heap_admin_ST,
1263 ULong* twice_stack_ST)
1264{
1265 UInt i, j;
1266 XPtSnapshot* xpt_snapshot;
1267
1268 // Heap --------------------------------------------------------
1269 if (clo_heap) {
1270 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
1271 // Compute total heap spacetime2 for the entire XTree using only the
1272 // top-XPt (the first XPt in xtree_snapshot).
1273 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1274
1275 // Increment spacetime2 for every XPt in xtree_snapshot (inc. top one)
1276 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1277 xpt_snapshot = & census->xtree_snapshots[i][j];
1278 xpt_snapshot->xpt->spacetime2 += d_t1_t2 * xpt_snapshot->space;
1279 }
1280 }
1281 *twice_heap_ST += d_t1_t2 * census->others_space;
1282 }
1283
1284 // Heap admin --------------------------------------------------
1285 if (clo_heap_admin > 0)
1286 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1287
1288 // Stack(s) ----------------------------------------------------
1289 if (clo_stacks)
1290 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1291}
1292
1293// This does the calculations for all censi.
1294static void calc_spacetime2(ULong* heap2, ULong* heap_admin2, ULong* stack2)
1295{
1296 UInt i, N = curr_census;
1297
1298 VGP_PUSHCC(VgpCalcSpacetime2);
1299
1300 *heap2 = 0;
1301 *heap_admin2 = 0;
1302 *stack2 = 0;
1303
1304 if (N <= 1)
1305 return;
1306
1307 calc_spacetime2b( &censi[0], censi[1].ms_time - censi[0].ms_time,
1308 heap2, heap_admin2, stack2 );
1309
1310 for (i = 1; i <= N-2; i++) {
1311 calc_spacetime2b( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1312 heap2, heap_admin2, stack2 );
1313 }
1314
1315 calc_spacetime2b( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1316 heap2, heap_admin2, stack2 );
1317 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1318 *heap2 /= 2;
1319 *heap_admin2 /= 2;
1320 *stack2 /= 2;
1321
1322 VGP_POPCC(VgpCalcSpacetime2);
1323}
1324
1325/*------------------------------------------------------------*/
1326/*--- Writing the graph file ---*/
1327/*------------------------------------------------------------*/
1328
1329static Char* make_filename(Char* dir, Char* suffix)
1330{
1331 Char* filename;
1332
1333 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1334 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1335 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1336
1337 return filename;
1338}
1339
1340// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1341static Char* clean_fnname(Char *d, Char* s)
1342{
1343 Char* dorig = d;
1344 while (*s) {
1345 if (' ' == *s) { *d = '%'; }
1346 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1347 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1348 else { *d = *s; };
1349 s++;
1350 d++;
1351 }
1352 *d = '\0';
1353 return dorig;
1354}
1355
1356static void file_err ( Char* file )
1357{
1358 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1359 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1360}
1361
1362/* Format, by example:
1363
1364 JOB "a.out -p"
1365 DATE "Fri Apr 17 11:43:45 1992"
1366 SAMPLE_UNIT "seconds"
1367 VALUE_UNIT "bytes"
1368 BEGIN_SAMPLE 0.00
1369 SYSTEM 24
1370 END_SAMPLE 0.00
1371 BEGIN_SAMPLE 1.00
1372 elim 180
1373 insert 24
1374 intersect 12
1375 disin 60
1376 main 12
1377 reduce 20
1378 SYSTEM 12
1379 END_SAMPLE 1.00
1380 MARK 1.50
1381 MARK 1.75
1382 MARK 1.80
1383 BEGIN_SAMPLE 2.00
1384 elim 192
1385 insert 24
1386 intersect 12
1387 disin 84
1388 main 12
1389 SYSTEM 24
1390 END_SAMPLE 2.00
1391 BEGIN_SAMPLE 2.82
1392 END_SAMPLE 2.82
1393 */
1394static void write_hp_file(void)
1395{
1396 Int i, j;
1397 Int fd, res;
1398 Char *hp_file, *ps_file, *aux_file;
1399 Char* cmdfmt;
1400 Char* cmdbuf;
1401 Int cmdlen;
1402
1403 VGP_PUSHCC(VgpPrintHp);
1404
1405 // Open file
1406 hp_file = make_filename( base_dir, ".hp" );
1407 ps_file = make_filename( base_dir, ".ps" );
1408 aux_file = make_filename( base_dir, ".aux" );
1409 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1410 VKI_S_IRUSR|VKI_S_IWUSR);
1411 if (fd < 0) {
1412 file_err( hp_file );
1413 VGP_POPCC(VgpPrintHp);
1414 return;
1415 }
1416
1417 // File header, including command line
1418 SPRINTF(buf, "JOB \"");
1419 for (i = 0; i < VG_(client_argc); i++)
1420 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1421 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1422 "DATE \"\"\n"
1423 "SAMPLE_UNIT \"ms\"\n"
1424 "VALUE_UNIT \"bytes\"\n", ms_interval);
1425
1426 // Censi
1427 for (i = 0; i < curr_census; i++) {
1428 Census* census = & censi[i];
1429
1430 // Census start
1431 SPRINTF(buf, "MARK %d.0\n"
1432 "BEGIN_SAMPLE %d.0\n",
1433 census->ms_time, census->ms_time);
1434
1435 // Heap -----------------------------------------------------------
1436 if (clo_heap) {
1437 // Print all the significant XPts from that census
1438 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1439 // Grab the jth top-XPt
1440 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
1441 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->eip, buf2, 16)) {
1442 VG_(sprintf)(buf2, "???");
1443 }
1444 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->eip,
1445 clean_fnname(buf3, buf2), xtree_snapshot->space);
1446 }
1447
1448 // Remaining heap block alloc points, combined
1449 if (census->others_space > 0)
1450 SPRINTF(buf, "other %d\n", census->others_space);
1451 }
1452
1453 // Heap admin -----------------------------------------------------
1454 if (clo_heap_admin > 0 && census->heap_admin_space)
1455 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1456
1457 // Stack(s) -------------------------------------------------------
1458 if (clo_stacks)
1459 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1460
1461 // Census end
1462 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1463 }
1464
1465 // Close file
1466 sk_assert(fd >= 0);
1467 VG_(close)(fd);
1468
1469 // Attempt to convert file using hp2ps
1470 cmdfmt = "%s/hp2ps -c -t1 %s";
1471 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1472 + VG_(strlen)(cmdfmt);
1473 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1474 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1475 res = VG_(system)(cmdbuf);
1476 VG_(free)(cmdbuf);
1477 if (res != 0) {
1478 VG_(message)(Vg_UserMsg,
1479 "Conversion to PostScript failed. Try converting manually.");
1480 } else {
1481 // remove the .hp and .aux file
1482 VG_(unlink)(hp_file);
1483 VG_(unlink)(aux_file);
1484 }
1485
1486 VG_(free)(hp_file);
1487 VG_(free)(ps_file);
1488 VG_(free)(aux_file);
1489
1490 VGP_POPCC(VgpPrintHp);
1491}
1492
1493/*------------------------------------------------------------*/
1494/*--- Writing the XPt text/HTML file ---*/
1495/*------------------------------------------------------------*/
1496
1497static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1498{
1499 int i, len, space;
1500
1501 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1502 len = VG_(strlen)(xbuf);
1503 space = field_width - len;
1504 if (space < 0) space = 0; /* Allow for v. small field_width */
1505 i = len;
1506
1507 /* Right justify in field */
1508 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1509 for (i = 0; i < space; i++) xbuf[i] = ' ';
1510}
1511
1512// Nb: uses a static buffer, each call trashes the last string returned.
1513static Char* make_perc(ULong spacetime, ULong total_spacetime)
1514{
1515 static Char mbuf[32];
1516
1517 UInt p = 10;
1518 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1519 return mbuf;
1520}
1521
1522// Nb: passed in XPt is a lower-level XPt; %eips are grabbed from
1523// bottom-to-top of XCon, and then printed in the reverse order.
1524static UInt pp_XCon(Int fd, XPt* xpt)
1525{
1526 Addr rev_eips[clo_depth+1];
1527 Int i = 0;
1528 Int n = 0;
1529 Bool is_HTML = ( XHTML == clo_format );
1530 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1531 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1532
1533 sk_assert(NULL != xpt);
1534
1535 while (True) {
1536 rev_eips[i] = xpt->eip;
1537 n++;
1538 if (alloc_xpt == xpt->parent) break;
1539 i++;
1540 xpt = xpt->parent;
1541 }
1542
1543 for (i = n-1; i >= 0; i--) {
1544 // -1 means point to calling line
1545 VG_(describe_eip)(rev_eips[i]-1, buf2, BUF_LEN);
1546 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1547 }
1548
1549 return n;
1550}
1551
1552// Important point: for HTML, each XPt must be identified uniquely for the
1553// HTML links to all match up correctly. Using xpt->eip is not
1554// sufficient, because function pointers mean that you can call more than
1555// one other function from a single code location. So instead we use the
1556// address of the xpt struct itself, which is guaranteed to be unique.
1557
1558static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1559 ULong total_spacetime)
1560{
1561 UInt i;
1562 XPt *xpt, *child;
1563 UInt L = 0;
1564 UInt c1 = 1;
1565 UInt c2 = 0;
1566 ULong sum = 0;
1567 UInt n;
1568 Char *eip_desc, *perc;
1569 Bool is_HTML = ( XHTML == clo_format );
1570 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1571 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1572 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1573 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1574 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1575 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1576 Char* end_hr = ( is_HTML ? "<hr>" :
1577 "=================================" );
1578 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1579
1580 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1581
1582 while (NULL != (xpt = (XPt*)dequeue(q))) {
1583 // Check that non-top-level XPts have a zero .spacetime field.
1584 if (xpt->parent != alloc_xpt) sk_assert( 0 == xpt->spacetime );
1585
1586 // Check that the sum of all children .spacetime2s equals parent's
1587 // (unless alloc_xpt, when it should == 0).
1588 if (alloc_xpt == xpt) {
1589 sk_assert(0 == xpt->spacetime2);
1590 } else {
1591 sum = 0;
1592 for (i = 0; i < xpt->n_children; i++) {
1593 sum += xpt->children[i]->spacetime2;
1594 }
1595 //sk_assert(sum == xpt->spacetime2);
1596 // It's possible that not all the children were included in the
1597 // spacetime2 calculations. Hopefully almost all of them were, and
1598 // all the important ones.
1599// sk_assert(sum <= xpt->spacetime2);
1600// sk_assert(sum * 1.05 > xpt->spacetime2 );
1601// if (sum != xpt->spacetime2) {
1602// VG_(printf)("%ld, %ld\n", sum, xpt->spacetime2);
1603// }
1604 }
1605
1606 if (xpt == alloc_xpt) {
1607 SPRINTF(buf, "Heap allocation functions accounted for "
1608 "%s of measured spacetime%s\n",
1609 make_perc(heap_spacetime, total_spacetime), maybe_br);
1610 } else {
1611 // Remember: spacetime2 is space.time *doubled*
1612 perc = make_perc(xpt->spacetime2 / 2, total_spacetime);
1613 if (is_HTML) {
1614 SPRINTF(buf, "<a name=\"b%x\"></a>"
1615 "Context accounted for "
1616 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1617 xpt, xpt, perc);
1618 } else {
1619 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1620 perc);
1621 }
1622 n = pp_XCon(fd, xpt);
1623 sk_assert(n == L);
1624 }
1625
1626 // Sort children by spacetime2
1627 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
1628 XPt_cmp_spacetime2);
1629
1630 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1631 for (i = 0; i < xpt->n_children; i++) {
1632 child = xpt->children[i];
1633
1634 // Stop when <1% of total spacetime
1635 if (child->spacetime2 * 1000 / (total_spacetime * 2) < 5) {
1636 UInt n_insig = xpt->n_children - i;
1637 Char* s = ( n_insig == 1 ? "" : "s" );
1638 Char* and = ( 0 == i ? "" : "and " );
1639 Char* other = ( 0 == i ? "" : "other " );
1640 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1641 maybe_li, and, n_insig, other, s, maybe_fli);
1642 break;
1643 }
1644
1645 // Remember: spacetime2 is space.time *doubled*
1646 perc = make_perc(child->spacetime2 / 2, total_spacetime);
1647 eip_desc = VG_(describe_eip)(child->eip-1, buf2, BUF_LEN);
1648 if (is_HTML) {
1649 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1650
1651 if (child->n_children > 0) {
1652 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1653 } else {
1654 SPRINTF(buf, "%s", perc);
1655 }
1656 SPRINTF(buf, ": %s\n", eip_desc);
1657 } else {
1658 SPRINTF(buf, " %6s: %s\n\n", perc, eip_desc);
1659 }
1660
1661 if (child->n_children > 0) {
1662 enqueue(q, (void*)child);
1663 c2++;
1664 }
1665 }
1666 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1667 c1--;
1668
1669 // Putting markers between levels of the structure:
1670 // c1 tracks how many to go on this level, c2 tracks how many we've
1671 // queued up for the next level while finishing off this level.
1672 // When c1 gets to zero, we've changed levels, so print a marker,
1673 // move c2 into c1, and zero c2.
1674 if (0 == c1) {
1675 L++;
1676 c1 = c2;
1677 c2 = 0;
1678 if (! is_empty_queue(q) ) { // avoid empty one at end
1679 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1680 }
1681 } else {
1682 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1683 }
1684 }
1685 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1686 "%s value for more.\n", end_hr, depth);
1687}
1688
1689static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1690 ULong total_spacetime)
1691{
1692 Queue* q = construct_queue(100);
1693 enqueue(q, xpt);
1694 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1695 destruct_queue(q);
1696}
1697
1698static void
1699write_text_file(ULong total_ST, ULong heap_ST)
1700{
1701 Int fd, i;
1702 Char* text_file;
1703 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1704
1705 VGP_PUSHCC(VgpPrintXPts);
1706
1707 // Open file
1708 text_file = make_filename( base_dir,
1709 ( XText == clo_format ? ".txt" : ".html" ) );
1710
1711 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1712 VKI_S_IRUSR|VKI_S_IWUSR);
1713 if (fd < 0) {
1714 file_err( text_file );
1715 VGP_POPCC(VgpPrintXPts);
1716 return;
1717 }
1718
1719 // Header
1720 if (XHTML == clo_format) {
1721 SPRINTF(buf, "<html>\n"
1722 "<head>\n"
1723 "<title>%s</title>\n"
1724 "</head>\n"
1725 "<body>\n",
1726 text_file);
1727 }
1728
1729 // Command line
1730 SPRINTF(buf, "Command: ");
1731 for (i = 0; i < VG_(client_argc); i++)
1732 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1733 SPRINTF(buf, "\n%s\n", maybe_p);
1734
1735 if (clo_heap)
1736 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1737
1738 sk_assert(fd >= 0);
1739 VG_(close)(fd);
1740
1741 VGP_POPCC(VgpPrintXPts);
1742}
1743
1744/*------------------------------------------------------------*/
1745/*--- Finalisation ---*/
1746/*------------------------------------------------------------*/
1747
1748static void
1749print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1750 ULong stack_ST)
1751{
1752 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1753
1754 // Heap --------------------------------------------------------------
1755 if (clo_heap)
1756 VG_(message)(Vg_UserMsg, "heap: %s",
1757 make_perc(heap_ST, total_ST) );
1758
1759 // Heap admin --------------------------------------------------------
1760 if (clo_heap_admin)
1761 VG_(message)(Vg_UserMsg, "heap admin: %s",
1762 make_perc(heap_admin_ST, total_ST));
1763
1764 sk_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
1765
1766 // Stack(s) ----------------------------------------------------------
1767 if (clo_stacks)
1768 VG_(message)(Vg_UserMsg, "stack(s): %s",
1769 make_perc(stack_ST, total_ST));
1770
1771 if (VG_(clo_verbosity) > 1) {
1772 sk_assert(n_xpts > 0); // always have alloc_xpt
1773 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1774 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1775 n_zero_allocs * 100 / n_allocs );
1776 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1777 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1778 n_xpts*sizeof(XPt));
1779 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1780 n_bot_xpts * 100 / n_xpts);
1781 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1782 alloc_xpt->n_children * 100 / n_xpts);
1783 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1784 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1785 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1786 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1787 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1788 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1789 }
1790}
1791
1792void SK_(fini)(Int exit_status)
1793{
1794 ULong total_ST = 0;
1795 ULong heap_ST = 0;
1796 ULong heap_admin_ST = 0;
1797 ULong stack_ST = 0;
1798
1799 // Do a final (empty) sample to show program's end
1800 hp_census();
1801
1802 // Redo spacetimes of significant contexts to match the .hp file.
1803 calc_spacetime2(&heap_ST, &heap_admin_ST, &stack_ST);
1804 total_ST = heap_ST + heap_admin_ST + stack_ST;
1805 write_hp_file ( );
1806 write_text_file( total_ST, heap_ST );
1807 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1808}
1809
1810VG_DETERMINE_INTERFACE_VERSION(SK_(pre_clo_init), 0)
1811
1812/*--------------------------------------------------------------------*/
1813/*--- end ms_main.c ---*/
1814/*--------------------------------------------------------------------*/
1815