blob: dda257a49fa073bbc2238688ea1d7d1faf74d498 [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
njnc7561b92005-06-19 01:24:32 +000037#include "pub_tool_basics.h"
sewardj45f4e7c2005-09-27 19:20:21 +000038#include "pub_tool_aspacemgr.h"
njnea27e462005-05-31 02:38:09 +000039#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +000040#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +000041#include "pub_tool_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +000042#include "pub_tool_libcassert.h"
njneb8896b2005-06-04 20:03:55 +000043#include "pub_tool_libcfile.h"
njn36a20fa2005-06-03 03:08:39 +000044#include "pub_tool_libcprint.h"
njnf39e9a32005-06-12 02:43:17 +000045#include "pub_tool_libcproc.h"
njnb506bd82005-06-21 04:01:51 +000046#include "pub_tool_machine.h"
njn717cde52005-05-10 02:47:21 +000047#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000048#include "pub_tool_options.h"
njn717cde52005-05-10 02:47:21 +000049#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000050#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000051#include "pub_tool_tooliface.h"
sewardj45f4e7c2005-09-27 19:20:21 +000052#include "pub_tool_clientstate.h"
nethercotec9f36922004-02-14 16:40:02 +000053
54#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
55
56/*------------------------------------------------------------*/
57/*--- Overview of operation ---*/
58/*------------------------------------------------------------*/
59
60// Heap blocks are tracked, and the amount of space allocated by various
61// contexts (ie. lines of code, more or less) is also tracked.
62// Periodically, a census is taken, and the amount of space used, at that
63// point, by the most significant (highly allocating) contexts is recorded.
64// Census start off frequently, but are scaled back as the program goes on,
65// so that there are always a good number of them. At the end, overall
66// spacetimes for different contexts (of differing levels of precision) is
67// calculated, the graph is printed, and the text giving spacetimes for the
68// increasingly precise contexts is given.
69//
70// Measures the following:
71// - heap blocks
72// - heap admin bytes
73// - stack(s)
74// - code (code segments loaded at startup, and loaded with mmap)
75// - data (data segments loaded at startup, and loaded/created with mmap,
76// and brk()d segments)
77
78/*------------------------------------------------------------*/
79/*--- Main types ---*/
80/*------------------------------------------------------------*/
81
82// An XPt represents an "execution point", ie. a code address. Each XPt is
83// part of a tree of XPts (an "execution tree", or "XTree"). Each
84// top-to-bottom path through an XTree gives an execution context ("XCon"),
85// and is equivalent to a traditional Valgrind ExeContext.
86//
87// The XPt at the top of an XTree (but below "alloc_xpt") is called a
88// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
89// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
90// bottom-XPTs in that XTree.
91//
92// All XCons have the same top-XPt, "alloc_xpt", which represents all
93// allocation functions like malloc(). It's a bit of a fake XPt, though,
94// and is only used because it makes some of the code simpler.
95//
96// XTrees are bi-directional.
97//
98// > parent < Example: if child1() calls parent() and child2()
99// / | \ also calls parent(), and parent() calls malloc(),
100// | / \ | the XTree will look like this.
101// | v v |
102// child1 child2
103
104typedef struct _XPt XPt;
105
106struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000107 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000108
109 // Bottom-XPts: space for the precise context.
110 // Other XPts: space of all the descendent bottom-XPts.
111 // Nb: this value goes up and down as the program executes.
112 UInt curr_space;
113
114 // An approximate space.time calculation used along the way for selecting
115 // which contexts to include at each census point.
116 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000117 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000118
nethercote43a15ce2004-08-30 19:15:12 +0000119 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000120 // used in the results.
121 // Note that it is *doubled*, to avoid rounding errors.
122 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000123 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000124
125 // n_children and max_children are integers; a very big program might
126 // have more than 65536 allocation points (Konqueror startup has 1800).
127 XPt* parent; // pointer to parent XPt
128 UInt n_children; // number of children
129 UInt max_children; // capacity of children array
130 XPt** children; // pointers to children XPts
131};
132
133// Each census snapshots the most significant XTrees, each XTree having a
134// top-XPt as its root. The 'curr_space' element for each XPt is recorded
135// in the snapshot. The snapshot contains all the XTree's XPts, not in a
136// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000137// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000138//
139// Graph resolution, x-axis: no point having more than about 200 census
140// x-points; you can't see them on the graph. Therefore:
141//
142// - do a census every 1 ms for first 200 --> 200, all (200 ms)
143// - halve (drop half of them) --> 100, every 2nd (200 ms)
144// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
145// - halve --> 100, every 4th (400 ms)
146// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
147// - etc.
148//
149// This isn't exactly right, because we actually drop (N/2)-1 when halving,
150// but it shows the basic idea.
151
152#define MAX_N_CENSI 200 // Keep it even, for simplicity
153
154// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
155// bands, rest get lumped into OTHERS. I only print the top N
156// (cumulative-so-far space-time) at each point. N should be a bit bigger
157// than 19 in case the cumulative space-time doesn't fit with the eventual
158// space-time computed by hp2ps (but it should be close if the samples are
159// evenly spread, since hp2ps does an approximate per-band space-time
160// calculation that just sums the totals; ie. it assumes all samples are
161// the same distance apart).
162
163#define MAX_SNAPSHOTS 32
164
165typedef
166 struct {
167 XPt* xpt;
168 UInt space;
169 }
170 XPtSnapshot;
171
172// An XTree snapshot is stored as an array of of XPt snapshots.
173typedef XPtSnapshot* XTreeSnapshot;
174
175typedef
176 struct {
177 Int ms_time; // Int: must allow -1
178 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
179 UInt others_space;
180 UInt heap_admin_space;
181 UInt stacks_space;
182 }
183 Census;
184
185// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
186// which is a foothold into the XCon at which it was allocated. From
187// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
188// decremented (at deallocation).
189//
190// Nb: first two fields must match core's VgHashNode.
191typedef
192 struct _HP_Chunk {
193 struct _HP_Chunk* next;
194 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000195 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000196 XPt* where; // Where allocated; bottom-XPt
197 }
198 HP_Chunk;
199
200/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +0000201/*--- Statistics ---*/
202/*------------------------------------------------------------*/
203
204// Konqueror startup, to give an idea of the numbers involved with a biggish
205// program, with default depth:
206//
207// depth=3 depth=40
208// - 310,000 allocations
209// - 300,000 frees
210// - 15,000 XPts 800,000 XPts
211// - 1,800 top-XPts
212
213static UInt n_xpts = 0;
214static UInt n_bot_xpts = 0;
215static UInt n_allocs = 0;
216static UInt n_zero_allocs = 0;
217static UInt n_frees = 0;
218static UInt n_children_reallocs = 0;
219static UInt n_snapshot_frees = 0;
220
221static UInt n_halvings = 0;
222static UInt n_real_censi = 0;
223static UInt n_fake_censi = 0;
224static UInt n_attempted_censi = 0;
225
226/*------------------------------------------------------------*/
227/*--- Globals ---*/
228/*------------------------------------------------------------*/
229
230#define FILENAME_LEN 256
231
232#define SPRINTF(zz_buf, fmt, args...) \
233 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
234 VG_(write)(fd, (void*)zz_buf, len); \
235 } while (0)
236
237#define BUF_LEN 1024 // general purpose
238static Char buf [BUF_LEN];
239static Char buf2[BUF_LEN];
240static Char buf3[BUF_LEN];
241
nethercote8b5f40c2004-11-02 13:29:50 +0000242static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000243
244static VgHashTable malloc_list = NULL; // HP_Chunks
245
246static UInt n_heap_blocks = 0;
247
njn51d827b2005-05-09 01:02:08 +0000248// Current directory at startup.
njn57ca7ab2005-06-21 23:44:58 +0000249static Char base_dir[VKI_PATH_MAX];
nethercotec9f36922004-02-14 16:40:02 +0000250
251#define MAX_ALLOC_FNS 32 // includes the builtin ones
252
nethercotec7469182004-05-11 09:21:08 +0000253// First few filled in, rest should be zeroed. Zero-terminated vector.
254static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000255static Char* alloc_fns[MAX_ALLOC_FNS] = {
256 "malloc",
257 "operator new(unsigned)",
258 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000259 "operator new(unsigned, std::nothrow_t const&)",
260 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000261 "__builtin_new",
262 "__builtin_vec_new",
263 "calloc",
264 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000265 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000266};
267
268
269/*------------------------------------------------------------*/
270/*--- Command line args ---*/
271/*------------------------------------------------------------*/
272
273#define MAX_DEPTH 50
274
275typedef
276 enum {
277 XText, XHTML,
278 }
279 XFormat;
280
281static Bool clo_heap = True;
282static UInt clo_heap_admin = 8;
283static Bool clo_stacks = True;
284static Bool clo_depth = 3;
285static XFormat clo_format = XText;
286
njn51d827b2005-05-09 01:02:08 +0000287static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000288{
njn45270a22005-03-27 01:00:11 +0000289 VG_BOOL_CLO(arg, "--heap", clo_heap)
290 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000291
njn45270a22005-03-27 01:00:11 +0000292 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
293 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000294
295 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
296 alloc_fns[n_alloc_fns] = & arg[11];
297 n_alloc_fns++;
298 if (n_alloc_fns >= MAX_ALLOC_FNS) {
299 VG_(printf)("Too many alloc functions specified, sorry");
300 VG_(bad_option)(arg);
301 }
302 }
303
304 else if (VG_CLO_STREQ(arg, "--format=text"))
305 clo_format = XText;
306 else if (VG_CLO_STREQ(arg, "--format=html"))
307 clo_format = XHTML;
308
309 else
310 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000311
nethercotec9f36922004-02-14 16:40:02 +0000312 return True;
313}
314
njn51d827b2005-05-09 01:02:08 +0000315static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000316{
317 VG_(printf)(
318" --heap=no|yes profile heap blocks [yes]\n"
319" --heap-admin=<number> average admin bytes per heap block [8]\n"
320" --stacks=no|yes profile stack(s) [yes]\n"
321" --depth=<number> depth of contexts [3]\n"
322" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
323" --format=text|html format of textual output [text]\n"
324 );
325 VG_(replacement_malloc_print_usage)();
326}
327
njn51d827b2005-05-09 01:02:08 +0000328static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000329{
330 VG_(replacement_malloc_print_debug_usage)();
331}
332
333/*------------------------------------------------------------*/
334/*--- Execution contexts ---*/
335/*------------------------------------------------------------*/
336
337// Fake XPt representing all allocation functions like malloc(). Acts as
338// parent node to all top-XPts.
339static XPt* alloc_xpt;
340
341// Cheap allocation for blocks that never need to be freed. Saves about 10%
342// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000343static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000344{
345 static Addr hp = 0; // current heap pointer
346 static Addr hp_lim = 0; // maximum usable byte in current block
347
348 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
349
350 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000351 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
352 if (hp == 0)
353 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
354 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000355 hp_lim = hp + SUPERBLOCK_SIZE - 1;
356 }
357
358 hp += n_bytes;
359
360 return (void*)(hp - n_bytes);
361}
362
363
364
njnd01fef72005-03-25 23:35:48 +0000365static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000366{
367 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000368 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000369
nethercote43a15ce2004-08-30 19:15:12 +0000370 xpt->curr_space = 0;
371 xpt->approx_ST = 0;
372 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000373
374 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000375
376 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000377 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000378
379 xpt->n_children = 0;
380
381 // If a bottom-XPt, don't allocate space for children. This can be 50%
382 // or more, although it tends to drop as --depth increases (eg. 10% for
383 // konqueror with --depth=20).
384 if ( is_bottom ) {
385 xpt->max_children = 0;
386 xpt->children = NULL;
387 n_bot_xpts++;
388 } else {
389 xpt->max_children = 4;
390 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
391 }
392
393 // Update statistics
394 n_xpts++;
395
396 return xpt;
397}
398
njnd01fef72005-03-25 23:35:48 +0000399static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000400{
401 Int i;
402
njnd01fef72005-03-25 23:35:48 +0000403 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000404 for (i = 0; i < n_alloc_fns; i++) {
405 if (VG_STREQ(buf, alloc_fns[i]))
406 return True;
407 }
408 }
409 return False;
410}
411
412// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
413// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
414// to ensure this in certain cases. See comments below.
415static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
416{
njnd01fef72005-03-25 23:35:48 +0000417 // Static to minimise stack size. +1 for added ~0 IP
418 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000419
420 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000421 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000422 UInt overestimate;
423 Bool reached_bottom;
424
nethercotec9f36922004-02-14 16:40:02 +0000425 // Want at least clo_depth non-alloc-fn entries in the snapshot.
426 // However, because we have 1 or more (an unknown number, at this point)
427 // alloc-fns ignored, we overestimate the size needed for the stack
428 // snapshot. Then, if necessary, we repeatedly increase the size until
429 // it is enough.
430 overestimate = 2;
431 while (True) {
njnd01fef72005-03-25 23:35:48 +0000432 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000433
njnd01fef72005-03-25 23:35:48 +0000434 // Now we add a dummy "unknown" IP at the end. This is only used if we
435 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000436 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
437 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000438 // the parent's approx_ST wouldn't be equal [or almost equal] to the
439 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000440 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000441
njnd01fef72005-03-25 23:35:48 +0000442 // Skip over alloc functions in ips[].
443 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000444
445 // Must be at least one alloc function, unless client used
446 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000447 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000448
449 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000450 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000451 overestimate += 2;
452 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000453 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000454 } else {
455 break;
456 }
457 }
458 A = L;
njnd01fef72005-03-25 23:35:48 +0000459 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000460 reached_bottom = False;
461
njnd01fef72005-03-25 23:35:48 +0000462 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000463
464 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000465 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000466 while (True) {
njnd01fef72005-03-25 23:35:48 +0000467 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000468 // XXX: linear search, ugh -- about 10% of time for konqueror startup
469 // XXX: tried cacheing last result, only hit about 4% for konqueror
470 // Nb: this search hits about 98% of the time for konqueror
nethercotec9f36922004-02-14 16:40:02 +0000471
472 // If we've searched/added deep enough, or run out of EIPs, this is
473 // the bottom XPt.
474 if (L - A + 1 == clo_depth || L == B)
475 reached_bottom = True;
476
477 nC = 0;
478 while (True) {
479 if (nC == xpt->n_children) {
480 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000481 tl_assert(xpt->max_children != 0);
482 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000483 // Expand 'children' if necessary
484 if (xpt->n_children == xpt->max_children) {
485 xpt->max_children *= 2;
486 xpt->children = VG_(realloc)( xpt->children,
487 xpt->max_children * sizeof(XPt*) );
488 n_children_reallocs++;
489 }
njnd01fef72005-03-25 23:35:48 +0000490 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000491 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000492 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000493 break;
494 }
njnd01fef72005-03-25 23:35:48 +0000495 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000496 nC++; // keep looking
497 }
nethercotec9f36922004-02-14 16:40:02 +0000498
499 // Return found/built bottom-XPt.
500 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000501 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000502 return xpt->children[nC];
503 }
504
505 // Descend to next level in XTree, the newly found/built non-bottom-XPt
506 xpt = xpt->children[nC];
507 L++;
508 }
509}
510
511// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
512static void update_XCon(XPt* xpt, Int space_delta)
513{
njnca82cc02004-11-22 17:18:48 +0000514 tl_assert(True == clo_heap);
515 tl_assert(0 != space_delta);
516 tl_assert(NULL != xpt);
517 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000518
519 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000520 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000521 xpt->curr_space += space_delta;
522 xpt = xpt->parent;
523 }
njnca82cc02004-11-22 17:18:48 +0000524 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000525 alloc_xpt->curr_space += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000526}
527
528// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000529static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000530{
531 XPt* xpt1 = *(XPt**)n1;
532 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000533 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000534}
535
nethercote43a15ce2004-08-30 19:15:12 +0000536static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000537{
538 XPt* xpt1 = *(XPt**)n1;
539 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000540 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000541}
542
543
544/*------------------------------------------------------------*/
545/*--- A generic Queue ---*/
546/*------------------------------------------------------------*/
547
548typedef
549 struct {
550 UInt head; // Index of first entry
551 UInt tail; // Index of final+1 entry, ie. next free slot
552 UInt max_elems;
553 void** elems;
554 }
555 Queue;
556
557static Queue* construct_queue(UInt size)
558{
559 UInt i;
560 Queue* q = VG_(malloc)(sizeof(Queue));
561 q->head = 0;
562 q->tail = 0;
563 q->max_elems = size;
564 q->elems = VG_(malloc)(size * sizeof(void*));
565 for (i = 0; i < size; i++)
566 q->elems[i] = NULL;
567
568 return q;
569}
570
571static void destruct_queue(Queue* q)
572{
573 VG_(free)(q->elems);
574 VG_(free)(q);
575}
576
577static void shuffle(Queue* dest_q, void** old_elems)
578{
579 UInt i, j;
580 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
581 dest_q->elems[i] = old_elems[j];
582 dest_q->head = 0;
583 dest_q->tail = i;
584 for ( ; i < dest_q->max_elems; i++)
585 dest_q->elems[i] = NULL; // paranoia
586}
587
588// Shuffles elements down. If not enough slots free, increase size. (We
589// don't wait until we've completely run out of space, because there could
590// be lots of shuffling just before that point which would be slow.)
591static void adjust(Queue* q)
592{
593 void** old_elems;
594
njnca82cc02004-11-22 17:18:48 +0000595 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000596 if (q->head < 10) {
597 old_elems = q->elems;
598 q->max_elems *= 2;
599 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
600 shuffle(q, old_elems);
601 VG_(free)(old_elems);
602 } else {
603 shuffle(q, q->elems);
604 }
605}
606
607static void enqueue(Queue* q, void* elem)
608{
609 if (q->tail == q->max_elems)
610 adjust(q);
611 q->elems[q->tail++] = elem;
612}
613
614static Bool is_empty_queue(Queue* q)
615{
616 return (q->head == q->tail);
617}
618
619static void* dequeue(Queue* q)
620{
621 if (is_empty_queue(q))
622 return NULL; // Queue empty
623 else
624 return q->elems[q->head++];
625}
626
627/*------------------------------------------------------------*/
628/*--- malloc() et al replacement wrappers ---*/
629/*------------------------------------------------------------*/
630
nethercotec9f36922004-02-14 16:40:02 +0000631// Forward declaration
632static void hp_census(void);
633
nethercote159dfef2004-09-13 13:27:30 +0000634static
njn57735902004-11-25 18:04:54 +0000635void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
636 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000637{
638 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000639 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000640 if (size < 0) return NULL;
641
nethercotec9f36922004-02-14 16:40:02 +0000642 // Update statistics
643 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000644 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000645
nethercote57e36b32004-07-10 14:56:28 +0000646 // Allocate and zero if necessary
647 if (!p) {
648 p = VG_(cli_malloc)( align, size );
649 if (!p) {
nethercote57e36b32004-07-10 14:56:28 +0000650 return NULL;
651 }
652 if (is_zeroed) VG_(memset)(p, 0, size);
653 }
654
njnf1c5def2005-08-11 02:17:07 +0000655 // Make new HP_Chunk node, add to malloc_list
nethercote57e36b32004-07-10 14:56:28 +0000656 hc = VG_(malloc)(sizeof(HP_Chunk));
657 hc->size = size;
658 hc->data = (Addr)p;
659 hc->where = NULL; // paranoia
660 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000661 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000662 if (0 != size)
663 update_XCon(hc->where, size);
664 }
njn246a9d22005-08-14 06:24:20 +0000665 VG_(HT_add_node)(malloc_list, hc);
njnf1c5def2005-08-11 02:17:07 +0000666 n_heap_blocks++;
nethercote57e36b32004-07-10 14:56:28 +0000667
668 // do a census!
669 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000670
nethercotec9f36922004-02-14 16:40:02 +0000671 return p;
672}
673
674static __inline__
675void die_block ( void* p, Bool custom_free )
676{
njnf1c5def2005-08-11 02:17:07 +0000677 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +0000678
nethercotec9f36922004-02-14 16:40:02 +0000679 // Update statistics
680 n_frees++;
681
njnf1c5def2005-08-11 02:17:07 +0000682 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +0000683 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn5cc5d7e2005-08-11 02:09:25 +0000684 if (NULL == hc)
685 return; // must have been a bogus free()
686 tl_assert(n_heap_blocks > 0);
687 n_heap_blocks--;
nethercotec9f36922004-02-14 16:40:02 +0000688
689 if (clo_heap && hc->size != 0)
690 update_XCon(hc->where, -hc->size);
691
nethercote57e36b32004-07-10 14:56:28 +0000692 VG_(free)( hc );
693
694 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000695 if (!custom_free)
696 VG_(cli_free)( p );
697
nethercote57e36b32004-07-10 14:56:28 +0000698 // do a census!
699 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000700}
701
702
njn51d827b2005-05-09 01:02:08 +0000703static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000704{
njn57735902004-11-25 18:04:54 +0000705 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000706}
707
njn51d827b2005-05-09 01:02:08 +0000708static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000709{
njn57735902004-11-25 18:04:54 +0000710 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000711}
712
njn51d827b2005-05-09 01:02:08 +0000713static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000714{
njn57735902004-11-25 18:04:54 +0000715 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000716}
717
njn51d827b2005-05-09 01:02:08 +0000718static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000719{
njn57735902004-11-25 18:04:54 +0000720 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000721}
722
njn51d827b2005-05-09 01:02:08 +0000723static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000724{
njn57735902004-11-25 18:04:54 +0000725 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000726}
727
njn51d827b2005-05-09 01:02:08 +0000728static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000729{
730 die_block( p, /*custom_free*/False );
731}
732
njn51d827b2005-05-09 01:02:08 +0000733static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000734{
735 die_block( p, /*custom_free*/False);
736}
737
njn51d827b2005-05-09 01:02:08 +0000738static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000739{
740 die_block( p, /*custom_free*/False );
741}
742
njn51d827b2005-05-09 01:02:08 +0000743static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000744{
njn5cc5d7e2005-08-11 02:09:25 +0000745 HP_Chunk* hc;
746 void* p_new;
747 SizeT old_size;
748 XPt *old_where, *new_where;
nethercotec9f36922004-02-14 16:40:02 +0000749
njna0793652005-08-16 03:34:56 +0000750 // Remove the old block
njn9a463242005-08-16 03:29:50 +0000751 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000752 if (hc == NULL) {
njn5cc5d7e2005-08-11 02:09:25 +0000753 return NULL; // must have been a bogus realloc()
nethercotec9f36922004-02-14 16:40:02 +0000754 }
755
nethercotec9f36922004-02-14 16:40:02 +0000756 old_size = hc->size;
757
758 if (new_size <= old_size) {
759 // new size is smaller or same; block not moved
760 p_new = p_old;
761
762 } else {
763 // new size is bigger; make new block, copy shared contents, free old
764 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
tom0cd42f02005-10-06 09:00:17 +0000765 if (p_new) {
766 VG_(memcpy)(p_new, p_old, old_size);
767 VG_(cli_free)(p_old);
768 }
nethercotec9f36922004-02-14 16:40:02 +0000769 }
nethercotec9f36922004-02-14 16:40:02 +0000770
tom0cd42f02005-10-06 09:00:17 +0000771 if (p_new) {
772 old_where = hc->where;
773 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000774
tom0cd42f02005-10-06 09:00:17 +0000775 // Update HP_Chunk
776 hc->data = (Addr)p_new;
777 hc->size = new_size;
778 hc->where = new_where;
779
780 // Update XPt curr_space fields
781 if (clo_heap) {
782 if (0 != old_size) update_XCon(old_where, -old_size);
783 if (0 != new_size) update_XCon(new_where, new_size);
784 }
nethercotec9f36922004-02-14 16:40:02 +0000785 }
786
njn5cc5d7e2005-08-11 02:09:25 +0000787 // Now insert the new hc (with a possibly new 'data' field) into
788 // malloc_list. If this realloc() did not increase the memory size, we
789 // will have removed and then re-added mc unnecessarily. But that's ok
790 // because shrinking a block with realloc() is (presumably) much rarer
791 // than growing it, and this way simplifies the growing case.
njn246a9d22005-08-14 06:24:20 +0000792 VG_(HT_add_node)(malloc_list, hc);
nethercotec9f36922004-02-14 16:40:02 +0000793
nethercotec9f36922004-02-14 16:40:02 +0000794 return p_new;
795}
796
797
798/*------------------------------------------------------------*/
799/*--- Taking a census ---*/
800/*------------------------------------------------------------*/
801
802static Census censi[MAX_N_CENSI];
803static UInt curr_census = 0;
804
nethercotec9f36922004-02-14 16:40:02 +0000805static UInt get_xtree_size(XPt* xpt, UInt ix)
806{
807 UInt i;
808
nethercote43a15ce2004-08-30 19:15:12 +0000809 // If no memory allocated at all, nothing interesting to record.
810 if (alloc_xpt->curr_space == 0) return 0;
811
812 // Ignore sub-XTrees that account for a miniscule fraction of current
813 // allocated space.
814 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000815 ix++;
816
817 // Count all (non-zero) descendent XPts
818 for (i = 0; i < xpt->n_children; i++)
819 ix = get_xtree_size(xpt->children[i], ix);
820 }
821 return ix;
822}
823
824static
825UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
826{
827 UInt i;
828
nethercote43a15ce2004-08-30 19:15:12 +0000829 // Structure of this function mirrors that of get_xtree_size().
830
831 if (alloc_xpt->curr_space == 0) return 0;
832
833 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000834 xtree_snapshot[ix].xpt = xpt;
835 xtree_snapshot[ix].space = xpt->curr_space;
836 ix++;
837
nethercotec9f36922004-02-14 16:40:02 +0000838 for (i = 0; i < xpt->n_children; i++)
839 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
840 }
841 return ix;
842}
843
844static UInt ms_interval;
845static UInt do_every_nth_census = 30;
846
847// Weed out half the censi; we choose those that represent the smallest
848// time-spans, because that loses the least information.
849//
850// Algorithm for N censi: We find the census representing the smallest
851// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
852// (It's (N/2)-1 because we never remove the first and last censi.)
853// We have to do this one census at a time, rather than finding the (N/2)-1
854// smallest censi in one hit, because when a census is removed, it's
855// neighbours immediately cover greater timespans. So it's N^2, but N only
856// equals 200, and this is only done every 100 censi, which is not too often.
857static void halve_censi(void)
858{
859 Int i, jp, j, jn, k;
860 Census* min_census;
861
862 n_halvings++;
863 if (VG_(clo_verbosity) > 1)
864 VG_(message)(Vg_UserMsg, "Halving censi...");
865
866 // Sets j to the index of the first not-yet-removed census at or after i
867 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000868 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000869
870 for (i = 2; i < MAX_N_CENSI; i += 2) {
871 // Find the censi representing the smallest timespan. The timespan
872 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
873 // censi A and B. We don't consider the first and last censi for
874 // removal.
875 Int min_span = 0x7fffffff;
876 Int min_j = 0;
877
878 // Initial triple: (prev, curr, next) == (jp, j, jn)
879 jp = 0;
880 FIND_CENSUS(1, j);
881 FIND_CENSUS(j+1, jn);
882 while (jn < MAX_N_CENSI) {
883 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000884 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000885 if (timespan < min_span) {
886 min_span = timespan;
887 min_j = j;
888 }
889 // Move on to next triple
890 jp = j;
891 j = jn;
892 FIND_CENSUS(jn+1, jn);
893 }
894 // We've found the least important census, now remove it
895 min_census = & censi[ min_j ];
896 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
897 n_snapshot_frees++;
898 VG_(free)(min_census->xtree_snapshots[k]);
899 min_census->xtree_snapshots[k] = NULL;
900 }
901 min_census->ms_time = -1;
902 }
903
904 // Slide down the remaining censi over the removed ones. The '<=' is
905 // because we are removing on (N/2)-1, rather than N/2.
906 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
907 FIND_CENSUS(j, j);
908 if (i != j) {
909 censi[i] = censi[j];
910 }
911 }
912 curr_census = i;
913
914 // Double intervals
915 ms_interval *= 2;
916 do_every_nth_census *= 2;
917
918 if (VG_(clo_verbosity) > 1)
919 VG_(message)(Vg_UserMsg, "...done");
920}
921
922// Take a census. Census time seems to be insignificant (usually <= 0 ms,
923// almost always <= 1ms) so don't have to worry about subtracting it from
924// running time in any way.
925//
926// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
927// 50ms!
928static void hp_census(void)
929{
930 static UInt ms_prev_census = 0;
931 static UInt ms_next_census = 0; // zero allows startup census
932
933 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000934 Census* census;
935
nethercotec9f36922004-02-14 16:40:02 +0000936 // Only do a census if it's time
937 ms_time = VG_(read_millisecond_timer)();
938 ms_time_since_prev = ms_time - ms_prev_census;
939 if (ms_time < ms_next_census) {
940 n_fake_censi++;
nethercotec9f36922004-02-14 16:40:02 +0000941 return;
942 }
943 n_real_censi++;
944
945 census = & censi[curr_census];
946
947 census->ms_time = ms_time;
948
949 // Heap: snapshot the K most significant XTrees -------------------
950 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +0000951 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +0000952 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
953 ? alloc_xpt->n_children
954 : MAX_SNAPSHOTS); // max out
955
nethercote43a15ce2004-08-30 19:15:12 +0000956 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +0000957 // We *do not* do it for any non-top-XPTs.
958 for (i = 0; i < alloc_xpt->n_children; i++) {
959 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +0000960 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000961 }
nethercote43a15ce2004-08-30 19:15:12 +0000962 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +0000963 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +0000964 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +0000965
nethercotec9f36922004-02-14 16:40:02 +0000966 // For each significant top-level XPt, record space info about its
967 // entire XTree, in a single census entry.
968 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
969 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +0000970 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +0000971 for (i = 0; i < K; i++) {
972 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +0000973// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
974 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +0000975 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
nethercote43a15ce2004-08-30 19:15:12 +0000976
977 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
978 // insignificant) then don't take any more snapshots.
979 if (0 == xtree_size) break;
980
981 // Make array of the appropriate size (+1 for zero termination,
982 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +0000983 census->xtree_snapshots[i] =
984 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +0000985 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +0000986 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
987 (xtree_size+1) * sizeof(XPtSnapshot));
988
989 // Take space-snapshot: copy 'curr_space' for every XPt in the
990 // XTree into the snapshot array, along with pointers to the XPts.
991 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +0000992 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +0000993 // saves a lot of memory and up to 40% time with big --depth valus.
nethercotec9f36922004-02-14 16:40:02 +0000994 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
995 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +0000996 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +0000997 }
998// VG_(printf)("\n\n");
999 // Zero-terminate 'xtree_snapshot' array
1000 census->xtree_snapshots[i] = NULL;
1001
nethercotec9f36922004-02-14 16:40:02 +00001002 //VG_(printf)("printed %d censi\n", K);
1003
1004 // Lump the rest into a single "others" entry.
1005 census->others_space = 0;
1006 for (i = K; i < alloc_xpt->n_children; i++) {
1007 census->others_space += alloc_xpt->children[i]->curr_space;
1008 }
1009 }
1010
1011 // Heap admin -------------------------------------------------------
1012 if (clo_heap_admin > 0)
1013 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1014
1015 // Stack(s) ---------------------------------------------------------
1016 if (clo_stacks) {
njn1d0cb0d2005-08-15 01:52:02 +00001017 ThreadId tid;
1018 Addr stack_min, stack_max;
thughes4ad52d02004-06-27 17:37:21 +00001019 census->stacks_space = sigstacks_space;
njn1d0cb0d2005-08-15 01:52:02 +00001020 VG_(thread_stack_reset_iter)();
1021 while ( VG_(thread_stack_next)(&tid, &stack_min, &stack_max) ) {
1022 census->stacks_space += (stack_max - stack_min);
1023 }
nethercotec9f36922004-02-14 16:40:02 +00001024 }
1025
1026 // Finish, update interval if necessary -----------------------------
1027 curr_census++;
1028 census = NULL; // don't use again now that curr_census changed
1029
1030 // Halve the entries, if our census table is full
1031 if (MAX_N_CENSI == curr_census) {
1032 halve_censi();
1033 }
1034
1035 // Take time for next census from now, rather than when this census
1036 // should have happened. Because, if there's a big gap due to a kernel
1037 // operation, there's no point doing catch-up censi every BB for a while
1038 // -- that would just give N censi at almost the same time.
1039 if (VG_(clo_verbosity) > 1) {
1040 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1041 VG_(read_millisecond_timer)() - ms_time );
1042 }
1043 ms_prev_census = ms_time;
1044 ms_next_census = ms_time + ms_interval;
1045 //ms_next_census += ms_interval;
1046
1047 //VG_(printf)("Next: %d ms\n", ms_next_census);
nethercotec9f36922004-02-14 16:40:02 +00001048}
1049
1050/*------------------------------------------------------------*/
1051/*--- Tracked events ---*/
1052/*------------------------------------------------------------*/
1053
nethercote8b5f40c2004-11-02 13:29:50 +00001054static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001055{
1056 sigstacks_space += len;
1057}
1058
nethercote8b5f40c2004-11-02 13:29:50 +00001059static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001060{
njnca82cc02004-11-22 17:18:48 +00001061 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001062 sigstacks_space -= len;
1063}
1064
1065/*------------------------------------------------------------*/
1066/*--- Client Requests ---*/
1067/*------------------------------------------------------------*/
1068
njn51d827b2005-05-09 01:02:08 +00001069static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001070{
1071 switch (argv[0]) {
1072 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001073 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001074 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001075 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001076 *ret = 0;
njn57735902004-11-25 18:04:54 +00001077 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001078 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001079 return True;
1080 }
1081 case VG_USERREQ__FREELIKE_BLOCK: {
1082 void* p = (void*)argv[1];
1083 *ret = 0;
1084 die_block( p, /*custom_free*/True );
1085 return True;
1086 }
1087 default:
1088 *ret = 0;
1089 return False;
1090 }
1091}
1092
1093/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001094/*--- Instrumentation ---*/
1095/*------------------------------------------------------------*/
1096
sewardj4ba057c2005-10-18 12:04:18 +00001097static
1098IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1099 Addr64 orig_addr_noredir, VexGuestExtents* vge,
1100 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001101{
sewardjd54babf2005-03-21 00:55:49 +00001102 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001103 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001104}
1105
1106/*------------------------------------------------------------*/
1107/*--- Spacetime recomputation ---*/
1108/*------------------------------------------------------------*/
1109
nethercote43a15ce2004-08-30 19:15:12 +00001110// Although we've been calculating space-time along the way, because the
1111// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001112// might not agree with what hp2ps sees, because we've thrown away some of
1113// the information. So recompute it at the scale that hp2ps sees, so we can
1114// confidently determine which contexts hp2ps will choose for displaying as
1115// distinct bands. This recomputation only happens to the significant ones
1116// that get printed in the .hp file, so it's cheap.
1117//
nethercote43a15ce2004-08-30 19:15:12 +00001118// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001119// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1120// where
1121// a[N] is the space at census N
1122// d(A,B) is the time interval between censi A and B
1123// and
1124// d(A,B) + d(B,C) == d(A,C)
1125//
1126// Key point: we can calculate the area for a census without knowing the
1127// previous or subsequent censi's space; because any over/underestimates
1128// for this census will be reversed in the next, balancing out. This is
1129// important, as getting the previous/next census entry for a particular
1130// AP is a pain with this data structure, but getting the prev/next
1131// census time is easy.
1132//
nethercote43a15ce2004-08-30 19:15:12 +00001133// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001134// The ULong* values are all running totals, hence the use of "+=" everywhere.
1135
1136// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001137static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001138 ULong* twice_heap_ST,
1139 ULong* twice_heap_admin_ST,
1140 ULong* twice_stack_ST)
1141{
1142 UInt i, j;
1143 XPtSnapshot* xpt_snapshot;
1144
1145 // Heap --------------------------------------------------------
1146 if (clo_heap) {
1147 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001148 // Compute total heap exact_ST_dbld for the entire XTree using only
1149 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001150 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1151
nethercote43a15ce2004-08-30 19:15:12 +00001152 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1153 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001154 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1155 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001156 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001157 }
1158 }
1159 *twice_heap_ST += d_t1_t2 * census->others_space;
1160 }
1161
1162 // Heap admin --------------------------------------------------
1163 if (clo_heap_admin > 0)
1164 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1165
1166 // Stack(s) ----------------------------------------------------
1167 if (clo_stacks)
1168 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1169}
1170
1171// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001172static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001173{
1174 UInt i, N = curr_census;
1175
nethercotec9f36922004-02-14 16:40:02 +00001176 *heap2 = 0;
1177 *heap_admin2 = 0;
1178 *stack2 = 0;
1179
1180 if (N <= 1)
1181 return;
1182
nethercote43a15ce2004-08-30 19:15:12 +00001183 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1184 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001185
1186 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001187 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1188 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001189 }
1190
nethercote43a15ce2004-08-30 19:15:12 +00001191 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1192 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001193 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1194 *heap2 /= 2;
1195 *heap_admin2 /= 2;
1196 *stack2 /= 2;
nethercotec9f36922004-02-14 16:40:02 +00001197}
1198
1199/*------------------------------------------------------------*/
1200/*--- Writing the graph file ---*/
1201/*------------------------------------------------------------*/
1202
1203static Char* make_filename(Char* dir, Char* suffix)
1204{
1205 Char* filename;
1206
1207 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1208 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1209 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1210
1211 return filename;
1212}
1213
1214// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1215static Char* clean_fnname(Char *d, Char* s)
1216{
1217 Char* dorig = d;
1218 while (*s) {
1219 if (' ' == *s) { *d = '%'; }
1220 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1221 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1222 else { *d = *s; };
1223 s++;
1224 d++;
1225 }
1226 *d = '\0';
1227 return dorig;
1228}
1229
1230static void file_err ( Char* file )
1231{
njn02bc4b82005-05-15 17:28:26 +00001232 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001233 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1234}
1235
1236/* Format, by example:
1237
1238 JOB "a.out -p"
1239 DATE "Fri Apr 17 11:43:45 1992"
1240 SAMPLE_UNIT "seconds"
1241 VALUE_UNIT "bytes"
1242 BEGIN_SAMPLE 0.00
1243 SYSTEM 24
1244 END_SAMPLE 0.00
1245 BEGIN_SAMPLE 1.00
1246 elim 180
1247 insert 24
1248 intersect 12
1249 disin 60
1250 main 12
1251 reduce 20
1252 SYSTEM 12
1253 END_SAMPLE 1.00
1254 MARK 1.50
1255 MARK 1.75
1256 MARK 1.80
1257 BEGIN_SAMPLE 2.00
1258 elim 192
1259 insert 24
1260 intersect 12
1261 disin 84
1262 main 12
1263 SYSTEM 24
1264 END_SAMPLE 2.00
1265 BEGIN_SAMPLE 2.82
1266 END_SAMPLE 2.82
1267 */
1268static void write_hp_file(void)
1269{
sewardj92645592005-07-23 09:18:34 +00001270 Int i, j;
1271 Int fd, res;
1272 SysRes sres;
1273 Char *hp_file, *ps_file, *aux_file;
1274 Char* cmdfmt;
1275 Char* cmdbuf;
1276 Int cmdlen;
nethercotec9f36922004-02-14 16:40:02 +00001277
nethercotec9f36922004-02-14 16:40:02 +00001278 // Open file
1279 hp_file = make_filename( base_dir, ".hp" );
1280 ps_file = make_filename( base_dir, ".ps" );
1281 aux_file = make_filename( base_dir, ".aux" );
sewardj92645592005-07-23 09:18:34 +00001282 sres = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1283 VKI_S_IRUSR|VKI_S_IWUSR);
1284 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001285 file_err( hp_file );
nethercotec9f36922004-02-14 16:40:02 +00001286 return;
sewardj92645592005-07-23 09:18:34 +00001287 } else {
1288 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001289 }
1290
1291 // File header, including command line
1292 SPRINTF(buf, "JOB \"");
sewardj45f4e7c2005-09-27 19:20:21 +00001293 if (VG_(args_the_exename)) {
1294 SPRINTF(buf, "%s", VG_(args_the_exename));
1295 }
1296 for (i = 0; i < VG_(args_for_client).used; i++) {
1297 if (VG_(args_for_client).strs[i])
1298 SPRINTF(buf, " %s", VG_(args_for_client).strs[i]);
njnd111d102005-09-13 00:46:27 +00001299 }
nethercotec9f36922004-02-14 16:40:02 +00001300 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1301 "DATE \"\"\n"
1302 "SAMPLE_UNIT \"ms\"\n"
1303 "VALUE_UNIT \"bytes\"\n", ms_interval);
1304
1305 // Censi
1306 for (i = 0; i < curr_census; i++) {
1307 Census* census = & censi[i];
1308
1309 // Census start
1310 SPRINTF(buf, "MARK %d.0\n"
1311 "BEGIN_SAMPLE %d.0\n",
1312 census->ms_time, census->ms_time);
1313
1314 // Heap -----------------------------------------------------------
1315 if (clo_heap) {
1316 // Print all the significant XPts from that census
1317 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1318 // Grab the jth top-XPt
1319 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001320 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001321 VG_(sprintf)(buf2, "???");
1322 }
njnd01fef72005-03-25 23:35:48 +00001323 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001324 clean_fnname(buf3, buf2), xtree_snapshot->space);
1325 }
1326
1327 // Remaining heap block alloc points, combined
1328 if (census->others_space > 0)
1329 SPRINTF(buf, "other %d\n", census->others_space);
1330 }
1331
1332 // Heap admin -----------------------------------------------------
1333 if (clo_heap_admin > 0 && census->heap_admin_space)
1334 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1335
1336 // Stack(s) -------------------------------------------------------
1337 if (clo_stacks)
1338 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1339
1340 // Census end
1341 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1342 }
1343
1344 // Close file
njnca82cc02004-11-22 17:18:48 +00001345 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001346 VG_(close)(fd);
1347
1348 // Attempt to convert file using hp2ps
1349 cmdfmt = "%s/hp2ps -c -t1 %s";
1350 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1351 + VG_(strlen)(cmdfmt);
1352 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1353 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1354 res = VG_(system)(cmdbuf);
1355 VG_(free)(cmdbuf);
1356 if (res != 0) {
1357 VG_(message)(Vg_UserMsg,
1358 "Conversion to PostScript failed. Try converting manually.");
1359 } else {
1360 // remove the .hp and .aux file
1361 VG_(unlink)(hp_file);
1362 VG_(unlink)(aux_file);
1363 }
1364
1365 VG_(free)(hp_file);
1366 VG_(free)(ps_file);
1367 VG_(free)(aux_file);
nethercotec9f36922004-02-14 16:40:02 +00001368}
1369
1370/*------------------------------------------------------------*/
1371/*--- Writing the XPt text/HTML file ---*/
1372/*------------------------------------------------------------*/
1373
1374static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1375{
1376 int i, len, space;
1377
1378 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1379 len = VG_(strlen)(xbuf);
1380 space = field_width - len;
1381 if (space < 0) space = 0; /* Allow for v. small field_width */
1382 i = len;
1383
1384 /* Right justify in field */
1385 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1386 for (i = 0; i < space; i++) xbuf[i] = ' ';
1387}
1388
1389// Nb: uses a static buffer, each call trashes the last string returned.
1390static Char* make_perc(ULong spacetime, ULong total_spacetime)
1391{
1392 static Char mbuf[32];
1393
1394 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001395 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001396 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1397 return mbuf;
1398}
1399
njnd01fef72005-03-25 23:35:48 +00001400// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001401// bottom-to-top of XCon, and then printed in the reverse order.
1402static UInt pp_XCon(Int fd, XPt* xpt)
1403{
njnd01fef72005-03-25 23:35:48 +00001404 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001405 Int i = 0;
1406 Int n = 0;
1407 Bool is_HTML = ( XHTML == clo_format );
1408 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1409 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1410
njnca82cc02004-11-22 17:18:48 +00001411 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001412
1413 while (True) {
njnd01fef72005-03-25 23:35:48 +00001414 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001415 n++;
1416 if (alloc_xpt == xpt->parent) break;
1417 i++;
1418 xpt = xpt->parent;
1419 }
1420
1421 for (i = n-1; i >= 0; i--) {
1422 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001423 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001424 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1425 }
1426
1427 return n;
1428}
1429
1430// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001431// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001432// sufficient, because function pointers mean that you can call more than
1433// one other function from a single code location. So instead we use the
1434// address of the xpt struct itself, which is guaranteed to be unique.
1435
1436static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1437 ULong total_spacetime)
1438{
1439 UInt i;
1440 XPt *xpt, *child;
1441 UInt L = 0;
1442 UInt c1 = 1;
1443 UInt c2 = 0;
1444 ULong sum = 0;
1445 UInt n;
njnd01fef72005-03-25 23:35:48 +00001446 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001447 Bool is_HTML = ( XHTML == clo_format );
1448 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1449 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1450 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1451 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1452 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1453 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1454 Char* end_hr = ( is_HTML ? "<hr>" :
1455 "=================================" );
1456 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1457
nethercote43a15ce2004-08-30 19:15:12 +00001458 if (total_spacetime == 0) {
1459 SPRINTF(buf, "(No heap memory allocated)\n");
1460 return;
1461 }
1462
1463
nethercotec9f36922004-02-14 16:40:02 +00001464 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1465
1466 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001467 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001468 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001469
nethercote43a15ce2004-08-30 19:15:12 +00001470 // Check that the sum of all children .exact_ST_dbld fields equals
1471 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001472 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001473 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001474 } else {
1475 sum = 0;
1476 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001477 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001478 }
njnca82cc02004-11-22 17:18:48 +00001479 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001480 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001481 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001482 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001483// tl_assert(sum <= xpt->exact_ST_dbld);
1484// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001485// if (sum != xpt->exact_ST_dbld) {
njn68e46592005-08-26 19:42:27 +00001486// VG_(printf)("%lld, %lld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001487// }
1488 }
1489
1490 if (xpt == alloc_xpt) {
1491 SPRINTF(buf, "Heap allocation functions accounted for "
1492 "%s of measured spacetime%s\n",
1493 make_perc(heap_spacetime, total_spacetime), maybe_br);
1494 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001495 // Remember: exact_ST_dbld is space.time *doubled*
1496 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001497 if (is_HTML) {
1498 SPRINTF(buf, "<a name=\"b%x\"></a>"
1499 "Context accounted for "
1500 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1501 xpt, xpt, perc);
1502 } else {
1503 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1504 perc);
1505 }
1506 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001507 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001508 }
1509
nethercote43a15ce2004-08-30 19:15:12 +00001510 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001511 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001512 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001513
1514 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1515 for (i = 0; i < xpt->n_children; i++) {
1516 child = xpt->children[i];
1517
1518 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001519 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001520 UInt n_insig = xpt->n_children - i;
1521 Char* s = ( n_insig == 1 ? "" : "s" );
1522 Char* and = ( 0 == i ? "" : "and " );
1523 Char* other = ( 0 == i ? "" : "other " );
1524 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1525 maybe_li, and, n_insig, other, s, maybe_fli);
1526 break;
1527 }
1528
nethercote43a15ce2004-08-30 19:15:12 +00001529 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001530 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1531 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001532 if (is_HTML) {
1533 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1534
1535 if (child->n_children > 0) {
1536 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1537 } else {
1538 SPRINTF(buf, "%s", perc);
1539 }
njnd01fef72005-03-25 23:35:48 +00001540 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001541 } else {
njnd01fef72005-03-25 23:35:48 +00001542 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001543 }
1544
1545 if (child->n_children > 0) {
1546 enqueue(q, (void*)child);
1547 c2++;
1548 }
1549 }
1550 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1551 c1--;
1552
1553 // Putting markers between levels of the structure:
1554 // c1 tracks how many to go on this level, c2 tracks how many we've
1555 // queued up for the next level while finishing off this level.
1556 // When c1 gets to zero, we've changed levels, so print a marker,
1557 // move c2 into c1, and zero c2.
1558 if (0 == c1) {
1559 L++;
1560 c1 = c2;
1561 c2 = 0;
1562 if (! is_empty_queue(q) ) { // avoid empty one at end
1563 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1564 }
1565 } else {
1566 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1567 }
1568 }
1569 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1570 "%s value for more.\n", end_hr, depth);
1571}
1572
1573static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1574 ULong total_spacetime)
1575{
1576 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001577
nethercotec9f36922004-02-14 16:40:02 +00001578 enqueue(q, xpt);
1579 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1580 destruct_queue(q);
1581}
1582
1583static void
1584write_text_file(ULong total_ST, ULong heap_ST)
1585{
sewardj92645592005-07-23 09:18:34 +00001586 SysRes sres;
1587 Int fd, i;
1588 Char* text_file;
1589 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
nethercotec9f36922004-02-14 16:40:02 +00001590
nethercotec9f36922004-02-14 16:40:02 +00001591 // Open file
1592 text_file = make_filename( base_dir,
1593 ( XText == clo_format ? ".txt" : ".html" ) );
1594
sewardj92645592005-07-23 09:18:34 +00001595 sres = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
nethercotec9f36922004-02-14 16:40:02 +00001596 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00001597 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001598 file_err( text_file );
nethercotec9f36922004-02-14 16:40:02 +00001599 return;
sewardj92645592005-07-23 09:18:34 +00001600 } else {
1601 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001602 }
1603
1604 // Header
1605 if (XHTML == clo_format) {
1606 SPRINTF(buf, "<html>\n"
1607 "<head>\n"
1608 "<title>%s</title>\n"
1609 "</head>\n"
1610 "<body>\n",
1611 text_file);
1612 }
1613
1614 // Command line
sewardj45f4e7c2005-09-27 19:20:21 +00001615 SPRINTF(buf, "Command:");
1616 if (VG_(args_the_exename)) {
1617 SPRINTF(buf, " %s", VG_(args_the_exename));
1618 }
1619 for (i = 0; i < VG_(args_for_client).used; i++) {
1620 if (VG_(args_for_client).strs[i])
1621 SPRINTF(buf, " %s", VG_(args_for_client).strs[i]);
njnd111d102005-09-13 00:46:27 +00001622 }
nethercotec9f36922004-02-14 16:40:02 +00001623 SPRINTF(buf, "\n%s\n", maybe_p);
1624
1625 if (clo_heap)
1626 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1627
njnca82cc02004-11-22 17:18:48 +00001628 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001629 VG_(close)(fd);
nethercotec9f36922004-02-14 16:40:02 +00001630}
1631
1632/*------------------------------------------------------------*/
1633/*--- Finalisation ---*/
1634/*------------------------------------------------------------*/
1635
1636static void
1637print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1638 ULong stack_ST)
1639{
njn99cb9e32005-09-25 17:59:16 +00001640 VG_(message)(Vg_UserMsg, "Total spacetime: %,llu ms.B", total_ST);
nethercotec9f36922004-02-14 16:40:02 +00001641
1642 // Heap --------------------------------------------------------------
1643 if (clo_heap)
1644 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001645 ( 0 == total_ST ? (Char*)"(n/a)"
1646 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001647
1648 // Heap admin --------------------------------------------------------
1649 if (clo_heap_admin)
1650 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001651 ( 0 == total_ST ? (Char*)"(n/a)"
1652 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001653
njnca82cc02004-11-22 17:18:48 +00001654 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001655
1656 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001657 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001658 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001659 ( 0 == stack_ST ? (Char*)"0%"
1660 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001661 }
nethercotec9f36922004-02-14 16:40:02 +00001662
1663 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001664 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001665 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1666 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1667 n_zero_allocs * 100 / n_allocs );
1668 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1669 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1670 n_xpts*sizeof(XPt));
1671 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1672 n_bot_xpts * 100 / n_xpts);
1673 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1674 alloc_xpt->n_children * 100 / n_xpts);
1675 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1676 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1677 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1678 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1679 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1680 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1681 }
1682}
1683
njn51d827b2005-05-09 01:02:08 +00001684static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001685{
1686 ULong total_ST = 0;
1687 ULong heap_ST = 0;
1688 ULong heap_admin_ST = 0;
1689 ULong stack_ST = 0;
1690
1691 // Do a final (empty) sample to show program's end
1692 hp_census();
1693
1694 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001695 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001696 total_ST = heap_ST + heap_admin_ST + stack_ST;
1697 write_hp_file ( );
1698 write_text_file( total_ST, heap_ST );
1699 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1700}
1701
njn51d827b2005-05-09 01:02:08 +00001702/*------------------------------------------------------------*/
1703/*--- Initialisation ---*/
1704/*------------------------------------------------------------*/
1705
1706static void ms_post_clo_init(void)
1707{
1708 ms_interval = 1;
1709
1710 // Do an initial sample for t = 0
1711 hp_census();
1712}
1713
tom151a6392005-11-11 12:30:36 +00001714static void ms_pre_clo_init(void)
njn51d827b2005-05-09 01:02:08 +00001715{
1716 VG_(details_name) ("Massif");
1717 VG_(details_version) (NULL);
1718 VG_(details_description) ("a space profiler");
1719 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1720 VG_(details_bug_reports_to) (VG_BUGS_TO);
1721
1722 // Basic functions
1723 VG_(basic_tool_funcs) (ms_post_clo_init,
1724 ms_instrument,
1725 ms_fini);
1726
1727 // Needs
1728 VG_(needs_libc_freeres)();
1729 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1730 ms_print_usage,
1731 ms_print_debug_usage);
1732 VG_(needs_client_requests) (ms_handle_client_request);
njnfc51f8d2005-06-21 03:20:17 +00001733 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00001734 ms___builtin_new,
1735 ms___builtin_vec_new,
1736 ms_memalign,
1737 ms_calloc,
1738 ms_free,
1739 ms___builtin_delete,
1740 ms___builtin_vec_delete,
1741 ms_realloc,
1742 0 );
1743
1744 // Events to track
1745 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1746 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1747
njn51d827b2005-05-09 01:02:08 +00001748 // HP_Chunks
njnf69f9452005-07-03 17:53:11 +00001749 malloc_list = VG_(HT_construct)( 80021 ); // prime, big
njn51d827b2005-05-09 01:02:08 +00001750
1751 // Dummy node at top of the context structure.
1752 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1753
njn57ca7ab2005-06-21 23:44:58 +00001754 tl_assert( VG_(getcwd)(base_dir, VKI_PATH_MAX) );
njn51d827b2005-05-09 01:02:08 +00001755}
1756
sewardj45f4e7c2005-09-27 19:20:21 +00001757VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00001758
1759/*--------------------------------------------------------------------*/
njnf1c5def2005-08-11 02:17:07 +00001760/*--- end ---*/
nethercotec9f36922004-02-14 16:40:02 +00001761/*--------------------------------------------------------------------*/
1762