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