blob: 2d8c26a054b94c5e4ef8766a4a78814e1ab673e4 [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
sewardj4d474d02008-02-11 11:34:59 +00009 Copyright (C) 2003-2008 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
njn734b8052007-11-01 04:40:37 +0000223//------------------------------------------------------------//
224//--- Statistics ---//
225//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000226
227// Konqueror startup, to give an idea of the numbers involved with a biggish
228// program, with default depth:
229//
230// depth=3 depth=40
231// - 310,000 allocations
232// - 300,000 frees
233// - 15,000 XPts 800,000 XPts
234// - 1,800 top-XPts
235
njn734b8052007-11-01 04:40:37 +0000236static UInt n_heap_allocs = 0;
237static UInt n_heap_reallocs = 0;
238static UInt n_heap_frees = 0;
239static UInt n_stack_allocs = 0;
240static UInt n_stack_frees = 0;
241static UInt n_xpts = 0;
242static UInt n_xpt_init_expansions = 0;
243static UInt n_xpt_later_expansions = 0;
244static UInt n_sxpt_allocs = 0;
245static UInt n_sxpt_frees = 0;
246static UInt n_skipped_snapshots = 0;
247static UInt n_real_snapshots = 0;
248static UInt n_detailed_snapshots = 0;
249static UInt n_peak_snapshots = 0;
250static UInt n_cullings = 0;
251static UInt n_XCon_redos = 0;
nethercotec9f36922004-02-14 16:40:02 +0000252
njn734b8052007-11-01 04:40:37 +0000253//------------------------------------------------------------//
254//--- Globals ---//
255//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000256
njn1a2741a2007-11-26 21:59:04 +0000257// Number of guest instructions executed so far. Only used with
258// --time-unit=i.
259static Long guest_instrs_executed = 0;
260
njn32397c02007-11-10 04:08:08 +0000261static SizeT heap_szB = 0; // Live heap size
262static SizeT heap_extra_szB = 0; // Live heap extra size -- slop + admin bytes
263static SizeT stacks_szB = 0; // Live stacks size
nethercotec9f36922004-02-14 16:40:02 +0000264
njn734b8052007-11-01 04:40:37 +0000265// This is the total size from the current peak snapshot, or 0 if no peak
266// snapshot has been taken yet.
267static SizeT peak_snapshot_total_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000268
njn734b8052007-11-01 04:40:37 +0000269// Incremented every time memory is allocated/deallocated, by the
270// allocated/deallocated amount; includes heap, heap-admin and stack
271// memory. An alternative to milliseconds as a unit of program "time".
272static ULong total_allocs_deallocs_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000273
njn734b8052007-11-01 04:40:37 +0000274// We don't start taking snapshots until the first basic block is executed,
275// rather than doing it in ms_post_clo_init (which is the obvious spot), for
276// two reasons.
277// - It lets us ignore stack events prior to that, because they're not
278// really proper ones and just would screw things up.
279// - Because there's still some core initialisation to do, and so there
280// would be an artificial time gap between the first and second snapshots.
281//
282static Bool have_started_executing_code = False;
nethercotec9f36922004-02-14 16:40:02 +0000283
njn734b8052007-11-01 04:40:37 +0000284//------------------------------------------------------------//
285//--- Alloc fns ---//
286//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000287
njn734b8052007-11-01 04:40:37 +0000288static XArray* alloc_fns;
nethercotec9f36922004-02-14 16:40:02 +0000289
njn734b8052007-11-01 04:40:37 +0000290static void init_alloc_fns(void)
291{
292 // Create the list, and add the default elements.
sewardj9c606bd2008-09-18 18:12:50 +0000293 alloc_fns = VG_(newXA)(VG_(malloc), "ms.main.iaf.1",
294 VG_(free), sizeof(Char*));
njn734b8052007-11-01 04:40:37 +0000295 #define DO(x) { Char* s = x; VG_(addToXA)(alloc_fns, &s); }
nethercotec9f36922004-02-14 16:40:02 +0000296
njn734b8052007-11-01 04:40:37 +0000297 // Ordered according to (presumed) frequency.
298 // Nb: The C++ "operator new*" ones are overloadable. We include them
299 // always anyway, because even if they're overloaded, it would be a
300 // prodigiously stupid overloading that caused them to not allocate
301 // memory.
302 DO("malloc" );
303 DO("__builtin_new" );
304 DO("operator new(unsigned)" );
305 DO("operator new(unsigned long)" );
306 DO("__builtin_vec_new" );
307 DO("operator new[](unsigned)" );
308 DO("operator new[](unsigned long)" );
309 DO("calloc" );
310 DO("realloc" );
311 DO("memalign" );
312 DO("operator new(unsigned, std::nothrow_t const&)" );
313 DO("operator new[](unsigned, std::nothrow_t const&)" );
314 DO("operator new(unsigned long, std::nothrow_t const&)" );
315 DO("operator new[](unsigned long, std::nothrow_t const&)");
316}
nethercotec9f36922004-02-14 16:40:02 +0000317
njn734b8052007-11-01 04:40:37 +0000318static Bool is_alloc_fn(Char* fnname)
319{
320 Char** alloc_fn_ptr;
321 Int i;
322
323 // Nb: It's a linear search through the list, because we're comparing
324 // strings rather than pointers to strings.
325 // Nb: This gets called a lot. It was an OSet, but they're quite slow to
326 // iterate through so it wasn't a good choice.
327 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
328 alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
329 if (VG_STREQ(fnname, *alloc_fn_ptr))
330 return True;
nethercotec9f36922004-02-14 16:40:02 +0000331 }
njn734b8052007-11-01 04:40:37 +0000332 return False;
333}
nethercotec9f36922004-02-14 16:40:02 +0000334
njn734b8052007-11-01 04:40:37 +0000335
336//------------------------------------------------------------//
337//--- Command line args ---//
338//------------------------------------------------------------//
339
340#define MAX_DEPTH 200
341
njn1a2741a2007-11-26 21:59:04 +0000342typedef enum { TimeI, TimeMS, TimeB } TimeUnit;
njn734b8052007-11-01 04:40:37 +0000343
344static Char* TimeUnit_to_string(TimeUnit time_unit)
345{
346 switch (time_unit) {
njn1a2741a2007-11-26 21:59:04 +0000347 case TimeI: return "i";
njn734b8052007-11-01 04:40:37 +0000348 case TimeMS: return "ms";
349 case TimeB: return "B";
350 default: tl_assert2(0, "TimeUnit_to_string: unrecognised TimeUnit");
351 }
352}
353
354static Bool clo_heap = True;
njn429afb42007-11-02 04:12:48 +0000355 // clo_heap_admin is deliberately a word-sized type. At one point it was
356 // a UInt, but this caused problems on 64-bit machines when it was
357 // multiplied by a small negative number and then promoted to a
358 // word-sized type -- it ended up with a value of 4.2 billion. Sigh.
njnefc13c22009-02-23 06:44:51 +0000359static SSizeT clo_heap_admin = 8;
njn62721e92007-11-11 22:15:58 +0000360static Bool clo_stacks = False;
njn83df0b62009-02-25 01:01:05 +0000361static Int clo_depth = 30;
njn62721e92007-11-11 22:15:58 +0000362static double clo_threshold = 1.0; // percentage
363static double clo_peak_inaccuracy = 1.0; // percentage
njn83df0b62009-02-25 01:01:05 +0000364static Int clo_time_unit = TimeI;
365static Int clo_detailed_freq = 10;
366static Int clo_max_snapshots = 100;
njnf4c665f2007-11-20 07:55:40 +0000367static Char* clo_massif_out_file = "massif.out.%p";
njn734b8052007-11-01 04:40:37 +0000368
369static XArray* args_for_massif;
nethercotec9f36922004-02-14 16:40:02 +0000370
njn51d827b2005-05-09 01:02:08 +0000371static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000372{
njn83df0b62009-02-25 01:01:05 +0000373 Char* tmp_str;
374
njn734b8052007-11-01 04:40:37 +0000375 // Remember the arg for later use.
376 VG_(addToXA)(args_for_massif, &arg);
nethercotec9f36922004-02-14 16:40:02 +0000377
njn83df0b62009-02-25 01:01:05 +0000378 if VG_BOOL_CLO(arg, "--heap", clo_heap) {}
379 else if VG_BOOL_CLO(arg, "--stacks", clo_stacks) {}
njn734b8052007-11-01 04:40:37 +0000380
njn83df0b62009-02-25 01:01:05 +0000381 else if VG_BINT_CLO(arg, "--heap-admin", clo_heap_admin, 0, 1024) {}
382 else if VG_BINT_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH) {}
njn734b8052007-11-01 04:40:37 +0000383
njn83df0b62009-02-25 01:01:05 +0000384 else if VG_DBL_CLO(arg, "--threshold", clo_threshold) {}
njn734b8052007-11-01 04:40:37 +0000385
njn83df0b62009-02-25 01:01:05 +0000386 else if VG_DBL_CLO(arg, "--peak-inaccuracy", clo_peak_inaccuracy) {}
njn734b8052007-11-01 04:40:37 +0000387
njn83df0b62009-02-25 01:01:05 +0000388 else if VG_BINT_CLO(arg, "--detailed-freq", clo_detailed_freq, 1, 10000) {}
389 else if VG_BINT_CLO(arg, "--max-snapshots", clo_max_snapshots, 10, 1000) {}
njn734b8052007-11-01 04:40:37 +0000390
njn83df0b62009-02-25 01:01:05 +0000391 else if VG_XACT_CLO(arg, "--time-unit=i", clo_time_unit, TimeI) {}
392 else if VG_XACT_CLO(arg, "--time-unit=ms", clo_time_unit, TimeMS) {}
393 else if VG_XACT_CLO(arg, "--time-unit=B", clo_time_unit, TimeB) {}
nethercotec9f36922004-02-14 16:40:02 +0000394
njn83df0b62009-02-25 01:01:05 +0000395 else if VG_STR_CLO(arg, "--alloc-fn", tmp_str) {
396 VG_(addToXA)(alloc_fns, &tmp_str);
nethercotec9f36922004-02-14 16:40:02 +0000397 }
398
njn83df0b62009-02-25 01:01:05 +0000399 else if VG_STR_CLO(arg, "--massif-out-file", clo_massif_out_file) {}
njnf4c665f2007-11-20 07:55:40 +0000400
nethercotec9f36922004-02-14 16:40:02 +0000401 else
402 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000403
nethercotec9f36922004-02-14 16:40:02 +0000404 return True;
405}
406
njn51d827b2005-05-09 01:02:08 +0000407static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000408{
njn734b8052007-11-01 04:40:37 +0000409 VG_(printf)(
nethercotec9f36922004-02-14 16:40:02 +0000410" --heap=no|yes profile heap blocks [yes]\n"
njn1a2741a2007-11-26 21:59:04 +0000411" --heap-admin=<number> average admin bytes per heap block;\n"
njn734b8052007-11-01 04:40:37 +0000412" ignored if --heap=no [8]\n"
413" --stacks=no|yes profile stack(s) [no]\n"
414" --depth=<number> depth of contexts [30]\n"
nethercotec9f36922004-02-14 16:40:02 +0000415" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
njn62721e92007-11-11 22:15:58 +0000416" --threshold=<m.n> significance threshold, as a percentage [1.0]\n"
417" --peak-inaccuracy=<m.n> maximum peak inaccuracy, as a percentage [1.0]\n"
njn1a2741a2007-11-26 21:59:04 +0000418" --time-unit=i|ms|B time unit: instructions executed, milliseconds\n"
419" or heap bytes alloc'd/dealloc'd [i]\n"
njn734b8052007-11-01 04:40:37 +0000420" --detailed-freq=<N> every Nth snapshot should be detailed [10]\n"
421" --max-snapshots=<N> maximum number of snapshots recorded [100]\n"
njn374a36d2007-11-23 01:41:32 +0000422" --massif-out-file=<file> output file name [massif.out.%%p]\n"
nethercotec9f36922004-02-14 16:40:02 +0000423 );
424 VG_(replacement_malloc_print_usage)();
425}
426
njn51d827b2005-05-09 01:02:08 +0000427static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000428{
429 VG_(replacement_malloc_print_debug_usage)();
430}
431
njn734b8052007-11-01 04:40:37 +0000432
433//------------------------------------------------------------//
434//--- XPts, XTrees and XCons ---//
435//------------------------------------------------------------//
436
437// An XPt represents an "execution point", ie. a code address. Each XPt is
438// part of a tree of XPts (an "execution tree", or "XTree"). The details of
439// the heap are represented by a single XTree.
440//
441// The root of the tree is 'alloc_xpt', which represents all allocation
442// functions, eg:
443// - malloc/calloc/realloc/memalign/new/new[];
444// - user-specified allocation functions (using --alloc-fn);
445// - custom allocation (MALLOCLIKE) points
446// It's a bit of a fake XPt (ie. its 'ip' is zero), and is only used because
447// it makes the code simpler.
448//
449// Any child of 'alloc_xpt' is called a "top-XPt". The XPts at the bottom
450// of an XTree (leaf nodes) are "bottom-XPTs".
451//
452// Each path from a top-XPt to a bottom-XPt through an XTree gives an
453// execution context ("XCon"), ie. a stack trace. (And sub-paths represent
454// stack sub-traces.) The number of XCons in an XTree is equal to the
455// number of bottom-XPTs in that XTree.
456//
457// alloc_xpt XTrees are bi-directional.
458// | ^
459// v |
460// > parent < Example: if child1() calls parent() and child2()
461// / | \ also calls parent(), and parent() calls malloc(),
462// | / \ | the XTree will look like this.
463// | v v |
464// child1 child2
465//
njndbeb5352007-12-04 03:15:23 +0000466// (Note that malformed stack traces can lead to difficulties. See the
467// comment at the bottom of get_XCon.)
468//
njn734b8052007-11-01 04:40:37 +0000469// XTrees and XPts are mirrored by SXTrees and SXPts, where the 'S' is short
470// for "saved". When the XTree is duplicated for a snapshot, we duplicate
471// it as an SXTree, which is similar but omits some things it does not need,
472// and aggregates up insignificant nodes. This is important as an SXTree is
473// typically much smaller than an XTree.
474
475// XXX: make XPt and SXPt extensible arrays, to avoid having to do two
476// allocations per Pt.
477
478typedef struct _XPt XPt;
479struct _XPt {
480 Addr ip; // code address
481
482 // Bottom-XPts: space for the precise context.
483 // Other XPts: space of all the descendent bottom-XPts.
484 // Nb: this value goes up and down as the program executes.
485 SizeT szB;
486
487 XPt* parent; // pointer to parent XPt
488
489 // Children.
490 // n_children and max_children are 32-bit integers. 16-bit integers
491 // are too small -- a very big program might have more than 65536
492 // allocation points (ie. top-XPts) -- Konqueror starting up has 1800.
493 UInt n_children; // number of children
494 UInt max_children; // capacity of children array
495 XPt** children; // pointers to children XPts
496};
497
498typedef
499 enum {
500 SigSXPt,
501 InsigSXPt
502 }
503 SXPtTag;
504
505typedef struct _SXPt SXPt;
506struct _SXPt {
507 SXPtTag tag;
508 SizeT szB; // memory size for the node, be it Sig or Insig
509 union {
510 // An SXPt representing a single significant code location. Much like
511 // an XPt, minus the fields that aren't necessary.
512 struct {
513 Addr ip;
514 UInt n_children;
515 SXPt** children;
516 }
517 Sig;
518
519 // An SXPt representing one or more code locations, all below the
520 // significance threshold.
521 struct {
522 Int n_xpts; // number of aggregated XPts
523 }
524 Insig;
525 };
526};
nethercotec9f36922004-02-14 16:40:02 +0000527
528// Fake XPt representing all allocation functions like malloc(). Acts as
529// parent node to all top-XPts.
530static XPt* alloc_xpt;
531
532// Cheap allocation for blocks that never need to be freed. Saves about 10%
533// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000534static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000535{
536 static Addr hp = 0; // current heap pointer
537 static Addr hp_lim = 0; // maximum usable byte in current block
538
539 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
540
541 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000542 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
njn84f32b22009-02-10 07:14:37 +0000543 if (0 == hp)
njn734b8052007-11-01 04:40:37 +0000544 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
sewardj45f4e7c2005-09-27 19:20:21 +0000545 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000546 hp_lim = hp + SUPERBLOCK_SIZE - 1;
547 }
548
549 hp += n_bytes;
550
551 return (void*)(hp - n_bytes);
552}
553
njn734b8052007-11-01 04:40:37 +0000554static XPt* new_XPt(Addr ip, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000555{
njn734b8052007-11-01 04:40:37 +0000556 // XPts are never freed, so we can use perm_malloc to allocate them.
557 // Note that we cannot use perm_malloc for the 'children' array, because
558 // that needs to be resizable.
559 XPt* xpt = perm_malloc(sizeof(XPt));
560 xpt->ip = ip;
561 xpt->szB = 0;
562 xpt->parent = parent;
nethercotec9f36922004-02-14 16:40:02 +0000563
njn734b8052007-11-01 04:40:37 +0000564 // We don't initially allocate any space for children. We let that
565 // happen on demand. Many XPts (ie. all the bottom-XPts) don't have any
566 // children anyway.
nethercotec9f36922004-02-14 16:40:02 +0000567 xpt->n_children = 0;
njn734b8052007-11-01 04:40:37 +0000568 xpt->max_children = 0;
569 xpt->children = NULL;
nethercotec9f36922004-02-14 16:40:02 +0000570
571 // Update statistics
572 n_xpts++;
573
574 return xpt;
575}
576
njn734b8052007-11-01 04:40:37 +0000577static void add_child_xpt(XPt* parent, XPt* child)
578{
579 // Expand 'children' if necessary.
580 tl_assert(parent->n_children <= parent->max_children);
581 if (parent->n_children == parent->max_children) {
njn84f32b22009-02-10 07:14:37 +0000582 if (0 == parent->max_children) {
njn734b8052007-11-01 04:40:37 +0000583 parent->max_children = 4;
sewardj9c606bd2008-09-18 18:12:50 +0000584 parent->children = VG_(malloc)( "ms.main.acx.1",
585 parent->max_children * sizeof(XPt*) );
njn734b8052007-11-01 04:40:37 +0000586 n_xpt_init_expansions++;
587 } else {
588 parent->max_children *= 2; // Double size
sewardj9c606bd2008-09-18 18:12:50 +0000589 parent->children = VG_(realloc)( "ms.main.acx.2",
590 parent->children,
njn734b8052007-11-01 04:40:37 +0000591 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.
njn84f32b22009-02-10 07:14:37 +0000636 if (0 == total_szB && 0 != clo_threshold) {
njn734b8052007-11-01 04:40:37 +0000637 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.
sewardj9c606bd2008-09-18 18:12:50 +0000653 sxpt = VG_(malloc)("ms.main.dX.1", sizeof(SXPt));
njn734b8052007-11-01 04:40:37 +0000654 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;
sewardj9c606bd2008-09-18 18:12:50 +0000664 sxpt->Sig.children = VG_(malloc)("ms.main.dX.2",
665 n_child_sxpts * sizeof(SXPt*));
njn734b8052007-11-01 04:40:37 +0000666
njndbeb5352007-12-04 03:15:23 +0000667 // Duplicate the significant children. (Nb: sig_children_szB +
668 // insig_children_szB doesn't necessarily equal xpt->szB.)
njn734b8052007-11-01 04:40:37 +0000669 j = 0;
670 for (i = 0; i < xpt->n_children; i++) {
671 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
672 sxpt->Sig.children[j++] = dup_XTree(xpt->children[i], total_szB);
njndbeb5352007-12-04 03:15:23 +0000673 sig_children_szB += xpt->children[i]->szB;
674 } else {
675 insig_children_szB += xpt->children[i]->szB;
njn734b8052007-11-01 04:40:37 +0000676 }
677 }
678
679 // Create the SXPt for the insignificant children, if any, and put it
680 // in the last child entry.
njn734b8052007-11-01 04:40:37 +0000681 if (n_insig_children > 0) {
682 // Nb: We 'n_sxpt_allocs' here because creating an Insig SXPt
683 // doesn't involve a call to dup_XTree().
sewardj9c606bd2008-09-18 18:12:50 +0000684 SXPt* insig_sxpt = VG_(malloc)("ms.main.dX.3", sizeof(SXPt));
njn734b8052007-11-01 04:40:37 +0000685 n_sxpt_allocs++;
686 insig_sxpt->tag = InsigSXPt;
687 insig_sxpt->szB = insig_children_szB;
688 insig_sxpt->Insig.n_xpts = n_insig_children;
689 sxpt->Sig.children[n_sig_children] = insig_sxpt;
690 }
691 } else {
692 sxpt->Sig.children = NULL;
693 }
694
695 return sxpt;
696}
697
698static void free_SXTree(SXPt* sxpt)
699{
700 Int i;
701 tl_assert(sxpt != NULL);
702
703 switch (sxpt->tag) {
704 case SigSXPt:
705 // Free all children SXPts, then the children array.
706 for (i = 0; i < sxpt->Sig.n_children; i++) {
707 free_SXTree(sxpt->Sig.children[i]);
708 sxpt->Sig.children[i] = NULL;
709 }
710 VG_(free)(sxpt->Sig.children); sxpt->Sig.children = NULL;
711 break;
712
713 case InsigSXPt:
714 break;
715
716 default: tl_assert2(0, "free_SXTree: unknown SXPt tag");
717 }
718
719 // Free the SXPt itself.
720 VG_(free)(sxpt); sxpt = NULL;
721 n_sxpt_frees++;
722}
723
724// Sanity checking: we periodically check the heap XTree with
725// ms_expensive_sanity_check.
726static void sanity_check_XTree(XPt* xpt, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000727{
njn734b8052007-11-01 04:40:37 +0000728 tl_assert(xpt != NULL);
729
730 // Check back-pointer.
731 tl_assert2(xpt->parent == parent,
732 "xpt->parent = %p, parent = %p\n", xpt->parent, parent);
733
734 // Check children counts look sane.
735 tl_assert(xpt->n_children <= xpt->max_children);
736
njndbeb5352007-12-04 03:15:23 +0000737 // Unfortunately, xpt's size is not necessarily equal to the sum of xpt's
738 // children's sizes. See comment at the bottom of get_XCon.
nethercotec9f36922004-02-14 16:40:02 +0000739}
740
njn734b8052007-11-01 04:40:37 +0000741// Sanity checking: we check SXTrees (which are in snapshots) after
742// snapshots are created, before they are deleted, and before they are
743// printed.
744static void sanity_check_SXTree(SXPt* sxpt)
nethercotec9f36922004-02-14 16:40:02 +0000745{
njn734b8052007-11-01 04:40:37 +0000746 Int i;
nethercotec9f36922004-02-14 16:40:02 +0000747
njn734b8052007-11-01 04:40:37 +0000748 tl_assert(sxpt != NULL);
nethercotec9f36922004-02-14 16:40:02 +0000749
njn734b8052007-11-01 04:40:37 +0000750 // Check the sum of any children szBs equals the SXPt's szB. Check the
751 // children at the same time.
752 switch (sxpt->tag) {
753 case SigSXPt: {
754 if (sxpt->Sig.n_children > 0) {
njn734b8052007-11-01 04:40:37 +0000755 for (i = 0; i < sxpt->Sig.n_children; i++) {
756 sanity_check_SXTree(sxpt->Sig.children[i]);
njn734b8052007-11-01 04:40:37 +0000757 }
njn734b8052007-11-01 04:40:37 +0000758 }
759 break;
760 }
761 case InsigSXPt:
762 break; // do nothing
763
764 default: tl_assert2(0, "sanity_check_SXTree: unknown SXPt tag");
765 }
766}
767
768
769//------------------------------------------------------------//
770//--- XCon Operations ---//
771//------------------------------------------------------------//
772
773// This is the limit on the number of removed alloc-fns that can be in a
774// single XCon.
775#define MAX_OVERESTIMATE 50
776#define MAX_IPS (MAX_DEPTH + MAX_OVERESTIMATE)
777
njnb11e5aa2008-01-20 22:30:52 +0000778// This is used for various buffers which can hold function names/IP
779// description. Some C++ names can get really long so 1024 isn't big
780// enough.
781#define BUF_LEN 2048
782
njn734b8052007-11-01 04:40:37 +0000783// Get the stack trace for an XCon, filtering out uninteresting entries:
784// alloc-fns and entries above alloc-fns, and entries below main-or-below-main.
785// Eg: alloc-fn1 / alloc-fn2 / a / b / main / (below main) / c
786// becomes: a / b / main
787// Nb: it's possible to end up with an empty trace, eg. if 'main' is marked
788// as an alloc-fn. This is ok.
789static
790Int get_IPs( ThreadId tid, Bool is_custom_alloc, Addr ips[])
791{
njn734b8052007-11-01 04:40:37 +0000792 Char buf[BUF_LEN];
793 Int n_ips, i, n_alloc_fns_removed;
794 Int overestimate;
795 Bool redo;
796
797 // We ask for a few more IPs than clo_depth suggests we need. Then we
798 // remove every entry that is an alloc-fn. Depending on the
799 // circumstances, we may need to redo it all, asking for more IPs.
800 // Details:
801 // - If the original stack trace is smaller than asked-for, redo=False
802 // - Else if after filtering we have >= clo_depth IPs, redo=False
803 // - Else redo=True
804 // In other words, to redo, we'd have to get a stack trace as big as we
805 // asked for and remove more than 'overestimate' alloc-fns.
806
807 // Main loop.
808 redo = True; // Assume this to begin with.
809 for (overestimate = 3; redo; overestimate += 6) {
810 // This should never happen -- would require MAX_OVERESTIMATE
811 // alloc-fns to be removed from the stack trace.
812 if (overestimate > MAX_OVERESTIMATE)
813 VG_(tool_panic)("get_IPs: ips[] too small, inc. MAX_OVERESTIMATE?");
814
815 // Ask for more IPs than clo_depth suggests we need.
sewardj39f34232007-11-09 23:02:28 +0000816 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate,
sewardjb8b79ad2008-03-03 01:35:41 +0000817 NULL/*array to dump SP values in*/,
818 NULL/*array to dump FP values in*/,
819 0/*first_ip_delta*/ );
njn734b8052007-11-01 04:40:37 +0000820 tl_assert(n_ips > 0);
nethercotec9f36922004-02-14 16:40:02 +0000821
njn734b8052007-11-01 04:40:37 +0000822 // If the original stack trace is smaller than asked-for, redo=False.
823 if (n_ips < clo_depth + overestimate) { redo = False; }
nethercotec9f36922004-02-14 16:40:02 +0000824
njn734b8052007-11-01 04:40:37 +0000825 // If it's a non-custom block, we will always remove the first stack
826 // trace entry (which will be one of malloc, __builtin_new, etc).
827 n_alloc_fns_removed = ( is_custom_alloc ? 0 : 1 );
nethercotec9f36922004-02-14 16:40:02 +0000828
njn734b8052007-11-01 04:40:37 +0000829 // Filter out alloc fns. If it's a non-custom block, we remove the
830 // first entry (which will be one of malloc, __builtin_new, etc)
831 // without looking at it, because VG_(get_fnname) is expensive (it
832 // involves calls to VG_(malloc)/VG_(free)).
833 for (i = n_alloc_fns_removed; i < n_ips; i++) {
834 if (VG_(get_fnname)(ips[i], buf, BUF_LEN)) {
835 if (is_alloc_fn(buf)) {
836 n_alloc_fns_removed++;
837 } else {
838 break;
839 }
840 }
841 }
842 // Remove the alloc fns by shuffling the rest down over them.
843 n_ips -= n_alloc_fns_removed;
844 for (i = 0; i < n_ips; i++) {
845 ips[i] = ips[i + n_alloc_fns_removed];
846 }
nethercotec9f36922004-02-14 16:40:02 +0000847
njn734b8052007-11-01 04:40:37 +0000848 // If after filtering we have >= clo_depth IPs, redo=False
849 if (n_ips >= clo_depth) {
850 redo = False;
851 n_ips = clo_depth; // Ignore any IPs below --depth.
852 }
853
854 if (redo) {
855 n_XCon_redos++;
nethercotec9f36922004-02-14 16:40:02 +0000856 }
857 }
njn734b8052007-11-01 04:40:37 +0000858 return n_ips;
859}
nethercotec9f36922004-02-14 16:40:02 +0000860
njn734b8052007-11-01 04:40:37 +0000861// Gets an XCon and puts it in the tree. Returns the XCon's bottom-XPt.
862static XPt* get_XCon( ThreadId tid, Bool is_custom_alloc )
863{
864 Addr ips[MAX_IPS];
865 Int i;
866 XPt* xpt = alloc_xpt;
nethercotec9f36922004-02-14 16:40:02 +0000867
njn734b8052007-11-01 04:40:37 +0000868 // After this call, the IPs we want are in ips[0]..ips[n_ips-1].
869 Int n_ips = get_IPs(tid, is_custom_alloc, ips);
870
871 // Now do the search/insertion of the XCon.
872 for (i = 0; i < n_ips; i++) {
873 Addr ip = ips[i];
874 Int ch;
njnd01fef72005-03-25 23:35:48 +0000875 // Look for IP in xpt's children.
njn734b8052007-11-01 04:40:37 +0000876 // Linear search, ugh -- about 10% of time for konqueror startup tried
877 // caching last result, only hit about 4% for konqueror.
nethercotec9f36922004-02-14 16:40:02 +0000878 // Nb: this search hits about 98% of the time for konqueror
njn734b8052007-11-01 04:40:37 +0000879 for (ch = 0; True; ch++) {
880 if (ch == xpt->n_children) {
881 // IP not found in the children.
882 // Create and add new child XPt, then stop.
883 XPt* new_child_xpt = new_XPt(ip, xpt);
884 add_child_xpt(xpt, new_child_xpt);
885 xpt = new_child_xpt;
886 break;
nethercotec9f36922004-02-14 16:40:02 +0000887
njn734b8052007-11-01 04:40:37 +0000888 } else if (ip == xpt->children[ch]->ip) {
889 // Found the IP in the children, stop.
890 xpt = xpt->children[ch];
nethercotec9f36922004-02-14 16:40:02 +0000891 break;
892 }
nethercotec9f36922004-02-14 16:40:02 +0000893 }
nethercotec9f36922004-02-14 16:40:02 +0000894 }
njndbeb5352007-12-04 03:15:23 +0000895
896 // [Note: several comments refer to this comment. Do not delete it
897 // without updating them.]
898 //
899 // A complication... If all stack traces were well-formed, then the
900 // returned xpt would always be a bottom-XPt. As a consequence, an XPt's
901 // size would always be equal to the sum of its children's sizes, which
902 // is an excellent sanity check.
903 //
904 // Unfortunately, stack traces occasionally are malformed, ie. truncated.
905 // This allows a stack trace to be a sub-trace of another, eg. a/b/c is a
906 // sub-trace of a/b/c/d. So we can't assume this xpt is a bottom-XPt;
907 // nor can we do sanity check an XPt's size against its children's sizes.
908 // This is annoying, but must be dealt with. (Older versions of Massif
909 // had this assertion in, and it was reported to fail by real users a
910 // couple of times.) Even more annoyingly, I can't come up with a simple
911 // test case that exhibit such a malformed stack trace, so I can't
912 // regression test it. Sigh.
913 //
914 // However, we can print a warning, so that if it happens (unexpectedly)
915 // in existing regression tests we'll know. Also, it warns users that
916 // the output snapshots may not add up the way they might expect.
917 //
918 //tl_assert(0 == xpt->n_children); // Must be bottom-XPt
919 if (0 != xpt->n_children) {
920 static Int n_moans = 0;
921 if (n_moans < 3) {
922 VG_(message)(Vg_UserMsg,
923 "Warning: Malformed stack trace detected. In Massif's output,");
924 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000925 " the size of an entry's child entries may not sum up");
njndbeb5352007-12-04 03:15:23 +0000926 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000927 " to the entry's size as they normally do.");
njndbeb5352007-12-04 03:15:23 +0000928 n_moans++;
929 if (3 == n_moans)
930 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000931 " (And Massif now won't warn about this again.)");
njndbeb5352007-12-04 03:15:23 +0000932 }
933 }
njn734b8052007-11-01 04:40:37 +0000934 return xpt;
nethercotec9f36922004-02-14 16:40:02 +0000935}
936
njn734b8052007-11-01 04:40:37 +0000937// Update 'szB' of every XPt in the XCon, by percolating upwards.
938static void update_XCon(XPt* xpt, SSizeT space_delta)
nethercotec9f36922004-02-14 16:40:02 +0000939{
njnca82cc02004-11-22 17:18:48 +0000940 tl_assert(True == clo_heap);
njnca82cc02004-11-22 17:18:48 +0000941 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +0000942
njn734b8052007-11-01 04:40:37 +0000943 if (0 == space_delta)
944 return;
945
nethercotec9f36922004-02-14 16:40:02 +0000946 while (xpt != alloc_xpt) {
njn734b8052007-11-01 04:40:37 +0000947 if (space_delta < 0) tl_assert(xpt->szB >= -space_delta);
948 xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000949 xpt = xpt->parent;
njn734b8052007-11-01 04:40:37 +0000950 }
951 if (space_delta < 0) tl_assert(alloc_xpt->szB >= -space_delta);
952 alloc_xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000953}
954
955
njn734b8052007-11-01 04:40:37 +0000956//------------------------------------------------------------//
957//--- Snapshots ---//
958//------------------------------------------------------------//
959
960// Snapshots are done in a way so that we always have a reasonable number of
961// them. We start by taking them quickly. Once we hit our limit, we cull
962// some (eg. half), and start taking them more slowly. Once we hit the
963// limit again, we again cull and then take them even more slowly, and so
964// on.
965
njn1a2741a2007-11-26 21:59:04 +0000966// Time is measured either in i or ms or bytes, depending on the --time-unit
njn734b8052007-11-01 04:40:37 +0000967// option. It's a Long because it can exceed 32-bits reasonably easily, and
968// because we need to allow negative values to represent unset times.
969typedef Long Time;
970
971#define UNUSED_SNAPSHOT_TIME -333 // A conspicuous negative number.
972
973typedef
974 enum {
975 Normal = 77,
976 Peak,
977 Unused
978 }
979 SnapshotKind;
nethercotec9f36922004-02-14 16:40:02 +0000980
981typedef
982 struct {
njn734b8052007-11-01 04:40:37 +0000983 SnapshotKind kind;
984 Time time;
985 SizeT heap_szB;
njn32397c02007-11-10 04:08:08 +0000986 SizeT heap_extra_szB;// Heap slop + admin bytes.
njn734b8052007-11-01 04:40:37 +0000987 SizeT stacks_szB;
988 SXPt* alloc_sxpt; // Heap XTree root, if a detailed snapshot,
njn32397c02007-11-10 04:08:08 +0000989 } // otherwise NULL.
njn734b8052007-11-01 04:40:37 +0000990 Snapshot;
nethercotec9f36922004-02-14 16:40:02 +0000991
njn734b8052007-11-01 04:40:37 +0000992static UInt next_snapshot_i = 0; // Index of where next snapshot will go.
993static Snapshot* snapshots; // Array of snapshots.
994
995static Bool is_snapshot_in_use(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +0000996{
njn734b8052007-11-01 04:40:37 +0000997 if (Unused == snapshot->kind) {
998 // If snapshot is unused, check all the fields are unset.
999 tl_assert(snapshot->time == UNUSED_SNAPSHOT_TIME);
njn32397c02007-11-10 04:08:08 +00001000 tl_assert(snapshot->heap_extra_szB == 0);
njn734b8052007-11-01 04:40:37 +00001001 tl_assert(snapshot->heap_szB == 0);
1002 tl_assert(snapshot->stacks_szB == 0);
1003 tl_assert(snapshot->alloc_sxpt == NULL);
1004 return False;
nethercotec9f36922004-02-14 16:40:02 +00001005 } else {
njn734b8052007-11-01 04:40:37 +00001006 tl_assert(snapshot->time != UNUSED_SNAPSHOT_TIME);
1007 return True;
nethercotec9f36922004-02-14 16:40:02 +00001008 }
1009}
1010
njn734b8052007-11-01 04:40:37 +00001011static Bool is_detailed_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001012{
njn734b8052007-11-01 04:40:37 +00001013 return (snapshot->alloc_sxpt ? True : False);
nethercotec9f36922004-02-14 16:40:02 +00001014}
1015
njn734b8052007-11-01 04:40:37 +00001016static Bool is_uncullable_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001017{
njn734b8052007-11-01 04:40:37 +00001018 return &snapshots[0] == snapshot // First snapshot
1019 || &snapshots[next_snapshot_i-1] == snapshot // Last snapshot
1020 || snapshot->kind == Peak; // Peak snapshot
nethercotec9f36922004-02-14 16:40:02 +00001021}
1022
njn734b8052007-11-01 04:40:37 +00001023static void sanity_check_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001024{
njn734b8052007-11-01 04:40:37 +00001025 if (snapshot->alloc_sxpt) {
1026 sanity_check_SXTree(snapshot->alloc_sxpt);
1027 }
nethercotec9f36922004-02-14 16:40:02 +00001028}
1029
njn734b8052007-11-01 04:40:37 +00001030// All the used entries should look used, all the unused ones should be clear.
1031static void sanity_check_snapshots_array(void)
1032{
1033 Int i;
1034 for (i = 0; i < next_snapshot_i; i++) {
1035 tl_assert( is_snapshot_in_use( & snapshots[i] ));
1036 }
1037 for ( ; i < clo_max_snapshots; i++) {
1038 tl_assert(!is_snapshot_in_use( & snapshots[i] ));
1039 }
1040}
nethercotec9f36922004-02-14 16:40:02 +00001041
njn734b8052007-11-01 04:40:37 +00001042// This zeroes all the fields in the snapshot, but does not free the heap
1043// XTree if present. It also does a sanity check unless asked not to; we
1044// can't sanity check at startup when clearing the initial snapshots because
1045// they're full of junk.
1046static void clear_snapshot(Snapshot* snapshot, Bool do_sanity_check)
1047{
1048 if (do_sanity_check) sanity_check_snapshot(snapshot);
1049 snapshot->kind = Unused;
1050 snapshot->time = UNUSED_SNAPSHOT_TIME;
njn32397c02007-11-10 04:08:08 +00001051 snapshot->heap_extra_szB = 0;
njn734b8052007-11-01 04:40:37 +00001052 snapshot->heap_szB = 0;
1053 snapshot->stacks_szB = 0;
1054 snapshot->alloc_sxpt = NULL;
1055}
1056
1057// This zeroes all the fields in the snapshot, and frees the heap XTree if
1058// present.
1059static void delete_snapshot(Snapshot* snapshot)
1060{
1061 // Nb: if there's an XTree, we free it after calling clear_snapshot,
1062 // because clear_snapshot does a sanity check which includes checking the
1063 // XTree.
1064 SXPt* tmp_sxpt = snapshot->alloc_sxpt;
1065 clear_snapshot(snapshot, /*do_sanity_check*/True);
1066 if (tmp_sxpt) {
1067 free_SXTree(tmp_sxpt);
1068 }
1069}
1070
1071static void VERB_snapshot(Int verbosity, Char* prefix, Int i)
1072{
1073 Snapshot* snapshot = &snapshots[i];
1074 Char* suffix;
1075 switch (snapshot->kind) {
1076 case Peak: suffix = "p"; break;
1077 case Normal: suffix = ( is_detailed_snapshot(snapshot) ? "d" : "." ); break;
1078 case Unused: suffix = "u"; break;
1079 default:
1080 tl_assert2(0, "VERB_snapshot: unknown snapshot kind: %d", snapshot->kind);
1081 }
njn32397c02007-11-10 04:08:08 +00001082 VERB(verbosity, "%s S%s%3d (t:%lld, hp:%ld, ex:%ld, st:%ld)",
njn734b8052007-11-01 04:40:37 +00001083 prefix, suffix, i,
1084 snapshot->time,
1085 snapshot->heap_szB,
njn32397c02007-11-10 04:08:08 +00001086 snapshot->heap_extra_szB,
njn734b8052007-11-01 04:40:37 +00001087 snapshot->stacks_szB
1088 );
1089}
1090
1091// Cull half the snapshots; we choose those that represent the smallest
1092// time-spans, because that gives us the most even distribution of snapshots
1093// over time. (It's possible to lose interesting spikes, however.)
1094//
1095// Algorithm for N snapshots: We find the snapshot representing the smallest
1096// timeframe, and remove it. We repeat this until (N/2) snapshots are gone.
1097// We have to do this one snapshot at a time, rather than finding the (N/2)
1098// smallest snapshots in one hit, because when a snapshot is removed, its
1099// neighbours immediately cover greater timespans. So it's O(N^2), but N is
1100// small, and it's not done very often.
1101//
1102// Once we're done, we return the new smallest interval between snapshots.
1103// That becomes our minimum time interval.
1104static UInt cull_snapshots(void)
1105{
1106 Int i, jp, j, jn, min_timespan_i;
1107 Int n_deleted = 0;
1108 Time min_timespan;
1109
1110 n_cullings++;
1111
1112 // Sets j to the index of the first not-yet-removed snapshot at or after i
1113 #define FIND_SNAPSHOT(i, j) \
1114 for (j = i; \
1115 j < clo_max_snapshots && !is_snapshot_in_use(&snapshots[j]); \
1116 j++) { }
1117
1118 VERB(2, "Culling...");
1119
1120 // First we remove enough snapshots by clearing them in-place. Once
1121 // that's done, we can slide the remaining ones down.
1122 for (i = 0; i < clo_max_snapshots/2; i++) {
1123 // Find the snapshot representing the smallest timespan. The timespan
1124 // for snapshot n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
1125 // snapshot A and B. We don't consider the first and last snapshots for
1126 // removal.
1127 Snapshot* min_snapshot;
1128 Int min_j;
1129
1130 // Initial triple: (prev, curr, next) == (jp, j, jn)
1131 // Initial min_timespan is the first one.
1132 jp = 0;
1133 FIND_SNAPSHOT(1, j);
1134 FIND_SNAPSHOT(j+1, jn);
1135 min_timespan = 0x7fffffffffffffffLL;
1136 min_j = -1;
1137 while (jn < clo_max_snapshots) {
1138 Time timespan = snapshots[jn].time - snapshots[jp].time;
1139 tl_assert(timespan >= 0);
1140 // Nb: We never cull the peak snapshot.
1141 if (Peak != snapshots[j].kind && timespan < min_timespan) {
1142 min_timespan = timespan;
1143 min_j = j;
1144 }
1145 // Move on to next triple
1146 jp = j;
1147 j = jn;
1148 FIND_SNAPSHOT(jn+1, jn);
1149 }
1150 // We've found the least important snapshot, now delete it. First
1151 // print it if necessary.
1152 tl_assert(-1 != min_j); // Check we found a minimum.
1153 min_snapshot = & snapshots[ min_j ];
1154 if (VG_(clo_verbosity) > 1) {
1155 Char buf[64];
1156 VG_(snprintf)(buf, 64, " %3d (t-span = %lld)", i, min_timespan);
1157 VERB_snapshot(2, buf, min_j);
1158 }
1159 delete_snapshot(min_snapshot);
1160 n_deleted++;
1161 }
1162
1163 // Slide down the remaining snapshots over the removed ones. First set i
1164 // to point to the first empty slot, and j to the first full slot after
1165 // i. Then slide everything down.
1166 for (i = 0; is_snapshot_in_use( &snapshots[i] ); i++) { }
1167 for (j = i; !is_snapshot_in_use( &snapshots[j] ); j++) { }
1168 for ( ; j < clo_max_snapshots; j++) {
1169 if (is_snapshot_in_use( &snapshots[j] )) {
1170 snapshots[i++] = snapshots[j];
1171 clear_snapshot(&snapshots[j], /*do_sanity_check*/True);
1172 }
1173 }
1174 next_snapshot_i = i;
1175
1176 // Check snapshots array looks ok after changes.
1177 sanity_check_snapshots_array();
1178
1179 // Find the minimum timespan remaining; that will be our new minimum
1180 // time interval. Note that above we were finding timespans by measuring
1181 // two intervals around a snapshot that was under consideration for
1182 // deletion. Here we only measure single intervals because all the
1183 // deletions have occurred.
1184 //
1185 // But we have to be careful -- some snapshots (eg. snapshot 0, and the
1186 // peak snapshot) are uncullable. If two uncullable snapshots end up
1187 // next to each other, they'll never be culled (assuming the peak doesn't
1188 // change), and the time gap between them will not change. However, the
1189 // time between the remaining cullable snapshots will grow ever larger.
1190 // This means that the min_timespan found will always be that between the
1191 // two uncullable snapshots, and it will be much smaller than it should
1192 // be. To avoid this problem, when computing the minimum timespan, we
1193 // ignore any timespans between two uncullable snapshots.
1194 tl_assert(next_snapshot_i > 1);
1195 min_timespan = 0x7fffffffffffffffLL;
1196 min_timespan_i = -1;
1197 for (i = 1; i < next_snapshot_i; i++) {
1198 if (is_uncullable_snapshot(&snapshots[i]) &&
1199 is_uncullable_snapshot(&snapshots[i-1]))
1200 {
1201 VERB(2, "(Ignoring interval %d--%d when computing minimum)", i-1, i);
1202 } else {
1203 Time timespan = snapshots[i].time - snapshots[i-1].time;
1204 tl_assert(timespan >= 0);
1205 if (timespan < min_timespan) {
1206 min_timespan = timespan;
1207 min_timespan_i = i;
1208 }
1209 }
1210 }
1211 tl_assert(-1 != min_timespan_i); // Check we found a minimum.
1212
1213 // Print remaining snapshots, if necessary.
1214 if (VG_(clo_verbosity) > 1) {
1215 VERB(2, "Finished culling (%3d of %3d deleted)",
1216 n_deleted, clo_max_snapshots);
1217 for (i = 0; i < next_snapshot_i; i++) {
1218 VERB_snapshot(2, " post-cull", i);
1219 }
1220 VERB(2, "New time interval = %lld (between snapshots %d and %d)",
1221 min_timespan, min_timespan_i-1, min_timespan_i);
1222 }
1223
1224 return min_timespan;
1225}
1226
1227static Time get_time(void)
1228{
1229 // Get current time, in whatever time unit we're using.
njn1a2741a2007-11-26 21:59:04 +00001230 if (clo_time_unit == TimeI) {
1231 return guest_instrs_executed;
1232 } else if (clo_time_unit == TimeMS) {
njn734b8052007-11-01 04:40:37 +00001233 // Some stuff happens between the millisecond timer being initialised
1234 // to zero and us taking our first snapshot. We determine that time
1235 // gap so we can subtract it from all subsequent times so that our
1236 // first snapshot is considered to be at t = 0ms. Unfortunately, a
1237 // bunch of symbols get read after the first snapshot is taken but
1238 // before the second one (which is triggered by the first allocation),
1239 // so when the time-unit is 'ms' we always have a big gap between the
1240 // first two snapshots. But at least users won't have to wonder why
1241 // the first snapshot isn't at t=0.
1242 static Bool is_first_get_time = True;
1243 static Time start_time_ms;
1244 if (is_first_get_time) {
1245 start_time_ms = VG_(read_millisecond_timer)();
1246 is_first_get_time = False;
1247 return 0;
1248 } else {
1249 return VG_(read_millisecond_timer)() - start_time_ms;
1250 }
1251 } else if (clo_time_unit == TimeB) {
1252 return total_allocs_deallocs_szB;
1253 } else {
1254 tl_assert2(0, "bad --time-unit value");
1255 }
1256}
1257
1258// Take a snapshot, and only that -- decisions on whether to take a
1259// snapshot, or what kind of snapshot, are made elsewhere.
1260static void
1261take_snapshot(Snapshot* snapshot, SnapshotKind kind, Time time,
njnefc13c22009-02-23 06:44:51 +00001262 Bool is_detailed)
njn734b8052007-11-01 04:40:37 +00001263{
1264 tl_assert(!is_snapshot_in_use(snapshot));
1265 tl_assert(have_started_executing_code);
1266
1267 // Heap and heap admin.
1268 if (clo_heap) {
1269 snapshot->heap_szB = heap_szB;
1270 if (is_detailed) {
njn32397c02007-11-10 04:08:08 +00001271 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001272 snapshot->alloc_sxpt = dup_XTree(alloc_xpt, total_szB);
1273 tl_assert( alloc_xpt->szB == heap_szB);
1274 tl_assert(snapshot->alloc_sxpt->szB == heap_szB);
1275 }
njn32397c02007-11-10 04:08:08 +00001276 snapshot->heap_extra_szB = heap_extra_szB;
njn734b8052007-11-01 04:40:37 +00001277 }
1278
1279 // Stack(s).
1280 if (clo_stacks) {
1281 snapshot->stacks_szB = stacks_szB;
1282 }
1283
1284 // Rest of snapshot.
1285 snapshot->kind = kind;
1286 snapshot->time = time;
1287 sanity_check_snapshot(snapshot);
1288
1289 // Update stats.
1290 if (Peak == kind) n_peak_snapshots++;
1291 if (is_detailed) n_detailed_snapshots++;
1292 n_real_snapshots++;
1293}
1294
1295
1296// Take a snapshot, if it's time, or if we've hit a peak.
1297static void
1298maybe_take_snapshot(SnapshotKind kind, Char* what)
1299{
1300 // 'min_time_interval' is the minimum time interval between snapshots.
1301 // If we try to take a snapshot and less than this much time has passed,
1302 // we don't take it. It gets larger as the program runs longer. It's
1303 // initialised to zero so that we begin by taking snapshots as quickly as
1304 // possible.
1305 static Time min_time_interval = 0;
1306 // Zero allows startup snapshot.
1307 static Time earliest_possible_time_of_next_snapshot = 0;
1308 static Int n_snapshots_since_last_detailed = 0;
1309 static Int n_skipped_snapshots_since_last_snapshot = 0;
1310
1311 Snapshot* snapshot;
1312 Bool is_detailed;
1313 Time time = get_time();
1314
1315 switch (kind) {
1316 case Normal:
1317 // Only do a snapshot if it's time.
1318 if (time < earliest_possible_time_of_next_snapshot) {
1319 n_skipped_snapshots++;
1320 n_skipped_snapshots_since_last_snapshot++;
1321 return;
1322 }
1323 is_detailed = (clo_detailed_freq-1 == n_snapshots_since_last_detailed);
1324 break;
1325
1326 case Peak: {
1327 // Because we're about to do a deallocation, we're coming down from a
1328 // local peak. If it is (a) actually a global peak, and (b) a certain
1329 // amount bigger than the previous peak, then we take a peak snapshot.
1330 // By not taking a snapshot for every peak, we save a lot of effort --
1331 // because many peaks remain peak only for a short time.
njn32397c02007-11-10 04:08:08 +00001332 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001333 SizeT excess_szB_for_new_peak =
njn62721e92007-11-11 22:15:58 +00001334 (SizeT)((peak_snapshot_total_szB * clo_peak_inaccuracy) / 100);
njn734b8052007-11-01 04:40:37 +00001335 if (total_szB <= peak_snapshot_total_szB + excess_szB_for_new_peak) {
1336 return;
1337 }
1338 is_detailed = True;
1339 break;
1340 }
1341
1342 default:
1343 tl_assert2(0, "maybe_take_snapshot: unrecognised snapshot kind");
1344 }
1345
1346 // Take the snapshot.
1347 snapshot = & snapshots[next_snapshot_i];
njnefc13c22009-02-23 06:44:51 +00001348 take_snapshot(snapshot, kind, time, is_detailed);
njn734b8052007-11-01 04:40:37 +00001349
1350 // Record if it was detailed.
1351 if (is_detailed) {
1352 n_snapshots_since_last_detailed = 0;
1353 } else {
1354 n_snapshots_since_last_detailed++;
1355 }
1356
1357 // Update peak data, if it's a Peak snapshot.
1358 if (Peak == kind) {
1359 Int i, number_of_peaks_snapshots_found = 0;
1360
1361 // Sanity check the size, then update our recorded peak.
1362 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00001363 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00001364 tl_assert2(snapshot_total_szB > peak_snapshot_total_szB,
1365 "%ld, %ld\n", snapshot_total_szB, peak_snapshot_total_szB);
1366 peak_snapshot_total_szB = snapshot_total_szB;
1367
1368 // Find the old peak snapshot, if it exists, and mark it as normal.
1369 for (i = 0; i < next_snapshot_i; i++) {
1370 if (Peak == snapshots[i].kind) {
1371 snapshots[i].kind = Normal;
1372 number_of_peaks_snapshots_found++;
1373 }
1374 }
1375 tl_assert(number_of_peaks_snapshots_found <= 1);
1376 }
1377
1378 // Finish up verbosity and stats stuff.
1379 if (n_skipped_snapshots_since_last_snapshot > 0) {
1380 VERB(2, " (skipped %d snapshot%s)",
1381 n_skipped_snapshots_since_last_snapshot,
njn84f32b22009-02-10 07:14:37 +00001382 ( 1 == n_skipped_snapshots_since_last_snapshot ? "" : "s") );
njn734b8052007-11-01 04:40:37 +00001383 }
1384 VERB_snapshot(2, what, next_snapshot_i);
1385 n_skipped_snapshots_since_last_snapshot = 0;
1386
1387 // Cull the entries, if our snapshot table is full.
1388 next_snapshot_i++;
1389 if (clo_max_snapshots == next_snapshot_i) {
1390 min_time_interval = cull_snapshots();
1391 }
1392
1393 // Work out the earliest time when the next snapshot can happen.
1394 earliest_possible_time_of_next_snapshot = time + min_time_interval;
1395}
1396
1397
1398//------------------------------------------------------------//
1399//--- Sanity checking ---//
1400//------------------------------------------------------------//
1401
1402static Bool ms_cheap_sanity_check ( void )
1403{
1404 return True; // Nothing useful we can cheaply check.
1405}
1406
1407static Bool ms_expensive_sanity_check ( void )
1408{
1409 sanity_check_XTree(alloc_xpt, /*parent*/NULL);
1410 sanity_check_snapshots_array();
1411 return True;
1412}
1413
1414
1415//------------------------------------------------------------//
1416//--- Heap management ---//
1417//------------------------------------------------------------//
1418
1419// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
1420// which is a foothold into the XCon at which it was allocated. From
1421// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
1422// decremented (at deallocation).
1423//
1424// Nb: first two fields must match core's VgHashNode.
1425typedef
1426 struct _HP_Chunk {
1427 struct _HP_Chunk* next;
njn32397c02007-11-10 04:08:08 +00001428 Addr data; // Ptr to actual block
1429 SizeT req_szB; // Size requested
1430 SizeT slop_szB; // Extra bytes given above those requested
1431 XPt* where; // Where allocated; bottom-XPt
njn734b8052007-11-01 04:40:37 +00001432 }
1433 HP_Chunk;
1434
1435static VgHashTable malloc_list = NULL; // HP_Chunks
1436
1437static void update_alloc_stats(SSizeT szB_delta)
1438{
1439 // Update total_allocs_deallocs_szB.
1440 if (szB_delta < 0) szB_delta = -szB_delta;
1441 total_allocs_deallocs_szB += szB_delta;
1442}
1443
njn32397c02007-11-10 04:08:08 +00001444static void update_heap_stats(SSizeT heap_szB_delta, Int heap_extra_szB_delta)
njn734b8052007-11-01 04:40:37 +00001445{
njn32397c02007-11-10 04:08:08 +00001446 if (heap_szB_delta < 0)
1447 tl_assert(heap_szB >= -heap_szB_delta);
1448 if (heap_extra_szB_delta < 0)
1449 tl_assert(heap_extra_szB >= -heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001450
njn32397c02007-11-10 04:08:08 +00001451 heap_extra_szB += heap_extra_szB_delta;
1452 heap_szB += heap_szB_delta;
1453
1454 update_alloc_stats(heap_szB_delta + heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001455}
nethercotec9f36922004-02-14 16:40:02 +00001456
nethercote159dfef2004-09-13 13:27:30 +00001457static
njn32397c02007-11-10 04:08:08 +00001458void* new_block ( ThreadId tid, void* p, SizeT req_szB, SizeT req_alignB,
njn57735902004-11-25 18:04:54 +00001459 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +00001460{
1461 HP_Chunk* hc;
njn734b8052007-11-01 04:40:37 +00001462 Bool is_custom_alloc = (NULL != p);
njn32397c02007-11-10 04:08:08 +00001463 SizeT actual_szB, slop_szB;
1464
njnefc13c22009-02-23 06:44:51 +00001465 if ((SSizeT)req_szB < 0) return NULL;
nethercotec9f36922004-02-14 16:40:02 +00001466
nethercote57e36b32004-07-10 14:56:28 +00001467 // Allocate and zero if necessary
1468 if (!p) {
njn32397c02007-11-10 04:08:08 +00001469 p = VG_(cli_malloc)( req_alignB, req_szB );
nethercote57e36b32004-07-10 14:56:28 +00001470 if (!p) {
nethercote57e36b32004-07-10 14:56:28 +00001471 return NULL;
1472 }
njn32397c02007-11-10 04:08:08 +00001473 if (is_zeroed) VG_(memset)(p, 0, req_szB);
1474 actual_szB = VG_(malloc_usable_size)(p);
1475 tl_assert(actual_szB >= req_szB);
1476 slop_szB = actual_szB - req_szB;
1477 } else {
1478 slop_szB = 0;
nethercote57e36b32004-07-10 14:56:28 +00001479 }
1480
njnf1c5def2005-08-11 02:17:07 +00001481 // Make new HP_Chunk node, add to malloc_list
sewardj9c606bd2008-09-18 18:12:50 +00001482 hc = VG_(malloc)("ms.main.nb.1", sizeof(HP_Chunk));
njn32397c02007-11-10 04:08:08 +00001483 hc->req_szB = req_szB;
1484 hc->slop_szB = slop_szB;
1485 hc->data = (Addr)p;
1486 hc->where = NULL;
njn246a9d22005-08-14 06:24:20 +00001487 VG_(HT_add_node)(malloc_list, hc);
nethercote57e36b32004-07-10 14:56:28 +00001488
njn734b8052007-11-01 04:40:37 +00001489 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001490 VERB(3, "<<< new_mem_heap (%lu, %lu)", req_szB, slop_szB);
njn734b8052007-11-01 04:40:37 +00001491
1492 // Update statistics.
1493 n_heap_allocs++;
1494
1495 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001496 update_heap_stats(req_szB, clo_heap_admin + slop_szB);
njn734b8052007-11-01 04:40:37 +00001497
1498 // Update XTree.
1499 hc->where = get_XCon( tid, is_custom_alloc );
njn32397c02007-11-10 04:08:08 +00001500 update_XCon(hc->where, req_szB);
njn734b8052007-11-01 04:40:37 +00001501
1502 // Maybe take a snapshot.
1503 maybe_take_snapshot(Normal, " alloc");
1504
1505 VERB(3, ">>>");
1506 }
nethercotec9f36922004-02-14 16:40:02 +00001507
nethercotec9f36922004-02-14 16:40:02 +00001508 return p;
1509}
1510
1511static __inline__
1512void die_block ( void* p, Bool custom_free )
1513{
njnf1c5def2005-08-11 02:17:07 +00001514 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +00001515
njnf1c5def2005-08-11 02:17:07 +00001516 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +00001517 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn734b8052007-11-01 04:40:37 +00001518 if (NULL == hc) {
njn5cc5d7e2005-08-11 02:09:25 +00001519 return; // must have been a bogus free()
njn734b8052007-11-01 04:40:37 +00001520 }
nethercotec9f36922004-02-14 16:40:02 +00001521
njn734b8052007-11-01 04:40:37 +00001522 if (clo_heap) {
1523 VERB(3, "<<< die_mem_heap");
nethercotec9f36922004-02-14 16:40:02 +00001524
njn734b8052007-11-01 04:40:37 +00001525 // Update statistics
1526 n_heap_frees++;
nethercote57e36b32004-07-10 14:56:28 +00001527
njn734b8052007-11-01 04:40:37 +00001528 // Maybe take a peak snapshot, since it's a deallocation.
1529 maybe_take_snapshot(Peak, "de-PEAK");
1530
1531 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001532 update_heap_stats(-hc->req_szB, -clo_heap_admin - hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001533
1534 // Update XTree.
njn32397c02007-11-10 04:08:08 +00001535 update_XCon(hc->where, -hc->req_szB);
njn734b8052007-11-01 04:40:37 +00001536
1537 // Maybe take a snapshot.
1538 maybe_take_snapshot(Normal, "dealloc");
1539
njn32397c02007-11-10 04:08:08 +00001540 VERB(3, ">>> (-%lu, -%lu)", hc->req_szB, hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001541 }
1542
1543 // Actually free the chunk, and the heap block (if necessary)
1544 VG_(free)( hc ); hc = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001545 if (!custom_free)
1546 VG_(cli_free)( p );
nethercotec9f36922004-02-14 16:40:02 +00001547}
1548
njn734b8052007-11-01 04:40:37 +00001549static __inline__
njn32397c02007-11-10 04:08:08 +00001550void* renew_block ( ThreadId tid, void* p_old, SizeT new_req_szB )
nethercotec9f36922004-02-14 16:40:02 +00001551{
njn734b8052007-11-01 04:40:37 +00001552 HP_Chunk* hc;
1553 void* p_new;
njn32397c02007-11-10 04:08:08 +00001554 SizeT old_req_szB, old_slop_szB, new_slop_szB, new_actual_szB;
njn734b8052007-11-01 04:40:37 +00001555 XPt *old_where, *new_where;
1556
1557 // Remove the old block
1558 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
1559 if (hc == NULL) {
1560 return NULL; // must have been a bogus realloc()
1561 }
1562
njn32397c02007-11-10 04:08:08 +00001563 old_req_szB = hc->req_szB;
1564 old_slop_szB = hc->slop_szB;
njn734b8052007-11-01 04:40:37 +00001565
1566 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001567 VERB(3, "<<< renew_mem_heap (%lu)", new_req_szB);
njn734b8052007-11-01 04:40:37 +00001568
1569 // Update statistics
1570 n_heap_reallocs++;
1571
1572 // Maybe take a peak snapshot, if it's (effectively) a deallocation.
njn32397c02007-11-10 04:08:08 +00001573 if (new_req_szB < old_req_szB) {
njn734b8052007-11-01 04:40:37 +00001574 maybe_take_snapshot(Peak, "re-PEAK");
1575 }
njn734b8052007-11-01 04:40:37 +00001576 }
1577
1578 // Actually do the allocation, if necessary.
njn32397c02007-11-10 04:08:08 +00001579 if (new_req_szB <= old_req_szB + old_slop_szB) {
1580 // New size is smaller or same; block not moved.
njn734b8052007-11-01 04:40:37 +00001581 p_new = p_old;
njn32397c02007-11-10 04:08:08 +00001582 new_slop_szB = old_slop_szB + (old_req_szB - new_req_szB);
njn734b8052007-11-01 04:40:37 +00001583
1584 } else {
njn32397c02007-11-10 04:08:08 +00001585 // New size is bigger; make new block, copy shared contents, free old.
1586 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_req_szB);
1587 if (!p_new) {
1588 // Nb: if realloc fails, NULL is returned but the old block is not
1589 // touched. What an awful function.
1590 return NULL;
njn734b8052007-11-01 04:40:37 +00001591 }
njn32397c02007-11-10 04:08:08 +00001592 VG_(memcpy)(p_new, p_old, old_req_szB);
1593 VG_(cli_free)(p_old);
1594 new_actual_szB = VG_(malloc_usable_size)(p_new);
1595 tl_assert(new_actual_szB >= new_req_szB);
1596 new_slop_szB = new_actual_szB - new_req_szB;
njn734b8052007-11-01 04:40:37 +00001597 }
1598
1599 if (p_new) {
1600 // Update HP_Chunk.
njn32397c02007-11-10 04:08:08 +00001601 hc->data = (Addr)p_new;
1602 hc->req_szB = new_req_szB;
1603 hc->slop_szB = new_slop_szB;
1604 old_where = hc->where;
1605 hc->where = NULL;
njn734b8052007-11-01 04:40:37 +00001606
1607 // Update XTree.
1608 if (clo_heap) {
1609 new_where = get_XCon( tid, /*custom_malloc*/False);
1610 hc->where = new_where;
njn32397c02007-11-10 04:08:08 +00001611 update_XCon(old_where, -old_req_szB);
1612 update_XCon(new_where, new_req_szB);
njn734b8052007-11-01 04:40:37 +00001613 }
1614 }
1615
1616 // Now insert the new hc (with a possibly new 'data' field) into
1617 // malloc_list. If this realloc() did not increase the memory size, we
1618 // will have removed and then re-added hc unnecessarily. But that's ok
1619 // because shrinking a block with realloc() is (presumably) much rarer
1620 // than growing it, and this way simplifies the growing case.
1621 VG_(HT_add_node)(malloc_list, hc);
1622
njn734b8052007-11-01 04:40:37 +00001623 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001624 // Update heap stats.
1625 update_heap_stats(new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
1626
1627 // Maybe take a snapshot.
njn734b8052007-11-01 04:40:37 +00001628 maybe_take_snapshot(Normal, "realloc");
1629
njn32397c02007-11-10 04:08:08 +00001630 VERB(3, ">>> (%ld, %ld)",
1631 new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
njn734b8052007-11-01 04:40:37 +00001632 }
1633
1634 return p_new;
nethercotec9f36922004-02-14 16:40:02 +00001635}
1636
njn734b8052007-11-01 04:40:37 +00001637
1638//------------------------------------------------------------//
1639//--- malloc() et al replacement wrappers ---//
1640//------------------------------------------------------------//
1641
1642static void* ms_malloc ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001643{
njn734b8052007-11-01 04:40:37 +00001644 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001645}
1646
njn734b8052007-11-01 04:40:37 +00001647static void* ms___builtin_new ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001648{
njn734b8052007-11-01 04:40:37 +00001649 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001650}
1651
njn734b8052007-11-01 04:40:37 +00001652static void* ms___builtin_vec_new ( ThreadId tid, SizeT szB )
fitzhardinge51f3ff12004-03-04 22:42:03 +00001653{
njn734b8052007-11-01 04:40:37 +00001654 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
1655}
1656
1657static void* ms_calloc ( ThreadId tid, SizeT m, SizeT szB )
1658{
1659 return new_block( tid, NULL, m*szB, VG_(clo_alignment), /*is_zeroed*/True );
1660}
1661
1662static void *ms_memalign ( ThreadId tid, SizeT alignB, SizeT szB )
1663{
1664 return new_block( tid, NULL, szB, alignB, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +00001665}
1666
njnefc13c22009-02-23 06:44:51 +00001667static void ms_free ( ThreadId tid __attribute__((unused)), void* p )
nethercotec9f36922004-02-14 16:40:02 +00001668{
1669 die_block( p, /*custom_free*/False );
1670}
1671
njn51d827b2005-05-09 01:02:08 +00001672static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001673{
1674 die_block( p, /*custom_free*/False);
1675}
1676
njn51d827b2005-05-09 01:02:08 +00001677static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001678{
1679 die_block( p, /*custom_free*/False );
1680}
1681
njn734b8052007-11-01 04:40:37 +00001682static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_szB )
nethercotec9f36922004-02-14 16:40:02 +00001683{
njn734b8052007-11-01 04:40:37 +00001684 return renew_block(tid, p_old, new_szB);
nethercotec9f36922004-02-14 16:40:02 +00001685}
1686
njnefc13c22009-02-23 06:44:51 +00001687static SizeT ms_malloc_usable_size ( ThreadId tid, void* p )
njn8b140de2009-02-17 04:31:18 +00001688{
1689 HP_Chunk* hc = VG_(HT_lookup)( malloc_list, (UWord)p );
1690
1691 return ( hc ? hc->req_szB + hc->slop_szB : 0 );
1692}
nethercotec9f36922004-02-14 16:40:02 +00001693
njn734b8052007-11-01 04:40:37 +00001694//------------------------------------------------------------//
1695//--- Stacks ---//
1696//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001697
njn734b8052007-11-01 04:40:37 +00001698// We really want the inlining to occur...
1699#define INLINE inline __attribute__((always_inline))
nethercotec9f36922004-02-14 16:40:02 +00001700
njn734b8052007-11-01 04:40:37 +00001701static void update_stack_stats(SSizeT stack_szB_delta)
nethercotec9f36922004-02-14 16:40:02 +00001702{
njn734b8052007-11-01 04:40:37 +00001703 if (stack_szB_delta < 0) tl_assert(stacks_szB >= -stack_szB_delta);
1704 stacks_szB += stack_szB_delta;
nethercotec9f36922004-02-14 16:40:02 +00001705
njn734b8052007-11-01 04:40:37 +00001706 update_alloc_stats(stack_szB_delta);
nethercotec9f36922004-02-14 16:40:02 +00001707}
1708
njnefc13c22009-02-23 06:44:51 +00001709static INLINE void new_mem_stack_2(SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001710{
njn734b8052007-11-01 04:40:37 +00001711 if (have_started_executing_code) {
1712 VERB(3, "<<< new_mem_stack (%ld)", len);
1713 n_stack_allocs++;
1714 update_stack_stats(len);
1715 maybe_take_snapshot(Normal, what);
1716 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001717 }
nethercotec9f36922004-02-14 16:40:02 +00001718}
1719
njnefc13c22009-02-23 06:44:51 +00001720static INLINE void die_mem_stack_2(SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001721{
njn734b8052007-11-01 04:40:37 +00001722 if (have_started_executing_code) {
1723 VERB(3, "<<< die_mem_stack (%ld)", -len);
1724 n_stack_frees++;
1725 maybe_take_snapshot(Peak, "stkPEAK");
1726 update_stack_stats(-len);
1727 maybe_take_snapshot(Normal, what);
1728 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001729 }
nethercotec9f36922004-02-14 16:40:02 +00001730}
1731
njn734b8052007-11-01 04:40:37 +00001732static void new_mem_stack(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001733{
njnefc13c22009-02-23 06:44:51 +00001734 new_mem_stack_2(len, "stk-new");
njn734b8052007-11-01 04:40:37 +00001735}
nethercotec9f36922004-02-14 16:40:02 +00001736
njn734b8052007-11-01 04:40:37 +00001737static void die_mem_stack(Addr a, SizeT len)
1738{
njnefc13c22009-02-23 06:44:51 +00001739 die_mem_stack_2(len, "stk-die");
njn734b8052007-11-01 04:40:37 +00001740}
nethercotec9f36922004-02-14 16:40:02 +00001741
sewardj7cf4e6b2008-05-01 20:24:26 +00001742static void new_mem_stack_signal(Addr a, SizeT len, ThreadId tid)
nethercotec9f36922004-02-14 16:40:02 +00001743{
njnefc13c22009-02-23 06:44:51 +00001744 new_mem_stack_2(len, "sig-new");
nethercotec9f36922004-02-14 16:40:02 +00001745}
1746
nethercote8b5f40c2004-11-02 13:29:50 +00001747static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001748{
njnefc13c22009-02-23 06:44:51 +00001749 die_mem_stack_2(len, "sig-die");
nethercotec9f36922004-02-14 16:40:02 +00001750}
1751
njn734b8052007-11-01 04:40:37 +00001752
1753//------------------------------------------------------------//
1754//--- Client Requests ---//
1755//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001756
njn51d827b2005-05-09 01:02:08 +00001757static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001758{
1759 switch (argv[0]) {
1760 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001761 void* res;
njn734b8052007-11-01 04:40:37 +00001762 void* p = (void*)argv[1];
1763 SizeT szB = argv[2];
1764 res = new_block( tid, p, szB, /*alignB--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001765 tl_assert(res == p);
njn734b8052007-11-01 04:40:37 +00001766 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001767 return True;
1768 }
1769 case VG_USERREQ__FREELIKE_BLOCK: {
njn734b8052007-11-01 04:40:37 +00001770 void* p = (void*)argv[1];
nethercotec9f36922004-02-14 16:40:02 +00001771 die_block( p, /*custom_free*/True );
njn734b8052007-11-01 04:40:37 +00001772 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001773 return True;
1774 }
1775 default:
1776 *ret = 0;
1777 return False;
1778 }
1779}
1780
njn734b8052007-11-01 04:40:37 +00001781//------------------------------------------------------------//
1782//--- Instrumentation ---//
1783//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001784
njn1a2741a2007-11-26 21:59:04 +00001785static void add_counter_update(IRSB* sbOut, Int n)
1786{
1787 #if defined(VG_BIGENDIAN)
1788 # define END Iend_BE
1789 #elif defined(VG_LITTLEENDIAN)
1790 # define END Iend_LE
1791 #else
1792 # error "Unknown endianness"
1793 #endif
1794 // Add code to increment 'guest_instrs_executed' by 'n', like this:
1795 // WrTmp(t1, Load64(&guest_instrs_executed))
1796 // WrTmp(t2, Add64(RdTmp(t1), Const(n)))
1797 // Store(&guest_instrs_executed, t2)
1798 IRTemp t1 = newIRTemp(sbOut->tyenv, Ity_I64);
1799 IRTemp t2 = newIRTemp(sbOut->tyenv, Ity_I64);
1800 IRExpr* counter_addr = mkIRExpr_HWord( (HWord)&guest_instrs_executed );
1801
1802 IRStmt* st1 = IRStmt_WrTmp(t1, IRExpr_Load(END, Ity_I64, counter_addr));
1803 IRStmt* st2 =
1804 IRStmt_WrTmp(t2,
1805 IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(t1),
1806 IRExpr_Const(IRConst_U64(n))));
1807 IRStmt* st3 = IRStmt_Store(END, counter_addr, IRExpr_RdTmp(t2));
1808
1809 addStmtToIRSB( sbOut, st1 );
1810 addStmtToIRSB( sbOut, st2 );
1811 addStmtToIRSB( sbOut, st3 );
1812}
1813
1814static IRSB* ms_instrument2( IRSB* sbIn )
1815{
1816 Int i, n = 0;
1817 IRSB* sbOut;
1818
1819 // We increment the instruction count in two places:
1820 // - just before any Ist_Exit statements;
1821 // - just before the IRSB's end.
1822 // In the former case, we zero 'n' and then continue instrumenting.
1823
1824 sbOut = deepCopyIRSBExceptStmts(sbIn);
1825
1826 for (i = 0; i < sbIn->stmts_used; i++) {
1827 IRStmt* st = sbIn->stmts[i];
1828
1829 if (!st || st->tag == Ist_NoOp) continue;
1830
1831 if (st->tag == Ist_IMark) {
1832 n++;
1833 } else if (st->tag == Ist_Exit) {
1834 if (n > 0) {
1835 // Add an increment before the Exit statement, then reset 'n'.
1836 add_counter_update(sbOut, n);
1837 n = 0;
1838 }
1839 }
1840 addStmtToIRSB( sbOut, st );
1841 }
1842
1843 if (n > 0) {
1844 // Add an increment before the SB end.
1845 add_counter_update(sbOut, n);
1846 }
1847 return sbOut;
1848}
1849
sewardj4ba057c2005-10-18 12:04:18 +00001850static
sewardj0b9d74a2006-12-24 02:24:11 +00001851IRSB* ms_instrument ( VgCallbackClosure* closure,
njn1a2741a2007-11-26 21:59:04 +00001852 IRSB* sbIn,
njn734b8052007-11-01 04:40:37 +00001853 VexGuestLayout* layout,
sewardj461df9c2006-01-17 02:06:39 +00001854 VexGuestExtents* vge,
sewardj4ba057c2005-10-18 12:04:18 +00001855 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001856{
njn734b8052007-11-01 04:40:37 +00001857 if (! have_started_executing_code) {
1858 // Do an initial sample to guarantee that we have at least one.
1859 // We use 'maybe_take_snapshot' instead of 'take_snapshot' to ensure
1860 // 'maybe_take_snapshot's internal static variables are initialised.
1861 have_started_executing_code = True;
1862 maybe_take_snapshot(Normal, "startup");
1863 }
njn1a2741a2007-11-26 21:59:04 +00001864
1865 if (clo_time_unit == TimeI) { return ms_instrument2(sbIn); }
1866 else if (clo_time_unit == TimeMS) { return sbIn; }
1867 else if (clo_time_unit == TimeB) { return sbIn; }
1868 else { tl_assert2(0, "bad --time-unit value"); }
nethercotec9f36922004-02-14 16:40:02 +00001869}
1870
nethercotec9f36922004-02-14 16:40:02 +00001871
njn734b8052007-11-01 04:40:37 +00001872//------------------------------------------------------------//
1873//--- Writing snapshots ---//
1874//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001875
njnb11e5aa2008-01-20 22:30:52 +00001876Char FP_buf[BUF_LEN];
nethercotec9f36922004-02-14 16:40:02 +00001877
njn734b8052007-11-01 04:40:37 +00001878// XXX: implement f{,n}printf in m_libcprint.c eventually, and use it here.
1879// Then change Cachegrind to use it too.
1880#define FP(format, args...) ({ \
njnb11e5aa2008-01-20 22:30:52 +00001881 VG_(snprintf)(FP_buf, BUF_LEN, format, ##args); \
1882 FP_buf[BUF_LEN-1] = '\0'; /* Make sure the string is terminated. */ \
1883 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf)); \
1884})
1885
nethercotec9f36922004-02-14 16:40:02 +00001886// Nb: uses a static buffer, each call trashes the last string returned.
njn734b8052007-11-01 04:40:37 +00001887static Char* make_perc(ULong x, ULong y)
nethercotec9f36922004-02-14 16:40:02 +00001888{
1889 static Char mbuf[32];
njn734b8052007-11-01 04:40:37 +00001890
1891// tl_assert(x <= y); XXX; put back in later...
1892
njn1a2741a2007-11-26 21:59:04 +00001893 // XXX: I'm not confident that VG_(percentify) works as it should...
njn734b8052007-11-01 04:40:37 +00001894 VG_(percentify)(x, y, 2, 6, mbuf);
1895 // XXX: this is bogus if the denominator was zero -- resulting string is
1896 // something like "0 --%")
1897 if (' ' == mbuf[0]) mbuf[0] = '0';
nethercotec9f36922004-02-14 16:40:02 +00001898 return mbuf;
1899}
1900
njn734b8052007-11-01 04:40:37 +00001901static void pp_snapshot_SXPt(Int fd, SXPt* sxpt, Int depth, Char* depth_str,
1902 Int depth_str_len,
1903 SizeT snapshot_heap_szB, SizeT snapshot_total_szB)
nethercotec9f36922004-02-14 16:40:02 +00001904{
njn466ed6e2009-02-18 05:14:44 +00001905 Int i, j, n_insig_children_sxpts;
njn734b8052007-11-01 04:40:37 +00001906 Char* perc;
njn734b8052007-11-01 04:40:37 +00001907 SXPt* pred = NULL;
1908 SXPt* child = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001909
sewardjf330ae82008-05-13 10:57:29 +00001910 // Used for printing function names. Is made static to keep it out
1911 // of the stack frame -- this function is recursive. Obviously this
1912 // now means its contents are trashed across the recursive call.
1913 static Char ip_desc_array[BUF_LEN];
1914 Char* ip_desc = ip_desc_array;
1915
njn734b8052007-11-01 04:40:37 +00001916 switch (sxpt->tag) {
1917 case SigSXPt:
1918 // Print the SXPt itself.
njn84f32b22009-02-10 07:14:37 +00001919 if (0 == depth) {
njn734b8052007-11-01 04:40:37 +00001920 ip_desc =
1921 "(heap allocation functions) malloc/new/new[], --alloc-fns, etc.";
1922 } else {
1923 // If it's main-or-below-main, we (if appropriate) ignore everything
1924 // below it by pretending it has no children.
njn68824432009-02-10 06:48:00 +00001925 if ( ! VG_(clo_show_below_main) ) {
1926 Vg_FnNameKind kind = VG_(get_fnname_kind_from_IP)(sxpt->Sig.ip);
1927 if (Vg_FnNameMain == kind || Vg_FnNameBelowMain == kind) {
1928 sxpt->Sig.n_children = 0;
1929 }
njn734b8052007-11-01 04:40:37 +00001930 }
njn68824432009-02-10 06:48:00 +00001931
njn734b8052007-11-01 04:40:37 +00001932 // We need the -1 to get the line number right, But I'm not sure why.
1933 ip_desc = VG_(describe_IP)(sxpt->Sig.ip-1, ip_desc, BUF_LEN);
1934 }
1935 perc = make_perc(sxpt->szB, snapshot_total_szB);
njn466ed6e2009-02-18 05:14:44 +00001936
1937 // Do the non-ip_desc part first...
1938 FP("%sn%d: %lu ", depth_str, sxpt->Sig.n_children, sxpt->szB);
1939
1940 // For ip_descs beginning with "0xABCD...:" addresses, we first
1941 // measure the length of the "0xabcd: " address at the start of the
1942 // ip_desc.
1943 j = 0;
1944 if ('0' == ip_desc[0] && 'x' == ip_desc[1]) {
1945 j = 2;
1946 while (True) {
1947 if (ip_desc[j]) {
1948 if (':' == ip_desc[j]) break;
1949 j++;
1950 } else {
1951 tl_assert2(0, "ip_desc has unexpected form: %s\n", ip_desc);
1952 }
1953 }
1954 }
1955 // Nb: We treat this specially (ie. we don't use FP) so that if the
1956 // ip_desc is too long (eg. due to a long C++ function name), it'll
1957 // get truncated, but the '\n' is still there so its a valid file.
1958 // (At one point we were truncating without adding the '\n', which
1959 // caused bug #155929.)
1960 //
1961 // Also, we account for the length of the address in ip_desc when
1962 // truncating. (The longest address we could have is 18 chars: "0x"
1963 // plus 16 address digits.) This ensures that the truncated function
1964 // name always has the same length, which makes truncation
1965 // deterministic and thus makes testing easier.
1966 tl_assert(j <= 18);
1967 VG_(snprintf)(FP_buf, BUF_LEN, "%s\n", ip_desc);
1968 FP_buf[BUF_LEN-18+j-5] = '.'; // "..." at the end make the
1969 FP_buf[BUF_LEN-18+j-4] = '.'; // truncation more obvious.
1970 FP_buf[BUF_LEN-18+j-3] = '.';
1971 FP_buf[BUF_LEN-18+j-2] = '\n'; // The last char is '\n'.
1972 FP_buf[BUF_LEN-18+j-1] = '\0'; // The string is terminated.
1973 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf));
nethercotec9f36922004-02-14 16:40:02 +00001974
njn734b8052007-11-01 04:40:37 +00001975 // Indent.
1976 tl_assert(depth+1 < depth_str_len-1); // -1 for end NUL char
1977 depth_str[depth+0] = ' ';
1978 depth_str[depth+1] = '\0';
1979
1980 // Sort SXPt's children by szB (reverse order: biggest to smallest).
1981 // Nb: we sort them here, rather than earlier (eg. in dup_XTree), for
1982 // two reasons. First, if we do it during dup_XTree, it can get
1983 // expensive (eg. 15% of execution time for konqueror
1984 // startup/shutdown). Second, this way we get the Insig SXPt (if one
1985 // is present) in its sorted position, not at the end.
1986 VG_(ssort)(sxpt->Sig.children, sxpt->Sig.n_children, sizeof(SXPt*),
1987 SXPt_revcmp_szB);
1988
1989 // Print the SXPt's children. They should already be in sorted order.
1990 n_insig_children_sxpts = 0;
1991 for (i = 0; i < sxpt->Sig.n_children; i++) {
1992 pred = child;
1993 child = sxpt->Sig.children[i];
1994
1995 if (InsigSXPt == child->tag)
1996 n_insig_children_sxpts++;
1997
sewardjf330ae82008-05-13 10:57:29 +00001998 // Ok, print the child. NB: contents of ip_desc_array will be
1999 // trashed by this recursive call. Doesn't matter currently,
2000 // but worth noting.
njn734b8052007-11-01 04:40:37 +00002001 pp_snapshot_SXPt(fd, child, depth+1, depth_str, depth_str_len,
2002 snapshot_heap_szB, snapshot_total_szB);
njn734b8052007-11-01 04:40:37 +00002003 }
njndbeb5352007-12-04 03:15:23 +00002004
2005 // Unindent.
2006 depth_str[depth+0] = '\0';
2007 depth_str[depth+1] = '\0';
2008
njn734b8052007-11-01 04:40:37 +00002009 // There should be 0 or 1 Insig children SXPts.
2010 tl_assert(n_insig_children_sxpts <= 1);
2011 break;
2012
2013 case InsigSXPt: {
njn84f32b22009-02-10 07:14:37 +00002014 Char* s = ( 1 == sxpt->Insig.n_xpts ? "," : "s, all" );
njn734b8052007-11-01 04:40:37 +00002015 perc = make_perc(sxpt->szB, snapshot_total_szB);
2016 FP("%sn0: %lu in %d place%s below massif's threshold (%s)\n",
2017 depth_str, sxpt->szB, sxpt->Insig.n_xpts, s,
njn62721e92007-11-11 22:15:58 +00002018 make_perc((ULong)clo_threshold, 100));
njn734b8052007-11-01 04:40:37 +00002019 break;
2020 }
2021
2022 default:
2023 tl_assert2(0, "pp_snapshot_SXPt: unrecognised SXPt tag");
nethercotec9f36922004-02-14 16:40:02 +00002024 }
nethercotec9f36922004-02-14 16:40:02 +00002025}
2026
njn734b8052007-11-01 04:40:37 +00002027static void pp_snapshot(Int fd, Snapshot* snapshot, Int snapshot_n)
nethercotec9f36922004-02-14 16:40:02 +00002028{
njn734b8052007-11-01 04:40:37 +00002029 sanity_check_snapshot(snapshot);
nethercotec9f36922004-02-14 16:40:02 +00002030
njn734b8052007-11-01 04:40:37 +00002031 FP("#-----------\n");
2032 FP("snapshot=%d\n", snapshot_n);
2033 FP("#-----------\n");
2034 FP("time=%lld\n", snapshot->time);
2035 FP("mem_heap_B=%lu\n", snapshot->heap_szB);
njn32397c02007-11-10 04:08:08 +00002036 FP("mem_heap_extra_B=%lu\n", snapshot->heap_extra_szB);
njn734b8052007-11-01 04:40:37 +00002037 FP("mem_stacks_B=%lu\n", snapshot->stacks_szB);
2038
2039 if (is_detailed_snapshot(snapshot)) {
2040 // Detailed snapshot -- print heap tree.
2041 Int depth_str_len = clo_depth + 3;
sewardj9c606bd2008-09-18 18:12:50 +00002042 Char* depth_str = VG_(malloc)("ms.main.pps.1",
2043 sizeof(Char) * depth_str_len);
njn734b8052007-11-01 04:40:37 +00002044 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00002045 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00002046 depth_str[0] = '\0'; // Initialise depth_str to "".
2047
2048 FP("heap_tree=%s\n", ( Peak == snapshot->kind ? "peak" : "detailed" ));
2049 pp_snapshot_SXPt(fd, snapshot->alloc_sxpt, 0, depth_str,
2050 depth_str_len, snapshot->heap_szB,
2051 snapshot_total_szB);
2052
2053 VG_(free)(depth_str);
2054
2055 } else {
2056 FP("heap_tree=empty\n");
nethercote43a15ce2004-08-30 19:15:12 +00002057 }
nethercotec9f36922004-02-14 16:40:02 +00002058}
2059
njn734b8052007-11-01 04:40:37 +00002060static void write_snapshots_to_file(void)
nethercotec9f36922004-02-14 16:40:02 +00002061{
njn734b8052007-11-01 04:40:37 +00002062 Int i, fd;
sewardj92645592005-07-23 09:18:34 +00002063 SysRes sres;
nethercotec9f36922004-02-14 16:40:02 +00002064
njn7064fb22008-05-29 23:09:52 +00002065 // Setup output filename. Nb: it's important to do this now, ie. as late
2066 // as possible. If we do it at start-up and the program forks and the
2067 // output file format string contains a %p (pid) specifier, both the
2068 // parent and child will incorrectly write to the same file; this
2069 // happened in 3.3.0.
2070 Char* massif_out_file =
2071 VG_(expand_file_name)("--massif-out-file", clo_massif_out_file);
2072
njn734b8052007-11-01 04:40:37 +00002073 sres = VG_(open)(massif_out_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
2074 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00002075 if (sres.isError) {
njn734b8052007-11-01 04:40:37 +00002076 // If the file can't be opened for whatever reason (conflict
2077 // between multiple cachegrinded processes?), give up now.
2078 VG_(message)(Vg_UserMsg,
2079 "error: can't open output file '%s'", massif_out_file );
2080 VG_(message)(Vg_UserMsg,
2081 " ... so profiling results will be missing.");
njn7064fb22008-05-29 23:09:52 +00002082 VG_(free)(massif_out_file);
nethercotec9f36922004-02-14 16:40:02 +00002083 return;
sewardj92645592005-07-23 09:18:34 +00002084 } else {
sewardje8089302006-10-17 02:15:17 +00002085 fd = sres.res;
njn7064fb22008-05-29 23:09:52 +00002086 VG_(free)(massif_out_file);
nethercotec9f36922004-02-14 16:40:02 +00002087 }
2088
njn734b8052007-11-01 04:40:37 +00002089 // Print massif-specific options that were used.
2090 // XXX: is it worth having a "desc:" line? Could just call it "options:"
2091 // -- this file format isn't as generic as Cachegrind's, so the
2092 // implied genericity of "desc:" is bogus.
2093 FP("desc:");
2094 for (i = 0; i < VG_(sizeXA)(args_for_massif); i++) {
2095 Char* arg = *(Char**)VG_(indexXA)(args_for_massif, i);
2096 FP(" %s", arg);
nethercotec9f36922004-02-14 16:40:02 +00002097 }
njn734b8052007-11-01 04:40:37 +00002098 if (0 == i) FP(" (none)");
2099 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002100
njn734b8052007-11-01 04:40:37 +00002101 // Print "cmd:" line.
2102 FP("cmd: ");
sewardj45f4e7c2005-09-27 19:20:21 +00002103 if (VG_(args_the_exename)) {
njn734b8052007-11-01 04:40:37 +00002104 FP("%s", VG_(args_the_exename));
2105 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
2106 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
2107 if (arg)
2108 FP(" %s", arg);
2109 }
2110 } else {
2111 FP(" ???");
sewardj45f4e7c2005-09-27 19:20:21 +00002112 }
njn734b8052007-11-01 04:40:37 +00002113 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002114
njn734b8052007-11-01 04:40:37 +00002115 FP("time_unit: %s\n", TimeUnit_to_string(clo_time_unit));
nethercotec9f36922004-02-14 16:40:02 +00002116
njn734b8052007-11-01 04:40:37 +00002117 for (i = 0; i < next_snapshot_i; i++) {
2118 Snapshot* snapshot = & snapshots[i];
2119 pp_snapshot(fd, snapshot, i); // Detailed snapshot!
nethercotec9f36922004-02-14 16:40:02 +00002120 }
2121}
2122
njn734b8052007-11-01 04:40:37 +00002123
2124//------------------------------------------------------------//
2125//--- Finalisation ---//
2126//------------------------------------------------------------//
2127
njn51d827b2005-05-09 01:02:08 +00002128static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00002129{
njn734b8052007-11-01 04:40:37 +00002130 // Output.
2131 write_snapshots_to_file();
nethercotec9f36922004-02-14 16:40:02 +00002132
njn734b8052007-11-01 04:40:37 +00002133 // Stats
2134 tl_assert(n_xpts > 0); // always have alloc_xpt
2135 VERB(1, "heap allocs: %u", n_heap_allocs);
2136 VERB(1, "heap reallocs: %u", n_heap_reallocs);
2137 VERB(1, "heap frees: %u", n_heap_frees);
2138 VERB(1, "stack allocs: %u", n_stack_allocs);
2139 VERB(1, "stack frees: %u", n_stack_frees);
2140 VERB(1, "XPts: %u", n_xpts);
2141 VERB(1, "top-XPts: %u (%d%%)",
2142 alloc_xpt->n_children,
2143 ( n_xpts ? alloc_xpt->n_children * 100 / n_xpts : 0));
njn55a30042007-11-10 04:18:39 +00002144 VERB(1, "XPt init expansions: %u", n_xpt_init_expansions);
2145 VERB(1, "XPt later expansions: %u", n_xpt_later_expansions);
njn734b8052007-11-01 04:40:37 +00002146 VERB(1, "SXPt allocs: %u", n_sxpt_allocs);
2147 VERB(1, "SXPt frees: %u", n_sxpt_frees);
2148 VERB(1, "skipped snapshots: %u", n_skipped_snapshots);
2149 VERB(1, "real snapshots: %u", n_real_snapshots);
2150 VERB(1, "detailed snapshots: %u", n_detailed_snapshots);
2151 VERB(1, "peak snapshots: %u", n_peak_snapshots);
2152 VERB(1, "cullings: %u", n_cullings);
njn55a30042007-11-10 04:18:39 +00002153 VERB(1, "XCon redos: %u", n_XCon_redos);
nethercotec9f36922004-02-14 16:40:02 +00002154}
2155
njn734b8052007-11-01 04:40:37 +00002156
2157//------------------------------------------------------------//
2158//--- Initialisation ---//
2159//------------------------------------------------------------//
njn51d827b2005-05-09 01:02:08 +00002160
2161static void ms_post_clo_init(void)
2162{
njn734b8052007-11-01 04:40:37 +00002163 Int i;
njn51d827b2005-05-09 01:02:08 +00002164
njn734b8052007-11-01 04:40:37 +00002165 // Check options.
njn62721e92007-11-11 22:15:58 +00002166 if (clo_threshold < 0 || clo_threshold > 100) {
2167 VG_(message)(Vg_UserMsg, "--threshold must be between 0.0 and 100.0");
njn734b8052007-11-01 04:40:37 +00002168 VG_(err_bad_option)("--threshold");
2169 }
njn734b8052007-11-01 04:40:37 +00002170
2171 // If we have --heap=no, set --heap-admin to zero, just to make sure we
2172 // don't accidentally use a non-zero heap-admin size somewhere.
2173 if (!clo_heap) {
2174 clo_heap_admin = 0;
2175 }
2176
2177 // Print alloc-fns, if necessary.
2178 if (VG_(clo_verbosity) > 1) {
2179 VERB(1, "alloc-fns:");
2180 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
2181 Char** alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
2182 VERB(1, " %d: %s", i, *alloc_fn_ptr);
2183 }
2184 }
2185
2186 // Events to track.
2187 if (clo_stacks) {
2188 VG_(track_new_mem_stack) ( new_mem_stack );
2189 VG_(track_die_mem_stack) ( die_mem_stack );
2190 VG_(track_new_mem_stack_signal) ( new_mem_stack_signal );
2191 VG_(track_die_mem_stack_signal) ( die_mem_stack_signal );
2192 }
2193
2194 // Initialise snapshot array, and sanity-check it.
sewardj9c606bd2008-09-18 18:12:50 +00002195 snapshots = VG_(malloc)("ms.main.mpoci.1",
2196 sizeof(Snapshot) * clo_max_snapshots);
njn734b8052007-11-01 04:40:37 +00002197 // We don't want to do snapshot sanity checks here, because they're
2198 // currently uninitialised.
2199 for (i = 0; i < clo_max_snapshots; i++) {
2200 clear_snapshot( & snapshots[i], /*do_sanity_check*/False );
2201 }
2202 sanity_check_snapshots_array();
njn51d827b2005-05-09 01:02:08 +00002203}
2204
tom151a6392005-11-11 12:30:36 +00002205static void ms_pre_clo_init(void)
njn734b8052007-11-01 04:40:37 +00002206{
njn51d827b2005-05-09 01:02:08 +00002207 VG_(details_name) ("Massif");
2208 VG_(details_version) (NULL);
njn1a2741a2007-11-26 21:59:04 +00002209 VG_(details_description) ("a heap profiler");
njn9a0cba42007-04-15 22:15:57 +00002210 VG_(details_copyright_author)(
sewardj4d474d02008-02-11 11:34:59 +00002211 "Copyright (C) 2003-2008, and GNU GPL'd, by Nicholas Nethercote");
njn51d827b2005-05-09 01:02:08 +00002212 VG_(details_bug_reports_to) (VG_BUGS_TO);
2213
2214 // Basic functions
2215 VG_(basic_tool_funcs) (ms_post_clo_init,
2216 ms_instrument,
2217 ms_fini);
2218
2219 // Needs
2220 VG_(needs_libc_freeres)();
2221 VG_(needs_command_line_options)(ms_process_cmd_line_option,
2222 ms_print_usage,
2223 ms_print_debug_usage);
2224 VG_(needs_client_requests) (ms_handle_client_request);
njn734b8052007-11-01 04:40:37 +00002225 VG_(needs_sanity_checks) (ms_cheap_sanity_check,
2226 ms_expensive_sanity_check);
njnfc51f8d2005-06-21 03:20:17 +00002227 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00002228 ms___builtin_new,
2229 ms___builtin_vec_new,
2230 ms_memalign,
2231 ms_calloc,
2232 ms_free,
2233 ms___builtin_delete,
2234 ms___builtin_vec_delete,
2235 ms_realloc,
njn8b140de2009-02-17 04:31:18 +00002236 ms_malloc_usable_size,
njn51d827b2005-05-09 01:02:08 +00002237 0 );
2238
njn51d827b2005-05-09 01:02:08 +00002239 // HP_Chunks
njn734b8052007-11-01 04:40:37 +00002240 malloc_list = VG_(HT_construct)( "Massif's malloc list" );
njn51d827b2005-05-09 01:02:08 +00002241
2242 // Dummy node at top of the context structure.
njn734b8052007-11-01 04:40:37 +00002243 alloc_xpt = new_XPt(/*ip*/0, /*parent*/NULL);
2244
2245 // Initialise alloc_fns.
2246 init_alloc_fns();
2247
2248 // Initialise args_for_massif.
sewardj9c606bd2008-09-18 18:12:50 +00002249 args_for_massif = VG_(newXA)(VG_(malloc), "ms.main.mprci.1",
2250 VG_(free), sizeof(HChar*));
njn51d827b2005-05-09 01:02:08 +00002251}
2252
sewardj45f4e7c2005-09-27 19:20:21 +00002253VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00002254
njn734b8052007-11-01 04:40:37 +00002255//--------------------------------------------------------------------//
2256//--- end ---//
2257//--------------------------------------------------------------------//