memprof_rtl.cpp 8.7 KB

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