summaryrefslogtreecommitdiff
path: root/src/pal/src/exception/seh.cpp
blob: 38779bf59bf8ab9dc10bfbf0e88d51f3c4acd780 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*++



Module Name:

    seh.cpp

Abstract:

    Implementation of exception API functions.



--*/

#include "pal/thread.hpp"
#include "pal/handleapi.hpp"
#include "pal/seh.hpp"
#include "pal/dbgmsg.h"
#include "pal/critsect.h"
#include "pal/debug.h"
#include "pal/init.h"
#include "pal/process.h"
#include "pal/malloc.hpp"
#include "signal.hpp"

#if HAVE_MACH_EXCEPTIONS
#include "machexception.h"
#else
#include <signal.h>
#endif

#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

// Define the std::move so that we don't have to include the <utility> header
// which on some platforms pulls in STL stuff that collides with PAL stuff.
// The std::move is needed to enable using move constructor and assignment operator
// for PAL_SEHException.
namespace std
{
    template<typename T>
    struct remove_reference
    {
        typedef T type;
    };

    template<typename T>
    struct remove_reference<T&>
    {
        typedef T type;
    };

    template<typename T>
    struct remove_reference<T&&>
    {
        typedef T type;
    };

    template<class T> inline
    typename remove_reference<T>::type&& move(T&& arg)
    {   // forward arg as movable
        return ((typename remove_reference<T>::type&&)arg);
    }
}

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(EXCEPT);

/* Constant and type definitions **********************************************/

/* Bit 28 of exception codes is reserved. */
const UINT RESERVED_SEH_BIT = 0x800000;

/* Internal variables definitions **********************************************/

PHARDWARE_EXCEPTION_HANDLER g_hardwareExceptionHandler = NULL;
// Function to check if an activation can be safely injected at a specified context
PHARDWARE_EXCEPTION_SAFETY_CHECK_FUNCTION g_safeExceptionCheckFunction = NULL;

PGET_GCMARKER_EXCEPTION_CODE g_getGcMarkerExceptionCode = NULL;

/* Internal function definitions **********************************************/

/*++
Function :
    SEHInitialize

    Initialize all SEH-related stuff (signals, etc)

Parameters :
    CPalThread * pthrCurrent : reference to the current thread.
    PAL initialize flags

Return value :
    TRUE  if SEH support initialization succeeded
    FALSE otherwise
--*/
BOOL 
SEHInitialize (CPalThread *pthrCurrent, DWORD flags)
{
#if !HAVE_MACH_EXCEPTIONS
    if (!SEHInitializeSignals(flags))
    {
        ERROR("SEHInitializeSignals failed!\n");
        SEHCleanup();
        return FALSE;
    }
#endif

    return TRUE;
}

/*++
Function :
    SEHCleanup

    Undo work done by SEHInitialize

Parameters :
    None

    (no return value)
    
--*/
VOID 
SEHCleanup()
{
    TRACE("Cleaning up SEH\n");

#if HAVE_MACH_EXCEPTIONS
    SEHCleanupExceptionPort();
#else
    SEHCleanupSignals();
#endif
}

/*++
Function:
    PAL_SetHardwareExceptionHandler

    Register a hardware exception handler.

Parameters:
    handler - exception handler

Return value:
    None
--*/
VOID
PALAPI 
PAL_SetHardwareExceptionHandler(
    IN PHARDWARE_EXCEPTION_HANDLER exceptionHandler,
    IN PHARDWARE_EXCEPTION_SAFETY_CHECK_FUNCTION exceptionCheckFunction)
{
    g_hardwareExceptionHandler = exceptionHandler;
    g_safeExceptionCheckFunction = exceptionCheckFunction;
}

/*++
Function:
    PAL_SetGetGcMarkerExceptionCode

    Register a function that determines if the specified IP has code that is a GC marker for GCCover.

Parameters:
    getGcMarkerExceptionCode - the function to register

Return value:
    None
--*/
VOID
PALAPI 
PAL_SetGetGcMarkerExceptionCode(
    IN PGET_GCMARKER_EXCEPTION_CODE getGcMarkerExceptionCode)
{
    g_getGcMarkerExceptionCode = getGcMarkerExceptionCode;
}

EXTERN_C void ThrowExceptionFromContextInternal(CONTEXT* context, PAL_SEHException* ex);

/*++
Function:
    PAL_ThrowExceptionFromContext

    This function creates a stack frame right below the target frame, restores all callee
    saved registers from the passed in context, sets the RSP to that frame and sets the
    return address to the target frame's RIP.
    Then it uses the ThrowExceptionHelper to throw the passed in exception from that context.

Parameters:
    CONTEXT* context - context from which the exception will be thrown
    PAL_SEHException* ex - the exception to throw.
--*/
VOID
PALAPI 
PAL_ThrowExceptionFromContext(CONTEXT* context, PAL_SEHException* ex)
{
    // We need to make a copy of the exception off stack, since the "ex" is located in one of the stack
    // frames that will become obsolete by the ThrowExceptionFromContextInternal and the ThrowExceptionHelper
    // could overwrite the "ex" object by stack e.g. when allocating the low level exception object for "throw".
    static __thread BYTE threadLocalExceptionStorage[sizeof(PAL_SEHException)];
    ThrowExceptionFromContextInternal(context, new (threadLocalExceptionStorage) PAL_SEHException(std::move(*ex)));
}

/*++
Function:
    ThrowExceptionHelper

    Helper function to throw the passed in exception.
    It is called from the assembler function ThrowExceptionFromContextInternal

Parameters:
    PAL_SEHException* ex - the exception to throw.
--*/
extern "C"
void ThrowExceptionHelper(PAL_SEHException* ex)
{
    throw std::move(*ex);
}

/*++
Function:
    SEHProcessException

    Send the PAL exception to any handler registered.

Parameters:
    PAL_SEHException* exception

Return value:
    Returns TRUE if the exception happened in managed code and the execution should 
    continue (with possibly modified context).
    Returns FALSE if the exception happened in managed code and it was not handled.
    In case the exception was handled by calling a catch handler, it doesn't return at all.
--*/
BOOL
SEHProcessException(PAL_SEHException* exception)
{
    CONTEXT* contextRecord = exception->GetContextRecord();
    EXCEPTION_RECORD* exceptionRecord = exception->GetExceptionRecord();

    if (!IsInDebugBreak(exceptionRecord->ExceptionAddress))
    {
        if (g_hardwareExceptionHandler != NULL)
        {
            _ASSERTE(g_safeExceptionCheckFunction != NULL);
            // Check if it is safe to handle the hardware exception (the exception happened in managed code
            // or in a jitter helper or it is a debugger breakpoint)
            if (g_safeExceptionCheckFunction(contextRecord, exceptionRecord))
            {
                if (exceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
                {
                    // Check if the failed access has hit a stack guard page. In such case, it
                    // was a stack probe that detected that there is not enough stack left.
                    void* stackLimit = CPalThread::GetStackLimit();
                    void* stackGuard = (void*)((size_t)stackLimit - getpagesize());
                    void* violationAddr = (void*)exceptionRecord->ExceptionInformation[1];
                    if ((violationAddr >= stackGuard) && (violationAddr < stackLimit))
                    {
                        // The exception happened in the page right below the stack limit,
                        // so it is a stack overflow
                        write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1);
                        PROCAbort();
                    }
                }

                if (g_hardwareExceptionHandler(exception))
                {
                    // The exception happened in managed code and the execution should continue.
                    return TRUE;
                }

                // The exception was a single step or a breakpoint and it was not handled by the debugger.
            }
        }

        if (CatchHardwareExceptionHolder::IsEnabled())
        {
            PAL_ThrowExceptionFromContext(exception->GetContextRecord(), exception);
        }
    }

    // Unhandled hardware exception pointers->ExceptionRecord->ExceptionCode at pointers->ExceptionRecord->ExceptionAddress
    return FALSE;
}

/*++
Function :
    SEHEnable

    Enable SEH-related stuff on this thread

Parameters:
    CPalThread * pthrCurrent : reference to the current thread.

Return value :
    TRUE  if enabling succeeded
    FALSE otherwise
--*/
extern "C"
PAL_ERROR SEHEnable(CPalThread *pthrCurrent)
{
#if HAVE_MACH_EXCEPTIONS
    return pthrCurrent->EnableMachExceptions();
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
    // TODO: This needs to be implemented. Cannot put an ASSERT here
    // because it will make other parts of PAL fail.
    return NO_ERROR;
#else// HAVE_MACH_EXCEPTIONS
#error not yet implemented
#endif // HAVE_MACH_EXCEPTIONS
}

/*++
Function :
    SEHDisable

    Disable SEH-related stuff on this thread

Parameters:
    CPalThread * pthrCurrent : reference to the current thread.

Return value :
    TRUE  if enabling succeeded
    FALSE otherwise
--*/
extern "C"
PAL_ERROR SEHDisable(CPalThread *pthrCurrent)
{
#if HAVE_MACH_EXCEPTIONS
    return pthrCurrent->DisableMachExceptions();
    // TODO: This needs to be implemented. Cannot put an ASSERT here
    // because it will make other parts of PAL fail.
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
    return NO_ERROR;
#else // HAVE_MACH_EXCEPTIONS
#error not yet implemented
#endif // HAVE_MACH_EXCEPTIONS
}

/*++

  CatchHardwareExceptionHolder implementation

--*/

CatchHardwareExceptionHolder::CatchHardwareExceptionHolder()
{
    CPalThread *pThread = InternalGetCurrentThread();
    ++pThread->m_hardwareExceptionHolderCount;
}

CatchHardwareExceptionHolder::~CatchHardwareExceptionHolder()
{
    CPalThread *pThread = InternalGetCurrentThread();
    --pThread->m_hardwareExceptionHolderCount;
}

bool CatchHardwareExceptionHolder::IsEnabled()
{
    CPalThread *pThread = InternalGetCurrentThread();
    return pThread->IsHardwareExceptionsEnabled();
}

/*++

  NativeExceptionHolderBase implementation

--*/

#ifdef __llvm__
__thread 
#else // __llvm__
__declspec(thread)
#endif // !__llvm__
static NativeExceptionHolderBase *t_nativeExceptionHolderHead = nullptr;

NativeExceptionHolderBase::NativeExceptionHolderBase()
{
    m_head = nullptr;
    m_next = nullptr;
}

NativeExceptionHolderBase::~NativeExceptionHolderBase()
{
    // Only destroy if Push was called
    if (m_head != nullptr)
    {
        *m_head = m_next;
        m_head = nullptr;
        m_next = nullptr;
    }
}

void 
NativeExceptionHolderBase::Push()
{
    NativeExceptionHolderBase **head = &t_nativeExceptionHolderHead;
    m_head = head;
    m_next = *head;
    *head = this;
}

NativeExceptionHolderBase *
NativeExceptionHolderBase::FindNextHolder(NativeExceptionHolderBase *currentHolder, void *stackLowAddress, void *stackHighAddress)
{
    NativeExceptionHolderBase *holder = (currentHolder == nullptr) ? t_nativeExceptionHolderHead : currentHolder->m_next;

    while (holder != nullptr)
    {
        if (((void *)holder >= stackLowAddress) && ((void *)holder < stackHighAddress))
        { 
            return holder;
        }
        // Get next holder
        holder = holder->m_next;
    }

    return nullptr;
}

#include "seh-unwind.cpp"