sanitizer_common.cpp 11 KB

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