linux arm regtest: leak_cpp_interior try again
[valgrind.git] / massif / ms_main.c
bloba232df94c04a9c550187e0b6179222c6ae9610f4
1 //--------------------------------------------------------------------//
2 //--- Massif: a heap profiling tool. ms_main.c ---//
3 //--------------------------------------------------------------------//
5 /*
6 This file is part of Massif, a Valgrind tool for profiling memory
7 usage of programs.
9 Copyright (C) 2003-2017 Nicholas Nethercote
10 njn@valgrind.org
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.
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.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, see <http://www.gnu.org/licenses/>.
25 The GNU General Public License is contained in the file COPYING.
28 //---------------------------------------------------------------------------
29 // XXX:
30 //---------------------------------------------------------------------------
31 // Todo -- nice, but less critical:
32 // - do a graph-drawing test
33 // - make file format more generic. Obstacles:
34 // - unit prefixes are not generic
35 // - preset column widths for stats are not generic
36 // - preset column headers are not generic
37 // - "Massif arguments:" line is not generic
38 // - do snapshots on some specific client requests
39 // - "show me the extra allocations since the last snapshot"
40 // - "start/stop logging" (eg. quickly skip boring bits)
41 // - Add ability to draw multiple graphs, eg. heap-only, stack-only, total.
42 // Give each graph a title. (try to do it generically!)
43 // - make --show-below-main=no work
44 // - Options like --alloc-fn='operator new(unsigned, std::nothrow_t const&)'
45 // don't work in a .valgrindrc file or in $VALGRIND_OPTS.
46 // m_commandline.c:add_args_from_string() needs to respect single quotes.
47 // - With --stack=yes, want to add a stack trace for detailed snapshots so
48 // it's clear where/why the peak is occurring. (Mattieu Castet) Also,
49 // possibly useful even with --stack=no? (Andi Yin)
51 // Performance:
52 // - To run the benchmarks:
54 // perl perf/vg_perf --tools=massif --reps=3 perf/{heap,tinycc} massif
55 // time valgrind --tool=massif --depth=100 konqueror
57 // The other benchmarks don't do much allocation, and so give similar speeds
58 // to Nulgrind.
60 // Timing results on 'nevermore' (njn's machine) as of r7013:
62 // heap 0.53s ma:12.4s (23.5x, -----)
63 // tinycc 0.46s ma: 4.9s (10.7x, -----)
64 // many-xpts 0.08s ma: 2.0s (25.0x, -----)
65 // konqueror 29.6s real 0:21.0s user
67 // [Introduction of --time-unit=i as the default slowed things down by
68 // roughly 0--20%.]
70 // Todo -- low priority:
71 // - In each XPt, record both bytes and the number of allocations, and
72 // possibly the global number of allocations.
73 // - (Andy Lin) Give a stack trace on detailed snapshots?
74 // - (Artur Wisz) add a feature to Massif to ignore any heap blocks larger
75 // than a certain size! Because: "linux's malloc allows to set a
76 // MMAP_THRESHOLD value, so we set it to 4096 - all blocks above that will
77 // be handled directly by the kernel, and are guaranteed to be returned to
78 // the system when freed. So we needed to profile only blocks below this
79 // limit."
81 // File format working notes:
83 #if 0
84 desc: --heap-admin=foo
85 cmd: date
86 time_unit: ms
87 #-----------
88 snapshot=0
89 #-----------
90 time=0
91 mem_heap_B=0
92 mem_heap_admin_B=0
93 mem_stacks_B=0
94 heap_tree=empty
95 #-----------
96 snapshot=1
97 #-----------
98 time=353
99 mem_heap_B=5
100 mem_heap_admin_B=0
101 mem_stacks_B=0
102 heap_tree=detailed
103 n1: 5 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
104 n1: 5 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
105 n1: 5 0x279DE6: _nl_load_locale_from_archive (in /lib/libc-2.3.5.so)
106 n1: 5 0x278E97: _nl_find_locale (in /lib/libc-2.3.5.so)
107 n1: 5 0x278871: setlocale (in /lib/libc-2.3.5.so)
108 n1: 5 0x8049821: (within /bin/date)
109 n0: 5 0x26ED5E: (below main) (in /lib/libc-2.3.5.so)
112 n_events: n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
113 t_events: B
114 n 0 0 0 0 0
115 n 0 0 0 0 0
116 t1: 5 <string...>
117 t1: 6 <string...>
119 Ideas:
120 - each snapshot specifies an x-axis value and one or more y-axis values.
121 - can display the y-axis values separately if you like
122 - can completely separate connection between snapshots and trees.
124 Challenges:
125 - how to specify and scale/abbreviate units on axes?
126 - how to combine multiple values into the y-axis?
128 --------------------------------------------------------------------------------Command: date
129 Massif arguments: --heap-admin=foo
130 ms_print arguments: massif.out
131 --------------------------------------------------------------------------------
133 6.472^ :#
134 | :# :: . .
136 | ::@ :@ :@ :@:::# :: : ::::
137 0 +-----------------------------------@---@---@-----@--@---#-------------->ms 0 713
139 Number of snapshots: 50
140 Detailed snapshots: [2, 11, 13, 19, 25, 32 (peak)]
141 -------------------------------------------------------------------------------- n time(ms) total(B) useful-heap(B) admin-heap(B) stacks(B)
142 -------------------------------------------------------------------------------- 0 0 0 0 0 0
143 1 345 5 5 0 0
144 2 353 5 5 0 0
145 100.00% (5B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
146 ->100.00% (5B) 0x27F6E0: _nl_normalize_codeset (in /lib/libc-2.3.5.so)
147 #endif
149 //---------------------------------------------------------------------------
151 #include "pub_tool_basics.h"
152 #include "pub_tool_vki.h"
153 #include "pub_tool_aspacemgr.h"
154 #include "pub_tool_debuginfo.h"
155 #include "pub_tool_hashtable.h"
156 #include "pub_tool_libcbase.h"
157 #include "pub_tool_libcassert.h"
158 #include "pub_tool_libcfile.h"
159 #include "pub_tool_libcprint.h"
160 #include "pub_tool_libcproc.h"
161 #include "pub_tool_machine.h"
162 #include "pub_tool_mallocfree.h"
163 #include "pub_tool_options.h"
164 #include "pub_tool_poolalloc.h"
165 #include "pub_tool_replacemalloc.h"
166 #include "pub_tool_stacktrace.h"
167 #include "pub_tool_threadstate.h"
168 #include "pub_tool_tooliface.h"
169 #include "pub_tool_xarray.h"
170 #include "pub_tool_xtree.h"
171 #include "pub_tool_xtmemory.h"
172 #include "pub_tool_clientstate.h"
173 #include "pub_tool_gdbserver.h"
175 #include "pub_tool_clreq.h" // For {MALLOC,FREE}LIKE_BLOCK
177 //------------------------------------------------------------*/
178 //--- Overview of operation ---*/
179 //------------------------------------------------------------*/
181 // The size of the stacks and heap is tracked. The heap is tracked in a lot
182 // of detail, enough to tell how many bytes each line of code is responsible
183 // for, more or less. The main data structure is an xtree maintaining the
184 // call tree beneath all the allocation functions like malloc().
185 // (Alternatively, if --pages-as-heap=yes is specified, memory is tracked at
186 // the page level, and each page is treated much like a heap block. We use
187 // "heap" throughout below to cover this case because the concepts are all the
188 // same.)
190 // "Snapshots" are recordings of the memory usage. There are two basic
191 // kinds:
192 // - Normal: these record the current time, total memory size, total heap
193 // size, heap admin size and stack size.
194 // - Detailed: these record those things in a normal snapshot, plus a very
195 // detailed XTree (see below) indicating how the heap is structured.
197 // Snapshots are taken every so often. There are two storage classes of
198 // snapshots:
199 // - Temporary: Massif does a temporary snapshot every so often. The idea
200 // is to always have a certain number of temporary snapshots around. So
201 // we take them frequently to begin with, but decreasingly often as the
202 // program continues to run. Also, we remove some old ones after a while.
203 // Overall it's a kind of exponential decay thing. Most of these are
204 // normal snapshots, a small fraction are detailed snapshots.
205 // - Permanent: Massif takes a permanent (detailed) snapshot in some
206 // circumstances. They are:
207 // - Peak snapshot: When the memory usage peak is reached, it takes a
208 // snapshot. It keeps this, unless the peak is subsequently exceeded,
209 // in which case it will overwrite the peak snapshot.
210 // - User-requested snapshots: These are done in response to client
211 // requests. They are always kept.
213 // Used for printing things when clo_verbosity > 1.
214 #define VERB(verb, format, args...) \
215 if (UNLIKELY(VG_(clo_verbosity) > verb)) { \
216 VG_(dmsg)("Massif: " format, ##args); \
219 //------------------------------------------------------------//
220 //--- Statistics ---//
221 //------------------------------------------------------------//
223 // Konqueror startup, to give an idea of the numbers involved with a biggish
224 // program, with default depth:
226 // depth=3 depth=40
227 // - 310,000 allocations
228 // - 300,000 frees
229 // - 15,000 XPts 800,000 XPts
230 // - 1,800 top-XPts
232 static UInt n_heap_allocs = 0;
233 static UInt n_heap_reallocs = 0;
234 static UInt n_heap_frees = 0;
235 static UInt n_ignored_heap_allocs = 0;
236 static UInt n_ignored_heap_frees = 0;
237 static UInt n_ignored_heap_reallocs = 0;
238 static UInt n_stack_allocs = 0;
239 static UInt n_stack_frees = 0;
241 static UInt n_skipped_snapshots = 0;
242 static UInt n_real_snapshots = 0;
243 static UInt n_detailed_snapshots = 0;
244 static UInt n_peak_snapshots = 0;
245 static UInt n_cullings = 0;
247 //------------------------------------------------------------//
248 //--- Globals ---//
249 //------------------------------------------------------------//
251 // Number of guest instructions executed so far. Only used with
252 // --time-unit=i.
253 static Long guest_instrs_executed = 0;
255 static SizeT heap_szB = 0; // Live heap size
256 static SizeT heap_extra_szB = 0; // Live heap extra size -- slop + admin bytes
257 static SizeT stacks_szB = 0; // Live stacks size
259 // This is the total size from the current peak snapshot, or 0 if no peak
260 // snapshot has been taken yet.
261 static SizeT peak_snapshot_total_szB = 0;
263 // Incremented every time memory is allocated/deallocated, by the
264 // allocated/deallocated amount; includes heap, heap-admin and stack
265 // memory. An alternative to milliseconds as a unit of program "time".
266 static ULong total_allocs_deallocs_szB = 0;
268 // When running with --heap=yes --pages-as-heap=no, we don't start taking
269 // snapshots until the first basic block is executed, rather than doing it in
270 // ms_post_clo_init (which is the obvious spot), for two reasons.
271 // - It lets us ignore stack events prior to that, because they're not
272 // really proper ones and just would screw things up.
273 // - Because there's still some core initialisation to do, and so there
274 // would be an artificial time gap between the first and second snapshots.
276 // When running with --heap=yes --pages-as-heap=yes, snapshots start much
277 // earlier due to new_mem_startup so this isn't relevant.
279 static Bool have_started_executing_code = False;
281 //------------------------------------------------------------//
282 //--- Alloc fns ---//
283 //------------------------------------------------------------//
285 // alloc_fns is not used for detecting allocations
286 // it is used when checking for ignore functions in the callstack
287 // see filter_IPs
288 // allocation detection uses the usual coregrind reaplace malloc
289 // mechanism which calls ms_malloc etc. here and in the end
290 // everything goes through alloc_and_record_block
291 static XArray* alloc_fns;
292 static XArray* ignore_fns;
294 static void init_alloc_fns(void)
296 // Create the list, and add the default elements.
297 alloc_fns = VG_(newXA)(VG_(malloc), "ms.main.iaf.1",
298 VG_(free), sizeof(HChar*));
299 #define DO(x) { const HChar* s = x; VG_(addToXA)(alloc_fns, &s); }
301 // Ordered roughly according to (presumed) frequency.
302 // Nb: The C++ "operator new*" ones are overloadable. We include them
303 // always anyway, because even if they're overloaded, it would be a
304 // prodigiously stupid overloading that caused them to not allocate
305 // memory.
307 // PJF: the above comment is a bit wide of the mark.
308 // See https://en.cppreference.com/w/cpp/memory/new/operator_new
309 // There are two "non-allocating placement allocation functions"
311 // Because of the above we can't use wildcards.
313 // XXX: because we don't look at the first stack entry (unless it's a
314 // custom allocation) there's not much point to having all these alloc
315 // functions here -- they should never appear anywhere (I think?) other
316 // than the top stack entry. The only exceptions are those that in
317 // vg_replace_malloc.c are partly or fully implemented in terms of another
318 // alloc function: realloc (which uses malloc); valloc,
319 // malloc_zone_valloc, posix_memalign and memalign_common (which use
320 // memalign).
322 DO("malloc" );
323 DO("__builtin_new" );
324 # if VG_WORDSIZE == 4
325 DO("operator new(unsigned)" );
326 #else
327 DO("operator new(unsigned long)" );
328 #endif
329 DO("__builtin_vec_new" );
330 # if VG_WORDSIZE == 4
331 DO("operator new[](unsigned)" );
332 #else
333 DO("operator new[](unsigned long)" );
334 #endif
335 DO("calloc" );
336 DO("aligned_alloc" );
337 DO("realloc" );
338 DO("memalign" );
339 DO("posix_memalign" );
340 DO("valloc" );
341 # if VG_WORDSIZE == 4
342 DO("operator new(unsigned, std::nothrow_t const&)" );
343 DO("operator new[](unsigned, std::nothrow_t const&)" );
344 DO("operator new(unsigned, std::align_val_t)" );
345 DO("operator new[](unsigned, std::align_val_t)" );
346 DO("operator new(unsigned, std::align_val_t, std::nothrow_t const&)" );
347 DO("operator new[](unsigned, std::align_val_t, std::nothrow_t const&)" );
348 #else
349 DO("operator new(unsigned long, std::nothrow_t const&)" );
350 DO("operator new[](unsigned long, std::nothrow_t const&)");
351 DO("operator new(unsigned long, std::align_val_t)" );
352 DO("operator new[](unsigned long, std::align_val_t)" );
353 DO("operator new(unsigned long, std::align_val_t, std::nothrow_t const&)" );
354 DO("operator new[](unsigned long, std::align_val_t, std::nothrow_t const&)" );
355 #endif
356 #if defined(VGO_darwin)
357 DO("malloc_zone_malloc" );
358 DO("malloc_zone_calloc" );
359 DO("malloc_zone_realloc" );
360 DO("malloc_zone_memalign" );
361 DO("malloc_zone_valloc" );
362 #endif
365 static void init_ignore_fns(void)
367 // Create the (empty) list.
368 ignore_fns = VG_(newXA)(VG_(malloc), "ms.main.iif.1",
369 VG_(free), sizeof(HChar*));
372 //------------------------------------------------------------//
373 //--- Command line args ---//
374 //------------------------------------------------------------//
376 #define MAX_DEPTH 200
378 typedef enum { TimeI, TimeMS, TimeB } TimeUnit;
380 static const HChar* TimeUnit_to_string(TimeUnit time_unit)
382 switch (time_unit) {
383 case TimeI: return "i";
384 case TimeMS: return "ms";
385 case TimeB: return "B";
386 default: tl_assert2(0, "TimeUnit_to_string: unrecognised TimeUnit");
390 static Bool clo_heap = True;
391 // clo_heap_admin is deliberately a word-sized type. At one point it was
392 // a UInt, but this caused problems on 64-bit machines when it was
393 // multiplied by a small negative number and then promoted to a
394 // word-sized type -- it ended up with a value of 4.2 billion. Sigh.
395 static SSizeT clo_heap_admin = 8;
396 static Bool clo_pages_as_heap = False;
397 static Bool clo_stacks = False;
398 static Int clo_depth = 30;
399 static double clo_threshold = 1.0; // percentage
400 static double clo_peak_inaccuracy = 1.0; // percentage
401 static Int clo_time_unit = TimeI;
402 static Int clo_detailed_freq = 10;
403 static Int clo_max_snapshots = 100;
404 static const HChar* clo_massif_out_file = "massif.out.%p";
406 static XArray* args_for_massif;
408 static Bool ms_process_cmd_line_option(const HChar* arg)
410 const HChar* tmp_str;
412 // Remember the arg for later use.
413 VG_(addToXA)(args_for_massif, &arg);
415 if VG_BOOL_CLO(arg, "--heap", clo_heap) {}
416 else if VG_BINT_CLO(arg, "--heap-admin", clo_heap_admin, 0, 1024) {}
418 else if VG_BOOL_CLO(arg, "--stacks", clo_stacks) {}
420 else if VG_BOOL_CLO(arg, "--pages-as-heap", clo_pages_as_heap) {}
422 else if VG_BINT_CLO(arg, "--depth", clo_depth, 1, MAX_DEPTH) {}
424 else if VG_STR_CLO(arg, "--alloc-fn", tmp_str) {
425 VG_(addToXA)(alloc_fns, &tmp_str);
427 else if VG_STR_CLO(arg, "--ignore-fn", tmp_str) {
428 VG_(addToXA)(ignore_fns, &tmp_str);
431 else if VG_DBL_CLO(arg, "--threshold", clo_threshold) {
432 if (clo_threshold < 0 || clo_threshold > 100) {
433 VG_(fmsg_bad_option)(arg,
434 "--threshold must be between 0.0 and 100.0\n");
438 else if VG_DBL_CLO(arg, "--peak-inaccuracy", clo_peak_inaccuracy) {}
440 else if VG_XACT_CLO(arg, "--time-unit=i", clo_time_unit, TimeI) {}
441 else if VG_XACT_CLO(arg, "--time-unit=ms", clo_time_unit, TimeMS) {}
442 else if VG_XACT_CLO(arg, "--time-unit=B", clo_time_unit, TimeB) {}
444 else if VG_BINT_CLO(arg, "--detailed-freq", clo_detailed_freq, 1, 1000000) {}
446 else if VG_BINT_CLO(arg, "--max-snapshots", clo_max_snapshots, 10, 1000) {}
448 else if VG_STR_CLO(arg, "--massif-out-file", clo_massif_out_file) {}
450 else
451 return VG_(replacement_malloc_process_cmd_line_option)(arg);
453 return True;
456 static void ms_print_usage(void)
458 VG_(printf)(
459 " --heap=no|yes profile heap blocks [yes]\n"
460 " --heap-admin=<size> average admin bytes per heap block;\n"
461 " ignored if --heap=no [8]\n"
462 " --stacks=no|yes profile stack(s) [no]\n"
463 " --pages-as-heap=no|yes profile memory at the page level [no]\n"
464 " --depth=<number> depth of contexts [30]\n"
465 " --alloc-fn=<name> specify <name> as an alloc function [empty]\n"
466 " --ignore-fn=<name> ignore heap allocations within <name> [empty]\n"
467 " --threshold=<m.n> significance threshold, as a percentage [1.0]\n"
468 " --peak-inaccuracy=<m.n> maximum peak inaccuracy, as a percentage [1.0]\n"
469 " --time-unit=i|ms|B time unit: instructions executed, milliseconds\n"
470 " or heap bytes alloc'd/dealloc'd [i]\n"
471 " --detailed-freq=<N> every Nth snapshot should be detailed [10]\n"
472 " --max-snapshots=<N> maximum number of snapshots recorded [100]\n"
473 " --massif-out-file=<file> output file name [massif.out.%%p]\n"
477 static void ms_print_debug_usage(void)
479 VG_(printf)(
480 " (none)\n"
485 //------------------------------------------------------------//
486 //--- XTrees ---//
487 //------------------------------------------------------------//
489 // The details of the heap are represented by a single XTree.
490 // This XTree maintains the nr of allocated bytes for each
491 // stacktrace/execontext.
493 // The root of the Xtree will be output as a top node 'alloc functions',
494 // which represents all allocation functions, eg:
495 // - malloc/calloc/realloc/memalign/new/new[];
496 // - user-specified allocation functions (using --alloc-fn);
497 // - custom allocation (MALLOCLIKE) points
498 static XTree* heap_xt;
499 /* heap_xt contains a SizeT: the nr of allocated bytes by this execontext. */
500 static void init_szB(void* value)
502 *((SizeT*)value) = 0;
504 static void add_szB(void* to, const void* value)
506 *((SizeT*)to) += *((const SizeT*)value);
508 static void sub_szB(void* from, const void* value)
510 *((SizeT*)from) -= *((const SizeT*)value);
512 static ULong alloc_szB(const void* value)
514 return (ULong)*((const SizeT*)value);
518 //------------------------------------------------------------//
519 //--- XTree Operations ---//
520 //------------------------------------------------------------//
522 // This is the limit on the number of filtered alloc-fns that can be in a
523 // single stacktrace.
524 #define MAX_OVERESTIMATE 50
525 #define MAX_IPS (MAX_DEPTH + MAX_OVERESTIMATE)
527 // filtering out uninteresting entries:
528 // alloc-fns and entries above alloc-fns, and entries below main-or-below-main.
529 // Eg: alloc-fn1 / alloc-fn2 / a / b / main / (below main) / c
530 // becomes: a / b / main
531 // Nb: it's possible to end up with an empty trace, eg. if 'main' is marked
532 // as an alloc-fn. This is ok.
533 static
534 void filter_IPs (Addr* ips, Int n_ips,
535 UInt* top, UInt* n_ips_sel)
537 Int i;
538 Bool top_has_fnname = False;
539 Bool is_alloc_fn = False;
540 Bool is_inline_fn = False;
541 const HChar *fnname;
543 *top = 0;
544 *n_ips_sel = n_ips;
546 // Advance *top as long as we find alloc functions
547 // PW Nov 2016 xtree work:
548 // old massif code was doing something really strange(?buggy):
549 // 'sliding' a bunch of functions without names by removing an
550 // alloc function 'inside' a stacktrace e.g.
551 // 0x1 0x2 0x3 alloc func1 main
552 // became 0x1 0x2 0x3 func1 main
553 const DiEpoch ep = VG_(current_DiEpoch)();
554 InlIPCursor *iipc = NULL;
556 for (i = *top; i < n_ips; ++i) {
557 iipc = VG_(new_IIPC)(ep, ips[i]);
558 do {
559 top_has_fnname = VG_(get_fnname_inl)(ep, ips[i], &fnname, iipc);
560 is_alloc_fn = top_has_fnname && VG_(strIsMemberXA)(alloc_fns, fnname);
561 is_inline_fn = VG_(next_IIPC)(iipc);
562 if (is_alloc_fn && is_inline_fn) {
563 VERB(4, "filtering inline alloc fn %s\n", fnname);
565 } while (is_alloc_fn && is_inline_fn);
566 VG_(delete_IIPC)(iipc);
568 if (is_alloc_fn) {
569 VERB(4, "filtering alloc fn %s\n", fnname);
570 (*top)++;
571 (*n_ips_sel)--;
572 } else {
573 break;
577 // filter the whole stacktrace if this allocation has to be ignored.
578 if (*n_ips_sel > 0 && VG_(sizeXA)(ignore_fns) > 0) {
579 if (!top_has_fnname) {
580 // top has no fnname => search for the first entry that has a fnname
581 for (i = *top; i < n_ips && !top_has_fnname; ++i) {
582 iipc = VG_(new_IIPC)(ep, ips[i]);
583 do {
584 top_has_fnname = VG_(get_fnname_inl)(ep, ips[i], &fnname, iipc);
585 if (top_has_fnname) {
586 break;
588 } while (VG_(next_IIPC)(iipc));
589 VG_(delete_IIPC)(iipc);
592 if (top_has_fnname && VG_(strIsMemberXA)(ignore_fns, fnname)) {
593 VERB(4, "ignored allocation from fn %s\n", fnname);
594 *top = n_ips;
595 *n_ips_sel = 0;
599 if (!VG_(clo_show_below_main) && *n_ips_sel > 0 ) {
600 // Technically, it would be better to use the 'real' epoch that
601 // was used to capture ips/n_ips. However, this searches
602 // for a main or below_main function. It is technically possible
603 // but unlikely that main or below main fn is in a dlclose-d library,
604 // so current epoch is reasonable enough, even if not perfect.
605 // FIXME PW EPOCH: would be better to also use the real ips epoch here,
606 // once m_xtree.c massif output format properly supports epoch.
607 const DiEpoch cur_ep = VG_(current_DiEpoch)();
608 Int mbm = VG_(XT_offset_main_or_below_main)(cur_ep, ips, n_ips);
610 if (mbm < *top) {
611 // Special case: the first main (or below main) function is an
612 // alloc function.
613 *n_ips_sel = 1;
614 VERB(4, "main/below main: keeping 1 fn\n");
615 } else {
616 *n_ips_sel -= n_ips - mbm - 1;
617 VERB(4, "main/below main: filtering %d\n", n_ips - mbm - 1);
621 // filter the frames if we have more than clo_depth
622 if (*n_ips_sel > clo_depth) {
623 VERB(4, "filtering IPs above clo_depth\n");
624 *n_ips_sel = clo_depth;
628 // Capture a stacktrace, and make an ec of it, without the first entry
629 // if exclude_first_entry is True.
630 static ExeContext* make_ec(ThreadId tid, Bool exclude_first_entry)
632 static Addr ips[MAX_IPS];
634 // After this call, the IPs we want are in ips[0]..ips[n_ips-1].
635 Int n_ips = VG_(get_StackTrace)( tid, ips, clo_depth + MAX_OVERESTIMATE,
636 NULL/*array to dump SP values in*/,
637 NULL/*array to dump FP values in*/,
638 0/*first_ip_delta*/ );
639 if (exclude_first_entry) {
640 if (n_ips > 1) {
641 const HChar *fnname;
642 VERB(4, "removing top fn %s from stacktrace\n",
643 VG_(get_fnname)(VG_(current_DiEpoch)(), ips[0], &fnname)
644 ? fnname : "???");
645 return VG_(make_ExeContext_from_StackTrace)(ips+1, n_ips-1);
646 } else {
647 VERB(4, "null execontext as removing top fn with n_ips %d\n", n_ips);
648 return VG_(null_ExeContext) ();
650 } else
651 return VG_(make_ExeContext_from_StackTrace)(ips, n_ips);
654 // Create (or update) in heap_xt an xec corresponding to the stacktrace of tid.
655 // req_szB is added to the xec (unless ec is fully filtered).
656 // Returns the correspding XTree xec.
657 // exclude_first_entry is an optimisation: if True, automatically removes
658 // the top level IP from the stacktrace. Should be set to True if it is known
659 // that this is an alloc fn. The top function presumably will be something like
660 // malloc or __builtin_new that we're sure to filter out).
661 static Xecu add_heap_xt( ThreadId tid, SizeT req_szB, Bool exclude_first_entry)
663 ExeContext *ec = make_ec(tid, exclude_first_entry);
665 if (UNLIKELY(VG_(clo_xtree_memory) == Vg_XTMemory_Full))
666 VG_(XTMemory_Full_alloc)(req_szB, ec);
667 return VG_(XT_add_to_ec) (heap_xt, ec, &req_szB);
670 // Substract req_szB from the heap_xt where.
671 static void sub_heap_xt(Xecu where, SizeT req_szB, Bool exclude_first_entry)
673 tl_assert(clo_heap);
675 if (0 == req_szB)
676 return;
678 VG_(XT_sub_from_xecu) (heap_xt, where, &req_szB);
679 if (UNLIKELY(VG_(clo_xtree_memory) == Vg_XTMemory_Full)) {
680 ExeContext *ec_free = make_ec(VG_(get_running_tid)(),
681 exclude_first_entry);
682 VG_(XTMemory_Full_free)(req_szB,
683 VG_(XT_get_ec_from_xecu)(heap_xt, where),
684 ec_free);
689 //------------------------------------------------------------//
690 //--- Snapshots ---//
691 //------------------------------------------------------------//
693 // Snapshots are done in a way so that we always have a reasonable number of
694 // them. We start by taking them quickly. Once we hit our limit, we cull
695 // some (eg. half), and start taking them more slowly. Once we hit the
696 // limit again, we again cull and then take them even more slowly, and so
697 // on.
699 #define UNUSED_SNAPSHOT_TIME -333 // A conspicuous negative number.
701 typedef
702 enum {
703 Normal = 77,
704 Peak,
705 Unused
707 SnapshotKind;
709 typedef
710 struct {
711 SnapshotKind kind;
712 Time time;
713 SizeT heap_szB;
714 SizeT heap_extra_szB;// Heap slop + admin bytes.
715 SizeT stacks_szB;
716 XTree* xt; // Snapshot of heap_xt, if a detailed snapshot,
717 } // otherwise NULL.
718 Snapshot;
720 static UInt next_snapshot_i = 0; // Index of where next snapshot will go.
721 static Snapshot* snapshots; // Array of snapshots.
723 static Bool is_snapshot_in_use(Snapshot* snapshot)
725 if (Unused == snapshot->kind) {
726 // If snapshot is unused, check all the fields are unset.
727 tl_assert(snapshot->time == UNUSED_SNAPSHOT_TIME);
728 tl_assert(snapshot->heap_extra_szB == 0);
729 tl_assert(snapshot->heap_szB == 0);
730 tl_assert(snapshot->stacks_szB == 0);
731 tl_assert(snapshot->xt == NULL);
732 return False;
733 } else {
734 tl_assert(snapshot->time != UNUSED_SNAPSHOT_TIME);
735 return True;
739 static Bool is_detailed_snapshot(Snapshot* snapshot)
741 return (snapshot->xt ? True : False);
744 static Bool is_uncullable_snapshot(Snapshot* snapshot)
746 return &snapshots[0] == snapshot // First snapshot
747 || &snapshots[next_snapshot_i-1] == snapshot // Last snapshot
748 || snapshot->kind == Peak; // Peak snapshot
751 static void sanity_check_snapshot(Snapshot* snapshot)
753 // Not much we can sanity check.
754 tl_assert(snapshot->xt == NULL || snapshot->kind != Unused);
757 // All the used entries should look used, all the unused ones should be clear.
758 static void sanity_check_snapshots_array(void)
760 Int i;
761 for (i = 0; i < next_snapshot_i; i++) {
762 tl_assert( is_snapshot_in_use( & snapshots[i] ));
764 for ( ; i < clo_max_snapshots; i++) {
765 tl_assert(!is_snapshot_in_use( & snapshots[i] ));
769 // This zeroes all the fields in the snapshot, but does not free the xt
770 // XTree if present. It also does a sanity check unless asked not to; we
771 // can't sanity check at startup when clearing the initial snapshots because
772 // they're full of junk.
773 static void clear_snapshot(Snapshot* snapshot, Bool do_sanity_check)
775 if (do_sanity_check) sanity_check_snapshot(snapshot);
776 snapshot->kind = Unused;
777 snapshot->time = UNUSED_SNAPSHOT_TIME;
778 snapshot->heap_extra_szB = 0;
779 snapshot->heap_szB = 0;
780 snapshot->stacks_szB = 0;
781 snapshot->xt = NULL;
784 // This zeroes all the fields in the snapshot, and frees the heap XTree xt if
785 // present.
786 static void delete_snapshot(Snapshot* snapshot)
788 // Nb: if there's an XTree, we free it after calling clear_snapshot,
789 // because clear_snapshot does a sanity check which includes checking the
790 // XTree.
791 XTree* tmp_xt = snapshot->xt;
792 clear_snapshot(snapshot, /*do_sanity_check*/True);
793 if (tmp_xt) {
794 VG_(XT_delete)(tmp_xt);
798 static void VERB_snapshot(Int verbosity, const HChar* prefix, Int i)
800 Snapshot* snapshot = &snapshots[i];
801 const HChar* suffix;
802 switch (snapshot->kind) {
803 case Peak: suffix = "p"; break;
804 case Normal: suffix = ( is_detailed_snapshot(snapshot) ? "d" : "." ); break;
805 case Unused: suffix = "u"; break;
806 default:
807 tl_assert2(0, "VERB_snapshot: unknown snapshot kind: %d", snapshot->kind);
809 VERB(verbosity, "%s S%s%3d (t:%lld, hp:%lu, ex:%lu, st:%lu)\n",
810 prefix, suffix, i,
811 snapshot->time,
812 snapshot->heap_szB,
813 snapshot->heap_extra_szB,
814 snapshot->stacks_szB
818 // Cull half the snapshots; we choose those that represent the smallest
819 // time-spans, because that gives us the most even distribution of snapshots
820 // over time. (It's possible to lose interesting spikes, however.)
822 // Algorithm for N snapshots: We find the snapshot representing the smallest
823 // timeframe, and remove it. We repeat this until (N/2) snapshots are gone.
824 // We have to do this one snapshot at a time, rather than finding the (N/2)
825 // smallest snapshots in one hit, because when a snapshot is removed, its
826 // neighbours immediately cover greater timespans. So it's O(N^2), but N is
827 // small, and it's not done very often.
829 // Once we're done, we return the new smallest interval between snapshots.
830 // That becomes our minimum time interval.
831 static UInt cull_snapshots(void)
833 Int i, jp, j, jn, min_timespan_i;
834 Int n_deleted = 0;
835 Time min_timespan;
837 n_cullings++;
839 // Sets j to the index of the first not-yet-removed snapshot at or after i
840 #define FIND_SNAPSHOT(i, j) \
841 for (j = i; \
842 j < clo_max_snapshots && !is_snapshot_in_use(&snapshots[j]); \
843 j++) { }
845 VERB(2, "Culling...\n");
847 // First we remove enough snapshots by clearing them in-place. Once
848 // that's done, we can slide the remaining ones down.
849 for (i = 0; i < clo_max_snapshots/2; i++) {
850 // Find the snapshot representing the smallest timespan. The timespan
851 // for snapshot n = d(N-1,N)+d(N,N+1), where d(A,B) is the time between
852 // snapshot A and B. We don't consider the first and last snapshots for
853 // removal.
854 Snapshot* min_snapshot;
855 Int min_j;
857 // Initial triple: (prev, curr, next) == (jp, j, jn)
858 // Initial min_timespan is the first one.
859 jp = 0;
860 FIND_SNAPSHOT(1, j);
861 FIND_SNAPSHOT(j+1, jn);
862 min_timespan = 0x7fffffffffffffffLL;
863 min_j = -1;
864 while (jn < clo_max_snapshots) {
865 Time timespan = snapshots[jn].time - snapshots[jp].time;
866 tl_assert(timespan >= 0);
867 // Nb: We never cull the peak snapshot.
868 if (Peak != snapshots[j].kind && timespan < min_timespan) {
869 min_timespan = timespan;
870 min_j = j;
872 // Move on to next triple
873 jp = j;
874 j = jn;
875 FIND_SNAPSHOT(jn+1, jn);
877 // We've found the least important snapshot, now delete it. First
878 // print it if necessary.
879 tl_assert(-1 != min_j); // Check we found a minimum.
880 min_snapshot = & snapshots[ min_j ];
881 if (VG_(clo_verbosity) > 1) {
882 HChar buf[64]; // large enough
883 VG_(snprintf)(buf, 64, " %3d (t-span = %lld)", i, min_timespan);
884 VERB_snapshot(2, buf, min_j);
886 delete_snapshot(min_snapshot);
887 n_deleted++;
890 // Slide down the remaining snapshots over the removed ones. First set i
891 // to point to the first empty slot, and j to the first full slot after
892 // i. Then slide everything down.
893 for (i = 0; is_snapshot_in_use( &snapshots[i] ); i++) { }
894 for (j = i; !is_snapshot_in_use( &snapshots[j] ); j++) { }
895 for ( ; j < clo_max_snapshots; j++) {
896 if (is_snapshot_in_use( &snapshots[j] )) {
897 snapshots[i++] = snapshots[j];
898 clear_snapshot(&snapshots[j], /*do_sanity_check*/True);
901 next_snapshot_i = i;
903 // Check snapshots array looks ok after changes.
904 sanity_check_snapshots_array();
906 // Find the minimum timespan remaining; that will be our new minimum
907 // time interval. Note that above we were finding timespans by measuring
908 // two intervals around a snapshot that was under consideration for
909 // deletion. Here we only measure single intervals because all the
910 // deletions have occurred.
912 // But we have to be careful -- some snapshots (eg. snapshot 0, and the
913 // peak snapshot) are uncullable. If two uncullable snapshots end up
914 // next to each other, they'll never be culled (assuming the peak doesn't
915 // change), and the time gap between them will not change. However, the
916 // time between the remaining cullable snapshots will grow ever larger.
917 // This means that the min_timespan found will always be that between the
918 // two uncullable snapshots, and it will be much smaller than it should
919 // be. To avoid this problem, when computing the minimum timespan, we
920 // ignore any timespans between two uncullable snapshots.
921 tl_assert(next_snapshot_i > 1);
922 min_timespan = 0x7fffffffffffffffLL;
923 min_timespan_i = -1;
924 for (i = 1; i < next_snapshot_i; i++) {
925 if (is_uncullable_snapshot(&snapshots[i]) &&
926 is_uncullable_snapshot(&snapshots[i-1]))
928 VERB(2, "(Ignoring interval %d--%d when computing minimum)\n", i-1, i);
929 } else {
930 Time timespan = snapshots[i].time - snapshots[i-1].time;
931 tl_assert(timespan >= 0);
932 if (timespan < min_timespan) {
933 min_timespan = timespan;
934 min_timespan_i = i;
938 tl_assert(-1 != min_timespan_i); // Check we found a minimum.
940 // Print remaining snapshots, if necessary.
941 if (VG_(clo_verbosity) > 1) {
942 VERB(2, "Finished culling (%3d of %3d deleted)\n",
943 n_deleted, clo_max_snapshots);
944 for (i = 0; i < next_snapshot_i; i++) {
945 VERB_snapshot(2, " post-cull", i);
947 VERB(2, "New time interval = %lld (between snapshots %d and %d)\n",
948 min_timespan, min_timespan_i-1, min_timespan_i);
951 return min_timespan;
954 static Time get_time(void)
956 // Get current time, in whatever time unit we're using.
957 if (clo_time_unit == TimeI) {
958 return guest_instrs_executed;
959 } else if (clo_time_unit == TimeMS) {
960 // Some stuff happens between the millisecond timer being initialised
961 // to zero and us taking our first snapshot. We determine that time
962 // gap so we can subtract it from all subsequent times so that our
963 // first snapshot is considered to be at t = 0ms. Unfortunately, a
964 // bunch of symbols get read after the first snapshot is taken but
965 // before the second one (which is triggered by the first allocation),
966 // so when the time-unit is 'ms' we always have a big gap between the
967 // first two snapshots. But at least users won't have to wonder why
968 // the first snapshot isn't at t=0.
969 static Bool is_first_get_time = True;
970 static Time start_time_ms;
971 if (is_first_get_time) {
972 start_time_ms = VG_(read_millisecond_timer)();
973 is_first_get_time = False;
974 return 0;
975 } else {
976 return VG_(read_millisecond_timer)() - start_time_ms;
978 } else if (clo_time_unit == TimeB) {
979 return total_allocs_deallocs_szB;
980 } else {
981 tl_assert2(0, "bad --time-unit value");
985 // Take a snapshot, and only that -- decisions on whether to take a
986 // snapshot, or what kind of snapshot, are made elsewhere.
987 // Nb: we call the arg "my_time" because "time" shadows a global declaration
988 // in /usr/include/time.h on Darwin.
989 static void
990 take_snapshot(Snapshot* snapshot, SnapshotKind kind, Time my_time,
991 Bool is_detailed)
993 tl_assert(!is_snapshot_in_use(snapshot));
994 if (!clo_pages_as_heap) {
995 tl_assert(have_started_executing_code);
998 // Heap and heap admin.
999 if (clo_heap) {
1000 snapshot->heap_szB = heap_szB;
1001 if (is_detailed) {
1002 snapshot->xt = VG_(XT_snapshot)(heap_xt);
1004 snapshot->heap_extra_szB = heap_extra_szB;
1007 // Stack(s).
1008 if (clo_stacks) {
1009 snapshot->stacks_szB = stacks_szB;
1012 // Rest of snapshot.
1013 snapshot->kind = kind;
1014 snapshot->time = my_time;
1015 sanity_check_snapshot(snapshot);
1017 // Update stats.
1018 if (Peak == kind) n_peak_snapshots++;
1019 if (is_detailed) n_detailed_snapshots++;
1020 n_real_snapshots++;
1024 // Take a snapshot, if it's time, or if we've hit a peak.
1025 static void
1026 maybe_take_snapshot(SnapshotKind kind, const HChar* what)
1028 // 'min_time_interval' is the minimum time interval between snapshots.
1029 // If we try to take a snapshot and less than this much time has passed,
1030 // we don't take it. It gets larger as the program runs longer. It's
1031 // initialised to zero so that we begin by taking snapshots as quickly as
1032 // possible.
1033 static Time min_time_interval = 0;
1034 // Zero allows startup snapshot.
1035 static Time earliest_possible_time_of_next_snapshot = 0;
1036 static Int n_snapshots_since_last_detailed = 0;
1037 static Int n_skipped_snapshots_since_last_snapshot = 0;
1039 Snapshot* snapshot;
1040 Bool is_detailed;
1041 // Nb: we call this variable "my_time" because "time" shadows a global
1042 // declaration in /usr/include/time.h on Darwin.
1043 Time my_time = get_time();
1045 switch (kind) {
1046 case Normal:
1047 // Only do a snapshot if it's time.
1048 if (my_time < earliest_possible_time_of_next_snapshot) {
1049 n_skipped_snapshots++;
1050 n_skipped_snapshots_since_last_snapshot++;
1051 return;
1053 is_detailed = (clo_detailed_freq-1 == n_snapshots_since_last_detailed);
1054 break;
1056 case Peak: {
1057 // Because we're about to do a deallocation, we're coming down from a
1058 // local peak. If it is (a) actually a global peak, and (b) a certain
1059 // amount bigger than the previous peak, then we take a peak snapshot.
1060 // By not taking a snapshot for every peak, we save a lot of effort --
1061 // because many peaks remain peak only for a short time.
1062 SizeT total_szB = heap_szB + heap_extra_szB + stacks_szB;
1063 SizeT excess_szB_for_new_peak =
1064 (SizeT)((peak_snapshot_total_szB * clo_peak_inaccuracy) / 100);
1065 if (total_szB <= peak_snapshot_total_szB + excess_szB_for_new_peak) {
1066 return;
1068 is_detailed = True;
1069 break;
1072 default:
1073 tl_assert2(0, "maybe_take_snapshot: unrecognised snapshot kind");
1076 // Take the snapshot.
1077 snapshot = & snapshots[next_snapshot_i];
1078 take_snapshot(snapshot, kind, my_time, is_detailed);
1080 // Record if it was detailed.
1081 if (is_detailed) {
1082 n_snapshots_since_last_detailed = 0;
1083 } else {
1084 n_snapshots_since_last_detailed++;
1087 // Update peak data, if it's a Peak snapshot.
1088 if (Peak == kind) {
1089 Int i, number_of_peaks_snapshots_found = 0;
1091 // Sanity check the size, then update our recorded peak.
1092 SizeT snapshot_total_szB =
1093 snapshot->heap_szB + snapshot->heap_extra_szB + snapshot->stacks_szB;
1094 tl_assert2(snapshot_total_szB > peak_snapshot_total_szB,
1095 "%ld, %ld\n", snapshot_total_szB, peak_snapshot_total_szB);
1096 peak_snapshot_total_szB = snapshot_total_szB;
1098 // Find the old peak snapshot, if it exists, and mark it as normal.
1099 for (i = 0; i < next_snapshot_i; i++) {
1100 if (Peak == snapshots[i].kind) {
1101 snapshots[i].kind = Normal;
1102 number_of_peaks_snapshots_found++;
1105 tl_assert(number_of_peaks_snapshots_found <= 1);
1108 // Finish up verbosity and stats stuff.
1109 if (n_skipped_snapshots_since_last_snapshot > 0) {
1110 VERB(2, " (skipped %d snapshot%s)\n",
1111 n_skipped_snapshots_since_last_snapshot,
1112 ( 1 == n_skipped_snapshots_since_last_snapshot ? "" : "s") );
1114 VERB_snapshot(2, what, next_snapshot_i);
1115 n_skipped_snapshots_since_last_snapshot = 0;
1117 // Cull the entries, if our snapshot table is full.
1118 next_snapshot_i++;
1119 if (clo_max_snapshots == next_snapshot_i) {
1120 min_time_interval = cull_snapshots();
1123 // Work out the earliest time when the next snapshot can happen.
1124 earliest_possible_time_of_next_snapshot = my_time + min_time_interval;
1128 //------------------------------------------------------------//
1129 //--- Sanity checking ---//
1130 //------------------------------------------------------------//
1132 static Bool ms_cheap_sanity_check ( void )
1134 return True; // Nothing useful we can cheaply check.
1137 static Bool ms_expensive_sanity_check ( void )
1139 tl_assert(heap_xt);
1140 sanity_check_snapshots_array();
1141 return True;
1145 //------------------------------------------------------------//
1146 //--- Heap management ---//
1147 //------------------------------------------------------------//
1149 // Metadata for heap blocks. Each one contains an Xecu,
1150 // which identifies the XTree ec at which it was allocated. From
1151 // HP_Chunks, XTree ec 'space' field is incremented (at allocation) and
1152 // decremented (at deallocation).
1154 // Nb: first two fields must match core's VgHashNode.
1155 typedef
1156 struct _HP_Chunk {
1157 struct _HP_Chunk* next;
1158 Addr data; // Ptr to actual block
1159 SizeT req_szB; // Size requested
1160 SizeT slop_szB; // Extra bytes given above those requested
1161 Xecu where; // Where allocated; XTree xecu from heap_xt
1163 HP_Chunk;
1165 /* Pool allocator for HP_Chunk. */
1166 static PoolAlloc *HP_chunk_poolalloc = NULL;
1168 static VgHashTable *malloc_list = NULL; // HP_Chunks
1170 static void update_alloc_stats(SSizeT szB_delta)
1172 // Update total_allocs_deallocs_szB.
1173 if (szB_delta < 0) szB_delta = -szB_delta;
1174 total_allocs_deallocs_szB += szB_delta;
1177 static void update_heap_stats(SSizeT heap_szB_delta, Int heap_extra_szB_delta)
1179 if (heap_szB_delta < 0)
1180 tl_assert(heap_szB >= -heap_szB_delta);
1181 if (heap_extra_szB_delta < 0)
1182 tl_assert(heap_extra_szB >= -heap_extra_szB_delta);
1184 heap_extra_szB += heap_extra_szB_delta;
1185 heap_szB += heap_szB_delta;
1187 update_alloc_stats(heap_szB_delta + heap_extra_szB_delta);
1190 static
1191 void* record_block( ThreadId tid, void* p, SizeT req_szB, SizeT slop_szB,
1192 Bool exclude_first_entry, Bool maybe_snapshot )
1194 // Make new HP_Chunk node, add to malloc_list
1195 HP_Chunk* hc = VG_(allocEltPA)(HP_chunk_poolalloc);
1196 hc->req_szB = req_szB;
1197 hc->slop_szB = slop_szB;
1198 hc->data = (Addr)p;
1199 hc->where = 0;
1200 VG_(HT_add_node)(malloc_list, hc);
1202 if (clo_heap) {
1203 VERB(3, "<<< record_block (%lu, %lu)\n", req_szB, slop_szB);
1205 hc->where = add_heap_xt( tid, req_szB, exclude_first_entry);
1207 if (VG_(XT_n_ips_sel)(heap_xt, hc->where) > 0) {
1208 // Update statistics.
1209 n_heap_allocs++;
1211 // Update heap stats.
1212 update_heap_stats(req_szB, clo_heap_admin + slop_szB);
1214 // Maybe take a snapshot.
1215 if (maybe_snapshot) {
1216 maybe_take_snapshot(Normal, " alloc");
1219 } else {
1220 // Ignored allocation.
1221 n_ignored_heap_allocs++;
1223 VERB(3, "(ignored)\n");
1226 VERB(3, ">>>\n");
1229 return p;
1232 static __inline__
1233 void* alloc_and_record_block ( ThreadId tid, SizeT req_szB, SizeT req_alignB,
1234 Bool is_zeroed )
1236 SizeT actual_szB, slop_szB;
1237 void* p;
1239 if ((SSizeT)req_szB < 0) return NULL;
1241 // Allocate and zero if necessary.
1242 p = VG_(cli_malloc)( req_alignB, req_szB );
1243 if (!p) {
1244 return NULL;
1246 if (is_zeroed) VG_(memset)(p, 0, req_szB);
1247 actual_szB = VG_(cli_malloc_usable_size)(p);
1248 tl_assert(actual_szB >= req_szB);
1249 slop_szB = actual_szB - req_szB;
1251 // Record block.
1252 record_block(tid, p, req_szB, slop_szB, /*exclude_first_entry*/True,
1253 /*maybe_snapshot*/True);
1255 return p;
1258 static __inline__
1259 void unrecord_block ( void* p, Bool maybe_snapshot, Bool exclude_first_entry )
1261 // Remove HP_Chunk from malloc_list
1262 HP_Chunk* hc = VG_(HT_remove)(malloc_list, (UWord)p);
1263 if (NULL == hc) {
1264 return; // must have been a bogus free()
1267 if (clo_heap) {
1268 VERB(3, "<<< unrecord_block\n");
1270 if (VG_(XT_n_ips_sel)(heap_xt, hc->where) > 0) {
1271 // Update statistics.
1272 n_heap_frees++;
1274 // Maybe take a peak snapshot, since it's a deallocation.
1275 if (maybe_snapshot) {
1276 maybe_take_snapshot(Peak, "de-PEAK");
1279 // Update heap stats.
1280 update_heap_stats(-hc->req_szB, -clo_heap_admin - hc->slop_szB);
1282 // Update XTree.
1283 sub_heap_xt(hc->where, hc->req_szB, exclude_first_entry);
1285 // Maybe take a snapshot.
1286 if (maybe_snapshot) {
1287 maybe_take_snapshot(Normal, "dealloc");
1290 } else {
1291 n_ignored_heap_frees++;
1293 VERB(3, "(ignored)\n");
1296 VERB(3, ">>> (-%lu, -%lu)\n", hc->req_szB, hc->slop_szB);
1299 // Actually free the chunk, and the heap block (if necessary)
1300 VG_(freeEltPA) (HP_chunk_poolalloc, hc); hc = NULL;
1303 // Nb: --ignore-fn is tricky for realloc. If the block's original alloc was
1304 // ignored, but the realloc is not requested to be ignored, and we are
1305 // shrinking the block, then we have to ignore the realloc -- otherwise we
1306 // could end up with negative heap sizes. This isn't a danger if we are
1307 // growing such a block, but for consistency (it also simplifies things) we
1308 // ignore such reallocs as well.
1309 // PW Nov 2016 xtree work: why can't we just consider that a realloc of an
1310 // ignored alloc is just a new alloc (i.e. do not remove the old sz from the
1311 // stats). Then everything would be fine, and a non ignored realloc would be
1312 // counted properly.
1313 static __inline__
1314 void* realloc_block ( ThreadId tid, void* p_old, SizeT new_req_szB )
1316 HP_Chunk* hc;
1317 void* p_new;
1318 SizeT old_req_szB, old_slop_szB, new_slop_szB, new_actual_szB;
1319 Xecu old_where;
1320 Bool is_ignored = False;
1322 if (p_old == NULL) {
1323 return alloc_and_record_block( tid, new_req_szB, VG_(clo_alignment), /*is_zeroed*/False );
1326 if (new_req_szB == 0U) {
1327 if (VG_(clo_realloc_zero_bytes_frees) == True) {
1328 /* like ms_free */
1329 unrecord_block(p_old, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1330 VG_(cli_free)(p_old);
1331 return NULL;
1333 new_req_szB = 1U;
1336 // Remove the old block
1337 hc = VG_(HT_remove)(malloc_list, (UWord)p_old);
1338 if (hc == NULL) {
1339 return NULL; // must have been a bogus realloc()
1342 old_req_szB = hc->req_szB;
1343 old_slop_szB = hc->slop_szB;
1345 tl_assert(!clo_pages_as_heap); // Shouldn't be here if --pages-as-heap=yes.
1346 if (clo_heap) {
1347 VERB(3, "<<< realloc_block (%lu)\n", new_req_szB);
1349 if (VG_(XT_n_ips_sel)(heap_xt, hc->where) > 0) {
1350 // Update statistics.
1351 n_heap_reallocs++;
1353 // Maybe take a peak snapshot, if it's (effectively) a deallocation.
1354 if (new_req_szB < old_req_szB) {
1355 maybe_take_snapshot(Peak, "re-PEAK");
1357 } else {
1358 // The original malloc was ignored, so we have to ignore the
1359 // realloc as well.
1360 is_ignored = True;
1364 // Actually do the allocation, if necessary.
1365 if (new_req_szB <= old_req_szB + old_slop_szB) {
1366 // New size is smaller or same; block not moved.
1367 p_new = p_old;
1368 new_slop_szB = old_slop_szB + (old_req_szB - new_req_szB);
1370 } else {
1371 // New size is bigger; make new block, copy shared contents, free old.
1372 p_new = VG_(cli_malloc)(VG_(clo_alignment), new_req_szB);
1373 if (!p_new) {
1374 // Nb: if realloc fails, NULL is returned but the old block is not
1375 // touched. What an awful function.
1376 return NULL;
1378 VG_(memcpy)(p_new, p_old, old_req_szB + old_slop_szB);
1379 VG_(cli_free)(p_old);
1380 new_actual_szB = VG_(cli_malloc_usable_size)(p_new);
1381 tl_assert(new_actual_szB >= new_req_szB);
1382 new_slop_szB = new_actual_szB - new_req_szB;
1385 if (p_new) {
1386 // Update HP_Chunk.
1387 hc->data = (Addr)p_new;
1388 hc->req_szB = new_req_szB;
1389 hc->slop_szB = new_slop_szB;
1390 old_where = hc->where;
1391 hc->where = 0;
1393 // Update XTree.
1394 if (clo_heap) {
1395 hc->where = add_heap_xt( tid, new_req_szB,
1396 /*exclude_first_entry*/True);
1397 if (!is_ignored && VG_(XT_n_ips_sel)(heap_xt, hc->where) > 0) {
1398 sub_heap_xt(old_where, old_req_szB, /*exclude_first_entry*/True);
1399 } else {
1400 // The realloc itself is ignored.
1401 is_ignored = True;
1403 /* XTREE??? hack to have something compatible with pre
1404 m_xtree massif: if the previous alloc/realloc was
1405 ignored, and this one is not ignored, then keep the
1406 previous where, to continue marking this memory as
1407 ignored. */
1408 if (VG_(XT_n_ips_sel)(heap_xt, hc->where) > 0
1409 && VG_(XT_n_ips_sel)(heap_xt, old_where) == 0)
1410 hc->where = old_where;
1412 // Update statistics.
1413 n_ignored_heap_reallocs++;
1418 // Now insert the new hc (with a possibly new 'data' field) into
1419 // malloc_list. If this realloc() did not increase the memory size, we
1420 // will have removed and then re-added hc unnecessarily. But that's ok
1421 // because shrinking a block with realloc() is (presumably) much rarer
1422 // than growing it, and this way simplifies the growing case.
1423 VG_(HT_add_node)(malloc_list, hc);
1425 if (clo_heap) {
1426 if (!is_ignored) {
1427 // Update heap stats.
1428 update_heap_stats(new_req_szB - old_req_szB,
1429 new_slop_szB - old_slop_szB);
1431 // Maybe take a snapshot.
1432 maybe_take_snapshot(Normal, "realloc");
1433 } else {
1435 VERB(3, "(ignored)\n");
1438 VERB(3, ">>> (%ld, %ld)\n",
1439 (SSizeT)(new_req_szB - old_req_szB),
1440 (SSizeT)(new_slop_szB - old_slop_szB));
1443 return p_new;
1447 //------------------------------------------------------------//
1448 //--- malloc() et al replacement wrappers ---//
1449 //------------------------------------------------------------//
1451 static void* ms_malloc ( ThreadId tid, SizeT szB )
1453 return alloc_and_record_block( tid, szB, VG_(clo_alignment), /*is_zeroed*/False );
1456 static void* ms___builtin_new ( ThreadId tid, SizeT szB )
1458 return alloc_and_record_block( tid, szB, VG_(clo_alignment), /*is_zeroed*/False );
1461 static void* ms___builtin_new_aligned ( ThreadId tid, SizeT szB, SizeT alignB , SizeT orig_alignB )
1463 return alloc_and_record_block( tid, szB, alignB, /*is_zeroed*/False );
1466 static void* ms___builtin_vec_new ( ThreadId tid, SizeT szB )
1468 return alloc_and_record_block( tid, szB, VG_(clo_alignment), /*is_zeroed*/False );
1471 static void* ms___builtin_vec_new_aligned ( ThreadId tid, SizeT szB, SizeT alignB, SizeT orig_alignB )
1473 return alloc_and_record_block( tid, szB, alignB, /*is_zeroed*/False );
1476 static void* ms_calloc ( ThreadId tid, SizeT m, SizeT szB )
1478 return alloc_and_record_block( tid, m*szB, VG_(clo_alignment), /*is_zeroed*/True );
1481 static void *ms_memalign ( ThreadId tid, SizeT alignB, SizeT orig_alignB, SizeT szB)
1483 return alloc_and_record_block( tid, szB, alignB, False );
1486 static void ms_free ( ThreadId tid __attribute__((unused)), void* p )
1488 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1489 VG_(cli_free)(p);
1492 static void ms___builtin_delete ( ThreadId tid, void* p )
1494 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1495 VG_(cli_free)(p);
1498 static void ms___builtin_delete_aligned ( ThreadId tid, void* p, SizeT align )
1500 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1501 VG_(cli_free)(p);
1504 static void ms___builtin_vec_delete ( ThreadId tid, void* p )
1506 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1507 VG_(cli_free)(p);
1510 static void ms___builtin_vec_delete_aligned ( ThreadId tid, void* p, SizeT align )
1512 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/True);
1513 VG_(cli_free)(p);
1516 static void* ms_realloc ( ThreadId tid, void* p_old, SizeT new_szB )
1518 return realloc_block(tid, p_old, new_szB);
1521 static SizeT ms_malloc_usable_size ( ThreadId tid, void* p )
1523 HP_Chunk* hc = VG_(HT_lookup)( malloc_list, (UWord)p );
1525 return ( hc ? hc->req_szB + hc->slop_szB : 0 );
1528 //------------------------------------------------------------//
1529 //--- Page handling ---//
1530 //------------------------------------------------------------//
1532 static
1533 void ms_record_page_mem ( Addr a, SizeT len )
1535 ThreadId tid = VG_(get_running_tid)();
1536 Addr end;
1537 tl_assert(VG_IS_PAGE_ALIGNED(len));
1538 tl_assert(len >= VKI_PAGE_SIZE);
1539 // Record the first N-1 pages as blocks, but don't do any snapshots.
1540 for (end = a + len - VKI_PAGE_SIZE; a < end; a += VKI_PAGE_SIZE) {
1541 record_block( tid, (void*)a, VKI_PAGE_SIZE, /*slop_szB*/0,
1542 /*exclude_first_entry*/False, /*maybe_snapshot*/False );
1544 // Record the last page as a block, and maybe do a snapshot afterwards.
1545 record_block( tid, (void*)a, VKI_PAGE_SIZE, /*slop_szB*/0,
1546 /*exclude_first_entry*/False, /*maybe_snapshot*/True );
1549 static
1550 void ms_unrecord_page_mem( Addr a, SizeT len )
1552 Addr end;
1553 tl_assert(VG_IS_PAGE_ALIGNED(len));
1554 tl_assert(len >= VKI_PAGE_SIZE);
1555 // Unrecord the first page. This might be the peak, so do a snapshot.
1556 unrecord_block((void*)a, /*maybe_snapshot*/True,
1557 /*exclude_first_entry*/False);
1558 a += VKI_PAGE_SIZE;
1559 // Then unrecord the remaining pages, but without snapshots.
1560 for (end = a + len - VKI_PAGE_SIZE; a < end; a += VKI_PAGE_SIZE) {
1561 unrecord_block((void*)a, /*maybe_snapshot*/False,
1562 /*exclude_first_entry*/False);
1566 //------------------------------------------------------------//
1568 static
1569 void ms_new_mem_mmap ( Addr a, SizeT len,
1570 Bool rr, Bool ww, Bool xx, ULong di_handle )
1572 tl_assert(VG_IS_PAGE_ALIGNED(len));
1573 ms_record_page_mem(a, len);
1576 static
1577 void ms_new_mem_startup( Addr a, SizeT len,
1578 Bool rr, Bool ww, Bool xx, ULong di_handle )
1580 // startup maps are always be page-sized, except the trampoline page is
1581 // marked by the core as only being the size of the trampoline itself,
1582 // which is something like 57 bytes. Round it up to page size.
1583 len = VG_PGROUNDUP(len);
1584 ms_record_page_mem(a, len);
1587 static
1588 void ms_new_mem_brk ( Addr a, SizeT len, ThreadId tid )
1590 // brk limit is not necessarily aligned on a page boundary.
1591 // If new memory being brk-ed implies to allocate a new page,
1592 // then call ms_record_page_mem with page aligned parameters
1593 // otherwise just ignore.
1594 Addr old_bottom_page = VG_PGROUNDDN(a - 1);
1595 Addr new_top_page = VG_PGROUNDDN(a + len - 1);
1596 if (old_bottom_page != new_top_page)
1597 ms_record_page_mem(VG_PGROUNDDN(a),
1598 (new_top_page - old_bottom_page));
1601 static
1602 void ms_copy_mem_remap( Addr from, Addr to, SizeT len)
1604 tl_assert(VG_IS_PAGE_ALIGNED(len));
1605 ms_unrecord_page_mem(from, len);
1606 ms_record_page_mem(to, len);
1609 static
1610 void ms_die_mem_munmap( Addr a, SizeT len )
1612 tl_assert(VG_IS_PAGE_ALIGNED(len));
1613 ms_unrecord_page_mem(a, len);
1616 static
1617 void ms_die_mem_brk( Addr a, SizeT len )
1619 // Call ms_unrecord_page_mem only if one or more pages are de-allocated.
1620 // See ms_new_mem_brk for more details.
1621 Addr new_bottom_page = VG_PGROUNDDN(a - 1);
1622 Addr old_top_page = VG_PGROUNDDN(a + len - 1);
1623 if (old_top_page != new_bottom_page)
1624 ms_unrecord_page_mem(VG_PGROUNDDN(a),
1625 (old_top_page - new_bottom_page));
1629 //------------------------------------------------------------//
1630 //--- Stacks ---//
1631 //------------------------------------------------------------//
1633 // We really want the inlining to occur...
1634 #define INLINE inline __attribute__((always_inline))
1636 static void update_stack_stats(SSizeT stack_szB_delta)
1638 if (stack_szB_delta < 0) tl_assert(stacks_szB >= -stack_szB_delta);
1639 stacks_szB += stack_szB_delta;
1641 update_alloc_stats(stack_szB_delta);
1644 static INLINE void new_mem_stack_2(SizeT len, const HChar* what)
1646 if (have_started_executing_code) {
1647 VERB(3, "<<< new_mem_stack (%lu)\n", len);
1648 n_stack_allocs++;
1649 update_stack_stats(len);
1650 maybe_take_snapshot(Normal, what);
1651 VERB(3, ">>>\n");
1655 static INLINE void die_mem_stack_2(SizeT len, const HChar* what)
1657 if (have_started_executing_code) {
1658 VERB(3, "<<< die_mem_stack (-%lu)\n", len);
1659 n_stack_frees++;
1660 maybe_take_snapshot(Peak, "stkPEAK");
1661 update_stack_stats(-len);
1662 maybe_take_snapshot(Normal, what);
1663 VERB(3, ">>>\n");
1667 static void new_mem_stack(Addr a, SizeT len)
1669 new_mem_stack_2(len, "stk-new");
1672 static void die_mem_stack(Addr a, SizeT len)
1674 die_mem_stack_2(len, "stk-die");
1677 static void new_mem_stack_signal(Addr a, SizeT len, ThreadId tid)
1679 new_mem_stack_2(len, "sig-new");
1682 static void die_mem_stack_signal(Addr a, SizeT len)
1684 die_mem_stack_2(len, "sig-die");
1688 //------------------------------------------------------------//
1689 //--- Client Requests ---//
1690 //------------------------------------------------------------//
1692 static void print_monitor_help ( void )
1694 VG_(gdb_printf) (
1695 "\n"
1696 "massif monitor commands:\n"
1697 " snapshot [<filename>]\n"
1698 " detailed_snapshot [<filename>]\n"
1699 " takes a snapshot (or a detailed snapshot)\n"
1700 " and saves it in <filename>\n"
1701 " default <filename> is massif.vgdb.out\n"
1702 " all_snapshots [<filename>]\n"
1703 " saves all snapshot(s) taken so far in <filename>\n"
1704 " default <filename> is massif.vgdb.out\n"
1705 " xtmemory [<filename>]\n"
1706 " dump xtree memory profile in <filename> (default xtmemory.kcg.%%p.%%n)\n"
1707 "\n");
1711 /* Forward declaration.
1712 return True if request recognised, False otherwise */
1713 static Bool handle_gdb_monitor_command (ThreadId tid, HChar *req);
1714 static Bool ms_handle_client_request ( ThreadId tid, UWord* argv, UWord* ret )
1716 switch (argv[0]) {
1717 case VG_USERREQ__MALLOCLIKE_BLOCK: {
1718 void* p = (void*)argv[1];
1719 SizeT szB = argv[2];
1720 record_block( tid, p, szB, /*slop_szB*/0, /*exclude_first_entry*/False,
1721 /*maybe_snapshot*/True );
1722 *ret = 0;
1723 return True;
1725 case VG_USERREQ__RESIZEINPLACE_BLOCK: {
1726 void* p = (void*)argv[1];
1727 SizeT newSizeB = argv[3];
1729 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/False);
1730 record_block(tid, p, newSizeB, /*slop_szB*/0,
1731 /*exclude_first_entry*/False, /*maybe_snapshot*/True);
1732 return True;
1734 case VG_USERREQ__FREELIKE_BLOCK: {
1735 void* p = (void*)argv[1];
1736 unrecord_block(p, /*maybe_snapshot*/True, /*exclude_first_entry*/False);
1737 *ret = 0;
1738 return True;
1740 case VG_USERREQ__GDB_MONITOR_COMMAND: {
1741 Bool handled = handle_gdb_monitor_command (tid, (HChar*)argv[1]);
1742 if (handled)
1743 *ret = 1;
1744 else
1745 *ret = 0;
1746 return handled;
1749 default:
1750 *ret = 0;
1751 return False;
1755 //------------------------------------------------------------//
1756 //--- Instrumentation ---//
1757 //------------------------------------------------------------//
1759 static void add_counter_update(IRSB* sbOut, Int n)
1761 #if defined(VG_BIGENDIAN)
1762 # define END Iend_BE
1763 #elif defined(VG_LITTLEENDIAN)
1764 # define END Iend_LE
1765 #else
1766 # error "Unknown endianness"
1767 #endif
1768 // Add code to increment 'guest_instrs_executed' by 'n', like this:
1769 // WrTmp(t1, Load64(&guest_instrs_executed))
1770 // WrTmp(t2, Add64(RdTmp(t1), Const(n)))
1771 // Store(&guest_instrs_executed, t2)
1772 IRTemp t1 = newIRTemp(sbOut->tyenv, Ity_I64);
1773 IRTemp t2 = newIRTemp(sbOut->tyenv, Ity_I64);
1774 IRExpr* counter_addr = mkIRExpr_HWord( (HWord)&guest_instrs_executed );
1776 IRStmt* st1 = IRStmt_WrTmp(t1, IRExpr_Load(END, Ity_I64, counter_addr));
1777 IRStmt* st2 =
1778 IRStmt_WrTmp(t2,
1779 IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(t1),
1780 IRExpr_Const(IRConst_U64(n))));
1781 IRStmt* st3 = IRStmt_Store(END, counter_addr, IRExpr_RdTmp(t2));
1783 addStmtToIRSB( sbOut, st1 );
1784 addStmtToIRSB( sbOut, st2 );
1785 addStmtToIRSB( sbOut, st3 );
1788 static IRSB* ms_instrument2( IRSB* sbIn )
1790 Int i, n = 0;
1791 IRSB* sbOut;
1793 // We increment the instruction count in two places:
1794 // - just before any Ist_Exit statements;
1795 // - just before the IRSB's end.
1796 // In the former case, we zero 'n' and then continue instrumenting.
1798 sbOut = deepCopyIRSBExceptStmts(sbIn);
1800 for (i = 0; i < sbIn->stmts_used; i++) {
1801 IRStmt* st = sbIn->stmts[i];
1803 if (!st || st->tag == Ist_NoOp) continue;
1805 if (st->tag == Ist_IMark) {
1806 n++;
1807 } else if (st->tag == Ist_Exit) {
1808 if (n > 0) {
1809 // Add an increment before the Exit statement, then reset 'n'.
1810 add_counter_update(sbOut, n);
1811 n = 0;
1814 addStmtToIRSB( sbOut, st );
1817 if (n > 0) {
1818 // Add an increment before the SB end.
1819 add_counter_update(sbOut, n);
1821 return sbOut;
1824 static
1825 IRSB* ms_instrument ( VgCallbackClosure* closure,
1826 IRSB* sbIn,
1827 const VexGuestLayout* layout,
1828 const VexGuestExtents* vge,
1829 const VexArchInfo* archinfo_host,
1830 IRType gWordTy, IRType hWordTy )
1832 if (! have_started_executing_code) {
1833 // Do an initial sample to guarantee that we have at least one.
1834 // We use 'maybe_take_snapshot' instead of 'take_snapshot' to ensure
1835 // 'maybe_take_snapshot's internal static variables are initialised.
1836 have_started_executing_code = True;
1837 maybe_take_snapshot(Normal, "startup");
1840 if (clo_time_unit == TimeI) { return ms_instrument2(sbIn); }
1841 else if (clo_time_unit == TimeMS) { return sbIn; }
1842 else if (clo_time_unit == TimeB) { return sbIn; }
1843 else { tl_assert2(0, "bad --time-unit value"); }
1847 //------------------------------------------------------------//
1848 //--- Writing snapshots ---//
1849 //------------------------------------------------------------//
1851 static void pp_snapshot(MsFile *fp, Snapshot* snapshot, Int snapshot_n)
1853 const Massif_Header header = (Massif_Header) {
1854 .snapshot_n = snapshot_n,
1855 .time = snapshot->time,
1856 .sz_B = snapshot->heap_szB,
1857 .extra_B = snapshot->heap_extra_szB,
1858 .stacks_B = snapshot->stacks_szB,
1859 .detailed = is_detailed_snapshot(snapshot),
1860 .peak = Peak == snapshot->kind,
1861 .top_node_desc = clo_pages_as_heap ?
1862 "(page allocation syscalls) mmap/mremap/brk, --alloc-fns, etc."
1863 : "(heap allocation functions) malloc/new/new[], --alloc-fns, etc.",
1864 .sig_threshold = clo_threshold
1867 sanity_check_snapshot(snapshot);
1869 VG_(XT_massif_print)(fp, snapshot->xt, &header, alloc_szB);
1872 static void write_snapshots_to_file(const HChar* massif_out_file,
1873 Snapshot snapshots_array[],
1874 Int nr_elements)
1876 Int i;
1877 MsFile *fp;
1879 fp = VG_(XT_massif_open)(massif_out_file,
1880 NULL,
1881 args_for_massif,
1882 TimeUnit_to_string(clo_time_unit));
1883 if (fp == NULL)
1884 return; // Error reported by VG_(XT_massif_open)
1886 for (i = 0; i < nr_elements; i++) {
1887 Snapshot* snapshot = & snapshots_array[i];
1888 pp_snapshot(fp, snapshot, i); // Detailed snapshot!
1890 VG_(XT_massif_close) (fp);
1893 static void write_snapshots_array_to_file(void)
1895 // Setup output filename. Nb: it's important to do this now, ie. as late
1896 // as possible. If we do it at start-up and the program forks and the
1897 // output file format string contains a %p (pid) specifier, both the
1898 // parent and child will incorrectly write to the same file; this
1899 // happened in 3.3.0.
1900 HChar* massif_out_file =
1901 VG_(expand_file_name)("--massif-out-file", clo_massif_out_file);
1902 write_snapshots_to_file (massif_out_file, snapshots, next_snapshot_i);
1903 VG_(free)(massif_out_file);
1906 static void handle_snapshot_monitor_command (const HChar *filename,
1907 Bool detailed)
1909 Snapshot snapshot;
1911 if (!clo_pages_as_heap && !have_started_executing_code) {
1912 // See comments of variable have_started_executing_code.
1913 VG_(gdb_printf)
1914 ("error: cannot take snapshot before execution has started\n");
1915 return;
1918 clear_snapshot(&snapshot, /* do_sanity_check */ False);
1919 take_snapshot(&snapshot, Normal, get_time(), detailed);
1920 write_snapshots_to_file ((filename == NULL) ?
1921 "massif.vgdb.out" : filename,
1922 &snapshot,
1924 delete_snapshot(&snapshot);
1927 static void handle_all_snapshots_monitor_command (const HChar *filename)
1929 if (!clo_pages_as_heap && !have_started_executing_code) {
1930 // See comments of variable have_started_executing_code.
1931 VG_(gdb_printf)
1932 ("error: cannot take snapshot before execution has started\n");
1933 return;
1936 write_snapshots_to_file ((filename == NULL) ?
1937 "massif.vgdb.out" : filename,
1938 snapshots, next_snapshot_i);
1941 static void xtmemory_report_next_block(XT_Allocs* xta, ExeContext** ec_alloc)
1943 const HP_Chunk* hc = VG_(HT_Next)(malloc_list);
1944 if (hc) {
1945 xta->nbytes = hc->req_szB;
1946 xta->nblocks = 1;
1947 *ec_alloc = VG_(XT_get_ec_from_xecu)(heap_xt, hc->where);
1948 } else
1949 xta->nblocks = 0;
1951 static void ms_xtmemory_report ( const HChar* filename, Bool fini )
1953 // Make xtmemory_report_next_block ready to be called.
1954 VG_(HT_ResetIter)(malloc_list);
1955 VG_(XTMemory_report)(filename, fini, xtmemory_report_next_block,
1956 VG_(XT_filter_maybe_below_main));
1957 /* As massif already filters one top function, use as filter
1958 VG_(XT_filter_maybe_below_main). */
1961 static Bool handle_gdb_monitor_command (ThreadId tid, HChar *req)
1963 HChar* wcmd;
1964 HChar s[VG_(strlen)(req) + 1]; /* copy for strtok_r */
1965 HChar *ssaveptr;
1967 VG_(strcpy) (s, req);
1969 wcmd = VG_(strtok_r) (s, " ", &ssaveptr);
1970 switch (VG_(keyword_id) ("help snapshot detailed_snapshot all_snapshots"
1971 " xtmemory",
1972 wcmd, kwd_report_duplicated_matches)) {
1973 case -2: /* multiple matches */
1974 return True;
1975 case -1: /* not found */
1976 return False;
1977 case 0: /* help */
1978 print_monitor_help();
1979 return True;
1980 case 1: { /* snapshot */
1981 HChar* filename;
1982 filename = VG_(strtok_r) (NULL, " ", &ssaveptr);
1983 handle_snapshot_monitor_command (filename, False /* detailed */);
1984 return True;
1986 case 2: { /* detailed_snapshot */
1987 HChar* filename;
1988 filename = VG_(strtok_r) (NULL, " ", &ssaveptr);
1989 handle_snapshot_monitor_command (filename, True /* detailed */);
1990 return True;
1992 case 3: { /* all_snapshots */
1993 HChar* filename;
1994 filename = VG_(strtok_r) (NULL, " ", &ssaveptr);
1995 handle_all_snapshots_monitor_command (filename);
1996 return True;
1998 case 4: { /* xtmemory */
1999 HChar* filename;
2000 filename = VG_(strtok_r) (NULL, " ", &ssaveptr);
2001 ms_xtmemory_report (filename, False);
2002 return True;
2004 default:
2005 tl_assert(0);
2006 return False;
2010 static void ms_print_stats (void)
2012 #define STATS(format, args...) \
2013 VG_(dmsg)("Massif: " format, ##args)
2015 STATS("heap allocs: %u\n", n_heap_allocs);
2016 STATS("heap reallocs: %u\n", n_heap_reallocs);
2017 STATS("heap frees: %u\n", n_heap_frees);
2018 STATS("ignored heap allocs: %u\n", n_ignored_heap_allocs);
2019 STATS("ignored heap frees: %u\n", n_ignored_heap_frees);
2020 STATS("ignored heap reallocs: %u\n", n_ignored_heap_reallocs);
2021 STATS("stack allocs: %u\n", n_stack_allocs);
2022 STATS("skipped snapshots: %u\n", n_skipped_snapshots);
2023 STATS("real snapshots: %u\n", n_real_snapshots);
2024 STATS("detailed snapshots: %u\n", n_detailed_snapshots);
2025 STATS("peak snapshots: %u\n", n_peak_snapshots);
2026 STATS("cullings: %u\n", n_cullings);
2027 #undef STATS
2031 //------------------------------------------------------------//
2032 //--- Finalisation ---//
2033 //------------------------------------------------------------//
2035 static void ms_fini(Int exit_status)
2037 ms_xtmemory_report(VG_(clo_xtree_memory_file), True);
2039 // Output.
2040 write_snapshots_array_to_file();
2042 if (VG_(clo_stats))
2043 ms_print_stats();
2047 //------------------------------------------------------------//
2048 //--- Initialisation ---//
2049 //------------------------------------------------------------//
2051 static void ms_post_clo_init(void)
2053 Int i;
2054 HChar* LD_PRELOAD_val;
2056 /* We will record execontext up to clo_depth + overestimate and
2057 we will store this as ec => we need to increase the backtrace size
2058 if smaller than what we will store. */
2059 if (VG_(clo_backtrace_size) < clo_depth + MAX_OVERESTIMATE)
2060 VG_(clo_backtrace_size) = clo_depth + MAX_OVERESTIMATE;
2062 // Check options.
2063 if (clo_pages_as_heap) {
2064 if (clo_stacks) {
2065 VG_(fmsg_bad_option)("--pages-as-heap=yes",
2066 "Cannot be used together with --stacks=yes");
2069 if (!clo_heap) {
2070 clo_pages_as_heap = False;
2073 // If --pages-as-heap=yes we don't want malloc replacement to occur. So we
2074 // disable vgpreload_massif-$PLATFORM.so by removing it from LD_PRELOAD (or
2075 // platform-equivalent). This is a bit of a hack, but LD_PRELOAD is setup
2076 // well before tool initialisation, so this seems the best way to do it.
2077 if (clo_pages_as_heap) {
2078 HChar* s1;
2079 HChar* s2;
2081 clo_heap_admin = 0; // No heap admin on pages.
2083 LD_PRELOAD_val = VG_(getenv)( VG_(LD_PRELOAD_var_name) );
2084 tl_assert(LD_PRELOAD_val);
2086 VERB(2, "clo_pages_as_heap orig LD_PRELOAD '%s'\n", LD_PRELOAD_val);
2088 // Make sure the vgpreload_core-$PLATFORM entry is there, for sanity.
2089 s1 = VG_(strstr)(LD_PRELOAD_val, "vgpreload_core");
2090 tl_assert(s1);
2092 // Now find the vgpreload_massif-$PLATFORM entry.
2093 s1 = VG_(strstr)(LD_PRELOAD_val, "vgpreload_massif");
2094 tl_assert(s1);
2095 s2 = s1;
2097 // Position s1 on the previous ':', which must be there because
2098 // of the preceding vgpreload_core-$PLATFORM entry.
2099 for (; *s1 != ':'; s1--)
2102 // Position s2 on the next ':' or \0
2103 for (; *s2 != ':' && *s2 != '\0'; s2++)
2106 // Move all characters from s2 to s1
2107 while ((*s1++ = *s2++))
2110 VERB(2, "clo_pages_as_heap cleaned LD_PRELOAD '%s'\n", LD_PRELOAD_val);
2113 // Print alloc-fns and ignore-fns, if necessary.
2114 if (VG_(clo_verbosity) > 1) {
2115 VERB(1, "alloc-fns:\n");
2116 for (i = 0; i < VG_(sizeXA)(alloc_fns); i++) {
2117 HChar** fn_ptr = VG_(indexXA)(alloc_fns, i);
2118 VERB(1, " %s\n", *fn_ptr);
2121 VERB(1, "ignore-fns:\n");
2122 if (0 == VG_(sizeXA)(ignore_fns)) {
2123 VERB(1, " <empty>\n");
2125 for (i = 0; i < VG_(sizeXA)(ignore_fns); i++) {
2126 HChar** fn_ptr = VG_(indexXA)(ignore_fns, i);
2127 VERB(1, " %d: %s\n", i, *fn_ptr);
2131 // Events to track.
2132 if (clo_stacks) {
2133 VG_(track_new_mem_stack) ( new_mem_stack );
2134 VG_(track_die_mem_stack) ( die_mem_stack );
2135 VG_(track_new_mem_stack_signal) ( new_mem_stack_signal );
2136 VG_(track_die_mem_stack_signal) ( die_mem_stack_signal );
2139 if (clo_pages_as_heap) {
2140 VG_(track_new_mem_startup) ( ms_new_mem_startup );
2141 VG_(track_new_mem_brk) ( ms_new_mem_brk );
2142 VG_(track_new_mem_mmap) ( ms_new_mem_mmap );
2144 VG_(track_copy_mem_remap) ( ms_copy_mem_remap );
2146 VG_(track_die_mem_brk) ( ms_die_mem_brk );
2147 VG_(track_die_mem_munmap) ( ms_die_mem_munmap );
2150 // Initialise snapshot array, and sanity-check it.
2151 snapshots = VG_(malloc)("ms.main.mpoci.1",
2152 sizeof(Snapshot) * clo_max_snapshots);
2153 // We don't want to do snapshot sanity checks here, because they're
2154 // currently uninitialised.
2155 for (i = 0; i < clo_max_snapshots; i++) {
2156 clear_snapshot( & snapshots[i], /*do_sanity_check*/False );
2158 sanity_check_snapshots_array();
2160 if (VG_(clo_xtree_memory) == Vg_XTMemory_Full)
2161 // Activate full xtree memory profiling.
2162 // As massif already filters one top function, use as filter
2163 // VG_(XT_filter_maybe_below_main).
2164 VG_(XTMemory_Full_init)(VG_(XT_filter_maybe_below_main));
2168 static void ms_pre_clo_init(void)
2170 VG_(details_name) ("Massif");
2171 VG_(details_version) (NULL);
2172 VG_(details_description) ("a heap profiler");
2173 VG_(details_copyright_author)(
2174 "Copyright (C) 2003-2017, and GNU GPL'd, by Nicholas Nethercote");
2175 VG_(details_bug_reports_to) (VG_BUGS_TO);
2177 VG_(details_avg_translation_sizeB) ( 330 );
2179 VG_(clo_vex_control).iropt_register_updates_default
2180 = VG_(clo_px_file_backed)
2181 = VexRegUpdSpAtMemAccess; // overridable by the user.
2183 // Basic functions.
2184 VG_(basic_tool_funcs) (ms_post_clo_init,
2185 ms_instrument,
2186 ms_fini);
2188 // Needs.
2189 VG_(needs_libc_freeres)();
2190 VG_(needs_cxx_freeres)();
2191 VG_(needs_command_line_options)(ms_process_cmd_line_option,
2192 ms_print_usage,
2193 ms_print_debug_usage);
2194 VG_(needs_client_requests) (ms_handle_client_request);
2195 VG_(needs_sanity_checks) (ms_cheap_sanity_check,
2196 ms_expensive_sanity_check);
2197 VG_(needs_print_stats) (ms_print_stats);
2198 VG_(needs_malloc_replacement) (ms_malloc,
2199 ms___builtin_new,
2200 ms___builtin_new_aligned,
2201 ms___builtin_vec_new,
2202 ms___builtin_vec_new_aligned,
2203 ms_memalign,
2204 ms_calloc,
2205 ms_free,
2206 ms___builtin_delete,
2207 ms___builtin_delete_aligned,
2208 ms___builtin_vec_delete,
2209 ms___builtin_vec_delete_aligned,
2210 ms_realloc,
2211 ms_malloc_usable_size,
2212 0 );
2214 // HP_Chunks.
2215 HP_chunk_poolalloc = VG_(newPA)
2216 (sizeof(HP_Chunk),
2217 1000,
2218 VG_(malloc),
2219 "massif MC_Chunk pool",
2220 VG_(free));
2221 malloc_list = VG_(HT_construct)( "Massif's malloc list" );
2223 // Heap XTree
2224 heap_xt = VG_(XT_create)(VG_(malloc),
2225 "ms.xtrees",
2226 VG_(free),
2227 sizeof(SizeT),
2228 init_szB, add_szB, sub_szB,
2229 filter_IPs);
2231 // Initialise alloc_fns and ignore_fns.
2232 init_alloc_fns();
2233 init_ignore_fns();
2235 // Initialise args_for_massif.
2236 args_for_massif = VG_(newXA)(VG_(malloc), "ms.main.mprci.1",
2237 VG_(free), sizeof(HChar*));
2240 VG_DETERMINE_INTERFACE_VERSION(ms_pre_clo_init)
2242 //--------------------------------------------------------------------//
2243 //--- end ---//
2244 //--------------------------------------------------------------------//