Stub implementation for MsiGetFileHashA/W.
[wine] / dlls / kernel / except.c
1 /*
2  * Win32 exception functions
3  *
4  * Copyright (c) 1996 Onno Hovers, (onno@stack.urc.tue.nl)
5  * Copyright (c) 1999 Alexandre Julliard
6  *
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.
11  *
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.
16  *
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
20  *
21  * Notes:
22  *  What really happens behind the scenes of those new
23  *  __try{...}__except(..){....}  and
24  *  __try{...}__finally{...}
25  *  statements is simply not documented by Microsoft. There could be different
26  *  reasons for this:
27  *  One reason could be that they try to hide the fact that exception
28  *  handling in Win32 looks almost the same as in OS/2 2.x.
29  *  Another reason could be that Microsoft does not want others to write
30  *  binary compatible implementations of the Win32 API (like us).
31  *
32  *  Whatever the reason, THIS SUCKS!! Ensuring portability or future
33  *  compatibility may be valid reasons to keep some things undocumented.
34  *  But exception handling is so basic to Win32 that it should be
35  *  documented!
36  *
37  */
38 #include "config.h"
39 #include "wine/port.h"
40
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include "ntstatus.h"
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winerror.h"
47 #include "winternl.h"
48 #include "wingdi.h"
49 #include "winuser.h"
50 #include "wine/exception.h"
51 #include "wine/library.h"
52 #include "excpt.h"
53 #include "wine/server.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
56
57 WINE_DEFAULT_DEBUG_CHANNEL(seh);
58
59 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
60
61 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
62 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
63
64 /*******************************************************************
65  *         RaiseException  (KERNEL32.@)
66  */
67 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const ULONG_PTR *args )
68 {
69     EXCEPTION_RECORD record;
70
71     /* Compose an exception record */
72
73     record.ExceptionCode    = code;
74     record.ExceptionFlags   = flags & EH_NONCONTINUABLE;
75     record.ExceptionRecord  = NULL;
76     record.ExceptionAddress = RaiseException;
77     if (nbargs && args)
78     {
79         if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
80         record.NumberParameters = nbargs;
81         memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
82     }
83     else record.NumberParameters = 0;
84
85     RtlRaiseException( &record );
86 }
87
88
89 /*******************************************************************
90  *         format_exception_msg
91  */
92 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
93 {
94     const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
95     int len,len2;
96
97     switch(rec->ExceptionCode)
98     {
99     case EXCEPTION_INT_DIVIDE_BY_ZERO:
100         len = snprintf( buffer, size, "Unhandled division by zero" );
101         break;
102     case EXCEPTION_INT_OVERFLOW:
103         len = snprintf( buffer, size, "Unhandled overflow" );
104         break;
105     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
106         len = snprintf( buffer, size, "Unhandled array bounds" );
107         break;
108     case EXCEPTION_ILLEGAL_INSTRUCTION:
109         len = snprintf( buffer, size, "Unhandled illegal instruction" );
110         break;
111     case EXCEPTION_STACK_OVERFLOW:
112         len = snprintf( buffer, size, "Unhandled stack overflow" );
113         break;
114     case EXCEPTION_PRIV_INSTRUCTION:
115         len = snprintf( buffer, size, "Unhandled privileged instruction" );
116         break;
117     case EXCEPTION_ACCESS_VIOLATION:
118         if (rec->NumberParameters == 2)
119             len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
120                      rec->ExceptionInformation[0] ? "write" : "read",
121                      rec->ExceptionInformation[1]);
122         else
123             len = snprintf( buffer, size, "Unhandled page fault");
124         break;
125     case EXCEPTION_DATATYPE_MISALIGNMENT:
126         len = snprintf( buffer, size, "Unhandled alignment" );
127         break;
128     case CONTROL_C_EXIT:
129         len = snprintf( buffer, size, "Unhandled ^C");
130         break;
131     case STATUS_POSSIBLE_DEADLOCK:
132         len = snprintf( buffer, size, "Critical section %08lx wait failed",
133                  rec->ExceptionInformation[0]);
134         break;
135     case EXCEPTION_WINE_STUB:
136         if (HIWORD(rec->ExceptionInformation[1]))
137             len = snprintf( buffer, size, "Unimplemented function %s.%s called",
138                             (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
139         else
140             len = snprintf( buffer, size, "Unimplemented function %s.%ld called",
141                             (char *)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
142         break;
143     case EXCEPTION_WINE_ASSERTION:
144         len = snprintf( buffer, size, "Assertion failed" );
145         break;
146     case EXCEPTION_VM86_INTx:
147         len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
148                  rec->ExceptionInformation[0]);
149         break;
150     case EXCEPTION_VM86_STI:
151         len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
152         break;
153     case EXCEPTION_VM86_PICRETURN:
154         len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
155         break;
156     default:
157         len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
158         break;
159     }
160     if ((len<0) || (len>=size))
161         return -1;
162 #ifdef __i386__
163     if (ptr->ContextRecord->SegCs != wine_get_cs())
164         len2 = snprintf(buffer+len, size-len,
165                         " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
166                         ptr->ContextRecord->SegCs,
167                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
168     else
169 #endif
170         len2 = snprintf(buffer+len, size-len,
171                         " at address %p.\nDo you wish to debug it ?",
172                         ptr->ExceptionRecord->ExceptionAddress);
173     if ((len2<0) || (len>=size-len))
174         return -1;
175     return len+len2;
176 }
177
178
179 /**********************************************************************
180  *           send_debug_event
181  *
182  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
183  */
184 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
185 {
186     NTSTATUS ret;
187     HANDLE handle = 0;
188
189     SERVER_START_REQ( queue_exception_event )
190     {
191         req->first   = first_chance;
192         wine_server_add_data( req, context, sizeof(*context) );
193         wine_server_add_data( req, rec, sizeof(*rec) );
194         if (!(ret = wine_server_call( req ))) handle = reply->handle;
195     }
196     SERVER_END_REQ;
197     if (ret) return ret;
198
199     WaitForSingleObject( handle, INFINITE );
200
201     SERVER_START_REQ( get_exception_status )
202     {
203         req->handle = handle;
204         wine_server_set_reply( req, context, sizeof(*context) );
205         ret = wine_server_call( req );
206     }
207     SERVER_END_REQ;
208     return ret;
209 }
210
211 /******************************************************************
212  *              start_debugger
213  *
214  * Does the effective debugger startup according to 'format'
215  */
216 static BOOL     start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
217 {
218     OBJECT_ATTRIBUTES attr;
219     UNICODE_STRING nameW;
220     char *cmdline, *env, *p;
221     HANDLE              hDbgConf;
222     DWORD               bAuto = FALSE;
223     PROCESS_INFORMATION info;
224     STARTUPINFOA        startup;
225     char*               format = NULL;
226     BOOL                ret = FALSE;
227
228     static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
229                                      'S','o','f','t','w','a','r','e','\\',
230                                      'M','i','c','r','o','s','o','f','t','\\',
231                                      'W','i','n','d','o','w','s',' ','N','T','\\',
232                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
233                                      'A','e','D','e','b','u','g',0};
234     static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
235     static const WCHAR AutoW[] = {'A','u','t','o',0};
236
237     MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
238
239     attr.Length = sizeof(attr);
240     attr.RootDirectory = 0;
241     attr.ObjectName = &nameW;
242     attr.Attributes = 0;
243     attr.SecurityDescriptor = NULL;
244     attr.SecurityQualityOfService = NULL;
245     RtlInitUnicodeString( &nameW, AeDebugW );
246
247     if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
248     {
249         char buffer[64];
250         KEY_VALUE_PARTIAL_INFORMATION *info;
251         DWORD format_size = 0;
252
253         RtlInitUnicodeString( &nameW, DebuggerW );
254         if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
255                              NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
256         {
257             char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
258             NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
259                              data, format_size, &format_size );
260             info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
261             RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
262             format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
263             RtlUnicodeToMultiByteN( format, format_size, NULL,
264                                     (WCHAR *)info->Data, info->DataLength );
265             format[format_size] = 0;
266
267             if (info->Type == REG_EXPAND_SZ)
268             {
269                 char* tmp;
270
271                 /* Expand environment variable references */
272                 format_size=ExpandEnvironmentStringsA(format,NULL,0);
273                 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
274                 ExpandEnvironmentStringsA(format,tmp,format_size);
275                 HeapFree(GetProcessHeap(), 0, format);
276                 format=tmp;
277             }
278             HeapFree( GetProcessHeap(), 0, data );
279         }
280
281         RtlInitUnicodeString( &nameW, AutoW );
282         if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
283                               buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
284        {
285            info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
286            if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
287            else if (info->Type == REG_SZ)
288            {
289                WCHAR *str = (WCHAR *)info->Data;
290                str[info->DataLength/sizeof(WCHAR)] = 0;
291                bAuto = atoiW( str );
292            }
293        }
294        else bAuto = TRUE;
295
296        NtClose(hDbgConf);
297     }
298
299     if (format)
300     {
301         cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
302         sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
303         HeapFree(GetProcessHeap(), 0, format);
304     }
305     else
306     {
307         cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
308         sprintf(cmdline, "winedbg --auto %ld %ld",
309                 GetCurrentProcessId(), (ULONG_PTR)hEvent);
310     }
311
312     if (!bAuto)
313     {
314         HMODULE                 mod = GetModuleHandleA( "user32.dll" );
315         MessageBoxA_funcptr     pMessageBoxA = NULL;
316
317         if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
318         if (pMessageBoxA)
319         {
320             char buffer[256];
321             format_exception_msg( epointers, buffer, sizeof(buffer) );
322             if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
323             {
324                 TRACE("Killing process\n");
325                 goto EXIT;
326             }
327         }
328     }
329
330     /* make WINEDEBUG empty in the environment */
331     env = GetEnvironmentStringsA();
332     for (p = env; *p; p += strlen(p) + 1)
333     {
334         if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
335         {
336             char *next = p + strlen(p);
337             char *end = next + 1;
338             while (*end) end += strlen(end) + 1;
339             memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
340             break;
341         }
342     }
343
344     TRACE("Starting debugger %s\n", debugstr_a(cmdline));
345     memset(&startup, 0, sizeof(startup));
346     startup.cb = sizeof(startup);
347     startup.dwFlags = STARTF_USESHOWWINDOW;
348     startup.wShowWindow = SW_SHOWNORMAL;
349     ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
350     FreeEnvironmentStringsA( env );
351
352     if (ret) WaitForSingleObject(hEvent, INFINITE);  /* wait for debugger to come up... */
353     else ERR("Couldn't start debugger (%s) (%ld)\n"
354              "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
355              debugstr_a(cmdline), GetLastError());
356 EXIT:
357     HeapFree(GetProcessHeap(), 0, cmdline);
358     return ret;
359 }
360
361 /******************************************************************
362  *              start_debugger_atomic
363  *
364  * starts the debugger in an atomic way:
365  *      - either the debugger is not started and it is started
366  *      - or the debugger has already been started by another thread
367  *      - or the debugger couldn't be started
368  *
369  * returns TRUE for the two first conditions, FALSE for the last
370  */
371 static  int     start_debugger_atomic(PEXCEPTION_POINTERS epointers)
372 {
373     static HANDLE       hRunOnce /* = 0 */;
374
375     if (hRunOnce == 0)
376     {
377         OBJECT_ATTRIBUTES       attr;
378         HANDLE                  hEvent;
379
380         attr.Length                   = sizeof(attr);
381         attr.RootDirectory            = 0;
382         attr.Attributes               = OBJ_INHERIT;
383         attr.ObjectName               = NULL;
384         attr.SecurityDescriptor       = NULL;
385         attr.SecurityQualityOfService = NULL;
386
387         /* ask for manual reset, so that once the debugger is started,
388          * every thread will know it */
389         NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
390         if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
391         {
392             /* ok, our event has been set... we're the winning thread */
393             BOOL        ret = start_debugger( epointers, hRunOnce );
394             DWORD       tmp;
395
396             if (!ret)
397             {
398                 /* so that the other threads won't be stuck */
399                 NtSetEvent( hRunOnce, &tmp );
400             }
401             return ret;
402         }
403
404         /* someone beat us here... */
405         CloseHandle( hEvent );
406     }
407
408     /* and wait for the winner to have actually created the debugger */
409     WaitForSingleObject( hRunOnce, INFINITE );
410     /* in fact, here, we only know that someone has tried to start the debugger,
411      * we'll know by reposting the exception if it has actually attached
412      * to the current process */
413     return TRUE;
414 }
415
416
417 /*******************************************************************
418  *         check_resource_write
419  *
420  * Check if the exception is a write attempt to the resource data.
421  * If yes, we unprotect the resources to let broken apps continue
422  * (Windows does this too).
423  */
424 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
425 {
426     void *addr, *rsrc;
427     DWORD size;
428     MEMORY_BASIC_INFORMATION info;
429
430     if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
431     if (rec->NumberParameters < 2) return FALSE;
432     if (!rec->ExceptionInformation[0]) return FALSE;  /* not a write access */
433     addr = (void *)rec->ExceptionInformation[1];
434     if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
435     if (info.State == MEM_FREE) return FALSE;
436     if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
437                                               IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
438         return FALSE;
439     if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
440     TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
441     VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
442     return TRUE;
443 }
444
445
446 /*******************************************************************
447  *         UnhandledExceptionFilter   (KERNEL32.@)
448  */
449 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
450 {
451     NTSTATUS status;
452
453     if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
454
455     if (!NtCurrentTeb()->Peb->BeingDebugged)
456     {
457         if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
458         {
459             /* do not launch the debugger on ^C, simply terminate the process */
460             TerminateProcess( GetCurrentProcess(), 1 );
461         }
462
463         if (top_filter)
464         {
465             DWORD ret = top_filter( epointers );
466             if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
467         }
468
469         /* FIXME: Should check the current error mode */
470
471         if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
472             return EXCEPTION_EXECUTE_HANDLER;
473     }
474
475     /* send a last chance event to the debugger */
476     status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
477     switch (status)
478     {
479     case DBG_CONTINUE:
480         return EXCEPTION_CONTINUE_EXECUTION;
481     case DBG_EXCEPTION_NOT_HANDLED:
482         TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
483         break; /* not reached */
484     default:
485         FIXME("Unhandled error on debug event: %lx\n", status);
486         break;
487     }
488     return EXCEPTION_EXECUTE_HANDLER;
489 }
490
491
492 /***********************************************************************
493  *            SetUnhandledExceptionFilter   (KERNEL32.@)
494  */
495 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
496                                           LPTOP_LEVEL_EXCEPTION_FILTER filter )
497 {
498     LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
499     top_filter = filter;
500     return old;
501 }
502
503
504 /**************************************************************************
505  *           FatalAppExitA   (KERNEL32.@)
506  */
507 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
508 {
509     HMODULE mod = GetModuleHandleA( "user32.dll" );
510     MessageBoxA_funcptr pMessageBoxA = NULL;
511
512     WARN("AppExit\n");
513
514     if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
515     if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
516     else ERR( "%s\n", debugstr_a(str) );
517     ExitProcess(0);
518 }
519
520
521 /**************************************************************************
522  *           FatalAppExitW   (KERNEL32.@)
523  */
524 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
525 {
526     static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
527
528     HMODULE mod = GetModuleHandleW( User32DllW );
529     MessageBoxW_funcptr pMessageBoxW = NULL;
530
531     WARN("AppExit\n");
532
533     if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
534     if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
535     else ERR( "%s\n", debugstr_w(str) );
536     ExitProcess(0);
537 }
538
539
540 /**************************************************************************
541  *           FatalExit   (KERNEL32.@)
542  */
543 void WINAPI FatalExit(int ExitCode)
544 {
545     WARN("FatalExit\n");
546     ExitProcess(ExitCode);
547 }