#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_WINDOWS
#define WIN32_LEAN_AND_MEAN
# include <stdlib.h>
# include <windows.h>
# include "asan_interceptors.h"
# include "asan_internal.h"
# include "asan_mapping.h"
# include "asan_report.h"
# include "asan_stack.h"
# include "asan_thread.h"
# include "sanitizer_common/sanitizer_libc.h"
# include "sanitizer_common/sanitizer_mutex.h"
# include "sanitizer_common/sanitizer_win.h"
# include "sanitizer_common/sanitizer_win_defs.h"
using namespace __asan;
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE
int __asan_should_detect_stack_use_after_return() {
__asan_init();
return __asan_option_detect_stack_use_after_return;
}
SANITIZER_INTERFACE_ATTRIBUTE
uptr __asan_get_shadow_memory_dynamic_address() {
__asan_init();
return __asan_shadow_memory_dynamic_address;
}
}
static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(
EXCEPTION_POINTERS *info) {
EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
CONTEXT *context = info->ContextRecord;
SignalContext sig(exception_record, context);
ReportDeadlySignal(sig);
UNREACHABLE("returned from reporting deadly signal");
}
static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
DWORD exception_code = info->ExceptionRecord->ExceptionCode;
if (__sanitizer::IsHandledDeadlyException(exception_code))
return __asan_unhandled_exception_filter(info);
if (user_seh_handler)
return user_seh_handler(info);
if (default_seh_handler)
return default_seh_handler(info);
return EXCEPTION_CONTINUE_SEARCH;
}
INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER, SetUnhandledExceptionFilter,
LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter) {
CHECK(REAL(SetUnhandledExceptionFilter));
if (ExceptionFilter == &SEHHandler)
return REAL(SetUnhandledExceptionFilter)(ExceptionFilter);
Swap(ExceptionFilter, user_seh_handler);
return ExceptionFilter;
}
INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
CHECK(REAL(RtlRaiseException));
if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
__asan_handle_no_return();
REAL(RtlRaiseException)(ExceptionRecord);
}
INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
CHECK(REAL(RaiseException));
__asan_handle_no_return();
REAL(RaiseException)(a, b, c, d);
}
#ifdef _WIN64
INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION, __C_specific_handler,
_EXCEPTION_RECORD *a, void *b, _CONTEXT *c,
_DISPATCHER_CONTEXT *d) {
CHECK(REAL(__C_specific_handler));
__asan_handle_no_return();
return REAL(__C_specific_handler)(a, b, c, d);
}
#else
INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
CHECK(REAL(_except_handler3));
__asan_handle_no_return();
return REAL(_except_handler3)(a, b, c, d);
}
#if ASAN_DYNAMIC
#define _except_handler4 …
#endif
INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
CHECK(REAL(_except_handler4));
__asan_handle_no_return();
return REAL(_except_handler4)(a, b, c, d);
}
#endif
struct ThreadStartParams {
thread_callback_t start_routine;
void *arg;
};
static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
AsanThread *t = (AsanThread *)arg;
SetCurrentThread(t);
t->ThreadStart(GetTid());
ThreadStartParams params;
t->GetStartData(params);
auto res = (*params.start_routine)(params.arg);
t->Destroy();
return res;
}
INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
void *arg, DWORD thr_flags, DWORD *tid) {
if (flags()->strict_init_order)
StopInitOrderChecking();
GET_STACK_TRACE_THREAD;
bool detached = false;
u32 current_tid = GetCurrentTidOrInvalid();
ThreadStartParams params = {start_routine, arg};
AsanThread *t = AsanThread::Create(params, current_tid, &stack, detached);
return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
thr_flags, tid);
}
namespace __asan {
void InitializePlatformInterceptors() {
__interception::SetErrorReportCallback(Report);
HMODULE pinned;
CHECK(GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
(LPCWSTR)&InitializePlatformInterceptors, &pinned));
ASAN_INTERCEPT_FUNC(CreateThread);
ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
#ifdef _WIN64
ASAN_INTERCEPT_FUNC(__C_specific_handler);
#else
ASAN_INTERCEPT_FUNC(_except_handler3);
ASAN_INTERCEPT_FUNC(_except_handler4);
#endif
if (!::__interception::OverrideFunction("RaiseException",
(uptr)WRAP(RaiseException),
(uptr *)&REAL(RaiseException))) {
CHECK(::__interception::OverrideFunction("RtlRaiseException",
(uptr)WRAP(RtlRaiseException),
(uptr *)&REAL(RtlRaiseException)));
}
}
void InstallAtExitCheckLeaks() {}
void InstallAtForkHandler() {}
void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
UNIMPLEMENTED();
}
void FlushUnneededASanShadowMemory(uptr p, uptr size) {
#if SANITIZER_WINDOWS64
ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
#endif
}
static bool tsd_key_inited = false;
static __declspec(thread) void *fake_tsd = 0;
typedef struct _TEB {
PVOID Reserved1[12];
PVOID ProcessEnvironmentBlock;
PVOID Reserved2[399];
BYTE Reserved3[1952];
PVOID TlsSlots[64];
BYTE Reserved4[8];
PVOID Reserved5[26];
PVOID ReservedForOle;
PVOID Reserved6[4];
PVOID TlsExpansionSlots;
} TEB, *PTEB;
constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
BOOL IsTlsInitialized() {
PTEB teb = (PTEB)NtCurrentTeb();
return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
nullptr;
}
void AsanTSDInit(void (*destructor)(void *tsd)) {
tsd_key_inited = true;
}
void *AsanTSDGet() {
CHECK(tsd_key_inited);
return IsTlsInitialized() ? fake_tsd : nullptr;
}
void AsanTSDSet(void *tsd) {
CHECK(tsd_key_inited);
fake_tsd = tsd;
}
void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
uptr FindDynamicShadowStart() {
return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
0, kHighMemEnd,
GetMmapGranularity());
}
void AsanCheckDynamicRTPrereqs() {}
void AsanCheckIncompatibleRT() {}
void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
bool PlatformUnpoisonStacks() { return false; }
#if SANITIZER_WINDOWS64
static LONG CALLBACK
ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
uptr page_size = GetPageSizeCached();
if (exception_pointers->ExceptionRecord->ExceptionCode !=
EXCEPTION_ACCESS_VIOLATION ||
exception_pointers->ExceptionRecord->NumberParameters < 2) {
__asan_handle_no_return();
return EXCEPTION_CONTINUE_SEARCH;
}
uptr addr =
(uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
if (!AddrIsInShadow(addr)) {
__asan_handle_no_return();
return EXCEPTION_CONTINUE_SEARCH;
}
uptr page = RoundDownTo(addr, page_size);
uptr result =
(uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
if (result != page)
return EXCEPTION_CONTINUE_SEARCH;
return EXCEPTION_CONTINUE_EXECUTION;
}
#endif
void InitializePlatformExceptionHandlers() {
#if SANITIZER_WINDOWS64
CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
#endif
}
bool IsSystemHeapAddress(uptr addr) {
return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
if (prev_seh_handler != &SEHHandler)
default_seh_handler = prev_seh_handler;
return 0;
}
bool HandleDlopenInit() {
static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
"Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
return false;
}
#if !ASAN_DYNAMIC
#pragma section(".CRT$XCAB", long, read)
__declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
__asan_set_seh_filter;
static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
if (reason == DLL_PROCESS_ATTACH)
__asan_init();
}
#pragma section(".CRT$XLAB", long, read)
__declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(
void *, unsigned long, void *) = asan_thread_init;
#endif
static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
if (reason == DLL_THREAD_DETACH) {
NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
__asan_unpoison_memory_region(tib->StackLimit, stackSize);
}
}
#pragma section(".CRT$XLY", long, read)
__declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(
void *, unsigned long, void *) = asan_thread_exit;
WIN_FORCE_LINK(__asan_dso_reg_hook)
}
#endif