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