blob: c25147352e8a2f8d7528012f9cb426996d219c79 [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"
njn36a20fa2005-06-03 03:08:39 +000041#include "pub_tool_libcprint.h"
njn717cde52005-05-10 02:47:21 +000042#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +000043#include "pub_tool_options.h"
njn31513b42005-06-01 03:09:59 +000044#include "pub_tool_profile.h"
njn717cde52005-05-10 02:47:21 +000045#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000046#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +000047#include "pub_tool_tooliface.h"
nethercotec9f36922004-02-14 16:40:02 +000048
49#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
50
51/*------------------------------------------------------------*/
52/*--- Overview of operation ---*/
53/*------------------------------------------------------------*/
54
55// Heap blocks are tracked, and the amount of space allocated by various
56// contexts (ie. lines of code, more or less) is also tracked.
57// Periodically, a census is taken, and the amount of space used, at that
58// point, by the most significant (highly allocating) contexts is recorded.
59// Census start off frequently, but are scaled back as the program goes on,
60// so that there are always a good number of them. At the end, overall
61// spacetimes for different contexts (of differing levels of precision) is
62// calculated, the graph is printed, and the text giving spacetimes for the
63// increasingly precise contexts is given.
64//
65// Measures the following:
66// - heap blocks
67// - heap admin bytes
68// - stack(s)
69// - code (code segments loaded at startup, and loaded with mmap)
70// - data (data segments loaded at startup, and loaded/created with mmap,
71// and brk()d segments)
72
73/*------------------------------------------------------------*/
74/*--- Main types ---*/
75/*------------------------------------------------------------*/
76
77// An XPt represents an "execution point", ie. a code address. Each XPt is
78// part of a tree of XPts (an "execution tree", or "XTree"). Each
79// top-to-bottom path through an XTree gives an execution context ("XCon"),
80// and is equivalent to a traditional Valgrind ExeContext.
81//
82// The XPt at the top of an XTree (but below "alloc_xpt") is called a
83// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
84// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
85// bottom-XPTs in that XTree.
86//
87// All XCons have the same top-XPt, "alloc_xpt", which represents all
88// allocation functions like malloc(). It's a bit of a fake XPt, though,
89// and is only used because it makes some of the code simpler.
90//
91// XTrees are bi-directional.
92//
93// > parent < Example: if child1() calls parent() and child2()
94// / | \ also calls parent(), and parent() calls malloc(),
95// | / \ | the XTree will look like this.
96// | v v |
97// child1 child2
98
99typedef struct _XPt XPt;
100
101struct _XPt {
njnd01fef72005-03-25 23:35:48 +0000102 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +0000103
104 // Bottom-XPts: space for the precise context.
105 // Other XPts: space of all the descendent bottom-XPts.
106 // Nb: this value goes up and down as the program executes.
107 UInt curr_space;
108
109 // An approximate space.time calculation used along the way for selecting
110 // which contexts to include at each census point.
111 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000112 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000113
nethercote43a15ce2004-08-30 19:15:12 +0000114 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000115 // used in the results.
116 // Note that it is *doubled*, to avoid rounding errors.
117 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000118 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000119
120 // n_children and max_children are integers; a very big program might
121 // have more than 65536 allocation points (Konqueror startup has 1800).
122 XPt* parent; // pointer to parent XPt
123 UInt n_children; // number of children
124 UInt max_children; // capacity of children array
125 XPt** children; // pointers to children XPts
126};
127
128// Each census snapshots the most significant XTrees, each XTree having a
129// top-XPt as its root. The 'curr_space' element for each XPt is recorded
130// in the snapshot. The snapshot contains all the XTree's XPts, not in a
131// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000132// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000133//
134// Graph resolution, x-axis: no point having more than about 200 census
135// x-points; you can't see them on the graph. Therefore:
136//
137// - do a census every 1 ms for first 200 --> 200, all (200 ms)
138// - halve (drop half of them) --> 100, every 2nd (200 ms)
139// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
140// - halve --> 100, every 4th (400 ms)
141// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
142// - etc.
143//
144// This isn't exactly right, because we actually drop (N/2)-1 when halving,
145// but it shows the basic idea.
146
147#define MAX_N_CENSI 200 // Keep it even, for simplicity
148
149// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
150// bands, rest get lumped into OTHERS. I only print the top N
151// (cumulative-so-far space-time) at each point. N should be a bit bigger
152// than 19 in case the cumulative space-time doesn't fit with the eventual
153// space-time computed by hp2ps (but it should be close if the samples are
154// evenly spread, since hp2ps does an approximate per-band space-time
155// calculation that just sums the totals; ie. it assumes all samples are
156// the same distance apart).
157
158#define MAX_SNAPSHOTS 32
159
160typedef
161 struct {
162 XPt* xpt;
163 UInt space;
164 }
165 XPtSnapshot;
166
167// An XTree snapshot is stored as an array of of XPt snapshots.
168typedef XPtSnapshot* XTreeSnapshot;
169
170typedef
171 struct {
172 Int ms_time; // Int: must allow -1
173 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
174 UInt others_space;
175 UInt heap_admin_space;
176 UInt stacks_space;
177 }
178 Census;
179
180// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
181// which is a foothold into the XCon at which it was allocated. From
182// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
183// decremented (at deallocation).
184//
185// Nb: first two fields must match core's VgHashNode.
186typedef
187 struct _HP_Chunk {
188 struct _HP_Chunk* next;
189 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000190 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000191 XPt* where; // Where allocated; bottom-XPt
192 }
193 HP_Chunk;
194
195/*------------------------------------------------------------*/
196/*--- Profiling events ---*/
197/*------------------------------------------------------------*/
198
199typedef
200 enum {
201 VgpGetXPt = VgpFini+1,
202 VgpGetXPtSearch,
203 VgpCensus,
204 VgpCensusHeap,
205 VgpCensusSnapshot,
206 VgpCensusTreeSize,
207 VgpUpdateXCon,
208 VgpCalcSpacetime2,
209 VgpPrintHp,
210 VgpPrintXPts,
211 }
njn4be0a692004-11-22 18:10:36 +0000212 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000213
214/*------------------------------------------------------------*/
215/*--- Statistics ---*/
216/*------------------------------------------------------------*/
217
218// Konqueror startup, to give an idea of the numbers involved with a biggish
219// program, with default depth:
220//
221// depth=3 depth=40
222// - 310,000 allocations
223// - 300,000 frees
224// - 15,000 XPts 800,000 XPts
225// - 1,800 top-XPts
226
227static UInt n_xpts = 0;
228static UInt n_bot_xpts = 0;
229static UInt n_allocs = 0;
230static UInt n_zero_allocs = 0;
231static UInt n_frees = 0;
232static UInt n_children_reallocs = 0;
233static UInt n_snapshot_frees = 0;
234
235static UInt n_halvings = 0;
236static UInt n_real_censi = 0;
237static UInt n_fake_censi = 0;
238static UInt n_attempted_censi = 0;
239
240/*------------------------------------------------------------*/
241/*--- Globals ---*/
242/*------------------------------------------------------------*/
243
244#define FILENAME_LEN 256
245
246#define SPRINTF(zz_buf, fmt, args...) \
247 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
248 VG_(write)(fd, (void*)zz_buf, len); \
249 } while (0)
250
251#define BUF_LEN 1024 // general purpose
252static Char buf [BUF_LEN];
253static Char buf2[BUF_LEN];
254static Char buf3[BUF_LEN];
255
nethercote8b5f40c2004-11-02 13:29:50 +0000256static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000257
258static VgHashTable malloc_list = NULL; // HP_Chunks
259
260static UInt n_heap_blocks = 0;
261
njn51d827b2005-05-09 01:02:08 +0000262// Current directory at startup.
263static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000264
265#define MAX_ALLOC_FNS 32 // includes the builtin ones
266
nethercotec7469182004-05-11 09:21:08 +0000267// First few filled in, rest should be zeroed. Zero-terminated vector.
268static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000269static Char* alloc_fns[MAX_ALLOC_FNS] = {
270 "malloc",
271 "operator new(unsigned)",
272 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000273 "operator new(unsigned, std::nothrow_t const&)",
274 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000275 "__builtin_new",
276 "__builtin_vec_new",
277 "calloc",
278 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000279 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000280};
281
282
283/*------------------------------------------------------------*/
284/*--- Command line args ---*/
285/*------------------------------------------------------------*/
286
287#define MAX_DEPTH 50
288
289typedef
290 enum {
291 XText, XHTML,
292 }
293 XFormat;
294
295static Bool clo_heap = True;
296static UInt clo_heap_admin = 8;
297static Bool clo_stacks = True;
298static Bool clo_depth = 3;
299static XFormat clo_format = XText;
300
njn51d827b2005-05-09 01:02:08 +0000301static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000302{
njn45270a22005-03-27 01:00:11 +0000303 VG_BOOL_CLO(arg, "--heap", clo_heap)
304 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000305
njn45270a22005-03-27 01:00:11 +0000306 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
307 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000308
309 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
310 alloc_fns[n_alloc_fns] = & arg[11];
311 n_alloc_fns++;
312 if (n_alloc_fns >= MAX_ALLOC_FNS) {
313 VG_(printf)("Too many alloc functions specified, sorry");
314 VG_(bad_option)(arg);
315 }
316 }
317
318 else if (VG_CLO_STREQ(arg, "--format=text"))
319 clo_format = XText;
320 else if (VG_CLO_STREQ(arg, "--format=html"))
321 clo_format = XHTML;
322
323 else
324 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000325
nethercotec9f36922004-02-14 16:40:02 +0000326 return True;
327}
328
njn51d827b2005-05-09 01:02:08 +0000329static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000330{
331 VG_(printf)(
332" --heap=no|yes profile heap blocks [yes]\n"
333" --heap-admin=<number> average admin bytes per heap block [8]\n"
334" --stacks=no|yes profile stack(s) [yes]\n"
335" --depth=<number> depth of contexts [3]\n"
336" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
337" --format=text|html format of textual output [text]\n"
338 );
339 VG_(replacement_malloc_print_usage)();
340}
341
njn51d827b2005-05-09 01:02:08 +0000342static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000343{
344 VG_(replacement_malloc_print_debug_usage)();
345}
346
347/*------------------------------------------------------------*/
348/*--- Execution contexts ---*/
349/*------------------------------------------------------------*/
350
351// Fake XPt representing all allocation functions like malloc(). Acts as
352// parent node to all top-XPts.
353static XPt* alloc_xpt;
354
355// Cheap allocation for blocks that never need to be freed. Saves about 10%
356// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000357static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000358{
359 static Addr hp = 0; // current heap pointer
360 static Addr hp_lim = 0; // maximum usable byte in current block
361
362 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
363
364 if (hp + n_bytes > hp_lim) {
365 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
366 hp_lim = hp + SUPERBLOCK_SIZE - 1;
367 }
368
369 hp += n_bytes;
370
371 return (void*)(hp - n_bytes);
372}
373
374
375
njnd01fef72005-03-25 23:35:48 +0000376static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000377{
378 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000379 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000380
nethercote43a15ce2004-08-30 19:15:12 +0000381 xpt->curr_space = 0;
382 xpt->approx_ST = 0;
383 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000384
385 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000386
387 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000388 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000389
390 xpt->n_children = 0;
391
392 // If a bottom-XPt, don't allocate space for children. This can be 50%
393 // or more, although it tends to drop as --depth increases (eg. 10% for
394 // konqueror with --depth=20).
395 if ( is_bottom ) {
396 xpt->max_children = 0;
397 xpt->children = NULL;
398 n_bot_xpts++;
399 } else {
400 xpt->max_children = 4;
401 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
402 }
403
404 // Update statistics
405 n_xpts++;
406
407 return xpt;
408}
409
njnd01fef72005-03-25 23:35:48 +0000410static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000411{
412 Int i;
413
njnd01fef72005-03-25 23:35:48 +0000414 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000415 for (i = 0; i < n_alloc_fns; i++) {
416 if (VG_STREQ(buf, alloc_fns[i]))
417 return True;
418 }
419 }
420 return False;
421}
422
423// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
424// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
425// to ensure this in certain cases. See comments below.
426static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
427{
njnd01fef72005-03-25 23:35:48 +0000428 // Static to minimise stack size. +1 for added ~0 IP
429 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000430
431 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000432 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000433 UInt overestimate;
434 Bool reached_bottom;
435
436 VGP_PUSHCC(VgpGetXPt);
437
438 // Want at least clo_depth non-alloc-fn entries in the snapshot.
439 // However, because we have 1 or more (an unknown number, at this point)
440 // alloc-fns ignored, we overestimate the size needed for the stack
441 // snapshot. Then, if necessary, we repeatedly increase the size until
442 // it is enough.
443 overestimate = 2;
444 while (True) {
njnd01fef72005-03-25 23:35:48 +0000445 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000446
njnd01fef72005-03-25 23:35:48 +0000447 // Now we add a dummy "unknown" IP at the end. This is only used if we
448 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000449 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
450 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000451 // the parent's approx_ST wouldn't be equal [or almost equal] to the
452 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000453 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000454
njnd01fef72005-03-25 23:35:48 +0000455 // Skip over alloc functions in ips[].
456 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000457
458 // Must be at least one alloc function, unless client used
459 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000460 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000461
462 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000463 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000464 overestimate += 2;
465 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000466 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000467 } else {
468 break;
469 }
470 }
471 A = L;
njnd01fef72005-03-25 23:35:48 +0000472 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000473 reached_bottom = False;
474
njnd01fef72005-03-25 23:35:48 +0000475 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000476
477 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000478 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000479 while (True) {
njnd01fef72005-03-25 23:35:48 +0000480 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000481 // XXX: linear search, ugh -- about 10% of time for konqueror startup
482 // XXX: tried cacheing last result, only hit about 4% for konqueror
483 // Nb: this search hits about 98% of the time for konqueror
484 VGP_PUSHCC(VgpGetXPtSearch);
485
486 // If we've searched/added deep enough, or run out of EIPs, this is
487 // the bottom XPt.
488 if (L - A + 1 == clo_depth || L == B)
489 reached_bottom = True;
490
491 nC = 0;
492 while (True) {
493 if (nC == xpt->n_children) {
494 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000495 tl_assert(xpt->max_children != 0);
496 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000497 // Expand 'children' if necessary
498 if (xpt->n_children == xpt->max_children) {
499 xpt->max_children *= 2;
500 xpt->children = VG_(realloc)( xpt->children,
501 xpt->max_children * sizeof(XPt*) );
502 n_children_reallocs++;
503 }
njnd01fef72005-03-25 23:35:48 +0000504 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000505 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000506 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000507 break;
508 }
njnd01fef72005-03-25 23:35:48 +0000509 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000510 nC++; // keep looking
511 }
512 VGP_POPCC(VgpGetXPtSearch);
513
514 // Return found/built bottom-XPt.
515 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000516 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000517 VGP_POPCC(VgpGetXPt);
518 return xpt->children[nC];
519 }
520
521 // Descend to next level in XTree, the newly found/built non-bottom-XPt
522 xpt = xpt->children[nC];
523 L++;
524 }
525}
526
527// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
528static void update_XCon(XPt* xpt, Int space_delta)
529{
530 VGP_PUSHCC(VgpUpdateXCon);
531
njnca82cc02004-11-22 17:18:48 +0000532 tl_assert(True == clo_heap);
533 tl_assert(0 != space_delta);
534 tl_assert(NULL != xpt);
535 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000536
537 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000538 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000539 xpt->curr_space += space_delta;
540 xpt = xpt->parent;
541 }
njnca82cc02004-11-22 17:18:48 +0000542 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000543 alloc_xpt->curr_space += space_delta;
544
545 VGP_POPCC(VgpUpdateXCon);
546}
547
548// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000549static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000550{
551 XPt* xpt1 = *(XPt**)n1;
552 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000553 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000554}
555
nethercote43a15ce2004-08-30 19:15:12 +0000556static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000557{
558 XPt* xpt1 = *(XPt**)n1;
559 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000560 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000561}
562
563
564/*------------------------------------------------------------*/
565/*--- A generic Queue ---*/
566/*------------------------------------------------------------*/
567
568typedef
569 struct {
570 UInt head; // Index of first entry
571 UInt tail; // Index of final+1 entry, ie. next free slot
572 UInt max_elems;
573 void** elems;
574 }
575 Queue;
576
577static Queue* construct_queue(UInt size)
578{
579 UInt i;
580 Queue* q = VG_(malloc)(sizeof(Queue));
581 q->head = 0;
582 q->tail = 0;
583 q->max_elems = size;
584 q->elems = VG_(malloc)(size * sizeof(void*));
585 for (i = 0; i < size; i++)
586 q->elems[i] = NULL;
587
588 return q;
589}
590
591static void destruct_queue(Queue* q)
592{
593 VG_(free)(q->elems);
594 VG_(free)(q);
595}
596
597static void shuffle(Queue* dest_q, void** old_elems)
598{
599 UInt i, j;
600 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
601 dest_q->elems[i] = old_elems[j];
602 dest_q->head = 0;
603 dest_q->tail = i;
604 for ( ; i < dest_q->max_elems; i++)
605 dest_q->elems[i] = NULL; // paranoia
606}
607
608// Shuffles elements down. If not enough slots free, increase size. (We
609// don't wait until we've completely run out of space, because there could
610// be lots of shuffling just before that point which would be slow.)
611static void adjust(Queue* q)
612{
613 void** old_elems;
614
njnca82cc02004-11-22 17:18:48 +0000615 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000616 if (q->head < 10) {
617 old_elems = q->elems;
618 q->max_elems *= 2;
619 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
620 shuffle(q, old_elems);
621 VG_(free)(old_elems);
622 } else {
623 shuffle(q, q->elems);
624 }
625}
626
627static void enqueue(Queue* q, void* elem)
628{
629 if (q->tail == q->max_elems)
630 adjust(q);
631 q->elems[q->tail++] = elem;
632}
633
634static Bool is_empty_queue(Queue* q)
635{
636 return (q->head == q->tail);
637}
638
639static void* dequeue(Queue* q)
640{
641 if (is_empty_queue(q))
642 return NULL; // Queue empty
643 else
644 return q->elems[q->head++];
645}
646
647/*------------------------------------------------------------*/
648/*--- malloc() et al replacement wrappers ---*/
649/*------------------------------------------------------------*/
650
651static __inline__
652void add_HP_Chunk(HP_Chunk* hc)
653{
654 n_heap_blocks++;
655 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
656}
657
658static __inline__
659HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
660{
nethercote3d6b6112004-11-04 16:39:43 +0000661 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000662 (VgHashNode***)prev_chunks_next_ptr );
663}
664
665static __inline__
666void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
667{
njnca82cc02004-11-22 17:18:48 +0000668 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000669 n_heap_blocks--;
670 *prev_chunks_next_ptr = hc->next;
671}
672
673// Forward declaration
674static void hp_census(void);
675
nethercote159dfef2004-09-13 13:27:30 +0000676static
njn57735902004-11-25 18:04:54 +0000677void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
678 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000679{
680 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000681 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000682 if (size < 0) return NULL;
683
684 VGP_PUSHCC(VgpCliMalloc);
685
686 // Update statistics
687 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000688 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000689
nethercote57e36b32004-07-10 14:56:28 +0000690 // Allocate and zero if necessary
691 if (!p) {
692 p = VG_(cli_malloc)( align, size );
693 if (!p) {
694 VGP_POPCC(VgpCliMalloc);
695 return NULL;
696 }
697 if (is_zeroed) VG_(memset)(p, 0, size);
698 }
699
700 // Make new HP_Chunk node, add to malloclist
701 hc = VG_(malloc)(sizeof(HP_Chunk));
702 hc->size = size;
703 hc->data = (Addr)p;
704 hc->where = NULL; // paranoia
705 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000706 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000707 if (0 != size)
708 update_XCon(hc->where, size);
709 }
710 add_HP_Chunk( hc );
711
712 // do a census!
713 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000714
715 VGP_POPCC(VgpCliMalloc);
716 return p;
717}
718
719static __inline__
720void die_block ( void* p, Bool custom_free )
721{
nethercote57e36b32004-07-10 14:56:28 +0000722 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000723
724 VGP_PUSHCC(VgpCliMalloc);
725
726 // Update statistics
727 n_frees++;
728
nethercote57e36b32004-07-10 14:56:28 +0000729 // Remove HP_Chunk from malloclist
730 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000731 if (hc == NULL)
732 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000733 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000734 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000735
736 if (clo_heap && hc->size != 0)
737 update_XCon(hc->where, -hc->size);
738
nethercote57e36b32004-07-10 14:56:28 +0000739 VG_(free)( hc );
740
741 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000742 if (!custom_free)
743 VG_(cli_free)( p );
744
nethercote57e36b32004-07-10 14:56:28 +0000745 // do a census!
746 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000747
nethercotec9f36922004-02-14 16:40:02 +0000748 VGP_POPCC(VgpCliMalloc);
749}
750
751
njn51d827b2005-05-09 01:02:08 +0000752static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000753{
njn57735902004-11-25 18:04:54 +0000754 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000755}
756
njn51d827b2005-05-09 01:02:08 +0000757static void* ms___builtin_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000758{
njn57735902004-11-25 18:04:54 +0000759 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000760}
761
njn51d827b2005-05-09 01:02:08 +0000762static void* ms___builtin_vec_new ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000763{
njn57735902004-11-25 18:04:54 +0000764 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000765}
766
njn51d827b2005-05-09 01:02:08 +0000767static void* ms_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000768{
njn57735902004-11-25 18:04:54 +0000769 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000770}
771
njn51d827b2005-05-09 01:02:08 +0000772static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000773{
njn57735902004-11-25 18:04:54 +0000774 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000775}
776
njn51d827b2005-05-09 01:02:08 +0000777static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000778{
779 die_block( p, /*custom_free*/False );
780}
781
njn51d827b2005-05-09 01:02:08 +0000782static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000783{
784 die_block( p, /*custom_free*/False);
785}
786
njn51d827b2005-05-09 01:02:08 +0000787static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000788{
789 die_block( p, /*custom_free*/False );
790}
791
njn51d827b2005-05-09 01:02:08 +0000792static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000793{
794 HP_Chunk* hc;
795 HP_Chunk** remove_handle;
796 Int i;
797 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000798 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000799 XPt *old_where, *new_where;
800
801 VGP_PUSHCC(VgpCliMalloc);
802
803 // First try and find the block.
804 hc = get_HP_Chunk ( p_old, &remove_handle );
805 if (hc == NULL) {
806 VGP_POPCC(VgpCliMalloc);
807 return NULL; // must have been a bogus free()
808 }
809
njnca82cc02004-11-22 17:18:48 +0000810 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000811 old_size = hc->size;
812
813 if (new_size <= old_size) {
814 // new size is smaller or same; block not moved
815 p_new = p_old;
816
817 } else {
818 // new size is bigger; make new block, copy shared contents, free old
819 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
820
821 for (i = 0; i < old_size; i++)
822 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
823
824 VG_(cli_free)(p_old);
825 }
826
827 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000828 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000829
830 // Update HP_Chunk
831 hc->data = (Addr)p_new;
832 hc->size = new_size;
833 hc->where = new_where;
834
835 // Update XPt curr_space fields
836 if (clo_heap) {
837 if (0 != old_size) update_XCon(old_where, -old_size);
838 if (0 != new_size) update_XCon(new_where, new_size);
839 }
840
841 // If block has moved, have to remove and reinsert in the malloclist
842 // (since the updated 'data' field is the hash lookup key).
843 if (p_new != p_old) {
844 remove_HP_Chunk(hc, remove_handle);
845 add_HP_Chunk(hc);
846 }
847
848 VGP_POPCC(VgpCliMalloc);
849 return p_new;
850}
851
852
853/*------------------------------------------------------------*/
854/*--- Taking a census ---*/
855/*------------------------------------------------------------*/
856
857static Census censi[MAX_N_CENSI];
858static UInt curr_census = 0;
859
860// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000861static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000862{
thughes4ad52d02004-06-27 17:37:21 +0000863 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000864 return False;
865}
866
867static UInt get_xtree_size(XPt* xpt, UInt ix)
868{
869 UInt i;
870
nethercote43a15ce2004-08-30 19:15:12 +0000871 // If no memory allocated at all, nothing interesting to record.
872 if (alloc_xpt->curr_space == 0) return 0;
873
874 // Ignore sub-XTrees that account for a miniscule fraction of current
875 // allocated space.
876 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000877 ix++;
878
879 // Count all (non-zero) descendent XPts
880 for (i = 0; i < xpt->n_children; i++)
881 ix = get_xtree_size(xpt->children[i], ix);
882 }
883 return ix;
884}
885
886static
887UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
888{
889 UInt i;
890
nethercote43a15ce2004-08-30 19:15:12 +0000891 // Structure of this function mirrors that of get_xtree_size().
892
893 if (alloc_xpt->curr_space == 0) return 0;
894
895 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000896 xtree_snapshot[ix].xpt = xpt;
897 xtree_snapshot[ix].space = xpt->curr_space;
898 ix++;
899
nethercotec9f36922004-02-14 16:40:02 +0000900 for (i = 0; i < xpt->n_children; i++)
901 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
902 }
903 return ix;
904}
905
906static UInt ms_interval;
907static UInt do_every_nth_census = 30;
908
909// Weed out half the censi; we choose those that represent the smallest
910// time-spans, because that loses the least information.
911//
912// Algorithm for N censi: We find the census representing the smallest
913// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
914// (It's (N/2)-1 because we never remove the first and last censi.)
915// We have to do this one census at a time, rather than finding the (N/2)-1
916// smallest censi in one hit, because when a census is removed, it's
917// neighbours immediately cover greater timespans. So it's N^2, but N only
918// equals 200, and this is only done every 100 censi, which is not too often.
919static void halve_censi(void)
920{
921 Int i, jp, j, jn, k;
922 Census* min_census;
923
924 n_halvings++;
925 if (VG_(clo_verbosity) > 1)
926 VG_(message)(Vg_UserMsg, "Halving censi...");
927
928 // Sets j to the index of the first not-yet-removed census at or after i
929 #define FIND_CENSUS(i, j) \
njn6f1f76d2005-05-24 21:28:54 +0000930 for (j = i; j < MAX_N_CENSI && -1 == censi[j].ms_time; j++) { }
nethercotec9f36922004-02-14 16:40:02 +0000931
932 for (i = 2; i < MAX_N_CENSI; i += 2) {
933 // Find the censi representing the smallest timespan. The timespan
934 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
935 // censi A and B. We don't consider the first and last censi for
936 // removal.
937 Int min_span = 0x7fffffff;
938 Int min_j = 0;
939
940 // Initial triple: (prev, curr, next) == (jp, j, jn)
941 jp = 0;
942 FIND_CENSUS(1, j);
943 FIND_CENSUS(j+1, jn);
944 while (jn < MAX_N_CENSI) {
945 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000946 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000947 if (timespan < min_span) {
948 min_span = timespan;
949 min_j = j;
950 }
951 // Move on to next triple
952 jp = j;
953 j = jn;
954 FIND_CENSUS(jn+1, jn);
955 }
956 // We've found the least important census, now remove it
957 min_census = & censi[ min_j ];
958 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
959 n_snapshot_frees++;
960 VG_(free)(min_census->xtree_snapshots[k]);
961 min_census->xtree_snapshots[k] = NULL;
962 }
963 min_census->ms_time = -1;
964 }
965
966 // Slide down the remaining censi over the removed ones. The '<=' is
967 // because we are removing on (N/2)-1, rather than N/2.
968 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
969 FIND_CENSUS(j, j);
970 if (i != j) {
971 censi[i] = censi[j];
972 }
973 }
974 curr_census = i;
975
976 // Double intervals
977 ms_interval *= 2;
978 do_every_nth_census *= 2;
979
980 if (VG_(clo_verbosity) > 1)
981 VG_(message)(Vg_UserMsg, "...done");
982}
983
984// Take a census. Census time seems to be insignificant (usually <= 0 ms,
985// almost always <= 1ms) so don't have to worry about subtracting it from
986// running time in any way.
987//
988// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
989// 50ms!
990static void hp_census(void)
991{
992 static UInt ms_prev_census = 0;
993 static UInt ms_next_census = 0; // zero allows startup census
994
995 Int ms_time, ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +0000996 Census* census;
997
998 VGP_PUSHCC(VgpCensus);
999
1000 // Only do a census if it's time
1001 ms_time = VG_(read_millisecond_timer)();
1002 ms_time_since_prev = ms_time - ms_prev_census;
1003 if (ms_time < ms_next_census) {
1004 n_fake_censi++;
1005 VGP_POPCC(VgpCensus);
1006 return;
1007 }
1008 n_real_censi++;
1009
1010 census = & censi[curr_census];
1011
1012 census->ms_time = ms_time;
1013
1014 // Heap: snapshot the K most significant XTrees -------------------
1015 if (clo_heap) {
njn6f1f76d2005-05-24 21:28:54 +00001016 Int i, K;
nethercotec9f36922004-02-14 16:40:02 +00001017 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1018 ? alloc_xpt->n_children
1019 : MAX_SNAPSHOTS); // max out
1020
nethercote43a15ce2004-08-30 19:15:12 +00001021 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001022 // We *do not* do it for any non-top-XPTs.
1023 for (i = 0; i < alloc_xpt->n_children; i++) {
1024 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001025 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001026 }
nethercote43a15ce2004-08-30 19:15:12 +00001027 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001028 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001029 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001030
1031 VGP_PUSHCC(VgpCensusHeap);
1032
1033 // For each significant top-level XPt, record space info about its
1034 // entire XTree, in a single census entry.
1035 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1036 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001037 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001038 for (i = 0; i < K; i++) {
1039 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001040// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1041 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001042 VGP_PUSHCC(VgpCensusTreeSize);
1043 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1044 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001045
1046 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1047 // insignificant) then don't take any more snapshots.
1048 if (0 == xtree_size) break;
1049
1050 // Make array of the appropriate size (+1 for zero termination,
1051 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001052 census->xtree_snapshots[i] =
1053 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001054 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001055 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1056 (xtree_size+1) * sizeof(XPtSnapshot));
1057
1058 // Take space-snapshot: copy 'curr_space' for every XPt in the
1059 // XTree into the snapshot array, along with pointers to the XPts.
1060 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001061 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001062 // saves a lot of memory and up to 40% time with big --depth valus.
1063 VGP_PUSHCC(VgpCensusSnapshot);
1064 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1065 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001066 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001067 VGP_POPCC(VgpCensusSnapshot);
1068 }
1069// VG_(printf)("\n\n");
1070 // Zero-terminate 'xtree_snapshot' array
1071 census->xtree_snapshots[i] = NULL;
1072
1073 VGP_POPCC(VgpCensusHeap);
1074
1075 //VG_(printf)("printed %d censi\n", K);
1076
1077 // Lump the rest into a single "others" entry.
1078 census->others_space = 0;
1079 for (i = K; i < alloc_xpt->n_children; i++) {
1080 census->others_space += alloc_xpt->children[i]->curr_space;
1081 }
1082 }
1083
1084 // Heap admin -------------------------------------------------------
1085 if (clo_heap_admin > 0)
1086 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1087
1088 // Stack(s) ---------------------------------------------------------
1089 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001090 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001091 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001092 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001093 }
1094
1095 // Finish, update interval if necessary -----------------------------
1096 curr_census++;
1097 census = NULL; // don't use again now that curr_census changed
1098
1099 // Halve the entries, if our census table is full
1100 if (MAX_N_CENSI == curr_census) {
1101 halve_censi();
1102 }
1103
1104 // Take time for next census from now, rather than when this census
1105 // should have happened. Because, if there's a big gap due to a kernel
1106 // operation, there's no point doing catch-up censi every BB for a while
1107 // -- that would just give N censi at almost the same time.
1108 if (VG_(clo_verbosity) > 1) {
1109 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1110 VG_(read_millisecond_timer)() - ms_time );
1111 }
1112 ms_prev_census = ms_time;
1113 ms_next_census = ms_time + ms_interval;
1114 //ms_next_census += ms_interval;
1115
1116 //VG_(printf)("Next: %d ms\n", ms_next_census);
1117
1118 VGP_POPCC(VgpCensus);
1119}
1120
1121/*------------------------------------------------------------*/
1122/*--- Tracked events ---*/
1123/*------------------------------------------------------------*/
1124
nethercote8b5f40c2004-11-02 13:29:50 +00001125static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001126{
1127 sigstacks_space += len;
1128}
1129
nethercote8b5f40c2004-11-02 13:29:50 +00001130static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001131{
njnca82cc02004-11-22 17:18:48 +00001132 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001133 sigstacks_space -= len;
1134}
1135
1136/*------------------------------------------------------------*/
1137/*--- Client Requests ---*/
1138/*------------------------------------------------------------*/
1139
njn51d827b2005-05-09 01:02:08 +00001140static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001141{
1142 switch (argv[0]) {
1143 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001144 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001145 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001146 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001147 *ret = 0;
njn57735902004-11-25 18:04:54 +00001148 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001149 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001150 return True;
1151 }
1152 case VG_USERREQ__FREELIKE_BLOCK: {
1153 void* p = (void*)argv[1];
1154 *ret = 0;
1155 die_block( p, /*custom_free*/True );
1156 return True;
1157 }
1158 default:
1159 *ret = 0;
1160 return False;
1161 }
1162}
1163
1164/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001165/*--- Instrumentation ---*/
1166/*------------------------------------------------------------*/
1167
njn51d827b2005-05-09 01:02:08 +00001168static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1169 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001170{
sewardjd54babf2005-03-21 00:55:49 +00001171 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001172 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001173}
1174
1175/*------------------------------------------------------------*/
1176/*--- Spacetime recomputation ---*/
1177/*------------------------------------------------------------*/
1178
nethercote43a15ce2004-08-30 19:15:12 +00001179// Although we've been calculating space-time along the way, because the
1180// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001181// might not agree with what hp2ps sees, because we've thrown away some of
1182// the information. So recompute it at the scale that hp2ps sees, so we can
1183// confidently determine which contexts hp2ps will choose for displaying as
1184// distinct bands. This recomputation only happens to the significant ones
1185// that get printed in the .hp file, so it's cheap.
1186//
nethercote43a15ce2004-08-30 19:15:12 +00001187// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001188// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1189// where
1190// a[N] is the space at census N
1191// d(A,B) is the time interval between censi A and B
1192// and
1193// d(A,B) + d(B,C) == d(A,C)
1194//
1195// Key point: we can calculate the area for a census without knowing the
1196// previous or subsequent censi's space; because any over/underestimates
1197// for this census will be reversed in the next, balancing out. This is
1198// important, as getting the previous/next census entry for a particular
1199// AP is a pain with this data structure, but getting the prev/next
1200// census time is easy.
1201//
nethercote43a15ce2004-08-30 19:15:12 +00001202// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001203// The ULong* values are all running totals, hence the use of "+=" everywhere.
1204
1205// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001206static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001207 ULong* twice_heap_ST,
1208 ULong* twice_heap_admin_ST,
1209 ULong* twice_stack_ST)
1210{
1211 UInt i, j;
1212 XPtSnapshot* xpt_snapshot;
1213
1214 // Heap --------------------------------------------------------
1215 if (clo_heap) {
1216 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001217 // Compute total heap exact_ST_dbld for the entire XTree using only
1218 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001219 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1220
nethercote43a15ce2004-08-30 19:15:12 +00001221 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1222 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001223 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1224 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001225 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001226 }
1227 }
1228 *twice_heap_ST += d_t1_t2 * census->others_space;
1229 }
1230
1231 // Heap admin --------------------------------------------------
1232 if (clo_heap_admin > 0)
1233 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1234
1235 // Stack(s) ----------------------------------------------------
1236 if (clo_stacks)
1237 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1238}
1239
1240// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001241static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001242{
1243 UInt i, N = curr_census;
1244
1245 VGP_PUSHCC(VgpCalcSpacetime2);
1246
1247 *heap2 = 0;
1248 *heap_admin2 = 0;
1249 *stack2 = 0;
1250
1251 if (N <= 1)
1252 return;
1253
nethercote43a15ce2004-08-30 19:15:12 +00001254 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1255 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001256
1257 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001258 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1259 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001260 }
1261
nethercote43a15ce2004-08-30 19:15:12 +00001262 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1263 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001264 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1265 *heap2 /= 2;
1266 *heap_admin2 /= 2;
1267 *stack2 /= 2;
1268
1269 VGP_POPCC(VgpCalcSpacetime2);
1270}
1271
1272/*------------------------------------------------------------*/
1273/*--- Writing the graph file ---*/
1274/*------------------------------------------------------------*/
1275
1276static Char* make_filename(Char* dir, Char* suffix)
1277{
1278 Char* filename;
1279
1280 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1281 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1282 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1283
1284 return filename;
1285}
1286
1287// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1288static Char* clean_fnname(Char *d, Char* s)
1289{
1290 Char* dorig = d;
1291 while (*s) {
1292 if (' ' == *s) { *d = '%'; }
1293 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1294 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1295 else { *d = *s; };
1296 s++;
1297 d++;
1298 }
1299 *d = '\0';
1300 return dorig;
1301}
1302
1303static void file_err ( Char* file )
1304{
njn02bc4b82005-05-15 17:28:26 +00001305 VG_(message)(Vg_UserMsg, "error: can't open output file '%s'", file );
nethercotec9f36922004-02-14 16:40:02 +00001306 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1307}
1308
1309/* Format, by example:
1310
1311 JOB "a.out -p"
1312 DATE "Fri Apr 17 11:43:45 1992"
1313 SAMPLE_UNIT "seconds"
1314 VALUE_UNIT "bytes"
1315 BEGIN_SAMPLE 0.00
1316 SYSTEM 24
1317 END_SAMPLE 0.00
1318 BEGIN_SAMPLE 1.00
1319 elim 180
1320 insert 24
1321 intersect 12
1322 disin 60
1323 main 12
1324 reduce 20
1325 SYSTEM 12
1326 END_SAMPLE 1.00
1327 MARK 1.50
1328 MARK 1.75
1329 MARK 1.80
1330 BEGIN_SAMPLE 2.00
1331 elim 192
1332 insert 24
1333 intersect 12
1334 disin 84
1335 main 12
1336 SYSTEM 24
1337 END_SAMPLE 2.00
1338 BEGIN_SAMPLE 2.82
1339 END_SAMPLE 2.82
1340 */
1341static void write_hp_file(void)
1342{
1343 Int i, j;
1344 Int fd, res;
1345 Char *hp_file, *ps_file, *aux_file;
1346 Char* cmdfmt;
1347 Char* cmdbuf;
1348 Int cmdlen;
1349
1350 VGP_PUSHCC(VgpPrintHp);
1351
1352 // Open file
1353 hp_file = make_filename( base_dir, ".hp" );
1354 ps_file = make_filename( base_dir, ".ps" );
1355 aux_file = make_filename( base_dir, ".aux" );
1356 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1357 VKI_S_IRUSR|VKI_S_IWUSR);
1358 if (fd < 0) {
1359 file_err( hp_file );
1360 VGP_POPCC(VgpPrintHp);
1361 return;
1362 }
1363
1364 // File header, including command line
1365 SPRINTF(buf, "JOB \"");
1366 for (i = 0; i < VG_(client_argc); i++)
1367 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1368 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1369 "DATE \"\"\n"
1370 "SAMPLE_UNIT \"ms\"\n"
1371 "VALUE_UNIT \"bytes\"\n", ms_interval);
1372
1373 // Censi
1374 for (i = 0; i < curr_census; i++) {
1375 Census* census = & censi[i];
1376
1377 // Census start
1378 SPRINTF(buf, "MARK %d.0\n"
1379 "BEGIN_SAMPLE %d.0\n",
1380 census->ms_time, census->ms_time);
1381
1382 // Heap -----------------------------------------------------------
1383 if (clo_heap) {
1384 // Print all the significant XPts from that census
1385 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1386 // Grab the jth top-XPt
1387 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001388 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001389 VG_(sprintf)(buf2, "???");
1390 }
njnd01fef72005-03-25 23:35:48 +00001391 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001392 clean_fnname(buf3, buf2), xtree_snapshot->space);
1393 }
1394
1395 // Remaining heap block alloc points, combined
1396 if (census->others_space > 0)
1397 SPRINTF(buf, "other %d\n", census->others_space);
1398 }
1399
1400 // Heap admin -----------------------------------------------------
1401 if (clo_heap_admin > 0 && census->heap_admin_space)
1402 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1403
1404 // Stack(s) -------------------------------------------------------
1405 if (clo_stacks)
1406 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1407
1408 // Census end
1409 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1410 }
1411
1412 // Close file
njnca82cc02004-11-22 17:18:48 +00001413 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001414 VG_(close)(fd);
1415
1416 // Attempt to convert file using hp2ps
1417 cmdfmt = "%s/hp2ps -c -t1 %s";
1418 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1419 + VG_(strlen)(cmdfmt);
1420 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1421 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1422 res = VG_(system)(cmdbuf);
1423 VG_(free)(cmdbuf);
1424 if (res != 0) {
1425 VG_(message)(Vg_UserMsg,
1426 "Conversion to PostScript failed. Try converting manually.");
1427 } else {
1428 // remove the .hp and .aux file
1429 VG_(unlink)(hp_file);
1430 VG_(unlink)(aux_file);
1431 }
1432
1433 VG_(free)(hp_file);
1434 VG_(free)(ps_file);
1435 VG_(free)(aux_file);
1436
1437 VGP_POPCC(VgpPrintHp);
1438}
1439
1440/*------------------------------------------------------------*/
1441/*--- Writing the XPt text/HTML file ---*/
1442/*------------------------------------------------------------*/
1443
1444static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1445{
1446 int i, len, space;
1447
1448 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1449 len = VG_(strlen)(xbuf);
1450 space = field_width - len;
1451 if (space < 0) space = 0; /* Allow for v. small field_width */
1452 i = len;
1453
1454 /* Right justify in field */
1455 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1456 for (i = 0; i < space; i++) xbuf[i] = ' ';
1457}
1458
1459// Nb: uses a static buffer, each call trashes the last string returned.
1460static Char* make_perc(ULong spacetime, ULong total_spacetime)
1461{
1462 static Char mbuf[32];
1463
1464 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001465 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001466 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1467 return mbuf;
1468}
1469
njnd01fef72005-03-25 23:35:48 +00001470// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001471// bottom-to-top of XCon, and then printed in the reverse order.
1472static UInt pp_XCon(Int fd, XPt* xpt)
1473{
njnd01fef72005-03-25 23:35:48 +00001474 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001475 Int i = 0;
1476 Int n = 0;
1477 Bool is_HTML = ( XHTML == clo_format );
1478 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1479 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1480
njnca82cc02004-11-22 17:18:48 +00001481 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001482
1483 while (True) {
njnd01fef72005-03-25 23:35:48 +00001484 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001485 n++;
1486 if (alloc_xpt == xpt->parent) break;
1487 i++;
1488 xpt = xpt->parent;
1489 }
1490
1491 for (i = n-1; i >= 0; i--) {
1492 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001493 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001494 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1495 }
1496
1497 return n;
1498}
1499
1500// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001501// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001502// sufficient, because function pointers mean that you can call more than
1503// one other function from a single code location. So instead we use the
1504// address of the xpt struct itself, which is guaranteed to be unique.
1505
1506static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1507 ULong total_spacetime)
1508{
1509 UInt i;
1510 XPt *xpt, *child;
1511 UInt L = 0;
1512 UInt c1 = 1;
1513 UInt c2 = 0;
1514 ULong sum = 0;
1515 UInt n;
njnd01fef72005-03-25 23:35:48 +00001516 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001517 Bool is_HTML = ( XHTML == clo_format );
1518 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1519 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1520 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1521 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1522 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1523 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1524 Char* end_hr = ( is_HTML ? "<hr>" :
1525 "=================================" );
1526 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1527
nethercote43a15ce2004-08-30 19:15:12 +00001528 if (total_spacetime == 0) {
1529 SPRINTF(buf, "(No heap memory allocated)\n");
1530 return;
1531 }
1532
1533
nethercotec9f36922004-02-14 16:40:02 +00001534 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1535
1536 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001537 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001538 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001539
nethercote43a15ce2004-08-30 19:15:12 +00001540 // Check that the sum of all children .exact_ST_dbld fields equals
1541 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001542 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001543 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001544 } else {
1545 sum = 0;
1546 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001547 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001548 }
njnca82cc02004-11-22 17:18:48 +00001549 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001550 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001551 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001552 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001553// tl_assert(sum <= xpt->exact_ST_dbld);
1554// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001555// if (sum != xpt->exact_ST_dbld) {
1556// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001557// }
1558 }
1559
1560 if (xpt == alloc_xpt) {
1561 SPRINTF(buf, "Heap allocation functions accounted for "
1562 "%s of measured spacetime%s\n",
1563 make_perc(heap_spacetime, total_spacetime), maybe_br);
1564 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001565 // Remember: exact_ST_dbld is space.time *doubled*
1566 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001567 if (is_HTML) {
1568 SPRINTF(buf, "<a name=\"b%x\"></a>"
1569 "Context accounted for "
1570 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1571 xpt, xpt, perc);
1572 } else {
1573 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1574 perc);
1575 }
1576 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001577 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001578 }
1579
nethercote43a15ce2004-08-30 19:15:12 +00001580 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001581 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001582 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001583
1584 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1585 for (i = 0; i < xpt->n_children; i++) {
1586 child = xpt->children[i];
1587
1588 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001589 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001590 UInt n_insig = xpt->n_children - i;
1591 Char* s = ( n_insig == 1 ? "" : "s" );
1592 Char* and = ( 0 == i ? "" : "and " );
1593 Char* other = ( 0 == i ? "" : "other " );
1594 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1595 maybe_li, and, n_insig, other, s, maybe_fli);
1596 break;
1597 }
1598
nethercote43a15ce2004-08-30 19:15:12 +00001599 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001600 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1601 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001602 if (is_HTML) {
1603 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1604
1605 if (child->n_children > 0) {
1606 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1607 } else {
1608 SPRINTF(buf, "%s", perc);
1609 }
njnd01fef72005-03-25 23:35:48 +00001610 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001611 } else {
njnd01fef72005-03-25 23:35:48 +00001612 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001613 }
1614
1615 if (child->n_children > 0) {
1616 enqueue(q, (void*)child);
1617 c2++;
1618 }
1619 }
1620 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1621 c1--;
1622
1623 // Putting markers between levels of the structure:
1624 // c1 tracks how many to go on this level, c2 tracks how many we've
1625 // queued up for the next level while finishing off this level.
1626 // When c1 gets to zero, we've changed levels, so print a marker,
1627 // move c2 into c1, and zero c2.
1628 if (0 == c1) {
1629 L++;
1630 c1 = c2;
1631 c2 = 0;
1632 if (! is_empty_queue(q) ) { // avoid empty one at end
1633 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1634 }
1635 } else {
1636 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1637 }
1638 }
1639 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1640 "%s value for more.\n", end_hr, depth);
1641}
1642
1643static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1644 ULong total_spacetime)
1645{
1646 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001647
nethercotec9f36922004-02-14 16:40:02 +00001648 enqueue(q, xpt);
1649 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1650 destruct_queue(q);
1651}
1652
1653static void
1654write_text_file(ULong total_ST, ULong heap_ST)
1655{
1656 Int fd, i;
1657 Char* text_file;
1658 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1659
1660 VGP_PUSHCC(VgpPrintXPts);
1661
1662 // Open file
1663 text_file = make_filename( base_dir,
1664 ( XText == clo_format ? ".txt" : ".html" ) );
1665
1666 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1667 VKI_S_IRUSR|VKI_S_IWUSR);
1668 if (fd < 0) {
1669 file_err( text_file );
1670 VGP_POPCC(VgpPrintXPts);
1671 return;
1672 }
1673
1674 // Header
1675 if (XHTML == clo_format) {
1676 SPRINTF(buf, "<html>\n"
1677 "<head>\n"
1678 "<title>%s</title>\n"
1679 "</head>\n"
1680 "<body>\n",
1681 text_file);
1682 }
1683
1684 // Command line
1685 SPRINTF(buf, "Command: ");
1686 for (i = 0; i < VG_(client_argc); i++)
1687 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1688 SPRINTF(buf, "\n%s\n", maybe_p);
1689
1690 if (clo_heap)
1691 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1692
njnca82cc02004-11-22 17:18:48 +00001693 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001694 VG_(close)(fd);
1695
1696 VGP_POPCC(VgpPrintXPts);
1697}
1698
1699/*------------------------------------------------------------*/
1700/*--- Finalisation ---*/
1701/*------------------------------------------------------------*/
1702
1703static void
1704print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1705 ULong stack_ST)
1706{
1707 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1708
1709 // Heap --------------------------------------------------------------
1710 if (clo_heap)
1711 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001712 ( 0 == total_ST ? (Char*)"(n/a)"
1713 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001714
1715 // Heap admin --------------------------------------------------------
1716 if (clo_heap_admin)
1717 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001718 ( 0 == total_ST ? (Char*)"(n/a)"
1719 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001720
njnca82cc02004-11-22 17:18:48 +00001721 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001722
1723 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001724 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001725 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001726 ( 0 == stack_ST ? (Char*)"0%"
1727 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001728 }
nethercotec9f36922004-02-14 16:40:02 +00001729
1730 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001731 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001732 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1733 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1734 n_zero_allocs * 100 / n_allocs );
1735 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1736 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1737 n_xpts*sizeof(XPt));
1738 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1739 n_bot_xpts * 100 / n_xpts);
1740 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1741 alloc_xpt->n_children * 100 / n_xpts);
1742 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1743 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1744 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1745 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1746 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1747 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1748 }
1749}
1750
njn51d827b2005-05-09 01:02:08 +00001751static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001752{
1753 ULong total_ST = 0;
1754 ULong heap_ST = 0;
1755 ULong heap_admin_ST = 0;
1756 ULong stack_ST = 0;
1757
1758 // Do a final (empty) sample to show program's end
1759 hp_census();
1760
1761 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001762 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001763 total_ST = heap_ST + heap_admin_ST + stack_ST;
1764 write_hp_file ( );
1765 write_text_file( total_ST, heap_ST );
1766 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1767}
1768
njn51d827b2005-05-09 01:02:08 +00001769/*------------------------------------------------------------*/
1770/*--- Initialisation ---*/
1771/*------------------------------------------------------------*/
1772
1773static void ms_post_clo_init(void)
1774{
1775 ms_interval = 1;
1776
1777 // Do an initial sample for t = 0
1778 hp_census();
1779}
1780
1781static void ms_pre_clo_init()
1782{
1783 VG_(details_name) ("Massif");
1784 VG_(details_version) (NULL);
1785 VG_(details_description) ("a space profiler");
1786 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1787 VG_(details_bug_reports_to) (VG_BUGS_TO);
1788
1789 // Basic functions
1790 VG_(basic_tool_funcs) (ms_post_clo_init,
1791 ms_instrument,
1792 ms_fini);
1793
1794 // Needs
1795 VG_(needs_libc_freeres)();
1796 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1797 ms_print_usage,
1798 ms_print_debug_usage);
1799 VG_(needs_client_requests) (ms_handle_client_request);
1800
1801 // Malloc replacement
1802 VG_(malloc_funcs) (ms_malloc,
1803 ms___builtin_new,
1804 ms___builtin_vec_new,
1805 ms_memalign,
1806 ms_calloc,
1807 ms_free,
1808 ms___builtin_delete,
1809 ms___builtin_vec_delete,
1810 ms_realloc,
1811 0 );
1812
1813 // Events to track
1814 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1815 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1816
1817 // Profiling events
1818 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1819 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1820 VG_(register_profile_event)(VgpCensus, "census");
1821 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1822 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1823 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1824 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1825 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1826 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1827 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1828
1829 // HP_Chunks
1830 malloc_list = VG_(HT_construct)();
1831
1832 // Dummy node at top of the context structure.
1833 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1834
1835 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1836}
1837
1838VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001839
1840/*--------------------------------------------------------------------*/
1841/*--- end ms_main.c ---*/
1842/*--------------------------------------------------------------------*/
1843