blob: 2a65bbda33807d6080b8981ab6eb3db0bd92f122 [file] [log] [blame]
nethercotec9f36922004-02-14 16:40:02 +00001
2/*--------------------------------------------------------------------*/
nethercote996901a2004-08-03 13:29:09 +00003/*--- Massif: a heap profiling tool. ms_main.c ---*/
nethercotec9f36922004-02-14 16:40:02 +00004/*--------------------------------------------------------------------*/
5
6/*
nethercote996901a2004-08-03 13:29:09 +00007 This file is part of Massif, a Valgrind tool for profiling memory
nethercotec9f36922004-02-14 16:40:02 +00008 usage of programs.
9
njn53612422005-03-12 16:22:54 +000010 Copyright (C) 2003-2005 Nicholas Nethercote
njn2bc10122005-05-08 02:10:27 +000011 njn@valgrind.org
nethercotec9f36922004-02-14 16:40:02 +000012
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation; either version 2 of the
16 License, or (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26 02111-1307, USA.
27
28 The GNU General Public License is contained in the file COPYING.
29*/
30
31// Memory profiler. Produces a graph, gives lots of information about
32// allocation contexts, in terms of space.time values (ie. area under the
33// graph). Allocation context information is hierarchical, and can thus
34// be inspected step-wise to an appropriate depth. See comments on data
35// structures below for more info on how things work.
36
nethercote46063202004-09-02 08:51:43 +000037#include "tool.h"
njnea27e462005-05-31 02:38:09 +000038#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +000039#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +000040#include "pub_tool_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +000041#include "pub_tool_libcassert.h"
njneb8896b2005-06-04 20:03:55 +000042#include "pub_tool_libcfile.h"
njne9befc62005-06-11 15:51:30 +000043#include "pub_tool_libcmman.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"
njn717cde52005-05-10 02:47:21 +000046#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000047#include "pub_tool_options.h"
njn31513b42005-06-01 03:09:59 +000048#include "pub_tool_profile.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"
nethercotec9f36922004-02-14 16:40:02 +000052
53#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
54
55/*------------------------------------------------------------*/
56/*--- Overview of operation ---*/
57/*------------------------------------------------------------*/
58
59// Heap blocks are tracked, and the amount of space allocated by various
60// contexts (ie. lines of code, more or less) is also tracked.
61// Periodically, a census is taken, and the amount of space used, at that
62// point, by the most significant (highly allocating) contexts is recorded.
63// Census start off frequently, but are scaled back as the program goes on,
64// so that there are always a good number of them. At the end, overall
65// spacetimes for different contexts (of differing levels of precision) is
66// calculated, the graph is printed, and the text giving spacetimes for the
67// increasingly precise contexts is given.
68//
69// Measures the following:
70// - heap blocks
71// - heap admin bytes
72// - stack(s)
73// - code (code segments loaded at startup, and loaded with mmap)
74// - data (data segments loaded at startup, and loaded/created with mmap,
75// and brk()d segments)
76
77/*------------------------------------------------------------*/
78/*--- Main types ---*/
79/*------------------------------------------------------------*/
80
81// An XPt represents an "execution point", ie. a code address. Each XPt is
82// part of a tree of XPts (an "execution tree", or "XTree"). Each
83// top-to-bottom path through an XTree gives an execution context ("XCon"),
84// and is equivalent to a traditional Valgrind ExeContext.
85//
86// The XPt at the top of an XTree (but below "alloc_xpt") is called a
87// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
88// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
89// bottom-XPTs in that XTree.
90//
91// All XCons have the same top-XPt, "alloc_xpt", which represents all
92// allocation functions like malloc(). It's a bit of a fake XPt, though,
93// and is only used because it makes some of the code simpler.
94//
95// XTrees are bi-directional.
96//
97// > parent < Example: if child1() calls parent() and child2()
98// / | \ also calls parent(), and parent() calls malloc(),
99// | / \ | the XTree will look like this.
100// | v v |
101// child1 child2
102
103typedef struct _XPt XPt;
104
105struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000106 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000107
108 // Bottom-XPts: space for the precise context.
109 // Other XPts: space of all the descendent bottom-XPts.
110 // Nb: this value goes up and down as the program executes.
111 UInt curr_space;
112
113 // An approximate space.time calculation used along the way for selecting
114 // which contexts to include at each census point.
115 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000116 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000117
nethercote43a15ce2004-08-30 19:15:12 +0000118 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000119 // used in the results.
120 // Note that it is *doubled*, to avoid rounding errors.
121 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000122 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000123
124 // n_children and max_children are integers; a very big program might
125 // have more than 65536 allocation points (Konqueror startup has 1800).
126 XPt* parent; // pointer to parent XPt
127 UInt n_children; // number of children
128 UInt max_children; // capacity of children array
129 XPt** children; // pointers to children XPts
130};
131
132// Each census snapshots the most significant XTrees, each XTree having a
133// top-XPt as its root. The 'curr_space' element for each XPt is recorded
134// in the snapshot. The snapshot contains all the XTree's XPts, not in a
135// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000136// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000137//
138// Graph resolution, x-axis: no point having more than about 200 census
139// x-points; you can't see them on the graph. Therefore:
140//
141// - do a census every 1 ms for first 200 --> 200, all (200 ms)
142// - halve (drop half of them) --> 100, every 2nd (200 ms)
143// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
144// - halve --> 100, every 4th (400 ms)
145// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
146// - etc.
147//
148// This isn't exactly right, because we actually drop (N/2)-1 when halving,
149// but it shows the basic idea.
150
151#define MAX_N_CENSI 200 // Keep it even, for simplicity
152
153// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
154// bands, rest get lumped into OTHERS. I only print the top N
155// (cumulative-so-far space-time) at each point. N should be a bit bigger
156// than 19 in case the cumulative space-time doesn't fit with the eventual
157// space-time computed by hp2ps (but it should be close if the samples are
158// evenly spread, since hp2ps does an approximate per-band space-time
159// calculation that just sums the totals; ie. it assumes all samples are
160// the same distance apart).
161
162#define MAX_SNAPSHOTS 32
163
164typedef
165 struct {
166 XPt* xpt;
167 UInt space;
168 }
169 XPtSnapshot;
170
171// An XTree snapshot is stored as an array of of XPt snapshots.
172typedef XPtSnapshot* XTreeSnapshot;
173
174typedef
175 struct {
176 Int ms_time; // Int: must allow -1
177 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
178 UInt others_space;
179 UInt heap_admin_space;
180 UInt stacks_space;
181 }
182 Census;
183
184// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
185// which is a foothold into the XCon at which it was allocated. From
186// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
187// decremented (at deallocation).
188//
189// Nb: first two fields must match core's VgHashNode.
190typedef
191 struct _HP_Chunk {
192 struct _HP_Chunk* next;
193 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000194 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000195 XPt* where; // Where allocated; bottom-XPt
196 }
197 HP_Chunk;
198
199/*------------------------------------------------------------*/
200/*--- Profiling events ---*/
201/*------------------------------------------------------------*/
202
203typedef
204 enum {
205 VgpGetXPt = VgpFini+1,
206 VgpGetXPtSearch,
207 VgpCensus,
208 VgpCensusHeap,
209 VgpCensusSnapshot,
210 VgpCensusTreeSize,
211 VgpUpdateXCon,
212 VgpCalcSpacetime2,
213 VgpPrintHp,
214 VgpPrintXPts,
215 }
njn4be0a692004-11-22 18:10:36 +0000216 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000217
218/*------------------------------------------------------------*/
219/*--- Statistics ---*/
220/*------------------------------------------------------------*/
221
222// Konqueror startup, to give an idea of the numbers involved with a biggish
223// program, with default depth:
224//
225// depth=3 depth=40
226// - 310,000 allocations
227// - 300,000 frees
228// - 15,000 XPts 800,000 XPts
229// - 1,800 top-XPts
230
231static UInt n_xpts = 0;
232static UInt n_bot_xpts = 0;
233static UInt n_allocs = 0;
234static UInt n_zero_allocs = 0;
235static UInt n_frees = 0;
236static UInt n_children_reallocs = 0;
237static UInt n_snapshot_frees = 0;
238
239static UInt n_halvings = 0;
240static UInt n_real_censi = 0;
241static UInt n_fake_censi = 0;
242static UInt n_attempted_censi = 0;
243
244/*------------------------------------------------------------*/
245/*--- Globals ---*/
246/*------------------------------------------------------------*/
247
248#define FILENAME_LEN 256
249
250#define SPRINTF(zz_buf, fmt, args...) \
251 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
252 VG_(write)(fd, (void*)zz_buf, len); \
253 } while (0)
254
255#define BUF_LEN 1024 // general purpose
256static Char buf [BUF_LEN];
257static Char buf2[BUF_LEN];
258static Char buf3[BUF_LEN];
259
nethercote8b5f40c2004-11-02 13:29:50 +0000260static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000261
262static VgHashTable malloc_list = NULL; // HP_Chunks
263
264static UInt n_heap_blocks = 0;
265
njn51d827b2005-05-09 01:02:08 +0000266// Current directory at startup.
267static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000268
269#define MAX_ALLOC_FNS 32 // includes the builtin ones
270
nethercotec7469182004-05-11 09:21:08 +0000271// First few filled in, rest should be zeroed. Zero-terminated vector.
272static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000273static Char* alloc_fns[MAX_ALLOC_FNS] = {
274 "malloc",
275 "operator new(unsigned)",
276 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000277 "operator new(unsigned, std::nothrow_t const&)",
278 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000279 "__builtin_new",
280 "__builtin_vec_new",
281 "calloc",
282 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000283 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000284};
285
286
287/*------------------------------------------------------------*/
288/*--- Command line args ---*/
289/*------------------------------------------------------------*/
290
291#define MAX_DEPTH 50
292
293typedef
294 enum {
295 XText, XHTML,
296 }
297 XFormat;
298
299static Bool clo_heap = True;
300static UInt clo_heap_admin = 8;
301static Bool clo_stacks = True;
302static Bool clo_depth = 3;
303static XFormat clo_format = XText;
304
njn51d827b2005-05-09 01:02:08 +0000305static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000306{
njn45270a22005-03-27 01:00:11 +0000307 VG_BOOL_CLO(arg, "--heap", clo_heap)
308 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000309
njn45270a22005-03-27 01:00:11 +0000310 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
311 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000312
313 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
314 alloc_fns[n_alloc_fns] = & arg[11];
315 n_alloc_fns++;
316 if (n_alloc_fns >= MAX_ALLOC_FNS) {
317 VG_(printf)("Too many alloc functions specified, sorry");
318 VG_(bad_option)(arg);
319 }
320 }
321
322 else if (VG_CLO_STREQ(arg, "--format=text"))
323 clo_format = XText;
324 else if (VG_CLO_STREQ(arg, "--format=html"))
325 clo_format = XHTML;
326
327 else
328 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000329
nethercotec9f36922004-02-14 16:40:02 +0000330 return True;
331}
332
njn51d827b2005-05-09 01:02:08 +0000333static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000334{
335 VG_(printf)(
336" --heap=no|yes profile heap blocks [yes]\n"
337" --heap-admin=<number> average admin bytes per heap block [8]\n"
338" --stacks=no|yes profile stack(s) [yes]\n"
339" --depth=<number> depth of contexts [3]\n"
340" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
341" --format=text|html format of textual output [text]\n"
342 );
343 VG_(replacement_malloc_print_usage)();
344}
345
njn51d827b2005-05-09 01:02:08 +0000346static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000347{
348 VG_(replacement_malloc_print_debug_usage)();
349}
350
351/*------------------------------------------------------------*/
352/*--- Execution contexts ---*/
353/*------------------------------------------------------------*/
354
355// Fake XPt representing all allocation functions like malloc(). Acts as
356// parent node to all top-XPts.
357static XPt* alloc_xpt;
358
359// Cheap allocation for blocks that never need to be freed. Saves about 10%
360// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000361static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000362{
363 static Addr hp = 0; // current heap pointer
364 static Addr hp_lim = 0; // maximum usable byte in current block
365
366 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
367
368 if (hp + n_bytes > hp_lim) {
369 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
370 hp_lim = hp + SUPERBLOCK_SIZE - 1;
371 }
372
373 hp += n_bytes;
374
375 return (void*)(hp - n_bytes);
376}
377
378
379
njnd01fef72005-03-25 23:35:48 +0000380static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000381{
382 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000383 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000384
nethercote43a15ce2004-08-30 19:15:12 +0000385 xpt->curr_space = 0;
386 xpt->approx_ST = 0;
387 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000388
389 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000390
391 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000392 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000393
394 xpt->n_children = 0;
395
396 // If a bottom-XPt, don't allocate space for children. This can be 50%
397 // or more, although it tends to drop as --depth increases (eg. 10% for
398 // konqueror with --depth=20).
399 if ( is_bottom ) {
400 xpt->max_children = 0;
401 xpt->children = NULL;
402 n_bot_xpts++;
403 } else {
404 xpt->max_children = 4;
405 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
406 }
407
408 // Update statistics
409 n_xpts++;
410
411 return xpt;
412}
413
njnd01fef72005-03-25 23:35:48 +0000414static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000415{
416 Int i;
417
njnd01fef72005-03-25 23:35:48 +0000418 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000419 for (i = 0; i < n_alloc_fns; i++) {
420 if (VG_STREQ(buf, alloc_fns[i]))
421 return True;
422 }
423 }
424 return False;
425}
426
427// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
428// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
429// to ensure this in certain cases. See comments below.
430static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
431{
njnd01fef72005-03-25 23:35:48 +0000432 // Static to minimise stack size. +1 for added ~0 IP
433 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000434
435 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000436 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000437 UInt overestimate;
438 Bool reached_bottom;
439
440 VGP_PUSHCC(VgpGetXPt);
441
442 // Want at least clo_depth non-alloc-fn entries in the snapshot.
443 // However, because we have 1 or more (an unknown number, at this point)
444 // alloc-fns ignored, we overestimate the size needed for the stack
445 // snapshot. Then, if necessary, we repeatedly increase the size until
446 // it is enough.
447 overestimate = 2;
448 while (True) {
njnd01fef72005-03-25 23:35:48 +0000449 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000450
njnd01fef72005-03-25 23:35:48 +0000451 // Now we add a dummy "unknown" IP at the end. This is only used if we
452 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000453 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
454 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000455 // the parent's approx_ST wouldn't be equal [or almost equal] to the
456 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000457 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000458
njnd01fef72005-03-25 23:35:48 +0000459 // Skip over alloc functions in ips[].
460 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000461
462 // Must be at least one alloc function, unless client used
463 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000464 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000465
466 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000467 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000468 overestimate += 2;
469 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000470 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000471 } else {
472 break;
473 }
474 }
475 A = L;
njnd01fef72005-03-25 23:35:48 +0000476 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000477 reached_bottom = False;
478
njnd01fef72005-03-25 23:35:48 +0000479 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000480
481 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000482 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000483 while (True) {
njnd01fef72005-03-25 23:35:48 +0000484 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000485 // XXX: linear search, ugh -- about 10% of time for konqueror startup
486 // XXX: tried cacheing last result, only hit about 4% for konqueror
487 // Nb: this search hits about 98% of the time for konqueror
488 VGP_PUSHCC(VgpGetXPtSearch);
489
490 // If we've searched/added deep enough, or run out of EIPs, this is
491 // the bottom XPt.
492 if (L - A + 1 == clo_depth || L == B)
493 reached_bottom = True;
494
495 nC = 0;
496 while (True) {
497 if (nC == xpt->n_children) {
498 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000499 tl_assert(xpt->max_children != 0);
500 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000501 // Expand 'children' if necessary
502 if (xpt->n_children == xpt->max_children) {
503 xpt->max_children *= 2;
504 xpt->children = VG_(realloc)( xpt->children,
505 xpt->max_children * sizeof(XPt*) );
506 n_children_reallocs++;
507 }
njnd01fef72005-03-25 23:35:48 +0000508 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000509 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000510 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000511 break;
512 }
njnd01fef72005-03-25 23:35:48 +0000513 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000514 nC++; // keep looking
515 }
516 VGP_POPCC(VgpGetXPtSearch);
517
518 // Return found/built bottom-XPt.
519 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000520 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000521 VGP_POPCC(VgpGetXPt);
522 return xpt->children[nC];
523 }
524
525 // Descend to next level in XTree, the newly found/built non-bottom-XPt
526 xpt = xpt->children[nC];
527 L++;
528 }
529}
530
531// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
532static void update_XCon(XPt* xpt, Int space_delta)
533{
534 VGP_PUSHCC(VgpUpdateXCon);
535
njnca82cc02004-11-22 17:18:48 +0000536 tl_assert(True == clo_heap);
537 tl_assert(0 != space_delta);
538 tl_assert(NULL != xpt);
539 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000540
541 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000542 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000543 xpt->curr_space += space_delta;
544 xpt = xpt->parent;
545 }
njnca82cc02004-11-22 17:18:48 +0000546 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000547 alloc_xpt->curr_space += space_delta;
548
549 VGP_POPCC(VgpUpdateXCon);
550}
551
552// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000553static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000554{
555 XPt* xpt1 = *(XPt**)n1;
556 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000557 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000558}
559
nethercote43a15ce2004-08-30 19:15:12 +0000560static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000561{
562 XPt* xpt1 = *(XPt**)n1;
563 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000564 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000565}
566
567
568/*------------------------------------------------------------*/
569/*--- A generic Queue ---*/
570/*------------------------------------------------------------*/
571
572typedef
573 struct {
574 UInt head; // Index of first entry
575 UInt tail; // Index of final+1 entry, ie. next free slot
576 UInt max_elems;
577 void** elems;
578 }
579 Queue;
580
581static Queue* construct_queue(UInt size)
582{
583 UInt i;
584 Queue* q = VG_(malloc)(sizeof(Queue));
585 q->head = 0;
586 q->tail = 0;
587 q->max_elems = size;
588 q->elems = VG_(malloc)(size * sizeof(void*));
589 for (i = 0; i < size; i++)
590 q->elems[i] = NULL;
591
592 return q;
593}
594
595static void destruct_queue(Queue* q)
596{
597 VG_(free)(q->elems);
598 VG_(free)(q);
599}
600
601static void shuffle(Queue* dest_q, void** old_elems)
602{
603 UInt i, j;
604 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
605 dest_q->elems[i] = old_elems[j];
606 dest_q->head = 0;
607 dest_q->tail = i;
608 for ( ; i < dest_q->max_elems; i++)
609 dest_q->elems[i] = NULL; // paranoia
610}
611
612// Shuffles elements down. If not enough slots free, increase size. (We
613// don't wait until we've completely run out of space, because there could
614// be lots of shuffling just before that point which would be slow.)
615static void adjust(Queue* q)
616{
617 void** old_elems;
618
njnca82cc02004-11-22 17:18:48 +0000619 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000620 if (q->head < 10) {
621 old_elems = q->elems;
622 q->max_elems *= 2;
623 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
624 shuffle(q, old_elems);
625 VG_(free)(old_elems);
626 } else {
627 shuffle(q, q->elems);
628 }
629}
630
631static void enqueue(Queue* q, void* elem)
632{
633 if (q->tail == q->max_elems)
634 adjust(q);
635 q->elems[q->tail++] = elem;
636}
637
638static Bool is_empty_queue(Queue* q)
639{
640 return (q->head == q->tail);
641}
642
643static void* dequeue(Queue* q)
644{
645 if (is_empty_queue(q))
646 return NULL; // Queue empty
647 else
648 return q->elems[q->head++];
649}
650
651/*------------------------------------------------------------*/
652/*--- malloc() et al replacement wrappers ---*/
653/*------------------------------------------------------------*/
654
655static __inline__
656void add_HP_Chunk(HP_Chunk* hc)
657{
658 n_heap_blocks++;
659 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
660}
661
662static __inline__
663HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
664{
nethercote3d6b6112004-11-04 16:39:43 +0000665 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000666 (VgHashNode***)prev_chunks_next_ptr );
667}
668
669static __inline__
670void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
671{
njnca82cc02004-11-22 17:18:48 +0000672 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000673 n_heap_blocks--;
674 *prev_chunks_next_ptr = hc->next;
675}
676
677// Forward declaration
678static void hp_census(void);
679
nethercote159dfef2004-09-13 13:27:30 +0000680static
njn57735902004-11-25 18:04:54 +0000681void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
682 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000683{
684 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000685 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000686 if (size < 0) return NULL;
687
688 VGP_PUSHCC(VgpCliMalloc);
689
690 // Update statistics
691 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000692 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000693
nethercote57e36b32004-07-10 14:56:28 +0000694 // Allocate and zero if necessary
695 if (!p) {
696 p = VG_(cli_malloc)( align, size );
697 if (!p) {
698 VGP_POPCC(VgpCliMalloc);
699 return NULL;
700 }
701 if (is_zeroed) VG_(memset)(p, 0, size);
702 }
703
704 // Make new HP_Chunk node, add to malloclist
705 hc = VG_(malloc)(sizeof(HP_Chunk));
706 hc->size = size;
707 hc->data = (Addr)p;
708 hc->where = NULL; // paranoia
709 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000710 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000711 if (0 != size)
712 update_XCon(hc->where, size);
713 }
714 add_HP_Chunk( hc );
715
716 // do a census!
717 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000718
719 VGP_POPCC(VgpCliMalloc);
720 return p;
721}
722
723static __inline__
724void die_block ( void* p, Bool custom_free )
725{
nethercote57e36b32004-07-10 14:56:28 +0000726 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000727
728 VGP_PUSHCC(VgpCliMalloc);
729
730 // Update statistics
731 n_frees++;
732
nethercote57e36b32004-07-10 14:56:28 +0000733 // Remove HP_Chunk from malloclist
734 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000735 if (hc == NULL)
736 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000737 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000738 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000739
740 if (clo_heap && hc->size != 0)
741 update_XCon(hc->where, -hc->size);
742
nethercote57e36b32004-07-10 14:56:28 +0000743 VG_(free)( hc );
744
745 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000746 if (!custom_free)
747 VG_(cli_free)( p );
748
nethercote57e36b32004-07-10 14:56:28 +0000749 // do a census!
750 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000751
nethercotec9f36922004-02-14 16:40:02 +0000752 VGP_POPCC(VgpCliMalloc);
753}
754
755
njn51d827b2005-05-09 01:02:08 +0000756static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000757{
njn57735902004-11-25 18:04:54 +0000758 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000759}
760
njn51d827b2005-05-09 01:02:08 +0000761static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000762{
njn57735902004-11-25 18:04:54 +0000763 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000764}
765
njn51d827b2005-05-09 01:02:08 +0000766static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000767{
njn57735902004-11-25 18:04:54 +0000768 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000769}
770
njn51d827b2005-05-09 01:02:08 +0000771static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000772{
njn57735902004-11-25 18:04:54 +0000773 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000774}
775
njn51d827b2005-05-09 01:02:08 +0000776static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000777{
njn57735902004-11-25 18:04:54 +0000778 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000779}
780
njn51d827b2005-05-09 01:02:08 +0000781static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000782{
783 die_block( p, /*custom_free*/False );
784}
785
njn51d827b2005-05-09 01:02:08 +0000786static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000787{
788 die_block( p, /*custom_free*/False);
789}
790
njn51d827b2005-05-09 01:02:08 +0000791static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000792{
793 die_block( p, /*custom_free*/False );
794}
795
njn51d827b2005-05-09 01:02:08 +0000796static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000797{
798 HP_Chunk* hc;
799 HP_Chunk** remove_handle;
800 Int i;
801 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000802 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000803 XPt *old_where, *new_where;
804
805 VGP_PUSHCC(VgpCliMalloc);
806
807 // First try and find the block.
808 hc = get_HP_Chunk ( p_old, &remove_handle );
809 if (hc == NULL) {
810 VGP_POPCC(VgpCliMalloc);
811 return NULL; // must have been a bogus free()
812 }
813
njnca82cc02004-11-22 17:18:48 +0000814 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000815 old_size = hc->size;
816
817 if (new_size <= old_size) {
818 // new size is smaller or same; block not moved
819 p_new = p_old;
820
821 } else {
822 // new size is bigger; make new block, copy shared contents, free old
823 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
824
825 for (i = 0; i < old_size; i++)
826 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
827
828 VG_(cli_free)(p_old);
829 }
830
831 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000832 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000833
834 // Update HP_Chunk
835 hc->data = (Addr)p_new;
836 hc->size = new_size;
837 hc->where = new_where;
838
839 // Update XPt curr_space fields
840 if (clo_heap) {
841 if (0 != old_size) update_XCon(old_where, -old_size);
842 if (0 != new_size) update_XCon(new_where, new_size);
843 }
844
845 // If block has moved, have to remove and reinsert in the malloclist
846 // (since the updated 'data' field is the hash lookup key).
847 if (p_new != p_old) {
848 remove_HP_Chunk(hc, remove_handle);
849 add_HP_Chunk(hc);
850 }
851
852 VGP_POPCC(VgpCliMalloc);
853 return p_new;
854}
855
856
857/*------------------------------------------------------------*/
858/*--- Taking a census ---*/
859/*------------------------------------------------------------*/
860
861static Census censi[MAX_N_CENSI];
862static UInt curr_census = 0;
863
864// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000865static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000866{
thughes4ad52d02004-06-27 17:37:21 +0000867 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000868 return False;
869}
870
871static UInt get_xtree_size(XPt* xpt, UInt ix)
872{
873 UInt i;
874
nethercote43a15ce2004-08-30 19:15:12 +0000875 // If no memory allocated at all, nothing interesting to record.
876 if (alloc_xpt->curr_space == 0) return 0;
877
878 // Ignore sub-XTrees that account for a miniscule fraction of current
879 // allocated space.
880 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000881 ix++;
882
883 // Count all (non-zero) descendent XPts
884 for (i = 0; i < xpt->n_children; i++)
885 ix = get_xtree_size(xpt->children[i], ix);
886 }
887 return ix;
888}
889
890static
891UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
892{
893 UInt i;
894
nethercote43a15ce2004-08-30 19:15:12 +0000895 // Structure of this function mirrors that of get_xtree_size().
896
897 if (alloc_xpt->curr_space == 0) return 0;
898
899 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000900 xtree_snapshot[ix].xpt = xpt;
901 xtree_snapshot[ix].space = xpt->curr_space;
902 ix++;
903
nethercotec9f36922004-02-14 16:40:02 +0000904 for (i = 0; i < xpt->n_children; i++)
905 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
906 }
907 return ix;
908}
909
910static UInt ms_interval;
911static UInt do_every_nth_census = 30;
912
913// Weed out half the censi; we choose those that represent the smallest
914// time-spans, because that loses the least information.
915//
916// Algorithm for N censi: We find the census representing the smallest
917// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
918// (It's (N/2)-1 because we never remove the first and last censi.)
919// We have to do this one census at a time, rather than finding the (N/2)-1
920// smallest censi in one hit, because when a census is removed, it's
921// neighbours immediately cover greater timespans. So it's N^2, but N only
922// equals 200, and this is only done every 100 censi, which is not too often.
923static void halve_censi(void)
924{
925 Int i, jp, j, jn, k;
926 Census* min_census;
927
928 n_halvings++;
929 if (VG_(clo_verbosity) > 1)
930 VG_(message)(Vg_UserMsg, "Halving censi...");
931
932 // Sets j to the index of the first not-yet-removed census at or after i
933 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000934 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000935
936 for (i = 2; i < MAX_N_CENSI; i += 2) {
937 // Find the censi representing the smallest timespan. The timespan
938 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
939 // censi A and B. We don't consider the first and last censi for
940 // removal.
941 Int min_span = 0x7fffffff;
942 Int min_j = 0;
943
944 // Initial triple: (prev, curr, next) == (jp, j, jn)
945 jp = 0;
946 FIND_CENSUS(1, j);
947 FIND_CENSUS(j+1, jn);
948 while (jn < MAX_N_CENSI) {
949 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000950 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000951 if (timespan < min_span) {
952 min_span = timespan;
953 min_j = j;
954 }
955 // Move on to next triple
956 jp = j;
957 j = jn;
958 FIND_CENSUS(jn+1, jn);
959 }
960 // We've found the least important census, now remove it
961 min_census = & censi[ min_j ];
962 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
963 n_snapshot_frees++;
964 VG_(free)(min_census->xtree_snapshots[k]);
965 min_census->xtree_snapshots[k] = NULL;
966 }
967 min_census->ms_time = -1;
968 }
969
970 // Slide down the remaining censi over the removed ones. The '<=' is
971 // because we are removing on (N/2)-1, rather than N/2.
972 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
973 FIND_CENSUS(j, j);
974 if (i != j) {
975 censi[i] = censi[j];
976 }
977 }
978 curr_census = i;
979
980 // Double intervals
981 ms_interval *= 2;
982 do_every_nth_census *= 2;
983
984 if (VG_(clo_verbosity) > 1)
985 VG_(message)(Vg_UserMsg, "...done");
986}
987
988// Take a census. Census time seems to be insignificant (usually <= 0 ms,
989// almost always <= 1ms) so don't have to worry about subtracting it from
990// running time in any way.
991//
992// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
993// 50ms!
994static void hp_census(void)
995{
996 static UInt ms_prev_census = 0;
997 static UInt ms_next_census = 0; // zero allows startup census
998
999 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001000 Census* census;
1001
1002 VGP_PUSHCC(VgpCensus);
1003
1004 // Only do a census if it's time
1005 ms_time = VG_(read_millisecond_timer)();
1006 ms_time_since_prev = ms_time - ms_prev_census;
1007 if (ms_time < ms_next_census) {
1008 n_fake_censi++;
1009 VGP_POPCC(VgpCensus);
1010 return;
1011 }
1012 n_real_censi++;
1013
1014 census = & censi[curr_census];
1015
1016 census->ms_time = ms_time;
1017
1018 // Heap: snapshot the K most significant XTrees -------------------
1019 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001020 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001021 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1022 ? alloc_xpt->n_children
1023 : MAX_SNAPSHOTS); // max out
1024
nethercote43a15ce2004-08-30 19:15:12 +00001025 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001026 // We *do not* do it for any non-top-XPTs.
1027 for (i = 0; i < alloc_xpt->n_children; i++) {
1028 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001029 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001030 }
nethercote43a15ce2004-08-30 19:15:12 +00001031 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001032 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001033 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001034
1035 VGP_PUSHCC(VgpCensusHeap);
1036
1037 // For each significant top-level XPt, record space info about its
1038 // entire XTree, in a single census entry.
1039 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1040 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001041 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001042 for (i = 0; i < K; i++) {
1043 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001044// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1045 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001046 VGP_PUSHCC(VgpCensusTreeSize);
1047 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1048 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001049
1050 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1051 // insignificant) then don't take any more snapshots.
1052 if (0 == xtree_size) break;
1053
1054 // Make array of the appropriate size (+1 for zero termination,
1055 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001056 census->xtree_snapshots[i] =
1057 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001058 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001059 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1060 (xtree_size+1) * sizeof(XPtSnapshot));
1061
1062 // Take space-snapshot: copy 'curr_space' for every XPt in the
1063 // XTree into the snapshot array, along with pointers to the XPts.
1064 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001065 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001066 // saves a lot of memory and up to 40% time with big --depth valus.
1067 VGP_PUSHCC(VgpCensusSnapshot);
1068 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1069 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001070 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001071 VGP_POPCC(VgpCensusSnapshot);
1072 }
1073// VG_(printf)("\n\n");
1074 // Zero-terminate 'xtree_snapshot' array
1075 census->xtree_snapshots[i] = NULL;
1076
1077 VGP_POPCC(VgpCensusHeap);
1078
1079 //VG_(printf)("printed %d censi\n", K);
1080
1081 // Lump the rest into a single "others" entry.
1082 census->others_space = 0;
1083 for (i = K; i < alloc_xpt->n_children; i++) {
1084 census->others_space += alloc_xpt->children[i]->curr_space;
1085 }
1086 }
1087
1088 // Heap admin -------------------------------------------------------
1089 if (clo_heap_admin > 0)
1090 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1091
1092 // Stack(s) ---------------------------------------------------------
1093 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001094 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001095 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001096 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001097 }
1098
1099 // Finish, update interval if necessary -----------------------------
1100 curr_census++;
1101 census = NULL; // don't use again now that curr_census changed
1102
1103 // Halve the entries, if our census table is full
1104 if (MAX_N_CENSI == curr_census) {
1105 halve_censi();
1106 }
1107
1108 // Take time for next census from now, rather than when this census
1109 // should have happened. Because, if there's a big gap due to a kernel
1110 // operation, there's no point doing catch-up censi every BB for a while
1111 // -- that would just give N censi at almost the same time.
1112 if (VG_(clo_verbosity) > 1) {
1113 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1114 VG_(read_millisecond_timer)() - ms_time );
1115 }
1116 ms_prev_census = ms_time;
1117 ms_next_census = ms_time + ms_interval;
1118 //ms_next_census += ms_interval;
1119
1120 //VG_(printf)("Next: %d ms\n", ms_next_census);
1121
1122 VGP_POPCC(VgpCensus);
1123}
1124
1125/*------------------------------------------------------------*/
1126/*--- Tracked events ---*/
1127/*------------------------------------------------------------*/
1128
nethercote8b5f40c2004-11-02 13:29:50 +00001129static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001130{
1131 sigstacks_space += len;
1132}
1133
nethercote8b5f40c2004-11-02 13:29:50 +00001134static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001135{
njnca82cc02004-11-22 17:18:48 +00001136 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001137 sigstacks_space -= len;
1138}
1139
1140/*------------------------------------------------------------*/
1141/*--- Client Requests ---*/
1142/*------------------------------------------------------------*/
1143
njn51d827b2005-05-09 01:02:08 +00001144static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001145{
1146 switch (argv[0]) {
1147 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001148 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001149 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001150 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001151 *ret = 0;
njn57735902004-11-25 18:04:54 +00001152 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001153 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001154 return True;
1155 }
1156 case VG_USERREQ__FREELIKE_BLOCK: {
1157 void* p = (void*)argv[1];
1158 *ret = 0;
1159 die_block( p, /*custom_free*/True );
1160 return True;
1161 }
1162 default:
1163 *ret = 0;
1164 return False;
1165 }
1166}
1167
1168/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001169/*--- Instrumentation ---*/
1170/*------------------------------------------------------------*/
1171
njn51d827b2005-05-09 01:02:08 +00001172static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1173 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001174{
sewardjd54babf2005-03-21 00:55:49 +00001175 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001176 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001177}
1178
1179/*------------------------------------------------------------*/
1180/*--- Spacetime recomputation ---*/
1181/*------------------------------------------------------------*/
1182
nethercote43a15ce2004-08-30 19:15:12 +00001183// Although we've been calculating space-time along the way, because the
1184// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001185// might not agree with what hp2ps sees, because we've thrown away some of
1186// the information. So recompute it at the scale that hp2ps sees, so we can
1187// confidently determine which contexts hp2ps will choose for displaying as
1188// distinct bands. This recomputation only happens to the significant ones
1189// that get printed in the .hp file, so it's cheap.
1190//
nethercote43a15ce2004-08-30 19:15:12 +00001191// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001192// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1193// where
1194// a[N] is the space at census N
1195// d(A,B) is the time interval between censi A and B
1196// and
1197// d(A,B) + d(B,C) == d(A,C)
1198//
1199// Key point: we can calculate the area for a census without knowing the
1200// previous or subsequent censi's space; because any over/underestimates
1201// for this census will be reversed in the next, balancing out. This is
1202// important, as getting the previous/next census entry for a particular
1203// AP is a pain with this data structure, but getting the prev/next
1204// census time is easy.
1205//
nethercote43a15ce2004-08-30 19:15:12 +00001206// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001207// The ULong* values are all running totals, hence the use of "+=" everywhere.
1208
1209// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001210static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001211 ULong* twice_heap_ST,
1212 ULong* twice_heap_admin_ST,
1213 ULong* twice_stack_ST)
1214{
1215 UInt i, j;
1216 XPtSnapshot* xpt_snapshot;
1217
1218 // Heap --------------------------------------------------------
1219 if (clo_heap) {
1220 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001221 // Compute total heap exact_ST_dbld for the entire XTree using only
1222 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001223 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1224
nethercote43a15ce2004-08-30 19:15:12 +00001225 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1226 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001227 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1228 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001229 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001230 }
1231 }
1232 *twice_heap_ST += d_t1_t2 * census->others_space;
1233 }
1234
1235 // Heap admin --------------------------------------------------
1236 if (clo_heap_admin > 0)
1237 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1238
1239 // Stack(s) ----------------------------------------------------
1240 if (clo_stacks)
1241 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1242}
1243
1244// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001245static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001246{
1247 UInt i, N = curr_census;
1248
1249 VGP_PUSHCC(VgpCalcSpacetime2);
1250
1251 *heap2 = 0;
1252 *heap_admin2 = 0;
1253 *stack2 = 0;
1254
1255 if (N <= 1)
1256 return;
1257
nethercote43a15ce2004-08-30 19:15:12 +00001258 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1259 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001260
1261 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001262 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1263 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001264 }
1265
nethercote43a15ce2004-08-30 19:15:12 +00001266 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1267 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001268 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1269 *heap2 /= 2;
1270 *heap_admin2 /= 2;
1271 *stack2 /= 2;
1272
1273 VGP_POPCC(VgpCalcSpacetime2);
1274}
1275
1276/*------------------------------------------------------------*/
1277/*--- Writing the graph file ---*/
1278/*------------------------------------------------------------*/
1279
1280static Char* make_filename(Char* dir, Char* suffix)
1281{
1282 Char* filename;
1283
1284 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1285 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1286 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1287
1288 return filename;
1289}
1290
1291// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1292static Char* clean_fnname(Char *d, Char* s)
1293{
1294 Char* dorig = d;
1295 while (*s) {
1296 if (' ' == *s) { *d = '%'; }
1297 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1298 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1299 else { *d = *s; };
1300 s++;
1301 d++;
1302 }
1303 *d = '\0';
1304 return dorig;
1305}
1306
1307static void file_err ( Char* file )
1308{
njn02bc4b82005-05-15 17:28:26 +00001309 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001310 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1311}
1312
1313/* Format, by example:
1314
1315 JOB "a.out -p"
1316 DATE "Fri Apr 17 11:43:45 1992"
1317 SAMPLE_UNIT "seconds"
1318 VALUE_UNIT "bytes"
1319 BEGIN_SAMPLE 0.00
1320 SYSTEM 24
1321 END_SAMPLE 0.00
1322 BEGIN_SAMPLE 1.00
1323 elim 180
1324 insert 24
1325 intersect 12
1326 disin 60
1327 main 12
1328 reduce 20
1329 SYSTEM 12
1330 END_SAMPLE 1.00
1331 MARK 1.50
1332 MARK 1.75
1333 MARK 1.80
1334 BEGIN_SAMPLE 2.00
1335 elim 192
1336 insert 24
1337 intersect 12
1338 disin 84
1339 main 12
1340 SYSTEM 24
1341 END_SAMPLE 2.00
1342 BEGIN_SAMPLE 2.82
1343 END_SAMPLE 2.82
1344 */
1345static void write_hp_file(void)
1346{
1347 Int i, j;
1348 Int fd, res;
1349 Char *hp_file, *ps_file, *aux_file;
1350 Char* cmdfmt;
1351 Char* cmdbuf;
1352 Int cmdlen;
1353
1354 VGP_PUSHCC(VgpPrintHp);
1355
1356 // Open file
1357 hp_file = make_filename( base_dir, ".hp" );
1358 ps_file = make_filename( base_dir, ".ps" );
1359 aux_file = make_filename( base_dir, ".aux" );
1360 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1361 VKI_S_IRUSR|VKI_S_IWUSR);
1362 if (fd < 0) {
1363 file_err( hp_file );
1364 VGP_POPCC(VgpPrintHp);
1365 return;
1366 }
1367
1368 // File header, including command line
1369 SPRINTF(buf, "JOB \"");
1370 for (i = 0; i < VG_(client_argc); i++)
1371 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1372 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1373 "DATE \"\"\n"
1374 "SAMPLE_UNIT \"ms\"\n"
1375 "VALUE_UNIT \"bytes\"\n", ms_interval);
1376
1377 // Censi
1378 for (i = 0; i < curr_census; i++) {
1379 Census* census = & censi[i];
1380
1381 // Census start
1382 SPRINTF(buf, "MARK %d.0\n"
1383 "BEGIN_SAMPLE %d.0\n",
1384 census->ms_time, census->ms_time);
1385
1386 // Heap -----------------------------------------------------------
1387 if (clo_heap) {
1388 // Print all the significant XPts from that census
1389 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1390 // Grab the jth top-XPt
1391 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001392 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001393 VG_(sprintf)(buf2, "???");
1394 }
njnd01fef72005-03-25 23:35:48 +00001395 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001396 clean_fnname(buf3, buf2), xtree_snapshot->space);
1397 }
1398
1399 // Remaining heap block alloc points, combined
1400 if (census->others_space > 0)
1401 SPRINTF(buf, "other %d\n", census->others_space);
1402 }
1403
1404 // Heap admin -----------------------------------------------------
1405 if (clo_heap_admin > 0 && census->heap_admin_space)
1406 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1407
1408 // Stack(s) -------------------------------------------------------
1409 if (clo_stacks)
1410 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1411
1412 // Census end
1413 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1414 }
1415
1416 // Close file
njnca82cc02004-11-22 17:18:48 +00001417 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001418 VG_(close)(fd);
1419
1420 // Attempt to convert file using hp2ps
1421 cmdfmt = "%s/hp2ps -c -t1 %s";
1422 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1423 + VG_(strlen)(cmdfmt);
1424 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1425 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1426 res = VG_(system)(cmdbuf);
1427 VG_(free)(cmdbuf);
1428 if (res != 0) {
1429 VG_(message)(Vg_UserMsg,
1430 "Conversion to PostScript failed. Try converting manually.");
1431 } else {
1432 // remove the .hp and .aux file
1433 VG_(unlink)(hp_file);
1434 VG_(unlink)(aux_file);
1435 }
1436
1437 VG_(free)(hp_file);
1438 VG_(free)(ps_file);
1439 VG_(free)(aux_file);
1440
1441 VGP_POPCC(VgpPrintHp);
1442}
1443
1444/*------------------------------------------------------------*/
1445/*--- Writing the XPt text/HTML file ---*/
1446/*------------------------------------------------------------*/
1447
1448static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1449{
1450 int i, len, space;
1451
1452 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1453 len = VG_(strlen)(xbuf);
1454 space = field_width - len;
1455 if (space < 0) space = 0; /* Allow for v. small field_width */
1456 i = len;
1457
1458 /* Right justify in field */
1459 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1460 for (i = 0; i < space; i++) xbuf[i] = ' ';
1461}
1462
1463// Nb: uses a static buffer, each call trashes the last string returned.
1464static Char* make_perc(ULong spacetime, ULong total_spacetime)
1465{
1466 static Char mbuf[32];
1467
1468 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001469 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001470 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1471 return mbuf;
1472}
1473
njnd01fef72005-03-25 23:35:48 +00001474// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001475// bottom-to-top of XCon, and then printed in the reverse order.
1476static UInt pp_XCon(Int fd, XPt* xpt)
1477{
njnd01fef72005-03-25 23:35:48 +00001478 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001479 Int i = 0;
1480 Int n = 0;
1481 Bool is_HTML = ( XHTML == clo_format );
1482 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1483 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1484
njnca82cc02004-11-22 17:18:48 +00001485 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001486
1487 while (True) {
njnd01fef72005-03-25 23:35:48 +00001488 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001489 n++;
1490 if (alloc_xpt == xpt->parent) break;
1491 i++;
1492 xpt = xpt->parent;
1493 }
1494
1495 for (i = n-1; i >= 0; i--) {
1496 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001497 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001498 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1499 }
1500
1501 return n;
1502}
1503
1504// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001505// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001506// sufficient, because function pointers mean that you can call more than
1507// one other function from a single code location. So instead we use the
1508// address of the xpt struct itself, which is guaranteed to be unique.
1509
1510static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1511 ULong total_spacetime)
1512{
1513 UInt i;
1514 XPt *xpt, *child;
1515 UInt L = 0;
1516 UInt c1 = 1;
1517 UInt c2 = 0;
1518 ULong sum = 0;
1519 UInt n;
njnd01fef72005-03-25 23:35:48 +00001520 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001521 Bool is_HTML = ( XHTML == clo_format );
1522 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1523 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1524 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1525 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1526 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1527 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1528 Char* end_hr = ( is_HTML ? "<hr>" :
1529 "=================================" );
1530 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1531
nethercote43a15ce2004-08-30 19:15:12 +00001532 if (total_spacetime == 0) {
1533 SPRINTF(buf, "(No heap memory allocated)\n");
1534 return;
1535 }
1536
1537
nethercotec9f36922004-02-14 16:40:02 +00001538 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1539
1540 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001541 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001542 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001543
nethercote43a15ce2004-08-30 19:15:12 +00001544 // Check that the sum of all children .exact_ST_dbld fields equals
1545 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001546 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001547 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001548 } else {
1549 sum = 0;
1550 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001551 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001552 }
njnca82cc02004-11-22 17:18:48 +00001553 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001554 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001555 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001556 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001557// tl_assert(sum <= xpt->exact_ST_dbld);
1558// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001559// if (sum != xpt->exact_ST_dbld) {
1560// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001561// }
1562 }
1563
1564 if (xpt == alloc_xpt) {
1565 SPRINTF(buf, "Heap allocation functions accounted for "
1566 "%s of measured spacetime%s\n",
1567 make_perc(heap_spacetime, total_spacetime), maybe_br);
1568 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001569 // Remember: exact_ST_dbld is space.time *doubled*
1570 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001571 if (is_HTML) {
1572 SPRINTF(buf, "<a name=\"b%x\"></a>"
1573 "Context accounted for "
1574 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1575 xpt, xpt, perc);
1576 } else {
1577 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1578 perc);
1579 }
1580 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001581 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001582 }
1583
nethercote43a15ce2004-08-30 19:15:12 +00001584 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001585 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001586 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001587
1588 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1589 for (i = 0; i < xpt->n_children; i++) {
1590 child = xpt->children[i];
1591
1592 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001593 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001594 UInt n_insig = xpt->n_children - i;
1595 Char* s = ( n_insig == 1 ? "" : "s" );
1596 Char* and = ( 0 == i ? "" : "and " );
1597 Char* other = ( 0 == i ? "" : "other " );
1598 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1599 maybe_li, and, n_insig, other, s, maybe_fli);
1600 break;
1601 }
1602
nethercote43a15ce2004-08-30 19:15:12 +00001603 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001604 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1605 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001606 if (is_HTML) {
1607 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1608
1609 if (child->n_children > 0) {
1610 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1611 } else {
1612 SPRINTF(buf, "%s", perc);
1613 }
njnd01fef72005-03-25 23:35:48 +00001614 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001615 } else {
njnd01fef72005-03-25 23:35:48 +00001616 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001617 }
1618
1619 if (child->n_children > 0) {
1620 enqueue(q, (void*)child);
1621 c2++;
1622 }
1623 }
1624 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1625 c1--;
1626
1627 // Putting markers between levels of the structure:
1628 // c1 tracks how many to go on this level, c2 tracks how many we've
1629 // queued up for the next level while finishing off this level.
1630 // When c1 gets to zero, we've changed levels, so print a marker,
1631 // move c2 into c1, and zero c2.
1632 if (0 == c1) {
1633 L++;
1634 c1 = c2;
1635 c2 = 0;
1636 if (! is_empty_queue(q) ) { // avoid empty one at end
1637 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1638 }
1639 } else {
1640 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1641 }
1642 }
1643 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1644 "%s value for more.\n", end_hr, depth);
1645}
1646
1647static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1648 ULong total_spacetime)
1649{
1650 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001651
nethercotec9f36922004-02-14 16:40:02 +00001652 enqueue(q, xpt);
1653 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1654 destruct_queue(q);
1655}
1656
1657static void
1658write_text_file(ULong total_ST, ULong heap_ST)
1659{
1660 Int fd, i;
1661 Char* text_file;
1662 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1663
1664 VGP_PUSHCC(VgpPrintXPts);
1665
1666 // Open file
1667 text_file = make_filename( base_dir,
1668 ( XText == clo_format ? ".txt" : ".html" ) );
1669
1670 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1671 VKI_S_IRUSR|VKI_S_IWUSR);
1672 if (fd < 0) {
1673 file_err( text_file );
1674 VGP_POPCC(VgpPrintXPts);
1675 return;
1676 }
1677
1678 // Header
1679 if (XHTML == clo_format) {
1680 SPRINTF(buf, "<html>\n"
1681 "<head>\n"
1682 "<title>%s</title>\n"
1683 "</head>\n"
1684 "<body>\n",
1685 text_file);
1686 }
1687
1688 // Command line
1689 SPRINTF(buf, "Command: ");
1690 for (i = 0; i < VG_(client_argc); i++)
1691 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1692 SPRINTF(buf, "\n%s\n", maybe_p);
1693
1694 if (clo_heap)
1695 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1696
njnca82cc02004-11-22 17:18:48 +00001697 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001698 VG_(close)(fd);
1699
1700 VGP_POPCC(VgpPrintXPts);
1701}
1702
1703/*------------------------------------------------------------*/
1704/*--- Finalisation ---*/
1705/*------------------------------------------------------------*/
1706
1707static void
1708print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1709 ULong stack_ST)
1710{
1711 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1712
1713 // Heap --------------------------------------------------------------
1714 if (clo_heap)
1715 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001716 ( 0 == total_ST ? (Char*)"(n/a)"
1717 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001718
1719 // Heap admin --------------------------------------------------------
1720 if (clo_heap_admin)
1721 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001722 ( 0 == total_ST ? (Char*)"(n/a)"
1723 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001724
njnca82cc02004-11-22 17:18:48 +00001725 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001726
1727 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001728 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001729 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001730 ( 0 == stack_ST ? (Char*)"0%"
1731 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001732 }
nethercotec9f36922004-02-14 16:40:02 +00001733
1734 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001735 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001736 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1737 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1738 n_zero_allocs * 100 / n_allocs );
1739 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1740 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1741 n_xpts*sizeof(XPt));
1742 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1743 n_bot_xpts * 100 / n_xpts);
1744 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1745 alloc_xpt->n_children * 100 / n_xpts);
1746 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1747 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1748 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1749 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1750 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1751 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1752 }
1753}
1754
njn51d827b2005-05-09 01:02:08 +00001755static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001756{
1757 ULong total_ST = 0;
1758 ULong heap_ST = 0;
1759 ULong heap_admin_ST = 0;
1760 ULong stack_ST = 0;
1761
1762 // Do a final (empty) sample to show program's end
1763 hp_census();
1764
1765 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001766 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001767 total_ST = heap_ST + heap_admin_ST + stack_ST;
1768 write_hp_file ( );
1769 write_text_file( total_ST, heap_ST );
1770 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1771}
1772
njn51d827b2005-05-09 01:02:08 +00001773/*------------------------------------------------------------*/
1774/*--- Initialisation ---*/
1775/*------------------------------------------------------------*/
1776
1777static void ms_post_clo_init(void)
1778{
1779 ms_interval = 1;
1780
1781 // Do an initial sample for t = 0
1782 hp_census();
1783}
1784
1785static void ms_pre_clo_init()
1786{
1787 VG_(details_name) ("Massif");
1788 VG_(details_version) (NULL);
1789 VG_(details_description) ("a space profiler");
1790 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1791 VG_(details_bug_reports_to) (VG_BUGS_TO);
1792
1793 // Basic functions
1794 VG_(basic_tool_funcs) (ms_post_clo_init,
1795 ms_instrument,
1796 ms_fini);
1797
1798 // Needs
1799 VG_(needs_libc_freeres)();
1800 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1801 ms_print_usage,
1802 ms_print_debug_usage);
1803 VG_(needs_client_requests) (ms_handle_client_request);
1804
1805 // Malloc replacement
1806 VG_(malloc_funcs) (ms_malloc,
1807 ms___builtin_new,
1808 ms___builtin_vec_new,
1809 ms_memalign,
1810 ms_calloc,
1811 ms_free,
1812 ms___builtin_delete,
1813 ms___builtin_vec_delete,
1814 ms_realloc,
1815 0 );
1816
1817 // Events to track
1818 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1819 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1820
1821 // Profiling events
1822 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1823 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1824 VG_(register_profile_event)(VgpCensus, "census");
1825 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1826 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1827 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1828 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1829 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1830 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1831 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1832
1833 // HP_Chunks
1834 malloc_list = VG_(HT_construct)();
1835
1836 // Dummy node at top of the context structure.
1837 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1838
1839 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1840}
1841
1842VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001843
1844/*--------------------------------------------------------------------*/
1845/*--- end ms_main.c ---*/
1846/*--------------------------------------------------------------------*/
1847