blob: 1c722162fa7c036543ed6ec77ce7298e0215503e [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
nethercote46063202004-09-02 08:51:43 +000037#include "tool.h"
nethercotec9f36922004-02-14 16:40:02 +000038//#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 !!!
nethercote43a15ce2004-08-30 19:15:12 +0000103 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000104
nethercote43a15ce2004-08-30 19:15:12 +0000105 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000106 // used in the results.
107 // Note that it is *doubled*, to avoid rounding errors.
108 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000109 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000110
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
nethercote43a15ce2004-08-30 19:15:12 +0000123// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000124//
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
nethercote7ac7f7b2004-11-02 12:36:02 +0000181 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000182 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 }
njn4be0a692004-11-22 18:10:36 +0000203 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000204
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
nethercote8b5f40c2004-11-02 13:29:50 +0000247static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000248
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
njn26f02512004-11-22 18:33:15 +0000291Bool TL_(process_cmd_line_option)(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000292{
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
njn26f02512004-11-22 18:33:15 +0000319void TL_(print_usage)(void)
nethercotec9f36922004-02-14 16:40:02 +0000320{
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
njn26f02512004-11-22 18:33:15 +0000332void TL_(print_debug_usage)(void)
nethercotec9f36922004-02-14 16:40:02 +0000333{
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.
nethercote7ac7f7b2004-11-02 12:36:02 +0000347static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000348{
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
nethercote43a15ce2004-08-30 19:15:12 +0000371 xpt->curr_space = 0;
372 xpt->approx_ST = 0;
373 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000374
375 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000376
377 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000378 tl_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{
nethercoteacac2fd2004-11-04 13:49:28 +0000418 // Static to minimise stack size. +1 for added ~0 %eip.
nethercotec9f36922004-02-14 16:40:02 +0000419 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.
nethercote43a15ce2004-08-30 19:15:12 +0000441 // the parent's approx_ST wouldn't be equal [or almost equal] to the
442 // total of the childrens' approx_STs).
nethercoteacac2fd2004-11-04 13:49:28 +0000443 eips[ n_eips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000444
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
njnca82cc02004-11-22 17:18:48 +0000450 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000451
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)
njn67993252004-11-22 18:02:32 +0000456 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000457 } 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
njnca82cc02004-11-22 17:18:48 +0000485 tl_assert(xpt->max_children != 0);
486 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000487 // 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) {
njnca82cc02004-11-22 17:18:48 +0000506 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000507 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
njnca82cc02004-11-22 17:18:48 +0000522 tl_assert(True == clo_heap);
523 tl_assert(0 != space_delta);
524 tl_assert(NULL != xpt);
525 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000526
527 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000528 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000529 xpt->curr_space += space_delta;
530 xpt = xpt->parent;
531 }
njnca82cc02004-11-22 17:18:48 +0000532 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000533 alloc_xpt->curr_space += space_delta;
534
535 VGP_POPCC(VgpUpdateXCon);
536}
537
538// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000539static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000540{
541 XPt* xpt1 = *(XPt**)n1;
542 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000543 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000544}
545
nethercote43a15ce2004-08-30 19:15:12 +0000546static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000547{
548 XPt* xpt1 = *(XPt**)n1;
549 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000550 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000551}
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
njnca82cc02004-11-22 17:18:48 +0000605 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000606 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{
nethercote3d6b6112004-11-04 16:39:43 +0000651 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000652 (VgHashNode***)prev_chunks_next_ptr );
653}
654
655static __inline__
656void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
657{
njnca82cc02004-11-22 17:18:48 +0000658 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000659 n_heap_blocks--;
660 *prev_chunks_next_ptr = hc->next;
661}
662
663// Forward declaration
664static void hp_census(void);
665
nethercote159dfef2004-09-13 13:27:30 +0000666static
njn57735902004-11-25 18:04:54 +0000667void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
668 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000669{
670 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000671 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000672 if (size < 0) return NULL;
673
674 VGP_PUSHCC(VgpCliMalloc);
675
676 // Update statistics
677 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000678 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000679
nethercote57e36b32004-07-10 14:56:28 +0000680 // Allocate and zero if necessary
681 if (!p) {
682 p = VG_(cli_malloc)( align, size );
683 if (!p) {
684 VGP_POPCC(VgpCliMalloc);
685 return NULL;
686 }
687 if (is_zeroed) VG_(memset)(p, 0, size);
688 }
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 hc->where = NULL; // paranoia
695 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000696 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000697 if (0 != size)
698 update_XCon(hc->where, size);
699 }
700 add_HP_Chunk( hc );
701
702 // do a census!
703 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000704
705 VGP_POPCC(VgpCliMalloc);
706 return p;
707}
708
709static __inline__
710void die_block ( void* p, Bool custom_free )
711{
nethercote57e36b32004-07-10 14:56:28 +0000712 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000713
714 VGP_PUSHCC(VgpCliMalloc);
715
716 // Update statistics
717 n_frees++;
718
nethercote57e36b32004-07-10 14:56:28 +0000719 // Remove HP_Chunk from malloclist
720 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000721 if (hc == NULL)
722 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000723 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000724 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000725
726 if (clo_heap && hc->size != 0)
727 update_XCon(hc->where, -hc->size);
728
nethercote57e36b32004-07-10 14:56:28 +0000729 VG_(free)( hc );
730
731 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000732 if (!custom_free)
733 VG_(cli_free)( p );
734
nethercote57e36b32004-07-10 14:56:28 +0000735 // do a census!
736 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000737
nethercotec9f36922004-02-14 16:40:02 +0000738 VGP_POPCC(VgpCliMalloc);
739}
740
741
njn57735902004-11-25 18:04:54 +0000742void* TL_(malloc) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000743{
njn57735902004-11-25 18:04:54 +0000744 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000745}
746
njn57735902004-11-25 18:04:54 +0000747void* TL_(__builtin_new) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000748{
njn57735902004-11-25 18:04:54 +0000749 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000750}
751
njn57735902004-11-25 18:04:54 +0000752void* TL_(__builtin_vec_new) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000753{
njn57735902004-11-25 18:04:54 +0000754 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000755}
756
njn57735902004-11-25 18:04:54 +0000757void* TL_(calloc) ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000758{
njn57735902004-11-25 18:04:54 +0000759 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000760}
761
njn57735902004-11-25 18:04:54 +0000762void *TL_(memalign)( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000763{
njn57735902004-11-25 18:04:54 +0000764 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000765}
766
njn57735902004-11-25 18:04:54 +0000767void TL_(free) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000768{
769 die_block( p, /*custom_free*/False );
770}
771
njn57735902004-11-25 18:04:54 +0000772void TL_(__builtin_delete) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000773{
774 die_block( p, /*custom_free*/False);
775}
776
njn57735902004-11-25 18:04:54 +0000777void TL_(__builtin_vec_delete) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000778{
779 die_block( p, /*custom_free*/False );
780}
781
njn57735902004-11-25 18:04:54 +0000782void* TL_(realloc) ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000783{
784 HP_Chunk* hc;
785 HP_Chunk** remove_handle;
786 Int i;
787 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000788 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000789 XPt *old_where, *new_where;
790
791 VGP_PUSHCC(VgpCliMalloc);
792
793 // First try and find the block.
794 hc = get_HP_Chunk ( p_old, &remove_handle );
795 if (hc == NULL) {
796 VGP_POPCC(VgpCliMalloc);
797 return NULL; // must have been a bogus free()
798 }
799
njnca82cc02004-11-22 17:18:48 +0000800 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000801 old_size = hc->size;
802
803 if (new_size <= old_size) {
804 // new size is smaller or same; block not moved
805 p_new = p_old;
806
807 } else {
808 // new size is bigger; make new block, copy shared contents, free old
809 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
810
811 for (i = 0; i < old_size; i++)
812 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
813
814 VG_(cli_free)(p_old);
815 }
816
817 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000818 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000819
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
nethercote43a15ce2004-08-30 19:15:12 +0000861 // If no memory allocated at all, nothing interesting to record.
862 if (alloc_xpt->curr_space == 0) return 0;
863
864 // Ignore sub-XTrees that account for a miniscule fraction of current
865 // allocated space.
866 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000867 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
nethercote43a15ce2004-08-30 19:15:12 +0000881 // Structure of this function mirrors that of get_xtree_size().
882
883 if (alloc_xpt->curr_space == 0) return 0;
884
885 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000886 xtree_snapshot[ix].xpt = xpt;
887 xtree_snapshot[ix].space = xpt->curr_space;
888 ix++;
889
nethercotec9f36922004-02-14 16:40:02 +0000890 for (i = 0; i < xpt->n_children; i++)
891 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
892 }
893 return ix;
894}
895
896static UInt ms_interval;
897static UInt do_every_nth_census = 30;
898
899// Weed out half the censi; we choose those that represent the smallest
900// time-spans, because that loses the least information.
901//
902// Algorithm for N censi: We find the census representing the smallest
903// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
904// (It's (N/2)-1 because we never remove the first and last censi.)
905// We have to do this one census at a time, rather than finding the (N/2)-1
906// smallest censi in one hit, because when a census is removed, it's
907// neighbours immediately cover greater timespans. So it's N^2, but N only
908// equals 200, and this is only done every 100 censi, which is not too often.
909static void halve_censi(void)
910{
911 Int i, jp, j, jn, k;
912 Census* min_census;
913
914 n_halvings++;
915 if (VG_(clo_verbosity) > 1)
916 VG_(message)(Vg_UserMsg, "Halving censi...");
917
918 // Sets j to the index of the first not-yet-removed census at or after i
919 #define FIND_CENSUS(i, j) \
920 for (j = i; -1 == censi[j].ms_time; j++) { }
921
922 for (i = 2; i < MAX_N_CENSI; i += 2) {
923 // Find the censi representing the smallest timespan. The timespan
924 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
925 // censi A and B. We don't consider the first and last censi for
926 // removal.
927 Int min_span = 0x7fffffff;
928 Int min_j = 0;
929
930 // Initial triple: (prev, curr, next) == (jp, j, jn)
931 jp = 0;
932 FIND_CENSUS(1, j);
933 FIND_CENSUS(j+1, jn);
934 while (jn < MAX_N_CENSI) {
935 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000936 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000937 if (timespan < min_span) {
938 min_span = timespan;
939 min_j = j;
940 }
941 // Move on to next triple
942 jp = j;
943 j = jn;
944 FIND_CENSUS(jn+1, jn);
945 }
946 // We've found the least important census, now remove it
947 min_census = & censi[ min_j ];
948 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
949 n_snapshot_frees++;
950 VG_(free)(min_census->xtree_snapshots[k]);
951 min_census->xtree_snapshots[k] = NULL;
952 }
953 min_census->ms_time = -1;
954 }
955
956 // Slide down the remaining censi over the removed ones. The '<=' is
957 // because we are removing on (N/2)-1, rather than N/2.
958 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
959 FIND_CENSUS(j, j);
960 if (i != j) {
961 censi[i] = censi[j];
962 }
963 }
964 curr_census = i;
965
966 // Double intervals
967 ms_interval *= 2;
968 do_every_nth_census *= 2;
969
970 if (VG_(clo_verbosity) > 1)
971 VG_(message)(Vg_UserMsg, "...done");
972}
973
974// Take a census. Census time seems to be insignificant (usually <= 0 ms,
975// almost always <= 1ms) so don't have to worry about subtracting it from
976// running time in any way.
977//
978// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
979// 50ms!
980static void hp_census(void)
981{
982 static UInt ms_prev_census = 0;
983 static UInt ms_next_census = 0; // zero allows startup census
984
985 Int ms_time, ms_time_since_prev;
986 Int i, K;
987 Census* census;
988
989 VGP_PUSHCC(VgpCensus);
990
991 // Only do a census if it's time
992 ms_time = VG_(read_millisecond_timer)();
993 ms_time_since_prev = ms_time - ms_prev_census;
994 if (ms_time < ms_next_census) {
995 n_fake_censi++;
996 VGP_POPCC(VgpCensus);
997 return;
998 }
999 n_real_censi++;
1000
1001 census = & censi[curr_census];
1002
1003 census->ms_time = ms_time;
1004
1005 // Heap: snapshot the K most significant XTrees -------------------
1006 if (clo_heap) {
1007 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1008 ? alloc_xpt->n_children
1009 : MAX_SNAPSHOTS); // max out
1010
nethercote43a15ce2004-08-30 19:15:12 +00001011 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001012 // We *do not* do it for any non-top-XPTs.
1013 for (i = 0; i < alloc_xpt->n_children; i++) {
1014 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001015 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001016 }
nethercote43a15ce2004-08-30 19:15:12 +00001017 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001018 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001019 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001020
1021 VGP_PUSHCC(VgpCensusHeap);
1022
1023 // For each significant top-level XPt, record space info about its
1024 // entire XTree, in a single census entry.
1025 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1026 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001027 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001028 for (i = 0; i < K; i++) {
1029 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001030// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1031 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001032 VGP_PUSHCC(VgpCensusTreeSize);
1033 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1034 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001035
1036 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1037 // insignificant) then don't take any more snapshots.
1038 if (0 == xtree_size) break;
1039
1040 // Make array of the appropriate size (+1 for zero termination,
1041 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001042 census->xtree_snapshots[i] =
1043 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001044 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001045 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1046 (xtree_size+1) * sizeof(XPtSnapshot));
1047
1048 // Take space-snapshot: copy 'curr_space' for every XPt in the
1049 // XTree into the snapshot array, along with pointers to the XPts.
1050 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001051 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001052 // saves a lot of memory and up to 40% time with big --depth valus.
1053 VGP_PUSHCC(VgpCensusSnapshot);
1054 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1055 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001056 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001057 VGP_POPCC(VgpCensusSnapshot);
1058 }
1059// VG_(printf)("\n\n");
1060 // Zero-terminate 'xtree_snapshot' array
1061 census->xtree_snapshots[i] = NULL;
1062
1063 VGP_POPCC(VgpCensusHeap);
1064
1065 //VG_(printf)("printed %d censi\n", K);
1066
1067 // Lump the rest into a single "others" entry.
1068 census->others_space = 0;
1069 for (i = K; i < alloc_xpt->n_children; i++) {
1070 census->others_space += alloc_xpt->children[i]->curr_space;
1071 }
1072 }
1073
1074 // Heap admin -------------------------------------------------------
1075 if (clo_heap_admin > 0)
1076 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1077
1078 // Stack(s) ---------------------------------------------------------
1079 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001080 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001081 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001082 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001083 i++;
1084 }
1085
1086 // Finish, update interval if necessary -----------------------------
1087 curr_census++;
1088 census = NULL; // don't use again now that curr_census changed
1089
1090 // Halve the entries, if our census table is full
1091 if (MAX_N_CENSI == curr_census) {
1092 halve_censi();
1093 }
1094
1095 // Take time for next census from now, rather than when this census
1096 // should have happened. Because, if there's a big gap due to a kernel
1097 // operation, there's no point doing catch-up censi every BB for a while
1098 // -- that would just give N censi at almost the same time.
1099 if (VG_(clo_verbosity) > 1) {
1100 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1101 VG_(read_millisecond_timer)() - ms_time );
1102 }
1103 ms_prev_census = ms_time;
1104 ms_next_census = ms_time + ms_interval;
1105 //ms_next_census += ms_interval;
1106
1107 //VG_(printf)("Next: %d ms\n", ms_next_census);
1108
1109 VGP_POPCC(VgpCensus);
1110}
1111
1112/*------------------------------------------------------------*/
1113/*--- Tracked events ---*/
1114/*------------------------------------------------------------*/
1115
nethercote8b5f40c2004-11-02 13:29:50 +00001116static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001117{
1118 sigstacks_space += len;
1119}
1120
nethercote8b5f40c2004-11-02 13:29:50 +00001121static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001122{
njnca82cc02004-11-22 17:18:48 +00001123 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001124 sigstacks_space -= len;
1125}
1126
1127/*------------------------------------------------------------*/
1128/*--- Client Requests ---*/
1129/*------------------------------------------------------------*/
1130
njn26f02512004-11-22 18:33:15 +00001131Bool TL_(handle_client_request) ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001132{
1133 switch (argv[0]) {
1134 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001135 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001136 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001137 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001138 *ret = 0;
njn57735902004-11-25 18:04:54 +00001139 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001140 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001141 return True;
1142 }
1143 case VG_USERREQ__FREELIKE_BLOCK: {
1144 void* p = (void*)argv[1];
1145 *ret = 0;
1146 die_block( p, /*custom_free*/True );
1147 return True;
1148 }
1149 default:
1150 *ret = 0;
1151 return False;
1152 }
1153}
1154
1155/*------------------------------------------------------------*/
1156/*--- Initialisation ---*/
1157/*------------------------------------------------------------*/
1158
1159// Current directory at startup.
1160static Char* base_dir;
1161
njn0e742df2004-11-30 13:26:29 +00001162SizeT VG_(vg_malloc_redzone_szB) = 0;
nethercotec9f36922004-02-14 16:40:02 +00001163
njn26f02512004-11-22 18:33:15 +00001164void TL_(pre_clo_init)()
nethercotec9f36922004-02-14 16:40:02 +00001165{
1166 VG_(details_name) ("Massif");
nethercote29b02612004-03-16 19:41:14 +00001167 VG_(details_version) (NULL);
nethercotec9f36922004-02-14 16:40:02 +00001168 VG_(details_description) ("a space profiler");
1169 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
nethercote27645c72004-02-23 15:33:33 +00001170 VG_(details_bug_reports_to) (VG_BUGS_TO);
nethercotec9f36922004-02-14 16:40:02 +00001171
1172 // Needs
1173 VG_(needs_libc_freeres)();
1174 VG_(needs_command_line_options)();
1175 VG_(needs_client_requests) ();
1176
1177 // Events to track
1178 VG_(init_new_mem_stack_signal) ( new_mem_stack_signal );
1179 VG_(init_die_mem_stack_signal) ( die_mem_stack_signal );
1180
1181 // Profiling events
1182 VGP_(register_profile_event)(VgpGetXPt, "get-XPt");
1183 VGP_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1184 VGP_(register_profile_event)(VgpCensus, "census");
1185 VGP_(register_profile_event)(VgpCensusHeap, "census-heap");
1186 VGP_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1187 VGP_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1188 VGP_(register_profile_event)(VgpUpdateXCon, "update-XCon");
nethercote43a15ce2004-08-30 19:15:12 +00001189 VGP_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
nethercotec9f36922004-02-14 16:40:02 +00001190 VGP_(register_profile_event)(VgpPrintHp, "print-hp");
1191 VGP_(register_profile_event)(VgpPrintXPts, "print-XPts");
1192
1193 // HP_Chunks
1194 malloc_list = VG_(HT_construct)();
1195
1196 // Dummy node at top of the context structure.
1197 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1198
njnca82cc02004-11-22 17:18:48 +00001199 tl_assert( VG_(getcwd_alloc)(&base_dir) );
nethercotec9f36922004-02-14 16:40:02 +00001200}
1201
njn26f02512004-11-22 18:33:15 +00001202void TL_(post_clo_init)(void)
nethercotec9f36922004-02-14 16:40:02 +00001203{
1204 ms_interval = 1;
1205
1206 // Do an initial sample for t = 0
1207 hp_census();
1208}
1209
1210/*------------------------------------------------------------*/
1211/*--- Instrumentation ---*/
1212/*------------------------------------------------------------*/
1213
njnee8a5862004-11-22 21:08:46 +00001214IRBB* TL_(instrument) ( IRBB* bb_in, VexGuestLayout* layout, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001215{
njnee8a5862004-11-22 21:08:46 +00001216 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001217}
1218
1219/*------------------------------------------------------------*/
1220/*--- Spacetime recomputation ---*/
1221/*------------------------------------------------------------*/
1222
nethercote43a15ce2004-08-30 19:15:12 +00001223// Although we've been calculating space-time along the way, because the
1224// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001225// might not agree with what hp2ps sees, because we've thrown away some of
1226// the information. So recompute it at the scale that hp2ps sees, so we can
1227// confidently determine which contexts hp2ps will choose for displaying as
1228// distinct bands. This recomputation only happens to the significant ones
1229// that get printed in the .hp file, so it's cheap.
1230//
nethercote43a15ce2004-08-30 19:15:12 +00001231// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001232// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1233// where
1234// a[N] is the space at census N
1235// d(A,B) is the time interval between censi A and B
1236// and
1237// d(A,B) + d(B,C) == d(A,C)
1238//
1239// Key point: we can calculate the area for a census without knowing the
1240// previous or subsequent censi's space; because any over/underestimates
1241// for this census will be reversed in the next, balancing out. This is
1242// important, as getting the previous/next census entry for a particular
1243// AP is a pain with this data structure, but getting the prev/next
1244// census time is easy.
1245//
nethercote43a15ce2004-08-30 19:15:12 +00001246// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001247// The ULong* values are all running totals, hence the use of "+=" everywhere.
1248
1249// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001250static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001251 ULong* twice_heap_ST,
1252 ULong* twice_heap_admin_ST,
1253 ULong* twice_stack_ST)
1254{
1255 UInt i, j;
1256 XPtSnapshot* xpt_snapshot;
1257
1258 // Heap --------------------------------------------------------
1259 if (clo_heap) {
1260 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001261 // Compute total heap exact_ST_dbld for the entire XTree using only
1262 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001263 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1264
nethercote43a15ce2004-08-30 19:15:12 +00001265 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1266 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001267 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1268 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001269 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001270 }
1271 }
1272 *twice_heap_ST += d_t1_t2 * census->others_space;
1273 }
1274
1275 // Heap admin --------------------------------------------------
1276 if (clo_heap_admin > 0)
1277 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1278
1279 // Stack(s) ----------------------------------------------------
1280 if (clo_stacks)
1281 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1282}
1283
1284// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001285static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001286{
1287 UInt i, N = curr_census;
1288
1289 VGP_PUSHCC(VgpCalcSpacetime2);
1290
1291 *heap2 = 0;
1292 *heap_admin2 = 0;
1293 *stack2 = 0;
1294
1295 if (N <= 1)
1296 return;
1297
nethercote43a15ce2004-08-30 19:15:12 +00001298 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1299 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001300
1301 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001302 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1303 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001304 }
1305
nethercote43a15ce2004-08-30 19:15:12 +00001306 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1307 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001308 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1309 *heap2 /= 2;
1310 *heap_admin2 /= 2;
1311 *stack2 /= 2;
1312
1313 VGP_POPCC(VgpCalcSpacetime2);
1314}
1315
1316/*------------------------------------------------------------*/
1317/*--- Writing the graph file ---*/
1318/*------------------------------------------------------------*/
1319
1320static Char* make_filename(Char* dir, Char* suffix)
1321{
1322 Char* filename;
1323
1324 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1325 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1326 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1327
1328 return filename;
1329}
1330
1331// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1332static Char* clean_fnname(Char *d, Char* s)
1333{
1334 Char* dorig = d;
1335 while (*s) {
1336 if (' ' == *s) { *d = '%'; }
1337 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1338 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1339 else { *d = *s; };
1340 s++;
1341 d++;
1342 }
1343 *d = '\0';
1344 return dorig;
1345}
1346
1347static void file_err ( Char* file )
1348{
1349 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1350 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1351}
1352
1353/* Format, by example:
1354
1355 JOB "a.out -p"
1356 DATE "Fri Apr 17 11:43:45 1992"
1357 SAMPLE_UNIT "seconds"
1358 VALUE_UNIT "bytes"
1359 BEGIN_SAMPLE 0.00
1360 SYSTEM 24
1361 END_SAMPLE 0.00
1362 BEGIN_SAMPLE 1.00
1363 elim 180
1364 insert 24
1365 intersect 12
1366 disin 60
1367 main 12
1368 reduce 20
1369 SYSTEM 12
1370 END_SAMPLE 1.00
1371 MARK 1.50
1372 MARK 1.75
1373 MARK 1.80
1374 BEGIN_SAMPLE 2.00
1375 elim 192
1376 insert 24
1377 intersect 12
1378 disin 84
1379 main 12
1380 SYSTEM 24
1381 END_SAMPLE 2.00
1382 BEGIN_SAMPLE 2.82
1383 END_SAMPLE 2.82
1384 */
1385static void write_hp_file(void)
1386{
1387 Int i, j;
1388 Int fd, res;
1389 Char *hp_file, *ps_file, *aux_file;
1390 Char* cmdfmt;
1391 Char* cmdbuf;
1392 Int cmdlen;
1393
1394 VGP_PUSHCC(VgpPrintHp);
1395
1396 // Open file
1397 hp_file = make_filename( base_dir, ".hp" );
1398 ps_file = make_filename( base_dir, ".ps" );
1399 aux_file = make_filename( base_dir, ".aux" );
1400 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1401 VKI_S_IRUSR|VKI_S_IWUSR);
1402 if (fd < 0) {
1403 file_err( hp_file );
1404 VGP_POPCC(VgpPrintHp);
1405 return;
1406 }
1407
1408 // File header, including command line
1409 SPRINTF(buf, "JOB \"");
1410 for (i = 0; i < VG_(client_argc); i++)
1411 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1412 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1413 "DATE \"\"\n"
1414 "SAMPLE_UNIT \"ms\"\n"
1415 "VALUE_UNIT \"bytes\"\n", ms_interval);
1416
1417 // Censi
1418 for (i = 0; i < curr_census; i++) {
1419 Census* census = & censi[i];
1420
1421 // Census start
1422 SPRINTF(buf, "MARK %d.0\n"
1423 "BEGIN_SAMPLE %d.0\n",
1424 census->ms_time, census->ms_time);
1425
1426 // Heap -----------------------------------------------------------
1427 if (clo_heap) {
1428 // Print all the significant XPts from that census
1429 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1430 // Grab the jth top-XPt
1431 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
1432 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->eip, buf2, 16)) {
1433 VG_(sprintf)(buf2, "???");
1434 }
1435 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->eip,
1436 clean_fnname(buf3, buf2), xtree_snapshot->space);
1437 }
1438
1439 // Remaining heap block alloc points, combined
1440 if (census->others_space > 0)
1441 SPRINTF(buf, "other %d\n", census->others_space);
1442 }
1443
1444 // Heap admin -----------------------------------------------------
1445 if (clo_heap_admin > 0 && census->heap_admin_space)
1446 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1447
1448 // Stack(s) -------------------------------------------------------
1449 if (clo_stacks)
1450 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1451
1452 // Census end
1453 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1454 }
1455
1456 // Close file
njnca82cc02004-11-22 17:18:48 +00001457 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001458 VG_(close)(fd);
1459
1460 // Attempt to convert file using hp2ps
1461 cmdfmt = "%s/hp2ps -c -t1 %s";
1462 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1463 + VG_(strlen)(cmdfmt);
1464 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1465 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1466 res = VG_(system)(cmdbuf);
1467 VG_(free)(cmdbuf);
1468 if (res != 0) {
1469 VG_(message)(Vg_UserMsg,
1470 "Conversion to PostScript failed. Try converting manually.");
1471 } else {
1472 // remove the .hp and .aux file
1473 VG_(unlink)(hp_file);
1474 VG_(unlink)(aux_file);
1475 }
1476
1477 VG_(free)(hp_file);
1478 VG_(free)(ps_file);
1479 VG_(free)(aux_file);
1480
1481 VGP_POPCC(VgpPrintHp);
1482}
1483
1484/*------------------------------------------------------------*/
1485/*--- Writing the XPt text/HTML file ---*/
1486/*------------------------------------------------------------*/
1487
1488static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1489{
1490 int i, len, space;
1491
1492 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1493 len = VG_(strlen)(xbuf);
1494 space = field_width - len;
1495 if (space < 0) space = 0; /* Allow for v. small field_width */
1496 i = len;
1497
1498 /* Right justify in field */
1499 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1500 for (i = 0; i < space; i++) xbuf[i] = ' ';
1501}
1502
1503// Nb: uses a static buffer, each call trashes the last string returned.
1504static Char* make_perc(ULong spacetime, ULong total_spacetime)
1505{
1506 static Char mbuf[32];
1507
1508 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001509 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001510 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1511 return mbuf;
1512}
1513
1514// Nb: passed in XPt is a lower-level XPt; %eips are grabbed from
1515// bottom-to-top of XCon, and then printed in the reverse order.
1516static UInt pp_XCon(Int fd, XPt* xpt)
1517{
1518 Addr rev_eips[clo_depth+1];
1519 Int i = 0;
1520 Int n = 0;
1521 Bool is_HTML = ( XHTML == clo_format );
1522 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1523 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1524
njnca82cc02004-11-22 17:18:48 +00001525 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001526
1527 while (True) {
1528 rev_eips[i] = xpt->eip;
1529 n++;
1530 if (alloc_xpt == xpt->parent) break;
1531 i++;
1532 xpt = xpt->parent;
1533 }
1534
1535 for (i = n-1; i >= 0; i--) {
1536 // -1 means point to calling line
1537 VG_(describe_eip)(rev_eips[i]-1, buf2, BUF_LEN);
1538 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1539 }
1540
1541 return n;
1542}
1543
1544// Important point: for HTML, each XPt must be identified uniquely for the
1545// HTML links to all match up correctly. Using xpt->eip is not
1546// sufficient, because function pointers mean that you can call more than
1547// one other function from a single code location. So instead we use the
1548// address of the xpt struct itself, which is guaranteed to be unique.
1549
1550static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1551 ULong total_spacetime)
1552{
1553 UInt i;
1554 XPt *xpt, *child;
1555 UInt L = 0;
1556 UInt c1 = 1;
1557 UInt c2 = 0;
1558 ULong sum = 0;
1559 UInt n;
1560 Char *eip_desc, *perc;
1561 Bool is_HTML = ( XHTML == clo_format );
1562 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1563 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1564 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1565 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1566 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1567 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1568 Char* end_hr = ( is_HTML ? "<hr>" :
1569 "=================================" );
1570 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1571
nethercote43a15ce2004-08-30 19:15:12 +00001572 if (total_spacetime == 0) {
1573 SPRINTF(buf, "(No heap memory allocated)\n");
1574 return;
1575 }
1576
1577
nethercotec9f36922004-02-14 16:40:02 +00001578 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1579
1580 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001581 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001582 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001583
nethercote43a15ce2004-08-30 19:15:12 +00001584 // Check that the sum of all children .exact_ST_dbld fields equals
1585 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001586 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001587 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001588 } else {
1589 sum = 0;
1590 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001591 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001592 }
njnca82cc02004-11-22 17:18:48 +00001593 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001594 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001595 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001596 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001597// tl_assert(sum <= xpt->exact_ST_dbld);
1598// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001599// if (sum != xpt->exact_ST_dbld) {
1600// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001601// }
1602 }
1603
1604 if (xpt == alloc_xpt) {
1605 SPRINTF(buf, "Heap allocation functions accounted for "
1606 "%s of measured spacetime%s\n",
1607 make_perc(heap_spacetime, total_spacetime), maybe_br);
1608 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001609 // Remember: exact_ST_dbld is space.time *doubled*
1610 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001611 if (is_HTML) {
1612 SPRINTF(buf, "<a name=\"b%x\"></a>"
1613 "Context accounted for "
1614 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1615 xpt, xpt, perc);
1616 } else {
1617 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1618 perc);
1619 }
1620 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001621 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001622 }
1623
nethercote43a15ce2004-08-30 19:15:12 +00001624 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001625 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001626 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001627
1628 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1629 for (i = 0; i < xpt->n_children; i++) {
1630 child = xpt->children[i];
1631
1632 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001633 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001634 UInt n_insig = xpt->n_children - i;
1635 Char* s = ( n_insig == 1 ? "" : "s" );
1636 Char* and = ( 0 == i ? "" : "and " );
1637 Char* other = ( 0 == i ? "" : "other " );
1638 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1639 maybe_li, and, n_insig, other, s, maybe_fli);
1640 break;
1641 }
1642
nethercote43a15ce2004-08-30 19:15:12 +00001643 // Remember: exact_ST_dbld is space.time *doubled*
1644 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001645 eip_desc = VG_(describe_eip)(child->eip-1, buf2, BUF_LEN);
1646 if (is_HTML) {
1647 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1648
1649 if (child->n_children > 0) {
1650 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1651 } else {
1652 SPRINTF(buf, "%s", perc);
1653 }
1654 SPRINTF(buf, ": %s\n", eip_desc);
1655 } else {
1656 SPRINTF(buf, " %6s: %s\n\n", perc, eip_desc);
1657 }
1658
1659 if (child->n_children > 0) {
1660 enqueue(q, (void*)child);
1661 c2++;
1662 }
1663 }
1664 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1665 c1--;
1666
1667 // Putting markers between levels of the structure:
1668 // c1 tracks how many to go on this level, c2 tracks how many we've
1669 // queued up for the next level while finishing off this level.
1670 // When c1 gets to zero, we've changed levels, so print a marker,
1671 // move c2 into c1, and zero c2.
1672 if (0 == c1) {
1673 L++;
1674 c1 = c2;
1675 c2 = 0;
1676 if (! is_empty_queue(q) ) { // avoid empty one at end
1677 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1678 }
1679 } else {
1680 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1681 }
1682 }
1683 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1684 "%s value for more.\n", end_hr, depth);
1685}
1686
1687static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1688 ULong total_spacetime)
1689{
1690 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001691
nethercotec9f36922004-02-14 16:40:02 +00001692 enqueue(q, xpt);
1693 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1694 destruct_queue(q);
1695}
1696
1697static void
1698write_text_file(ULong total_ST, ULong heap_ST)
1699{
1700 Int fd, i;
1701 Char* text_file;
1702 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1703
1704 VGP_PUSHCC(VgpPrintXPts);
1705
1706 // Open file
1707 text_file = make_filename( base_dir,
1708 ( XText == clo_format ? ".txt" : ".html" ) );
1709
1710 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1711 VKI_S_IRUSR|VKI_S_IWUSR);
1712 if (fd < 0) {
1713 file_err( text_file );
1714 VGP_POPCC(VgpPrintXPts);
1715 return;
1716 }
1717
1718 // Header
1719 if (XHTML == clo_format) {
1720 SPRINTF(buf, "<html>\n"
1721 "<head>\n"
1722 "<title>%s</title>\n"
1723 "</head>\n"
1724 "<body>\n",
1725 text_file);
1726 }
1727
1728 // Command line
1729 SPRINTF(buf, "Command: ");
1730 for (i = 0; i < VG_(client_argc); i++)
1731 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1732 SPRINTF(buf, "\n%s\n", maybe_p);
1733
1734 if (clo_heap)
1735 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1736
njnca82cc02004-11-22 17:18:48 +00001737 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001738 VG_(close)(fd);
1739
1740 VGP_POPCC(VgpPrintXPts);
1741}
1742
1743/*------------------------------------------------------------*/
1744/*--- Finalisation ---*/
1745/*------------------------------------------------------------*/
1746
1747static void
1748print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1749 ULong stack_ST)
1750{
1751 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1752
1753 // Heap --------------------------------------------------------------
1754 if (clo_heap)
1755 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001756 ( 0 == total_ST ? (Char*)"(n/a)"
1757 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001758
1759 // Heap admin --------------------------------------------------------
1760 if (clo_heap_admin)
1761 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001762 ( 0 == total_ST ? (Char*)"(n/a)"
1763 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001764
njnca82cc02004-11-22 17:18:48 +00001765 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001766
1767 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001768 if (clo_stacks) {
njnca82cc02004-11-22 17:18:48 +00001769 tl_assert(0 != total_ST);
nethercotec9f36922004-02-14 16:40:02 +00001770 VG_(message)(Vg_UserMsg, "stack(s): %s",
nethercote43a15ce2004-08-30 19:15:12 +00001771 make_perc(stack_ST, total_ST) );
1772 }
nethercotec9f36922004-02-14 16:40:02 +00001773
1774 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001775 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001776 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1777 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1778 n_zero_allocs * 100 / n_allocs );
1779 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1780 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1781 n_xpts*sizeof(XPt));
1782 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1783 n_bot_xpts * 100 / n_xpts);
1784 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1785 alloc_xpt->n_children * 100 / n_xpts);
1786 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1787 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1788 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1789 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1790 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1791 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1792 }
1793}
1794
njn26f02512004-11-22 18:33:15 +00001795void TL_(fini)(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001796{
1797 ULong total_ST = 0;
1798 ULong heap_ST = 0;
1799 ULong heap_admin_ST = 0;
1800 ULong stack_ST = 0;
1801
1802 // Do a final (empty) sample to show program's end
1803 hp_census();
1804
1805 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001806 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001807 total_ST = heap_ST + heap_admin_ST + stack_ST;
1808 write_hp_file ( );
1809 write_text_file( total_ST, heap_ST );
1810 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1811}
1812
njn26f02512004-11-22 18:33:15 +00001813VG_DETERMINE_INTERFACE_VERSION(TL_(pre_clo_init), 0)
nethercotec9f36922004-02-14 16:40:02 +00001814
1815/*--------------------------------------------------------------------*/
1816/*--- end ms_main.c ---*/
1817/*--------------------------------------------------------------------*/
1818