blob: df2ca807b8f81a9686e42f3442d11792d2c45fa0 [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"
njn717cde52005-05-10 02:47:21 +000038#include "pub_tool_mallocfree.h"
39#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +000040#include "pub_tool_stacktrace.h"
nethercotec9f36922004-02-14 16:40:02 +000041
42#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
43
44/*------------------------------------------------------------*/
45/*--- Overview of operation ---*/
46/*------------------------------------------------------------*/
47
48// Heap blocks are tracked, and the amount of space allocated by various
49// contexts (ie. lines of code, more or less) is also tracked.
50// Periodically, a census is taken, and the amount of space used, at that
51// point, by the most significant (highly allocating) contexts is recorded.
52// Census start off frequently, but are scaled back as the program goes on,
53// so that there are always a good number of them. At the end, overall
54// spacetimes for different contexts (of differing levels of precision) is
55// calculated, the graph is printed, and the text giving spacetimes for the
56// increasingly precise contexts is given.
57//
58// Measures the following:
59// - heap blocks
60// - heap admin bytes
61// - stack(s)
62// - code (code segments loaded at startup, and loaded with mmap)
63// - data (data segments loaded at startup, and loaded/created with mmap,
64// and brk()d segments)
65
66/*------------------------------------------------------------*/
67/*--- Main types ---*/
68/*------------------------------------------------------------*/
69
70// An XPt represents an "execution point", ie. a code address. Each XPt is
71// part of a tree of XPts (an "execution tree", or "XTree"). Each
72// top-to-bottom path through an XTree gives an execution context ("XCon"),
73// and is equivalent to a traditional Valgrind ExeContext.
74//
75// The XPt at the top of an XTree (but below "alloc_xpt") is called a
76// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
77// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
78// bottom-XPTs in that XTree.
79//
80// All XCons have the same top-XPt, "alloc_xpt", which represents all
81// allocation functions like malloc(). It's a bit of a fake XPt, though,
82// and is only used because it makes some of the code simpler.
83//
84// XTrees are bi-directional.
85//
86// > parent < Example: if child1() calls parent() and child2()
87// / | \ also calls parent(), and parent() calls malloc(),
88// | / \ | the XTree will look like this.
89// | v v |
90// child1 child2
91
92typedef struct _XPt XPt;
93
94struct _XPt {
njnd01fef72005-03-25 23:35:48 +000095 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +000096
97 // Bottom-XPts: space for the precise context.
98 // Other XPts: space of all the descendent bottom-XPts.
99 // Nb: this value goes up and down as the program executes.
100 UInt curr_space;
101
102 // An approximate space.time calculation used along the way for selecting
103 // which contexts to include at each census point.
104 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000105 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000106
nethercote43a15ce2004-08-30 19:15:12 +0000107 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000108 // used in the results.
109 // Note that it is *doubled*, to avoid rounding errors.
110 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000111 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000112
113 // n_children and max_children are integers; a very big program might
114 // have more than 65536 allocation points (Konqueror startup has 1800).
115 XPt* parent; // pointer to parent XPt
116 UInt n_children; // number of children
117 UInt max_children; // capacity of children array
118 XPt** children; // pointers to children XPts
119};
120
121// Each census snapshots the most significant XTrees, each XTree having a
122// top-XPt as its root. The 'curr_space' element for each XPt is recorded
123// in the snapshot. The snapshot contains all the XTree's XPts, not in a
124// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000125// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000126//
127// Graph resolution, x-axis: no point having more than about 200 census
128// x-points; you can't see them on the graph. Therefore:
129//
130// - do a census every 1 ms for first 200 --> 200, all (200 ms)
131// - halve (drop half of them) --> 100, every 2nd (200 ms)
132// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
133// - halve --> 100, every 4th (400 ms)
134// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
135// - etc.
136//
137// This isn't exactly right, because we actually drop (N/2)-1 when halving,
138// but it shows the basic idea.
139
140#define MAX_N_CENSI 200 // Keep it even, for simplicity
141
142// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
143// bands, rest get lumped into OTHERS. I only print the top N
144// (cumulative-so-far space-time) at each point. N should be a bit bigger
145// than 19 in case the cumulative space-time doesn't fit with the eventual
146// space-time computed by hp2ps (but it should be close if the samples are
147// evenly spread, since hp2ps does an approximate per-band space-time
148// calculation that just sums the totals; ie. it assumes all samples are
149// the same distance apart).
150
151#define MAX_SNAPSHOTS 32
152
153typedef
154 struct {
155 XPt* xpt;
156 UInt space;
157 }
158 XPtSnapshot;
159
160// An XTree snapshot is stored as an array of of XPt snapshots.
161typedef XPtSnapshot* XTreeSnapshot;
162
163typedef
164 struct {
165 Int ms_time; // Int: must allow -1
166 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
167 UInt others_space;
168 UInt heap_admin_space;
169 UInt stacks_space;
170 }
171 Census;
172
173// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
174// which is a foothold into the XCon at which it was allocated. From
175// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
176// decremented (at deallocation).
177//
178// Nb: first two fields must match core's VgHashNode.
179typedef
180 struct _HP_Chunk {
181 struct _HP_Chunk* next;
182 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000183 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000184 XPt* where; // Where allocated; bottom-XPt
185 }
186 HP_Chunk;
187
188/*------------------------------------------------------------*/
189/*--- Profiling events ---*/
190/*------------------------------------------------------------*/
191
192typedef
193 enum {
194 VgpGetXPt = VgpFini+1,
195 VgpGetXPtSearch,
196 VgpCensus,
197 VgpCensusHeap,
198 VgpCensusSnapshot,
199 VgpCensusTreeSize,
200 VgpUpdateXCon,
201 VgpCalcSpacetime2,
202 VgpPrintHp,
203 VgpPrintXPts,
204 }
njn4be0a692004-11-22 18:10:36 +0000205 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000206
207/*------------------------------------------------------------*/
208/*--- Statistics ---*/
209/*------------------------------------------------------------*/
210
211// Konqueror startup, to give an idea of the numbers involved with a biggish
212// program, with default depth:
213//
214// depth=3 depth=40
215// - 310,000 allocations
216// - 300,000 frees
217// - 15,000 XPts 800,000 XPts
218// - 1,800 top-XPts
219
220static UInt n_xpts = 0;
221static UInt n_bot_xpts = 0;
222static UInt n_allocs = 0;
223static UInt n_zero_allocs = 0;
224static UInt n_frees = 0;
225static UInt n_children_reallocs = 0;
226static UInt n_snapshot_frees = 0;
227
228static UInt n_halvings = 0;
229static UInt n_real_censi = 0;
230static UInt n_fake_censi = 0;
231static UInt n_attempted_censi = 0;
232
233/*------------------------------------------------------------*/
234/*--- Globals ---*/
235/*------------------------------------------------------------*/
236
237#define FILENAME_LEN 256
238
239#define SPRINTF(zz_buf, fmt, args...) \
240 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
241 VG_(write)(fd, (void*)zz_buf, len); \
242 } while (0)
243
244#define BUF_LEN 1024 // general purpose
245static Char buf [BUF_LEN];
246static Char buf2[BUF_LEN];
247static Char buf3[BUF_LEN];
248
nethercote8b5f40c2004-11-02 13:29:50 +0000249static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000250
251static VgHashTable malloc_list = NULL; // HP_Chunks
252
253static UInt n_heap_blocks = 0;
254
njn51d827b2005-05-09 01:02:08 +0000255// Current directory at startup.
256static Char* base_dir;
nethercotec9f36922004-02-14 16:40:02 +0000257
258#define MAX_ALLOC_FNS 32 // includes the builtin ones
259
nethercotec7469182004-05-11 09:21:08 +0000260// First few filled in, rest should be zeroed. Zero-terminated vector.
261static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000262static Char* alloc_fns[MAX_ALLOC_FNS] = {
263 "malloc",
264 "operator new(unsigned)",
265 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000266 "operator new(unsigned, std::nothrow_t const&)",
267 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000268 "__builtin_new",
269 "__builtin_vec_new",
270 "calloc",
271 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000272 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000273};
274
275
276/*------------------------------------------------------------*/
277/*--- Command line args ---*/
278/*------------------------------------------------------------*/
279
280#define MAX_DEPTH 50
281
282typedef
283 enum {
284 XText, XHTML,
285 }
286 XFormat;
287
288static Bool clo_heap = True;
289static UInt clo_heap_admin = 8;
290static Bool clo_stacks = True;
291static Bool clo_depth = 3;
292static XFormat clo_format = XText;
293
njn51d827b2005-05-09 01:02:08 +0000294static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000295{
njn45270a22005-03-27 01:00:11 +0000296 VG_BOOL_CLO(arg, "--heap", clo_heap)
297 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000298
njn45270a22005-03-27 01:00:11 +0000299 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
300 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000301
302 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
303 alloc_fns[n_alloc_fns] = & arg[11];
304 n_alloc_fns++;
305 if (n_alloc_fns >= MAX_ALLOC_FNS) {
306 VG_(printf)("Too many alloc functions specified, sorry");
307 VG_(bad_option)(arg);
308 }
309 }
310
311 else if (VG_CLO_STREQ(arg, "--format=text"))
312 clo_format = XText;
313 else if (VG_CLO_STREQ(arg, "--format=html"))
314 clo_format = XHTML;
315
316 else
317 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000318
nethercotec9f36922004-02-14 16:40:02 +0000319 return True;
320}
321
njn51d827b2005-05-09 01:02:08 +0000322static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000323{
324 VG_(printf)(
325" --heap=no|yes profile heap blocks [yes]\n"
326" --heap-admin=<number> average admin bytes per heap block [8]\n"
327" --stacks=no|yes profile stack(s) [yes]\n"
328" --depth=<number> depth of contexts [3]\n"
329" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
330" --format=text|html format of textual output [text]\n"
331 );
332 VG_(replacement_malloc_print_usage)();
333}
334
njn51d827b2005-05-09 01:02:08 +0000335static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000336{
337 VG_(replacement_malloc_print_debug_usage)();
338}
339
340/*------------------------------------------------------------*/
341/*--- Execution contexts ---*/
342/*------------------------------------------------------------*/
343
344// Fake XPt representing all allocation functions like malloc(). Acts as
345// parent node to all top-XPts.
346static XPt* alloc_xpt;
347
348// Cheap allocation for blocks that never need to be freed. Saves about 10%
349// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000350static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000351{
352 static Addr hp = 0; // current heap pointer
353 static Addr hp_lim = 0; // maximum usable byte in current block
354
355 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
356
357 if (hp + n_bytes > hp_lim) {
358 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
359 hp_lim = hp + SUPERBLOCK_SIZE - 1;
360 }
361
362 hp += n_bytes;
363
364 return (void*)(hp - n_bytes);
365}
366
367
368
njnd01fef72005-03-25 23:35:48 +0000369static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000370{
371 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000372 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000373
nethercote43a15ce2004-08-30 19:15:12 +0000374 xpt->curr_space = 0;
375 xpt->approx_ST = 0;
376 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000377
378 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000379
380 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000381 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000382
383 xpt->n_children = 0;
384
385 // If a bottom-XPt, don't allocate space for children. This can be 50%
386 // or more, although it tends to drop as --depth increases (eg. 10% for
387 // konqueror with --depth=20).
388 if ( is_bottom ) {
389 xpt->max_children = 0;
390 xpt->children = NULL;
391 n_bot_xpts++;
392 } else {
393 xpt->max_children = 4;
394 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
395 }
396
397 // Update statistics
398 n_xpts++;
399
400 return xpt;
401}
402
njnd01fef72005-03-25 23:35:48 +0000403static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000404{
405 Int i;
406
njnd01fef72005-03-25 23:35:48 +0000407 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000408 for (i = 0; i < n_alloc_fns; i++) {
409 if (VG_STREQ(buf, alloc_fns[i]))
410 return True;
411 }
412 }
413 return False;
414}
415
416// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
417// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
418// to ensure this in certain cases. See comments below.
419static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
420{
njnd01fef72005-03-25 23:35:48 +0000421 // Static to minimise stack size. +1 for added ~0 IP
422 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000423
424 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000425 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000426 UInt overestimate;
427 Bool reached_bottom;
428
429 VGP_PUSHCC(VgpGetXPt);
430
431 // Want at least clo_depth non-alloc-fn entries in the snapshot.
432 // However, because we have 1 or more (an unknown number, at this point)
433 // alloc-fns ignored, we overestimate the size needed for the stack
434 // snapshot. Then, if necessary, we repeatedly increase the size until
435 // it is enough.
436 overestimate = 2;
437 while (True) {
njnd01fef72005-03-25 23:35:48 +0000438 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000439
njnd01fef72005-03-25 23:35:48 +0000440 // Now we add a dummy "unknown" IP at the end. This is only used if we
441 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000442 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
443 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000444 // the parent's approx_ST wouldn't be equal [or almost equal] to the
445 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000446 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000447
njnd01fef72005-03-25 23:35:48 +0000448 // Skip over alloc functions in ips[].
449 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000450
451 // Must be at least one alloc function, unless client used
452 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000453 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000454
455 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000456 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000457 overestimate += 2;
458 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000459 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000460 } else {
461 break;
462 }
463 }
464 A = L;
njnd01fef72005-03-25 23:35:48 +0000465 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000466 reached_bottom = False;
467
njnd01fef72005-03-25 23:35:48 +0000468 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000469
470 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000471 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000472 while (True) {
njnd01fef72005-03-25 23:35:48 +0000473 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000474 // XXX: linear search, ugh -- about 10% of time for konqueror startup
475 // XXX: tried cacheing last result, only hit about 4% for konqueror
476 // Nb: this search hits about 98% of the time for konqueror
477 VGP_PUSHCC(VgpGetXPtSearch);
478
479 // If we've searched/added deep enough, or run out of EIPs, this is
480 // the bottom XPt.
481 if (L - A + 1 == clo_depth || L == B)
482 reached_bottom = True;
483
484 nC = 0;
485 while (True) {
486 if (nC == xpt->n_children) {
487 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000488 tl_assert(xpt->max_children != 0);
489 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000490 // Expand 'children' if necessary
491 if (xpt->n_children == xpt->max_children) {
492 xpt->max_children *= 2;
493 xpt->children = VG_(realloc)( xpt->children,
494 xpt->max_children * sizeof(XPt*) );
495 n_children_reallocs++;
496 }
njnd01fef72005-03-25 23:35:48 +0000497 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000498 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000499 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000500 break;
501 }
njnd01fef72005-03-25 23:35:48 +0000502 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000503 nC++; // keep looking
504 }
505 VGP_POPCC(VgpGetXPtSearch);
506
507 // Return found/built bottom-XPt.
508 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000509 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000510 VGP_POPCC(VgpGetXPt);
511 return xpt->children[nC];
512 }
513
514 // Descend to next level in XTree, the newly found/built non-bottom-XPt
515 xpt = xpt->children[nC];
516 L++;
517 }
518}
519
520// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
521static void update_XCon(XPt* xpt, Int space_delta)
522{
523 VGP_PUSHCC(VgpUpdateXCon);
524
njnca82cc02004-11-22 17:18:48 +0000525 tl_assert(True == clo_heap);
526 tl_assert(0 != space_delta);
527 tl_assert(NULL != xpt);
528 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000529
530 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000531 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000532 xpt->curr_space += space_delta;
533 xpt = xpt->parent;
534 }
njnca82cc02004-11-22 17:18:48 +0000535 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000536 alloc_xpt->curr_space += space_delta;
537
538 VGP_POPCC(VgpUpdateXCon);
539}
540
541// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000542static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000543{
544 XPt* xpt1 = *(XPt**)n1;
545 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000546 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000547}
548
nethercote43a15ce2004-08-30 19:15:12 +0000549static Int XPt_cmp_exact_ST_dbld(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->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000554}
555
556
557/*------------------------------------------------------------*/
558/*--- A generic Queue ---*/
559/*------------------------------------------------------------*/
560
561typedef
562 struct {
563 UInt head; // Index of first entry
564 UInt tail; // Index of final+1 entry, ie. next free slot
565 UInt max_elems;
566 void** elems;
567 }
568 Queue;
569
570static Queue* construct_queue(UInt size)
571{
572 UInt i;
573 Queue* q = VG_(malloc)(sizeof(Queue));
574 q->head = 0;
575 q->tail = 0;
576 q->max_elems = size;
577 q->elems = VG_(malloc)(size * sizeof(void*));
578 for (i = 0; i < size; i++)
579 q->elems[i] = NULL;
580
581 return q;
582}
583
584static void destruct_queue(Queue* q)
585{
586 VG_(free)(q->elems);
587 VG_(free)(q);
588}
589
590static void shuffle(Queue* dest_q, void** old_elems)
591{
592 UInt i, j;
593 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
594 dest_q->elems[i] = old_elems[j];
595 dest_q->head = 0;
596 dest_q->tail = i;
597 for ( ; i < dest_q->max_elems; i++)
598 dest_q->elems[i] = NULL; // paranoia
599}
600
601// Shuffles elements down. If not enough slots free, increase size. (We
602// don't wait until we've completely run out of space, because there could
603// be lots of shuffling just before that point which would be slow.)
604static void adjust(Queue* q)
605{
606 void** old_elems;
607
njnca82cc02004-11-22 17:18:48 +0000608 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000609 if (q->head < 10) {
610 old_elems = q->elems;
611 q->max_elems *= 2;
612 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
613 shuffle(q, old_elems);
614 VG_(free)(old_elems);
615 } else {
616 shuffle(q, q->elems);
617 }
618}
619
620static void enqueue(Queue* q, void* elem)
621{
622 if (q->tail == q->max_elems)
623 adjust(q);
624 q->elems[q->tail++] = elem;
625}
626
627static Bool is_empty_queue(Queue* q)
628{
629 return (q->head == q->tail);
630}
631
632static void* dequeue(Queue* q)
633{
634 if (is_empty_queue(q))
635 return NULL; // Queue empty
636 else
637 return q->elems[q->head++];
638}
639
640/*------------------------------------------------------------*/
641/*--- malloc() et al replacement wrappers ---*/
642/*------------------------------------------------------------*/
643
644static __inline__
645void add_HP_Chunk(HP_Chunk* hc)
646{
647 n_heap_blocks++;
648 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
649}
650
651static __inline__
652HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
653{
nethercote3d6b6112004-11-04 16:39:43 +0000654 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000655 (VgHashNode***)prev_chunks_next_ptr );
656}
657
658static __inline__
659void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
660{
njnca82cc02004-11-22 17:18:48 +0000661 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000662 n_heap_blocks--;
663 *prev_chunks_next_ptr = hc->next;
664}
665
666// Forward declaration
667static void hp_census(void);
668
nethercote159dfef2004-09-13 13:27:30 +0000669static
njn57735902004-11-25 18:04:54 +0000670void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
671 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000672{
673 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000674 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000675 if (size < 0) return NULL;
676
677 VGP_PUSHCC(VgpCliMalloc);
678
679 // Update statistics
680 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000681 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000682
nethercote57e36b32004-07-10 14:56:28 +0000683 // Allocate and zero if necessary
684 if (!p) {
685 p = VG_(cli_malloc)( align, size );
686 if (!p) {
687 VGP_POPCC(VgpCliMalloc);
688 return NULL;
689 }
690 if (is_zeroed) VG_(memset)(p, 0, size);
691 }
692
693 // Make new HP_Chunk node, add to malloclist
694 hc = VG_(malloc)(sizeof(HP_Chunk));
695 hc->size = size;
696 hc->data = (Addr)p;
697 hc->where = NULL; // paranoia
698 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000699 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000700 if (0 != size)
701 update_XCon(hc->where, size);
702 }
703 add_HP_Chunk( hc );
704
705 // do a census!
706 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000707
708 VGP_POPCC(VgpCliMalloc);
709 return p;
710}
711
712static __inline__
713void die_block ( void* p, Bool custom_free )
714{
nethercote57e36b32004-07-10 14:56:28 +0000715 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000716
717 VGP_PUSHCC(VgpCliMalloc);
718
719 // Update statistics
720 n_frees++;
721
nethercote57e36b32004-07-10 14:56:28 +0000722 // Remove HP_Chunk from malloclist
723 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000724 if (hc == NULL)
725 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000726 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000727 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000728
729 if (clo_heap && hc->size != 0)
730 update_XCon(hc->where, -hc->size);
731
nethercote57e36b32004-07-10 14:56:28 +0000732 VG_(free)( hc );
733
734 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000735 if (!custom_free)
736 VG_(cli_free)( p );
737
nethercote57e36b32004-07-10 14:56:28 +0000738 // do a census!
739 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000740
nethercotec9f36922004-02-14 16:40:02 +0000741 VGP_POPCC(VgpCliMalloc);
742}
743
744
njn51d827b2005-05-09 01:02:08 +0000745static void* ms_malloc ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000746{
njn57735902004-11-25 18:04:54 +0000747 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000748}
749
njn51d827b2005-05-09 01:02:08 +0000750static void* ms___builtin_new ( 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_vec_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_calloc ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000761{
njn57735902004-11-25 18:04:54 +0000762 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000763}
764
njn51d827b2005-05-09 01:02:08 +0000765static void *ms_memalign ( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000766{
njn57735902004-11-25 18:04:54 +0000767 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000768}
769
njn51d827b2005-05-09 01:02:08 +0000770static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000771{
772 die_block( p, /*custom_free*/False );
773}
774
njn51d827b2005-05-09 01:02:08 +0000775static void ms___builtin_delete ( 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_vec_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_realloc ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000786{
787 HP_Chunk* hc;
788 HP_Chunk** remove_handle;
789 Int i;
790 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000791 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000792 XPt *old_where, *new_where;
793
794 VGP_PUSHCC(VgpCliMalloc);
795
796 // First try and find the block.
797 hc = get_HP_Chunk ( p_old, &remove_handle );
798 if (hc == NULL) {
799 VGP_POPCC(VgpCliMalloc);
800 return NULL; // must have been a bogus free()
801 }
802
njnca82cc02004-11-22 17:18:48 +0000803 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000804 old_size = hc->size;
805
806 if (new_size <= old_size) {
807 // new size is smaller or same; block not moved
808 p_new = p_old;
809
810 } else {
811 // new size is bigger; make new block, copy shared contents, free old
812 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
813
814 for (i = 0; i < old_size; i++)
815 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
816
817 VG_(cli_free)(p_old);
818 }
819
820 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000821 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000822
823 // Update HP_Chunk
824 hc->data = (Addr)p_new;
825 hc->size = new_size;
826 hc->where = new_where;
827
828 // Update XPt curr_space fields
829 if (clo_heap) {
830 if (0 != old_size) update_XCon(old_where, -old_size);
831 if (0 != new_size) update_XCon(new_where, new_size);
832 }
833
834 // If block has moved, have to remove and reinsert in the malloclist
835 // (since the updated 'data' field is the hash lookup key).
836 if (p_new != p_old) {
837 remove_HP_Chunk(hc, remove_handle);
838 add_HP_Chunk(hc);
839 }
840
841 VGP_POPCC(VgpCliMalloc);
842 return p_new;
843}
844
845
846/*------------------------------------------------------------*/
847/*--- Taking a census ---*/
848/*------------------------------------------------------------*/
849
850static Census censi[MAX_N_CENSI];
851static UInt curr_census = 0;
852
853// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000854static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000855{
thughes4ad52d02004-06-27 17:37:21 +0000856 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000857 return False;
858}
859
860static UInt get_xtree_size(XPt* xpt, UInt ix)
861{
862 UInt i;
863
nethercote43a15ce2004-08-30 19:15:12 +0000864 // If no memory allocated at all, nothing interesting to record.
865 if (alloc_xpt->curr_space == 0) return 0;
866
867 // Ignore sub-XTrees that account for a miniscule fraction of current
868 // allocated space.
869 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000870 ix++;
871
872 // Count all (non-zero) descendent XPts
873 for (i = 0; i < xpt->n_children; i++)
874 ix = get_xtree_size(xpt->children[i], ix);
875 }
876 return ix;
877}
878
879static
880UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
881{
882 UInt i;
883
nethercote43a15ce2004-08-30 19:15:12 +0000884 // Structure of this function mirrors that of get_xtree_size().
885
886 if (alloc_xpt->curr_space == 0) return 0;
887
888 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000889 xtree_snapshot[ix].xpt = xpt;
890 xtree_snapshot[ix].space = xpt->curr_space;
891 ix++;
892
nethercotec9f36922004-02-14 16:40:02 +0000893 for (i = 0; i < xpt->n_children; i++)
894 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
895 }
896 return ix;
897}
898
899static UInt ms_interval;
900static UInt do_every_nth_census = 30;
901
902// Weed out half the censi; we choose those that represent the smallest
903// time-spans, because that loses the least information.
904//
905// Algorithm for N censi: We find the census representing the smallest
906// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
907// (It's (N/2)-1 because we never remove the first and last censi.)
908// We have to do this one census at a time, rather than finding the (N/2)-1
909// smallest censi in one hit, because when a census is removed, it's
910// neighbours immediately cover greater timespans. So it's N^2, but N only
911// equals 200, and this is only done every 100 censi, which is not too often.
912static void halve_censi(void)
913{
914 Int i, jp, j, jn, k;
915 Census* min_census;
916
917 n_halvings++;
918 if (VG_(clo_verbosity) > 1)
919 VG_(message)(Vg_UserMsg, "Halving censi...");
920
921 // Sets j to the index of the first not-yet-removed census at or after i
922 #define FIND_CENSUS(i, j) \
923 for (j = i; -1 == censi[j].ms_time; j++) { }
924
925 for (i = 2; i < MAX_N_CENSI; i += 2) {
926 // Find the censi representing the smallest timespan. The timespan
927 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
928 // censi A and B. We don't consider the first and last censi for
929 // removal.
930 Int min_span = 0x7fffffff;
931 Int min_j = 0;
932
933 // Initial triple: (prev, curr, next) == (jp, j, jn)
934 jp = 0;
935 FIND_CENSUS(1, j);
936 FIND_CENSUS(j+1, jn);
937 while (jn < MAX_N_CENSI) {
938 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000939 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000940 if (timespan < min_span) {
941 min_span = timespan;
942 min_j = j;
943 }
944 // Move on to next triple
945 jp = j;
946 j = jn;
947 FIND_CENSUS(jn+1, jn);
948 }
949 // We've found the least important census, now remove it
950 min_census = & censi[ min_j ];
951 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
952 n_snapshot_frees++;
953 VG_(free)(min_census->xtree_snapshots[k]);
954 min_census->xtree_snapshots[k] = NULL;
955 }
956 min_census->ms_time = -1;
957 }
958
959 // Slide down the remaining censi over the removed ones. The '<=' is
960 // because we are removing on (N/2)-1, rather than N/2.
961 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
962 FIND_CENSUS(j, j);
963 if (i != j) {
964 censi[i] = censi[j];
965 }
966 }
967 curr_census = i;
968
969 // Double intervals
970 ms_interval *= 2;
971 do_every_nth_census *= 2;
972
973 if (VG_(clo_verbosity) > 1)
974 VG_(message)(Vg_UserMsg, "...done");
975}
976
977// Take a census. Census time seems to be insignificant (usually <= 0 ms,
978// almost always <= 1ms) so don't have to worry about subtracting it from
979// running time in any way.
980//
981// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
982// 50ms!
983static void hp_census(void)
984{
985 static UInt ms_prev_census = 0;
986 static UInt ms_next_census = 0; // zero allows startup census
987
988 Int ms_time, ms_time_since_prev;
989 Int i, K;
990 Census* census;
991
992 VGP_PUSHCC(VgpCensus);
993
994 // Only do a census if it's time
995 ms_time = VG_(read_millisecond_timer)();
996 ms_time_since_prev = ms_time - ms_prev_census;
997 if (ms_time < ms_next_census) {
998 n_fake_censi++;
999 VGP_POPCC(VgpCensus);
1000 return;
1001 }
1002 n_real_censi++;
1003
1004 census = & censi[curr_census];
1005
1006 census->ms_time = ms_time;
1007
1008 // Heap: snapshot the K most significant XTrees -------------------
1009 if (clo_heap) {
1010 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1011 ? alloc_xpt->n_children
1012 : MAX_SNAPSHOTS); // max out
1013
nethercote43a15ce2004-08-30 19:15:12 +00001014 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001015 // We *do not* do it for any non-top-XPTs.
1016 for (i = 0; i < alloc_xpt->n_children; i++) {
1017 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001018 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001019 }
nethercote43a15ce2004-08-30 19:15:12 +00001020 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001021 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001022 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001023
1024 VGP_PUSHCC(VgpCensusHeap);
1025
1026 // For each significant top-level XPt, record space info about its
1027 // entire XTree, in a single census entry.
1028 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1029 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001030 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001031 for (i = 0; i < K; i++) {
1032 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001033// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1034 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001035 VGP_PUSHCC(VgpCensusTreeSize);
1036 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1037 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001038
1039 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1040 // insignificant) then don't take any more snapshots.
1041 if (0 == xtree_size) break;
1042
1043 // Make array of the appropriate size (+1 for zero termination,
1044 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001045 census->xtree_snapshots[i] =
1046 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001047 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001048 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1049 (xtree_size+1) * sizeof(XPtSnapshot));
1050
1051 // Take space-snapshot: copy 'curr_space' for every XPt in the
1052 // XTree into the snapshot array, along with pointers to the XPts.
1053 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001054 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001055 // saves a lot of memory and up to 40% time with big --depth valus.
1056 VGP_PUSHCC(VgpCensusSnapshot);
1057 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1058 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001059 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001060 VGP_POPCC(VgpCensusSnapshot);
1061 }
1062// VG_(printf)("\n\n");
1063 // Zero-terminate 'xtree_snapshot' array
1064 census->xtree_snapshots[i] = NULL;
1065
1066 VGP_POPCC(VgpCensusHeap);
1067
1068 //VG_(printf)("printed %d censi\n", K);
1069
1070 // Lump the rest into a single "others" entry.
1071 census->others_space = 0;
1072 for (i = K; i < alloc_xpt->n_children; i++) {
1073 census->others_space += alloc_xpt->children[i]->curr_space;
1074 }
1075 }
1076
1077 // Heap admin -------------------------------------------------------
1078 if (clo_heap_admin > 0)
1079 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1080
1081 // Stack(s) ---------------------------------------------------------
1082 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001083 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001084 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001085 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001086 i++;
1087 }
1088
1089 // Finish, update interval if necessary -----------------------------
1090 curr_census++;
1091 census = NULL; // don't use again now that curr_census changed
1092
1093 // Halve the entries, if our census table is full
1094 if (MAX_N_CENSI == curr_census) {
1095 halve_censi();
1096 }
1097
1098 // Take time for next census from now, rather than when this census
1099 // should have happened. Because, if there's a big gap due to a kernel
1100 // operation, there's no point doing catch-up censi every BB for a while
1101 // -- that would just give N censi at almost the same time.
1102 if (VG_(clo_verbosity) > 1) {
1103 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1104 VG_(read_millisecond_timer)() - ms_time );
1105 }
1106 ms_prev_census = ms_time;
1107 ms_next_census = ms_time + ms_interval;
1108 //ms_next_census += ms_interval;
1109
1110 //VG_(printf)("Next: %d ms\n", ms_next_census);
1111
1112 VGP_POPCC(VgpCensus);
1113}
1114
1115/*------------------------------------------------------------*/
1116/*--- Tracked events ---*/
1117/*------------------------------------------------------------*/
1118
nethercote8b5f40c2004-11-02 13:29:50 +00001119static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001120{
1121 sigstacks_space += len;
1122}
1123
nethercote8b5f40c2004-11-02 13:29:50 +00001124static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001125{
njnca82cc02004-11-22 17:18:48 +00001126 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001127 sigstacks_space -= len;
1128}
1129
1130/*------------------------------------------------------------*/
1131/*--- Client Requests ---*/
1132/*------------------------------------------------------------*/
1133
njn51d827b2005-05-09 01:02:08 +00001134static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001135{
1136 switch (argv[0]) {
1137 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001138 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001139 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001140 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001141 *ret = 0;
njn57735902004-11-25 18:04:54 +00001142 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001143 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001144 return True;
1145 }
1146 case VG_USERREQ__FREELIKE_BLOCK: {
1147 void* p = (void*)argv[1];
1148 *ret = 0;
1149 die_block( p, /*custom_free*/True );
1150 return True;
1151 }
1152 default:
1153 *ret = 0;
1154 return False;
1155 }
1156}
1157
1158/*------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00001159/*--- Instrumentation ---*/
1160/*------------------------------------------------------------*/
1161
njn51d827b2005-05-09 01:02:08 +00001162static IRBB* ms_instrument ( IRBB* bb_in, VexGuestLayout* layout,
1163 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001164{
sewardjd54babf2005-03-21 00:55:49 +00001165 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001166 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001167}
1168
1169/*------------------------------------------------------------*/
1170/*--- Spacetime recomputation ---*/
1171/*------------------------------------------------------------*/
1172
nethercote43a15ce2004-08-30 19:15:12 +00001173// Although we've been calculating space-time along the way, because the
1174// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001175// might not agree with what hp2ps sees, because we've thrown away some of
1176// the information. So recompute it at the scale that hp2ps sees, so we can
1177// confidently determine which contexts hp2ps will choose for displaying as
1178// distinct bands. This recomputation only happens to the significant ones
1179// that get printed in the .hp file, so it's cheap.
1180//
nethercote43a15ce2004-08-30 19:15:12 +00001181// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001182// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1183// where
1184// a[N] is the space at census N
1185// d(A,B) is the time interval between censi A and B
1186// and
1187// d(A,B) + d(B,C) == d(A,C)
1188//
1189// Key point: we can calculate the area for a census without knowing the
1190// previous or subsequent censi's space; because any over/underestimates
1191// for this census will be reversed in the next, balancing out. This is
1192// important, as getting the previous/next census entry for a particular
1193// AP is a pain with this data structure, but getting the prev/next
1194// census time is easy.
1195//
nethercote43a15ce2004-08-30 19:15:12 +00001196// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001197// The ULong* values are all running totals, hence the use of "+=" everywhere.
1198
1199// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001200static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001201 ULong* twice_heap_ST,
1202 ULong* twice_heap_admin_ST,
1203 ULong* twice_stack_ST)
1204{
1205 UInt i, j;
1206 XPtSnapshot* xpt_snapshot;
1207
1208 // Heap --------------------------------------------------------
1209 if (clo_heap) {
1210 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001211 // Compute total heap exact_ST_dbld for the entire XTree using only
1212 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001213 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1214
nethercote43a15ce2004-08-30 19:15:12 +00001215 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1216 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001217 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1218 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001219 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001220 }
1221 }
1222 *twice_heap_ST += d_t1_t2 * census->others_space;
1223 }
1224
1225 // Heap admin --------------------------------------------------
1226 if (clo_heap_admin > 0)
1227 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1228
1229 // Stack(s) ----------------------------------------------------
1230 if (clo_stacks)
1231 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1232}
1233
1234// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001235static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001236{
1237 UInt i, N = curr_census;
1238
1239 VGP_PUSHCC(VgpCalcSpacetime2);
1240
1241 *heap2 = 0;
1242 *heap_admin2 = 0;
1243 *stack2 = 0;
1244
1245 if (N <= 1)
1246 return;
1247
nethercote43a15ce2004-08-30 19:15:12 +00001248 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1249 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001250
1251 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001252 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1253 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001254 }
1255
nethercote43a15ce2004-08-30 19:15:12 +00001256 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1257 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001258 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1259 *heap2 /= 2;
1260 *heap_admin2 /= 2;
1261 *stack2 /= 2;
1262
1263 VGP_POPCC(VgpCalcSpacetime2);
1264}
1265
1266/*------------------------------------------------------------*/
1267/*--- Writing the graph file ---*/
1268/*------------------------------------------------------------*/
1269
1270static Char* make_filename(Char* dir, Char* suffix)
1271{
1272 Char* filename;
1273
1274 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1275 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1276 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1277
1278 return filename;
1279}
1280
1281// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1282static Char* clean_fnname(Char *d, Char* s)
1283{
1284 Char* dorig = d;
1285 while (*s) {
1286 if (' ' == *s) { *d = '%'; }
1287 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1288 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1289 else { *d = *s; };
1290 s++;
1291 d++;
1292 }
1293 *d = '\0';
1294 return dorig;
1295}
1296
1297static void file_err ( Char* file )
1298{
1299 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1300 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1301}
1302
1303/* Format, by example:
1304
1305 JOB "a.out -p"
1306 DATE "Fri Apr 17 11:43:45 1992"
1307 SAMPLE_UNIT "seconds"
1308 VALUE_UNIT "bytes"
1309 BEGIN_SAMPLE 0.00
1310 SYSTEM 24
1311 END_SAMPLE 0.00
1312 BEGIN_SAMPLE 1.00
1313 elim 180
1314 insert 24
1315 intersect 12
1316 disin 60
1317 main 12
1318 reduce 20
1319 SYSTEM 12
1320 END_SAMPLE 1.00
1321 MARK 1.50
1322 MARK 1.75
1323 MARK 1.80
1324 BEGIN_SAMPLE 2.00
1325 elim 192
1326 insert 24
1327 intersect 12
1328 disin 84
1329 main 12
1330 SYSTEM 24
1331 END_SAMPLE 2.00
1332 BEGIN_SAMPLE 2.82
1333 END_SAMPLE 2.82
1334 */
1335static void write_hp_file(void)
1336{
1337 Int i, j;
1338 Int fd, res;
1339 Char *hp_file, *ps_file, *aux_file;
1340 Char* cmdfmt;
1341 Char* cmdbuf;
1342 Int cmdlen;
1343
1344 VGP_PUSHCC(VgpPrintHp);
1345
1346 // Open file
1347 hp_file = make_filename( base_dir, ".hp" );
1348 ps_file = make_filename( base_dir, ".ps" );
1349 aux_file = make_filename( base_dir, ".aux" );
1350 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1351 VKI_S_IRUSR|VKI_S_IWUSR);
1352 if (fd < 0) {
1353 file_err( hp_file );
1354 VGP_POPCC(VgpPrintHp);
1355 return;
1356 }
1357
1358 // File header, including command line
1359 SPRINTF(buf, "JOB \"");
1360 for (i = 0; i < VG_(client_argc); i++)
1361 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1362 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1363 "DATE \"\"\n"
1364 "SAMPLE_UNIT \"ms\"\n"
1365 "VALUE_UNIT \"bytes\"\n", ms_interval);
1366
1367 // Censi
1368 for (i = 0; i < curr_census; i++) {
1369 Census* census = & censi[i];
1370
1371 // Census start
1372 SPRINTF(buf, "MARK %d.0\n"
1373 "BEGIN_SAMPLE %d.0\n",
1374 census->ms_time, census->ms_time);
1375
1376 // Heap -----------------------------------------------------------
1377 if (clo_heap) {
1378 // Print all the significant XPts from that census
1379 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1380 // Grab the jth top-XPt
1381 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001382 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001383 VG_(sprintf)(buf2, "???");
1384 }
njnd01fef72005-03-25 23:35:48 +00001385 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001386 clean_fnname(buf3, buf2), xtree_snapshot->space);
1387 }
1388
1389 // Remaining heap block alloc points, combined
1390 if (census->others_space > 0)
1391 SPRINTF(buf, "other %d\n", census->others_space);
1392 }
1393
1394 // Heap admin -----------------------------------------------------
1395 if (clo_heap_admin > 0 && census->heap_admin_space)
1396 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1397
1398 // Stack(s) -------------------------------------------------------
1399 if (clo_stacks)
1400 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1401
1402 // Census end
1403 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1404 }
1405
1406 // Close file
njnca82cc02004-11-22 17:18:48 +00001407 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001408 VG_(close)(fd);
1409
1410 // Attempt to convert file using hp2ps
1411 cmdfmt = "%s/hp2ps -c -t1 %s";
1412 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1413 + VG_(strlen)(cmdfmt);
1414 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1415 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1416 res = VG_(system)(cmdbuf);
1417 VG_(free)(cmdbuf);
1418 if (res != 0) {
1419 VG_(message)(Vg_UserMsg,
1420 "Conversion to PostScript failed. Try converting manually.");
1421 } else {
1422 // remove the .hp and .aux file
1423 VG_(unlink)(hp_file);
1424 VG_(unlink)(aux_file);
1425 }
1426
1427 VG_(free)(hp_file);
1428 VG_(free)(ps_file);
1429 VG_(free)(aux_file);
1430
1431 VGP_POPCC(VgpPrintHp);
1432}
1433
1434/*------------------------------------------------------------*/
1435/*--- Writing the XPt text/HTML file ---*/
1436/*------------------------------------------------------------*/
1437
1438static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1439{
1440 int i, len, space;
1441
1442 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1443 len = VG_(strlen)(xbuf);
1444 space = field_width - len;
1445 if (space < 0) space = 0; /* Allow for v. small field_width */
1446 i = len;
1447
1448 /* Right justify in field */
1449 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1450 for (i = 0; i < space; i++) xbuf[i] = ' ';
1451}
1452
1453// Nb: uses a static buffer, each call trashes the last string returned.
1454static Char* make_perc(ULong spacetime, ULong total_spacetime)
1455{
1456 static Char mbuf[32];
1457
1458 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001459 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001460 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1461 return mbuf;
1462}
1463
njnd01fef72005-03-25 23:35:48 +00001464// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001465// bottom-to-top of XCon, and then printed in the reverse order.
1466static UInt pp_XCon(Int fd, XPt* xpt)
1467{
njnd01fef72005-03-25 23:35:48 +00001468 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001469 Int i = 0;
1470 Int n = 0;
1471 Bool is_HTML = ( XHTML == clo_format );
1472 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1473 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1474
njnca82cc02004-11-22 17:18:48 +00001475 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001476
1477 while (True) {
njnd01fef72005-03-25 23:35:48 +00001478 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001479 n++;
1480 if (alloc_xpt == xpt->parent) break;
1481 i++;
1482 xpt = xpt->parent;
1483 }
1484
1485 for (i = n-1; i >= 0; i--) {
1486 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001487 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001488 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1489 }
1490
1491 return n;
1492}
1493
1494// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001495// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001496// sufficient, because function pointers mean that you can call more than
1497// one other function from a single code location. So instead we use the
1498// address of the xpt struct itself, which is guaranteed to be unique.
1499
1500static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1501 ULong total_spacetime)
1502{
1503 UInt i;
1504 XPt *xpt, *child;
1505 UInt L = 0;
1506 UInt c1 = 1;
1507 UInt c2 = 0;
1508 ULong sum = 0;
1509 UInt n;
njnd01fef72005-03-25 23:35:48 +00001510 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001511 Bool is_HTML = ( XHTML == clo_format );
1512 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1513 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1514 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1515 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1516 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1517 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1518 Char* end_hr = ( is_HTML ? "<hr>" :
1519 "=================================" );
1520 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1521
nethercote43a15ce2004-08-30 19:15:12 +00001522 if (total_spacetime == 0) {
1523 SPRINTF(buf, "(No heap memory allocated)\n");
1524 return;
1525 }
1526
1527
nethercotec9f36922004-02-14 16:40:02 +00001528 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1529
1530 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001531 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001532 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001533
nethercote43a15ce2004-08-30 19:15:12 +00001534 // Check that the sum of all children .exact_ST_dbld fields equals
1535 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001536 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001537 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001538 } else {
1539 sum = 0;
1540 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001541 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001542 }
njnca82cc02004-11-22 17:18:48 +00001543 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001544 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001545 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001546 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001547// tl_assert(sum <= xpt->exact_ST_dbld);
1548// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001549// if (sum != xpt->exact_ST_dbld) {
1550// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001551// }
1552 }
1553
1554 if (xpt == alloc_xpt) {
1555 SPRINTF(buf, "Heap allocation functions accounted for "
1556 "%s of measured spacetime%s\n",
1557 make_perc(heap_spacetime, total_spacetime), maybe_br);
1558 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001559 // Remember: exact_ST_dbld is space.time *doubled*
1560 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001561 if (is_HTML) {
1562 SPRINTF(buf, "<a name=\"b%x\"></a>"
1563 "Context accounted for "
1564 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1565 xpt, xpt, perc);
1566 } else {
1567 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1568 perc);
1569 }
1570 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001571 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001572 }
1573
nethercote43a15ce2004-08-30 19:15:12 +00001574 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001575 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001576 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001577
1578 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1579 for (i = 0; i < xpt->n_children; i++) {
1580 child = xpt->children[i];
1581
1582 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001583 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001584 UInt n_insig = xpt->n_children - i;
1585 Char* s = ( n_insig == 1 ? "" : "s" );
1586 Char* and = ( 0 == i ? "" : "and " );
1587 Char* other = ( 0 == i ? "" : "other " );
1588 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1589 maybe_li, and, n_insig, other, s, maybe_fli);
1590 break;
1591 }
1592
nethercote43a15ce2004-08-30 19:15:12 +00001593 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001594 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1595 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001596 if (is_HTML) {
1597 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1598
1599 if (child->n_children > 0) {
1600 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1601 } else {
1602 SPRINTF(buf, "%s", perc);
1603 }
njnd01fef72005-03-25 23:35:48 +00001604 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001605 } else {
njnd01fef72005-03-25 23:35:48 +00001606 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001607 }
1608
1609 if (child->n_children > 0) {
1610 enqueue(q, (void*)child);
1611 c2++;
1612 }
1613 }
1614 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1615 c1--;
1616
1617 // Putting markers between levels of the structure:
1618 // c1 tracks how many to go on this level, c2 tracks how many we've
1619 // queued up for the next level while finishing off this level.
1620 // When c1 gets to zero, we've changed levels, so print a marker,
1621 // move c2 into c1, and zero c2.
1622 if (0 == c1) {
1623 L++;
1624 c1 = c2;
1625 c2 = 0;
1626 if (! is_empty_queue(q) ) { // avoid empty one at end
1627 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1628 }
1629 } else {
1630 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1631 }
1632 }
1633 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1634 "%s value for more.\n", end_hr, depth);
1635}
1636
1637static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1638 ULong total_spacetime)
1639{
1640 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001641
nethercotec9f36922004-02-14 16:40:02 +00001642 enqueue(q, xpt);
1643 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1644 destruct_queue(q);
1645}
1646
1647static void
1648write_text_file(ULong total_ST, ULong heap_ST)
1649{
1650 Int fd, i;
1651 Char* text_file;
1652 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1653
1654 VGP_PUSHCC(VgpPrintXPts);
1655
1656 // Open file
1657 text_file = make_filename( base_dir,
1658 ( XText == clo_format ? ".txt" : ".html" ) );
1659
1660 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1661 VKI_S_IRUSR|VKI_S_IWUSR);
1662 if (fd < 0) {
1663 file_err( text_file );
1664 VGP_POPCC(VgpPrintXPts);
1665 return;
1666 }
1667
1668 // Header
1669 if (XHTML == clo_format) {
1670 SPRINTF(buf, "<html>\n"
1671 "<head>\n"
1672 "<title>%s</title>\n"
1673 "</head>\n"
1674 "<body>\n",
1675 text_file);
1676 }
1677
1678 // Command line
1679 SPRINTF(buf, "Command: ");
1680 for (i = 0; i < VG_(client_argc); i++)
1681 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1682 SPRINTF(buf, "\n%s\n", maybe_p);
1683
1684 if (clo_heap)
1685 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1686
njnca82cc02004-11-22 17:18:48 +00001687 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001688 VG_(close)(fd);
1689
1690 VGP_POPCC(VgpPrintXPts);
1691}
1692
1693/*------------------------------------------------------------*/
1694/*--- Finalisation ---*/
1695/*------------------------------------------------------------*/
1696
1697static void
1698print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1699 ULong stack_ST)
1700{
1701 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1702
1703 // Heap --------------------------------------------------------------
1704 if (clo_heap)
1705 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001706 ( 0 == total_ST ? (Char*)"(n/a)"
1707 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001708
1709 // Heap admin --------------------------------------------------------
1710 if (clo_heap_admin)
1711 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001712 ( 0 == total_ST ? (Char*)"(n/a)"
1713 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001714
njnca82cc02004-11-22 17:18:48 +00001715 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001716
1717 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001718 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001719 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001720 ( 0 == stack_ST ? (Char*)"0%"
1721 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001722 }
nethercotec9f36922004-02-14 16:40:02 +00001723
1724 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001725 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001726 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1727 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1728 n_zero_allocs * 100 / n_allocs );
1729 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1730 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1731 n_xpts*sizeof(XPt));
1732 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1733 n_bot_xpts * 100 / n_xpts);
1734 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1735 alloc_xpt->n_children * 100 / n_xpts);
1736 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1737 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1738 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1739 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1740 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1741 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1742 }
1743}
1744
njn51d827b2005-05-09 01:02:08 +00001745static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001746{
1747 ULong total_ST = 0;
1748 ULong heap_ST = 0;
1749 ULong heap_admin_ST = 0;
1750 ULong stack_ST = 0;
1751
1752 // Do a final (empty) sample to show program's end
1753 hp_census();
1754
1755 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001756 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001757 total_ST = heap_ST + heap_admin_ST + stack_ST;
1758 write_hp_file ( );
1759 write_text_file( total_ST, heap_ST );
1760 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1761}
1762
njn51d827b2005-05-09 01:02:08 +00001763/*------------------------------------------------------------*/
1764/*--- Initialisation ---*/
1765/*------------------------------------------------------------*/
1766
1767static void ms_post_clo_init(void)
1768{
1769 ms_interval = 1;
1770
1771 // Do an initial sample for t = 0
1772 hp_census();
1773}
1774
1775static void ms_pre_clo_init()
1776{
1777 VG_(details_name) ("Massif");
1778 VG_(details_version) (NULL);
1779 VG_(details_description) ("a space profiler");
1780 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
1781 VG_(details_bug_reports_to) (VG_BUGS_TO);
1782
1783 // Basic functions
1784 VG_(basic_tool_funcs) (ms_post_clo_init,
1785 ms_instrument,
1786 ms_fini);
1787
1788 // Needs
1789 VG_(needs_libc_freeres)();
1790 VG_(needs_command_line_options)(ms_process_cmd_line_option,
1791 ms_print_usage,
1792 ms_print_debug_usage);
1793 VG_(needs_client_requests) (ms_handle_client_request);
1794
1795 // Malloc replacement
1796 VG_(malloc_funcs) (ms_malloc,
1797 ms___builtin_new,
1798 ms___builtin_vec_new,
1799 ms_memalign,
1800 ms_calloc,
1801 ms_free,
1802 ms___builtin_delete,
1803 ms___builtin_vec_delete,
1804 ms_realloc,
1805 0 );
1806
1807 // Events to track
1808 VG_(track_new_mem_stack_signal)( new_mem_stack_signal );
1809 VG_(track_die_mem_stack_signal)( die_mem_stack_signal );
1810
1811 // Profiling events
1812 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1813 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1814 VG_(register_profile_event)(VgpCensus, "census");
1815 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1816 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1817 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1818 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1819 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1820 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1821 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
1822
1823 // HP_Chunks
1824 malloc_list = VG_(HT_construct)();
1825
1826 // Dummy node at top of the context structure.
1827 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1828
1829 tl_assert( VG_(getcwd_alloc)(&base_dir) );
1830}
1831
1832VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init, 0)
nethercotec9f36922004-02-14 16:40:02 +00001833
1834/*--------------------------------------------------------------------*/
1835/*--- end ms_main.c ---*/
1836/*--------------------------------------------------------------------*/
1837