blob: 55be3c2ac0fd906a6afed2c8c339a1dd37ac1119 [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"
njn717cde52005-05-10 02:47:21 +000038#include "pub_tool_mallocfree.h"
39#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000040#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000041#include "pub_tool_tooliface.h"
nethercotec9f36922004-02-14 16:40:02 +000042
43#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
44
45/*------------------------------------------------------------*/
46/*--- Overview of operation ---*/
47/*------------------------------------------------------------*/
48
49// Heap blocks are tracked, and the amount of space allocated by various
50// contexts (ie. lines of code, more or less) is also tracked.
51// Periodically, a census is taken, and the amount of space used, at that
52// point, by the most significant (highly allocating) contexts is recorded.
53// Census start off frequently, but are scaled back as the program goes on,
54// so that there are always a good number of them. At the end, overall
55// spacetimes for different contexts (of differing levels of precision) is
56// calculated, the graph is printed, and the text giving spacetimes for the
57// increasingly precise contexts is given.
58//
59// Measures the following:
60// - heap blocks
61// - heap admin bytes
62// - stack(s)
63// - code (code segments loaded at startup, and loaded with mmap)
64// - data (data segments loaded at startup, and loaded/created with mmap,
65// and brk()d segments)
66
67/*------------------------------------------------------------*/
68/*--- Main types ---*/
69/*------------------------------------------------------------*/
70
71// An XPt represents an "execution point", ie. a code address. Each XPt is
72// part of a tree of XPts (an "execution tree", or "XTree"). Each
73// top-to-bottom path through an XTree gives an execution context ("XCon"),
74// and is equivalent to a traditional Valgrind ExeContext.
75//
76// The XPt at the top of an XTree (but below "alloc_xpt") is called a
77// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
78// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
79// bottom-XPTs in that XTree.
80//
81// All XCons have the same top-XPt, "alloc_xpt", which represents all
82// allocation functions like malloc(). It's a bit of a fake XPt, though,
83// and is only used because it makes some of the code simpler.
84//
85// XTrees are bi-directional.
86//
87// > parent < Example: if child1() calls parent() and child2()
88// / | \ also calls parent(), and parent() calls malloc(),
89// | / \ | the XTree will look like this.
90// | v v |
91// child1 child2
92
93typedef struct _XPt XPt;
94
95struct _XPt {
njnd01fef72005-03-25 23:35:48 +000096 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +000097
98 // Bottom-XPts: space for the precise context.
99 // Other XPts: space of all the descendent bottom-XPts.
100 // Nb: this value goes up and down as the program executes.
101 UInt curr_space;
102
103 // An approximate space.time calculation used along the way for selecting
104 // which contexts to include at each census point.
105 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000106 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000107
nethercote43a15ce2004-08-30 19:15:12 +0000108 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000109 // used in the results.
110 // Note that it is *doubled*, to avoid rounding errors.
111 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000112 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000113
114 // n_children and max_children are integers; a very big program might
115 // have more than 65536 allocation points (Konqueror startup has 1800).
116 XPt* parent; // pointer to parent XPt
117 UInt n_children; // number of children
118 UInt max_children; // capacity of children array
119 XPt** children; // pointers to children XPts
120};
121
122// Each census snapshots the most significant XTrees, each XTree having a
123// top-XPt as its root. The 'curr_space' element for each XPt is recorded
124// in the snapshot. The snapshot contains all the XTree's XPts, not in a
125// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000126// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000127//
128// Graph resolution, x-axis: no point having more than about 200 census
129// x-points; you can't see them on the graph. Therefore:
130//
131// - do a census every 1 ms for first 200 --> 200, all (200 ms)
132// - halve (drop half of them) --> 100, every 2nd (200 ms)
133// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
134// - halve --> 100, every 4th (400 ms)
135// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
136// - etc.
137//
138// This isn't exactly right, because we actually drop (N/2)-1 when halving,
139// but it shows the basic idea.
140
141#define MAX_N_CENSI 200 // Keep it even, for simplicity
142
143// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
144// bands, rest get lumped into OTHERS. I only print the top N
145// (cumulative-so-far space-time) at each point. N should be a bit bigger
146// than 19 in case the cumulative space-time doesn't fit with the eventual
147// space-time computed by hp2ps (but it should be close if the samples are
148// evenly spread, since hp2ps does an approximate per-band space-time
149// calculation that just sums the totals; ie. it assumes all samples are
150// the same distance apart).
151
152#define MAX_SNAPSHOTS 32
153
154typedef
155 struct {
156 XPt* xpt;
157 UInt space;
158 }
159 XPtSnapshot;
160
161// An XTree snapshot is stored as an array of of XPt snapshots.
162typedef XPtSnapshot* XTreeSnapshot;
163
164typedef
165 struct {
166 Int ms_time; // Int: must allow -1
167 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
168 UInt others_space;
169 UInt heap_admin_space;
170 UInt stacks_space;
171 }
172 Census;
173
174// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
175// which is a foothold into the XCon at which it was allocated. From
176// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
177// decremented (at deallocation).
178//
179// Nb: first two fields must match core's VgHashNode.
180typedef
181 struct _HP_Chunk {
182 struct _HP_Chunk* next;
183 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000184 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000185 XPt* where; // Where allocated; bottom-XPt
186 }
187 HP_Chunk;
188
189/*------------------------------------------------------------*/
190/*--- Profiling events ---*/
191/*------------------------------------------------------------*/
192
193typedef
194 enum {
195 VgpGetXPt = VgpFini+1,
196 VgpGetXPtSearch,
197 VgpCensus,
198 VgpCensusHeap,
199 VgpCensusSnapshot,
200 VgpCensusTreeSize,
201 VgpUpdateXCon,
202 VgpCalcSpacetime2,
203 VgpPrintHp,
204 VgpPrintXPts,
205 }
njn4be0a692004-11-22 18:10:36 +0000206 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000207
208/*------------------------------------------------------------*/
209/*--- Statistics ---*/
210/*------------------------------------------------------------*/
211
212// Konqueror startup, to give an idea of the numbers involved with a biggish
213// program, with default depth:
214//
215// depth=3 depth=40
216// - 310,000 allocations
217// - 300,000 frees
218// - 15,000 XPts 800,000 XPts
219// - 1,800 top-XPts
220
221static UInt n_xpts = 0;
222static UInt n_bot_xpts = 0;
223static UInt n_allocs = 0;
224static UInt n_zero_allocs = 0;
225static UInt n_frees = 0;
226static UInt n_children_reallocs = 0;
227static UInt n_snapshot_frees = 0;
228
229static UInt n_halvings = 0;
230static UInt n_real_censi = 0;
231static UInt n_fake_censi = 0;
232static UInt n_attempted_censi = 0;
233
234/*------------------------------------------------------------*/
235/*--- Globals ---*/
236/*------------------------------------------------------------*/
237
238#define FILENAME_LEN 256
239
240#define SPRINTF(zz_buf, fmt, args...) \
241 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
242 VG_(write)(fd, (void*)zz_buf, len); \
243 } while (0)
244
245#define BUF_LEN 1024 // general purpose
246static Char buf [BUF_LEN];
247static Char buf2[BUF_LEN];
248static Char buf3[BUF_LEN];
249
nethercote8b5f40c2004-11-02 13:29:50 +0000250static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000251
252static VgHashTable malloc_list = NULL; // HP_Chunks
253
254static UInt n_heap_blocks = 0;
255
njn51d827b2005-05-09 01:02:08 +0000256// Current directory at startup.
257static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000258
259#define MAX_ALLOC_FNS 32 // includes the builtin ones
260
nethercotec7469182004-05-11 09:21:08 +0000261// First few filled in, rest should be zeroed. Zero-terminated vector.
262static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000263static Char* alloc_fns[MAX_ALLOC_FNS] = {
264 "malloc",
265 "operator new(unsigned)",
266 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000267 "operator new(unsigned, std::nothrow_t const&)",
268 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000269 "__builtin_new",
270 "__builtin_vec_new",
271 "calloc",
272 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000273 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000274};
275
276
277/*------------------------------------------------------------*/
278/*--- Command line args ---*/
279/*------------------------------------------------------------*/
280
281#define MAX_DEPTH 50
282
283typedef
284 enum {
285 XText, XHTML,
286 }
287 XFormat;
288
289static Bool clo_heap = True;
290static UInt clo_heap_admin = 8;
291static Bool clo_stacks = True;
292static Bool clo_depth = 3;
293static XFormat clo_format = XText;
294
njn51d827b2005-05-09 01:02:08 +0000295static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000296{
njn45270a22005-03-27 01:00:11 +0000297 VG_BOOL_CLO(arg, "--heap", clo_heap)
298 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000299
njn45270a22005-03-27 01:00:11 +0000300 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
301 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000302
303 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
304 alloc_fns[n_alloc_fns] = & arg[11];
305 n_alloc_fns++;
306 if (n_alloc_fns >= MAX_ALLOC_FNS) {
307 VG_(printf)("Too many alloc functions specified, sorry");
308 VG_(bad_option)(arg);
309 }
310 }
311
312 else if (VG_CLO_STREQ(arg, "--format=text"))
313 clo_format = XText;
314 else if (VG_CLO_STREQ(arg, "--format=html"))
315 clo_format = XHTML;
316
317 else
318 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000319
nethercotec9f36922004-02-14 16:40:02 +0000320 return True;
321}
322
njn51d827b2005-05-09 01:02:08 +0000323static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000324{
325 VG_(printf)(
326" --heap=no|yes profile heap blocks [yes]\n"
327" --heap-admin=<number> average admin bytes per heap block [8]\n"
328" --stacks=no|yes profile stack(s) [yes]\n"
329" --depth=<number> depth of contexts [3]\n"
330" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
331" --format=text|html format of textual output [text]\n"
332 );
333 VG_(replacement_malloc_print_usage)();
334}
335
njn51d827b2005-05-09 01:02:08 +0000336static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000337{
338 VG_(replacement_malloc_print_debug_usage)();
339}
340
341/*------------------------------------------------------------*/
342/*--- Execution contexts ---*/
343/*------------------------------------------------------------*/
344
345// Fake XPt representing all allocation functions like malloc(). Acts as
346// parent node to all top-XPts.
347static XPt* alloc_xpt;
348
349// Cheap allocation for blocks that never need to be freed. Saves about 10%
350// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000351static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000352{
353 static Addr hp = 0; // current heap pointer
354 static Addr hp_lim = 0; // maximum usable byte in current block
355
356 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
357
358 if (hp + n_bytes > hp_lim) {
359 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
360 hp_lim = hp + SUPERBLOCK_SIZE - 1;
361 }
362
363 hp += n_bytes;
364
365 return (void*)(hp - n_bytes);
366}
367
368
369
njnd01fef72005-03-25 23:35:48 +0000370static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000371{
372 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000373 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000374
nethercote43a15ce2004-08-30 19:15:12 +0000375 xpt->curr_space = 0;
376 xpt->approx_ST = 0;
377 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000378
379 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000380
381 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000382 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000383
384 xpt->n_children = 0;
385
386 // If a bottom-XPt, don't allocate space for children. This can be 50%
387 // or more, although it tends to drop as --depth increases (eg. 10% for
388 // konqueror with --depth=20).
389 if ( is_bottom ) {
390 xpt->max_children = 0;
391 xpt->children = NULL;
392 n_bot_xpts++;
393 } else {
394 xpt->max_children = 4;
395 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
396 }
397
398 // Update statistics
399 n_xpts++;
400
401 return xpt;
402}
403
njnd01fef72005-03-25 23:35:48 +0000404static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000405{
406 Int i;
407
njnd01fef72005-03-25 23:35:48 +0000408 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000409 for (i = 0; i < n_alloc_fns; i++) {
410 if (VG_STREQ(buf, alloc_fns[i]))
411 return True;
412 }
413 }
414 return False;
415}
416
417// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
418// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
419// to ensure this in certain cases. See comments below.
420static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
421{
njnd01fef72005-03-25 23:35:48 +0000422 // Static to minimise stack size. +1 for added ~0 IP
423 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000424
425 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000426 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000427 UInt overestimate;
428 Bool reached_bottom;
429
430 VGP_PUSHCC(VgpGetXPt);
431
432 // Want at least clo_depth non-alloc-fn entries in the snapshot.
433 // However, because we have 1 or more (an unknown number, at this point)
434 // alloc-fns ignored, we overestimate the size needed for the stack
435 // snapshot. Then, if necessary, we repeatedly increase the size until
436 // it is enough.
437 overestimate = 2;
438 while (True) {
njnd01fef72005-03-25 23:35:48 +0000439 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000440
njnd01fef72005-03-25 23:35:48 +0000441 // Now we add a dummy "unknown" IP at the end. This is only used if we
442 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000443 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
444 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000445 // the parent's approx_ST wouldn't be equal [or almost equal] to the
446 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000447 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000448
njnd01fef72005-03-25 23:35:48 +0000449 // Skip over alloc functions in ips[].
450 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000451
452 // Must be at least one alloc function, unless client used
453 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000454 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000455
456 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000457 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000458 overestimate += 2;
459 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000460 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000461 } else {
462 break;
463 }
464 }
465 A = L;
njnd01fef72005-03-25 23:35:48 +0000466 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000467 reached_bottom = False;
468
njnd01fef72005-03-25 23:35:48 +0000469 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000470
471 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000472 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000473 while (True) {
njnd01fef72005-03-25 23:35:48 +0000474 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000475 // XXX: linear search, ugh -- about 10% of time for konqueror startup
476 // XXX: tried cacheing last result, only hit about 4% for konqueror
477 // Nb: this search hits about 98% of the time for konqueror
478 VGP_PUSHCC(VgpGetXPtSearch);
479
480 // If we've searched/added deep enough, or run out of EIPs, this is
481 // the bottom XPt.
482 if (L - A + 1 == clo_depth || L == B)
483 reached_bottom = True;
484
485 nC = 0;
486 while (True) {
487 if (nC == xpt->n_children) {
488 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000489 tl_assert(xpt->max_children != 0);
490 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000491 // Expand 'children' if necessary
492 if (xpt->n_children == xpt->max_children) {
493 xpt->max_children *= 2;
494 xpt->children = VG_(realloc)( xpt->children,
495 xpt->max_children * sizeof(XPt*) );
496 n_children_reallocs++;
497 }
njnd01fef72005-03-25 23:35:48 +0000498 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000499 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000500 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000501 break;
502 }
njnd01fef72005-03-25 23:35:48 +0000503 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000504 nC++; // keep looking
505 }
506 VGP_POPCC(VgpGetXPtSearch);
507
508 // Return found/built bottom-XPt.
509 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000510 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000511 VGP_POPCC(VgpGetXPt);
512 return xpt->children[nC];
513 }
514
515 // Descend to next level in XTree, the newly found/built non-bottom-XPt
516 xpt = xpt->children[nC];
517 L++;
518 }
519}
520
521// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
522static void update_XCon(XPt* xpt, Int space_delta)
523{
524 VGP_PUSHCC(VgpUpdateXCon);
525
njnca82cc02004-11-22 17:18:48 +0000526 tl_assert(True == clo_heap);
527 tl_assert(0 != space_delta);
528 tl_assert(NULL != xpt);
529 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000530
531 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000532 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000533 xpt->curr_space += space_delta;
534 xpt = xpt->parent;
535 }
njnca82cc02004-11-22 17:18:48 +0000536 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000537 alloc_xpt->curr_space += space_delta;
538
539 VGP_POPCC(VgpUpdateXCon);
540}
541
542// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000543static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000544{
545 XPt* xpt1 = *(XPt**)n1;
546 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000547 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000548}
549
nethercote43a15ce2004-08-30 19:15:12 +0000550static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000551{
552 XPt* xpt1 = *(XPt**)n1;
553 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000554 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000555}
556
557
558/*------------------------------------------------------------*/
559/*--- A generic Queue ---*/
560/*------------------------------------------------------------*/
561
562typedef
563 struct {
564 UInt head; // Index of first entry
565 UInt tail; // Index of final+1 entry, ie. next free slot
566 UInt max_elems;
567 void** elems;
568 }
569 Queue;
570
571static Queue* construct_queue(UInt size)
572{
573 UInt i;
574 Queue* q = VG_(malloc)(sizeof(Queue));
575 q->head = 0;
576 q->tail = 0;
577 q->max_elems = size;
578 q->elems = VG_(malloc)(size * sizeof(void*));
579 for (i = 0; i < size; i++)
580 q->elems[i] = NULL;
581
582 return q;
583}
584
585static void destruct_queue(Queue* q)
586{
587 VG_(free)(q->elems);
588 VG_(free)(q);
589}
590
591static void shuffle(Queue* dest_q, void** old_elems)
592{
593 UInt i, j;
594 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
595 dest_q->elems[i] = old_elems[j];
596 dest_q->head = 0;
597 dest_q->tail = i;
598 for ( ; i < dest_q->max_elems; i++)
599 dest_q->elems[i] = NULL; // paranoia
600}
601
602// Shuffles elements down. If not enough slots free, increase size. (We
603// don't wait until we've completely run out of space, because there could
604// be lots of shuffling just before that point which would be slow.)
605static void adjust(Queue* q)
606{
607 void** old_elems;
608
njnca82cc02004-11-22 17:18:48 +0000609 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000610 if (q->head < 10) {
611 old_elems = q->elems;
612 q->max_elems *= 2;
613 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
614 shuffle(q, old_elems);
615 VG_(free)(old_elems);
616 } else {
617 shuffle(q, q->elems);
618 }
619}
620
621static void enqueue(Queue* q, void* elem)
622{
623 if (q->tail == q->max_elems)
624 adjust(q);
625 q->elems[q->tail++] = elem;
626}
627
628static Bool is_empty_queue(Queue* q)
629{
630 return (q->head == q->tail);
631}
632
633static void* dequeue(Queue* q)
634{
635 if (is_empty_queue(q))
636 return NULL; // Queue empty
637 else
638 return q->elems[q->head++];
639}
640
641/*------------------------------------------------------------*/
642/*--- malloc() et al replacement wrappers ---*/
643/*------------------------------------------------------------*/
644
645static __inline__
646void add_HP_Chunk(HP_Chunk* hc)
647{
648 n_heap_blocks++;
649 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
650}
651
652static __inline__
653HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
654{
nethercote3d6b6112004-11-04 16:39:43 +0000655 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000656 (VgHashNode***)prev_chunks_next_ptr );
657}
658
659static __inline__
660void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
661{
njnca82cc02004-11-22 17:18:48 +0000662 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000663 n_heap_blocks--;
664 *prev_chunks_next_ptr = hc->next;
665}
666
667// Forward declaration
668static void hp_census(void);
669
nethercote159dfef2004-09-13 13:27:30 +0000670static
njn57735902004-11-25 18:04:54 +0000671void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
672 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000673{
674 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000675 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000676 if (size < 0) return NULL;
677
678 VGP_PUSHCC(VgpCliMalloc);
679
680 // Update statistics
681 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000682 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000683
nethercote57e36b32004-07-10 14:56:28 +0000684 // Allocate and zero if necessary
685 if (!p) {
686 p = VG_(cli_malloc)( align, size );
687 if (!p) {
688 VGP_POPCC(VgpCliMalloc);
689 return NULL;
690 }
691 if (is_zeroed) VG_(memset)(p, 0, size);
692 }
693
694 // Make new HP_Chunk node, add to malloclist
695 hc = VG_(malloc)(sizeof(HP_Chunk));
696 hc->size = size;
697 hc->data = (Addr)p;
698 hc->where = NULL; // paranoia
699 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000700 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000701 if (0 != size)
702 update_XCon(hc->where, size);
703 }
704 add_HP_Chunk( hc );
705
706 // do a census!
707 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000708
709 VGP_POPCC(VgpCliMalloc);
710 return p;
711}
712
713static __inline__
714void die_block ( void* p, Bool custom_free )
715{
nethercote57e36b32004-07-10 14:56:28 +0000716 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000717
718 VGP_PUSHCC(VgpCliMalloc);
719
720 // Update statistics
721 n_frees++;
722
nethercote57e36b32004-07-10 14:56:28 +0000723 // Remove HP_Chunk from malloclist
724 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000725 if (hc == NULL)
726 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000727 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000728 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000729
730 if (clo_heap && hc->size != 0)
731 update_XCon(hc->where, -hc->size);
732
nethercote57e36b32004-07-10 14:56:28 +0000733 VG_(free)( hc );
734
735 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000736 if (!custom_free)
737 VG_(cli_free)( p );
738
nethercote57e36b32004-07-10 14:56:28 +0000739 // do a census!
740 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000741
nethercotec9f36922004-02-14 16:40:02 +0000742 VGP_POPCC(VgpCliMalloc);
743}
744
745
njn51d827b2005-05-09 01:02:08 +0000746static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000747{
njn57735902004-11-25 18:04:54 +0000748 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000749}
750
njn51d827b2005-05-09 01:02:08 +0000751static void* ms___builtin_new ( 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_vec_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_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000762{
njn57735902004-11-25 18:04:54 +0000763 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000764}
765
njn51d827b2005-05-09 01:02:08 +0000766static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000767{
njn57735902004-11-25 18:04:54 +0000768 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000769}
770
njn51d827b2005-05-09 01:02:08 +0000771static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000772{
773 die_block( p, /*custom_free*/False );
774}
775
njn51d827b2005-05-09 01:02:08 +0000776static void ms___builtin_delete ( 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_vec_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_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000787{
788 HP_Chunk* hc;
789 HP_Chunk** remove_handle;
790 Int i;
791 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000792 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000793 XPt *old_where, *new_where;
794
795 VGP_PUSHCC(VgpCliMalloc);
796
797 // First try and find the block.
798 hc = get_HP_Chunk ( p_old, &remove_handle );
799 if (hc == NULL) {
800 VGP_POPCC(VgpCliMalloc);
801 return NULL; // must have been a bogus free()
802 }
803
njnca82cc02004-11-22 17:18:48 +0000804 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000805 old_size = hc->size;
806
807 if (new_size <= old_size) {
808 // new size is smaller or same; block not moved
809 p_new = p_old;
810
811 } else {
812 // new size is bigger; make new block, copy shared contents, free old
813 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
814
815 for (i = 0; i < old_size; i++)
816 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
817
818 VG_(cli_free)(p_old);
819 }
820
821 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000822 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000823
824 // Update HP_Chunk
825 hc->data = (Addr)p_new;
826 hc->size = new_size;
827 hc->where = new_where;
828
829 // Update XPt curr_space fields
830 if (clo_heap) {
831 if (0 != old_size) update_XCon(old_where, -old_size);
832 if (0 != new_size) update_XCon(new_where, new_size);
833 }
834
835 // If block has moved, have to remove and reinsert in the malloclist
836 // (since the updated 'data' field is the hash lookup key).
837 if (p_new != p_old) {
838 remove_HP_Chunk(hc, remove_handle);
839 add_HP_Chunk(hc);
840 }
841
842 VGP_POPCC(VgpCliMalloc);
843 return p_new;
844}
845
846
847/*------------------------------------------------------------*/
848/*--- Taking a census ---*/
849/*------------------------------------------------------------*/
850
851static Census censi[MAX_N_CENSI];
852static UInt curr_census = 0;
853
854// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000855static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000856{
thughes4ad52d02004-06-27 17:37:21 +0000857 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000858 return False;
859}
860
861static UInt get_xtree_size(XPt* xpt, UInt ix)
862{
863 UInt i;
864
nethercote43a15ce2004-08-30 19:15:12 +0000865 // If no memory allocated at all, nothing interesting to record.
866 if (alloc_xpt->curr_space == 0) return 0;
867
868 // Ignore sub-XTrees that account for a miniscule fraction of current
869 // allocated space.
870 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000871 ix++;
872
873 // Count all (non-zero) descendent XPts
874 for (i = 0; i < xpt->n_children; i++)
875 ix = get_xtree_size(xpt->children[i], ix);
876 }
877 return ix;
878}
879
880static
881UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
882{
883 UInt i;
884
nethercote43a15ce2004-08-30 19:15:12 +0000885 // Structure of this function mirrors that of get_xtree_size().
886
887 if (alloc_xpt->curr_space == 0) return 0;
888
889 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000890 xtree_snapshot[ix].xpt = xpt;
891 xtree_snapshot[ix].space = xpt->curr_space;
892 ix++;
893
nethercotec9f36922004-02-14 16:40:02 +0000894 for (i = 0; i < xpt->n_children; i++)
895 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
896 }
897 return ix;
898}
899
900static UInt ms_interval;
901static UInt do_every_nth_census = 30;
902
903// Weed out half the censi; we choose those that represent the smallest
904// time-spans, because that loses the least information.
905//
906// Algorithm for N censi: We find the census representing the smallest
907// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
908// (It's (N/2)-1 because we never remove the first and last censi.)
909// We have to do this one census at a time, rather than finding the (N/2)-1
910// smallest censi in one hit, because when a census is removed, it's
911// neighbours immediately cover greater timespans. So it's N^2, but N only
912// equals 200, and this is only done every 100 censi, which is not too often.
913static void halve_censi(void)
914{
915 Int i, jp, j, jn, k;
916 Census* min_census;
917
918 n_halvings++;
919 if (VG_(clo_verbosity) > 1)
920 VG_(message)(Vg_UserMsg, "Halving censi...");
921
922 // Sets j to the index of the first not-yet-removed census at or after i
923 #define FIND_CENSUS(i, j) \
924 for (j = i; -1 == censi[j].ms_time; j++) { }
925
926 for (i = 2; i < MAX_N_CENSI; i += 2) {
927 // Find the censi representing the smallest timespan. The timespan
928 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
929 // censi A and B. We don't consider the first and last censi for
930 // removal.
931 Int min_span = 0x7fffffff;
932 Int min_j = 0;
933
934 // Initial triple: (prev, curr, next) == (jp, j, jn)
935 jp = 0;
936 FIND_CENSUS(1, j);
937 FIND_CENSUS(j+1, jn);
938 while (jn < MAX_N_CENSI) {
939 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000940 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000941 if (timespan < min_span) {
942 min_span = timespan;
943 min_j = j;
944 }
945 // Move on to next triple
946 jp = j;
947 j = jn;
948 FIND_CENSUS(jn+1, jn);
949 }
950 // We've found the least important census, now remove it
951 min_census = & censi[ min_j ];
952 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
953 n_snapshot_frees++;
954 VG_(free)(min_census->xtree_snapshots[k]);
955 min_census->xtree_snapshots[k] = NULL;
956 }
957 min_census->ms_time = -1;
958 }
959
960 // Slide down the remaining censi over the removed ones. The '<=' is
961 // because we are removing on (N/2)-1, rather than N/2.
962 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
963 FIND_CENSUS(j, j);
964 if (i != j) {
965 censi[i] = censi[j];
966 }
967 }
968 curr_census = i;
969
970 // Double intervals
971 ms_interval *= 2;
972 do_every_nth_census *= 2;
973
974 if (VG_(clo_verbosity) > 1)
975 VG_(message)(Vg_UserMsg, "...done");
976}
977
978// Take a census. Census time seems to be insignificant (usually <= 0 ms,
979// almost always <= 1ms) so don't have to worry about subtracting it from
980// running time in any way.
981//
982// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
983// 50ms!
984static void hp_census(void)
985{
986 static UInt ms_prev_census = 0;
987 static UInt ms_next_census = 0; // zero allows startup census
988
989 Int ms_time, ms_time_since_prev;
990 Int i, K;
991 Census* census;
992
993 VGP_PUSHCC(VgpCensus);
994
995 // Only do a census if it's time
996 ms_time = VG_(read_millisecond_timer)();
997 ms_time_since_prev = ms_time - ms_prev_census;
998 if (ms_time < ms_next_census) {
999 n_fake_censi++;
1000 VGP_POPCC(VgpCensus);
1001 return;
1002 }
1003 n_real_censi++;
1004
1005 census = & censi[curr_census];
1006
1007 census->ms_time = ms_time;
1008
1009 // Heap: snapshot the K most significant XTrees -------------------
1010 if (clo_heap) {
1011 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1012 ? alloc_xpt->n_children
1013 : MAX_SNAPSHOTS); // max out
1014
nethercote43a15ce2004-08-30 19:15:12 +00001015 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001016 // We *do not* do it for any non-top-XPTs.
1017 for (i = 0; i < alloc_xpt->n_children; i++) {
1018 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001019 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001020 }
nethercote43a15ce2004-08-30 19:15:12 +00001021 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001022 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001023 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001024
1025 VGP_PUSHCC(VgpCensusHeap);
1026
1027 // For each significant top-level XPt, record space info about its
1028 // entire XTree, in a single census entry.
1029 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1030 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001031 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001032 for (i = 0; i < K; i++) {
1033 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001034// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1035 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001036 VGP_PUSHCC(VgpCensusTreeSize);
1037 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1038 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001039
1040 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1041 // insignificant) then don't take any more snapshots.
1042 if (0 == xtree_size) break;
1043
1044 // Make array of the appropriate size (+1 for zero termination,
1045 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001046 census->xtree_snapshots[i] =
1047 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001048 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001049 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1050 (xtree_size+1) * sizeof(XPtSnapshot));
1051
1052 // Take space-snapshot: copy 'curr_space' for every XPt in the
1053 // XTree into the snapshot array, along with pointers to the XPts.
1054 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001055 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001056 // saves a lot of memory and up to 40% time with big --depth valus.
1057 VGP_PUSHCC(VgpCensusSnapshot);
1058 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1059 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001060 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001061 VGP_POPCC(VgpCensusSnapshot);
1062 }
1063// VG_(printf)("\n\n");
1064 // Zero-terminate 'xtree_snapshot' array
1065 census->xtree_snapshots[i] = NULL;
1066
1067 VGP_POPCC(VgpCensusHeap);
1068
1069 //VG_(printf)("printed %d censi\n", K);
1070
1071 // Lump the rest into a single "others" entry.
1072 census->others_space = 0;
1073 for (i = K; i < alloc_xpt->n_children; i++) {
1074 census->others_space += alloc_xpt->children[i]->curr_space;
1075 }
1076 }
1077
1078 // Heap admin -------------------------------------------------------
1079 if (clo_heap_admin > 0)
1080 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1081
1082 // Stack(s) ---------------------------------------------------------
1083 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001084 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001085 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001086 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001087 i++;
1088 }
1089
1090 // Finish, update interval if necessary -----------------------------
1091 curr_census++;
1092 census = NULL; // don't use again now that curr_census changed
1093
1094 // Halve the entries, if our census table is full
1095 if (MAX_N_CENSI == curr_census) {
1096 halve_censi();
1097 }
1098
1099 // Take time for next census from now, rather than when this census
1100 // should have happened. Because, if there's a big gap due to a kernel
1101 // operation, there's no point doing catch-up censi every BB for a while
1102 // -- that would just give N censi at almost the same time.
1103 if (VG_(clo_verbosity) > 1) {
1104 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1105 VG_(read_millisecond_timer)() - ms_time );
1106 }
1107 ms_prev_census = ms_time;
1108 ms_next_census = ms_time + ms_interval;
1109 //ms_next_census += ms_interval;
1110
1111 //VG_(printf)("Next: %d ms\n", ms_next_census);
1112
1113 VGP_POPCC(VgpCensus);
1114}
1115
1116/*------------------------------------------------------------*/
1117/*--- Tracked events ---*/
1118/*------------------------------------------------------------*/
1119
nethercote8b5f40c2004-11-02 13:29:50 +00001120static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001121{
1122 sigstacks_space += len;
1123}
1124
nethercote8b5f40c2004-11-02 13:29:50 +00001125static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001126{
njnca82cc02004-11-22 17:18:48 +00001127 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001128 sigstacks_space -= len;
1129}
1130
1131/*------------------------------------------------------------*/
1132/*--- Client Requests ---*/
1133/*------------------------------------------------------------*/
1134
njn51d827b2005-05-09 01:02:08 +00001135static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001136{
1137 switch (argv[0]) {
1138 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001139 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001140 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001141 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001142 *ret = 0;
njn57735902004-11-25 18:04:54 +00001143 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001144 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001145 return True;
1146 }
1147 case VG_USERREQ__FREELIKE_BLOCK: {
1148 void* p = (void*)argv[1];
1149 *ret = 0;
1150 die_block( p, /*custom_free*/True );
1151 return True;
1152 }
1153 default:
1154 *ret = 0;
1155 return False;
1156 }
1157}
1158
1159/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001160/*--- Instrumentation ---*/
1161/*------------------------------------------------------------*/
1162
njn51d827b2005-05-09 01:02:08 +00001163static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1164 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001165{
sewardjd54babf2005-03-21 00:55:49 +00001166 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001167 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001168}
1169
1170/*------------------------------------------------------------*/
1171/*--- Spacetime recomputation ---*/
1172/*------------------------------------------------------------*/
1173
nethercote43a15ce2004-08-30 19:15:12 +00001174// Although we've been calculating space-time along the way, because the
1175// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001176// might not agree with what hp2ps sees, because we've thrown away some of
1177// the information. So recompute it at the scale that hp2ps sees, so we can
1178// confidently determine which contexts hp2ps will choose for displaying as
1179// distinct bands. This recomputation only happens to the significant ones
1180// that get printed in the .hp file, so it's cheap.
1181//
nethercote43a15ce2004-08-30 19:15:12 +00001182// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001183// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1184// where
1185// a[N] is the space at census N
1186// d(A,B) is the time interval between censi A and B
1187// and
1188// d(A,B) + d(B,C) == d(A,C)
1189//
1190// Key point: we can calculate the area for a census without knowing the
1191// previous or subsequent censi's space; because any over/underestimates
1192// for this census will be reversed in the next, balancing out. This is
1193// important, as getting the previous/next census entry for a particular
1194// AP is a pain with this data structure, but getting the prev/next
1195// census time is easy.
1196//
nethercote43a15ce2004-08-30 19:15:12 +00001197// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001198// The ULong* values are all running totals, hence the use of "+=" everywhere.
1199
1200// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001201static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001202 ULong* twice_heap_ST,
1203 ULong* twice_heap_admin_ST,
1204 ULong* twice_stack_ST)
1205{
1206 UInt i, j;
1207 XPtSnapshot* xpt_snapshot;
1208
1209 // Heap --------------------------------------------------------
1210 if (clo_heap) {
1211 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001212 // Compute total heap exact_ST_dbld for the entire XTree using only
1213 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001214 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1215
nethercote43a15ce2004-08-30 19:15:12 +00001216 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1217 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001218 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1219 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001220 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001221 }
1222 }
1223 *twice_heap_ST += d_t1_t2 * census->others_space;
1224 }
1225
1226 // Heap admin --------------------------------------------------
1227 if (clo_heap_admin > 0)
1228 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1229
1230 // Stack(s) ----------------------------------------------------
1231 if (clo_stacks)
1232 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1233}
1234
1235// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001236static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001237{
1238 UInt i, N = curr_census;
1239
1240 VGP_PUSHCC(VgpCalcSpacetime2);
1241
1242 *heap2 = 0;
1243 *heap_admin2 = 0;
1244 *stack2 = 0;
1245
1246 if (N <= 1)
1247 return;
1248
nethercote43a15ce2004-08-30 19:15:12 +00001249 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1250 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001251
1252 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001253 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1254 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001255 }
1256
nethercote43a15ce2004-08-30 19:15:12 +00001257 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1258 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001259 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1260 *heap2 /= 2;
1261 *heap_admin2 /= 2;
1262 *stack2 /= 2;
1263
1264 VGP_POPCC(VgpCalcSpacetime2);
1265}
1266
1267/*------------------------------------------------------------*/
1268/*--- Writing the graph file ---*/
1269/*------------------------------------------------------------*/
1270
1271static Char* make_filename(Char* dir, Char* suffix)
1272{
1273 Char* filename;
1274
1275 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1276 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1277 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1278
1279 return filename;
1280}
1281
1282// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1283static Char* clean_fnname(Char *d, Char* s)
1284{
1285 Char* dorig = d;
1286 while (*s) {
1287 if (' ' == *s) { *d = '%'; }
1288 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1289 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1290 else { *d = *s; };
1291 s++;
1292 d++;
1293 }
1294 *d = '\0';
1295 return dorig;
1296}
1297
1298static void file_err ( Char* file )
1299{
1300 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1301 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1302}
1303
1304/* Format, by example:
1305
1306 JOB "a.out -p"
1307 DATE "Fri Apr 17 11:43:45 1992"
1308 SAMPLE_UNIT "seconds"
1309 VALUE_UNIT "bytes"
1310 BEGIN_SAMPLE 0.00
1311 SYSTEM 24
1312 END_SAMPLE 0.00
1313 BEGIN_SAMPLE 1.00
1314 elim 180
1315 insert 24
1316 intersect 12
1317 disin 60
1318 main 12
1319 reduce 20
1320 SYSTEM 12
1321 END_SAMPLE 1.00
1322 MARK 1.50
1323 MARK 1.75
1324 MARK 1.80
1325 BEGIN_SAMPLE 2.00
1326 elim 192
1327 insert 24
1328 intersect 12
1329 disin 84
1330 main 12
1331 SYSTEM 24
1332 END_SAMPLE 2.00
1333 BEGIN_SAMPLE 2.82
1334 END_SAMPLE 2.82
1335 */
1336static void write_hp_file(void)
1337{
1338 Int i, j;
1339 Int fd, res;
1340 Char *hp_file, *ps_file, *aux_file;
1341 Char* cmdfmt;
1342 Char* cmdbuf;
1343 Int cmdlen;
1344
1345 VGP_PUSHCC(VgpPrintHp);
1346
1347 // Open file
1348 hp_file = make_filename( base_dir, ".hp" );
1349 ps_file = make_filename( base_dir, ".ps" );
1350 aux_file = make_filename( base_dir, ".aux" );
1351 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1352 VKI_S_IRUSR|VKI_S_IWUSR);
1353 if (fd < 0) {
1354 file_err( hp_file );
1355 VGP_POPCC(VgpPrintHp);
1356 return;
1357 }
1358
1359 // File header, including command line
1360 SPRINTF(buf, "JOB \"");
1361 for (i = 0; i < VG_(client_argc); i++)
1362 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1363 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1364 "DATE \"\"\n"
1365 "SAMPLE_UNIT \"ms\"\n"
1366 "VALUE_UNIT \"bytes\"\n", ms_interval);
1367
1368 // Censi
1369 for (i = 0; i < curr_census; i++) {
1370 Census* census = & censi[i];
1371
1372 // Census start
1373 SPRINTF(buf, "MARK %d.0\n"
1374 "BEGIN_SAMPLE %d.0\n",
1375 census->ms_time, census->ms_time);
1376
1377 // Heap -----------------------------------------------------------
1378 if (clo_heap) {
1379 // Print all the significant XPts from that census
1380 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1381 // Grab the jth top-XPt
1382 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001383 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001384 VG_(sprintf)(buf2, "???");
1385 }
njnd01fef72005-03-25 23:35:48 +00001386 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001387 clean_fnname(buf3, buf2), xtree_snapshot->space);
1388 }
1389
1390 // Remaining heap block alloc points, combined
1391 if (census->others_space > 0)
1392 SPRINTF(buf, "other %d\n", census->others_space);
1393 }
1394
1395 // Heap admin -----------------------------------------------------
1396 if (clo_heap_admin > 0 && census->heap_admin_space)
1397 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1398
1399 // Stack(s) -------------------------------------------------------
1400 if (clo_stacks)
1401 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1402
1403 // Census end
1404 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1405 }
1406
1407 // Close file
njnca82cc02004-11-22 17:18:48 +00001408 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001409 VG_(close)(fd);
1410
1411 // Attempt to convert file using hp2ps
1412 cmdfmt = "%s/hp2ps -c -t1 %s";
1413 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1414 + VG_(strlen)(cmdfmt);
1415 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1416 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1417 res = VG_(system)(cmdbuf);
1418 VG_(free)(cmdbuf);
1419 if (res != 0) {
1420 VG_(message)(Vg_UserMsg,
1421 "Conversion to PostScript failed. Try converting manually.");
1422 } else {
1423 // remove the .hp and .aux file
1424 VG_(unlink)(hp_file);
1425 VG_(unlink)(aux_file);
1426 }
1427
1428 VG_(free)(hp_file);
1429 VG_(free)(ps_file);
1430 VG_(free)(aux_file);
1431
1432 VGP_POPCC(VgpPrintHp);
1433}
1434
1435/*------------------------------------------------------------*/
1436/*--- Writing the XPt text/HTML file ---*/
1437/*------------------------------------------------------------*/
1438
1439static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1440{
1441 int i, len, space;
1442
1443 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1444 len = VG_(strlen)(xbuf);
1445 space = field_width - len;
1446 if (space < 0) space = 0; /* Allow for v. small field_width */
1447 i = len;
1448
1449 /* Right justify in field */
1450 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1451 for (i = 0; i < space; i++) xbuf[i] = ' ';
1452}
1453
1454// Nb: uses a static buffer, each call trashes the last string returned.
1455static Char* make_perc(ULong spacetime, ULong total_spacetime)
1456{
1457 static Char mbuf[32];
1458
1459 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001460 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001461 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1462 return mbuf;
1463}
1464
njnd01fef72005-03-25 23:35:48 +00001465// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001466// bottom-to-top of XCon, and then printed in the reverse order.
1467static UInt pp_XCon(Int fd, XPt* xpt)
1468{
njnd01fef72005-03-25 23:35:48 +00001469 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001470 Int i = 0;
1471 Int n = 0;
1472 Bool is_HTML = ( XHTML == clo_format );
1473 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1474 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1475
njnca82cc02004-11-22 17:18:48 +00001476 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001477
1478 while (True) {
njnd01fef72005-03-25 23:35:48 +00001479 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001480 n++;
1481 if (alloc_xpt == xpt->parent) break;
1482 i++;
1483 xpt = xpt->parent;
1484 }
1485
1486 for (i = n-1; i >= 0; i--) {
1487 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001488 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001489 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1490 }
1491
1492 return n;
1493}
1494
1495// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001496// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001497// sufficient, because function pointers mean that you can call more than
1498// one other function from a single code location. So instead we use the
1499// address of the xpt struct itself, which is guaranteed to be unique.
1500
1501static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1502 ULong total_spacetime)
1503{
1504 UInt i;
1505 XPt *xpt, *child;
1506 UInt L = 0;
1507 UInt c1 = 1;
1508 UInt c2 = 0;
1509 ULong sum = 0;
1510 UInt n;
njnd01fef72005-03-25 23:35:48 +00001511 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001512 Bool is_HTML = ( XHTML == clo_format );
1513 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1514 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1515 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1516 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1517 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1518 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1519 Char* end_hr = ( is_HTML ? "<hr>" :
1520 "=================================" );
1521 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1522
nethercote43a15ce2004-08-30 19:15:12 +00001523 if (total_spacetime == 0) {
1524 SPRINTF(buf, "(No heap memory allocated)\n");
1525 return;
1526 }
1527
1528
nethercotec9f36922004-02-14 16:40:02 +00001529 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1530
1531 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001532 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001533 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001534
nethercote43a15ce2004-08-30 19:15:12 +00001535 // Check that the sum of all children .exact_ST_dbld fields equals
1536 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001537 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001538 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001539 } else {
1540 sum = 0;
1541 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001542 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001543 }
njnca82cc02004-11-22 17:18:48 +00001544 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001545 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001546 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001547 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001548// tl_assert(sum <= xpt->exact_ST_dbld);
1549// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001550// if (sum != xpt->exact_ST_dbld) {
1551// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001552// }
1553 }
1554
1555 if (xpt == alloc_xpt) {
1556 SPRINTF(buf, "Heap allocation functions accounted for "
1557 "%s of measured spacetime%s\n",
1558 make_perc(heap_spacetime, total_spacetime), maybe_br);
1559 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001560 // Remember: exact_ST_dbld is space.time *doubled*
1561 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001562 if (is_HTML) {
1563 SPRINTF(buf, "<a name=\"b%x\"></a>"
1564 "Context accounted for "
1565 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1566 xpt, xpt, perc);
1567 } else {
1568 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1569 perc);
1570 }
1571 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001572 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001573 }
1574
nethercote43a15ce2004-08-30 19:15:12 +00001575 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001576 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001577 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001578
1579 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1580 for (i = 0; i < xpt->n_children; i++) {
1581 child = xpt->children[i];
1582
1583 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001584 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001585 UInt n_insig = xpt->n_children - i;
1586 Char* s = ( n_insig == 1 ? "" : "s" );
1587 Char* and = ( 0 == i ? "" : "and " );
1588 Char* other = ( 0 == i ? "" : "other " );
1589 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1590 maybe_li, and, n_insig, other, s, maybe_fli);
1591 break;
1592 }
1593
nethercote43a15ce2004-08-30 19:15:12 +00001594 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001595 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1596 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001597 if (is_HTML) {
1598 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1599
1600 if (child->n_children > 0) {
1601 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1602 } else {
1603 SPRINTF(buf, "%s", perc);
1604 }
njnd01fef72005-03-25 23:35:48 +00001605 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001606 } else {
njnd01fef72005-03-25 23:35:48 +00001607 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001608 }
1609
1610 if (child->n_children > 0) {
1611 enqueue(q, (void*)child);
1612 c2++;
1613 }
1614 }
1615 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1616 c1--;
1617
1618 // Putting markers between levels of the structure:
1619 // c1 tracks how many to go on this level, c2 tracks how many we've
1620 // queued up for the next level while finishing off this level.
1621 // When c1 gets to zero, we've changed levels, so print a marker,
1622 // move c2 into c1, and zero c2.
1623 if (0 == c1) {
1624 L++;
1625 c1 = c2;
1626 c2 = 0;
1627 if (! is_empty_queue(q) ) { // avoid empty one at end
1628 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1629 }
1630 } else {
1631 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1632 }
1633 }
1634 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1635 "%s value for more.\n", end_hr, depth);
1636}
1637
1638static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1639 ULong total_spacetime)
1640{
1641 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001642
nethercotec9f36922004-02-14 16:40:02 +00001643 enqueue(q, xpt);
1644 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1645 destruct_queue(q);
1646}
1647
1648static void
1649write_text_file(ULong total_ST, ULong heap_ST)
1650{
1651 Int fd, i;
1652 Char* text_file;
1653 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1654
1655 VGP_PUSHCC(VgpPrintXPts);
1656
1657 // Open file
1658 text_file = make_filename( base_dir,
1659 ( XText == clo_format ? ".txt" : ".html" ) );
1660
1661 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1662 VKI_S_IRUSR|VKI_S_IWUSR);
1663 if (fd < 0) {
1664 file_err( text_file );
1665 VGP_POPCC(VgpPrintXPts);
1666 return;
1667 }
1668
1669 // Header
1670 if (XHTML == clo_format) {
1671 SPRINTF(buf, "<html>\n"
1672 "<head>\n"
1673 "<title>%s</title>\n"
1674 "</head>\n"
1675 "<body>\n",
1676 text_file);
1677 }
1678
1679 // Command line
1680 SPRINTF(buf, "Command: ");
1681 for (i = 0; i < VG_(client_argc); i++)
1682 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1683 SPRINTF(buf, "\n%s\n", maybe_p);
1684
1685 if (clo_heap)
1686 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1687
njnca82cc02004-11-22 17:18:48 +00001688 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001689 VG_(close)(fd);
1690
1691 VGP_POPCC(VgpPrintXPts);
1692}
1693
1694/*------------------------------------------------------------*/
1695/*--- Finalisation ---*/
1696/*------------------------------------------------------------*/
1697
1698static void
1699print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1700 ULong stack_ST)
1701{
1702 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1703
1704 // Heap --------------------------------------------------------------
1705 if (clo_heap)
1706 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001707 ( 0 == total_ST ? (Char*)"(n/a)"
1708 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001709
1710 // Heap admin --------------------------------------------------------
1711 if (clo_heap_admin)
1712 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001713 ( 0 == total_ST ? (Char*)"(n/a)"
1714 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001715
njnca82cc02004-11-22 17:18:48 +00001716 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001717
1718 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001719 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001720 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001721 ( 0 == stack_ST ? (Char*)"0%"
1722 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001723 }
nethercotec9f36922004-02-14 16:40:02 +00001724
1725 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001726 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001727 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1728 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1729 n_zero_allocs * 100 / n_allocs );
1730 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1731 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1732 n_xpts*sizeof(XPt));
1733 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1734 n_bot_xpts * 100 / n_xpts);
1735 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1736 alloc_xpt->n_children * 100 / n_xpts);
1737 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1738 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1739 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1740 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1741 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1742 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1743 }
1744}
1745
njn51d827b2005-05-09 01:02:08 +00001746static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001747{
1748 ULong total_ST = 0;
1749 ULong heap_ST = 0;
1750 ULong heap_admin_ST = 0;
1751 ULong stack_ST = 0;
1752
1753 // Do a final (empty) sample to show program's end
1754 hp_census();
1755
1756 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001757 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001758 total_ST = heap_ST + heap_admin_ST + stack_ST;
1759 write_hp_file ( );
1760 write_text_file( total_ST, heap_ST );
1761 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1762}
1763
njn51d827b2005-05-09 01:02:08 +00001764/*------------------------------------------------------------*/
1765/*--- Initialisation ---*/
1766/*------------------------------------------------------------*/
1767
1768static void ms_post_clo_init(void)
1769{
1770 ms_interval = 1;
1771
1772 // Do an initial sample for t = 0
1773 hp_census();
1774}
1775
1776static void ms_pre_clo_init()
1777{
1778 VG_(details_name) ("Massif");
1779 VG_(details_version) (NULL);
1780 VG_(details_description) ("a space profiler");
1781 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1782 VG_(details_bug_reports_to) (VG_BUGS_TO);
1783
1784 // Basic functions
1785 VG_(basic_tool_funcs) (ms_post_clo_init,
1786 ms_instrument,
1787 ms_fini);
1788
1789 // Needs
1790 VG_(needs_libc_freeres)();
1791 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1792 ms_print_usage,
1793 ms_print_debug_usage);
1794 VG_(needs_client_requests) (ms_handle_client_request);
1795
1796 // Malloc replacement
1797 VG_(malloc_funcs) (ms_malloc,
1798 ms___builtin_new,
1799 ms___builtin_vec_new,
1800 ms_memalign,
1801 ms_calloc,
1802 ms_free,
1803 ms___builtin_delete,
1804 ms___builtin_vec_delete,
1805 ms_realloc,
1806 0 );
1807
1808 // Events to track
1809 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1810 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1811
1812 // Profiling events
1813 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1814 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1815 VG_(register_profile_event)(VgpCensus, "census");
1816 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1817 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1818 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1819 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1820 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1821 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1822 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1823
1824 // HP_Chunks
1825 malloc_list = VG_(HT_construct)();
1826
1827 // Dummy node at top of the context structure.
1828 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1829
1830 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1831}
1832
1833VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001834
1835/*--------------------------------------------------------------------*/
1836/*--- end ms_main.c ---*/
1837/*--------------------------------------------------------------------*/
1838