blob: 73c49d0dc8fc1310a24bacbdc654cbf25b0258d0 [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
nethercotec9f36922004-02-14 16:40:02 +0000656// Forward declaration
657static void hp_census(void);
658
nethercote159dfef2004-09-13 13:27:30 +0000659static
njn57735902004-11-25 18:04:54 +0000660void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
661 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000662{
663 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000664 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000665 if (size < 0) return NULL;
666
667 VGP_PUSHCC(VgpCliMalloc);
668
669 // Update statistics
670 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000671 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000672
nethercote57e36b32004-07-10 14:56:28 +0000673 // Allocate and zero if necessary
674 if (!p) {
675 p = VG_(cli_malloc)( align, size );
676 if (!p) {
677 VGP_POPCC(VgpCliMalloc);
678 return NULL;
679 }
680 if (is_zeroed) VG_(memset)(p, 0, size);
681 }
682
njnf1c5def2005-08-11 02:17:07 +0000683 // Make new HP_Chunk node, add to malloc_list
nethercote57e36b32004-07-10 14:56:28 +0000684 hc = VG_(malloc)(sizeof(HP_Chunk));
685 hc->size = size;
686 hc->data = (Addr)p;
687 hc->where = NULL; // paranoia
688 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000689 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000690 if (0 != size)
691 update_XCon(hc->where, size);
692 }
njn246a9d22005-08-14 06:24:20 +0000693 VG_(HT_add_node)(malloc_list, hc);
njnf1c5def2005-08-11 02:17:07 +0000694 n_heap_blocks++;
nethercote57e36b32004-07-10 14:56:28 +0000695
696 // do a census!
697 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000698
699 VGP_POPCC(VgpCliMalloc);
700 return p;
701}
702
703static __inline__
704void die_block ( void* p, Bool custom_free )
705{
njnf1c5def2005-08-11 02:17:07 +0000706 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +0000707
708 VGP_PUSHCC(VgpCliMalloc);
709
710 // Update statistics
711 n_frees++;
712
njnf1c5def2005-08-11 02:17:07 +0000713 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +0000714 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn5cc5d7e2005-08-11 02:09:25 +0000715 if (NULL == hc)
716 return; // must have been a bogus free()
717 tl_assert(n_heap_blocks > 0);
718 n_heap_blocks--;
nethercotec9f36922004-02-14 16:40:02 +0000719
720 if (clo_heap && hc->size != 0)
721 update_XCon(hc->where, -hc->size);
722
nethercote57e36b32004-07-10 14:56:28 +0000723 VG_(free)( hc );
724
725 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000726 if (!custom_free)
727 VG_(cli_free)( p );
728
nethercote57e36b32004-07-10 14:56:28 +0000729 // do a census!
730 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000731
nethercotec9f36922004-02-14 16:40:02 +0000732 VGP_POPCC(VgpCliMalloc);
733}
734
735
njn51d827b2005-05-09 01:02:08 +0000736static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000737{
njn57735902004-11-25 18:04:54 +0000738 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000739}
740
njn51d827b2005-05-09 01:02:08 +0000741static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000742{
njn57735902004-11-25 18:04:54 +0000743 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000744}
745
njn51d827b2005-05-09 01:02:08 +0000746static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000747{
njn57735902004-11-25 18:04:54 +0000748 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000749}
750
njn51d827b2005-05-09 01:02:08 +0000751static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000752{
njn57735902004-11-25 18:04:54 +0000753 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000754}
755
njn51d827b2005-05-09 01:02:08 +0000756static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000757{
njn57735902004-11-25 18:04:54 +0000758 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000759}
760
njn51d827b2005-05-09 01:02:08 +0000761static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000762{
763 die_block( p, /*custom_free*/False );
764}
765
njn51d827b2005-05-09 01:02:08 +0000766static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000767{
768 die_block( p, /*custom_free*/False);
769}
770
njn51d827b2005-05-09 01:02:08 +0000771static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000772{
773 die_block( p, /*custom_free*/False );
774}
775
njn51d827b2005-05-09 01:02:08 +0000776static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000777{
njn5cc5d7e2005-08-11 02:09:25 +0000778 HP_Chunk* hc;
779 void* p_new;
780 SizeT old_size;
781 XPt *old_where, *new_where;
nethercotec9f36922004-02-14 16:40:02 +0000782
783 VGP_PUSHCC(VgpCliMalloc);
784
njna0793652005-08-16 03:34:56 +0000785 // Remove the old block
njn9a463242005-08-16 03:29:50 +0000786 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000787 if (hc == NULL) {
788 VGP_POPCC(VgpCliMalloc);
njn5cc5d7e2005-08-11 02:09:25 +0000789 return NULL; // must have been a bogus realloc()
nethercotec9f36922004-02-14 16:40:02 +0000790 }
791
nethercotec9f36922004-02-14 16:40:02 +0000792 old_size = hc->size;
793
794 if (new_size <= old_size) {
795 // new size is smaller or same; block not moved
796 p_new = p_old;
797
798 } else {
799 // new size is bigger; make new block, copy shared contents, free old
800 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
njn9e7ce212005-08-10 21:25:36 +0000801 VG_(memcpy)(p_new, p_old, old_size);
nethercotec9f36922004-02-14 16:40:02 +0000802 VG_(cli_free)(p_old);
803 }
804
805 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000806 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000807
808 // Update HP_Chunk
809 hc->data = (Addr)p_new;
810 hc->size = new_size;
811 hc->where = new_where;
812
813 // Update XPt curr_space fields
814 if (clo_heap) {
815 if (0 != old_size) update_XCon(old_where, -old_size);
816 if (0 != new_size) update_XCon(new_where, new_size);
817 }
818
njn5cc5d7e2005-08-11 02:09:25 +0000819 // Now insert the new hc (with a possibly new 'data' field) into
820 // malloc_list. If this realloc() did not increase the memory size, we
821 // will have removed and then re-added mc unnecessarily. But that's ok
822 // because shrinking a block with realloc() is (presumably) much rarer
823 // than growing it, and this way simplifies the growing case.
njn246a9d22005-08-14 06:24:20 +0000824 VG_(HT_add_node)(malloc_list, hc);
nethercotec9f36922004-02-14 16:40:02 +0000825
826 VGP_POPCC(VgpCliMalloc);
827 return p_new;
828}
829
830
831/*------------------------------------------------------------*/
832/*--- Taking a census ---*/
833/*------------------------------------------------------------*/
834
835static Census censi[MAX_N_CENSI];
836static UInt curr_census = 0;
837
nethercotec9f36922004-02-14 16:40:02 +0000838static UInt get_xtree_size(XPt* xpt, UInt ix)
839{
840 UInt i;
841
nethercote43a15ce2004-08-30 19:15:12 +0000842 // If no memory allocated at all, nothing interesting to record.
843 if (alloc_xpt->curr_space == 0) return 0;
844
845 // Ignore sub-XTrees that account for a miniscule fraction of current
846 // allocated space.
847 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000848 ix++;
849
850 // Count all (non-zero) descendent XPts
851 for (i = 0; i < xpt->n_children; i++)
852 ix = get_xtree_size(xpt->children[i], ix);
853 }
854 return ix;
855}
856
857static
858UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
859{
860 UInt i;
861
nethercote43a15ce2004-08-30 19:15:12 +0000862 // Structure of this function mirrors that of get_xtree_size().
863
864 if (alloc_xpt->curr_space == 0) return 0;
865
866 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000867 xtree_snapshot[ix].xpt = xpt;
868 xtree_snapshot[ix].space = xpt->curr_space;
869 ix++;
870
nethercotec9f36922004-02-14 16:40:02 +0000871 for (i = 0; i < xpt->n_children; i++)
872 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
873 }
874 return ix;
875}
876
877static UInt ms_interval;
878static UInt do_every_nth_census = 30;
879
880// Weed out half the censi; we choose those that represent the smallest
881// time-spans, because that loses the least information.
882//
883// Algorithm for N censi: We find the census representing the smallest
884// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
885// (It's (N/2)-1 because we never remove the first and last censi.)
886// We have to do this one census at a time, rather than finding the (N/2)-1
887// smallest censi in one hit, because when a census is removed, it's
888// neighbours immediately cover greater timespans. So it's N^2, but N only
889// equals 200, and this is only done every 100 censi, which is not too often.
890static void halve_censi(void)
891{
892 Int i, jp, j, jn, k;
893 Census* min_census;
894
895 n_halvings++;
896 if (VG_(clo_verbosity) > 1)
897 VG_(message)(Vg_UserMsg, "Halving censi...");
898
899 // Sets j to the index of the first not-yet-removed census at or after i
900 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000901 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000902
903 for (i = 2; i < MAX_N_CENSI; i += 2) {
904 // Find the censi representing the smallest timespan. The timespan
905 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
906 // censi A and B. We don't consider the first and last censi for
907 // removal.
908 Int min_span = 0x7fffffff;
909 Int min_j = 0;
910
911 // Initial triple: (prev, curr, next) == (jp, j, jn)
912 jp = 0;
913 FIND_CENSUS(1, j);
914 FIND_CENSUS(j+1, jn);
915 while (jn < MAX_N_CENSI) {
916 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000917 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000918 if (timespan < min_span) {
919 min_span = timespan;
920 min_j = j;
921 }
922 // Move on to next triple
923 jp = j;
924 j = jn;
925 FIND_CENSUS(jn+1, jn);
926 }
927 // We've found the least important census, now remove it
928 min_census = & censi[ min_j ];
929 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
930 n_snapshot_frees++;
931 VG_(free)(min_census->xtree_snapshots[k]);
932 min_census->xtree_snapshots[k] = NULL;
933 }
934 min_census->ms_time = -1;
935 }
936
937 // Slide down the remaining censi over the removed ones. The '<=' is
938 // because we are removing on (N/2)-1, rather than N/2.
939 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
940 FIND_CENSUS(j, j);
941 if (i != j) {
942 censi[i] = censi[j];
943 }
944 }
945 curr_census = i;
946
947 // Double intervals
948 ms_interval *= 2;
949 do_every_nth_census *= 2;
950
951 if (VG_(clo_verbosity) > 1)
952 VG_(message)(Vg_UserMsg, "...done");
953}
954
955// Take a census. Census time seems to be insignificant (usually <= 0 ms,
956// almost always <= 1ms) so don't have to worry about subtracting it from
957// running time in any way.
958//
959// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
960// 50ms!
961static void hp_census(void)
962{
963 static UInt ms_prev_census = 0;
964 static UInt ms_next_census = 0; // zero allows startup census
965
966 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000967 Census* census;
968
969 VGP_PUSHCC(VgpCensus);
970
971 // Only do a census if it's time
972 ms_time = VG_(read_millisecond_timer)();
973 ms_time_since_prev = ms_time - ms_prev_census;
974 if (ms_time < ms_next_census) {
975 n_fake_censi++;
976 VGP_POPCC(VgpCensus);
977 return;
978 }
979 n_real_censi++;
980
981 census = & censi[curr_census];
982
983 census->ms_time = ms_time;
984
985 // Heap: snapshot the K most significant XTrees -------------------
986 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +0000987 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +0000988 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
989 ? alloc_xpt->n_children
990 : MAX_SNAPSHOTS); // max out
991
nethercote43a15ce2004-08-30 19:15:12 +0000992 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +0000993 // We *do not* do it for any non-top-XPTs.
994 for (i = 0; i < alloc_xpt->n_children; i++) {
995 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +0000996 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000997 }
nethercote43a15ce2004-08-30 19:15:12 +0000998 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +0000999 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001000 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001001
1002 VGP_PUSHCC(VgpCensusHeap);
1003
1004 // For each significant top-level XPt, record space info about its
1005 // entire XTree, in a single census entry.
1006 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1007 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001008 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001009 for (i = 0; i < K; i++) {
1010 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001011// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1012 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001013 VGP_PUSHCC(VgpCensusTreeSize);
1014 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1015 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001016
1017 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1018 // insignificant) then don't take any more snapshots.
1019 if (0 == xtree_size) break;
1020
1021 // Make array of the appropriate size (+1 for zero termination,
1022 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001023 census->xtree_snapshots[i] =
1024 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001025 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001026 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1027 (xtree_size+1) * sizeof(XPtSnapshot));
1028
1029 // Take space-snapshot: copy 'curr_space' for every XPt in the
1030 // XTree into the snapshot array, along with pointers to the XPts.
1031 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001032 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001033 // saves a lot of memory and up to 40% time with big --depth valus.
1034 VGP_PUSHCC(VgpCensusSnapshot);
1035 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1036 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001037 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001038 VGP_POPCC(VgpCensusSnapshot);
1039 }
1040// VG_(printf)("\n\n");
1041 // Zero-terminate 'xtree_snapshot' array
1042 census->xtree_snapshots[i] = NULL;
1043
1044 VGP_POPCC(VgpCensusHeap);
1045
1046 //VG_(printf)("printed %d censi\n", K);
1047
1048 // Lump the rest into a single "others" entry.
1049 census->others_space = 0;
1050 for (i = K; i < alloc_xpt->n_children; i++) {
1051 census->others_space += alloc_xpt->children[i]->curr_space;
1052 }
1053 }
1054
1055 // Heap admin -------------------------------------------------------
1056 if (clo_heap_admin > 0)
1057 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1058
1059 // Stack(s) ---------------------------------------------------------
1060 if (clo_stacks) {
njn1d0cb0d2005-08-15 01:52:02 +00001061 ThreadId tid;
1062 Addr stack_min, stack_max;
thughes4ad52d02004-06-27 17:37:21 +00001063 census->stacks_space = sigstacks_space;
njn1d0cb0d2005-08-15 01:52:02 +00001064 VG_(thread_stack_reset_iter)();
1065 while ( VG_(thread_stack_next)(&tid, &stack_min, &stack_max) ) {
1066 census->stacks_space += (stack_max - stack_min);
1067 }
nethercotec9f36922004-02-14 16:40:02 +00001068 }
1069
1070 // Finish, update interval if necessary -----------------------------
1071 curr_census++;
1072 census = NULL; // don't use again now that curr_census changed
1073
1074 // Halve the entries, if our census table is full
1075 if (MAX_N_CENSI == curr_census) {
1076 halve_censi();
1077 }
1078
1079 // Take time for next census from now, rather than when this census
1080 // should have happened. Because, if there's a big gap due to a kernel
1081 // operation, there's no point doing catch-up censi every BB for a while
1082 // -- that would just give N censi at almost the same time.
1083 if (VG_(clo_verbosity) > 1) {
1084 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1085 VG_(read_millisecond_timer)() - ms_time );
1086 }
1087 ms_prev_census = ms_time;
1088 ms_next_census = ms_time + ms_interval;
1089 //ms_next_census += ms_interval;
1090
1091 //VG_(printf)("Next: %d ms\n", ms_next_census);
1092
1093 VGP_POPCC(VgpCensus);
1094}
1095
1096/*------------------------------------------------------------*/
1097/*--- Tracked events ---*/
1098/*------------------------------------------------------------*/
1099
nethercote8b5f40c2004-11-02 13:29:50 +00001100static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001101{
1102 sigstacks_space += len;
1103}
1104
nethercote8b5f40c2004-11-02 13:29:50 +00001105static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001106{
njnca82cc02004-11-22 17:18:48 +00001107 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001108 sigstacks_space -= len;
1109}
1110
1111/*------------------------------------------------------------*/
1112/*--- Client Requests ---*/
1113/*------------------------------------------------------------*/
1114
njn51d827b2005-05-09 01:02:08 +00001115static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001116{
1117 switch (argv[0]) {
1118 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001119 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001120 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001121 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001122 *ret = 0;
njn57735902004-11-25 18:04:54 +00001123 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001124 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001125 return True;
1126 }
1127 case VG_USERREQ__FREELIKE_BLOCK: {
1128 void* p = (void*)argv[1];
1129 *ret = 0;
1130 die_block( p, /*custom_free*/True );
1131 return True;
1132 }
1133 default:
1134 *ret = 0;
1135 return False;
1136 }
1137}
1138
1139/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001140/*--- Instrumentation ---*/
1141/*------------------------------------------------------------*/
1142
njn51d827b2005-05-09 01:02:08 +00001143static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1144 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001145{
sewardjd54babf2005-03-21 00:55:49 +00001146 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001147 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001148}
1149
1150/*------------------------------------------------------------*/
1151/*--- Spacetime recomputation ---*/
1152/*------------------------------------------------------------*/
1153
nethercote43a15ce2004-08-30 19:15:12 +00001154// Although we've been calculating space-time along the way, because the
1155// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001156// might not agree with what hp2ps sees, because we've thrown away some of
1157// the information. So recompute it at the scale that hp2ps sees, so we can
1158// confidently determine which contexts hp2ps will choose for displaying as
1159// distinct bands. This recomputation only happens to the significant ones
1160// that get printed in the .hp file, so it's cheap.
1161//
nethercote43a15ce2004-08-30 19:15:12 +00001162// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001163// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1164// where
1165// a[N] is the space at census N
1166// d(A,B) is the time interval between censi A and B
1167// and
1168// d(A,B) + d(B,C) == d(A,C)
1169//
1170// Key point: we can calculate the area for a census without knowing the
1171// previous or subsequent censi's space; because any over/underestimates
1172// for this census will be reversed in the next, balancing out. This is
1173// important, as getting the previous/next census entry for a particular
1174// AP is a pain with this data structure, but getting the prev/next
1175// census time is easy.
1176//
nethercote43a15ce2004-08-30 19:15:12 +00001177// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001178// The ULong* values are all running totals, hence the use of "+=" everywhere.
1179
1180// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001181static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001182 ULong* twice_heap_ST,
1183 ULong* twice_heap_admin_ST,
1184 ULong* twice_stack_ST)
1185{
1186 UInt i, j;
1187 XPtSnapshot* xpt_snapshot;
1188
1189 // Heap --------------------------------------------------------
1190 if (clo_heap) {
1191 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001192 // Compute total heap exact_ST_dbld for the entire XTree using only
1193 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001194 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1195
nethercote43a15ce2004-08-30 19:15:12 +00001196 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1197 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001198 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1199 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001200 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001201 }
1202 }
1203 *twice_heap_ST += d_t1_t2 * census->others_space;
1204 }
1205
1206 // Heap admin --------------------------------------------------
1207 if (clo_heap_admin > 0)
1208 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1209
1210 // Stack(s) ----------------------------------------------------
1211 if (clo_stacks)
1212 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1213}
1214
1215// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001216static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001217{
1218 UInt i, N = curr_census;
1219
1220 VGP_PUSHCC(VgpCalcSpacetime2);
1221
1222 *heap2 = 0;
1223 *heap_admin2 = 0;
1224 *stack2 = 0;
1225
1226 if (N <= 1)
1227 return;
1228
nethercote43a15ce2004-08-30 19:15:12 +00001229 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1230 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001231
1232 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001233 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1234 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001235 }
1236
nethercote43a15ce2004-08-30 19:15:12 +00001237 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1238 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001239 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1240 *heap2 /= 2;
1241 *heap_admin2 /= 2;
1242 *stack2 /= 2;
1243
1244 VGP_POPCC(VgpCalcSpacetime2);
1245}
1246
1247/*------------------------------------------------------------*/
1248/*--- Writing the graph file ---*/
1249/*------------------------------------------------------------*/
1250
1251static Char* make_filename(Char* dir, Char* suffix)
1252{
1253 Char* filename;
1254
1255 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1256 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1257 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1258
1259 return filename;
1260}
1261
1262// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1263static Char* clean_fnname(Char *d, Char* s)
1264{
1265 Char* dorig = d;
1266 while (*s) {
1267 if (' ' == *s) { *d = '%'; }
1268 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1269 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1270 else { *d = *s; };
1271 s++;
1272 d++;
1273 }
1274 *d = '\0';
1275 return dorig;
1276}
1277
1278static void file_err ( Char* file )
1279{
njn02bc4b82005-05-15 17:28:26 +00001280 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001281 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1282}
1283
1284/* Format, by example:
1285
1286 JOB "a.out -p"
1287 DATE "Fri Apr 17 11:43:45 1992"
1288 SAMPLE_UNIT "seconds"
1289 VALUE_UNIT "bytes"
1290 BEGIN_SAMPLE 0.00
1291 SYSTEM 24
1292 END_SAMPLE 0.00
1293 BEGIN_SAMPLE 1.00
1294 elim 180
1295 insert 24
1296 intersect 12
1297 disin 60
1298 main 12
1299 reduce 20
1300 SYSTEM 12
1301 END_SAMPLE 1.00
1302 MARK 1.50
1303 MARK 1.75
1304 MARK 1.80
1305 BEGIN_SAMPLE 2.00
1306 elim 192
1307 insert 24
1308 intersect 12
1309 disin 84
1310 main 12
1311 SYSTEM 24
1312 END_SAMPLE 2.00
1313 BEGIN_SAMPLE 2.82
1314 END_SAMPLE 2.82
1315 */
1316static void write_hp_file(void)
1317{
sewardj92645592005-07-23 09:18:34 +00001318 Int i, j;
1319 Int fd, res;
1320 SysRes sres;
1321 Char *hp_file, *ps_file, *aux_file;
1322 Char* cmdfmt;
1323 Char* cmdbuf;
1324 Int cmdlen;
nethercotec9f36922004-02-14 16:40:02 +00001325
1326 VGP_PUSHCC(VgpPrintHp);
1327
1328 // Open file
1329 hp_file = make_filename( base_dir, ".hp" );
1330 ps_file = make_filename( base_dir, ".ps" );
1331 aux_file = make_filename( base_dir, ".aux" );
sewardj92645592005-07-23 09:18:34 +00001332 sres = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1333 VKI_S_IRUSR|VKI_S_IWUSR);
1334 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001335 file_err( hp_file );
1336 VGP_POPCC(VgpPrintHp);
1337 return;
sewardj92645592005-07-23 09:18:34 +00001338 } else {
1339 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001340 }
1341
1342 // File header, including command line
1343 SPRINTF(buf, "JOB \"");
njnd111d102005-09-13 00:46:27 +00001344 for (i = 0; i < VG_(client_argc); i++) {
1345 if (VG_(client_argv)[i])
1346 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1347 }
nethercotec9f36922004-02-14 16:40:02 +00001348 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1349 "DATE \"\"\n"
1350 "SAMPLE_UNIT \"ms\"\n"
1351 "VALUE_UNIT \"bytes\"\n", ms_interval);
1352
1353 // Censi
1354 for (i = 0; i < curr_census; i++) {
1355 Census* census = & censi[i];
1356
1357 // Census start
1358 SPRINTF(buf, "MARK %d.0\n"
1359 "BEGIN_SAMPLE %d.0\n",
1360 census->ms_time, census->ms_time);
1361
1362 // Heap -----------------------------------------------------------
1363 if (clo_heap) {
1364 // Print all the significant XPts from that census
1365 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1366 // Grab the jth top-XPt
1367 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001368 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001369 VG_(sprintf)(buf2, "???");
1370 }
njnd01fef72005-03-25 23:35:48 +00001371 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001372 clean_fnname(buf3, buf2), xtree_snapshot->space);
1373 }
1374
1375 // Remaining heap block alloc points, combined
1376 if (census->others_space > 0)
1377 SPRINTF(buf, "other %d\n", census->others_space);
1378 }
1379
1380 // Heap admin -----------------------------------------------------
1381 if (clo_heap_admin > 0 && census->heap_admin_space)
1382 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1383
1384 // Stack(s) -------------------------------------------------------
1385 if (clo_stacks)
1386 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1387
1388 // Census end
1389 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1390 }
1391
1392 // Close file
njnca82cc02004-11-22 17:18:48 +00001393 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001394 VG_(close)(fd);
1395
1396 // Attempt to convert file using hp2ps
1397 cmdfmt = "%s/hp2ps -c -t1 %s";
1398 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1399 + VG_(strlen)(cmdfmt);
1400 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1401 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1402 res = VG_(system)(cmdbuf);
1403 VG_(free)(cmdbuf);
1404 if (res != 0) {
1405 VG_(message)(Vg_UserMsg,
1406 "Conversion to PostScript failed. Try converting manually.");
1407 } else {
1408 // remove the .hp and .aux file
1409 VG_(unlink)(hp_file);
1410 VG_(unlink)(aux_file);
1411 }
1412
1413 VG_(free)(hp_file);
1414 VG_(free)(ps_file);
1415 VG_(free)(aux_file);
1416
1417 VGP_POPCC(VgpPrintHp);
1418}
1419
1420/*------------------------------------------------------------*/
1421/*--- Writing the XPt text/HTML file ---*/
1422/*------------------------------------------------------------*/
1423
1424static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1425{
1426 int i, len, space;
1427
1428 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1429 len = VG_(strlen)(xbuf);
1430 space = field_width - len;
1431 if (space < 0) space = 0; /* Allow for v. small field_width */
1432 i = len;
1433
1434 /* Right justify in field */
1435 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1436 for (i = 0; i < space; i++) xbuf[i] = ' ';
1437}
1438
1439// Nb: uses a static buffer, each call trashes the last string returned.
1440static Char* make_perc(ULong spacetime, ULong total_spacetime)
1441{
1442 static Char mbuf[32];
1443
1444 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001445 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001446 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1447 return mbuf;
1448}
1449
njnd01fef72005-03-25 23:35:48 +00001450// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001451// bottom-to-top of XCon, and then printed in the reverse order.
1452static UInt pp_XCon(Int fd, XPt* xpt)
1453{
njnd01fef72005-03-25 23:35:48 +00001454 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001455 Int i = 0;
1456 Int n = 0;
1457 Bool is_HTML = ( XHTML == clo_format );
1458 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1459 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1460
njnca82cc02004-11-22 17:18:48 +00001461 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001462
1463 while (True) {
njnd01fef72005-03-25 23:35:48 +00001464 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001465 n++;
1466 if (alloc_xpt == xpt->parent) break;
1467 i++;
1468 xpt = xpt->parent;
1469 }
1470
1471 for (i = n-1; i >= 0; i--) {
1472 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001473 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001474 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1475 }
1476
1477 return n;
1478}
1479
1480// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001481// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001482// sufficient, because function pointers mean that you can call more than
1483// one other function from a single code location. So instead we use the
1484// address of the xpt struct itself, which is guaranteed to be unique.
1485
1486static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1487 ULong total_spacetime)
1488{
1489 UInt i;
1490 XPt *xpt, *child;
1491 UInt L = 0;
1492 UInt c1 = 1;
1493 UInt c2 = 0;
1494 ULong sum = 0;
1495 UInt n;
njnd01fef72005-03-25 23:35:48 +00001496 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001497 Bool is_HTML = ( XHTML == clo_format );
1498 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1499 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1500 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1501 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1502 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1503 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1504 Char* end_hr = ( is_HTML ? "<hr>" :
1505 "=================================" );
1506 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1507
nethercote43a15ce2004-08-30 19:15:12 +00001508 if (total_spacetime == 0) {
1509 SPRINTF(buf, "(No heap memory allocated)\n");
1510 return;
1511 }
1512
1513
nethercotec9f36922004-02-14 16:40:02 +00001514 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1515
1516 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001517 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001518 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001519
nethercote43a15ce2004-08-30 19:15:12 +00001520 // Check that the sum of all children .exact_ST_dbld fields equals
1521 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001522 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001523 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001524 } else {
1525 sum = 0;
1526 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001527 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001528 }
njnca82cc02004-11-22 17:18:48 +00001529 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001530 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001531 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001532 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001533// tl_assert(sum <= xpt->exact_ST_dbld);
1534// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001535// if (sum != xpt->exact_ST_dbld) {
njn68e46592005-08-26 19:42:27 +00001536// VG_(printf)("%lld, %lld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001537// }
1538 }
1539
1540 if (xpt == alloc_xpt) {
1541 SPRINTF(buf, "Heap allocation functions accounted for "
1542 "%s of measured spacetime%s\n",
1543 make_perc(heap_spacetime, total_spacetime), maybe_br);
1544 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001545 // Remember: exact_ST_dbld is space.time *doubled*
1546 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001547 if (is_HTML) {
1548 SPRINTF(buf, "<a name=\"b%x\"></a>"
1549 "Context accounted for "
1550 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1551 xpt, xpt, perc);
1552 } else {
1553 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1554 perc);
1555 }
1556 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001557 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001558 }
1559
nethercote43a15ce2004-08-30 19:15:12 +00001560 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001561 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001562 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001563
1564 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1565 for (i = 0; i < xpt->n_children; i++) {
1566 child = xpt->children[i];
1567
1568 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001569 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001570 UInt n_insig = xpt->n_children - i;
1571 Char* s = ( n_insig == 1 ? "" : "s" );
1572 Char* and = ( 0 == i ? "" : "and " );
1573 Char* other = ( 0 == i ? "" : "other " );
1574 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1575 maybe_li, and, n_insig, other, s, maybe_fli);
1576 break;
1577 }
1578
nethercote43a15ce2004-08-30 19:15:12 +00001579 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001580 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1581 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001582 if (is_HTML) {
1583 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1584
1585 if (child->n_children > 0) {
1586 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1587 } else {
1588 SPRINTF(buf, "%s", perc);
1589 }
njnd01fef72005-03-25 23:35:48 +00001590 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001591 } else {
njnd01fef72005-03-25 23:35:48 +00001592 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001593 }
1594
1595 if (child->n_children > 0) {
1596 enqueue(q, (void*)child);
1597 c2++;
1598 }
1599 }
1600 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1601 c1--;
1602
1603 // Putting markers between levels of the structure:
1604 // c1 tracks how many to go on this level, c2 tracks how many we've
1605 // queued up for the next level while finishing off this level.
1606 // When c1 gets to zero, we've changed levels, so print a marker,
1607 // move c2 into c1, and zero c2.
1608 if (0 == c1) {
1609 L++;
1610 c1 = c2;
1611 c2 = 0;
1612 if (! is_empty_queue(q) ) { // avoid empty one at end
1613 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1614 }
1615 } else {
1616 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1617 }
1618 }
1619 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1620 "%s value for more.\n", end_hr, depth);
1621}
1622
1623static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1624 ULong total_spacetime)
1625{
1626 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001627
nethercotec9f36922004-02-14 16:40:02 +00001628 enqueue(q, xpt);
1629 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1630 destruct_queue(q);
1631}
1632
1633static void
1634write_text_file(ULong total_ST, ULong heap_ST)
1635{
sewardj92645592005-07-23 09:18:34 +00001636 SysRes sres;
1637 Int fd, i;
1638 Char* text_file;
1639 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
nethercotec9f36922004-02-14 16:40:02 +00001640
1641 VGP_PUSHCC(VgpPrintXPts);
1642
1643 // Open file
1644 text_file = make_filename( base_dir,
1645 ( XText == clo_format ? ".txt" : ".html" ) );
1646
sewardj92645592005-07-23 09:18:34 +00001647 sres = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
nethercotec9f36922004-02-14 16:40:02 +00001648 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00001649 if (sres.isError) {
nethercotec9f36922004-02-14 16:40:02 +00001650 file_err( text_file );
1651 VGP_POPCC(VgpPrintXPts);
1652 return;
sewardj92645592005-07-23 09:18:34 +00001653 } else {
1654 fd = sres.val;
nethercotec9f36922004-02-14 16:40:02 +00001655 }
1656
1657 // Header
1658 if (XHTML == clo_format) {
1659 SPRINTF(buf, "<html>\n"
1660 "<head>\n"
1661 "<title>%s</title>\n"
1662 "</head>\n"
1663 "<body>\n",
1664 text_file);
1665 }
1666
1667 // Command line
1668 SPRINTF(buf, "Command: ");
njnd111d102005-09-13 00:46:27 +00001669 for (i = 0; i < VG_(client_argc); i++) {
1670 if (VG_(client_argv)[i])
1671 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1672 }
nethercotec9f36922004-02-14 16:40:02 +00001673 SPRINTF(buf, "\n%s\n", maybe_p);
1674
1675 if (clo_heap)
1676 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1677
njnca82cc02004-11-22 17:18:48 +00001678 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001679 VG_(close)(fd);
1680
1681 VGP_POPCC(VgpPrintXPts);
1682}
1683
1684/*------------------------------------------------------------*/
1685/*--- Finalisation ---*/
1686/*------------------------------------------------------------*/
1687
1688static void
1689print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1690 ULong stack_ST)
1691{
njn99cb9e32005-09-25 17:59:16 +00001692 VG_(message)(Vg_UserMsg, "Total spacetime: %,llu ms.B", total_ST);
nethercotec9f36922004-02-14 16:40:02 +00001693
1694 // Heap --------------------------------------------------------------
1695 if (clo_heap)
1696 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001697 ( 0 == total_ST ? (Char*)"(n/a)"
1698 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001699
1700 // Heap admin --------------------------------------------------------
1701 if (clo_heap_admin)
1702 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001703 ( 0 == total_ST ? (Char*)"(n/a)"
1704 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001705
njnca82cc02004-11-22 17:18:48 +00001706 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001707
1708 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001709 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001710 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001711 ( 0 == stack_ST ? (Char*)"0%"
1712 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001713 }
nethercotec9f36922004-02-14 16:40:02 +00001714
1715 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001716 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001717 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1718 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1719 n_zero_allocs * 100 / n_allocs );
1720 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1721 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1722 n_xpts*sizeof(XPt));
1723 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1724 n_bot_xpts * 100 / n_xpts);
1725 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1726 alloc_xpt->n_children * 100 / n_xpts);
1727 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1728 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1729 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1730 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1731 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1732 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1733 }
1734}
1735
njn51d827b2005-05-09 01:02:08 +00001736static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001737{
1738 ULong total_ST = 0;
1739 ULong heap_ST = 0;
1740 ULong heap_admin_ST = 0;
1741 ULong stack_ST = 0;
1742
1743 // Do a final (empty) sample to show program's end
1744 hp_census();
1745
1746 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001747 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001748 total_ST = heap_ST + heap_admin_ST + stack_ST;
1749 write_hp_file ( );
1750 write_text_file( total_ST, heap_ST );
1751 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1752}
1753
njn51d827b2005-05-09 01:02:08 +00001754/*------------------------------------------------------------*/
1755/*--- Initialisation ---*/
1756/*------------------------------------------------------------*/
1757
1758static void ms_post_clo_init(void)
1759{
1760 ms_interval = 1;
1761
1762 // Do an initial sample for t = 0
1763 hp_census();
1764}
1765
1766static void ms_pre_clo_init()
1767{
1768 VG_(details_name) ("Massif");
1769 VG_(details_version) (NULL);
1770 VG_(details_description) ("a space profiler");
1771 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1772 VG_(details_bug_reports_to) (VG_BUGS_TO);
1773
1774 // Basic functions
1775 VG_(basic_tool_funcs) (ms_post_clo_init,
1776 ms_instrument,
1777 ms_fini);
1778
1779 // Needs
1780 VG_(needs_libc_freeres)();
1781 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1782 ms_print_usage,
1783 ms_print_debug_usage);
1784 VG_(needs_client_requests) (ms_handle_client_request);
njnfc51f8d2005-06-21 03:20:17 +00001785 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00001786 ms___builtin_new,
1787 ms___builtin_vec_new,
1788 ms_memalign,
1789 ms_calloc,
1790 ms_free,
1791 ms___builtin_delete,
1792 ms___builtin_vec_delete,
1793 ms_realloc,
1794 0 );
1795
1796 // Events to track
1797 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1798 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1799
1800 // Profiling events
1801 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1802 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1803 VG_(register_profile_event)(VgpCensus, "census");
1804 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1805 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1806 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1807 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1808 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1809 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1810 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1811
1812 // HP_Chunks
njnf69f9452005-07-03 17:53:11 +00001813 malloc_list = VG_(HT_construct)( 80021 ); // prime, big
njn51d827b2005-05-09 01:02:08 +00001814
1815 // Dummy node at top of the context structure.
1816 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1817
njn57ca7ab2005-06-21 23:44:58 +00001818 tl_assert( VG_(getcwd)(base_dir, VKI_PATH_MAX) );
njn51d827b2005-05-09 01:02:08 +00001819}
1820
1821VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001822
1823/*--------------------------------------------------------------------*/
njnf1c5def2005-08-11 02:17:07 +00001824/*--- end ---*/
nethercotec9f36922004-02-14 16:40:02 +00001825/*--------------------------------------------------------------------*/
1826