aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/clang18-rt/lib/memprof/memprof_rtl.cpp
blob: 5e2e7bc2be3f7931d5ff6d71d92ab6d37e6ba604 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//===-- memprof_rtl.cpp --------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of MemProfiler, a memory profiler.
//
// Main file of the MemProf run-time library.
//===----------------------------------------------------------------------===//

#include "memprof_allocator.h"
#include "memprof_interceptors.h"
#include "memprof_interface_internal.h"
#include "memprof_internal.h"
#include "memprof_mapping.h"
#include "memprof_stack.h"
#include "memprof_stats.h"
#include "memprof_thread.h"
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_interface_internal.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_symbolizer.h"

#include <time.h>

uptr __memprof_shadow_memory_dynamic_address; // Global interface symbol.

// Allow the user to specify a profile output file via the binary.
SANITIZER_WEAK_ATTRIBUTE char __memprof_profile_filename[1];

namespace __memprof {

static void MemprofDie() {
  static atomic_uint32_t num_calls;
  if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
    // Don't die twice - run a busy loop.
    while (1) {
      internal_sched_yield();
    }
  }
  if (common_flags()->print_module_map >= 1)
    DumpProcessMap();
  if (flags()->unmap_shadow_on_exit) {
    if (kHighShadowEnd)
      UnmapOrDie((void *)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
  }
}

static void MemprofOnDeadlySignal(int signo, void *siginfo, void *context) {
  // We call StartReportDeadlySignal not HandleDeadlySignal so we get the
  // deadly signal message to stderr but no writing to the profile output file
  StartReportDeadlySignal();
  __memprof_profile_dump();
  Die();
}

static void CheckUnwind() {
  GET_STACK_TRACE(kStackTraceMax, common_flags()->fast_unwind_on_check);
  stack.Print();
}

// -------------------------- Globals --------------------- {{{1
int memprof_inited;
bool memprof_init_is_running;
int memprof_timestamp_inited;
long memprof_init_timestamp_s;

uptr kHighMemEnd;

// -------------------------- Run-time entry ------------------- {{{1
// exported functions

#define MEMPROF_MEMORY_ACCESS_CALLBACK_BODY() __memprof::RecordAccess(addr);

#define MEMPROF_MEMORY_ACCESS_CALLBACK(type)                                   \
  extern "C" NOINLINE INTERFACE_ATTRIBUTE void __memprof_##type(uptr addr) {   \
    MEMPROF_MEMORY_ACCESS_CALLBACK_BODY()                                      \
  }

MEMPROF_MEMORY_ACCESS_CALLBACK(load)
MEMPROF_MEMORY_ACCESS_CALLBACK(store)

// Force the linker to keep the symbols for various MemProf interface
// functions. We want to keep those in the executable in order to let the
// instrumented dynamic libraries access the symbol even if it is not used by
// the executable itself. This should help if the build system is removing dead
// code at link time.
static NOINLINE void force_interface_symbols() {
  volatile int fake_condition = 0; // prevent dead condition elimination.
  // clang-format off
  switch (fake_condition) {
    case 1: __memprof_record_access(nullptr); break;
    case 2: __memprof_record_access_range(nullptr, 0); break;
  }
  // clang-format on
}

static void memprof_atexit() {
  Printf("MemProfiler exit stats:\n");
  __memprof_print_accumulated_stats();
}

static void InitializeHighMemEnd() {
  kHighMemEnd = GetMaxUserVirtualAddress();
  // Increase kHighMemEnd to make sure it's properly
  // aligned together with kHighMemBeg:
  kHighMemEnd |= (GetMmapGranularity() << SHADOW_SCALE) - 1;
}

void PrintAddressSpaceLayout() {
  if (kHighMemBeg) {
    Printf("|| `[%p, %p]` || HighMem    ||\n", (void *)kHighMemBeg,
           (void *)kHighMemEnd);
    Printf("|| `[%p, %p]` || HighShadow ||\n", (void *)kHighShadowBeg,
           (void *)kHighShadowEnd);
  }
  Printf("|| `[%p, %p]` || ShadowGap  ||\n", (void *)kShadowGapBeg,
         (void *)kShadowGapEnd);
  if (kLowShadowBeg) {
    Printf("|| `[%p, %p]` || LowShadow  ||\n", (void *)kLowShadowBeg,
           (void *)kLowShadowEnd);
    Printf("|| `[%p, %p]` || LowMem     ||\n", (void *)kLowMemBeg,
           (void *)kLowMemEnd);
  }
  Printf("MemToShadow(shadow): %p %p", (void *)MEM_TO_SHADOW(kLowShadowBeg),
         (void *)MEM_TO_SHADOW(kLowShadowEnd));
  if (kHighMemBeg) {
    Printf(" %p %p", (void *)MEM_TO_SHADOW(kHighShadowBeg),
           (void *)MEM_TO_SHADOW(kHighShadowEnd));
  }
  Printf("\n");
  Printf("malloc_context_size=%zu\n",
         (uptr)common_flags()->malloc_context_size);

  Printf("SHADOW_SCALE: %d\n", (int)SHADOW_SCALE);
  Printf("SHADOW_GRANULARITY: %d\n", (int)SHADOW_GRANULARITY);
  Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)SHADOW_OFFSET);
  CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
}

static void MemprofInitInternal() {
  if (LIKELY(memprof_inited))
    return;
  SanitizerToolName = "MemProfiler";
  CHECK(!memprof_init_is_running && "MemProf init calls itself!");
  memprof_init_is_running = true;

  CacheBinaryName();

  // Initialize flags. This must be done early, because most of the
  // initialization steps look at flags().
  InitializeFlags();

  AvoidCVE_2016_2143();

  SetMallocContextSize(common_flags()->malloc_context_size);

  InitializeHighMemEnd();

  // Make sure we are not statically linked.
  MemprofDoesNotSupportStaticLinkage();

  // Install tool-specific callbacks in sanitizer_common.
  AddDieCallback(MemprofDie);
  SetCheckUnwindCallback(CheckUnwind);

  // Use profile name specified via the binary itself if it exists, and hasn't
  // been overrriden by a flag at runtime.
  if (__memprof_profile_filename[0] != 0 && !common_flags()->log_path)
    __sanitizer_set_report_path(__memprof_profile_filename);
  else
    __sanitizer_set_report_path(common_flags()->log_path);

  __sanitizer::InitializePlatformEarly();

  // Setup internal allocator callback.
  SetLowLevelAllocateMinAlignment(SHADOW_GRANULARITY);

  InitializeMemprofInterceptors();
  CheckASLR();

  ReplaceSystemMalloc();

  DisableCoreDumperIfNecessary();

  InitializeShadowMemory();

  TSDInit(PlatformTSDDtor);
  InstallDeadlySignalHandlers(MemprofOnDeadlySignal);

  InitializeAllocator();

  if (flags()->atexit)
    Atexit(memprof_atexit);

  InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);

  // interceptors
  InitTlsSize();

  // Create main thread.
  MemprofThread *main_thread = CreateMainThread();
  CHECK_EQ(0, main_thread->tid());
  force_interface_symbols(); // no-op.
  SanitizerInitializeUnwinder();

  Symbolizer::LateInitialize();

  VReport(1, "MemProfiler Init done\n");

  memprof_init_is_running = false;
  memprof_inited = 1;
}

void MemprofInitTime() {
  if (LIKELY(memprof_timestamp_inited))
    return;
  timespec ts;
  clock_gettime(CLOCK_REALTIME, &ts);
  memprof_init_timestamp_s = ts.tv_sec;
  memprof_timestamp_inited = 1;
}

// Initialize as requested from some part of MemProf runtime library
// (interceptors, allocator, etc).
void MemprofInitFromRtl() { MemprofInitInternal(); }

#if MEMPROF_DYNAMIC
// Initialize runtime in case it's LD_PRELOAD-ed into uninstrumented executable
// (and thus normal initializers from .preinit_array or modules haven't run).

class MemprofInitializer {
public:
  MemprofInitializer() { MemprofInitFromRtl(); }
};

static MemprofInitializer memprof_initializer;
#endif // MEMPROF_DYNAMIC

} // namespace __memprof

// ---------------------- Interface ---------------- {{{1
using namespace __memprof;

// Initialize as requested from instrumented application code.
void __memprof_init() {
  MemprofInitTime();
  MemprofInitInternal();
}

void __memprof_preinit() { MemprofInitInternal(); }

void __memprof_version_mismatch_check_v1() {}

void __memprof_record_access(void const volatile *addr) {
  __memprof::RecordAccess((uptr)addr);
}

void __memprof_record_access_range(void const volatile *addr, uptr size) {
  for (uptr a = (uptr)addr; a < (uptr)addr + size; a += kWordSize)
    __memprof::RecordAccess(a);
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE u16
__sanitizer_unaligned_load16(const uu16 *p) {
  __memprof_record_access(p);
  return *p;
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE u32
__sanitizer_unaligned_load32(const uu32 *p) {
  __memprof_record_access(p);
  return *p;
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE u64
__sanitizer_unaligned_load64(const uu64 *p) {
  __memprof_record_access(p);
  return *p;
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
__sanitizer_unaligned_store16(uu16 *p, u16 x) {
  __memprof_record_access(p);
  *p = x;
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
__sanitizer_unaligned_store32(uu32 *p, u32 x) {
  __memprof_record_access(p);
  *p = x;
}

extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
__sanitizer_unaligned_store64(uu64 *p, u64 x) {
  __memprof_record_access(p);
  *p = x;
}