Add missing cast.
[wine/dibdrv.git] / win32 / except.c
blobd10783523d0b45dc20fbba3b5605e9468d888620
1 /*
2 * Win32 exception functions
4 * Copyright (c) 1996 Onno Hovers, (onno@stack.urc.tue.nl)
5 * Copyright (c) 1999 Alexandre Julliard
7 * Notes:
8 * What really happens behind the scenes of those new
9 * __try{...}__except(..){....} and
10 * __try{...}__finally{...}
11 * statements is simply not documented by Microsoft. There could be different
12 * reasons for this:
13 * One reason could be that they try to hide the fact that exception
14 * handling in Win32 looks almost the same as in OS/2 2.x.
15 * Another reason could be that Microsoft does not want others to write
16 * binary compatible implementations of the Win32 API (like us).
18 * Whatever the reason, THIS SUCKS!! Ensuring portability or future
19 * compatibility may be valid reasons to keep some things undocumented.
20 * But exception handling is so basic to Win32 that it should be
21 * documented!
25 #include <stdio.h>
26 #include "windef.h"
27 #include "winerror.h"
28 #include "ntddk.h"
29 #include "wingdi.h"
30 #include "winuser.h"
31 #include "wine/exception.h"
32 #include "thread.h"
33 #include "stackframe.h"
34 #include "wine/server.h"
35 #include "debugtools.h"
37 DEFAULT_DEBUG_CHANNEL(seh);
39 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
41 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
42 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
44 /*******************************************************************
45 * RaiseException (KERNEL32.@)
47 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
49 EXCEPTION_RECORD record;
51 /* Compose an exception record */
53 record.ExceptionCode = code;
54 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
55 record.ExceptionRecord = NULL;
56 record.ExceptionAddress = RaiseException;
57 if (nbargs && args)
59 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
60 record.NumberParameters = nbargs;
61 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
63 else record.NumberParameters = 0;
65 RtlRaiseException( &record );
69 /*******************************************************************
70 * format_exception_msg
72 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
74 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
75 int len,len2;
77 switch(rec->ExceptionCode)
79 case EXCEPTION_INT_DIVIDE_BY_ZERO:
80 len = snprintf( buffer, size, "Unhandled division by zero" );
81 break;
82 case EXCEPTION_INT_OVERFLOW:
83 len = snprintf( buffer, size, "Unhandled overflow" );
84 break;
85 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
86 len = snprintf( buffer, size, "Unhandled array bounds" );
87 break;
88 case EXCEPTION_ILLEGAL_INSTRUCTION:
89 len = snprintf( buffer, size, "Unhandled illegal instruction" );
90 break;
91 case EXCEPTION_STACK_OVERFLOW:
92 len = snprintf( buffer, size, "Unhandled stack overflow" );
93 break;
94 case EXCEPTION_PRIV_INSTRUCTION:
95 len = snprintf( buffer, size, "Unhandled privileged instruction" );
96 break;
97 case EXCEPTION_ACCESS_VIOLATION:
98 if (rec->NumberParameters == 2)
99 len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
100 rec->ExceptionInformation[0] ? "write" : "read",
101 rec->ExceptionInformation[1]);
102 else
103 len = snprintf( buffer, size, "Unhandled page fault");
104 break;
105 case EXCEPTION_DATATYPE_MISALIGNMENT:
106 len = snprintf( buffer, size, "Unhandled alignment" );
107 break;
108 case CONTROL_C_EXIT:
109 len = snprintf( buffer, size, "Unhandled ^C");
110 break;
111 case EXCEPTION_CRITICAL_SECTION_WAIT:
112 len = snprintf( buffer, size, "Critical section %08lx wait failed",
113 rec->ExceptionInformation[0]);
114 break;
115 case EXCEPTION_WINE_STUB:
116 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
117 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
118 break;
119 case EXCEPTION_VM86_INTx:
120 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
121 rec->ExceptionInformation[0]);
122 break;
123 case EXCEPTION_VM86_STI:
124 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
125 break;
126 case EXCEPTION_VM86_PICRETURN:
127 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
128 break;
129 default:
130 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
131 break;
133 if ((len<0) || (len>=size))
134 return -1;
135 #ifdef __i386__
136 if (ptr->ContextRecord->SegCs != __get_cs())
137 len2 = snprintf(buffer+len, size-len,
138 " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
139 ptr->ContextRecord->SegCs,
140 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
141 else
142 #endif
143 len2 = snprintf(buffer+len, size-len,
144 " at address 0x%08lx.\nDo you wish to debug it ?",
145 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
146 if ((len2<0) || (len>=size-len))
147 return -1;
148 return len+len2;
152 /**********************************************************************
153 * send_debug_event
155 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
157 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
159 int ret;
160 HANDLE handle = 0;
162 SERVER_START_REQ( queue_exception_event )
164 req->first = first_chance;
165 wine_server_add_data( req, context, sizeof(*context) );
166 wine_server_add_data( req, rec, sizeof(*rec) );
167 if (!wine_server_call(req)) handle = reply->handle;
169 SERVER_END_REQ;
170 if (!handle) return 0; /* no debugger present or other error */
172 /* No need to wait on the handle since the process gets suspended
173 * once the event is passed to the debugger, so when we get back
174 * here the event has been continued already.
176 SERVER_START_REQ( get_exception_status )
178 req->handle = handle;
179 wine_server_set_reply( req, context, sizeof(*context) );
180 wine_server_call( req );
181 ret = reply->status;
183 SERVER_END_REQ;
184 NtClose( handle );
185 return ret;
188 /******************************************************************
189 * start_debugger
191 * Does the effective debugger startup according to 'format'
193 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
195 HKEY hDbgConf;
196 DWORD bAuto = FALSE;
197 PROCESS_INFORMATION info;
198 STARTUPINFOA startup;
199 char* cmdline = NULL;
200 char* format = NULL;
201 DWORD format_size;
202 BOOL ret = FALSE;
204 MESSAGE("wine: Unhandled exception, starting debugger...\n");
206 if (!RegOpenKeyA(HKEY_LOCAL_MACHINE,
207 "Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", &hDbgConf)) {
208 DWORD type;
209 DWORD count;
211 format_size = 0;
212 if (!RegQueryValueExA(hDbgConf, "Debugger", 0, &type, NULL, &format_size)) {
213 format = HeapAlloc(GetProcessHeap(), 0, format_size);
214 RegQueryValueExA(hDbgConf, "Debugger", 0, &type, format, &format_size);
215 if (type==REG_EXPAND_SZ) {
216 char* tmp;
218 /* Expand environment variable references */
219 format_size=ExpandEnvironmentStringsA(format,NULL,0);
220 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
221 ExpandEnvironmentStringsA(format,tmp,format_size);
222 HeapFree(GetProcessHeap(), 0, format);
223 format=tmp;
227 count = sizeof(bAuto);
228 if (RegQueryValueExA(hDbgConf, "Auto", 0, &type, (char*)&bAuto, &count))
229 bAuto = TRUE;
230 else if (type == REG_SZ)
232 char autostr[10];
233 count = sizeof(autostr);
234 if (!RegQueryValueExA(hDbgConf, "Auto", 0, &type, autostr, &count))
235 bAuto = atoi(autostr);
237 RegCloseKey(hDbgConf);
238 } else {
239 /* try a default setup... */
240 strcpy( format, "winedbg --debugmsg -all -- --auto %ld %ld" );
243 if (!bAuto)
245 HMODULE mod = GetModuleHandleA( "user32.dll" );
246 MessageBoxA_funcptr pMessageBoxA = NULL;
248 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
249 if (pMessageBoxA)
251 char buffer[256];
252 format_exception_msg( epointers, buffer, sizeof(buffer) );
253 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
255 TRACE("Killing process\n");
256 goto EXIT;
261 if (format) {
262 TRACE("Starting debugger (fmt=%s)\n", format);
263 cmdline=HeapAlloc(GetProcessHeap(), 0, format_size+2*20);
264 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
265 memset(&startup, 0, sizeof(startup));
266 startup.cb = sizeof(startup);
267 startup.dwFlags = STARTF_USESHOWWINDOW;
268 startup.wShowWindow = SW_SHOWNORMAL;
269 if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &info)) {
270 /* wait for debugger to come up... */
271 WaitForSingleObject(hEvent, INFINITE);
272 ret = TRUE;
273 goto EXIT;
275 } else {
276 cmdline = NULL;
278 ERR("Couldn't start debugger (%s) (%ld)\n"
279 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
280 debugstr_a(cmdline), GetLastError());
282 EXIT:
283 if (cmdline)
284 HeapFree(GetProcessHeap(), 0, cmdline);
285 if (format)
286 HeapFree(GetProcessHeap(), 0, format);
287 return ret;
290 /******************************************************************
291 * start_debugger_atomic
293 * starts the debugger in an atomic way:
294 * - either the debugger is not started and it is started
295 * - or the debugger has already been started by another thread
296 * - or the debugger couldn't be started
298 * returns TRUE for the two first conditions, FALSE for the last
300 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
302 static HANDLE hRunOnce /* = 0 */;
304 if (hRunOnce == 0)
306 OBJECT_ATTRIBUTES attr;
307 HANDLE hEvent;
309 attr.Length = sizeof(attr);
310 attr.RootDirectory = 0;
311 attr.Attributes = OBJ_INHERIT;
312 attr.ObjectName = NULL;
313 attr.SecurityDescriptor = NULL;
314 attr.SecurityQualityOfService = NULL;
316 /* ask for manual reset, so that once the debugger is started,
317 * every thread will know it */
318 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
319 if (InterlockedCompareExchange( (LPLONG)&hRunOnce, hEvent, 0 ) == 0)
321 /* ok, our event has been set... we're the winning thread */
322 BOOL ret = start_debugger( epointers, hRunOnce );
323 DWORD tmp;
325 if (!ret)
327 /* so that the other threads won't be stuck */
328 NtSetEvent( hRunOnce, &tmp );
330 return ret;
333 /* someone beat us here... */
334 CloseHandle( hEvent );
337 /* and wait for the winner to have actually created the debugger */
338 WaitForSingleObject( hRunOnce, INFINITE );
339 /* in fact, here, we only know that someone has tried to start the debugger,
340 * we'll know by reposting the exception if it has actually attached
341 * to the current process */
342 return TRUE;
346 /*******************************************************************
347 * UnhandledExceptionFilter (KERNEL32.@)
349 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
351 int status;
352 int loop = 0;
354 for (loop = 0; loop <= 1; loop++)
356 /* send a last chance event to the debugger */
357 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
358 switch (status)
360 case DBG_CONTINUE:
361 return EXCEPTION_CONTINUE_EXECUTION;
362 case DBG_EXCEPTION_NOT_HANDLED:
363 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
364 break; /* not reached */
365 case 0: /* no debugger is present */
366 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
368 /* do not launch the debugger on ^C, simply terminate the process */
369 TerminateProcess( GetCurrentProcess(), 1 );
371 /* second try, the debugger isn't present... */
372 if (loop == 1) return EXCEPTION_EXECUTE_HANDLER;
373 break;
374 default:
375 FIXME("Unsupported yet debug continue value %d (please report)\n", status);
376 return EXCEPTION_EXECUTE_HANDLER;
379 /* should only be there when loop == 0 */
381 if (top_filter)
383 DWORD ret = top_filter( epointers );
384 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
387 /* FIXME: Should check the current error mode */
389 if (!start_debugger_atomic( epointers ))
390 return EXCEPTION_EXECUTE_HANDLER;
391 /* now that we should have a debugger attached, try to resend event */
394 return EXCEPTION_EXECUTE_HANDLER;
398 /***********************************************************************
399 * SetUnhandledExceptionFilter (KERNEL32.@)
401 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
402 LPTOP_LEVEL_EXCEPTION_FILTER filter )
404 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
405 top_filter = filter;
406 return old;
410 /**************************************************************************
411 * FatalAppExitA (KERNEL32.@)
413 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
415 HMODULE mod = GetModuleHandleA( "user32.dll" );
416 MessageBoxA_funcptr pMessageBoxA = NULL;
418 WARN("AppExit\n");
420 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
421 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
422 else ERR( "%s\n", debugstr_a(str) );
423 ExitProcess(0);
427 /**************************************************************************
428 * FatalAppExitW (KERNEL32.@)
430 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
432 HMODULE mod = GetModuleHandleA( "user32.dll" );
433 MessageBoxW_funcptr pMessageBoxW = NULL;
435 WARN("AppExit\n");
437 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
438 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
439 else ERR( "%s\n", debugstr_w(str) );
440 ExitProcess(0);