sanitizer_common.cpp 12 KB

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