sanitizer_common.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. //===-- sanitizer_common.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 shared between AddressSanitizer and ThreadSanitizer
  10. // run-time libraries.
  11. //===----------------------------------------------------------------------===//
  12. #include "sanitizer_common.h"
  13. #include "sanitizer_allocator_interface.h"
  14. #include "sanitizer_allocator_internal.h"
  15. #include "sanitizer_atomic.h"
  16. #include "sanitizer_flags.h"
  17. #include "sanitizer_interface_internal.h"
  18. #include "sanitizer_libc.h"
  19. #include "sanitizer_placement_new.h"
  20. namespace __sanitizer {
  21. const char *SanitizerToolName = "SanitizerTool";
  22. atomic_uint32_t current_verbosity;
  23. uptr PageSizeCached;
  24. u32 NumberOfCPUsCached;
  25. // PID of the tracer task in StopTheWorld. It shares the address space with the
  26. // main process, but has a different PID and thus requires special handling.
  27. uptr stoptheworld_tracer_pid = 0;
  28. // Cached pid of parent process - if the parent process dies, we want to keep
  29. // writing to the same log file.
  30. uptr stoptheworld_tracer_ppid = 0;
  31. void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
  32. const char *mmap_type, error_t err,
  33. bool raw_report) {
  34. static int recursion_count;
  35. if (raw_report || recursion_count) {
  36. // If raw report is requested or we went into recursion just die. The
  37. // Report() and CHECK calls below may call mmap recursively and fail.
  38. RawWrite("ERROR: Failed to mmap\n");
  39. Die();
  40. }
  41. recursion_count++;
  42. if (ErrorIsOOM(err)) {
  43. ERROR_OOM("failed to %s 0x%zx (%zd) bytes of %s (error code: %d)\n",
  44. mmap_type, size, size, mem_type, err);
  45. } else {
  46. Report(
  47. "ERROR: %s failed to "
  48. "%s 0x%zx (%zd) bytes of %s (error code: %d)\n",
  49. SanitizerToolName, mmap_type, size, size, mem_type, err);
  50. }
  51. #if !SANITIZER_GO
  52. DumpProcessMap();
  53. #endif
  54. UNREACHABLE("unable to mmap");
  55. }
  56. typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
  57. typedef bool U32ComparisonFunction(const u32 &a, const u32 &b);
  58. const char *StripPathPrefix(const char *filepath,
  59. const char *strip_path_prefix) {
  60. if (!filepath) return nullptr;
  61. if (!strip_path_prefix) return filepath;
  62. const char *res = filepath;
  63. if (const char *pos = internal_strstr(filepath, strip_path_prefix))
  64. res = pos + internal_strlen(strip_path_prefix);
  65. if (res[0] == '.' && res[1] == '/')
  66. res += 2;
  67. return res;
  68. }
  69. const char *StripModuleName(const char *module) {
  70. if (!module)
  71. return nullptr;
  72. if (SANITIZER_WINDOWS) {
  73. // On Windows, both slash and backslash are possible.
  74. // Pick the one that goes last.
  75. if (const char *bslash_pos = internal_strrchr(module, '\\'))
  76. return StripModuleName(bslash_pos + 1);
  77. }
  78. if (const char *slash_pos = internal_strrchr(module, '/')) {
  79. return slash_pos + 1;
  80. }
  81. return module;
  82. }
  83. void ReportErrorSummary(const char *error_message, const char *alt_tool_name) {
  84. if (!common_flags()->print_summary)
  85. return;
  86. InternalScopedString buff;
  87. buff.append("SUMMARY: %s: %s",
  88. alt_tool_name ? alt_tool_name : SanitizerToolName, error_message);
  89. __sanitizer_report_error_summary(buff.data());
  90. }
  91. // Removes the ANSI escape sequences from the input string (in-place).
  92. void RemoveANSIEscapeSequencesFromString(char *str) {
  93. if (!str)
  94. return;
  95. // We are going to remove the escape sequences in place.
  96. char *s = str;
  97. char *z = str;
  98. while (*s != '\0') {
  99. CHECK_GE(s, z);
  100. // Skip over ANSI escape sequences with pointer 's'.
  101. if (*s == '\033' && *(s + 1) == '[') {
  102. s = internal_strchrnul(s, 'm');
  103. if (*s == '\0') {
  104. break;
  105. }
  106. s++;
  107. continue;
  108. }
  109. // 's' now points at a character we want to keep. Copy over the buffer
  110. // content if the escape sequence has been perviously skipped andadvance
  111. // both pointers.
  112. if (s != z)
  113. *z = *s;
  114. // If we have not seen an escape sequence, just advance both pointers.
  115. z++;
  116. s++;
  117. }
  118. // Null terminate the string.
  119. *z = '\0';
  120. }
  121. void LoadedModule::set(const char *module_name, uptr base_address) {
  122. clear();
  123. full_name_ = internal_strdup(module_name);
  124. base_address_ = base_address;
  125. }
  126. void LoadedModule::set(const char *module_name, uptr base_address,
  127. ModuleArch arch, u8 uuid[kModuleUUIDSize],
  128. bool instrumented) {
  129. set(module_name, base_address);
  130. arch_ = arch;
  131. internal_memcpy(uuid_, uuid, sizeof(uuid_));
  132. uuid_size_ = kModuleUUIDSize;
  133. instrumented_ = instrumented;
  134. }
  135. void LoadedModule::setUuid(const char *uuid, uptr size) {
  136. if (size > kModuleUUIDSize)
  137. size = kModuleUUIDSize;
  138. internal_memcpy(uuid_, uuid, size);
  139. uuid_size_ = size;
  140. }
  141. void LoadedModule::clear() {
  142. InternalFree(full_name_);
  143. base_address_ = 0;
  144. max_address_ = 0;
  145. full_name_ = nullptr;
  146. arch_ = kModuleArchUnknown;
  147. internal_memset(uuid_, 0, kModuleUUIDSize);
  148. instrumented_ = false;
  149. while (!ranges_.empty()) {
  150. AddressRange *r = ranges_.front();
  151. ranges_.pop_front();
  152. InternalFree(r);
  153. }
  154. }
  155. void LoadedModule::addAddressRange(uptr beg, uptr end, bool executable,
  156. bool writable, const char *name) {
  157. void *mem = InternalAlloc(sizeof(AddressRange));
  158. AddressRange *r =
  159. new(mem) AddressRange(beg, end, executable, writable, name);
  160. ranges_.push_back(r);
  161. max_address_ = Max(max_address_, end);
  162. }
  163. bool LoadedModule::containsAddress(uptr address) const {
  164. for (const AddressRange &r : ranges()) {
  165. if (r.beg <= address && address < r.end)
  166. return true;
  167. }
  168. return false;
  169. }
  170. static atomic_uintptr_t g_total_mmaped;
  171. void IncreaseTotalMmap(uptr size) {
  172. if (!common_flags()->mmap_limit_mb) return;
  173. uptr total_mmaped =
  174. atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
  175. // Since for now mmap_limit_mb is not a user-facing flag, just kill
  176. // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
  177. RAW_CHECK((total_mmaped >> 20) < common_flags()->mmap_limit_mb);
  178. }
  179. void DecreaseTotalMmap(uptr size) {
  180. if (!common_flags()->mmap_limit_mb) return;
  181. atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
  182. }
  183. bool TemplateMatch(const char *templ, const char *str) {
  184. if ((!str) || str[0] == 0)
  185. return false;
  186. bool start = false;
  187. if (templ && templ[0] == '^') {
  188. start = true;
  189. templ++;
  190. }
  191. bool asterisk = false;
  192. while (templ && templ[0]) {
  193. if (templ[0] == '*') {
  194. templ++;
  195. start = false;
  196. asterisk = true;
  197. continue;
  198. }
  199. if (templ[0] == '$')
  200. return str[0] == 0 || asterisk;
  201. if (str[0] == 0)
  202. return false;
  203. char *tpos = (char*)internal_strchr(templ, '*');
  204. char *tpos1 = (char*)internal_strchr(templ, '$');
  205. if ((!tpos) || (tpos1 && tpos1 < tpos))
  206. tpos = tpos1;
  207. if (tpos)
  208. tpos[0] = 0;
  209. const char *str0 = str;
  210. const char *spos = internal_strstr(str, templ);
  211. str = spos + internal_strlen(templ);
  212. templ = tpos;
  213. if (tpos)
  214. tpos[0] = tpos == tpos1 ? '$' : '*';
  215. if (!spos)
  216. return false;
  217. if (start && spos != str0)
  218. return false;
  219. start = false;
  220. asterisk = false;
  221. }
  222. return true;
  223. }
  224. static char binary_name_cache_str[kMaxPathLength];
  225. static char process_name_cache_str[kMaxPathLength];
  226. const char *GetProcessName() {
  227. return process_name_cache_str;
  228. }
  229. static uptr ReadProcessName(/*out*/ char *buf, uptr buf_len) {
  230. ReadLongProcessName(buf, buf_len);
  231. char *s = const_cast<char *>(StripModuleName(buf));
  232. uptr len = internal_strlen(s);
  233. if (s != buf) {
  234. internal_memmove(buf, s, len);
  235. buf[len] = '\0';
  236. }
  237. return len;
  238. }
  239. void UpdateProcessName() {
  240. ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
  241. }
  242. // Call once to make sure that binary_name_cache_str is initialized
  243. void CacheBinaryName() {
  244. if (binary_name_cache_str[0] != '\0')
  245. return;
  246. ReadBinaryName(binary_name_cache_str, sizeof(binary_name_cache_str));
  247. ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
  248. }
  249. uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len) {
  250. CacheBinaryName();
  251. uptr name_len = internal_strlen(binary_name_cache_str);
  252. name_len = (name_len < buf_len - 1) ? name_len : buf_len - 1;
  253. if (buf_len == 0)
  254. return 0;
  255. internal_memcpy(buf, binary_name_cache_str, name_len);
  256. buf[name_len] = '\0';
  257. return name_len;
  258. }
  259. uptr ReadBinaryDir(/*out*/ char *buf, uptr buf_len) {
  260. ReadBinaryNameCached(buf, buf_len);
  261. const char *exec_name_pos = StripModuleName(buf);
  262. uptr name_len = exec_name_pos - buf;
  263. buf[name_len] = '\0';
  264. return name_len;
  265. }
  266. #if !SANITIZER_GO
  267. void PrintCmdline() {
  268. char **argv = GetArgv();
  269. if (!argv) return;
  270. Printf("\nCommand: ");
  271. for (uptr i = 0; argv[i]; ++i)
  272. Printf("%s ", argv[i]);
  273. Printf("\n\n");
  274. }
  275. #endif
  276. // Malloc hooks.
  277. static const int kMaxMallocFreeHooks = 5;
  278. struct MallocFreeHook {
  279. void (*malloc_hook)(const void *, uptr);
  280. void (*free_hook)(const void *);
  281. };
  282. static MallocFreeHook MFHooks[kMaxMallocFreeHooks];
  283. void RunMallocHooks(void *ptr, uptr size) {
  284. __sanitizer_malloc_hook(ptr, size);
  285. for (int i = 0; i < kMaxMallocFreeHooks; i++) {
  286. auto hook = MFHooks[i].malloc_hook;
  287. if (!hook)
  288. break;
  289. hook(ptr, size);
  290. }
  291. }
  292. void RunFreeHooks(void *ptr) {
  293. __sanitizer_free_hook(ptr);
  294. for (int i = 0; i < kMaxMallocFreeHooks; i++) {
  295. auto hook = MFHooks[i].free_hook;
  296. if (!hook)
  297. break;
  298. hook(ptr);
  299. }
  300. }
  301. static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
  302. void (*free_hook)(const void *)) {
  303. if (!malloc_hook || !free_hook) return 0;
  304. for (int i = 0; i < kMaxMallocFreeHooks; i++) {
  305. if (MFHooks[i].malloc_hook == nullptr) {
  306. MFHooks[i].malloc_hook = malloc_hook;
  307. MFHooks[i].free_hook = free_hook;
  308. return i + 1;
  309. }
  310. }
  311. return 0;
  312. }
  313. void internal_sleep(unsigned seconds) {
  314. internal_usleep((u64)seconds * 1000 * 1000);
  315. }
  316. void SleepForSeconds(unsigned seconds) {
  317. internal_usleep((u64)seconds * 1000 * 1000);
  318. }
  319. void SleepForMillis(unsigned millis) { internal_usleep((u64)millis * 1000); }
  320. void WaitForDebugger(unsigned seconds, const char *label) {
  321. if (seconds) {
  322. Report("Sleeping for %u second(s) %s\n", seconds, label);
  323. SleepForSeconds(seconds);
  324. }
  325. }
  326. } // namespace __sanitizer
  327. using namespace __sanitizer;
  328. extern "C" {
  329. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary,
  330. const char *error_summary) {
  331. Printf("%s\n", error_summary);
  332. }
  333. SANITIZER_INTERFACE_ATTRIBUTE
  334. int __sanitizer_acquire_crash_state() {
  335. static atomic_uint8_t in_crash_state = {};
  336. return !atomic_exchange(&in_crash_state, 1, memory_order_relaxed);
  337. }
  338. SANITIZER_INTERFACE_ATTRIBUTE
  339. int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const void *,
  340. uptr),
  341. void (*free_hook)(const void *)) {
  342. return InstallMallocFreeHooks(malloc_hook, free_hook);
  343. }
  344. // Provide default (no-op) implementation of malloc hooks.
  345. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr,
  346. uptr size) {
  347. (void)ptr;
  348. (void)size;
  349. }
  350. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
  351. (void)ptr;
  352. }
  353. } // extern "C"