Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /* Structured Exception Handling (SEH) runtime interface routines.
  2.    Copyright (C) 2010-2015 Free Software Foundation, Inc.
  3.  
  4.    This file is part of GCC.
  5.  
  6.    GCC is free software; you can redistribute it and/or modify it
  7.    under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 3, or (at your option)
  9.    any later version.
  10.  
  11.    GCC is distributed in the hope that it will be useful, but WITHOUT
  12.    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  13.    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  14.    License for more details.
  15.  
  16.    Under Section 7 of GPL version 3, you are granted additional
  17.    permissions described in the GCC Runtime Library Exception, version
  18.    3.1, as published by the Free Software Foundation.
  19.  
  20.    You should have received a copy of the GNU General Public License and
  21.    a copy of the GCC Runtime Library Exception along with this program;
  22.    see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
  23.    <http://www.gnu.org/licenses/>.  */
  24.  
  25. #include "tconfig.h"
  26. #include "tsystem.h"
  27. #include "coretypes.h"
  28. #include "tm.h"
  29. #include "unwind.h"
  30.  
  31. #if defined (__SEH__) && !defined (__USING_SJLJ_EXCEPTIONS__)
  32.  
  33. /* At the moment everything is written for x64, but in theory this could
  34.    also be used for i386, arm, mips and other extant embedded Windows.  */
  35. #ifndef __x86_64__
  36. #error "Unsupported architecture."
  37. #endif
  38. /* Define GCC's exception codes.  See
  39.      http://msdn.microsoft.com/en-us/library/het71c37(v=VS.80).aspx
  40.    In particular, MS defines bits:
  41.      [31:30] = 3 (error), 2 (warning), 1 (info), 0 (success)
  42.      [29]    = 1 (user-defined)
  43.      [28]    = 0 (reserved)
  44.    We define bits:
  45.      [24:27] = type
  46.      [0:23]  = magic
  47.    We set "magic" to "GCC", which is similar to MVC++ which uses "msc"
  48.    as the low 3 bytes of its user-defined codes for C++ exceptions.
  49.  
  50.    We define the ExceptionInformation entries as follows:
  51.      [0] = _Unwind_Exception pointer
  52.      [1] = target frame
  53.      [2] = target ip
  54.      [3] = target rdx
  55. */
  56.  
  57. #define STATUS_USER_DEFINED             (1U << 29)
  58.  
  59. #define GCC_MAGIC                       (('G' << 16) | ('C' << 8) | 'C')
  60. #define GCC_EXCEPTION(TYPE)             \
  61.        (STATUS_USER_DEFINED | ((TYPE) << 24) | GCC_MAGIC)
  62.  
  63. #define STATUS_GCC_THROW                GCC_EXCEPTION (0)
  64. #define STATUS_GCC_UNWIND               GCC_EXCEPTION (1)
  65. #define STATUS_GCC_FORCED               GCC_EXCEPTION (2)
  66.  
  67. struct _Unwind_Context
  68. {
  69.   _Unwind_Word cfa;
  70.   _Unwind_Word ra;
  71.   _Unwind_Word reg[2];
  72.   PDISPATCHER_CONTEXT disp;
  73. };
  74.  
  75. /* Get the value of register INDEX as saved in CONTEXT.  */
  76.  
  77. _Unwind_Word
  78. _Unwind_GetGR (struct _Unwind_Context *c, int index)
  79. {
  80.   if (index < 0 || index >= 2)
  81.     abort ();
  82.   return c->reg[index];
  83. }
  84.  
  85. /* Overwrite the saved value for register INDEX in CONTEXT with VAL.  */
  86.  
  87. void
  88. _Unwind_SetGR (struct _Unwind_Context *c, int index, _Unwind_Word val)
  89. {
  90.   if (index < 0 || index >= 2)
  91.     abort ();
  92.   c->reg[index] = val;
  93. }
  94.  
  95. /* Get the value of the CFA as saved in CONTEXT.  */
  96.  
  97. _Unwind_Word
  98. _Unwind_GetCFA (struct _Unwind_Context *c)
  99. {
  100.   return c->cfa;
  101. }
  102.  
  103. /* Retrieve the return address for CONTEXT.  */
  104.  
  105. _Unwind_Ptr
  106. _Unwind_GetIP (struct _Unwind_Context *c)
  107. {
  108.   return c->ra;
  109. }
  110.  
  111. /* Retrieve the return address and flag whether that IP is before
  112.    or after first not yet fully executed instruction.  */
  113.  
  114. _Unwind_Ptr
  115. _Unwind_GetIPInfo (struct _Unwind_Context *c, int *ip_before_insn)
  116. {
  117.   /* ??? Is there a concept of a signal context properly?  There's
  118.      obviously an UNWP_PUSH_MACHFRAME opcode, but the runtime might
  119.      have arranged for that not to matter, really.  */
  120.   *ip_before_insn = 0;
  121.   return c->ra;
  122. }
  123.  
  124. /* Overwrite the return address for CONTEXT with VAL.  */
  125.  
  126. void
  127. _Unwind_SetIP (struct _Unwind_Context *c, _Unwind_Ptr val)
  128. {
  129.   c->ra = val;
  130. }
  131.  
  132. void *
  133. _Unwind_GetLanguageSpecificData (struct _Unwind_Context *c)
  134. {
  135.   return c->disp->HandlerData;
  136. }
  137.  
  138. _Unwind_Ptr
  139. _Unwind_GetRegionStart (struct _Unwind_Context *c)
  140. {
  141.   return c->disp->FunctionEntry->BeginAddress + c->disp->ImageBase;
  142. }
  143.  
  144. void *
  145. _Unwind_FindEnclosingFunction (void *pc)
  146. {
  147.   PRUNTIME_FUNCTION entry;
  148.   ULONG64 ImageBase;
  149.  
  150.   entry = RtlLookupFunctionEntry ((ULONG64)pc, &ImageBase, NULL);
  151.  
  152.   return (entry ? (void *)(entry->BeginAddress + ImageBase) : NULL);
  153. }
  154.  
  155. _Unwind_Ptr
  156. _Unwind_GetDataRelBase (struct _Unwind_Context *c ATTRIBUTE_UNUSED)
  157. {
  158.   return 0;
  159. }
  160.  
  161. _Unwind_Ptr
  162. _Unwind_GetTextRelBase (struct _Unwind_Context *c)
  163. {
  164.   return c->disp->ImageBase;
  165. }
  166.  
  167. /* The two-phase unwind process that GCC uses is ordered differently
  168.    from the two-phase unwind process that SEH uses.  The mechansism
  169.    that GCC uses is to have the filter return _URC_HANDER_FOUND; the
  170.    mechanism that SEH uses is for the filter function call back into
  171.    the unwinder.
  172.  
  173.    An Ideal port to SEH would have GCC emit handler functions that
  174.    can be called, given a pointer to the "EstablisherFrame" (i.e.
  175.    the frame pointer base of the user-level function) can manipulate
  176.    the user-level variables within the user-level function's stack
  177.    frame.  Once done manipulating the variables, it would return
  178.    a ExceptionContinueSearch, and the unwind process would continue.
  179.  
  180.    GCC has always done things a bit differently.  We continue to
  181.    transfer control back into the user-level function which, once
  182.    done manipulating the user-level variables, re-throws the exception.  */
  183.  
  184. /* The "real" language-specific personality handler forwards to here
  185.    where we handle the MS SEH state and transforms it into the GCC
  186.    unwind state as per GCC's <unwind.h>, at which point we defer to
  187.    the regular language-specfic exception handler, which is passed in.  */
  188.  
  189. EXCEPTION_DISPOSITION
  190. _GCC_specific_handler (PEXCEPTION_RECORD ms_exc, void *this_frame,
  191.                        PCONTEXT ms_orig_context, PDISPATCHER_CONTEXT ms_disp,
  192.                        _Unwind_Personality_Fn gcc_per)
  193. {
  194.   DWORD ms_flags = ms_exc->ExceptionFlags;
  195.   DWORD ms_code = ms_exc->ExceptionCode;
  196.  
  197.   struct _Unwind_Exception *gcc_exc
  198.     = (struct _Unwind_Exception *) ms_exc->ExceptionInformation[0];
  199.   struct _Unwind_Context gcc_context;
  200.   _Unwind_Action gcc_action;
  201.   _Unwind_Reason_Code gcc_reason;
  202.  
  203.   if (ms_flags & EXCEPTION_TARGET_UNWIND)
  204.     {
  205.       /* This frame is known to be the target frame.  We've already
  206.          "installed" the target_ip and RAX value via the arguments
  207.          to RtlUnwindEx.  All that's left is to set the RDX value
  208.          and "continue" to have the context installed.  */
  209.       ms_disp->ContextRecord->Rdx = ms_exc->ExceptionInformation[3];
  210.       return ExceptionContinueSearch;
  211.     }
  212.  
  213.   if (ms_code == STATUS_GCC_UNWIND)
  214.     {
  215.       /* This is a colliding exception that we threw so that we could
  216.          cancel the already in-flight exception and stop in a frame
  217.          that wanted to perform some unwind action.  The only relevant
  218.          test is that we're the target frame.  */
  219.       if (ms_exc->ExceptionInformation[1] == (_Unwind_Ptr) this_frame)
  220.         {
  221.           RtlUnwindEx (this_frame, ms_exc->ExceptionInformation[2],
  222.                        ms_exc, gcc_exc, ms_orig_context,
  223.                        ms_disp->HistoryTable);
  224.           abort ();
  225.         }
  226.       return ExceptionContinueSearch;
  227.     }
  228.  
  229.   gcc_context.cfa = ms_disp->ContextRecord->Rsp;
  230.   gcc_context.ra = ms_disp->ControlPc;
  231.   gcc_context.reg[0] = 0xdeadbeef;      /* These are write-only.  */
  232.   gcc_context.reg[1] = 0xdeadbeef;
  233.   gcc_context.disp = ms_disp;
  234.  
  235.   if (ms_code == STATUS_GCC_FORCED)
  236.     {
  237.        _Unwind_Stop_Fn stop = (_Unwind_Stop_Fn) gcc_exc->private_[0];
  238.        void *stop_argument = (void *) gcc_exc->private_[4];
  239.  
  240.        gcc_action = _UA_FORCE_UNWIND | _UA_CLEANUP_PHASE;
  241.  
  242.        stop (1, gcc_action, gcc_exc->exception_class, gcc_exc,
  243.              &gcc_context, stop_argument);
  244.  
  245.        goto phase2;
  246.     }
  247.  
  248.   /* ??? TODO: handling non-gcc user-defined exceptions as foreign.  */
  249.   if (ms_code != STATUS_GCC_THROW)
  250.     return ExceptionContinueSearch;
  251.  
  252.   if (ms_flags & (EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND))
  253.     {
  254.       /* This is Phase 2.  */
  255.       /* We know this isn't the target frame because we've already tested
  256.          EXCEPTION_TARGET_UNWIND.  The remaining possibility is that the
  257.          gcc personality has unwind code to run.  */
  258.  
  259.       gcc_action = _UA_CLEANUP_PHASE;
  260.     phase2:
  261.       gcc_reason = gcc_per (1, gcc_action, gcc_exc->exception_class,
  262.                             gcc_exc, &gcc_context);
  263.  
  264.       if (gcc_reason == _URC_CONTINUE_UNWIND)
  265.         return ExceptionContinueSearch;
  266.  
  267.       if (gcc_reason == _URC_INSTALL_CONTEXT)
  268.         {
  269.           /* Scratch space for the bits for the unwind catch.  */
  270.           ms_exc->ExceptionInformation[1] = (_Unwind_Ptr) this_frame;
  271.           ms_exc->ExceptionInformation[2] = gcc_context.ra;
  272.           ms_exc->ExceptionInformation[3] = gcc_context.reg[1];
  273.  
  274.           /* Cancel the current exception by raising another.  */
  275.           RaiseException (STATUS_GCC_UNWIND, EXCEPTION_NONCONTINUABLE,
  276.                           4, ms_exc->ExceptionInformation);
  277.  
  278.           /* Is RaiseException declared noreturn?  */
  279.         }
  280.  
  281.       /* In _Unwind_RaiseException_Phase2 we return _URC_FATAL_PHASE2_ERROR. */
  282.     }
  283.   else
  284.     {
  285.       /* This is Phase 1.  */
  286.       gcc_reason = gcc_per (1, _UA_SEARCH_PHASE, gcc_exc->exception_class,
  287.                             gcc_exc, &gcc_context);
  288.  
  289.       if (gcc_reason == _URC_CONTINUE_UNWIND)
  290.         return ExceptionContinueSearch;
  291.  
  292.       if (gcc_reason == _URC_HANDLER_FOUND)
  293.         {
  294.           /* We really need some of the information that GCC's personality
  295.              routines compute during phase 2 right now, like the target IP.
  296.              Go ahead and ask for it now, and cache it.  */
  297.           gcc_reason = gcc_per (1, _UA_CLEANUP_PHASE | _UA_HANDLER_FRAME,
  298.                                 gcc_exc->exception_class, gcc_exc,
  299.                                 &gcc_context);
  300.           if (gcc_reason != _URC_INSTALL_CONTEXT)
  301.             abort ();
  302.  
  303.           gcc_exc->private_[1] = (_Unwind_Ptr) this_frame;
  304.           gcc_exc->private_[2] = gcc_context.ra;
  305.           gcc_exc->private_[3] = gcc_context.reg[1];
  306.  
  307.           ms_exc->NumberParameters = 4;
  308.           ms_exc->ExceptionInformation[1] = (_Unwind_Ptr) this_frame;
  309.           ms_exc->ExceptionInformation[2] = gcc_context.ra;
  310.           ms_exc->ExceptionInformation[3] = gcc_context.reg[1];
  311.  
  312.           /* Begin phase 2.  Perform the unwinding.  */
  313.           RtlUnwindEx (this_frame, gcc_context.ra, ms_exc,
  314.                        (PVOID)gcc_context.reg[0], ms_orig_context,
  315.                        ms_disp->HistoryTable);
  316.         }
  317.  
  318.       /* In _Unwind_RaiseException we return _URC_FATAL_PHASE1_ERROR.  */
  319.     }
  320.   abort ();
  321. }
  322.  
  323. /* Raise an exception, passing along the given exception object.  */
  324.  
  325. _Unwind_Reason_Code
  326. _Unwind_RaiseException (struct _Unwind_Exception *exc)
  327. {
  328.   memset (exc->private_, 0, sizeof (exc->private_));
  329.  
  330.   /* The ExceptionInformation array will have only 1 element, EXC.  */
  331.   RaiseException (STATUS_GCC_THROW, 0, 1, (ULONG_PTR *)&exc);
  332.  
  333.   /* The exception handler installed in crt0 will continue any GCC
  334.      exception that reaches there (and isn't marked non-continuable).
  335.      Returning allows the C++ runtime to call std::terminate.  */
  336.   return _URC_END_OF_STACK;
  337. }
  338.  
  339. /* Resume propagation of an existing exception.  This is used after
  340.    e.g. executing cleanup code, and not to implement rethrowing.  */
  341.  
  342. void
  343. _Unwind_Resume (struct _Unwind_Exception *gcc_exc)
  344. {
  345.   UNWIND_HISTORY_TABLE ms_history;
  346.   EXCEPTION_RECORD ms_exc;
  347.   CONTEXT ms_context;
  348.  
  349.   memset (&ms_exc, 0, sizeof(ms_exc));
  350.   memset (&ms_history, 0, sizeof(ms_history));
  351.  
  352.   /* ??? Not 100% perfect, since we aren't passing on the *original*
  353.      exception context, but should be good enough.  */
  354.   ms_exc.ExceptionCode = STATUS_GCC_THROW;
  355.   ms_exc.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
  356.   ms_exc.NumberParameters = 4;
  357.   ms_exc.ExceptionInformation[0] = (ULONG_PTR) gcc_exc;
  358.   ms_exc.ExceptionInformation[1] = gcc_exc->private_[1];
  359.   ms_exc.ExceptionInformation[2] = gcc_exc->private_[2];
  360.   ms_exc.ExceptionInformation[3] = gcc_exc->private_[3];
  361.  
  362.   ms_context.ContextFlags = CONTEXT_ALL;
  363.   RtlCaptureContext (&ms_context);
  364.  
  365.   RtlUnwindEx ((void *) gcc_exc->private_[1], gcc_exc->private_[2],
  366.                &ms_exc, gcc_exc, &ms_context, &ms_history);
  367.  
  368.   /* Is RtlUnwindEx declared noreturn?  */
  369.   abort ();
  370. }
  371.  
  372. static _Unwind_Reason_Code
  373. _Unwind_ForcedUnwind_Phase2 (struct _Unwind_Exception *exc)
  374. {
  375.   _Unwind_Stop_Fn stop;
  376.   void * stop_argument;
  377.  
  378.   RaiseException (STATUS_GCC_FORCED, 0, 1, (ULONG_PTR *)&exc);
  379.  
  380.   /* If we get here, we got to top-of-stack.  */
  381.   /* ??? We no longer have a context pointer to pass in.  */
  382.  
  383.   stop = (_Unwind_Stop_Fn) exc->private_[0];
  384.   stop_argument = (void *) exc->private_[4];
  385.   stop (1, _UA_FORCE_UNWIND | _UA_CLEANUP_PHASE | _UA_END_OF_STACK,
  386.         exc->exception_class, exc, NULL, stop_argument);
  387.  
  388.   return _UA_END_OF_STACK;
  389. }
  390.  
  391. _Unwind_Reason_Code
  392. _Unwind_Resume_or_Rethrow (struct _Unwind_Exception *exc)
  393. {
  394.   if (exc->private_[0] == 0)
  395.     _Unwind_RaiseException (exc);
  396.   else
  397.     _Unwind_ForcedUnwind_Phase2 (exc);
  398.   abort ();
  399. }
  400.  
  401. /* Raise an exception for forced unwinding.  */
  402.  
  403. _Unwind_Reason_Code
  404. _Unwind_ForcedUnwind (struct _Unwind_Exception *exc,
  405.                       _Unwind_Stop_Fn stop, void * stop_argument)
  406. {
  407.   /* ??? This is a hack that only works with _GCC_specific_handler.
  408.      There's no way to invoke STOP within frames that use a different
  409.      exception handler.  This is essentially just good enough to run
  410.      the code within the gcc testsuite.  */
  411.  
  412.   memset (exc->private_, 0, sizeof (exc->private_));
  413.   exc->private_[0] = (_Unwind_Ptr) stop;
  414.   exc->private_[4] = (_Unwind_Ptr) stop_argument;
  415.  
  416.   return _Unwind_ForcedUnwind_Phase2 (exc);
  417. }
  418.  
  419. /* A convenience function that calls the exception_cleanup field.  */
  420.  
  421. void
  422. _Unwind_DeleteException (struct _Unwind_Exception *exc)
  423. {
  424.   if (exc->exception_cleanup)
  425.     (*exc->exception_cleanup) (_URC_FOREIGN_EXCEPTION_CAUGHT, exc);
  426. }
  427.  
  428. /* Perform stack backtrace through unwind data.  */
  429.  
  430. _Unwind_Reason_Code
  431. _Unwind_Backtrace(_Unwind_Trace_Fn trace,
  432.                   void *trace_argument)
  433. {
  434.   UNWIND_HISTORY_TABLE ms_history;
  435.   CONTEXT ms_context;
  436.   struct _Unwind_Context gcc_context;
  437.   DISPATCHER_CONTEXT disp_context;
  438.  
  439.   memset (&ms_history, 0, sizeof(ms_history));
  440.   memset (&gcc_context, 0, sizeof(gcc_context));
  441.   memset (&disp_context, 0, sizeof(disp_context));
  442.  
  443.   ms_context.ContextFlags = CONTEXT_ALL;
  444.   RtlCaptureContext (&ms_context);
  445.  
  446.   gcc_context.disp = &disp_context;
  447.   gcc_context.disp->ContextRecord = &ms_context;
  448.   gcc_context.disp->HistoryTable = &ms_history;
  449.  
  450.   while (1)
  451.     {
  452.       gcc_context.disp->ControlPc = ms_context.Rip;
  453.       gcc_context.disp->FunctionEntry
  454.         = RtlLookupFunctionEntry (ms_context.Rip, &gcc_context.disp->ImageBase,
  455.                                   &ms_history);
  456.  
  457.       if (!gcc_context.disp->FunctionEntry)
  458.         return _URC_END_OF_STACK;
  459.  
  460.       gcc_context.disp->LanguageHandler
  461.         = RtlVirtualUnwind (0, gcc_context.disp->ImageBase, ms_context.Rip,
  462.                             gcc_context.disp->FunctionEntry, &ms_context,
  463.                             &gcc_context.disp->HandlerData,
  464.                             &gcc_context.disp->EstablisherFrame, NULL);
  465.  
  466.       /* Call trace function.  */
  467.       if (trace (&gcc_context, trace_argument) != _URC_NO_REASON)
  468.         return _URC_FATAL_PHASE1_ERROR;
  469.  
  470.       /* ??? Check for invalid stack pointer.  */
  471.       if (ms_context.Rip == 0)
  472.         return _URC_END_OF_STACK;
  473.     }
  474. }
  475. #endif /* __SEH__  && !defined (__USING_SJLJ_EXCEPTIONS__)  */
  476.