blob: 74a0e4d4e0ccc5ce06a1ef9e3bd27f955b70d8d9 [file] [log] [blame]
nethercotec9f36922004-02-14 16:40:02 +00001
2/*--------------------------------------------------------------------*/
nethercote996901a2004-08-03 13:29:09 +00003/*--- Massif: a heap profiling tool. ms_main.c ---*/
nethercotec9f36922004-02-14 16:40:02 +00004/*--------------------------------------------------------------------*/
5
6/*
nethercote996901a2004-08-03 13:29:09 +00007 This file is part of Massif, a Valgrind tool for profiling memory
nethercotec9f36922004-02-14 16:40:02 +00008 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__
nethercote57e36b32004-07-10 14:56:28 +0000667void* new_block ( void* p, Int size, UInt align, Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000668{
669 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000670 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000671 if (size < 0) return NULL;
672
673 VGP_PUSHCC(VgpCliMalloc);
674
675 // Update statistics
676 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000677 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000678
nethercote57e36b32004-07-10 14:56:28 +0000679 // Allocate and zero if necessary
680 if (!p) {
681 p = VG_(cli_malloc)( align, size );
682 if (!p) {
683 VGP_POPCC(VgpCliMalloc);
684 return NULL;
685 }
686 if (is_zeroed) VG_(memset)(p, 0, size);
687 }
688
689 // Make new HP_Chunk node, add to malloclist
690 hc = VG_(malloc)(sizeof(HP_Chunk));
691 hc->size = size;
692 hc->data = (Addr)p;
693 hc->where = NULL; // paranoia
694 if (clo_heap) {
695 hc->where = get_XCon( VG_(get_current_or_recent_tid)(), custom_alloc );
696 if (0 != size)
697 update_XCon(hc->where, size);
698 }
699 add_HP_Chunk( hc );
700
701 // do a census!
702 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000703
704 VGP_POPCC(VgpCliMalloc);
705 return p;
706}
707
708static __inline__
709void die_block ( void* p, Bool custom_free )
710{
nethercote57e36b32004-07-10 14:56:28 +0000711 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000712
713 VGP_PUSHCC(VgpCliMalloc);
714
715 // Update statistics
716 n_frees++;
717
nethercote57e36b32004-07-10 14:56:28 +0000718 // Remove HP_Chunk from malloclist
719 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000720 if (hc == NULL)
721 return; // must have been a bogus free(), or p==NULL
nethercotec9f36922004-02-14 16:40:02 +0000722 sk_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000723 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000724
725 if (clo_heap && hc->size != 0)
726 update_XCon(hc->where, -hc->size);
727
nethercote57e36b32004-07-10 14:56:28 +0000728 VG_(free)( hc );
729
730 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000731 if (!custom_free)
732 VG_(cli_free)( p );
733
nethercote57e36b32004-07-10 14:56:28 +0000734 // do a census!
735 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000736
nethercotec9f36922004-02-14 16:40:02 +0000737 VGP_POPCC(VgpCliMalloc);
738}
739
740
741void* SK_(malloc) ( Int n )
742{
nethercote57e36b32004-07-10 14:56:28 +0000743 return new_block( NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000744}
745
746void* SK_(__builtin_new) ( Int n )
747{
nethercote57e36b32004-07-10 14:56:28 +0000748 return new_block( NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000749}
750
751void* SK_(__builtin_vec_new) ( Int n )
752{
nethercote57e36b32004-07-10 14:56:28 +0000753 return new_block( NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000754}
755
756void* SK_(calloc) ( Int m, Int size )
757{
nethercote57e36b32004-07-10 14:56:28 +0000758 return new_block( NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000759}
760
fitzhardinge51f3ff12004-03-04 22:42:03 +0000761void *SK_(memalign)( Int align, Int n )
762{
nethercote57e36b32004-07-10 14:56:28 +0000763 return new_block( NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000764}
765
nethercotec9f36922004-02-14 16:40:02 +0000766void SK_(free) ( void* p )
767{
768 die_block( p, /*custom_free*/False );
769}
770
771void SK_(__builtin_delete) ( void* p )
772{
773 die_block( p, /*custom_free*/False);
774}
775
776void SK_(__builtin_vec_delete) ( void* p )
777{
778 die_block( p, /*custom_free*/False );
779}
780
781void* SK_(realloc) ( void* p_old, Int new_size )
782{
783 HP_Chunk* hc;
784 HP_Chunk** remove_handle;
785 Int i;
786 void* p_new;
787 UInt old_size;
788 XPt *old_where, *new_where;
789
790 VGP_PUSHCC(VgpCliMalloc);
791
792 // First try and find the block.
793 hc = get_HP_Chunk ( p_old, &remove_handle );
794 if (hc == NULL) {
795 VGP_POPCC(VgpCliMalloc);
796 return NULL; // must have been a bogus free()
797 }
798
799 sk_assert(hc->data == (Addr)p_old);
800 old_size = hc->size;
801
802 if (new_size <= old_size) {
803 // new size is smaller or same; block not moved
804 p_new = p_old;
805
806 } else {
807 // new size is bigger; make new block, copy shared contents, free old
808 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
809
810 for (i = 0; i < old_size; i++)
811 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
812
813 VG_(cli_free)(p_old);
814 }
815
816 old_where = hc->where;
817 new_where = get_XCon( VG_(get_current_or_recent_tid)(),
818 /*custom_malloc*/False);
819
820 // Update HP_Chunk
821 hc->data = (Addr)p_new;
822 hc->size = new_size;
823 hc->where = new_where;
824
825 // Update XPt curr_space fields
826 if (clo_heap) {
827 if (0 != old_size) update_XCon(old_where, -old_size);
828 if (0 != new_size) update_XCon(new_where, new_size);
829 }
830
831 // If block has moved, have to remove and reinsert in the malloclist
832 // (since the updated 'data' field is the hash lookup key).
833 if (p_new != p_old) {
834 remove_HP_Chunk(hc, remove_handle);
835 add_HP_Chunk(hc);
836 }
837
838 VGP_POPCC(VgpCliMalloc);
839 return p_new;
840}
841
842
843/*------------------------------------------------------------*/
844/*--- Taking a census ---*/
845/*------------------------------------------------------------*/
846
847static Census censi[MAX_N_CENSI];
848static UInt curr_census = 0;
849
850// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000851static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000852{
thughes4ad52d02004-06-27 17:37:21 +0000853 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000854 return False;
855}
856
857static UInt get_xtree_size(XPt* xpt, UInt ix)
858{
859 UInt i;
860
861// VG_(printf)("%4d ", xpt->curr_space);
862
863 // If this one has size zero, all the children will be size zero too, so
864 // nothing interesting to record.
865// if (0 != xpt->curr_space || 0 == ix) {
866 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002 || 0 == ix) {
867 ix++;
868
869 // Count all (non-zero) descendent XPts
870 for (i = 0; i < xpt->n_children; i++)
871 ix = get_xtree_size(xpt->children[i], ix);
872 }
873 return ix;
874}
875
876static
877UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
878{
879 UInt i;
880
881 // Snapshot this XPt, if non-zero space, or the first one
882// if (0 != xpt->curr_space || 0 == ix) {
883 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002 || 0 == ix) {
884 xtree_snapshot[ix].xpt = xpt;
885 xtree_snapshot[ix].space = xpt->curr_space;
886 ix++;
887
888 // Snapshot all (non-zero) descendent XPts
889 for (i = 0; i < xpt->n_children; i++)
890 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
891 }
892 return ix;
893}
894
895static UInt ms_interval;
896static UInt do_every_nth_census = 30;
897
898// Weed out half the censi; we choose those that represent the smallest
899// time-spans, because that loses the least information.
900//
901// Algorithm for N censi: We find the census representing the smallest
902// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
903// (It's (N/2)-1 because we never remove the first and last censi.)
904// We have to do this one census at a time, rather than finding the (N/2)-1
905// smallest censi in one hit, because when a census is removed, it's
906// neighbours immediately cover greater timespans. So it's N^2, but N only
907// equals 200, and this is only done every 100 censi, which is not too often.
908static void halve_censi(void)
909{
910 Int i, jp, j, jn, k;
911 Census* min_census;
912
913 n_halvings++;
914 if (VG_(clo_verbosity) > 1)
915 VG_(message)(Vg_UserMsg, "Halving censi...");
916
917 // Sets j to the index of the first not-yet-removed census at or after i
918 #define FIND_CENSUS(i, j) \
919 for (j = i; -1 == censi[j].ms_time; j++) { }
920
921 for (i = 2; i < MAX_N_CENSI; i += 2) {
922 // Find the censi representing the smallest timespan. The timespan
923 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
924 // censi A and B. We don't consider the first and last censi for
925 // removal.
926 Int min_span = 0x7fffffff;
927 Int min_j = 0;
928
929 // Initial triple: (prev, curr, next) == (jp, j, jn)
930 jp = 0;
931 FIND_CENSUS(1, j);
932 FIND_CENSUS(j+1, jn);
933 while (jn < MAX_N_CENSI) {
934 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
935 sk_assert(timespan >= 0);
936 if (timespan < min_span) {
937 min_span = timespan;
938 min_j = j;
939 }
940 // Move on to next triple
941 jp = j;
942 j = jn;
943 FIND_CENSUS(jn+1, jn);
944 }
945 // We've found the least important census, now remove it
946 min_census = & censi[ min_j ];
947 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
948 n_snapshot_frees++;
949 VG_(free)(min_census->xtree_snapshots[k]);
950 min_census->xtree_snapshots[k] = NULL;
951 }
952 min_census->ms_time = -1;
953 }
954
955 // Slide down the remaining censi over the removed ones. The '<=' is
956 // because we are removing on (N/2)-1, rather than N/2.
957 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
958 FIND_CENSUS(j, j);
959 if (i != j) {
960 censi[i] = censi[j];
961 }
962 }
963 curr_census = i;
964
965 // Double intervals
966 ms_interval *= 2;
967 do_every_nth_census *= 2;
968
969 if (VG_(clo_verbosity) > 1)
970 VG_(message)(Vg_UserMsg, "...done");
971}
972
973// Take a census. Census time seems to be insignificant (usually <= 0 ms,
974// almost always <= 1ms) so don't have to worry about subtracting it from
975// running time in any way.
976//
977// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
978// 50ms!
979static void hp_census(void)
980{
981 static UInt ms_prev_census = 0;
982 static UInt ms_next_census = 0; // zero allows startup census
983
984 Int ms_time, ms_time_since_prev;
985 Int i, K;
986 Census* census;
987
988 VGP_PUSHCC(VgpCensus);
989
990 // Only do a census if it's time
991 ms_time = VG_(read_millisecond_timer)();
992 ms_time_since_prev = ms_time - ms_prev_census;
993 if (ms_time < ms_next_census) {
994 n_fake_censi++;
995 VGP_POPCC(VgpCensus);
996 return;
997 }
998 n_real_censi++;
999
1000 census = & censi[curr_census];
1001
1002 census->ms_time = ms_time;
1003
1004 // Heap: snapshot the K most significant XTrees -------------------
1005 if (clo_heap) {
1006 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1007 ? alloc_xpt->n_children
1008 : MAX_SNAPSHOTS); // max out
1009
1010 // Update .spacetime field (approximatively) for all top-XPts.
1011 // We *do not* do it for any non-top-XPTs.
1012 for (i = 0; i < alloc_xpt->n_children; i++) {
1013 XPt* top_XPt = alloc_xpt->children[i];
1014 top_XPt->spacetime += top_XPt->curr_space * ms_time_since_prev;
1015 }
1016 // Sort top-XPts by spacetime2 field.
1017 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
1018 XPt_cmp_spacetime);
1019
1020 VGP_PUSHCC(VgpCensusHeap);
1021
1022 // For each significant top-level XPt, record space info about its
1023 // entire XTree, in a single census entry.
1024 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1025 // snapshot, take similar amounts of time (measured with the
1026 // millesecond counter).
1027 for (i = 0; i < K; i++) {
1028 UInt xtree_size, xtree_size2;
1029// VG_(printf)("%7u ", alloc_xpt->children[i]->spacetime);
1030 // Count how many XPts are in the XTree; make array of that size
1031 // (+1 for zero termination, which calloc() does for us).
1032 VGP_PUSHCC(VgpCensusTreeSize);
1033 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1034 VGP_POPCC(VgpCensusTreeSize);
1035 census->xtree_snapshots[i] =
1036 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001037 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001038 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1039 (xtree_size+1) * sizeof(XPtSnapshot));
1040
1041 // Take space-snapshot: copy 'curr_space' for every XPt in the
1042 // XTree into the snapshot array, along with pointers to the XPts.
1043 // (Except for ones with curr_space==0, which wouldn't contribute
1044 // to the final spacetime2 calculation anyway; excluding them
1045 // saves a lot of memory and up to 40% time with big --depth valus.
1046 VGP_PUSHCC(VgpCensusSnapshot);
1047 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1048 census->xtree_snapshots[i], 0);
1049 sk_assert(xtree_size == xtree_size2);
1050 VGP_POPCC(VgpCensusSnapshot);
1051 }
1052// VG_(printf)("\n\n");
1053 // Zero-terminate 'xtree_snapshot' array
1054 census->xtree_snapshots[i] = NULL;
1055
1056 VGP_POPCC(VgpCensusHeap);
1057
1058 //VG_(printf)("printed %d censi\n", K);
1059
1060 // Lump the rest into a single "others" entry.
1061 census->others_space = 0;
1062 for (i = K; i < alloc_xpt->n_children; i++) {
1063 census->others_space += alloc_xpt->children[i]->curr_space;
1064 }
1065 }
1066
1067 // Heap admin -------------------------------------------------------
1068 if (clo_heap_admin > 0)
1069 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1070
1071 // Stack(s) ---------------------------------------------------------
1072 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001073 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001074 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001075 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001076 i++;
1077 }
1078
1079 // Finish, update interval if necessary -----------------------------
1080 curr_census++;
1081 census = NULL; // don't use again now that curr_census changed
1082
1083 // Halve the entries, if our census table is full
1084 if (MAX_N_CENSI == curr_census) {
1085 halve_censi();
1086 }
1087
1088 // Take time for next census from now, rather than when this census
1089 // should have happened. Because, if there's a big gap due to a kernel
1090 // operation, there's no point doing catch-up censi every BB for a while
1091 // -- that would just give N censi at almost the same time.
1092 if (VG_(clo_verbosity) > 1) {
1093 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1094 VG_(read_millisecond_timer)() - ms_time );
1095 }
1096 ms_prev_census = ms_time;
1097 ms_next_census = ms_time + ms_interval;
1098 //ms_next_census += ms_interval;
1099
1100 //VG_(printf)("Next: %d ms\n", ms_next_census);
1101
1102 VGP_POPCC(VgpCensus);
1103}
1104
1105/*------------------------------------------------------------*/
1106/*--- Tracked events ---*/
1107/*------------------------------------------------------------*/
1108
1109static void new_mem_stack_signal(Addr a, UInt len)
1110{
1111 sigstacks_space += len;
1112}
1113
1114static void die_mem_stack_signal(Addr a, UInt len)
1115{
1116 sk_assert(sigstacks_space >= len);
1117 sigstacks_space -= len;
1118}
1119
1120/*------------------------------------------------------------*/
1121/*--- Client Requests ---*/
1122/*------------------------------------------------------------*/
1123
1124Bool SK_(handle_client_request) ( ThreadId tid, UInt* argv, UInt* ret )
1125{
1126 switch (argv[0]) {
1127 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001128 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001129 void* p = (void*)argv[1];
1130 UInt sizeB = argv[2];
1131 *ret = 0;
nethercote57e36b32004-07-10 14:56:28 +00001132 res = new_block( p, sizeB, /*align -- ignored*/0, /*is_zeroed*/False );
1133 sk_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001134 return True;
1135 }
1136 case VG_USERREQ__FREELIKE_BLOCK: {
1137 void* p = (void*)argv[1];
1138 *ret = 0;
1139 die_block( p, /*custom_free*/True );
1140 return True;
1141 }
1142 default:
1143 *ret = 0;
1144 return False;
1145 }
1146}
1147
1148/*------------------------------------------------------------*/
1149/*--- Initialisation ---*/
1150/*------------------------------------------------------------*/
1151
1152// Current directory at startup.
1153static Char* base_dir;
1154
1155UInt VG_(vg_malloc_redzone_szB) = 0;
1156
1157void SK_(pre_clo_init)()
1158{
1159 VG_(details_name) ("Massif");
nethercote29b02612004-03-16 19:41:14 +00001160 VG_(details_version) (NULL);
nethercotec9f36922004-02-14 16:40:02 +00001161 VG_(details_description) ("a space profiler");
1162 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
nethercote27645c72004-02-23 15:33:33 +00001163 VG_(details_bug_reports_to) (VG_BUGS_TO);
nethercotec9f36922004-02-14 16:40:02 +00001164
1165 // Needs
1166 VG_(needs_libc_freeres)();
1167 VG_(needs_command_line_options)();
1168 VG_(needs_client_requests) ();
1169
1170 // Events to track
1171 VG_(init_new_mem_stack_signal) ( new_mem_stack_signal );
1172 VG_(init_die_mem_stack_signal) ( die_mem_stack_signal );
1173
1174 // Profiling events
1175 VGP_(register_profile_event)(VgpGetXPt, "get-XPt");
1176 VGP_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1177 VGP_(register_profile_event)(VgpCensus, "census");
1178 VGP_(register_profile_event)(VgpCensusHeap, "census-heap");
1179 VGP_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1180 VGP_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1181 VGP_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1182 VGP_(register_profile_event)(VgpCalcSpacetime2, "calc-spacetime2");
1183 VGP_(register_profile_event)(VgpPrintHp, "print-hp");
1184 VGP_(register_profile_event)(VgpPrintXPts, "print-XPts");
1185
1186 // HP_Chunks
1187 malloc_list = VG_(HT_construct)();
1188
1189 // Dummy node at top of the context structure.
1190 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1191
1192 sk_assert( VG_(getcwd_alloc)(&base_dir) );
1193}
1194
1195void SK_(post_clo_init)(void)
1196{
1197 ms_interval = 1;
1198
1199 // Do an initial sample for t = 0
1200 hp_census();
1201}
1202
1203/*------------------------------------------------------------*/
1204/*--- Instrumentation ---*/
1205/*------------------------------------------------------------*/
1206
1207UCodeBlock* SK_(instrument)(UCodeBlock* cb_in, Addr orig_addr)
1208{
1209 return cb_in;
1210}
1211
1212/*------------------------------------------------------------*/
1213/*--- Spacetime recomputation ---*/
1214/*------------------------------------------------------------*/
1215
1216// Although we've been calculating spacetime along the way, because the
1217// earlier calculations were done at a finer timescale, the .spacetime field
1218// might not agree with what hp2ps sees, because we've thrown away some of
1219// the information. So recompute it at the scale that hp2ps sees, so we can
1220// confidently determine which contexts hp2ps will choose for displaying as
1221// distinct bands. This recomputation only happens to the significant ones
1222// that get printed in the .hp file, so it's cheap.
1223//
1224// The spacetime calculation:
1225// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1226// where
1227// a[N] is the space at census N
1228// d(A,B) is the time interval between censi A and B
1229// and
1230// d(A,B) + d(B,C) == d(A,C)
1231//
1232// Key point: we can calculate the area for a census without knowing the
1233// previous or subsequent censi's space; because any over/underestimates
1234// for this census will be reversed in the next, balancing out. This is
1235// important, as getting the previous/next census entry for a particular
1236// AP is a pain with this data structure, but getting the prev/next
1237// census time is easy.
1238//
1239// Each heap calculation gets added to its context's spacetime2 field.
1240// The ULong* values are all running totals, hence the use of "+=" everywhere.
1241
1242// This does the calculations for a single census.
1243static void calc_spacetime2b(Census* census, UInt d_t1_t2,
1244 ULong* twice_heap_ST,
1245 ULong* twice_heap_admin_ST,
1246 ULong* twice_stack_ST)
1247{
1248 UInt i, j;
1249 XPtSnapshot* xpt_snapshot;
1250
1251 // Heap --------------------------------------------------------
1252 if (clo_heap) {
1253 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
1254 // Compute total heap spacetime2 for the entire XTree using only the
1255 // top-XPt (the first XPt in xtree_snapshot).
1256 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1257
1258 // Increment spacetime2 for every XPt in xtree_snapshot (inc. top one)
1259 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1260 xpt_snapshot = & census->xtree_snapshots[i][j];
1261 xpt_snapshot->xpt->spacetime2 += d_t1_t2 * xpt_snapshot->space;
1262 }
1263 }
1264 *twice_heap_ST += d_t1_t2 * census->others_space;
1265 }
1266
1267 // Heap admin --------------------------------------------------
1268 if (clo_heap_admin > 0)
1269 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1270
1271 // Stack(s) ----------------------------------------------------
1272 if (clo_stacks)
1273 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1274}
1275
1276// This does the calculations for all censi.
1277static void calc_spacetime2(ULong* heap2, ULong* heap_admin2, ULong* stack2)
1278{
1279 UInt i, N = curr_census;
1280
1281 VGP_PUSHCC(VgpCalcSpacetime2);
1282
1283 *heap2 = 0;
1284 *heap_admin2 = 0;
1285 *stack2 = 0;
1286
1287 if (N <= 1)
1288 return;
1289
1290 calc_spacetime2b( &censi[0], censi[1].ms_time - censi[0].ms_time,
1291 heap2, heap_admin2, stack2 );
1292
1293 for (i = 1; i <= N-2; i++) {
1294 calc_spacetime2b( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1295 heap2, heap_admin2, stack2 );
1296 }
1297
1298 calc_spacetime2b( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1299 heap2, heap_admin2, stack2 );
1300 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1301 *heap2 /= 2;
1302 *heap_admin2 /= 2;
1303 *stack2 /= 2;
1304
1305 VGP_POPCC(VgpCalcSpacetime2);
1306}
1307
1308/*------------------------------------------------------------*/
1309/*--- Writing the graph file ---*/
1310/*------------------------------------------------------------*/
1311
1312static Char* make_filename(Char* dir, Char* suffix)
1313{
1314 Char* filename;
1315
1316 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1317 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1318 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1319
1320 return filename;
1321}
1322
1323// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1324static Char* clean_fnname(Char *d, Char* s)
1325{
1326 Char* dorig = d;
1327 while (*s) {
1328 if (' ' == *s) { *d = '%'; }
1329 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1330 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1331 else { *d = *s; };
1332 s++;
1333 d++;
1334 }
1335 *d = '\0';
1336 return dorig;
1337}
1338
1339static void file_err ( Char* file )
1340{
1341 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1342 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1343}
1344
1345/* Format, by example:
1346
1347 JOB "a.out -p"
1348 DATE "Fri Apr 17 11:43:45 1992"
1349 SAMPLE_UNIT "seconds"
1350 VALUE_UNIT "bytes"
1351 BEGIN_SAMPLE 0.00
1352 SYSTEM 24
1353 END_SAMPLE 0.00
1354 BEGIN_SAMPLE 1.00
1355 elim 180
1356 insert 24
1357 intersect 12
1358 disin 60
1359 main 12
1360 reduce 20
1361 SYSTEM 12
1362 END_SAMPLE 1.00
1363 MARK 1.50
1364 MARK 1.75
1365 MARK 1.80
1366 BEGIN_SAMPLE 2.00
1367 elim 192
1368 insert 24
1369 intersect 12
1370 disin 84
1371 main 12
1372 SYSTEM 24
1373 END_SAMPLE 2.00
1374 BEGIN_SAMPLE 2.82
1375 END_SAMPLE 2.82
1376 */
1377static void write_hp_file(void)
1378{
1379 Int i, j;
1380 Int fd, res;
1381 Char *hp_file, *ps_file, *aux_file;
1382 Char* cmdfmt;
1383 Char* cmdbuf;
1384 Int cmdlen;
1385
1386 VGP_PUSHCC(VgpPrintHp);
1387
1388 // Open file
1389 hp_file = make_filename( base_dir, ".hp" );
1390 ps_file = make_filename( base_dir, ".ps" );
1391 aux_file = make_filename( base_dir, ".aux" );
1392 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1393 VKI_S_IRUSR|VKI_S_IWUSR);
1394 if (fd < 0) {
1395 file_err( hp_file );
1396 VGP_POPCC(VgpPrintHp);
1397 return;
1398 }
1399
1400 // File header, including command line
1401 SPRINTF(buf, "JOB \"");
1402 for (i = 0; i < VG_(client_argc); i++)
1403 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1404 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1405 "DATE \"\"\n"
1406 "SAMPLE_UNIT \"ms\"\n"
1407 "VALUE_UNIT \"bytes\"\n", ms_interval);
1408
1409 // Censi
1410 for (i = 0; i < curr_census; i++) {
1411 Census* census = & censi[i];
1412
1413 // Census start
1414 SPRINTF(buf, "MARK %d.0\n"
1415 "BEGIN_SAMPLE %d.0\n",
1416 census->ms_time, census->ms_time);
1417
1418 // Heap -----------------------------------------------------------
1419 if (clo_heap) {
1420 // Print all the significant XPts from that census
1421 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1422 // Grab the jth top-XPt
1423 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
1424 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->eip, buf2, 16)) {
1425 VG_(sprintf)(buf2, "???");
1426 }
1427 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->eip,
1428 clean_fnname(buf3, buf2), xtree_snapshot->space);
1429 }
1430
1431 // Remaining heap block alloc points, combined
1432 if (census->others_space > 0)
1433 SPRINTF(buf, "other %d\n", census->others_space);
1434 }
1435
1436 // Heap admin -----------------------------------------------------
1437 if (clo_heap_admin > 0 && census->heap_admin_space)
1438 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1439
1440 // Stack(s) -------------------------------------------------------
1441 if (clo_stacks)
1442 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1443
1444 // Census end
1445 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1446 }
1447
1448 // Close file
1449 sk_assert(fd >= 0);
1450 VG_(close)(fd);
1451
1452 // Attempt to convert file using hp2ps
1453 cmdfmt = "%s/hp2ps -c -t1 %s";
1454 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1455 + VG_(strlen)(cmdfmt);
1456 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1457 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1458 res = VG_(system)(cmdbuf);
1459 VG_(free)(cmdbuf);
1460 if (res != 0) {
1461 VG_(message)(Vg_UserMsg,
1462 "Conversion to PostScript failed. Try converting manually.");
1463 } else {
1464 // remove the .hp and .aux file
1465 VG_(unlink)(hp_file);
1466 VG_(unlink)(aux_file);
1467 }
1468
1469 VG_(free)(hp_file);
1470 VG_(free)(ps_file);
1471 VG_(free)(aux_file);
1472
1473 VGP_POPCC(VgpPrintHp);
1474}
1475
1476/*------------------------------------------------------------*/
1477/*--- Writing the XPt text/HTML file ---*/
1478/*------------------------------------------------------------*/
1479
1480static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1481{
1482 int i, len, space;
1483
1484 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1485 len = VG_(strlen)(xbuf);
1486 space = field_width - len;
1487 if (space < 0) space = 0; /* Allow for v. small field_width */
1488 i = len;
1489
1490 /* Right justify in field */
1491 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1492 for (i = 0; i < space; i++) xbuf[i] = ' ';
1493}
1494
1495// Nb: uses a static buffer, each call trashes the last string returned.
1496static Char* make_perc(ULong spacetime, ULong total_spacetime)
1497{
1498 static Char mbuf[32];
1499
1500 UInt p = 10;
1501 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1502 return mbuf;
1503}
1504
1505// Nb: passed in XPt is a lower-level XPt; %eips are grabbed from
1506// bottom-to-top of XCon, and then printed in the reverse order.
1507static UInt pp_XCon(Int fd, XPt* xpt)
1508{
1509 Addr rev_eips[clo_depth+1];
1510 Int i = 0;
1511 Int n = 0;
1512 Bool is_HTML = ( XHTML == clo_format );
1513 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1514 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1515
1516 sk_assert(NULL != xpt);
1517
1518 while (True) {
1519 rev_eips[i] = xpt->eip;
1520 n++;
1521 if (alloc_xpt == xpt->parent) break;
1522 i++;
1523 xpt = xpt->parent;
1524 }
1525
1526 for (i = n-1; i >= 0; i--) {
1527 // -1 means point to calling line
1528 VG_(describe_eip)(rev_eips[i]-1, buf2, BUF_LEN);
1529 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1530 }
1531
1532 return n;
1533}
1534
1535// Important point: for HTML, each XPt must be identified uniquely for the
1536// HTML links to all match up correctly. Using xpt->eip is not
1537// sufficient, because function pointers mean that you can call more than
1538// one other function from a single code location. So instead we use the
1539// address of the xpt struct itself, which is guaranteed to be unique.
1540
1541static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1542 ULong total_spacetime)
1543{
1544 UInt i;
1545 XPt *xpt, *child;
1546 UInt L = 0;
1547 UInt c1 = 1;
1548 UInt c2 = 0;
1549 ULong sum = 0;
1550 UInt n;
1551 Char *eip_desc, *perc;
1552 Bool is_HTML = ( XHTML == clo_format );
1553 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1554 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1555 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1556 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1557 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1558 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1559 Char* end_hr = ( is_HTML ? "<hr>" :
1560 "=================================" );
1561 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1562
1563 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1564
1565 while (NULL != (xpt = (XPt*)dequeue(q))) {
1566 // Check that non-top-level XPts have a zero .spacetime field.
1567 if (xpt->parent != alloc_xpt) sk_assert( 0 == xpt->spacetime );
1568
1569 // Check that the sum of all children .spacetime2s equals parent's
1570 // (unless alloc_xpt, when it should == 0).
1571 if (alloc_xpt == xpt) {
1572 sk_assert(0 == xpt->spacetime2);
1573 } else {
1574 sum = 0;
1575 for (i = 0; i < xpt->n_children; i++) {
1576 sum += xpt->children[i]->spacetime2;
1577 }
1578 //sk_assert(sum == xpt->spacetime2);
1579 // It's possible that not all the children were included in the
1580 // spacetime2 calculations. Hopefully almost all of them were, and
1581 // all the important ones.
1582// sk_assert(sum <= xpt->spacetime2);
1583// sk_assert(sum * 1.05 > xpt->spacetime2 );
1584// if (sum != xpt->spacetime2) {
1585// VG_(printf)("%ld, %ld\n", sum, xpt->spacetime2);
1586// }
1587 }
1588
1589 if (xpt == alloc_xpt) {
1590 SPRINTF(buf, "Heap allocation functions accounted for "
1591 "%s of measured spacetime%s\n",
1592 make_perc(heap_spacetime, total_spacetime), maybe_br);
1593 } else {
1594 // Remember: spacetime2 is space.time *doubled*
1595 perc = make_perc(xpt->spacetime2 / 2, total_spacetime);
1596 if (is_HTML) {
1597 SPRINTF(buf, "<a name=\"b%x\"></a>"
1598 "Context accounted for "
1599 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1600 xpt, xpt, perc);
1601 } else {
1602 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1603 perc);
1604 }
1605 n = pp_XCon(fd, xpt);
1606 sk_assert(n == L);
1607 }
1608
1609 // Sort children by spacetime2
1610 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
1611 XPt_cmp_spacetime2);
1612
1613 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1614 for (i = 0; i < xpt->n_children; i++) {
1615 child = xpt->children[i];
1616
1617 // Stop when <1% of total spacetime
1618 if (child->spacetime2 * 1000 / (total_spacetime * 2) < 5) {
1619 UInt n_insig = xpt->n_children - i;
1620 Char* s = ( n_insig == 1 ? "" : "s" );
1621 Char* and = ( 0 == i ? "" : "and " );
1622 Char* other = ( 0 == i ? "" : "other " );
1623 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1624 maybe_li, and, n_insig, other, s, maybe_fli);
1625 break;
1626 }
1627
1628 // Remember: spacetime2 is space.time *doubled*
1629 perc = make_perc(child->spacetime2 / 2, total_spacetime);
1630 eip_desc = VG_(describe_eip)(child->eip-1, buf2, BUF_LEN);
1631 if (is_HTML) {
1632 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1633
1634 if (child->n_children > 0) {
1635 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1636 } else {
1637 SPRINTF(buf, "%s", perc);
1638 }
1639 SPRINTF(buf, ": %s\n", eip_desc);
1640 } else {
1641 SPRINTF(buf, " %6s: %s\n\n", perc, eip_desc);
1642 }
1643
1644 if (child->n_children > 0) {
1645 enqueue(q, (void*)child);
1646 c2++;
1647 }
1648 }
1649 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1650 c1--;
1651
1652 // Putting markers between levels of the structure:
1653 // c1 tracks how many to go on this level, c2 tracks how many we've
1654 // queued up for the next level while finishing off this level.
1655 // When c1 gets to zero, we've changed levels, so print a marker,
1656 // move c2 into c1, and zero c2.
1657 if (0 == c1) {
1658 L++;
1659 c1 = c2;
1660 c2 = 0;
1661 if (! is_empty_queue(q) ) { // avoid empty one at end
1662 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1663 }
1664 } else {
1665 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1666 }
1667 }
1668 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1669 "%s value for more.\n", end_hr, depth);
1670}
1671
1672static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1673 ULong total_spacetime)
1674{
1675 Queue* q = construct_queue(100);
1676 enqueue(q, xpt);
1677 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1678 destruct_queue(q);
1679}
1680
1681static void
1682write_text_file(ULong total_ST, ULong heap_ST)
1683{
1684 Int fd, i;
1685 Char* text_file;
1686 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1687
1688 VGP_PUSHCC(VgpPrintXPts);
1689
1690 // Open file
1691 text_file = make_filename( base_dir,
1692 ( XText == clo_format ? ".txt" : ".html" ) );
1693
1694 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1695 VKI_S_IRUSR|VKI_S_IWUSR);
1696 if (fd < 0) {
1697 file_err( text_file );
1698 VGP_POPCC(VgpPrintXPts);
1699 return;
1700 }
1701
1702 // Header
1703 if (XHTML == clo_format) {
1704 SPRINTF(buf, "<html>\n"
1705 "<head>\n"
1706 "<title>%s</title>\n"
1707 "</head>\n"
1708 "<body>\n",
1709 text_file);
1710 }
1711
1712 // Command line
1713 SPRINTF(buf, "Command: ");
1714 for (i = 0; i < VG_(client_argc); i++)
1715 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1716 SPRINTF(buf, "\n%s\n", maybe_p);
1717
1718 if (clo_heap)
1719 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1720
1721 sk_assert(fd >= 0);
1722 VG_(close)(fd);
1723
1724 VGP_POPCC(VgpPrintXPts);
1725}
1726
1727/*------------------------------------------------------------*/
1728/*--- Finalisation ---*/
1729/*------------------------------------------------------------*/
1730
1731static void
1732print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1733 ULong stack_ST)
1734{
1735 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1736
1737 // Heap --------------------------------------------------------------
1738 if (clo_heap)
1739 VG_(message)(Vg_UserMsg, "heap: %s",
1740 make_perc(heap_ST, total_ST) );
1741
1742 // Heap admin --------------------------------------------------------
1743 if (clo_heap_admin)
1744 VG_(message)(Vg_UserMsg, "heap admin: %s",
1745 make_perc(heap_admin_ST, total_ST));
1746
1747 sk_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
1748
1749 // Stack(s) ----------------------------------------------------------
1750 if (clo_stacks)
1751 VG_(message)(Vg_UserMsg, "stack(s): %s",
1752 make_perc(stack_ST, total_ST));
1753
1754 if (VG_(clo_verbosity) > 1) {
1755 sk_assert(n_xpts > 0); // always have alloc_xpt
1756 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1757 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1758 n_zero_allocs * 100 / n_allocs );
1759 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1760 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1761 n_xpts*sizeof(XPt));
1762 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1763 n_bot_xpts * 100 / n_xpts);
1764 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1765 alloc_xpt->n_children * 100 / n_xpts);
1766 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1767 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1768 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1769 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1770 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1771 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1772 }
1773}
1774
1775void SK_(fini)(Int exit_status)
1776{
1777 ULong total_ST = 0;
1778 ULong heap_ST = 0;
1779 ULong heap_admin_ST = 0;
1780 ULong stack_ST = 0;
1781
1782 // Do a final (empty) sample to show program's end
1783 hp_census();
1784
1785 // Redo spacetimes of significant contexts to match the .hp file.
1786 calc_spacetime2(&heap_ST, &heap_admin_ST, &stack_ST);
1787 total_ST = heap_ST + heap_admin_ST + stack_ST;
1788 write_hp_file ( );
1789 write_text_file( total_ST, heap_ST );
1790 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1791}
1792
1793VG_DETERMINE_INTERFACE_VERSION(SK_(pre_clo_init), 0)
1794
1795/*--------------------------------------------------------------------*/
1796/*--- end ms_main.c ---*/
1797/*--------------------------------------------------------------------*/
1798