From c0bc9d472e242ae9a7422ccf06fd1b783340e474 Mon Sep 17 00:00:00 2001
From: Jan Vorlicek <janvorli@microsoft.com>
Date: Fri, 7 Jan 2022 00:42:26 +0100
Subject: [PATCH 1/3] Fix exception propagation over HW exception frame on
 macOS arm64

There is a bug in setting up the fake stack frame for
the PAL_DispatchExceptionWrapper. The FP and SP were not saved
to the stack frame and the FP of the context was not set to
match the fake prologue. That caused failure to unwind over the
PAL_DispatchExceptionWrapper, reaching an unrelated native
function.

This change fixes it.
---
 src/coreclr/pal/src/exception/machexception.cpp | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/coreclr/pal/src/exception/machexception.cpp b/src/coreclr/pal/src/exception/machexception.cpp
index e5aebdf652c6a5..31b68b53743430 100644
--- a/src/coreclr/pal/src/exception/machexception.cpp
+++ b/src/coreclr/pal/src/exception/machexception.cpp
@@ -907,9 +907,13 @@ HijackFaultingThread(
     ts64.__x[1] = (uint64_t)pExceptionRecord;
     ts64.__x[2] = (uint64_t)pMachExceptionInfo;
 
+    FramePointer = (void **)((ULONG_PTR)FramePointer - 2 * sizeof(void *));
     // Make sure it's aligned - SP has 16-byte alignment
     FramePointer = (void **)((ULONG_PTR)FramePointer - ((ULONG_PTR)FramePointer % 16));
+    FramePointer[0] = (void*)pContext->Fp;
+    FramePointer[1] = (void*)pContext->Lr;
     arm_thread_state64_set_sp(ts64, FramePointer);
+    arm_thread_state64_set_fp(ts64, FramePointer);
 
     // Make the call to DispatchException
     arm_thread_state64_set_lr_fptr(ts64, (uint64_t)PAL_DispatchExceptionWrapper + PAL_DispatchExceptionReturnOffset);

From f2fc88d6d684621be889bfcc3744d0be34dccf11 Mon Sep 17 00:00:00 2001
From: Jan Vorlicek <janvorli@microsoft.com>
Date: Fri, 7 Jan 2022 15:27:15 +0100
Subject: [PATCH 2/3] Add regression tests for the issue

---
 .../coreclr/GitHub_62058/test62058.cs         | 60 +++++++++++++++++++
 .../coreclr/GitHub_62058/test62058.csproj     |  9 +++
 2 files changed, 69 insertions(+)
 create mode 100644 src/tests/Regressions/coreclr/GitHub_62058/test62058.cs
 create mode 100644 src/tests/Regressions/coreclr/GitHub_62058/test62058.csproj

diff --git a/src/tests/Regressions/coreclr/GitHub_62058/test62058.cs b/src/tests/Regressions/coreclr/GitHub_62058/test62058.cs
new file mode 100644
index 00000000000000..3744007d9e45ac
--- /dev/null
+++ b/src/tests/Regressions/coreclr/GitHub_62058/test62058.cs
@@ -0,0 +1,60 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+
+public class Program
+{
+    private interface IFoo
+    {
+        bool IsValid { get; }
+    }
+
+    private class Foo : IFoo
+    {
+        public bool IsValid { get; set; }
+    }
+
+    public static int Main(string[] args)
+    {
+        bool warmup = new Foo().IsValid;
+        CatchIgnore(() =>
+        CatchRethrow(() =>
+        {
+            IFoo[] foos = {new Foo(), null};
+            foreach (var foo in foos)
+            {
+                bool check = foo.IsValid;
+            }
+        }));
+
+        return 100;
+    }
+
+    public static void CatchRethrow(Action action)
+    {
+        try
+        {
+            action.Invoke();
+        }
+        catch (Exception e)
+        {
+            Console.Out.WriteLine("catch");
+            Console.Out.Flush();
+            throw new Exception("catch", e);  // throw; doesn't work either
+        }
+    }
+
+    public static void CatchIgnore(Action action)
+    {
+        try
+        {
+            action.Invoke();
+        }
+        catch (Exception)
+        {
+            Console.Out.WriteLine("ignore");
+            Console.Out.Flush();
+        }
+    }
+}
diff --git a/src/tests/Regressions/coreclr/GitHub_62058/test62058.csproj b/src/tests/Regressions/coreclr/GitHub_62058/test62058.csproj
new file mode 100644
index 00000000000000..0fce5a0556f40e
--- /dev/null
+++ b/src/tests/Regressions/coreclr/GitHub_62058/test62058.csproj
@@ -0,0 +1,9 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <CLRTestPriority>1</CLRTestPriority>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="test62058.cs" />
+  </ItemGroup>
+</Project>

From e3675d2751c151659fd7a88b343f3e78d7aac493 Mon Sep 17 00:00:00 2001
From: Jan Vorlicek <janvorli@microsoft.com>
Date: Fri, 7 Jan 2022 21:55:52 +0100
Subject: [PATCH 3/3] Real fix of the issue

Unifies the hardware exception frame unwinding with Linux,
it is necessary on arm64 to get correct and distinct LR and
PC in the frame of the hardware exception.
---
 src/coreclr/pal/src/exception/machexception.cpp |  6 ++----
 src/coreclr/pal/src/exception/seh-unwind.cpp    | 16 ++++++++--------
 src/coreclr/pal/src/exception/signal.cpp        |  7 ++-----
 src/coreclr/pal/src/include/pal/seh.hpp         |  5 +++++
 4 files changed, 17 insertions(+), 17 deletions(-)

diff --git a/src/coreclr/pal/src/exception/machexception.cpp b/src/coreclr/pal/src/exception/machexception.cpp
index 31b68b53743430..0449be77458df3 100644
--- a/src/coreclr/pal/src/exception/machexception.cpp
+++ b/src/coreclr/pal/src/exception/machexception.cpp
@@ -376,6 +376,8 @@ void PAL_DispatchException(PCONTEXT pContext, PEXCEPTION_RECORD pExRecord, MachE
     *contextRecord = *pContext;
     *exceptionRecord = *pExRecord;
 
+    g_hardware_exception_context_locvar_offset = (int)((char*)&contextRecord - (char*)__builtin_frame_address(0));
+
     contextRecord->ContextFlags |= CONTEXT_EXCEPTION_ACTIVE;
     bool continueExecution;
 
@@ -907,13 +909,9 @@ HijackFaultingThread(
     ts64.__x[1] = (uint64_t)pExceptionRecord;
     ts64.__x[2] = (uint64_t)pMachExceptionInfo;
 
-    FramePointer = (void **)((ULONG_PTR)FramePointer - 2 * sizeof(void *));
     // Make sure it's aligned - SP has 16-byte alignment
     FramePointer = (void **)((ULONG_PTR)FramePointer - ((ULONG_PTR)FramePointer % 16));
-    FramePointer[0] = (void*)pContext->Fp;
-    FramePointer[1] = (void*)pContext->Lr;
     arm_thread_state64_set_sp(ts64, FramePointer);
-    arm_thread_state64_set_fp(ts64, FramePointer);
 
     // Make the call to DispatchException
     arm_thread_state64_set_lr_fptr(ts64, (uint64_t)PAL_DispatchExceptionWrapper + PAL_DispatchExceptionReturnOffset);
diff --git a/src/coreclr/pal/src/exception/seh-unwind.cpp b/src/coreclr/pal/src/exception/seh-unwind.cpp
index 9a1f5d0b5e89d4..a9ddb179d5f822 100644
--- a/src/coreclr/pal/src/exception/seh-unwind.cpp
+++ b/src/coreclr/pal/src/exception/seh-unwind.cpp
@@ -476,7 +476,9 @@ void GetContextPointers(unw_cursor_t *cursor, unw_context_t *unwContext, KNONVOL
 
 #ifndef HOST_WINDOWS
 
-extern int g_common_signal_handler_context_locvar_offset;
+// Frame pointer relative offset of a local containing a pointer to the windows style context of a location
+// where a hardware exception occured.
+int g_hardware_exception_context_locvar_offset = 0;
 
 BOOL PAL_VirtualUnwind(CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *contextPointers)
 {
@@ -486,19 +488,17 @@ BOOL PAL_VirtualUnwind(CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *contextP
 
     DWORD64 curPc = CONTEXTGetPC(context);
 
-#ifndef __APPLE__
-    // Check if the PC is the return address from the SEHProcessException in the common_signal_handler.
-    // If that's the case, extract its local variable containing the windows style context of the hardware
+    // Check if the PC is the return address from the SEHProcessException.
+    // If that's the case, extract its local variable containing a pointer to the windows style context of the hardware
     // exception and return that. This skips the hardware signal handler trampoline that the libunwind
-    // cannot cross on some systems.
+    // cannot cross on some systems. On macOS, it skips a similar trampoline we create in HijackFaultingThread.
     if ((void*)curPc == g_SEHProcessExceptionReturnAddress)
     {
-        CONTEXT* signalContext = (CONTEXT*)(CONTEXTGetFP(context) + g_common_signal_handler_context_locvar_offset);
-        memcpy_s(context, sizeof(CONTEXT), signalContext, sizeof(CONTEXT));
+        CONTEXT* exceptionContext = *(CONTEXT**)(CONTEXTGetFP(context) + g_hardware_exception_context_locvar_offset);
+        memcpy_s(context, sizeof(CONTEXT), exceptionContext, sizeof(CONTEXT));
 
         return TRUE;
     }
-#endif
 
     if ((context->ContextFlags & CONTEXT_EXCEPTION_ACTIVE) != 0)
     {
diff --git a/src/coreclr/pal/src/exception/signal.cpp b/src/coreclr/pal/src/exception/signal.cpp
index 59b513b87204e9..4d9e8582acf949 100644
--- a/src/coreclr/pal/src/exception/signal.cpp
+++ b/src/coreclr/pal/src/exception/signal.cpp
@@ -114,10 +114,6 @@ struct sigaction g_previous_sigabrt;
 
 #if !HAVE_MACH_EXCEPTIONS
 
-// Offset of the local variable containing pointer to windows style context in the common_signal_handler function.
-// This offset is relative to the frame pointer.
-int g_common_signal_handler_context_locvar_offset = 0;
-
 // TOP of special stack for handling stack overflow
 volatile void* g_stackOverflowHandlerStack = NULL;
 
@@ -931,11 +927,12 @@ static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext
 #if !HAVE_MACH_EXCEPTIONS
     sigset_t signal_set;
     CONTEXT signalContextRecord;
+    CONTEXT* signalContextRecordPtr = &signalContextRecord;
     EXCEPTION_RECORD exceptionRecord;
     native_context_t *ucontext;
 
     ucontext = (native_context_t *)sigcontext;
-    g_common_signal_handler_context_locvar_offset = (int)((char*)&signalContextRecord - (char*)__builtin_frame_address(0));
+    g_hardware_exception_context_locvar_offset = (int)((char*)&signalContextRecordPtr - (char*)__builtin_frame_address(0));
 
     if (code == (SIGSEGV | StackOverflowFlag))
     {
diff --git a/src/coreclr/pal/src/include/pal/seh.hpp b/src/coreclr/pal/src/include/pal/seh.hpp
index 6ad89df0fdd650..327fe0d7fb03e2 100644
--- a/src/coreclr/pal/src/include/pal/seh.hpp
+++ b/src/coreclr/pal/src/include/pal/seh.hpp
@@ -145,5 +145,10 @@ CorUnix::PAL_ERROR SEHDisable(CorUnix::CPalThread *pthrCurrent);
 
 }
 
+// Offset of the local variable containing pointer to windows style context in the common_signal_handler / PAL_DispatchException function.
+// This offset is relative to the frame pointer.
+extern int g_hardware_exception_context_locvar_offset;
+
+
 #endif /* _PAL_SEH_HPP_ */
 
