Capture CONTEXT registers at the beginning of the function with explicit
compiler memory barrier to prevent compiler from clobbering registers.

Fix filling of Esp/Rsp and Ebp/Rbp registers.

Add explaining comments for most of the function logic.
---
 mingw-w64-crt/misc/_invoke_watson.c | 87 ++++++++++++++++++++++-------
 1 file changed, 67 insertions(+), 20 deletions(-)

diff --git a/mingw-w64-crt/misc/_invoke_watson.c 
b/mingw-w64-crt/misc/_invoke_watson.c
index a7fa505024b2..dbec112126f7 100644
--- a/mingw-w64-crt/misc/_invoke_watson.c
+++ b/mingw-w64-crt/misc/_invoke_watson.c
@@ -7,6 +7,11 @@
 #include <corecrt.h>
 #include <windows.h>
 
+/* keep SEH_INLINE_ASM in sync with mingw-w64-crt/crt/crtexe.c */
+#if defined(__SEH__) && (!defined(__clang__) || __clang_major__ >= 7)
+#define SEH_INLINE_ASM
+#endif
+
 #if defined(__i386__)
 DECLSPEC_NOINLINE /* decrease chance of modifying caller's registers and/or 
stack frame */
 #endif
@@ -29,25 +34,19 @@ static BOOL is_fastfail_available(void)
 /* DECLSPEC_NOINLINE is needed for __builtin_return_address() and 
__builtin_frame_address() usage */
 DECLSPEC_NOINLINE __MINGW_ATTRIB_NORETURN void __cdecl _invoke_watson(const 
wchar_t * __UNUSED_PARAM(expression), const wchar_t * 
__UNUSED_PARAM(function_name), const wchar_t * __UNUSED_PARAM(file_name), 
unsigned int __UNUSED_PARAM(line_number), uintptr_t __UNUSED_PARAM(reserved))
 {
-    EXCEPTION_RECORD exception_record = { 0, };
-    CONTEXT context = { 0, };
-    EXCEPTION_POINTERS exception_pointers = { &exception_record, &context };
-#if defined(__x86_64__)
-    ULONG64 establisher_frame;
-    ULONG64 image_base;
-    PRUNTIME_FUNCTION function_entry;
-    PVOID handler_data;
-#endif
-
     if (is_fastfail_available())
         __fastfail(FAST_FAIL_INVALID_ARG);
 
+    CONTEXT context; /* do not initialize context (to zeros) to prevent using 
registers and clobbering their content. */
     /*
      * RtlCaptureContext() is available since Windows XP.
      * UCRT runtime uses inline assemly on 32-bit x86.
      * For compatibility with UCRT do same thing.
      */
 #if defined(__i386__)
+    /* Values for context.Eip, context.Esp and context.Ebp are explicitly
+     * not filled because they are overwritten few lines below.
+     */
     asm volatile(
         "mov %%eax, %0\n\t"
         "mov %%ecx, %1\n\t"
@@ -71,34 +70,82 @@ DECLSPEC_NOINLINE __MINGW_ATTRIB_NORETURN void __cdecl 
_invoke_watson(const wcha
         "=m" (context.SegEs), "=m" (context.SegFs), "=m" (context.SegGs),
         "=m" (context.EFlags)
       :
-      :
+      : "memory" /* compiler barrier */
     );
+    context.ContextFlags = CONTEXT_CONTROL;
 #else
     RtlCaptureContext(&context);
+    asm volatile("" ::: "memory"); /* compiler barrier to prevent executing 
something before RtlCaptureContext() */
+#endif
+
+    /* Define and fill all other variables after capturing registers. */
+    EXCEPTION_RECORD exception_record = { 0, };
+    EXCEPTION_POINTERS exception_pointers = { &exception_record, &context };
+#if defined(__x86_64__)
+    ULONG64 image_base;
+    PRUNTIME_FUNCTION function_entry;
 #endif
 
     /* Fill additional platform specific fields of the parent (caller) 
function into context. */
 #if defined(__i386__)
-    context.ContextFlags = CONTEXT_CONTROL;
+    /*
+     * Current stack frame returned by __builtin_frame_address(0) contains
+     * values of caller function: ebp, eip. Therefore esp of called
+     * function is address of stack frame plus size of those 2 registers and
+     * ebp of called function is dereferenced first value (indexed from 1).
+     * Note that msvc _AddressOfReturnAddress() is address of the eip value
+     * which should be &(((uintptr_t *)__builtin_frame_address(0))[1]) and
+     * therefore below code for context.Esp/Ebp should match the msvc behavior.
+     */
     context.Eip = 
(uintptr_t)__builtin_extract_return_addr(__builtin_return_address(0)); /* msvc 
uses _ReturnAddress() */
-    context.Esp = (uintptr_t)__builtin_frame_address(0); /* msvc uses 
_AddressOfReturnAddress() */
-    context.Ebp = *((uintptr_t *)__builtin_frame_address(0)-1); /* msvc uses 
*((ULONG *)_AddressOfReturnAddress()-1) */
+    context.Esp = (uintptr_t)__builtin_frame_address(0) + 2*sizeof(uintptr_t); 
/* msvc uses _AddressOfReturnAddress() */
+    context.Ebp = ((uintptr_t *)__builtin_frame_address(0))[0]; /* msvc uses 
*((ULONG *)_AddressOfReturnAddress()-1) */
 #elif defined(__x86_64__)
+#if defined(SEH_INLINE_ASM)
+    /* FIXME: function_entry is pointer to SEH unwind data table for the 
current
+     * function, which is generated by linker at the link time. Linker should 
be
+     * able to provide this pointer at link time and therefore it would not be
+     * required to lookup it at runtime.
+     * TODO: Let linker to resolve function_entry at link time and avoid 
calling
+     * RtlLookupFunctionEntry() function at all.
+     */
     function_entry = RtlLookupFunctionEntry(context.Rip, &image_base, NULL);
-    if (function_entry)
-        RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, 
function_entry, &context, &handler_data, &establisher_frame, NULL);
-    context.Rip = 
(uintptr_t)__builtin_extract_return_addr(__builtin_return_address(0)); /* msvc 
uses _ReturnAddress() */
-    context.Rsp = (uintptr_t)__builtin_frame_address(0); /* msvc uses 
_AddressOfReturnAddress()+8 */
-    context.Rbp = *((uintptr_t *)__builtin_frame_address(0)-1); /* not filled 
filled by msvc */
+#else
+    /* SEH unwind data table is not used, so RtlVirtualUnwind() cannot be 
called. */
+    function_entry = NULL;
+#endif
+    if (function_entry) {
+        /* If possible use SEH unwind data table to fill the &context structure
+         * with data from the parent (caller). This will update at least 
fields:
+         * context.Rip, context.Rsp, context.Rbp
+         */
+        RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, 
function_entry, &context, &(PVOID){NULL} /*out: HandlerData*/, &(ULONG64){0} 
/*out: EstablisherFrame*/, NULL);
+    } else {
+        /* If SEH unwind data table is not available then just fix RIP/RSP/RBP.
+         * Current stack frame returned by __builtin_frame_address(0) contains
+         * values of caller function: rdi, rbp, rip. Therefore rsp of called
+         * function is address of stack frame plus size of those 3 registers 
and
+         * rbp of called function is dereferenced second value (indexed from 
1).
+         * Note that msvc _AddressOfReturnAddress() is address of the rip value
+         * which should be &(((uintptr_t *)__builtin_frame_address(0))[2]) and
+         * therefore below code for context.Rsp should match the msvc behavior.
+         */
+        context.Rip = 
(uintptr_t)__builtin_extract_return_addr(__builtin_return_address(0)); /* msvc 
uses _ReturnAddress() */
+        context.Rsp = (uintptr_t)__builtin_frame_address(0) + 
3*sizeof(uintptr_t); /* msvc uses _AddressOfReturnAddress()+8 */
+        context.Rbp = ((uintptr_t *)__builtin_frame_address(0))[1]; /* not 
filled by msvc */
+    }
 #endif
 
     exception_record.ExceptionCode = STATUS_INVALID_CRUNTIME_PARAMETER;
     exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
     exception_record.ExceptionAddress = 
__builtin_extract_return_addr(__builtin_return_address(0)); /* msvc uses 
_ReturnAddress() */
 
-    /* Remove all filters, trigger exception and terminate the process. */
+    /* Remove top level exception filter and throw unhandled exception.
+     * It will break into debugger or directly start Dr. Watson. */
     SetUnhandledExceptionFilter(NULL);
     UnhandledExceptionFilter(&exception_pointers);
+
+    /* In case debugger or Dr. Watson returned back then terminate the 
process. */
     TerminateProcess(GetCurrentProcess(), STATUS_INVALID_CRUNTIME_PARAMETER);
     __builtin_unreachable();
 }
-- 
2.20.1



_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to