Merge trunk head (r43756)
[reactos.git] / reactos / 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
128 static VOID
129 _dump_context(PCONTEXT pc)
130 {
131 #ifdef _M_IX86
132 /*
133 * Print out the CPU registers
134 */
135 DbgPrint("CS:EIP %x:%x\n", pc->SegCs&0xffff, pc->Eip );
136 DbgPrint("DS %x ES %x FS %x GS %x\n", pc->SegDs&0xffff, pc->SegEs&0xffff,
137 pc->SegFs&0xffff, pc->SegGs&0xfff);
138 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", pc->Eax, pc->Ebx, pc->Ecx);
139 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x ESP: %.8x\n", pc->Edx,
140 pc->Ebp, pc->Esi, pc->Esp);
141 DbgPrint("EDI: %.8x EFLAGS: %.8x\n", pc->Edi, pc->EFlags);
142 #elif defined(_M_AMD64)
143 DbgPrint("CS:EIP %x:%I64x\n", pc->SegCs&0xffff, pc->Rip );
144 DbgPrint("DS %x ES %x FS %x GS %x\n", pc->SegDs&0xffff, pc->SegEs&0xffff,
145 pc->SegFs&0xffff, pc->SegGs&0xfff);
146 DbgPrint("RAX: %I64x RBX: %I64x RCX: %I64x RDI: %I64x\n", pc->Rax, pc->Rbx, pc->Rcx, pc->Rdi);
147 DbgPrint("RDX: %I64x RBP: %I64x RSI: %I64x RSP: %I64x\n", pc->Rdx, pc->Rbp, pc->Rsi, pc->Rsp);
148 DbgPrint("R8: %I64x R9: %I64x R10: %I64x R11: %I64x\n", pc->R8, pc->R9, pc->R10, pc->R11);
149 DbgPrint("R12: %I64x R13: %I64x R14: %I64x R15: %I64x\n", pc->R12, pc->R13, pc->R14, pc->R15);
150 DbgPrint("EFLAGS: %.8x\n", pc->EFlags);
151 #else
152 #warning Unknown architecture
153 #endif
154 }
155
156 static LONG
157 BasepCheckForReadOnlyResource(IN PVOID Ptr)
158 {
159 PVOID Data;
160 ULONG Size, OldProtect;
161 MEMORY_BASIC_INFORMATION mbi;
162 NTSTATUS Status;
163 LONG Ret = EXCEPTION_CONTINUE_SEARCH;
164
165 /* Check if it was an attempt to write to a read-only image section! */
166 Status = NtQueryVirtualMemory(NtCurrentProcess(),
167 Ptr,
168 MemoryBasicInformation,
169 &mbi,
170 sizeof(mbi),
171 NULL);
172 if (NT_SUCCESS(Status) &&
173 mbi.Protect == PAGE_READONLY && mbi.Type == MEM_IMAGE)
174 {
175 /* Attempt to treat it as a resource section. We need to
176 use SEH here because we don't know if it's actually a
177 resource mapping */
178
179 _SEH2_TRY
180 {
181 Data = RtlImageDirectoryEntryToData(mbi.AllocationBase,
182 TRUE,
183 IMAGE_DIRECTORY_ENTRY_RESOURCE,
184 &Size);
185
186 if (Data != NULL &&
187 (ULONG_PTR)Ptr >= (ULONG_PTR)Data &&
188 (ULONG_PTR)Ptr < (ULONG_PTR)Data + Size)
189 {
190 /* The user tried to write into the resources. Make the page
191 writable... */
192 Size = 1;
193 Status = NtProtectVirtualMemory(NtCurrentProcess(),
194 &Ptr,
195 &Size,
196 PAGE_READWRITE,
197 &OldProtect);
198 if (NT_SUCCESS(Status))
199 {
200 Ret = EXCEPTION_CONTINUE_EXECUTION;
201 }
202 }
203 }
204 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
205 {
206 }
207 _SEH2_END;
208 }
209
210 return Ret;
211 }
212
213 /*
214 * @unimplemented
215 */
216 LONG WINAPI
217 UnhandledExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)
218 {
219 LONG RetValue;
220 HANDLE DebugPort = NULL;
221 NTSTATUS ErrCode;
222 ULONG_PTR ErrorParameters[4];
223 ULONG ErrorResponse;
224
225 if ((NTSTATUS)ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
226 ExceptionInfo->ExceptionRecord->NumberParameters >= 2)
227 {
228 switch(ExceptionInfo->ExceptionRecord->ExceptionInformation[0])
229 {
230 case EXCEPTION_WRITE_FAULT:
231 /* Change the protection on some write attempts, some InstallShield setups
232 have this bug */
233 RetValue = BasepCheckForReadOnlyResource(
234 (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
235 if (RetValue == EXCEPTION_CONTINUE_EXECUTION)
236 return EXCEPTION_CONTINUE_EXECUTION;
237 break;
238 case EXCEPTION_EXECUTE_FAULT:
239 /* FIXME */
240 break;
241 }
242 }
243
244 /* Is there a debugger running ? */
245 ErrCode = NtQueryInformationProcess(NtCurrentProcess(), ProcessDebugPort,
246 &DebugPort, sizeof(HANDLE), NULL);
247 if (!NT_SUCCESS(ErrCode) && ErrCode != STATUS_NOT_IMPLEMENTED)
248 {
249 SetLastErrorByStatus(ErrCode);
250 return EXCEPTION_EXECUTE_HANDLER;
251 }
252
253 if (DebugPort)
254 {
255 /* Pass the exception to debugger. */
256 DPRINT("Passing exception to debugger\n");
257 return EXCEPTION_CONTINUE_SEARCH;
258 }
259
260 if (GlobalTopLevelExceptionFilter)
261 {
262 LONG ret = GlobalTopLevelExceptionFilter( ExceptionInfo );
263 if (ret != EXCEPTION_CONTINUE_SEARCH)
264 return ret;
265 }
266
267 if ((GetErrorMode() & SEM_NOGPFAULTERRORBOX) == 0)
268 {
269 #ifdef __i386__
270 PULONG Frame;
271 #endif
272 PVOID StartAddr;
273 CHAR szMod[128] = "";
274
275 /* Print a stack trace. */
276 DbgPrint("Unhandled exception\n");
277 DbgPrint("ExceptionCode: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionCode);
278 if ((NTSTATUS)ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
279 ExceptionInfo->ExceptionRecord->NumberParameters == 2)
280 {
281 DbgPrint("Faulting Address: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
282 }
283 DbgPrint("Address: %8x %s\n",
284 ExceptionInfo->ExceptionRecord->ExceptionAddress,
285 _module_name_from_addr(ExceptionInfo->ExceptionRecord->ExceptionAddress, &StartAddr, szMod, sizeof(szMod)));
286 _dump_context ( ExceptionInfo->ContextRecord );
287 #ifdef __i386__
288 DbgPrint("Frames:\n");
289 _SEH2_TRY
290 {
291 Frame = (PULONG)ExceptionInfo->ContextRecord->Ebp;
292 while (Frame[1] != 0 && Frame[1] != 0xdeadbeef)
293 {
294 if (IsBadReadPtr((PVOID)Frame[1], 4)) {
295 DbgPrint(" %8x%9s %s\n", Frame[1], "<invalid address>"," ");
296 } else {
297 _module_name_from_addr((const void*)Frame[1], &StartAddr,
298 szMod, sizeof(szMod));
299 DbgPrint(" %8x+%-8x %s\n",
300 (PVOID)StartAddr,
301 (ULONG_PTR)Frame[1] - (ULONG_PTR)StartAddr, szMod);
302 }
303 if (IsBadReadPtr((PVOID)Frame[0], sizeof(*Frame) * 2)) {
304 break;
305 }
306 Frame = (PULONG)Frame[0];
307 }
308 }
309 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
310 {
311 DbgPrint("<error dumping stack trace: 0x%x>\n", _SEH2_GetExceptionCode());
312 }
313 _SEH2_END;
314 #endif
315 }
316
317 /* Save exception code and address */
318 ErrorParameters[0] = (ULONG)ExceptionInfo->ExceptionRecord->ExceptionCode;
319 ErrorParameters[1] = (ULONG_PTR)ExceptionInfo->ExceptionRecord->ExceptionAddress;
320
321 if ((NTSTATUS)ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION)
322 {
323 /* get the type of operation that caused the access violation */
324 ErrorParameters[2] = ExceptionInfo->ExceptionRecord->ExceptionInformation[0];
325 }
326 else
327 {
328 ErrorParameters[2] = ExceptionInfo->ExceptionRecord->ExceptionInformation[2];
329 }
330
331 /* Save faulting address */
332 ErrorParameters[3] = ExceptionInfo->ExceptionRecord->ExceptionInformation[1];
333
334 /* Raise the harderror */
335 ErrCode = NtRaiseHardError(STATUS_UNHANDLED_EXCEPTION | 0x10000000,
336 4, 0, ErrorParameters, OptionOkCancel, &ErrorResponse);
337
338 if (NT_SUCCESS(ErrCode) && (ErrorResponse == ResponseCancel))
339 {
340 /* FIXME: Check the result, if the "Cancel" button was
341 clicked run a debugger */
342 DPRINT1("Debugging is not implemented yet\n");
343 }
344
345 /*
346 * Returning EXCEPTION_EXECUTE_HANDLER means that the code in
347 * the __except block will be executed. Normally this will end up in a
348 * Terminate process.
349 */
350
351 return EXCEPTION_EXECUTE_HANDLER;
352 }
353
354 /*
355 * @implemented
356 */
357 VOID
358 WINAPI
359 RaiseException(IN DWORD dwExceptionCode,
360 IN DWORD dwExceptionFlags,
361 IN DWORD nNumberOfArguments,
362 IN CONST ULONG_PTR *lpArguments OPTIONAL)
363 {
364 EXCEPTION_RECORD ExceptionRecord;
365
366 /* Setup the exception record */
367 ExceptionRecord.ExceptionCode = dwExceptionCode;
368 ExceptionRecord.ExceptionRecord = NULL;
369 ExceptionRecord.ExceptionAddress = (PVOID)RaiseException;
370 ExceptionRecord.ExceptionFlags = dwExceptionFlags & EXCEPTION_NONCONTINUABLE;
371
372 /* Check if we have arguments */
373 if (!lpArguments)
374 {
375 /* We don't */
376 ExceptionRecord.NumberParameters = 0;
377 }
378 else
379 {
380 /* We do, normalize the count */
381 if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS)
382 {
383 nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS;
384 }
385
386 /* Set the count of parameters */
387 ExceptionRecord.NumberParameters = nNumberOfArguments;
388
389 /* Loop each parameter */
390 for (nNumberOfArguments = 0;
391 (nNumberOfArguments < ExceptionRecord.NumberParameters);
392 nNumberOfArguments ++)
393 {
394 /* Copy the exception information */
395 ExceptionRecord.ExceptionInformation[nNumberOfArguments] =
396 *lpArguments++;
397 }
398 }
399
400 if (dwExceptionCode == 0xeedface)
401 {
402 DPRINT1("Delphi Exception at address: %p\n", ExceptionRecord.ExceptionInformation[0]);
403 DPRINT1("Exception-Object: %p\n", ExceptionRecord.ExceptionInformation[1]);
404 DPRINT1("Exception text: %s\n", ExceptionRecord.ExceptionInformation[2]);
405 }
406
407 /* Trace the wine special error and show the modulename and functionname */
408 if (dwExceptionCode == 0x80000100 /*EXCEPTION_WINE_STUB*/)
409 {
410 /* Numbers of parameter must be equal to two */
411 if (ExceptionRecord.NumberParameters == 2)
412 {
413 DPRINT1("Missing function in : %s\n", ExceptionRecord.ExceptionInformation[0]);
414 DPRINT1("with the functionname : %s\n", ExceptionRecord.ExceptionInformation[1]);
415 }
416 }
417
418 /* Raise the exception */
419 RtlRaiseException(&ExceptionRecord);
420 }
421
422 /* EOF */