blob: aebc27d96245ffeab62a7f17a40ca9f9d23512b2 [file] [log] [blame]
nethercotec9f36922004-02-14 16:40:02 +00001
2/*--------------------------------------------------------------------*/
nethercote996901a2004-08-03 13:29:09 +00003/*--- Massif: a heap profiling tool. ms_main.c ---*/
nethercotec9f36922004-02-14 16:40:02 +00004/*--------------------------------------------------------------------*/
5
6/*
nethercote996901a2004-08-03 13:29:09 +00007 This file is part of Massif, a Valgrind tool for profiling memory
nethercotec9f36922004-02-14 16:40:02 +00008 usage of programs.
9
njn53612422005-03-12 16:22:54 +000010 Copyright (C) 2003-2005 Nicholas Nethercote
njn2bc10122005-05-08 02:10:27 +000011 njn@valgrind.org
nethercotec9f36922004-02-14 16:40:02 +000012
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation; either version 2 of the
16 License, or (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26 02111-1307, USA.
27
28 The GNU General Public License is contained in the file COPYING.
29*/
30
31// Memory profiler. Produces a graph, gives lots of information about
32// allocation contexts, in terms of space.time values (ie. area under the
33// graph). Allocation context information is hierarchical, and can thus
34// be inspected step-wise to an appropriate depth. See comments on data
35// structures below for more info on how things work.
36
nethercote46063202004-09-02 08:51:43 +000037#include "tool.h"
njnea27e462005-05-31 02:38:09 +000038#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +000039#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +000040#include "pub_tool_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +000041#include "pub_tool_libcassert.h"
njn36a20fa2005-06-03 03:08:39 +000042#include "pub_tool_libcprint.h"
njn717cde52005-05-10 02:47:21 +000043#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000044#include "pub_tool_options.h"
njn31513b42005-06-01 03:09:59 +000045#include "pub_tool_profile.h"
njn717cde52005-05-10 02:47:21 +000046#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000047#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000048#include "pub_tool_tooliface.h"
nethercotec9f36922004-02-14 16:40:02 +000049
50#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
51
52/*------------------------------------------------------------*/
53/*--- Overview of operation ---*/
54/*------------------------------------------------------------*/
55
56// Heap blocks are tracked, and the amount of space allocated by various
57// contexts (ie. lines of code, more or less) is also tracked.
58// Periodically, a census is taken, and the amount of space used, at that
59// point, by the most significant (highly allocating) contexts is recorded.
60// Census start off frequently, but are scaled back as the program goes on,
61// so that there are always a good number of them. At the end, overall
62// spacetimes for different contexts (of differing levels of precision) is
63// calculated, the graph is printed, and the text giving spacetimes for the
64// increasingly precise contexts is given.
65//
66// Measures the following:
67// - heap blocks
68// - heap admin bytes
69// - stack(s)
70// - code (code segments loaded at startup, and loaded with mmap)
71// - data (data segments loaded at startup, and loaded/created with mmap,
72// and brk()d segments)
73
74/*------------------------------------------------------------*/
75/*--- Main types ---*/
76/*------------------------------------------------------------*/
77
78// An XPt represents an "execution point", ie. a code address. Each XPt is
79// part of a tree of XPts (an "execution tree", or "XTree"). Each
80// top-to-bottom path through an XTree gives an execution context ("XCon"),
81// and is equivalent to a traditional Valgrind ExeContext.
82//
83// The XPt at the top of an XTree (but below "alloc_xpt") is called a
84// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
85// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
86// bottom-XPTs in that XTree.
87//
88// All XCons have the same top-XPt, "alloc_xpt", which represents all
89// allocation functions like malloc(). It's a bit of a fake XPt, though,
90// and is only used because it makes some of the code simpler.
91//
92// XTrees are bi-directional.
93//
94// > parent < Example: if child1() calls parent() and child2()
95// / | \ also calls parent(), and parent() calls malloc(),
96// | / \ | the XTree will look like this.
97// | v v |
98// child1 child2
99
100typedef struct _XPt XPt;
101
102struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000103 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000104
105 // Bottom-XPts: space for the precise context.
106 // Other XPts: space of all the descendent bottom-XPts.
107 // Nb: this value goes up and down as the program executes.
108 UInt curr_space;
109
110 // An approximate space.time calculation used along the way for selecting
111 // which contexts to include at each census point.
112 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000113 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000114
nethercote43a15ce2004-08-30 19:15:12 +0000115 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000116 // used in the results.
117 // Note that it is *doubled*, to avoid rounding errors.
118 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000119 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000120
121 // n_children and max_children are integers; a very big program might
122 // have more than 65536 allocation points (Konqueror startup has 1800).
123 XPt* parent; // pointer to parent XPt
124 UInt n_children; // number of children
125 UInt max_children; // capacity of children array
126 XPt** children; // pointers to children XPts
127};
128
129// Each census snapshots the most significant XTrees, each XTree having a
130// top-XPt as its root. The 'curr_space' element for each XPt is recorded
131// in the snapshot. The snapshot contains all the XTree's XPts, not in a
132// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000133// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000134//
135// Graph resolution, x-axis: no point having more than about 200 census
136// x-points; you can't see them on the graph. Therefore:
137//
138// - do a census every 1 ms for first 200 --> 200, all (200 ms)
139// - halve (drop half of them) --> 100, every 2nd (200 ms)
140// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
141// - halve --> 100, every 4th (400 ms)
142// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
143// - etc.
144//
145// This isn't exactly right, because we actually drop (N/2)-1 when halving,
146// but it shows the basic idea.
147
148#define MAX_N_CENSI 200 // Keep it even, for simplicity
149
150// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
151// bands, rest get lumped into OTHERS. I only print the top N
152// (cumulative-so-far space-time) at each point. N should be a bit bigger
153// than 19 in case the cumulative space-time doesn't fit with the eventual
154// space-time computed by hp2ps (but it should be close if the samples are
155// evenly spread, since hp2ps does an approximate per-band space-time
156// calculation that just sums the totals; ie. it assumes all samples are
157// the same distance apart).
158
159#define MAX_SNAPSHOTS 32
160
161typedef
162 struct {
163 XPt* xpt;
164 UInt space;
165 }
166 XPtSnapshot;
167
168// An XTree snapshot is stored as an array of of XPt snapshots.
169typedef XPtSnapshot* XTreeSnapshot;
170
171typedef
172 struct {
173 Int ms_time; // Int: must allow -1
174 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
175 UInt others_space;
176 UInt heap_admin_space;
177 UInt stacks_space;
178 }
179 Census;
180
181// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
182// which is a foothold into the XCon at which it was allocated. From
183// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
184// decremented (at deallocation).
185//
186// Nb: first two fields must match core's VgHashNode.
187typedef
188 struct _HP_Chunk {
189 struct _HP_Chunk* next;
190 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000191 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000192 XPt* where; // Where allocated; bottom-XPt
193 }
194 HP_Chunk;
195
196/*------------------------------------------------------------*/
197/*--- Profiling events ---*/
198/*------------------------------------------------------------*/
199
200typedef
201 enum {
202 VgpGetXPt = VgpFini+1,
203 VgpGetXPtSearch,
204 VgpCensus,
205 VgpCensusHeap,
206 VgpCensusSnapshot,
207 VgpCensusTreeSize,
208 VgpUpdateXCon,
209 VgpCalcSpacetime2,
210 VgpPrintHp,
211 VgpPrintXPts,
212 }
njn4be0a692004-11-22 18:10:36 +0000213 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000214
215/*------------------------------------------------------------*/
216/*--- Statistics ---*/
217/*------------------------------------------------------------*/
218
219// Konqueror startup, to give an idea of the numbers involved with a biggish
220// program, with default depth:
221//
222// depth=3 depth=40
223// - 310,000 allocations
224// - 300,000 frees
225// - 15,000 XPts 800,000 XPts
226// - 1,800 top-XPts
227
228static UInt n_xpts = 0;
229static UInt n_bot_xpts = 0;
230static UInt n_allocs = 0;
231static UInt n_zero_allocs = 0;
232static UInt n_frees = 0;
233static UInt n_children_reallocs = 0;
234static UInt n_snapshot_frees = 0;
235
236static UInt n_halvings = 0;
237static UInt n_real_censi = 0;
238static UInt n_fake_censi = 0;
239static UInt n_attempted_censi = 0;
240
241/*------------------------------------------------------------*/
242/*--- Globals ---*/
243/*------------------------------------------------------------*/
244
245#define FILENAME_LEN 256
246
247#define SPRINTF(zz_buf, fmt, args...) \
248 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
249 VG_(write)(fd, (void*)zz_buf, len); \
250 } while (0)
251
252#define BUF_LEN 1024 // general purpose
253static Char buf [BUF_LEN];
254static Char buf2[BUF_LEN];
255static Char buf3[BUF_LEN];
256
nethercote8b5f40c2004-11-02 13:29:50 +0000257static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000258
259static VgHashTable malloc_list = NULL; // HP_Chunks
260
261static UInt n_heap_blocks = 0;
262
njn51d827b2005-05-09 01:02:08 +0000263// Current directory at startup.
264static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000265
266#define MAX_ALLOC_FNS 32 // includes the builtin ones
267
nethercotec7469182004-05-11 09:21:08 +0000268// First few filled in, rest should be zeroed. Zero-terminated vector.
269static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000270static Char* alloc_fns[MAX_ALLOC_FNS] = {
271 "malloc",
272 "operator new(unsigned)",
273 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000274 "operator new(unsigned, std::nothrow_t const&)",
275 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000276 "__builtin_new",
277 "__builtin_vec_new",
278 "calloc",
279 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000280 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000281};
282
283
284/*------------------------------------------------------------*/
285/*--- Command line args ---*/
286/*------------------------------------------------------------*/
287
288#define MAX_DEPTH 50
289
290typedef
291 enum {
292 XText, XHTML,
293 }
294 XFormat;
295
296static Bool clo_heap = True;
297static UInt clo_heap_admin = 8;
298static Bool clo_stacks = True;
299static Bool clo_depth = 3;
300static XFormat clo_format = XText;
301
njn51d827b2005-05-09 01:02:08 +0000302static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000303{
njn45270a22005-03-27 01:00:11 +0000304 VG_BOOL_CLO(arg, "--heap", clo_heap)
305 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000306
njn45270a22005-03-27 01:00:11 +0000307 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
308 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000309
310 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
311 alloc_fns[n_alloc_fns] = & arg[11];
312 n_alloc_fns++;
313 if (n_alloc_fns >= MAX_ALLOC_FNS) {
314 VG_(printf)("Too many alloc functions specified, sorry");
315 VG_(bad_option)(arg);
316 }
317 }
318
319 else if (VG_CLO_STREQ(arg, "--format=text"))
320 clo_format = XText;
321 else if (VG_CLO_STREQ(arg, "--format=html"))
322 clo_format = XHTML;
323
324 else
325 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000326
nethercotec9f36922004-02-14 16:40:02 +0000327 return True;
328}
329
njn51d827b2005-05-09 01:02:08 +0000330static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000331{
332 VG_(printf)(
333" --heap=no|yes profile heap blocks [yes]\n"
334" --heap-admin=<number> average admin bytes per heap block [8]\n"
335" --stacks=no|yes profile stack(s) [yes]\n"
336" --depth=<number> depth of contexts [3]\n"
337" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
338" --format=text|html format of textual output [text]\n"
339 );
340 VG_(replacement_malloc_print_usage)();
341}
342
njn51d827b2005-05-09 01:02:08 +0000343static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000344{
345 VG_(replacement_malloc_print_debug_usage)();
346}
347
348/*------------------------------------------------------------*/
349/*--- Execution contexts ---*/
350/*------------------------------------------------------------*/
351
352// Fake XPt representing all allocation functions like malloc(). Acts as
353// parent node to all top-XPts.
354static XPt* alloc_xpt;
355
356// Cheap allocation for blocks that never need to be freed. Saves about 10%
357// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000358static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000359{
360 static Addr hp = 0; // current heap pointer
361 static Addr hp_lim = 0; // maximum usable byte in current block
362
363 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
364
365 if (hp + n_bytes > hp_lim) {
366 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
367 hp_lim = hp + SUPERBLOCK_SIZE - 1;
368 }
369
370 hp += n_bytes;
371
372 return (void*)(hp - n_bytes);
373}
374
375
376
njnd01fef72005-03-25 23:35:48 +0000377static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000378{
379 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000380 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000381
nethercote43a15ce2004-08-30 19:15:12 +0000382 xpt->curr_space = 0;
383 xpt->approx_ST = 0;
384 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000385
386 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000387
388 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000389 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000390
391 xpt->n_children = 0;
392
393 // If a bottom-XPt, don't allocate space for children. This can be 50%
394 // or more, although it tends to drop as --depth increases (eg. 10% for
395 // konqueror with --depth=20).
396 if ( is_bottom ) {
397 xpt->max_children = 0;
398 xpt->children = NULL;
399 n_bot_xpts++;
400 } else {
401 xpt->max_children = 4;
402 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
403 }
404
405 // Update statistics
406 n_xpts++;
407
408 return xpt;
409}
410
njnd01fef72005-03-25 23:35:48 +0000411static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000412{
413 Int i;
414
njnd01fef72005-03-25 23:35:48 +0000415 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000416 for (i = 0; i < n_alloc_fns; i++) {
417 if (VG_STREQ(buf, alloc_fns[i]))
418 return True;
419 }
420 }
421 return False;
422}
423
424// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
425// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
426// to ensure this in certain cases. See comments below.
427static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
428{
njnd01fef72005-03-25 23:35:48 +0000429 // Static to minimise stack size. +1 for added ~0 IP
430 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000431
432 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000433 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000434 UInt overestimate;
435 Bool reached_bottom;
436
437 VGP_PUSHCC(VgpGetXPt);
438
439 // Want at least clo_depth non-alloc-fn entries in the snapshot.
440 // However, because we have 1 or more (an unknown number, at this point)
441 // alloc-fns ignored, we overestimate the size needed for the stack
442 // snapshot. Then, if necessary, we repeatedly increase the size until
443 // it is enough.
444 overestimate = 2;
445 while (True) {
njnd01fef72005-03-25 23:35:48 +0000446 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000447
njnd01fef72005-03-25 23:35:48 +0000448 // Now we add a dummy "unknown" IP at the end. This is only used if we
449 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000450 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
451 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000452 // the parent's approx_ST wouldn't be equal [or almost equal] to the
453 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000454 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000455
njnd01fef72005-03-25 23:35:48 +0000456 // Skip over alloc functions in ips[].
457 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000458
459 // Must be at least one alloc function, unless client used
460 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000461 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000462
463 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000464 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000465 overestimate += 2;
466 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000467 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000468 } else {
469 break;
470 }
471 }
472 A = L;
njnd01fef72005-03-25 23:35:48 +0000473 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000474 reached_bottom = False;
475
njnd01fef72005-03-25 23:35:48 +0000476 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000477
478 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000479 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000480 while (True) {
njnd01fef72005-03-25 23:35:48 +0000481 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000482 // XXX: linear search, ugh -- about 10% of time for konqueror startup
483 // XXX: tried cacheing last result, only hit about 4% for konqueror
484 // Nb: this search hits about 98% of the time for konqueror
485 VGP_PUSHCC(VgpGetXPtSearch);
486
487 // If we've searched/added deep enough, or run out of EIPs, this is
488 // the bottom XPt.
489 if (L - A + 1 == clo_depth || L == B)
490 reached_bottom = True;
491
492 nC = 0;
493 while (True) {
494 if (nC == xpt->n_children) {
495 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000496 tl_assert(xpt->max_children != 0);
497 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000498 // Expand 'children' if necessary
499 if (xpt->n_children == xpt->max_children) {
500 xpt->max_children *= 2;
501 xpt->children = VG_(realloc)( xpt->children,
502 xpt->max_children * sizeof(XPt*) );
503 n_children_reallocs++;
504 }
njnd01fef72005-03-25 23:35:48 +0000505 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000506 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000507 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000508 break;
509 }
njnd01fef72005-03-25 23:35:48 +0000510 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000511 nC++; // keep looking
512 }
513 VGP_POPCC(VgpGetXPtSearch);
514
515 // Return found/built bottom-XPt.
516 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000517 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000518 VGP_POPCC(VgpGetXPt);
519 return xpt->children[nC];
520 }
521
522 // Descend to next level in XTree, the newly found/built non-bottom-XPt
523 xpt = xpt->children[nC];
524 L++;
525 }
526}
527
528// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
529static void update_XCon(XPt* xpt, Int space_delta)
530{
531 VGP_PUSHCC(VgpUpdateXCon);
532
njnca82cc02004-11-22 17:18:48 +0000533 tl_assert(True == clo_heap);
534 tl_assert(0 != space_delta);
535 tl_assert(NULL != xpt);
536 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000537
538 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000539 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000540 xpt->curr_space += space_delta;
541 xpt = xpt->parent;
542 }
njnca82cc02004-11-22 17:18:48 +0000543 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000544 alloc_xpt->curr_space += space_delta;
545
546 VGP_POPCC(VgpUpdateXCon);
547}
548
549// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000550static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000551{
552 XPt* xpt1 = *(XPt**)n1;
553 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000554 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000555}
556
nethercote43a15ce2004-08-30 19:15:12 +0000557static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000558{
559 XPt* xpt1 = *(XPt**)n1;
560 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000561 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000562}
563
564
565/*------------------------------------------------------------*/
566/*--- A generic Queue ---*/
567/*------------------------------------------------------------*/
568
569typedef
570 struct {
571 UInt head; // Index of first entry
572 UInt tail; // Index of final+1 entry, ie. next free slot
573 UInt max_elems;
574 void** elems;
575 }
576 Queue;
577
578static Queue* construct_queue(UInt size)
579{
580 UInt i;
581 Queue* q = VG_(malloc)(sizeof(Queue));
582 q->head = 0;
583 q->tail = 0;
584 q->max_elems = size;
585 q->elems = VG_(malloc)(size * sizeof(void*));
586 for (i = 0; i < size; i++)
587 q->elems[i] = NULL;
588
589 return q;
590}
591
592static void destruct_queue(Queue* q)
593{
594 VG_(free)(q->elems);
595 VG_(free)(q);
596}
597
598static void shuffle(Queue* dest_q, void** old_elems)
599{
600 UInt i, j;
601 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
602 dest_q->elems[i] = old_elems[j];
603 dest_q->head = 0;
604 dest_q->tail = i;
605 for ( ; i < dest_q->max_elems; i++)
606 dest_q->elems[i] = NULL; // paranoia
607}
608
609// Shuffles elements down. If not enough slots free, increase size. (We
610// don't wait until we've completely run out of space, because there could
611// be lots of shuffling just before that point which would be slow.)
612static void adjust(Queue* q)
613{
614 void** old_elems;
615
njnca82cc02004-11-22 17:18:48 +0000616 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000617 if (q->head < 10) {
618 old_elems = q->elems;
619 q->max_elems *= 2;
620 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
621 shuffle(q, old_elems);
622 VG_(free)(old_elems);
623 } else {
624 shuffle(q, q->elems);
625 }
626}
627
628static void enqueue(Queue* q, void* elem)
629{
630 if (q->tail == q->max_elems)
631 adjust(q);
632 q->elems[q->tail++] = elem;
633}
634
635static Bool is_empty_queue(Queue* q)
636{
637 return (q->head == q->tail);
638}
639
640static void* dequeue(Queue* q)
641{
642 if (is_empty_queue(q))
643 return NULL; // Queue empty
644 else
645 return q->elems[q->head++];
646}
647
648/*------------------------------------------------------------*/
649/*--- malloc() et al replacement wrappers ---*/
650/*------------------------------------------------------------*/
651
652static __inline__
653void add_HP_Chunk(HP_Chunk* hc)
654{
655 n_heap_blocks++;
656 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
657}
658
659static __inline__
660HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
661{
nethercote3d6b6112004-11-04 16:39:43 +0000662 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000663 (VgHashNode***)prev_chunks_next_ptr );
664}
665
666static __inline__
667void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
668{
njnca82cc02004-11-22 17:18:48 +0000669 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000670 n_heap_blocks--;
671 *prev_chunks_next_ptr = hc->next;
672}
673
674// Forward declaration
675static void hp_census(void);
676
nethercote159dfef2004-09-13 13:27:30 +0000677static
njn57735902004-11-25 18:04:54 +0000678void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
679 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000680{
681 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000682 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000683 if (size < 0) return NULL;
684
685 VGP_PUSHCC(VgpCliMalloc);
686
687 // Update statistics
688 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000689 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000690
nethercote57e36b32004-07-10 14:56:28 +0000691 // Allocate and zero if necessary
692 if (!p) {
693 p = VG_(cli_malloc)( align, size );
694 if (!p) {
695 VGP_POPCC(VgpCliMalloc);
696 return NULL;
697 }
698 if (is_zeroed) VG_(memset)(p, 0, size);
699 }
700
701 // Make new HP_Chunk node, add to malloclist
702 hc = VG_(malloc)(sizeof(HP_Chunk));
703 hc->size = size;
704 hc->data = (Addr)p;
705 hc->where = NULL; // paranoia
706 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000707 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000708 if (0 != size)
709 update_XCon(hc->where, size);
710 }
711 add_HP_Chunk( hc );
712
713 // do a census!
714 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000715
716 VGP_POPCC(VgpCliMalloc);
717 return p;
718}
719
720static __inline__
721void die_block ( void* p, Bool custom_free )
722{
nethercote57e36b32004-07-10 14:56:28 +0000723 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000724
725 VGP_PUSHCC(VgpCliMalloc);
726
727 // Update statistics
728 n_frees++;
729
nethercote57e36b32004-07-10 14:56:28 +0000730 // Remove HP_Chunk from malloclist
731 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000732 if (hc == NULL)
733 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000734 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000735 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000736
737 if (clo_heap && hc->size != 0)
738 update_XCon(hc->where, -hc->size);
739
nethercote57e36b32004-07-10 14:56:28 +0000740 VG_(free)( hc );
741
742 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000743 if (!custom_free)
744 VG_(cli_free)( p );
745
nethercote57e36b32004-07-10 14:56:28 +0000746 // do a census!
747 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000748
nethercotec9f36922004-02-14 16:40:02 +0000749 VGP_POPCC(VgpCliMalloc);
750}
751
752
njn51d827b2005-05-09 01:02:08 +0000753static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000754{
njn57735902004-11-25 18:04:54 +0000755 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000756}
757
njn51d827b2005-05-09 01:02:08 +0000758static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000759{
njn57735902004-11-25 18:04:54 +0000760 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000761}
762
njn51d827b2005-05-09 01:02:08 +0000763static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000764{
njn57735902004-11-25 18:04:54 +0000765 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000766}
767
njn51d827b2005-05-09 01:02:08 +0000768static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000769{
njn57735902004-11-25 18:04:54 +0000770 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000771}
772
njn51d827b2005-05-09 01:02:08 +0000773static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000774{
njn57735902004-11-25 18:04:54 +0000775 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000776}
777
njn51d827b2005-05-09 01:02:08 +0000778static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000779{
780 die_block( p, /*custom_free*/False );
781}
782
njn51d827b2005-05-09 01:02:08 +0000783static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000784{
785 die_block( p, /*custom_free*/False);
786}
787
njn51d827b2005-05-09 01:02:08 +0000788static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000789{
790 die_block( p, /*custom_free*/False );
791}
792
njn51d827b2005-05-09 01:02:08 +0000793static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000794{
795 HP_Chunk* hc;
796 HP_Chunk** remove_handle;
797 Int i;
798 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000799 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000800 XPt *old_where, *new_where;
801
802 VGP_PUSHCC(VgpCliMalloc);
803
804 // First try and find the block.
805 hc = get_HP_Chunk ( p_old, &remove_handle );
806 if (hc == NULL) {
807 VGP_POPCC(VgpCliMalloc);
808 return NULL; // must have been a bogus free()
809 }
810
njnca82cc02004-11-22 17:18:48 +0000811 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000812 old_size = hc->size;
813
814 if (new_size <= old_size) {
815 // new size is smaller or same; block not moved
816 p_new = p_old;
817
818 } else {
819 // new size is bigger; make new block, copy shared contents, free old
820 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
821
822 for (i = 0; i < old_size; i++)
823 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
824
825 VG_(cli_free)(p_old);
826 }
827
828 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000829 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000830
831 // Update HP_Chunk
832 hc->data = (Addr)p_new;
833 hc->size = new_size;
834 hc->where = new_where;
835
836 // Update XPt curr_space fields
837 if (clo_heap) {
838 if (0 != old_size) update_XCon(old_where, -old_size);
839 if (0 != new_size) update_XCon(new_where, new_size);
840 }
841
842 // If block has moved, have to remove and reinsert in the malloclist
843 // (since the updated 'data' field is the hash lookup key).
844 if (p_new != p_old) {
845 remove_HP_Chunk(hc, remove_handle);
846 add_HP_Chunk(hc);
847 }
848
849 VGP_POPCC(VgpCliMalloc);
850 return p_new;
851}
852
853
854/*------------------------------------------------------------*/
855/*--- Taking a census ---*/
856/*------------------------------------------------------------*/
857
858static Census censi[MAX_N_CENSI];
859static UInt curr_census = 0;
860
861// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000862static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000863{
thughes4ad52d02004-06-27 17:37:21 +0000864 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000865 return False;
866}
867
868static UInt get_xtree_size(XPt* xpt, UInt ix)
869{
870 UInt i;
871
nethercote43a15ce2004-08-30 19:15:12 +0000872 // If no memory allocated at all, nothing interesting to record.
873 if (alloc_xpt->curr_space == 0) return 0;
874
875 // Ignore sub-XTrees that account for a miniscule fraction of current
876 // allocated space.
877 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000878 ix++;
879
880 // Count all (non-zero) descendent XPts
881 for (i = 0; i < xpt->n_children; i++)
882 ix = get_xtree_size(xpt->children[i], ix);
883 }
884 return ix;
885}
886
887static
888UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
889{
890 UInt i;
891
nethercote43a15ce2004-08-30 19:15:12 +0000892 // Structure of this function mirrors that of get_xtree_size().
893
894 if (alloc_xpt->curr_space == 0) return 0;
895
896 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000897 xtree_snapshot[ix].xpt = xpt;
898 xtree_snapshot[ix].space = xpt->curr_space;
899 ix++;
900
nethercotec9f36922004-02-14 16:40:02 +0000901 for (i = 0; i < xpt->n_children; i++)
902 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
903 }
904 return ix;
905}
906
907static UInt ms_interval;
908static UInt do_every_nth_census = 30;
909
910// Weed out half the censi; we choose those that represent the smallest
911// time-spans, because that loses the least information.
912//
913// Algorithm for N censi: We find the census representing the smallest
914// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
915// (It's (N/2)-1 because we never remove the first and last censi.)
916// We have to do this one census at a time, rather than finding the (N/2)-1
917// smallest censi in one hit, because when a census is removed, it's
918// neighbours immediately cover greater timespans. So it's N^2, but N only
919// equals 200, and this is only done every 100 censi, which is not too often.
920static void halve_censi(void)
921{
922 Int i, jp, j, jn, k;
923 Census* min_census;
924
925 n_halvings++;
926 if (VG_(clo_verbosity) > 1)
927 VG_(message)(Vg_UserMsg, "Halving censi...");
928
929 // Sets j to the index of the first not-yet-removed census at or after i
930 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000931 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000932
933 for (i = 2; i < MAX_N_CENSI; i += 2) {
934 // Find the censi representing the smallest timespan. The timespan
935 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
936 // censi A and B. We don't consider the first and last censi for
937 // removal.
938 Int min_span = 0x7fffffff;
939 Int min_j = 0;
940
941 // Initial triple: (prev, curr, next) == (jp, j, jn)
942 jp = 0;
943 FIND_CENSUS(1, j);
944 FIND_CENSUS(j+1, jn);
945 while (jn < MAX_N_CENSI) {
946 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000947 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000948 if (timespan < min_span) {
949 min_span = timespan;
950 min_j = j;
951 }
952 // Move on to next triple
953 jp = j;
954 j = jn;
955 FIND_CENSUS(jn+1, jn);
956 }
957 // We've found the least important census, now remove it
958 min_census = & censi[ min_j ];
959 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
960 n_snapshot_frees++;
961 VG_(free)(min_census->xtree_snapshots[k]);
962 min_census->xtree_snapshots[k] = NULL;
963 }
964 min_census->ms_time = -1;
965 }
966
967 // Slide down the remaining censi over the removed ones. The '<=' is
968 // because we are removing on (N/2)-1, rather than N/2.
969 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
970 FIND_CENSUS(j, j);
971 if (i != j) {
972 censi[i] = censi[j];
973 }
974 }
975 curr_census = i;
976
977 // Double intervals
978 ms_interval *= 2;
979 do_every_nth_census *= 2;
980
981 if (VG_(clo_verbosity) > 1)
982 VG_(message)(Vg_UserMsg, "...done");
983}
984
985// Take a census. Census time seems to be insignificant (usually <= 0 ms,
986// almost always <= 1ms) so don't have to worry about subtracting it from
987// running time in any way.
988//
989// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
990// 50ms!
991static void hp_census(void)
992{
993 static UInt ms_prev_census = 0;
994 static UInt ms_next_census = 0; // zero allows startup census
995
996 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000997 Census* census;
998
999 VGP_PUSHCC(VgpCensus);
1000
1001 // Only do a census if it's time
1002 ms_time = VG_(read_millisecond_timer)();
1003 ms_time_since_prev = ms_time - ms_prev_census;
1004 if (ms_time < ms_next_census) {
1005 n_fake_censi++;
1006 VGP_POPCC(VgpCensus);
1007 return;
1008 }
1009 n_real_censi++;
1010
1011 census = & censi[curr_census];
1012
1013 census->ms_time = ms_time;
1014
1015 // Heap: snapshot the K most significant XTrees -------------------
1016 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001017 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001018 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1019 ? alloc_xpt->n_children
1020 : MAX_SNAPSHOTS); // max out
1021
nethercote43a15ce2004-08-30 19:15:12 +00001022 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001023 // We *do not* do it for any non-top-XPTs.
1024 for (i = 0; i < alloc_xpt->n_children; i++) {
1025 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001026 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001027 }
nethercote43a15ce2004-08-30 19:15:12 +00001028 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001029 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001030 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001031
1032 VGP_PUSHCC(VgpCensusHeap);
1033
1034 // For each significant top-level XPt, record space info about its
1035 // entire XTree, in a single census entry.
1036 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1037 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001038 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001039 for (i = 0; i < K; i++) {
1040 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001041// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1042 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001043 VGP_PUSHCC(VgpCensusTreeSize);
1044 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1045 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001046
1047 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1048 // insignificant) then don't take any more snapshots.
1049 if (0 == xtree_size) break;
1050
1051 // Make array of the appropriate size (+1 for zero termination,
1052 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001053 census->xtree_snapshots[i] =
1054 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001055 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001056 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1057 (xtree_size+1) * sizeof(XPtSnapshot));
1058
1059 // Take space-snapshot: copy 'curr_space' for every XPt in the
1060 // XTree into the snapshot array, along with pointers to the XPts.
1061 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001062 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001063 // saves a lot of memory and up to 40% time with big --depth valus.
1064 VGP_PUSHCC(VgpCensusSnapshot);
1065 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1066 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001067 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001068 VGP_POPCC(VgpCensusSnapshot);
1069 }
1070// VG_(printf)("\n\n");
1071 // Zero-terminate 'xtree_snapshot' array
1072 census->xtree_snapshots[i] = NULL;
1073
1074 VGP_POPCC(VgpCensusHeap);
1075
1076 //VG_(printf)("printed %d censi\n", K);
1077
1078 // Lump the rest into a single "others" entry.
1079 census->others_space = 0;
1080 for (i = K; i < alloc_xpt->n_children; i++) {
1081 census->others_space += alloc_xpt->children[i]->curr_space;
1082 }
1083 }
1084
1085 // Heap admin -------------------------------------------------------
1086 if (clo_heap_admin > 0)
1087 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1088
1089 // Stack(s) ---------------------------------------------------------
1090 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001091 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001092 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001093 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001094 }
1095
1096 // Finish, update interval if necessary -----------------------------
1097 curr_census++;
1098 census = NULL; // don't use again now that curr_census changed
1099
1100 // Halve the entries, if our census table is full
1101 if (MAX_N_CENSI == curr_census) {
1102 halve_censi();
1103 }
1104
1105 // Take time for next census from now, rather than when this census
1106 // should have happened. Because, if there's a big gap due to a kernel
1107 // operation, there's no point doing catch-up censi every BB for a while
1108 // -- that would just give N censi at almost the same time.
1109 if (VG_(clo_verbosity) > 1) {
1110 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1111 VG_(read_millisecond_timer)() - ms_time );
1112 }
1113 ms_prev_census = ms_time;
1114 ms_next_census = ms_time + ms_interval;
1115 //ms_next_census += ms_interval;
1116
1117 //VG_(printf)("Next: %d ms\n", ms_next_census);
1118
1119 VGP_POPCC(VgpCensus);
1120}
1121
1122/*------------------------------------------------------------*/
1123/*--- Tracked events ---*/
1124/*------------------------------------------------------------*/
1125
nethercote8b5f40c2004-11-02 13:29:50 +00001126static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001127{
1128 sigstacks_space += len;
1129}
1130
nethercote8b5f40c2004-11-02 13:29:50 +00001131static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001132{
njnca82cc02004-11-22 17:18:48 +00001133 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001134 sigstacks_space -= len;
1135}
1136
1137/*------------------------------------------------------------*/
1138/*--- Client Requests ---*/
1139/*------------------------------------------------------------*/
1140
njn51d827b2005-05-09 01:02:08 +00001141static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001142{
1143 switch (argv[0]) {
1144 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001145 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001146 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001147 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001148 *ret = 0;
njn57735902004-11-25 18:04:54 +00001149 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001150 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001151 return True;
1152 }
1153 case VG_USERREQ__FREELIKE_BLOCK: {
1154 void* p = (void*)argv[1];
1155 *ret = 0;
1156 die_block( p, /*custom_free*/True );
1157 return True;
1158 }
1159 default:
1160 *ret = 0;
1161 return False;
1162 }
1163}
1164
1165/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001166/*--- Instrumentation ---*/
1167/*------------------------------------------------------------*/
1168
njn51d827b2005-05-09 01:02:08 +00001169static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1170 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001171{
sewardjd54babf2005-03-21 00:55:49 +00001172 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001173 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001174}
1175
1176/*------------------------------------------------------------*/
1177/*--- Spacetime recomputation ---*/
1178/*------------------------------------------------------------*/
1179
nethercote43a15ce2004-08-30 19:15:12 +00001180// Although we've been calculating space-time along the way, because the
1181// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001182// might not agree with what hp2ps sees, because we've thrown away some of
1183// the information. So recompute it at the scale that hp2ps sees, so we can
1184// confidently determine which contexts hp2ps will choose for displaying as
1185// distinct bands. This recomputation only happens to the significant ones
1186// that get printed in the .hp file, so it's cheap.
1187//
nethercote43a15ce2004-08-30 19:15:12 +00001188// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001189// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1190// where
1191// a[N] is the space at census N
1192// d(A,B) is the time interval between censi A and B
1193// and
1194// d(A,B) + d(B,C) == d(A,C)
1195//
1196// Key point: we can calculate the area for a census without knowing the
1197// previous or subsequent censi's space; because any over/underestimates
1198// for this census will be reversed in the next, balancing out. This is
1199// important, as getting the previous/next census entry for a particular
1200// AP is a pain with this data structure, but getting the prev/next
1201// census time is easy.
1202//
nethercote43a15ce2004-08-30 19:15:12 +00001203// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001204// The ULong* values are all running totals, hence the use of "+=" everywhere.
1205
1206// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001207static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001208 ULong* twice_heap_ST,
1209 ULong* twice_heap_admin_ST,
1210 ULong* twice_stack_ST)
1211{
1212 UInt i, j;
1213 XPtSnapshot* xpt_snapshot;
1214
1215 // Heap --------------------------------------------------------
1216 if (clo_heap) {
1217 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001218 // Compute total heap exact_ST_dbld for the entire XTree using only
1219 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001220 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1221
nethercote43a15ce2004-08-30 19:15:12 +00001222 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1223 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001224 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1225 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001226 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001227 }
1228 }
1229 *twice_heap_ST += d_t1_t2 * census->others_space;
1230 }
1231
1232 // Heap admin --------------------------------------------------
1233 if (clo_heap_admin > 0)
1234 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1235
1236 // Stack(s) ----------------------------------------------------
1237 if (clo_stacks)
1238 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1239}
1240
1241// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001242static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001243{
1244 UInt i, N = curr_census;
1245
1246 VGP_PUSHCC(VgpCalcSpacetime2);
1247
1248 *heap2 = 0;
1249 *heap_admin2 = 0;
1250 *stack2 = 0;
1251
1252 if (N <= 1)
1253 return;
1254
nethercote43a15ce2004-08-30 19:15:12 +00001255 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1256 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001257
1258 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001259 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1260 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001261 }
1262
nethercote43a15ce2004-08-30 19:15:12 +00001263 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1264 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001265 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1266 *heap2 /= 2;
1267 *heap_admin2 /= 2;
1268 *stack2 /= 2;
1269
1270 VGP_POPCC(VgpCalcSpacetime2);
1271}
1272
1273/*------------------------------------------------------------*/
1274/*--- Writing the graph file ---*/
1275/*------------------------------------------------------------*/
1276
1277static Char* make_filename(Char* dir, Char* suffix)
1278{
1279 Char* filename;
1280
1281 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1282 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1283 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1284
1285 return filename;
1286}
1287
1288// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1289static Char* clean_fnname(Char *d, Char* s)
1290{
1291 Char* dorig = d;
1292 while (*s) {
1293 if (' ' == *s) { *d = '%'; }
1294 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1295 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1296 else { *d = *s; };
1297 s++;
1298 d++;
1299 }
1300 *d = '\0';
1301 return dorig;
1302}
1303
1304static void file_err ( Char* file )
1305{
njn02bc4b82005-05-15 17:28:26 +00001306 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001307 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1308}
1309
1310/* Format, by example:
1311
1312 JOB "a.out -p"
1313 DATE "Fri Apr 17 11:43:45 1992"
1314 SAMPLE_UNIT "seconds"
1315 VALUE_UNIT "bytes"
1316 BEGIN_SAMPLE 0.00
1317 SYSTEM 24
1318 END_SAMPLE 0.00
1319 BEGIN_SAMPLE 1.00
1320 elim 180
1321 insert 24
1322 intersect 12
1323 disin 60
1324 main 12
1325 reduce 20
1326 SYSTEM 12
1327 END_SAMPLE 1.00
1328 MARK 1.50
1329 MARK 1.75
1330 MARK 1.80
1331 BEGIN_SAMPLE 2.00
1332 elim 192
1333 insert 24
1334 intersect 12
1335 disin 84
1336 main 12
1337 SYSTEM 24
1338 END_SAMPLE 2.00
1339 BEGIN_SAMPLE 2.82
1340 END_SAMPLE 2.82
1341 */
1342static void write_hp_file(void)
1343{
1344 Int i, j;
1345 Int fd, res;
1346 Char *hp_file, *ps_file, *aux_file;
1347 Char* cmdfmt;
1348 Char* cmdbuf;
1349 Int cmdlen;
1350
1351 VGP_PUSHCC(VgpPrintHp);
1352
1353 // Open file
1354 hp_file = make_filename( base_dir, ".hp" );
1355 ps_file = make_filename( base_dir, ".ps" );
1356 aux_file = make_filename( base_dir, ".aux" );
1357 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1358 VKI_S_IRUSR|VKI_S_IWUSR);
1359 if (fd < 0) {
1360 file_err( hp_file );
1361 VGP_POPCC(VgpPrintHp);
1362 return;
1363 }
1364
1365 // File header, including command line
1366 SPRINTF(buf, "JOB \"");
1367 for (i = 0; i < VG_(client_argc); i++)
1368 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1369 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1370 "DATE \"\"\n"
1371 "SAMPLE_UNIT \"ms\"\n"
1372 "VALUE_UNIT \"bytes\"\n", ms_interval);
1373
1374 // Censi
1375 for (i = 0; i < curr_census; i++) {
1376 Census* census = & censi[i];
1377
1378 // Census start
1379 SPRINTF(buf, "MARK %d.0\n"
1380 "BEGIN_SAMPLE %d.0\n",
1381 census->ms_time, census->ms_time);
1382
1383 // Heap -----------------------------------------------------------
1384 if (clo_heap) {
1385 // Print all the significant XPts from that census
1386 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1387 // Grab the jth top-XPt
1388 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001389 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001390 VG_(sprintf)(buf2, "???");
1391 }
njnd01fef72005-03-25 23:35:48 +00001392 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001393 clean_fnname(buf3, buf2), xtree_snapshot->space);
1394 }
1395
1396 // Remaining heap block alloc points, combined
1397 if (census->others_space > 0)
1398 SPRINTF(buf, "other %d\n", census->others_space);
1399 }
1400
1401 // Heap admin -----------------------------------------------------
1402 if (clo_heap_admin > 0 && census->heap_admin_space)
1403 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1404
1405 // Stack(s) -------------------------------------------------------
1406 if (clo_stacks)
1407 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1408
1409 // Census end
1410 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1411 }
1412
1413 // Close file
njnca82cc02004-11-22 17:18:48 +00001414 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001415 VG_(close)(fd);
1416
1417 // Attempt to convert file using hp2ps
1418 cmdfmt = "%s/hp2ps -c -t1 %s";
1419 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1420 + VG_(strlen)(cmdfmt);
1421 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1422 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1423 res = VG_(system)(cmdbuf);
1424 VG_(free)(cmdbuf);
1425 if (res != 0) {
1426 VG_(message)(Vg_UserMsg,
1427 "Conversion to PostScript failed. Try converting manually.");
1428 } else {
1429 // remove the .hp and .aux file
1430 VG_(unlink)(hp_file);
1431 VG_(unlink)(aux_file);
1432 }
1433
1434 VG_(free)(hp_file);
1435 VG_(free)(ps_file);
1436 VG_(free)(aux_file);
1437
1438 VGP_POPCC(VgpPrintHp);
1439}
1440
1441/*------------------------------------------------------------*/
1442/*--- Writing the XPt text/HTML file ---*/
1443/*------------------------------------------------------------*/
1444
1445static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1446{
1447 int i, len, space;
1448
1449 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1450 len = VG_(strlen)(xbuf);
1451 space = field_width - len;
1452 if (space < 0) space = 0; /* Allow for v. small field_width */
1453 i = len;
1454
1455 /* Right justify in field */
1456 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1457 for (i = 0; i < space; i++) xbuf[i] = ' ';
1458}
1459
1460// Nb: uses a static buffer, each call trashes the last string returned.
1461static Char* make_perc(ULong spacetime, ULong total_spacetime)
1462{
1463 static Char mbuf[32];
1464
1465 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001466 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001467 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1468 return mbuf;
1469}
1470
njnd01fef72005-03-25 23:35:48 +00001471// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001472// bottom-to-top of XCon, and then printed in the reverse order.
1473static UInt pp_XCon(Int fd, XPt* xpt)
1474{
njnd01fef72005-03-25 23:35:48 +00001475 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001476 Int i = 0;
1477 Int n = 0;
1478 Bool is_HTML = ( XHTML == clo_format );
1479 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1480 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1481
njnca82cc02004-11-22 17:18:48 +00001482 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001483
1484 while (True) {
njnd01fef72005-03-25 23:35:48 +00001485 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001486 n++;
1487 if (alloc_xpt == xpt->parent) break;
1488 i++;
1489 xpt = xpt->parent;
1490 }
1491
1492 for (i = n-1; i >= 0; i--) {
1493 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001494 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001495 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1496 }
1497
1498 return n;
1499}
1500
1501// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001502// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001503// sufficient, because function pointers mean that you can call more than
1504// one other function from a single code location. So instead we use the
1505// address of the xpt struct itself, which is guaranteed to be unique.
1506
1507static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1508 ULong total_spacetime)
1509{
1510 UInt i;
1511 XPt *xpt, *child;
1512 UInt L = 0;
1513 UInt c1 = 1;
1514 UInt c2 = 0;
1515 ULong sum = 0;
1516 UInt n;
njnd01fef72005-03-25 23:35:48 +00001517 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001518 Bool is_HTML = ( XHTML == clo_format );
1519 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1520 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1521 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1522 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1523 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1524 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1525 Char* end_hr = ( is_HTML ? "<hr>" :
1526 "=================================" );
1527 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1528
nethercote43a15ce2004-08-30 19:15:12 +00001529 if (total_spacetime == 0) {
1530 SPRINTF(buf, "(No heap memory allocated)\n");
1531 return;
1532 }
1533
1534
nethercotec9f36922004-02-14 16:40:02 +00001535 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1536
1537 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001538 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001539 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001540
nethercote43a15ce2004-08-30 19:15:12 +00001541 // Check that the sum of all children .exact_ST_dbld fields equals
1542 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001543 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001544 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001545 } else {
1546 sum = 0;
1547 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001548 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001549 }
njnca82cc02004-11-22 17:18:48 +00001550 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001551 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001552 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001553 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001554// tl_assert(sum <= xpt->exact_ST_dbld);
1555// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001556// if (sum != xpt->exact_ST_dbld) {
1557// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001558// }
1559 }
1560
1561 if (xpt == alloc_xpt) {
1562 SPRINTF(buf, "Heap allocation functions accounted for "
1563 "%s of measured spacetime%s\n",
1564 make_perc(heap_spacetime, total_spacetime), maybe_br);
1565 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001566 // Remember: exact_ST_dbld is space.time *doubled*
1567 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001568 if (is_HTML) {
1569 SPRINTF(buf, "<a name=\"b%x\"></a>"
1570 "Context accounted for "
1571 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1572 xpt, xpt, perc);
1573 } else {
1574 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1575 perc);
1576 }
1577 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001578 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001579 }
1580
nethercote43a15ce2004-08-30 19:15:12 +00001581 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001582 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001583 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001584
1585 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1586 for (i = 0; i < xpt->n_children; i++) {
1587 child = xpt->children[i];
1588
1589 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001590 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001591 UInt n_insig = xpt->n_children - i;
1592 Char* s = ( n_insig == 1 ? "" : "s" );
1593 Char* and = ( 0 == i ? "" : "and " );
1594 Char* other = ( 0 == i ? "" : "other " );
1595 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1596 maybe_li, and, n_insig, other, s, maybe_fli);
1597 break;
1598 }
1599
nethercote43a15ce2004-08-30 19:15:12 +00001600 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001601 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1602 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001603 if (is_HTML) {
1604 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1605
1606 if (child->n_children > 0) {
1607 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1608 } else {
1609 SPRINTF(buf, "%s", perc);
1610 }
njnd01fef72005-03-25 23:35:48 +00001611 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001612 } else {
njnd01fef72005-03-25 23:35:48 +00001613 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001614 }
1615
1616 if (child->n_children > 0) {
1617 enqueue(q, (void*)child);
1618 c2++;
1619 }
1620 }
1621 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1622 c1--;
1623
1624 // Putting markers between levels of the structure:
1625 // c1 tracks how many to go on this level, c2 tracks how many we've
1626 // queued up for the next level while finishing off this level.
1627 // When c1 gets to zero, we've changed levels, so print a marker,
1628 // move c2 into c1, and zero c2.
1629 if (0 == c1) {
1630 L++;
1631 c1 = c2;
1632 c2 = 0;
1633 if (! is_empty_queue(q) ) { // avoid empty one at end
1634 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1635 }
1636 } else {
1637 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1638 }
1639 }
1640 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1641 "%s value for more.\n", end_hr, depth);
1642}
1643
1644static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1645 ULong total_spacetime)
1646{
1647 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001648
nethercotec9f36922004-02-14 16:40:02 +00001649 enqueue(q, xpt);
1650 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1651 destruct_queue(q);
1652}
1653
1654static void
1655write_text_file(ULong total_ST, ULong heap_ST)
1656{
1657 Int fd, i;
1658 Char* text_file;
1659 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1660
1661 VGP_PUSHCC(VgpPrintXPts);
1662
1663 // Open file
1664 text_file = make_filename( base_dir,
1665 ( XText == clo_format ? ".txt" : ".html" ) );
1666
1667 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1668 VKI_S_IRUSR|VKI_S_IWUSR);
1669 if (fd < 0) {
1670 file_err( text_file );
1671 VGP_POPCC(VgpPrintXPts);
1672 return;
1673 }
1674
1675 // Header
1676 if (XHTML == clo_format) {
1677 SPRINTF(buf, "<html>\n"
1678 "<head>\n"
1679 "<title>%s</title>\n"
1680 "</head>\n"
1681 "<body>\n",
1682 text_file);
1683 }
1684
1685 // Command line
1686 SPRINTF(buf, "Command: ");
1687 for (i = 0; i < VG_(client_argc); i++)
1688 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1689 SPRINTF(buf, "\n%s\n", maybe_p);
1690
1691 if (clo_heap)
1692 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1693
njnca82cc02004-11-22 17:18:48 +00001694 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001695 VG_(close)(fd);
1696
1697 VGP_POPCC(VgpPrintXPts);
1698}
1699
1700/*------------------------------------------------------------*/
1701/*--- Finalisation ---*/
1702/*------------------------------------------------------------*/
1703
1704static void
1705print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1706 ULong stack_ST)
1707{
1708 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1709
1710 // Heap --------------------------------------------------------------
1711 if (clo_heap)
1712 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001713 ( 0 == total_ST ? (Char*)"(n/a)"
1714 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001715
1716 // Heap admin --------------------------------------------------------
1717 if (clo_heap_admin)
1718 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001719 ( 0 == total_ST ? (Char*)"(n/a)"
1720 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001721
njnca82cc02004-11-22 17:18:48 +00001722 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001723
1724 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001725 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001726 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001727 ( 0 == stack_ST ? (Char*)"0%"
1728 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001729 }
nethercotec9f36922004-02-14 16:40:02 +00001730
1731 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001732 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001733 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1734 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1735 n_zero_allocs * 100 / n_allocs );
1736 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1737 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1738 n_xpts*sizeof(XPt));
1739 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1740 n_bot_xpts * 100 / n_xpts);
1741 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1742 alloc_xpt->n_children * 100 / n_xpts);
1743 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1744 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1745 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1746 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1747 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1748 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1749 }
1750}
1751
njn51d827b2005-05-09 01:02:08 +00001752static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001753{
1754 ULong total_ST = 0;
1755 ULong heap_ST = 0;
1756 ULong heap_admin_ST = 0;
1757 ULong stack_ST = 0;
1758
1759 // Do a final (empty) sample to show program's end
1760 hp_census();
1761
1762 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001763 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001764 total_ST = heap_ST + heap_admin_ST + stack_ST;
1765 write_hp_file ( );
1766 write_text_file( total_ST, heap_ST );
1767 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1768}
1769
njn51d827b2005-05-09 01:02:08 +00001770/*------------------------------------------------------------*/
1771/*--- Initialisation ---*/
1772/*------------------------------------------------------------*/
1773
1774static void ms_post_clo_init(void)
1775{
1776 ms_interval = 1;
1777
1778 // Do an initial sample for t = 0
1779 hp_census();
1780}
1781
1782static void ms_pre_clo_init()
1783{
1784 VG_(details_name) ("Massif");
1785 VG_(details_version) (NULL);
1786 VG_(details_description) ("a space profiler");
1787 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1788 VG_(details_bug_reports_to) (VG_BUGS_TO);
1789
1790 // Basic functions
1791 VG_(basic_tool_funcs) (ms_post_clo_init,
1792 ms_instrument,
1793 ms_fini);
1794
1795 // Needs
1796 VG_(needs_libc_freeres)();
1797 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1798 ms_print_usage,
1799 ms_print_debug_usage);
1800 VG_(needs_client_requests) (ms_handle_client_request);
1801
1802 // Malloc replacement
1803 VG_(malloc_funcs) (ms_malloc,
1804 ms___builtin_new,
1805 ms___builtin_vec_new,
1806 ms_memalign,
1807 ms_calloc,
1808 ms_free,
1809 ms___builtin_delete,
1810 ms___builtin_vec_delete,
1811 ms_realloc,
1812 0 );
1813
1814 // Events to track
1815 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1816 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1817
1818 // Profiling events
1819 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1820 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1821 VG_(register_profile_event)(VgpCensus, "census");
1822 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1823 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1824 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1825 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1826 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1827 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1828 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1829
1830 // HP_Chunks
1831 malloc_list = VG_(HT_construct)();
1832
1833 // Dummy node at top of the context structure.
1834 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1835
1836 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1837}
1838
1839VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001840
1841/*--------------------------------------------------------------------*/
1842/*--- end ms_main.c ---*/
1843/*--------------------------------------------------------------------*/
1844