memprof_rtl.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. //===-- memprof_rtl.cpp --------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is a part of MemProfiler, a memory profiler.
  10. //
  11. // Main file of the MemProf run-time library.
  12. //===----------------------------------------------------------------------===//
  13. #include "memprof_allocator.h"
  14. #include "memprof_interceptors.h"
  15. #include "memprof_interface_internal.h"
  16. #include "memprof_internal.h"
  17. #include "memprof_mapping.h"
  18. #include "memprof_stack.h"
  19. #include "memprof_stats.h"
  20. #include "memprof_thread.h"
  21. #include "sanitizer_common/sanitizer_atomic.h"
  22. #include "sanitizer_common/sanitizer_flags.h"
  23. #include "sanitizer_common/sanitizer_interface_internal.h"
  24. #include "sanitizer_common/sanitizer_libc.h"
  25. #include "sanitizer_common/sanitizer_symbolizer.h"
  26. #include <time.h>
  27. uptr __memprof_shadow_memory_dynamic_address; // Global interface symbol.
  28. // Allow the user to specify a profile output file via the binary.
  29. SANITIZER_WEAK_ATTRIBUTE char __memprof_profile_filename[1];
  30. namespace __memprof {
  31. static void MemprofDie() {
  32. static atomic_uint32_t num_calls;
  33. if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
  34. // Don't die twice - run a busy loop.
  35. while (1) {
  36. internal_sched_yield();
  37. }
  38. }
  39. if (common_flags()->print_module_map >= 1)
  40. DumpProcessMap();
  41. if (flags()->unmap_shadow_on_exit) {
  42. if (kHighShadowEnd)
  43. UnmapOrDie((void *)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
  44. }
  45. }
  46. static void MemprofOnDeadlySignal(int signo, void *siginfo, void *context) {
  47. // We call StartReportDeadlySignal not HandleDeadlySignal so we get the
  48. // deadly signal message to stderr but no writing to the profile output file
  49. StartReportDeadlySignal();
  50. __memprof_profile_dump();
  51. Die();
  52. }
  53. static void CheckUnwind() {
  54. GET_STACK_TRACE(kStackTraceMax, common_flags()->fast_unwind_on_check);
  55. stack.Print();
  56. }
  57. // -------------------------- Globals --------------------- {{{1
  58. int memprof_inited;
  59. int memprof_init_done;
  60. bool memprof_init_is_running;
  61. int memprof_timestamp_inited;
  62. long memprof_init_timestamp_s;
  63. uptr kHighMemEnd;
  64. // -------------------------- Run-time entry ------------------- {{{1
  65. // exported functions
  66. #define MEMPROF_MEMORY_ACCESS_CALLBACK_BODY() __memprof::RecordAccess(addr);
  67. #define MEMPROF_MEMORY_ACCESS_CALLBACK(type) \
  68. extern "C" NOINLINE INTERFACE_ATTRIBUTE void __memprof_##type(uptr addr) { \
  69. MEMPROF_MEMORY_ACCESS_CALLBACK_BODY() \
  70. }
  71. MEMPROF_MEMORY_ACCESS_CALLBACK(load)
  72. MEMPROF_MEMORY_ACCESS_CALLBACK(store)
  73. // Force the linker to keep the symbols for various MemProf interface
  74. // functions. We want to keep those in the executable in order to let the
  75. // instrumented dynamic libraries access the symbol even if it is not used by
  76. // the executable itself. This should help if the build system is removing dead
  77. // code at link time.
  78. static NOINLINE void force_interface_symbols() {
  79. volatile int fake_condition = 0; // prevent dead condition elimination.
  80. // clang-format off
  81. switch (fake_condition) {
  82. case 1: __memprof_record_access(nullptr); break;
  83. case 2: __memprof_record_access_range(nullptr, 0); break;
  84. }
  85. // clang-format on
  86. }
  87. static void memprof_atexit() {
  88. Printf("MemProfiler exit stats:\n");
  89. __memprof_print_accumulated_stats();
  90. }
  91. static void InitializeHighMemEnd() {
  92. kHighMemEnd = GetMaxUserVirtualAddress();
  93. // Increase kHighMemEnd to make sure it's properly
  94. // aligned together with kHighMemBeg:
  95. kHighMemEnd |= (GetMmapGranularity() << SHADOW_SCALE) - 1;
  96. }
  97. void PrintAddressSpaceLayout() {
  98. if (kHighMemBeg) {
  99. Printf("|| `[%p, %p]` || HighMem ||\n", (void *)kHighMemBeg,
  100. (void *)kHighMemEnd);
  101. Printf("|| `[%p, %p]` || HighShadow ||\n", (void *)kHighShadowBeg,
  102. (void *)kHighShadowEnd);
  103. }
  104. Printf("|| `[%p, %p]` || ShadowGap ||\n", (void *)kShadowGapBeg,
  105. (void *)kShadowGapEnd);
  106. if (kLowShadowBeg) {
  107. Printf("|| `[%p, %p]` || LowShadow ||\n", (void *)kLowShadowBeg,
  108. (void *)kLowShadowEnd);
  109. Printf("|| `[%p, %p]` || LowMem ||\n", (void *)kLowMemBeg,
  110. (void *)kLowMemEnd);
  111. }
  112. Printf("MemToShadow(shadow): %p %p", (void *)MEM_TO_SHADOW(kLowShadowBeg),
  113. (void *)MEM_TO_SHADOW(kLowShadowEnd));
  114. if (kHighMemBeg) {
  115. Printf(" %p %p", (void *)MEM_TO_SHADOW(kHighShadowBeg),
  116. (void *)MEM_TO_SHADOW(kHighShadowEnd));
  117. }
  118. Printf("\n");
  119. Printf("malloc_context_size=%zu\n",
  120. (uptr)common_flags()->malloc_context_size);
  121. Printf("SHADOW_SCALE: %d\n", (int)SHADOW_SCALE);
  122. Printf("SHADOW_GRANULARITY: %d\n", (int)SHADOW_GRANULARITY);
  123. Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)SHADOW_OFFSET);
  124. CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
  125. }
  126. static void MemprofInitInternal() {
  127. if (LIKELY(memprof_inited))
  128. return;
  129. SanitizerToolName = "MemProfiler";
  130. CHECK(!memprof_init_is_running && "MemProf init calls itself!");
  131. memprof_init_is_running = true;
  132. CacheBinaryName();
  133. // Initialize flags. This must be done early, because most of the
  134. // initialization steps look at flags().
  135. InitializeFlags();
  136. AvoidCVE_2016_2143();
  137. SetMallocContextSize(common_flags()->malloc_context_size);
  138. InitializeHighMemEnd();
  139. // Make sure we are not statically linked.
  140. MemprofDoesNotSupportStaticLinkage();
  141. // Install tool-specific callbacks in sanitizer_common.
  142. AddDieCallback(MemprofDie);
  143. SetCheckUnwindCallback(CheckUnwind);
  144. // Use profile name specified via the binary itself if it exists, and hasn't
  145. // been overrriden by a flag at runtime.
  146. if (__memprof_profile_filename[0] != 0 && !common_flags()->log_path)
  147. __sanitizer_set_report_path(__memprof_profile_filename);
  148. else
  149. __sanitizer_set_report_path(common_flags()->log_path);
  150. __sanitizer::InitializePlatformEarly();
  151. // Setup internal allocator callback.
  152. SetLowLevelAllocateMinAlignment(SHADOW_GRANULARITY);
  153. InitializeMemprofInterceptors();
  154. CheckASLR();
  155. ReplaceSystemMalloc();
  156. DisableCoreDumperIfNecessary();
  157. InitializeShadowMemory();
  158. TSDInit(PlatformTSDDtor);
  159. InstallDeadlySignalHandlers(MemprofOnDeadlySignal);
  160. InitializeAllocator();
  161. // On Linux MemprofThread::ThreadStart() calls malloc() that's why
  162. // memprof_inited should be set to 1 prior to initializing the threads.
  163. memprof_inited = 1;
  164. memprof_init_is_running = false;
  165. if (flags()->atexit)
  166. Atexit(memprof_atexit);
  167. InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
  168. // interceptors
  169. InitTlsSize();
  170. // Create main thread.
  171. MemprofThread *main_thread = CreateMainThread();
  172. CHECK_EQ(0, main_thread->tid());
  173. force_interface_symbols(); // no-op.
  174. SanitizerInitializeUnwinder();
  175. Symbolizer::LateInitialize();
  176. VReport(1, "MemProfiler Init done\n");
  177. memprof_init_done = 1;
  178. }
  179. void MemprofInitTime() {
  180. if (LIKELY(memprof_timestamp_inited))
  181. return;
  182. timespec ts;
  183. clock_gettime(CLOCK_REALTIME, &ts);
  184. memprof_init_timestamp_s = ts.tv_sec;
  185. memprof_timestamp_inited = 1;
  186. }
  187. // Initialize as requested from some part of MemProf runtime library
  188. // (interceptors, allocator, etc).
  189. void MemprofInitFromRtl() { MemprofInitInternal(); }
  190. #if MEMPROF_DYNAMIC
  191. // Initialize runtime in case it's LD_PRELOAD-ed into uninstrumented executable
  192. // (and thus normal initializers from .preinit_array or modules haven't run).
  193. class MemprofInitializer {
  194. public:
  195. MemprofInitializer() { MemprofInitFromRtl(); }
  196. };
  197. static MemprofInitializer memprof_initializer;
  198. #endif // MEMPROF_DYNAMIC
  199. } // namespace __memprof
  200. // ---------------------- Interface ---------------- {{{1
  201. using namespace __memprof;
  202. // Initialize as requested from instrumented application code.
  203. void __memprof_init() {
  204. MemprofInitTime();
  205. MemprofInitInternal();
  206. }
  207. void __memprof_preinit() { MemprofInitInternal(); }
  208. void __memprof_version_mismatch_check_v1() {}
  209. void __memprof_record_access(void const volatile *addr) {
  210. __memprof::RecordAccess((uptr)addr);
  211. }
  212. void __memprof_record_access_range(void const volatile *addr, uptr size) {
  213. for (uptr a = (uptr)addr; a < (uptr)addr + size; a += kWordSize)
  214. __memprof::RecordAccess(a);
  215. }
  216. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u16
  217. __sanitizer_unaligned_load16(const uu16 *p) {
  218. __memprof_record_access(p);
  219. return *p;
  220. }
  221. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u32
  222. __sanitizer_unaligned_load32(const uu32 *p) {
  223. __memprof_record_access(p);
  224. return *p;
  225. }
  226. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u64
  227. __sanitizer_unaligned_load64(const uu64 *p) {
  228. __memprof_record_access(p);
  229. return *p;
  230. }
  231. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  232. __sanitizer_unaligned_store16(uu16 *p, u16 x) {
  233. __memprof_record_access(p);
  234. *p = x;
  235. }
  236. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  237. __sanitizer_unaligned_store32(uu32 *p, u32 x) {
  238. __memprof_record_access(p);
  239. *p = x;
  240. }
  241. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  242. __sanitizer_unaligned_store64(uu64 *p, u64 x) {
  243. __memprof_record_access(p);
  244. *p = x;
  245. }