Esempio n. 1
0
/* Win64 exception handler for interpreter frame. */
LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
  void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
{
  lua_State *L = cframe_L(cf);
  int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
		LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
  if ((rec->ExceptionFlags & 6)) {  /* EH_UNWINDING|EH_EXIT_UNWIND */
    /* Unwind internal frames. */
    err_unwind(L, cf, errcode);
  } else {
    void *cf2 = err_unwind(L, cf, 0);
    if (cf2) {  /* We catch it, so start unwinding the upper frames. */
      if (rec->ExceptionCode == LJ_MSVC_EXCODE) {
#ifdef _MSC_VER
	__DestructExceptionObject(rec, 1);
#endif
	setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
      } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
	/* Don't catch access violations etc. */
	return ExceptionContinueSearch;
      }
      /* Unwind the stack and call all handlers for all lower C frames
      ** (including ourselves) again with EH_UNWINDING set. Then set
      ** rsp = cf, rax = errcode and jump to the specified target.
      */
      RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
			       lj_vm_unwind_ff_eh :
			       lj_vm_unwind_c_eh),
		  rec, (void *)errcode, ctx, dispatch->HistoryTable);
      /* RtlUnwindEx should never return. */
    }
  }
  return ExceptionContinueSearch;
}
Esempio n. 2
0
/** Personality function that is called to request a stack unwinding operation.
 *  The purpose of this function is essentially to jump to the nearest then
 *  (or else) branch of a Pony try/then/else expression, relative to the 'error'
 *  expression that triggered this unwind request.
 *
 *  The EstablisherFrame given to this function describes the stack pointer
 *  (RSP) value of the target of this unwind operation.
 *
 *  Hence, the EstablisherFrame refers to the stack pointer of the caller
 *  of the function that caused the exception that we are inspecting here.
 *  Depending on the current exception handling state, this frame pointer
 *  is the target to a call to RtlUnwindEx, which implements the logic
 *  to unwind the stack to some frame further down the call stack.
 *
 *  Most importantly, RtlUnwindEx is capable of unwinding past multiple
 *  procedure frames, such that the cost of a Pony exception (neglecting
 *  the kernel transition of RaiseException) ends up in being a single
 *  longjump to the correct stack frame, where the handling else (and
 *  possibly then block) resides. We statically know that there will
 *  be one.
 *
 *  Signature of RtlUnwindEx:
 *
 *  VOID
 *  NTAPI
 *  RtlUnwindEx(
 *    __in_opt ULONG64               TargetFrame,
 *    __in_opt ULONG64               TargetIp,
 *    __in_opt PEXCEPTION_RECORD     ExceptionRecord,
 *    __in     PVOID                 ReturnValue,
 *    __out    PCONTEXT              OriginalContext,
 *    __in_opt PUNWIND_HISTORY_TABLE HistoryTable
 *  );
 *
 *  TargetFrame is the stack pointer value to which we want to unwind to.
 *  Consequently, TargetIp is the instruction pointer (which must be valid
 *  within the provided stack frame) to an instruction where execution
 *  should be continued. For our purposes, the ExceptionRecord argument
 *  is optional and describes the reason of an exception. In Pony, there
 *  is only one reason for stack unwinding, so we will basically ignore
 *  the ExceptionRecord and simply pass it through from this personality
 *  function. The motivation for this is performance, as otherwise
 *  RtlUnwindEx would allocate a default record type STATUS_UNWIND).
 *
 *  The ReturnValue argument can be used to place a value into the return
 *  register once stack unwinding is completed. Since we are unwinding
 *  function calls, we ignore this parameter. The OriginalContext can be
 *  used to supply user defined scratch space to store information between
 *  unwind operations. The runtimes exception dispatcher 'pony_throw' does
 *  not supply any arguments, so this parameter is ignored as well.
 *
 *  The HistoryTable can be used as a cache to improve performance of
 *  repeated function entry lookups. If unwinding non-trivial call frames
 *  becomes critical, using it might improve performance.
 *
 *  RtlUnwindEx does not ever return to its caller (i.e. this personality
 *  function). If it does, the process will (most likely) be terminated.
 */
EXCEPTION_DISPOSITION pony_personality_v0(EXCEPTION_RECORD *ExcRecord,
  void* EstablisherFrame, _CONTEXT *ContextRecord, DISPATCHER_CONTEXT* DispatcherContext)
{
  if(ExcRecord->ExceptionCode != PONY_EXCEPTION_CLASS || IS_UNWINDING(ExcRecord->ExceptionFlags))
    return ExceptionContinueSearch;

  if(!(ExcRecord->ExceptionFlags  &
    (EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND)))
  {
    if(!ponyint_lsda_scan(DispatcherContext, &landing_pad))
      return ExceptionContinueSearch;

    RtlUnwindEx(EstablisherFrame, (PVOID)landing_pad, ExcRecord,
      NULL, ContextRecord, DispatcherContext->HistoryTable);
  }

  if(ExcRecord->ExceptionFlags & EXCEPTION_TARGET_UNWIND)
  {
    DispatcherContext->ContextRecord->Rdx = landing_pad;
    return ExceptionContinueSearch;
  }

  //never reaches here, if it does, impending doom incoming
  abort();
}
Esempio n. 3
0
extern "C" void __cdecl _UnwindNestedFrames(
    EHRegistrationNode  *pFrame,            // Unwind up to (but not including) this frame
    EHExceptionRecord   *pExcept,           // The exception that initiated this unwind
    CONTEXT             *pContext,           // Context info for current exception
    EHRegistrationNode  *pEstablisher,
    void                *Handler,
    __ehstate_t         TargetUnwindState,
    FuncInfo            *pFuncInfo,
    DispatcherContext   *pDC,
    BOOLEAN             recursive

) {
    static const EXCEPTION_RECORD ExceptionTemplate = // A generic exception record
    {
        STATUS_UNWIND_CONSOLIDATE,         // STATUS_UNWIND_CONSOLIDATE
        EXCEPTION_NONCONTINUABLE,          // Exception flags (we don't do resume)
        nullptr,                           // Additional record (none)
        nullptr,                           // Address of exception (OS fills in)
        15,                                // Number of parameters
        {   EH_MAGIC_NUMBER1,              // Our version control magic number
            0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0
        }                                  // pThrowInfo
    };

    CONTEXT Context;
    EXCEPTION_RECORD ExceptionRecord = ExceptionTemplate;
    ExceptionRecord.ExceptionInformation[0] = (ULONG_PTR)__CxxCallCatchBlock;
                // Address of call back function
    ExceptionRecord.ExceptionInformation[1] = (ULONG_PTR)pEstablisher;
                // Used by callback funciton
    ExceptionRecord.ExceptionInformation[2] = (ULONG_PTR)Handler;
                // Used by callback function to call catch block
    ExceptionRecord.ExceptionInformation[3] = (ULONG_PTR)TargetUnwindState;
                // Used by CxxFrameHandler to unwind to target_state
    ExceptionRecord.ExceptionInformation[4] = (ULONG_PTR)pContext;
                // used to set pCurrentExContext in callback function
    ExceptionRecord.ExceptionInformation[5] = (ULONG_PTR)pFuncInfo;
                // Used in callback function to set state on stack to -2
    ExceptionRecord.ExceptionInformation[6] = (ULONG_PTR)pExcept;
                // Used for passing current Exception
    ExceptionRecord.ExceptionInformation[7] = (ULONG_PTR)recursive;
                // Used for translated Exceptions
    ExceptionRecord.ExceptionInformation[8] = EH_MAGIC_NUMBER1;
                // Used in __InternalCxxFrameHandler to detected if it's being
                // called from _UnwindNestedFrames.
    RtlUnwindEx((void *)*pFrame,
                (void *)pDC->ControlPc,    // Address where control left function
                &ExceptionRecord,
                nullptr,
                &Context,
                (PUNWIND_HISTORY_TABLE)pDC->HistoryTable);
}
Esempio n. 4
0
DECLSPEC_GUARD_SUPPRESS
EXCEPTION_DISPOSITION
__C_specific_handler (
    _In_ PEXCEPTION_RECORD ExceptionRecord,
    _In_ PVOID EstablisherFrame,
    _Inout_ PCONTEXT ContextRecord,
    _Inout_ PDISPATCHER_CONTEXT DispatcherContext
    )

/*++

Routine Description:

    This function scans the scope tables associated with the specified
    procedure and calls exception and termination handlers as necessary.

Arguments:

    ExceptionRecord - Supplies a pointer to an exception record.

    EstablisherFrame - Supplies a pointer to frame of the establisher function.

    ContextRecord - Supplies a pointer to a context record.

    DispatcherContext - Supplies a pointer to the exception dispatcher or
        unwind dispatcher context.

    N.B. SHRINK WRAPPING MUST BE DISABLED FOR THIS FUNCTION.

Return Value:

    If an exception is being dispatched and the exception is handled by one
    of the exception filter routines, then there is no return from this
    routine and RtlUnwind is called. Otherwise, an exception disposition
    value of continue execution or continue search is returned.

    If an unwind is being dispatched, then each termination handler is called
    and a value of continue search is returned.

--*/

{

    ULONG_PTR ControlPc;
    PEXCEPTION_FILTER ExceptionFilter;
    EXCEPTION_POINTERS ExceptionPointers;
    ULONG_PTR ImageBase;
    ULONG_PTR Handler;
    ULONG Index;
    PSCOPE_TABLE ScopeTable;
    ULONG TargetIndex;
    ULONG_PTR TargetPc;
    PTERMINATION_HANDLER TerminationHandler;
    LONG Value;

    DISABLE_SHRINK_WRAPPING();

#if defined(_M_AMD64)

    //
    // Validate integrity of context record.
    //
    __except_validate_context_record(ContextRecord);

#endif

    //
    // Get the image base address. compute the relative address of where
    // control left the establisher, and get the address of the scope table.
    //

    ImageBase = DispatcherContext->ImageBase;
    ControlPc = DispatcherContext->ControlPc - ImageBase;
    ScopeTable = (PSCOPE_TABLE)(DispatcherContext->HandlerData);

#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_)

    //
    // Do we have an indirect scope table?
    //

    if ((ScopeTable->Count & (1 << 31)) != 0) {
        ScopeTable = (PSCOPE_TABLE)(ImageBase + (ScopeTable->Count & ~(1 << 31)));
    }

    //
    // If this context came from an unwind to a call, then the ControlPc points
    // to a return address, which could put us at the start of a neighboring
    // scope. To correct for this, back the PC up by the minimum instruction
    // size to ensure we are in the same scope as the original branch opcode.
    //

    if (DispatcherContext->ControlPcIsUnwound != FALSE) {

#if defined(_M_ARM_NT)

        ControlPc -= 2;

#else

        ControlPc -= 4;

#endif

    }

#endif // defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_)

    //
    // If an unwind is not in progress, then scan the scope table and call
    // the appropriate exception filter routines. Otherwise, scan the scope
    // table and call the appropriate termination handlers using the target
    // PC obtained from the dispatcher context.
    //

    if (IS_DISPATCHING(ExceptionRecord->ExceptionFlags)) {

        //
        // Scan the scope table and call the appropriate exception filter
        // routines.
        //

        ExceptionPointers.ExceptionRecord = ExceptionRecord;
        ExceptionPointers.ContextRecord = ContextRecord;
        for (Index = DispatcherContext->ScopeIndex; Index < ScopeTable->Count; Index += 1) {
            if ((ControlPc >= ScopeTable->ScopeRecord[Index].BeginAddress) &&
                (ControlPc < ScopeTable->ScopeRecord[Index].EndAddress) &&
                (ScopeTable->ScopeRecord[Index].JumpTarget != 0)) {

                //
                // If the filter function address is the distinguished value
                // one, then set the disposition value to execute handler.
                // Otherwise, call the exception filter function to get the
                // disposition value.
                //

                if (ScopeTable->ScopeRecord[Index].HandlerAddress == 1) {
                    Value = EXCEPTION_EXECUTE_HANDLER;

                } else {
                    ExceptionFilter =
                        (PEXCEPTION_FILTER)(ScopeTable->ScopeRecord[Index].HandlerAddress + ImageBase);

                    Value = EXECUTE_EXCEPTION_FILTER(&ExceptionPointers,
                                                     EstablisherFrame,
                                                     ExceptionFilter,
                                                     DispatcherContext);
                }

                //
                // If the return value is less than zero, then dismiss the
                // exception. Otherwise, if the value is greater than zero,
                // then unwind to the target exception handler. Otherwise,
                // continue the search for an exception filter.
                //

                if (Value < 0) {
                    return ExceptionContinueExecution;

                } else if (Value > 0) {

                    //
                    // If a thrown C++ exception is being handled, then let
                    // the C++ exception handler destruct the thrown object.
                    //

#ifndef _NTSUBSET_

                    if ((ExceptionRecord->ExceptionCode == EH_EXCEPTION_NUMBER) &&
                        (_pDestructExceptionObject != NULL) &&
                        (_IsNonwritableInCurrentImage(&_pDestructExceptionObject))) {

                        (*_pDestructExceptionObject)(ExceptionRecord, TRUE);
                    }

#endif

                    //
                    // Inform the debugger that control is about to be passed
                    // to an exception handler and pass the handler's address
                    // to NLG_Notify.
                    //

                    Handler = ImageBase + ScopeTable->ScopeRecord[Index].JumpTarget;
                    _NLG_Notify((PVOID)Handler, EstablisherFrame, 0x1);
                    RtlUnwindEx(EstablisherFrame,
                                (PVOID)(ScopeTable->ScopeRecord[Index].JumpTarget + ImageBase),
                                ExceptionRecord,
                                (PVOID)((ULONG_PTR)ExceptionRecord->ExceptionCode),
                                (PCONTEXT)DispatcherContext->ContextRecord,
                                DispatcherContext->HistoryTable);


                    //
                    // Notify debugger : return from exception handler
                    //

                    __NLG_Return2();
                }
            }
        }

    } else {

        //
        // Scan the scope table and call the appropriate termination handler
        // routines.
        //

        TargetPc = DC_TARGETPC(DispatcherContext) - ImageBase;
        for (Index = DispatcherContext->ScopeIndex; Index < ScopeTable->Count; Index += 1) {
            if ((ControlPc >= ScopeTable->ScopeRecord[Index].BeginAddress) &&
                (ControlPc < ScopeTable->ScopeRecord[Index].EndAddress)) {

                if (IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags)) {

                    //
                    // If the target PC is within the same scope as the control PC,
                    // then this is an uplevel goto out of an inner try scope or a
                    // long jump back into a try scope. Terminate the scan for a
                    // termination handler.
                    //
                    // N.B.  Due to a bug in the AMD64 compiler, try scopes may
                    //       be split into multiple regions, requiring a scan
                    //       of the earlier region of the table to verify that
                    //       the target PC is not within the same try scope.
                    //       The split scopes could reside both before or after
                    //       the currently searched scope in the scope table.
                    //
                    // N.B.  The target PC can be just beyond the end of the
                    //       scope in which case it is a leave from a scope.
                    //       The "leave from a scope" case is subsequently
                    //       handled before control is transferred.
                    //

                    for (TargetIndex = 0; TargetIndex < ScopeTable->Count; TargetIndex += 1) {
                        if ((TargetPc >= ScopeTable->ScopeRecord[TargetIndex].BeginAddress) &&
                            (TargetPc < ScopeTable->ScopeRecord[TargetIndex].EndAddress) &&
                            (ScopeTable->ScopeRecord[TargetIndex].JumpTarget == ScopeTable->ScopeRecord[Index].JumpTarget) &&
                            (ScopeTable->ScopeRecord[TargetIndex].HandlerAddress == ScopeTable->ScopeRecord[Index].HandlerAddress)) {

                            break;
                        }
                    }

                    if (TargetIndex != ScopeTable->Count) {
                        break;
                    }
                }

                //
                // If the scope table entry describes an exception filter
                // and the associated exception handler is the target of
                // the unwind, then terminate the scan for termination
                // handlers. Otherwise, if the scope table entry describes
                // a termination handler, then record the address of the
                // end of the scope as the new control PC address and call
                // the termination handler.
                //

                if (ScopeTable->ScopeRecord[Index].JumpTarget != 0) {
                    if ((TargetPc == ScopeTable->ScopeRecord[Index].JumpTarget) &&
                        (IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags))) {

                        break;
                    }

                } else {
                    DispatcherContext->ScopeIndex = Index + 1;
                    TerminationHandler =
                        (PTERMINATION_HANDLER)(ScopeTable->ScopeRecord[Index].HandlerAddress + ImageBase);

                    EXECUTE_TERMINATION_HANDLER(TRUE,
                                                EstablisherFrame,
                                                TerminationHandler,
                                                DispatcherContext);
                }
            }
        }
    }

    //
    // Continue search for exception or termination handlers.
    //

    ENABLE_SHRINK_WRAPPING();

    return ExceptionContinueSearch;
}