blob: f436d0f6251392cafd9fa3376eaf34700fb7a747 [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"
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"
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"
nethercotec9f36922004-02-14 16:40:02 +000053
54#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
55
56/*------------------------------------------------------------*/
57/*--- Overview of operation ---*/
58/*------------------------------------------------------------*/
59
60// Heap blocks are tracked, and the amount of space allocated by various
61// contexts (ie. lines of code, more or less) is also tracked.
62// Periodically, a census is taken, and the amount of space used, at that
63// point, by the most significant (highly allocating) contexts is recorded.
64// Census start off frequently, but are scaled back as the program goes on,
65// so that there are always a good number of them. At the end, overall
66// spacetimes for different contexts (of differing levels of precision) is
67// calculated, the graph is printed, and the text giving spacetimes for the
68// increasingly precise contexts is given.
69//
70// Measures the following:
71// - heap blocks
72// - heap admin bytes
73// - stack(s)
74// - code (code segments loaded at startup, and loaded with mmap)
75// - data (data segments loaded at startup, and loaded/created with mmap,
76// and brk()d segments)
77
78/*------------------------------------------------------------*/
79/*--- Main types ---*/
80/*------------------------------------------------------------*/
81
82// An XPt represents an "execution point", ie. a code address. Each XPt is
83// part of a tree of XPts (an "execution tree", or "XTree"). Each
84// top-to-bottom path through an XTree gives an execution context ("XCon"),
85// and is equivalent to a traditional Valgrind ExeContext.
86//
87// The XPt at the top of an XTree (but below "alloc_xpt") is called a
88// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
89// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
90// bottom-XPTs in that XTree.
91//
92// All XCons have the same top-XPt, "alloc_xpt", which represents all
93// allocation functions like malloc(). It's a bit of a fake XPt, though,
94// and is only used because it makes some of the code simpler.
95//
96// XTrees are bi-directional.
97//
98// > parent < Example: if child1() calls parent() and child2()
99// / | \ also calls parent(), and parent() calls malloc(),
100// | / \ | the XTree will look like this.
101// | v v |
102// child1 child2
103
104typedef struct _XPt XPt;
105
106struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000107 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000108
109 // Bottom-XPts: space for the precise context.
110 // Other XPts: space of all the descendent bottom-XPts.
111 // Nb: this value goes up and down as the program executes.
112 UInt curr_space;
113
114 // An approximate space.time calculation used along the way for selecting
115 // which contexts to include at each census point.
116 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000117 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000118
nethercote43a15ce2004-08-30 19:15:12 +0000119 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000120 // used in the results.
121 // Note that it is *doubled*, to avoid rounding errors.
122 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000123 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000124
125 // n_children and max_children are integers; a very big program might
126 // have more than 65536 allocation points (Konqueror startup has 1800).
127 XPt* parent; // pointer to parent XPt
128 UInt n_children; // number of children
129 UInt max_children; // capacity of children array
130 XPt** children; // pointers to children XPts
131};
132
133// Each census snapshots the most significant XTrees, each XTree having a
134// top-XPt as its root. The 'curr_space' element for each XPt is recorded
135// in the snapshot. The snapshot contains all the XTree's XPts, not in a
136// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000137// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000138//
139// Graph resolution, x-axis: no point having more than about 200 census
140// x-points; you can't see them on the graph. Therefore:
141//
142// - do a census every 1 ms for first 200 --> 200, all (200 ms)
143// - halve (drop half of them) --> 100, every 2nd (200 ms)
144// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
145// - halve --> 100, every 4th (400 ms)
146// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
147// - etc.
148//
149// This isn't exactly right, because we actually drop (N/2)-1 when halving,
150// but it shows the basic idea.
151
152#define MAX_N_CENSI 200 // Keep it even, for simplicity
153
154// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
155// bands, rest get lumped into OTHERS. I only print the top N
156// (cumulative-so-far space-time) at each point. N should be a bit bigger
157// than 19 in case the cumulative space-time doesn't fit with the eventual
158// space-time computed by hp2ps (but it should be close if the samples are
159// evenly spread, since hp2ps does an approximate per-band space-time
160// calculation that just sums the totals; ie. it assumes all samples are
161// the same distance apart).
162
163#define MAX_SNAPSHOTS 32
164
165typedef
166 struct {
167 XPt* xpt;
168 UInt space;
169 }
170 XPtSnapshot;
171
172// An XTree snapshot is stored as an array of of XPt snapshots.
173typedef XPtSnapshot* XTreeSnapshot;
174
175typedef
176 struct {
177 Int ms_time; // Int: must allow -1
178 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
179 UInt others_space;
180 UInt heap_admin_space;
181 UInt stacks_space;
182 }
183 Census;
184
185// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
186// which is a foothold into the XCon at which it was allocated. From
187// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
188// decremented (at deallocation).
189//
190// Nb: first two fields must match core's VgHashNode.
191typedef
192 struct _HP_Chunk {
193 struct _HP_Chunk* next;
194 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000195 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000196 XPt* where; // Where allocated; bottom-XPt
197 }
198 HP_Chunk;
199
200/*------------------------------------------------------------*/
201/*--- Profiling events ---*/
202/*------------------------------------------------------------*/
203
204typedef
205 enum {
206 VgpGetXPt = VgpFini+1,
207 VgpGetXPtSearch,
208 VgpCensus,
209 VgpCensusHeap,
210 VgpCensusSnapshot,
211 VgpCensusTreeSize,
212 VgpUpdateXCon,
213 VgpCalcSpacetime2,
214 VgpPrintHp,
215 VgpPrintXPts,
216 }
njn4be0a692004-11-22 18:10:36 +0000217 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000218
219/*------------------------------------------------------------*/
220/*--- Statistics ---*/
221/*------------------------------------------------------------*/
222
223// Konqueror startup, to give an idea of the numbers involved with a biggish
224// program, with default depth:
225//
226// depth=3 depth=40
227// - 310,000 allocations
228// - 300,000 frees
229// - 15,000 XPts 800,000 XPts
230// - 1,800 top-XPts
231
232static UInt n_xpts = 0;
233static UInt n_bot_xpts = 0;
234static UInt n_allocs = 0;
235static UInt n_zero_allocs = 0;
236static UInt n_frees = 0;
237static UInt n_children_reallocs = 0;
238static UInt n_snapshot_frees = 0;
239
240static UInt n_halvings = 0;
241static UInt n_real_censi = 0;
242static UInt n_fake_censi = 0;
243static UInt n_attempted_censi = 0;
244
245/*------------------------------------------------------------*/
246/*--- Globals ---*/
247/*------------------------------------------------------------*/
248
249#define FILENAME_LEN 256
250
251#define SPRINTF(zz_buf, fmt, args...) \
252 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
253 VG_(write)(fd, (void*)zz_buf, len); \
254 } while (0)
255
256#define BUF_LEN 1024 // general purpose
257static Char buf [BUF_LEN];
258static Char buf2[BUF_LEN];
259static Char buf3[BUF_LEN];
260
nethercote8b5f40c2004-11-02 13:29:50 +0000261static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000262
263static VgHashTable malloc_list = NULL; // HP_Chunks
264
265static UInt n_heap_blocks = 0;
266
njn51d827b2005-05-09 01:02:08 +0000267// Current directory at startup.
njn57ca7ab2005-06-21 23:44:58 +0000268static Char base_dir[VKI_PATH_MAX];
nethercotec9f36922004-02-14 16:40:02 +0000269
270#define MAX_ALLOC_FNS 32 // includes the builtin ones
271
nethercotec7469182004-05-11 09:21:08 +0000272// First few filled in, rest should be zeroed. Zero-terminated vector.
273static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000274static Char* alloc_fns[MAX_ALLOC_FNS] = {
275 "malloc",
276 "operator new(unsigned)",
277 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000278 "operator new(unsigned, std::nothrow_t const&)",
279 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000280 "__builtin_new",
281 "__builtin_vec_new",
282 "calloc",
283 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000284 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000285};
286
287
288/*------------------------------------------------------------*/
289/*--- Command line args ---*/
290/*------------------------------------------------------------*/
291
292#define MAX_DEPTH 50
293
294typedef
295 enum {
296 XText, XHTML,
297 }
298 XFormat;
299
300static Bool clo_heap = True;
301static UInt clo_heap_admin = 8;
302static Bool clo_stacks = True;
303static Bool clo_depth = 3;
304static XFormat clo_format = XText;
305
njn51d827b2005-05-09 01:02:08 +0000306static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000307{
njn45270a22005-03-27 01:00:11 +0000308 VG_BOOL_CLO(arg, "--heap", clo_heap)
309 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000310
njn45270a22005-03-27 01:00:11 +0000311 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
312 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000313
314 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
315 alloc_fns[n_alloc_fns] = & arg[11];
316 n_alloc_fns++;
317 if (n_alloc_fns >= MAX_ALLOC_FNS) {
318 VG_(printf)("Too many alloc functions specified, sorry");
319 VG_(bad_option)(arg);
320 }
321 }
322
323 else if (VG_CLO_STREQ(arg, "--format=text"))
324 clo_format = XText;
325 else if (VG_CLO_STREQ(arg, "--format=html"))
326 clo_format = XHTML;
327
328 else
329 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000330
nethercotec9f36922004-02-14 16:40:02 +0000331 return True;
332}
333
njn51d827b2005-05-09 01:02:08 +0000334static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000335{
336 VG_(printf)(
337" --heap=no|yes profile heap blocks [yes]\n"
338" --heap-admin=<number> average admin bytes per heap block [8]\n"
339" --stacks=no|yes profile stack(s) [yes]\n"
340" --depth=<number> depth of contexts [3]\n"
341" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
342" --format=text|html format of textual output [text]\n"
343 );
344 VG_(replacement_malloc_print_usage)();
345}
346
njn51d827b2005-05-09 01:02:08 +0000347static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000348{
349 VG_(replacement_malloc_print_debug_usage)();
350}
351
352/*------------------------------------------------------------*/
353/*--- Execution contexts ---*/
354/*------------------------------------------------------------*/
355
356// Fake XPt representing all allocation functions like malloc(). Acts as
357// parent node to all top-XPts.
358static XPt* alloc_xpt;
359
360// Cheap allocation for blocks that never need to be freed. Saves about 10%
361// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000362static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000363{
364 static Addr hp = 0; // current heap pointer
365 static Addr hp_lim = 0; // maximum usable byte in current block
366
367 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
368
369 if (hp + n_bytes > hp_lim) {
370 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
371 hp_lim = hp + SUPERBLOCK_SIZE - 1;
372 }
373
374 hp += n_bytes;
375
376 return (void*)(hp - n_bytes);
377}
378
379
380
njnd01fef72005-03-25 23:35:48 +0000381static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000382{
383 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000384 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000385
nethercote43a15ce2004-08-30 19:15:12 +0000386 xpt->curr_space = 0;
387 xpt->approx_ST = 0;
388 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000389
390 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000391
392 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000393 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000394
395 xpt->n_children = 0;
396
397 // If a bottom-XPt, don't allocate space for children. This can be 50%
398 // or more, although it tends to drop as --depth increases (eg. 10% for
399 // konqueror with --depth=20).
400 if ( is_bottom ) {
401 xpt->max_children = 0;
402 xpt->children = NULL;
403 n_bot_xpts++;
404 } else {
405 xpt->max_children = 4;
406 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
407 }
408
409 // Update statistics
410 n_xpts++;
411
412 return xpt;
413}
414
njnd01fef72005-03-25 23:35:48 +0000415static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000416{
417 Int i;
418
njnd01fef72005-03-25 23:35:48 +0000419 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000420 for (i = 0; i < n_alloc_fns; i++) {
421 if (VG_STREQ(buf, alloc_fns[i]))
422 return True;
423 }
424 }
425 return False;
426}
427
428// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
429// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
430// to ensure this in certain cases. See comments below.
431static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
432{
njnd01fef72005-03-25 23:35:48 +0000433 // Static to minimise stack size. +1 for added ~0 IP
434 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000435
436 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000437 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000438 UInt overestimate;
439 Bool reached_bottom;
440
441 VGP_PUSHCC(VgpGetXPt);
442
443 // Want at least clo_depth non-alloc-fn entries in the snapshot.
444 // However, because we have 1 or more (an unknown number, at this point)
445 // alloc-fns ignored, we overestimate the size needed for the stack
446 // snapshot. Then, if necessary, we repeatedly increase the size until
447 // it is enough.
448 overestimate = 2;
449 while (True) {
njnd01fef72005-03-25 23:35:48 +0000450 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000451
njnd01fef72005-03-25 23:35:48 +0000452 // Now we add a dummy "unknown" IP at the end. This is only used if we
453 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000454 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
455 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000456 // the parent's approx_ST wouldn't be equal [or almost equal] to the
457 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000458 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000459
njnd01fef72005-03-25 23:35:48 +0000460 // Skip over alloc functions in ips[].
461 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000462
463 // Must be at least one alloc function, unless client used
464 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000465 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000466
467 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000468 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000469 overestimate += 2;
470 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000471 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000472 } else {
473 break;
474 }
475 }
476 A = L;
njnd01fef72005-03-25 23:35:48 +0000477 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000478 reached_bottom = False;
479
njnd01fef72005-03-25 23:35:48 +0000480 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000481
482 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000483 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000484 while (True) {
njnd01fef72005-03-25 23:35:48 +0000485 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000486 // XXX: linear search, ugh -- about 10% of time for konqueror startup
487 // XXX: tried cacheing last result, only hit about 4% for konqueror
488 // Nb: this search hits about 98% of the time for konqueror
489 VGP_PUSHCC(VgpGetXPtSearch);
490
491 // If we've searched/added deep enough, or run out of EIPs, this is
492 // the bottom XPt.
493 if (L - A + 1 == clo_depth || L == B)
494 reached_bottom = True;
495
496 nC = 0;
497 while (True) {
498 if (nC == xpt->n_children) {
499 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000500 tl_assert(xpt->max_children != 0);
501 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000502 // Expand 'children' if necessary
503 if (xpt->n_children == xpt->max_children) {
504 xpt->max_children *= 2;
505 xpt->children = VG_(realloc)( xpt->children,
506 xpt->max_children * sizeof(XPt*) );
507 n_children_reallocs++;
508 }
njnd01fef72005-03-25 23:35:48 +0000509 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000510 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000511 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000512 break;
513 }
njnd01fef72005-03-25 23:35:48 +0000514 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000515 nC++; // keep looking
516 }
517 VGP_POPCC(VgpGetXPtSearch);
518
519 // Return found/built bottom-XPt.
520 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000521 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000522 VGP_POPCC(VgpGetXPt);
523 return xpt->children[nC];
524 }
525
526 // Descend to next level in XTree, the newly found/built non-bottom-XPt
527 xpt = xpt->children[nC];
528 L++;
529 }
530}
531
532// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
533static void update_XCon(XPt* xpt, Int space_delta)
534{
535 VGP_PUSHCC(VgpUpdateXCon);
536
njnca82cc02004-11-22 17:18:48 +0000537 tl_assert(True == clo_heap);
538 tl_assert(0 != space_delta);
539 tl_assert(NULL != xpt);
540 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000541
542 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000543 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000544 xpt->curr_space += space_delta;
545 xpt = xpt->parent;
546 }
njnca82cc02004-11-22 17:18:48 +0000547 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000548 alloc_xpt->curr_space += space_delta;
549
550 VGP_POPCC(VgpUpdateXCon);
551}
552
553// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000554static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000555{
556 XPt* xpt1 = *(XPt**)n1;
557 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000558 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000559}
560
nethercote43a15ce2004-08-30 19:15:12 +0000561static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000562{
563 XPt* xpt1 = *(XPt**)n1;
564 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000565 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000566}
567
568
569/*------------------------------------------------------------*/
570/*--- A generic Queue ---*/
571/*------------------------------------------------------------*/
572
573typedef
574 struct {
575 UInt head; // Index of first entry
576 UInt tail; // Index of final+1 entry, ie. next free slot
577 UInt max_elems;
578 void** elems;
579 }
580 Queue;
581
582static Queue* construct_queue(UInt size)
583{
584 UInt i;
585 Queue* q = VG_(malloc)(sizeof(Queue));
586 q->head = 0;
587 q->tail = 0;
588 q->max_elems = size;
589 q->elems = VG_(malloc)(size * sizeof(void*));
590 for (i = 0; i < size; i++)
591 q->elems[i] = NULL;
592
593 return q;
594}
595
596static void destruct_queue(Queue* q)
597{
598 VG_(free)(q->elems);
599 VG_(free)(q);
600}
601
602static void shuffle(Queue* dest_q, void** old_elems)
603{
604 UInt i, j;
605 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
606 dest_q->elems[i] = old_elems[j];
607 dest_q->head = 0;
608 dest_q->tail = i;
609 for ( ; i < dest_q->max_elems; i++)
610 dest_q->elems[i] = NULL; // paranoia
611}
612
613// Shuffles elements down. If not enough slots free, increase size. (We
614// don't wait until we've completely run out of space, because there could
615// be lots of shuffling just before that point which would be slow.)
616static void adjust(Queue* q)
617{
618 void** old_elems;
619
njnca82cc02004-11-22 17:18:48 +0000620 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000621 if (q->head < 10) {
622 old_elems = q->elems;
623 q->max_elems *= 2;
624 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
625 shuffle(q, old_elems);
626 VG_(free)(old_elems);
627 } else {
628 shuffle(q, q->elems);
629 }
630}
631
632static void enqueue(Queue* q, void* elem)
633{
634 if (q->tail == q->max_elems)
635 adjust(q);
636 q->elems[q->tail++] = elem;
637}
638
639static Bool is_empty_queue(Queue* q)
640{
641 return (q->head == q->tail);
642}
643
644static void* dequeue(Queue* q)
645{
646 if (is_empty_queue(q))
647 return NULL; // Queue empty
648 else
649 return q->elems[q->head++];
650}
651
652/*------------------------------------------------------------*/
653/*--- malloc() et al replacement wrappers ---*/
654/*------------------------------------------------------------*/
655
656static __inline__
657void add_HP_Chunk(HP_Chunk* hc)
658{
659 n_heap_blocks++;
660 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
661}
662
663static __inline__
664HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
665{
nethercote3d6b6112004-11-04 16:39:43 +0000666 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000667 (VgHashNode***)prev_chunks_next_ptr );
668}
669
670static __inline__
671void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
672{
njnca82cc02004-11-22 17:18:48 +0000673 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000674 n_heap_blocks--;
675 *prev_chunks_next_ptr = hc->next;
676}
677
678// Forward declaration
679static void hp_census(void);
680
nethercote159dfef2004-09-13 13:27:30 +0000681static
njn57735902004-11-25 18:04:54 +0000682void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
683 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000684{
685 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000686 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000687 if (size < 0) return NULL;
688
689 VGP_PUSHCC(VgpCliMalloc);
690
691 // Update statistics
692 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000693 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000694
nethercote57e36b32004-07-10 14:56:28 +0000695 // Allocate and zero if necessary
696 if (!p) {
697 p = VG_(cli_malloc)( align, size );
698 if (!p) {
699 VGP_POPCC(VgpCliMalloc);
700 return NULL;
701 }
702 if (is_zeroed) VG_(memset)(p, 0, size);
703 }
704
705 // Make new HP_Chunk node, add to malloclist
706 hc = VG_(malloc)(sizeof(HP_Chunk));
707 hc->size = size;
708 hc->data = (Addr)p;
709 hc->where = NULL; // paranoia
710 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000711 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000712 if (0 != size)
713 update_XCon(hc->where, size);
714 }
715 add_HP_Chunk( hc );
716
717 // do a census!
718 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000719
720 VGP_POPCC(VgpCliMalloc);
721 return p;
722}
723
724static __inline__
725void die_block ( void* p, Bool custom_free )
726{
nethercote57e36b32004-07-10 14:56:28 +0000727 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000728
729 VGP_PUSHCC(VgpCliMalloc);
730
731 // Update statistics
732 n_frees++;
733
nethercote57e36b32004-07-10 14:56:28 +0000734 // Remove HP_Chunk from malloclist
735 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000736 if (hc == NULL)
737 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000738 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000739 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000740
741 if (clo_heap && hc->size != 0)
742 update_XCon(hc->where, -hc->size);
743
nethercote57e36b32004-07-10 14:56:28 +0000744 VG_(free)( hc );
745
746 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000747 if (!custom_free)
748 VG_(cli_free)( p );
749
nethercote57e36b32004-07-10 14:56:28 +0000750 // do a census!
751 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000752
nethercotec9f36922004-02-14 16:40:02 +0000753 VGP_POPCC(VgpCliMalloc);
754}
755
756
njn51d827b2005-05-09 01:02:08 +0000757static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000758{
njn57735902004-11-25 18:04:54 +0000759 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000760}
761
njn51d827b2005-05-09 01:02:08 +0000762static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000763{
njn57735902004-11-25 18:04:54 +0000764 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000765}
766
njn51d827b2005-05-09 01:02:08 +0000767static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000768{
njn57735902004-11-25 18:04:54 +0000769 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000770}
771
njn51d827b2005-05-09 01:02:08 +0000772static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000773{
njn57735902004-11-25 18:04:54 +0000774 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000775}
776
njn51d827b2005-05-09 01:02:08 +0000777static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000778{
njn57735902004-11-25 18:04:54 +0000779 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000780}
781
njn51d827b2005-05-09 01:02:08 +0000782static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000783{
784 die_block( p, /*custom_free*/False );
785}
786
njn51d827b2005-05-09 01:02:08 +0000787static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000788{
789 die_block( p, /*custom_free*/False);
790}
791
njn51d827b2005-05-09 01:02:08 +0000792static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000793{
794 die_block( p, /*custom_free*/False );
795}
796
njn51d827b2005-05-09 01:02:08 +0000797static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000798{
799 HP_Chunk* hc;
800 HP_Chunk** remove_handle;
801 Int i;
802 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000803 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000804 XPt *old_where, *new_where;
805
806 VGP_PUSHCC(VgpCliMalloc);
807
808 // First try and find the block.
809 hc = get_HP_Chunk ( p_old, &remove_handle );
810 if (hc == NULL) {
811 VGP_POPCC(VgpCliMalloc);
812 return NULL; // must have been a bogus free()
813 }
814
njnca82cc02004-11-22 17:18:48 +0000815 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000816 old_size = hc->size;
817
818 if (new_size <= old_size) {
819 // new size is smaller or same; block not moved
820 p_new = p_old;
821
822 } else {
823 // new size is bigger; make new block, copy shared contents, free old
824 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
825
826 for (i = 0; i < old_size; i++)
827 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
828
829 VG_(cli_free)(p_old);
830 }
831
832 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000833 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000834
835 // Update HP_Chunk
836 hc->data = (Addr)p_new;
837 hc->size = new_size;
838 hc->where = new_where;
839
840 // Update XPt curr_space fields
841 if (clo_heap) {
842 if (0 != old_size) update_XCon(old_where, -old_size);
843 if (0 != new_size) update_XCon(new_where, new_size);
844 }
845
846 // If block has moved, have to remove and reinsert in the malloclist
847 // (since the updated 'data' field is the hash lookup key).
848 if (p_new != p_old) {
849 remove_HP_Chunk(hc, remove_handle);
850 add_HP_Chunk(hc);
851 }
852
853 VGP_POPCC(VgpCliMalloc);
854 return p_new;
855}
856
857
858/*------------------------------------------------------------*/
859/*--- Taking a census ---*/
860/*------------------------------------------------------------*/
861
862static Census censi[MAX_N_CENSI];
863static UInt curr_census = 0;
864
865// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000866static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000867{
thughes4ad52d02004-06-27 17:37:21 +0000868 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000869 return False;
870}
871
872static UInt get_xtree_size(XPt* xpt, UInt ix)
873{
874 UInt i;
875
nethercote43a15ce2004-08-30 19:15:12 +0000876 // If no memory allocated at all, nothing interesting to record.
877 if (alloc_xpt->curr_space == 0) return 0;
878
879 // Ignore sub-XTrees that account for a miniscule fraction of current
880 // allocated space.
881 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000882 ix++;
883
884 // Count all (non-zero) descendent XPts
885 for (i = 0; i < xpt->n_children; i++)
886 ix = get_xtree_size(xpt->children[i], ix);
887 }
888 return ix;
889}
890
891static
892UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
893{
894 UInt i;
895
nethercote43a15ce2004-08-30 19:15:12 +0000896 // Structure of this function mirrors that of get_xtree_size().
897
898 if (alloc_xpt->curr_space == 0) return 0;
899
900 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000901 xtree_snapshot[ix].xpt = xpt;
902 xtree_snapshot[ix].space = xpt->curr_space;
903 ix++;
904
nethercotec9f36922004-02-14 16:40:02 +0000905 for (i = 0; i < xpt->n_children; i++)
906 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
907 }
908 return ix;
909}
910
911static UInt ms_interval;
912static UInt do_every_nth_census = 30;
913
914// Weed out half the censi; we choose those that represent the smallest
915// time-spans, because that loses the least information.
916//
917// Algorithm for N censi: We find the census representing the smallest
918// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
919// (It's (N/2)-1 because we never remove the first and last censi.)
920// We have to do this one census at a time, rather than finding the (N/2)-1
921// smallest censi in one hit, because when a census is removed, it's
922// neighbours immediately cover greater timespans. So it's N^2, but N only
923// equals 200, and this is only done every 100 censi, which is not too often.
924static void halve_censi(void)
925{
926 Int i, jp, j, jn, k;
927 Census* min_census;
928
929 n_halvings++;
930 if (VG_(clo_verbosity) > 1)
931 VG_(message)(Vg_UserMsg, "Halving censi...");
932
933 // Sets j to the index of the first not-yet-removed census at or after i
934 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000935 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000936
937 for (i = 2; i < MAX_N_CENSI; i += 2) {
938 // Find the censi representing the smallest timespan. The timespan
939 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
940 // censi A and B. We don't consider the first and last censi for
941 // removal.
942 Int min_span = 0x7fffffff;
943 Int min_j = 0;
944
945 // Initial triple: (prev, curr, next) == (jp, j, jn)
946 jp = 0;
947 FIND_CENSUS(1, j);
948 FIND_CENSUS(j+1, jn);
949 while (jn < MAX_N_CENSI) {
950 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000951 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000952 if (timespan < min_span) {
953 min_span = timespan;
954 min_j = j;
955 }
956 // Move on to next triple
957 jp = j;
958 j = jn;
959 FIND_CENSUS(jn+1, jn);
960 }
961 // We've found the least important census, now remove it
962 min_census = & censi[ min_j ];
963 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
964 n_snapshot_frees++;
965 VG_(free)(min_census->xtree_snapshots[k]);
966 min_census->xtree_snapshots[k] = NULL;
967 }
968 min_census->ms_time = -1;
969 }
970
971 // Slide down the remaining censi over the removed ones. The '<=' is
972 // because we are removing on (N/2)-1, rather than N/2.
973 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
974 FIND_CENSUS(j, j);
975 if (i != j) {
976 censi[i] = censi[j];
977 }
978 }
979 curr_census = i;
980
981 // Double intervals
982 ms_interval *= 2;
983 do_every_nth_census *= 2;
984
985 if (VG_(clo_verbosity) > 1)
986 VG_(message)(Vg_UserMsg, "...done");
987}
988
989// Take a census. Census time seems to be insignificant (usually <= 0 ms,
990// almost always <= 1ms) so don't have to worry about subtracting it from
991// running time in any way.
992//
993// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
994// 50ms!
995static void hp_census(void)
996{
997 static UInt ms_prev_census = 0;
998 static UInt ms_next_census = 0; // zero allows startup census
999
1000 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001001 Census* census;
1002
1003 VGP_PUSHCC(VgpCensus);
1004
1005 // Only do a census if it's time
1006 ms_time = VG_(read_millisecond_timer)();
1007 ms_time_since_prev = ms_time - ms_prev_census;
1008 if (ms_time < ms_next_census) {
1009 n_fake_censi++;
1010 VGP_POPCC(VgpCensus);
1011 return;
1012 }
1013 n_real_censi++;
1014
1015 census = & censi[curr_census];
1016
1017 census->ms_time = ms_time;
1018
1019 // Heap: snapshot the K most significant XTrees -------------------
1020 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001021 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001022 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1023 ? alloc_xpt->n_children
1024 : MAX_SNAPSHOTS); // max out
1025
nethercote43a15ce2004-08-30 19:15:12 +00001026 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001027 // We *do not* do it for any non-top-XPTs.
1028 for (i = 0; i < alloc_xpt->n_children; i++) {
1029 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001030 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001031 }
nethercote43a15ce2004-08-30 19:15:12 +00001032 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001033 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001034 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001035
1036 VGP_PUSHCC(VgpCensusHeap);
1037
1038 // For each significant top-level XPt, record space info about its
1039 // entire XTree, in a single census entry.
1040 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1041 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001042 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001043 for (i = 0; i < K; i++) {
1044 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001045// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1046 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001047 VGP_PUSHCC(VgpCensusTreeSize);
1048 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1049 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001050
1051 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1052 // insignificant) then don't take any more snapshots.
1053 if (0 == xtree_size) break;
1054
1055 // Make array of the appropriate size (+1 for zero termination,
1056 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001057 census->xtree_snapshots[i] =
1058 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001059 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001060 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1061 (xtree_size+1) * sizeof(XPtSnapshot));
1062
1063 // Take space-snapshot: copy 'curr_space' for every XPt in the
1064 // XTree into the snapshot array, along with pointers to the XPts.
1065 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001066 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001067 // saves a lot of memory and up to 40% time with big --depth valus.
1068 VGP_PUSHCC(VgpCensusSnapshot);
1069 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1070 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001071 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001072 VGP_POPCC(VgpCensusSnapshot);
1073 }
1074// VG_(printf)("\n\n");
1075 // Zero-terminate 'xtree_snapshot' array
1076 census->xtree_snapshots[i] = NULL;
1077
1078 VGP_POPCC(VgpCensusHeap);
1079
1080 //VG_(printf)("printed %d censi\n", K);
1081
1082 // Lump the rest into a single "others" entry.
1083 census->others_space = 0;
1084 for (i = K; i < alloc_xpt->n_children; i++) {
1085 census->others_space += alloc_xpt->children[i]->curr_space;
1086 }
1087 }
1088
1089 // Heap admin -------------------------------------------------------
1090 if (clo_heap_admin > 0)
1091 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1092
1093 // Stack(s) ---------------------------------------------------------
1094 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001095 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001096 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001097 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001098 }
1099
1100 // Finish, update interval if necessary -----------------------------
1101 curr_census++;
1102 census = NULL; // don't use again now that curr_census changed
1103
1104 // Halve the entries, if our census table is full
1105 if (MAX_N_CENSI == curr_census) {
1106 halve_censi();
1107 }
1108
1109 // Take time for next census from now, rather than when this census
1110 // should have happened. Because, if there's a big gap due to a kernel
1111 // operation, there's no point doing catch-up censi every BB for a while
1112 // -- that would just give N censi at almost the same time.
1113 if (VG_(clo_verbosity) > 1) {
1114 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1115 VG_(read_millisecond_timer)() - ms_time );
1116 }
1117 ms_prev_census = ms_time;
1118 ms_next_census = ms_time + ms_interval;
1119 //ms_next_census += ms_interval;
1120
1121 //VG_(printf)("Next: %d ms\n", ms_next_census);
1122
1123 VGP_POPCC(VgpCensus);
1124}
1125
1126/*------------------------------------------------------------*/
1127/*--- Tracked events ---*/
1128/*------------------------------------------------------------*/
1129
nethercote8b5f40c2004-11-02 13:29:50 +00001130static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001131{
1132 sigstacks_space += len;
1133}
1134
nethercote8b5f40c2004-11-02 13:29:50 +00001135static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001136{
njnca82cc02004-11-22 17:18:48 +00001137 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001138 sigstacks_space -= len;
1139}
1140
1141/*------------------------------------------------------------*/
1142/*--- Client Requests ---*/
1143/*------------------------------------------------------------*/
1144
njn51d827b2005-05-09 01:02:08 +00001145static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001146{
1147 switch (argv[0]) {
1148 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001149 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001150 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001151 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001152 *ret = 0;
njn57735902004-11-25 18:04:54 +00001153 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001154 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001155 return True;
1156 }
1157 case VG_USERREQ__FREELIKE_BLOCK: {
1158 void* p = (void*)argv[1];
1159 *ret = 0;
1160 die_block( p, /*custom_free*/True );
1161 return True;
1162 }
1163 default:
1164 *ret = 0;
1165 return False;
1166 }
1167}
1168
1169/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001170/*--- Instrumentation ---*/
1171/*------------------------------------------------------------*/
1172
njn51d827b2005-05-09 01:02:08 +00001173static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1174 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001175{
sewardjd54babf2005-03-21 00:55:49 +00001176 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001177 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001178}
1179
1180/*------------------------------------------------------------*/
1181/*--- Spacetime recomputation ---*/
1182/*------------------------------------------------------------*/
1183
nethercote43a15ce2004-08-30 19:15:12 +00001184// Although we've been calculating space-time along the way, because the
1185// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001186// might not agree with what hp2ps sees, because we've thrown away some of
1187// the information. So recompute it at the scale that hp2ps sees, so we can
1188// confidently determine which contexts hp2ps will choose for displaying as
1189// distinct bands. This recomputation only happens to the significant ones
1190// that get printed in the .hp file, so it's cheap.
1191//
nethercote43a15ce2004-08-30 19:15:12 +00001192// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001193// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1194// where
1195// a[N] is the space at census N
1196// d(A,B) is the time interval between censi A and B
1197// and
1198// d(A,B) + d(B,C) == d(A,C)
1199//
1200// Key point: we can calculate the area for a census without knowing the
1201// previous or subsequent censi's space; because any over/underestimates
1202// for this census will be reversed in the next, balancing out. This is
1203// important, as getting the previous/next census entry for a particular
1204// AP is a pain with this data structure, but getting the prev/next
1205// census time is easy.
1206//
nethercote43a15ce2004-08-30 19:15:12 +00001207// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001208// The ULong* values are all running totals, hence the use of "+=" everywhere.
1209
1210// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001211static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001212 ULong* twice_heap_ST,
1213 ULong* twice_heap_admin_ST,
1214 ULong* twice_stack_ST)
1215{
1216 UInt i, j;
1217 XPtSnapshot* xpt_snapshot;
1218
1219 // Heap --------------------------------------------------------
1220 if (clo_heap) {
1221 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001222 // Compute total heap exact_ST_dbld for the entire XTree using only
1223 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001224 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1225
nethercote43a15ce2004-08-30 19:15:12 +00001226 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1227 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001228 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1229 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001230 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001231 }
1232 }
1233 *twice_heap_ST += d_t1_t2 * census->others_space;
1234 }
1235
1236 // Heap admin --------------------------------------------------
1237 if (clo_heap_admin > 0)
1238 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1239
1240 // Stack(s) ----------------------------------------------------
1241 if (clo_stacks)
1242 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1243}
1244
1245// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001246static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001247{
1248 UInt i, N = curr_census;
1249
1250 VGP_PUSHCC(VgpCalcSpacetime2);
1251
1252 *heap2 = 0;
1253 *heap_admin2 = 0;
1254 *stack2 = 0;
1255
1256 if (N <= 1)
1257 return;
1258
nethercote43a15ce2004-08-30 19:15:12 +00001259 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1260 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001261
1262 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001263 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1264 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001265 }
1266
nethercote43a15ce2004-08-30 19:15:12 +00001267 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1268 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001269 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1270 *heap2 /= 2;
1271 *heap_admin2 /= 2;
1272 *stack2 /= 2;
1273
1274 VGP_POPCC(VgpCalcSpacetime2);
1275}
1276
1277/*------------------------------------------------------------*/
1278/*--- Writing the graph file ---*/
1279/*------------------------------------------------------------*/
1280
1281static Char* make_filename(Char* dir, Char* suffix)
1282{
1283 Char* filename;
1284
1285 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1286 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1287 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1288
1289 return filename;
1290}
1291
1292// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1293static Char* clean_fnname(Char *d, Char* s)
1294{
1295 Char* dorig = d;
1296 while (*s) {
1297 if (' ' == *s) { *d = '%'; }
1298 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1299 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1300 else { *d = *s; };
1301 s++;
1302 d++;
1303 }
1304 *d = '\0';
1305 return dorig;
1306}
1307
1308static void file_err ( Char* file )
1309{
njn02bc4b82005-05-15 17:28:26 +00001310 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001311 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1312}
1313
1314/* Format, by example:
1315
1316 JOB "a.out -p"
1317 DATE "Fri Apr 17 11:43:45 1992"
1318 SAMPLE_UNIT "seconds"
1319 VALUE_UNIT "bytes"
1320 BEGIN_SAMPLE 0.00
1321 SYSTEM 24
1322 END_SAMPLE 0.00
1323 BEGIN_SAMPLE 1.00
1324 elim 180
1325 insert 24
1326 intersect 12
1327 disin 60
1328 main 12
1329 reduce 20
1330 SYSTEM 12
1331 END_SAMPLE 1.00
1332 MARK 1.50
1333 MARK 1.75
1334 MARK 1.80
1335 BEGIN_SAMPLE 2.00
1336 elim 192
1337 insert 24
1338 intersect 12
1339 disin 84
1340 main 12
1341 SYSTEM 24
1342 END_SAMPLE 2.00
1343 BEGIN_SAMPLE 2.82
1344 END_SAMPLE 2.82
1345 */
1346static void write_hp_file(void)
1347{
1348 Int i, j;
1349 Int fd, res;
1350 Char *hp_file, *ps_file, *aux_file;
1351 Char* cmdfmt;
1352 Char* cmdbuf;
1353 Int cmdlen;
1354
1355 VGP_PUSHCC(VgpPrintHp);
1356
1357 // Open file
1358 hp_file = make_filename( base_dir, ".hp" );
1359 ps_file = make_filename( base_dir, ".ps" );
1360 aux_file = make_filename( base_dir, ".aux" );
1361 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1362 VKI_S_IRUSR|VKI_S_IWUSR);
1363 if (fd < 0) {
1364 file_err( hp_file );
1365 VGP_POPCC(VgpPrintHp);
1366 return;
1367 }
1368
1369 // File header, including command line
1370 SPRINTF(buf, "JOB \"");
1371 for (i = 0; i < VG_(client_argc); i++)
1372 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1373 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1374 "DATE \"\"\n"
1375 "SAMPLE_UNIT \"ms\"\n"
1376 "VALUE_UNIT \"bytes\"\n", ms_interval);
1377
1378 // Censi
1379 for (i = 0; i < curr_census; i++) {
1380 Census* census = & censi[i];
1381
1382 // Census start
1383 SPRINTF(buf, "MARK %d.0\n"
1384 "BEGIN_SAMPLE %d.0\n",
1385 census->ms_time, census->ms_time);
1386
1387 // Heap -----------------------------------------------------------
1388 if (clo_heap) {
1389 // Print all the significant XPts from that census
1390 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1391 // Grab the jth top-XPt
1392 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001393 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001394 VG_(sprintf)(buf2, "???");
1395 }
njnd01fef72005-03-25 23:35:48 +00001396 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001397 clean_fnname(buf3, buf2), xtree_snapshot->space);
1398 }
1399
1400 // Remaining heap block alloc points, combined
1401 if (census->others_space > 0)
1402 SPRINTF(buf, "other %d\n", census->others_space);
1403 }
1404
1405 // Heap admin -----------------------------------------------------
1406 if (clo_heap_admin > 0 && census->heap_admin_space)
1407 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1408
1409 // Stack(s) -------------------------------------------------------
1410 if (clo_stacks)
1411 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1412
1413 // Census end
1414 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1415 }
1416
1417 // Close file
njnca82cc02004-11-22 17:18:48 +00001418 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001419 VG_(close)(fd);
1420
1421 // Attempt to convert file using hp2ps
1422 cmdfmt = "%s/hp2ps -c -t1 %s";
1423 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1424 + VG_(strlen)(cmdfmt);
1425 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1426 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1427 res = VG_(system)(cmdbuf);
1428 VG_(free)(cmdbuf);
1429 if (res != 0) {
1430 VG_(message)(Vg_UserMsg,
1431 "Conversion to PostScript failed. Try converting manually.");
1432 } else {
1433 // remove the .hp and .aux file
1434 VG_(unlink)(hp_file);
1435 VG_(unlink)(aux_file);
1436 }
1437
1438 VG_(free)(hp_file);
1439 VG_(free)(ps_file);
1440 VG_(free)(aux_file);
1441
1442 VGP_POPCC(VgpPrintHp);
1443}
1444
1445/*------------------------------------------------------------*/
1446/*--- Writing the XPt text/HTML file ---*/
1447/*------------------------------------------------------------*/
1448
1449static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1450{
1451 int i, len, space;
1452
1453 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1454 len = VG_(strlen)(xbuf);
1455 space = field_width - len;
1456 if (space < 0) space = 0; /* Allow for v. small field_width */
1457 i = len;
1458
1459 /* Right justify in field */
1460 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1461 for (i = 0; i < space; i++) xbuf[i] = ' ';
1462}
1463
1464// Nb: uses a static buffer, each call trashes the last string returned.
1465static Char* make_perc(ULong spacetime, ULong total_spacetime)
1466{
1467 static Char mbuf[32];
1468
1469 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001470 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001471 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1472 return mbuf;
1473}
1474
njnd01fef72005-03-25 23:35:48 +00001475// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001476// bottom-to-top of XCon, and then printed in the reverse order.
1477static UInt pp_XCon(Int fd, XPt* xpt)
1478{
njnd01fef72005-03-25 23:35:48 +00001479 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001480 Int i = 0;
1481 Int n = 0;
1482 Bool is_HTML = ( XHTML == clo_format );
1483 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1484 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1485
njnca82cc02004-11-22 17:18:48 +00001486 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001487
1488 while (True) {
njnd01fef72005-03-25 23:35:48 +00001489 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001490 n++;
1491 if (alloc_xpt == xpt->parent) break;
1492 i++;
1493 xpt = xpt->parent;
1494 }
1495
1496 for (i = n-1; i >= 0; i--) {
1497 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001498 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001499 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1500 }
1501
1502 return n;
1503}
1504
1505// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001506// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001507// sufficient, because function pointers mean that you can call more than
1508// one other function from a single code location. So instead we use the
1509// address of the xpt struct itself, which is guaranteed to be unique.
1510
1511static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1512 ULong total_spacetime)
1513{
1514 UInt i;
1515 XPt *xpt, *child;
1516 UInt L = 0;
1517 UInt c1 = 1;
1518 UInt c2 = 0;
1519 ULong sum = 0;
1520 UInt n;
njnd01fef72005-03-25 23:35:48 +00001521 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001522 Bool is_HTML = ( XHTML == clo_format );
1523 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1524 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1525 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1526 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1527 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1528 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1529 Char* end_hr = ( is_HTML ? "<hr>" :
1530 "=================================" );
1531 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1532
nethercote43a15ce2004-08-30 19:15:12 +00001533 if (total_spacetime == 0) {
1534 SPRINTF(buf, "(No heap memory allocated)\n");
1535 return;
1536 }
1537
1538
nethercotec9f36922004-02-14 16:40:02 +00001539 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1540
1541 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001542 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001543 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001544
nethercote43a15ce2004-08-30 19:15:12 +00001545 // Check that the sum of all children .exact_ST_dbld fields equals
1546 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001547 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001548 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001549 } else {
1550 sum = 0;
1551 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001552 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001553 }
njnca82cc02004-11-22 17:18:48 +00001554 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001555 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001556 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001557 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001558// tl_assert(sum <= xpt->exact_ST_dbld);
1559// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001560// if (sum != xpt->exact_ST_dbld) {
1561// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001562// }
1563 }
1564
1565 if (xpt == alloc_xpt) {
1566 SPRINTF(buf, "Heap allocation functions accounted for "
1567 "%s of measured spacetime%s\n",
1568 make_perc(heap_spacetime, total_spacetime), maybe_br);
1569 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001570 // Remember: exact_ST_dbld is space.time *doubled*
1571 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001572 if (is_HTML) {
1573 SPRINTF(buf, "<a name=\"b%x\"></a>"
1574 "Context accounted for "
1575 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1576 xpt, xpt, perc);
1577 } else {
1578 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1579 perc);
1580 }
1581 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001582 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001583 }
1584
nethercote43a15ce2004-08-30 19:15:12 +00001585 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001586 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001587 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001588
1589 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1590 for (i = 0; i < xpt->n_children; i++) {
1591 child = xpt->children[i];
1592
1593 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001594 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001595 UInt n_insig = xpt->n_children - i;
1596 Char* s = ( n_insig == 1 ? "" : "s" );
1597 Char* and = ( 0 == i ? "" : "and " );
1598 Char* other = ( 0 == i ? "" : "other " );
1599 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1600 maybe_li, and, n_insig, other, s, maybe_fli);
1601 break;
1602 }
1603
nethercote43a15ce2004-08-30 19:15:12 +00001604 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001605 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1606 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001607 if (is_HTML) {
1608 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1609
1610 if (child->n_children > 0) {
1611 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1612 } else {
1613 SPRINTF(buf, "%s", perc);
1614 }
njnd01fef72005-03-25 23:35:48 +00001615 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001616 } else {
njnd01fef72005-03-25 23:35:48 +00001617 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001618 }
1619
1620 if (child->n_children > 0) {
1621 enqueue(q, (void*)child);
1622 c2++;
1623 }
1624 }
1625 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1626 c1--;
1627
1628 // Putting markers between levels of the structure:
1629 // c1 tracks how many to go on this level, c2 tracks how many we've
1630 // queued up for the next level while finishing off this level.
1631 // When c1 gets to zero, we've changed levels, so print a marker,
1632 // move c2 into c1, and zero c2.
1633 if (0 == c1) {
1634 L++;
1635 c1 = c2;
1636 c2 = 0;
1637 if (! is_empty_queue(q) ) { // avoid empty one at end
1638 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1639 }
1640 } else {
1641 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1642 }
1643 }
1644 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1645 "%s value for more.\n", end_hr, depth);
1646}
1647
1648static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1649 ULong total_spacetime)
1650{
1651 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001652
nethercotec9f36922004-02-14 16:40:02 +00001653 enqueue(q, xpt);
1654 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1655 destruct_queue(q);
1656}
1657
1658static void
1659write_text_file(ULong total_ST, ULong heap_ST)
1660{
1661 Int fd, i;
1662 Char* text_file;
1663 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1664
1665 VGP_PUSHCC(VgpPrintXPts);
1666
1667 // Open file
1668 text_file = make_filename( base_dir,
1669 ( XText == clo_format ? ".txt" : ".html" ) );
1670
1671 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1672 VKI_S_IRUSR|VKI_S_IWUSR);
1673 if (fd < 0) {
1674 file_err( text_file );
1675 VGP_POPCC(VgpPrintXPts);
1676 return;
1677 }
1678
1679 // Header
1680 if (XHTML == clo_format) {
1681 SPRINTF(buf, "<html>\n"
1682 "<head>\n"
1683 "<title>%s</title>\n"
1684 "</head>\n"
1685 "<body>\n",
1686 text_file);
1687 }
1688
1689 // Command line
1690 SPRINTF(buf, "Command: ");
1691 for (i = 0; i < VG_(client_argc); i++)
1692 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1693 SPRINTF(buf, "\n%s\n", maybe_p);
1694
1695 if (clo_heap)
1696 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1697
njnca82cc02004-11-22 17:18:48 +00001698 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001699 VG_(close)(fd);
1700
1701 VGP_POPCC(VgpPrintXPts);
1702}
1703
1704/*------------------------------------------------------------*/
1705/*--- Finalisation ---*/
1706/*------------------------------------------------------------*/
1707
1708static void
1709print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1710 ULong stack_ST)
1711{
1712 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1713
1714 // Heap --------------------------------------------------------------
1715 if (clo_heap)
1716 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001717 ( 0 == total_ST ? (Char*)"(n/a)"
1718 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001719
1720 // Heap admin --------------------------------------------------------
1721 if (clo_heap_admin)
1722 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001723 ( 0 == total_ST ? (Char*)"(n/a)"
1724 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001725
njnca82cc02004-11-22 17:18:48 +00001726 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001727
1728 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001729 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001730 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001731 ( 0 == stack_ST ? (Char*)"0%"
1732 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001733 }
nethercotec9f36922004-02-14 16:40:02 +00001734
1735 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001736 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001737 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1738 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1739 n_zero_allocs * 100 / n_allocs );
1740 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1741 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1742 n_xpts*sizeof(XPt));
1743 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1744 n_bot_xpts * 100 / n_xpts);
1745 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1746 alloc_xpt->n_children * 100 / n_xpts);
1747 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1748 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1749 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1750 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1751 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1752 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1753 }
1754}
1755
njn51d827b2005-05-09 01:02:08 +00001756static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001757{
1758 ULong total_ST = 0;
1759 ULong heap_ST = 0;
1760 ULong heap_admin_ST = 0;
1761 ULong stack_ST = 0;
1762
1763 // Do a final (empty) sample to show program's end
1764 hp_census();
1765
1766 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001767 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001768 total_ST = heap_ST + heap_admin_ST + stack_ST;
1769 write_hp_file ( );
1770 write_text_file( total_ST, heap_ST );
1771 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1772}
1773
njn51d827b2005-05-09 01:02:08 +00001774/*------------------------------------------------------------*/
1775/*--- Initialisation ---*/
1776/*------------------------------------------------------------*/
1777
1778static void ms_post_clo_init(void)
1779{
1780 ms_interval = 1;
1781
1782 // Do an initial sample for t = 0
1783 hp_census();
1784}
1785
1786static void ms_pre_clo_init()
1787{
1788 VG_(details_name) ("Massif");
1789 VG_(details_version) (NULL);
1790 VG_(details_description) ("a space profiler");
1791 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1792 VG_(details_bug_reports_to) (VG_BUGS_TO);
1793
1794 // Basic functions
1795 VG_(basic_tool_funcs) (ms_post_clo_init,
1796 ms_instrument,
1797 ms_fini);
1798
1799 // Needs
1800 VG_(needs_libc_freeres)();
1801 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1802 ms_print_usage,
1803 ms_print_debug_usage);
1804 VG_(needs_client_requests) (ms_handle_client_request);
njnfc51f8d2005-06-21 03:20:17 +00001805 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00001806 ms___builtin_new,
1807 ms___builtin_vec_new,
1808 ms_memalign,
1809 ms_calloc,
1810 ms_free,
1811 ms___builtin_delete,
1812 ms___builtin_vec_delete,
1813 ms_realloc,
1814 0 );
1815
1816 // Events to track
1817 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1818 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1819
1820 // Profiling events
1821 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1822 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1823 VG_(register_profile_event)(VgpCensus, "census");
1824 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1825 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1826 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1827 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1828 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1829 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1830 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1831
1832 // HP_Chunks
njnf69f9452005-07-03 17:53:11 +00001833 malloc_list = VG_(HT_construct)( 80021 ); // prime, big
njn51d827b2005-05-09 01:02:08 +00001834
1835 // Dummy node at top of the context structure.
1836 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1837
njn57ca7ab2005-06-21 23:44:58 +00001838 tl_assert( VG_(getcwd)(base_dir, VKI_PATH_MAX) );
njn51d827b2005-05-09 01:02:08 +00001839}
1840
1841VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001842
1843/*--------------------------------------------------------------------*/
1844/*--- end ms_main.c ---*/
1845/*--------------------------------------------------------------------*/
1846