Sync with trunk head.
[reactos.git] / dll / win32 / kernel32 / except / except.c
1 /* $Id$
2 *
3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS system libraries
5 * FILE: lib/kernel32/misc/except.c
6 * PURPOSE: Exception functions
7 * PROGRAMMER: Ariadne ( ariadne@xs4all.nl)
8 * modified from WINE [ Onno Hovers, (onno@stack.urc.tue.nl) ]
9 * UPDATE HISTORY:
10 * Created 01/11/98
11 */
12
13 #include <k32.h>
14
15 #define NDEBUG
16 #include <debug.h>
17
18 LPTOP_LEVEL_EXCEPTION_FILTER GlobalTopLevelExceptionFilter = NULL;
19
20 UINT
21 WINAPI
22 GetErrorMode(VOID)
23 {
24 NTSTATUS Status;
25 UINT ErrMode;
26
27 /* Query the current setting */
28 Status = NtQueryInformationProcess(NtCurrentProcess(),
29 ProcessDefaultHardErrorMode,
30 (PVOID)&ErrMode,
31 sizeof(ErrMode),
32 NULL);
33 if (!NT_SUCCESS(Status))
34 {
35 /* Fail if we couldn't query */
36 SetLastErrorByStatus(Status);
37 return 0;
38 }
39
40 /* Check if NOT failing critical errors was requested */
41 if (ErrMode & SEM_FAILCRITICALERRORS)
42 {
43 /* Mask it out, since the native API works differently */
44 ErrMode &= ~SEM_FAILCRITICALERRORS;
45 }
46 else
47 {
48 /* OR it if the caller didn't, due to different native semantics */
49 ErrMode |= SEM_FAILCRITICALERRORS;
50 }
51
52 /* Return the mode */
53 return ErrMode;
54 }
55
56 /*
57 * @implemented
58 */
59 UINT
60 WINAPI
61 SetErrorMode(IN UINT uMode)
62 {
63 UINT PrevErrMode, NewMode;
64 NTSTATUS Status;
65
66 /* Get the previous mode */
67 PrevErrMode = GetErrorMode();
68 NewMode = uMode;
69
70 /* Check if failing critical errors was requested */
71 if (NewMode & SEM_FAILCRITICALERRORS)
72 {
73 /* Mask it out, since the native API works differently */
74 NewMode &= ~SEM_FAILCRITICALERRORS;
75 }
76 else
77 {
78 /* OR it if the caller didn't, due to different native semantics */
79 NewMode |= SEM_FAILCRITICALERRORS;
80 }
81
82 /* Set the new mode */
83 Status = NtSetInformationProcess(NtCurrentProcess(),
84 ProcessDefaultHardErrorMode,
85 (PVOID)&NewMode,
86 sizeof(NewMode));
87 if(!NT_SUCCESS(Status)) SetLastErrorByStatus(Status);
88
89 /* Return the previous mode */
90 return PrevErrMode;
91 }
92
93 /*
94 * @implemented
95 */
96 LPTOP_LEVEL_EXCEPTION_FILTER
97 WINAPI
98 SetUnhandledExceptionFilter(
99 IN LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter)
100 {
101 return InterlockedExchangePointer(&GlobalTopLevelExceptionFilter,
102 lpTopLevelExceptionFilter);
103 }
104
105 /*
106 * Private helper function to lookup the module name from a given address.
107 * The address can point to anywhere within the module.
108 */
109 static const char*
110 _module_name_from_addr(const void* addr, void **module_start_addr,
111 char* psz, size_t nChars)
112 {
113 MEMORY_BASIC_INFORMATION mbi;
114 if (VirtualQuery(addr, &mbi, sizeof(mbi)) != sizeof(mbi) ||
115 !GetModuleFileNameA((HMODULE)mbi.AllocationBase, psz, nChars))
116 {
117 psz[0] = '\0';
118 *module_start_addr = 0;
119 }
120 else
121 {
122 *module_start_addr = (void *)mbi.AllocationBase;
123 }
124 return psz;
125 }
126
127 #ifdef _M_IX86
128 static VOID
129 _dump_context(PCONTEXT pc)
130 {
131 /*
132 * Print out the CPU registers
133 */
134 DbgPrint("CS:EIP %x:%x\n", pc->SegCs&0xffff, pc->Eip );
135 DbgPrint("DS %x ES %x FS %x GS %x\n", pc->SegDs&0xffff, pc->SegEs&0xffff,
136 pc->SegFs&0xffff, pc->SegGs&0xfff);
137 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", pc->Eax, pc->Ebx, pc->Ecx);
138 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x ESP: %.8x\n", pc->Edx,
139 pc->Ebp, pc->Esi, pc->Esp);
140 DbgPrint("EDI: %.8x EFLAGS: %.8x\n", pc->Edi, pc->EFlags);
141 }
142 #else
143 #warning Unknown architecture
144 static VOID
145 _dump_context(PCONTEXT pc)
146 {
147 }
148 #endif
149
150 static LONG
151 BasepCheckForReadOnlyResource(IN PVOID Ptr)
152 {
153 PVOID Data;
154 ULONG Size, OldProtect;
155 MEMORY_BASIC_INFORMATION mbi;
156 NTSTATUS Status;
157 LONG Ret = EXCEPTION_CONTINUE_SEARCH;
158
159 /* Check if it was an attempt to write to a read-only image section! */
160 Status = NtQueryVirtualMemory(NtCurrentProcess(),
161 Ptr,
162 MemoryBasicInformation,
163 &mbi,
164 sizeof(mbi),
165 NULL);
166 if (NT_SUCCESS(Status) &&
167 mbi.Protect == PAGE_READONLY && mbi.Type == MEM_IMAGE)
168 {
169 /* Attempt to treat it as a resource section. We need to
170 use SEH here because we don't know if it's actually a
171 resource mapping */
172
173 _SEH2_TRY
174 {
175 Data = RtlImageDirectoryEntryToData(mbi.AllocationBase,
176 TRUE,
177 IMAGE_DIRECTORY_ENTRY_RESOURCE,
178 &Size);
179
180 if (Data != NULL &&
181 (ULONG_PTR)Ptr >= (ULONG_PTR)Data &&
182 (ULONG_PTR)Ptr < (ULONG_PTR)Data + Size)
183 {
184 /* The user tried to write into the resources. Make the page
185 writable... */
186 Size = 1;
187 Status = NtProtectVirtualMemory(NtCurrentProcess(),
188 &Ptr,
189 &Size,
190 PAGE_READWRITE,
191 &OldProtect);
192 if (NT_SUCCESS(Status))
193 {
194 Ret = EXCEPTION_CONTINUE_EXECUTION;
195 }
196 }
197 }
198 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
199 {
200 }
201 _SEH2_END;
202 }
203
204 return Ret;
205 }
206
207 static VOID
208 PrintStackTrace(struct _EXCEPTION_POINTERS *ExceptionInfo)
209 {
210 PVOID StartAddr;
211 CHAR szMod[128] = "";
212 PEXCEPTION_RECORD ExceptionRecord = ExceptionInfo->ExceptionRecord;
213 PCONTEXT ContextRecord = ExceptionInfo->ContextRecord;
214
215 /* Print a stack trace. */
216 DbgPrint("Unhandled exception\n");
217 DbgPrint("ExceptionCode: %8x\n", ExceptionRecord->ExceptionCode);
218
219 if ((NTSTATUS)ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
220 ExceptionRecord->NumberParameters == 2)
221 {
222 DbgPrint("Faulting Address: %8x\n", ExceptionRecord->ExceptionInformation[1]);
223 }
224
225 _dump_context (ContextRecord);
226 _module_name_from_addr(ExceptionRecord->ExceptionAddress, &StartAddr, szMod, sizeof(szMod));
227 DbgPrint("Address:\n %8x+%-8x %s\n",
228 (PVOID)StartAddr,
229 (ULONG_PTR)ExceptionRecord->ExceptionAddress - (ULONG_PTR)StartAddr,
230 szMod);
231 #ifdef _M_IX86
232 DbgPrint("Frames:\n");
233
234 _SEH2_TRY
235 {
236 UINT i;
237 PULONG Frame = (PULONG)ContextRecord->Ebp;
238
239 for (i = 0; Frame[1] != 0 && Frame[1] != 0xdeadbeef && i < 128; i++)
240 {
241 if (IsBadReadPtr((PVOID)Frame[1], 4))
242 {
243 DbgPrint(" %8x%9s %s\n", Frame[1], "<invalid address>"," ");
244 }
245 else
246 {
247 _module_name_from_addr((const void*)Frame[1], &StartAddr,
248 szMod, sizeof(szMod));
249 DbgPrint(" %8x+%-8x %s\n",
250 (PVOID)StartAddr,
251 (ULONG_PTR)Frame[1] - (ULONG_PTR)StartAddr,
252 szMod);
253 }
254
255 if (IsBadReadPtr((PVOID)Frame[0], sizeof(*Frame) * 2))
256 break;
257
258 Frame = (PULONG)Frame[0];
259 }
260 }
261 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
262 {
263 DbgPrint("<error dumping stack trace: 0x%x>\n", _SEH2_GetExceptionCode());
264 }
265 _SEH2_END;
266 #endif
267 }
268
269 /*
270 * @implemented
271 */
272 LONG WINAPI
273 UnhandledExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)
274 {
275 LONG RetValue;
276 HANDLE DebugPort = NULL;
277 NTSTATUS ErrCode;
278 ULONG ErrorParameters[4];
279 ULONG ErrorResponse;
280 PEXCEPTION_RECORD ExceptionRecord = ExceptionInfo->ExceptionRecord;
281
282 if ((NTSTATUS)ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
283 ExceptionRecord->NumberParameters >= 2)
284 {
285 switch(ExceptionRecord->ExceptionInformation[0])
286 {
287 case EXCEPTION_WRITE_FAULT:
288 /* Change the protection on some write attempts, some InstallShield setups
289 have this bug */
290 RetValue = BasepCheckForReadOnlyResource(
291 (PVOID)ExceptionRecord->ExceptionInformation[1]);
292 if (RetValue == EXCEPTION_CONTINUE_EXECUTION)
293 return EXCEPTION_CONTINUE_EXECUTION;
294 break;
295 case EXCEPTION_EXECUTE_FAULT:
296 /* FIXME */
297 break;
298 }
299 }
300
301 /* Is there a debugger running ? */
302 ErrCode = NtQueryInformationProcess(NtCurrentProcess(), ProcessDebugPort,
303 &DebugPort, sizeof(HANDLE), NULL);
304 if (!NT_SUCCESS(ErrCode) && ErrCode != STATUS_NOT_IMPLEMENTED)
305 {
306 SetLastErrorByStatus(ErrCode);
307 return EXCEPTION_EXECUTE_HANDLER;
308 }
309
310 if (DebugPort)
311 {
312 /* Pass the exception to debugger. */
313 DPRINT("Passing exception to debugger\n");
314 return EXCEPTION_CONTINUE_SEARCH;
315 }
316
317 if (GlobalTopLevelExceptionFilter)
318 {
319 LONG ret = GlobalTopLevelExceptionFilter(ExceptionInfo);
320 if (ret != EXCEPTION_CONTINUE_SEARCH)
321 return ret;
322 }
323
324 if ((GetErrorMode() & SEM_NOGPFAULTERRORBOX) == 0)
325 PrintStackTrace(ExceptionInfo);
326
327 /* Save exception code and address */
328 ErrorParameters[0] = (ULONG)ExceptionRecord->ExceptionCode;
329 ErrorParameters[1] = (ULONG)ExceptionRecord->ExceptionAddress;
330
331 if ((NTSTATUS)ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION)
332 {
333 /* get the type of operation that caused the access violation */
334 ErrorParameters[2] = ExceptionRecord->ExceptionInformation[0];
335 }
336 else
337 {
338 ErrorParameters[2] = ExceptionRecord->ExceptionInformation[2];
339 }
340
341 /* Save faulting address */
342 ErrorParameters[3] = ExceptionRecord->ExceptionInformation[1];
343
344 /* Raise the harderror */
345 ErrCode = NtRaiseHardError(STATUS_UNHANDLED_EXCEPTION | 0x10000000,
346 4, 0, ErrorParameters, OptionOkCancel, &ErrorResponse);
347
348 if (NT_SUCCESS(ErrCode) && (ErrorResponse == ResponseCancel))
349 {
350 /* FIXME: Check the result, if the "Cancel" button was
351 clicked run a debugger */
352 DPRINT1("Debugging is not implemented yet\n");
353 }
354
355 /*
356 * Returning EXCEPTION_EXECUTE_HANDLER means that the code in
357 * the __except block will be executed. Normally this will end up in a
358 * Terminate process.
359 */
360
361 return EXCEPTION_EXECUTE_HANDLER;
362 }
363
364 /*
365 * @implemented
366 */
367 VOID
368 WINAPI
369 RaiseException(IN DWORD dwExceptionCode,
370 IN DWORD dwExceptionFlags,
371 IN DWORD nNumberOfArguments,
372 IN CONST ULONG_PTR *lpArguments OPTIONAL)
373 {
374 EXCEPTION_RECORD ExceptionRecord;
375
376 /* Setup the exception record */
377 ExceptionRecord.ExceptionCode = dwExceptionCode;
378 ExceptionRecord.ExceptionRecord = NULL;
379 ExceptionRecord.ExceptionAddress = (PVOID)RaiseException;
380 ExceptionRecord.ExceptionFlags = dwExceptionFlags & EXCEPTION_NONCONTINUABLE;
381
382 /* Check if we have arguments */
383 if (!lpArguments)
384 {
385 /* We don't */
386 ExceptionRecord.NumberParameters = 0;
387 }
388 else
389 {
390 /* We do, normalize the count */
391 if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS)
392 {
393 nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS;
394 }
395
396 /* Set the count of parameters */
397 ExceptionRecord.NumberParameters = nNumberOfArguments;
398
399 /* Loop each parameter */
400 for (nNumberOfArguments = 0;
401 (nNumberOfArguments < ExceptionRecord.NumberParameters);
402 nNumberOfArguments ++)
403 {
404 /* Copy the exception information */
405 ExceptionRecord.ExceptionInformation[nNumberOfArguments] =
406 *lpArguments++;
407 }
408 }
409
410 if (dwExceptionCode == 0xeedface)
411 {
412 DPRINT1("Delphi Exception at address: %p\n", ExceptionRecord.ExceptionInformation[0]);
413 DPRINT1("Exception-Object: %p\n", ExceptionRecord.ExceptionInformation[1]);
414 DPRINT1("Exception text: %s\n", ExceptionRecord.ExceptionInformation[2]);
415 }
416
417 /* Trace the wine special error and show the modulename and functionname */
418 if (dwExceptionCode == 0x80000100 /*EXCEPTION_WINE_STUB*/)
419 {
420 /* Numbers of parameter must be equal to two */
421 if (ExceptionRecord.NumberParameters == 2)
422 {
423 DPRINT1("Missing function in : %s\n", ExceptionRecord.ExceptionInformation[0]);
424 DPRINT1("with the functionname : %s\n", ExceptionRecord.ExceptionInformation[1]);
425 }
426 }
427
428 /* Raise the exception */
429 RtlRaiseException(&ExceptionRecord);
430 }
431
432 /* EOF */