blob: 3c3c99dc19d00e8c7e55ba7e4a774cee91123cdf [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"
njn31513b42005-06-01 03:09:59 +000049#include "pub_tool_profile.h"
njn717cde52005-05-10 02:47:21 +000050#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000051#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000052#include "pub_tool_tooliface.h"
sewardj45f4e7c2005-09-27 19:20:21 +000053#include "pub_tool_clientstate.h"
nethercotec9f36922004-02-14 16:40:02 +000054
55#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
56
57/*------------------------------------------------------------*/
58/*--- Overview of operation ---*/
59/*------------------------------------------------------------*/
60
61// Heap blocks are tracked, and the amount of space allocated by various
62// contexts (ie. lines of code, more or less) is also tracked.
63// Periodically, a census is taken, and the amount of space used, at that
64// point, by the most significant (highly allocating) contexts is recorded.
65// Census start off frequently, but are scaled back as the program goes on,
66// so that there are always a good number of them. At the end, overall
67// spacetimes for different contexts (of differing levels of precision) is
68// calculated, the graph is printed, and the text giving spacetimes for the
69// increasingly precise contexts is given.
70//
71// Measures the following:
72// - heap blocks
73// - heap admin bytes
74// - stack(s)
75// - code (code segments loaded at startup, and loaded with mmap)
76// - data (data segments loaded at startup, and loaded/created with mmap,
77// and brk()d segments)
78
79/*------------------------------------------------------------*/
80/*--- Main types ---*/
81/*------------------------------------------------------------*/
82
83// An XPt represents an "execution point", ie. a code address. Each XPt is
84// part of a tree of XPts (an "execution tree", or "XTree"). Each
85// top-to-bottom path through an XTree gives an execution context ("XCon"),
86// and is equivalent to a traditional Valgrind ExeContext.
87//
88// The XPt at the top of an XTree (but below "alloc_xpt") is called a
89// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
90// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
91// bottom-XPTs in that XTree.
92//
93// All XCons have the same top-XPt, "alloc_xpt", which represents all
94// allocation functions like malloc(). It's a bit of a fake XPt, though,
95// and is only used because it makes some of the code simpler.
96//
97// XTrees are bi-directional.
98//
99// > parent < Example: if child1() calls parent() and child2()
100// / | \ also calls parent(), and parent() calls malloc(),
101// | / \ | the XTree will look like this.
102// | v v |
103// child1 child2
104
105typedef struct _XPt XPt;
106
107struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000108 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000109
110 // Bottom-XPts: space for the precise context.
111 // Other XPts: space of all the descendent bottom-XPts.
112 // Nb: this value goes up and down as the program executes.
113 UInt curr_space;
114
115 // An approximate space.time calculation used along the way for selecting
116 // which contexts to include at each census point.
117 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000118 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000119
nethercote43a15ce2004-08-30 19:15:12 +0000120 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000121 // used in the results.
122 // Note that it is *doubled*, to avoid rounding errors.
123 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000124 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000125
126 // n_children and max_children are integers; a very big program might
127 // have more than 65536 allocation points (Konqueror startup has 1800).
128 XPt* parent; // pointer to parent XPt
129 UInt n_children; // number of children
130 UInt max_children; // capacity of children array
131 XPt** children; // pointers to children XPts
132};
133
134// Each census snapshots the most significant XTrees, each XTree having a
135// top-XPt as its root. The 'curr_space' element for each XPt is recorded
136// in the snapshot. The snapshot contains all the XTree's XPts, not in a
137// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000138// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000139//
140// Graph resolution, x-axis: no point having more than about 200 census
141// x-points; you can't see them on the graph. Therefore:
142//
143// - do a census every 1 ms for first 200 --> 200, all (200 ms)
144// - halve (drop half of them) --> 100, every 2nd (200 ms)
145// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
146// - halve --> 100, every 4th (400 ms)
147// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
148// - etc.
149//
150// This isn't exactly right, because we actually drop (N/2)-1 when halving,
151// but it shows the basic idea.
152
153#define MAX_N_CENSI 200 // Keep it even, for simplicity
154
155// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
156// bands, rest get lumped into OTHERS. I only print the top N
157// (cumulative-so-far space-time) at each point. N should be a bit bigger
158// than 19 in case the cumulative space-time doesn't fit with the eventual
159// space-time computed by hp2ps (but it should be close if the samples are
160// evenly spread, since hp2ps does an approximate per-band space-time
161// calculation that just sums the totals; ie. it assumes all samples are
162// the same distance apart).
163
164#define MAX_SNAPSHOTS 32
165
166typedef
167 struct {
168 XPt* xpt;
169 UInt space;
170 }
171 XPtSnapshot;
172
173// An XTree snapshot is stored as an array of of XPt snapshots.
174typedef XPtSnapshot* XTreeSnapshot;
175
176typedef
177 struct {
178 Int ms_time; // Int: must allow -1
179 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
180 UInt others_space;
181 UInt heap_admin_space;
182 UInt stacks_space;
183 }
184 Census;
185
186// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
187// which is a foothold into the XCon at which it was allocated. From
188// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
189// decremented (at deallocation).
190//
191// Nb: first two fields must match core's VgHashNode.
192typedef
193 struct _HP_Chunk {
194 struct _HP_Chunk* next;
195 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000196 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000197 XPt* where; // Where allocated; bottom-XPt
198 }
199 HP_Chunk;
200
201/*------------------------------------------------------------*/
202/*--- Profiling events ---*/
203/*------------------------------------------------------------*/
204
205typedef
206 enum {
207 VgpGetXPt = VgpFini+1,
208 VgpGetXPtSearch,
209 VgpCensus,
210 VgpCensusHeap,
211 VgpCensusSnapshot,
212 VgpCensusTreeSize,
213 VgpUpdateXCon,
214 VgpCalcSpacetime2,
215 VgpPrintHp,
216 VgpPrintXPts,
217 }
njn4be0a692004-11-22 18:10:36 +0000218 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000219
220/*------------------------------------------------------------*/
221/*--- Statistics ---*/
222/*------------------------------------------------------------*/
223
224// Konqueror startup, to give an idea of the numbers involved with a biggish
225// program, with default depth:
226//
227// depth=3 depth=40
228// - 310,000 allocations
229// - 300,000 frees
230// - 15,000 XPts 800,000 XPts
231// - 1,800 top-XPts
232
233static UInt n_xpts = 0;
234static UInt n_bot_xpts = 0;
235static UInt n_allocs = 0;
236static UInt n_zero_allocs = 0;
237static UInt n_frees = 0;
238static UInt n_children_reallocs = 0;
239static UInt n_snapshot_frees = 0;
240
241static UInt n_halvings = 0;
242static UInt n_real_censi = 0;
243static UInt n_fake_censi = 0;
244static UInt n_attempted_censi = 0;
245
246/*------------------------------------------------------------*/
247/*--- Globals ---*/
248/*------------------------------------------------------------*/
249
250#define FILENAME_LEN 256
251
252#define SPRINTF(zz_buf, fmt, args...) \
253 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
254 VG_(write)(fd, (void*)zz_buf, len); \
255 } while (0)
256
257#define BUF_LEN 1024 // general purpose
258static Char buf [BUF_LEN];
259static Char buf2[BUF_LEN];
260static Char buf3[BUF_LEN];
261
nethercote8b5f40c2004-11-02 13:29:50 +0000262static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000263
264static VgHashTable malloc_list = NULL; // HP_Chunks
265
266static UInt n_heap_blocks = 0;
267
njn51d827b2005-05-09 01:02:08 +0000268// Current directory at startup.
njn57ca7ab2005-06-21 23:44:58 +0000269static Char base_dir[VKI_PATH_MAX];
nethercotec9f36922004-02-14 16:40:02 +0000270
271#define MAX_ALLOC_FNS 32 // includes the builtin ones
272
nethercotec7469182004-05-11 09:21:08 +0000273// First few filled in, rest should be zeroed. Zero-terminated vector.
274static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000275static Char* alloc_fns[MAX_ALLOC_FNS] = {
276 "malloc",
277 "operator new(unsigned)",
278 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000279 "operator new(unsigned, std::nothrow_t const&)",
280 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000281 "__builtin_new",
282 "__builtin_vec_new",
283 "calloc",
284 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000285 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000286};
287
288
289/*------------------------------------------------------------*/
290/*--- Command line args ---*/
291/*------------------------------------------------------------*/
292
293#define MAX_DEPTH 50
294
295typedef
296 enum {
297 XText, XHTML,
298 }
299 XFormat;
300
301static Bool clo_heap = True;
302static UInt clo_heap_admin = 8;
303static Bool clo_stacks = True;
304static Bool clo_depth = 3;
305static XFormat clo_format = XText;
306
njn51d827b2005-05-09 01:02:08 +0000307static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000308{
njn45270a22005-03-27 01:00:11 +0000309 VG_BOOL_CLO(arg, "--heap", clo_heap)
310 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000311
njn45270a22005-03-27 01:00:11 +0000312 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
313 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000314
315 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
316 alloc_fns[n_alloc_fns] = & arg[11];
317 n_alloc_fns++;
318 if (n_alloc_fns >= MAX_ALLOC_FNS) {
319 VG_(printf)("Too many alloc functions specified, sorry");
320 VG_(bad_option)(arg);
321 }
322 }
323
324 else if (VG_CLO_STREQ(arg, "--format=text"))
325 clo_format = XText;
326 else if (VG_CLO_STREQ(arg, "--format=html"))
327 clo_format = XHTML;
328
329 else
330 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000331
nethercotec9f36922004-02-14 16:40:02 +0000332 return True;
333}
334
njn51d827b2005-05-09 01:02:08 +0000335static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000336{
337 VG_(printf)(
338" --heap=no|yes profile heap blocks [yes]\n"
339" --heap-admin=<number> average admin bytes per heap block [8]\n"
340" --stacks=no|yes profile stack(s) [yes]\n"
341" --depth=<number> depth of contexts [3]\n"
342" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
343" --format=text|html format of textual output [text]\n"
344 );
345 VG_(replacement_malloc_print_usage)();
346}
347
njn51d827b2005-05-09 01:02:08 +0000348static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000349{
350 VG_(replacement_malloc_print_debug_usage)();
351}
352
353/*------------------------------------------------------------*/
354/*--- Execution contexts ---*/
355/*------------------------------------------------------------*/
356
357// Fake XPt representing all allocation functions like malloc(). Acts as
358// parent node to all top-XPts.
359static XPt* alloc_xpt;
360
361// Cheap allocation for blocks that never need to be freed. Saves about 10%
362// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000363static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000364{
365 static Addr hp = 0; // current heap pointer
366 static Addr hp_lim = 0; // maximum usable byte in current block
367
368 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
369
370 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000371 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
372 if (hp == 0)
373 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
374 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000375 hp_lim = hp + SUPERBLOCK_SIZE - 1;
376 }
377
378 hp += n_bytes;
379
380 return (void*)(hp - n_bytes);
381}
382
383
384
njnd01fef72005-03-25 23:35:48 +0000385static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000386{
387 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000388 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000389
nethercote43a15ce2004-08-30 19:15:12 +0000390 xpt->curr_space = 0;
391 xpt->approx_ST = 0;
392 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000393
394 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000395
396 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000397 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000398
399 xpt->n_children = 0;
400
401 // If a bottom-XPt, don't allocate space for children. This can be 50%
402 // or more, although it tends to drop as --depth increases (eg. 10% for
403 // konqueror with --depth=20).
404 if ( is_bottom ) {
405 xpt->max_children = 0;
406 xpt->children = NULL;
407 n_bot_xpts++;
408 } else {
409 xpt->max_children = 4;
410 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
411 }
412
413 // Update statistics
414 n_xpts++;
415
416 return xpt;
417}
418
njnd01fef72005-03-25 23:35:48 +0000419static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000420{
421 Int i;
422
njnd01fef72005-03-25 23:35:48 +0000423 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000424 for (i = 0; i < n_alloc_fns; i++) {
425 if (VG_STREQ(buf, alloc_fns[i]))
426 return True;
427 }
428 }
429 return False;
430}
431
432// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
433// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
434// to ensure this in certain cases. See comments below.
435static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
436{
njnd01fef72005-03-25 23:35:48 +0000437 // Static to minimise stack size. +1 for added ~0 IP
438 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000439
440 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000441 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000442 UInt overestimate;
443 Bool reached_bottom;
444
445 VGP_PUSHCC(VgpGetXPt);
446
447 // Want at least clo_depth non-alloc-fn entries in the snapshot.
448 // However, because we have 1 or more (an unknown number, at this point)
449 // alloc-fns ignored, we overestimate the size needed for the stack
450 // snapshot. Then, if necessary, we repeatedly increase the size until
451 // it is enough.
452 overestimate = 2;
453 while (True) {
njnd01fef72005-03-25 23:35:48 +0000454 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000455
njnd01fef72005-03-25 23:35:48 +0000456 // Now we add a dummy "unknown" IP at the end. This is only used if we
457 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000458 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
459 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000460 // the parent's approx_ST wouldn't be equal [or almost equal] to the
461 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000462 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000463
njnd01fef72005-03-25 23:35:48 +0000464 // Skip over alloc functions in ips[].
465 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000466
467 // Must be at least one alloc function, unless client used
468 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000469 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000470
471 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000472 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000473 overestimate += 2;
474 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000475 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000476 } else {
477 break;
478 }
479 }
480 A = L;
njnd01fef72005-03-25 23:35:48 +0000481 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000482 reached_bottom = False;
483
njnd01fef72005-03-25 23:35:48 +0000484 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000485
486 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000487 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000488 while (True) {
njnd01fef72005-03-25 23:35:48 +0000489 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000490 // XXX: linear search, ugh -- about 10% of time for konqueror startup
491 // XXX: tried cacheing last result, only hit about 4% for konqueror
492 // Nb: this search hits about 98% of the time for konqueror
493 VGP_PUSHCC(VgpGetXPtSearch);
494
495 // If we've searched/added deep enough, or run out of EIPs, this is
496 // the bottom XPt.
497 if (L - A + 1 == clo_depth || L == B)
498 reached_bottom = True;
499
500 nC = 0;
501 while (True) {
502 if (nC == xpt->n_children) {
503 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000504 tl_assert(xpt->max_children != 0);
505 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000506 // Expand 'children' if necessary
507 if (xpt->n_children == xpt->max_children) {
508 xpt->max_children *= 2;
509 xpt->children = VG_(realloc)( xpt->children,
510 xpt->max_children * sizeof(XPt*) );
511 n_children_reallocs++;
512 }
njnd01fef72005-03-25 23:35:48 +0000513 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000514 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000515 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000516 break;
517 }
njnd01fef72005-03-25 23:35:48 +0000518 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000519 nC++; // keep looking
520 }
521 VGP_POPCC(VgpGetXPtSearch);
522
523 // Return found/built bottom-XPt.
524 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000525 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000526 VGP_POPCC(VgpGetXPt);
527 return xpt->children[nC];
528 }
529
530 // Descend to next level in XTree, the newly found/built non-bottom-XPt
531 xpt = xpt->children[nC];
532 L++;
533 }
534}
535
536// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
537static void update_XCon(XPt* xpt, Int space_delta)
538{
539 VGP_PUSHCC(VgpUpdateXCon);
540
njnca82cc02004-11-22 17:18:48 +0000541 tl_assert(True == clo_heap);
542 tl_assert(0 != space_delta);
543 tl_assert(NULL != xpt);
544 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000545
546 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000547 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000548 xpt->curr_space += space_delta;
549 xpt = xpt->parent;
550 }
njnca82cc02004-11-22 17:18:48 +0000551 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000552 alloc_xpt->curr_space += space_delta;
553
554 VGP_POPCC(VgpUpdateXCon);
555}
556
557// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000558static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000559{
560 XPt* xpt1 = *(XPt**)n1;
561 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000562 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000563}
564
nethercote43a15ce2004-08-30 19:15:12 +0000565static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000566{
567 XPt* xpt1 = *(XPt**)n1;
568 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000569 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000570}
571
572
573/*------------------------------------------------------------*/
574/*--- A generic Queue ---*/
575/*------------------------------------------------------------*/
576
577typedef
578 struct {
579 UInt head; // Index of first entry
580 UInt tail; // Index of final+1 entry, ie. next free slot
581 UInt max_elems;
582 void** elems;
583 }
584 Queue;
585
586static Queue* construct_queue(UInt size)
587{
588 UInt i;
589 Queue* q = VG_(malloc)(sizeof(Queue));
590 q->head = 0;
591 q->tail = 0;
592 q->max_elems = size;
593 q->elems = VG_(malloc)(size * sizeof(void*));
594 for (i = 0; i < size; i++)
595 q->elems[i] = NULL;
596
597 return q;
598}
599
600static void destruct_queue(Queue* q)
601{
602 VG_(free)(q->elems);
603 VG_(free)(q);
604}
605
606static void shuffle(Queue* dest_q, void** old_elems)
607{
608 UInt i, j;
609 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
610 dest_q->elems[i] = old_elems[j];
611 dest_q->head = 0;
612 dest_q->tail = i;
613 for ( ; i < dest_q->max_elems; i++)
614 dest_q->elems[i] = NULL; // paranoia
615}
616
617// Shuffles elements down. If not enough slots free, increase size. (We
618// don't wait until we've completely run out of space, because there could
619// be lots of shuffling just before that point which would be slow.)
620static void adjust(Queue* q)
621{
622 void** old_elems;
623
njnca82cc02004-11-22 17:18:48 +0000624 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000625 if (q->head < 10) {
626 old_elems = q->elems;
627 q->max_elems *= 2;
628 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
629 shuffle(q, old_elems);
630 VG_(free)(old_elems);
631 } else {
632 shuffle(q, q->elems);
633 }
634}
635
636static void enqueue(Queue* q, void* elem)
637{
638 if (q->tail == q->max_elems)
639 adjust(q);
640 q->elems[q->tail++] = elem;
641}
642
643static Bool is_empty_queue(Queue* q)
644{
645 return (q->head == q->tail);
646}
647
648static void* dequeue(Queue* q)
649{
650 if (is_empty_queue(q))
651 return NULL; // Queue empty
652 else
653 return q->elems[q->head++];
654}
655
656/*------------------------------------------------------------*/
657/*--- malloc() et al replacement wrappers ---*/
658/*------------------------------------------------------------*/
659
nethercotec9f36922004-02-14 16:40:02 +0000660// Forward declaration
661static void hp_census(void);
662
nethercote159dfef2004-09-13 13:27:30 +0000663static
njn57735902004-11-25 18:04:54 +0000664void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
665 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000666{
667 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000668 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000669 if (size < 0) return NULL;
670
671 VGP_PUSHCC(VgpCliMalloc);
672
673 // Update statistics
674 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000675 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000676
nethercote57e36b32004-07-10 14:56:28 +0000677 // Allocate and zero if necessary
678 if (!p) {
679 p = VG_(cli_malloc)( align, size );
680 if (!p) {
681 VGP_POPCC(VgpCliMalloc);
682 return NULL;
683 }
684 if (is_zeroed) VG_(memset)(p, 0, size);
685 }
686
njnf1c5def2005-08-11 02:17:07 +0000687 // Make new HP_Chunk node, add to malloc_list
nethercote57e36b32004-07-10 14:56:28 +0000688 hc = VG_(malloc)(sizeof(HP_Chunk));
689 hc->size = size;
690 hc->data = (Addr)p;
691 hc->where = NULL; // paranoia
692 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000693 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000694 if (0 != size)
695 update_XCon(hc->where, size);
696 }
njn246a9d22005-08-14 06:24:20 +0000697 VG_(HT_add_node)(malloc_list, hc);
njnf1c5def2005-08-11 02:17:07 +0000698 n_heap_blocks++;
nethercote57e36b32004-07-10 14:56:28 +0000699
700 // do a census!
701 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000702
703 VGP_POPCC(VgpCliMalloc);
704 return p;
705}
706
707static __inline__
708void die_block ( void* p, Bool custom_free )
709{
njnf1c5def2005-08-11 02:17:07 +0000710 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +0000711
712 VGP_PUSHCC(VgpCliMalloc);
713
714 // Update statistics
715 n_frees++;
716
njnf1c5def2005-08-11 02:17:07 +0000717 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +0000718 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn5cc5d7e2005-08-11 02:09:25 +0000719 if (NULL == hc)
720 return; // must have been a bogus free()
721 tl_assert(n_heap_blocks > 0);
722 n_heap_blocks--;
nethercotec9f36922004-02-14 16:40:02 +0000723
724 if (clo_heap && hc->size != 0)
725 update_XCon(hc->where, -hc->size);
726
nethercote57e36b32004-07-10 14:56:28 +0000727 VG_(free)( hc );
728
729 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000730 if (!custom_free)
731 VG_(cli_free)( p );
732
nethercote57e36b32004-07-10 14:56:28 +0000733 // do a census!
734 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000735
nethercotec9f36922004-02-14 16:40:02 +0000736 VGP_POPCC(VgpCliMalloc);
737}
738
739
njn51d827b2005-05-09 01:02:08 +0000740static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000741{
njn57735902004-11-25 18:04:54 +0000742 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000743}
744
njn51d827b2005-05-09 01:02:08 +0000745static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000746{
njn57735902004-11-25 18:04:54 +0000747 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000748}
749
njn51d827b2005-05-09 01:02:08 +0000750static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000751{
njn57735902004-11-25 18:04:54 +0000752 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000753}
754
njn51d827b2005-05-09 01:02:08 +0000755static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000756{
njn57735902004-11-25 18:04:54 +0000757 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000758}
759
njn51d827b2005-05-09 01:02:08 +0000760static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000761{
njn57735902004-11-25 18:04:54 +0000762 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000763}
764
njn51d827b2005-05-09 01:02:08 +0000765static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000766{
767 die_block( p, /*custom_free*/False );
768}
769
njn51d827b2005-05-09 01:02:08 +0000770static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000771{
772 die_block( p, /*custom_free*/False);
773}
774
njn51d827b2005-05-09 01:02:08 +0000775static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000776{
777 die_block( p, /*custom_free*/False );
778}
779
njn51d827b2005-05-09 01:02:08 +0000780static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000781{
njn5cc5d7e2005-08-11 02:09:25 +0000782 HP_Chunk* hc;
783 void* p_new;
784 SizeT old_size;
785 XPt *old_where, *new_where;
nethercotec9f36922004-02-14 16:40:02 +0000786
787 VGP_PUSHCC(VgpCliMalloc);
788
njna0793652005-08-16 03:34:56 +0000789 // Remove the old block
njn9a463242005-08-16 03:29:50 +0000790 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000791 if (hc == NULL) {
792 VGP_POPCC(VgpCliMalloc);
njn5cc5d7e2005-08-11 02:09:25 +0000793 return NULL; // must have been a bogus realloc()
nethercotec9f36922004-02-14 16:40:02 +0000794 }
795
nethercotec9f36922004-02-14 16:40:02 +0000796 old_size = hc->size;
797
798 if (new_size <= old_size) {
799 // new size is smaller or same; block not moved
800 p_new = p_old;
801
802 } else {
803 // new size is bigger; make new block, copy shared contents, free old
804 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
tom0cd42f02005-10-06 09:00:17 +0000805 if (p_new) {
806 VG_(memcpy)(p_new, p_old, old_size);
807 VG_(cli_free)(p_old);
808 }
nethercotec9f36922004-02-14 16:40:02 +0000809 }
nethercotec9f36922004-02-14 16:40:02 +0000810
tom0cd42f02005-10-06 09:00:17 +0000811 if (p_new) {
812 old_where = hc->where;
813 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000814
tom0cd42f02005-10-06 09:00:17 +0000815 // Update HP_Chunk
816 hc->data = (Addr)p_new;
817 hc->size = new_size;
818 hc->where = new_where;
819
820 // Update XPt curr_space fields
821 if (clo_heap) {
822 if (0 != old_size) update_XCon(old_where, -old_size);
823 if (0 != new_size) update_XCon(new_where, new_size);
824 }
nethercotec9f36922004-02-14 16:40:02 +0000825 }
826
njn5cc5d7e2005-08-11 02:09:25 +0000827 // Now insert the new hc (with a possibly new 'data' field) into
828 // malloc_list. If this realloc() did not increase the memory size, we
829 // will have removed and then re-added mc unnecessarily. But that's ok
830 // because shrinking a block with realloc() is (presumably) much rarer
831 // than growing it, and this way simplifies the growing case.
njn246a9d22005-08-14 06:24:20 +0000832 VG_(HT_add_node)(malloc_list, hc);
nethercotec9f36922004-02-14 16:40:02 +0000833
834 VGP_POPCC(VgpCliMalloc);
835 return p_new;
836}
837
838
839/*------------------------------------------------------------*/
840/*--- Taking a census ---*/
841/*------------------------------------------------------------*/
842
843static Census censi[MAX_N_CENSI];
844static UInt curr_census = 0;
845
nethercotec9f36922004-02-14 16:40:02 +0000846static UInt get_xtree_size(XPt* xpt, UInt ix)
847{
848 UInt i;
849
nethercote43a15ce2004-08-30 19:15:12 +0000850 // If no memory allocated at all, nothing interesting to record.
851 if (alloc_xpt->curr_space == 0) return 0;
852
853 // Ignore sub-XTrees that account for a miniscule fraction of current
854 // allocated space.
855 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000856 ix++;
857
858 // Count all (non-zero) descendent XPts
859 for (i = 0; i < xpt->n_children; i++)
860 ix = get_xtree_size(xpt->children[i], ix);
861 }
862 return ix;
863}
864
865static
866UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
867{
868 UInt i;
869
nethercote43a15ce2004-08-30 19:15:12 +0000870 // Structure of this function mirrors that of get_xtree_size().
871
872 if (alloc_xpt->curr_space == 0) return 0;
873
874 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000875 xtree_snapshot[ix].xpt = xpt;
876 xtree_snapshot[ix].space = xpt->curr_space;
877 ix++;
878
nethercotec9f36922004-02-14 16:40:02 +0000879 for (i = 0; i < xpt->n_children; i++)
880 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
881 }
882 return ix;
883}
884
885static UInt ms_interval;
886static UInt do_every_nth_census = 30;
887
888// Weed out half the censi; we choose those that represent the smallest
889// time-spans, because that loses the least information.
890//
891// Algorithm for N censi: We find the census representing the smallest
892// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
893// (It's (N/2)-1 because we never remove the first and last censi.)
894// We have to do this one census at a time, rather than finding the (N/2)-1
895// smallest censi in one hit, because when a census is removed, it's
896// neighbours immediately cover greater timespans. So it's N^2, but N only
897// equals 200, and this is only done every 100 censi, which is not too often.
898static void halve_censi(void)
899{
900 Int i, jp, j, jn, k;
901 Census* min_census;
902
903 n_halvings++;
904 if (VG_(clo_verbosity) > 1)
905 VG_(message)(Vg_UserMsg, "Halving censi...");
906
907 // Sets j to the index of the first not-yet-removed census at or after i
908 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000909 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000910
911 for (i = 2; i < MAX_N_CENSI; i += 2) {
912 // Find the censi representing the smallest timespan. The timespan
913 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
914 // censi A and B. We don't consider the first and last censi for
915 // removal.
916 Int min_span = 0x7fffffff;
917 Int min_j = 0;
918
919 // Initial triple: (prev, curr, next) == (jp, j, jn)
920 jp = 0;
921 FIND_CENSUS(1, j);
922 FIND_CENSUS(j+1, jn);
923 while (jn < MAX_N_CENSI) {
924 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000925 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000926 if (timespan < min_span) {
927 min_span = timespan;
928 min_j = j;
929 }
930 // Move on to next triple
931 jp = j;
932 j = jn;
933 FIND_CENSUS(jn+1, jn);
934 }
935 // We've found the least important census, now remove it
936 min_census = & censi[ min_j ];
937 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
938 n_snapshot_frees++;
939 VG_(free)(min_census->xtree_snapshots[k]);
940 min_census->xtree_snapshots[k] = NULL;
941 }
942 min_census->ms_time = -1;
943 }
944
945 // Slide down the remaining censi over the removed ones. The '<=' is
946 // because we are removing on (N/2)-1, rather than N/2.
947 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
948 FIND_CENSUS(j, j);
949 if (i != j) {
950 censi[i] = censi[j];
951 }
952 }
953 curr_census = i;
954
955 // Double intervals
956 ms_interval *= 2;
957 do_every_nth_census *= 2;
958
959 if (VG_(clo_verbosity) > 1)
960 VG_(message)(Vg_UserMsg, "...done");
961}
962
963// Take a census. Census time seems to be insignificant (usually <= 0 ms,
964// almost always <= 1ms) so don't have to worry about subtracting it from
965// running time in any way.
966//
967// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
968// 50ms!
969static void hp_census(void)
970{
971 static UInt ms_prev_census = 0;
972 static UInt ms_next_census = 0; // zero allows startup census
973
974 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000975 Census* census;
976
977 VGP_PUSHCC(VgpCensus);
978
979 // Only do a census if it's time
980 ms_time = VG_(read_millisecond_timer)();
981 ms_time_since_prev = ms_time - ms_prev_census;
982 if (ms_time < ms_next_census) {
983 n_fake_censi++;
984 VGP_POPCC(VgpCensus);
985 return;
986 }
987 n_real_censi++;
988
989 census = & censi[curr_census];
990
991 census->ms_time = ms_time;
992
993 // Heap: snapshot the K most significant XTrees -------------------
994 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +0000995 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +0000996 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
997 ? alloc_xpt->n_children
998 : MAX_SNAPSHOTS); // max out
999
nethercote43a15ce2004-08-30 19:15:12 +00001000 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001001 // We *do not* do it for any non-top-XPTs.
1002 for (i = 0; i < alloc_xpt->n_children; i++) {
1003 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001004 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001005 }
nethercote43a15ce2004-08-30 19:15:12 +00001006 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001007 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001008 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001009
1010 VGP_PUSHCC(VgpCensusHeap);
1011
1012 // For each significant top-level XPt, record space info about its
1013 // entire XTree, in a single census entry.
1014 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1015 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001016 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001017 for (i = 0; i < K; i++) {
1018 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001019// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1020 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001021 VGP_PUSHCC(VgpCensusTreeSize);
1022 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1023 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001024
1025 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1026 // insignificant) then don't take any more snapshots.
1027 if (0 == xtree_size) break;
1028
1029 // Make array of the appropriate size (+1 for zero termination,
1030 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001031 census->xtree_snapshots[i] =
1032 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001033 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001034 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1035 (xtree_size+1) * sizeof(XPtSnapshot));
1036
1037 // Take space-snapshot: copy 'curr_space' for every XPt in the
1038 // XTree into the snapshot array, along with pointers to the XPts.
1039 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001040 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001041 // saves a lot of memory and up to 40% time with big --depth valus.
1042 VGP_PUSHCC(VgpCensusSnapshot);
1043 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1044 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001045 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001046 VGP_POPCC(VgpCensusSnapshot);
1047 }
1048// VG_(printf)("\n\n");
1049 // Zero-terminate 'xtree_snapshot' array
1050 census->xtree_snapshots[i] = NULL;
1051
1052 VGP_POPCC(VgpCensusHeap);
1053
1054 //VG_(printf)("printed %d censi\n", K);
1055
1056 // Lump the rest into a single "others" entry.
1057 census->others_space = 0;
1058 for (i = K; i < alloc_xpt->n_children; i++) {
1059 census->others_space += alloc_xpt->children[i]->curr_space;
1060 }
1061 }
1062
1063 // Heap admin -------------------------------------------------------
1064 if (clo_heap_admin > 0)
1065 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1066
1067 // Stack(s) ---------------------------------------------------------
1068 if (clo_stacks) {
njn1d0cb0d2005-08-15 01:52:02 +00001069 ThreadId tid;
1070 Addr stack_min, stack_max;
thughes4ad52d02004-06-27 17:37:21 +00001071 census->stacks_space = sigstacks_space;
njn1d0cb0d2005-08-15 01:52:02 +00001072 VG_(thread_stack_reset_iter)();
1073 while ( VG_(thread_stack_next)(&tid, &stack_min, &stack_max) ) {
1074 census->stacks_space += (stack_max - stack_min);
1075 }
nethercotec9f36922004-02-14 16:40:02 +00001076 }
1077
1078 // Finish, update interval if necessary -----------------------------
1079 curr_census++;
1080 census = NULL; // don't use again now that curr_census changed
1081
1082 // Halve the entries, if our census table is full
1083 if (MAX_N_CENSI == curr_census) {
1084 halve_censi();
1085 }
1086
1087 // Take time for next census from now, rather than when this census
1088 // should have happened. Because, if there's a big gap due to a kernel
1089 // operation, there's no point doing catch-up censi every BB for a while
1090 // -- that would just give N censi at almost the same time.
1091 if (VG_(clo_verbosity) > 1) {
1092 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1093 VG_(read_millisecond_timer)() - ms_time );
1094 }
1095 ms_prev_census = ms_time;
1096 ms_next_census = ms_time + ms_interval;
1097 //ms_next_census += ms_interval;
1098
1099 //VG_(printf)("Next: %d ms\n", ms_next_census);
1100
1101 VGP_POPCC(VgpCensus);
1102}
1103
1104/*------------------------------------------------------------*/
1105/*--- Tracked events ---*/
1106/*------------------------------------------------------------*/
1107
nethercote8b5f40c2004-11-02 13:29:50 +00001108static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001109{
1110 sigstacks_space += len;
1111}
1112
nethercote8b5f40c2004-11-02 13:29:50 +00001113static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001114{
njnca82cc02004-11-22 17:18:48 +00001115 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001116 sigstacks_space -= len;
1117}
1118
1119/*------------------------------------------------------------*/
1120/*--- Client Requests ---*/
1121/*------------------------------------------------------------*/
1122
njn51d827b2005-05-09 01:02:08 +00001123static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001124{
1125 switch (argv[0]) {
1126 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001127 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001128 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001129 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001130 *ret = 0;
njn57735902004-11-25 18:04:54 +00001131 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001132 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001133 return True;
1134 }
1135 case VG_USERREQ__FREELIKE_BLOCK: {
1136 void* p = (void*)argv[1];
1137 *ret = 0;
1138 die_block( p, /*custom_free*/True );
1139 return True;
1140 }
1141 default:
1142 *ret = 0;
1143 return False;
1144 }
1145}
1146
1147/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001148/*--- Instrumentation ---*/
1149/*------------------------------------------------------------*/
1150
sewardj4ba057c2005-10-18 12:04:18 +00001151static
1152IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1153 Addr64 orig_addr_noredir, VexGuestExtents* vge,
1154 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001155{
sewardjd54babf2005-03-21 00:55:49 +00001156 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001157 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001158}
1159
1160/*------------------------------------------------------------*/
1161/*--- Spacetime recomputation ---*/
1162/*------------------------------------------------------------*/
1163
nethercote43a15ce2004-08-30 19:15:12 +00001164// Although we've been calculating space-time along the way, because the
1165// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001166// might not agree with what hp2ps sees, because we've thrown away some of
1167// the information. So recompute it at the scale that hp2ps sees, so we can
1168// confidently determine which contexts hp2ps will choose for displaying as
1169// distinct bands. This recomputation only happens to the significant ones
1170// that get printed in the .hp file, so it's cheap.
1171//
nethercote43a15ce2004-08-30 19:15:12 +00001172// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001173// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1174// where
1175// a[N] is the space at census N
1176// d(A,B) is the time interval between censi A and B
1177// and
1178// d(A,B) + d(B,C) == d(A,C)
1179//
1180// Key point: we can calculate the area for a census without knowing the
1181// previous or subsequent censi's space; because any over/underestimates
1182// for this census will be reversed in the next, balancing out. This is
1183// important, as getting the previous/next census entry for a particular
1184// AP is a pain with this data structure, but getting the prev/next
1185// census time is easy.
1186//
nethercote43a15ce2004-08-30 19:15:12 +00001187// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001188// The ULong* values are all running totals, hence the use of "+=" everywhere.
1189
1190// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001191static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001192 ULong* twice_heap_ST,
1193 ULong* twice_heap_admin_ST,
1194 ULong* twice_stack_ST)
1195{
1196 UInt i, j;
1197 XPtSnapshot* xpt_snapshot;
1198
1199 // Heap --------------------------------------------------------
1200 if (clo_heap) {
1201 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001202 // Compute total heap exact_ST_dbld for the entire XTree using only
1203 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001204 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1205
nethercote43a15ce2004-08-30 19:15:12 +00001206 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1207 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001208 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1209 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001210 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001211 }
1212 }
1213 *twice_heap_ST += d_t1_t2 * census->others_space;
1214 }
1215
1216 // Heap admin --------------------------------------------------
1217 if (clo_heap_admin > 0)
1218 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1219
1220 // Stack(s) ----------------------------------------------------
1221 if (clo_stacks)
1222 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1223}
1224
1225// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001226static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001227{
1228 UInt i, N = curr_census;
1229
1230 VGP_PUSHCC(VgpCalcSpacetime2);
1231
1232 *heap2 = 0;
1233 *heap_admin2 = 0;
1234 *stack2 = 0;
1235
1236 if (N <= 1)
1237 return;
1238
nethercote43a15ce2004-08-30 19:15:12 +00001239 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1240 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001241
1242 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001243 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1244 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001245 }
1246
nethercote43a15ce2004-08-30 19:15:12 +00001247 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1248 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001249 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1250 *heap2 /= 2;
1251 *heap_admin2 /= 2;
1252 *stack2 /= 2;
1253
1254 VGP_POPCC(VgpCalcSpacetime2);
1255}
1256
1257/*------------------------------------------------------------*/
1258/*--- Writing the graph file ---*/
1259/*------------------------------------------------------------*/
1260
1261static Char* make_filename(Char* dir, Char* suffix)
1262{
1263 Char* filename;
1264
1265 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1266 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1267 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1268
1269 return filename;
1270}
1271
1272// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1273static Char* clean_fnname(Char *d, Char* s)
1274{
1275 Char* dorig = d;
1276 while (*s) {
1277 if (' ' == *s) { *d = '%'; }
1278 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1279 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1280 else { *d = *s; };
1281 s++;
1282 d++;
1283 }
1284 *d = '\0';
1285 return dorig;
1286}
1287
1288static void file_err ( Char* file )
1289{
njn02bc4b82005-05-15 17:28:26 +00001290 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001291 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1292}
1293
1294/* Format, by example:
1295
1296 JOB "a.out -p"
1297 DATE "Fri Apr 17 11:43:45 1992"
1298 SAMPLE_UNIT "seconds"
1299 VALUE_UNIT "bytes"
1300 BEGIN_SAMPLE 0.00
1301 SYSTEM 24
1302 END_SAMPLE 0.00
1303 BEGIN_SAMPLE 1.00
1304 elim 180
1305 insert 24
1306 intersect 12
1307 disin 60
1308 main 12
1309 reduce 20
1310 SYSTEM 12
1311 END_SAMPLE 1.00
1312 MARK 1.50
1313 MARK 1.75
1314 MARK 1.80
1315 BEGIN_SAMPLE 2.00
1316 elim 192
1317 insert 24
1318 intersect 12
1319 disin 84
1320 main 12
1321 SYSTEM 24
1322 END_SAMPLE 2.00
1323 BEGIN_SAMPLE 2.82
1324 END_SAMPLE 2.82
1325 */
1326static void write_hp_file(void)
1327{
sewardj92645592005-07-23 09:18:34 +00001328 Int i, j;
1329 Int fd, res;
1330 SysRes sres;
1331 Char *hp_file, *ps_file, *aux_file;
1332 Char* cmdfmt;
1333 Char* cmdbuf;
1334 Int cmdlen;
nethercotec9f36922004-02-14 16:40:02 +00001335
1336 VGP_PUSHCC(VgpPrintHp);
1337
1338 // Open file
1339 hp_file = make_filename( base_dir, ".hp" );
1340 ps_file = make_filename( base_dir, ".ps" );
1341 aux_file = make_filename( base_dir, ".aux" );
sewardj92645592005-07-23 09:18:34 +00001342 sres = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1343 VKI_S_IRUSR|VKI_S_IWUSR);
1344 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001345 file_err( hp_file );
1346 VGP_POPCC(VgpPrintHp);
1347 return;
sewardj92645592005-07-23 09:18:34 +00001348 } else {
1349 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001350 }
1351
1352 // File header, including command line
1353 SPRINTF(buf, "JOB \"");
sewardj45f4e7c2005-09-27 19:20:21 +00001354 if (VG_(args_the_exename)) {
1355 SPRINTF(buf, "%s", VG_(args_the_exename));
1356 }
1357 for (i = 0; i < VG_(args_for_client).used; i++) {
1358 if (VG_(args_for_client).strs[i])
1359 SPRINTF(buf, " %s", VG_(args_for_client).strs[i]);
njnd111d102005-09-13 00:46:27 +00001360 }
nethercotec9f36922004-02-14 16:40:02 +00001361 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1362 "DATE \"\"\n"
1363 "SAMPLE_UNIT \"ms\"\n"
1364 "VALUE_UNIT \"bytes\"\n", ms_interval);
1365
1366 // Censi
1367 for (i = 0; i < curr_census; i++) {
1368 Census* census = & censi[i];
1369
1370 // Census start
1371 SPRINTF(buf, "MARK %d.0\n"
1372 "BEGIN_SAMPLE %d.0\n",
1373 census->ms_time, census->ms_time);
1374
1375 // Heap -----------------------------------------------------------
1376 if (clo_heap) {
1377 // Print all the significant XPts from that census
1378 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1379 // Grab the jth top-XPt
1380 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001381 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001382 VG_(sprintf)(buf2, "???");
1383 }
njnd01fef72005-03-25 23:35:48 +00001384 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001385 clean_fnname(buf3, buf2), xtree_snapshot->space);
1386 }
1387
1388 // Remaining heap block alloc points, combined
1389 if (census->others_space > 0)
1390 SPRINTF(buf, "other %d\n", census->others_space);
1391 }
1392
1393 // Heap admin -----------------------------------------------------
1394 if (clo_heap_admin > 0 && census->heap_admin_space)
1395 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1396
1397 // Stack(s) -------------------------------------------------------
1398 if (clo_stacks)
1399 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1400
1401 // Census end
1402 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1403 }
1404
1405 // Close file
njnca82cc02004-11-22 17:18:48 +00001406 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001407 VG_(close)(fd);
1408
1409 // Attempt to convert file using hp2ps
1410 cmdfmt = "%s/hp2ps -c -t1 %s";
1411 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1412 + VG_(strlen)(cmdfmt);
1413 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1414 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1415 res = VG_(system)(cmdbuf);
1416 VG_(free)(cmdbuf);
1417 if (res != 0) {
1418 VG_(message)(Vg_UserMsg,
1419 "Conversion to PostScript failed. Try converting manually.");
1420 } else {
1421 // remove the .hp and .aux file
1422 VG_(unlink)(hp_file);
1423 VG_(unlink)(aux_file);
1424 }
1425
1426 VG_(free)(hp_file);
1427 VG_(free)(ps_file);
1428 VG_(free)(aux_file);
1429
1430 VGP_POPCC(VgpPrintHp);
1431}
1432
1433/*------------------------------------------------------------*/
1434/*--- Writing the XPt text/HTML file ---*/
1435/*------------------------------------------------------------*/
1436
1437static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1438{
1439 int i, len, space;
1440
1441 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1442 len = VG_(strlen)(xbuf);
1443 space = field_width - len;
1444 if (space < 0) space = 0; /* Allow for v. small field_width */
1445 i = len;
1446
1447 /* Right justify in field */
1448 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1449 for (i = 0; i < space; i++) xbuf[i] = ' ';
1450}
1451
1452// Nb: uses a static buffer, each call trashes the last string returned.
1453static Char* make_perc(ULong spacetime, ULong total_spacetime)
1454{
1455 static Char mbuf[32];
1456
1457 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001458 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001459 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1460 return mbuf;
1461}
1462
njnd01fef72005-03-25 23:35:48 +00001463// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001464// bottom-to-top of XCon, and then printed in the reverse order.
1465static UInt pp_XCon(Int fd, XPt* xpt)
1466{
njnd01fef72005-03-25 23:35:48 +00001467 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001468 Int i = 0;
1469 Int n = 0;
1470 Bool is_HTML = ( XHTML == clo_format );
1471 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1472 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1473
njnca82cc02004-11-22 17:18:48 +00001474 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001475
1476 while (True) {
njnd01fef72005-03-25 23:35:48 +00001477 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001478 n++;
1479 if (alloc_xpt == xpt->parent) break;
1480 i++;
1481 xpt = xpt->parent;
1482 }
1483
1484 for (i = n-1; i >= 0; i--) {
1485 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001486 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001487 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1488 }
1489
1490 return n;
1491}
1492
1493// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001494// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001495// sufficient, because function pointers mean that you can call more than
1496// one other function from a single code location. So instead we use the
1497// address of the xpt struct itself, which is guaranteed to be unique.
1498
1499static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1500 ULong total_spacetime)
1501{
1502 UInt i;
1503 XPt *xpt, *child;
1504 UInt L = 0;
1505 UInt c1 = 1;
1506 UInt c2 = 0;
1507 ULong sum = 0;
1508 UInt n;
njnd01fef72005-03-25 23:35:48 +00001509 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001510 Bool is_HTML = ( XHTML == clo_format );
1511 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1512 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1513 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1514 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1515 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1516 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1517 Char* end_hr = ( is_HTML ? "<hr>" :
1518 "=================================" );
1519 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1520
nethercote43a15ce2004-08-30 19:15:12 +00001521 if (total_spacetime == 0) {
1522 SPRINTF(buf, "(No heap memory allocated)\n");
1523 return;
1524 }
1525
1526
nethercotec9f36922004-02-14 16:40:02 +00001527 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1528
1529 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001530 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001531 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001532
nethercote43a15ce2004-08-30 19:15:12 +00001533 // Check that the sum of all children .exact_ST_dbld fields equals
1534 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001535 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001536 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001537 } else {
1538 sum = 0;
1539 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001540 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001541 }
njnca82cc02004-11-22 17:18:48 +00001542 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001543 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001544 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001545 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001546// tl_assert(sum <= xpt->exact_ST_dbld);
1547// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001548// if (sum != xpt->exact_ST_dbld) {
njn68e46592005-08-26 19:42:27 +00001549// VG_(printf)("%lld, %lld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001550// }
1551 }
1552
1553 if (xpt == alloc_xpt) {
1554 SPRINTF(buf, "Heap allocation functions accounted for "
1555 "%s of measured spacetime%s\n",
1556 make_perc(heap_spacetime, total_spacetime), maybe_br);
1557 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001558 // Remember: exact_ST_dbld is space.time *doubled*
1559 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001560 if (is_HTML) {
1561 SPRINTF(buf, "<a name=\"b%x\"></a>"
1562 "Context accounted for "
1563 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1564 xpt, xpt, perc);
1565 } else {
1566 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1567 perc);
1568 }
1569 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001570 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001571 }
1572
nethercote43a15ce2004-08-30 19:15:12 +00001573 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001574 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001575 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001576
1577 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1578 for (i = 0; i < xpt->n_children; i++) {
1579 child = xpt->children[i];
1580
1581 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001582 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001583 UInt n_insig = xpt->n_children - i;
1584 Char* s = ( n_insig == 1 ? "" : "s" );
1585 Char* and = ( 0 == i ? "" : "and " );
1586 Char* other = ( 0 == i ? "" : "other " );
1587 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1588 maybe_li, and, n_insig, other, s, maybe_fli);
1589 break;
1590 }
1591
nethercote43a15ce2004-08-30 19:15:12 +00001592 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001593 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1594 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001595 if (is_HTML) {
1596 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1597
1598 if (child->n_children > 0) {
1599 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1600 } else {
1601 SPRINTF(buf, "%s", perc);
1602 }
njnd01fef72005-03-25 23:35:48 +00001603 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001604 } else {
njnd01fef72005-03-25 23:35:48 +00001605 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001606 }
1607
1608 if (child->n_children > 0) {
1609 enqueue(q, (void*)child);
1610 c2++;
1611 }
1612 }
1613 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1614 c1--;
1615
1616 // Putting markers between levels of the structure:
1617 // c1 tracks how many to go on this level, c2 tracks how many we've
1618 // queued up for the next level while finishing off this level.
1619 // When c1 gets to zero, we've changed levels, so print a marker,
1620 // move c2 into c1, and zero c2.
1621 if (0 == c1) {
1622 L++;
1623 c1 = c2;
1624 c2 = 0;
1625 if (! is_empty_queue(q) ) { // avoid empty one at end
1626 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1627 }
1628 } else {
1629 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1630 }
1631 }
1632 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1633 "%s value for more.\n", end_hr, depth);
1634}
1635
1636static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1637 ULong total_spacetime)
1638{
1639 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001640
nethercotec9f36922004-02-14 16:40:02 +00001641 enqueue(q, xpt);
1642 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1643 destruct_queue(q);
1644}
1645
1646static void
1647write_text_file(ULong total_ST, ULong heap_ST)
1648{
sewardj92645592005-07-23 09:18:34 +00001649 SysRes sres;
1650 Int fd, i;
1651 Char* text_file;
1652 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
nethercotec9f36922004-02-14 16:40:02 +00001653
1654 VGP_PUSHCC(VgpPrintXPts);
1655
1656 // Open file
1657 text_file = make_filename( base_dir,
1658 ( XText == clo_format ? ".txt" : ".html" ) );
1659
sewardj92645592005-07-23 09:18:34 +00001660 sres = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
nethercotec9f36922004-02-14 16:40:02 +00001661 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00001662 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001663 file_err( text_file );
1664 VGP_POPCC(VgpPrintXPts);
1665 return;
sewardj92645592005-07-23 09:18:34 +00001666 } else {
1667 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001668 }
1669
1670 // Header
1671 if (XHTML == clo_format) {
1672 SPRINTF(buf, "<html>\n"
1673 "<head>\n"
1674 "<title>%s</title>\n"
1675 "</head>\n"
1676 "<body>\n",
1677 text_file);
1678 }
1679
1680 // Command line
sewardj45f4e7c2005-09-27 19:20:21 +00001681 SPRINTF(buf, "Command:");
1682 if (VG_(args_the_exename)) {
1683 SPRINTF(buf, " %s", VG_(args_the_exename));
1684 }
1685 for (i = 0; i < VG_(args_for_client).used; i++) {
1686 if (VG_(args_for_client).strs[i])
1687 SPRINTF(buf, " %s", VG_(args_for_client).strs[i]);
njnd111d102005-09-13 00:46:27 +00001688 }
nethercotec9f36922004-02-14 16:40:02 +00001689 SPRINTF(buf, "\n%s\n", maybe_p);
1690
1691 if (clo_heap)
1692 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1693
njnca82cc02004-11-22 17:18:48 +00001694 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001695 VG_(close)(fd);
1696
1697 VGP_POPCC(VgpPrintXPts);
1698}
1699
1700/*------------------------------------------------------------*/
1701/*--- Finalisation ---*/
1702/*------------------------------------------------------------*/
1703
1704static void
1705print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1706 ULong stack_ST)
1707{
njn99cb9e32005-09-25 17:59:16 +00001708 VG_(message)(Vg_UserMsg, "Total spacetime: %,llu ms.B", total_ST);
nethercotec9f36922004-02-14 16:40:02 +00001709
1710 // Heap --------------------------------------------------------------
1711 if (clo_heap)
1712 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001713 ( 0 == total_ST ? (Char*)"(n/a)"
1714 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001715
1716 // Heap admin --------------------------------------------------------
1717 if (clo_heap_admin)
1718 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001719 ( 0 == total_ST ? (Char*)"(n/a)"
1720 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001721
njnca82cc02004-11-22 17:18:48 +00001722 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001723
1724 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001725 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001726 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001727 ( 0 == stack_ST ? (Char*)"0%"
1728 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001729 }
nethercotec9f36922004-02-14 16:40:02 +00001730
1731 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001732 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001733 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1734 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1735 n_zero_allocs * 100 / n_allocs );
1736 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1737 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1738 n_xpts*sizeof(XPt));
1739 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1740 n_bot_xpts * 100 / n_xpts);
1741 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1742 alloc_xpt->n_children * 100 / n_xpts);
1743 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1744 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1745 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1746 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1747 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1748 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1749 }
1750}
1751
njn51d827b2005-05-09 01:02:08 +00001752static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001753{
1754 ULong total_ST = 0;
1755 ULong heap_ST = 0;
1756 ULong heap_admin_ST = 0;
1757 ULong stack_ST = 0;
1758
1759 // Do a final (empty) sample to show program's end
1760 hp_census();
1761
1762 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001763 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001764 total_ST = heap_ST + heap_admin_ST + stack_ST;
1765 write_hp_file ( );
1766 write_text_file( total_ST, heap_ST );
1767 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1768}
1769
njn51d827b2005-05-09 01:02:08 +00001770/*------------------------------------------------------------*/
1771/*--- Initialisation ---*/
1772/*------------------------------------------------------------*/
1773
1774static void ms_post_clo_init(void)
1775{
1776 ms_interval = 1;
1777
1778 // Do an initial sample for t = 0
1779 hp_census();
1780}
1781
tom151a6392005-11-11 12:30:36 +00001782static void ms_pre_clo_init(void)
njn51d827b2005-05-09 01:02:08 +00001783{
1784 VG_(details_name) ("Massif");
1785 VG_(details_version) (NULL);
1786 VG_(details_description) ("a space profiler");
1787 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1788 VG_(details_bug_reports_to) (VG_BUGS_TO);
1789
1790 // Basic functions
1791 VG_(basic_tool_funcs) (ms_post_clo_init,
1792 ms_instrument,
1793 ms_fini);
1794
1795 // Needs
1796 VG_(needs_libc_freeres)();
1797 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1798 ms_print_usage,
1799 ms_print_debug_usage);
1800 VG_(needs_client_requests) (ms_handle_client_request);
njnfc51f8d2005-06-21 03:20:17 +00001801 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00001802 ms___builtin_new,
1803 ms___builtin_vec_new,
1804 ms_memalign,
1805 ms_calloc,
1806 ms_free,
1807 ms___builtin_delete,
1808 ms___builtin_vec_delete,
1809 ms_realloc,
1810 0 );
1811
1812 // Events to track
1813 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1814 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1815
1816 // Profiling events
1817 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1818 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1819 VG_(register_profile_event)(VgpCensus, "census");
1820 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1821 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1822 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1823 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1824 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1825 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1826 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1827
1828 // HP_Chunks
njnf69f9452005-07-03 17:53:11 +00001829 malloc_list = VG_(HT_construct)( 80021 ); // prime, big
njn51d827b2005-05-09 01:02:08 +00001830
1831 // Dummy node at top of the context structure.
1832 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1833
njn57ca7ab2005-06-21 23:44:58 +00001834 tl_assert( VG_(getcwd)(base_dir, VKI_PATH_MAX) );
njn51d827b2005-05-09 01:02:08 +00001835}
1836
sewardj45f4e7c2005-09-27 19:20:21 +00001837VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00001838
1839/*--------------------------------------------------------------------*/
njnf1c5def2005-08-11 02:17:07 +00001840/*--- end ---*/
nethercotec9f36922004-02-14 16:40:02 +00001841/*--------------------------------------------------------------------*/
1842