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