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