sanitizer_win.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. //===-- sanitizer_win.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 and implements windows-specific functions from
  11. // sanitizer_libc.h.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_platform.h"
  14. #if SANITIZER_WINDOWS
  15. #define WIN32_LEAN_AND_MEAN
  16. #define NOGDI
  17. #include <windows.h>
  18. #include <io.h>
  19. #include <psapi.h>
  20. #include <stdlib.h>
  21. #include "sanitizer_common.h"
  22. #include "sanitizer_file.h"
  23. #include "sanitizer_libc.h"
  24. #include "sanitizer_mutex.h"
  25. #include "sanitizer_placement_new.h"
  26. #include "sanitizer_win_defs.h"
  27. #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
  28. #pragma comment(lib, "psapi")
  29. #endif
  30. #if SANITIZER_WIN_TRACE
  31. #error #include <traceloggingprovider.h>
  32. // Windows trace logging provider init
  33. #pragma comment(lib, "advapi32.lib")
  34. TRACELOGGING_DECLARE_PROVIDER(g_asan_provider);
  35. // GUID must be the same in utils/AddressSanitizerLoggingProvider.wprp
  36. TRACELOGGING_DEFINE_PROVIDER(g_asan_provider, "AddressSanitizerLoggingProvider",
  37. (0x6c6c766d, 0x3846, 0x4e6a, 0xa4, 0xfb, 0x5b,
  38. 0x53, 0x0b, 0xd0, 0xf3, 0xfa));
  39. #else
  40. #define TraceLoggingUnregister(x)
  41. #endif
  42. // For WaitOnAddress
  43. # pragma comment(lib, "synchronization.lib")
  44. // A macro to tell the compiler that this part of the code cannot be reached,
  45. // if the compiler supports this feature. Since we're using this in
  46. // code that is called when terminating the process, the expansion of the
  47. // macro should not terminate the process to avoid infinite recursion.
  48. #if defined(__clang__)
  49. # define BUILTIN_UNREACHABLE() __builtin_unreachable()
  50. #elif defined(__GNUC__) && \
  51. (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  52. # define BUILTIN_UNREACHABLE() __builtin_unreachable()
  53. #elif defined(_MSC_VER)
  54. # define BUILTIN_UNREACHABLE() __assume(0)
  55. #else
  56. # define BUILTIN_UNREACHABLE()
  57. #endif
  58. namespace __sanitizer {
  59. #include "sanitizer_syscall_generic.inc"
  60. // --------------------- sanitizer_common.h
  61. uptr GetPageSize() {
  62. SYSTEM_INFO si;
  63. GetSystemInfo(&si);
  64. return si.dwPageSize;
  65. }
  66. uptr GetMmapGranularity() {
  67. SYSTEM_INFO si;
  68. GetSystemInfo(&si);
  69. return si.dwAllocationGranularity;
  70. }
  71. uptr GetMaxUserVirtualAddress() {
  72. SYSTEM_INFO si;
  73. GetSystemInfo(&si);
  74. return (uptr)si.lpMaximumApplicationAddress;
  75. }
  76. uptr GetMaxVirtualAddress() {
  77. return GetMaxUserVirtualAddress();
  78. }
  79. bool FileExists(const char *filename) {
  80. return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
  81. }
  82. bool DirExists(const char *path) {
  83. auto attr = ::GetFileAttributesA(path);
  84. return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
  85. }
  86. uptr internal_getpid() {
  87. return GetProcessId(GetCurrentProcess());
  88. }
  89. int internal_dlinfo(void *handle, int request, void *p) {
  90. UNIMPLEMENTED();
  91. }
  92. // In contrast to POSIX, on Windows GetCurrentThreadId()
  93. // returns a system-unique identifier.
  94. tid_t GetTid() {
  95. return GetCurrentThreadId();
  96. }
  97. uptr GetThreadSelf() {
  98. return GetTid();
  99. }
  100. #if !SANITIZER_GO
  101. void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
  102. uptr *stack_bottom) {
  103. CHECK(stack_top);
  104. CHECK(stack_bottom);
  105. MEMORY_BASIC_INFORMATION mbi;
  106. CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
  107. // FIXME: is it possible for the stack to not be a single allocation?
  108. // Are these values what ASan expects to get (reserved, not committed;
  109. // including stack guard page) ?
  110. *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
  111. *stack_bottom = (uptr)mbi.AllocationBase;
  112. }
  113. #endif // #if !SANITIZER_GO
  114. bool ErrorIsOOM(error_t err) {
  115. // TODO: This should check which `err`s correspond to OOM.
  116. return false;
  117. }
  118. void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
  119. void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  120. if (rv == 0)
  121. ReportMmapFailureAndDie(size, mem_type, "allocate",
  122. GetLastError(), raw_report);
  123. return rv;
  124. }
  125. void UnmapOrDie(void *addr, uptr size) {
  126. if (!size || !addr)
  127. return;
  128. MEMORY_BASIC_INFORMATION mbi;
  129. CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
  130. // MEM_RELEASE can only be used to unmap whole regions previously mapped with
  131. // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
  132. // fails try MEM_DECOMMIT.
  133. if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
  134. if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
  135. Report("ERROR: %s failed to "
  136. "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
  137. SanitizerToolName, size, size, addr, GetLastError());
  138. CHECK("unable to unmap" && 0);
  139. }
  140. }
  141. }
  142. static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
  143. const char *mmap_type) {
  144. error_t last_error = GetLastError();
  145. if (last_error == ERROR_NOT_ENOUGH_MEMORY)
  146. return nullptr;
  147. ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
  148. }
  149. void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
  150. void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  151. if (rv == 0)
  152. return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
  153. return rv;
  154. }
  155. // We want to map a chunk of address space aligned to 'alignment'.
  156. void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
  157. const char *mem_type) {
  158. CHECK(IsPowerOfTwo(size));
  159. CHECK(IsPowerOfTwo(alignment));
  160. // Windows will align our allocations to at least 64K.
  161. alignment = Max(alignment, GetMmapGranularity());
  162. uptr mapped_addr =
  163. (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  164. if (!mapped_addr)
  165. return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
  166. // If we got it right on the first try, return. Otherwise, unmap it and go to
  167. // the slow path.
  168. if (IsAligned(mapped_addr, alignment))
  169. return (void*)mapped_addr;
  170. if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
  171. ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
  172. // If we didn't get an aligned address, overallocate, find an aligned address,
  173. // unmap, and try to allocate at that aligned address.
  174. int retries = 0;
  175. const int kMaxRetries = 10;
  176. for (; retries < kMaxRetries &&
  177. (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
  178. retries++) {
  179. // Overallocate size + alignment bytes.
  180. mapped_addr =
  181. (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
  182. if (!mapped_addr)
  183. return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
  184. // Find the aligned address.
  185. uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
  186. // Free the overallocation.
  187. if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
  188. ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
  189. // Attempt to allocate exactly the number of bytes we need at the aligned
  190. // address. This may fail for a number of reasons, in which case we continue
  191. // the loop.
  192. mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
  193. MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  194. }
  195. // Fail if we can't make this work quickly.
  196. if (retries == kMaxRetries && mapped_addr == 0)
  197. return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
  198. return (void *)mapped_addr;
  199. }
  200. // ZeroMmapFixedRegion zero's out a region of memory previously returned from a
  201. // call to one of the MmapFixed* helpers. On non-windows systems this would be
  202. // done with another mmap, but on windows remapping is not an option.
  203. // VirtualFree(DECOMMIT)+VirtualAlloc(RECOMMIT) would also be a way to zero the
  204. // memory, but we can't do this atomically, so instead we fall back to using
  205. // internal_memset.
  206. bool ZeroMmapFixedRegion(uptr fixed_addr, uptr size) {
  207. internal_memset((void*) fixed_addr, 0, size);
  208. return true;
  209. }
  210. bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
  211. // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
  212. // but on Win64 it does.
  213. (void)name; // unsupported
  214. #if !SANITIZER_GO && SANITIZER_WINDOWS64
  215. // On asan/Windows64, use MEM_COMMIT would result in error
  216. // 1455:ERROR_COMMITMENT_LIMIT.
  217. // Asan uses exception handler to commit page on demand.
  218. void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
  219. #else
  220. void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
  221. PAGE_READWRITE);
  222. #endif
  223. if (p == 0) {
  224. Report("ERROR: %s failed to "
  225. "allocate %p (%zd) bytes at %p (error code: %d)\n",
  226. SanitizerToolName, size, size, fixed_addr, GetLastError());
  227. return false;
  228. }
  229. return true;
  230. }
  231. bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
  232. // FIXME: Windows support large pages too. Might be worth checking
  233. return MmapFixedNoReserve(fixed_addr, size, name);
  234. }
  235. // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
  236. // 'MmapFixedNoAccess'.
  237. void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
  238. void *p = VirtualAlloc((LPVOID)fixed_addr, size,
  239. MEM_COMMIT, PAGE_READWRITE);
  240. if (p == 0) {
  241. char mem_type[30];
  242. internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
  243. fixed_addr);
  244. ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
  245. }
  246. return p;
  247. }
  248. // Uses fixed_addr for now.
  249. // Will use offset instead once we've implemented this function for real.
  250. uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) {
  251. return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
  252. }
  253. uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
  254. const char *name) {
  255. return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
  256. }
  257. void ReservedAddressRange::Unmap(uptr addr, uptr size) {
  258. // Only unmap if it covers the entire range.
  259. CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
  260. // We unmap the whole range, just null out the base.
  261. base_ = nullptr;
  262. size_ = 0;
  263. UnmapOrDie(reinterpret_cast<void*>(addr), size);
  264. }
  265. void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
  266. void *p = VirtualAlloc((LPVOID)fixed_addr, size,
  267. MEM_COMMIT, PAGE_READWRITE);
  268. if (p == 0) {
  269. char mem_type[30];
  270. internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
  271. fixed_addr);
  272. return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
  273. }
  274. return p;
  275. }
  276. void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
  277. // FIXME: make this really NoReserve?
  278. return MmapOrDie(size, mem_type);
  279. }
  280. uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
  281. base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
  282. size_ = size;
  283. name_ = name;
  284. (void)os_handle_; // unsupported
  285. return reinterpret_cast<uptr>(base_);
  286. }
  287. void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
  288. (void)name; // unsupported
  289. void *res = VirtualAlloc((LPVOID)fixed_addr, size,
  290. MEM_RESERVE, PAGE_NOACCESS);
  291. if (res == 0)
  292. Report("WARNING: %s failed to "
  293. "mprotect %p (%zd) bytes at %p (error code: %d)\n",
  294. SanitizerToolName, size, size, fixed_addr, GetLastError());
  295. return res;
  296. }
  297. void *MmapNoAccess(uptr size) {
  298. void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
  299. if (res == 0)
  300. Report("WARNING: %s failed to "
  301. "mprotect %p (%zd) bytes (error code: %d)\n",
  302. SanitizerToolName, size, size, GetLastError());
  303. return res;
  304. }
  305. bool MprotectNoAccess(uptr addr, uptr size) {
  306. DWORD old_protection;
  307. return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
  308. }
  309. bool MprotectReadOnly(uptr addr, uptr size) {
  310. DWORD old_protection;
  311. return VirtualProtect((LPVOID)addr, size, PAGE_READONLY, &old_protection);
  312. }
  313. bool MprotectReadWrite(uptr addr, uptr size) {
  314. DWORD old_protection;
  315. return VirtualProtect((LPVOID)addr, size, PAGE_READWRITE, &old_protection);
  316. }
  317. void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
  318. uptr beg_aligned = RoundDownTo(beg, GetPageSizeCached()),
  319. end_aligned = RoundDownTo(end, GetPageSizeCached());
  320. CHECK(beg < end); // make sure the region is sane
  321. if (beg_aligned == end_aligned) // make sure we're freeing at least 1 page;
  322. return;
  323. UnmapOrDie((void *)beg, end_aligned - beg_aligned);
  324. }
  325. void SetShadowRegionHugePageMode(uptr addr, uptr size) {
  326. // FIXME: probably similar to ReleaseMemoryToOS.
  327. }
  328. bool DontDumpShadowMemory(uptr addr, uptr length) {
  329. // This is almost useless on 32-bits.
  330. // FIXME: add madvise-analog when we move to 64-bits.
  331. return true;
  332. }
  333. uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
  334. uptr min_shadow_base_alignment,
  335. UNUSED uptr &high_mem_end) {
  336. const uptr granularity = GetMmapGranularity();
  337. const uptr alignment =
  338. Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
  339. const uptr left_padding =
  340. Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
  341. uptr space_size = shadow_size_bytes + left_padding;
  342. uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
  343. granularity, nullptr, nullptr);
  344. CHECK_NE((uptr)0, shadow_start);
  345. CHECK(IsAligned(shadow_start, alignment));
  346. return shadow_start;
  347. }
  348. uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
  349. uptr *largest_gap_found,
  350. uptr *max_occupied_addr) {
  351. uptr address = 0;
  352. while (true) {
  353. MEMORY_BASIC_INFORMATION info;
  354. if (!::VirtualQuery((void*)address, &info, sizeof(info)))
  355. return 0;
  356. if (info.State == MEM_FREE) {
  357. uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
  358. alignment);
  359. if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
  360. return shadow_address;
  361. }
  362. // Move to the next region.
  363. address = (uptr)info.BaseAddress + info.RegionSize;
  364. }
  365. return 0;
  366. }
  367. uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
  368. uptr num_aliases, uptr ring_buffer_size) {
  369. CHECK(false && "HWASan aliasing is unimplemented on Windows");
  370. return 0;
  371. }
  372. bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
  373. MEMORY_BASIC_INFORMATION mbi;
  374. CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
  375. return mbi.Protect == PAGE_NOACCESS &&
  376. (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
  377. }
  378. void *MapFileToMemory(const char *file_name, uptr *buff_size) {
  379. UNIMPLEMENTED();
  380. }
  381. void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
  382. UNIMPLEMENTED();
  383. }
  384. static const int kMaxEnvNameLength = 128;
  385. static const DWORD kMaxEnvValueLength = 32767;
  386. namespace {
  387. struct EnvVariable {
  388. char name[kMaxEnvNameLength];
  389. char value[kMaxEnvValueLength];
  390. };
  391. } // namespace
  392. static const int kEnvVariables = 5;
  393. static EnvVariable env_vars[kEnvVariables];
  394. static int num_env_vars;
  395. const char *GetEnv(const char *name) {
  396. // Note: this implementation caches the values of the environment variables
  397. // and limits their quantity.
  398. for (int i = 0; i < num_env_vars; i++) {
  399. if (0 == internal_strcmp(name, env_vars[i].name))
  400. return env_vars[i].value;
  401. }
  402. CHECK_LT(num_env_vars, kEnvVariables);
  403. DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
  404. kMaxEnvValueLength);
  405. if (rv > 0 && rv < kMaxEnvValueLength) {
  406. CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
  407. internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
  408. num_env_vars++;
  409. return env_vars[num_env_vars - 1].value;
  410. }
  411. return 0;
  412. }
  413. const char *GetPwd() {
  414. UNIMPLEMENTED();
  415. }
  416. u32 GetUid() {
  417. UNIMPLEMENTED();
  418. }
  419. namespace {
  420. struct ModuleInfo {
  421. const char *filepath;
  422. uptr base_address;
  423. uptr end_address;
  424. };
  425. #if !SANITIZER_GO
  426. int CompareModulesBase(const void *pl, const void *pr) {
  427. const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
  428. if (l->base_address < r->base_address)
  429. return -1;
  430. return l->base_address > r->base_address;
  431. }
  432. #endif
  433. } // namespace
  434. #if !SANITIZER_GO
  435. void DumpProcessMap() {
  436. Report("Dumping process modules:\n");
  437. ListOfModules modules;
  438. modules.init();
  439. uptr num_modules = modules.size();
  440. InternalMmapVector<ModuleInfo> module_infos(num_modules);
  441. for (size_t i = 0; i < num_modules; ++i) {
  442. module_infos[i].filepath = modules[i].full_name();
  443. module_infos[i].base_address = modules[i].ranges().front()->beg;
  444. module_infos[i].end_address = modules[i].ranges().back()->end;
  445. }
  446. qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
  447. CompareModulesBase);
  448. for (size_t i = 0; i < num_modules; ++i) {
  449. const ModuleInfo &mi = module_infos[i];
  450. if (mi.end_address != 0) {
  451. Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
  452. mi.filepath[0] ? mi.filepath : "[no name]");
  453. } else if (mi.filepath[0]) {
  454. Printf("\t??\?-??? %s\n", mi.filepath);
  455. } else {
  456. Printf("\t???\n");
  457. }
  458. }
  459. }
  460. #endif
  461. void DisableCoreDumperIfNecessary() {
  462. // Do nothing.
  463. }
  464. void ReExec() {
  465. UNIMPLEMENTED();
  466. }
  467. void PlatformPrepareForSandboxing(void *args) {}
  468. bool StackSizeIsUnlimited() {
  469. UNIMPLEMENTED();
  470. }
  471. void SetStackSizeLimitInBytes(uptr limit) {
  472. UNIMPLEMENTED();
  473. }
  474. bool AddressSpaceIsUnlimited() {
  475. UNIMPLEMENTED();
  476. }
  477. void SetAddressSpaceUnlimited() {
  478. UNIMPLEMENTED();
  479. }
  480. bool IsPathSeparator(const char c) {
  481. return c == '\\' || c == '/';
  482. }
  483. static bool IsAlpha(char c) {
  484. c = ToLower(c);
  485. return c >= 'a' && c <= 'z';
  486. }
  487. bool IsAbsolutePath(const char *path) {
  488. return path != nullptr && IsAlpha(path[0]) && path[1] == ':' &&
  489. IsPathSeparator(path[2]);
  490. }
  491. void internal_usleep(u64 useconds) { Sleep(useconds / 1000); }
  492. u64 NanoTime() {
  493. static LARGE_INTEGER frequency = {};
  494. LARGE_INTEGER counter;
  495. if (UNLIKELY(frequency.QuadPart == 0)) {
  496. QueryPerformanceFrequency(&frequency);
  497. CHECK_NE(frequency.QuadPart, 0);
  498. }
  499. QueryPerformanceCounter(&counter);
  500. counter.QuadPart *= 1000ULL * 1000000ULL;
  501. counter.QuadPart /= frequency.QuadPart;
  502. return counter.QuadPart;
  503. }
  504. u64 MonotonicNanoTime() { return NanoTime(); }
  505. void Abort() {
  506. internal__exit(3);
  507. }
  508. bool CreateDir(const char *pathname) {
  509. return CreateDirectoryA(pathname, nullptr) != 0;
  510. }
  511. #if !SANITIZER_GO
  512. // Read the file to extract the ImageBase field from the PE header. If ASLR is
  513. // disabled and this virtual address is available, the loader will typically
  514. // load the image at this address. Therefore, we call it the preferred base. Any
  515. // addresses in the DWARF typically assume that the object has been loaded at
  516. // this address.
  517. static uptr GetPreferredBase(const char *modname, char *buf, size_t buf_size) {
  518. fd_t fd = OpenFile(modname, RdOnly, nullptr);
  519. if (fd == kInvalidFd)
  520. return 0;
  521. FileCloser closer(fd);
  522. // Read just the DOS header.
  523. IMAGE_DOS_HEADER dos_header;
  524. uptr bytes_read;
  525. if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
  526. bytes_read != sizeof(dos_header))
  527. return 0;
  528. // The file should start with the right signature.
  529. if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
  530. return 0;
  531. // The layout at e_lfanew is:
  532. // "PE\0\0"
  533. // IMAGE_FILE_HEADER
  534. // IMAGE_OPTIONAL_HEADER
  535. // Seek to e_lfanew and read all that data.
  536. if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
  537. INVALID_SET_FILE_POINTER)
  538. return 0;
  539. if (!ReadFromFile(fd, buf, buf_size, &bytes_read) || bytes_read != buf_size)
  540. return 0;
  541. // Check for "PE\0\0" before the PE header.
  542. char *pe_sig = &buf[0];
  543. if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
  544. return 0;
  545. // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
  546. IMAGE_OPTIONAL_HEADER *pe_header =
  547. (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
  548. // Check for more magic in the PE header.
  549. if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
  550. return 0;
  551. // Finally, return the ImageBase.
  552. return (uptr)pe_header->ImageBase;
  553. }
  554. void ListOfModules::init() {
  555. clearOrInit();
  556. HANDLE cur_process = GetCurrentProcess();
  557. // Query the list of modules. Start by assuming there are no more than 256
  558. // modules and retry if that's not sufficient.
  559. HMODULE *hmodules = 0;
  560. uptr modules_buffer_size = sizeof(HMODULE) * 256;
  561. DWORD bytes_required;
  562. while (!hmodules) {
  563. hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
  564. CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
  565. &bytes_required));
  566. if (bytes_required > modules_buffer_size) {
  567. // Either there turned out to be more than 256 hmodules, or new hmodules
  568. // could have loaded since the last try. Retry.
  569. UnmapOrDie(hmodules, modules_buffer_size);
  570. hmodules = 0;
  571. modules_buffer_size = bytes_required;
  572. }
  573. }
  574. InternalMmapVector<char> buf(4 + sizeof(IMAGE_FILE_HEADER) +
  575. sizeof(IMAGE_OPTIONAL_HEADER));
  576. InternalMmapVector<wchar_t> modname_utf16(kMaxPathLength);
  577. InternalMmapVector<char> module_name(kMaxPathLength);
  578. // |num_modules| is the number of modules actually present,
  579. size_t num_modules = bytes_required / sizeof(HMODULE);
  580. for (size_t i = 0; i < num_modules; ++i) {
  581. HMODULE handle = hmodules[i];
  582. MODULEINFO mi;
  583. if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
  584. continue;
  585. // Get the UTF-16 path and convert to UTF-8.
  586. int modname_utf16_len =
  587. GetModuleFileNameW(handle, &modname_utf16[0], kMaxPathLength);
  588. if (modname_utf16_len == 0)
  589. modname_utf16[0] = '\0';
  590. int module_name_len = ::WideCharToMultiByte(
  591. CP_UTF8, 0, &modname_utf16[0], modname_utf16_len + 1, &module_name[0],
  592. kMaxPathLength, NULL, NULL);
  593. module_name[module_name_len] = '\0';
  594. uptr base_address = (uptr)mi.lpBaseOfDll;
  595. uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
  596. // Adjust the base address of the module so that we get a VA instead of an
  597. // RVA when computing the module offset. This helps llvm-symbolizer find the
  598. // right DWARF CU. In the common case that the image is loaded at it's
  599. // preferred address, we will now print normal virtual addresses.
  600. uptr preferred_base =
  601. GetPreferredBase(&module_name[0], &buf[0], buf.size());
  602. uptr adjusted_base = base_address - preferred_base;
  603. modules_.push_back(LoadedModule());
  604. LoadedModule &cur_module = modules_.back();
  605. cur_module.set(&module_name[0], adjusted_base);
  606. // We add the whole module as one single address range.
  607. cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
  608. /*writable*/ true);
  609. }
  610. UnmapOrDie(hmodules, modules_buffer_size);
  611. }
  612. void ListOfModules::fallbackInit() { clear(); }
  613. // We can't use atexit() directly at __asan_init time as the CRT is not fully
  614. // initialized at this point. Place the functions into a vector and use
  615. // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
  616. InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
  617. static int queueAtexit(void (*function)(void)) {
  618. atexit_functions.push_back(function);
  619. return 0;
  620. }
  621. // If Atexit() is being called after RunAtexit() has already been run, it needs
  622. // to be able to call atexit() directly. Here we use a function ponter to
  623. // switch out its behaviour.
  624. // An example of where this is needed is the asan_dynamic runtime on MinGW-w64.
  625. // On this environment, __asan_init is called during global constructor phase,
  626. // way after calling the .CRT$XID initializer.
  627. static int (*volatile queueOrCallAtExit)(void (*)(void)) = &queueAtexit;
  628. int Atexit(void (*function)(void)) { return queueOrCallAtExit(function); }
  629. static int RunAtexit() {
  630. TraceLoggingUnregister(g_asan_provider);
  631. queueOrCallAtExit = &atexit;
  632. int ret = 0;
  633. for (uptr i = 0; i < atexit_functions.size(); ++i) {
  634. ret |= atexit(atexit_functions[i]);
  635. }
  636. return ret;
  637. }
  638. #pragma section(".CRT$XID", long, read)
  639. __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
  640. #endif
  641. // ------------------ sanitizer_libc.h
  642. fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
  643. // FIXME: Use the wide variants to handle Unicode filenames.
  644. fd_t res;
  645. if (mode == RdOnly) {
  646. res = CreateFileA(filename, GENERIC_READ,
  647. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  648. nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  649. } else if (mode == WrOnly) {
  650. res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
  651. FILE_ATTRIBUTE_NORMAL, nullptr);
  652. } else {
  653. UNIMPLEMENTED();
  654. }
  655. CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
  656. CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
  657. if (res == kInvalidFd && last_error)
  658. *last_error = GetLastError();
  659. return res;
  660. }
  661. void CloseFile(fd_t fd) {
  662. CloseHandle(fd);
  663. }
  664. bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
  665. error_t *error_p) {
  666. CHECK(fd != kInvalidFd);
  667. // bytes_read can't be passed directly to ReadFile:
  668. // uptr is unsigned long long on 64-bit Windows.
  669. unsigned long num_read_long;
  670. bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
  671. if (!success && error_p)
  672. *error_p = GetLastError();
  673. if (bytes_read)
  674. *bytes_read = num_read_long;
  675. return success;
  676. }
  677. bool SupportsColoredOutput(fd_t fd) {
  678. // FIXME: support colored output.
  679. return false;
  680. }
  681. bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
  682. error_t *error_p) {
  683. CHECK(fd != kInvalidFd);
  684. // Handle null optional parameters.
  685. error_t dummy_error;
  686. error_p = error_p ? error_p : &dummy_error;
  687. uptr dummy_bytes_written;
  688. bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
  689. // Initialize output parameters in case we fail.
  690. *error_p = 0;
  691. *bytes_written = 0;
  692. // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
  693. // closed, in which case this will fail.
  694. if (fd == kStdoutFd || fd == kStderrFd) {
  695. fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
  696. if (fd == 0) {
  697. *error_p = ERROR_INVALID_HANDLE;
  698. return false;
  699. }
  700. }
  701. DWORD bytes_written_32;
  702. if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
  703. *error_p = GetLastError();
  704. return false;
  705. } else {
  706. *bytes_written = bytes_written_32;
  707. return true;
  708. }
  709. }
  710. uptr internal_sched_yield() {
  711. Sleep(0);
  712. return 0;
  713. }
  714. void internal__exit(int exitcode) {
  715. TraceLoggingUnregister(g_asan_provider);
  716. // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
  717. // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
  718. // so add our own breakpoint here.
  719. if (::IsDebuggerPresent())
  720. __debugbreak();
  721. TerminateProcess(GetCurrentProcess(), exitcode);
  722. BUILTIN_UNREACHABLE();
  723. }
  724. uptr internal_ftruncate(fd_t fd, uptr size) {
  725. UNIMPLEMENTED();
  726. }
  727. uptr GetRSS() {
  728. PROCESS_MEMORY_COUNTERS counters;
  729. if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
  730. return 0;
  731. return counters.WorkingSetSize;
  732. }
  733. void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
  734. void internal_join_thread(void *th) { }
  735. void FutexWait(atomic_uint32_t *p, u32 cmp) {
  736. WaitOnAddress(p, &cmp, sizeof(cmp), INFINITE);
  737. }
  738. void FutexWake(atomic_uint32_t *p, u32 count) {
  739. if (count == 1)
  740. WakeByAddressSingle(p);
  741. else
  742. WakeByAddressAll(p);
  743. }
  744. uptr GetTlsSize() {
  745. return 0;
  746. }
  747. void InitTlsSize() {
  748. }
  749. void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
  750. uptr *tls_addr, uptr *tls_size) {
  751. #if SANITIZER_GO
  752. *stk_addr = 0;
  753. *stk_size = 0;
  754. *tls_addr = 0;
  755. *tls_size = 0;
  756. #else
  757. uptr stack_top, stack_bottom;
  758. GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
  759. *stk_addr = stack_bottom;
  760. *stk_size = stack_top - stack_bottom;
  761. *tls_addr = 0;
  762. *tls_size = 0;
  763. #endif
  764. }
  765. void ReportFile::Write(const char *buffer, uptr length) {
  766. SpinMutexLock l(mu);
  767. ReopenIfNecessary();
  768. if (!WriteToFile(fd, buffer, length)) {
  769. // stderr may be closed, but we may be able to print to the debugger
  770. // instead. This is the case when launching a program from Visual Studio,
  771. // and the following routine should write to its console.
  772. OutputDebugStringA(buffer);
  773. }
  774. }
  775. void SetAlternateSignalStack() {
  776. // FIXME: Decide what to do on Windows.
  777. }
  778. void UnsetAlternateSignalStack() {
  779. // FIXME: Decide what to do on Windows.
  780. }
  781. void InstallDeadlySignalHandlers(SignalHandlerType handler) {
  782. (void)handler;
  783. // FIXME: Decide what to do on Windows.
  784. }
  785. HandleSignalMode GetHandleSignalMode(int signum) {
  786. // FIXME: Decide what to do on Windows.
  787. return kHandleSignalNo;
  788. }
  789. // Check based on flags if we should handle this exception.
  790. bool IsHandledDeadlyException(DWORD exceptionCode) {
  791. switch (exceptionCode) {
  792. case EXCEPTION_ACCESS_VIOLATION:
  793. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  794. case EXCEPTION_STACK_OVERFLOW:
  795. case EXCEPTION_DATATYPE_MISALIGNMENT:
  796. case EXCEPTION_IN_PAGE_ERROR:
  797. return common_flags()->handle_segv;
  798. case EXCEPTION_ILLEGAL_INSTRUCTION:
  799. case EXCEPTION_PRIV_INSTRUCTION:
  800. case EXCEPTION_BREAKPOINT:
  801. return common_flags()->handle_sigill;
  802. case EXCEPTION_FLT_DENORMAL_OPERAND:
  803. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  804. case EXCEPTION_FLT_INEXACT_RESULT:
  805. case EXCEPTION_FLT_INVALID_OPERATION:
  806. case EXCEPTION_FLT_OVERFLOW:
  807. case EXCEPTION_FLT_STACK_CHECK:
  808. case EXCEPTION_FLT_UNDERFLOW:
  809. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  810. case EXCEPTION_INT_OVERFLOW:
  811. return common_flags()->handle_sigfpe;
  812. }
  813. return false;
  814. }
  815. bool IsAccessibleMemoryRange(uptr beg, uptr size) {
  816. SYSTEM_INFO si;
  817. GetNativeSystemInfo(&si);
  818. uptr page_size = si.dwPageSize;
  819. uptr page_mask = ~(page_size - 1);
  820. for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
  821. page <= end;) {
  822. MEMORY_BASIC_INFORMATION info;
  823. if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
  824. return false;
  825. if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
  826. info.Protect == PAGE_EXECUTE)
  827. return false;
  828. if (info.RegionSize == 0)
  829. return false;
  830. page += info.RegionSize;
  831. }
  832. return true;
  833. }
  834. bool SignalContext::IsStackOverflow() const {
  835. return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
  836. }
  837. void SignalContext::InitPcSpBp() {
  838. EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
  839. CONTEXT *context_record = (CONTEXT *)context;
  840. pc = (uptr)exception_record->ExceptionAddress;
  841. # if SANITIZER_WINDOWS64
  842. # if SANITIZER_ARM64
  843. bp = (uptr)context_record->Fp;
  844. sp = (uptr)context_record->Sp;
  845. # else
  846. bp = (uptr)context_record->Rbp;
  847. sp = (uptr)context_record->Rsp;
  848. # endif
  849. # else
  850. bp = (uptr)context_record->Ebp;
  851. sp = (uptr)context_record->Esp;
  852. # endif
  853. }
  854. uptr SignalContext::GetAddress() const {
  855. EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
  856. if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
  857. return exception_record->ExceptionInformation[1];
  858. return (uptr)exception_record->ExceptionAddress;
  859. }
  860. bool SignalContext::IsMemoryAccess() const {
  861. return ((EXCEPTION_RECORD *)siginfo)->ExceptionCode ==
  862. EXCEPTION_ACCESS_VIOLATION;
  863. }
  864. bool SignalContext::IsTrueFaultingAddress() const { return true; }
  865. SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
  866. EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
  867. // The write flag is only available for access violation exceptions.
  868. if (exception_record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
  869. return SignalContext::Unknown;
  870. // The contents of this array are documented at
  871. // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
  872. // The first element indicates read as 0, write as 1, or execute as 8. The
  873. // second element is the faulting address.
  874. switch (exception_record->ExceptionInformation[0]) {
  875. case 0:
  876. return SignalContext::Read;
  877. case 1:
  878. return SignalContext::Write;
  879. case 8:
  880. return SignalContext::Unknown;
  881. }
  882. return SignalContext::Unknown;
  883. }
  884. void SignalContext::DumpAllRegisters(void *context) {
  885. // FIXME: Implement this.
  886. }
  887. int SignalContext::GetType() const {
  888. return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
  889. }
  890. const char *SignalContext::Describe() const {
  891. unsigned code = GetType();
  892. // Get the string description of the exception if this is a known deadly
  893. // exception.
  894. switch (code) {
  895. case EXCEPTION_ACCESS_VIOLATION:
  896. return "access-violation";
  897. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  898. return "array-bounds-exceeded";
  899. case EXCEPTION_STACK_OVERFLOW:
  900. return "stack-overflow";
  901. case EXCEPTION_DATATYPE_MISALIGNMENT:
  902. return "datatype-misalignment";
  903. case EXCEPTION_IN_PAGE_ERROR:
  904. return "in-page-error";
  905. case EXCEPTION_ILLEGAL_INSTRUCTION:
  906. return "illegal-instruction";
  907. case EXCEPTION_PRIV_INSTRUCTION:
  908. return "priv-instruction";
  909. case EXCEPTION_BREAKPOINT:
  910. return "breakpoint";
  911. case EXCEPTION_FLT_DENORMAL_OPERAND:
  912. return "flt-denormal-operand";
  913. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  914. return "flt-divide-by-zero";
  915. case EXCEPTION_FLT_INEXACT_RESULT:
  916. return "flt-inexact-result";
  917. case EXCEPTION_FLT_INVALID_OPERATION:
  918. return "flt-invalid-operation";
  919. case EXCEPTION_FLT_OVERFLOW:
  920. return "flt-overflow";
  921. case EXCEPTION_FLT_STACK_CHECK:
  922. return "flt-stack-check";
  923. case EXCEPTION_FLT_UNDERFLOW:
  924. return "flt-underflow";
  925. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  926. return "int-divide-by-zero";
  927. case EXCEPTION_INT_OVERFLOW:
  928. return "int-overflow";
  929. }
  930. return "unknown exception";
  931. }
  932. uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
  933. if (buf_len == 0)
  934. return 0;
  935. // Get the UTF-16 path and convert to UTF-8.
  936. InternalMmapVector<wchar_t> binname_utf16(kMaxPathLength);
  937. int binname_utf16_len =
  938. GetModuleFileNameW(NULL, &binname_utf16[0], kMaxPathLength);
  939. if (binname_utf16_len == 0) {
  940. buf[0] = '\0';
  941. return 0;
  942. }
  943. int binary_name_len =
  944. ::WideCharToMultiByte(CP_UTF8, 0, &binname_utf16[0], binname_utf16_len,
  945. buf, buf_len, NULL, NULL);
  946. if ((unsigned)binary_name_len == buf_len)
  947. --binary_name_len;
  948. buf[binary_name_len] = '\0';
  949. return binary_name_len;
  950. }
  951. uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
  952. return ReadBinaryName(buf, buf_len);
  953. }
  954. void CheckVMASize() {
  955. // Do nothing.
  956. }
  957. void InitializePlatformEarly() {
  958. // Do nothing.
  959. }
  960. void CheckASLR() {
  961. // Do nothing
  962. }
  963. void CheckMPROTECT() {
  964. // Do nothing
  965. }
  966. char **GetArgv() {
  967. // FIXME: Actually implement this function.
  968. return 0;
  969. }
  970. char **GetEnviron() {
  971. // FIXME: Actually implement this function.
  972. return 0;
  973. }
  974. pid_t StartSubprocess(const char *program, const char *const argv[],
  975. const char *const envp[], fd_t stdin_fd, fd_t stdout_fd,
  976. fd_t stderr_fd) {
  977. // FIXME: implement on this platform
  978. // Should be implemented based on
  979. // SymbolizerProcess::StarAtSymbolizerSubprocess
  980. // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
  981. return -1;
  982. }
  983. bool IsProcessRunning(pid_t pid) {
  984. // FIXME: implement on this platform.
  985. return false;
  986. }
  987. int WaitForProcess(pid_t pid) { return -1; }
  988. // FIXME implement on this platform.
  989. void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
  990. void CheckNoDeepBind(const char *filename, int flag) {
  991. // Do nothing.
  992. }
  993. // FIXME: implement on this platform.
  994. bool GetRandom(void *buffer, uptr length, bool blocking) {
  995. UNIMPLEMENTED();
  996. }
  997. u32 GetNumberOfCPUs() {
  998. SYSTEM_INFO sysinfo = {};
  999. GetNativeSystemInfo(&sysinfo);
  1000. return sysinfo.dwNumberOfProcessors;
  1001. }
  1002. #if SANITIZER_WIN_TRACE
  1003. // TODO(mcgov): Rename this project-wide to PlatformLogInit
  1004. void AndroidLogInit(void) {
  1005. HRESULT hr = TraceLoggingRegister(g_asan_provider);
  1006. if (!SUCCEEDED(hr))
  1007. return;
  1008. }
  1009. void SetAbortMessage(const char *) {}
  1010. void LogFullErrorReport(const char *buffer) {
  1011. if (common_flags()->log_to_syslog) {
  1012. InternalMmapVector<wchar_t> filename;
  1013. DWORD filename_length = 0;
  1014. do {
  1015. filename.resize(filename.size() + 0x100);
  1016. filename_length =
  1017. GetModuleFileNameW(NULL, filename.begin(), filename.size());
  1018. } while (filename_length >= filename.size());
  1019. TraceLoggingWrite(g_asan_provider, "AsanReportEvent",
  1020. TraceLoggingValue(filename.begin(), "ExecutableName"),
  1021. TraceLoggingValue(buffer, "AsanReportContents"));
  1022. }
  1023. }
  1024. #endif // SANITIZER_WIN_TRACE
  1025. void InitializePlatformCommonFlags(CommonFlags *cf) {}
  1026. } // namespace __sanitizer
  1027. #endif // _WIN32