blob: 660a7188b749716df53a2b348d713117a94cfcc4 [file] [log] [blame]
njn734b8052007-11-01 04:40:37 +00001//--------------------------------------------------------------------*/
2//--- Massif: a heap profiling tool. ms_main.c ---*/
3//--------------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +00004
5/*
nethercote996901a2004-08-03 13:29:09 +00006 This file is part of Massif, a Valgrind tool for profiling memory
nethercotec9f36922004-02-14 16:40:02 +00007 usage of programs.
8
sewardj9ebd6e02007-01-08 06:01:59 +00009 Copyright (C) 2003-2007 Nicholas Nethercote
njn2bc10122005-05-08 02:10:27 +000010 njn@valgrind.org
nethercotec9f36922004-02-14 16:40:02 +000011
12 This program is free software; you can redistribute it and/or
13 modify it under the terms of the GNU General Public License as
14 published by the Free Software Foundation; either version 2 of the
15 License, or (at your option) any later version.
16
17 This program is distributed in the hope that it will be useful, but
18 WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25 02111-1307, USA.
26
27 The GNU General Public License is contained in the file COPYING.
28*/
29
njn734b8052007-11-01 04:40:37 +000030//---------------------------------------------------------------------------
31// XXX:
32//---------------------------------------------------------------------------
33// Todo -- critical for release:
njn62721e92007-11-11 22:15:58 +000034// - address/close all the bug reports below (after writing docs)
njn734b8052007-11-01 04:40:37 +000035// - do a graph-drawing test
njn374a36d2007-11-23 01:41:32 +000036// - Get Josef to update the Callgrind --callgrind-out-file option.
njn1a2741a2007-11-26 21:59:04 +000037// - Use '_' instead of '.' for detailed/peak bars?
38// - ms_print -- XXX on line 535
njndf02bbc2007-11-02 21:44:02 +000039//
njn734b8052007-11-01 04:40:37 +000040// Todo -- nice, but less critical:
41// - make file format more generic. Obstacles:
42// - unit prefixes are not generic
43// - preset column widths for stats are not generic
44// - preset column headers are not generic
45// - "Massif arguments:" line is not generic
46// - do snapshots on client requests
47// - (Michael Meeks): have an interactive way to request a dump
48// (callgrind_control-style)
49// - "profile now"
50// - "show me the extra allocations since the last snapshot"
51// - "start/stop logging" (eg. quickly skip boring bits)
52// - Add ability to draw multiple graphs, eg. heap-only, stack-only, total.
53// Give each graph a title. (try to do it generically!)
54// - allow truncation of long fnnames if the exact line number is
55// identified? [hmm, could make getting the name of alloc-fns more
56// difficult] [could dump full names to file, truncate in ms_print]
57// - make --show-below-main=no work
njn1a2741a2007-11-26 21:59:04 +000058// - Options like --alloc-fn='operator new(unsigned, std::nothrow_t const&)'
59// don't work in a .valgrindrc file or in $VALGRIND_OPTS.
60// m_commandline.c:add_args_from_string() needs to respect single quotes.
61//
njn734b8052007-11-01 04:40:37 +000062//
63// Performance:
64// - To run the benchmarks:
65//
66// perl perf/vg_perf --tools=massif --reps=3 perf/{heap,tinycc} massif
67// time valgrind --tool=massif --depth=100 konqueror
68//
69// The other benchmarks don't do much allocation, and so give similar speeds
70// to Nulgrind.
71//
72// Timing results on 'nevermore' (njn's machine) as of r7013:
73//
74// heap 0.53s ma:12.4s (23.5x, -----)
75// tinycc 0.46s ma: 4.9s (10.7x, -----)
76// many-xpts 0.08s ma: 2.0s (25.0x, -----)
77// konqueror 29.6s real 0:21.0s user
78//
79// - get_XCon accounts for about 9% of konqueror startup time. Try
80// keeping XPt children sorted by 'ip' and use binary search in get_XCon.
81// Requires factoring out binary search code from various places into a
82// VG_(bsearch) function.
83//
84// Todo -- low priority:
njn734b8052007-11-01 04:40:37 +000085// - In each XPt, record both bytes and the number of allocations, and
86// possibly the global number of allocations.
87// - (Artur Wisz) add a feature to Massif to ignore any heap blocks larger
88// than a certain size! Because: "linux's malloc allows to set a
89// MMAP_THRESHOLD value, so we set it to 4096 - all blocks above that will
90// be handled directly by the kernel, and are guaranteed to be returned to
91// the system when freed. So we needed to profile only blocks below this
92// limit."
93//
94// Examine and fix bugs on bugzilla:
95// IGNORE:
96// 112163 nor MASSIF crashed with signal 7 (SIGBUS) after running 2 days
97// - weird, crashes in VEX, ignore
98// 82871 nor Massif output function names too short
99// - on .ps graph, now irrelevant, ignore
100// 129576 nor Massif loses track of memory, incorrect graphs
101// - dunno, hard to reproduce, ignore
102// 132132 nor massif --format=html output does not do html entity escaping
103// - only for HTML output, irrelevant, ignore
104// 132950 Heap alloc/usage summary
105// - doesn't seem that interesting or general
106//
107// FIXED/NOW IRRELEVANT:
108// 89061 cra Massif: ms_main.c:485 (get_XCon): Assertion `xpt->max_chi...
109// - relevant code now gone
110// 143062 cra massif crashes on app exit with signal 8 SIGFPE
111// - fixed
112// 95483 nor massif feature request: include peak allocation in report
113// - implemented in Massif2
114// 92615 nor Write output from Massif at crash
115// - this happens unless Massif2 itself crashes
116// 121629 add instruction-counting mode for timing
117// - time-unit=B is similar, plus I'm considering this above anyway
118// 142197 nor massif tool ignores --massif:alloc-fn parameters in .valg...
119// - fixed in trunk
120// 142491 nor Maximise use of alloc_fns array
121// - addressed, it's now an XArray and thus unlimited in size
122// 144453 (get_XCon): Assertion 'xpt->max_children != 0' failed.
123// - relevant code now gone
124//
125// POSSIBLY FIXED BY BETTER SANITY CHECKING, BUT HARD TO TELL:
126// 141631 Massif: percentages don't add up correctly
127// - better sanity-checking should help this greatly
128// 142706 massif numbers don't seem to add up
129// - better sanity-checking should help this greatly
130// 149504 Assertion hit on alloc_xpt->curr_space >= -space_delta
131// - better sanity-checking should help this greatly
132// 146456 (update_XCon): Assertion 'xpt->curr_space >= -space_delta' failed.
133// - better sanity-checking should help this greatly
134//
135// File format working notes:
136
137#if 0
138desc: --heap-admin=foo
139cmd: date
140time_unit: ms
141#-----------
142snapshot=0
143#-----------
144time=0
145mem_heap_B=0
146mem_heap_admin_B=0
147mem_stacks_B=0
148heap_tree=empty
149#-----------
150snapshot=1
151#-----------
152time=353
153mem_heap_B=5
154mem_heap_admin_B=0
155mem_stacks_B=0
156heap_tree=detailed
157n1: 5 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
158 n1: 5 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
159 n1: 5 0x279DE6: _nl_load_locale_from_archive (in /lib/libc-2.3.5.so)
160 n1: 5 0x278E97: _nl_find_locale (in /lib/libc-2.3.5.so)
161 n1: 5 0x278871: setlocale (in /lib/libc-2.3.5.so)
162 n1: 5 0x8049821: (within /bin/date)
163 n0: 5 0x26ED5E: (below main) (in /lib/libc-2.3.5.so)
164
165
166n_events: n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
167t_events: B
168n 0 0 0 0 0
169n 0 0 0 0 0
170t1: 5 <string...>
171 t1: 6 <string...>
172
173Ideas:
174- each snapshot specifies an x-axis value and one or more y-axis values.
175- can display the y-axis values separately if you like
176- can completely separate connection between snapshots and trees.
177
178Challenges:
179- how to specify and scale/abbreviate units on axes?
180- how to combine multiple values into the y-axis?
181
182--------------------------------------------------------------------------------Command: date
183Massif arguments: --heap-admin=foo
184ms_print arguments: massif.out
185--------------------------------------------------------------------------------
186 KB
1876.472^ :#
188 | :# :: . .
189 ...
190 | ::@ :@ :@ :@:::# :: : ::::
191 0 +-----------------------------------@---@---@-----@--@---#-------------->ms 0 713
192
193Number of snapshots: 50
194 Detailed snapshots: [2, 11, 13, 19, 25, 32 (peak)]
195-------------------------------------------------------------------------------- n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
196-------------------------------------------------------------------------------- 0 0 0 0 0 0
197 1 345 5 5 0 0
198 2 353 5 5 0 0
199100.00% (5B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
200->100.00% (5B) 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
201#endif
202
203//---------------------------------------------------------------------------
nethercotec9f36922004-02-14 16:40:02 +0000204
njnc7561b92005-06-19 01:24:32 +0000205#include "pub_tool_basics.h"
sewardj4cfea4f2006-10-14 19:26:10 +0000206#include "pub_tool_vki.h"
sewardj45f4e7c2005-09-27 19:20:21 +0000207#include "pub_tool_aspacemgr.h"
njnea27e462005-05-31 02:38:09 +0000208#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +0000209#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +0000210#include "pub_tool_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +0000211#include "pub_tool_libcassert.h"
njneb8896b2005-06-04 20:03:55 +0000212#include "pub_tool_libcfile.h"
njn36a20fa2005-06-03 03:08:39 +0000213#include "pub_tool_libcprint.h"
njnf39e9a32005-06-12 02:43:17 +0000214#include "pub_tool_libcproc.h"
njnb506bd82005-06-21 04:01:51 +0000215#include "pub_tool_machine.h"
njn717cde52005-05-10 02:47:21 +0000216#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +0000217#include "pub_tool_options.h"
njn717cde52005-05-10 02:47:21 +0000218#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +0000219#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +0000220#include "pub_tool_tooliface.h"
sewardj14c7cc52007-02-25 15:08:24 +0000221#include "pub_tool_xarray.h"
sewardj45f4e7c2005-09-27 19:20:21 +0000222#include "pub_tool_clientstate.h"
nethercotec9f36922004-02-14 16:40:02 +0000223
224#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
225
njn734b8052007-11-01 04:40:37 +0000226//------------------------------------------------------------*/
227//--- Overview of operation ---*/
228//------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +0000229
njn734b8052007-11-01 04:40:37 +0000230// The size of the stacks and heap is tracked. The heap is tracked in a lot
231// of detail, enough to tell how many bytes each line of code is responsible
232// for, more or less. The main data structure is a tree representing the
233// call tree beneath all the allocation functions like malloc().
nethercotec9f36922004-02-14 16:40:02 +0000234//
njn734b8052007-11-01 04:40:37 +0000235// "Snapshots" are recordings of the memory usage. There are two basic
236// kinds:
237// - Normal: these record the current time, total memory size, total heap
238// size, heap admin size and stack size.
239// - Detailed: these record those things in a normal snapshot, plus a very
240// detailed XTree (see below) indicating how the heap is structured.
nethercotec9f36922004-02-14 16:40:02 +0000241//
njn734b8052007-11-01 04:40:37 +0000242// Snapshots are taken every so often. There are two storage classes of
243// snapshots:
244// - Temporary: Massif does a temporary snapshot every so often. The idea
245// is to always have a certain number of temporary snapshots around. So
246// we take them frequently to begin with, but decreasingly often as the
247// program continues to run. Also, we remove some old ones after a while.
248// Overall it's a kind of exponential decay thing. Most of these are
249// normal snapshots, a small fraction are detailed snapshots.
250// - Permanent: Massif takes a permanent (detailed) snapshot in some
251// circumstances. They are:
252// - Peak snapshot: When the memory usage peak is reached, it takes a
253// snapshot. It keeps this, unless the peak is subsequently exceeded,
254// in which case it will overwrite the peak snapshot.
255// - User-requested snapshots: These are done in response to client
256// requests. They are always kept.
nethercotec9f36922004-02-14 16:40:02 +0000257
njn734b8052007-11-01 04:40:37 +0000258// Used for printing things when clo_verbosity > 1.
259#define VERB(verb, format, args...) \
260 if (VG_(clo_verbosity) > verb) { \
261 VG_(message)(Vg_DebugMsg, "Massif: " format, ##args); \
nethercotec9f36922004-02-14 16:40:02 +0000262 }
nethercotec9f36922004-02-14 16:40:02 +0000263
nethercotec9f36922004-02-14 16:40:02 +0000264
nethercotec9f36922004-02-14 16:40:02 +0000265
njn734b8052007-11-01 04:40:37 +0000266//------------------------------------------------------------//
267//--- Statistics ---//
268//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000269
270// Konqueror startup, to give an idea of the numbers involved with a biggish
271// program, with default depth:
272//
273// depth=3 depth=40
274// - 310,000 allocations
275// - 300,000 frees
276// - 15,000 XPts 800,000 XPts
277// - 1,800 top-XPts
278
njn734b8052007-11-01 04:40:37 +0000279static UInt n_heap_allocs = 0;
280static UInt n_heap_reallocs = 0;
281static UInt n_heap_frees = 0;
282static UInt n_stack_allocs = 0;
283static UInt n_stack_frees = 0;
284static UInt n_xpts = 0;
285static UInt n_xpt_init_expansions = 0;
286static UInt n_xpt_later_expansions = 0;
287static UInt n_sxpt_allocs = 0;
288static UInt n_sxpt_frees = 0;
289static UInt n_skipped_snapshots = 0;
290static UInt n_real_snapshots = 0;
291static UInt n_detailed_snapshots = 0;
292static UInt n_peak_snapshots = 0;
293static UInt n_cullings = 0;
294static UInt n_XCon_redos = 0;
nethercotec9f36922004-02-14 16:40:02 +0000295
njn734b8052007-11-01 04:40:37 +0000296//------------------------------------------------------------//
297//--- Globals ---//
298//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000299
njn1a2741a2007-11-26 21:59:04 +0000300// Number of guest instructions executed so far. Only used with
301// --time-unit=i.
302static Long guest_instrs_executed = 0;
303
njn32397c02007-11-10 04:08:08 +0000304static SizeT heap_szB = 0; // Live heap size
305static SizeT heap_extra_szB = 0; // Live heap extra size -- slop + admin bytes
306static SizeT stacks_szB = 0; // Live stacks size
nethercotec9f36922004-02-14 16:40:02 +0000307
njn734b8052007-11-01 04:40:37 +0000308// This is the total size from the current peak snapshot, or 0 if no peak
309// snapshot has been taken yet.
310static SizeT peak_snapshot_total_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000311
njn734b8052007-11-01 04:40:37 +0000312// Incremented every time memory is allocated/deallocated, by the
313// allocated/deallocated amount; includes heap, heap-admin and stack
314// memory. An alternative to milliseconds as a unit of program "time".
315static ULong total_allocs_deallocs_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000316
njn734b8052007-11-01 04:40:37 +0000317// We don't start taking snapshots until the first basic block is executed,
318// rather than doing it in ms_post_clo_init (which is the obvious spot), for
319// two reasons.
320// - It lets us ignore stack events prior to that, because they're not
321// really proper ones and just would screw things up.
322// - Because there's still some core initialisation to do, and so there
323// would be an artificial time gap between the first and second snapshots.
324//
325static Bool have_started_executing_code = False;
nethercotec9f36922004-02-14 16:40:02 +0000326
njn734b8052007-11-01 04:40:37 +0000327//------------------------------------------------------------//
328//--- Alloc fns ---//
329//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000330
njn734b8052007-11-01 04:40:37 +0000331static XArray* alloc_fns;
nethercotec9f36922004-02-14 16:40:02 +0000332
njn734b8052007-11-01 04:40:37 +0000333static void init_alloc_fns(void)
334{
335 // Create the list, and add the default elements.
336 alloc_fns = VG_(newXA)(VG_(malloc), VG_(free), sizeof(Char*));
337 #define DO(x) { Char* s = x; VG_(addToXA)(alloc_fns, &s); }
nethercotec9f36922004-02-14 16:40:02 +0000338
njn734b8052007-11-01 04:40:37 +0000339 // Ordered according to (presumed) frequency.
340 // Nb: The C++ "operator new*" ones are overloadable. We include them
341 // always anyway, because even if they're overloaded, it would be a
342 // prodigiously stupid overloading that caused them to not allocate
343 // memory.
344 DO("malloc" );
345 DO("__builtin_new" );
346 DO("operator new(unsigned)" );
347 DO("operator new(unsigned long)" );
348 DO("__builtin_vec_new" );
349 DO("operator new[](unsigned)" );
350 DO("operator new[](unsigned long)" );
351 DO("calloc" );
352 DO("realloc" );
353 DO("memalign" );
354 DO("operator new(unsigned, std::nothrow_t const&)" );
355 DO("operator new[](unsigned, std::nothrow_t const&)" );
356 DO("operator new(unsigned long, std::nothrow_t const&)" );
357 DO("operator new[](unsigned long, std::nothrow_t const&)");
358}
nethercotec9f36922004-02-14 16:40:02 +0000359
njn734b8052007-11-01 04:40:37 +0000360static Bool is_alloc_fn(Char* fnname)
361{
362 Char** alloc_fn_ptr;
363 Int i;
364
365 // Nb: It's a linear search through the list, because we're comparing
366 // strings rather than pointers to strings.
367 // Nb: This gets called a lot. It was an OSet, but they're quite slow to
368 // iterate through so it wasn't a good choice.
369 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
370 alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
371 if (VG_STREQ(fnname, *alloc_fn_ptr))
372 return True;
nethercotec9f36922004-02-14 16:40:02 +0000373 }
njn734b8052007-11-01 04:40:37 +0000374 return False;
375}
nethercotec9f36922004-02-14 16:40:02 +0000376
njn734b8052007-11-01 04:40:37 +0000377
378//------------------------------------------------------------//
379//--- Command line args ---//
380//------------------------------------------------------------//
381
382#define MAX_DEPTH 200
383
njn1a2741a2007-11-26 21:59:04 +0000384typedef enum { TimeI, TimeMS, TimeB } TimeUnit;
njn734b8052007-11-01 04:40:37 +0000385
386static Char* TimeUnit_to_string(TimeUnit time_unit)
387{
388 switch (time_unit) {
njn1a2741a2007-11-26 21:59:04 +0000389 case TimeI: return "i";
njn734b8052007-11-01 04:40:37 +0000390 case TimeMS: return "ms";
391 case TimeB: return "B";
392 default: tl_assert2(0, "TimeUnit_to_string: unrecognised TimeUnit");
393 }
394}
395
396static Bool clo_heap = True;
njn429afb42007-11-02 04:12:48 +0000397 // clo_heap_admin is deliberately a word-sized type. At one point it was
398 // a UInt, but this caused problems on 64-bit machines when it was
399 // multiplied by a small negative number and then promoted to a
400 // word-sized type -- it ended up with a value of 4.2 billion. Sigh.
njn62721e92007-11-11 22:15:58 +0000401static SizeT clo_heap_admin = 8;
402static Bool clo_stacks = False;
403static UInt clo_depth = 30;
404static double clo_threshold = 1.0; // percentage
405static double clo_peak_inaccuracy = 1.0; // percentage
njn1a2741a2007-11-26 21:59:04 +0000406static UInt clo_time_unit = TimeI;
njn62721e92007-11-11 22:15:58 +0000407static UInt clo_detailed_freq = 10;
408static UInt clo_max_snapshots = 100;
njnf4c665f2007-11-20 07:55:40 +0000409static Char* clo_massif_out_file = "massif.out.%p";
njn734b8052007-11-01 04:40:37 +0000410
411static XArray* args_for_massif;
nethercotec9f36922004-02-14 16:40:02 +0000412
njn51d827b2005-05-09 01:02:08 +0000413static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000414{
njn734b8052007-11-01 04:40:37 +0000415 // Remember the arg for later use.
416 VG_(addToXA)(args_for_massif, &arg);
nethercotec9f36922004-02-14 16:40:02 +0000417
njn734b8052007-11-01 04:40:37 +0000418 VG_BOOL_CLO(arg, "--heap", clo_heap)
419 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
420
njn734b8052007-11-01 04:40:37 +0000421 else VG_NUM_CLO(arg, "--heap-admin", clo_heap_admin)
422 else VG_NUM_CLO(arg, "--depth", clo_depth)
423
njn62721e92007-11-11 22:15:58 +0000424 else VG_DBL_CLO(arg, "--threshold", clo_threshold)
njn734b8052007-11-01 04:40:37 +0000425
njn62721e92007-11-11 22:15:58 +0000426 else VG_DBL_CLO(arg, "--peak-inaccuracy", clo_peak_inaccuracy)
njn734b8052007-11-01 04:40:37 +0000427
428 else VG_NUM_CLO(arg, "--detailed-freq", clo_detailed_freq)
429 else VG_NUM_CLO(arg, "--max-snapshots", clo_max_snapshots)
430
njn1a2741a2007-11-26 21:59:04 +0000431 else if (VG_CLO_STREQ(arg, "--time-unit=i")) clo_time_unit = TimeI;
njn734b8052007-11-01 04:40:37 +0000432 else if (VG_CLO_STREQ(arg, "--time-unit=ms")) clo_time_unit = TimeMS;
433 else if (VG_CLO_STREQ(arg, "--time-unit=B")) clo_time_unit = TimeB;
nethercotec9f36922004-02-14 16:40:02 +0000434
435 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
njn734b8052007-11-01 04:40:37 +0000436 Char* alloc_fn = &arg[11];
437 VG_(addToXA)(alloc_fns, &alloc_fn);
nethercotec9f36922004-02-14 16:40:02 +0000438 }
439
njnf4c665f2007-11-20 07:55:40 +0000440 else if (VG_CLO_STREQN(14, arg, "--massif-out-file=")) {
441 clo_massif_out_file = &arg[18];
442 }
443
nethercotec9f36922004-02-14 16:40:02 +0000444 else
445 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000446
nethercotec9f36922004-02-14 16:40:02 +0000447 return True;
448}
449
njn51d827b2005-05-09 01:02:08 +0000450static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000451{
njn734b8052007-11-01 04:40:37 +0000452 VG_(printf)(
nethercotec9f36922004-02-14 16:40:02 +0000453" --heap=no|yes profile heap blocks [yes]\n"
njn1a2741a2007-11-26 21:59:04 +0000454" --heap-admin=<number> average admin bytes per heap block;\n"
njn734b8052007-11-01 04:40:37 +0000455" ignored if --heap=no [8]\n"
456" --stacks=no|yes profile stack(s) [no]\n"
457" --depth=<number> depth of contexts [30]\n"
nethercotec9f36922004-02-14 16:40:02 +0000458" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
njn62721e92007-11-11 22:15:58 +0000459" --threshold=<m.n> significance threshold, as a percentage [1.0]\n"
460" --peak-inaccuracy=<m.n> maximum peak inaccuracy, as a percentage [1.0]\n"
njn1a2741a2007-11-26 21:59:04 +0000461" --time-unit=i|ms|B time unit: instructions executed, milliseconds\n"
462" or heap bytes alloc'd/dealloc'd [i]\n"
njn734b8052007-11-01 04:40:37 +0000463" --detailed-freq=<N> every Nth snapshot should be detailed [10]\n"
464" --max-snapshots=<N> maximum number of snapshots recorded [100]\n"
njn374a36d2007-11-23 01:41:32 +0000465" --massif-out-file=<file> output file name [massif.out.%%p]\n"
nethercotec9f36922004-02-14 16:40:02 +0000466 );
467 VG_(replacement_malloc_print_usage)();
468}
469
njn51d827b2005-05-09 01:02:08 +0000470static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000471{
472 VG_(replacement_malloc_print_debug_usage)();
473}
474
njn734b8052007-11-01 04:40:37 +0000475
476//------------------------------------------------------------//
477//--- XPts, XTrees and XCons ---//
478//------------------------------------------------------------//
479
480// An XPt represents an "execution point", ie. a code address. Each XPt is
481// part of a tree of XPts (an "execution tree", or "XTree"). The details of
482// the heap are represented by a single XTree.
483//
484// The root of the tree is 'alloc_xpt', which represents all allocation
485// functions, eg:
486// - malloc/calloc/realloc/memalign/new/new[];
487// - user-specified allocation functions (using --alloc-fn);
488// - custom allocation (MALLOCLIKE) points
489// It's a bit of a fake XPt (ie. its 'ip' is zero), and is only used because
490// it makes the code simpler.
491//
492// Any child of 'alloc_xpt' is called a "top-XPt". The XPts at the bottom
493// of an XTree (leaf nodes) are "bottom-XPTs".
494//
495// Each path from a top-XPt to a bottom-XPt through an XTree gives an
496// execution context ("XCon"), ie. a stack trace. (And sub-paths represent
497// stack sub-traces.) The number of XCons in an XTree is equal to the
498// number of bottom-XPTs in that XTree.
499//
500// alloc_xpt XTrees are bi-directional.
501// | ^
502// v |
503// > parent < Example: if child1() calls parent() and child2()
504// / | \ also calls parent(), and parent() calls malloc(),
505// | / \ | the XTree will look like this.
506// | v v |
507// child1 child2
508//
509// XTrees and XPts are mirrored by SXTrees and SXPts, where the 'S' is short
510// for "saved". When the XTree is duplicated for a snapshot, we duplicate
511// it as an SXTree, which is similar but omits some things it does not need,
512// and aggregates up insignificant nodes. This is important as an SXTree is
513// typically much smaller than an XTree.
514
515// XXX: make XPt and SXPt extensible arrays, to avoid having to do two
516// allocations per Pt.
517
518typedef struct _XPt XPt;
519struct _XPt {
520 Addr ip; // code address
521
522 // Bottom-XPts: space for the precise context.
523 // Other XPts: space of all the descendent bottom-XPts.
524 // Nb: this value goes up and down as the program executes.
525 SizeT szB;
526
527 XPt* parent; // pointer to parent XPt
528
529 // Children.
530 // n_children and max_children are 32-bit integers. 16-bit integers
531 // are too small -- a very big program might have more than 65536
532 // allocation points (ie. top-XPts) -- Konqueror starting up has 1800.
533 UInt n_children; // number of children
534 UInt max_children; // capacity of children array
535 XPt** children; // pointers to children XPts
536};
537
538typedef
539 enum {
540 SigSXPt,
541 InsigSXPt
542 }
543 SXPtTag;
544
545typedef struct _SXPt SXPt;
546struct _SXPt {
547 SXPtTag tag;
548 SizeT szB; // memory size for the node, be it Sig or Insig
549 union {
550 // An SXPt representing a single significant code location. Much like
551 // an XPt, minus the fields that aren't necessary.
552 struct {
553 Addr ip;
554 UInt n_children;
555 SXPt** children;
556 }
557 Sig;
558
559 // An SXPt representing one or more code locations, all below the
560 // significance threshold.
561 struct {
562 Int n_xpts; // number of aggregated XPts
563 }
564 Insig;
565 };
566};
nethercotec9f36922004-02-14 16:40:02 +0000567
568// Fake XPt representing all allocation functions like malloc(). Acts as
569// parent node to all top-XPts.
570static XPt* alloc_xpt;
571
572// Cheap allocation for blocks that never need to be freed. Saves about 10%
573// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000574static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000575{
576 static Addr hp = 0; // current heap pointer
577 static Addr hp_lim = 0; // maximum usable byte in current block
578
579 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
580
581 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000582 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
583 if (hp == 0)
njn734b8052007-11-01 04:40:37 +0000584 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
sewardj45f4e7c2005-09-27 19:20:21 +0000585 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000586 hp_lim = hp + SUPERBLOCK_SIZE - 1;
587 }
588
589 hp += n_bytes;
590
591 return (void*)(hp - n_bytes);
592}
593
njn734b8052007-11-01 04:40:37 +0000594static XPt* new_XPt(Addr ip, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000595{
njn734b8052007-11-01 04:40:37 +0000596 // XPts are never freed, so we can use perm_malloc to allocate them.
597 // Note that we cannot use perm_malloc for the 'children' array, because
598 // that needs to be resizable.
599 XPt* xpt = perm_malloc(sizeof(XPt));
600 xpt->ip = ip;
601 xpt->szB = 0;
602 xpt->parent = parent;
nethercotec9f36922004-02-14 16:40:02 +0000603
njn734b8052007-11-01 04:40:37 +0000604 // We don't initially allocate any space for children. We let that
605 // happen on demand. Many XPts (ie. all the bottom-XPts) don't have any
606 // children anyway.
nethercotec9f36922004-02-14 16:40:02 +0000607 xpt->n_children = 0;
njn734b8052007-11-01 04:40:37 +0000608 xpt->max_children = 0;
609 xpt->children = NULL;
nethercotec9f36922004-02-14 16:40:02 +0000610
611 // Update statistics
612 n_xpts++;
613
614 return xpt;
615}
616
njn734b8052007-11-01 04:40:37 +0000617static void add_child_xpt(XPt* parent, XPt* child)
618{
619 // Expand 'children' if necessary.
620 tl_assert(parent->n_children <= parent->max_children);
621 if (parent->n_children == parent->max_children) {
622 if (parent->max_children == 0) {
623 parent->max_children = 4;
624 parent->children = VG_(malloc)( parent->max_children * sizeof(XPt*) );
625 n_xpt_init_expansions++;
626 } else {
627 parent->max_children *= 2; // Double size
628 parent->children = VG_(realloc)( parent->children,
629 parent->max_children * sizeof(XPt*) );
630 n_xpt_later_expansions++;
631 }
632 }
633
634 // Insert new child XPt in parent's children list.
635 parent->children[ parent->n_children++ ] = child;
636}
637
638// Reverse comparison for a reverse sort -- biggest to smallest.
639static Int SXPt_revcmp_szB(void* n1, void* n2)
640{
641 SXPt* sxpt1 = *(SXPt**)n1;
642 SXPt* sxpt2 = *(SXPt**)n2;
643 return ( sxpt1->szB < sxpt2->szB ? 1
644 : sxpt1->szB > sxpt2->szB ? -1
645 : 0);
646}
647
648//------------------------------------------------------------//
649//--- XTree Operations ---//
650//------------------------------------------------------------//
651
652// Duplicates an XTree as an SXTree.
653static SXPt* dup_XTree(XPt* xpt, SizeT total_szB)
654{
655 Int i, n_sig_children, n_insig_children, n_child_sxpts;
656 SizeT insig_children_szB, sig_child_threshold_szB;
657 SXPt* sxpt;
658
659 // Number of XPt children Action for SXPT
660 // ------------------ ---------------
661 // 0 sig, 0 insig alloc 0 children
662 // N sig, 0 insig alloc N children, dup all
663 // N sig, M insig alloc N+1, dup first N, aggregate remaining M
664 // 0 sig, M insig alloc 1, aggregate M
665
666 // Work out how big a child must be to be significant. If the current
667 // total_szB is zero, then we set it to 1, which means everything will be
668 // judged insignificant -- this is sensible, as there's no point showing
669 // any detail for this case. Unless they used --threshold=0, in which
670 // case we show them everything because that's what they asked for.
671 //
672 // Nb: We do this once now, rather than once per child, because if we do
673 // that the cost of all the divisions adds up to something significant.
674 if (total_szB == 0 && clo_threshold != 0) {
675 sig_child_threshold_szB = 1;
676 } else {
njn62721e92007-11-11 22:15:58 +0000677 sig_child_threshold_szB = (SizeT)((total_szB * clo_threshold) / 100);
njn734b8052007-11-01 04:40:37 +0000678 }
679
680 // How many children are significant? And do we need an aggregate SXPt?
681 n_sig_children = 0;
682 for (i = 0; i < xpt->n_children; i++) {
683 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
684 n_sig_children++;
685 }
686 }
687 n_insig_children = xpt->n_children - n_sig_children;
688 n_child_sxpts = n_sig_children + ( n_insig_children > 0 ? 1 : 0 );
689
690 // Duplicate the XPt.
691 sxpt = VG_(malloc)(sizeof(SXPt));
692 n_sxpt_allocs++;
693 sxpt->tag = SigSXPt;
694 sxpt->szB = xpt->szB;
695 sxpt->Sig.ip = xpt->ip;
696 sxpt->Sig.n_children = n_child_sxpts;
697
698 // Create the SXPt's children.
699 if (n_child_sxpts > 0) {
700 Int j;
701 SizeT sig_children_szB = 0;
702 sxpt->Sig.children = VG_(malloc)(n_child_sxpts * sizeof(SXPt*));
703
704 // Duplicate the significant children.
705 j = 0;
706 for (i = 0; i < xpt->n_children; i++) {
707 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
708 sxpt->Sig.children[j++] = dup_XTree(xpt->children[i], total_szB);
709 sig_children_szB += xpt->children[i]->szB;
710 }
711 }
712
713 // Create the SXPt for the insignificant children, if any, and put it
714 // in the last child entry.
715 insig_children_szB = sxpt->szB - sig_children_szB;
716 if (n_insig_children > 0) {
717 // Nb: We 'n_sxpt_allocs' here because creating an Insig SXPt
718 // doesn't involve a call to dup_XTree().
719 SXPt* insig_sxpt = VG_(malloc)(sizeof(SXPt));
720 n_sxpt_allocs++;
721 insig_sxpt->tag = InsigSXPt;
722 insig_sxpt->szB = insig_children_szB;
723 insig_sxpt->Insig.n_xpts = n_insig_children;
724 sxpt->Sig.children[n_sig_children] = insig_sxpt;
725 }
726 } else {
727 sxpt->Sig.children = NULL;
728 }
729
730 return sxpt;
731}
732
733static void free_SXTree(SXPt* sxpt)
734{
735 Int i;
736 tl_assert(sxpt != NULL);
737
738 switch (sxpt->tag) {
739 case SigSXPt:
740 // Free all children SXPts, then the children array.
741 for (i = 0; i < sxpt->Sig.n_children; i++) {
742 free_SXTree(sxpt->Sig.children[i]);
743 sxpt->Sig.children[i] = NULL;
744 }
745 VG_(free)(sxpt->Sig.children); sxpt->Sig.children = NULL;
746 break;
747
748 case InsigSXPt:
749 break;
750
751 default: tl_assert2(0, "free_SXTree: unknown SXPt tag");
752 }
753
754 // Free the SXPt itself.
755 VG_(free)(sxpt); sxpt = NULL;
756 n_sxpt_frees++;
757}
758
759// Sanity checking: we periodically check the heap XTree with
760// ms_expensive_sanity_check.
761static void sanity_check_XTree(XPt* xpt, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000762{
763 Int i;
764
njn734b8052007-11-01 04:40:37 +0000765 tl_assert(xpt != NULL);
766
767 // Check back-pointer.
768 tl_assert2(xpt->parent == parent,
769 "xpt->parent = %p, parent = %p\n", xpt->parent, parent);
770
771 // Check children counts look sane.
772 tl_assert(xpt->n_children <= xpt->max_children);
773
774 // Check the sum of any children szBs equals the XPt's szB. Check the
775 // children at the same time.
776 if (xpt->n_children > 0) {
777 SizeT children_sum_szB = 0;
778 for (i = 0; i < xpt->n_children; i++) {
779 sanity_check_XTree(xpt->children[i], xpt);
780 children_sum_szB += xpt->children[i]->szB;
nethercotec9f36922004-02-14 16:40:02 +0000781 }
njn734b8052007-11-01 04:40:37 +0000782 tl_assert(children_sum_szB == xpt->szB);
nethercotec9f36922004-02-14 16:40:02 +0000783 }
nethercotec9f36922004-02-14 16:40:02 +0000784}
785
njn734b8052007-11-01 04:40:37 +0000786// Sanity checking: we check SXTrees (which are in snapshots) after
787// snapshots are created, before they are deleted, and before they are
788// printed.
789static void sanity_check_SXTree(SXPt* sxpt)
nethercotec9f36922004-02-14 16:40:02 +0000790{
njn734b8052007-11-01 04:40:37 +0000791 Int i;
nethercotec9f36922004-02-14 16:40:02 +0000792
njn734b8052007-11-01 04:40:37 +0000793 tl_assert(sxpt != NULL);
nethercotec9f36922004-02-14 16:40:02 +0000794
njn734b8052007-11-01 04:40:37 +0000795 // Check the sum of any children szBs equals the SXPt's szB. Check the
796 // children at the same time.
797 switch (sxpt->tag) {
798 case SigSXPt: {
799 if (sxpt->Sig.n_children > 0) {
800 SizeT children_sum_szB = 0;
801 for (i = 0; i < sxpt->Sig.n_children; i++) {
802 sanity_check_SXTree(sxpt->Sig.children[i]);
803 children_sum_szB += sxpt->Sig.children[i]->szB;
804 }
805 tl_assert(children_sum_szB == sxpt->szB);
806 }
807 break;
808 }
809 case InsigSXPt:
810 break; // do nothing
811
812 default: tl_assert2(0, "sanity_check_SXTree: unknown SXPt tag");
813 }
814}
815
816
817//------------------------------------------------------------//
818//--- XCon Operations ---//
819//------------------------------------------------------------//
820
821// This is the limit on the number of removed alloc-fns that can be in a
822// single XCon.
823#define MAX_OVERESTIMATE 50
824#define MAX_IPS (MAX_DEPTH + MAX_OVERESTIMATE)
825
826// Get the stack trace for an XCon, filtering out uninteresting entries:
827// alloc-fns and entries above alloc-fns, and entries below main-or-below-main.
828// Eg: alloc-fn1 / alloc-fn2 / a / b / main / (below main) / c
829// becomes: a / b / main
830// Nb: it's possible to end up with an empty trace, eg. if 'main' is marked
831// as an alloc-fn. This is ok.
832static
833Int get_IPs( ThreadId tid, Bool is_custom_alloc, Addr ips[])
834{
835 #define BUF_LEN 1024
836 Char buf[BUF_LEN];
837 Int n_ips, i, n_alloc_fns_removed;
838 Int overestimate;
839 Bool redo;
840
841 // We ask for a few more IPs than clo_depth suggests we need. Then we
842 // remove every entry that is an alloc-fn. Depending on the
843 // circumstances, we may need to redo it all, asking for more IPs.
844 // Details:
845 // - If the original stack trace is smaller than asked-for, redo=False
846 // - Else if after filtering we have >= clo_depth IPs, redo=False
847 // - Else redo=True
848 // In other words, to redo, we'd have to get a stack trace as big as we
849 // asked for and remove more than 'overestimate' alloc-fns.
850
851 // Main loop.
852 redo = True; // Assume this to begin with.
853 for (overestimate = 3; redo; overestimate += 6) {
854 // This should never happen -- would require MAX_OVERESTIMATE
855 // alloc-fns to be removed from the stack trace.
856 if (overestimate > MAX_OVERESTIMATE)
857 VG_(tool_panic)("get_IPs: ips[] too small, inc. MAX_OVERESTIMATE?");
858
859 // Ask for more IPs than clo_depth suggests we need.
sewardj39f34232007-11-09 23:02:28 +0000860 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate,
861 0/*first_ip_delta*/ );
njn734b8052007-11-01 04:40:37 +0000862 tl_assert(n_ips > 0);
nethercotec9f36922004-02-14 16:40:02 +0000863
njn734b8052007-11-01 04:40:37 +0000864 // If the original stack trace is smaller than asked-for, redo=False.
865 if (n_ips < clo_depth + overestimate) { redo = False; }
nethercotec9f36922004-02-14 16:40:02 +0000866
njn734b8052007-11-01 04:40:37 +0000867 // If it's a non-custom block, we will always remove the first stack
868 // trace entry (which will be one of malloc, __builtin_new, etc).
869 n_alloc_fns_removed = ( is_custom_alloc ? 0 : 1 );
nethercotec9f36922004-02-14 16:40:02 +0000870
njn734b8052007-11-01 04:40:37 +0000871 // Filter out alloc fns. If it's a non-custom block, we remove the
872 // first entry (which will be one of malloc, __builtin_new, etc)
873 // without looking at it, because VG_(get_fnname) is expensive (it
874 // involves calls to VG_(malloc)/VG_(free)).
875 for (i = n_alloc_fns_removed; i < n_ips; i++) {
876 if (VG_(get_fnname)(ips[i], buf, BUF_LEN)) {
877 if (is_alloc_fn(buf)) {
878 n_alloc_fns_removed++;
879 } else {
880 break;
881 }
882 }
883 }
884 // Remove the alloc fns by shuffling the rest down over them.
885 n_ips -= n_alloc_fns_removed;
886 for (i = 0; i < n_ips; i++) {
887 ips[i] = ips[i + n_alloc_fns_removed];
888 }
nethercotec9f36922004-02-14 16:40:02 +0000889
njn734b8052007-11-01 04:40:37 +0000890 // If after filtering we have >= clo_depth IPs, redo=False
891 if (n_ips >= clo_depth) {
892 redo = False;
893 n_ips = clo_depth; // Ignore any IPs below --depth.
894 }
895
896 if (redo) {
897 n_XCon_redos++;
nethercotec9f36922004-02-14 16:40:02 +0000898 }
899 }
njn734b8052007-11-01 04:40:37 +0000900 return n_ips;
901}
nethercotec9f36922004-02-14 16:40:02 +0000902
njn734b8052007-11-01 04:40:37 +0000903// Gets an XCon and puts it in the tree. Returns the XCon's bottom-XPt.
904static XPt* get_XCon( ThreadId tid, Bool is_custom_alloc )
905{
906 Addr ips[MAX_IPS];
907 Int i;
908 XPt* xpt = alloc_xpt;
nethercotec9f36922004-02-14 16:40:02 +0000909
njn734b8052007-11-01 04:40:37 +0000910 // After this call, the IPs we want are in ips[0]..ips[n_ips-1].
911 Int n_ips = get_IPs(tid, is_custom_alloc, ips);
912
913 // Now do the search/insertion of the XCon.
914 for (i = 0; i < n_ips; i++) {
915 Addr ip = ips[i];
916 Int ch;
njnd01fef72005-03-25 23:35:48 +0000917 // Look for IP in xpt's children.
njn734b8052007-11-01 04:40:37 +0000918 // Linear search, ugh -- about 10% of time for konqueror startup tried
919 // caching last result, only hit about 4% for konqueror.
nethercotec9f36922004-02-14 16:40:02 +0000920 // Nb: this search hits about 98% of the time for konqueror
njn734b8052007-11-01 04:40:37 +0000921 for (ch = 0; True; ch++) {
922 if (ch == xpt->n_children) {
923 // IP not found in the children.
924 // Create and add new child XPt, then stop.
925 XPt* new_child_xpt = new_XPt(ip, xpt);
926 add_child_xpt(xpt, new_child_xpt);
927 xpt = new_child_xpt;
928 break;
nethercotec9f36922004-02-14 16:40:02 +0000929
njn734b8052007-11-01 04:40:37 +0000930 } else if (ip == xpt->children[ch]->ip) {
931 // Found the IP in the children, stop.
932 xpt = xpt->children[ch];
nethercotec9f36922004-02-14 16:40:02 +0000933 break;
934 }
nethercotec9f36922004-02-14 16:40:02 +0000935 }
nethercotec9f36922004-02-14 16:40:02 +0000936 }
njn734b8052007-11-01 04:40:37 +0000937 tl_assert(0 == xpt->n_children); // Must be bottom-XPt
938 return xpt;
nethercotec9f36922004-02-14 16:40:02 +0000939}
940
njn734b8052007-11-01 04:40:37 +0000941// Update 'szB' of every XPt in the XCon, by percolating upwards.
942static void update_XCon(XPt* xpt, SSizeT space_delta)
nethercotec9f36922004-02-14 16:40:02 +0000943{
njnca82cc02004-11-22 17:18:48 +0000944 tl_assert(True == clo_heap);
njnca82cc02004-11-22 17:18:48 +0000945 tl_assert(NULL != xpt);
946 tl_assert(0 == xpt->n_children); // must be bottom-XPt
nethercotec9f36922004-02-14 16:40:02 +0000947
njn734b8052007-11-01 04:40:37 +0000948 if (0 == space_delta)
949 return;
950
nethercotec9f36922004-02-14 16:40:02 +0000951 while (xpt != alloc_xpt) {
njn734b8052007-11-01 04:40:37 +0000952 if (space_delta < 0) tl_assert(xpt->szB >= -space_delta);
953 xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000954 xpt = xpt->parent;
njn734b8052007-11-01 04:40:37 +0000955 }
956 if (space_delta < 0) tl_assert(alloc_xpt->szB >= -space_delta);
957 alloc_xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000958}
959
960
njn734b8052007-11-01 04:40:37 +0000961//------------------------------------------------------------//
962//--- Snapshots ---//
963//------------------------------------------------------------//
964
965// Snapshots are done in a way so that we always have a reasonable number of
966// them. We start by taking them quickly. Once we hit our limit, we cull
967// some (eg. half), and start taking them more slowly. Once we hit the
968// limit again, we again cull and then take them even more slowly, and so
969// on.
970
njn1a2741a2007-11-26 21:59:04 +0000971// Time is measured either in i or ms or bytes, depending on the --time-unit
njn734b8052007-11-01 04:40:37 +0000972// option. It's a Long because it can exceed 32-bits reasonably easily, and
973// because we need to allow negative values to represent unset times.
974typedef Long Time;
975
976#define UNUSED_SNAPSHOT_TIME -333 // A conspicuous negative number.
977
978typedef
979 enum {
980 Normal = 77,
981 Peak,
982 Unused
983 }
984 SnapshotKind;
nethercotec9f36922004-02-14 16:40:02 +0000985
986typedef
987 struct {
njn734b8052007-11-01 04:40:37 +0000988 SnapshotKind kind;
989 Time time;
990 SizeT heap_szB;
njn32397c02007-11-10 04:08:08 +0000991 SizeT heap_extra_szB;// Heap slop + admin bytes.
njn734b8052007-11-01 04:40:37 +0000992 SizeT stacks_szB;
993 SXPt* alloc_sxpt; // Heap XTree root, if a detailed snapshot,
njn32397c02007-11-10 04:08:08 +0000994 } // otherwise NULL.
njn734b8052007-11-01 04:40:37 +0000995 Snapshot;
nethercotec9f36922004-02-14 16:40:02 +0000996
njn734b8052007-11-01 04:40:37 +0000997static UInt next_snapshot_i = 0; // Index of where next snapshot will go.
998static Snapshot* snapshots; // Array of snapshots.
999
1000static Bool is_snapshot_in_use(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001001{
njn734b8052007-11-01 04:40:37 +00001002 if (Unused == snapshot->kind) {
1003 // If snapshot is unused, check all the fields are unset.
1004 tl_assert(snapshot->time == UNUSED_SNAPSHOT_TIME);
njn32397c02007-11-10 04:08:08 +00001005 tl_assert(snapshot->heap_extra_szB == 0);
njn734b8052007-11-01 04:40:37 +00001006 tl_assert(snapshot->heap_szB == 0);
1007 tl_assert(snapshot->stacks_szB == 0);
1008 tl_assert(snapshot->alloc_sxpt == NULL);
1009 return False;
nethercotec9f36922004-02-14 16:40:02 +00001010 } else {
njn734b8052007-11-01 04:40:37 +00001011 tl_assert(snapshot->time != UNUSED_SNAPSHOT_TIME);
1012 return True;
nethercotec9f36922004-02-14 16:40:02 +00001013 }
1014}
1015
njn734b8052007-11-01 04:40:37 +00001016static Bool is_detailed_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001017{
njn734b8052007-11-01 04:40:37 +00001018 return (snapshot->alloc_sxpt ? True : False);
nethercotec9f36922004-02-14 16:40:02 +00001019}
1020
njn734b8052007-11-01 04:40:37 +00001021static Bool is_uncullable_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001022{
njn734b8052007-11-01 04:40:37 +00001023 return &snapshots[0] == snapshot // First snapshot
1024 || &snapshots[next_snapshot_i-1] == snapshot // Last snapshot
1025 || snapshot->kind == Peak; // Peak snapshot
nethercotec9f36922004-02-14 16:40:02 +00001026}
1027
njn734b8052007-11-01 04:40:37 +00001028static void sanity_check_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001029{
njn734b8052007-11-01 04:40:37 +00001030 if (snapshot->alloc_sxpt) {
1031 sanity_check_SXTree(snapshot->alloc_sxpt);
1032 }
nethercotec9f36922004-02-14 16:40:02 +00001033}
1034
njn734b8052007-11-01 04:40:37 +00001035// All the used entries should look used, all the unused ones should be clear.
1036static void sanity_check_snapshots_array(void)
1037{
1038 Int i;
1039 for (i = 0; i < next_snapshot_i; i++) {
1040 tl_assert( is_snapshot_in_use( & snapshots[i] ));
1041 }
1042 for ( ; i < clo_max_snapshots; i++) {
1043 tl_assert(!is_snapshot_in_use( & snapshots[i] ));
1044 }
1045}
nethercotec9f36922004-02-14 16:40:02 +00001046
njn734b8052007-11-01 04:40:37 +00001047// This zeroes all the fields in the snapshot, but does not free the heap
1048// XTree if present. It also does a sanity check unless asked not to; we
1049// can't sanity check at startup when clearing the initial snapshots because
1050// they're full of junk.
1051static void clear_snapshot(Snapshot* snapshot, Bool do_sanity_check)
1052{
1053 if (do_sanity_check) sanity_check_snapshot(snapshot);
1054 snapshot->kind = Unused;
1055 snapshot->time = UNUSED_SNAPSHOT_TIME;
njn32397c02007-11-10 04:08:08 +00001056 snapshot->heap_extra_szB = 0;
njn734b8052007-11-01 04:40:37 +00001057 snapshot->heap_szB = 0;
1058 snapshot->stacks_szB = 0;
1059 snapshot->alloc_sxpt = NULL;
1060}
1061
1062// This zeroes all the fields in the snapshot, and frees the heap XTree if
1063// present.
1064static void delete_snapshot(Snapshot* snapshot)
1065{
1066 // Nb: if there's an XTree, we free it after calling clear_snapshot,
1067 // because clear_snapshot does a sanity check which includes checking the
1068 // XTree.
1069 SXPt* tmp_sxpt = snapshot->alloc_sxpt;
1070 clear_snapshot(snapshot, /*do_sanity_check*/True);
1071 if (tmp_sxpt) {
1072 free_SXTree(tmp_sxpt);
1073 }
1074}
1075
1076static void VERB_snapshot(Int verbosity, Char* prefix, Int i)
1077{
1078 Snapshot* snapshot = &snapshots[i];
1079 Char* suffix;
1080 switch (snapshot->kind) {
1081 case Peak: suffix = "p"; break;
1082 case Normal: suffix = ( is_detailed_snapshot(snapshot) ? "d" : "." ); break;
1083 case Unused: suffix = "u"; break;
1084 default:
1085 tl_assert2(0, "VERB_snapshot: unknown snapshot kind: %d", snapshot->kind);
1086 }
njn32397c02007-11-10 04:08:08 +00001087 VERB(verbosity, "%s S%s%3d (t:%lld, hp:%ld, ex:%ld, st:%ld)",
njn734b8052007-11-01 04:40:37 +00001088 prefix, suffix, i,
1089 snapshot->time,
1090 snapshot->heap_szB,
njn32397c02007-11-10 04:08:08 +00001091 snapshot->heap_extra_szB,
njn734b8052007-11-01 04:40:37 +00001092 snapshot->stacks_szB
1093 );
1094}
1095
1096// Cull half the snapshots; we choose those that represent the smallest
1097// time-spans, because that gives us the most even distribution of snapshots
1098// over time. (It's possible to lose interesting spikes, however.)
1099//
1100// Algorithm for N snapshots: We find the snapshot representing the smallest
1101// timeframe, and remove it. We repeat this until (N/2) snapshots are gone.
1102// We have to do this one snapshot at a time, rather than finding the (N/2)
1103// smallest snapshots in one hit, because when a snapshot is removed, its
1104// neighbours immediately cover greater timespans. So it's O(N^2), but N is
1105// small, and it's not done very often.
1106//
1107// Once we're done, we return the new smallest interval between snapshots.
1108// That becomes our minimum time interval.
1109static UInt cull_snapshots(void)
1110{
1111 Int i, jp, j, jn, min_timespan_i;
1112 Int n_deleted = 0;
1113 Time min_timespan;
1114
1115 n_cullings++;
1116
1117 // Sets j to the index of the first not-yet-removed snapshot at or after i
1118 #define FIND_SNAPSHOT(i, j) \
1119 for (j = i; \
1120 j < clo_max_snapshots && !is_snapshot_in_use(&snapshots[j]); \
1121 j++) { }
1122
1123 VERB(2, "Culling...");
1124
1125 // First we remove enough snapshots by clearing them in-place. Once
1126 // that's done, we can slide the remaining ones down.
1127 for (i = 0; i < clo_max_snapshots/2; i++) {
1128 // Find the snapshot representing the smallest timespan. The timespan
1129 // for snapshot n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
1130 // snapshot A and B. We don't consider the first and last snapshots for
1131 // removal.
1132 Snapshot* min_snapshot;
1133 Int min_j;
1134
1135 // Initial triple: (prev, curr, next) == (jp, j, jn)
1136 // Initial min_timespan is the first one.
1137 jp = 0;
1138 FIND_SNAPSHOT(1, j);
1139 FIND_SNAPSHOT(j+1, jn);
1140 min_timespan = 0x7fffffffffffffffLL;
1141 min_j = -1;
1142 while (jn < clo_max_snapshots) {
1143 Time timespan = snapshots[jn].time - snapshots[jp].time;
1144 tl_assert(timespan >= 0);
1145 // Nb: We never cull the peak snapshot.
1146 if (Peak != snapshots[j].kind && timespan < min_timespan) {
1147 min_timespan = timespan;
1148 min_j = j;
1149 }
1150 // Move on to next triple
1151 jp = j;
1152 j = jn;
1153 FIND_SNAPSHOT(jn+1, jn);
1154 }
1155 // We've found the least important snapshot, now delete it. First
1156 // print it if necessary.
1157 tl_assert(-1 != min_j); // Check we found a minimum.
1158 min_snapshot = & snapshots[ min_j ];
1159 if (VG_(clo_verbosity) > 1) {
1160 Char buf[64];
1161 VG_(snprintf)(buf, 64, " %3d (t-span = %lld)", i, min_timespan);
1162 VERB_snapshot(2, buf, min_j);
1163 }
1164 delete_snapshot(min_snapshot);
1165 n_deleted++;
1166 }
1167
1168 // Slide down the remaining snapshots over the removed ones. First set i
1169 // to point to the first empty slot, and j to the first full slot after
1170 // i. Then slide everything down.
1171 for (i = 0; is_snapshot_in_use( &snapshots[i] ); i++) { }
1172 for (j = i; !is_snapshot_in_use( &snapshots[j] ); j++) { }
1173 for ( ; j < clo_max_snapshots; j++) {
1174 if (is_snapshot_in_use( &snapshots[j] )) {
1175 snapshots[i++] = snapshots[j];
1176 clear_snapshot(&snapshots[j], /*do_sanity_check*/True);
1177 }
1178 }
1179 next_snapshot_i = i;
1180
1181 // Check snapshots array looks ok after changes.
1182 sanity_check_snapshots_array();
1183
1184 // Find the minimum timespan remaining; that will be our new minimum
1185 // time interval. Note that above we were finding timespans by measuring
1186 // two intervals around a snapshot that was under consideration for
1187 // deletion. Here we only measure single intervals because all the
1188 // deletions have occurred.
1189 //
1190 // But we have to be careful -- some snapshots (eg. snapshot 0, and the
1191 // peak snapshot) are uncullable. If two uncullable snapshots end up
1192 // next to each other, they'll never be culled (assuming the peak doesn't
1193 // change), and the time gap between them will not change. However, the
1194 // time between the remaining cullable snapshots will grow ever larger.
1195 // This means that the min_timespan found will always be that between the
1196 // two uncullable snapshots, and it will be much smaller than it should
1197 // be. To avoid this problem, when computing the minimum timespan, we
1198 // ignore any timespans between two uncullable snapshots.
1199 tl_assert(next_snapshot_i > 1);
1200 min_timespan = 0x7fffffffffffffffLL;
1201 min_timespan_i = -1;
1202 for (i = 1; i < next_snapshot_i; i++) {
1203 if (is_uncullable_snapshot(&snapshots[i]) &&
1204 is_uncullable_snapshot(&snapshots[i-1]))
1205 {
1206 VERB(2, "(Ignoring interval %d--%d when computing minimum)", i-1, i);
1207 } else {
1208 Time timespan = snapshots[i].time - snapshots[i-1].time;
1209 tl_assert(timespan >= 0);
1210 if (timespan < min_timespan) {
1211 min_timespan = timespan;
1212 min_timespan_i = i;
1213 }
1214 }
1215 }
1216 tl_assert(-1 != min_timespan_i); // Check we found a minimum.
1217
1218 // Print remaining snapshots, if necessary.
1219 if (VG_(clo_verbosity) > 1) {
1220 VERB(2, "Finished culling (%3d of %3d deleted)",
1221 n_deleted, clo_max_snapshots);
1222 for (i = 0; i < next_snapshot_i; i++) {
1223 VERB_snapshot(2, " post-cull", i);
1224 }
1225 VERB(2, "New time interval = %lld (between snapshots %d and %d)",
1226 min_timespan, min_timespan_i-1, min_timespan_i);
1227 }
1228
1229 return min_timespan;
1230}
1231
1232static Time get_time(void)
1233{
1234 // Get current time, in whatever time unit we're using.
njn1a2741a2007-11-26 21:59:04 +00001235 if (clo_time_unit == TimeI) {
1236 return guest_instrs_executed;
1237 } else if (clo_time_unit == TimeMS) {
njn734b8052007-11-01 04:40:37 +00001238 // Some stuff happens between the millisecond timer being initialised
1239 // to zero and us taking our first snapshot. We determine that time
1240 // gap so we can subtract it from all subsequent times so that our
1241 // first snapshot is considered to be at t = 0ms. Unfortunately, a
1242 // bunch of symbols get read after the first snapshot is taken but
1243 // before the second one (which is triggered by the first allocation),
1244 // so when the time-unit is 'ms' we always have a big gap between the
1245 // first two snapshots. But at least users won't have to wonder why
1246 // the first snapshot isn't at t=0.
1247 static Bool is_first_get_time = True;
1248 static Time start_time_ms;
1249 if (is_first_get_time) {
1250 start_time_ms = VG_(read_millisecond_timer)();
1251 is_first_get_time = False;
1252 return 0;
1253 } else {
1254 return VG_(read_millisecond_timer)() - start_time_ms;
1255 }
1256 } else if (clo_time_unit == TimeB) {
1257 return total_allocs_deallocs_szB;
1258 } else {
1259 tl_assert2(0, "bad --time-unit value");
1260 }
1261}
1262
1263// Take a snapshot, and only that -- decisions on whether to take a
1264// snapshot, or what kind of snapshot, are made elsewhere.
1265static void
1266take_snapshot(Snapshot* snapshot, SnapshotKind kind, Time time,
1267 Bool is_detailed, Char* what)
1268{
1269 tl_assert(!is_snapshot_in_use(snapshot));
1270 tl_assert(have_started_executing_code);
1271
1272 // Heap and heap admin.
1273 if (clo_heap) {
1274 snapshot->heap_szB = heap_szB;
1275 if (is_detailed) {
njn32397c02007-11-10 04:08:08 +00001276 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001277 snapshot->alloc_sxpt = dup_XTree(alloc_xpt, total_szB);
1278 tl_assert( alloc_xpt->szB == heap_szB);
1279 tl_assert(snapshot->alloc_sxpt->szB == heap_szB);
1280 }
njn32397c02007-11-10 04:08:08 +00001281 snapshot->heap_extra_szB = heap_extra_szB;
njn734b8052007-11-01 04:40:37 +00001282 }
1283
1284 // Stack(s).
1285 if (clo_stacks) {
1286 snapshot->stacks_szB = stacks_szB;
1287 }
1288
1289 // Rest of snapshot.
1290 snapshot->kind = kind;
1291 snapshot->time = time;
1292 sanity_check_snapshot(snapshot);
1293
1294 // Update stats.
1295 if (Peak == kind) n_peak_snapshots++;
1296 if (is_detailed) n_detailed_snapshots++;
1297 n_real_snapshots++;
1298}
1299
1300
1301// Take a snapshot, if it's time, or if we've hit a peak.
1302static void
1303maybe_take_snapshot(SnapshotKind kind, Char* what)
1304{
1305 // 'min_time_interval' is the minimum time interval between snapshots.
1306 // If we try to take a snapshot and less than this much time has passed,
1307 // we don't take it. It gets larger as the program runs longer. It's
1308 // initialised to zero so that we begin by taking snapshots as quickly as
1309 // possible.
1310 static Time min_time_interval = 0;
1311 // Zero allows startup snapshot.
1312 static Time earliest_possible_time_of_next_snapshot = 0;
1313 static Int n_snapshots_since_last_detailed = 0;
1314 static Int n_skipped_snapshots_since_last_snapshot = 0;
1315
1316 Snapshot* snapshot;
1317 Bool is_detailed;
1318 Time time = get_time();
1319
1320 switch (kind) {
1321 case Normal:
1322 // Only do a snapshot if it's time.
1323 if (time < earliest_possible_time_of_next_snapshot) {
1324 n_skipped_snapshots++;
1325 n_skipped_snapshots_since_last_snapshot++;
1326 return;
1327 }
1328 is_detailed = (clo_detailed_freq-1 == n_snapshots_since_last_detailed);
1329 break;
1330
1331 case Peak: {
1332 // Because we're about to do a deallocation, we're coming down from a
1333 // local peak. If it is (a) actually a global peak, and (b) a certain
1334 // amount bigger than the previous peak, then we take a peak snapshot.
1335 // By not taking a snapshot for every peak, we save a lot of effort --
1336 // because many peaks remain peak only for a short time.
njn32397c02007-11-10 04:08:08 +00001337 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001338 SizeT excess_szB_for_new_peak =
njn62721e92007-11-11 22:15:58 +00001339 (SizeT)((peak_snapshot_total_szB * clo_peak_inaccuracy) / 100);
njn734b8052007-11-01 04:40:37 +00001340 if (total_szB <= peak_snapshot_total_szB + excess_szB_for_new_peak) {
1341 return;
1342 }
1343 is_detailed = True;
1344 break;
1345 }
1346
1347 default:
1348 tl_assert2(0, "maybe_take_snapshot: unrecognised snapshot kind");
1349 }
1350
1351 // Take the snapshot.
1352 snapshot = & snapshots[next_snapshot_i];
1353 take_snapshot(snapshot, kind, time, is_detailed, what);
1354
1355 // Record if it was detailed.
1356 if (is_detailed) {
1357 n_snapshots_since_last_detailed = 0;
1358 } else {
1359 n_snapshots_since_last_detailed++;
1360 }
1361
1362 // Update peak data, if it's a Peak snapshot.
1363 if (Peak == kind) {
1364 Int i, number_of_peaks_snapshots_found = 0;
1365
1366 // Sanity check the size, then update our recorded peak.
1367 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00001368 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00001369 tl_assert2(snapshot_total_szB > peak_snapshot_total_szB,
1370 "%ld, %ld\n", snapshot_total_szB, peak_snapshot_total_szB);
1371 peak_snapshot_total_szB = snapshot_total_szB;
1372
1373 // Find the old peak snapshot, if it exists, and mark it as normal.
1374 for (i = 0; i < next_snapshot_i; i++) {
1375 if (Peak == snapshots[i].kind) {
1376 snapshots[i].kind = Normal;
1377 number_of_peaks_snapshots_found++;
1378 }
1379 }
1380 tl_assert(number_of_peaks_snapshots_found <= 1);
1381 }
1382
1383 // Finish up verbosity and stats stuff.
1384 if (n_skipped_snapshots_since_last_snapshot > 0) {
1385 VERB(2, " (skipped %d snapshot%s)",
1386 n_skipped_snapshots_since_last_snapshot,
1387 ( n_skipped_snapshots_since_last_snapshot == 1 ? "" : "s") );
1388 }
1389 VERB_snapshot(2, what, next_snapshot_i);
1390 n_skipped_snapshots_since_last_snapshot = 0;
1391
1392 // Cull the entries, if our snapshot table is full.
1393 next_snapshot_i++;
1394 if (clo_max_snapshots == next_snapshot_i) {
1395 min_time_interval = cull_snapshots();
1396 }
1397
1398 // Work out the earliest time when the next snapshot can happen.
1399 earliest_possible_time_of_next_snapshot = time + min_time_interval;
1400}
1401
1402
1403//------------------------------------------------------------//
1404//--- Sanity checking ---//
1405//------------------------------------------------------------//
1406
1407static Bool ms_cheap_sanity_check ( void )
1408{
1409 return True; // Nothing useful we can cheaply check.
1410}
1411
1412static Bool ms_expensive_sanity_check ( void )
1413{
1414 sanity_check_XTree(alloc_xpt, /*parent*/NULL);
1415 sanity_check_snapshots_array();
1416 return True;
1417}
1418
1419
1420//------------------------------------------------------------//
1421//--- Heap management ---//
1422//------------------------------------------------------------//
1423
1424// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
1425// which is a foothold into the XCon at which it was allocated. From
1426// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
1427// decremented (at deallocation).
1428//
1429// Nb: first two fields must match core's VgHashNode.
1430typedef
1431 struct _HP_Chunk {
1432 struct _HP_Chunk* next;
njn32397c02007-11-10 04:08:08 +00001433 Addr data; // Ptr to actual block
1434 SizeT req_szB; // Size requested
1435 SizeT slop_szB; // Extra bytes given above those requested
1436 XPt* where; // Where allocated; bottom-XPt
njn734b8052007-11-01 04:40:37 +00001437 }
1438 HP_Chunk;
1439
1440static VgHashTable malloc_list = NULL; // HP_Chunks
1441
1442static void update_alloc_stats(SSizeT szB_delta)
1443{
1444 // Update total_allocs_deallocs_szB.
1445 if (szB_delta < 0) szB_delta = -szB_delta;
1446 total_allocs_deallocs_szB += szB_delta;
1447}
1448
njn32397c02007-11-10 04:08:08 +00001449static void update_heap_stats(SSizeT heap_szB_delta, Int heap_extra_szB_delta)
njn734b8052007-11-01 04:40:37 +00001450{
njn32397c02007-11-10 04:08:08 +00001451 if (heap_szB_delta < 0)
1452 tl_assert(heap_szB >= -heap_szB_delta);
1453 if (heap_extra_szB_delta < 0)
1454 tl_assert(heap_extra_szB >= -heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001455
njn32397c02007-11-10 04:08:08 +00001456 heap_extra_szB += heap_extra_szB_delta;
1457 heap_szB += heap_szB_delta;
1458
1459 update_alloc_stats(heap_szB_delta + heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001460}
nethercotec9f36922004-02-14 16:40:02 +00001461
nethercote159dfef2004-09-13 13:27:30 +00001462static
njn32397c02007-11-10 04:08:08 +00001463void* new_block ( ThreadId tid, void* p, SizeT req_szB, SizeT req_alignB,
njn57735902004-11-25 18:04:54 +00001464 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +00001465{
1466 HP_Chunk* hc;
njn734b8052007-11-01 04:40:37 +00001467 Bool is_custom_alloc = (NULL != p);
njn32397c02007-11-10 04:08:08 +00001468 SizeT actual_szB, slop_szB;
1469
1470 if (req_szB < 0) return NULL;
nethercotec9f36922004-02-14 16:40:02 +00001471
nethercote57e36b32004-07-10 14:56:28 +00001472 // Allocate and zero if necessary
1473 if (!p) {
njn32397c02007-11-10 04:08:08 +00001474 p = VG_(cli_malloc)( req_alignB, req_szB );
nethercote57e36b32004-07-10 14:56:28 +00001475 if (!p) {
nethercote57e36b32004-07-10 14:56:28 +00001476 return NULL;
1477 }
njn32397c02007-11-10 04:08:08 +00001478 if (is_zeroed) VG_(memset)(p, 0, req_szB);
1479 actual_szB = VG_(malloc_usable_size)(p);
1480 tl_assert(actual_szB >= req_szB);
1481 slop_szB = actual_szB - req_szB;
1482 } else {
1483 slop_szB = 0;
nethercote57e36b32004-07-10 14:56:28 +00001484 }
1485
njnf1c5def2005-08-11 02:17:07 +00001486 // Make new HP_Chunk node, add to malloc_list
njn32397c02007-11-10 04:08:08 +00001487 hc = VG_(malloc)(sizeof(HP_Chunk));
1488 hc->req_szB = req_szB;
1489 hc->slop_szB = slop_szB;
1490 hc->data = (Addr)p;
1491 hc->where = NULL;
njn246a9d22005-08-14 06:24:20 +00001492 VG_(HT_add_node)(malloc_list, hc);
nethercote57e36b32004-07-10 14:56:28 +00001493
njn734b8052007-11-01 04:40:37 +00001494 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001495 VERB(3, "<<< new_mem_heap (%lu, %lu)", req_szB, slop_szB);
njn734b8052007-11-01 04:40:37 +00001496
1497 // Update statistics.
1498 n_heap_allocs++;
1499
1500 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001501 update_heap_stats(req_szB, clo_heap_admin + slop_szB);
njn734b8052007-11-01 04:40:37 +00001502
1503 // Update XTree.
1504 hc->where = get_XCon( tid, is_custom_alloc );
njn32397c02007-11-10 04:08:08 +00001505 update_XCon(hc->where, req_szB);
njn734b8052007-11-01 04:40:37 +00001506
1507 // Maybe take a snapshot.
1508 maybe_take_snapshot(Normal, " alloc");
1509
1510 VERB(3, ">>>");
1511 }
nethercotec9f36922004-02-14 16:40:02 +00001512
nethercotec9f36922004-02-14 16:40:02 +00001513 return p;
1514}
1515
1516static __inline__
1517void die_block ( void* p, Bool custom_free )
1518{
njnf1c5def2005-08-11 02:17:07 +00001519 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +00001520
njnf1c5def2005-08-11 02:17:07 +00001521 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +00001522 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn734b8052007-11-01 04:40:37 +00001523 if (NULL == hc) {
njn5cc5d7e2005-08-11 02:09:25 +00001524 return; // must have been a bogus free()
njn734b8052007-11-01 04:40:37 +00001525 }
nethercotec9f36922004-02-14 16:40:02 +00001526
njn734b8052007-11-01 04:40:37 +00001527 if (clo_heap) {
1528 VERB(3, "<<< die_mem_heap");
nethercotec9f36922004-02-14 16:40:02 +00001529
njn734b8052007-11-01 04:40:37 +00001530 // Update statistics
1531 n_heap_frees++;
nethercote57e36b32004-07-10 14:56:28 +00001532
njn734b8052007-11-01 04:40:37 +00001533 // Maybe take a peak snapshot, since it's a deallocation.
1534 maybe_take_snapshot(Peak, "de-PEAK");
1535
1536 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001537 update_heap_stats(-hc->req_szB, -clo_heap_admin - hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001538
1539 // Update XTree.
njn32397c02007-11-10 04:08:08 +00001540 update_XCon(hc->where, -hc->req_szB);
njn734b8052007-11-01 04:40:37 +00001541
1542 // Maybe take a snapshot.
1543 maybe_take_snapshot(Normal, "dealloc");
1544
njn32397c02007-11-10 04:08:08 +00001545 VERB(3, ">>> (-%lu, -%lu)", hc->req_szB, hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001546 }
1547
1548 // Actually free the chunk, and the heap block (if necessary)
1549 VG_(free)( hc ); hc = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001550 if (!custom_free)
1551 VG_(cli_free)( p );
nethercotec9f36922004-02-14 16:40:02 +00001552}
1553
njn734b8052007-11-01 04:40:37 +00001554static __inline__
njn32397c02007-11-10 04:08:08 +00001555void* renew_block ( ThreadId tid, void* p_old, SizeT new_req_szB )
nethercotec9f36922004-02-14 16:40:02 +00001556{
njn734b8052007-11-01 04:40:37 +00001557 HP_Chunk* hc;
1558 void* p_new;
njn32397c02007-11-10 04:08:08 +00001559 SizeT old_req_szB, old_slop_szB, new_slop_szB, new_actual_szB;
njn734b8052007-11-01 04:40:37 +00001560 XPt *old_where, *new_where;
1561
1562 // Remove the old block
1563 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
1564 if (hc == NULL) {
1565 return NULL; // must have been a bogus realloc()
1566 }
1567
njn32397c02007-11-10 04:08:08 +00001568 old_req_szB = hc->req_szB;
1569 old_slop_szB = hc->slop_szB;
njn734b8052007-11-01 04:40:37 +00001570
1571 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001572 VERB(3, "<<< renew_mem_heap (%lu)", new_req_szB);
njn734b8052007-11-01 04:40:37 +00001573
1574 // Update statistics
1575 n_heap_reallocs++;
1576
1577 // Maybe take a peak snapshot, if it's (effectively) a deallocation.
njn32397c02007-11-10 04:08:08 +00001578 if (new_req_szB < old_req_szB) {
njn734b8052007-11-01 04:40:37 +00001579 maybe_take_snapshot(Peak, "re-PEAK");
1580 }
njn734b8052007-11-01 04:40:37 +00001581 }
1582
1583 // Actually do the allocation, if necessary.
njn32397c02007-11-10 04:08:08 +00001584 if (new_req_szB <= old_req_szB + old_slop_szB) {
1585 // New size is smaller or same; block not moved.
njn734b8052007-11-01 04:40:37 +00001586 p_new = p_old;
njn32397c02007-11-10 04:08:08 +00001587 new_slop_szB = old_slop_szB + (old_req_szB - new_req_szB);
njn734b8052007-11-01 04:40:37 +00001588
1589 } else {
njn32397c02007-11-10 04:08:08 +00001590 // New size is bigger; make new block, copy shared contents, free old.
1591 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_req_szB);
1592 if (!p_new) {
1593 // Nb: if realloc fails, NULL is returned but the old block is not
1594 // touched. What an awful function.
1595 return NULL;
njn734b8052007-11-01 04:40:37 +00001596 }
njn32397c02007-11-10 04:08:08 +00001597 VG_(memcpy)(p_new, p_old, old_req_szB);
1598 VG_(cli_free)(p_old);
1599 new_actual_szB = VG_(malloc_usable_size)(p_new);
1600 tl_assert(new_actual_szB >= new_req_szB);
1601 new_slop_szB = new_actual_szB - new_req_szB;
njn734b8052007-11-01 04:40:37 +00001602 }
1603
1604 if (p_new) {
1605 // Update HP_Chunk.
njn32397c02007-11-10 04:08:08 +00001606 hc->data = (Addr)p_new;
1607 hc->req_szB = new_req_szB;
1608 hc->slop_szB = new_slop_szB;
1609 old_where = hc->where;
1610 hc->where = NULL;
njn734b8052007-11-01 04:40:37 +00001611
1612 // Update XTree.
1613 if (clo_heap) {
1614 new_where = get_XCon( tid, /*custom_malloc*/False);
1615 hc->where = new_where;
njn32397c02007-11-10 04:08:08 +00001616 update_XCon(old_where, -old_req_szB);
1617 update_XCon(new_where, new_req_szB);
njn734b8052007-11-01 04:40:37 +00001618 }
1619 }
1620
1621 // Now insert the new hc (with a possibly new 'data' field) into
1622 // malloc_list. If this realloc() did not increase the memory size, we
1623 // will have removed and then re-added hc unnecessarily. But that's ok
1624 // because shrinking a block with realloc() is (presumably) much rarer
1625 // than growing it, and this way simplifies the growing case.
1626 VG_(HT_add_node)(malloc_list, hc);
1627
njn734b8052007-11-01 04:40:37 +00001628 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001629 // Update heap stats.
1630 update_heap_stats(new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
1631
1632 // Maybe take a snapshot.
njn734b8052007-11-01 04:40:37 +00001633 maybe_take_snapshot(Normal, "realloc");
1634
njn32397c02007-11-10 04:08:08 +00001635 VERB(3, ">>> (%ld, %ld)",
1636 new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
njn734b8052007-11-01 04:40:37 +00001637 }
1638
1639 return p_new;
nethercotec9f36922004-02-14 16:40:02 +00001640}
1641
njn734b8052007-11-01 04:40:37 +00001642
1643//------------------------------------------------------------//
1644//--- malloc() et al replacement wrappers ---//
1645//------------------------------------------------------------//
1646
1647static void* ms_malloc ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001648{
njn734b8052007-11-01 04:40:37 +00001649 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001650}
1651
njn734b8052007-11-01 04:40:37 +00001652static void* ms___builtin_new ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001653{
njn734b8052007-11-01 04:40:37 +00001654 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001655}
1656
njn734b8052007-11-01 04:40:37 +00001657static void* ms___builtin_vec_new ( ThreadId tid, SizeT szB )
fitzhardinge51f3ff12004-03-04 22:42:03 +00001658{
njn734b8052007-11-01 04:40:37 +00001659 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
1660}
1661
1662static void* ms_calloc ( ThreadId tid, SizeT m, SizeT szB )
1663{
1664 return new_block( tid, NULL, m*szB, VG_(clo_alignment), /*is_zeroed*/True );
1665}
1666
1667static void *ms_memalign ( ThreadId tid, SizeT alignB, SizeT szB )
1668{
1669 return new_block( tid, NULL, szB, alignB, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +00001670}
1671
njn51d827b2005-05-09 01:02:08 +00001672static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001673{
1674 die_block( p, /*custom_free*/False );
1675}
1676
njn51d827b2005-05-09 01:02:08 +00001677static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001678{
1679 die_block( p, /*custom_free*/False);
1680}
1681
njn51d827b2005-05-09 01:02:08 +00001682static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001683{
1684 die_block( p, /*custom_free*/False );
1685}
1686
njn734b8052007-11-01 04:40:37 +00001687static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_szB )
nethercotec9f36922004-02-14 16:40:02 +00001688{
njn734b8052007-11-01 04:40:37 +00001689 return renew_block(tid, p_old, new_szB);
nethercotec9f36922004-02-14 16:40:02 +00001690}
1691
1692
njn734b8052007-11-01 04:40:37 +00001693//------------------------------------------------------------//
1694//--- Stacks ---//
1695//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001696
njn734b8052007-11-01 04:40:37 +00001697// We really want the inlining to occur...
1698#define INLINE inline __attribute__((always_inline))
nethercotec9f36922004-02-14 16:40:02 +00001699
njn734b8052007-11-01 04:40:37 +00001700static void update_stack_stats(SSizeT stack_szB_delta)
nethercotec9f36922004-02-14 16:40:02 +00001701{
njn734b8052007-11-01 04:40:37 +00001702 if (stack_szB_delta < 0) tl_assert(stacks_szB >= -stack_szB_delta);
1703 stacks_szB += stack_szB_delta;
nethercotec9f36922004-02-14 16:40:02 +00001704
njn734b8052007-11-01 04:40:37 +00001705 update_alloc_stats(stack_szB_delta);
nethercotec9f36922004-02-14 16:40:02 +00001706}
1707
njn734b8052007-11-01 04:40:37 +00001708static INLINE void new_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001709{
njn734b8052007-11-01 04:40:37 +00001710 if (have_started_executing_code) {
1711 VERB(3, "<<< new_mem_stack (%ld)", len);
1712 n_stack_allocs++;
1713 update_stack_stats(len);
1714 maybe_take_snapshot(Normal, what);
1715 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001716 }
nethercotec9f36922004-02-14 16:40:02 +00001717}
1718
njn734b8052007-11-01 04:40:37 +00001719static INLINE void die_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001720{
njn734b8052007-11-01 04:40:37 +00001721 if (have_started_executing_code) {
1722 VERB(3, "<<< die_mem_stack (%ld)", -len);
1723 n_stack_frees++;
1724 maybe_take_snapshot(Peak, "stkPEAK");
1725 update_stack_stats(-len);
1726 maybe_take_snapshot(Normal, what);
1727 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001728 }
nethercotec9f36922004-02-14 16:40:02 +00001729}
1730
njn734b8052007-11-01 04:40:37 +00001731static void new_mem_stack(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001732{
njn734b8052007-11-01 04:40:37 +00001733 new_mem_stack_2(a, len, "stk-new");
1734}
nethercotec9f36922004-02-14 16:40:02 +00001735
njn734b8052007-11-01 04:40:37 +00001736static void die_mem_stack(Addr a, SizeT len)
1737{
1738 die_mem_stack_2(a, len, "stk-die");
1739}
nethercotec9f36922004-02-14 16:40:02 +00001740
nethercote8b5f40c2004-11-02 13:29:50 +00001741static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001742{
njn734b8052007-11-01 04:40:37 +00001743 new_mem_stack_2(a, len, "sig-new");
nethercotec9f36922004-02-14 16:40:02 +00001744}
1745
nethercote8b5f40c2004-11-02 13:29:50 +00001746static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001747{
njn734b8052007-11-01 04:40:37 +00001748 die_mem_stack_2(a, len, "sig-die");
nethercotec9f36922004-02-14 16:40:02 +00001749}
1750
njn734b8052007-11-01 04:40:37 +00001751
1752//------------------------------------------------------------//
1753//--- Client Requests ---//
1754//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001755
njn51d827b2005-05-09 01:02:08 +00001756static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001757{
1758 switch (argv[0]) {
1759 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001760 void* res;
njn734b8052007-11-01 04:40:37 +00001761 void* p = (void*)argv[1];
1762 SizeT szB = argv[2];
1763 res = new_block( tid, p, szB, /*alignB--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001764 tl_assert(res == p);
njn734b8052007-11-01 04:40:37 +00001765 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001766 return True;
1767 }
1768 case VG_USERREQ__FREELIKE_BLOCK: {
njn734b8052007-11-01 04:40:37 +00001769 void* p = (void*)argv[1];
nethercotec9f36922004-02-14 16:40:02 +00001770 die_block( p, /*custom_free*/True );
njn734b8052007-11-01 04:40:37 +00001771 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001772 return True;
1773 }
1774 default:
1775 *ret = 0;
1776 return False;
1777 }
1778}
1779
njn734b8052007-11-01 04:40:37 +00001780//------------------------------------------------------------//
1781//--- Instrumentation ---//
1782//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001783
njn1a2741a2007-11-26 21:59:04 +00001784static void add_counter_update(IRSB* sbOut, Int n)
1785{
1786 #if defined(VG_BIGENDIAN)
1787 # define END Iend_BE
1788 #elif defined(VG_LITTLEENDIAN)
1789 # define END Iend_LE
1790 #else
1791 # error "Unknown endianness"
1792 #endif
1793 // Add code to increment 'guest_instrs_executed' by 'n', like this:
1794 // WrTmp(t1, Load64(&guest_instrs_executed))
1795 // WrTmp(t2, Add64(RdTmp(t1), Const(n)))
1796 // Store(&guest_instrs_executed, t2)
1797 IRTemp t1 = newIRTemp(sbOut->tyenv, Ity_I64);
1798 IRTemp t2 = newIRTemp(sbOut->tyenv, Ity_I64);
1799 IRExpr* counter_addr = mkIRExpr_HWord( (HWord)&guest_instrs_executed );
1800
1801 IRStmt* st1 = IRStmt_WrTmp(t1, IRExpr_Load(END, Ity_I64, counter_addr));
1802 IRStmt* st2 =
1803 IRStmt_WrTmp(t2,
1804 IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(t1),
1805 IRExpr_Const(IRConst_U64(n))));
1806 IRStmt* st3 = IRStmt_Store(END, counter_addr, IRExpr_RdTmp(t2));
1807
1808 addStmtToIRSB( sbOut, st1 );
1809 addStmtToIRSB( sbOut, st2 );
1810 addStmtToIRSB( sbOut, st3 );
1811}
1812
1813static IRSB* ms_instrument2( IRSB* sbIn )
1814{
1815 Int i, n = 0;
1816 IRSB* sbOut;
1817
1818 // We increment the instruction count in two places:
1819 // - just before any Ist_Exit statements;
1820 // - just before the IRSB's end.
1821 // In the former case, we zero 'n' and then continue instrumenting.
1822
1823 sbOut = deepCopyIRSBExceptStmts(sbIn);
1824
1825 for (i = 0; i < sbIn->stmts_used; i++) {
1826 IRStmt* st = sbIn->stmts[i];
1827
1828 if (!st || st->tag == Ist_NoOp) continue;
1829
1830 if (st->tag == Ist_IMark) {
1831 n++;
1832 } else if (st->tag == Ist_Exit) {
1833 if (n > 0) {
1834 // Add an increment before the Exit statement, then reset 'n'.
1835 add_counter_update(sbOut, n);
1836 n = 0;
1837 }
1838 }
1839 addStmtToIRSB( sbOut, st );
1840 }
1841
1842 if (n > 0) {
1843 // Add an increment before the SB end.
1844 add_counter_update(sbOut, n);
1845 }
1846 return sbOut;
1847}
1848
sewardj4ba057c2005-10-18 12:04:18 +00001849static
sewardj0b9d74a2006-12-24 02:24:11 +00001850IRSB* ms_instrument ( VgCallbackClosure* closure,
njn1a2741a2007-11-26 21:59:04 +00001851 IRSB* sbIn,
njn734b8052007-11-01 04:40:37 +00001852 VexGuestLayout* layout,
sewardj461df9c2006-01-17 02:06:39 +00001853 VexGuestExtents* vge,
sewardj4ba057c2005-10-18 12:04:18 +00001854 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001855{
njn734b8052007-11-01 04:40:37 +00001856 if (! have_started_executing_code) {
1857 // Do an initial sample to guarantee that we have at least one.
1858 // We use 'maybe_take_snapshot' instead of 'take_snapshot' to ensure
1859 // 'maybe_take_snapshot's internal static variables are initialised.
1860 have_started_executing_code = True;
1861 maybe_take_snapshot(Normal, "startup");
1862 }
njn1a2741a2007-11-26 21:59:04 +00001863
1864 if (clo_time_unit == TimeI) { return ms_instrument2(sbIn); }
1865 else if (clo_time_unit == TimeMS) { return sbIn; }
1866 else if (clo_time_unit == TimeB) { return sbIn; }
1867 else { tl_assert2(0, "bad --time-unit value"); }
nethercotec9f36922004-02-14 16:40:02 +00001868}
1869
nethercotec9f36922004-02-14 16:40:02 +00001870
njn734b8052007-11-01 04:40:37 +00001871//------------------------------------------------------------//
1872//--- Writing snapshots ---//
1873//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001874
njn374a36d2007-11-23 01:41:32 +00001875// The output file name. Controlled by --massif-out-file.
1876static Char* massif_out_file = NULL;
1877
njn734b8052007-11-01 04:40:37 +00001878#define FP_BUF_SIZE 1024
1879Char FP_buf[FP_BUF_SIZE];
nethercotec9f36922004-02-14 16:40:02 +00001880
njn734b8052007-11-01 04:40:37 +00001881// XXX: implement f{,n}printf in m_libcprint.c eventually, and use it here.
1882// Then change Cachegrind to use it too.
1883#define FP(format, args...) ({ \
1884 VG_(snprintf)(FP_buf, FP_BUF_SIZE, format, ##args); \
1885 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf)); \
1886})
nethercotec9f36922004-02-14 16:40:02 +00001887
1888// Nb: uses a static buffer, each call trashes the last string returned.
njn734b8052007-11-01 04:40:37 +00001889static Char* make_perc(ULong x, ULong y)
nethercotec9f36922004-02-14 16:40:02 +00001890{
1891 static Char mbuf[32];
njn734b8052007-11-01 04:40:37 +00001892
1893// tl_assert(x <= y); XXX; put back in later...
1894
njn1a2741a2007-11-26 21:59:04 +00001895 // XXX: I'm not confident that VG_(percentify) works as it should...
njn734b8052007-11-01 04:40:37 +00001896 VG_(percentify)(x, y, 2, 6, mbuf);
1897 // XXX: this is bogus if the denominator was zero -- resulting string is
1898 // something like "0 --%")
1899 if (' ' == mbuf[0]) mbuf[0] = '0';
nethercotec9f36922004-02-14 16:40:02 +00001900 return mbuf;
1901}
1902
njn734b8052007-11-01 04:40:37 +00001903static void pp_snapshot_SXPt(Int fd, SXPt* sxpt, Int depth, Char* depth_str,
1904 Int depth_str_len,
1905 SizeT snapshot_heap_szB, SizeT snapshot_total_szB)
nethercotec9f36922004-02-14 16:40:02 +00001906{
njn734b8052007-11-01 04:40:37 +00001907 #define BUF_LEN 1024
1908 Int i, n_insig_children_sxpts;
1909 Char* perc;
1910 Char ip_desc_array[BUF_LEN];
1911 Char* ip_desc = ip_desc_array;
1912 SXPt* pred = NULL;
1913 SXPt* child = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001914
njn734b8052007-11-01 04:40:37 +00001915 switch (sxpt->tag) {
1916 case SigSXPt:
1917 // Print the SXPt itself.
1918 if (sxpt->Sig.ip == 0) {
1919 ip_desc =
1920 "(heap allocation functions) malloc/new/new[], --alloc-fns, etc.";
1921 } else {
1922 // If it's main-or-below-main, we (if appropriate) ignore everything
1923 // below it by pretending it has no children.
1924 // XXX: get this properly. Also, don't hard-code "(below main)"
1925 // here -- look at the "(below main)"/"__libc_start_main" mess
1926 // (m_stacktrace.c and m_demangle.c).
1927 // [Nb: Josef wants --show-below-main to work for his fn entry/exit
1928 // tracing]
1929 Bool should_hide_below_main = /*!VG_(clo_show_below_main)*/True;
1930 if (should_hide_below_main &&
1931 VG_(get_fnname)(sxpt->Sig.ip, ip_desc, BUF_LEN) &&
1932 (VG_STREQ(ip_desc, "main") || VG_STREQ(ip_desc, "(below main)")))
1933 {
1934 sxpt->Sig.n_children = 0;
1935 }
1936 // We need the -1 to get the line number right, But I'm not sure why.
1937 ip_desc = VG_(describe_IP)(sxpt->Sig.ip-1, ip_desc, BUF_LEN);
1938 }
1939 perc = make_perc(sxpt->szB, snapshot_total_szB);
1940 FP("%sn%d: %lu %s\n",
1941 depth_str, sxpt->Sig.n_children, sxpt->szB, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001942
njn734b8052007-11-01 04:40:37 +00001943 // Indent.
1944 tl_assert(depth+1 < depth_str_len-1); // -1 for end NUL char
1945 depth_str[depth+0] = ' ';
1946 depth_str[depth+1] = '\0';
1947
1948 // Sort SXPt's children by szB (reverse order: biggest to smallest).
1949 // Nb: we sort them here, rather than earlier (eg. in dup_XTree), for
1950 // two reasons. First, if we do it during dup_XTree, it can get
1951 // expensive (eg. 15% of execution time for konqueror
1952 // startup/shutdown). Second, this way we get the Insig SXPt (if one
1953 // is present) in its sorted position, not at the end.
1954 VG_(ssort)(sxpt->Sig.children, sxpt->Sig.n_children, sizeof(SXPt*),
1955 SXPt_revcmp_szB);
1956
1957 // Print the SXPt's children. They should already be in sorted order.
1958 n_insig_children_sxpts = 0;
1959 for (i = 0; i < sxpt->Sig.n_children; i++) {
1960 pred = child;
1961 child = sxpt->Sig.children[i];
1962
1963 if (InsigSXPt == child->tag)
1964 n_insig_children_sxpts++;
1965
1966 // Ok, print the child.
1967 pp_snapshot_SXPt(fd, child, depth+1, depth_str, depth_str_len,
1968 snapshot_heap_szB, snapshot_total_szB);
1969
1970 // Unindent.
1971 depth_str[depth+0] = '\0';
1972 depth_str[depth+1] = '\0';
1973 }
1974 // There should be 0 or 1 Insig children SXPts.
1975 tl_assert(n_insig_children_sxpts <= 1);
1976 break;
1977
1978 case InsigSXPt: {
1979 Char* s = ( sxpt->Insig.n_xpts == 1 ? "," : "s, all" );
1980 perc = make_perc(sxpt->szB, snapshot_total_szB);
1981 FP("%sn0: %lu in %d place%s below massif's threshold (%s)\n",
1982 depth_str, sxpt->szB, sxpt->Insig.n_xpts, s,
njn62721e92007-11-11 22:15:58 +00001983 make_perc((ULong)clo_threshold, 100));
njn734b8052007-11-01 04:40:37 +00001984 break;
1985 }
1986
1987 default:
1988 tl_assert2(0, "pp_snapshot_SXPt: unrecognised SXPt tag");
nethercotec9f36922004-02-14 16:40:02 +00001989 }
nethercotec9f36922004-02-14 16:40:02 +00001990}
1991
njn734b8052007-11-01 04:40:37 +00001992static void pp_snapshot(Int fd, Snapshot* snapshot, Int snapshot_n)
nethercotec9f36922004-02-14 16:40:02 +00001993{
njn734b8052007-11-01 04:40:37 +00001994 sanity_check_snapshot(snapshot);
nethercotec9f36922004-02-14 16:40:02 +00001995
njn734b8052007-11-01 04:40:37 +00001996 FP("#-----------\n");
1997 FP("snapshot=%d\n", snapshot_n);
1998 FP("#-----------\n");
1999 FP("time=%lld\n", snapshot->time);
2000 FP("mem_heap_B=%lu\n", snapshot->heap_szB);
njn32397c02007-11-10 04:08:08 +00002001 FP("mem_heap_extra_B=%lu\n", snapshot->heap_extra_szB);
njn734b8052007-11-01 04:40:37 +00002002 FP("mem_stacks_B=%lu\n", snapshot->stacks_szB);
2003
2004 if (is_detailed_snapshot(snapshot)) {
2005 // Detailed snapshot -- print heap tree.
2006 Int depth_str_len = clo_depth + 3;
2007 Char* depth_str = VG_(malloc)(sizeof(Char) * depth_str_len);
2008 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00002009 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00002010 depth_str[0] = '\0'; // Initialise depth_str to "".
2011
2012 FP("heap_tree=%s\n", ( Peak == snapshot->kind ? "peak" : "detailed" ));
2013 pp_snapshot_SXPt(fd, snapshot->alloc_sxpt, 0, depth_str,
2014 depth_str_len, snapshot->heap_szB,
2015 snapshot_total_szB);
2016
2017 VG_(free)(depth_str);
2018
2019 } else {
2020 FP("heap_tree=empty\n");
nethercote43a15ce2004-08-30 19:15:12 +00002021 }
nethercotec9f36922004-02-14 16:40:02 +00002022}
2023
njn734b8052007-11-01 04:40:37 +00002024static void write_snapshots_to_file(void)
nethercotec9f36922004-02-14 16:40:02 +00002025{
njn734b8052007-11-01 04:40:37 +00002026 Int i, fd;
sewardj92645592005-07-23 09:18:34 +00002027 SysRes sres;
nethercotec9f36922004-02-14 16:40:02 +00002028
njn734b8052007-11-01 04:40:37 +00002029 sres = VG_(open)(massif_out_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
2030 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00002031 if (sres.isError) {
njn734b8052007-11-01 04:40:37 +00002032 // If the file can't be opened for whatever reason (conflict
2033 // between multiple cachegrinded processes?), give up now.
2034 VG_(message)(Vg_UserMsg,
2035 "error: can't open output file '%s'", massif_out_file );
2036 VG_(message)(Vg_UserMsg,
2037 " ... so profiling results will be missing.");
nethercotec9f36922004-02-14 16:40:02 +00002038 return;
sewardj92645592005-07-23 09:18:34 +00002039 } else {
sewardje8089302006-10-17 02:15:17 +00002040 fd = sres.res;
nethercotec9f36922004-02-14 16:40:02 +00002041 }
2042
njn734b8052007-11-01 04:40:37 +00002043 // Print massif-specific options that were used.
2044 // XXX: is it worth having a "desc:" line? Could just call it "options:"
2045 // -- this file format isn't as generic as Cachegrind's, so the
2046 // implied genericity of "desc:" is bogus.
2047 FP("desc:");
2048 for (i = 0; i < VG_(sizeXA)(args_for_massif); i++) {
2049 Char* arg = *(Char**)VG_(indexXA)(args_for_massif, i);
2050 FP(" %s", arg);
nethercotec9f36922004-02-14 16:40:02 +00002051 }
njn734b8052007-11-01 04:40:37 +00002052 if (0 == i) FP(" (none)");
2053 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002054
njn734b8052007-11-01 04:40:37 +00002055 // Print "cmd:" line.
2056 FP("cmd: ");
sewardj45f4e7c2005-09-27 19:20:21 +00002057 if (VG_(args_the_exename)) {
njn734b8052007-11-01 04:40:37 +00002058 FP("%s", VG_(args_the_exename));
2059 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
2060 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
2061 if (arg)
2062 FP(" %s", arg);
2063 }
2064 } else {
2065 FP(" ???");
sewardj45f4e7c2005-09-27 19:20:21 +00002066 }
njn734b8052007-11-01 04:40:37 +00002067 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002068
njn734b8052007-11-01 04:40:37 +00002069 FP("time_unit: %s\n", TimeUnit_to_string(clo_time_unit));
nethercotec9f36922004-02-14 16:40:02 +00002070
njn734b8052007-11-01 04:40:37 +00002071 for (i = 0; i < next_snapshot_i; i++) {
2072 Snapshot* snapshot = & snapshots[i];
2073 pp_snapshot(fd, snapshot, i); // Detailed snapshot!
nethercotec9f36922004-02-14 16:40:02 +00002074 }
2075}
2076
njn734b8052007-11-01 04:40:37 +00002077
2078//------------------------------------------------------------//
2079//--- Finalisation ---//
2080//------------------------------------------------------------//
2081
njn51d827b2005-05-09 01:02:08 +00002082static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00002083{
njn734b8052007-11-01 04:40:37 +00002084 // Output.
2085 write_snapshots_to_file();
nethercotec9f36922004-02-14 16:40:02 +00002086
njn734b8052007-11-01 04:40:37 +00002087 // Stats
2088 tl_assert(n_xpts > 0); // always have alloc_xpt
2089 VERB(1, "heap allocs: %u", n_heap_allocs);
2090 VERB(1, "heap reallocs: %u", n_heap_reallocs);
2091 VERB(1, "heap frees: %u", n_heap_frees);
2092 VERB(1, "stack allocs: %u", n_stack_allocs);
2093 VERB(1, "stack frees: %u", n_stack_frees);
2094 VERB(1, "XPts: %u", n_xpts);
2095 VERB(1, "top-XPts: %u (%d%%)",
2096 alloc_xpt->n_children,
2097 ( n_xpts ? alloc_xpt->n_children * 100 / n_xpts : 0));
njn55a30042007-11-10 04:18:39 +00002098 VERB(1, "XPt init expansions: %u", n_xpt_init_expansions);
2099 VERB(1, "XPt later expansions: %u", n_xpt_later_expansions);
njn734b8052007-11-01 04:40:37 +00002100 VERB(1, "SXPt allocs: %u", n_sxpt_allocs);
2101 VERB(1, "SXPt frees: %u", n_sxpt_frees);
2102 VERB(1, "skipped snapshots: %u", n_skipped_snapshots);
2103 VERB(1, "real snapshots: %u", n_real_snapshots);
2104 VERB(1, "detailed snapshots: %u", n_detailed_snapshots);
2105 VERB(1, "peak snapshots: %u", n_peak_snapshots);
2106 VERB(1, "cullings: %u", n_cullings);
njn55a30042007-11-10 04:18:39 +00002107 VERB(1, "XCon redos: %u", n_XCon_redos);
nethercotec9f36922004-02-14 16:40:02 +00002108}
2109
njn734b8052007-11-01 04:40:37 +00002110
2111//------------------------------------------------------------//
2112//--- Initialisation ---//
2113//------------------------------------------------------------//
njn51d827b2005-05-09 01:02:08 +00002114
2115static void ms_post_clo_init(void)
2116{
njn734b8052007-11-01 04:40:37 +00002117 Int i;
njn51d827b2005-05-09 01:02:08 +00002118
njn734b8052007-11-01 04:40:37 +00002119 // Check options.
2120 if (clo_heap_admin < 0 || clo_heap_admin > 1024) {
2121 VG_(message)(Vg_UserMsg, "--heap-admin must be between 0 and 1024");
2122 VG_(err_bad_option)("--heap-admin");
2123 }
2124 if (clo_depth < 1 || clo_depth > MAX_DEPTH) {
2125 VG_(message)(Vg_UserMsg, "--depth must be between 1 and %d", MAX_DEPTH);
2126 VG_(err_bad_option)("--depth");
2127 }
njn62721e92007-11-11 22:15:58 +00002128 if (clo_threshold < 0 || clo_threshold > 100) {
2129 VG_(message)(Vg_UserMsg, "--threshold must be between 0.0 and 100.0");
njn734b8052007-11-01 04:40:37 +00002130 VG_(err_bad_option)("--threshold");
2131 }
2132 if (clo_detailed_freq < 1 || clo_detailed_freq > 10000) {
2133 VG_(message)(Vg_UserMsg, "--detailed-freq must be between 1 and 10000");
2134 VG_(err_bad_option)("--detailed-freq");
2135 }
2136 if (clo_max_snapshots < 10 || clo_max_snapshots > 1000) {
2137 VG_(message)(Vg_UserMsg, "--max-snapshots must be between 10 and 1000");
2138 VG_(err_bad_option)("--max-snapshots");
2139 }
2140
2141 // If we have --heap=no, set --heap-admin to zero, just to make sure we
2142 // don't accidentally use a non-zero heap-admin size somewhere.
2143 if (!clo_heap) {
2144 clo_heap_admin = 0;
2145 }
2146
2147 // Print alloc-fns, if necessary.
2148 if (VG_(clo_verbosity) > 1) {
2149 VERB(1, "alloc-fns:");
2150 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
2151 Char** alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
2152 VERB(1, " %d: %s", i, *alloc_fn_ptr);
2153 }
2154 }
2155
2156 // Events to track.
2157 if (clo_stacks) {
2158 VG_(track_new_mem_stack) ( new_mem_stack );
2159 VG_(track_die_mem_stack) ( die_mem_stack );
2160 VG_(track_new_mem_stack_signal) ( new_mem_stack_signal );
2161 VG_(track_die_mem_stack_signal) ( die_mem_stack_signal );
2162 }
2163
2164 // Initialise snapshot array, and sanity-check it.
2165 snapshots = VG_(malloc)(sizeof(Snapshot) * clo_max_snapshots);
2166 // We don't want to do snapshot sanity checks here, because they're
2167 // currently uninitialised.
2168 for (i = 0; i < clo_max_snapshots; i++) {
2169 clear_snapshot( & snapshots[i], /*do_sanity_check*/False );
2170 }
2171 sanity_check_snapshots_array();
njnf4c665f2007-11-20 07:55:40 +00002172
2173 // Setup output filename.
njn3ed19712007-11-22 23:01:59 +00002174 massif_out_file =
2175 VG_(expand_file_name)("--massif-out-file", clo_massif_out_file);
njn51d827b2005-05-09 01:02:08 +00002176}
2177
tom151a6392005-11-11 12:30:36 +00002178static void ms_pre_clo_init(void)
njn734b8052007-11-01 04:40:37 +00002179{
njn51d827b2005-05-09 01:02:08 +00002180 VG_(details_name) ("Massif");
2181 VG_(details_version) (NULL);
njn1a2741a2007-11-26 21:59:04 +00002182 VG_(details_description) ("a heap profiler");
njn9a0cba42007-04-15 22:15:57 +00002183 VG_(details_copyright_author)(
njn734b8052007-11-01 04:40:37 +00002184 "Copyright (C) 2003-2007, and GNU GPL'd, by Nicholas Nethercote");
njn51d827b2005-05-09 01:02:08 +00002185 VG_(details_bug_reports_to) (VG_BUGS_TO);
2186
2187 // Basic functions
2188 VG_(basic_tool_funcs) (ms_post_clo_init,
2189 ms_instrument,
2190 ms_fini);
2191
2192 // Needs
2193 VG_(needs_libc_freeres)();
2194 VG_(needs_command_line_options)(ms_process_cmd_line_option,
2195 ms_print_usage,
2196 ms_print_debug_usage);
2197 VG_(needs_client_requests) (ms_handle_client_request);
njn734b8052007-11-01 04:40:37 +00002198 VG_(needs_sanity_checks) (ms_cheap_sanity_check,
2199 ms_expensive_sanity_check);
njnfc51f8d2005-06-21 03:20:17 +00002200 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00002201 ms___builtin_new,
2202 ms___builtin_vec_new,
2203 ms_memalign,
2204 ms_calloc,
2205 ms_free,
2206 ms___builtin_delete,
2207 ms___builtin_vec_delete,
2208 ms_realloc,
2209 0 );
2210
njn51d827b2005-05-09 01:02:08 +00002211 // HP_Chunks
njn734b8052007-11-01 04:40:37 +00002212 malloc_list = VG_(HT_construct)( "Massif's malloc list" );
njn51d827b2005-05-09 01:02:08 +00002213
2214 // Dummy node at top of the context structure.
njn734b8052007-11-01 04:40:37 +00002215 alloc_xpt = new_XPt(/*ip*/0, /*parent*/NULL);
2216
2217 // Initialise alloc_fns.
2218 init_alloc_fns();
2219
2220 // Initialise args_for_massif.
2221 args_for_massif = VG_(newXA)(VG_(malloc), VG_(free), sizeof(HChar*));
njn51d827b2005-05-09 01:02:08 +00002222}
2223
sewardj45f4e7c2005-09-27 19:20:21 +00002224VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00002225
njn734b8052007-11-01 04:40:37 +00002226//--------------------------------------------------------------------//
2227//--- end ---//
2228//--------------------------------------------------------------------//