blob: daadac24c5315be1093ad8a93b0f7bbdad33dccf [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//---------------------------------------------------------------------------
njn734b8052007-11-01 04:40:37 +000033// Todo -- nice, but less critical:
njnab23b612007-11-27 00:53:56 +000034// - do a graph-drawing test
njn734b8052007-11-01 04:40:37 +000035// - make file format more generic. Obstacles:
36// - unit prefixes are not generic
37// - preset column widths for stats are not generic
38// - preset column headers are not generic
39// - "Massif arguments:" line is not generic
40// - do snapshots on client requests
41// - (Michael Meeks): have an interactive way to request a dump
42// (callgrind_control-style)
43// - "profile now"
44// - "show me the extra allocations since the last snapshot"
45// - "start/stop logging" (eg. quickly skip boring bits)
46// - Add ability to draw multiple graphs, eg. heap-only, stack-only, total.
47// Give each graph a title. (try to do it generically!)
48// - allow truncation of long fnnames if the exact line number is
49// identified? [hmm, could make getting the name of alloc-fns more
50// difficult] [could dump full names to file, truncate in ms_print]
51// - make --show-below-main=no work
njn1a2741a2007-11-26 21:59:04 +000052// - Options like --alloc-fn='operator new(unsigned, std::nothrow_t const&)'
53// don't work in a .valgrindrc file or in $VALGRIND_OPTS.
54// m_commandline.c:add_args_from_string() needs to respect single quotes.
njn3b677e52007-12-03 21:29:22 +000055// - With --stack=yes, want to add a stack trace for detailed snapshots so
56// it's clear where/why the peak is occurring. (Mattieu Castet) Also,
57// possibly useful even with --stack=no? (Andi Yin)
njn734b8052007-11-01 04:40:37 +000058//
59// Performance:
60// - To run the benchmarks:
61//
62// perl perf/vg_perf --tools=massif --reps=3 perf/{heap,tinycc} massif
63// time valgrind --tool=massif --depth=100 konqueror
64//
65// The other benchmarks don't do much allocation, and so give similar speeds
66// to Nulgrind.
67//
68// Timing results on 'nevermore' (njn's machine) as of r7013:
69//
70// heap 0.53s ma:12.4s (23.5x, -----)
71// tinycc 0.46s ma: 4.9s (10.7x, -----)
72// many-xpts 0.08s ma: 2.0s (25.0x, -----)
73// konqueror 29.6s real 0:21.0s user
74//
njnab23b612007-11-27 00:53:56 +000075// [Introduction of --time-unit=i as the default slowed things down by
76// roughly 0--20%.]
77//
njn734b8052007-11-01 04:40:37 +000078// - get_XCon accounts for about 9% of konqueror startup time. Try
79// keeping XPt children sorted by 'ip' and use binary search in get_XCon.
80// Requires factoring out binary search code from various places into a
81// VG_(bsearch) function.
82//
83// Todo -- low priority:
njn734b8052007-11-01 04:40:37 +000084// - In each XPt, record both bytes and the number of allocations, and
85// possibly the global number of allocations.
njn0f85e022007-11-27 02:03:44 +000086// - (Andy Lin) Give a stack trace on detailed snapshots?
njn734b8052007-11-01 04:40:37 +000087// - (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//
njn734b8052007-11-01 04:40:37 +000094// File format working notes:
95
96#if 0
97desc: --heap-admin=foo
98cmd: date
99time_unit: ms
100#-----------
101snapshot=0
102#-----------
103time=0
104mem_heap_B=0
105mem_heap_admin_B=0
106mem_stacks_B=0
107heap_tree=empty
108#-----------
109snapshot=1
110#-----------
111time=353
112mem_heap_B=5
113mem_heap_admin_B=0
114mem_stacks_B=0
115heap_tree=detailed
116n1: 5 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
117 n1: 5 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
118 n1: 5 0x279DE6: _nl_load_locale_from_archive (in /lib/libc-2.3.5.so)
119 n1: 5 0x278E97: _nl_find_locale (in /lib/libc-2.3.5.so)
120 n1: 5 0x278871: setlocale (in /lib/libc-2.3.5.so)
121 n1: 5 0x8049821: (within /bin/date)
122 n0: 5 0x26ED5E: (below main) (in /lib/libc-2.3.5.so)
123
124
125n_events: n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
126t_events: B
127n 0 0 0 0 0
128n 0 0 0 0 0
129t1: 5 <string...>
130 t1: 6 <string...>
131
132Ideas:
133- each snapshot specifies an x-axis value and one or more y-axis values.
134- can display the y-axis values separately if you like
135- can completely separate connection between snapshots and trees.
136
137Challenges:
138- how to specify and scale/abbreviate units on axes?
139- how to combine multiple values into the y-axis?
140
141--------------------------------------------------------------------------------Command: date
142Massif arguments: --heap-admin=foo
143ms_print arguments: massif.out
144--------------------------------------------------------------------------------
145 KB
1466.472^ :#
147 | :# :: . .
148 ...
149 | ::@ :@ :@ :@:::# :: : ::::
150 0 +-----------------------------------@---@---@-----@--@---#-------------->ms 0 713
151
152Number of snapshots: 50
153 Detailed snapshots: [2, 11, 13, 19, 25, 32 (peak)]
154-------------------------------------------------------------------------------- n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
155-------------------------------------------------------------------------------- 0 0 0 0 0 0
156 1 345 5 5 0 0
157 2 353 5 5 0 0
158100.00% (5B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
159->100.00% (5B) 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
160#endif
161
162//---------------------------------------------------------------------------
nethercotec9f36922004-02-14 16:40:02 +0000163
njnc7561b92005-06-19 01:24:32 +0000164#include "pub_tool_basics.h"
sewardj4cfea4f2006-10-14 19:26:10 +0000165#include "pub_tool_vki.h"
sewardj45f4e7c2005-09-27 19:20:21 +0000166#include "pub_tool_aspacemgr.h"
njnea27e462005-05-31 02:38:09 +0000167#include "pub_tool_debuginfo.h"
njn81c00df2005-05-14 21:28:43 +0000168#include "pub_tool_hashtable.h"
njn97405b22005-06-02 03:39:33 +0000169#include "pub_tool_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +0000170#include "pub_tool_libcassert.h"
njneb8896b2005-06-04 20:03:55 +0000171#include "pub_tool_libcfile.h"
njn36a20fa2005-06-03 03:08:39 +0000172#include "pub_tool_libcprint.h"
njnf39e9a32005-06-12 02:43:17 +0000173#include "pub_tool_libcproc.h"
njnb506bd82005-06-21 04:01:51 +0000174#include "pub_tool_machine.h"
njn717cde52005-05-10 02:47:21 +0000175#include "pub_tool_mallocfree.h"
njn20242342005-05-16 23:31:24 +0000176#include "pub_tool_options.h"
njn717cde52005-05-10 02:47:21 +0000177#include "pub_tool_replacemalloc.h"
njnd01fef72005-03-25 23:35:48 +0000178#include "pub_tool_stacktrace.h"
njn43b9a8a2005-05-10 04:37:01 +0000179#include "pub_tool_tooliface.h"
sewardj14c7cc52007-02-25 15:08:24 +0000180#include "pub_tool_xarray.h"
sewardj45f4e7c2005-09-27 19:20:21 +0000181#include "pub_tool_clientstate.h"
nethercotec9f36922004-02-14 16:40:02 +0000182
183#include "valgrind.h" // For {MALLOC,FREE}LIKE_BLOCK
184
njn734b8052007-11-01 04:40:37 +0000185//------------------------------------------------------------*/
186//--- Overview of operation ---*/
187//------------------------------------------------------------*/
nethercotec9f36922004-02-14 16:40:02 +0000188
njn734b8052007-11-01 04:40:37 +0000189// The size of the stacks and heap is tracked. The heap is tracked in a lot
190// of detail, enough to tell how many bytes each line of code is responsible
191// for, more or less. The main data structure is a tree representing the
192// call tree beneath all the allocation functions like malloc().
nethercotec9f36922004-02-14 16:40:02 +0000193//
njn734b8052007-11-01 04:40:37 +0000194// "Snapshots" are recordings of the memory usage. There are two basic
195// kinds:
196// - Normal: these record the current time, total memory size, total heap
197// size, heap admin size and stack size.
198// - Detailed: these record those things in a normal snapshot, plus a very
199// detailed XTree (see below) indicating how the heap is structured.
nethercotec9f36922004-02-14 16:40:02 +0000200//
njn734b8052007-11-01 04:40:37 +0000201// Snapshots are taken every so often. There are two storage classes of
202// snapshots:
203// - Temporary: Massif does a temporary snapshot every so often. The idea
204// is to always have a certain number of temporary snapshots around. So
205// we take them frequently to begin with, but decreasingly often as the
206// program continues to run. Also, we remove some old ones after a while.
207// Overall it's a kind of exponential decay thing. Most of these are
208// normal snapshots, a small fraction are detailed snapshots.
209// - Permanent: Massif takes a permanent (detailed) snapshot in some
210// circumstances. They are:
211// - Peak snapshot: When the memory usage peak is reached, it takes a
212// snapshot. It keeps this, unless the peak is subsequently exceeded,
213// in which case it will overwrite the peak snapshot.
214// - User-requested snapshots: These are done in response to client
215// requests. They are always kept.
nethercotec9f36922004-02-14 16:40:02 +0000216
njn734b8052007-11-01 04:40:37 +0000217// Used for printing things when clo_verbosity > 1.
218#define VERB(verb, format, args...) \
219 if (VG_(clo_verbosity) > verb) { \
220 VG_(message)(Vg_DebugMsg, "Massif: " format, ##args); \
nethercotec9f36922004-02-14 16:40:02 +0000221 }
nethercotec9f36922004-02-14 16:40:02 +0000222
nethercotec9f36922004-02-14 16:40:02 +0000223
nethercotec9f36922004-02-14 16:40:02 +0000224
njn734b8052007-11-01 04:40:37 +0000225//------------------------------------------------------------//
226//--- Statistics ---//
227//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000228
229// Konqueror startup, to give an idea of the numbers involved with a biggish
230// program, with default depth:
231//
232// depth=3 depth=40
233// - 310,000 allocations
234// - 300,000 frees
235// - 15,000 XPts 800,000 XPts
236// - 1,800 top-XPts
237
njn734b8052007-11-01 04:40:37 +0000238static UInt n_heap_allocs = 0;
239static UInt n_heap_reallocs = 0;
240static UInt n_heap_frees = 0;
241static UInt n_stack_allocs = 0;
242static UInt n_stack_frees = 0;
243static UInt n_xpts = 0;
244static UInt n_xpt_init_expansions = 0;
245static UInt n_xpt_later_expansions = 0;
246static UInt n_sxpt_allocs = 0;
247static UInt n_sxpt_frees = 0;
248static UInt n_skipped_snapshots = 0;
249static UInt n_real_snapshots = 0;
250static UInt n_detailed_snapshots = 0;
251static UInt n_peak_snapshots = 0;
252static UInt n_cullings = 0;
253static UInt n_XCon_redos = 0;
nethercotec9f36922004-02-14 16:40:02 +0000254
njn734b8052007-11-01 04:40:37 +0000255//------------------------------------------------------------//
256//--- Globals ---//
257//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000258
njn1a2741a2007-11-26 21:59:04 +0000259// Number of guest instructions executed so far. Only used with
260// --time-unit=i.
261static Long guest_instrs_executed = 0;
262
njn32397c02007-11-10 04:08:08 +0000263static SizeT heap_szB = 0; // Live heap size
264static SizeT heap_extra_szB = 0; // Live heap extra size -- slop + admin bytes
265static SizeT stacks_szB = 0; // Live stacks size
nethercotec9f36922004-02-14 16:40:02 +0000266
njn734b8052007-11-01 04:40:37 +0000267// This is the total size from the current peak snapshot, or 0 if no peak
268// snapshot has been taken yet.
269static SizeT peak_snapshot_total_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000270
njn734b8052007-11-01 04:40:37 +0000271// Incremented every time memory is allocated/deallocated, by the
272// allocated/deallocated amount; includes heap, heap-admin and stack
273// memory. An alternative to milliseconds as a unit of program "time".
274static ULong total_allocs_deallocs_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000275
njn734b8052007-11-01 04:40:37 +0000276// We don't start taking snapshots until the first basic block is executed,
277// rather than doing it in ms_post_clo_init (which is the obvious spot), for
278// two reasons.
279// - It lets us ignore stack events prior to that, because they're not
280// really proper ones and just would screw things up.
281// - Because there's still some core initialisation to do, and so there
282// would be an artificial time gap between the first and second snapshots.
283//
284static Bool have_started_executing_code = False;
nethercotec9f36922004-02-14 16:40:02 +0000285
njn734b8052007-11-01 04:40:37 +0000286//------------------------------------------------------------//
287//--- Alloc fns ---//
288//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000289
njn734b8052007-11-01 04:40:37 +0000290static XArray* alloc_fns;
nethercotec9f36922004-02-14 16:40:02 +0000291
njn734b8052007-11-01 04:40:37 +0000292static void init_alloc_fns(void)
293{
294 // Create the list, and add the default elements.
295 alloc_fns = VG_(newXA)(VG_(malloc), VG_(free), sizeof(Char*));
296 #define DO(x) { Char* s = x; VG_(addToXA)(alloc_fns, &s); }
nethercotec9f36922004-02-14 16:40:02 +0000297
njn734b8052007-11-01 04:40:37 +0000298 // Ordered according to (presumed) frequency.
299 // Nb: The C++ "operator new*" ones are overloadable. We include them
300 // always anyway, because even if they're overloaded, it would be a
301 // prodigiously stupid overloading that caused them to not allocate
302 // memory.
303 DO("malloc" );
304 DO("__builtin_new" );
305 DO("operator new(unsigned)" );
306 DO("operator new(unsigned long)" );
307 DO("__builtin_vec_new" );
308 DO("operator new[](unsigned)" );
309 DO("operator new[](unsigned long)" );
310 DO("calloc" );
311 DO("realloc" );
312 DO("memalign" );
313 DO("operator new(unsigned, std::nothrow_t const&)" );
314 DO("operator new[](unsigned, std::nothrow_t const&)" );
315 DO("operator new(unsigned long, std::nothrow_t const&)" );
316 DO("operator new[](unsigned long, std::nothrow_t const&)");
317}
nethercotec9f36922004-02-14 16:40:02 +0000318
njn734b8052007-11-01 04:40:37 +0000319static Bool is_alloc_fn(Char* fnname)
320{
321 Char** alloc_fn_ptr;
322 Int i;
323
324 // Nb: It's a linear search through the list, because we're comparing
325 // strings rather than pointers to strings.
326 // Nb: This gets called a lot. It was an OSet, but they're quite slow to
327 // iterate through so it wasn't a good choice.
328 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
329 alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
330 if (VG_STREQ(fnname, *alloc_fn_ptr))
331 return True;
nethercotec9f36922004-02-14 16:40:02 +0000332 }
njn734b8052007-11-01 04:40:37 +0000333 return False;
334}
nethercotec9f36922004-02-14 16:40:02 +0000335
njn734b8052007-11-01 04:40:37 +0000336
337//------------------------------------------------------------//
338//--- Command line args ---//
339//------------------------------------------------------------//
340
341#define MAX_DEPTH 200
342
njn1a2741a2007-11-26 21:59:04 +0000343typedef enum { TimeI, TimeMS, TimeB } TimeUnit;
njn734b8052007-11-01 04:40:37 +0000344
345static Char* TimeUnit_to_string(TimeUnit time_unit)
346{
347 switch (time_unit) {
njn1a2741a2007-11-26 21:59:04 +0000348 case TimeI: return "i";
njn734b8052007-11-01 04:40:37 +0000349 case TimeMS: return "ms";
350 case TimeB: return "B";
351 default: tl_assert2(0, "TimeUnit_to_string: unrecognised TimeUnit");
352 }
353}
354
355static Bool clo_heap = True;
njn429afb42007-11-02 04:12:48 +0000356 // clo_heap_admin is deliberately a word-sized type. At one point it was
357 // a UInt, but this caused problems on 64-bit machines when it was
358 // multiplied by a small negative number and then promoted to a
359 // word-sized type -- it ended up with a value of 4.2 billion. Sigh.
njn62721e92007-11-11 22:15:58 +0000360static SizeT clo_heap_admin = 8;
361static Bool clo_stacks = False;
362static UInt clo_depth = 30;
363static double clo_threshold = 1.0; // percentage
364static double clo_peak_inaccuracy = 1.0; // percentage
njn1a2741a2007-11-26 21:59:04 +0000365static UInt clo_time_unit = TimeI;
njn62721e92007-11-11 22:15:58 +0000366static UInt clo_detailed_freq = 10;
367static UInt clo_max_snapshots = 100;
njnf4c665f2007-11-20 07:55:40 +0000368static Char* clo_massif_out_file = "massif.out.%p";
njn734b8052007-11-01 04:40:37 +0000369
370static XArray* args_for_massif;
nethercotec9f36922004-02-14 16:40:02 +0000371
njn51d827b2005-05-09 01:02:08 +0000372static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000373{
njn734b8052007-11-01 04:40:37 +0000374 // Remember the arg for later use.
375 VG_(addToXA)(args_for_massif, &arg);
nethercotec9f36922004-02-14 16:40:02 +0000376
njn734b8052007-11-01 04:40:37 +0000377 VG_BOOL_CLO(arg, "--heap", clo_heap)
378 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
379
njn734b8052007-11-01 04:40:37 +0000380 else VG_NUM_CLO(arg, "--heap-admin", clo_heap_admin)
381 else VG_NUM_CLO(arg, "--depth", clo_depth)
382
njn62721e92007-11-11 22:15:58 +0000383 else VG_DBL_CLO(arg, "--threshold", clo_threshold)
njn734b8052007-11-01 04:40:37 +0000384
njn62721e92007-11-11 22:15:58 +0000385 else VG_DBL_CLO(arg, "--peak-inaccuracy", clo_peak_inaccuracy)
njn734b8052007-11-01 04:40:37 +0000386
387 else VG_NUM_CLO(arg, "--detailed-freq", clo_detailed_freq)
388 else VG_NUM_CLO(arg, "--max-snapshots", clo_max_snapshots)
389
njn1a2741a2007-11-26 21:59:04 +0000390 else if (VG_CLO_STREQ(arg, "--time-unit=i")) clo_time_unit = TimeI;
njn734b8052007-11-01 04:40:37 +0000391 else if (VG_CLO_STREQ(arg, "--time-unit=ms")) clo_time_unit = TimeMS;
392 else if (VG_CLO_STREQ(arg, "--time-unit=B")) clo_time_unit = TimeB;
nethercotec9f36922004-02-14 16:40:02 +0000393
394 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
njn734b8052007-11-01 04:40:37 +0000395 Char* alloc_fn = &arg[11];
396 VG_(addToXA)(alloc_fns, &alloc_fn);
nethercotec9f36922004-02-14 16:40:02 +0000397 }
398
njnf4c665f2007-11-20 07:55:40 +0000399 else if (VG_CLO_STREQN(14, arg, "--massif-out-file=")) {
400 clo_massif_out_file = &arg[18];
401 }
402
nethercotec9f36922004-02-14 16:40:02 +0000403 else
404 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000405
nethercotec9f36922004-02-14 16:40:02 +0000406 return True;
407}
408
njn51d827b2005-05-09 01:02:08 +0000409static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000410{
njn734b8052007-11-01 04:40:37 +0000411 VG_(printf)(
nethercotec9f36922004-02-14 16:40:02 +0000412" --heap=no|yes profile heap blocks [yes]\n"
njn1a2741a2007-11-26 21:59:04 +0000413" --heap-admin=<number> average admin bytes per heap block;\n"
njn734b8052007-11-01 04:40:37 +0000414" ignored if --heap=no [8]\n"
415" --stacks=no|yes profile stack(s) [no]\n"
416" --depth=<number> depth of contexts [30]\n"
nethercotec9f36922004-02-14 16:40:02 +0000417" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
njn62721e92007-11-11 22:15:58 +0000418" --threshold=<m.n> significance threshold, as a percentage [1.0]\n"
419" --peak-inaccuracy=<m.n> maximum peak inaccuracy, as a percentage [1.0]\n"
njn1a2741a2007-11-26 21:59:04 +0000420" --time-unit=i|ms|B time unit: instructions executed, milliseconds\n"
421" or heap bytes alloc'd/dealloc'd [i]\n"
njn734b8052007-11-01 04:40:37 +0000422" --detailed-freq=<N> every Nth snapshot should be detailed [10]\n"
423" --max-snapshots=<N> maximum number of snapshots recorded [100]\n"
njn374a36d2007-11-23 01:41:32 +0000424" --massif-out-file=<file> output file name [massif.out.%%p]\n"
nethercotec9f36922004-02-14 16:40:02 +0000425 );
426 VG_(replacement_malloc_print_usage)();
427}
428
njn51d827b2005-05-09 01:02:08 +0000429static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000430{
431 VG_(replacement_malloc_print_debug_usage)();
432}
433
njn734b8052007-11-01 04:40:37 +0000434
435//------------------------------------------------------------//
436//--- XPts, XTrees and XCons ---//
437//------------------------------------------------------------//
438
439// An XPt represents an "execution point", ie. a code address. Each XPt is
440// part of a tree of XPts (an "execution tree", or "XTree"). The details of
441// the heap are represented by a single XTree.
442//
443// The root of the tree is 'alloc_xpt', which represents all allocation
444// functions, eg:
445// - malloc/calloc/realloc/memalign/new/new[];
446// - user-specified allocation functions (using --alloc-fn);
447// - custom allocation (MALLOCLIKE) points
448// It's a bit of a fake XPt (ie. its 'ip' is zero), and is only used because
449// it makes the code simpler.
450//
451// Any child of 'alloc_xpt' is called a "top-XPt". The XPts at the bottom
452// of an XTree (leaf nodes) are "bottom-XPTs".
453//
454// Each path from a top-XPt to a bottom-XPt through an XTree gives an
455// execution context ("XCon"), ie. a stack trace. (And sub-paths represent
456// stack sub-traces.) The number of XCons in an XTree is equal to the
457// number of bottom-XPTs in that XTree.
458//
459// alloc_xpt XTrees are bi-directional.
460// | ^
461// v |
462// > parent < Example: if child1() calls parent() and child2()
463// / | \ also calls parent(), and parent() calls malloc(),
464// | / \ | the XTree will look like this.
465// | v v |
466// child1 child2
467//
njndbeb5352007-12-04 03:15:23 +0000468// (Note that malformed stack traces can lead to difficulties. See the
469// comment at the bottom of get_XCon.)
470//
njn734b8052007-11-01 04:40:37 +0000471// XTrees and XPts are mirrored by SXTrees and SXPts, where the 'S' is short
472// for "saved". When the XTree is duplicated for a snapshot, we duplicate
473// it as an SXTree, which is similar but omits some things it does not need,
474// and aggregates up insignificant nodes. This is important as an SXTree is
475// typically much smaller than an XTree.
476
477// XXX: make XPt and SXPt extensible arrays, to avoid having to do two
478// allocations per Pt.
479
480typedef struct _XPt XPt;
481struct _XPt {
482 Addr ip; // code address
483
484 // Bottom-XPts: space for the precise context.
485 // Other XPts: space of all the descendent bottom-XPts.
486 // Nb: this value goes up and down as the program executes.
487 SizeT szB;
488
489 XPt* parent; // pointer to parent XPt
490
491 // Children.
492 // n_children and max_children are 32-bit integers. 16-bit integers
493 // are too small -- a very big program might have more than 65536
494 // allocation points (ie. top-XPts) -- Konqueror starting up has 1800.
495 UInt n_children; // number of children
496 UInt max_children; // capacity of children array
497 XPt** children; // pointers to children XPts
498};
499
500typedef
501 enum {
502 SigSXPt,
503 InsigSXPt
504 }
505 SXPtTag;
506
507typedef struct _SXPt SXPt;
508struct _SXPt {
509 SXPtTag tag;
510 SizeT szB; // memory size for the node, be it Sig or Insig
511 union {
512 // An SXPt representing a single significant code location. Much like
513 // an XPt, minus the fields that aren't necessary.
514 struct {
515 Addr ip;
516 UInt n_children;
517 SXPt** children;
518 }
519 Sig;
520
521 // An SXPt representing one or more code locations, all below the
522 // significance threshold.
523 struct {
524 Int n_xpts; // number of aggregated XPts
525 }
526 Insig;
527 };
528};
nethercotec9f36922004-02-14 16:40:02 +0000529
530// Fake XPt representing all allocation functions like malloc(). Acts as
531// parent node to all top-XPts.
532static XPt* alloc_xpt;
533
534// Cheap allocation for blocks that never need to be freed. Saves about 10%
535// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000536static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000537{
538 static Addr hp = 0; // current heap pointer
539 static Addr hp_lim = 0; // maximum usable byte in current block
540
541 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
542
543 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000544 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
545 if (hp == 0)
njn734b8052007-11-01 04:40:37 +0000546 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
sewardj45f4e7c2005-09-27 19:20:21 +0000547 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000548 hp_lim = hp + SUPERBLOCK_SIZE - 1;
549 }
550
551 hp += n_bytes;
552
553 return (void*)(hp - n_bytes);
554}
555
njn734b8052007-11-01 04:40:37 +0000556static XPt* new_XPt(Addr ip, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000557{
njn734b8052007-11-01 04:40:37 +0000558 // XPts are never freed, so we can use perm_malloc to allocate them.
559 // Note that we cannot use perm_malloc for the 'children' array, because
560 // that needs to be resizable.
561 XPt* xpt = perm_malloc(sizeof(XPt));
562 xpt->ip = ip;
563 xpt->szB = 0;
564 xpt->parent = parent;
nethercotec9f36922004-02-14 16:40:02 +0000565
njn734b8052007-11-01 04:40:37 +0000566 // We don't initially allocate any space for children. We let that
567 // happen on demand. Many XPts (ie. all the bottom-XPts) don't have any
568 // children anyway.
nethercotec9f36922004-02-14 16:40:02 +0000569 xpt->n_children = 0;
njn734b8052007-11-01 04:40:37 +0000570 xpt->max_children = 0;
571 xpt->children = NULL;
nethercotec9f36922004-02-14 16:40:02 +0000572
573 // Update statistics
574 n_xpts++;
575
576 return xpt;
577}
578
njn734b8052007-11-01 04:40:37 +0000579static void add_child_xpt(XPt* parent, XPt* child)
580{
581 // Expand 'children' if necessary.
582 tl_assert(parent->n_children <= parent->max_children);
583 if (parent->n_children == parent->max_children) {
584 if (parent->max_children == 0) {
585 parent->max_children = 4;
586 parent->children = VG_(malloc)( parent->max_children * sizeof(XPt*) );
587 n_xpt_init_expansions++;
588 } else {
589 parent->max_children *= 2; // Double size
590 parent->children = VG_(realloc)( parent->children,
591 parent->max_children * sizeof(XPt*) );
592 n_xpt_later_expansions++;
593 }
594 }
595
596 // Insert new child XPt in parent's children list.
597 parent->children[ parent->n_children++ ] = child;
598}
599
600// Reverse comparison for a reverse sort -- biggest to smallest.
601static Int SXPt_revcmp_szB(void* n1, void* n2)
602{
603 SXPt* sxpt1 = *(SXPt**)n1;
604 SXPt* sxpt2 = *(SXPt**)n2;
605 return ( sxpt1->szB < sxpt2->szB ? 1
606 : sxpt1->szB > sxpt2->szB ? -1
607 : 0);
608}
609
610//------------------------------------------------------------//
611//--- XTree Operations ---//
612//------------------------------------------------------------//
613
614// Duplicates an XTree as an SXTree.
615static SXPt* dup_XTree(XPt* xpt, SizeT total_szB)
616{
617 Int i, n_sig_children, n_insig_children, n_child_sxpts;
njndbeb5352007-12-04 03:15:23 +0000618 SizeT sig_child_threshold_szB;
njn734b8052007-11-01 04:40:37 +0000619 SXPt* sxpt;
620
621 // Number of XPt children Action for SXPT
622 // ------------------ ---------------
623 // 0 sig, 0 insig alloc 0 children
624 // N sig, 0 insig alloc N children, dup all
625 // N sig, M insig alloc N+1, dup first N, aggregate remaining M
626 // 0 sig, M insig alloc 1, aggregate M
627
628 // Work out how big a child must be to be significant. If the current
629 // total_szB is zero, then we set it to 1, which means everything will be
630 // judged insignificant -- this is sensible, as there's no point showing
631 // any detail for this case. Unless they used --threshold=0, in which
632 // case we show them everything because that's what they asked for.
633 //
634 // Nb: We do this once now, rather than once per child, because if we do
635 // that the cost of all the divisions adds up to something significant.
636 if (total_szB == 0 && clo_threshold != 0) {
637 sig_child_threshold_szB = 1;
638 } else {
njn62721e92007-11-11 22:15:58 +0000639 sig_child_threshold_szB = (SizeT)((total_szB * clo_threshold) / 100);
njn734b8052007-11-01 04:40:37 +0000640 }
641
642 // How many children are significant? And do we need an aggregate SXPt?
643 n_sig_children = 0;
644 for (i = 0; i < xpt->n_children; i++) {
645 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
646 n_sig_children++;
647 }
648 }
649 n_insig_children = xpt->n_children - n_sig_children;
650 n_child_sxpts = n_sig_children + ( n_insig_children > 0 ? 1 : 0 );
651
652 // Duplicate the XPt.
653 sxpt = VG_(malloc)(sizeof(SXPt));
654 n_sxpt_allocs++;
655 sxpt->tag = SigSXPt;
656 sxpt->szB = xpt->szB;
657 sxpt->Sig.ip = xpt->ip;
658 sxpt->Sig.n_children = n_child_sxpts;
659
660 // Create the SXPt's children.
661 if (n_child_sxpts > 0) {
662 Int j;
njndbeb5352007-12-04 03:15:23 +0000663 SizeT sig_children_szB = 0, insig_children_szB = 0;
njn734b8052007-11-01 04:40:37 +0000664 sxpt->Sig.children = VG_(malloc)(n_child_sxpts * sizeof(SXPt*));
665
njndbeb5352007-12-04 03:15:23 +0000666 // Duplicate the significant children. (Nb: sig_children_szB +
667 // insig_children_szB doesn't necessarily equal xpt->szB.)
njn734b8052007-11-01 04:40:37 +0000668 j = 0;
669 for (i = 0; i < xpt->n_children; i++) {
670 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
671 sxpt->Sig.children[j++] = dup_XTree(xpt->children[i], total_szB);
njndbeb5352007-12-04 03:15:23 +0000672 sig_children_szB += xpt->children[i]->szB;
673 } else {
674 insig_children_szB += xpt->children[i]->szB;
njn734b8052007-11-01 04:40:37 +0000675 }
676 }
677
678 // Create the SXPt for the insignificant children, if any, and put it
679 // in the last child entry.
njn734b8052007-11-01 04:40:37 +0000680 if (n_insig_children > 0) {
681 // Nb: We 'n_sxpt_allocs' here because creating an Insig SXPt
682 // doesn't involve a call to dup_XTree().
683 SXPt* insig_sxpt = VG_(malloc)(sizeof(SXPt));
684 n_sxpt_allocs++;
685 insig_sxpt->tag = InsigSXPt;
686 insig_sxpt->szB = insig_children_szB;
687 insig_sxpt->Insig.n_xpts = n_insig_children;
688 sxpt->Sig.children[n_sig_children] = insig_sxpt;
689 }
690 } else {
691 sxpt->Sig.children = NULL;
692 }
693
694 return sxpt;
695}
696
697static void free_SXTree(SXPt* sxpt)
698{
699 Int i;
700 tl_assert(sxpt != NULL);
701
702 switch (sxpt->tag) {
703 case SigSXPt:
704 // Free all children SXPts, then the children array.
705 for (i = 0; i < sxpt->Sig.n_children; i++) {
706 free_SXTree(sxpt->Sig.children[i]);
707 sxpt->Sig.children[i] = NULL;
708 }
709 VG_(free)(sxpt->Sig.children); sxpt->Sig.children = NULL;
710 break;
711
712 case InsigSXPt:
713 break;
714
715 default: tl_assert2(0, "free_SXTree: unknown SXPt tag");
716 }
717
718 // Free the SXPt itself.
719 VG_(free)(sxpt); sxpt = NULL;
720 n_sxpt_frees++;
721}
722
723// Sanity checking: we periodically check the heap XTree with
724// ms_expensive_sanity_check.
725static void sanity_check_XTree(XPt* xpt, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000726{
njn734b8052007-11-01 04:40:37 +0000727 tl_assert(xpt != NULL);
728
729 // Check back-pointer.
730 tl_assert2(xpt->parent == parent,
731 "xpt->parent = %p, parent = %p\n", xpt->parent, parent);
732
733 // Check children counts look sane.
734 tl_assert(xpt->n_children <= xpt->max_children);
735
njndbeb5352007-12-04 03:15:23 +0000736 // Unfortunately, xpt's size is not necessarily equal to the sum of xpt's
737 // children's sizes. See comment at the bottom of get_XCon.
nethercotec9f36922004-02-14 16:40:02 +0000738}
739
njn734b8052007-11-01 04:40:37 +0000740// Sanity checking: we check SXTrees (which are in snapshots) after
741// snapshots are created, before they are deleted, and before they are
742// printed.
743static void sanity_check_SXTree(SXPt* sxpt)
nethercotec9f36922004-02-14 16:40:02 +0000744{
njn734b8052007-11-01 04:40:37 +0000745 Int i;
nethercotec9f36922004-02-14 16:40:02 +0000746
njn734b8052007-11-01 04:40:37 +0000747 tl_assert(sxpt != NULL);
nethercotec9f36922004-02-14 16:40:02 +0000748
njn734b8052007-11-01 04:40:37 +0000749 // Check the sum of any children szBs equals the SXPt's szB. Check the
750 // children at the same time.
751 switch (sxpt->tag) {
752 case SigSXPt: {
753 if (sxpt->Sig.n_children > 0) {
njn734b8052007-11-01 04:40:37 +0000754 for (i = 0; i < sxpt->Sig.n_children; i++) {
755 sanity_check_SXTree(sxpt->Sig.children[i]);
njn734b8052007-11-01 04:40:37 +0000756 }
njn734b8052007-11-01 04:40:37 +0000757 }
758 break;
759 }
760 case InsigSXPt:
761 break; // do nothing
762
763 default: tl_assert2(0, "sanity_check_SXTree: unknown SXPt tag");
764 }
765}
766
767
768//------------------------------------------------------------//
769//--- XCon Operations ---//
770//------------------------------------------------------------//
771
772// This is the limit on the number of removed alloc-fns that can be in a
773// single XCon.
774#define MAX_OVERESTIMATE 50
775#define MAX_IPS (MAX_DEPTH + MAX_OVERESTIMATE)
776
777// Get the stack trace for an XCon, filtering out uninteresting entries:
778// alloc-fns and entries above alloc-fns, and entries below main-or-below-main.
779// Eg: alloc-fn1 / alloc-fn2 / a / b / main / (below main) / c
780// becomes: a / b / main
781// Nb: it's possible to end up with an empty trace, eg. if 'main' is marked
782// as an alloc-fn. This is ok.
783static
784Int get_IPs( ThreadId tid, Bool is_custom_alloc, Addr ips[])
785{
786 #define BUF_LEN 1024
787 Char buf[BUF_LEN];
788 Int n_ips, i, n_alloc_fns_removed;
789 Int overestimate;
790 Bool redo;
791
792 // We ask for a few more IPs than clo_depth suggests we need. Then we
793 // remove every entry that is an alloc-fn. Depending on the
794 // circumstances, we may need to redo it all, asking for more IPs.
795 // Details:
796 // - If the original stack trace is smaller than asked-for, redo=False
797 // - Else if after filtering we have >= clo_depth IPs, redo=False
798 // - Else redo=True
799 // In other words, to redo, we'd have to get a stack trace as big as we
800 // asked for and remove more than 'overestimate' alloc-fns.
801
802 // Main loop.
803 redo = True; // Assume this to begin with.
804 for (overestimate = 3; redo; overestimate += 6) {
805 // This should never happen -- would require MAX_OVERESTIMATE
806 // alloc-fns to be removed from the stack trace.
807 if (overestimate > MAX_OVERESTIMATE)
808 VG_(tool_panic)("get_IPs: ips[] too small, inc. MAX_OVERESTIMATE?");
809
810 // Ask for more IPs than clo_depth suggests we need.
sewardj39f34232007-11-09 23:02:28 +0000811 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate,
812 0/*first_ip_delta*/ );
njn734b8052007-11-01 04:40:37 +0000813 tl_assert(n_ips > 0);
nethercotec9f36922004-02-14 16:40:02 +0000814
njn734b8052007-11-01 04:40:37 +0000815 // If the original stack trace is smaller than asked-for, redo=False.
816 if (n_ips < clo_depth + overestimate) { redo = False; }
nethercotec9f36922004-02-14 16:40:02 +0000817
njn734b8052007-11-01 04:40:37 +0000818 // If it's a non-custom block, we will always remove the first stack
819 // trace entry (which will be one of malloc, __builtin_new, etc).
820 n_alloc_fns_removed = ( is_custom_alloc ? 0 : 1 );
nethercotec9f36922004-02-14 16:40:02 +0000821
njn734b8052007-11-01 04:40:37 +0000822 // Filter out alloc fns. If it's a non-custom block, we remove the
823 // first entry (which will be one of malloc, __builtin_new, etc)
824 // without looking at it, because VG_(get_fnname) is expensive (it
825 // involves calls to VG_(malloc)/VG_(free)).
826 for (i = n_alloc_fns_removed; i < n_ips; i++) {
827 if (VG_(get_fnname)(ips[i], buf, BUF_LEN)) {
828 if (is_alloc_fn(buf)) {
829 n_alloc_fns_removed++;
830 } else {
831 break;
832 }
833 }
834 }
835 // Remove the alloc fns by shuffling the rest down over them.
836 n_ips -= n_alloc_fns_removed;
837 for (i = 0; i < n_ips; i++) {
838 ips[i] = ips[i + n_alloc_fns_removed];
839 }
nethercotec9f36922004-02-14 16:40:02 +0000840
njn734b8052007-11-01 04:40:37 +0000841 // If after filtering we have >= clo_depth IPs, redo=False
842 if (n_ips >= clo_depth) {
843 redo = False;
844 n_ips = clo_depth; // Ignore any IPs below --depth.
845 }
846
847 if (redo) {
848 n_XCon_redos++;
nethercotec9f36922004-02-14 16:40:02 +0000849 }
850 }
njn734b8052007-11-01 04:40:37 +0000851 return n_ips;
852}
nethercotec9f36922004-02-14 16:40:02 +0000853
njn734b8052007-11-01 04:40:37 +0000854// Gets an XCon and puts it in the tree. Returns the XCon's bottom-XPt.
855static XPt* get_XCon( ThreadId tid, Bool is_custom_alloc )
856{
857 Addr ips[MAX_IPS];
858 Int i;
859 XPt* xpt = alloc_xpt;
nethercotec9f36922004-02-14 16:40:02 +0000860
njn734b8052007-11-01 04:40:37 +0000861 // After this call, the IPs we want are in ips[0]..ips[n_ips-1].
862 Int n_ips = get_IPs(tid, is_custom_alloc, ips);
863
864 // Now do the search/insertion of the XCon.
865 for (i = 0; i < n_ips; i++) {
866 Addr ip = ips[i];
867 Int ch;
njnd01fef72005-03-25 23:35:48 +0000868 // Look for IP in xpt's children.
njn734b8052007-11-01 04:40:37 +0000869 // Linear search, ugh -- about 10% of time for konqueror startup tried
870 // caching last result, only hit about 4% for konqueror.
nethercotec9f36922004-02-14 16:40:02 +0000871 // Nb: this search hits about 98% of the time for konqueror
njn734b8052007-11-01 04:40:37 +0000872 for (ch = 0; True; ch++) {
873 if (ch == xpt->n_children) {
874 // IP not found in the children.
875 // Create and add new child XPt, then stop.
876 XPt* new_child_xpt = new_XPt(ip, xpt);
877 add_child_xpt(xpt, new_child_xpt);
878 xpt = new_child_xpt;
879 break;
nethercotec9f36922004-02-14 16:40:02 +0000880
njn734b8052007-11-01 04:40:37 +0000881 } else if (ip == xpt->children[ch]->ip) {
882 // Found the IP in the children, stop.
883 xpt = xpt->children[ch];
nethercotec9f36922004-02-14 16:40:02 +0000884 break;
885 }
nethercotec9f36922004-02-14 16:40:02 +0000886 }
nethercotec9f36922004-02-14 16:40:02 +0000887 }
njndbeb5352007-12-04 03:15:23 +0000888
889 // [Note: several comments refer to this comment. Do not delete it
890 // without updating them.]
891 //
892 // A complication... If all stack traces were well-formed, then the
893 // returned xpt would always be a bottom-XPt. As a consequence, an XPt's
894 // size would always be equal to the sum of its children's sizes, which
895 // is an excellent sanity check.
896 //
897 // Unfortunately, stack traces occasionally are malformed, ie. truncated.
898 // This allows a stack trace to be a sub-trace of another, eg. a/b/c is a
899 // sub-trace of a/b/c/d. So we can't assume this xpt is a bottom-XPt;
900 // nor can we do sanity check an XPt's size against its children's sizes.
901 // This is annoying, but must be dealt with. (Older versions of Massif
902 // had this assertion in, and it was reported to fail by real users a
903 // couple of times.) Even more annoyingly, I can't come up with a simple
904 // test case that exhibit such a malformed stack trace, so I can't
905 // regression test it. Sigh.
906 //
907 // However, we can print a warning, so that if it happens (unexpectedly)
908 // in existing regression tests we'll know. Also, it warns users that
909 // the output snapshots may not add up the way they might expect.
910 //
911 //tl_assert(0 == xpt->n_children); // Must be bottom-XPt
912 if (0 != xpt->n_children) {
913 static Int n_moans = 0;
914 if (n_moans < 3) {
915 VG_(message)(Vg_UserMsg,
916 "Warning: Malformed stack trace detected. In Massif's output,");
917 VG_(message)(Vg_UserMsg,
918 "Warning: the size of an entry's child entries may not sum up");
919 VG_(message)(Vg_UserMsg,
920 "Warning: to the entry's size as they normally do.");
921 n_moans++;
922 if (3 == n_moans)
923 VG_(message)(Vg_UserMsg,
924 "Warning: (And Massif now won't warn about this again.)");
925 }
926 }
njn734b8052007-11-01 04:40:37 +0000927 return xpt;
nethercotec9f36922004-02-14 16:40:02 +0000928}
929
njn734b8052007-11-01 04:40:37 +0000930// Update 'szB' of every XPt in the XCon, by percolating upwards.
931static void update_XCon(XPt* xpt, SSizeT space_delta)
nethercotec9f36922004-02-14 16:40:02 +0000932{
njnca82cc02004-11-22 17:18:48 +0000933 tl_assert(True == clo_heap);
njnca82cc02004-11-22 17:18:48 +0000934 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +0000935
njn734b8052007-11-01 04:40:37 +0000936 if (0 == space_delta)
937 return;
938
nethercotec9f36922004-02-14 16:40:02 +0000939 while (xpt != alloc_xpt) {
njn734b8052007-11-01 04:40:37 +0000940 if (space_delta < 0) tl_assert(xpt->szB >= -space_delta);
941 xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000942 xpt = xpt->parent;
njn734b8052007-11-01 04:40:37 +0000943 }
944 if (space_delta < 0) tl_assert(alloc_xpt->szB >= -space_delta);
945 alloc_xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000946}
947
948
njn734b8052007-11-01 04:40:37 +0000949//------------------------------------------------------------//
950//--- Snapshots ---//
951//------------------------------------------------------------//
952
953// Snapshots are done in a way so that we always have a reasonable number of
954// them. We start by taking them quickly. Once we hit our limit, we cull
955// some (eg. half), and start taking them more slowly. Once we hit the
956// limit again, we again cull and then take them even more slowly, and so
957// on.
958
njn1a2741a2007-11-26 21:59:04 +0000959// Time is measured either in i or ms or bytes, depending on the --time-unit
njn734b8052007-11-01 04:40:37 +0000960// option. It's a Long because it can exceed 32-bits reasonably easily, and
961// because we need to allow negative values to represent unset times.
962typedef Long Time;
963
964#define UNUSED_SNAPSHOT_TIME -333 // A conspicuous negative number.
965
966typedef
967 enum {
968 Normal = 77,
969 Peak,
970 Unused
971 }
972 SnapshotKind;
nethercotec9f36922004-02-14 16:40:02 +0000973
974typedef
975 struct {
njn734b8052007-11-01 04:40:37 +0000976 SnapshotKind kind;
977 Time time;
978 SizeT heap_szB;
njn32397c02007-11-10 04:08:08 +0000979 SizeT heap_extra_szB;// Heap slop + admin bytes.
njn734b8052007-11-01 04:40:37 +0000980 SizeT stacks_szB;
981 SXPt* alloc_sxpt; // Heap XTree root, if a detailed snapshot,
njn32397c02007-11-10 04:08:08 +0000982 } // otherwise NULL.
njn734b8052007-11-01 04:40:37 +0000983 Snapshot;
nethercotec9f36922004-02-14 16:40:02 +0000984
njn734b8052007-11-01 04:40:37 +0000985static UInt next_snapshot_i = 0; // Index of where next snapshot will go.
986static Snapshot* snapshots; // Array of snapshots.
987
988static Bool is_snapshot_in_use(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +0000989{
njn734b8052007-11-01 04:40:37 +0000990 if (Unused == snapshot->kind) {
991 // If snapshot is unused, check all the fields are unset.
992 tl_assert(snapshot->time == UNUSED_SNAPSHOT_TIME);
njn32397c02007-11-10 04:08:08 +0000993 tl_assert(snapshot->heap_extra_szB == 0);
njn734b8052007-11-01 04:40:37 +0000994 tl_assert(snapshot->heap_szB == 0);
995 tl_assert(snapshot->stacks_szB == 0);
996 tl_assert(snapshot->alloc_sxpt == NULL);
997 return False;
nethercotec9f36922004-02-14 16:40:02 +0000998 } else {
njn734b8052007-11-01 04:40:37 +0000999 tl_assert(snapshot->time != UNUSED_SNAPSHOT_TIME);
1000 return True;
nethercotec9f36922004-02-14 16:40:02 +00001001 }
1002}
1003
njn734b8052007-11-01 04:40:37 +00001004static Bool is_detailed_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001005{
njn734b8052007-11-01 04:40:37 +00001006 return (snapshot->alloc_sxpt ? True : False);
nethercotec9f36922004-02-14 16:40:02 +00001007}
1008
njn734b8052007-11-01 04:40:37 +00001009static Bool is_uncullable_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001010{
njn734b8052007-11-01 04:40:37 +00001011 return &snapshots[0] == snapshot // First snapshot
1012 || &snapshots[next_snapshot_i-1] == snapshot // Last snapshot
1013 || snapshot->kind == Peak; // Peak snapshot
nethercotec9f36922004-02-14 16:40:02 +00001014}
1015
njn734b8052007-11-01 04:40:37 +00001016static void sanity_check_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001017{
njn734b8052007-11-01 04:40:37 +00001018 if (snapshot->alloc_sxpt) {
1019 sanity_check_SXTree(snapshot->alloc_sxpt);
1020 }
nethercotec9f36922004-02-14 16:40:02 +00001021}
1022
njn734b8052007-11-01 04:40:37 +00001023// All the used entries should look used, all the unused ones should be clear.
1024static void sanity_check_snapshots_array(void)
1025{
1026 Int i;
1027 for (i = 0; i < next_snapshot_i; i++) {
1028 tl_assert( is_snapshot_in_use( & snapshots[i] ));
1029 }
1030 for ( ; i < clo_max_snapshots; i++) {
1031 tl_assert(!is_snapshot_in_use( & snapshots[i] ));
1032 }
1033}
nethercotec9f36922004-02-14 16:40:02 +00001034
njn734b8052007-11-01 04:40:37 +00001035// This zeroes all the fields in the snapshot, but does not free the heap
1036// XTree if present. It also does a sanity check unless asked not to; we
1037// can't sanity check at startup when clearing the initial snapshots because
1038// they're full of junk.
1039static void clear_snapshot(Snapshot* snapshot, Bool do_sanity_check)
1040{
1041 if (do_sanity_check) sanity_check_snapshot(snapshot);
1042 snapshot->kind = Unused;
1043 snapshot->time = UNUSED_SNAPSHOT_TIME;
njn32397c02007-11-10 04:08:08 +00001044 snapshot->heap_extra_szB = 0;
njn734b8052007-11-01 04:40:37 +00001045 snapshot->heap_szB = 0;
1046 snapshot->stacks_szB = 0;
1047 snapshot->alloc_sxpt = NULL;
1048}
1049
1050// This zeroes all the fields in the snapshot, and frees the heap XTree if
1051// present.
1052static void delete_snapshot(Snapshot* snapshot)
1053{
1054 // Nb: if there's an XTree, we free it after calling clear_snapshot,
1055 // because clear_snapshot does a sanity check which includes checking the
1056 // XTree.
1057 SXPt* tmp_sxpt = snapshot->alloc_sxpt;
1058 clear_snapshot(snapshot, /*do_sanity_check*/True);
1059 if (tmp_sxpt) {
1060 free_SXTree(tmp_sxpt);
1061 }
1062}
1063
1064static void VERB_snapshot(Int verbosity, Char* prefix, Int i)
1065{
1066 Snapshot* snapshot = &snapshots[i];
1067 Char* suffix;
1068 switch (snapshot->kind) {
1069 case Peak: suffix = "p"; break;
1070 case Normal: suffix = ( is_detailed_snapshot(snapshot) ? "d" : "." ); break;
1071 case Unused: suffix = "u"; break;
1072 default:
1073 tl_assert2(0, "VERB_snapshot: unknown snapshot kind: %d", snapshot->kind);
1074 }
njn32397c02007-11-10 04:08:08 +00001075 VERB(verbosity, "%s S%s%3d (t:%lld, hp:%ld, ex:%ld, st:%ld)",
njn734b8052007-11-01 04:40:37 +00001076 prefix, suffix, i,
1077 snapshot->time,
1078 snapshot->heap_szB,
njn32397c02007-11-10 04:08:08 +00001079 snapshot->heap_extra_szB,
njn734b8052007-11-01 04:40:37 +00001080 snapshot->stacks_szB
1081 );
1082}
1083
1084// Cull half the snapshots; we choose those that represent the smallest
1085// time-spans, because that gives us the most even distribution of snapshots
1086// over time. (It's possible to lose interesting spikes, however.)
1087//
1088// Algorithm for N snapshots: We find the snapshot representing the smallest
1089// timeframe, and remove it. We repeat this until (N/2) snapshots are gone.
1090// We have to do this one snapshot at a time, rather than finding the (N/2)
1091// smallest snapshots in one hit, because when a snapshot is removed, its
1092// neighbours immediately cover greater timespans. So it's O(N^2), but N is
1093// small, and it's not done very often.
1094//
1095// Once we're done, we return the new smallest interval between snapshots.
1096// That becomes our minimum time interval.
1097static UInt cull_snapshots(void)
1098{
1099 Int i, jp, j, jn, min_timespan_i;
1100 Int n_deleted = 0;
1101 Time min_timespan;
1102
1103 n_cullings++;
1104
1105 // Sets j to the index of the first not-yet-removed snapshot at or after i
1106 #define FIND_SNAPSHOT(i, j) \
1107 for (j = i; \
1108 j < clo_max_snapshots && !is_snapshot_in_use(&snapshots[j]); \
1109 j++) { }
1110
1111 VERB(2, "Culling...");
1112
1113 // First we remove enough snapshots by clearing them in-place. Once
1114 // that's done, we can slide the remaining ones down.
1115 for (i = 0; i < clo_max_snapshots/2; i++) {
1116 // Find the snapshot representing the smallest timespan. The timespan
1117 // for snapshot n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
1118 // snapshot A and B. We don't consider the first and last snapshots for
1119 // removal.
1120 Snapshot* min_snapshot;
1121 Int min_j;
1122
1123 // Initial triple: (prev, curr, next) == (jp, j, jn)
1124 // Initial min_timespan is the first one.
1125 jp = 0;
1126 FIND_SNAPSHOT(1, j);
1127 FIND_SNAPSHOT(j+1, jn);
1128 min_timespan = 0x7fffffffffffffffLL;
1129 min_j = -1;
1130 while (jn < clo_max_snapshots) {
1131 Time timespan = snapshots[jn].time - snapshots[jp].time;
1132 tl_assert(timespan >= 0);
1133 // Nb: We never cull the peak snapshot.
1134 if (Peak != snapshots[j].kind && timespan < min_timespan) {
1135 min_timespan = timespan;
1136 min_j = j;
1137 }
1138 // Move on to next triple
1139 jp = j;
1140 j = jn;
1141 FIND_SNAPSHOT(jn+1, jn);
1142 }
1143 // We've found the least important snapshot, now delete it. First
1144 // print it if necessary.
1145 tl_assert(-1 != min_j); // Check we found a minimum.
1146 min_snapshot = & snapshots[ min_j ];
1147 if (VG_(clo_verbosity) > 1) {
1148 Char buf[64];
1149 VG_(snprintf)(buf, 64, " %3d (t-span = %lld)", i, min_timespan);
1150 VERB_snapshot(2, buf, min_j);
1151 }
1152 delete_snapshot(min_snapshot);
1153 n_deleted++;
1154 }
1155
1156 // Slide down the remaining snapshots over the removed ones. First set i
1157 // to point to the first empty slot, and j to the first full slot after
1158 // i. Then slide everything down.
1159 for (i = 0; is_snapshot_in_use( &snapshots[i] ); i++) { }
1160 for (j = i; !is_snapshot_in_use( &snapshots[j] ); j++) { }
1161 for ( ; j < clo_max_snapshots; j++) {
1162 if (is_snapshot_in_use( &snapshots[j] )) {
1163 snapshots[i++] = snapshots[j];
1164 clear_snapshot(&snapshots[j], /*do_sanity_check*/True);
1165 }
1166 }
1167 next_snapshot_i = i;
1168
1169 // Check snapshots array looks ok after changes.
1170 sanity_check_snapshots_array();
1171
1172 // Find the minimum timespan remaining; that will be our new minimum
1173 // time interval. Note that above we were finding timespans by measuring
1174 // two intervals around a snapshot that was under consideration for
1175 // deletion. Here we only measure single intervals because all the
1176 // deletions have occurred.
1177 //
1178 // But we have to be careful -- some snapshots (eg. snapshot 0, and the
1179 // peak snapshot) are uncullable. If two uncullable snapshots end up
1180 // next to each other, they'll never be culled (assuming the peak doesn't
1181 // change), and the time gap between them will not change. However, the
1182 // time between the remaining cullable snapshots will grow ever larger.
1183 // This means that the min_timespan found will always be that between the
1184 // two uncullable snapshots, and it will be much smaller than it should
1185 // be. To avoid this problem, when computing the minimum timespan, we
1186 // ignore any timespans between two uncullable snapshots.
1187 tl_assert(next_snapshot_i > 1);
1188 min_timespan = 0x7fffffffffffffffLL;
1189 min_timespan_i = -1;
1190 for (i = 1; i < next_snapshot_i; i++) {
1191 if (is_uncullable_snapshot(&snapshots[i]) &&
1192 is_uncullable_snapshot(&snapshots[i-1]))
1193 {
1194 VERB(2, "(Ignoring interval %d--%d when computing minimum)", i-1, i);
1195 } else {
1196 Time timespan = snapshots[i].time - snapshots[i-1].time;
1197 tl_assert(timespan >= 0);
1198 if (timespan < min_timespan) {
1199 min_timespan = timespan;
1200 min_timespan_i = i;
1201 }
1202 }
1203 }
1204 tl_assert(-1 != min_timespan_i); // Check we found a minimum.
1205
1206 // Print remaining snapshots, if necessary.
1207 if (VG_(clo_verbosity) > 1) {
1208 VERB(2, "Finished culling (%3d of %3d deleted)",
1209 n_deleted, clo_max_snapshots);
1210 for (i = 0; i < next_snapshot_i; i++) {
1211 VERB_snapshot(2, " post-cull", i);
1212 }
1213 VERB(2, "New time interval = %lld (between snapshots %d and %d)",
1214 min_timespan, min_timespan_i-1, min_timespan_i);
1215 }
1216
1217 return min_timespan;
1218}
1219
1220static Time get_time(void)
1221{
1222 // Get current time, in whatever time unit we're using.
njn1a2741a2007-11-26 21:59:04 +00001223 if (clo_time_unit == TimeI) {
1224 return guest_instrs_executed;
1225 } else if (clo_time_unit == TimeMS) {
njn734b8052007-11-01 04:40:37 +00001226 // Some stuff happens between the millisecond timer being initialised
1227 // to zero and us taking our first snapshot. We determine that time
1228 // gap so we can subtract it from all subsequent times so that our
1229 // first snapshot is considered to be at t = 0ms. Unfortunately, a
1230 // bunch of symbols get read after the first snapshot is taken but
1231 // before the second one (which is triggered by the first allocation),
1232 // so when the time-unit is 'ms' we always have a big gap between the
1233 // first two snapshots. But at least users won't have to wonder why
1234 // the first snapshot isn't at t=0.
1235 static Bool is_first_get_time = True;
1236 static Time start_time_ms;
1237 if (is_first_get_time) {
1238 start_time_ms = VG_(read_millisecond_timer)();
1239 is_first_get_time = False;
1240 return 0;
1241 } else {
1242 return VG_(read_millisecond_timer)() - start_time_ms;
1243 }
1244 } else if (clo_time_unit == TimeB) {
1245 return total_allocs_deallocs_szB;
1246 } else {
1247 tl_assert2(0, "bad --time-unit value");
1248 }
1249}
1250
1251// Take a snapshot, and only that -- decisions on whether to take a
1252// snapshot, or what kind of snapshot, are made elsewhere.
1253static void
1254take_snapshot(Snapshot* snapshot, SnapshotKind kind, Time time,
1255 Bool is_detailed, Char* what)
1256{
1257 tl_assert(!is_snapshot_in_use(snapshot));
1258 tl_assert(have_started_executing_code);
1259
1260 // Heap and heap admin.
1261 if (clo_heap) {
1262 snapshot->heap_szB = heap_szB;
1263 if (is_detailed) {
njn32397c02007-11-10 04:08:08 +00001264 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001265 snapshot->alloc_sxpt = dup_XTree(alloc_xpt, total_szB);
1266 tl_assert( alloc_xpt->szB == heap_szB);
1267 tl_assert(snapshot->alloc_sxpt->szB == heap_szB);
1268 }
njn32397c02007-11-10 04:08:08 +00001269 snapshot->heap_extra_szB = heap_extra_szB;
njn734b8052007-11-01 04:40:37 +00001270 }
1271
1272 // Stack(s).
1273 if (clo_stacks) {
1274 snapshot->stacks_szB = stacks_szB;
1275 }
1276
1277 // Rest of snapshot.
1278 snapshot->kind = kind;
1279 snapshot->time = time;
1280 sanity_check_snapshot(snapshot);
1281
1282 // Update stats.
1283 if (Peak == kind) n_peak_snapshots++;
1284 if (is_detailed) n_detailed_snapshots++;
1285 n_real_snapshots++;
1286}
1287
1288
1289// Take a snapshot, if it's time, or if we've hit a peak.
1290static void
1291maybe_take_snapshot(SnapshotKind kind, Char* what)
1292{
1293 // 'min_time_interval' is the minimum time interval between snapshots.
1294 // If we try to take a snapshot and less than this much time has passed,
1295 // we don't take it. It gets larger as the program runs longer. It's
1296 // initialised to zero so that we begin by taking snapshots as quickly as
1297 // possible.
1298 static Time min_time_interval = 0;
1299 // Zero allows startup snapshot.
1300 static Time earliest_possible_time_of_next_snapshot = 0;
1301 static Int n_snapshots_since_last_detailed = 0;
1302 static Int n_skipped_snapshots_since_last_snapshot = 0;
1303
1304 Snapshot* snapshot;
1305 Bool is_detailed;
1306 Time time = get_time();
1307
1308 switch (kind) {
1309 case Normal:
1310 // Only do a snapshot if it's time.
1311 if (time < earliest_possible_time_of_next_snapshot) {
1312 n_skipped_snapshots++;
1313 n_skipped_snapshots_since_last_snapshot++;
1314 return;
1315 }
1316 is_detailed = (clo_detailed_freq-1 == n_snapshots_since_last_detailed);
1317 break;
1318
1319 case Peak: {
1320 // Because we're about to do a deallocation, we're coming down from a
1321 // local peak. If it is (a) actually a global peak, and (b) a certain
1322 // amount bigger than the previous peak, then we take a peak snapshot.
1323 // By not taking a snapshot for every peak, we save a lot of effort --
1324 // because many peaks remain peak only for a short time.
njn32397c02007-11-10 04:08:08 +00001325 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001326 SizeT excess_szB_for_new_peak =
njn62721e92007-11-11 22:15:58 +00001327 (SizeT)((peak_snapshot_total_szB * clo_peak_inaccuracy) / 100);
njn734b8052007-11-01 04:40:37 +00001328 if (total_szB <= peak_snapshot_total_szB + excess_szB_for_new_peak) {
1329 return;
1330 }
1331 is_detailed = True;
1332 break;
1333 }
1334
1335 default:
1336 tl_assert2(0, "maybe_take_snapshot: unrecognised snapshot kind");
1337 }
1338
1339 // Take the snapshot.
1340 snapshot = & snapshots[next_snapshot_i];
1341 take_snapshot(snapshot, kind, time, is_detailed, what);
1342
1343 // Record if it was detailed.
1344 if (is_detailed) {
1345 n_snapshots_since_last_detailed = 0;
1346 } else {
1347 n_snapshots_since_last_detailed++;
1348 }
1349
1350 // Update peak data, if it's a Peak snapshot.
1351 if (Peak == kind) {
1352 Int i, number_of_peaks_snapshots_found = 0;
1353
1354 // Sanity check the size, then update our recorded peak.
1355 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00001356 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00001357 tl_assert2(snapshot_total_szB > peak_snapshot_total_szB,
1358 "%ld, %ld\n", snapshot_total_szB, peak_snapshot_total_szB);
1359 peak_snapshot_total_szB = snapshot_total_szB;
1360
1361 // Find the old peak snapshot, if it exists, and mark it as normal.
1362 for (i = 0; i < next_snapshot_i; i++) {
1363 if (Peak == snapshots[i].kind) {
1364 snapshots[i].kind = Normal;
1365 number_of_peaks_snapshots_found++;
1366 }
1367 }
1368 tl_assert(number_of_peaks_snapshots_found <= 1);
1369 }
1370
1371 // Finish up verbosity and stats stuff.
1372 if (n_skipped_snapshots_since_last_snapshot > 0) {
1373 VERB(2, " (skipped %d snapshot%s)",
1374 n_skipped_snapshots_since_last_snapshot,
1375 ( n_skipped_snapshots_since_last_snapshot == 1 ? "" : "s") );
1376 }
1377 VERB_snapshot(2, what, next_snapshot_i);
1378 n_skipped_snapshots_since_last_snapshot = 0;
1379
1380 // Cull the entries, if our snapshot table is full.
1381 next_snapshot_i++;
1382 if (clo_max_snapshots == next_snapshot_i) {
1383 min_time_interval = cull_snapshots();
1384 }
1385
1386 // Work out the earliest time when the next snapshot can happen.
1387 earliest_possible_time_of_next_snapshot = time + min_time_interval;
1388}
1389
1390
1391//------------------------------------------------------------//
1392//--- Sanity checking ---//
1393//------------------------------------------------------------//
1394
1395static Bool ms_cheap_sanity_check ( void )
1396{
1397 return True; // Nothing useful we can cheaply check.
1398}
1399
1400static Bool ms_expensive_sanity_check ( void )
1401{
1402 sanity_check_XTree(alloc_xpt, /*parent*/NULL);
1403 sanity_check_snapshots_array();
1404 return True;
1405}
1406
1407
1408//------------------------------------------------------------//
1409//--- Heap management ---//
1410//------------------------------------------------------------//
1411
1412// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
1413// which is a foothold into the XCon at which it was allocated. From
1414// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
1415// decremented (at deallocation).
1416//
1417// Nb: first two fields must match core's VgHashNode.
1418typedef
1419 struct _HP_Chunk {
1420 struct _HP_Chunk* next;
njn32397c02007-11-10 04:08:08 +00001421 Addr data; // Ptr to actual block
1422 SizeT req_szB; // Size requested
1423 SizeT slop_szB; // Extra bytes given above those requested
1424 XPt* where; // Where allocated; bottom-XPt
njn734b8052007-11-01 04:40:37 +00001425 }
1426 HP_Chunk;
1427
1428static VgHashTable malloc_list = NULL; // HP_Chunks
1429
1430static void update_alloc_stats(SSizeT szB_delta)
1431{
1432 // Update total_allocs_deallocs_szB.
1433 if (szB_delta < 0) szB_delta = -szB_delta;
1434 total_allocs_deallocs_szB += szB_delta;
1435}
1436
njn32397c02007-11-10 04:08:08 +00001437static void update_heap_stats(SSizeT heap_szB_delta, Int heap_extra_szB_delta)
njn734b8052007-11-01 04:40:37 +00001438{
njn32397c02007-11-10 04:08:08 +00001439 if (heap_szB_delta < 0)
1440 tl_assert(heap_szB >= -heap_szB_delta);
1441 if (heap_extra_szB_delta < 0)
1442 tl_assert(heap_extra_szB >= -heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001443
njn32397c02007-11-10 04:08:08 +00001444 heap_extra_szB += heap_extra_szB_delta;
1445 heap_szB += heap_szB_delta;
1446
1447 update_alloc_stats(heap_szB_delta + heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001448}
nethercotec9f36922004-02-14 16:40:02 +00001449
nethercote159dfef2004-09-13 13:27:30 +00001450static
njn32397c02007-11-10 04:08:08 +00001451void* new_block ( ThreadId tid, void* p, SizeT req_szB, SizeT req_alignB,
njn57735902004-11-25 18:04:54 +00001452 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +00001453{
1454 HP_Chunk* hc;
njn734b8052007-11-01 04:40:37 +00001455 Bool is_custom_alloc = (NULL != p);
njn32397c02007-11-10 04:08:08 +00001456 SizeT actual_szB, slop_szB;
1457
1458 if (req_szB < 0) return NULL;
nethercotec9f36922004-02-14 16:40:02 +00001459
nethercote57e36b32004-07-10 14:56:28 +00001460 // Allocate and zero if necessary
1461 if (!p) {
njn32397c02007-11-10 04:08:08 +00001462 p = VG_(cli_malloc)( req_alignB, req_szB );
nethercote57e36b32004-07-10 14:56:28 +00001463 if (!p) {
nethercote57e36b32004-07-10 14:56:28 +00001464 return NULL;
1465 }
njn32397c02007-11-10 04:08:08 +00001466 if (is_zeroed) VG_(memset)(p, 0, req_szB);
1467 actual_szB = VG_(malloc_usable_size)(p);
1468 tl_assert(actual_szB >= req_szB);
1469 slop_szB = actual_szB - req_szB;
1470 } else {
1471 slop_szB = 0;
nethercote57e36b32004-07-10 14:56:28 +00001472 }
1473
njnf1c5def2005-08-11 02:17:07 +00001474 // Make new HP_Chunk node, add to malloc_list
njn32397c02007-11-10 04:08:08 +00001475 hc = VG_(malloc)(sizeof(HP_Chunk));
1476 hc->req_szB = req_szB;
1477 hc->slop_szB = slop_szB;
1478 hc->data = (Addr)p;
1479 hc->where = NULL;
njn246a9d22005-08-14 06:24:20 +00001480 VG_(HT_add_node)(malloc_list, hc);
nethercote57e36b32004-07-10 14:56:28 +00001481
njn734b8052007-11-01 04:40:37 +00001482 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001483 VERB(3, "<<< new_mem_heap (%lu, %lu)", req_szB, slop_szB);
njn734b8052007-11-01 04:40:37 +00001484
1485 // Update statistics.
1486 n_heap_allocs++;
1487
1488 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001489 update_heap_stats(req_szB, clo_heap_admin + slop_szB);
njn734b8052007-11-01 04:40:37 +00001490
1491 // Update XTree.
1492 hc->where = get_XCon( tid, is_custom_alloc );
njn32397c02007-11-10 04:08:08 +00001493 update_XCon(hc->where, req_szB);
njn734b8052007-11-01 04:40:37 +00001494
1495 // Maybe take a snapshot.
1496 maybe_take_snapshot(Normal, " alloc");
1497
1498 VERB(3, ">>>");
1499 }
nethercotec9f36922004-02-14 16:40:02 +00001500
nethercotec9f36922004-02-14 16:40:02 +00001501 return p;
1502}
1503
1504static __inline__
1505void die_block ( void* p, Bool custom_free )
1506{
njnf1c5def2005-08-11 02:17:07 +00001507 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +00001508
njnf1c5def2005-08-11 02:17:07 +00001509 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +00001510 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn734b8052007-11-01 04:40:37 +00001511 if (NULL == hc) {
njn5cc5d7e2005-08-11 02:09:25 +00001512 return; // must have been a bogus free()
njn734b8052007-11-01 04:40:37 +00001513 }
nethercotec9f36922004-02-14 16:40:02 +00001514
njn734b8052007-11-01 04:40:37 +00001515 if (clo_heap) {
1516 VERB(3, "<<< die_mem_heap");
nethercotec9f36922004-02-14 16:40:02 +00001517
njn734b8052007-11-01 04:40:37 +00001518 // Update statistics
1519 n_heap_frees++;
nethercote57e36b32004-07-10 14:56:28 +00001520
njn734b8052007-11-01 04:40:37 +00001521 // Maybe take a peak snapshot, since it's a deallocation.
1522 maybe_take_snapshot(Peak, "de-PEAK");
1523
1524 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001525 update_heap_stats(-hc->req_szB, -clo_heap_admin - hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001526
1527 // Update XTree.
njn32397c02007-11-10 04:08:08 +00001528 update_XCon(hc->where, -hc->req_szB);
njn734b8052007-11-01 04:40:37 +00001529
1530 // Maybe take a snapshot.
1531 maybe_take_snapshot(Normal, "dealloc");
1532
njn32397c02007-11-10 04:08:08 +00001533 VERB(3, ">>> (-%lu, -%lu)", hc->req_szB, hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001534 }
1535
1536 // Actually free the chunk, and the heap block (if necessary)
1537 VG_(free)( hc ); hc = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001538 if (!custom_free)
1539 VG_(cli_free)( p );
nethercotec9f36922004-02-14 16:40:02 +00001540}
1541
njn734b8052007-11-01 04:40:37 +00001542static __inline__
njn32397c02007-11-10 04:08:08 +00001543void* renew_block ( ThreadId tid, void* p_old, SizeT new_req_szB )
nethercotec9f36922004-02-14 16:40:02 +00001544{
njn734b8052007-11-01 04:40:37 +00001545 HP_Chunk* hc;
1546 void* p_new;
njn32397c02007-11-10 04:08:08 +00001547 SizeT old_req_szB, old_slop_szB, new_slop_szB, new_actual_szB;
njn734b8052007-11-01 04:40:37 +00001548 XPt *old_where, *new_where;
1549
1550 // Remove the old block
1551 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
1552 if (hc == NULL) {
1553 return NULL; // must have been a bogus realloc()
1554 }
1555
njn32397c02007-11-10 04:08:08 +00001556 old_req_szB = hc->req_szB;
1557 old_slop_szB = hc->slop_szB;
njn734b8052007-11-01 04:40:37 +00001558
1559 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001560 VERB(3, "<<< renew_mem_heap (%lu)", new_req_szB);
njn734b8052007-11-01 04:40:37 +00001561
1562 // Update statistics
1563 n_heap_reallocs++;
1564
1565 // Maybe take a peak snapshot, if it's (effectively) a deallocation.
njn32397c02007-11-10 04:08:08 +00001566 if (new_req_szB < old_req_szB) {
njn734b8052007-11-01 04:40:37 +00001567 maybe_take_snapshot(Peak, "re-PEAK");
1568 }
njn734b8052007-11-01 04:40:37 +00001569 }
1570
1571 // Actually do the allocation, if necessary.
njn32397c02007-11-10 04:08:08 +00001572 if (new_req_szB <= old_req_szB + old_slop_szB) {
1573 // New size is smaller or same; block not moved.
njn734b8052007-11-01 04:40:37 +00001574 p_new = p_old;
njn32397c02007-11-10 04:08:08 +00001575 new_slop_szB = old_slop_szB + (old_req_szB - new_req_szB);
njn734b8052007-11-01 04:40:37 +00001576
1577 } else {
njn32397c02007-11-10 04:08:08 +00001578 // New size is bigger; make new block, copy shared contents, free old.
1579 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_req_szB);
1580 if (!p_new) {
1581 // Nb: if realloc fails, NULL is returned but the old block is not
1582 // touched. What an awful function.
1583 return NULL;
njn734b8052007-11-01 04:40:37 +00001584 }
njn32397c02007-11-10 04:08:08 +00001585 VG_(memcpy)(p_new, p_old, old_req_szB);
1586 VG_(cli_free)(p_old);
1587 new_actual_szB = VG_(malloc_usable_size)(p_new);
1588 tl_assert(new_actual_szB >= new_req_szB);
1589 new_slop_szB = new_actual_szB - new_req_szB;
njn734b8052007-11-01 04:40:37 +00001590 }
1591
1592 if (p_new) {
1593 // Update HP_Chunk.
njn32397c02007-11-10 04:08:08 +00001594 hc->data = (Addr)p_new;
1595 hc->req_szB = new_req_szB;
1596 hc->slop_szB = new_slop_szB;
1597 old_where = hc->where;
1598 hc->where = NULL;
njn734b8052007-11-01 04:40:37 +00001599
1600 // Update XTree.
1601 if (clo_heap) {
1602 new_where = get_XCon( tid, /*custom_malloc*/False);
1603 hc->where = new_where;
njn32397c02007-11-10 04:08:08 +00001604 update_XCon(old_where, -old_req_szB);
1605 update_XCon(new_where, new_req_szB);
njn734b8052007-11-01 04:40:37 +00001606 }
1607 }
1608
1609 // Now insert the new hc (with a possibly new 'data' field) into
1610 // malloc_list. If this realloc() did not increase the memory size, we
1611 // will have removed and then re-added hc unnecessarily. But that's ok
1612 // because shrinking a block with realloc() is (presumably) much rarer
1613 // than growing it, and this way simplifies the growing case.
1614 VG_(HT_add_node)(malloc_list, hc);
1615
njn734b8052007-11-01 04:40:37 +00001616 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001617 // Update heap stats.
1618 update_heap_stats(new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
1619
1620 // Maybe take a snapshot.
njn734b8052007-11-01 04:40:37 +00001621 maybe_take_snapshot(Normal, "realloc");
1622
njn32397c02007-11-10 04:08:08 +00001623 VERB(3, ">>> (%ld, %ld)",
1624 new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
njn734b8052007-11-01 04:40:37 +00001625 }
1626
1627 return p_new;
nethercotec9f36922004-02-14 16:40:02 +00001628}
1629
njn734b8052007-11-01 04:40:37 +00001630
1631//------------------------------------------------------------//
1632//--- malloc() et al replacement wrappers ---//
1633//------------------------------------------------------------//
1634
1635static void* ms_malloc ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001636{
njn734b8052007-11-01 04:40:37 +00001637 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001638}
1639
njn734b8052007-11-01 04:40:37 +00001640static void* ms___builtin_new ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001641{
njn734b8052007-11-01 04:40:37 +00001642 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001643}
1644
njn734b8052007-11-01 04:40:37 +00001645static void* ms___builtin_vec_new ( ThreadId tid, SizeT szB )
fitzhardinge51f3ff12004-03-04 22:42:03 +00001646{
njn734b8052007-11-01 04:40:37 +00001647 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
1648}
1649
1650static void* ms_calloc ( ThreadId tid, SizeT m, SizeT szB )
1651{
1652 return new_block( tid, NULL, m*szB, VG_(clo_alignment), /*is_zeroed*/True );
1653}
1654
1655static void *ms_memalign ( ThreadId tid, SizeT alignB, SizeT szB )
1656{
1657 return new_block( tid, NULL, szB, alignB, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +00001658}
1659
njn51d827b2005-05-09 01:02:08 +00001660static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001661{
1662 die_block( p, /*custom_free*/False );
1663}
1664
njn51d827b2005-05-09 01:02:08 +00001665static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001666{
1667 die_block( p, /*custom_free*/False);
1668}
1669
njn51d827b2005-05-09 01:02:08 +00001670static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001671{
1672 die_block( p, /*custom_free*/False );
1673}
1674
njn734b8052007-11-01 04:40:37 +00001675static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_szB )
nethercotec9f36922004-02-14 16:40:02 +00001676{
njn734b8052007-11-01 04:40:37 +00001677 return renew_block(tid, p_old, new_szB);
nethercotec9f36922004-02-14 16:40:02 +00001678}
1679
1680
njn734b8052007-11-01 04:40:37 +00001681//------------------------------------------------------------//
1682//--- Stacks ---//
1683//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001684
njn734b8052007-11-01 04:40:37 +00001685// We really want the inlining to occur...
1686#define INLINE inline __attribute__((always_inline))
nethercotec9f36922004-02-14 16:40:02 +00001687
njn734b8052007-11-01 04:40:37 +00001688static void update_stack_stats(SSizeT stack_szB_delta)
nethercotec9f36922004-02-14 16:40:02 +00001689{
njn734b8052007-11-01 04:40:37 +00001690 if (stack_szB_delta < 0) tl_assert(stacks_szB >= -stack_szB_delta);
1691 stacks_szB += stack_szB_delta;
nethercotec9f36922004-02-14 16:40:02 +00001692
njn734b8052007-11-01 04:40:37 +00001693 update_alloc_stats(stack_szB_delta);
nethercotec9f36922004-02-14 16:40:02 +00001694}
1695
njn734b8052007-11-01 04:40:37 +00001696static INLINE void new_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001697{
njn734b8052007-11-01 04:40:37 +00001698 if (have_started_executing_code) {
1699 VERB(3, "<<< new_mem_stack (%ld)", len);
1700 n_stack_allocs++;
1701 update_stack_stats(len);
1702 maybe_take_snapshot(Normal, what);
1703 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001704 }
nethercotec9f36922004-02-14 16:40:02 +00001705}
1706
njn734b8052007-11-01 04:40:37 +00001707static INLINE void die_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001708{
njn734b8052007-11-01 04:40:37 +00001709 if (have_started_executing_code) {
1710 VERB(3, "<<< die_mem_stack (%ld)", -len);
1711 n_stack_frees++;
1712 maybe_take_snapshot(Peak, "stkPEAK");
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 void new_mem_stack(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001720{
njn734b8052007-11-01 04:40:37 +00001721 new_mem_stack_2(a, len, "stk-new");
1722}
nethercotec9f36922004-02-14 16:40:02 +00001723
njn734b8052007-11-01 04:40:37 +00001724static void die_mem_stack(Addr a, SizeT len)
1725{
1726 die_mem_stack_2(a, len, "stk-die");
1727}
nethercotec9f36922004-02-14 16:40:02 +00001728
nethercote8b5f40c2004-11-02 13:29:50 +00001729static void new_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001730{
njn734b8052007-11-01 04:40:37 +00001731 new_mem_stack_2(a, len, "sig-new");
nethercotec9f36922004-02-14 16:40:02 +00001732}
1733
nethercote8b5f40c2004-11-02 13:29:50 +00001734static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001735{
njn734b8052007-11-01 04:40:37 +00001736 die_mem_stack_2(a, len, "sig-die");
nethercotec9f36922004-02-14 16:40:02 +00001737}
1738
njn734b8052007-11-01 04:40:37 +00001739
1740//------------------------------------------------------------//
1741//--- Client Requests ---//
1742//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001743
njn51d827b2005-05-09 01:02:08 +00001744static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001745{
1746 switch (argv[0]) {
1747 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001748 void* res;
njn734b8052007-11-01 04:40:37 +00001749 void* p = (void*)argv[1];
1750 SizeT szB = argv[2];
1751 res = new_block( tid, p, szB, /*alignB--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001752 tl_assert(res == p);
njn734b8052007-11-01 04:40:37 +00001753 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001754 return True;
1755 }
1756 case VG_USERREQ__FREELIKE_BLOCK: {
njn734b8052007-11-01 04:40:37 +00001757 void* p = (void*)argv[1];
nethercotec9f36922004-02-14 16:40:02 +00001758 die_block( p, /*custom_free*/True );
njn734b8052007-11-01 04:40:37 +00001759 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001760 return True;
1761 }
1762 default:
1763 *ret = 0;
1764 return False;
1765 }
1766}
1767
njn734b8052007-11-01 04:40:37 +00001768//------------------------------------------------------------//
1769//--- Instrumentation ---//
1770//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001771
njn1a2741a2007-11-26 21:59:04 +00001772static void add_counter_update(IRSB* sbOut, Int n)
1773{
1774 #if defined(VG_BIGENDIAN)
1775 # define END Iend_BE
1776 #elif defined(VG_LITTLEENDIAN)
1777 # define END Iend_LE
1778 #else
1779 # error "Unknown endianness"
1780 #endif
1781 // Add code to increment 'guest_instrs_executed' by 'n', like this:
1782 // WrTmp(t1, Load64(&guest_instrs_executed))
1783 // WrTmp(t2, Add64(RdTmp(t1), Const(n)))
1784 // Store(&guest_instrs_executed, t2)
1785 IRTemp t1 = newIRTemp(sbOut->tyenv, Ity_I64);
1786 IRTemp t2 = newIRTemp(sbOut->tyenv, Ity_I64);
1787 IRExpr* counter_addr = mkIRExpr_HWord( (HWord)&guest_instrs_executed );
1788
1789 IRStmt* st1 = IRStmt_WrTmp(t1, IRExpr_Load(END, Ity_I64, counter_addr));
1790 IRStmt* st2 =
1791 IRStmt_WrTmp(t2,
1792 IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(t1),
1793 IRExpr_Const(IRConst_U64(n))));
1794 IRStmt* st3 = IRStmt_Store(END, counter_addr, IRExpr_RdTmp(t2));
1795
1796 addStmtToIRSB( sbOut, st1 );
1797 addStmtToIRSB( sbOut, st2 );
1798 addStmtToIRSB( sbOut, st3 );
1799}
1800
1801static IRSB* ms_instrument2( IRSB* sbIn )
1802{
1803 Int i, n = 0;
1804 IRSB* sbOut;
1805
1806 // We increment the instruction count in two places:
1807 // - just before any Ist_Exit statements;
1808 // - just before the IRSB's end.
1809 // In the former case, we zero 'n' and then continue instrumenting.
1810
1811 sbOut = deepCopyIRSBExceptStmts(sbIn);
1812
1813 for (i = 0; i < sbIn->stmts_used; i++) {
1814 IRStmt* st = sbIn->stmts[i];
1815
1816 if (!st || st->tag == Ist_NoOp) continue;
1817
1818 if (st->tag == Ist_IMark) {
1819 n++;
1820 } else if (st->tag == Ist_Exit) {
1821 if (n > 0) {
1822 // Add an increment before the Exit statement, then reset 'n'.
1823 add_counter_update(sbOut, n);
1824 n = 0;
1825 }
1826 }
1827 addStmtToIRSB( sbOut, st );
1828 }
1829
1830 if (n > 0) {
1831 // Add an increment before the SB end.
1832 add_counter_update(sbOut, n);
1833 }
1834 return sbOut;
1835}
1836
sewardj4ba057c2005-10-18 12:04:18 +00001837static
sewardj0b9d74a2006-12-24 02:24:11 +00001838IRSB* ms_instrument ( VgCallbackClosure* closure,
njn1a2741a2007-11-26 21:59:04 +00001839 IRSB* sbIn,
njn734b8052007-11-01 04:40:37 +00001840 VexGuestLayout* layout,
sewardj461df9c2006-01-17 02:06:39 +00001841 VexGuestExtents* vge,
sewardj4ba057c2005-10-18 12:04:18 +00001842 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001843{
njn734b8052007-11-01 04:40:37 +00001844 if (! have_started_executing_code) {
1845 // Do an initial sample to guarantee that we have at least one.
1846 // We use 'maybe_take_snapshot' instead of 'take_snapshot' to ensure
1847 // 'maybe_take_snapshot's internal static variables are initialised.
1848 have_started_executing_code = True;
1849 maybe_take_snapshot(Normal, "startup");
1850 }
njn1a2741a2007-11-26 21:59:04 +00001851
1852 if (clo_time_unit == TimeI) { return ms_instrument2(sbIn); }
1853 else if (clo_time_unit == TimeMS) { return sbIn; }
1854 else if (clo_time_unit == TimeB) { return sbIn; }
1855 else { tl_assert2(0, "bad --time-unit value"); }
nethercotec9f36922004-02-14 16:40:02 +00001856}
1857
nethercotec9f36922004-02-14 16:40:02 +00001858
njn734b8052007-11-01 04:40:37 +00001859//------------------------------------------------------------//
1860//--- Writing snapshots ---//
1861//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001862
njn374a36d2007-11-23 01:41:32 +00001863// The output file name. Controlled by --massif-out-file.
1864static Char* massif_out_file = NULL;
1865
njn734b8052007-11-01 04:40:37 +00001866#define FP_BUF_SIZE 1024
1867Char FP_buf[FP_BUF_SIZE];
nethercotec9f36922004-02-14 16:40:02 +00001868
njn734b8052007-11-01 04:40:37 +00001869// XXX: implement f{,n}printf in m_libcprint.c eventually, and use it here.
1870// Then change Cachegrind to use it too.
1871#define FP(format, args...) ({ \
1872 VG_(snprintf)(FP_buf, FP_BUF_SIZE, format, ##args); \
1873 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf)); \
1874})
nethercotec9f36922004-02-14 16:40:02 +00001875
1876// Nb: uses a static buffer, each call trashes the last string returned.
njn734b8052007-11-01 04:40:37 +00001877static Char* make_perc(ULong x, ULong y)
nethercotec9f36922004-02-14 16:40:02 +00001878{
1879 static Char mbuf[32];
njn734b8052007-11-01 04:40:37 +00001880
1881// tl_assert(x <= y); XXX; put back in later...
1882
njn1a2741a2007-11-26 21:59:04 +00001883 // XXX: I'm not confident that VG_(percentify) works as it should...
njn734b8052007-11-01 04:40:37 +00001884 VG_(percentify)(x, y, 2, 6, mbuf);
1885 // XXX: this is bogus if the denominator was zero -- resulting string is
1886 // something like "0 --%")
1887 if (' ' == mbuf[0]) mbuf[0] = '0';
nethercotec9f36922004-02-14 16:40:02 +00001888 return mbuf;
1889}
1890
njn734b8052007-11-01 04:40:37 +00001891static void pp_snapshot_SXPt(Int fd, SXPt* sxpt, Int depth, Char* depth_str,
1892 Int depth_str_len,
1893 SizeT snapshot_heap_szB, SizeT snapshot_total_szB)
nethercotec9f36922004-02-14 16:40:02 +00001894{
njn734b8052007-11-01 04:40:37 +00001895 #define BUF_LEN 1024
1896 Int i, n_insig_children_sxpts;
1897 Char* perc;
1898 Char ip_desc_array[BUF_LEN];
1899 Char* ip_desc = ip_desc_array;
1900 SXPt* pred = NULL;
1901 SXPt* child = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001902
njn734b8052007-11-01 04:40:37 +00001903 switch (sxpt->tag) {
1904 case SigSXPt:
1905 // Print the SXPt itself.
1906 if (sxpt->Sig.ip == 0) {
1907 ip_desc =
1908 "(heap allocation functions) malloc/new/new[], --alloc-fns, etc.";
1909 } else {
1910 // If it's main-or-below-main, we (if appropriate) ignore everything
1911 // below it by pretending it has no children.
1912 // XXX: get this properly. Also, don't hard-code "(below main)"
1913 // here -- look at the "(below main)"/"__libc_start_main" mess
1914 // (m_stacktrace.c and m_demangle.c).
1915 // [Nb: Josef wants --show-below-main to work for his fn entry/exit
1916 // tracing]
1917 Bool should_hide_below_main = /*!VG_(clo_show_below_main)*/True;
1918 if (should_hide_below_main &&
1919 VG_(get_fnname)(sxpt->Sig.ip, ip_desc, BUF_LEN) &&
1920 (VG_STREQ(ip_desc, "main") || VG_STREQ(ip_desc, "(below main)")))
1921 {
1922 sxpt->Sig.n_children = 0;
1923 }
1924 // We need the -1 to get the line number right, But I'm not sure why.
1925 ip_desc = VG_(describe_IP)(sxpt->Sig.ip-1, ip_desc, BUF_LEN);
1926 }
1927 perc = make_perc(sxpt->szB, snapshot_total_szB);
1928 FP("%sn%d: %lu %s\n",
1929 depth_str, sxpt->Sig.n_children, sxpt->szB, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001930
njn734b8052007-11-01 04:40:37 +00001931 // Indent.
1932 tl_assert(depth+1 < depth_str_len-1); // -1 for end NUL char
1933 depth_str[depth+0] = ' ';
1934 depth_str[depth+1] = '\0';
1935
1936 // Sort SXPt's children by szB (reverse order: biggest to smallest).
1937 // Nb: we sort them here, rather than earlier (eg. in dup_XTree), for
1938 // two reasons. First, if we do it during dup_XTree, it can get
1939 // expensive (eg. 15% of execution time for konqueror
1940 // startup/shutdown). Second, this way we get the Insig SXPt (if one
1941 // is present) in its sorted position, not at the end.
1942 VG_(ssort)(sxpt->Sig.children, sxpt->Sig.n_children, sizeof(SXPt*),
1943 SXPt_revcmp_szB);
1944
1945 // Print the SXPt's children. They should already be in sorted order.
1946 n_insig_children_sxpts = 0;
1947 for (i = 0; i < sxpt->Sig.n_children; i++) {
1948 pred = child;
1949 child = sxpt->Sig.children[i];
1950
1951 if (InsigSXPt == child->tag)
1952 n_insig_children_sxpts++;
1953
1954 // Ok, print the child.
1955 pp_snapshot_SXPt(fd, child, depth+1, depth_str, depth_str_len,
1956 snapshot_heap_szB, snapshot_total_szB);
njn734b8052007-11-01 04:40:37 +00001957 }
njndbeb5352007-12-04 03:15:23 +00001958
1959 // Unindent.
1960 depth_str[depth+0] = '\0';
1961 depth_str[depth+1] = '\0';
1962
njn734b8052007-11-01 04:40:37 +00001963 // There should be 0 or 1 Insig children SXPts.
1964 tl_assert(n_insig_children_sxpts <= 1);
1965 break;
1966
1967 case InsigSXPt: {
1968 Char* s = ( sxpt->Insig.n_xpts == 1 ? "," : "s, all" );
1969 perc = make_perc(sxpt->szB, snapshot_total_szB);
1970 FP("%sn0: %lu in %d place%s below massif's threshold (%s)\n",
1971 depth_str, sxpt->szB, sxpt->Insig.n_xpts, s,
njn62721e92007-11-11 22:15:58 +00001972 make_perc((ULong)clo_threshold, 100));
njn734b8052007-11-01 04:40:37 +00001973 break;
1974 }
1975
1976 default:
1977 tl_assert2(0, "pp_snapshot_SXPt: unrecognised SXPt tag");
nethercotec9f36922004-02-14 16:40:02 +00001978 }
nethercotec9f36922004-02-14 16:40:02 +00001979}
1980
njn734b8052007-11-01 04:40:37 +00001981static void pp_snapshot(Int fd, Snapshot* snapshot, Int snapshot_n)
nethercotec9f36922004-02-14 16:40:02 +00001982{
njn734b8052007-11-01 04:40:37 +00001983 sanity_check_snapshot(snapshot);
nethercotec9f36922004-02-14 16:40:02 +00001984
njn734b8052007-11-01 04:40:37 +00001985 FP("#-----------\n");
1986 FP("snapshot=%d\n", snapshot_n);
1987 FP("#-----------\n");
1988 FP("time=%lld\n", snapshot->time);
1989 FP("mem_heap_B=%lu\n", snapshot->heap_szB);
njn32397c02007-11-10 04:08:08 +00001990 FP("mem_heap_extra_B=%lu\n", snapshot->heap_extra_szB);
njn734b8052007-11-01 04:40:37 +00001991 FP("mem_stacks_B=%lu\n", snapshot->stacks_szB);
1992
1993 if (is_detailed_snapshot(snapshot)) {
1994 // Detailed snapshot -- print heap tree.
1995 Int depth_str_len = clo_depth + 3;
1996 Char* depth_str = VG_(malloc)(sizeof(Char) * depth_str_len);
1997 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00001998 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00001999 depth_str[0] = '\0'; // Initialise depth_str to "".
2000
2001 FP("heap_tree=%s\n", ( Peak == snapshot->kind ? "peak" : "detailed" ));
2002 pp_snapshot_SXPt(fd, snapshot->alloc_sxpt, 0, depth_str,
2003 depth_str_len, snapshot->heap_szB,
2004 snapshot_total_szB);
2005
2006 VG_(free)(depth_str);
2007
2008 } else {
2009 FP("heap_tree=empty\n");
nethercote43a15ce2004-08-30 19:15:12 +00002010 }
nethercotec9f36922004-02-14 16:40:02 +00002011}
2012
njn734b8052007-11-01 04:40:37 +00002013static void write_snapshots_to_file(void)
nethercotec9f36922004-02-14 16:40:02 +00002014{
njn734b8052007-11-01 04:40:37 +00002015 Int i, fd;
sewardj92645592005-07-23 09:18:34 +00002016 SysRes sres;
nethercotec9f36922004-02-14 16:40:02 +00002017
njn734b8052007-11-01 04:40:37 +00002018 sres = VG_(open)(massif_out_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
2019 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00002020 if (sres.isError) {
njn734b8052007-11-01 04:40:37 +00002021 // If the file can't be opened for whatever reason (conflict
2022 // between multiple cachegrinded processes?), give up now.
2023 VG_(message)(Vg_UserMsg,
2024 "error: can't open output file '%s'", massif_out_file );
2025 VG_(message)(Vg_UserMsg,
2026 " ... so profiling results will be missing.");
nethercotec9f36922004-02-14 16:40:02 +00002027 return;
sewardj92645592005-07-23 09:18:34 +00002028 } else {
sewardje8089302006-10-17 02:15:17 +00002029 fd = sres.res;
nethercotec9f36922004-02-14 16:40:02 +00002030 }
2031
njn734b8052007-11-01 04:40:37 +00002032 // Print massif-specific options that were used.
2033 // XXX: is it worth having a "desc:" line? Could just call it "options:"
2034 // -- this file format isn't as generic as Cachegrind's, so the
2035 // implied genericity of "desc:" is bogus.
2036 FP("desc:");
2037 for (i = 0; i < VG_(sizeXA)(args_for_massif); i++) {
2038 Char* arg = *(Char**)VG_(indexXA)(args_for_massif, i);
2039 FP(" %s", arg);
nethercotec9f36922004-02-14 16:40:02 +00002040 }
njn734b8052007-11-01 04:40:37 +00002041 if (0 == i) FP(" (none)");
2042 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002043
njn734b8052007-11-01 04:40:37 +00002044 // Print "cmd:" line.
2045 FP("cmd: ");
sewardj45f4e7c2005-09-27 19:20:21 +00002046 if (VG_(args_the_exename)) {
njn734b8052007-11-01 04:40:37 +00002047 FP("%s", VG_(args_the_exename));
2048 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
2049 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
2050 if (arg)
2051 FP(" %s", arg);
2052 }
2053 } else {
2054 FP(" ???");
sewardj45f4e7c2005-09-27 19:20:21 +00002055 }
njn734b8052007-11-01 04:40:37 +00002056 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002057
njn734b8052007-11-01 04:40:37 +00002058 FP("time_unit: %s\n", TimeUnit_to_string(clo_time_unit));
nethercotec9f36922004-02-14 16:40:02 +00002059
njn734b8052007-11-01 04:40:37 +00002060 for (i = 0; i < next_snapshot_i; i++) {
2061 Snapshot* snapshot = & snapshots[i];
2062 pp_snapshot(fd, snapshot, i); // Detailed snapshot!
nethercotec9f36922004-02-14 16:40:02 +00002063 }
2064}
2065
njn734b8052007-11-01 04:40:37 +00002066
2067//------------------------------------------------------------//
2068//--- Finalisation ---//
2069//------------------------------------------------------------//
2070
njn51d827b2005-05-09 01:02:08 +00002071static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00002072{
njn734b8052007-11-01 04:40:37 +00002073 // Output.
2074 write_snapshots_to_file();
nethercotec9f36922004-02-14 16:40:02 +00002075
njn734b8052007-11-01 04:40:37 +00002076 // Stats
2077 tl_assert(n_xpts > 0); // always have alloc_xpt
2078 VERB(1, "heap allocs: %u", n_heap_allocs);
2079 VERB(1, "heap reallocs: %u", n_heap_reallocs);
2080 VERB(1, "heap frees: %u", n_heap_frees);
2081 VERB(1, "stack allocs: %u", n_stack_allocs);
2082 VERB(1, "stack frees: %u", n_stack_frees);
2083 VERB(1, "XPts: %u", n_xpts);
2084 VERB(1, "top-XPts: %u (%d%%)",
2085 alloc_xpt->n_children,
2086 ( n_xpts ? alloc_xpt->n_children * 100 / n_xpts : 0));
njn55a30042007-11-10 04:18:39 +00002087 VERB(1, "XPt init expansions: %u", n_xpt_init_expansions);
2088 VERB(1, "XPt later expansions: %u", n_xpt_later_expansions);
njn734b8052007-11-01 04:40:37 +00002089 VERB(1, "SXPt allocs: %u", n_sxpt_allocs);
2090 VERB(1, "SXPt frees: %u", n_sxpt_frees);
2091 VERB(1, "skipped snapshots: %u", n_skipped_snapshots);
2092 VERB(1, "real snapshots: %u", n_real_snapshots);
2093 VERB(1, "detailed snapshots: %u", n_detailed_snapshots);
2094 VERB(1, "peak snapshots: %u", n_peak_snapshots);
2095 VERB(1, "cullings: %u", n_cullings);
njn55a30042007-11-10 04:18:39 +00002096 VERB(1, "XCon redos: %u", n_XCon_redos);
nethercotec9f36922004-02-14 16:40:02 +00002097}
2098
njn734b8052007-11-01 04:40:37 +00002099
2100//------------------------------------------------------------//
2101//--- Initialisation ---//
2102//------------------------------------------------------------//
njn51d827b2005-05-09 01:02:08 +00002103
2104static void ms_post_clo_init(void)
2105{
njn734b8052007-11-01 04:40:37 +00002106 Int i;
njn51d827b2005-05-09 01:02:08 +00002107
njn734b8052007-11-01 04:40:37 +00002108 // Check options.
2109 if (clo_heap_admin < 0 || clo_heap_admin > 1024) {
2110 VG_(message)(Vg_UserMsg, "--heap-admin must be between 0 and 1024");
2111 VG_(err_bad_option)("--heap-admin");
2112 }
2113 if (clo_depth < 1 || clo_depth > MAX_DEPTH) {
2114 VG_(message)(Vg_UserMsg, "--depth must be between 1 and %d", MAX_DEPTH);
2115 VG_(err_bad_option)("--depth");
2116 }
njn62721e92007-11-11 22:15:58 +00002117 if (clo_threshold < 0 || clo_threshold > 100) {
2118 VG_(message)(Vg_UserMsg, "--threshold must be between 0.0 and 100.0");
njn734b8052007-11-01 04:40:37 +00002119 VG_(err_bad_option)("--threshold");
2120 }
2121 if (clo_detailed_freq < 1 || clo_detailed_freq > 10000) {
2122 VG_(message)(Vg_UserMsg, "--detailed-freq must be between 1 and 10000");
2123 VG_(err_bad_option)("--detailed-freq");
2124 }
2125 if (clo_max_snapshots < 10 || clo_max_snapshots > 1000) {
2126 VG_(message)(Vg_UserMsg, "--max-snapshots must be between 10 and 1000");
2127 VG_(err_bad_option)("--max-snapshots");
2128 }
2129
2130 // If we have --heap=no, set --heap-admin to zero, just to make sure we
2131 // don't accidentally use a non-zero heap-admin size somewhere.
2132 if (!clo_heap) {
2133 clo_heap_admin = 0;
2134 }
2135
2136 // Print alloc-fns, if necessary.
2137 if (VG_(clo_verbosity) > 1) {
2138 VERB(1, "alloc-fns:");
2139 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
2140 Char** alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
2141 VERB(1, " %d: %s", i, *alloc_fn_ptr);
2142 }
2143 }
2144
2145 // Events to track.
2146 if (clo_stacks) {
2147 VG_(track_new_mem_stack) ( new_mem_stack );
2148 VG_(track_die_mem_stack) ( die_mem_stack );
2149 VG_(track_new_mem_stack_signal) ( new_mem_stack_signal );
2150 VG_(track_die_mem_stack_signal) ( die_mem_stack_signal );
2151 }
2152
2153 // Initialise snapshot array, and sanity-check it.
2154 snapshots = VG_(malloc)(sizeof(Snapshot) * clo_max_snapshots);
2155 // We don't want to do snapshot sanity checks here, because they're
2156 // currently uninitialised.
2157 for (i = 0; i < clo_max_snapshots; i++) {
2158 clear_snapshot( & snapshots[i], /*do_sanity_check*/False );
2159 }
2160 sanity_check_snapshots_array();
njnf4c665f2007-11-20 07:55:40 +00002161
2162 // Setup output filename.
njn3ed19712007-11-22 23:01:59 +00002163 massif_out_file =
2164 VG_(expand_file_name)("--massif-out-file", clo_massif_out_file);
njn51d827b2005-05-09 01:02:08 +00002165}
2166
tom151a6392005-11-11 12:30:36 +00002167static void ms_pre_clo_init(void)
njn734b8052007-11-01 04:40:37 +00002168{
njn51d827b2005-05-09 01:02:08 +00002169 VG_(details_name) ("Massif");
2170 VG_(details_version) (NULL);
njn1a2741a2007-11-26 21:59:04 +00002171 VG_(details_description) ("a heap profiler");
njn9a0cba42007-04-15 22:15:57 +00002172 VG_(details_copyright_author)(
njn734b8052007-11-01 04:40:37 +00002173 "Copyright (C) 2003-2007, and GNU GPL'd, by Nicholas Nethercote");
njn51d827b2005-05-09 01:02:08 +00002174 VG_(details_bug_reports_to) (VG_BUGS_TO);
2175
2176 // Basic functions
2177 VG_(basic_tool_funcs) (ms_post_clo_init,
2178 ms_instrument,
2179 ms_fini);
2180
2181 // Needs
2182 VG_(needs_libc_freeres)();
2183 VG_(needs_command_line_options)(ms_process_cmd_line_option,
2184 ms_print_usage,
2185 ms_print_debug_usage);
2186 VG_(needs_client_requests) (ms_handle_client_request);
njn734b8052007-11-01 04:40:37 +00002187 VG_(needs_sanity_checks) (ms_cheap_sanity_check,
2188 ms_expensive_sanity_check);
njnfc51f8d2005-06-21 03:20:17 +00002189 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00002190 ms___builtin_new,
2191 ms___builtin_vec_new,
2192 ms_memalign,
2193 ms_calloc,
2194 ms_free,
2195 ms___builtin_delete,
2196 ms___builtin_vec_delete,
2197 ms_realloc,
2198 0 );
2199
njn51d827b2005-05-09 01:02:08 +00002200 // HP_Chunks
njn734b8052007-11-01 04:40:37 +00002201 malloc_list = VG_(HT_construct)( "Massif's malloc list" );
njn51d827b2005-05-09 01:02:08 +00002202
2203 // Dummy node at top of the context structure.
njn734b8052007-11-01 04:40:37 +00002204 alloc_xpt = new_XPt(/*ip*/0, /*parent*/NULL);
2205
2206 // Initialise alloc_fns.
2207 init_alloc_fns();
2208
2209 // Initialise args_for_massif.
2210 args_for_massif = VG_(newXA)(VG_(malloc), VG_(free), sizeof(HChar*));
njn51d827b2005-05-09 01:02:08 +00002211}
2212
sewardj45f4e7c2005-09-27 19:20:21 +00002213VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00002214
njn734b8052007-11-01 04:40:37 +00002215//--------------------------------------------------------------------//
2216//--- end ---//
2217//--------------------------------------------------------------------//