blob: 7ac1832099c85f86ff707770020d14db2cebddaa [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
nethercotec9f36922004-02-14 16:40:02 +000011 njn25@cam.ac.uk
12
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"
njnd01fef72005-03-25 23:35:48 +000038#include "pub_tool_stacktrace.h"
nethercotec9f36922004-02-14 16:40:02 +000039//#include "vg_profile.c"
40
41#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
42
43/*------------------------------------------------------------*/
44/*--- Overview of operation ---*/
45/*------------------------------------------------------------*/
46
47// Heap blocks are tracked, and the amount of space allocated by various
48// contexts (ie. lines of code, more or less) is also tracked.
49// Periodically, a census is taken, and the amount of space used, at that
50// point, by the most significant (highly allocating) contexts is recorded.
51// Census start off frequently, but are scaled back as the program goes on,
52// so that there are always a good number of them. At the end, overall
53// spacetimes for different contexts (of differing levels of precision) is
54// calculated, the graph is printed, and the text giving spacetimes for the
55// increasingly precise contexts is given.
56//
57// Measures the following:
58// - heap blocks
59// - heap admin bytes
60// - stack(s)
61// - code (code segments loaded at startup, and loaded with mmap)
62// - data (data segments loaded at startup, and loaded/created with mmap,
63// and brk()d segments)
64
65/*------------------------------------------------------------*/
66/*--- Main types ---*/
67/*------------------------------------------------------------*/
68
69// An XPt represents an "execution point", ie. a code address. Each XPt is
70// part of a tree of XPts (an "execution tree", or "XTree"). Each
71// top-to-bottom path through an XTree gives an execution context ("XCon"),
72// and is equivalent to a traditional Valgrind ExeContext.
73//
74// The XPt at the top of an XTree (but below "alloc_xpt") is called a
75// "top-XPt". The XPts are the bottom of an XTree (leaf nodes) are
76// "bottom-XPTs". The number of XCons in an XTree is equal to the number of
77// bottom-XPTs in that XTree.
78//
79// All XCons have the same top-XPt, "alloc_xpt", which represents all
80// allocation functions like malloc(). It's a bit of a fake XPt, though,
81// and is only used because it makes some of the code simpler.
82//
83// XTrees are bi-directional.
84//
85// > parent < Example: if child1() calls parent() and child2()
86// / | \ also calls parent(), and parent() calls malloc(),
87// | / \ | the XTree will look like this.
88// | v v |
89// child1 child2
90
91typedef struct _XPt XPt;
92
93struct _XPt {
njnd01fef72005-03-25 23:35:48 +000094 Addr ip; // code address
nethercotec9f36922004-02-14 16:40:02 +000095
96 // Bottom-XPts: space for the precise context.
97 // Other XPts: space of all the descendent bottom-XPts.
98 // Nb: this value goes up and down as the program executes.
99 UInt curr_space;
100
101 // An approximate space.time calculation used along the way for selecting
102 // which contexts to include at each census point.
103 // !!! top-XPTs only !!!
nethercote43a15ce2004-08-30 19:15:12 +0000104 ULong approx_ST;
nethercotec9f36922004-02-14 16:40:02 +0000105
nethercote43a15ce2004-08-30 19:15:12 +0000106 // exact_ST_dbld is an exact space.time calculation done at the end, and
nethercotec9f36922004-02-14 16:40:02 +0000107 // used in the results.
108 // Note that it is *doubled*, to avoid rounding errors.
109 // !!! not used for 'alloc_xpt' !!!
nethercote43a15ce2004-08-30 19:15:12 +0000110 ULong exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +0000111
112 // n_children and max_children are integers; a very big program might
113 // have more than 65536 allocation points (Konqueror startup has 1800).
114 XPt* parent; // pointer to parent XPt
115 UInt n_children; // number of children
116 UInt max_children; // capacity of children array
117 XPt** children; // pointers to children XPts
118};
119
120// Each census snapshots the most significant XTrees, each XTree having a
121// top-XPt as its root. The 'curr_space' element for each XPt is recorded
122// in the snapshot. The snapshot contains all the XTree's XPts, not in a
123// tree structure, but flattened into an array. This flat snapshot is used
nethercote43a15ce2004-08-30 19:15:12 +0000124// at the end for computing exact_ST_dbld for each XPt.
nethercotec9f36922004-02-14 16:40:02 +0000125//
126// Graph resolution, x-axis: no point having more than about 200 census
127// x-points; you can't see them on the graph. Therefore:
128//
129// - do a census every 1 ms for first 200 --> 200, all (200 ms)
130// - halve (drop half of them) --> 100, every 2nd (200 ms)
131// - do a census every 2 ms for next 200 --> 200, every 2nd (400 ms)
132// - halve --> 100, every 4th (400 ms)
133// - do a census every 4 ms for next 400 --> 200, every 4th (800 ms)
134// - etc.
135//
136// This isn't exactly right, because we actually drop (N/2)-1 when halving,
137// but it shows the basic idea.
138
139#define MAX_N_CENSI 200 // Keep it even, for simplicity
140
141// Graph resolution, y-axis: hp2ps only draws the 19 biggest (in space-time)
142// bands, rest get lumped into OTHERS. I only print the top N
143// (cumulative-so-far space-time) at each point. N should be a bit bigger
144// than 19 in case the cumulative space-time doesn't fit with the eventual
145// space-time computed by hp2ps (but it should be close if the samples are
146// evenly spread, since hp2ps does an approximate per-band space-time
147// calculation that just sums the totals; ie. it assumes all samples are
148// the same distance apart).
149
150#define MAX_SNAPSHOTS 32
151
152typedef
153 struct {
154 XPt* xpt;
155 UInt space;
156 }
157 XPtSnapshot;
158
159// An XTree snapshot is stored as an array of of XPt snapshots.
160typedef XPtSnapshot* XTreeSnapshot;
161
162typedef
163 struct {
164 Int ms_time; // Int: must allow -1
165 XTreeSnapshot xtree_snapshots[MAX_SNAPSHOTS+1]; // +1 for zero-termination
166 UInt others_space;
167 UInt heap_admin_space;
168 UInt stacks_space;
169 }
170 Census;
171
172// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
173// which is a foothold into the XCon at which it was allocated. From
174// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
175// decremented (at deallocation).
176//
177// Nb: first two fields must match core's VgHashNode.
178typedef
179 struct _HP_Chunk {
180 struct _HP_Chunk* next;
181 Addr data; // Ptr to actual block
nethercote7ac7f7b2004-11-02 12:36:02 +0000182 SizeT size; // Size requested
nethercotec9f36922004-02-14 16:40:02 +0000183 XPt* where; // Where allocated; bottom-XPt
184 }
185 HP_Chunk;
186
187/*------------------------------------------------------------*/
188/*--- Profiling events ---*/
189/*------------------------------------------------------------*/
190
191typedef
192 enum {
193 VgpGetXPt = VgpFini+1,
194 VgpGetXPtSearch,
195 VgpCensus,
196 VgpCensusHeap,
197 VgpCensusSnapshot,
198 VgpCensusTreeSize,
199 VgpUpdateXCon,
200 VgpCalcSpacetime2,
201 VgpPrintHp,
202 VgpPrintXPts,
203 }
njn4be0a692004-11-22 18:10:36 +0000204 VgpToolCC;
nethercotec9f36922004-02-14 16:40:02 +0000205
206/*------------------------------------------------------------*/
207/*--- Statistics ---*/
208/*------------------------------------------------------------*/
209
210// Konqueror startup, to give an idea of the numbers involved with a biggish
211// program, with default depth:
212//
213// depth=3 depth=40
214// - 310,000 allocations
215// - 300,000 frees
216// - 15,000 XPts 800,000 XPts
217// - 1,800 top-XPts
218
219static UInt n_xpts = 0;
220static UInt n_bot_xpts = 0;
221static UInt n_allocs = 0;
222static UInt n_zero_allocs = 0;
223static UInt n_frees = 0;
224static UInt n_children_reallocs = 0;
225static UInt n_snapshot_frees = 0;
226
227static UInt n_halvings = 0;
228static UInt n_real_censi = 0;
229static UInt n_fake_censi = 0;
230static UInt n_attempted_censi = 0;
231
232/*------------------------------------------------------------*/
233/*--- Globals ---*/
234/*------------------------------------------------------------*/
235
236#define FILENAME_LEN 256
237
238#define SPRINTF(zz_buf, fmt, args...) \
239 do { Int len = VG_(sprintf)(zz_buf, fmt, ## args); \
240 VG_(write)(fd, (void*)zz_buf, len); \
241 } while (0)
242
243#define BUF_LEN 1024 // general purpose
244static Char buf [BUF_LEN];
245static Char buf2[BUF_LEN];
246static Char buf3[BUF_LEN];
247
nethercote8b5f40c2004-11-02 13:29:50 +0000248static SizeT sigstacks_space = 0; // Current signal stacks space sum
nethercotec9f36922004-02-14 16:40:02 +0000249
250static VgHashTable malloc_list = NULL; // HP_Chunks
251
252static UInt n_heap_blocks = 0;
253
254
255#define MAX_ALLOC_FNS 32 // includes the builtin ones
256
nethercotec7469182004-05-11 09:21:08 +0000257// First few filled in, rest should be zeroed. Zero-terminated vector.
258static UInt n_alloc_fns = 11;
nethercotec9f36922004-02-14 16:40:02 +0000259static Char* alloc_fns[MAX_ALLOC_FNS] = {
260 "malloc",
261 "operator new(unsigned)",
262 "operator new[](unsigned)",
nethercoteeb479cb2004-05-11 16:37:17 +0000263 "operator new(unsigned, std::nothrow_t const&)",
264 "operator new[](unsigned, std::nothrow_t const&)",
nethercotec9f36922004-02-14 16:40:02 +0000265 "__builtin_new",
266 "__builtin_vec_new",
267 "calloc",
268 "realloc",
fitzhardinge51f3ff12004-03-04 22:42:03 +0000269 "memalign",
nethercotec9f36922004-02-14 16:40:02 +0000270};
271
272
273/*------------------------------------------------------------*/
274/*--- Command line args ---*/
275/*------------------------------------------------------------*/
276
277#define MAX_DEPTH 50
278
279typedef
280 enum {
281 XText, XHTML,
282 }
283 XFormat;
284
285static Bool clo_heap = True;
286static UInt clo_heap_admin = 8;
287static Bool clo_stacks = True;
288static Bool clo_depth = 3;
289static XFormat clo_format = XText;
290
njn26f02512004-11-22 18:33:15 +0000291Bool TL_(process_cmd_line_option)(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000292{
njn45270a22005-03-27 01:00:11 +0000293 VG_BOOL_CLO(arg, "--heap", clo_heap)
294 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
nethercotec9f36922004-02-14 16:40:02 +0000295
njn45270a22005-03-27 01:00:11 +0000296 else VG_NUM_CLO (arg, "--heap-admin", clo_heap_admin)
297 else VG_BNUM_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH)
nethercotec9f36922004-02-14 16:40:02 +0000298
299 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
300 alloc_fns[n_alloc_fns] = & arg[11];
301 n_alloc_fns++;
302 if (n_alloc_fns >= MAX_ALLOC_FNS) {
303 VG_(printf)("Too many alloc functions specified, sorry");
304 VG_(bad_option)(arg);
305 }
306 }
307
308 else if (VG_CLO_STREQ(arg, "--format=text"))
309 clo_format = XText;
310 else if (VG_CLO_STREQ(arg, "--format=html"))
311 clo_format = XHTML;
312
313 else
314 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000315
nethercotec9f36922004-02-14 16:40:02 +0000316 return True;
317}
318
njn26f02512004-11-22 18:33:15 +0000319void TL_(print_usage)(void)
nethercotec9f36922004-02-14 16:40:02 +0000320{
321 VG_(printf)(
322" --heap=no|yes profile heap blocks [yes]\n"
323" --heap-admin=<number> average admin bytes per heap block [8]\n"
324" --stacks=no|yes profile stack(s) [yes]\n"
325" --depth=<number> depth of contexts [3]\n"
326" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
327" --format=text|html format of textual output [text]\n"
328 );
329 VG_(replacement_malloc_print_usage)();
330}
331
njn26f02512004-11-22 18:33:15 +0000332void TL_(print_debug_usage)(void)
nethercotec9f36922004-02-14 16:40:02 +0000333{
334 VG_(replacement_malloc_print_debug_usage)();
335}
336
337/*------------------------------------------------------------*/
338/*--- Execution contexts ---*/
339/*------------------------------------------------------------*/
340
341// Fake XPt representing all allocation functions like malloc(). Acts as
342// parent node to all top-XPts.
343static XPt* alloc_xpt;
344
345// Cheap allocation for blocks that never need to be freed. Saves about 10%
346// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000347static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000348{
349 static Addr hp = 0; // current heap pointer
350 static Addr hp_lim = 0; // maximum usable byte in current block
351
352 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
353
354 if (hp + n_bytes > hp_lim) {
355 hp = (Addr)VG_(get_memory_from_mmap)(SUPERBLOCK_SIZE, "perm_malloc");
356 hp_lim = hp + SUPERBLOCK_SIZE - 1;
357 }
358
359 hp += n_bytes;
360
361 return (void*)(hp - n_bytes);
362}
363
364
365
njnd01fef72005-03-25 23:35:48 +0000366static XPt* new_XPt(Addr ip, XPt* parent, Bool is_bottom)
nethercotec9f36922004-02-14 16:40:02 +0000367{
368 XPt* xpt = perm_malloc(sizeof(XPt));
njnd01fef72005-03-25 23:35:48 +0000369 xpt->ip = ip;
nethercotec9f36922004-02-14 16:40:02 +0000370
nethercote43a15ce2004-08-30 19:15:12 +0000371 xpt->curr_space = 0;
372 xpt->approx_ST = 0;
373 xpt->exact_ST_dbld = 0;
nethercotec9f36922004-02-14 16:40:02 +0000374
375 xpt->parent = parent;
nethercotefc016352004-04-27 09:51:51 +0000376
377 // Check parent is not a bottom-XPt
njnca82cc02004-11-22 17:18:48 +0000378 tl_assert(parent == NULL || 0 != parent->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000379
380 xpt->n_children = 0;
381
382 // If a bottom-XPt, don't allocate space for children. This can be 50%
383 // or more, although it tends to drop as --depth increases (eg. 10% for
384 // konqueror with --depth=20).
385 if ( is_bottom ) {
386 xpt->max_children = 0;
387 xpt->children = NULL;
388 n_bot_xpts++;
389 } else {
390 xpt->max_children = 4;
391 xpt->children = VG_(malloc)( xpt->max_children * sizeof(XPt*) );
392 }
393
394 // Update statistics
395 n_xpts++;
396
397 return xpt;
398}
399
njnd01fef72005-03-25 23:35:48 +0000400static Bool is_alloc_fn(Addr ip)
nethercotec9f36922004-02-14 16:40:02 +0000401{
402 Int i;
403
njnd01fef72005-03-25 23:35:48 +0000404 if ( VG_(get_fnname)(ip, buf, BUF_LEN) ) {
nethercotec9f36922004-02-14 16:40:02 +0000405 for (i = 0; i < n_alloc_fns; i++) {
406 if (VG_STREQ(buf, alloc_fns[i]))
407 return True;
408 }
409 }
410 return False;
411}
412
413// Returns an XCon, from the bottom-XPt. Nb: the XPt returned must be a
414// bottom-XPt now and must always remain a bottom-XPt. We go to some effort
415// to ensure this in certain cases. See comments below.
416static XPt* get_XCon( ThreadId tid, Bool custom_malloc )
417{
njnd01fef72005-03-25 23:35:48 +0000418 // Static to minimise stack size. +1 for added ~0 IP
419 static Addr ips[MAX_DEPTH + MAX_ALLOC_FNS + 1];
nethercotec9f36922004-02-14 16:40:02 +0000420
421 XPt* xpt = alloc_xpt;
njnd01fef72005-03-25 23:35:48 +0000422 UInt n_ips, L, A, B, nC;
nethercotec9f36922004-02-14 16:40:02 +0000423 UInt overestimate;
424 Bool reached_bottom;
425
426 VGP_PUSHCC(VgpGetXPt);
427
428 // Want at least clo_depth non-alloc-fn entries in the snapshot.
429 // However, because we have 1 or more (an unknown number, at this point)
430 // alloc-fns ignored, we overestimate the size needed for the stack
431 // snapshot. Then, if necessary, we repeatedly increase the size until
432 // it is enough.
433 overestimate = 2;
434 while (True) {
njnd01fef72005-03-25 23:35:48 +0000435 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate );
nethercotec9f36922004-02-14 16:40:02 +0000436
njnd01fef72005-03-25 23:35:48 +0000437 // Now we add a dummy "unknown" IP at the end. This is only used if we
438 // run out of IPs before hitting clo_depth. It's done to ensure the
nethercotec9f36922004-02-14 16:40:02 +0000439 // XPt we return is (now and forever) a bottom-XPt. If the returned XPt
440 // wasn't a bottom-XPt (now or later) it would cause problems later (eg.
nethercote43a15ce2004-08-30 19:15:12 +0000441 // the parent's approx_ST wouldn't be equal [or almost equal] to the
442 // total of the childrens' approx_STs).
njnd01fef72005-03-25 23:35:48 +0000443 ips[ n_ips++ ] = ~((Addr)0);
nethercotec9f36922004-02-14 16:40:02 +0000444
njnd01fef72005-03-25 23:35:48 +0000445 // Skip over alloc functions in ips[].
446 for (L = 0; is_alloc_fn(ips[L]) && L < n_ips; L++) { }
nethercotec9f36922004-02-14 16:40:02 +0000447
448 // Must be at least one alloc function, unless client used
449 // MALLOCLIKE_BLOCK
njnca82cc02004-11-22 17:18:48 +0000450 if (!custom_malloc) tl_assert(L > 0);
nethercotec9f36922004-02-14 16:40:02 +0000451
452 // Should be at least one non-alloc function. If not, try again.
njnd01fef72005-03-25 23:35:48 +0000453 if (L == n_ips) {
nethercotec9f36922004-02-14 16:40:02 +0000454 overestimate += 2;
455 if (overestimate > MAX_ALLOC_FNS)
njn67993252004-11-22 18:02:32 +0000456 VG_(tool_panic)("No stk snapshot big enough to find non-alloc fns");
nethercotec9f36922004-02-14 16:40:02 +0000457 } else {
458 break;
459 }
460 }
461 A = L;
njnd01fef72005-03-25 23:35:48 +0000462 B = n_ips - 1;
nethercotec9f36922004-02-14 16:40:02 +0000463 reached_bottom = False;
464
njnd01fef72005-03-25 23:35:48 +0000465 // By this point, the IPs we care about are in ips[A]..ips[B]
nethercotec9f36922004-02-14 16:40:02 +0000466
467 // Now do the search/insertion of the XCon. 'L' is the loop counter,
njnd01fef72005-03-25 23:35:48 +0000468 // being the index into ips[].
nethercotec9f36922004-02-14 16:40:02 +0000469 while (True) {
njnd01fef72005-03-25 23:35:48 +0000470 // Look for IP in xpt's children.
nethercotec9f36922004-02-14 16:40:02 +0000471 // XXX: linear search, ugh -- about 10% of time for konqueror startup
472 // XXX: tried cacheing last result, only hit about 4% for konqueror
473 // Nb: this search hits about 98% of the time for konqueror
474 VGP_PUSHCC(VgpGetXPtSearch);
475
476 // If we've searched/added deep enough, or run out of EIPs, this is
477 // the bottom XPt.
478 if (L - A + 1 == clo_depth || L == B)
479 reached_bottom = True;
480
481 nC = 0;
482 while (True) {
483 if (nC == xpt->n_children) {
484 // not found, insert new XPt
njnca82cc02004-11-22 17:18:48 +0000485 tl_assert(xpt->max_children != 0);
486 tl_assert(xpt->n_children <= xpt->max_children);
nethercotec9f36922004-02-14 16:40:02 +0000487 // Expand 'children' if necessary
488 if (xpt->n_children == xpt->max_children) {
489 xpt->max_children *= 2;
490 xpt->children = VG_(realloc)( xpt->children,
491 xpt->max_children * sizeof(XPt*) );
492 n_children_reallocs++;
493 }
njnd01fef72005-03-25 23:35:48 +0000494 // Make new XPt for IP, insert in list
nethercotec9f36922004-02-14 16:40:02 +0000495 xpt->children[ xpt->n_children++ ] =
njnd01fef72005-03-25 23:35:48 +0000496 new_XPt(ips[L], xpt, reached_bottom);
nethercotec9f36922004-02-14 16:40:02 +0000497 break;
498 }
njnd01fef72005-03-25 23:35:48 +0000499 if (ips[L] == xpt->children[nC]->ip) break; // found the IP
nethercotec9f36922004-02-14 16:40:02 +0000500 nC++; // keep looking
501 }
502 VGP_POPCC(VgpGetXPtSearch);
503
504 // Return found/built bottom-XPt.
505 if (reached_bottom) {
njnca82cc02004-11-22 17:18:48 +0000506 tl_assert(0 == xpt->children[nC]->n_children); // Must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000507 VGP_POPCC(VgpGetXPt);
508 return xpt->children[nC];
509 }
510
511 // Descend to next level in XTree, the newly found/built non-bottom-XPt
512 xpt = xpt->children[nC];
513 L++;
514 }
515}
516
517// Update 'curr_space' of every XPt in the XCon, by percolating upwards.
518static void update_XCon(XPt* xpt, Int space_delta)
519{
520 VGP_PUSHCC(VgpUpdateXCon);
521
njnca82cc02004-11-22 17:18:48 +0000522 tl_assert(True == clo_heap);
523 tl_assert(0 != space_delta);
524 tl_assert(NULL != xpt);
525 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000526
527 while (xpt != alloc_xpt) {
njnca82cc02004-11-22 17:18:48 +0000528 if (space_delta < 0) tl_assert(xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000529 xpt->curr_space += space_delta;
530 xpt = xpt->parent;
531 }
njnca82cc02004-11-22 17:18:48 +0000532 if (space_delta < 0) tl_assert(alloc_xpt->curr_space >= -space_delta);
nethercotec9f36922004-02-14 16:40:02 +0000533 alloc_xpt->curr_space += space_delta;
534
535 VGP_POPCC(VgpUpdateXCon);
536}
537
538// Actually want a reverse sort, biggest to smallest
nethercote43a15ce2004-08-30 19:15:12 +0000539static Int XPt_cmp_approx_ST(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000540{
541 XPt* xpt1 = *(XPt**)n1;
542 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000543 return (xpt1->approx_ST < xpt2->approx_ST ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000544}
545
nethercote43a15ce2004-08-30 19:15:12 +0000546static Int XPt_cmp_exact_ST_dbld(void* n1, void* n2)
nethercotec9f36922004-02-14 16:40:02 +0000547{
548 XPt* xpt1 = *(XPt**)n1;
549 XPt* xpt2 = *(XPt**)n2;
nethercote43a15ce2004-08-30 19:15:12 +0000550 return (xpt1->exact_ST_dbld < xpt2->exact_ST_dbld ? 1 : -1);
nethercotec9f36922004-02-14 16:40:02 +0000551}
552
553
554/*------------------------------------------------------------*/
555/*--- A generic Queue ---*/
556/*------------------------------------------------------------*/
557
558typedef
559 struct {
560 UInt head; // Index of first entry
561 UInt tail; // Index of final+1 entry, ie. next free slot
562 UInt max_elems;
563 void** elems;
564 }
565 Queue;
566
567static Queue* construct_queue(UInt size)
568{
569 UInt i;
570 Queue* q = VG_(malloc)(sizeof(Queue));
571 q->head = 0;
572 q->tail = 0;
573 q->max_elems = size;
574 q->elems = VG_(malloc)(size * sizeof(void*));
575 for (i = 0; i < size; i++)
576 q->elems[i] = NULL;
577
578 return q;
579}
580
581static void destruct_queue(Queue* q)
582{
583 VG_(free)(q->elems);
584 VG_(free)(q);
585}
586
587static void shuffle(Queue* dest_q, void** old_elems)
588{
589 UInt i, j;
590 for (i = 0, j = dest_q->head; j < dest_q->tail; i++, j++)
591 dest_q->elems[i] = old_elems[j];
592 dest_q->head = 0;
593 dest_q->tail = i;
594 for ( ; i < dest_q->max_elems; i++)
595 dest_q->elems[i] = NULL; // paranoia
596}
597
598// Shuffles elements down. If not enough slots free, increase size. (We
599// don't wait until we've completely run out of space, because there could
600// be lots of shuffling just before that point which would be slow.)
601static void adjust(Queue* q)
602{
603 void** old_elems;
604
njnca82cc02004-11-22 17:18:48 +0000605 tl_assert(q->tail == q->max_elems);
nethercotec9f36922004-02-14 16:40:02 +0000606 if (q->head < 10) {
607 old_elems = q->elems;
608 q->max_elems *= 2;
609 q->elems = VG_(malloc)(q->max_elems * sizeof(void*));
610 shuffle(q, old_elems);
611 VG_(free)(old_elems);
612 } else {
613 shuffle(q, q->elems);
614 }
615}
616
617static void enqueue(Queue* q, void* elem)
618{
619 if (q->tail == q->max_elems)
620 adjust(q);
621 q->elems[q->tail++] = elem;
622}
623
624static Bool is_empty_queue(Queue* q)
625{
626 return (q->head == q->tail);
627}
628
629static void* dequeue(Queue* q)
630{
631 if (is_empty_queue(q))
632 return NULL; // Queue empty
633 else
634 return q->elems[q->head++];
635}
636
637/*------------------------------------------------------------*/
638/*--- malloc() et al replacement wrappers ---*/
639/*------------------------------------------------------------*/
640
641static __inline__
642void add_HP_Chunk(HP_Chunk* hc)
643{
644 n_heap_blocks++;
645 VG_(HT_add_node) ( malloc_list, (VgHashNode*)hc );
646}
647
648static __inline__
649HP_Chunk* get_HP_Chunk(void* p, HP_Chunk*** prev_chunks_next_ptr)
650{
nethercote3d6b6112004-11-04 16:39:43 +0000651 return (HP_Chunk*)VG_(HT_get_node) ( malloc_list, (UWord)p,
nethercotec9f36922004-02-14 16:40:02 +0000652 (VgHashNode***)prev_chunks_next_ptr );
653}
654
655static __inline__
656void remove_HP_Chunk(HP_Chunk* hc, HP_Chunk** prev_chunks_next_ptr)
657{
njnca82cc02004-11-22 17:18:48 +0000658 tl_assert(n_heap_blocks > 0);
nethercotec9f36922004-02-14 16:40:02 +0000659 n_heap_blocks--;
660 *prev_chunks_next_ptr = hc->next;
661}
662
663// Forward declaration
664static void hp_census(void);
665
nethercote159dfef2004-09-13 13:27:30 +0000666static
njn57735902004-11-25 18:04:54 +0000667void* new_block ( ThreadId tid, void* p, SizeT size, SizeT align,
668 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +0000669{
670 HP_Chunk* hc;
nethercote57e36b32004-07-10 14:56:28 +0000671 Bool custom_alloc = (NULL == p);
nethercotec9f36922004-02-14 16:40:02 +0000672 if (size < 0) return NULL;
673
674 VGP_PUSHCC(VgpCliMalloc);
675
676 // Update statistics
677 n_allocs++;
nethercote57e36b32004-07-10 14:56:28 +0000678 if (0 == size) n_zero_allocs++;
nethercotec9f36922004-02-14 16:40:02 +0000679
nethercote57e36b32004-07-10 14:56:28 +0000680 // Allocate and zero if necessary
681 if (!p) {
682 p = VG_(cli_malloc)( align, size );
683 if (!p) {
684 VGP_POPCC(VgpCliMalloc);
685 return NULL;
686 }
687 if (is_zeroed) VG_(memset)(p, 0, size);
688 }
689
690 // Make new HP_Chunk node, add to malloclist
691 hc = VG_(malloc)(sizeof(HP_Chunk));
692 hc->size = size;
693 hc->data = (Addr)p;
694 hc->where = NULL; // paranoia
695 if (clo_heap) {
njn57735902004-11-25 18:04:54 +0000696 hc->where = get_XCon( tid, custom_alloc );
nethercote57e36b32004-07-10 14:56:28 +0000697 if (0 != size)
698 update_XCon(hc->where, size);
699 }
700 add_HP_Chunk( hc );
701
702 // do a census!
703 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000704
705 VGP_POPCC(VgpCliMalloc);
706 return p;
707}
708
709static __inline__
710void die_block ( void* p, Bool custom_free )
711{
nethercote57e36b32004-07-10 14:56:28 +0000712 HP_Chunk *hc, **remove_handle;
nethercotec9f36922004-02-14 16:40:02 +0000713
714 VGP_PUSHCC(VgpCliMalloc);
715
716 // Update statistics
717 n_frees++;
718
nethercote57e36b32004-07-10 14:56:28 +0000719 // Remove HP_Chunk from malloclist
720 hc = get_HP_Chunk( p, &remove_handle );
nethercotec9f36922004-02-14 16:40:02 +0000721 if (hc == NULL)
722 return; // must have been a bogus free(), or p==NULL
njnca82cc02004-11-22 17:18:48 +0000723 tl_assert(hc->data == (Addr)p);
nethercote57e36b32004-07-10 14:56:28 +0000724 remove_HP_Chunk(hc, remove_handle);
nethercotec9f36922004-02-14 16:40:02 +0000725
726 if (clo_heap && hc->size != 0)
727 update_XCon(hc->where, -hc->size);
728
nethercote57e36b32004-07-10 14:56:28 +0000729 VG_(free)( hc );
730
731 // Actually free the heap block, if necessary
nethercotec9f36922004-02-14 16:40:02 +0000732 if (!custom_free)
733 VG_(cli_free)( p );
734
nethercote57e36b32004-07-10 14:56:28 +0000735 // do a census!
736 hp_census();
nethercotec9f36922004-02-14 16:40:02 +0000737
nethercotec9f36922004-02-14 16:40:02 +0000738 VGP_POPCC(VgpCliMalloc);
739}
740
741
njn57735902004-11-25 18:04:54 +0000742void* TL_(malloc) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000743{
njn57735902004-11-25 18:04:54 +0000744 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000745}
746
njn57735902004-11-25 18:04:54 +0000747void* TL_(__builtin_new) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000748{
njn57735902004-11-25 18:04:54 +0000749 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000750}
751
njn57735902004-11-25 18:04:54 +0000752void* TL_(__builtin_vec_new) ( ThreadId tid, SizeT n )
nethercotec9f36922004-02-14 16:40:02 +0000753{
njn57735902004-11-25 18:04:54 +0000754 return new_block( tid, NULL, n, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +0000755}
756
njn57735902004-11-25 18:04:54 +0000757void* TL_(calloc) ( ThreadId tid, SizeT m, SizeT size )
nethercotec9f36922004-02-14 16:40:02 +0000758{
njn57735902004-11-25 18:04:54 +0000759 return new_block( tid, NULL, m*size, VG_(clo_alignment), /*is_zeroed*/True );
nethercotec9f36922004-02-14 16:40:02 +0000760}
761
njn57735902004-11-25 18:04:54 +0000762void *TL_(memalign)( ThreadId tid, SizeT align, SizeT n )
fitzhardinge51f3ff12004-03-04 22:42:03 +0000763{
njn57735902004-11-25 18:04:54 +0000764 return new_block( tid, NULL, n, align, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +0000765}
766
njn57735902004-11-25 18:04:54 +0000767void TL_(free) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000768{
769 die_block( p, /*custom_free*/False );
770}
771
njn57735902004-11-25 18:04:54 +0000772void TL_(__builtin_delete) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000773{
774 die_block( p, /*custom_free*/False);
775}
776
njn57735902004-11-25 18:04:54 +0000777void TL_(__builtin_vec_delete) ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +0000778{
779 die_block( p, /*custom_free*/False );
780}
781
njn57735902004-11-25 18:04:54 +0000782void* TL_(realloc) ( ThreadId tid, void* p_old, SizeT new_size )
nethercotec9f36922004-02-14 16:40:02 +0000783{
784 HP_Chunk* hc;
785 HP_Chunk** remove_handle;
786 Int i;
787 void* p_new;
nethercote7ac7f7b2004-11-02 12:36:02 +0000788 SizeT old_size;
nethercotec9f36922004-02-14 16:40:02 +0000789 XPt *old_where, *new_where;
790
791 VGP_PUSHCC(VgpCliMalloc);
792
793 // First try and find the block.
794 hc = get_HP_Chunk ( p_old, &remove_handle );
795 if (hc == NULL) {
796 VGP_POPCC(VgpCliMalloc);
797 return NULL; // must have been a bogus free()
798 }
799
njnca82cc02004-11-22 17:18:48 +0000800 tl_assert(hc->data == (Addr)p_old);
nethercotec9f36922004-02-14 16:40:02 +0000801 old_size = hc->size;
802
803 if (new_size <= old_size) {
804 // new size is smaller or same; block not moved
805 p_new = p_old;
806
807 } else {
808 // new size is bigger; make new block, copy shared contents, free old
809 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_size);
810
811 for (i = 0; i < old_size; i++)
812 ((UChar*)p_new)[i] = ((UChar*)p_old)[i];
813
814 VG_(cli_free)(p_old);
815 }
816
817 old_where = hc->where;
njn57735902004-11-25 18:04:54 +0000818 new_where = get_XCon( tid, /*custom_malloc*/False);
nethercotec9f36922004-02-14 16:40:02 +0000819
820 // Update HP_Chunk
821 hc->data = (Addr)p_new;
822 hc->size = new_size;
823 hc->where = new_where;
824
825 // Update XPt curr_space fields
826 if (clo_heap) {
827 if (0 != old_size) update_XCon(old_where, -old_size);
828 if (0 != new_size) update_XCon(new_where, new_size);
829 }
830
831 // If block has moved, have to remove and reinsert in the malloclist
832 // (since the updated 'data' field is the hash lookup key).
833 if (p_new != p_old) {
834 remove_HP_Chunk(hc, remove_handle);
835 add_HP_Chunk(hc);
836 }
837
838 VGP_POPCC(VgpCliMalloc);
839 return p_new;
840}
841
842
843/*------------------------------------------------------------*/
844/*--- Taking a census ---*/
845/*------------------------------------------------------------*/
846
847static Census censi[MAX_N_CENSI];
848static UInt curr_census = 0;
849
850// Must return False so that all stacks are traversed
thughes4ad52d02004-06-27 17:37:21 +0000851static Bool count_stack_size( Addr stack_min, Addr stack_max, void *cp )
nethercotec9f36922004-02-14 16:40:02 +0000852{
thughes4ad52d02004-06-27 17:37:21 +0000853 *(UInt *)cp += (stack_max - stack_min);
nethercotec9f36922004-02-14 16:40:02 +0000854 return False;
855}
856
857static UInt get_xtree_size(XPt* xpt, UInt ix)
858{
859 UInt i;
860
nethercote43a15ce2004-08-30 19:15:12 +0000861 // If no memory allocated at all, nothing interesting to record.
862 if (alloc_xpt->curr_space == 0) return 0;
863
864 // Ignore sub-XTrees that account for a miniscule fraction of current
865 // allocated space.
866 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000867 ix++;
868
869 // Count all (non-zero) descendent XPts
870 for (i = 0; i < xpt->n_children; i++)
871 ix = get_xtree_size(xpt->children[i], ix);
872 }
873 return ix;
874}
875
876static
877UInt do_space_snapshot(XPt xpt[], XTreeSnapshot xtree_snapshot, UInt ix)
878{
879 UInt i;
880
nethercote43a15ce2004-08-30 19:15:12 +0000881 // Structure of this function mirrors that of get_xtree_size().
882
883 if (alloc_xpt->curr_space == 0) return 0;
884
885 if (xpt->curr_space / (double)alloc_xpt->curr_space > 0.002) {
nethercotec9f36922004-02-14 16:40:02 +0000886 xtree_snapshot[ix].xpt = xpt;
887 xtree_snapshot[ix].space = xpt->curr_space;
888 ix++;
889
nethercotec9f36922004-02-14 16:40:02 +0000890 for (i = 0; i < xpt->n_children; i++)
891 ix = do_space_snapshot(xpt->children[i], xtree_snapshot, ix);
892 }
893 return ix;
894}
895
896static UInt ms_interval;
897static UInt do_every_nth_census = 30;
898
899// Weed out half the censi; we choose those that represent the smallest
900// time-spans, because that loses the least information.
901//
902// Algorithm for N censi: We find the census representing the smallest
903// timeframe, and remove it. We repeat this until (N/2)-1 censi are gone.
904// (It's (N/2)-1 because we never remove the first and last censi.)
905// We have to do this one census at a time, rather than finding the (N/2)-1
906// smallest censi in one hit, because when a census is removed, it's
907// neighbours immediately cover greater timespans. So it's N^2, but N only
908// equals 200, and this is only done every 100 censi, which is not too often.
909static void halve_censi(void)
910{
911 Int i, jp, j, jn, k;
912 Census* min_census;
913
914 n_halvings++;
915 if (VG_(clo_verbosity) > 1)
916 VG_(message)(Vg_UserMsg, "Halving censi...");
917
918 // Sets j to the index of the first not-yet-removed census at or after i
919 #define FIND_CENSUS(i, j) \
920 for (j = i; -1 == censi[j].ms_time; j++) { }
921
922 for (i = 2; i < MAX_N_CENSI; i += 2) {
923 // Find the censi representing the smallest timespan. The timespan
924 // for census n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
925 // censi A and B. We don't consider the first and last censi for
926 // removal.
927 Int min_span = 0x7fffffff;
928 Int min_j = 0;
929
930 // Initial triple: (prev, curr, next) == (jp, j, jn)
931 jp = 0;
932 FIND_CENSUS(1, j);
933 FIND_CENSUS(j+1, jn);
934 while (jn < MAX_N_CENSI) {
935 Int timespan = censi[jn].ms_time - censi[jp].ms_time;
njnca82cc02004-11-22 17:18:48 +0000936 tl_assert(timespan >= 0);
nethercotec9f36922004-02-14 16:40:02 +0000937 if (timespan < min_span) {
938 min_span = timespan;
939 min_j = j;
940 }
941 // Move on to next triple
942 jp = j;
943 j = jn;
944 FIND_CENSUS(jn+1, jn);
945 }
946 // We've found the least important census, now remove it
947 min_census = & censi[ min_j ];
948 for (k = 0; NULL != min_census->xtree_snapshots[k]; k++) {
949 n_snapshot_frees++;
950 VG_(free)(min_census->xtree_snapshots[k]);
951 min_census->xtree_snapshots[k] = NULL;
952 }
953 min_census->ms_time = -1;
954 }
955
956 // Slide down the remaining censi over the removed ones. The '<=' is
957 // because we are removing on (N/2)-1, rather than N/2.
958 for (i = 0, j = 0; i <= MAX_N_CENSI / 2; i++, j++) {
959 FIND_CENSUS(j, j);
960 if (i != j) {
961 censi[i] = censi[j];
962 }
963 }
964 curr_census = i;
965
966 // Double intervals
967 ms_interval *= 2;
968 do_every_nth_census *= 2;
969
970 if (VG_(clo_verbosity) > 1)
971 VG_(message)(Vg_UserMsg, "...done");
972}
973
974// Take a census. Census time seems to be insignificant (usually <= 0 ms,
975// almost always <= 1ms) so don't have to worry about subtracting it from
976// running time in any way.
977//
978// XXX: NOT TRUE! with bigger depths, konqueror censuses can easily take
979// 50ms!
980static void hp_census(void)
981{
982 static UInt ms_prev_census = 0;
983 static UInt ms_next_census = 0; // zero allows startup census
984
985 Int ms_time, ms_time_since_prev;
986 Int i, K;
987 Census* census;
988
989 VGP_PUSHCC(VgpCensus);
990
991 // Only do a census if it's time
992 ms_time = VG_(read_millisecond_timer)();
993 ms_time_since_prev = ms_time - ms_prev_census;
994 if (ms_time < ms_next_census) {
995 n_fake_censi++;
996 VGP_POPCC(VgpCensus);
997 return;
998 }
999 n_real_censi++;
1000
1001 census = & censi[curr_census];
1002
1003 census->ms_time = ms_time;
1004
1005 // Heap: snapshot the K most significant XTrees -------------------
1006 if (clo_heap) {
1007 K = ( alloc_xpt->n_children < MAX_SNAPSHOTS
1008 ? alloc_xpt->n_children
1009 : MAX_SNAPSHOTS); // max out
1010
nethercote43a15ce2004-08-30 19:15:12 +00001011 // Update .approx_ST field (approximatively) for all top-XPts.
nethercotec9f36922004-02-14 16:40:02 +00001012 // We *do not* do it for any non-top-XPTs.
1013 for (i = 0; i < alloc_xpt->n_children; i++) {
1014 XPt* top_XPt = alloc_xpt->children[i];
nethercote43a15ce2004-08-30 19:15:12 +00001015 top_XPt->approx_ST += top_XPt->curr_space * ms_time_since_prev;
nethercotec9f36922004-02-14 16:40:02 +00001016 }
nethercote43a15ce2004-08-30 19:15:12 +00001017 // Sort top-XPts by approx_ST field.
nethercotec9f36922004-02-14 16:40:02 +00001018 VG_(ssort)(alloc_xpt->children, alloc_xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001019 XPt_cmp_approx_ST);
nethercotec9f36922004-02-14 16:40:02 +00001020
1021 VGP_PUSHCC(VgpCensusHeap);
1022
1023 // For each significant top-level XPt, record space info about its
1024 // entire XTree, in a single census entry.
1025 // Nb: the xtree_size count/snapshot buffer allocation, and the actual
1026 // snapshot, take similar amounts of time (measured with the
nethercote43a15ce2004-08-30 19:15:12 +00001027 // millisecond counter).
nethercotec9f36922004-02-14 16:40:02 +00001028 for (i = 0; i < K; i++) {
1029 UInt xtree_size, xtree_size2;
nethercote43a15ce2004-08-30 19:15:12 +00001030// VG_(printf)("%7u ", alloc_xpt->children[i]->approx_ST);
1031 // Count how many XPts are in the XTree
nethercotec9f36922004-02-14 16:40:02 +00001032 VGP_PUSHCC(VgpCensusTreeSize);
1033 xtree_size = get_xtree_size( alloc_xpt->children[i], 0 );
1034 VGP_POPCC(VgpCensusTreeSize);
nethercote43a15ce2004-08-30 19:15:12 +00001035
1036 // If no XPts counted (ie. alloc_xpt.curr_space==0 or XTree
1037 // insignificant) then don't take any more snapshots.
1038 if (0 == xtree_size) break;
1039
1040 // Make array of the appropriate size (+1 for zero termination,
1041 // which calloc() does for us).
nethercotec9f36922004-02-14 16:40:02 +00001042 census->xtree_snapshots[i] =
1043 VG_(calloc)(xtree_size+1, sizeof(XPtSnapshot));
jseward612e8362004-03-07 10:23:20 +00001044 if (0 && VG_(clo_verbosity) > 1)
nethercotec9f36922004-02-14 16:40:02 +00001045 VG_(printf)("calloc: %d (%d B)\n", xtree_size+1,
1046 (xtree_size+1) * sizeof(XPtSnapshot));
1047
1048 // Take space-snapshot: copy 'curr_space' for every XPt in the
1049 // XTree into the snapshot array, along with pointers to the XPts.
1050 // (Except for ones with curr_space==0, which wouldn't contribute
nethercote43a15ce2004-08-30 19:15:12 +00001051 // to the final exact_ST_dbld calculation anyway; excluding them
nethercotec9f36922004-02-14 16:40:02 +00001052 // saves a lot of memory and up to 40% time with big --depth valus.
1053 VGP_PUSHCC(VgpCensusSnapshot);
1054 xtree_size2 = do_space_snapshot(alloc_xpt->children[i],
1055 census->xtree_snapshots[i], 0);
njnca82cc02004-11-22 17:18:48 +00001056 tl_assert(xtree_size == xtree_size2);
nethercotec9f36922004-02-14 16:40:02 +00001057 VGP_POPCC(VgpCensusSnapshot);
1058 }
1059// VG_(printf)("\n\n");
1060 // Zero-terminate 'xtree_snapshot' array
1061 census->xtree_snapshots[i] = NULL;
1062
1063 VGP_POPCC(VgpCensusHeap);
1064
1065 //VG_(printf)("printed %d censi\n", K);
1066
1067 // Lump the rest into a single "others" entry.
1068 census->others_space = 0;
1069 for (i = K; i < alloc_xpt->n_children; i++) {
1070 census->others_space += alloc_xpt->children[i]->curr_space;
1071 }
1072 }
1073
1074 // Heap admin -------------------------------------------------------
1075 if (clo_heap_admin > 0)
1076 census->heap_admin_space = clo_heap_admin * n_heap_blocks;
1077
1078 // Stack(s) ---------------------------------------------------------
1079 if (clo_stacks) {
thughes4ad52d02004-06-27 17:37:21 +00001080 census->stacks_space = sigstacks_space;
nethercotec9f36922004-02-14 16:40:02 +00001081 // slightly abusing this function
thughes4ad52d02004-06-27 17:37:21 +00001082 VG_(first_matching_thread_stack)( count_stack_size, &census->stacks_space );
nethercotec9f36922004-02-14 16:40:02 +00001083 i++;
1084 }
1085
1086 // Finish, update interval if necessary -----------------------------
1087 curr_census++;
1088 census = NULL; // don't use again now that curr_census changed
1089
1090 // Halve the entries, if our census table is full
1091 if (MAX_N_CENSI == curr_census) {
1092 halve_censi();
1093 }
1094
1095 // Take time for next census from now, rather than when this census
1096 // should have happened. Because, if there's a big gap due to a kernel
1097 // operation, there's no point doing catch-up censi every BB for a while
1098 // -- that would just give N censi at almost the same time.
1099 if (VG_(clo_verbosity) > 1) {
1100 VG_(message)(Vg_UserMsg, "census: %d ms (took %d ms)", ms_time,
1101 VG_(read_millisecond_timer)() - ms_time );
1102 }
1103 ms_prev_census = ms_time;
1104 ms_next_census = ms_time + ms_interval;
1105 //ms_next_census += ms_interval;
1106
1107 //VG_(printf)("Next: %d ms\n", ms_next_census);
1108
1109 VGP_POPCC(VgpCensus);
1110}
1111
1112/*------------------------------------------------------------*/
1113/*--- Tracked events ---*/
1114/*------------------------------------------------------------*/
1115
nethercote8b5f40c2004-11-02 13:29:50 +00001116static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001117{
1118 sigstacks_space += len;
1119}
1120
nethercote8b5f40c2004-11-02 13:29:50 +00001121static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001122{
njnca82cc02004-11-22 17:18:48 +00001123 tl_assert(sigstacks_space >= len);
nethercotec9f36922004-02-14 16:40:02 +00001124 sigstacks_space -= len;
1125}
1126
1127/*------------------------------------------------------------*/
1128/*--- Client Requests ---*/
1129/*------------------------------------------------------------*/
1130
njn26f02512004-11-22 18:33:15 +00001131Bool TL_(handle_client_request) ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001132{
1133 switch (argv[0]) {
1134 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001135 void* res;
nethercotec9f36922004-02-14 16:40:02 +00001136 void* p = (void*)argv[1];
nethercoted1b64b22004-11-04 18:22:28 +00001137 SizeT sizeB = argv[2];
nethercotec9f36922004-02-14 16:40:02 +00001138 *ret = 0;
njn57735902004-11-25 18:04:54 +00001139 res = new_block( tid, p, sizeB, /*align--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001140 tl_assert(res == p);
nethercotec9f36922004-02-14 16:40:02 +00001141 return True;
1142 }
1143 case VG_USERREQ__FREELIKE_BLOCK: {
1144 void* p = (void*)argv[1];
1145 *ret = 0;
1146 die_block( p, /*custom_free*/True );
1147 return True;
1148 }
1149 default:
1150 *ret = 0;
1151 return False;
1152 }
1153}
1154
1155/*------------------------------------------------------------*/
1156/*--- Initialisation ---*/
1157/*------------------------------------------------------------*/
1158
1159// Current directory at startup.
1160static Char* base_dir;
1161
njn0e742df2004-11-30 13:26:29 +00001162SizeT VG_(vg_malloc_redzone_szB) = 0;
nethercotec9f36922004-02-14 16:40:02 +00001163
njn26f02512004-11-22 18:33:15 +00001164void TL_(pre_clo_init)()
nethercotec9f36922004-02-14 16:40:02 +00001165{
1166 VG_(details_name) ("Massif");
nethercote29b02612004-03-16 19:41:14 +00001167 VG_(details_version) (NULL);
nethercotec9f36922004-02-14 16:40:02 +00001168 VG_(details_description) ("a space profiler");
1169 VG_(details_copyright_author)("Copyright (C) 2003, Nicholas Nethercote");
nethercote27645c72004-02-23 15:33:33 +00001170 VG_(details_bug_reports_to) (VG_BUGS_TO);
nethercotec9f36922004-02-14 16:40:02 +00001171
1172 // Needs
1173 VG_(needs_libc_freeres)();
1174 VG_(needs_command_line_options)();
1175 VG_(needs_client_requests) ();
1176
1177 // Events to track
1178 VG_(init_new_mem_stack_signal) ( new_mem_stack_signal );
1179 VG_(init_die_mem_stack_signal) ( die_mem_stack_signal );
1180
1181 // Profiling events
njn31066fd2005-03-26 00:42:02 +00001182 VG_(register_profile_event)(VgpGetXPt, "get-XPt");
1183 VG_(register_profile_event)(VgpGetXPtSearch, "get-XPt-search");
1184 VG_(register_profile_event)(VgpCensus, "census");
1185 VG_(register_profile_event)(VgpCensusHeap, "census-heap");
1186 VG_(register_profile_event)(VgpCensusSnapshot, "census-snapshot");
1187 VG_(register_profile_event)(VgpCensusTreeSize, "census-treesize");
1188 VG_(register_profile_event)(VgpUpdateXCon, "update-XCon");
1189 VG_(register_profile_event)(VgpCalcSpacetime2, "calc-exact_ST_dbld");
1190 VG_(register_profile_event)(VgpPrintHp, "print-hp");
1191 VG_(register_profile_event)(VgpPrintXPts, "print-XPts");
nethercotec9f36922004-02-14 16:40:02 +00001192
1193 // HP_Chunks
1194 malloc_list = VG_(HT_construct)();
1195
1196 // Dummy node at top of the context structure.
1197 alloc_xpt = new_XPt(0, NULL, /*is_bottom*/False);
1198
njnca82cc02004-11-22 17:18:48 +00001199 tl_assert( VG_(getcwd_alloc)(&base_dir) );
nethercotec9f36922004-02-14 16:40:02 +00001200}
1201
njn26f02512004-11-22 18:33:15 +00001202void TL_(post_clo_init)(void)
nethercotec9f36922004-02-14 16:40:02 +00001203{
1204 ms_interval = 1;
1205
1206 // Do an initial sample for t = 0
1207 hp_census();
1208}
1209
1210/*------------------------------------------------------------*/
1211/*--- Instrumentation ---*/
1212/*------------------------------------------------------------*/
1213
sewardjd54babf2005-03-21 00:55:49 +00001214IRBB* TL_(instrument) ( IRBB* bb_in, VexGuestLayout* layout,
1215 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001216{
sewardjd54babf2005-03-21 00:55:49 +00001217 /* XXX Will Massif work when gWordTy != hWordTy ? */
njnee8a5862004-11-22 21:08:46 +00001218 return bb_in;
nethercotec9f36922004-02-14 16:40:02 +00001219}
1220
1221/*------------------------------------------------------------*/
1222/*--- Spacetime recomputation ---*/
1223/*------------------------------------------------------------*/
1224
nethercote43a15ce2004-08-30 19:15:12 +00001225// Although we've been calculating space-time along the way, because the
1226// earlier calculations were done at a finer timescale, the .approx_ST field
nethercotec9f36922004-02-14 16:40:02 +00001227// might not agree with what hp2ps sees, because we've thrown away some of
1228// the information. So recompute it at the scale that hp2ps sees, so we can
1229// confidently determine which contexts hp2ps will choose for displaying as
1230// distinct bands. This recomputation only happens to the significant ones
1231// that get printed in the .hp file, so it's cheap.
1232//
nethercote43a15ce2004-08-30 19:15:12 +00001233// The approx_ST calculation:
nethercotec9f36922004-02-14 16:40:02 +00001234// ( a[0]*d(0,1) + a[1]*(d(0,1) + d(1,2)) + ... + a[N-1]*d(N-2,N-1) ) / 2
1235// where
1236// a[N] is the space at census N
1237// d(A,B) is the time interval between censi A and B
1238// and
1239// d(A,B) + d(B,C) == d(A,C)
1240//
1241// Key point: we can calculate the area for a census without knowing the
1242// previous or subsequent censi's space; because any over/underestimates
1243// for this census will be reversed in the next, balancing out. This is
1244// important, as getting the previous/next census entry for a particular
1245// AP is a pain with this data structure, but getting the prev/next
1246// census time is easy.
1247//
nethercote43a15ce2004-08-30 19:15:12 +00001248// Each heap calculation gets added to its context's exact_ST_dbld field.
nethercotec9f36922004-02-14 16:40:02 +00001249// The ULong* values are all running totals, hence the use of "+=" everywhere.
1250
1251// This does the calculations for a single census.
nethercote43a15ce2004-08-30 19:15:12 +00001252static void calc_exact_ST_dbld2(Census* census, UInt d_t1_t2,
nethercotec9f36922004-02-14 16:40:02 +00001253 ULong* twice_heap_ST,
1254 ULong* twice_heap_admin_ST,
1255 ULong* twice_stack_ST)
1256{
1257 UInt i, j;
1258 XPtSnapshot* xpt_snapshot;
1259
1260 // Heap --------------------------------------------------------
1261 if (clo_heap) {
1262 for (i = 0; NULL != census->xtree_snapshots[i]; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001263 // Compute total heap exact_ST_dbld for the entire XTree using only
1264 // the top-XPt (the first XPt in xtree_snapshot).
nethercotec9f36922004-02-14 16:40:02 +00001265 *twice_heap_ST += d_t1_t2 * census->xtree_snapshots[i][0].space;
1266
nethercote43a15ce2004-08-30 19:15:12 +00001267 // Increment exact_ST_dbld for every XPt in xtree_snapshot (inc.
1268 // top one)
nethercotec9f36922004-02-14 16:40:02 +00001269 for (j = 0; NULL != census->xtree_snapshots[i][j].xpt; j++) {
1270 xpt_snapshot = & census->xtree_snapshots[i][j];
nethercote43a15ce2004-08-30 19:15:12 +00001271 xpt_snapshot->xpt->exact_ST_dbld += d_t1_t2 * xpt_snapshot->space;
nethercotec9f36922004-02-14 16:40:02 +00001272 }
1273 }
1274 *twice_heap_ST += d_t1_t2 * census->others_space;
1275 }
1276
1277 // Heap admin --------------------------------------------------
1278 if (clo_heap_admin > 0)
1279 *twice_heap_admin_ST += d_t1_t2 * census->heap_admin_space;
1280
1281 // Stack(s) ----------------------------------------------------
1282 if (clo_stacks)
1283 *twice_stack_ST += d_t1_t2 * census->stacks_space;
1284}
1285
1286// This does the calculations for all censi.
nethercote43a15ce2004-08-30 19:15:12 +00001287static void calc_exact_ST_dbld(ULong* heap2, ULong* heap_admin2, ULong* stack2)
nethercotec9f36922004-02-14 16:40:02 +00001288{
1289 UInt i, N = curr_census;
1290
1291 VGP_PUSHCC(VgpCalcSpacetime2);
1292
1293 *heap2 = 0;
1294 *heap_admin2 = 0;
1295 *stack2 = 0;
1296
1297 if (N <= 1)
1298 return;
1299
nethercote43a15ce2004-08-30 19:15:12 +00001300 calc_exact_ST_dbld2( &censi[0], censi[1].ms_time - censi[0].ms_time,
1301 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001302
1303 for (i = 1; i <= N-2; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001304 calc_exact_ST_dbld2( & censi[i], censi[i+1].ms_time - censi[i-1].ms_time,
1305 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001306 }
1307
nethercote43a15ce2004-08-30 19:15:12 +00001308 calc_exact_ST_dbld2( & censi[N-1], censi[N-1].ms_time - censi[N-2].ms_time,
1309 heap2, heap_admin2, stack2 );
nethercotec9f36922004-02-14 16:40:02 +00001310 // Now get rid of the halves. May lose a 0.5 on each, doesn't matter.
1311 *heap2 /= 2;
1312 *heap_admin2 /= 2;
1313 *stack2 /= 2;
1314
1315 VGP_POPCC(VgpCalcSpacetime2);
1316}
1317
1318/*------------------------------------------------------------*/
1319/*--- Writing the graph file ---*/
1320/*------------------------------------------------------------*/
1321
1322static Char* make_filename(Char* dir, Char* suffix)
1323{
1324 Char* filename;
1325
1326 /* Block is big enough for dir name + massif.<pid>.<suffix> */
1327 filename = VG_(malloc)((VG_(strlen)(dir) + 32)*sizeof(Char));
1328 VG_(sprintf)(filename, "%s/massif.%d%s", dir, VG_(getpid)(), suffix);
1329
1330 return filename;
1331}
1332
1333// Make string acceptable to hp2ps (sigh): remove spaces, escape parentheses.
1334static Char* clean_fnname(Char *d, Char* s)
1335{
1336 Char* dorig = d;
1337 while (*s) {
1338 if (' ' == *s) { *d = '%'; }
1339 else if ('(' == *s) { *d++ = '\\'; *d = '('; }
1340 else if (')' == *s) { *d++ = '\\'; *d = ')'; }
1341 else { *d = *s; };
1342 s++;
1343 d++;
1344 }
1345 *d = '\0';
1346 return dorig;
1347}
1348
1349static void file_err ( Char* file )
1350{
1351 VG_(message)(Vg_UserMsg, "error: can't open output file `%s'", file );
1352 VG_(message)(Vg_UserMsg, " ... so profile results will be missing.");
1353}
1354
1355/* Format, by example:
1356
1357 JOB "a.out -p"
1358 DATE "Fri Apr 17 11:43:45 1992"
1359 SAMPLE_UNIT "seconds"
1360 VALUE_UNIT "bytes"
1361 BEGIN_SAMPLE 0.00
1362 SYSTEM 24
1363 END_SAMPLE 0.00
1364 BEGIN_SAMPLE 1.00
1365 elim 180
1366 insert 24
1367 intersect 12
1368 disin 60
1369 main 12
1370 reduce 20
1371 SYSTEM 12
1372 END_SAMPLE 1.00
1373 MARK 1.50
1374 MARK 1.75
1375 MARK 1.80
1376 BEGIN_SAMPLE 2.00
1377 elim 192
1378 insert 24
1379 intersect 12
1380 disin 84
1381 main 12
1382 SYSTEM 24
1383 END_SAMPLE 2.00
1384 BEGIN_SAMPLE 2.82
1385 END_SAMPLE 2.82
1386 */
1387static void write_hp_file(void)
1388{
1389 Int i, j;
1390 Int fd, res;
1391 Char *hp_file, *ps_file, *aux_file;
1392 Char* cmdfmt;
1393 Char* cmdbuf;
1394 Int cmdlen;
1395
1396 VGP_PUSHCC(VgpPrintHp);
1397
1398 // Open file
1399 hp_file = make_filename( base_dir, ".hp" );
1400 ps_file = make_filename( base_dir, ".ps" );
1401 aux_file = make_filename( base_dir, ".aux" );
1402 fd = VG_(open)(hp_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1403 VKI_S_IRUSR|VKI_S_IWUSR);
1404 if (fd < 0) {
1405 file_err( hp_file );
1406 VGP_POPCC(VgpPrintHp);
1407 return;
1408 }
1409
1410 // File header, including command line
1411 SPRINTF(buf, "JOB \"");
1412 for (i = 0; i < VG_(client_argc); i++)
1413 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1414 SPRINTF(buf, /*" (%d ms/sample)\"\n"*/ "\"\n"
1415 "DATE \"\"\n"
1416 "SAMPLE_UNIT \"ms\"\n"
1417 "VALUE_UNIT \"bytes\"\n", ms_interval);
1418
1419 // Censi
1420 for (i = 0; i < curr_census; i++) {
1421 Census* census = & censi[i];
1422
1423 // Census start
1424 SPRINTF(buf, "MARK %d.0\n"
1425 "BEGIN_SAMPLE %d.0\n",
1426 census->ms_time, census->ms_time);
1427
1428 // Heap -----------------------------------------------------------
1429 if (clo_heap) {
1430 // Print all the significant XPts from that census
1431 for (j = 0; NULL != census->xtree_snapshots[j]; j++) {
1432 // Grab the jth top-XPt
1433 XTreeSnapshot xtree_snapshot = & census->xtree_snapshots[j][0];
njnd01fef72005-03-25 23:35:48 +00001434 if ( ! VG_(get_fnname)(xtree_snapshot->xpt->ip, buf2, 16)) {
nethercotec9f36922004-02-14 16:40:02 +00001435 VG_(sprintf)(buf2, "???");
1436 }
njnd01fef72005-03-25 23:35:48 +00001437 SPRINTF(buf, "x%x:%s %d\n", xtree_snapshot->xpt->ip,
nethercotec9f36922004-02-14 16:40:02 +00001438 clean_fnname(buf3, buf2), xtree_snapshot->space);
1439 }
1440
1441 // Remaining heap block alloc points, combined
1442 if (census->others_space > 0)
1443 SPRINTF(buf, "other %d\n", census->others_space);
1444 }
1445
1446 // Heap admin -----------------------------------------------------
1447 if (clo_heap_admin > 0 && census->heap_admin_space)
1448 SPRINTF(buf, "heap-admin %d\n", census->heap_admin_space);
1449
1450 // Stack(s) -------------------------------------------------------
1451 if (clo_stacks)
1452 SPRINTF(buf, "stack(s) %d\n", census->stacks_space);
1453
1454 // Census end
1455 SPRINTF(buf, "END_SAMPLE %d.0\n", census->ms_time);
1456 }
1457
1458 // Close file
njnca82cc02004-11-22 17:18:48 +00001459 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001460 VG_(close)(fd);
1461
1462 // Attempt to convert file using hp2ps
1463 cmdfmt = "%s/hp2ps -c -t1 %s";
1464 cmdlen = VG_(strlen)(VG_(libdir)) + VG_(strlen)(hp_file)
1465 + VG_(strlen)(cmdfmt);
1466 cmdbuf = VG_(malloc)( sizeof(Char) * cmdlen );
1467 VG_(sprintf)(cmdbuf, cmdfmt, VG_(libdir), hp_file);
1468 res = VG_(system)(cmdbuf);
1469 VG_(free)(cmdbuf);
1470 if (res != 0) {
1471 VG_(message)(Vg_UserMsg,
1472 "Conversion to PostScript failed. Try converting manually.");
1473 } else {
1474 // remove the .hp and .aux file
1475 VG_(unlink)(hp_file);
1476 VG_(unlink)(aux_file);
1477 }
1478
1479 VG_(free)(hp_file);
1480 VG_(free)(ps_file);
1481 VG_(free)(aux_file);
1482
1483 VGP_POPCC(VgpPrintHp);
1484}
1485
1486/*------------------------------------------------------------*/
1487/*--- Writing the XPt text/HTML file ---*/
1488/*------------------------------------------------------------*/
1489
1490static void percentify(Int n, Int pow, Int field_width, char xbuf[])
1491{
1492 int i, len, space;
1493
1494 VG_(sprintf)(xbuf, "%d.%d%%", n / pow, n % pow);
1495 len = VG_(strlen)(xbuf);
1496 space = field_width - len;
1497 if (space < 0) space = 0; /* Allow for v. small field_width */
1498 i = len;
1499
1500 /* Right justify in field */
1501 for ( ; i >= 0; i--) xbuf[i + space] = xbuf[i];
1502 for (i = 0; i < space; i++) xbuf[i] = ' ';
1503}
1504
1505// Nb: uses a static buffer, each call trashes the last string returned.
1506static Char* make_perc(ULong spacetime, ULong total_spacetime)
1507{
1508 static Char mbuf[32];
1509
1510 UInt p = 10;
njnca82cc02004-11-22 17:18:48 +00001511 tl_assert(0 != total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001512 percentify(spacetime * 100 * p / total_spacetime, p, 5, mbuf);
1513 return mbuf;
1514}
1515
njnd01fef72005-03-25 23:35:48 +00001516// Nb: passed in XPt is a lower-level XPt; IPs are grabbed from
nethercotec9f36922004-02-14 16:40:02 +00001517// bottom-to-top of XCon, and then printed in the reverse order.
1518static UInt pp_XCon(Int fd, XPt* xpt)
1519{
njnd01fef72005-03-25 23:35:48 +00001520 Addr rev_ips[clo_depth+1];
nethercotec9f36922004-02-14 16:40:02 +00001521 Int i = 0;
1522 Int n = 0;
1523 Bool is_HTML = ( XHTML == clo_format );
1524 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1525 Char* maybe_indent = ( is_HTML ? "&nbsp;&nbsp;" : "" );
1526
njnca82cc02004-11-22 17:18:48 +00001527 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +00001528
1529 while (True) {
njnd01fef72005-03-25 23:35:48 +00001530 rev_ips[i] = xpt->ip;
nethercotec9f36922004-02-14 16:40:02 +00001531 n++;
1532 if (alloc_xpt == xpt->parent) break;
1533 i++;
1534 xpt = xpt->parent;
1535 }
1536
1537 for (i = n-1; i >= 0; i--) {
1538 // -1 means point to calling line
njnd01fef72005-03-25 23:35:48 +00001539 VG_(describe_IP)(rev_ips[i]-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001540 SPRINTF(buf, " %s%s%s\n", maybe_indent, buf2, maybe_br);
1541 }
1542
1543 return n;
1544}
1545
1546// Important point: for HTML, each XPt must be identified uniquely for the
njnd01fef72005-03-25 23:35:48 +00001547// HTML links to all match up correctly. Using xpt->ip is not
nethercotec9f36922004-02-14 16:40:02 +00001548// sufficient, because function pointers mean that you can call more than
1549// one other function from a single code location. So instead we use the
1550// address of the xpt struct itself, which is guaranteed to be unique.
1551
1552static void pp_all_XPts2(Int fd, Queue* q, ULong heap_spacetime,
1553 ULong total_spacetime)
1554{
1555 UInt i;
1556 XPt *xpt, *child;
1557 UInt L = 0;
1558 UInt c1 = 1;
1559 UInt c2 = 0;
1560 ULong sum = 0;
1561 UInt n;
njnd01fef72005-03-25 23:35:48 +00001562 Char *ip_desc, *perc;
nethercotec9f36922004-02-14 16:40:02 +00001563 Bool is_HTML = ( XHTML == clo_format );
1564 Char* maybe_br = ( is_HTML ? "<br>" : "" );
1565 Char* maybe_p = ( is_HTML ? "<p>" : "" );
1566 Char* maybe_ul = ( is_HTML ? "<ul>" : "" );
1567 Char* maybe_li = ( is_HTML ? "<li>" : "" );
1568 Char* maybe_fli = ( is_HTML ? "</li>" : "" );
1569 Char* maybe_ful = ( is_HTML ? "</ul>" : "" );
1570 Char* end_hr = ( is_HTML ? "<hr>" :
1571 "=================================" );
1572 Char* depth = ( is_HTML ? "<code>--depth</code>" : "--depth" );
1573
nethercote43a15ce2004-08-30 19:15:12 +00001574 if (total_spacetime == 0) {
1575 SPRINTF(buf, "(No heap memory allocated)\n");
1576 return;
1577 }
1578
1579
nethercotec9f36922004-02-14 16:40:02 +00001580 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1581
1582 while (NULL != (xpt = (XPt*)dequeue(q))) {
nethercote43a15ce2004-08-30 19:15:12 +00001583 // Check that non-top-level XPts have a zero .approx_ST field.
njnca82cc02004-11-22 17:18:48 +00001584 if (xpt->parent != alloc_xpt) tl_assert( 0 == xpt->approx_ST );
nethercotec9f36922004-02-14 16:40:02 +00001585
nethercote43a15ce2004-08-30 19:15:12 +00001586 // Check that the sum of all children .exact_ST_dbld fields equals
1587 // parent's (unless alloc_xpt, when it should == 0).
nethercotec9f36922004-02-14 16:40:02 +00001588 if (alloc_xpt == xpt) {
njnca82cc02004-11-22 17:18:48 +00001589 tl_assert(0 == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001590 } else {
1591 sum = 0;
1592 for (i = 0; i < xpt->n_children; i++) {
nethercote43a15ce2004-08-30 19:15:12 +00001593 sum += xpt->children[i]->exact_ST_dbld;
nethercotec9f36922004-02-14 16:40:02 +00001594 }
njnca82cc02004-11-22 17:18:48 +00001595 //tl_assert(sum == xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001596 // It's possible that not all the children were included in the
nethercote43a15ce2004-08-30 19:15:12 +00001597 // exact_ST_dbld calculations. Hopefully almost all of them were, and
nethercotec9f36922004-02-14 16:40:02 +00001598 // all the important ones.
njnca82cc02004-11-22 17:18:48 +00001599// tl_assert(sum <= xpt->exact_ST_dbld);
1600// tl_assert(sum * 1.05 > xpt->exact_ST_dbld );
nethercote43a15ce2004-08-30 19:15:12 +00001601// if (sum != xpt->exact_ST_dbld) {
1602// VG_(printf)("%ld, %ld\n", sum, xpt->exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001603// }
1604 }
1605
1606 if (xpt == alloc_xpt) {
1607 SPRINTF(buf, "Heap allocation functions accounted for "
1608 "%s of measured spacetime%s\n",
1609 make_perc(heap_spacetime, total_spacetime), maybe_br);
1610 } else {
nethercote43a15ce2004-08-30 19:15:12 +00001611 // Remember: exact_ST_dbld is space.time *doubled*
1612 perc = make_perc(xpt->exact_ST_dbld / 2, total_spacetime);
nethercotec9f36922004-02-14 16:40:02 +00001613 if (is_HTML) {
1614 SPRINTF(buf, "<a name=\"b%x\"></a>"
1615 "Context accounted for "
1616 "<a href=\"#a%x\">%s</a> of measured spacetime<br>\n",
1617 xpt, xpt, perc);
1618 } else {
1619 SPRINTF(buf, "Context accounted for %s of measured spacetime\n",
1620 perc);
1621 }
1622 n = pp_XCon(fd, xpt);
njnca82cc02004-11-22 17:18:48 +00001623 tl_assert(n == L);
nethercotec9f36922004-02-14 16:40:02 +00001624 }
1625
nethercote43a15ce2004-08-30 19:15:12 +00001626 // Sort children by exact_ST_dbld
nethercotec9f36922004-02-14 16:40:02 +00001627 VG_(ssort)(xpt->children, xpt->n_children, sizeof(XPt*),
nethercote43a15ce2004-08-30 19:15:12 +00001628 XPt_cmp_exact_ST_dbld);
nethercotec9f36922004-02-14 16:40:02 +00001629
1630 SPRINTF(buf, "%s\nCalled from:%s\n", maybe_p, maybe_ul);
1631 for (i = 0; i < xpt->n_children; i++) {
1632 child = xpt->children[i];
1633
1634 // Stop when <1% of total spacetime
nethercote43a15ce2004-08-30 19:15:12 +00001635 if (child->exact_ST_dbld * 1000 / (total_spacetime * 2) < 5) {
nethercotec9f36922004-02-14 16:40:02 +00001636 UInt n_insig = xpt->n_children - i;
1637 Char* s = ( n_insig == 1 ? "" : "s" );
1638 Char* and = ( 0 == i ? "" : "and " );
1639 Char* other = ( 0 == i ? "" : "other " );
1640 SPRINTF(buf, " %s%s%d %sinsignificant place%s%s\n\n",
1641 maybe_li, and, n_insig, other, s, maybe_fli);
1642 break;
1643 }
1644
nethercote43a15ce2004-08-30 19:15:12 +00001645 // Remember: exact_ST_dbld is space.time *doubled*
njnd01fef72005-03-25 23:35:48 +00001646 perc = make_perc(child->exact_ST_dbld / 2, total_spacetime);
1647 ip_desc = VG_(describe_IP)(child->ip-1, buf2, BUF_LEN);
nethercotec9f36922004-02-14 16:40:02 +00001648 if (is_HTML) {
1649 SPRINTF(buf, "<li><a name=\"a%x\"></a>", child );
1650
1651 if (child->n_children > 0) {
1652 SPRINTF(buf, "<a href=\"#b%x\">%s</a>", child, perc);
1653 } else {
1654 SPRINTF(buf, "%s", perc);
1655 }
njnd01fef72005-03-25 23:35:48 +00001656 SPRINTF(buf, ": %s\n", ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001657 } else {
njnd01fef72005-03-25 23:35:48 +00001658 SPRINTF(buf, " %6s: %s\n\n", perc, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001659 }
1660
1661 if (child->n_children > 0) {
1662 enqueue(q, (void*)child);
1663 c2++;
1664 }
1665 }
1666 SPRINTF(buf, "%s%s", maybe_ful, maybe_p);
1667 c1--;
1668
1669 // Putting markers between levels of the structure:
1670 // c1 tracks how many to go on this level, c2 tracks how many we've
1671 // queued up for the next level while finishing off this level.
1672 // When c1 gets to zero, we've changed levels, so print a marker,
1673 // move c2 into c1, and zero c2.
1674 if (0 == c1) {
1675 L++;
1676 c1 = c2;
1677 c2 = 0;
1678 if (! is_empty_queue(q) ) { // avoid empty one at end
1679 SPRINTF(buf, "== %d ===========================%s\n", L, maybe_br);
1680 }
1681 } else {
1682 SPRINTF(buf, "---------------------------------%s\n", maybe_br);
1683 }
1684 }
1685 SPRINTF(buf, "%s\n\nEnd of information. Rerun with a bigger "
1686 "%s value for more.\n", end_hr, depth);
1687}
1688
1689static void pp_all_XPts(Int fd, XPt* xpt, ULong heap_spacetime,
1690 ULong total_spacetime)
1691{
1692 Queue* q = construct_queue(100);
nethercote43a15ce2004-08-30 19:15:12 +00001693
nethercotec9f36922004-02-14 16:40:02 +00001694 enqueue(q, xpt);
1695 pp_all_XPts2(fd, q, heap_spacetime, total_spacetime);
1696 destruct_queue(q);
1697}
1698
1699static void
1700write_text_file(ULong total_ST, ULong heap_ST)
1701{
1702 Int fd, i;
1703 Char* text_file;
1704 Char* maybe_p = ( XHTML == clo_format ? "<p>" : "" );
1705
1706 VGP_PUSHCC(VgpPrintXPts);
1707
1708 // Open file
1709 text_file = make_filename( base_dir,
1710 ( XText == clo_format ? ".txt" : ".html" ) );
1711
1712 fd = VG_(open)(text_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
1713 VKI_S_IRUSR|VKI_S_IWUSR);
1714 if (fd < 0) {
1715 file_err( text_file );
1716 VGP_POPCC(VgpPrintXPts);
1717 return;
1718 }
1719
1720 // Header
1721 if (XHTML == clo_format) {
1722 SPRINTF(buf, "<html>\n"
1723 "<head>\n"
1724 "<title>%s</title>\n"
1725 "</head>\n"
1726 "<body>\n",
1727 text_file);
1728 }
1729
1730 // Command line
1731 SPRINTF(buf, "Command: ");
1732 for (i = 0; i < VG_(client_argc); i++)
1733 SPRINTF(buf, "%s ", VG_(client_argv)[i]);
1734 SPRINTF(buf, "\n%s\n", maybe_p);
1735
1736 if (clo_heap)
1737 pp_all_XPts(fd, alloc_xpt, heap_ST, total_ST);
1738
njnca82cc02004-11-22 17:18:48 +00001739 tl_assert(fd >= 0);
nethercotec9f36922004-02-14 16:40:02 +00001740 VG_(close)(fd);
1741
1742 VGP_POPCC(VgpPrintXPts);
1743}
1744
1745/*------------------------------------------------------------*/
1746/*--- Finalisation ---*/
1747/*------------------------------------------------------------*/
1748
1749static void
1750print_summary(ULong total_ST, ULong heap_ST, ULong heap_admin_ST,
1751 ULong stack_ST)
1752{
1753 VG_(message)(Vg_UserMsg, "Total spacetime: %,ld ms.B", total_ST);
1754
1755 // Heap --------------------------------------------------------------
1756 if (clo_heap)
1757 VG_(message)(Vg_UserMsg, "heap: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001758 ( 0 == total_ST ? (Char*)"(n/a)"
1759 : make_perc(heap_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001760
1761 // Heap admin --------------------------------------------------------
1762 if (clo_heap_admin)
1763 VG_(message)(Vg_UserMsg, "heap admin: %s",
nethercote43a15ce2004-08-30 19:15:12 +00001764 ( 0 == total_ST ? (Char*)"(n/a)"
1765 : make_perc(heap_admin_ST, total_ST) ) );
nethercotec9f36922004-02-14 16:40:02 +00001766
njnca82cc02004-11-22 17:18:48 +00001767 tl_assert( VG_(HT_count_nodes)(malloc_list) == n_heap_blocks );
nethercotec9f36922004-02-14 16:40:02 +00001768
1769 // Stack(s) ----------------------------------------------------------
nethercote43a15ce2004-08-30 19:15:12 +00001770 if (clo_stacks) {
nethercotec9f36922004-02-14 16:40:02 +00001771 VG_(message)(Vg_UserMsg, "stack(s): %s",
sewardjb5f6f512005-03-10 23:59:00 +00001772 ( 0 == stack_ST ? (Char*)"0%"
1773 : make_perc(stack_ST, total_ST) ) );
nethercote43a15ce2004-08-30 19:15:12 +00001774 }
nethercotec9f36922004-02-14 16:40:02 +00001775
1776 if (VG_(clo_verbosity) > 1) {
njnca82cc02004-11-22 17:18:48 +00001777 tl_assert(n_xpts > 0); // always have alloc_xpt
nethercotec9f36922004-02-14 16:40:02 +00001778 VG_(message)(Vg_DebugMsg, " allocs: %u", n_allocs);
1779 VG_(message)(Vg_DebugMsg, "zeroallocs: %u (%d%%)", n_zero_allocs,
1780 n_zero_allocs * 100 / n_allocs );
1781 VG_(message)(Vg_DebugMsg, " frees: %u", n_frees);
1782 VG_(message)(Vg_DebugMsg, " XPts: %u (%d B)", n_xpts,
1783 n_xpts*sizeof(XPt));
1784 VG_(message)(Vg_DebugMsg, " bot-XPts: %u (%d%%)", n_bot_xpts,
1785 n_bot_xpts * 100 / n_xpts);
1786 VG_(message)(Vg_DebugMsg, " top-XPts: %u (%d%%)", alloc_xpt->n_children,
1787 alloc_xpt->n_children * 100 / n_xpts);
1788 VG_(message)(Vg_DebugMsg, "c-reallocs: %u", n_children_reallocs);
1789 VG_(message)(Vg_DebugMsg, "snap-frees: %u", n_snapshot_frees);
1790 VG_(message)(Vg_DebugMsg, "atmp censi: %u", n_attempted_censi);
1791 VG_(message)(Vg_DebugMsg, "fake censi: %u", n_fake_censi);
1792 VG_(message)(Vg_DebugMsg, "real censi: %u", n_real_censi);
1793 VG_(message)(Vg_DebugMsg, " halvings: %u", n_halvings);
1794 }
1795}
1796
njn26f02512004-11-22 18:33:15 +00001797void TL_(fini)(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00001798{
1799 ULong total_ST = 0;
1800 ULong heap_ST = 0;
1801 ULong heap_admin_ST = 0;
1802 ULong stack_ST = 0;
1803
1804 // Do a final (empty) sample to show program's end
1805 hp_census();
1806
1807 // Redo spacetimes of significant contexts to match the .hp file.
nethercote43a15ce2004-08-30 19:15:12 +00001808 calc_exact_ST_dbld(&heap_ST, &heap_admin_ST, &stack_ST);
nethercotec9f36922004-02-14 16:40:02 +00001809 total_ST = heap_ST + heap_admin_ST + stack_ST;
1810 write_hp_file ( );
1811 write_text_file( total_ST, heap_ST );
1812 print_summary ( total_ST, heap_ST, heap_admin_ST, stack_ST );
1813}
1814
njn26f02512004-11-22 18:33:15 +00001815VG_DETERMINE_INTERFACE_VERSION(TL_(pre_clo_init), 0)
nethercotec9f36922004-02-14 16:40:02 +00001816
1817/*--------------------------------------------------------------------*/
1818/*--- end ms_main.c ---*/
1819/*--------------------------------------------------------------------*/
1820