Define GET_IP for x86_64.
[wine/dcerpc.git] / dlls / ntdll / exception.c
blobcd7cc6f790a445774e1f126c3953a4e12da450b3
1 /*
2 * NT exception handling routines
4 * Copyright 1999 Turchanov Sergey
5 * Copyright 1999 Alexandre Julliard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <signal.h>
27 #include <stdarg.h>
29 #include "ntstatus.h"
30 #include "windef.h"
31 #include "winternl.h"
32 #include "wine/exception.h"
33 #include "wine/server.h"
34 #include "wine/list.h"
35 #include "wine/debug.h"
36 #include "excpt.h"
37 #include "ntdll_misc.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(seh);
41 /* Exception record for handling exceptions happening inside exception handlers */
42 typedef struct
44 EXCEPTION_REGISTRATION_RECORD frame;
45 EXCEPTION_REGISTRATION_RECORD *prevFrame;
46 } EXC_NESTED_FRAME;
48 typedef struct
50 struct list entry;
51 PVECTORED_EXCEPTION_HANDLER func;
52 } VECTORED_HANDLER;
54 static struct list vectored_handlers = LIST_INIT(vectored_handlers);
56 static RTL_CRITICAL_SECTION vectored_handlers_section;
57 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
59 0, 0, &vectored_handlers_section,
60 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
61 0, 0, { 0, (DWORD)(__FILE__ ": vectored_handlers_section") }
63 static RTL_CRITICAL_SECTION vectored_handlers_section = { &critsect_debug, -1, 0, 0, 0, 0 };
65 #ifdef __i386__
66 # define GET_IP(context) ((LPVOID)(context)->Eip)
67 #elif defined(__sparc__)
68 # define GET_IP(context) ((LPVOID)(context)->pc)
69 #elif defined(__powerpc__)
70 # define GET_IP(context) ((LPVOID)(context)->Iar)
71 #elif defined(__ALPHA__)
72 # define GET_IP(context) ((LPVOID)(context)->Fir)
73 #elif defined(__x86_64__)
74 # define GET_IP(context) ((LPVOID)(context)->Rip)
75 #else
76 # error You must define GET_IP for this CPU
77 #endif
80 /*******************************************************************
81 * EXC_RaiseHandler
83 * Handler for exceptions happening inside a handler.
85 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
86 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
88 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
89 return ExceptionContinueSearch;
90 /* We shouldn't get here so we store faulty frame in dispatcher */
91 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
92 return ExceptionNestedException;
96 /*******************************************************************
97 * EXC_UnwindHandler
99 * Handler for exceptions happening inside an unwind handler.
101 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
102 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
104 if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
105 return ExceptionContinueSearch;
106 /* We shouldn't get here so we store faulty frame in dispatcher */
107 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
108 return ExceptionCollidedUnwind;
112 /*******************************************************************
113 * EXC_CallHandler
115 * Call an exception handler, setting up an exception frame to catch exceptions
116 * happening during the handler execution.
117 * Please do not change the first 4 parameters order in any way - some exceptions handlers
118 * rely on Base Pointer (EBP) to have a fixed position related to the exception frame
120 static DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
121 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
122 PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler)
124 EXC_NESTED_FRAME newframe;
125 DWORD ret;
127 newframe.frame.Handler = nested_handler;
128 newframe.prevFrame = frame;
129 __wine_push_frame( &newframe.frame );
130 TRACE( "calling handler at %p code=%lx flags=%lx\n",
131 handler, record->ExceptionCode, record->ExceptionFlags );
132 ret = handler( record, frame, context, dispatcher );
133 TRACE( "handler returned %lx\n", ret );
134 __wine_pop_frame( &newframe.frame );
135 return ret;
139 /**********************************************************************
140 * send_debug_event
142 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
144 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
146 int ret;
147 HANDLE handle = 0;
149 if (!NtCurrentTeb()->Peb->BeingDebugged) return 0; /* no debugger present */
151 SERVER_START_REQ( queue_exception_event )
153 req->first = first_chance;
154 wine_server_add_data( req, context, sizeof(*context) );
155 wine_server_add_data( req, rec, sizeof(*rec) );
156 if (!wine_server_call( req )) handle = reply->handle;
158 SERVER_END_REQ;
159 if (!handle) return 0;
161 /* No need to wait on the handle since the process gets suspended
162 * once the event is passed to the debugger, so when we get back
163 * here the event has been continued already.
165 SERVER_START_REQ( get_exception_status )
167 req->handle = handle;
168 wine_server_set_reply( req, context, sizeof(*context) );
169 wine_server_call( req );
170 ret = reply->status;
172 SERVER_END_REQ;
173 NtClose( handle );
174 return ret;
178 /**********************************************************************
179 * call_vectored_handlers
181 * Call the vectored handlers chain.
183 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
185 struct list *ptr;
186 LONG ret = EXCEPTION_CONTINUE_SEARCH;
187 EXCEPTION_POINTERS except_ptrs;
189 except_ptrs.ExceptionRecord = rec;
190 except_ptrs.ContextRecord = context;
192 RtlEnterCriticalSection( &vectored_handlers_section );
193 LIST_FOR_EACH( ptr, &vectored_handlers )
195 VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
196 ret = handler->func( &except_ptrs );
197 if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
199 RtlLeaveCriticalSection( &vectored_handlers_section );
200 return ret;
204 /*******************************************************************
205 * EXC_DefaultHandling
207 * Default handling for exceptions. Called when we didn't find a suitable handler.
209 static void EXC_DefaultHandling( EXCEPTION_RECORD *rec, CONTEXT *context )
211 if (send_debug_event( rec, FALSE, context ) == DBG_CONTINUE) return; /* continue execution */
213 if (rec->ExceptionFlags & EH_STACK_INVALID)
214 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
215 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
216 ERR("Process attempted to continue execution after noncontinuable exception.\n");
217 else
218 ERR("Unhandled exception code %lx flags %lx addr %p\n",
219 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
220 NtTerminateProcess( NtCurrentProcess(), 1 );
224 /***********************************************************************
225 * RtlRaiseException (NTDLL.@)
227 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
229 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
230 EXCEPTION_RECORD newrec;
231 DWORD res, c;
233 TRACE( "code=%lx flags=%lx addr=%p\n", rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
234 for (c=0; c<rec->NumberParameters; c++) TRACE(" info[%ld]=%08lx\n", c, rec->ExceptionInformation[c]);
235 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
237 if (HIWORD(rec->ExceptionInformation[1]))
238 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
239 rec->ExceptionAddress,
240 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
241 else
242 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
243 rec->ExceptionAddress,
244 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
246 #ifdef __i386__
247 else
249 TRACE(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
250 context->Eax, context->Ebx, context->Ecx,
251 context->Edx, context->Esi, context->Edi );
252 TRACE(" ebp=%08lx esp=%08lx cs=%04lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
253 context->Ebp, context->Esp, context->SegCs, context->SegDs,
254 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
256 #endif
258 if (send_debug_event( rec, TRUE, context ) == DBG_CONTINUE) return; /* continue execution */
260 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION) return;
262 frame = NtCurrentTeb()->Tib.ExceptionList;
263 nested_frame = NULL;
264 while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
266 /* Check frame address */
267 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
268 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
269 (ULONG_PTR)frame & 3)
271 rec->ExceptionFlags |= EH_STACK_INVALID;
272 break;
275 /* Call handler */
276 res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
277 if (frame == nested_frame)
279 /* no longer nested */
280 nested_frame = NULL;
281 rec->ExceptionFlags &= ~EH_NESTED_CALL;
284 switch(res)
286 case ExceptionContinueExecution:
287 if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return;
288 newrec.ExceptionCode = STATUS_NONCONTINUABLE_EXCEPTION;
289 newrec.ExceptionFlags = EH_NONCONTINUABLE;
290 newrec.ExceptionRecord = rec;
291 newrec.NumberParameters = 0;
292 RtlRaiseException( &newrec ); /* never returns */
293 break;
294 case ExceptionContinueSearch:
295 break;
296 case ExceptionNestedException:
297 if (nested_frame < dispatch) nested_frame = dispatch;
298 rec->ExceptionFlags |= EH_NESTED_CALL;
299 break;
300 default:
301 newrec.ExceptionCode = STATUS_INVALID_DISPOSITION;
302 newrec.ExceptionFlags = EH_NONCONTINUABLE;
303 newrec.ExceptionRecord = rec;
304 newrec.NumberParameters = 0;
305 RtlRaiseException( &newrec ); /* never returns */
306 break;
308 frame = frame->Prev;
310 EXC_DefaultHandling( rec, context );
313 /**********************************************************************/
315 #ifdef DEFINE_REGS_ENTRYPOINT
316 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 4, 4 );
317 #else
318 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
320 CONTEXT context;
321 memset( &context, 0, sizeof(context) );
322 __regs_RtlRaiseException( rec, &context );
324 #endif
327 /*******************************************************************
328 * RtlUnwind (NTDLL.@)
330 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
331 PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
333 EXCEPTION_RECORD record, newrec;
334 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
336 #ifdef __i386__
337 context->Eax = (DWORD)returnEax;
338 #endif
340 /* build an exception record, if we do not have one */
341 if (!pRecord)
343 record.ExceptionCode = STATUS_UNWIND;
344 record.ExceptionFlags = 0;
345 record.ExceptionRecord = NULL;
346 record.ExceptionAddress = GET_IP(context);
347 record.NumberParameters = 0;
348 pRecord = &record;
351 pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
353 TRACE( "code=%lx flags=%lx\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
355 /* get chain of exception frames */
356 frame = NtCurrentTeb()->Tib.ExceptionList;
357 while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
359 /* Check frame address */
360 if (pEndFrame && (frame > pEndFrame))
362 newrec.ExceptionCode = STATUS_INVALID_UNWIND_TARGET;
363 newrec.ExceptionFlags = EH_NONCONTINUABLE;
364 newrec.ExceptionRecord = pRecord;
365 newrec.NumberParameters = 0;
366 RtlRaiseException( &newrec ); /* never returns */
368 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
369 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
370 (int)frame & 3)
372 newrec.ExceptionCode = STATUS_BAD_STACK;
373 newrec.ExceptionFlags = EH_NONCONTINUABLE;
374 newrec.ExceptionRecord = pRecord;
375 newrec.NumberParameters = 0;
376 RtlRaiseException( &newrec ); /* never returns */
379 /* Call handler */
380 switch(EXC_CallHandler( pRecord, frame, context, &dispatch,
381 frame->Handler, EXC_UnwindHandler ))
383 case ExceptionContinueSearch:
384 break;
385 case ExceptionCollidedUnwind:
386 frame = dispatch;
387 break;
388 default:
389 newrec.ExceptionCode = STATUS_INVALID_DISPOSITION;
390 newrec.ExceptionFlags = EH_NONCONTINUABLE;
391 newrec.ExceptionRecord = pRecord;
392 newrec.NumberParameters = 0;
393 RtlRaiseException( &newrec ); /* never returns */
394 break;
396 frame = __wine_pop_frame( frame );
400 /**********************************************************************/
402 #ifdef DEFINE_REGS_ENTRYPOINT
403 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 16, 16 );
404 #else
405 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
406 PEXCEPTION_RECORD pRecord, PVOID returnEax )
408 CONTEXT context;
409 memset( &context, 0, sizeof(context) );
410 __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
412 #endif
415 /*******************************************************************
416 * NtRaiseException (NTDLL.@)
418 void WINAPI __regs_NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx,
419 BOOL first, CONTEXT *context )
421 __regs_RtlRaiseException( rec, ctx );
422 *context = *ctx;
425 #ifdef DEFINE_REGS_ENTRYPOINT
426 DEFINE_REGS_ENTRYPOINT( NtRaiseException, 12, 12 );
427 #else
428 void WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx, BOOL first )
430 CONTEXT context;
431 memset( &context, 0, sizeof(context) );
432 __regs_NtRaiseException( rec, ctx, first, &context );
434 #endif
437 /***********************************************************************
438 * RtlRaiseStatus (NTDLL.@)
440 * Raise an exception with ExceptionCode = status
442 void WINAPI RtlRaiseStatus( NTSTATUS status )
444 EXCEPTION_RECORD ExceptionRec;
446 ExceptionRec.ExceptionCode = status;
447 ExceptionRec.ExceptionFlags = EH_NONCONTINUABLE;
448 ExceptionRec.ExceptionRecord = NULL;
449 ExceptionRec.NumberParameters = 0;
450 RtlRaiseException( &ExceptionRec );
454 /*******************************************************************
455 * RtlAddVectoredExceptionHandler (NTDLL.@)
457 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
459 VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
460 if (handler)
462 handler->func = func;
463 RtlEnterCriticalSection( &vectored_handlers_section );
464 if (first) list_add_head( &vectored_handlers, &handler->entry );
465 else list_add_tail( &vectored_handlers, &handler->entry );
466 RtlLeaveCriticalSection( &vectored_handlers_section );
468 return handler;
472 /*******************************************************************
473 * RtlRemoveVectoredExceptionHandler (NTDLL.@)
475 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
477 struct list *ptr;
478 ULONG ret = FALSE;
480 RtlEnterCriticalSection( &vectored_handlers_section );
481 LIST_FOR_EACH( ptr, &vectored_handlers )
483 VECTORED_HANDLER *curr_handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
484 if (curr_handler == handler)
486 list_remove( ptr );
487 ret = TRUE;
488 break;
491 RtlLeaveCriticalSection( &vectored_handlers_section );
492 if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
493 return ret;
497 /*************************************************************
498 * __wine_exception_handler (NTDLL.@)
500 * Exception handler for exception blocks declared in Wine code.
502 DWORD __wine_exception_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
503 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
505 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
507 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))
508 return ExceptionContinueSearch;
509 if (wine_frame->u.filter)
511 EXCEPTION_POINTERS ptrs;
512 ptrs.ExceptionRecord = record;
513 ptrs.ContextRecord = context;
514 switch(wine_frame->u.filter( &ptrs ))
516 case EXCEPTION_CONTINUE_SEARCH:
517 return ExceptionContinueSearch;
518 case EXCEPTION_CONTINUE_EXECUTION:
519 return ExceptionContinueExecution;
520 case EXCEPTION_EXECUTE_HANDLER:
521 break;
522 default:
523 MESSAGE( "Invalid return value from exception filter\n" );
524 assert( FALSE );
527 /* hack to make GetExceptionCode() work in handler */
528 wine_frame->ExceptionCode = record->ExceptionCode;
529 wine_frame->ExceptionRecord = wine_frame;
531 RtlUnwind( frame, 0, record, 0 );
532 __wine_pop_frame( frame );
533 siglongjmp( wine_frame->jmp, 1 );
537 /*************************************************************
538 * __wine_finally_handler (NTDLL.@)
540 * Exception handler for try/finally blocks declared in Wine code.
542 DWORD __wine_finally_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
543 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
545 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
547 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
548 wine_frame->u.finally_func( FALSE );
550 return ExceptionContinueSearch;
554 /*************************************************************
555 * __wine_spec_unimplemented_stub
557 * ntdll-specific implementation to avoid depending on kernel functions.
558 * Can be removed once ntdll.spec no longer contains stubs.
560 void __wine_spec_unimplemented_stub( const char *module, const char *function )
562 EXCEPTION_RECORD record;
564 record.ExceptionCode = EXCEPTION_WINE_STUB;
565 record.ExceptionFlags = EH_NONCONTINUABLE;
566 record.ExceptionRecord = NULL;
567 record.ExceptionAddress = __wine_spec_unimplemented_stub;
568 record.NumberParameters = 2;
569 record.ExceptionInformation[0] = (ULONG_PTR)module;
570 record.ExceptionInformation[1] = (ULONG_PTR)function;
571 RtlRaiseException( &record );