1//===-- asan_stats.cc -----------------------------------------------------===//
2//
3// This file is distributed under the University of Illinois Open Source
4// License. See LICENSE.TXT for details.
5//
6//===----------------------------------------------------------------------===//
7//
8// This file is a part of AddressSanitizer, an address sanity checker.
9//
10// Code related to statistics collected by AddressSanitizer.
11//===----------------------------------------------------------------------===//
12#include "asan_interceptors.h"
13#include "asan_internal.h"
14#include "asan_stats.h"
15#include "asan_thread.h"
16#include "sanitizer_common/sanitizer_allocator_interface.h"
17#include "sanitizer_common/sanitizer_mutex.h"
18#include "sanitizer_common/sanitizer_stackdepot.h"
19
20namespace __asan {
21
22AsanStats::AsanStats() {
23  Clear();
24}
25
26void AsanStats::Clear() {
27  CHECK(REAL(memset));
28  REAL(memset)(this, 0, sizeof(AsanStats));
29}
30
31static void PrintMallocStatsArray(const char *prefix,
32                                  uptr (&array)[kNumberOfSizeClasses]) {
33  Printf("%s", prefix);
34  for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
35    if (!array[i]) continue;
36    Printf("%zu:%zu; ", i, array[i]);
37  }
38  Printf("\n");
39}
40
41void AsanStats::Print() {
42  Printf("Stats: %zuM malloced (%zuM for red zones) by %zu calls\n",
43             malloced>>20, malloced_redzones>>20, mallocs);
44  Printf("Stats: %zuM realloced by %zu calls\n", realloced>>20, reallocs);
45  Printf("Stats: %zuM freed by %zu calls\n", freed>>20, frees);
46  Printf("Stats: %zuM really freed by %zu calls\n",
47             really_freed>>20, real_frees);
48  Printf("Stats: %zuM (%zuM-%zuM) mmaped; %zu maps, %zu unmaps\n",
49             (mmaped-munmaped)>>20, mmaped>>20, munmaped>>20,
50             mmaps, munmaps);
51
52  PrintMallocStatsArray("  mmaps   by size class: ", mmaped_by_size);
53  PrintMallocStatsArray("  mallocs by size class: ", malloced_by_size);
54  PrintMallocStatsArray("  frees   by size class: ", freed_by_size);
55  PrintMallocStatsArray("  rfrees  by size class: ", really_freed_by_size);
56  Printf("Stats: malloc large: %zu small slow: %zu\n",
57             malloc_large, malloc_small_slow);
58}
59
60void AsanStats::MergeFrom(const AsanStats *stats) {
61  uptr *dst_ptr = reinterpret_cast<uptr*>(this);
62  const uptr *src_ptr = reinterpret_cast<const uptr*>(stats);
63  uptr num_fields = sizeof(*this) / sizeof(uptr);
64  for (uptr i = 0; i < num_fields; i++)
65    dst_ptr[i] += src_ptr[i];
66}
67
68static BlockingMutex print_lock(LINKER_INITIALIZED);
69
70static AsanStats unknown_thread_stats(LINKER_INITIALIZED);
71static AsanStats dead_threads_stats(LINKER_INITIALIZED);
72static BlockingMutex dead_threads_stats_lock(LINKER_INITIALIZED);
73// Required for malloc_zone_statistics() on OS X. This can't be stored in
74// per-thread AsanStats.
75static uptr max_malloced_memory;
76
77static void MergeThreadStats(ThreadContextBase *tctx_base, void *arg) {
78  AsanStats *accumulated_stats = reinterpret_cast<AsanStats*>(arg);
79  AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
80  if (AsanThread *t = tctx->thread)
81    accumulated_stats->MergeFrom(&t->stats());
82}
83
84static void GetAccumulatedStats(AsanStats *stats) {
85  stats->Clear();
86  {
87    ThreadRegistryLock l(&asanThreadRegistry());
88    asanThreadRegistry()
89        .RunCallbackForEachThreadLocked(MergeThreadStats, stats);
90  }
91  stats->MergeFrom(&unknown_thread_stats);
92  {
93    BlockingMutexLock lock(&dead_threads_stats_lock);
94    stats->MergeFrom(&dead_threads_stats);
95  }
96  // This is not very accurate: we may miss allocation peaks that happen
97  // between two updates of accumulated_stats_. For more accurate bookkeeping
98  // the maximum should be updated on every malloc(), which is unacceptable.
99  if (max_malloced_memory < stats->malloced) {
100    max_malloced_memory = stats->malloced;
101  }
102}
103
104void FlushToDeadThreadStats(AsanStats *stats) {
105  BlockingMutexLock lock(&dead_threads_stats_lock);
106  dead_threads_stats.MergeFrom(stats);
107  stats->Clear();
108}
109
110void FillMallocStatistics(AsanMallocStats *malloc_stats) {
111  AsanStats stats;
112  GetAccumulatedStats(&stats);
113  malloc_stats->blocks_in_use = stats.mallocs;
114  malloc_stats->size_in_use = stats.malloced;
115  malloc_stats->max_size_in_use = max_malloced_memory;
116  malloc_stats->size_allocated = stats.mmaped;
117}
118
119AsanStats &GetCurrentThreadStats() {
120  AsanThread *t = GetCurrentThread();
121  return (t) ? t->stats() : unknown_thread_stats;
122}
123
124static void PrintAccumulatedStats() {
125  AsanStats stats;
126  GetAccumulatedStats(&stats);
127  // Use lock to keep reports from mixing up.
128  BlockingMutexLock lock(&print_lock);
129  stats.Print();
130  StackDepotStats *stack_depot_stats = StackDepotGetStats();
131  Printf("Stats: StackDepot: %zd ids; %zdM allocated\n",
132         stack_depot_stats->n_uniq_ids, stack_depot_stats->allocated >> 20);
133  PrintInternalAllocatorStats();
134}
135
136}  // namespace __asan
137
138// ---------------------- Interface ---------------- {{{1
139using namespace __asan;  // NOLINT
140
141uptr __sanitizer_get_current_allocated_bytes() {
142  AsanStats stats;
143  GetAccumulatedStats(&stats);
144  uptr malloced = stats.malloced;
145  uptr freed = stats.freed;
146  // Return sane value if malloced < freed due to racy
147  // way we update accumulated stats.
148  return (malloced > freed) ? malloced - freed : 1;
149}
150
151uptr __sanitizer_get_heap_size() {
152  AsanStats stats;
153  GetAccumulatedStats(&stats);
154  return stats.mmaped - stats.munmaped;
155}
156
157uptr __sanitizer_get_free_bytes() {
158  AsanStats stats;
159  GetAccumulatedStats(&stats);
160  uptr total_free = stats.mmaped
161                  - stats.munmaped
162                  + stats.really_freed
163                  + stats.really_freed_redzones;
164  uptr total_used = stats.malloced
165                  + stats.malloced_redzones;
166  // Return sane value if total_free < total_used due to racy
167  // way we update accumulated stats.
168  return (total_free > total_used) ? total_free - total_used : 1;
169}
170
171uptr __sanitizer_get_unmapped_bytes() {
172  return 0;
173}
174
175void __asan_print_accumulated_stats() {
176  PrintAccumulatedStats();
177}
178