blob: 1631fe2ce5699cd76a8558d671bf1384cda5ca55 [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
nethercotec9f36922004-02-14 16:40:02 +0000223
nethercotec9f36922004-02-14 16:40:02 +0000224
njn734b8052007-11-01 04:40:37 +0000225//------------------------------------------------------------//
226//--- Statistics ---//
227//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000228
229// Konqueror startup, to give an idea of the numbers involved with a biggish
230// program, with default depth:
231//
232// depth=3 depth=40
233// - 310,000 allocations
234// - 300,000 frees
235// - 15,000 XPts 800,000 XPts
236// - 1,800 top-XPts
237
njn734b8052007-11-01 04:40:37 +0000238static UInt n_heap_allocs = 0;
239static UInt n_heap_reallocs = 0;
240static UInt n_heap_frees = 0;
241static UInt n_stack_allocs = 0;
242static UInt n_stack_frees = 0;
243static UInt n_xpts = 0;
244static UInt n_xpt_init_expansions = 0;
245static UInt n_xpt_later_expansions = 0;
246static UInt n_sxpt_allocs = 0;
247static UInt n_sxpt_frees = 0;
248static UInt n_skipped_snapshots = 0;
249static UInt n_real_snapshots = 0;
250static UInt n_detailed_snapshots = 0;
251static UInt n_peak_snapshots = 0;
252static UInt n_cullings = 0;
253static UInt n_XCon_redos = 0;
nethercotec9f36922004-02-14 16:40:02 +0000254
njn734b8052007-11-01 04:40:37 +0000255//------------------------------------------------------------//
256//--- Globals ---//
257//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000258
njn1a2741a2007-11-26 21:59:04 +0000259// Number of guest instructions executed so far. Only used with
260// --time-unit=i.
261static Long guest_instrs_executed = 0;
262
njn32397c02007-11-10 04:08:08 +0000263static SizeT heap_szB = 0; // Live heap size
264static SizeT heap_extra_szB = 0; // Live heap extra size -- slop + admin bytes
265static SizeT stacks_szB = 0; // Live stacks size
nethercotec9f36922004-02-14 16:40:02 +0000266
njn734b8052007-11-01 04:40:37 +0000267// This is the total size from the current peak snapshot, or 0 if no peak
268// snapshot has been taken yet.
269static SizeT peak_snapshot_total_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000270
njn734b8052007-11-01 04:40:37 +0000271// Incremented every time memory is allocated/deallocated, by the
272// allocated/deallocated amount; includes heap, heap-admin and stack
273// memory. An alternative to milliseconds as a unit of program "time".
274static ULong total_allocs_deallocs_szB = 0;
nethercotec9f36922004-02-14 16:40:02 +0000275
njn734b8052007-11-01 04:40:37 +0000276// We don't start taking snapshots until the first basic block is executed,
277// rather than doing it in ms_post_clo_init (which is the obvious spot), for
278// two reasons.
279// - It lets us ignore stack events prior to that, because they're not
280// really proper ones and just would screw things up.
281// - Because there's still some core initialisation to do, and so there
282// would be an artificial time gap between the first and second snapshots.
283//
284static Bool have_started_executing_code = False;
nethercotec9f36922004-02-14 16:40:02 +0000285
njn734b8052007-11-01 04:40:37 +0000286//------------------------------------------------------------//
287//--- Alloc fns ---//
288//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +0000289
njn734b8052007-11-01 04:40:37 +0000290static XArray* alloc_fns;
nethercotec9f36922004-02-14 16:40:02 +0000291
njn734b8052007-11-01 04:40:37 +0000292static void init_alloc_fns(void)
293{
294 // Create the list, and add the default elements.
295 alloc_fns = VG_(newXA)(VG_(malloc), VG_(free), sizeof(Char*));
296 #define DO(x) { Char* s = x; VG_(addToXA)(alloc_fns, &s); }
nethercotec9f36922004-02-14 16:40:02 +0000297
njn734b8052007-11-01 04:40:37 +0000298 // Ordered according to (presumed) frequency.
299 // Nb: The C++ "operator new*" ones are overloadable. We include them
300 // always anyway, because even if they're overloaded, it would be a
301 // prodigiously stupid overloading that caused them to not allocate
302 // memory.
303 DO("malloc" );
304 DO("__builtin_new" );
305 DO("operator new(unsigned)" );
306 DO("operator new(unsigned long)" );
307 DO("__builtin_vec_new" );
308 DO("operator new[](unsigned)" );
309 DO("operator new[](unsigned long)" );
310 DO("calloc" );
311 DO("realloc" );
312 DO("memalign" );
313 DO("operator new(unsigned, std::nothrow_t const&)" );
314 DO("operator new[](unsigned, std::nothrow_t const&)" );
315 DO("operator new(unsigned long, std::nothrow_t const&)" );
316 DO("operator new[](unsigned long, std::nothrow_t const&)");
317}
nethercotec9f36922004-02-14 16:40:02 +0000318
njn734b8052007-11-01 04:40:37 +0000319static Bool is_alloc_fn(Char* fnname)
320{
321 Char** alloc_fn_ptr;
322 Int i;
323
324 // Nb: It's a linear search through the list, because we're comparing
325 // strings rather than pointers to strings.
326 // Nb: This gets called a lot. It was an OSet, but they're quite slow to
327 // iterate through so it wasn't a good choice.
328 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
329 alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
330 if (VG_STREQ(fnname, *alloc_fn_ptr))
331 return True;
nethercotec9f36922004-02-14 16:40:02 +0000332 }
njn734b8052007-11-01 04:40:37 +0000333 return False;
334}
nethercotec9f36922004-02-14 16:40:02 +0000335
njn734b8052007-11-01 04:40:37 +0000336
337//------------------------------------------------------------//
338//--- Command line args ---//
339//------------------------------------------------------------//
340
341#define MAX_DEPTH 200
342
njn1a2741a2007-11-26 21:59:04 +0000343typedef enum { TimeI, TimeMS, TimeB } TimeUnit;
njn734b8052007-11-01 04:40:37 +0000344
345static Char* TimeUnit_to_string(TimeUnit time_unit)
346{
347 switch (time_unit) {
njn1a2741a2007-11-26 21:59:04 +0000348 case TimeI: return "i";
njn734b8052007-11-01 04:40:37 +0000349 case TimeMS: return "ms";
350 case TimeB: return "B";
351 default: tl_assert2(0, "TimeUnit_to_string: unrecognised TimeUnit");
352 }
353}
354
355static Bool clo_heap = True;
njn429afb42007-11-02 04:12:48 +0000356 // clo_heap_admin is deliberately a word-sized type. At one point it was
357 // a UInt, but this caused problems on 64-bit machines when it was
358 // multiplied by a small negative number and then promoted to a
359 // word-sized type -- it ended up with a value of 4.2 billion. Sigh.
njn62721e92007-11-11 22:15:58 +0000360static SizeT clo_heap_admin = 8;
361static Bool clo_stacks = False;
362static UInt clo_depth = 30;
363static double clo_threshold = 1.0; // percentage
364static double clo_peak_inaccuracy = 1.0; // percentage
njn1a2741a2007-11-26 21:59:04 +0000365static UInt clo_time_unit = TimeI;
njn62721e92007-11-11 22:15:58 +0000366static UInt clo_detailed_freq = 10;
367static UInt clo_max_snapshots = 100;
njnf4c665f2007-11-20 07:55:40 +0000368static Char* clo_massif_out_file = "massif.out.%p";
njn734b8052007-11-01 04:40:37 +0000369
370static XArray* args_for_massif;
nethercotec9f36922004-02-14 16:40:02 +0000371
njn51d827b2005-05-09 01:02:08 +0000372static Bool ms_process_cmd_line_option(Char* arg)
nethercotec9f36922004-02-14 16:40:02 +0000373{
njn734b8052007-11-01 04:40:37 +0000374 // Remember the arg for later use.
375 VG_(addToXA)(args_for_massif, &arg);
nethercotec9f36922004-02-14 16:40:02 +0000376
njn734b8052007-11-01 04:40:37 +0000377 VG_BOOL_CLO(arg, "--heap", clo_heap)
378 else VG_BOOL_CLO(arg, "--stacks", clo_stacks)
379
njn734b8052007-11-01 04:40:37 +0000380 else VG_NUM_CLO(arg, "--heap-admin", clo_heap_admin)
381 else VG_NUM_CLO(arg, "--depth", clo_depth)
382
njn62721e92007-11-11 22:15:58 +0000383 else VG_DBL_CLO(arg, "--threshold", clo_threshold)
njn734b8052007-11-01 04:40:37 +0000384
njn62721e92007-11-11 22:15:58 +0000385 else VG_DBL_CLO(arg, "--peak-inaccuracy", clo_peak_inaccuracy)
njn734b8052007-11-01 04:40:37 +0000386
387 else VG_NUM_CLO(arg, "--detailed-freq", clo_detailed_freq)
388 else VG_NUM_CLO(arg, "--max-snapshots", clo_max_snapshots)
389
njn1a2741a2007-11-26 21:59:04 +0000390 else if (VG_CLO_STREQ(arg, "--time-unit=i")) clo_time_unit = TimeI;
njn734b8052007-11-01 04:40:37 +0000391 else if (VG_CLO_STREQ(arg, "--time-unit=ms")) clo_time_unit = TimeMS;
392 else if (VG_CLO_STREQ(arg, "--time-unit=B")) clo_time_unit = TimeB;
nethercotec9f36922004-02-14 16:40:02 +0000393
394 else if (VG_CLO_STREQN(11, arg, "--alloc-fn=")) {
njn734b8052007-11-01 04:40:37 +0000395 Char* alloc_fn = &arg[11];
396 VG_(addToXA)(alloc_fns, &alloc_fn);
nethercotec9f36922004-02-14 16:40:02 +0000397 }
398
njnf4c665f2007-11-20 07:55:40 +0000399 else if (VG_CLO_STREQN(14, arg, "--massif-out-file=")) {
400 clo_massif_out_file = &arg[18];
401 }
402
nethercotec9f36922004-02-14 16:40:02 +0000403 else
404 return VG_(replacement_malloc_process_cmd_line_option)(arg);
nethercote27fec902004-06-16 21:26:32 +0000405
nethercotec9f36922004-02-14 16:40:02 +0000406 return True;
407}
408
njn51d827b2005-05-09 01:02:08 +0000409static void ms_print_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000410{
njn734b8052007-11-01 04:40:37 +0000411 VG_(printf)(
nethercotec9f36922004-02-14 16:40:02 +0000412" --heap=no|yes profile heap blocks [yes]\n"
njn1a2741a2007-11-26 21:59:04 +0000413" --heap-admin=<number> average admin bytes per heap block;\n"
njn734b8052007-11-01 04:40:37 +0000414" ignored if --heap=no [8]\n"
415" --stacks=no|yes profile stack(s) [no]\n"
416" --depth=<number> depth of contexts [30]\n"
nethercotec9f36922004-02-14 16:40:02 +0000417" --alloc-fn=<name> specify <fn> as an alloc function [empty]\n"
njn62721e92007-11-11 22:15:58 +0000418" --threshold=<m.n> significance threshold, as a percentage [1.0]\n"
419" --peak-inaccuracy=<m.n> maximum peak inaccuracy, as a percentage [1.0]\n"
njn1a2741a2007-11-26 21:59:04 +0000420" --time-unit=i|ms|B time unit: instructions executed, milliseconds\n"
421" or heap bytes alloc'd/dealloc'd [i]\n"
njn734b8052007-11-01 04:40:37 +0000422" --detailed-freq=<N> every Nth snapshot should be detailed [10]\n"
423" --max-snapshots=<N> maximum number of snapshots recorded [100]\n"
njn374a36d2007-11-23 01:41:32 +0000424" --massif-out-file=<file> output file name [massif.out.%%p]\n"
nethercotec9f36922004-02-14 16:40:02 +0000425 );
426 VG_(replacement_malloc_print_usage)();
427}
428
njn51d827b2005-05-09 01:02:08 +0000429static void ms_print_debug_usage(void)
nethercotec9f36922004-02-14 16:40:02 +0000430{
431 VG_(replacement_malloc_print_debug_usage)();
432}
433
njn734b8052007-11-01 04:40:37 +0000434
435//------------------------------------------------------------//
436//--- XPts, XTrees and XCons ---//
437//------------------------------------------------------------//
438
439// An XPt represents an "execution point", ie. a code address. Each XPt is
440// part of a tree of XPts (an "execution tree", or "XTree"). The details of
441// the heap are represented by a single XTree.
442//
443// The root of the tree is 'alloc_xpt', which represents all allocation
444// functions, eg:
445// - malloc/calloc/realloc/memalign/new/new[];
446// - user-specified allocation functions (using --alloc-fn);
447// - custom allocation (MALLOCLIKE) points
448// It's a bit of a fake XPt (ie. its 'ip' is zero), and is only used because
449// it makes the code simpler.
450//
451// Any child of 'alloc_xpt' is called a "top-XPt". The XPts at the bottom
452// of an XTree (leaf nodes) are "bottom-XPTs".
453//
454// Each path from a top-XPt to a bottom-XPt through an XTree gives an
455// execution context ("XCon"), ie. a stack trace. (And sub-paths represent
456// stack sub-traces.) The number of XCons in an XTree is equal to the
457// number of bottom-XPTs in that XTree.
458//
459// alloc_xpt XTrees are bi-directional.
460// | ^
461// v |
462// > parent < Example: if child1() calls parent() and child2()
463// / | \ also calls parent(), and parent() calls malloc(),
464// | / \ | the XTree will look like this.
465// | v v |
466// child1 child2
467//
njndbeb5352007-12-04 03:15:23 +0000468// (Note that malformed stack traces can lead to difficulties. See the
469// comment at the bottom of get_XCon.)
470//
njn734b8052007-11-01 04:40:37 +0000471// XTrees and XPts are mirrored by SXTrees and SXPts, where the 'S' is short
472// for "saved". When the XTree is duplicated for a snapshot, we duplicate
473// it as an SXTree, which is similar but omits some things it does not need,
474// and aggregates up insignificant nodes. This is important as an SXTree is
475// typically much smaller than an XTree.
476
477// XXX: make XPt and SXPt extensible arrays, to avoid having to do two
478// allocations per Pt.
479
480typedef struct _XPt XPt;
481struct _XPt {
482 Addr ip; // code address
483
484 // Bottom-XPts: space for the precise context.
485 // Other XPts: space of all the descendent bottom-XPts.
486 // Nb: this value goes up and down as the program executes.
487 SizeT szB;
488
489 XPt* parent; // pointer to parent XPt
490
491 // Children.
492 // n_children and max_children are 32-bit integers. 16-bit integers
493 // are too small -- a very big program might have more than 65536
494 // allocation points (ie. top-XPts) -- Konqueror starting up has 1800.
495 UInt n_children; // number of children
496 UInt max_children; // capacity of children array
497 XPt** children; // pointers to children XPts
498};
499
500typedef
501 enum {
502 SigSXPt,
503 InsigSXPt
504 }
505 SXPtTag;
506
507typedef struct _SXPt SXPt;
508struct _SXPt {
509 SXPtTag tag;
510 SizeT szB; // memory size for the node, be it Sig or Insig
511 union {
512 // An SXPt representing a single significant code location. Much like
513 // an XPt, minus the fields that aren't necessary.
514 struct {
515 Addr ip;
516 UInt n_children;
517 SXPt** children;
518 }
519 Sig;
520
521 // An SXPt representing one or more code locations, all below the
522 // significance threshold.
523 struct {
524 Int n_xpts; // number of aggregated XPts
525 }
526 Insig;
527 };
528};
nethercotec9f36922004-02-14 16:40:02 +0000529
530// Fake XPt representing all allocation functions like malloc(). Acts as
531// parent node to all top-XPts.
532static XPt* alloc_xpt;
533
534// Cheap allocation for blocks that never need to be freed. Saves about 10%
535// for Konqueror startup with --depth=40.
nethercote7ac7f7b2004-11-02 12:36:02 +0000536static void* perm_malloc(SizeT n_bytes)
nethercotec9f36922004-02-14 16:40:02 +0000537{
538 static Addr hp = 0; // current heap pointer
539 static Addr hp_lim = 0; // maximum usable byte in current block
540
541 #define SUPERBLOCK_SIZE (1 << 20) // 1 MB
542
543 if (hp + n_bytes > hp_lim) {
sewardj45f4e7c2005-09-27 19:20:21 +0000544 hp = (Addr)VG_(am_shadow_alloc)(SUPERBLOCK_SIZE);
545 if (hp == 0)
njn734b8052007-11-01 04:40:37 +0000546 VG_(out_of_memory_NORETURN)( "massif:perm_malloc",
sewardj45f4e7c2005-09-27 19:20:21 +0000547 SUPERBLOCK_SIZE);
nethercotec9f36922004-02-14 16:40:02 +0000548 hp_lim = hp + SUPERBLOCK_SIZE - 1;
549 }
550
551 hp += n_bytes;
552
553 return (void*)(hp - n_bytes);
554}
555
njn734b8052007-11-01 04:40:37 +0000556static XPt* new_XPt(Addr ip, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000557{
njn734b8052007-11-01 04:40:37 +0000558 // XPts are never freed, so we can use perm_malloc to allocate them.
559 // Note that we cannot use perm_malloc for the 'children' array, because
560 // that needs to be resizable.
561 XPt* xpt = perm_malloc(sizeof(XPt));
562 xpt->ip = ip;
563 xpt->szB = 0;
564 xpt->parent = parent;
nethercotec9f36922004-02-14 16:40:02 +0000565
njn734b8052007-11-01 04:40:37 +0000566 // We don't initially allocate any space for children. We let that
567 // happen on demand. Many XPts (ie. all the bottom-XPts) don't have any
568 // children anyway.
nethercotec9f36922004-02-14 16:40:02 +0000569 xpt->n_children = 0;
njn734b8052007-11-01 04:40:37 +0000570 xpt->max_children = 0;
571 xpt->children = NULL;
nethercotec9f36922004-02-14 16:40:02 +0000572
573 // Update statistics
574 n_xpts++;
575
576 return xpt;
577}
578
njn734b8052007-11-01 04:40:37 +0000579static void add_child_xpt(XPt* parent, XPt* child)
580{
581 // Expand 'children' if necessary.
582 tl_assert(parent->n_children <= parent->max_children);
583 if (parent->n_children == parent->max_children) {
584 if (parent->max_children == 0) {
585 parent->max_children = 4;
586 parent->children = VG_(malloc)( parent->max_children * sizeof(XPt*) );
587 n_xpt_init_expansions++;
588 } else {
589 parent->max_children *= 2; // Double size
590 parent->children = VG_(realloc)( parent->children,
591 parent->max_children * sizeof(XPt*) );
592 n_xpt_later_expansions++;
593 }
594 }
595
596 // Insert new child XPt in parent's children list.
597 parent->children[ parent->n_children++ ] = child;
598}
599
600// Reverse comparison for a reverse sort -- biggest to smallest.
601static Int SXPt_revcmp_szB(void* n1, void* n2)
602{
603 SXPt* sxpt1 = *(SXPt**)n1;
604 SXPt* sxpt2 = *(SXPt**)n2;
605 return ( sxpt1->szB < sxpt2->szB ? 1
606 : sxpt1->szB > sxpt2->szB ? -1
607 : 0);
608}
609
610//------------------------------------------------------------//
611//--- XTree Operations ---//
612//------------------------------------------------------------//
613
614// Duplicates an XTree as an SXTree.
615static SXPt* dup_XTree(XPt* xpt, SizeT total_szB)
616{
617 Int i, n_sig_children, n_insig_children, n_child_sxpts;
njndbeb5352007-12-04 03:15:23 +0000618 SizeT sig_child_threshold_szB;
njn734b8052007-11-01 04:40:37 +0000619 SXPt* sxpt;
620
621 // Number of XPt children Action for SXPT
622 // ------------------ ---------------
623 // 0 sig, 0 insig alloc 0 children
624 // N sig, 0 insig alloc N children, dup all
625 // N sig, M insig alloc N+1, dup first N, aggregate remaining M
626 // 0 sig, M insig alloc 1, aggregate M
627
628 // Work out how big a child must be to be significant. If the current
629 // total_szB is zero, then we set it to 1, which means everything will be
630 // judged insignificant -- this is sensible, as there's no point showing
631 // any detail for this case. Unless they used --threshold=0, in which
632 // case we show them everything because that's what they asked for.
633 //
634 // Nb: We do this once now, rather than once per child, because if we do
635 // that the cost of all the divisions adds up to something significant.
636 if (total_szB == 0 && clo_threshold != 0) {
637 sig_child_threshold_szB = 1;
638 } else {
njn62721e92007-11-11 22:15:58 +0000639 sig_child_threshold_szB = (SizeT)((total_szB * clo_threshold) / 100);
njn734b8052007-11-01 04:40:37 +0000640 }
641
642 // How many children are significant? And do we need an aggregate SXPt?
643 n_sig_children = 0;
644 for (i = 0; i < xpt->n_children; i++) {
645 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
646 n_sig_children++;
647 }
648 }
649 n_insig_children = xpt->n_children - n_sig_children;
650 n_child_sxpts = n_sig_children + ( n_insig_children > 0 ? 1 : 0 );
651
652 // Duplicate the XPt.
653 sxpt = VG_(malloc)(sizeof(SXPt));
654 n_sxpt_allocs++;
655 sxpt->tag = SigSXPt;
656 sxpt->szB = xpt->szB;
657 sxpt->Sig.ip = xpt->ip;
658 sxpt->Sig.n_children = n_child_sxpts;
659
660 // Create the SXPt's children.
661 if (n_child_sxpts > 0) {
662 Int j;
njndbeb5352007-12-04 03:15:23 +0000663 SizeT sig_children_szB = 0, insig_children_szB = 0;
njn734b8052007-11-01 04:40:37 +0000664 sxpt->Sig.children = VG_(malloc)(n_child_sxpts * sizeof(SXPt*));
665
njndbeb5352007-12-04 03:15:23 +0000666 // Duplicate the significant children. (Nb: sig_children_szB +
667 // insig_children_szB doesn't necessarily equal xpt->szB.)
njn734b8052007-11-01 04:40:37 +0000668 j = 0;
669 for (i = 0; i < xpt->n_children; i++) {
670 if (xpt->children[i]->szB >= sig_child_threshold_szB) {
671 sxpt->Sig.children[j++] = dup_XTree(xpt->children[i], total_szB);
njndbeb5352007-12-04 03:15:23 +0000672 sig_children_szB += xpt->children[i]->szB;
673 } else {
674 insig_children_szB += xpt->children[i]->szB;
njn734b8052007-11-01 04:40:37 +0000675 }
676 }
677
678 // Create the SXPt for the insignificant children, if any, and put it
679 // in the last child entry.
njn734b8052007-11-01 04:40:37 +0000680 if (n_insig_children > 0) {
681 // Nb: We 'n_sxpt_allocs' here because creating an Insig SXPt
682 // doesn't involve a call to dup_XTree().
683 SXPt* insig_sxpt = VG_(malloc)(sizeof(SXPt));
684 n_sxpt_allocs++;
685 insig_sxpt->tag = InsigSXPt;
686 insig_sxpt->szB = insig_children_szB;
687 insig_sxpt->Insig.n_xpts = n_insig_children;
688 sxpt->Sig.children[n_sig_children] = insig_sxpt;
689 }
690 } else {
691 sxpt->Sig.children = NULL;
692 }
693
694 return sxpt;
695}
696
697static void free_SXTree(SXPt* sxpt)
698{
699 Int i;
700 tl_assert(sxpt != NULL);
701
702 switch (sxpt->tag) {
703 case SigSXPt:
704 // Free all children SXPts, then the children array.
705 for (i = 0; i < sxpt->Sig.n_children; i++) {
706 free_SXTree(sxpt->Sig.children[i]);
707 sxpt->Sig.children[i] = NULL;
708 }
709 VG_(free)(sxpt->Sig.children); sxpt->Sig.children = NULL;
710 break;
711
712 case InsigSXPt:
713 break;
714
715 default: tl_assert2(0, "free_SXTree: unknown SXPt tag");
716 }
717
718 // Free the SXPt itself.
719 VG_(free)(sxpt); sxpt = NULL;
720 n_sxpt_frees++;
721}
722
723// Sanity checking: we periodically check the heap XTree with
724// ms_expensive_sanity_check.
725static void sanity_check_XTree(XPt* xpt, XPt* parent)
nethercotec9f36922004-02-14 16:40:02 +0000726{
njn734b8052007-11-01 04:40:37 +0000727 tl_assert(xpt != NULL);
728
729 // Check back-pointer.
730 tl_assert2(xpt->parent == parent,
731 "xpt->parent = %p, parent = %p\n", xpt->parent, parent);
732
733 // Check children counts look sane.
734 tl_assert(xpt->n_children <= xpt->max_children);
735
njndbeb5352007-12-04 03:15:23 +0000736 // Unfortunately, xpt's size is not necessarily equal to the sum of xpt's
737 // children's sizes. See comment at the bottom of get_XCon.
nethercotec9f36922004-02-14 16:40:02 +0000738}
739
njn734b8052007-11-01 04:40:37 +0000740// Sanity checking: we check SXTrees (which are in snapshots) after
741// snapshots are created, before they are deleted, and before they are
742// printed.
743static void sanity_check_SXTree(SXPt* sxpt)
nethercotec9f36922004-02-14 16:40:02 +0000744{
njn734b8052007-11-01 04:40:37 +0000745 Int i;
nethercotec9f36922004-02-14 16:40:02 +0000746
njn734b8052007-11-01 04:40:37 +0000747 tl_assert(sxpt != NULL);
nethercotec9f36922004-02-14 16:40:02 +0000748
njn734b8052007-11-01 04:40:37 +0000749 // Check the sum of any children szBs equals the SXPt's szB. Check the
750 // children at the same time.
751 switch (sxpt->tag) {
752 case SigSXPt: {
753 if (sxpt->Sig.n_children > 0) {
njn734b8052007-11-01 04:40:37 +0000754 for (i = 0; i < sxpt->Sig.n_children; i++) {
755 sanity_check_SXTree(sxpt->Sig.children[i]);
njn734b8052007-11-01 04:40:37 +0000756 }
njn734b8052007-11-01 04:40:37 +0000757 }
758 break;
759 }
760 case InsigSXPt:
761 break; // do nothing
762
763 default: tl_assert2(0, "sanity_check_SXTree: unknown SXPt tag");
764 }
765}
766
767
768//------------------------------------------------------------//
769//--- XCon Operations ---//
770//------------------------------------------------------------//
771
772// This is the limit on the number of removed alloc-fns that can be in a
773// single XCon.
774#define MAX_OVERESTIMATE 50
775#define MAX_IPS (MAX_DEPTH + MAX_OVERESTIMATE)
776
njnb11e5aa2008-01-20 22:30:52 +0000777// This is used for various buffers which can hold function names/IP
778// description. Some C++ names can get really long so 1024 isn't big
779// enough.
780#define BUF_LEN 2048
781
njn734b8052007-11-01 04:40:37 +0000782// Get the stack trace for an XCon, filtering out uninteresting entries:
783// alloc-fns and entries above alloc-fns, and entries below main-or-below-main.
784// Eg: alloc-fn1 / alloc-fn2 / a / b / main / (below main) / c
785// becomes: a / b / main
786// Nb: it's possible to end up with an empty trace, eg. if 'main' is marked
787// as an alloc-fn. This is ok.
788static
789Int get_IPs( ThreadId tid, Bool is_custom_alloc, Addr ips[])
790{
njn734b8052007-11-01 04:40:37 +0000791 Char buf[BUF_LEN];
792 Int n_ips, i, n_alloc_fns_removed;
793 Int overestimate;
794 Bool redo;
795
796 // We ask for a few more IPs than clo_depth suggests we need. Then we
797 // remove every entry that is an alloc-fn. Depending on the
798 // circumstances, we may need to redo it all, asking for more IPs.
799 // Details:
800 // - If the original stack trace is smaller than asked-for, redo=False
801 // - Else if after filtering we have >= clo_depth IPs, redo=False
802 // - Else redo=True
803 // In other words, to redo, we'd have to get a stack trace as big as we
804 // asked for and remove more than 'overestimate' alloc-fns.
805
806 // Main loop.
807 redo = True; // Assume this to begin with.
808 for (overestimate = 3; redo; overestimate += 6) {
809 // This should never happen -- would require MAX_OVERESTIMATE
810 // alloc-fns to be removed from the stack trace.
811 if (overestimate > MAX_OVERESTIMATE)
812 VG_(tool_panic)("get_IPs: ips[] too small, inc. MAX_OVERESTIMATE?");
813
814 // Ask for more IPs than clo_depth suggests we need.
sewardj39f34232007-11-09 23:02:28 +0000815 n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + overestimate,
sewardjb8b79ad2008-03-03 01:35:41 +0000816 NULL/*array to dump SP values in*/,
817 NULL/*array to dump FP values in*/,
818 0/*first_ip_delta*/ );
njn734b8052007-11-01 04:40:37 +0000819 tl_assert(n_ips > 0);
nethercotec9f36922004-02-14 16:40:02 +0000820
njn734b8052007-11-01 04:40:37 +0000821 // If the original stack trace is smaller than asked-for, redo=False.
822 if (n_ips < clo_depth + overestimate) { redo = False; }
nethercotec9f36922004-02-14 16:40:02 +0000823
njn734b8052007-11-01 04:40:37 +0000824 // If it's a non-custom block, we will always remove the first stack
825 // trace entry (which will be one of malloc, __builtin_new, etc).
826 n_alloc_fns_removed = ( is_custom_alloc ? 0 : 1 );
nethercotec9f36922004-02-14 16:40:02 +0000827
njn734b8052007-11-01 04:40:37 +0000828 // Filter out alloc fns. If it's a non-custom block, we remove the
829 // first entry (which will be one of malloc, __builtin_new, etc)
830 // without looking at it, because VG_(get_fnname) is expensive (it
831 // involves calls to VG_(malloc)/VG_(free)).
832 for (i = n_alloc_fns_removed; i < n_ips; i++) {
833 if (VG_(get_fnname)(ips[i], buf, BUF_LEN)) {
834 if (is_alloc_fn(buf)) {
835 n_alloc_fns_removed++;
836 } else {
837 break;
838 }
839 }
840 }
841 // Remove the alloc fns by shuffling the rest down over them.
842 n_ips -= n_alloc_fns_removed;
843 for (i = 0; i < n_ips; i++) {
844 ips[i] = ips[i + n_alloc_fns_removed];
845 }
nethercotec9f36922004-02-14 16:40:02 +0000846
njn734b8052007-11-01 04:40:37 +0000847 // If after filtering we have >= clo_depth IPs, redo=False
848 if (n_ips >= clo_depth) {
849 redo = False;
850 n_ips = clo_depth; // Ignore any IPs below --depth.
851 }
852
853 if (redo) {
854 n_XCon_redos++;
nethercotec9f36922004-02-14 16:40:02 +0000855 }
856 }
njn734b8052007-11-01 04:40:37 +0000857 return n_ips;
858}
nethercotec9f36922004-02-14 16:40:02 +0000859
njn734b8052007-11-01 04:40:37 +0000860// Gets an XCon and puts it in the tree. Returns the XCon's bottom-XPt.
861static XPt* get_XCon( ThreadId tid, Bool is_custom_alloc )
862{
863 Addr ips[MAX_IPS];
864 Int i;
865 XPt* xpt = alloc_xpt;
nethercotec9f36922004-02-14 16:40:02 +0000866
njn734b8052007-11-01 04:40:37 +0000867 // After this call, the IPs we want are in ips[0]..ips[n_ips-1].
868 Int n_ips = get_IPs(tid, is_custom_alloc, ips);
869
870 // Now do the search/insertion of the XCon.
871 for (i = 0; i < n_ips; i++) {
872 Addr ip = ips[i];
873 Int ch;
njnd01fef72005-03-25 23:35:48 +0000874 // Look for IP in xpt's children.
njn734b8052007-11-01 04:40:37 +0000875 // Linear search, ugh -- about 10% of time for konqueror startup tried
876 // caching last result, only hit about 4% for konqueror.
nethercotec9f36922004-02-14 16:40:02 +0000877 // Nb: this search hits about 98% of the time for konqueror
njn734b8052007-11-01 04:40:37 +0000878 for (ch = 0; True; ch++) {
879 if (ch == xpt->n_children) {
880 // IP not found in the children.
881 // Create and add new child XPt, then stop.
882 XPt* new_child_xpt = new_XPt(ip, xpt);
883 add_child_xpt(xpt, new_child_xpt);
884 xpt = new_child_xpt;
885 break;
nethercotec9f36922004-02-14 16:40:02 +0000886
njn734b8052007-11-01 04:40:37 +0000887 } else if (ip == xpt->children[ch]->ip) {
888 // Found the IP in the children, stop.
889 xpt = xpt->children[ch];
nethercotec9f36922004-02-14 16:40:02 +0000890 break;
891 }
nethercotec9f36922004-02-14 16:40:02 +0000892 }
nethercotec9f36922004-02-14 16:40:02 +0000893 }
njndbeb5352007-12-04 03:15:23 +0000894
895 // [Note: several comments refer to this comment. Do not delete it
896 // without updating them.]
897 //
898 // A complication... If all stack traces were well-formed, then the
899 // returned xpt would always be a bottom-XPt. As a consequence, an XPt's
900 // size would always be equal to the sum of its children's sizes, which
901 // is an excellent sanity check.
902 //
903 // Unfortunately, stack traces occasionally are malformed, ie. truncated.
904 // This allows a stack trace to be a sub-trace of another, eg. a/b/c is a
905 // sub-trace of a/b/c/d. So we can't assume this xpt is a bottom-XPt;
906 // nor can we do sanity check an XPt's size against its children's sizes.
907 // This is annoying, but must be dealt with. (Older versions of Massif
908 // had this assertion in, and it was reported to fail by real users a
909 // couple of times.) Even more annoyingly, I can't come up with a simple
910 // test case that exhibit such a malformed stack trace, so I can't
911 // regression test it. Sigh.
912 //
913 // However, we can print a warning, so that if it happens (unexpectedly)
914 // in existing regression tests we'll know. Also, it warns users that
915 // the output snapshots may not add up the way they might expect.
916 //
917 //tl_assert(0 == xpt->n_children); // Must be bottom-XPt
918 if (0 != xpt->n_children) {
919 static Int n_moans = 0;
920 if (n_moans < 3) {
921 VG_(message)(Vg_UserMsg,
922 "Warning: Malformed stack trace detected. In Massif's output,");
923 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000924 " the size of an entry's child entries may not sum up");
njndbeb5352007-12-04 03:15:23 +0000925 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000926 " to the entry's size as they normally do.");
njndbeb5352007-12-04 03:15:23 +0000927 n_moans++;
928 if (3 == n_moans)
929 VG_(message)(Vg_UserMsg,
njnd59c9d52007-12-04 03:27:40 +0000930 " (And Massif now won't warn about this again.)");
njndbeb5352007-12-04 03:15:23 +0000931 }
932 }
njn734b8052007-11-01 04:40:37 +0000933 return xpt;
nethercotec9f36922004-02-14 16:40:02 +0000934}
935
njn734b8052007-11-01 04:40:37 +0000936// Update 'szB' of every XPt in the XCon, by percolating upwards.
937static void update_XCon(XPt* xpt, SSizeT space_delta)
nethercotec9f36922004-02-14 16:40:02 +0000938{
njnca82cc02004-11-22 17:18:48 +0000939 tl_assert(True == clo_heap);
njnca82cc02004-11-22 17:18:48 +0000940 tl_assert(NULL != xpt);
nethercotec9f36922004-02-14 16:40:02 +0000941
njn734b8052007-11-01 04:40:37 +0000942 if (0 == space_delta)
943 return;
944
nethercotec9f36922004-02-14 16:40:02 +0000945 while (xpt != alloc_xpt) {
njn734b8052007-11-01 04:40:37 +0000946 if (space_delta < 0) tl_assert(xpt->szB >= -space_delta);
947 xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000948 xpt = xpt->parent;
njn734b8052007-11-01 04:40:37 +0000949 }
950 if (space_delta < 0) tl_assert(alloc_xpt->szB >= -space_delta);
951 alloc_xpt->szB += space_delta;
nethercotec9f36922004-02-14 16:40:02 +0000952}
953
954
njn734b8052007-11-01 04:40:37 +0000955//------------------------------------------------------------//
956//--- Snapshots ---//
957//------------------------------------------------------------//
958
959// Snapshots are done in a way so that we always have a reasonable number of
960// them. We start by taking them quickly. Once we hit our limit, we cull
961// some (eg. half), and start taking them more slowly. Once we hit the
962// limit again, we again cull and then take them even more slowly, and so
963// on.
964
njn1a2741a2007-11-26 21:59:04 +0000965// Time is measured either in i or ms or bytes, depending on the --time-unit
njn734b8052007-11-01 04:40:37 +0000966// option. It's a Long because it can exceed 32-bits reasonably easily, and
967// because we need to allow negative values to represent unset times.
968typedef Long Time;
969
970#define UNUSED_SNAPSHOT_TIME -333 // A conspicuous negative number.
971
972typedef
973 enum {
974 Normal = 77,
975 Peak,
976 Unused
977 }
978 SnapshotKind;
nethercotec9f36922004-02-14 16:40:02 +0000979
980typedef
981 struct {
njn734b8052007-11-01 04:40:37 +0000982 SnapshotKind kind;
983 Time time;
984 SizeT heap_szB;
njn32397c02007-11-10 04:08:08 +0000985 SizeT heap_extra_szB;// Heap slop + admin bytes.
njn734b8052007-11-01 04:40:37 +0000986 SizeT stacks_szB;
987 SXPt* alloc_sxpt; // Heap XTree root, if a detailed snapshot,
njn32397c02007-11-10 04:08:08 +0000988 } // otherwise NULL.
njn734b8052007-11-01 04:40:37 +0000989 Snapshot;
nethercotec9f36922004-02-14 16:40:02 +0000990
njn734b8052007-11-01 04:40:37 +0000991static UInt next_snapshot_i = 0; // Index of where next snapshot will go.
992static Snapshot* snapshots; // Array of snapshots.
993
994static Bool is_snapshot_in_use(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +0000995{
njn734b8052007-11-01 04:40:37 +0000996 if (Unused == snapshot->kind) {
997 // If snapshot is unused, check all the fields are unset.
998 tl_assert(snapshot->time == UNUSED_SNAPSHOT_TIME);
njn32397c02007-11-10 04:08:08 +0000999 tl_assert(snapshot->heap_extra_szB == 0);
njn734b8052007-11-01 04:40:37 +00001000 tl_assert(snapshot->heap_szB == 0);
1001 tl_assert(snapshot->stacks_szB == 0);
1002 tl_assert(snapshot->alloc_sxpt == NULL);
1003 return False;
nethercotec9f36922004-02-14 16:40:02 +00001004 } else {
njn734b8052007-11-01 04:40:37 +00001005 tl_assert(snapshot->time != UNUSED_SNAPSHOT_TIME);
1006 return True;
nethercotec9f36922004-02-14 16:40:02 +00001007 }
1008}
1009
njn734b8052007-11-01 04:40:37 +00001010static Bool is_detailed_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001011{
njn734b8052007-11-01 04:40:37 +00001012 return (snapshot->alloc_sxpt ? True : False);
nethercotec9f36922004-02-14 16:40:02 +00001013}
1014
njn734b8052007-11-01 04:40:37 +00001015static Bool is_uncullable_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001016{
njn734b8052007-11-01 04:40:37 +00001017 return &snapshots[0] == snapshot // First snapshot
1018 || &snapshots[next_snapshot_i-1] == snapshot // Last snapshot
1019 || snapshot->kind == Peak; // Peak snapshot
nethercotec9f36922004-02-14 16:40:02 +00001020}
1021
njn734b8052007-11-01 04:40:37 +00001022static void sanity_check_snapshot(Snapshot* snapshot)
nethercotec9f36922004-02-14 16:40:02 +00001023{
njn734b8052007-11-01 04:40:37 +00001024 if (snapshot->alloc_sxpt) {
1025 sanity_check_SXTree(snapshot->alloc_sxpt);
1026 }
nethercotec9f36922004-02-14 16:40:02 +00001027}
1028
njn734b8052007-11-01 04:40:37 +00001029// All the used entries should look used, all the unused ones should be clear.
1030static void sanity_check_snapshots_array(void)
1031{
1032 Int i;
1033 for (i = 0; i < next_snapshot_i; i++) {
1034 tl_assert( is_snapshot_in_use( & snapshots[i] ));
1035 }
1036 for ( ; i < clo_max_snapshots; i++) {
1037 tl_assert(!is_snapshot_in_use( & snapshots[i] ));
1038 }
1039}
nethercotec9f36922004-02-14 16:40:02 +00001040
njn734b8052007-11-01 04:40:37 +00001041// This zeroes all the fields in the snapshot, but does not free the heap
1042// XTree if present. It also does a sanity check unless asked not to; we
1043// can't sanity check at startup when clearing the initial snapshots because
1044// they're full of junk.
1045static void clear_snapshot(Snapshot* snapshot, Bool do_sanity_check)
1046{
1047 if (do_sanity_check) sanity_check_snapshot(snapshot);
1048 snapshot->kind = Unused;
1049 snapshot->time = UNUSED_SNAPSHOT_TIME;
njn32397c02007-11-10 04:08:08 +00001050 snapshot->heap_extra_szB = 0;
njn734b8052007-11-01 04:40:37 +00001051 snapshot->heap_szB = 0;
1052 snapshot->stacks_szB = 0;
1053 snapshot->alloc_sxpt = NULL;
1054}
1055
1056// This zeroes all the fields in the snapshot, and frees the heap XTree if
1057// present.
1058static void delete_snapshot(Snapshot* snapshot)
1059{
1060 // Nb: if there's an XTree, we free it after calling clear_snapshot,
1061 // because clear_snapshot does a sanity check which includes checking the
1062 // XTree.
1063 SXPt* tmp_sxpt = snapshot->alloc_sxpt;
1064 clear_snapshot(snapshot, /*do_sanity_check*/True);
1065 if (tmp_sxpt) {
1066 free_SXTree(tmp_sxpt);
1067 }
1068}
1069
1070static void VERB_snapshot(Int verbosity, Char* prefix, Int i)
1071{
1072 Snapshot* snapshot = &snapshots[i];
1073 Char* suffix;
1074 switch (snapshot->kind) {
1075 case Peak: suffix = "p"; break;
1076 case Normal: suffix = ( is_detailed_snapshot(snapshot) ? "d" : "." ); break;
1077 case Unused: suffix = "u"; break;
1078 default:
1079 tl_assert2(0, "VERB_snapshot: unknown snapshot kind: %d", snapshot->kind);
1080 }
njn32397c02007-11-10 04:08:08 +00001081 VERB(verbosity, "%s S%s%3d (t:%lld, hp:%ld, ex:%ld, st:%ld)",
njn734b8052007-11-01 04:40:37 +00001082 prefix, suffix, i,
1083 snapshot->time,
1084 snapshot->heap_szB,
njn32397c02007-11-10 04:08:08 +00001085 snapshot->heap_extra_szB,
njn734b8052007-11-01 04:40:37 +00001086 snapshot->stacks_szB
1087 );
1088}
1089
1090// Cull half the snapshots; we choose those that represent the smallest
1091// time-spans, because that gives us the most even distribution of snapshots
1092// over time. (It's possible to lose interesting spikes, however.)
1093//
1094// Algorithm for N snapshots: We find the snapshot representing the smallest
1095// timeframe, and remove it. We repeat this until (N/2) snapshots are gone.
1096// We have to do this one snapshot at a time, rather than finding the (N/2)
1097// smallest snapshots in one hit, because when a snapshot is removed, its
1098// neighbours immediately cover greater timespans. So it's O(N^2), but N is
1099// small, and it's not done very often.
1100//
1101// Once we're done, we return the new smallest interval between snapshots.
1102// That becomes our minimum time interval.
1103static UInt cull_snapshots(void)
1104{
1105 Int i, jp, j, jn, min_timespan_i;
1106 Int n_deleted = 0;
1107 Time min_timespan;
1108
1109 n_cullings++;
1110
1111 // Sets j to the index of the first not-yet-removed snapshot at or after i
1112 #define FIND_SNAPSHOT(i, j) \
1113 for (j = i; \
1114 j < clo_max_snapshots && !is_snapshot_in_use(&snapshots[j]); \
1115 j++) { }
1116
1117 VERB(2, "Culling...");
1118
1119 // First we remove enough snapshots by clearing them in-place. Once
1120 // that's done, we can slide the remaining ones down.
1121 for (i = 0; i < clo_max_snapshots/2; i++) {
1122 // Find the snapshot representing the smallest timespan. The timespan
1123 // for snapshot n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
1124 // snapshot A and B. We don't consider the first and last snapshots for
1125 // removal.
1126 Snapshot* min_snapshot;
1127 Int min_j;
1128
1129 // Initial triple: (prev, curr, next) == (jp, j, jn)
1130 // Initial min_timespan is the first one.
1131 jp = 0;
1132 FIND_SNAPSHOT(1, j);
1133 FIND_SNAPSHOT(j+1, jn);
1134 min_timespan = 0x7fffffffffffffffLL;
1135 min_j = -1;
1136 while (jn < clo_max_snapshots) {
1137 Time timespan = snapshots[jn].time - snapshots[jp].time;
1138 tl_assert(timespan >= 0);
1139 // Nb: We never cull the peak snapshot.
1140 if (Peak != snapshots[j].kind && timespan < min_timespan) {
1141 min_timespan = timespan;
1142 min_j = j;
1143 }
1144 // Move on to next triple
1145 jp = j;
1146 j = jn;
1147 FIND_SNAPSHOT(jn+1, jn);
1148 }
1149 // We've found the least important snapshot, now delete it. First
1150 // print it if necessary.
1151 tl_assert(-1 != min_j); // Check we found a minimum.
1152 min_snapshot = & snapshots[ min_j ];
1153 if (VG_(clo_verbosity) > 1) {
1154 Char buf[64];
1155 VG_(snprintf)(buf, 64, " %3d (t-span = %lld)", i, min_timespan);
1156 VERB_snapshot(2, buf, min_j);
1157 }
1158 delete_snapshot(min_snapshot);
1159 n_deleted++;
1160 }
1161
1162 // Slide down the remaining snapshots over the removed ones. First set i
1163 // to point to the first empty slot, and j to the first full slot after
1164 // i. Then slide everything down.
1165 for (i = 0; is_snapshot_in_use( &snapshots[i] ); i++) { }
1166 for (j = i; !is_snapshot_in_use( &snapshots[j] ); j++) { }
1167 for ( ; j < clo_max_snapshots; j++) {
1168 if (is_snapshot_in_use( &snapshots[j] )) {
1169 snapshots[i++] = snapshots[j];
1170 clear_snapshot(&snapshots[j], /*do_sanity_check*/True);
1171 }
1172 }
1173 next_snapshot_i = i;
1174
1175 // Check snapshots array looks ok after changes.
1176 sanity_check_snapshots_array();
1177
1178 // Find the minimum timespan remaining; that will be our new minimum
1179 // time interval. Note that above we were finding timespans by measuring
1180 // two intervals around a snapshot that was under consideration for
1181 // deletion. Here we only measure single intervals because all the
1182 // deletions have occurred.
1183 //
1184 // But we have to be careful -- some snapshots (eg. snapshot 0, and the
1185 // peak snapshot) are uncullable. If two uncullable snapshots end up
1186 // next to each other, they'll never be culled (assuming the peak doesn't
1187 // change), and the time gap between them will not change. However, the
1188 // time between the remaining cullable snapshots will grow ever larger.
1189 // This means that the min_timespan found will always be that between the
1190 // two uncullable snapshots, and it will be much smaller than it should
1191 // be. To avoid this problem, when computing the minimum timespan, we
1192 // ignore any timespans between two uncullable snapshots.
1193 tl_assert(next_snapshot_i > 1);
1194 min_timespan = 0x7fffffffffffffffLL;
1195 min_timespan_i = -1;
1196 for (i = 1; i < next_snapshot_i; i++) {
1197 if (is_uncullable_snapshot(&snapshots[i]) &&
1198 is_uncullable_snapshot(&snapshots[i-1]))
1199 {
1200 VERB(2, "(Ignoring interval %d--%d when computing minimum)", i-1, i);
1201 } else {
1202 Time timespan = snapshots[i].time - snapshots[i-1].time;
1203 tl_assert(timespan >= 0);
1204 if (timespan < min_timespan) {
1205 min_timespan = timespan;
1206 min_timespan_i = i;
1207 }
1208 }
1209 }
1210 tl_assert(-1 != min_timespan_i); // Check we found a minimum.
1211
1212 // Print remaining snapshots, if necessary.
1213 if (VG_(clo_verbosity) > 1) {
1214 VERB(2, "Finished culling (%3d of %3d deleted)",
1215 n_deleted, clo_max_snapshots);
1216 for (i = 0; i < next_snapshot_i; i++) {
1217 VERB_snapshot(2, " post-cull", i);
1218 }
1219 VERB(2, "New time interval = %lld (between snapshots %d and %d)",
1220 min_timespan, min_timespan_i-1, min_timespan_i);
1221 }
1222
1223 return min_timespan;
1224}
1225
1226static Time get_time(void)
1227{
1228 // Get current time, in whatever time unit we're using.
njn1a2741a2007-11-26 21:59:04 +00001229 if (clo_time_unit == TimeI) {
1230 return guest_instrs_executed;
1231 } else if (clo_time_unit == TimeMS) {
njn734b8052007-11-01 04:40:37 +00001232 // Some stuff happens between the millisecond timer being initialised
1233 // to zero and us taking our first snapshot. We determine that time
1234 // gap so we can subtract it from all subsequent times so that our
1235 // first snapshot is considered to be at t = 0ms. Unfortunately, a
1236 // bunch of symbols get read after the first snapshot is taken but
1237 // before the second one (which is triggered by the first allocation),
1238 // so when the time-unit is 'ms' we always have a big gap between the
1239 // first two snapshots. But at least users won't have to wonder why
1240 // the first snapshot isn't at t=0.
1241 static Bool is_first_get_time = True;
1242 static Time start_time_ms;
1243 if (is_first_get_time) {
1244 start_time_ms = VG_(read_millisecond_timer)();
1245 is_first_get_time = False;
1246 return 0;
1247 } else {
1248 return VG_(read_millisecond_timer)() - start_time_ms;
1249 }
1250 } else if (clo_time_unit == TimeB) {
1251 return total_allocs_deallocs_szB;
1252 } else {
1253 tl_assert2(0, "bad --time-unit value");
1254 }
1255}
1256
1257// Take a snapshot, and only that -- decisions on whether to take a
1258// snapshot, or what kind of snapshot, are made elsewhere.
1259static void
1260take_snapshot(Snapshot* snapshot, SnapshotKind kind, Time time,
1261 Bool is_detailed, Char* what)
1262{
1263 tl_assert(!is_snapshot_in_use(snapshot));
1264 tl_assert(have_started_executing_code);
1265
1266 // Heap and heap admin.
1267 if (clo_heap) {
1268 snapshot->heap_szB = heap_szB;
1269 if (is_detailed) {
njn32397c02007-11-10 04:08:08 +00001270 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001271 snapshot->alloc_sxpt = dup_XTree(alloc_xpt, total_szB);
1272 tl_assert( alloc_xpt->szB == heap_szB);
1273 tl_assert(snapshot->alloc_sxpt->szB == heap_szB);
1274 }
njn32397c02007-11-10 04:08:08 +00001275 snapshot->heap_extra_szB = heap_extra_szB;
njn734b8052007-11-01 04:40:37 +00001276 }
1277
1278 // Stack(s).
1279 if (clo_stacks) {
1280 snapshot->stacks_szB = stacks_szB;
1281 }
1282
1283 // Rest of snapshot.
1284 snapshot->kind = kind;
1285 snapshot->time = time;
1286 sanity_check_snapshot(snapshot);
1287
1288 // Update stats.
1289 if (Peak == kind) n_peak_snapshots++;
1290 if (is_detailed) n_detailed_snapshots++;
1291 n_real_snapshots++;
1292}
1293
1294
1295// Take a snapshot, if it's time, or if we've hit a peak.
1296static void
1297maybe_take_snapshot(SnapshotKind kind, Char* what)
1298{
1299 // 'min_time_interval' is the minimum time interval between snapshots.
1300 // If we try to take a snapshot and less than this much time has passed,
1301 // we don't take it. It gets larger as the program runs longer. It's
1302 // initialised to zero so that we begin by taking snapshots as quickly as
1303 // possible.
1304 static Time min_time_interval = 0;
1305 // Zero allows startup snapshot.
1306 static Time earliest_possible_time_of_next_snapshot = 0;
1307 static Int n_snapshots_since_last_detailed = 0;
1308 static Int n_skipped_snapshots_since_last_snapshot = 0;
1309
1310 Snapshot* snapshot;
1311 Bool is_detailed;
1312 Time time = get_time();
1313
1314 switch (kind) {
1315 case Normal:
1316 // Only do a snapshot if it's time.
1317 if (time < earliest_possible_time_of_next_snapshot) {
1318 n_skipped_snapshots++;
1319 n_skipped_snapshots_since_last_snapshot++;
1320 return;
1321 }
1322 is_detailed = (clo_detailed_freq-1 == n_snapshots_since_last_detailed);
1323 break;
1324
1325 case Peak: {
1326 // Because we're about to do a deallocation, we're coming down from a
1327 // local peak. If it is (a) actually a global peak, and (b) a certain
1328 // amount bigger than the previous peak, then we take a peak snapshot.
1329 // By not taking a snapshot for every peak, we save a lot of effort --
1330 // because many peaks remain peak only for a short time.
njn32397c02007-11-10 04:08:08 +00001331 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
njn734b8052007-11-01 04:40:37 +00001332 SizeT excess_szB_for_new_peak =
njn62721e92007-11-11 22:15:58 +00001333 (SizeT)((peak_snapshot_total_szB * clo_peak_inaccuracy) / 100);
njn734b8052007-11-01 04:40:37 +00001334 if (total_szB <= peak_snapshot_total_szB + excess_szB_for_new_peak) {
1335 return;
1336 }
1337 is_detailed = True;
1338 break;
1339 }
1340
1341 default:
1342 tl_assert2(0, "maybe_take_snapshot: unrecognised snapshot kind");
1343 }
1344
1345 // Take the snapshot.
1346 snapshot = & snapshots[next_snapshot_i];
1347 take_snapshot(snapshot, kind, time, is_detailed, what);
1348
1349 // Record if it was detailed.
1350 if (is_detailed) {
1351 n_snapshots_since_last_detailed = 0;
1352 } else {
1353 n_snapshots_since_last_detailed++;
1354 }
1355
1356 // Update peak data, if it's a Peak snapshot.
1357 if (Peak == kind) {
1358 Int i, number_of_peaks_snapshots_found = 0;
1359
1360 // Sanity check the size, then update our recorded peak.
1361 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00001362 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00001363 tl_assert2(snapshot_total_szB > peak_snapshot_total_szB,
1364 "%ld, %ld\n", snapshot_total_szB, peak_snapshot_total_szB);
1365 peak_snapshot_total_szB = snapshot_total_szB;
1366
1367 // Find the old peak snapshot, if it exists, and mark it as normal.
1368 for (i = 0; i < next_snapshot_i; i++) {
1369 if (Peak == snapshots[i].kind) {
1370 snapshots[i].kind = Normal;
1371 number_of_peaks_snapshots_found++;
1372 }
1373 }
1374 tl_assert(number_of_peaks_snapshots_found <= 1);
1375 }
1376
1377 // Finish up verbosity and stats stuff.
1378 if (n_skipped_snapshots_since_last_snapshot > 0) {
1379 VERB(2, " (skipped %d snapshot%s)",
1380 n_skipped_snapshots_since_last_snapshot,
1381 ( n_skipped_snapshots_since_last_snapshot == 1 ? "" : "s") );
1382 }
1383 VERB_snapshot(2, what, next_snapshot_i);
1384 n_skipped_snapshots_since_last_snapshot = 0;
1385
1386 // Cull the entries, if our snapshot table is full.
1387 next_snapshot_i++;
1388 if (clo_max_snapshots == next_snapshot_i) {
1389 min_time_interval = cull_snapshots();
1390 }
1391
1392 // Work out the earliest time when the next snapshot can happen.
1393 earliest_possible_time_of_next_snapshot = time + min_time_interval;
1394}
1395
1396
1397//------------------------------------------------------------//
1398//--- Sanity checking ---//
1399//------------------------------------------------------------//
1400
1401static Bool ms_cheap_sanity_check ( void )
1402{
1403 return True; // Nothing useful we can cheaply check.
1404}
1405
1406static Bool ms_expensive_sanity_check ( void )
1407{
1408 sanity_check_XTree(alloc_xpt, /*parent*/NULL);
1409 sanity_check_snapshots_array();
1410 return True;
1411}
1412
1413
1414//------------------------------------------------------------//
1415//--- Heap management ---//
1416//------------------------------------------------------------//
1417
1418// Metadata for heap blocks. Each one contains a pointer to a bottom-XPt,
1419// which is a foothold into the XCon at which it was allocated. From
1420// HP_Chunks, XPt 'space' fields are incremented (at allocation) and
1421// decremented (at deallocation).
1422//
1423// Nb: first two fields must match core's VgHashNode.
1424typedef
1425 struct _HP_Chunk {
1426 struct _HP_Chunk* next;
njn32397c02007-11-10 04:08:08 +00001427 Addr data; // Ptr to actual block
1428 SizeT req_szB; // Size requested
1429 SizeT slop_szB; // Extra bytes given above those requested
1430 XPt* where; // Where allocated; bottom-XPt
njn734b8052007-11-01 04:40:37 +00001431 }
1432 HP_Chunk;
1433
1434static VgHashTable malloc_list = NULL; // HP_Chunks
1435
1436static void update_alloc_stats(SSizeT szB_delta)
1437{
1438 // Update total_allocs_deallocs_szB.
1439 if (szB_delta < 0) szB_delta = -szB_delta;
1440 total_allocs_deallocs_szB += szB_delta;
1441}
1442
njn32397c02007-11-10 04:08:08 +00001443static void update_heap_stats(SSizeT heap_szB_delta, Int heap_extra_szB_delta)
njn734b8052007-11-01 04:40:37 +00001444{
njn32397c02007-11-10 04:08:08 +00001445 if (heap_szB_delta < 0)
1446 tl_assert(heap_szB >= -heap_szB_delta);
1447 if (heap_extra_szB_delta < 0)
1448 tl_assert(heap_extra_szB >= -heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001449
njn32397c02007-11-10 04:08:08 +00001450 heap_extra_szB += heap_extra_szB_delta;
1451 heap_szB += heap_szB_delta;
1452
1453 update_alloc_stats(heap_szB_delta + heap_extra_szB_delta);
njn734b8052007-11-01 04:40:37 +00001454}
nethercotec9f36922004-02-14 16:40:02 +00001455
nethercote159dfef2004-09-13 13:27:30 +00001456static
njn32397c02007-11-10 04:08:08 +00001457void* new_block ( ThreadId tid, void* p, SizeT req_szB, SizeT req_alignB,
njn57735902004-11-25 18:04:54 +00001458 Bool is_zeroed )
nethercotec9f36922004-02-14 16:40:02 +00001459{
1460 HP_Chunk* hc;
njn734b8052007-11-01 04:40:37 +00001461 Bool is_custom_alloc = (NULL != p);
njn32397c02007-11-10 04:08:08 +00001462 SizeT actual_szB, slop_szB;
1463
1464 if (req_szB < 0) return NULL;
nethercotec9f36922004-02-14 16:40:02 +00001465
nethercote57e36b32004-07-10 14:56:28 +00001466 // Allocate and zero if necessary
1467 if (!p) {
njn32397c02007-11-10 04:08:08 +00001468 p = VG_(cli_malloc)( req_alignB, req_szB );
nethercote57e36b32004-07-10 14:56:28 +00001469 if (!p) {
nethercote57e36b32004-07-10 14:56:28 +00001470 return NULL;
1471 }
njn32397c02007-11-10 04:08:08 +00001472 if (is_zeroed) VG_(memset)(p, 0, req_szB);
1473 actual_szB = VG_(malloc_usable_size)(p);
1474 tl_assert(actual_szB >= req_szB);
1475 slop_szB = actual_szB - req_szB;
1476 } else {
1477 slop_szB = 0;
nethercote57e36b32004-07-10 14:56:28 +00001478 }
1479
njnf1c5def2005-08-11 02:17:07 +00001480 // Make new HP_Chunk node, add to malloc_list
njn32397c02007-11-10 04:08:08 +00001481 hc = VG_(malloc)(sizeof(HP_Chunk));
1482 hc->req_szB = req_szB;
1483 hc->slop_szB = slop_szB;
1484 hc->data = (Addr)p;
1485 hc->where = NULL;
njn246a9d22005-08-14 06:24:20 +00001486 VG_(HT_add_node)(malloc_list, hc);
nethercote57e36b32004-07-10 14:56:28 +00001487
njn734b8052007-11-01 04:40:37 +00001488 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001489 VERB(3, "<<< new_mem_heap (%lu, %lu)", req_szB, slop_szB);
njn734b8052007-11-01 04:40:37 +00001490
1491 // Update statistics.
1492 n_heap_allocs++;
1493
1494 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001495 update_heap_stats(req_szB, clo_heap_admin + slop_szB);
njn734b8052007-11-01 04:40:37 +00001496
1497 // Update XTree.
1498 hc->where = get_XCon( tid, is_custom_alloc );
njn32397c02007-11-10 04:08:08 +00001499 update_XCon(hc->where, req_szB);
njn734b8052007-11-01 04:40:37 +00001500
1501 // Maybe take a snapshot.
1502 maybe_take_snapshot(Normal, " alloc");
1503
1504 VERB(3, ">>>");
1505 }
nethercotec9f36922004-02-14 16:40:02 +00001506
nethercotec9f36922004-02-14 16:40:02 +00001507 return p;
1508}
1509
1510static __inline__
1511void die_block ( void* p, Bool custom_free )
1512{
njnf1c5def2005-08-11 02:17:07 +00001513 HP_Chunk* hc;
nethercotec9f36922004-02-14 16:40:02 +00001514
njnf1c5def2005-08-11 02:17:07 +00001515 // Remove HP_Chunk from malloc_list
njn9a463242005-08-16 03:29:50 +00001516 hc = VG_(HT_remove)(malloc_list, (UWord)p);
njn734b8052007-11-01 04:40:37 +00001517 if (NULL == hc) {
njn5cc5d7e2005-08-11 02:09:25 +00001518 return; // must have been a bogus free()
njn734b8052007-11-01 04:40:37 +00001519 }
nethercotec9f36922004-02-14 16:40:02 +00001520
njn734b8052007-11-01 04:40:37 +00001521 if (clo_heap) {
1522 VERB(3, "<<< die_mem_heap");
nethercotec9f36922004-02-14 16:40:02 +00001523
njn734b8052007-11-01 04:40:37 +00001524 // Update statistics
1525 n_heap_frees++;
nethercote57e36b32004-07-10 14:56:28 +00001526
njn734b8052007-11-01 04:40:37 +00001527 // Maybe take a peak snapshot, since it's a deallocation.
1528 maybe_take_snapshot(Peak, "de-PEAK");
1529
1530 // Update heap stats.
njn32397c02007-11-10 04:08:08 +00001531 update_heap_stats(-hc->req_szB, -clo_heap_admin - hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001532
1533 // Update XTree.
njn32397c02007-11-10 04:08:08 +00001534 update_XCon(hc->where, -hc->req_szB);
njn734b8052007-11-01 04:40:37 +00001535
1536 // Maybe take a snapshot.
1537 maybe_take_snapshot(Normal, "dealloc");
1538
njn32397c02007-11-10 04:08:08 +00001539 VERB(3, ">>> (-%lu, -%lu)", hc->req_szB, hc->slop_szB);
njn734b8052007-11-01 04:40:37 +00001540 }
1541
1542 // Actually free the chunk, and the heap block (if necessary)
1543 VG_(free)( hc ); hc = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001544 if (!custom_free)
1545 VG_(cli_free)( p );
nethercotec9f36922004-02-14 16:40:02 +00001546}
1547
njn734b8052007-11-01 04:40:37 +00001548static __inline__
njn32397c02007-11-10 04:08:08 +00001549void* renew_block ( ThreadId tid, void* p_old, SizeT new_req_szB )
nethercotec9f36922004-02-14 16:40:02 +00001550{
njn734b8052007-11-01 04:40:37 +00001551 HP_Chunk* hc;
1552 void* p_new;
njn32397c02007-11-10 04:08:08 +00001553 SizeT old_req_szB, old_slop_szB, new_slop_szB, new_actual_szB;
njn734b8052007-11-01 04:40:37 +00001554 XPt *old_where, *new_where;
1555
1556 // Remove the old block
1557 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
1558 if (hc == NULL) {
1559 return NULL; // must have been a bogus realloc()
1560 }
1561
njn32397c02007-11-10 04:08:08 +00001562 old_req_szB = hc->req_szB;
1563 old_slop_szB = hc->slop_szB;
njn734b8052007-11-01 04:40:37 +00001564
1565 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001566 VERB(3, "<<< renew_mem_heap (%lu)", new_req_szB);
njn734b8052007-11-01 04:40:37 +00001567
1568 // Update statistics
1569 n_heap_reallocs++;
1570
1571 // Maybe take a peak snapshot, if it's (effectively) a deallocation.
njn32397c02007-11-10 04:08:08 +00001572 if (new_req_szB < old_req_szB) {
njn734b8052007-11-01 04:40:37 +00001573 maybe_take_snapshot(Peak, "re-PEAK");
1574 }
njn734b8052007-11-01 04:40:37 +00001575 }
1576
1577 // Actually do the allocation, if necessary.
njn32397c02007-11-10 04:08:08 +00001578 if (new_req_szB <= old_req_szB + old_slop_szB) {
1579 // New size is smaller or same; block not moved.
njn734b8052007-11-01 04:40:37 +00001580 p_new = p_old;
njn32397c02007-11-10 04:08:08 +00001581 new_slop_szB = old_slop_szB + (old_req_szB - new_req_szB);
njn734b8052007-11-01 04:40:37 +00001582
1583 } else {
njn32397c02007-11-10 04:08:08 +00001584 // New size is bigger; make new block, copy shared contents, free old.
1585 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_req_szB);
1586 if (!p_new) {
1587 // Nb: if realloc fails, NULL is returned but the old block is not
1588 // touched. What an awful function.
1589 return NULL;
njn734b8052007-11-01 04:40:37 +00001590 }
njn32397c02007-11-10 04:08:08 +00001591 VG_(memcpy)(p_new, p_old, old_req_szB);
1592 VG_(cli_free)(p_old);
1593 new_actual_szB = VG_(malloc_usable_size)(p_new);
1594 tl_assert(new_actual_szB >= new_req_szB);
1595 new_slop_szB = new_actual_szB - new_req_szB;
njn734b8052007-11-01 04:40:37 +00001596 }
1597
1598 if (p_new) {
1599 // Update HP_Chunk.
njn32397c02007-11-10 04:08:08 +00001600 hc->data = (Addr)p_new;
1601 hc->req_szB = new_req_szB;
1602 hc->slop_szB = new_slop_szB;
1603 old_where = hc->where;
1604 hc->where = NULL;
njn734b8052007-11-01 04:40:37 +00001605
1606 // Update XTree.
1607 if (clo_heap) {
1608 new_where = get_XCon( tid, /*custom_malloc*/False);
1609 hc->where = new_where;
njn32397c02007-11-10 04:08:08 +00001610 update_XCon(old_where, -old_req_szB);
1611 update_XCon(new_where, new_req_szB);
njn734b8052007-11-01 04:40:37 +00001612 }
1613 }
1614
1615 // Now insert the new hc (with a possibly new 'data' field) into
1616 // malloc_list. If this realloc() did not increase the memory size, we
1617 // will have removed and then re-added hc unnecessarily. But that's ok
1618 // because shrinking a block with realloc() is (presumably) much rarer
1619 // than growing it, and this way simplifies the growing case.
1620 VG_(HT_add_node)(malloc_list, hc);
1621
njn734b8052007-11-01 04:40:37 +00001622 if (clo_heap) {
njn32397c02007-11-10 04:08:08 +00001623 // Update heap stats.
1624 update_heap_stats(new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
1625
1626 // Maybe take a snapshot.
njn734b8052007-11-01 04:40:37 +00001627 maybe_take_snapshot(Normal, "realloc");
1628
njn32397c02007-11-10 04:08:08 +00001629 VERB(3, ">>> (%ld, %ld)",
1630 new_req_szB - old_req_szB, new_slop_szB - old_slop_szB);
njn734b8052007-11-01 04:40:37 +00001631 }
1632
1633 return p_new;
nethercotec9f36922004-02-14 16:40:02 +00001634}
1635
njn734b8052007-11-01 04:40:37 +00001636
1637//------------------------------------------------------------//
1638//--- malloc() et al replacement wrappers ---//
1639//------------------------------------------------------------//
1640
1641static void* ms_malloc ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001642{
njn734b8052007-11-01 04:40:37 +00001643 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001644}
1645
njn734b8052007-11-01 04:40:37 +00001646static void* ms___builtin_new ( ThreadId tid, SizeT szB )
nethercotec9f36922004-02-14 16:40:02 +00001647{
njn734b8052007-11-01 04:40:37 +00001648 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
nethercotec9f36922004-02-14 16:40:02 +00001649}
1650
njn734b8052007-11-01 04:40:37 +00001651static void* ms___builtin_vec_new ( ThreadId tid, SizeT szB )
fitzhardinge51f3ff12004-03-04 22:42:03 +00001652{
njn734b8052007-11-01 04:40:37 +00001653 return new_block( tid, NULL, szB, VG_(clo_alignment), /*is_zeroed*/False );
1654}
1655
1656static void* ms_calloc ( ThreadId tid, SizeT m, SizeT szB )
1657{
1658 return new_block( tid, NULL, m*szB, VG_(clo_alignment), /*is_zeroed*/True );
1659}
1660
1661static void *ms_memalign ( ThreadId tid, SizeT alignB, SizeT szB )
1662{
1663 return new_block( tid, NULL, szB, alignB, False );
fitzhardinge51f3ff12004-03-04 22:42:03 +00001664}
1665
njn51d827b2005-05-09 01:02:08 +00001666static void ms_free ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001667{
1668 die_block( p, /*custom_free*/False );
1669}
1670
njn51d827b2005-05-09 01:02:08 +00001671static void ms___builtin_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001672{
1673 die_block( p, /*custom_free*/False);
1674}
1675
njn51d827b2005-05-09 01:02:08 +00001676static void ms___builtin_vec_delete ( ThreadId tid, void* p )
nethercotec9f36922004-02-14 16:40:02 +00001677{
1678 die_block( p, /*custom_free*/False );
1679}
1680
njn734b8052007-11-01 04:40:37 +00001681static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_szB )
nethercotec9f36922004-02-14 16:40:02 +00001682{
njn734b8052007-11-01 04:40:37 +00001683 return renew_block(tid, p_old, new_szB);
nethercotec9f36922004-02-14 16:40:02 +00001684}
1685
1686
njn734b8052007-11-01 04:40:37 +00001687//------------------------------------------------------------//
1688//--- Stacks ---//
1689//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001690
njn734b8052007-11-01 04:40:37 +00001691// We really want the inlining to occur...
1692#define INLINE inline __attribute__((always_inline))
nethercotec9f36922004-02-14 16:40:02 +00001693
njn734b8052007-11-01 04:40:37 +00001694static void update_stack_stats(SSizeT stack_szB_delta)
nethercotec9f36922004-02-14 16:40:02 +00001695{
njn734b8052007-11-01 04:40:37 +00001696 if (stack_szB_delta < 0) tl_assert(stacks_szB >= -stack_szB_delta);
1697 stacks_szB += stack_szB_delta;
nethercotec9f36922004-02-14 16:40:02 +00001698
njn734b8052007-11-01 04:40:37 +00001699 update_alloc_stats(stack_szB_delta);
nethercotec9f36922004-02-14 16:40:02 +00001700}
1701
njn734b8052007-11-01 04:40:37 +00001702static INLINE void new_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001703{
njn734b8052007-11-01 04:40:37 +00001704 if (have_started_executing_code) {
1705 VERB(3, "<<< new_mem_stack (%ld)", len);
1706 n_stack_allocs++;
1707 update_stack_stats(len);
1708 maybe_take_snapshot(Normal, what);
1709 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001710 }
nethercotec9f36922004-02-14 16:40:02 +00001711}
1712
njn734b8052007-11-01 04:40:37 +00001713static INLINE void die_mem_stack_2(Addr a, SizeT len, Char* what)
nethercotec9f36922004-02-14 16:40:02 +00001714{
njn734b8052007-11-01 04:40:37 +00001715 if (have_started_executing_code) {
1716 VERB(3, "<<< die_mem_stack (%ld)", -len);
1717 n_stack_frees++;
1718 maybe_take_snapshot(Peak, "stkPEAK");
1719 update_stack_stats(-len);
1720 maybe_take_snapshot(Normal, what);
1721 VERB(3, ">>>");
nethercotec9f36922004-02-14 16:40:02 +00001722 }
nethercotec9f36922004-02-14 16:40:02 +00001723}
1724
njn734b8052007-11-01 04:40:37 +00001725static void new_mem_stack(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001726{
njn734b8052007-11-01 04:40:37 +00001727 new_mem_stack_2(a, len, "stk-new");
1728}
nethercotec9f36922004-02-14 16:40:02 +00001729
njn734b8052007-11-01 04:40:37 +00001730static void die_mem_stack(Addr a, SizeT len)
1731{
1732 die_mem_stack_2(a, len, "stk-die");
1733}
nethercotec9f36922004-02-14 16:40:02 +00001734
sewardj7cf4e6b2008-05-01 20:24:26 +00001735static void new_mem_stack_signal(Addr a, SizeT len, ThreadId tid)
nethercotec9f36922004-02-14 16:40:02 +00001736{
njn734b8052007-11-01 04:40:37 +00001737 new_mem_stack_2(a, len, "sig-new");
nethercotec9f36922004-02-14 16:40:02 +00001738}
1739
nethercote8b5f40c2004-11-02 13:29:50 +00001740static void die_mem_stack_signal(Addr a, SizeT len)
nethercotec9f36922004-02-14 16:40:02 +00001741{
njn734b8052007-11-01 04:40:37 +00001742 die_mem_stack_2(a, len, "sig-die");
nethercotec9f36922004-02-14 16:40:02 +00001743}
1744
njn734b8052007-11-01 04:40:37 +00001745
1746//------------------------------------------------------------//
1747//--- Client Requests ---//
1748//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001749
njn51d827b2005-05-09 01:02:08 +00001750static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
nethercotec9f36922004-02-14 16:40:02 +00001751{
1752 switch (argv[0]) {
1753 case VG_USERREQ__MALLOCLIKE_BLOCK: {
nethercote57e36b32004-07-10 14:56:28 +00001754 void* res;
njn734b8052007-11-01 04:40:37 +00001755 void* p = (void*)argv[1];
1756 SizeT szB = argv[2];
1757 res = new_block( tid, p, szB, /*alignB--ignored*/0, /*is_zeroed*/False );
njnca82cc02004-11-22 17:18:48 +00001758 tl_assert(res == p);
njn734b8052007-11-01 04:40:37 +00001759 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001760 return True;
1761 }
1762 case VG_USERREQ__FREELIKE_BLOCK: {
njn734b8052007-11-01 04:40:37 +00001763 void* p = (void*)argv[1];
nethercotec9f36922004-02-14 16:40:02 +00001764 die_block( p, /*custom_free*/True );
njn734b8052007-11-01 04:40:37 +00001765 *ret = 0;
nethercotec9f36922004-02-14 16:40:02 +00001766 return True;
1767 }
1768 default:
1769 *ret = 0;
1770 return False;
1771 }
1772}
1773
njn734b8052007-11-01 04:40:37 +00001774//------------------------------------------------------------//
1775//--- Instrumentation ---//
1776//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001777
njn1a2741a2007-11-26 21:59:04 +00001778static void add_counter_update(IRSB* sbOut, Int n)
1779{
1780 #if defined(VG_BIGENDIAN)
1781 # define END Iend_BE
1782 #elif defined(VG_LITTLEENDIAN)
1783 # define END Iend_LE
1784 #else
1785 # error "Unknown endianness"
1786 #endif
1787 // Add code to increment 'guest_instrs_executed' by 'n', like this:
1788 // WrTmp(t1, Load64(&guest_instrs_executed))
1789 // WrTmp(t2, Add64(RdTmp(t1), Const(n)))
1790 // Store(&guest_instrs_executed, t2)
1791 IRTemp t1 = newIRTemp(sbOut->tyenv, Ity_I64);
1792 IRTemp t2 = newIRTemp(sbOut->tyenv, Ity_I64);
1793 IRExpr* counter_addr = mkIRExpr_HWord( (HWord)&guest_instrs_executed );
1794
1795 IRStmt* st1 = IRStmt_WrTmp(t1, IRExpr_Load(END, Ity_I64, counter_addr));
1796 IRStmt* st2 =
1797 IRStmt_WrTmp(t2,
1798 IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(t1),
1799 IRExpr_Const(IRConst_U64(n))));
1800 IRStmt* st3 = IRStmt_Store(END, counter_addr, IRExpr_RdTmp(t2));
1801
1802 addStmtToIRSB( sbOut, st1 );
1803 addStmtToIRSB( sbOut, st2 );
1804 addStmtToIRSB( sbOut, st3 );
1805}
1806
1807static IRSB* ms_instrument2( IRSB* sbIn )
1808{
1809 Int i, n = 0;
1810 IRSB* sbOut;
1811
1812 // We increment the instruction count in two places:
1813 // - just before any Ist_Exit statements;
1814 // - just before the IRSB's end.
1815 // In the former case, we zero 'n' and then continue instrumenting.
1816
1817 sbOut = deepCopyIRSBExceptStmts(sbIn);
1818
1819 for (i = 0; i < sbIn->stmts_used; i++) {
1820 IRStmt* st = sbIn->stmts[i];
1821
1822 if (!st || st->tag == Ist_NoOp) continue;
1823
1824 if (st->tag == Ist_IMark) {
1825 n++;
1826 } else if (st->tag == Ist_Exit) {
1827 if (n > 0) {
1828 // Add an increment before the Exit statement, then reset 'n'.
1829 add_counter_update(sbOut, n);
1830 n = 0;
1831 }
1832 }
1833 addStmtToIRSB( sbOut, st );
1834 }
1835
1836 if (n > 0) {
1837 // Add an increment before the SB end.
1838 add_counter_update(sbOut, n);
1839 }
1840 return sbOut;
1841}
1842
sewardj4ba057c2005-10-18 12:04:18 +00001843static
sewardj0b9d74a2006-12-24 02:24:11 +00001844IRSB* ms_instrument ( VgCallbackClosure* closure,
njn1a2741a2007-11-26 21:59:04 +00001845 IRSB* sbIn,
njn734b8052007-11-01 04:40:37 +00001846 VexGuestLayout* layout,
sewardj461df9c2006-01-17 02:06:39 +00001847 VexGuestExtents* vge,
sewardj4ba057c2005-10-18 12:04:18 +00001848 IRType gWordTy, IRType hWordTy )
nethercotec9f36922004-02-14 16:40:02 +00001849{
njn734b8052007-11-01 04:40:37 +00001850 if (! have_started_executing_code) {
1851 // Do an initial sample to guarantee that we have at least one.
1852 // We use 'maybe_take_snapshot' instead of 'take_snapshot' to ensure
1853 // 'maybe_take_snapshot's internal static variables are initialised.
1854 have_started_executing_code = True;
1855 maybe_take_snapshot(Normal, "startup");
1856 }
njn1a2741a2007-11-26 21:59:04 +00001857
1858 if (clo_time_unit == TimeI) { return ms_instrument2(sbIn); }
1859 else if (clo_time_unit == TimeMS) { return sbIn; }
1860 else if (clo_time_unit == TimeB) { return sbIn; }
1861 else { tl_assert2(0, "bad --time-unit value"); }
nethercotec9f36922004-02-14 16:40:02 +00001862}
1863
nethercotec9f36922004-02-14 16:40:02 +00001864
njn734b8052007-11-01 04:40:37 +00001865//------------------------------------------------------------//
1866//--- Writing snapshots ---//
1867//------------------------------------------------------------//
nethercotec9f36922004-02-14 16:40:02 +00001868
njnb11e5aa2008-01-20 22:30:52 +00001869Char FP_buf[BUF_LEN];
nethercotec9f36922004-02-14 16:40:02 +00001870
njn734b8052007-11-01 04:40:37 +00001871// XXX: implement f{,n}printf in m_libcprint.c eventually, and use it here.
1872// Then change Cachegrind to use it too.
1873#define FP(format, args...) ({ \
njnb11e5aa2008-01-20 22:30:52 +00001874 VG_(snprintf)(FP_buf, BUF_LEN, format, ##args); \
1875 FP_buf[BUF_LEN-1] = '\0'; /* Make sure the string is terminated. */ \
1876 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf)); \
1877})
1878
1879// Same as FP, but guarantees a '\n' at the end. (At one point we were
1880// truncating without adding the '\n', which caused bug #155929.)
1881#define FPn(format, args...) ({ \
1882 VG_(snprintf)(FP_buf, BUF_LEN, format, ##args); \
1883 FP_buf[BUF_LEN-5] = '.'; /* "..." at the end make the truncation */ \
1884 FP_buf[BUF_LEN-4] = '.'; /* more obvious */ \
1885 FP_buf[BUF_LEN-3] = '.'; \
1886 FP_buf[BUF_LEN-2] = '\n'; /* Make sure the last char is a newline. */ \
1887 FP_buf[BUF_LEN-1] = '\0'; /* Make sure the string is terminated. */ \
njn734b8052007-11-01 04:40:37 +00001888 VG_(write)(fd, (void*)FP_buf, VG_(strlen)(FP_buf)); \
1889})
nethercotec9f36922004-02-14 16:40:02 +00001890
1891// Nb: uses a static buffer, each call trashes the last string returned.
njn734b8052007-11-01 04:40:37 +00001892static Char* make_perc(ULong x, ULong y)
nethercotec9f36922004-02-14 16:40:02 +00001893{
1894 static Char mbuf[32];
njn734b8052007-11-01 04:40:37 +00001895
1896// tl_assert(x <= y); XXX; put back in later...
1897
njn1a2741a2007-11-26 21:59:04 +00001898 // XXX: I'm not confident that VG_(percentify) works as it should...
njn734b8052007-11-01 04:40:37 +00001899 VG_(percentify)(x, y, 2, 6, mbuf);
1900 // XXX: this is bogus if the denominator was zero -- resulting string is
1901 // something like "0 --%")
1902 if (' ' == mbuf[0]) mbuf[0] = '0';
nethercotec9f36922004-02-14 16:40:02 +00001903 return mbuf;
1904}
1905
njn734b8052007-11-01 04:40:37 +00001906static void pp_snapshot_SXPt(Int fd, SXPt* sxpt, Int depth, Char* depth_str,
1907 Int depth_str_len,
1908 SizeT snapshot_heap_szB, SizeT snapshot_total_szB)
nethercotec9f36922004-02-14 16:40:02 +00001909{
njn734b8052007-11-01 04:40:37 +00001910 Int i, n_insig_children_sxpts;
1911 Char* perc;
njn734b8052007-11-01 04:40:37 +00001912 SXPt* pred = NULL;
1913 SXPt* child = NULL;
nethercotec9f36922004-02-14 16:40:02 +00001914
sewardjf330ae82008-05-13 10:57:29 +00001915 // Used for printing function names. Is made static to keep it out
1916 // of the stack frame -- this function is recursive. Obviously this
1917 // now means its contents are trashed across the recursive call.
1918 static Char ip_desc_array[BUF_LEN];
1919 Char* ip_desc = ip_desc_array;
1920
njn734b8052007-11-01 04:40:37 +00001921 switch (sxpt->tag) {
1922 case SigSXPt:
1923 // Print the SXPt itself.
1924 if (sxpt->Sig.ip == 0) {
1925 ip_desc =
1926 "(heap allocation functions) malloc/new/new[], --alloc-fns, etc.";
1927 } else {
1928 // If it's main-or-below-main, we (if appropriate) ignore everything
1929 // below it by pretending it has no children.
1930 // XXX: get this properly. Also, don't hard-code "(below main)"
1931 // here -- look at the "(below main)"/"__libc_start_main" mess
1932 // (m_stacktrace.c and m_demangle.c).
1933 // [Nb: Josef wants --show-below-main to work for his fn entry/exit
1934 // tracing]
1935 Bool should_hide_below_main = /*!VG_(clo_show_below_main)*/True;
1936 if (should_hide_below_main &&
1937 VG_(get_fnname)(sxpt->Sig.ip, ip_desc, BUF_LEN) &&
1938 (VG_STREQ(ip_desc, "main") || VG_STREQ(ip_desc, "(below main)")))
1939 {
1940 sxpt->Sig.n_children = 0;
1941 }
1942 // We need the -1 to get the line number right, But I'm not sure why.
1943 ip_desc = VG_(describe_IP)(sxpt->Sig.ip-1, ip_desc, BUF_LEN);
1944 }
1945 perc = make_perc(sxpt->szB, snapshot_total_szB);
njnb11e5aa2008-01-20 22:30:52 +00001946 // Nb: we deliberately use 'FPn', not 'FP'. So if the ip_desc is
1947 // too long (eg. due to a long C++ function name), it'll get
1948 // truncated, but the '\n' is still there so its a valid file.
1949 FPn("%sn%d: %lu %s\n",
njn734b8052007-11-01 04:40:37 +00001950 depth_str, sxpt->Sig.n_children, sxpt->szB, ip_desc);
nethercotec9f36922004-02-14 16:40:02 +00001951
njn734b8052007-11-01 04:40:37 +00001952 // Indent.
1953 tl_assert(depth+1 < depth_str_len-1); // -1 for end NUL char
1954 depth_str[depth+0] = ' ';
1955 depth_str[depth+1] = '\0';
1956
1957 // Sort SXPt's children by szB (reverse order: biggest to smallest).
1958 // Nb: we sort them here, rather than earlier (eg. in dup_XTree), for
1959 // two reasons. First, if we do it during dup_XTree, it can get
1960 // expensive (eg. 15% of execution time for konqueror
1961 // startup/shutdown). Second, this way we get the Insig SXPt (if one
1962 // is present) in its sorted position, not at the end.
1963 VG_(ssort)(sxpt->Sig.children, sxpt->Sig.n_children, sizeof(SXPt*),
1964 SXPt_revcmp_szB);
1965
1966 // Print the SXPt's children. They should already be in sorted order.
1967 n_insig_children_sxpts = 0;
1968 for (i = 0; i < sxpt->Sig.n_children; i++) {
1969 pred = child;
1970 child = sxpt->Sig.children[i];
1971
1972 if (InsigSXPt == child->tag)
1973 n_insig_children_sxpts++;
1974
sewardjf330ae82008-05-13 10:57:29 +00001975 // Ok, print the child. NB: contents of ip_desc_array will be
1976 // trashed by this recursive call. Doesn't matter currently,
1977 // but worth noting.
njn734b8052007-11-01 04:40:37 +00001978 pp_snapshot_SXPt(fd, child, depth+1, depth_str, depth_str_len,
1979 snapshot_heap_szB, snapshot_total_szB);
njn734b8052007-11-01 04:40:37 +00001980 }
njndbeb5352007-12-04 03:15:23 +00001981
1982 // Unindent.
1983 depth_str[depth+0] = '\0';
1984 depth_str[depth+1] = '\0';
1985
njn734b8052007-11-01 04:40:37 +00001986 // There should be 0 or 1 Insig children SXPts.
1987 tl_assert(n_insig_children_sxpts <= 1);
1988 break;
1989
1990 case InsigSXPt: {
1991 Char* s = ( sxpt->Insig.n_xpts == 1 ? "," : "s, all" );
1992 perc = make_perc(sxpt->szB, snapshot_total_szB);
1993 FP("%sn0: %lu in %d place%s below massif's threshold (%s)\n",
1994 depth_str, sxpt->szB, sxpt->Insig.n_xpts, s,
njn62721e92007-11-11 22:15:58 +00001995 make_perc((ULong)clo_threshold, 100));
njn734b8052007-11-01 04:40:37 +00001996 break;
1997 }
1998
1999 default:
2000 tl_assert2(0, "pp_snapshot_SXPt: unrecognised SXPt tag");
nethercotec9f36922004-02-14 16:40:02 +00002001 }
nethercotec9f36922004-02-14 16:40:02 +00002002}
2003
njn734b8052007-11-01 04:40:37 +00002004static void pp_snapshot(Int fd, Snapshot* snapshot, Int snapshot_n)
nethercotec9f36922004-02-14 16:40:02 +00002005{
njn734b8052007-11-01 04:40:37 +00002006 sanity_check_snapshot(snapshot);
nethercotec9f36922004-02-14 16:40:02 +00002007
njn734b8052007-11-01 04:40:37 +00002008 FP("#-----------\n");
2009 FP("snapshot=%d\n", snapshot_n);
2010 FP("#-----------\n");
2011 FP("time=%lld\n", snapshot->time);
2012 FP("mem_heap_B=%lu\n", snapshot->heap_szB);
njn32397c02007-11-10 04:08:08 +00002013 FP("mem_heap_extra_B=%lu\n", snapshot->heap_extra_szB);
njn734b8052007-11-01 04:40:37 +00002014 FP("mem_stacks_B=%lu\n", snapshot->stacks_szB);
2015
2016 if (is_detailed_snapshot(snapshot)) {
2017 // Detailed snapshot -- print heap tree.
2018 Int depth_str_len = clo_depth + 3;
2019 Char* depth_str = VG_(malloc)(sizeof(Char) * depth_str_len);
2020 SizeT snapshot_total_szB =
njn32397c02007-11-10 04:08:08 +00002021 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
njn734b8052007-11-01 04:40:37 +00002022 depth_str[0] = '\0'; // Initialise depth_str to "".
2023
2024 FP("heap_tree=%s\n", ( Peak == snapshot->kind ? "peak" : "detailed" ));
2025 pp_snapshot_SXPt(fd, snapshot->alloc_sxpt, 0, depth_str,
2026 depth_str_len, snapshot->heap_szB,
2027 snapshot_total_szB);
2028
2029 VG_(free)(depth_str);
2030
2031 } else {
2032 FP("heap_tree=empty\n");
nethercote43a15ce2004-08-30 19:15:12 +00002033 }
nethercotec9f36922004-02-14 16:40:02 +00002034}
2035
njn734b8052007-11-01 04:40:37 +00002036static void write_snapshots_to_file(void)
nethercotec9f36922004-02-14 16:40:02 +00002037{
njn734b8052007-11-01 04:40:37 +00002038 Int i, fd;
sewardj92645592005-07-23 09:18:34 +00002039 SysRes sres;
nethercotec9f36922004-02-14 16:40:02 +00002040
njn7064fb22008-05-29 23:09:52 +00002041 // Setup output filename. Nb: it's important to do this now, ie. as late
2042 // as possible. If we do it at start-up and the program forks and the
2043 // output file format string contains a %p (pid) specifier, both the
2044 // parent and child will incorrectly write to the same file; this
2045 // happened in 3.3.0.
2046 Char* massif_out_file =
2047 VG_(expand_file_name)("--massif-out-file", clo_massif_out_file);
2048
njn734b8052007-11-01 04:40:37 +00002049 sres = VG_(open)(massif_out_file, VKI_O_CREAT|VKI_O_TRUNC|VKI_O_WRONLY,
2050 VKI_S_IRUSR|VKI_S_IWUSR);
sewardj92645592005-07-23 09:18:34 +00002051 if (sres.isError) {
njn734b8052007-11-01 04:40:37 +00002052 // If the file can't be opened for whatever reason (conflict
2053 // between multiple cachegrinded processes?), give up now.
2054 VG_(message)(Vg_UserMsg,
2055 "error: can't open output file '%s'", massif_out_file );
2056 VG_(message)(Vg_UserMsg,
2057 " ... so profiling results will be missing.");
njn7064fb22008-05-29 23:09:52 +00002058 VG_(free)(massif_out_file);
nethercotec9f36922004-02-14 16:40:02 +00002059 return;
sewardj92645592005-07-23 09:18:34 +00002060 } else {
sewardje8089302006-10-17 02:15:17 +00002061 fd = sres.res;
njn7064fb22008-05-29 23:09:52 +00002062 VG_(free)(massif_out_file);
nethercotec9f36922004-02-14 16:40:02 +00002063 }
2064
njn734b8052007-11-01 04:40:37 +00002065 // Print massif-specific options that were used.
2066 // XXX: is it worth having a "desc:" line? Could just call it "options:"
2067 // -- this file format isn't as generic as Cachegrind's, so the
2068 // implied genericity of "desc:" is bogus.
2069 FP("desc:");
2070 for (i = 0; i < VG_(sizeXA)(args_for_massif); i++) {
2071 Char* arg = *(Char**)VG_(indexXA)(args_for_massif, i);
2072 FP(" %s", arg);
nethercotec9f36922004-02-14 16:40:02 +00002073 }
njn734b8052007-11-01 04:40:37 +00002074 if (0 == i) FP(" (none)");
2075 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002076
njn734b8052007-11-01 04:40:37 +00002077 // Print "cmd:" line.
2078 FP("cmd: ");
sewardj45f4e7c2005-09-27 19:20:21 +00002079 if (VG_(args_the_exename)) {
njn734b8052007-11-01 04:40:37 +00002080 FP("%s", VG_(args_the_exename));
2081 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
2082 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
2083 if (arg)
2084 FP(" %s", arg);
2085 }
2086 } else {
2087 FP(" ???");
sewardj45f4e7c2005-09-27 19:20:21 +00002088 }
njn734b8052007-11-01 04:40:37 +00002089 FP("\n");
nethercotec9f36922004-02-14 16:40:02 +00002090
njn734b8052007-11-01 04:40:37 +00002091 FP("time_unit: %s\n", TimeUnit_to_string(clo_time_unit));
nethercotec9f36922004-02-14 16:40:02 +00002092
njn734b8052007-11-01 04:40:37 +00002093 for (i = 0; i < next_snapshot_i; i++) {
2094 Snapshot* snapshot = & snapshots[i];
2095 pp_snapshot(fd, snapshot, i); // Detailed snapshot!
nethercotec9f36922004-02-14 16:40:02 +00002096 }
2097}
2098
njn734b8052007-11-01 04:40:37 +00002099
2100//------------------------------------------------------------//
2101//--- Finalisation ---//
2102//------------------------------------------------------------//
2103
njn51d827b2005-05-09 01:02:08 +00002104static void ms_fini(Int exit_status)
nethercotec9f36922004-02-14 16:40:02 +00002105{
njn734b8052007-11-01 04:40:37 +00002106 // Output.
2107 write_snapshots_to_file();
nethercotec9f36922004-02-14 16:40:02 +00002108
njn734b8052007-11-01 04:40:37 +00002109 // Stats
2110 tl_assert(n_xpts > 0); // always have alloc_xpt
2111 VERB(1, "heap allocs: %u", n_heap_allocs);
2112 VERB(1, "heap reallocs: %u", n_heap_reallocs);
2113 VERB(1, "heap frees: %u", n_heap_frees);
2114 VERB(1, "stack allocs: %u", n_stack_allocs);
2115 VERB(1, "stack frees: %u", n_stack_frees);
2116 VERB(1, "XPts: %u", n_xpts);
2117 VERB(1, "top-XPts: %u (%d%%)",
2118 alloc_xpt->n_children,
2119 ( n_xpts ? alloc_xpt->n_children * 100 / n_xpts : 0));
njn55a30042007-11-10 04:18:39 +00002120 VERB(1, "XPt init expansions: %u", n_xpt_init_expansions);
2121 VERB(1, "XPt later expansions: %u", n_xpt_later_expansions);
njn734b8052007-11-01 04:40:37 +00002122 VERB(1, "SXPt allocs: %u", n_sxpt_allocs);
2123 VERB(1, "SXPt frees: %u", n_sxpt_frees);
2124 VERB(1, "skipped snapshots: %u", n_skipped_snapshots);
2125 VERB(1, "real snapshots: %u", n_real_snapshots);
2126 VERB(1, "detailed snapshots: %u", n_detailed_snapshots);
2127 VERB(1, "peak snapshots: %u", n_peak_snapshots);
2128 VERB(1, "cullings: %u", n_cullings);
njn55a30042007-11-10 04:18:39 +00002129 VERB(1, "XCon redos: %u", n_XCon_redos);
nethercotec9f36922004-02-14 16:40:02 +00002130}
2131
njn734b8052007-11-01 04:40:37 +00002132
2133//------------------------------------------------------------//
2134//--- Initialisation ---//
2135//------------------------------------------------------------//
njn51d827b2005-05-09 01:02:08 +00002136
2137static void ms_post_clo_init(void)
2138{
njn734b8052007-11-01 04:40:37 +00002139 Int i;
njn51d827b2005-05-09 01:02:08 +00002140
njn734b8052007-11-01 04:40:37 +00002141 // Check options.
2142 if (clo_heap_admin < 0 || clo_heap_admin > 1024) {
2143 VG_(message)(Vg_UserMsg, "--heap-admin must be between 0 and 1024");
2144 VG_(err_bad_option)("--heap-admin");
2145 }
2146 if (clo_depth < 1 || clo_depth > MAX_DEPTH) {
2147 VG_(message)(Vg_UserMsg, "--depth must be between 1 and %d", MAX_DEPTH);
2148 VG_(err_bad_option)("--depth");
2149 }
njn62721e92007-11-11 22:15:58 +00002150 if (clo_threshold < 0 || clo_threshold > 100) {
2151 VG_(message)(Vg_UserMsg, "--threshold must be between 0.0 and 100.0");
njn734b8052007-11-01 04:40:37 +00002152 VG_(err_bad_option)("--threshold");
2153 }
2154 if (clo_detailed_freq < 1 || clo_detailed_freq > 10000) {
2155 VG_(message)(Vg_UserMsg, "--detailed-freq must be between 1 and 10000");
2156 VG_(err_bad_option)("--detailed-freq");
2157 }
2158 if (clo_max_snapshots < 10 || clo_max_snapshots > 1000) {
2159 VG_(message)(Vg_UserMsg, "--max-snapshots must be between 10 and 1000");
2160 VG_(err_bad_option)("--max-snapshots");
2161 }
2162
2163 // If we have --heap=no, set --heap-admin to zero, just to make sure we
2164 // don't accidentally use a non-zero heap-admin size somewhere.
2165 if (!clo_heap) {
2166 clo_heap_admin = 0;
2167 }
2168
2169 // Print alloc-fns, if necessary.
2170 if (VG_(clo_verbosity) > 1) {
2171 VERB(1, "alloc-fns:");
2172 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
2173 Char** alloc_fn_ptr = VG_(indexXA)(alloc_fns, i);
2174 VERB(1, " %d: %s", i, *alloc_fn_ptr);
2175 }
2176 }
2177
2178 // Events to track.
2179 if (clo_stacks) {
2180 VG_(track_new_mem_stack) ( new_mem_stack );
2181 VG_(track_die_mem_stack) ( die_mem_stack );
2182 VG_(track_new_mem_stack_signal) ( new_mem_stack_signal );
2183 VG_(track_die_mem_stack_signal) ( die_mem_stack_signal );
2184 }
2185
2186 // Initialise snapshot array, and sanity-check it.
2187 snapshots = VG_(malloc)(sizeof(Snapshot) * clo_max_snapshots);
2188 // We don't want to do snapshot sanity checks here, because they're
2189 // currently uninitialised.
2190 for (i = 0; i < clo_max_snapshots; i++) {
2191 clear_snapshot( & snapshots[i], /*do_sanity_check*/False );
2192 }
2193 sanity_check_snapshots_array();
njn51d827b2005-05-09 01:02:08 +00002194}
2195
tom151a6392005-11-11 12:30:36 +00002196static void ms_pre_clo_init(void)
njn734b8052007-11-01 04:40:37 +00002197{
njn51d827b2005-05-09 01:02:08 +00002198 VG_(details_name) ("Massif");
2199 VG_(details_version) (NULL);
njn1a2741a2007-11-26 21:59:04 +00002200 VG_(details_description) ("a heap profiler");
njn9a0cba42007-04-15 22:15:57 +00002201 VG_(details_copyright_author)(
sewardj4d474d02008-02-11 11:34:59 +00002202 "Copyright (C) 2003-2008, and GNU GPL'd, by Nicholas Nethercote");
njn51d827b2005-05-09 01:02:08 +00002203 VG_(details_bug_reports_to) (VG_BUGS_TO);
2204
2205 // Basic functions
2206 VG_(basic_tool_funcs) (ms_post_clo_init,
2207 ms_instrument,
2208 ms_fini);
2209
2210 // Needs
2211 VG_(needs_libc_freeres)();
2212 VG_(needs_command_line_options)(ms_process_cmd_line_option,
2213 ms_print_usage,
2214 ms_print_debug_usage);
2215 VG_(needs_client_requests) (ms_handle_client_request);
njn734b8052007-11-01 04:40:37 +00002216 VG_(needs_sanity_checks) (ms_cheap_sanity_check,
2217 ms_expensive_sanity_check);
njnfc51f8d2005-06-21 03:20:17 +00002218 VG_(needs_malloc_replacement) (ms_malloc,
njn51d827b2005-05-09 01:02:08 +00002219 ms___builtin_new,
2220 ms___builtin_vec_new,
2221 ms_memalign,
2222 ms_calloc,
2223 ms_free,
2224 ms___builtin_delete,
2225 ms___builtin_vec_delete,
2226 ms_realloc,
2227 0 );
2228
njn51d827b2005-05-09 01:02:08 +00002229 // HP_Chunks
njn734b8052007-11-01 04:40:37 +00002230 malloc_list = VG_(HT_construct)( "Massif's malloc list" );
njn51d827b2005-05-09 01:02:08 +00002231
2232 // Dummy node at top of the context structure.
njn734b8052007-11-01 04:40:37 +00002233 alloc_xpt = new_XPt(/*ip*/0, /*parent*/NULL);
2234
2235 // Initialise alloc_fns.
2236 init_alloc_fns();
2237
2238 // Initialise args_for_massif.
2239 args_for_massif = VG_(newXA)(VG_(malloc), VG_(free), sizeof(HChar*));
njn51d827b2005-05-09 01:02:08 +00002240}
2241
sewardj45f4e7c2005-09-27 19:20:21 +00002242VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
nethercotec9f36922004-02-14 16:40:02 +00002243
njn734b8052007-11-01 04:40:37 +00002244//--------------------------------------------------------------------//
2245//--- end ---//
2246//--------------------------------------------------------------------//