unwind-seh.c 15 KB

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