memprof_rtl.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. bool memprof_init_is_running;
  60. int memprof_timestamp_inited;
  61. long memprof_init_timestamp_s;
  62. uptr kHighMemEnd;
  63. // -------------------------- Run-time entry ------------------- {{{1
  64. // exported functions
  65. #define MEMPROF_MEMORY_ACCESS_CALLBACK_BODY() __memprof::RecordAccess(addr);
  66. #define MEMPROF_MEMORY_ACCESS_CALLBACK(type) \
  67. extern "C" NOINLINE INTERFACE_ATTRIBUTE void __memprof_##type(uptr addr) { \
  68. MEMPROF_MEMORY_ACCESS_CALLBACK_BODY() \
  69. }
  70. MEMPROF_MEMORY_ACCESS_CALLBACK(load)
  71. MEMPROF_MEMORY_ACCESS_CALLBACK(store)
  72. // Force the linker to keep the symbols for various MemProf interface
  73. // functions. We want to keep those in the executable in order to let the
  74. // instrumented dynamic libraries access the symbol even if it is not used by
  75. // the executable itself. This should help if the build system is removing dead
  76. // code at link time.
  77. static NOINLINE void force_interface_symbols() {
  78. volatile int fake_condition = 0; // prevent dead condition elimination.
  79. // clang-format off
  80. switch (fake_condition) {
  81. case 1: __memprof_record_access(nullptr); break;
  82. case 2: __memprof_record_access_range(nullptr, 0); break;
  83. }
  84. // clang-format on
  85. }
  86. static void memprof_atexit() {
  87. Printf("MemProfiler exit stats:\n");
  88. __memprof_print_accumulated_stats();
  89. }
  90. static void InitializeHighMemEnd() {
  91. kHighMemEnd = GetMaxUserVirtualAddress();
  92. // Increase kHighMemEnd to make sure it's properly
  93. // aligned together with kHighMemBeg:
  94. kHighMemEnd |= (GetMmapGranularity() << SHADOW_SCALE) - 1;
  95. }
  96. void PrintAddressSpaceLayout() {
  97. if (kHighMemBeg) {
  98. Printf("|| `[%p, %p]` || HighMem ||\n", (void *)kHighMemBeg,
  99. (void *)kHighMemEnd);
  100. Printf("|| `[%p, %p]` || HighShadow ||\n", (void *)kHighShadowBeg,
  101. (void *)kHighShadowEnd);
  102. }
  103. Printf("|| `[%p, %p]` || ShadowGap ||\n", (void *)kShadowGapBeg,
  104. (void *)kShadowGapEnd);
  105. if (kLowShadowBeg) {
  106. Printf("|| `[%p, %p]` || LowShadow ||\n", (void *)kLowShadowBeg,
  107. (void *)kLowShadowEnd);
  108. Printf("|| `[%p, %p]` || LowMem ||\n", (void *)kLowMemBeg,
  109. (void *)kLowMemEnd);
  110. }
  111. Printf("MemToShadow(shadow): %p %p", (void *)MEM_TO_SHADOW(kLowShadowBeg),
  112. (void *)MEM_TO_SHADOW(kLowShadowEnd));
  113. if (kHighMemBeg) {
  114. Printf(" %p %p", (void *)MEM_TO_SHADOW(kHighShadowBeg),
  115. (void *)MEM_TO_SHADOW(kHighShadowEnd));
  116. }
  117. Printf("\n");
  118. Printf("malloc_context_size=%zu\n",
  119. (uptr)common_flags()->malloc_context_size);
  120. Printf("SHADOW_SCALE: %d\n", (int)SHADOW_SCALE);
  121. Printf("SHADOW_GRANULARITY: %d\n", (int)SHADOW_GRANULARITY);
  122. Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)SHADOW_OFFSET);
  123. CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
  124. }
  125. static void MemprofInitInternal() {
  126. if (LIKELY(memprof_inited))
  127. return;
  128. SanitizerToolName = "MemProfiler";
  129. CHECK(!memprof_init_is_running && "MemProf init calls itself!");
  130. memprof_init_is_running = true;
  131. CacheBinaryName();
  132. // Initialize flags. This must be done early, because most of the
  133. // initialization steps look at flags().
  134. InitializeFlags();
  135. AvoidCVE_2016_2143();
  136. SetMallocContextSize(common_flags()->malloc_context_size);
  137. InitializeHighMemEnd();
  138. // Make sure we are not statically linked.
  139. MemprofDoesNotSupportStaticLinkage();
  140. // Install tool-specific callbacks in sanitizer_common.
  141. AddDieCallback(MemprofDie);
  142. SetCheckUnwindCallback(CheckUnwind);
  143. // Use profile name specified via the binary itself if it exists, and hasn't
  144. // been overrriden by a flag at runtime.
  145. if (__memprof_profile_filename[0] != 0 && !common_flags()->log_path)
  146. __sanitizer_set_report_path(__memprof_profile_filename);
  147. else
  148. __sanitizer_set_report_path(common_flags()->log_path);
  149. __sanitizer::InitializePlatformEarly();
  150. // Setup internal allocator callback.
  151. SetLowLevelAllocateMinAlignment(SHADOW_GRANULARITY);
  152. InitializeMemprofInterceptors();
  153. CheckASLR();
  154. ReplaceSystemMalloc();
  155. DisableCoreDumperIfNecessary();
  156. InitializeShadowMemory();
  157. TSDInit(PlatformTSDDtor);
  158. InstallDeadlySignalHandlers(MemprofOnDeadlySignal);
  159. InitializeAllocator();
  160. if (flags()->atexit)
  161. Atexit(memprof_atexit);
  162. InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
  163. // interceptors
  164. InitTlsSize();
  165. // Create main thread.
  166. MemprofThread *main_thread = CreateMainThread();
  167. CHECK_EQ(0, main_thread->tid());
  168. force_interface_symbols(); // no-op.
  169. SanitizerInitializeUnwinder();
  170. Symbolizer::LateInitialize();
  171. VReport(1, "MemProfiler Init done\n");
  172. memprof_init_is_running = false;
  173. memprof_inited = 1;
  174. }
  175. void MemprofInitTime() {
  176. if (LIKELY(memprof_timestamp_inited))
  177. return;
  178. timespec ts;
  179. clock_gettime(CLOCK_REALTIME, &ts);
  180. memprof_init_timestamp_s = ts.tv_sec;
  181. memprof_timestamp_inited = 1;
  182. }
  183. // Initialize as requested from some part of MemProf runtime library
  184. // (interceptors, allocator, etc).
  185. void MemprofInitFromRtl() { MemprofInitInternal(); }
  186. #if MEMPROF_DYNAMIC
  187. // Initialize runtime in case it's LD_PRELOAD-ed into uninstrumented executable
  188. // (and thus normal initializers from .preinit_array or modules haven't run).
  189. class MemprofInitializer {
  190. public:
  191. MemprofInitializer() { MemprofInitFromRtl(); }
  192. };
  193. static MemprofInitializer memprof_initializer;
  194. #endif // MEMPROF_DYNAMIC
  195. } // namespace __memprof
  196. // ---------------------- Interface ---------------- {{{1
  197. using namespace __memprof;
  198. // Initialize as requested from instrumented application code.
  199. void __memprof_init() {
  200. MemprofInitTime();
  201. MemprofInitInternal();
  202. }
  203. void __memprof_preinit() { MemprofInitInternal(); }
  204. void __memprof_version_mismatch_check_v1() {}
  205. void __memprof_record_access(void const volatile *addr) {
  206. __memprof::RecordAccess((uptr)addr);
  207. }
  208. void __memprof_record_access_range(void const volatile *addr, uptr size) {
  209. for (uptr a = (uptr)addr; a < (uptr)addr + size; a += kWordSize)
  210. __memprof::RecordAccess(a);
  211. }
  212. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u16
  213. __sanitizer_unaligned_load16(const uu16 *p) {
  214. __memprof_record_access(p);
  215. return *p;
  216. }
  217. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u32
  218. __sanitizer_unaligned_load32(const uu32 *p) {
  219. __memprof_record_access(p);
  220. return *p;
  221. }
  222. extern "C" SANITIZER_INTERFACE_ATTRIBUTE u64
  223. __sanitizer_unaligned_load64(const uu64 *p) {
  224. __memprof_record_access(p);
  225. return *p;
  226. }
  227. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  228. __sanitizer_unaligned_store16(uu16 *p, u16 x) {
  229. __memprof_record_access(p);
  230. *p = x;
  231. }
  232. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  233. __sanitizer_unaligned_store32(uu32 *p, u32 x) {
  234. __memprof_record_access(p);
  235. *p = x;
  236. }
  237. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  238. __sanitizer_unaligned_store64(uu64 *p, u64 x) {
  239. __memprof_record_access(p);
  240. *p = x;
  241. }