blob: c427bc78e8ff489b9d93ca128d1920d26396c5a0 [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"
njn717cde52005-05-10 02:47:21 +000040#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000041#include "pub_tool_options.h"
njn717cde52005-05-10 02:47:21 +000042#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000043#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000044#include "pub_tool_tooliface.h"
nethercotec9f36922004-02-14 16:40:02 +000045
46#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
47
48/*------------------------------------------------------------*/
49/*--- Overview of operation ---*/
50/*------------------------------------------------------------*/
51
52// Heap blocks are tracked, and the amount of space allocated by various
53// contexts (ie. lines of code, more or less) is also tracked.
54// Periodically, a census is taken, and the amount of space used, at that
55// point, by the most significant (highly allocating) contexts is recorded.
56// Census start off frequently, but are scaled back as the program goes on,
57// so that there are always a good number of them. At the end, overall
58// spacetimes for different contexts (of differing levels of precision) is
59// calculated, the graph is printed, and the text giving spacetimes for the
60// increasingly precise contexts is given.
61//
62// Measures the following:
63// - heap blocks
64// - heap admin bytes
65// - stack(s)
66// - code (code segments loaded at startup, and loaded with mmap)
67// - data (data segments loaded at startup, and loaded/created with mmap,
68// and brk()d segments)
69
70/*------------------------------------------------------------*/
71/*--- Main types ---*/
72/*------------------------------------------------------------*/
73
74// An XPt represents an "execution point", ie. a code address. Each XPt is
75// part of a tree of XPts (an "execution tree", or "XTree"). Each
76// top-to-bottom path through an XTree gives an execution context ("XCon"),
77// and is equivalent to a traditional Valgrind ExeContext.
78//
79// The XPt at the top of an XTree (but below "alloc_xpt") is called a
80// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
81// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
82// bottom-XPTs in that XTree.
83//
84// All XCons have the same top-XPt, "alloc_xpt", which represents all
85// allocation functions like malloc(). It's a bit of a fake XPt, though,
86// and is only used because it makes some of the code simpler.
87//
88// XTrees are bi-directional.
89//
90// > parent < Example: if child1() calls parent() and child2()
91// / | \ also calls parent(), and parent() calls malloc(),
92// | / \ | the XTree will look like this.
93// | v v |
94// child1 child2
95
96typedef struct _XPt XPt;
97
98struct _XPt {
njnd01fef72005-03-25 23:35:48 +000099 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000100
101 // Bottom-XPts: space for the precise context.
102 // Other XPts: space of all the descendent bottom-XPts.
103 // Nb: this value goes up and down as the program executes.
104 UInt curr_space;
105
106 // An approximate space.time calculation used along the way for selecting
107 // which contexts to include at each census point.
108 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000109 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000110
nethercote43a15ce2004-08-30 19:15:12 +0000111 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000112 // used in the results.
113 // Note that it is *doubled*, to avoid rounding errors.
114 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000115 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000116
117 // n_children and max_children are integers; a very big program might
118 // have more than 65536 allocation points (Konqueror startup has 1800).
119 XPt* parent; // pointer to parent XPt
120 UInt n_children; // number of children
121 UInt max_children; // capacity of children array
122 XPt** children; // pointers to children XPts
123};
124
125// Each census snapshots the most significant XTrees, each XTree having a
126// top-XPt as its root. The 'curr_space' element for each XPt is recorded
127// in the snapshot. The snapshot contains all the XTree's XPts, not in a
128// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000129// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000130//
131// Graph resolution, x-axis: no point having more than about 200 census
132// x-points; you can't see them on the graph. Therefore:
133//
134// - do a census every 1 ms for first 200 --> 200, all (200 ms)
135// - halve (drop half of them) --> 100, every 2nd (200 ms)
136// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
137// - halve --> 100, every 4th (400 ms)
138// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
139// - etc.
140//
141// This isn't exactly right, because we actually drop (N/2)-1 when halving,
142// but it shows the basic idea.
143
144#define MAX_N_CENSI 200 // Keep it even, for simplicity
145
146// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
147// bands, rest get lumped into OTHERS. I only print the top N
148// (cumulative-so-far space-time) at each point. N should be a bit bigger
149// than 19 in case the cumulative space-time doesn't fit with the eventual
150// space-time computed by hp2ps (but it should be close if the samples are
151// evenly spread, since hp2ps does an approximate per-band space-time
152// calculation that just sums the totals; ie. it assumes all samples are
153// the same distance apart).
154
155#define MAX_SNAPSHOTS 32
156
157typedef
158 struct {
159 XPt* xpt;
160 UInt space;
161 }
162 XPtSnapshot;
163
164// An XTree snapshot is stored as an array of of XPt snapshots.
165typedef XPtSnapshot* XTreeSnapshot;
166
167typedef
168 struct {
169 Int ms_time; // Int: must allow -1
170 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
171 UInt others_space;
172 UInt heap_admin_space;
173 UInt stacks_space;
174 }
175 Census;
176
177// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
178// which is a foothold into the XCon at which it was allocated. From
179// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
180// decremented (at deallocation).
181//
182// Nb: first two fields must match core's VgHashNode.
183typedef
184 struct _HP_Chunk {
185 struct _HP_Chunk* next;
186 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000187 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000188 XPt* where; // Where allocated; bottom-XPt
189 }
190 HP_Chunk;
191
192/*------------------------------------------------------------*/
193/*--- Profiling events ---*/
194/*------------------------------------------------------------*/
195
196typedef
197 enum {
198 VgpGetXPt = VgpFini+1,
199 VgpGetXPtSearch,
200 VgpCensus,
201 VgpCensusHeap,
202 VgpCensusSnapshot,
203 VgpCensusTreeSize,
204 VgpUpdateXCon,
205 VgpCalcSpacetime2,
206 VgpPrintHp,
207 VgpPrintXPts,
208 }
njn4be0a692004-11-22 18:10:36 +0000209 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000210
211/*------------------------------------------------------------*/
212/*--- Statistics ---*/
213/*------------------------------------------------------------*/
214
215// Konqueror startup, to give an idea of the numbers involved with a biggish
216// program, with default depth:
217//
218// depth=3 depth=40
219// - 310,000 allocations
220// - 300,000 frees
221// - 15,000 XPts 800,000 XPts
222// - 1,800 top-XPts
223
224static UInt n_xpts = 0;
225static UInt n_bot_xpts = 0;
226static UInt n_allocs = 0;
227static UInt n_zero_allocs = 0;
228static UInt n_frees = 0;
229static UInt n_children_reallocs = 0;
230static UInt n_snapshot_frees = 0;
231
232static UInt n_halvings = 0;
233static UInt n_real_censi = 0;
234static UInt n_fake_censi = 0;
235static UInt n_attempted_censi = 0;
236
237/*------------------------------------------------------------*/
238/*--- Globals ---*/
239/*------------------------------------------------------------*/
240
241#define FILENAME_LEN 256
242
243#define SPRINTF(zz_buf, fmt, args...) \
244 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
245 VG_(write)(fd, (void*)zz_buf, len); \
246 } while (0)
247
248#define BUF_LEN 1024 // general purpose
249static Char buf [BUF_LEN];
250static Char buf2[BUF_LEN];
251static Char buf3[BUF_LEN];
252
nethercote8b5f40c2004-11-02 13:29:50 +0000253static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000254
255static VgHashTable malloc_list = NULL; // HP_Chunks
256
257static UInt n_heap_blocks = 0;
258
njn51d827b2005-05-09 01:02:08 +0000259// Current directory at startup.
260static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000261
262#define MAX_ALLOC_FNS 32 // includes the builtin ones
263
nethercotec7469182004-05-11 09:21:08 +0000264// First few filled in, rest should be zeroed. Zero-terminated vector.
265static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000266static Char* alloc_fns[MAX_ALLOC_FNS] = {
267 "malloc",
268 "operator new(unsigned)",
269 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000270 "operator new(unsigned, std::nothrow_t const&)",
271 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000272 "__builtin_new",
273 "__builtin_vec_new",
274 "calloc",
275 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000276 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000277};
278
279
280/*------------------------------------------------------------*/
281/*--- Command line args ---*/
282/*------------------------------------------------------------*/
283
284#define MAX_DEPTH 50
285
286typedef
287 enum {
288 XText, XHTML,
289 }
290 XFormat;
291
292static Bool clo_heap = True;
293static UInt clo_heap_admin = 8;
294static Bool clo_stacks = True;
295static Bool clo_depth = 3;
296static XFormat clo_format = XText;
297
njn51d827b2005-05-09 01:02:08 +0000298static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000299{
njn45270a22005-03-27 01:00:11 +0000300 VG_BOOL_CLO(arg, "--heap", clo_heap)
301 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000302
njn45270a22005-03-27 01:00:11 +0000303 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
304 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000305
306 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
307 alloc_fns[n_alloc_fns] = & arg[11];
308 n_alloc_fns++;
309 if (n_alloc_fns >= MAX_ALLOC_FNS) {
310 VG_(printf)("Too many alloc functions specified, sorry");
311 VG_(bad_option)(arg);
312 }
313 }
314
315 else if (VG_CLO_STREQ(arg, "--format=text"))
316 clo_format = XText;
317 else if (VG_CLO_STREQ(arg, "--format=html"))
318 clo_format = XHTML;
319
320 else
321 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000322
nethercotec9f36922004-02-14 16:40:02 +0000323 return True;
324}
325
njn51d827b2005-05-09 01:02:08 +0000326static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000327{
328 VG_(printf)(
329" --heap=no|yes profile heap blocks [yes]\n"
330" --heap-admin=<number> average admin bytes per heap block [8]\n"
331" --stacks=no|yes profile stack(s) [yes]\n"
332" --depth=<number> depth of contexts [3]\n"
333" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
334" --format=text|html format of textual output [text]\n"
335 );
336 VG_(replacement_malloc_print_usage)();
337}
338
njn51d827b2005-05-09 01:02:08 +0000339static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000340{
341 VG_(replacement_malloc_print_debug_usage)();
342}
343
344/*------------------------------------------------------------*/
345/*--- Execution contexts ---*/
346/*------------------------------------------------------------*/
347
348// Fake XPt representing all allocation functions like malloc(). Acts as
349// parent node to all top-XPts.
350static XPt* alloc_xpt;
351
352// Cheap allocation for blocks that never need to be freed. Saves about 10%
353// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000354static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000355{
356 static Addr hp = 0; // current heap pointer
357 static Addr hp_lim = 0; // maximum usable byte in current block
358
359 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
360
361 if (hp + n_bytes > hp_lim) {
362 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
363 hp_lim = hp + SUPERBLOCK_SIZE - 1;
364 }
365
366 hp += n_bytes;
367
368 return (void*)(hp - n_bytes);
369}
370
371
372
njnd01fef72005-03-25 23:35:48 +0000373static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000374{
375 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000376 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000377
nethercote43a15ce2004-08-30 19:15:12 +0000378 xpt->curr_space = 0;
379 xpt->approx_ST = 0;
380 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000381
382 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000383
384 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000385 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000386
387 xpt->n_children = 0;
388
389 // If a bottom-XPt, don't allocate space for children. This can be 50%
390 // or more, although it tends to drop as --depth increases (eg. 10% for
391 // konqueror with --depth=20).
392 if ( is_bottom ) {
393 xpt->max_children = 0;
394 xpt->children = NULL;
395 n_bot_xpts++;
396 } else {
397 xpt->max_children = 4;
398 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
399 }
400
401 // Update statistics
402 n_xpts++;
403
404 return xpt;
405}
406
njnd01fef72005-03-25 23:35:48 +0000407static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000408{
409 Int i;
410
njnd01fef72005-03-25 23:35:48 +0000411 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000412 for (i = 0; i < n_alloc_fns; i++) {
413 if (VG_STREQ(buf, alloc_fns[i]))
414 return True;
415 }
416 }
417 return False;
418}
419
420// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
421// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
422// to ensure this in certain cases. See comments below.
423static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
424{
njnd01fef72005-03-25 23:35:48 +0000425 // Static to minimise stack size. +1 for added ~0 IP
426 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000427
428 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000429 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000430 UInt overestimate;
431 Bool reached_bottom;
432
433 VGP_PUSHCC(VgpGetXPt);
434
435 // Want at least clo_depth non-alloc-fn entries in the snapshot.
436 // However, because we have 1 or more (an unknown number, at this point)
437 // alloc-fns ignored, we overestimate the size needed for the stack
438 // snapshot. Then, if necessary, we repeatedly increase the size until
439 // it is enough.
440 overestimate = 2;
441 while (True) {
njnd01fef72005-03-25 23:35:48 +0000442 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000443
njnd01fef72005-03-25 23:35:48 +0000444 // Now we add a dummy "unknown" IP at the end. This is only used if we
445 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000446 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
447 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000448 // the parent's approx_ST wouldn't be equal [or almost equal] to the
449 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000450 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000451
njnd01fef72005-03-25 23:35:48 +0000452 // Skip over alloc functions in ips[].
453 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000454
455 // Must be at least one alloc function, unless client used
456 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000457 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000458
459 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000460 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000461 overestimate += 2;
462 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000463 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000464 } else {
465 break;
466 }
467 }
468 A = L;
njnd01fef72005-03-25 23:35:48 +0000469 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000470 reached_bottom = False;
471
njnd01fef72005-03-25 23:35:48 +0000472 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000473
474 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000475 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000476 while (True) {
njnd01fef72005-03-25 23:35:48 +0000477 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000478 // XXX: linear search, ugh -- about 10% of time for konqueror startup
479 // XXX: tried cacheing last result, only hit about 4% for konqueror
480 // Nb: this search hits about 98% of the time for konqueror
481 VGP_PUSHCC(VgpGetXPtSearch);
482
483 // If we've searched/added deep enough, or run out of EIPs, this is
484 // the bottom XPt.
485 if (L - A + 1 == clo_depth || L == B)
486 reached_bottom = True;
487
488 nC = 0;
489 while (True) {
490 if (nC == xpt->n_children) {
491 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000492 tl_assert(xpt->max_children != 0);
493 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000494 // Expand 'children' if necessary
495 if (xpt->n_children == xpt->max_children) {
496 xpt->max_children *= 2;
497 xpt->children = VG_(realloc)( xpt->children,
498 xpt->max_children * sizeof(XPt*) );
499 n_children_reallocs++;
500 }
njnd01fef72005-03-25 23:35:48 +0000501 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000502 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000503 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000504 break;
505 }
njnd01fef72005-03-25 23:35:48 +0000506 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000507 nC++; // keep looking
508 }
509 VGP_POPCC(VgpGetXPtSearch);
510
511 // Return found/built bottom-XPt.
512 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000513 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000514 VGP_POPCC(VgpGetXPt);
515 return xpt->children[nC];
516 }
517
518 // Descend to next level in XTree, the newly found/built non-bottom-XPt
519 xpt = xpt->children[nC];
520 L++;
521 }
522}
523
524// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
525static void update_XCon(XPt* xpt, Int space_delta)
526{
527 VGP_PUSHCC(VgpUpdateXCon);
528
njnca82cc02004-11-22 17:18:48 +0000529 tl_assert(True == clo_heap);
530 tl_assert(0 != space_delta);
531 tl_assert(NULL != xpt);
532 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000533
534 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000535 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000536 xpt->curr_space += space_delta;
537 xpt = xpt->parent;
538 }
njnca82cc02004-11-22 17:18:48 +0000539 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000540 alloc_xpt->curr_space += space_delta;
541
542 VGP_POPCC(VgpUpdateXCon);
543}
544
545// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000546static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000547{
548 XPt* xpt1 = *(XPt**)n1;
549 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000550 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000551}
552
nethercote43a15ce2004-08-30 19:15:12 +0000553static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000554{
555 XPt* xpt1 = *(XPt**)n1;
556 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000557 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000558}
559
560
561/*------------------------------------------------------------*/
562/*--- A generic Queue ---*/
563/*------------------------------------------------------------*/
564
565typedef
566 struct {
567 UInt head; // Index of first entry
568 UInt tail; // Index of final+1 entry, ie. next free slot
569 UInt max_elems;
570 void** elems;
571 }
572 Queue;
573
574static Queue* construct_queue(UInt size)
575{
576 UInt i;
577 Queue* q = VG_(malloc)(sizeof(Queue));
578 q->head = 0;
579 q->tail = 0;
580 q->max_elems = size;
581 q->elems = VG_(malloc)(size * sizeof(void*));
582 for (i = 0; i < size; i++)
583 q->elems[i] = NULL;
584
585 return q;
586}
587
588static void destruct_queue(Queue* q)
589{
590 VG_(free)(q->elems);
591 VG_(free)(q);
592}
593
594static void shuffle(Queue* dest_q, void** old_elems)
595{
596 UInt i, j;
597 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
598 dest_q->elems[i] = old_elems[j];
599 dest_q->head = 0;
600 dest_q->tail = i;
601 for ( ; i < dest_q->max_elems; i++)
602 dest_q->elems[i] = NULL; // paranoia
603}
604
605// Shuffles elements down. If not enough slots free, increase size. (We
606// don't wait until we've completely run out of space, because there could
607// be lots of shuffling just before that point which would be slow.)
608static void adjust(Queue* q)
609{
610 void** old_elems;
611
njnca82cc02004-11-22 17:18:48 +0000612 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000613 if (q->head < 10) {
614 old_elems = q->elems;
615 q->max_elems *= 2;
616 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
617 shuffle(q, old_elems);
618 VG_(free)(old_elems);
619 } else {
620 shuffle(q, q->elems);
621 }
622}
623
624static void enqueue(Queue* q, void* elem)
625{
626 if (q->tail == q->max_elems)
627 adjust(q);
628 q->elems[q->tail++] = elem;
629}
630
631static Bool is_empty_queue(Queue* q)
632{
633 return (q->head == q->tail);
634}
635
636static void* dequeue(Queue* q)
637{
638 if (is_empty_queue(q))
639 return NULL; // Queue empty
640 else
641 return q->elems[q->head++];
642}
643
644/*------------------------------------------------------------*/
645/*--- malloc() et al replacement wrappers ---*/
646/*------------------------------------------------------------*/
647
648static __inline__
649void add_HP_Chunk(HP_Chunk* hc)
650{
651 n_heap_blocks++;
652 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
653}
654
655static __inline__
656HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
657{
nethercote3d6b6112004-11-04 16:39:43 +0000658 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000659 (VgHashNode***)prev_chunks_next_ptr );
660}
661
662static __inline__
663void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
664{
njnca82cc02004-11-22 17:18:48 +0000665 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000666 n_heap_blocks--;
667 *prev_chunks_next_ptr = hc->next;
668}
669
670// Forward declaration
671static void hp_census(void);
672
nethercote159dfef2004-09-13 13:27:30 +0000673static
njn57735902004-11-25 18:04:54 +0000674void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
675 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000676{
677 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000678 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000679 if (size < 0) return NULL;
680
681 VGP_PUSHCC(VgpCliMalloc);
682
683 // Update statistics
684 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000685 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000686
nethercote57e36b32004-07-10 14:56:28 +0000687 // Allocate and zero if necessary
688 if (!p) {
689 p = VG_(cli_malloc)( align, size );
690 if (!p) {
691 VGP_POPCC(VgpCliMalloc);
692 return NULL;
693 }
694 if (is_zeroed) VG_(memset)(p, 0, size);
695 }
696
697 // Make new HP_Chunk node, add to malloclist
698 hc = VG_(malloc)(sizeof(HP_Chunk));
699 hc->size = size;
700 hc->data = (Addr)p;
701 hc->where = NULL; // paranoia
702 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000703 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000704 if (0 != size)
705 update_XCon(hc->where, size);
706 }
707 add_HP_Chunk( hc );
708
709 // do a census!
710 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000711
712 VGP_POPCC(VgpCliMalloc);
713 return p;
714}
715
716static __inline__
717void die_block ( void* p, Bool custom_free )
718{
nethercote57e36b32004-07-10 14:56:28 +0000719 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000720
721 VGP_PUSHCC(VgpCliMalloc);
722
723 // Update statistics
724 n_frees++;
725
nethercote57e36b32004-07-10 14:56:28 +0000726 // Remove HP_Chunk from malloclist
727 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000728 if (hc == NULL)
729 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000730 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000731 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000732
733 if (clo_heap && hc->size != 0)
734 update_XCon(hc->where, -hc->size);
735
nethercote57e36b32004-07-10 14:56:28 +0000736 VG_(free)( hc );
737
738 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000739 if (!custom_free)
740 VG_(cli_free)( p );
741
nethercote57e36b32004-07-10 14:56:28 +0000742 // do a census!
743 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000744
nethercotec9f36922004-02-14 16:40:02 +0000745 VGP_POPCC(VgpCliMalloc);
746}
747
748
njn51d827b2005-05-09 01:02:08 +0000749static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000750{
njn57735902004-11-25 18:04:54 +0000751 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000752}
753
njn51d827b2005-05-09 01:02:08 +0000754static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000755{
njn57735902004-11-25 18:04:54 +0000756 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000757}
758
njn51d827b2005-05-09 01:02:08 +0000759static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000760{
njn57735902004-11-25 18:04:54 +0000761 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000762}
763
njn51d827b2005-05-09 01:02:08 +0000764static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000765{
njn57735902004-11-25 18:04:54 +0000766 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000767}
768
njn51d827b2005-05-09 01:02:08 +0000769static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000770{
njn57735902004-11-25 18:04:54 +0000771 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000772}
773
njn51d827b2005-05-09 01:02:08 +0000774static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000775{
776 die_block( p, /*custom_free*/False );
777}
778
njn51d827b2005-05-09 01:02:08 +0000779static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000780{
781 die_block( p, /*custom_free*/False);
782}
783
njn51d827b2005-05-09 01:02:08 +0000784static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000785{
786 die_block( p, /*custom_free*/False );
787}
788
njn51d827b2005-05-09 01:02:08 +0000789static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000790{
791 HP_Chunk* hc;
792 HP_Chunk** remove_handle;
793 Int i;
794 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000795 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000796 XPt *old_where, *new_where;
797
798 VGP_PUSHCC(VgpCliMalloc);
799
800 // First try and find the block.
801 hc = get_HP_Chunk ( p_old, &remove_handle );
802 if (hc == NULL) {
803 VGP_POPCC(VgpCliMalloc);
804 return NULL; // must have been a bogus free()
805 }
806
njnca82cc02004-11-22 17:18:48 +0000807 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000808 old_size = hc->size;
809
810 if (new_size <= old_size) {
811 // new size is smaller or same; block not moved
812 p_new = p_old;
813
814 } else {
815 // new size is bigger; make new block, copy shared contents, free old
816 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
817
818 for (i = 0; i < old_size; i++)
819 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
820
821 VG_(cli_free)(p_old);
822 }
823
824 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000825 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000826
827 // Update HP_Chunk
828 hc->data = (Addr)p_new;
829 hc->size = new_size;
830 hc->where = new_where;
831
832 // Update XPt curr_space fields
833 if (clo_heap) {
834 if (0 != old_size) update_XCon(old_where, -old_size);
835 if (0 != new_size) update_XCon(new_where, new_size);
836 }
837
838 // If block has moved, have to remove and reinsert in the malloclist
839 // (since the updated 'data' field is the hash lookup key).
840 if (p_new != p_old) {
841 remove_HP_Chunk(hc, remove_handle);
842 add_HP_Chunk(hc);
843 }
844
845 VGP_POPCC(VgpCliMalloc);
846 return p_new;
847}
848
849
850/*------------------------------------------------------------*/
851/*--- Taking a census ---*/
852/*------------------------------------------------------------*/
853
854static Census censi[MAX_N_CENSI];
855static UInt curr_census = 0;
856
857// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000858static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000859{
thughes4ad52d02004-06-27 17:37:21 +0000860 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000861 return False;
862}
863
864static UInt get_xtree_size(XPt* xpt, UInt ix)
865{
866 UInt i;
867
nethercote43a15ce2004-08-30 19:15:12 +0000868 // If no memory allocated at all, nothing interesting to record.
869 if (alloc_xpt->curr_space == 0) return 0;
870
871 // Ignore sub-XTrees that account for a miniscule fraction of current
872 // allocated space.
873 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000874 ix++;
875
876 // Count all (non-zero) descendent XPts
877 for (i = 0; i < xpt->n_children; i++)
878 ix = get_xtree_size(xpt->children[i], ix);
879 }
880 return ix;
881}
882
883static
884UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
885{
886 UInt i;
887
nethercote43a15ce2004-08-30 19:15:12 +0000888 // Structure of this function mirrors that of get_xtree_size().
889
890 if (alloc_xpt->curr_space == 0) return 0;
891
892 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000893 xtree_snapshot[ix].xpt = xpt;
894 xtree_snapshot[ix].space = xpt->curr_space;
895 ix++;
896
nethercotec9f36922004-02-14 16:40:02 +0000897 for (i = 0; i < xpt->n_children; i++)
898 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
899 }
900 return ix;
901}
902
903static UInt ms_interval;
904static UInt do_every_nth_census = 30;
905
906// Weed out half the censi; we choose those that represent the smallest
907// time-spans, because that loses the least information.
908//
909// Algorithm for N censi: We find the census representing the smallest
910// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
911// (It's (N/2)-1 because we never remove the first and last censi.)
912// We have to do this one census at a time, rather than finding the (N/2)-1
913// smallest censi in one hit, because when a census is removed, it's
914// neighbours immediately cover greater timespans. So it's N^2, but N only
915// equals 200, and this is only done every 100 censi, which is not too often.
916static void halve_censi(void)
917{
918 Int i, jp, j, jn, k;
919 Census* min_census;
920
921 n_halvings++;
922 if (VG_(clo_verbosity) > 1)
923 VG_(message)(Vg_UserMsg, "Halving censi...");
924
925 // Sets j to the index of the first not-yet-removed census at or after i
926 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000927 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000928
929 for (i = 2; i < MAX_N_CENSI; i += 2) {
930 // Find the censi representing the smallest timespan. The timespan
931 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
932 // censi A and B. We don't consider the first and last censi for
933 // removal.
934 Int min_span = 0x7fffffff;
935 Int min_j = 0;
936
937 // Initial triple: (prev, curr, next) == (jp, j, jn)
938 jp = 0;
939 FIND_CENSUS(1, j);
940 FIND_CENSUS(j+1, jn);
941 while (jn < MAX_N_CENSI) {
942 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000943 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000944 if (timespan < min_span) {
945 min_span = timespan;
946 min_j = j;
947 }
948 // Move on to next triple
949 jp = j;
950 j = jn;
951 FIND_CENSUS(jn+1, jn);
952 }
953 // We've found the least important census, now remove it
954 min_census = & censi[ min_j ];
955 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
956 n_snapshot_frees++;
957 VG_(free)(min_census->xtree_snapshots[k]);
958 min_census->xtree_snapshots[k] = NULL;
959 }
960 min_census->ms_time = -1;
961 }
962
963 // Slide down the remaining censi over the removed ones. The '<=' is
964 // because we are removing on (N/2)-1, rather than N/2.
965 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
966 FIND_CENSUS(j, j);
967 if (i != j) {
968 censi[i] = censi[j];
969 }
970 }
971 curr_census = i;
972
973 // Double intervals
974 ms_interval *= 2;
975 do_every_nth_census *= 2;
976
977 if (VG_(clo_verbosity) > 1)
978 VG_(message)(Vg_UserMsg, "...done");
979}
980
981// Take a census. Census time seems to be insignificant (usually <= 0 ms,
982// almost always <= 1ms) so don't have to worry about subtracting it from
983// running time in any way.
984//
985// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
986// 50ms!
987static void hp_census(void)
988{
989 static UInt ms_prev_census = 0;
990 static UInt ms_next_census = 0; // zero allows startup census
991
992 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000993 Census* census;
994
995 VGP_PUSHCC(VgpCensus);
996
997 // Only do a census if it's time
998 ms_time = VG_(read_millisecond_timer)();
999 ms_time_since_prev = ms_time - ms_prev_census;
1000 if (ms_time < ms_next_census) {
1001 n_fake_censi++;
1002 VGP_POPCC(VgpCensus);
1003 return;
1004 }
1005 n_real_censi++;
1006
1007 census = & censi[curr_census];
1008
1009 census->ms_time = ms_time;
1010
1011 // Heap: snapshot the K most significant XTrees -------------------
1012 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001013 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001014 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1015 ? alloc_xpt->n_children
1016 : MAX_SNAPSHOTS); // max out
1017
nethercote43a15ce2004-08-30 19:15:12 +00001018 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001019 // We *do not* do it for any non-top-XPTs.
1020 for (i = 0; i < alloc_xpt->n_children; i++) {
1021 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001022 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001023 }
nethercote43a15ce2004-08-30 19:15:12 +00001024 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001025 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001026 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001027
1028 VGP_PUSHCC(VgpCensusHeap);
1029
1030 // For each significant top-level XPt, record space info about its
1031 // entire XTree, in a single census entry.
1032 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1033 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001034 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001035 for (i = 0; i < K; i++) {
1036 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001037// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1038 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001039 VGP_PUSHCC(VgpCensusTreeSize);
1040 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1041 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001042
1043 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1044 // insignificant) then don't take any more snapshots.
1045 if (0 == xtree_size) break;
1046
1047 // Make array of the appropriate size (+1 for zero termination,
1048 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001049 census->xtree_snapshots[i] =
1050 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001051 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001052 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1053 (xtree_size+1) * sizeof(XPtSnapshot));
1054
1055 // Take space-snapshot: copy 'curr_space' for every XPt in the
1056 // XTree into the snapshot array, along with pointers to the XPts.
1057 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001058 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001059 // saves a lot of memory and up to 40% time with big --depth valus.
1060 VGP_PUSHCC(VgpCensusSnapshot);
1061 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1062 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001063 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001064 VGP_POPCC(VgpCensusSnapshot);
1065 }
1066// VG_(printf)("\n\n");
1067 // Zero-terminate 'xtree_snapshot' array
1068 census->xtree_snapshots[i] = NULL;
1069
1070 VGP_POPCC(VgpCensusHeap);
1071
1072 //VG_(printf)("printed %d censi\n", K);
1073
1074 // Lump the rest into a single "others" entry.
1075 census->others_space = 0;
1076 for (i = K; i < alloc_xpt->n_children; i++) {
1077 census->others_space += alloc_xpt->children[i]->curr_space;
1078 }
1079 }
1080
1081 // Heap admin -------------------------------------------------------
1082 if (clo_heap_admin > 0)
1083 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1084
1085 // Stack(s) ---------------------------------------------------------
1086 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001087 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001088 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001089 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001090 }
1091
1092 // Finish, update interval if necessary -----------------------------
1093 curr_census++;
1094 census = NULL; // don't use again now that curr_census changed
1095
1096 // Halve the entries, if our census table is full
1097 if (MAX_N_CENSI == curr_census) {
1098 halve_censi();
1099 }
1100
1101 // Take time for next census from now, rather than when this census
1102 // should have happened. Because, if there's a big gap due to a kernel
1103 // operation, there's no point doing catch-up censi every BB for a while
1104 // -- that would just give N censi at almost the same time.
1105 if (VG_(clo_verbosity) > 1) {
1106 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1107 VG_(read_millisecond_timer)() - ms_time );
1108 }
1109 ms_prev_census = ms_time;
1110 ms_next_census = ms_time + ms_interval;
1111 //ms_next_census += ms_interval;
1112
1113 //VG_(printf)("Next: %d ms\n", ms_next_census);
1114
1115 VGP_POPCC(VgpCensus);
1116}
1117
1118/*------------------------------------------------------------*/
1119/*--- Tracked events ---*/
1120/*------------------------------------------------------------*/
1121
nethercote8b5f40c2004-11-02 13:29:50 +00001122static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001123{
1124 sigstacks_space += len;
1125}
1126
nethercote8b5f40c2004-11-02 13:29:50 +00001127static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001128{
njnca82cc02004-11-22 17:18:48 +00001129 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001130 sigstacks_space -= len;
1131}
1132
1133/*------------------------------------------------------------*/
1134/*--- Client Requests ---*/
1135/*------------------------------------------------------------*/
1136
njn51d827b2005-05-09 01:02:08 +00001137static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001138{
1139 switch (argv[0]) {
1140 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001141 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001142 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001143 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001144 *ret = 0;
njn57735902004-11-25 18:04:54 +00001145 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001146 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001147 return True;
1148 }
1149 case VG_USERREQ__FREELIKE_BLOCK: {
1150 void* p = (void*)argv[1];
1151 *ret = 0;
1152 die_block( p, /*custom_free*/True );
1153 return True;
1154 }
1155 default:
1156 *ret = 0;
1157 return False;
1158 }
1159}
1160
1161/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001162/*--- Instrumentation ---*/
1163/*------------------------------------------------------------*/
1164
njn51d827b2005-05-09 01:02:08 +00001165static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1166 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001167{
sewardjd54babf2005-03-21 00:55:49 +00001168 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001169 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001170}
1171
1172/*------------------------------------------------------------*/
1173/*--- Spacetime recomputation ---*/
1174/*------------------------------------------------------------*/
1175
nethercote43a15ce2004-08-30 19:15:12 +00001176// Although we've been calculating space-time along the way, because the
1177// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001178// might not agree with what hp2ps sees, because we've thrown away some of
1179// the information. So recompute it at the scale that hp2ps sees, so we can
1180// confidently determine which contexts hp2ps will choose for displaying as
1181// distinct bands. This recomputation only happens to the significant ones
1182// that get printed in the .hp file, so it's cheap.
1183//
nethercote43a15ce2004-08-30 19:15:12 +00001184// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001185// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1186// where
1187// a[N] is the space at census N
1188// d(A,B) is the time interval between censi A and B
1189// and
1190// d(A,B) + d(B,C) == d(A,C)
1191//
1192// Key point: we can calculate the area for a census without knowing the
1193// previous or subsequent censi's space; because any over/underestimates
1194// for this census will be reversed in the next, balancing out. This is
1195// important, as getting the previous/next census entry for a particular
1196// AP is a pain with this data structure, but getting the prev/next
1197// census time is easy.
1198//
nethercote43a15ce2004-08-30 19:15:12 +00001199// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001200// The ULong* values are all running totals, hence the use of "+=" everywhere.
1201
1202// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001203static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001204 ULong* twice_heap_ST,
1205 ULong* twice_heap_admin_ST,
1206 ULong* twice_stack_ST)
1207{
1208 UInt i, j;
1209 XPtSnapshot* xpt_snapshot;
1210
1211 // Heap --------------------------------------------------------
1212 if (clo_heap) {
1213 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001214 // Compute total heap exact_ST_dbld for the entire XTree using only
1215 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001216 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1217
nethercote43a15ce2004-08-30 19:15:12 +00001218 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1219 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001220 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1221 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001222 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001223 }
1224 }
1225 *twice_heap_ST += d_t1_t2 * census->others_space;
1226 }
1227
1228 // Heap admin --------------------------------------------------
1229 if (clo_heap_admin > 0)
1230 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1231
1232 // Stack(s) ----------------------------------------------------
1233 if (clo_stacks)
1234 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1235}
1236
1237// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001238static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001239{
1240 UInt i, N = curr_census;
1241
1242 VGP_PUSHCC(VgpCalcSpacetime2);
1243
1244 *heap2 = 0;
1245 *heap_admin2 = 0;
1246 *stack2 = 0;
1247
1248 if (N <= 1)
1249 return;
1250
nethercote43a15ce2004-08-30 19:15:12 +00001251 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1252 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001253
1254 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001255 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1256 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001257 }
1258
nethercote43a15ce2004-08-30 19:15:12 +00001259 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1260 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001261 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1262 *heap2 /= 2;
1263 *heap_admin2 /= 2;
1264 *stack2 /= 2;
1265
1266 VGP_POPCC(VgpCalcSpacetime2);
1267}
1268
1269/*------------------------------------------------------------*/
1270/*--- Writing the graph file ---*/
1271/*------------------------------------------------------------*/
1272
1273static Char* make_filename(Char* dir, Char* suffix)
1274{
1275 Char* filename;
1276
1277 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1278 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1279 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1280
1281 return filename;
1282}
1283
1284// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1285static Char* clean_fnname(Char *d, Char* s)
1286{
1287 Char* dorig = d;
1288 while (*s) {
1289 if (' ' == *s) { *d = '%'; }
1290 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1291 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1292 else { *d = *s; };
1293 s++;
1294 d++;
1295 }
1296 *d = '\0';
1297 return dorig;
1298}
1299
1300static void file_err ( Char* file )
1301{
njn02bc4b82005-05-15 17:28:26 +00001302 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001303 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1304}
1305
1306/* Format, by example:
1307
1308 JOB "a.out -p"
1309 DATE "Fri Apr 17 11:43:45 1992"
1310 SAMPLE_UNIT "seconds"
1311 VALUE_UNIT "bytes"
1312 BEGIN_SAMPLE 0.00
1313 SYSTEM 24
1314 END_SAMPLE 0.00
1315 BEGIN_SAMPLE 1.00
1316 elim 180
1317 insert 24
1318 intersect 12
1319 disin 60
1320 main 12
1321 reduce 20
1322 SYSTEM 12
1323 END_SAMPLE 1.00
1324 MARK 1.50
1325 MARK 1.75
1326 MARK 1.80
1327 BEGIN_SAMPLE 2.00
1328 elim 192
1329 insert 24
1330 intersect 12
1331 disin 84
1332 main 12
1333 SYSTEM 24
1334 END_SAMPLE 2.00
1335 BEGIN_SAMPLE 2.82
1336 END_SAMPLE 2.82
1337 */
1338static void write_hp_file(void)
1339{
1340 Int i, j;
1341 Int fd, res;
1342 Char *hp_file, *ps_file, *aux_file;
1343 Char* cmdfmt;
1344 Char* cmdbuf;
1345 Int cmdlen;
1346
1347 VGP_PUSHCC(VgpPrintHp);
1348
1349 // Open file
1350 hp_file = make_filename( base_dir, ".hp" );
1351 ps_file = make_filename( base_dir, ".ps" );
1352 aux_file = make_filename( base_dir, ".aux" );
1353 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1354 VKI_S_IRUSR|VKI_S_IWUSR);
1355 if (fd < 0) {
1356 file_err( hp_file );
1357 VGP_POPCC(VgpPrintHp);
1358 return;
1359 }
1360
1361 // File header, including command line
1362 SPRINTF(buf, "JOB \"");
1363 for (i = 0; i < VG_(client_argc); i++)
1364 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1365 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1366 "DATE \"\"\n"
1367 "SAMPLE_UNIT \"ms\"\n"
1368 "VALUE_UNIT \"bytes\"\n", ms_interval);
1369
1370 // Censi
1371 for (i = 0; i < curr_census; i++) {
1372 Census* census = & censi[i];
1373
1374 // Census start
1375 SPRINTF(buf, "MARK %d.0\n"
1376 "BEGIN_SAMPLE %d.0\n",
1377 census->ms_time, census->ms_time);
1378
1379 // Heap -----------------------------------------------------------
1380 if (clo_heap) {
1381 // Print all the significant XPts from that census
1382 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1383 // Grab the jth top-XPt
1384 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001385 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001386 VG_(sprintf)(buf2, "???");
1387 }
njnd01fef72005-03-25 23:35:48 +00001388 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001389 clean_fnname(buf3, buf2), xtree_snapshot->space);
1390 }
1391
1392 // Remaining heap block alloc points, combined
1393 if (census->others_space > 0)
1394 SPRINTF(buf, "other %d\n", census->others_space);
1395 }
1396
1397 // Heap admin -----------------------------------------------------
1398 if (clo_heap_admin > 0 && census->heap_admin_space)
1399 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1400
1401 // Stack(s) -------------------------------------------------------
1402 if (clo_stacks)
1403 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1404
1405 // Census end
1406 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1407 }
1408
1409 // Close file
njnca82cc02004-11-22 17:18:48 +00001410 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001411 VG_(close)(fd);
1412
1413 // Attempt to convert file using hp2ps
1414 cmdfmt = "%s/hp2ps -c -t1 %s";
1415 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1416 + VG_(strlen)(cmdfmt);
1417 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1418 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1419 res = VG_(system)(cmdbuf);
1420 VG_(free)(cmdbuf);
1421 if (res != 0) {
1422 VG_(message)(Vg_UserMsg,
1423 "Conversion to PostScript failed. Try converting manually.");
1424 } else {
1425 // remove the .hp and .aux file
1426 VG_(unlink)(hp_file);
1427 VG_(unlink)(aux_file);
1428 }
1429
1430 VG_(free)(hp_file);
1431 VG_(free)(ps_file);
1432 VG_(free)(aux_file);
1433
1434 VGP_POPCC(VgpPrintHp);
1435}
1436
1437/*------------------------------------------------------------*/
1438/*--- Writing the XPt text/HTML file ---*/
1439/*------------------------------------------------------------*/
1440
1441static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1442{
1443 int i, len, space;
1444
1445 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1446 len = VG_(strlen)(xbuf);
1447 space = field_width - len;
1448 if (space < 0) space = 0; /* Allow for v. small field_width */
1449 i = len;
1450
1451 /* Right justify in field */
1452 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1453 for (i = 0; i < space; i++) xbuf[i] = ' ';
1454}
1455
1456// Nb: uses a static buffer, each call trashes the last string returned.
1457static Char* make_perc(ULong spacetime, ULong total_spacetime)
1458{
1459 static Char mbuf[32];
1460
1461 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001462 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001463 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1464 return mbuf;
1465}
1466
njnd01fef72005-03-25 23:35:48 +00001467// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001468// bottom-to-top of XCon, and then printed in the reverse order.
1469static UInt pp_XCon(Int fd, XPt* xpt)
1470{
njnd01fef72005-03-25 23:35:48 +00001471 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001472 Int i = 0;
1473 Int n = 0;
1474 Bool is_HTML = ( XHTML == clo_format );
1475 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1476 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1477
njnca82cc02004-11-22 17:18:48 +00001478 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001479
1480 while (True) {
njnd01fef72005-03-25 23:35:48 +00001481 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001482 n++;
1483 if (alloc_xpt == xpt->parent) break;
1484 i++;
1485 xpt = xpt->parent;
1486 }
1487
1488 for (i = n-1; i >= 0; i--) {
1489 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001490 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001491 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1492 }
1493
1494 return n;
1495}
1496
1497// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001498// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001499// sufficient, because function pointers mean that you can call more than
1500// one other function from a single code location. So instead we use the
1501// address of the xpt struct itself, which is guaranteed to be unique.
1502
1503static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1504 ULong total_spacetime)
1505{
1506 UInt i;
1507 XPt *xpt, *child;
1508 UInt L = 0;
1509 UInt c1 = 1;
1510 UInt c2 = 0;
1511 ULong sum = 0;
1512 UInt n;
njnd01fef72005-03-25 23:35:48 +00001513 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001514 Bool is_HTML = ( XHTML == clo_format );
1515 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1516 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1517 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1518 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1519 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1520 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1521 Char* end_hr = ( is_HTML ? "<hr>" :
1522 "=================================" );
1523 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1524
nethercote43a15ce2004-08-30 19:15:12 +00001525 if (total_spacetime == 0) {
1526 SPRINTF(buf, "(No heap memory allocated)\n");
1527 return;
1528 }
1529
1530
nethercotec9f36922004-02-14 16:40:02 +00001531 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1532
1533 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001534 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001535 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001536
nethercote43a15ce2004-08-30 19:15:12 +00001537 // Check that the sum of all children .exact_ST_dbld fields equals
1538 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001539 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001540 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001541 } else {
1542 sum = 0;
1543 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001544 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001545 }
njnca82cc02004-11-22 17:18:48 +00001546 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001547 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001548 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001549 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001550// tl_assert(sum <= xpt->exact_ST_dbld);
1551// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001552// if (sum != xpt->exact_ST_dbld) {
1553// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001554// }
1555 }
1556
1557 if (xpt == alloc_xpt) {
1558 SPRINTF(buf, "Heap allocation functions accounted for "
1559 "%s of measured spacetime%s\n",
1560 make_perc(heap_spacetime, total_spacetime), maybe_br);
1561 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001562 // Remember: exact_ST_dbld is space.time *doubled*
1563 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001564 if (is_HTML) {
1565 SPRINTF(buf, "<a name=\"b%x\"></a>"
1566 "Context accounted for "
1567 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1568 xpt, xpt, perc);
1569 } else {
1570 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1571 perc);
1572 }
1573 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001574 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001575 }
1576
nethercote43a15ce2004-08-30 19:15:12 +00001577 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001578 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001579 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001580
1581 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1582 for (i = 0; i < xpt->n_children; i++) {
1583 child = xpt->children[i];
1584
1585 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001586 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001587 UInt n_insig = xpt->n_children - i;
1588 Char* s = ( n_insig == 1 ? "" : "s" );
1589 Char* and = ( 0 == i ? "" : "and " );
1590 Char* other = ( 0 == i ? "" : "other " );
1591 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1592 maybe_li, and, n_insig, other, s, maybe_fli);
1593 break;
1594 }
1595
nethercote43a15ce2004-08-30 19:15:12 +00001596 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001597 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1598 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001599 if (is_HTML) {
1600 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1601
1602 if (child->n_children > 0) {
1603 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1604 } else {
1605 SPRINTF(buf, "%s", perc);
1606 }
njnd01fef72005-03-25 23:35:48 +00001607 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001608 } else {
njnd01fef72005-03-25 23:35:48 +00001609 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001610 }
1611
1612 if (child->n_children > 0) {
1613 enqueue(q, (void*)child);
1614 c2++;
1615 }
1616 }
1617 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1618 c1--;
1619
1620 // Putting markers between levels of the structure:
1621 // c1 tracks how many to go on this level, c2 tracks how many we've
1622 // queued up for the next level while finishing off this level.
1623 // When c1 gets to zero, we've changed levels, so print a marker,
1624 // move c2 into c1, and zero c2.
1625 if (0 == c1) {
1626 L++;
1627 c1 = c2;
1628 c2 = 0;
1629 if (! is_empty_queue(q) ) { // avoid empty one at end
1630 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1631 }
1632 } else {
1633 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1634 }
1635 }
1636 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1637 "%s value for more.\n", end_hr, depth);
1638}
1639
1640static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1641 ULong total_spacetime)
1642{
1643 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001644
nethercotec9f36922004-02-14 16:40:02 +00001645 enqueue(q, xpt);
1646 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1647 destruct_queue(q);
1648}
1649
1650static void
1651write_text_file(ULong total_ST, ULong heap_ST)
1652{
1653 Int fd, i;
1654 Char* text_file;
1655 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1656
1657 VGP_PUSHCC(VgpPrintXPts);
1658
1659 // Open file
1660 text_file = make_filename( base_dir,
1661 ( XText == clo_format ? ".txt" : ".html" ) );
1662
1663 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1664 VKI_S_IRUSR|VKI_S_IWUSR);
1665 if (fd < 0) {
1666 file_err( text_file );
1667 VGP_POPCC(VgpPrintXPts);
1668 return;
1669 }
1670
1671 // Header
1672 if (XHTML == clo_format) {
1673 SPRINTF(buf, "<html>\n"
1674 "<head>\n"
1675 "<title>%s</title>\n"
1676 "</head>\n"
1677 "<body>\n",
1678 text_file);
1679 }
1680
1681 // Command line
1682 SPRINTF(buf, "Command: ");
1683 for (i = 0; i < VG_(client_argc); i++)
1684 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1685 SPRINTF(buf, "\n%s\n", maybe_p);
1686
1687 if (clo_heap)
1688 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1689
njnca82cc02004-11-22 17:18:48 +00001690 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001691 VG_(close)(fd);
1692
1693 VGP_POPCC(VgpPrintXPts);
1694}
1695
1696/*------------------------------------------------------------*/
1697/*--- Finalisation ---*/
1698/*------------------------------------------------------------*/
1699
1700static void
1701print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1702 ULong stack_ST)
1703{
1704 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1705
1706 // Heap --------------------------------------------------------------
1707 if (clo_heap)
1708 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001709 ( 0 == total_ST ? (Char*)"(n/a)"
1710 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001711
1712 // Heap admin --------------------------------------------------------
1713 if (clo_heap_admin)
1714 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001715 ( 0 == total_ST ? (Char*)"(n/a)"
1716 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001717
njnca82cc02004-11-22 17:18:48 +00001718 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001719
1720 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001721 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001722 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001723 ( 0 == stack_ST ? (Char*)"0%"
1724 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001725 }
nethercotec9f36922004-02-14 16:40:02 +00001726
1727 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001728 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001729 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1730 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1731 n_zero_allocs * 100 / n_allocs );
1732 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1733 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1734 n_xpts*sizeof(XPt));
1735 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1736 n_bot_xpts * 100 / n_xpts);
1737 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1738 alloc_xpt->n_children * 100 / n_xpts);
1739 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1740 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1741 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1742 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1743 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1744 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1745 }
1746}
1747
njn51d827b2005-05-09 01:02:08 +00001748static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001749{
1750 ULong total_ST = 0;
1751 ULong heap_ST = 0;
1752 ULong heap_admin_ST = 0;
1753 ULong stack_ST = 0;
1754
1755 // Do a final (empty) sample to show program's end
1756 hp_census();
1757
1758 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001759 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001760 total_ST = heap_ST + heap_admin_ST + stack_ST;
1761 write_hp_file ( );
1762 write_text_file( total_ST, heap_ST );
1763 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1764}
1765
njn51d827b2005-05-09 01:02:08 +00001766/*------------------------------------------------------------*/
1767/*--- Initialisation ---*/
1768/*------------------------------------------------------------*/
1769
1770static void ms_post_clo_init(void)
1771{
1772 ms_interval = 1;
1773
1774 // Do an initial sample for t = 0
1775 hp_census();
1776}
1777
1778static void ms_pre_clo_init()
1779{
1780 VG_(details_name) ("Massif");
1781 VG_(details_version) (NULL);
1782 VG_(details_description) ("a space profiler");
1783 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1784 VG_(details_bug_reports_to) (VG_BUGS_TO);
1785
1786 // Basic functions
1787 VG_(basic_tool_funcs) (ms_post_clo_init,
1788 ms_instrument,
1789 ms_fini);
1790
1791 // Needs
1792 VG_(needs_libc_freeres)();
1793 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1794 ms_print_usage,
1795 ms_print_debug_usage);
1796 VG_(needs_client_requests) (ms_handle_client_request);
1797
1798 // Malloc replacement
1799 VG_(malloc_funcs) (ms_malloc,
1800 ms___builtin_new,
1801 ms___builtin_vec_new,
1802 ms_memalign,
1803 ms_calloc,
1804 ms_free,
1805 ms___builtin_delete,
1806 ms___builtin_vec_delete,
1807 ms_realloc,
1808 0 );
1809
1810 // Events to track
1811 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1812 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1813
1814 // Profiling events
1815 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1816 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1817 VG_(register_profile_event)(VgpCensus, "census");
1818 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1819 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1820 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1821 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1822 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1823 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1824 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1825
1826 // HP_Chunks
1827 malloc_list = VG_(HT_construct)();
1828
1829 // Dummy node at top of the context structure.
1830 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1831
1832 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1833}
1834
1835VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001836
1837/*--------------------------------------------------------------------*/
1838/*--- end ms_main.c ---*/
1839/*--------------------------------------------------------------------*/
1840