blob: ec8ebeb70424de9e0b0bae5d41aa5cc667b89baa [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
njn53612422005-03-12 16:22:54 +000010 Copyright (C) 2003-2005 Nicholas Nethercote
njn2bc10122005-05-08 02:10:27 +000011 njn@valgrind.org
nethercotec9f36922004-02-14 16:40:02 +000012
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"
njnea27e462005-05-31 02:38:09 +000038#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +000039#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +000040#include "pub_tool_libcbase.h"
njn717cde52005-05-10 02:47:21 +000041#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000042#include "pub_tool_options.h"
njn31513b42005-06-01 03:09:59 +000043#include "pub_tool_profile.h"
njn717cde52005-05-10 02:47:21 +000044#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000045#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000046#include "pub_tool_tooliface.h"
nethercotec9f36922004-02-14 16:40:02 +000047
48#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
49
50/*------------------------------------------------------------*/
51/*--- Overview of operation ---*/
52/*------------------------------------------------------------*/
53
54// Heap blocks are tracked, and the amount of space allocated by various
55// contexts (ie. lines of code, more or less) is also tracked.
56// Periodically, a census is taken, and the amount of space used, at that
57// point, by the most significant (highly allocating) contexts is recorded.
58// Census start off frequently, but are scaled back as the program goes on,
59// so that there are always a good number of them. At the end, overall
60// spacetimes for different contexts (of differing levels of precision) is
61// calculated, the graph is printed, and the text giving spacetimes for the
62// increasingly precise contexts is given.
63//
64// Measures the following:
65// - heap blocks
66// - heap admin bytes
67// - stack(s)
68// - code (code segments loaded at startup, and loaded with mmap)
69// - data (data segments loaded at startup, and loaded/created with mmap,
70// and brk()d segments)
71
72/*------------------------------------------------------------*/
73/*--- Main types ---*/
74/*------------------------------------------------------------*/
75
76// An XPt represents an "execution point", ie. a code address. Each XPt is
77// part of a tree of XPts (an "execution tree", or "XTree"). Each
78// top-to-bottom path through an XTree gives an execution context ("XCon"),
79// and is equivalent to a traditional Valgrind ExeContext.
80//
81// The XPt at the top of an XTree (but below "alloc_xpt") is called a
82// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
83// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
84// bottom-XPTs in that XTree.
85//
86// All XCons have the same top-XPt, "alloc_xpt", which represents all
87// allocation functions like malloc(). It's a bit of a fake XPt, though,
88// and is only used because it makes some of the code simpler.
89//
90// XTrees are bi-directional.
91//
92// > parent < Example: if child1() calls parent() and child2()
93// / | \ also calls parent(), and parent() calls malloc(),
94// | / \ | the XTree will look like this.
95// | v v |
96// child1 child2
97
98typedef struct _XPt XPt;
99
100struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000101 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000102
103 // Bottom-XPts: space for the precise context.
104 // Other XPts: space of all the descendent bottom-XPts.
105 // Nb: this value goes up and down as the program executes.
106 UInt curr_space;
107
108 // An approximate space.time calculation used along the way for selecting
109 // which contexts to include at each census point.
110 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000111 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000112
nethercote43a15ce2004-08-30 19:15:12 +0000113 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000114 // used in the results.
115 // Note that it is *doubled*, to avoid rounding errors.
116 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000117 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000118
119 // n_children and max_children are integers; a very big program might
120 // have more than 65536 allocation points (Konqueror startup has 1800).
121 XPt* parent; // pointer to parent XPt
122 UInt n_children; // number of children
123 UInt max_children; // capacity of children array
124 XPt** children; // pointers to children XPts
125};
126
127// Each census snapshots the most significant XTrees, each XTree having a
128// top-XPt as its root. The 'curr_space' element for each XPt is recorded
129// in the snapshot. The snapshot contains all the XTree's XPts, not in a
130// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000131// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000132//
133// Graph resolution, x-axis: no point having more than about 200 census
134// x-points; you can't see them on the graph. Therefore:
135//
136// - do a census every 1 ms for first 200 --> 200, all (200 ms)
137// - halve (drop half of them) --> 100, every 2nd (200 ms)
138// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
139// - halve --> 100, every 4th (400 ms)
140// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
141// - etc.
142//
143// This isn't exactly right, because we actually drop (N/2)-1 when halving,
144// but it shows the basic idea.
145
146#define MAX_N_CENSI 200 // Keep it even, for simplicity
147
148// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
149// bands, rest get lumped into OTHERS. I only print the top N
150// (cumulative-so-far space-time) at each point. N should be a bit bigger
151// than 19 in case the cumulative space-time doesn't fit with the eventual
152// space-time computed by hp2ps (but it should be close if the samples are
153// evenly spread, since hp2ps does an approximate per-band space-time
154// calculation that just sums the totals; ie. it assumes all samples are
155// the same distance apart).
156
157#define MAX_SNAPSHOTS 32
158
159typedef
160 struct {
161 XPt* xpt;
162 UInt space;
163 }
164 XPtSnapshot;
165
166// An XTree snapshot is stored as an array of of XPt snapshots.
167typedef XPtSnapshot* XTreeSnapshot;
168
169typedef
170 struct {
171 Int ms_time; // Int: must allow -1
172 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
173 UInt others_space;
174 UInt heap_admin_space;
175 UInt stacks_space;
176 }
177 Census;
178
179// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
180// which is a foothold into the XCon at which it was allocated. From
181// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
182// decremented (at deallocation).
183//
184// Nb: first two fields must match core's VgHashNode.
185typedef
186 struct _HP_Chunk {
187 struct _HP_Chunk* next;
188 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000189 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000190 XPt* where; // Where allocated; bottom-XPt
191 }
192 HP_Chunk;
193
194/*------------------------------------------------------------*/
195/*--- Profiling events ---*/
196/*------------------------------------------------------------*/
197
198typedef
199 enum {
200 VgpGetXPt = VgpFini+1,
201 VgpGetXPtSearch,
202 VgpCensus,
203 VgpCensusHeap,
204 VgpCensusSnapshot,
205 VgpCensusTreeSize,
206 VgpUpdateXCon,
207 VgpCalcSpacetime2,
208 VgpPrintHp,
209 VgpPrintXPts,
210 }
njn4be0a692004-11-22 18:10:36 +0000211 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000212
213/*------------------------------------------------------------*/
214/*--- Statistics ---*/
215/*------------------------------------------------------------*/
216
217// Konqueror startup, to give an idea of the numbers involved with a biggish
218// program, with default depth:
219//
220// depth=3 depth=40
221// - 310,000 allocations
222// - 300,000 frees
223// - 15,000 XPts 800,000 XPts
224// - 1,800 top-XPts
225
226static UInt n_xpts = 0;
227static UInt n_bot_xpts = 0;
228static UInt n_allocs = 0;
229static UInt n_zero_allocs = 0;
230static UInt n_frees = 0;
231static UInt n_children_reallocs = 0;
232static UInt n_snapshot_frees = 0;
233
234static UInt n_halvings = 0;
235static UInt n_real_censi = 0;
236static UInt n_fake_censi = 0;
237static UInt n_attempted_censi = 0;
238
239/*------------------------------------------------------------*/
240/*--- Globals ---*/
241/*------------------------------------------------------------*/
242
243#define FILENAME_LEN 256
244
245#define SPRINTF(zz_buf, fmt, args...) \
246 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
247 VG_(write)(fd, (void*)zz_buf, len); \
248 } while (0)
249
250#define BUF_LEN 1024 // general purpose
251static Char buf [BUF_LEN];
252static Char buf2[BUF_LEN];
253static Char buf3[BUF_LEN];
254
nethercote8b5f40c2004-11-02 13:29:50 +0000255static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000256
257static VgHashTable malloc_list = NULL; // HP_Chunks
258
259static UInt n_heap_blocks = 0;
260
njn51d827b2005-05-09 01:02:08 +0000261// Current directory at startup.
262static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000263
264#define MAX_ALLOC_FNS 32 // includes the builtin ones
265
nethercotec7469182004-05-11 09:21:08 +0000266// First few filled in, rest should be zeroed. Zero-terminated vector.
267static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000268static Char* alloc_fns[MAX_ALLOC_FNS] = {
269 "malloc",
270 "operator new(unsigned)",
271 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000272 "operator new(unsigned, std::nothrow_t const&)",
273 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000274 "__builtin_new",
275 "__builtin_vec_new",
276 "calloc",
277 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000278 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000279};
280
281
282/*------------------------------------------------------------*/
283/*--- Command line args ---*/
284/*------------------------------------------------------------*/
285
286#define MAX_DEPTH 50
287
288typedef
289 enum {
290 XText, XHTML,
291 }
292 XFormat;
293
294static Bool clo_heap = True;
295static UInt clo_heap_admin = 8;
296static Bool clo_stacks = True;
297static Bool clo_depth = 3;
298static XFormat clo_format = XText;
299
njn51d827b2005-05-09 01:02:08 +0000300static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000301{
njn45270a22005-03-27 01:00:11 +0000302 VG_BOOL_CLO(arg, "--heap", clo_heap)
303 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000304
njn45270a22005-03-27 01:00:11 +0000305 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
306 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000307
308 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
309 alloc_fns[n_alloc_fns] = & arg[11];
310 n_alloc_fns++;
311 if (n_alloc_fns >= MAX_ALLOC_FNS) {
312 VG_(printf)("Too many alloc functions specified, sorry");
313 VG_(bad_option)(arg);
314 }
315 }
316
317 else if (VG_CLO_STREQ(arg, "--format=text"))
318 clo_format = XText;
319 else if (VG_CLO_STREQ(arg, "--format=html"))
320 clo_format = XHTML;
321
322 else
323 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000324
nethercotec9f36922004-02-14 16:40:02 +0000325 return True;
326}
327
njn51d827b2005-05-09 01:02:08 +0000328static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000329{
330 VG_(printf)(
331" --heap=no|yes profile heap blocks [yes]\n"
332" --heap-admin=<number> average admin bytes per heap block [8]\n"
333" --stacks=no|yes profile stack(s) [yes]\n"
334" --depth=<number> depth of contexts [3]\n"
335" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
336" --format=text|html format of textual output [text]\n"
337 );
338 VG_(replacement_malloc_print_usage)();
339}
340
njn51d827b2005-05-09 01:02:08 +0000341static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000342{
343 VG_(replacement_malloc_print_debug_usage)();
344}
345
346/*------------------------------------------------------------*/
347/*--- Execution contexts ---*/
348/*------------------------------------------------------------*/
349
350// Fake XPt representing all allocation functions like malloc(). Acts as
351// parent node to all top-XPts.
352static XPt* alloc_xpt;
353
354// Cheap allocation for blocks that never need to be freed. Saves about 10%
355// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000356static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000357{
358 static Addr hp = 0; // current heap pointer
359 static Addr hp_lim = 0; // maximum usable byte in current block
360
361 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
362
363 if (hp + n_bytes > hp_lim) {
364 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
365 hp_lim = hp + SUPERBLOCK_SIZE - 1;
366 }
367
368 hp += n_bytes;
369
370 return (void*)(hp - n_bytes);
371}
372
373
374
njnd01fef72005-03-25 23:35:48 +0000375static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000376{
377 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000378 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000379
nethercote43a15ce2004-08-30 19:15:12 +0000380 xpt->curr_space = 0;
381 xpt->approx_ST = 0;
382 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000383
384 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000385
386 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000387 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000388
389 xpt->n_children = 0;
390
391 // If a bottom-XPt, don't allocate space for children. This can be 50%
392 // or more, although it tends to drop as --depth increases (eg. 10% for
393 // konqueror with --depth=20).
394 if ( is_bottom ) {
395 xpt->max_children = 0;
396 xpt->children = NULL;
397 n_bot_xpts++;
398 } else {
399 xpt->max_children = 4;
400 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
401 }
402
403 // Update statistics
404 n_xpts++;
405
406 return xpt;
407}
408
njnd01fef72005-03-25 23:35:48 +0000409static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000410{
411 Int i;
412
njnd01fef72005-03-25 23:35:48 +0000413 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000414 for (i = 0; i < n_alloc_fns; i++) {
415 if (VG_STREQ(buf, alloc_fns[i]))
416 return True;
417 }
418 }
419 return False;
420}
421
422// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
423// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
424// to ensure this in certain cases. See comments below.
425static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
426{
njnd01fef72005-03-25 23:35:48 +0000427 // Static to minimise stack size. +1 for added ~0 IP
428 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000429
430 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000431 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000432 UInt overestimate;
433 Bool reached_bottom;
434
435 VGP_PUSHCC(VgpGetXPt);
436
437 // Want at least clo_depth non-alloc-fn entries in the snapshot.
438 // However, because we have 1 or more (an unknown number, at this point)
439 // alloc-fns ignored, we overestimate the size needed for the stack
440 // snapshot. Then, if necessary, we repeatedly increase the size until
441 // it is enough.
442 overestimate = 2;
443 while (True) {
njnd01fef72005-03-25 23:35:48 +0000444 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000445
njnd01fef72005-03-25 23:35:48 +0000446 // Now we add a dummy "unknown" IP at the end. This is only used if we
447 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000448 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
449 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000450 // the parent's approx_ST wouldn't be equal [or almost equal] to the
451 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000452 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000453
njnd01fef72005-03-25 23:35:48 +0000454 // Skip over alloc functions in ips[].
455 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000456
457 // Must be at least one alloc function, unless client used
458 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000459 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000460
461 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000462 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000463 overestimate += 2;
464 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000465 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000466 } else {
467 break;
468 }
469 }
470 A = L;
njnd01fef72005-03-25 23:35:48 +0000471 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000472 reached_bottom = False;
473
njnd01fef72005-03-25 23:35:48 +0000474 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000475
476 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000477 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000478 while (True) {
njnd01fef72005-03-25 23:35:48 +0000479 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000480 // XXX: linear search, ugh -- about 10% of time for konqueror startup
481 // XXX: tried cacheing last result, only hit about 4% for konqueror
482 // Nb: this search hits about 98% of the time for konqueror
483 VGP_PUSHCC(VgpGetXPtSearch);
484
485 // If we've searched/added deep enough, or run out of EIPs, this is
486 // the bottom XPt.
487 if (L - A + 1 == clo_depth || L == B)
488 reached_bottom = True;
489
490 nC = 0;
491 while (True) {
492 if (nC == xpt->n_children) {
493 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000494 tl_assert(xpt->max_children != 0);
495 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000496 // Expand 'children' if necessary
497 if (xpt->n_children == xpt->max_children) {
498 xpt->max_children *= 2;
499 xpt->children = VG_(realloc)( xpt->children,
500 xpt->max_children * sizeof(XPt*) );
501 n_children_reallocs++;
502 }
njnd01fef72005-03-25 23:35:48 +0000503 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000504 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000505 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000506 break;
507 }
njnd01fef72005-03-25 23:35:48 +0000508 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000509 nC++; // keep looking
510 }
511 VGP_POPCC(VgpGetXPtSearch);
512
513 // Return found/built bottom-XPt.
514 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000515 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000516 VGP_POPCC(VgpGetXPt);
517 return xpt->children[nC];
518 }
519
520 // Descend to next level in XTree, the newly found/built non-bottom-XPt
521 xpt = xpt->children[nC];
522 L++;
523 }
524}
525
526// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
527static void update_XCon(XPt* xpt, Int space_delta)
528{
529 VGP_PUSHCC(VgpUpdateXCon);
530
njnca82cc02004-11-22 17:18:48 +0000531 tl_assert(True == clo_heap);
532 tl_assert(0 != space_delta);
533 tl_assert(NULL != xpt);
534 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000535
536 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000537 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000538 xpt->curr_space += space_delta;
539 xpt = xpt->parent;
540 }
njnca82cc02004-11-22 17:18:48 +0000541 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000542 alloc_xpt->curr_space += space_delta;
543
544 VGP_POPCC(VgpUpdateXCon);
545}
546
547// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000548static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000549{
550 XPt* xpt1 = *(XPt**)n1;
551 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000552 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000553}
554
nethercote43a15ce2004-08-30 19:15:12 +0000555static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000556{
557 XPt* xpt1 = *(XPt**)n1;
558 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000559 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000560}
561
562
563/*------------------------------------------------------------*/
564/*--- A generic Queue ---*/
565/*------------------------------------------------------------*/
566
567typedef
568 struct {
569 UInt head; // Index of first entry
570 UInt tail; // Index of final+1 entry, ie. next free slot
571 UInt max_elems;
572 void** elems;
573 }
574 Queue;
575
576static Queue* construct_queue(UInt size)
577{
578 UInt i;
579 Queue* q = VG_(malloc)(sizeof(Queue));
580 q->head = 0;
581 q->tail = 0;
582 q->max_elems = size;
583 q->elems = VG_(malloc)(size * sizeof(void*));
584 for (i = 0; i < size; i++)
585 q->elems[i] = NULL;
586
587 return q;
588}
589
590static void destruct_queue(Queue* q)
591{
592 VG_(free)(q->elems);
593 VG_(free)(q);
594}
595
596static void shuffle(Queue* dest_q, void** old_elems)
597{
598 UInt i, j;
599 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
600 dest_q->elems[i] = old_elems[j];
601 dest_q->head = 0;
602 dest_q->tail = i;
603 for ( ; i < dest_q->max_elems; i++)
604 dest_q->elems[i] = NULL; // paranoia
605}
606
607// Shuffles elements down. If not enough slots free, increase size. (We
608// don't wait until we've completely run out of space, because there could
609// be lots of shuffling just before that point which would be slow.)
610static void adjust(Queue* q)
611{
612 void** old_elems;
613
njnca82cc02004-11-22 17:18:48 +0000614 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000615 if (q->head < 10) {
616 old_elems = q->elems;
617 q->max_elems *= 2;
618 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
619 shuffle(q, old_elems);
620 VG_(free)(old_elems);
621 } else {
622 shuffle(q, q->elems);
623 }
624}
625
626static void enqueue(Queue* q, void* elem)
627{
628 if (q->tail == q->max_elems)
629 adjust(q);
630 q->elems[q->tail++] = elem;
631}
632
633static Bool is_empty_queue(Queue* q)
634{
635 return (q->head == q->tail);
636}
637
638static void* dequeue(Queue* q)
639{
640 if (is_empty_queue(q))
641 return NULL; // Queue empty
642 else
643 return q->elems[q->head++];
644}
645
646/*------------------------------------------------------------*/
647/*--- malloc() et al replacement wrappers ---*/
648/*------------------------------------------------------------*/
649
650static __inline__
651void add_HP_Chunk(HP_Chunk* hc)
652{
653 n_heap_blocks++;
654 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
655}
656
657static __inline__
658HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
659{
nethercote3d6b6112004-11-04 16:39:43 +0000660 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000661 (VgHashNode***)prev_chunks_next_ptr );
662}
663
664static __inline__
665void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
666{
njnca82cc02004-11-22 17:18:48 +0000667 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000668 n_heap_blocks--;
669 *prev_chunks_next_ptr = hc->next;
670}
671
672// Forward declaration
673static void hp_census(void);
674
nethercote159dfef2004-09-13 13:27:30 +0000675static
njn57735902004-11-25 18:04:54 +0000676void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
677 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000678{
679 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000680 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000681 if (size < 0) return NULL;
682
683 VGP_PUSHCC(VgpCliMalloc);
684
685 // Update statistics
686 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000687 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000688
nethercote57e36b32004-07-10 14:56:28 +0000689 // Allocate and zero if necessary
690 if (!p) {
691 p = VG_(cli_malloc)( align, size );
692 if (!p) {
693 VGP_POPCC(VgpCliMalloc);
694 return NULL;
695 }
696 if (is_zeroed) VG_(memset)(p, 0, size);
697 }
698
699 // Make new HP_Chunk node, add to malloclist
700 hc = VG_(malloc)(sizeof(HP_Chunk));
701 hc->size = size;
702 hc->data = (Addr)p;
703 hc->where = NULL; // paranoia
704 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000705 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000706 if (0 != size)
707 update_XCon(hc->where, size);
708 }
709 add_HP_Chunk( hc );
710
711 // do a census!
712 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000713
714 VGP_POPCC(VgpCliMalloc);
715 return p;
716}
717
718static __inline__
719void die_block ( void* p, Bool custom_free )
720{
nethercote57e36b32004-07-10 14:56:28 +0000721 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000722
723 VGP_PUSHCC(VgpCliMalloc);
724
725 // Update statistics
726 n_frees++;
727
nethercote57e36b32004-07-10 14:56:28 +0000728 // Remove HP_Chunk from malloclist
729 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000730 if (hc == NULL)
731 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000732 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000733 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000734
735 if (clo_heap && hc->size != 0)
736 update_XCon(hc->where, -hc->size);
737
nethercote57e36b32004-07-10 14:56:28 +0000738 VG_(free)( hc );
739
740 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000741 if (!custom_free)
742 VG_(cli_free)( p );
743
nethercote57e36b32004-07-10 14:56:28 +0000744 // do a census!
745 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000746
nethercotec9f36922004-02-14 16:40:02 +0000747 VGP_POPCC(VgpCliMalloc);
748}
749
750
njn51d827b2005-05-09 01:02:08 +0000751static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000752{
njn57735902004-11-25 18:04:54 +0000753 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000754}
755
njn51d827b2005-05-09 01:02:08 +0000756static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000757{
njn57735902004-11-25 18:04:54 +0000758 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000759}
760
njn51d827b2005-05-09 01:02:08 +0000761static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000762{
njn57735902004-11-25 18:04:54 +0000763 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000764}
765
njn51d827b2005-05-09 01:02:08 +0000766static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000767{
njn57735902004-11-25 18:04:54 +0000768 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000769}
770
njn51d827b2005-05-09 01:02:08 +0000771static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000772{
njn57735902004-11-25 18:04:54 +0000773 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000774}
775
njn51d827b2005-05-09 01:02:08 +0000776static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000777{
778 die_block( p, /*custom_free*/False );
779}
780
njn51d827b2005-05-09 01:02:08 +0000781static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000782{
783 die_block( p, /*custom_free*/False);
784}
785
njn51d827b2005-05-09 01:02:08 +0000786static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000787{
788 die_block( p, /*custom_free*/False );
789}
790
njn51d827b2005-05-09 01:02:08 +0000791static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000792{
793 HP_Chunk* hc;
794 HP_Chunk** remove_handle;
795 Int i;
796 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000797 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000798 XPt *old_where, *new_where;
799
800 VGP_PUSHCC(VgpCliMalloc);
801
802 // First try and find the block.
803 hc = get_HP_Chunk ( p_old, &remove_handle );
804 if (hc == NULL) {
805 VGP_POPCC(VgpCliMalloc);
806 return NULL; // must have been a bogus free()
807 }
808
njnca82cc02004-11-22 17:18:48 +0000809 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000810 old_size = hc->size;
811
812 if (new_size <= old_size) {
813 // new size is smaller or same; block not moved
814 p_new = p_old;
815
816 } else {
817 // new size is bigger; make new block, copy shared contents, free old
818 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
819
820 for (i = 0; i < old_size; i++)
821 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
822
823 VG_(cli_free)(p_old);
824 }
825
826 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000827 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000828
829 // Update HP_Chunk
830 hc->data = (Addr)p_new;
831 hc->size = new_size;
832 hc->where = new_where;
833
834 // Update XPt curr_space fields
835 if (clo_heap) {
836 if (0 != old_size) update_XCon(old_where, -old_size);
837 if (0 != new_size) update_XCon(new_where, new_size);
838 }
839
840 // If block has moved, have to remove and reinsert in the malloclist
841 // (since the updated 'data' field is the hash lookup key).
842 if (p_new != p_old) {
843 remove_HP_Chunk(hc, remove_handle);
844 add_HP_Chunk(hc);
845 }
846
847 VGP_POPCC(VgpCliMalloc);
848 return p_new;
849}
850
851
852/*------------------------------------------------------------*/
853/*--- Taking a census ---*/
854/*------------------------------------------------------------*/
855
856static Census censi[MAX_N_CENSI];
857static UInt curr_census = 0;
858
859// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000860static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000861{
thughes4ad52d02004-06-27 17:37:21 +0000862 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000863 return False;
864}
865
866static UInt get_xtree_size(XPt* xpt, UInt ix)
867{
868 UInt i;
869
nethercote43a15ce2004-08-30 19:15:12 +0000870 // If no memory allocated at all, nothing interesting to record.
871 if (alloc_xpt->curr_space == 0) return 0;
872
873 // Ignore sub-XTrees that account for a miniscule fraction of current
874 // allocated space.
875 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000876 ix++;
877
878 // Count all (non-zero) descendent XPts
879 for (i = 0; i < xpt->n_children; i++)
880 ix = get_xtree_size(xpt->children[i], ix);
881 }
882 return ix;
883}
884
885static
886UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
887{
888 UInt i;
889
nethercote43a15ce2004-08-30 19:15:12 +0000890 // Structure of this function mirrors that of get_xtree_size().
891
892 if (alloc_xpt->curr_space == 0) return 0;
893
894 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000895 xtree_snapshot[ix].xpt = xpt;
896 xtree_snapshot[ix].space = xpt->curr_space;
897 ix++;
898
nethercotec9f36922004-02-14 16:40:02 +0000899 for (i = 0; i < xpt->n_children; i++)
900 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
901 }
902 return ix;
903}
904
905static UInt ms_interval;
906static UInt do_every_nth_census = 30;
907
908// Weed out half the censi; we choose those that represent the smallest
909// time-spans, because that loses the least information.
910//
911// Algorithm for N censi: We find the census representing the smallest
912// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
913// (It's (N/2)-1 because we never remove the first and last censi.)
914// We have to do this one census at a time, rather than finding the (N/2)-1
915// smallest censi in one hit, because when a census is removed, it's
916// neighbours immediately cover greater timespans. So it's N^2, but N only
917// equals 200, and this is only done every 100 censi, which is not too often.
918static void halve_censi(void)
919{
920 Int i, jp, j, jn, k;
921 Census* min_census;
922
923 n_halvings++;
924 if (VG_(clo_verbosity) > 1)
925 VG_(message)(Vg_UserMsg, "Halving censi...");
926
927 // Sets j to the index of the first not-yet-removed census at or after i
928 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000929 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000930
931 for (i = 2; i < MAX_N_CENSI; i += 2) {
932 // Find the censi representing the smallest timespan. The timespan
933 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
934 // censi A and B. We don't consider the first and last censi for
935 // removal.
936 Int min_span = 0x7fffffff;
937 Int min_j = 0;
938
939 // Initial triple: (prev, curr, next) == (jp, j, jn)
940 jp = 0;
941 FIND_CENSUS(1, j);
942 FIND_CENSUS(j+1, jn);
943 while (jn < MAX_N_CENSI) {
944 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000945 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000946 if (timespan < min_span) {
947 min_span = timespan;
948 min_j = j;
949 }
950 // Move on to next triple
951 jp = j;
952 j = jn;
953 FIND_CENSUS(jn+1, jn);
954 }
955 // We've found the least important census, now remove it
956 min_census = & censi[ min_j ];
957 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
958 n_snapshot_frees++;
959 VG_(free)(min_census->xtree_snapshots[k]);
960 min_census->xtree_snapshots[k] = NULL;
961 }
962 min_census->ms_time = -1;
963 }
964
965 // Slide down the remaining censi over the removed ones. The '<=' is
966 // because we are removing on (N/2)-1, rather than N/2.
967 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
968 FIND_CENSUS(j, j);
969 if (i != j) {
970 censi[i] = censi[j];
971 }
972 }
973 curr_census = i;
974
975 // Double intervals
976 ms_interval *= 2;
977 do_every_nth_census *= 2;
978
979 if (VG_(clo_verbosity) > 1)
980 VG_(message)(Vg_UserMsg, "...done");
981}
982
983// Take a census. Census time seems to be insignificant (usually <= 0 ms,
984// almost always <= 1ms) so don't have to worry about subtracting it from
985// running time in any way.
986//
987// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
988// 50ms!
989static void hp_census(void)
990{
991 static UInt ms_prev_census = 0;
992 static UInt ms_next_census = 0; // zero allows startup census
993
994 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000995 Census* census;
996
997 VGP_PUSHCC(VgpCensus);
998
999 // Only do a census if it's time
1000 ms_time = VG_(read_millisecond_timer)();
1001 ms_time_since_prev = ms_time - ms_prev_census;
1002 if (ms_time < ms_next_census) {
1003 n_fake_censi++;
1004 VGP_POPCC(VgpCensus);
1005 return;
1006 }
1007 n_real_censi++;
1008
1009 census = & censi[curr_census];
1010
1011 census->ms_time = ms_time;
1012
1013 // Heap: snapshot the K most significant XTrees -------------------
1014 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001015 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001016 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1017 ? alloc_xpt->n_children
1018 : MAX_SNAPSHOTS); // max out
1019
nethercote43a15ce2004-08-30 19:15:12 +00001020 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001021 // We *do not* do it for any non-top-XPTs.
1022 for (i = 0; i < alloc_xpt->n_children; i++) {
1023 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001024 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001025 }
nethercote43a15ce2004-08-30 19:15:12 +00001026 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001027 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001028 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001029
1030 VGP_PUSHCC(VgpCensusHeap);
1031
1032 // For each significant top-level XPt, record space info about its
1033 // entire XTree, in a single census entry.
1034 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1035 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001036 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001037 for (i = 0; i < K; i++) {
1038 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001039// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1040 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001041 VGP_PUSHCC(VgpCensusTreeSize);
1042 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1043 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001044
1045 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1046 // insignificant) then don't take any more snapshots.
1047 if (0 == xtree_size) break;
1048
1049 // Make array of the appropriate size (+1 for zero termination,
1050 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001051 census->xtree_snapshots[i] =
1052 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001053 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001054 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1055 (xtree_size+1) * sizeof(XPtSnapshot));
1056
1057 // Take space-snapshot: copy 'curr_space' for every XPt in the
1058 // XTree into the snapshot array, along with pointers to the XPts.
1059 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001060 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001061 // saves a lot of memory and up to 40% time with big --depth valus.
1062 VGP_PUSHCC(VgpCensusSnapshot);
1063 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1064 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001065 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001066 VGP_POPCC(VgpCensusSnapshot);
1067 }
1068// VG_(printf)("\n\n");
1069 // Zero-terminate 'xtree_snapshot' array
1070 census->xtree_snapshots[i] = NULL;
1071
1072 VGP_POPCC(VgpCensusHeap);
1073
1074 //VG_(printf)("printed %d censi\n", K);
1075
1076 // Lump the rest into a single "others" entry.
1077 census->others_space = 0;
1078 for (i = K; i < alloc_xpt->n_children; i++) {
1079 census->others_space += alloc_xpt->children[i]->curr_space;
1080 }
1081 }
1082
1083 // Heap admin -------------------------------------------------------
1084 if (clo_heap_admin > 0)
1085 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1086
1087 // Stack(s) ---------------------------------------------------------
1088 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001089 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001090 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001091 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001092 }
1093
1094 // Finish, update interval if necessary -----------------------------
1095 curr_census++;
1096 census = NULL; // don't use again now that curr_census changed
1097
1098 // Halve the entries, if our census table is full
1099 if (MAX_N_CENSI == curr_census) {
1100 halve_censi();
1101 }
1102
1103 // Take time for next census from now, rather than when this census
1104 // should have happened. Because, if there's a big gap due to a kernel
1105 // operation, there's no point doing catch-up censi every BB for a while
1106 // -- that would just give N censi at almost the same time.
1107 if (VG_(clo_verbosity) > 1) {
1108 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1109 VG_(read_millisecond_timer)() - ms_time );
1110 }
1111 ms_prev_census = ms_time;
1112 ms_next_census = ms_time + ms_interval;
1113 //ms_next_census += ms_interval;
1114
1115 //VG_(printf)("Next: %d ms\n", ms_next_census);
1116
1117 VGP_POPCC(VgpCensus);
1118}
1119
1120/*------------------------------------------------------------*/
1121/*--- Tracked events ---*/
1122/*------------------------------------------------------------*/
1123
nethercote8b5f40c2004-11-02 13:29:50 +00001124static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001125{
1126 sigstacks_space += len;
1127}
1128
nethercote8b5f40c2004-11-02 13:29:50 +00001129static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001130{
njnca82cc02004-11-22 17:18:48 +00001131 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001132 sigstacks_space -= len;
1133}
1134
1135/*------------------------------------------------------------*/
1136/*--- Client Requests ---*/
1137/*------------------------------------------------------------*/
1138
njn51d827b2005-05-09 01:02:08 +00001139static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001140{
1141 switch (argv[0]) {
1142 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001143 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001144 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001145 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001146 *ret = 0;
njn57735902004-11-25 18:04:54 +00001147 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001148 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001149 return True;
1150 }
1151 case VG_USERREQ__FREELIKE_BLOCK: {
1152 void* p = (void*)argv[1];
1153 *ret = 0;
1154 die_block( p, /*custom_free*/True );
1155 return True;
1156 }
1157 default:
1158 *ret = 0;
1159 return False;
1160 }
1161}
1162
1163/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001164/*--- Instrumentation ---*/
1165/*------------------------------------------------------------*/
1166
njn51d827b2005-05-09 01:02:08 +00001167static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1168 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001169{
sewardjd54babf2005-03-21 00:55:49 +00001170 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001171 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001172}
1173
1174/*------------------------------------------------------------*/
1175/*--- Spacetime recomputation ---*/
1176/*------------------------------------------------------------*/
1177
nethercote43a15ce2004-08-30 19:15:12 +00001178// Although we've been calculating space-time along the way, because the
1179// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001180// might not agree with what hp2ps sees, because we've thrown away some of
1181// the information. So recompute it at the scale that hp2ps sees, so we can
1182// confidently determine which contexts hp2ps will choose for displaying as
1183// distinct bands. This recomputation only happens to the significant ones
1184// that get printed in the .hp file, so it's cheap.
1185//
nethercote43a15ce2004-08-30 19:15:12 +00001186// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001187// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1188// where
1189// a[N] is the space at census N
1190// d(A,B) is the time interval between censi A and B
1191// and
1192// d(A,B) + d(B,C) == d(A,C)
1193//
1194// Key point: we can calculate the area for a census without knowing the
1195// previous or subsequent censi's space; because any over/underestimates
1196// for this census will be reversed in the next, balancing out. This is
1197// important, as getting the previous/next census entry for a particular
1198// AP is a pain with this data structure, but getting the prev/next
1199// census time is easy.
1200//
nethercote43a15ce2004-08-30 19:15:12 +00001201// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001202// The ULong* values are all running totals, hence the use of "+=" everywhere.
1203
1204// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001205static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001206 ULong* twice_heap_ST,
1207 ULong* twice_heap_admin_ST,
1208 ULong* twice_stack_ST)
1209{
1210 UInt i, j;
1211 XPtSnapshot* xpt_snapshot;
1212
1213 // Heap --------------------------------------------------------
1214 if (clo_heap) {
1215 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001216 // Compute total heap exact_ST_dbld for the entire XTree using only
1217 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001218 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1219
nethercote43a15ce2004-08-30 19:15:12 +00001220 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1221 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001222 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1223 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001224 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001225 }
1226 }
1227 *twice_heap_ST += d_t1_t2 * census->others_space;
1228 }
1229
1230 // Heap admin --------------------------------------------------
1231 if (clo_heap_admin > 0)
1232 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1233
1234 // Stack(s) ----------------------------------------------------
1235 if (clo_stacks)
1236 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1237}
1238
1239// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001240static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001241{
1242 UInt i, N = curr_census;
1243
1244 VGP_PUSHCC(VgpCalcSpacetime2);
1245
1246 *heap2 = 0;
1247 *heap_admin2 = 0;
1248 *stack2 = 0;
1249
1250 if (N <= 1)
1251 return;
1252
nethercote43a15ce2004-08-30 19:15:12 +00001253 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1254 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001255
1256 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001257 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1258 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001259 }
1260
nethercote43a15ce2004-08-30 19:15:12 +00001261 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1262 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001263 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1264 *heap2 /= 2;
1265 *heap_admin2 /= 2;
1266 *stack2 /= 2;
1267
1268 VGP_POPCC(VgpCalcSpacetime2);
1269}
1270
1271/*------------------------------------------------------------*/
1272/*--- Writing the graph file ---*/
1273/*------------------------------------------------------------*/
1274
1275static Char* make_filename(Char* dir, Char* suffix)
1276{
1277 Char* filename;
1278
1279 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1280 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1281 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1282
1283 return filename;
1284}
1285
1286// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1287static Char* clean_fnname(Char *d, Char* s)
1288{
1289 Char* dorig = d;
1290 while (*s) {
1291 if (' ' == *s) { *d = '%'; }
1292 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1293 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1294 else { *d = *s; };
1295 s++;
1296 d++;
1297 }
1298 *d = '\0';
1299 return dorig;
1300}
1301
1302static void file_err ( Char* file )
1303{
njn02bc4b82005-05-15 17:28:26 +00001304 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001305 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1306}
1307
1308/* Format, by example:
1309
1310 JOB "a.out -p"
1311 DATE "Fri Apr 17 11:43:45 1992"
1312 SAMPLE_UNIT "seconds"
1313 VALUE_UNIT "bytes"
1314 BEGIN_SAMPLE 0.00
1315 SYSTEM 24
1316 END_SAMPLE 0.00
1317 BEGIN_SAMPLE 1.00
1318 elim 180
1319 insert 24
1320 intersect 12
1321 disin 60
1322 main 12
1323 reduce 20
1324 SYSTEM 12
1325 END_SAMPLE 1.00
1326 MARK 1.50
1327 MARK 1.75
1328 MARK 1.80
1329 BEGIN_SAMPLE 2.00
1330 elim 192
1331 insert 24
1332 intersect 12
1333 disin 84
1334 main 12
1335 SYSTEM 24
1336 END_SAMPLE 2.00
1337 BEGIN_SAMPLE 2.82
1338 END_SAMPLE 2.82
1339 */
1340static void write_hp_file(void)
1341{
1342 Int i, j;
1343 Int fd, res;
1344 Char *hp_file, *ps_file, *aux_file;
1345 Char* cmdfmt;
1346 Char* cmdbuf;
1347 Int cmdlen;
1348
1349 VGP_PUSHCC(VgpPrintHp);
1350
1351 // Open file
1352 hp_file = make_filename( base_dir, ".hp" );
1353 ps_file = make_filename( base_dir, ".ps" );
1354 aux_file = make_filename( base_dir, ".aux" );
1355 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1356 VKI_S_IRUSR|VKI_S_IWUSR);
1357 if (fd < 0) {
1358 file_err( hp_file );
1359 VGP_POPCC(VgpPrintHp);
1360 return;
1361 }
1362
1363 // File header, including command line
1364 SPRINTF(buf, "JOB \"");
1365 for (i = 0; i < VG_(client_argc); i++)
1366 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1367 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1368 "DATE \"\"\n"
1369 "SAMPLE_UNIT \"ms\"\n"
1370 "VALUE_UNIT \"bytes\"\n", ms_interval);
1371
1372 // Censi
1373 for (i = 0; i < curr_census; i++) {
1374 Census* census = & censi[i];
1375
1376 // Census start
1377 SPRINTF(buf, "MARK %d.0\n"
1378 "BEGIN_SAMPLE %d.0\n",
1379 census->ms_time, census->ms_time);
1380
1381 // Heap -----------------------------------------------------------
1382 if (clo_heap) {
1383 // Print all the significant XPts from that census
1384 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1385 // Grab the jth top-XPt
1386 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001387 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001388 VG_(sprintf)(buf2, "???");
1389 }
njnd01fef72005-03-25 23:35:48 +00001390 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001391 clean_fnname(buf3, buf2), xtree_snapshot->space);
1392 }
1393
1394 // Remaining heap block alloc points, combined
1395 if (census->others_space > 0)
1396 SPRINTF(buf, "other %d\n", census->others_space);
1397 }
1398
1399 // Heap admin -----------------------------------------------------
1400 if (clo_heap_admin > 0 && census->heap_admin_space)
1401 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1402
1403 // Stack(s) -------------------------------------------------------
1404 if (clo_stacks)
1405 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1406
1407 // Census end
1408 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1409 }
1410
1411 // Close file
njnca82cc02004-11-22 17:18:48 +00001412 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001413 VG_(close)(fd);
1414
1415 // Attempt to convert file using hp2ps
1416 cmdfmt = "%s/hp2ps -c -t1 %s";
1417 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1418 + VG_(strlen)(cmdfmt);
1419 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1420 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1421 res = VG_(system)(cmdbuf);
1422 VG_(free)(cmdbuf);
1423 if (res != 0) {
1424 VG_(message)(Vg_UserMsg,
1425 "Conversion to PostScript failed. Try converting manually.");
1426 } else {
1427 // remove the .hp and .aux file
1428 VG_(unlink)(hp_file);
1429 VG_(unlink)(aux_file);
1430 }
1431
1432 VG_(free)(hp_file);
1433 VG_(free)(ps_file);
1434 VG_(free)(aux_file);
1435
1436 VGP_POPCC(VgpPrintHp);
1437}
1438
1439/*------------------------------------------------------------*/
1440/*--- Writing the XPt text/HTML file ---*/
1441/*------------------------------------------------------------*/
1442
1443static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1444{
1445 int i, len, space;
1446
1447 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1448 len = VG_(strlen)(xbuf);
1449 space = field_width - len;
1450 if (space < 0) space = 0; /* Allow for v. small field_width */
1451 i = len;
1452
1453 /* Right justify in field */
1454 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1455 for (i = 0; i < space; i++) xbuf[i] = ' ';
1456}
1457
1458// Nb: uses a static buffer, each call trashes the last string returned.
1459static Char* make_perc(ULong spacetime, ULong total_spacetime)
1460{
1461 static Char mbuf[32];
1462
1463 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001464 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001465 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1466 return mbuf;
1467}
1468
njnd01fef72005-03-25 23:35:48 +00001469// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001470// bottom-to-top of XCon, and then printed in the reverse order.
1471static UInt pp_XCon(Int fd, XPt* xpt)
1472{
njnd01fef72005-03-25 23:35:48 +00001473 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001474 Int i = 0;
1475 Int n = 0;
1476 Bool is_HTML = ( XHTML == clo_format );
1477 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1478 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1479
njnca82cc02004-11-22 17:18:48 +00001480 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001481
1482 while (True) {
njnd01fef72005-03-25 23:35:48 +00001483 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001484 n++;
1485 if (alloc_xpt == xpt->parent) break;
1486 i++;
1487 xpt = xpt->parent;
1488 }
1489
1490 for (i = n-1; i >= 0; i--) {
1491 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001492 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001493 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1494 }
1495
1496 return n;
1497}
1498
1499// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001500// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001501// sufficient, because function pointers mean that you can call more than
1502// one other function from a single code location. So instead we use the
1503// address of the xpt struct itself, which is guaranteed to be unique.
1504
1505static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1506 ULong total_spacetime)
1507{
1508 UInt i;
1509 XPt *xpt, *child;
1510 UInt L = 0;
1511 UInt c1 = 1;
1512 UInt c2 = 0;
1513 ULong sum = 0;
1514 UInt n;
njnd01fef72005-03-25 23:35:48 +00001515 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001516 Bool is_HTML = ( XHTML == clo_format );
1517 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1518 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1519 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1520 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1521 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1522 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1523 Char* end_hr = ( is_HTML ? "<hr>" :
1524 "=================================" );
1525 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1526
nethercote43a15ce2004-08-30 19:15:12 +00001527 if (total_spacetime == 0) {
1528 SPRINTF(buf, "(No heap memory allocated)\n");
1529 return;
1530 }
1531
1532
nethercotec9f36922004-02-14 16:40:02 +00001533 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1534
1535 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001536 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001537 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001538
nethercote43a15ce2004-08-30 19:15:12 +00001539 // Check that the sum of all children .exact_ST_dbld fields equals
1540 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001541 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001542 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001543 } else {
1544 sum = 0;
1545 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001546 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001547 }
njnca82cc02004-11-22 17:18:48 +00001548 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001549 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001550 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001551 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001552// tl_assert(sum <= xpt->exact_ST_dbld);
1553// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001554// if (sum != xpt->exact_ST_dbld) {
1555// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001556// }
1557 }
1558
1559 if (xpt == alloc_xpt) {
1560 SPRINTF(buf, "Heap allocation functions accounted for "
1561 "%s of measured spacetime%s\n",
1562 make_perc(heap_spacetime, total_spacetime), maybe_br);
1563 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001564 // Remember: exact_ST_dbld is space.time *doubled*
1565 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001566 if (is_HTML) {
1567 SPRINTF(buf, "<a name=\"b%x\"></a>"
1568 "Context accounted for "
1569 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1570 xpt, xpt, perc);
1571 } else {
1572 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1573 perc);
1574 }
1575 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001576 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001577 }
1578
nethercote43a15ce2004-08-30 19:15:12 +00001579 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001580 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001581 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001582
1583 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1584 for (i = 0; i < xpt->n_children; i++) {
1585 child = xpt->children[i];
1586
1587 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001588 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001589 UInt n_insig = xpt->n_children - i;
1590 Char* s = ( n_insig == 1 ? "" : "s" );
1591 Char* and = ( 0 == i ? "" : "and " );
1592 Char* other = ( 0 == i ? "" : "other " );
1593 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1594 maybe_li, and, n_insig, other, s, maybe_fli);
1595 break;
1596 }
1597
nethercote43a15ce2004-08-30 19:15:12 +00001598 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001599 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1600 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001601 if (is_HTML) {
1602 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1603
1604 if (child->n_children > 0) {
1605 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1606 } else {
1607 SPRINTF(buf, "%s", perc);
1608 }
njnd01fef72005-03-25 23:35:48 +00001609 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001610 } else {
njnd01fef72005-03-25 23:35:48 +00001611 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001612 }
1613
1614 if (child->n_children > 0) {
1615 enqueue(q, (void*)child);
1616 c2++;
1617 }
1618 }
1619 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1620 c1--;
1621
1622 // Putting markers between levels of the structure:
1623 // c1 tracks how many to go on this level, c2 tracks how many we've
1624 // queued up for the next level while finishing off this level.
1625 // When c1 gets to zero, we've changed levels, so print a marker,
1626 // move c2 into c1, and zero c2.
1627 if (0 == c1) {
1628 L++;
1629 c1 = c2;
1630 c2 = 0;
1631 if (! is_empty_queue(q) ) { // avoid empty one at end
1632 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1633 }
1634 } else {
1635 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1636 }
1637 }
1638 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1639 "%s value for more.\n", end_hr, depth);
1640}
1641
1642static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1643 ULong total_spacetime)
1644{
1645 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001646
nethercotec9f36922004-02-14 16:40:02 +00001647 enqueue(q, xpt);
1648 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1649 destruct_queue(q);
1650}
1651
1652static void
1653write_text_file(ULong total_ST, ULong heap_ST)
1654{
1655 Int fd, i;
1656 Char* text_file;
1657 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1658
1659 VGP_PUSHCC(VgpPrintXPts);
1660
1661 // Open file
1662 text_file = make_filename( base_dir,
1663 ( XText == clo_format ? ".txt" : ".html" ) );
1664
1665 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1666 VKI_S_IRUSR|VKI_S_IWUSR);
1667 if (fd < 0) {
1668 file_err( text_file );
1669 VGP_POPCC(VgpPrintXPts);
1670 return;
1671 }
1672
1673 // Header
1674 if (XHTML == clo_format) {
1675 SPRINTF(buf, "<html>\n"
1676 "<head>\n"
1677 "<title>%s</title>\n"
1678 "</head>\n"
1679 "<body>\n",
1680 text_file);
1681 }
1682
1683 // Command line
1684 SPRINTF(buf, "Command: ");
1685 for (i = 0; i < VG_(client_argc); i++)
1686 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1687 SPRINTF(buf, "\n%s\n", maybe_p);
1688
1689 if (clo_heap)
1690 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1691
njnca82cc02004-11-22 17:18:48 +00001692 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001693 VG_(close)(fd);
1694
1695 VGP_POPCC(VgpPrintXPts);
1696}
1697
1698/*------------------------------------------------------------*/
1699/*--- Finalisation ---*/
1700/*------------------------------------------------------------*/
1701
1702static void
1703print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1704 ULong stack_ST)
1705{
1706 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1707
1708 // Heap --------------------------------------------------------------
1709 if (clo_heap)
1710 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001711 ( 0 == total_ST ? (Char*)"(n/a)"
1712 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001713
1714 // Heap admin --------------------------------------------------------
1715 if (clo_heap_admin)
1716 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001717 ( 0 == total_ST ? (Char*)"(n/a)"
1718 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001719
njnca82cc02004-11-22 17:18:48 +00001720 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001721
1722 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001723 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001724 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001725 ( 0 == stack_ST ? (Char*)"0%"
1726 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001727 }
nethercotec9f36922004-02-14 16:40:02 +00001728
1729 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001730 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001731 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1732 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1733 n_zero_allocs * 100 / n_allocs );
1734 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1735 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1736 n_xpts*sizeof(XPt));
1737 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1738 n_bot_xpts * 100 / n_xpts);
1739 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1740 alloc_xpt->n_children * 100 / n_xpts);
1741 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1742 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1743 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1744 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1745 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1746 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1747 }
1748}
1749
njn51d827b2005-05-09 01:02:08 +00001750static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001751{
1752 ULong total_ST = 0;
1753 ULong heap_ST = 0;
1754 ULong heap_admin_ST = 0;
1755 ULong stack_ST = 0;
1756
1757 // Do a final (empty) sample to show program's end
1758 hp_census();
1759
1760 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001761 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001762 total_ST = heap_ST + heap_admin_ST + stack_ST;
1763 write_hp_file ( );
1764 write_text_file( total_ST, heap_ST );
1765 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1766}
1767
njn51d827b2005-05-09 01:02:08 +00001768/*------------------------------------------------------------*/
1769/*--- Initialisation ---*/
1770/*------------------------------------------------------------*/
1771
1772static void ms_post_clo_init(void)
1773{
1774 ms_interval = 1;
1775
1776 // Do an initial sample for t = 0
1777 hp_census();
1778}
1779
1780static void ms_pre_clo_init()
1781{
1782 VG_(details_name) ("Massif");
1783 VG_(details_version) (NULL);
1784 VG_(details_description) ("a space profiler");
1785 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1786 VG_(details_bug_reports_to) (VG_BUGS_TO);
1787
1788 // Basic functions
1789 VG_(basic_tool_funcs) (ms_post_clo_init,
1790 ms_instrument,
1791 ms_fini);
1792
1793 // Needs
1794 VG_(needs_libc_freeres)();
1795 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1796 ms_print_usage,
1797 ms_print_debug_usage);
1798 VG_(needs_client_requests) (ms_handle_client_request);
1799
1800 // Malloc replacement
1801 VG_(malloc_funcs) (ms_malloc,
1802 ms___builtin_new,
1803 ms___builtin_vec_new,
1804 ms_memalign,
1805 ms_calloc,
1806 ms_free,
1807 ms___builtin_delete,
1808 ms___builtin_vec_delete,
1809 ms_realloc,
1810 0 );
1811
1812 // Events to track
1813 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1814 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1815
1816 // Profiling events
1817 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1818 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1819 VG_(register_profile_event)(VgpCensus, "census");
1820 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1821 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1822 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1823 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1824 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1825 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1826 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1827
1828 // HP_Chunks
1829 malloc_list = VG_(HT_construct)();
1830
1831 // Dummy node at top of the context structure.
1832 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1833
1834 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1835}
1836
1837VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001838
1839/*--------------------------------------------------------------------*/
1840/*--- end ms_main.c ---*/
1841/*--------------------------------------------------------------------*/
1842