forked from Alexpux/Cygwin
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathexceptions.cc
2104 lines (1886 loc) · 59.7 KB
/
exceptions.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* exceptions.cc
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#define CYGTLS_HANDLE
#include "winsup.h"
#include "miscfuncs.h"
#include <imagehlp.h>
#include <stdlib.h>
#include <stdarg.h>
#include <syslog.h>
#include <wchar.h>
#include "cygtls.h"
#include "pinfo.h"
#include "sigproc.h"
#include "shared_info.h"
#include "perprocess.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "child_info.h"
#include "ntdll.h"
#include "exception.h"
#include "cygwin/exit_process.h"
/* Definitions for code simplification */
#ifdef __x86_64__
# define _GR(reg) R ## reg
# define _AFMT "%011X"
# define _ADDR DWORD64
#else
# define _GR(reg) E ## reg
# define _AFMT "%08x"
# define _ADDR DWORD
#endif
#define CALL_HANDLER_RETRY_OUTER 10
#define CALL_HANDLER_RETRY_INNER 10
PWCHAR debugger_command;
extern uint8_t _sigbe;
extern uint8_t _sigdelayed_end;
static BOOL WINAPI ctrl_c_handler (DWORD);
static const struct
{
NTSTATUS code;
const char *name;
} status_info[] =
{
#define X(s) s, #s
{ X (STATUS_ABANDONED_WAIT_0) },
{ X (STATUS_ACCESS_VIOLATION) },
{ X (STATUS_ARRAY_BOUNDS_EXCEEDED) },
{ X (STATUS_BREAKPOINT) },
{ X (STATUS_CONTROL_C_EXIT) },
{ X (STATUS_DATATYPE_MISALIGNMENT) },
{ X (STATUS_FLOAT_DENORMAL_OPERAND) },
{ X (STATUS_FLOAT_DIVIDE_BY_ZERO) },
{ X (STATUS_FLOAT_INEXACT_RESULT) },
{ X (STATUS_FLOAT_INVALID_OPERATION) },
{ X (STATUS_FLOAT_OVERFLOW) },
{ X (STATUS_FLOAT_STACK_CHECK) },
{ X (STATUS_FLOAT_UNDERFLOW) },
{ X (STATUS_GUARD_PAGE_VIOLATION) },
{ X (STATUS_ILLEGAL_INSTRUCTION) },
{ X (STATUS_INTEGER_DIVIDE_BY_ZERO) },
{ X (STATUS_INTEGER_OVERFLOW) },
{ X (STATUS_INVALID_DISPOSITION) },
{ X (STATUS_IN_PAGE_ERROR) },
{ X (STATUS_NONCONTINUABLE_EXCEPTION) },
{ X (STATUS_NO_MEMORY) },
{ X (STATUS_PENDING) },
{ X (STATUS_PRIVILEGED_INSTRUCTION) },
{ X (STATUS_SINGLE_STEP) },
{ X (STATUS_STACK_OVERFLOW) },
{ X (STATUS_TIMEOUT) },
{ X (STATUS_USER_APC) },
{ X (STATUS_WAIT_0) },
{ 0, 0 }
#undef X
};
/* Initialization code. */
void
init_console_handler (bool install_handler)
{
BOOL res;
SetConsoleCtrlHandler (ctrl_c_handler, FALSE);
SetConsoleCtrlHandler (NULL, FALSE);
if (install_handler)
res = SetConsoleCtrlHandler (ctrl_c_handler, TRUE);
else
res = SetConsoleCtrlHandler (NULL, TRUE);
if (!res)
system_printf ("SetConsoleCtrlHandler failed, %E");
}
extern "C" void
error_start_init (const char *buf)
{
if (!buf || !*buf)
return;
if (!debugger_command &&
!(debugger_command = (PWCHAR) malloc ((2 * NT_MAX_PATH + 20)
* sizeof (WCHAR))))
return;
PWCHAR cp = debugger_command
+ sys_mbstowcs (debugger_command, NT_MAX_PATH, buf) - 1;
cp = wcpcpy (cp, L" \"");
wcpcpy (cp, global_progname);
for (PWCHAR p = wcschr (cp, L'\\'); p; p = wcschr (p, L'\\'))
*p = L'/';
wcscat (cp, L"\"");
}
void
cygwin_exception::open_stackdumpfile ()
{
/* If we have no executable name, or if the CWD handle is NULL,
which means, the CWD is a virtual path, don't even try to open
a stackdump file. */
if (myself->progname[0] && cygheap->cwd.get_handle ())
{
const WCHAR *p;
/* write to progname.stackdump if possible */
if (!myself->progname[0])
p = L"unknown";
else if ((p = wcsrchr (myself->progname, L'\\')))
p++;
else
p = myself->progname;
WCHAR corefile[wcslen (p) + sizeof (".stackdump")];
wcpcpy (wcpcpy(corefile, p), L".stackdump");
UNICODE_STRING ucore;
OBJECT_ATTRIBUTES attr;
/* Create the UNICODE variation of <progname>.stackdump. */
RtlInitUnicodeString (&ucore, corefile);
/* Create an object attribute which refers to <progname>.stackdump
in Cygwin's cwd. Stick to caseinsensitivity. */
InitializeObjectAttributes (&attr, &ucore, OBJ_CASE_INSENSITIVE,
cygheap->cwd.get_handle (), NULL);
IO_STATUS_BLOCK io;
NTSTATUS status;
/* Try to open it to dump the stack in it. */
status = NtCreateFile (&h, GENERIC_WRITE | SYNCHRONIZE, &attr, &io,
NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OVERWRITE_IF,
FILE_SYNCHRONOUS_IO_NONALERT
| FILE_OPEN_FOR_BACKUP_INTENT, NULL, 0);
if (NT_SUCCESS (status))
{
if (!myself->cygstarted)
system_printf ("Dumping stack trace to %S", &ucore);
else
debug_printf ("Dumping stack trace to %S", &ucore);
SetStdHandle (STD_ERROR_HANDLE, h);
}
}
}
/* Utilities for dumping the stack, etc. */
void
cygwin_exception::dump_exception ()
{
const char *exception_name = NULL;
for (int i = 0; status_info[i].name; i++)
{
if (status_info[i].code == (NTSTATUS) e->ExceptionCode)
{
exception_name = status_info[i].name;
break;
}
}
#ifdef __x86_64__
if (exception_name)
small_printf ("Exception: %s at rip=%011X\r\n", exception_name, ctx->Rip);
else
small_printf ("Signal %d at rip=%011X\r\n", e->ExceptionCode, ctx->Rip);
small_printf ("rax=%016X rbx=%016X rcx=%016X\r\n",
ctx->Rax, ctx->Rbx, ctx->Rcx);
small_printf ("rdx=%016X rsi=%016X rdi=%016X\r\n",
ctx->Rdx, ctx->Rsi, ctx->Rdi);
small_printf ("r8 =%016X r9 =%016X r10=%016X\r\n",
ctx->R8, ctx->R9, ctx->R10);
small_printf ("r11=%016X r12=%016X r13=%016X\r\n",
ctx->R11, ctx->R12, ctx->R13);
small_printf ("r14=%016X r15=%016X\r\n", ctx->R14, ctx->R15);
small_printf ("rbp=%016X rsp=%016X\r\n", ctx->Rbp, ctx->Rsp);
small_printf ("program=%W, pid %u, thread %s\r\n",
myself->progname, myself->pid, cygthread::name ());
#else
if (exception_name)
small_printf ("Exception: %s at eip=%08x\r\n", exception_name, ctx->Eip);
else
small_printf ("Signal %d at eip=%08x\r\n", e->ExceptionCode, ctx->Eip);
small_printf ("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\r\n",
ctx->Eax, ctx->Ebx, ctx->Ecx, ctx->Edx, ctx->Esi, ctx->Edi);
small_printf ("ebp=%08x esp=%08x program=%W, pid %u, thread %s\r\n",
ctx->Ebp, ctx->Esp, myself->progname, myself->pid,
cygthread::name ());
#endif
small_printf ("cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x\r\n",
ctx->SegCs, ctx->SegDs, ctx->SegEs, ctx->SegFs,
ctx->SegGs, ctx->SegSs);
}
/* A class for manipulating the stack. */
class stack_info
{
int walk (); /* Uses the "old" method */
char *next_offset () {return *((char **) sf.AddrFrame.Offset);}
bool needargs;
PUINT_PTR dummy_frame;
#ifdef __x86_64__
CONTEXT c;
UNWIND_HISTORY_TABLE hist;
__tlsstack_t *sigstackptr;
#endif
public:
STACKFRAME sf; /* For storing the stack information */
void init (PUINT_PTR, bool, PCONTEXT); /* Called the first time that stack info is needed */
/* Postfix ++ iterates over the stack, returning zero when nothing is left. */
int operator ++(int) { return walk (); }
};
/* The number of parameters used in STACKFRAME */
#define NPARAMS (sizeof (thestack.sf.Params) / sizeof (thestack.sf.Params[0]))
/* This is the main stack frame info for this process. */
static NO_COPY stack_info thestack;
/* Initialize everything needed to start iterating. */
void
stack_info::init (PUINT_PTR framep, bool wantargs, PCONTEXT ctx)
{
#ifdef __x86_64__
memset (&hist, 0, sizeof hist);
if (ctx)
memcpy (&c, ctx, sizeof c);
else
{
memset (&c, 0, sizeof c);
c.ContextFlags = CONTEXT_ALL;
}
sigstackptr = _my_tls.stackptr;
#endif
memset (&sf, 0, sizeof (sf));
if (ctx)
sf.AddrFrame.Offset = (UINT_PTR) framep;
else
{
dummy_frame = framep;
sf.AddrFrame.Offset = (UINT_PTR) &dummy_frame;
}
if (framep)
sf.AddrReturn.Offset = framep[1];
sf.AddrFrame.Mode = AddrModeFlat;
needargs = wantargs;
}
extern "C" void _cygwin_exit_return ();
#ifdef __x86_64__
static inline void
__unwind_single_frame (PCONTEXT ctx)
{
PRUNTIME_FUNCTION f;
ULONG64 imagebase;
UNWIND_HISTORY_TABLE hist;
DWORD64 establisher;
PVOID hdl;
f = RtlLookupFunctionEntry (ctx->Rip, &imagebase, &hist);
if (f)
RtlVirtualUnwind (0, imagebase, ctx->Rip, f, ctx, &hdl, &establisher,
NULL);
else
{
ctx->Rip = *(ULONG_PTR *) ctx->Rsp;
ctx->Rsp += 8;
}
}
#else
#define __unwind_single_frame(ctx)
#endif
/* Walk the stack.
On 32 bit we're doing this by looking at successive stored 'ebp' frames.
This is not foolproof. */
int
stack_info::walk ()
{
#ifdef __x86_64__
if (!c.Rip)
return 0;
sf.AddrPC.Offset = c.Rip;
sf.AddrStack.Offset = c.Rsp;
sf.AddrFrame.Offset = c.Rbp;
if ((c.Rip >= (DWORD64)&_sigbe) && (c.Rip < (DWORD64)&_sigdelayed_end))
{
/* _sigbe and sigdelayed don't have SEH unwinding data, so virtually
unwind the tls sigstack */
c.Rip = sigstackptr[-1];
sigstackptr--;
return 1;
}
__unwind_single_frame (&c);
if (needargs && c.Rip)
{
PULONG_PTR p = (PULONG_PTR) c.Rsp;
for (unsigned i = 0; i < NPARAMS; ++i)
sf.Params[i] = p[i + 1];
}
return 1;
#else
char **framep;
if ((void (*) ()) sf.AddrPC.Offset == _cygwin_exit_return)
return 0; /* stack frames are exhausted */
if (((framep = (char **) next_offset ()) == NULL)
|| (framep >= (char **) cygwin_hmodule))
return 0;
sf.AddrFrame.Offset = (_ADDR) framep;
sf.AddrPC.Offset = sf.AddrReturn.Offset;
/* The return address always follows the stack pointer */
sf.AddrReturn.Offset = (_ADDR) *++framep;
if (needargs)
{
unsigned nparams = NPARAMS;
/* The arguments follow the return address */
sf.Params[0] = (_ADDR) *++framep;
for (unsigned i = 1; i < nparams; i++)
sf.Params[i] = (_ADDR) *++framep;
}
return 1;
#endif
}
void
cygwin_exception::dumpstack ()
{
static bool already_dumped;
__try
{
if (already_dumped || cygheap->rlim_core == 0Ul)
return;
already_dumped = true;
open_stackdumpfile ();
if (e)
dump_exception ();
int i;
thestack.init (framep, 1, ctx); /* Initialize from the input CONTEXT */
#ifdef __x86_64__
small_printf ("Stack trace:\r\nFrame Function Args\r\n");
#else
small_printf ("Stack trace:\r\nFrame Function Args\r\n");
#endif
for (i = 0; i < 16 && thestack++; i++)
{
small_printf (_AFMT " " _AFMT, thestack.sf.AddrFrame.Offset,
thestack.sf.AddrPC.Offset);
for (unsigned j = 0; j < NPARAMS; j++)
small_printf ("%s" _AFMT, j == 0 ? " (" : ", ",
thestack.sf.Params[j]);
small_printf (")\r\n");
}
small_printf ("End of stack trace%s\n",
i == 16 ? " (more stack frames may be present)" : "");
if (h)
NtClose (h);
}
__except (NO_ERROR) {}
__endtry
}
bool
_cygtls::inside_kernel (CONTEXT *cx)
{
int res;
MEMORY_BASIC_INFORMATION m;
if (!isinitialized ())
return true;
memset (&m, 0, sizeof m);
if (!VirtualQuery ((LPCVOID) cx->_GR(ip), &m, sizeof m))
sigproc_printf ("couldn't get memory info, pc %p, %E", cx->_GR(ip));
size_t size = (windows_system_directory_length + 6) * sizeof (WCHAR);
PWCHAR checkdir = (PWCHAR) alloca (size);
memset (checkdir, 0, size);
# define h ((HMODULE) m.AllocationBase)
if (!h || m.State != MEM_COMMIT) /* Be defensive */
res = true;
else if (h == hntdll)
res = true; /* Calling GetModuleFilename on ntdll.dll
can hang */
else if (h == user_data->hmodule)
res = false;
else if (!GetModuleFileNameW (h, checkdir,
windows_system_directory_length + 6))
res = false;
else
{
/* Skip potential long path prefix. */
if (!wcsncmp (checkdir, L"\\\\?\\", 4))
checkdir += 4;
res = wcsncasecmp (windows_system_directory, checkdir,
windows_system_directory_length) == 0;
#ifndef __x86_64__
if (!res && system_wow64_directory_length)
res = wcsncasecmp (system_wow64_directory, checkdir,
system_wow64_directory_length) == 0;
#endif
}
sigproc_printf ("pc %p, h %p, inside_kernel %d", cx->_GR(ip), h, res);
# undef h
return res;
}
/* Temporary (?) function for external callers to get a stack dump */
extern "C" void
cygwin_stackdump ()
{
CONTEXT c;
c.ContextFlags = CONTEXT_FULL;
RtlCaptureContext (&c);
cygwin_exception exc ((PUINT_PTR) c._GR(bp), &c);
exc.dumpstack ();
}
#define TIME_TO_WAIT_FOR_DEBUGGER 10000
extern "C" int
try_to_debug (bool waitloop)
{
if (!debugger_command)
return 0;
debug_printf ("debugger_command '%W'", debugger_command);
if (being_debugged ())
{
extern void break_here ();
break_here ();
return 0;
}
PWCHAR dbg_end = wcschr (debugger_command, L'\0');
__small_swprintf (dbg_end, L" %u", GetCurrentProcessId ());
LONG prio = GetThreadPriority (GetCurrentThread ());
SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);
PROCESS_INFORMATION pi = {NULL, 0, 0, 0};
STARTUPINFOW si = {0, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
NULL, NULL, NULL, NULL};
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.dwFlags = 0;
si.cb = sizeof (si);
/* FIXME: need to know handles of all running threads to
suspend_all_threads_except (current_thread_id);
*/
/* If the tty mutex is owned, we will fail to start any cygwin app
until the trapped app exits. However, this will only release any
the mutex if it is owned by this thread so that may be problematic. */
lock_ttys::release ();
/* prevent recursive exception handling */
PWCHAR rawenv = GetEnvironmentStringsW () ;
for (PWCHAR p = rawenv; *p != L'\0'; p = wcschr (p, L'\0') + 1)
{
if (wcsncmp (p, L"MSYS=", wcslen (L"MSYS=")) == 0)
{
PWCHAR q = wcsstr (p, L"error_start") ;
/* replace 'error_start=...' with '_rror_start=...' */
if (q)
{
*q = L'_' ;
SetEnvironmentVariableW (L"MSYS", p + wcslen (L"MSYS=")) ;
}
break;
}
}
FreeEnvironmentStringsW (rawenv);
console_printf ("*** starting debugger for pid %u, tid %u\n",
cygwin_pid (GetCurrentProcessId ()), GetCurrentThreadId ());
BOOL dbg;
dbg = CreateProcessW (NULL,
debugger_command,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
NULL,
NULL,
&si,
&pi);
*dbg_end = L'\0';
if (!dbg)
system_printf ("Failed to start debugger, %E");
else
{
if (!waitloop)
return dbg;
SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_IDLE);
while (!being_debugged ())
Sleep (1);
Sleep (2000);
}
console_printf ("*** continuing pid %u from debugger call (%d)\n",
cygwin_pid (GetCurrentProcessId ()), dbg);
SetThreadPriority (GetCurrentThread (), prio);
return dbg;
}
#ifdef __x86_64__
/* Don't unwind the stack on x86_64. It's not necessary to do that from the
exception handler. */
#define rtl_unwind(el,er)
#else
static void __reg3 rtl_unwind (exception_list *, PEXCEPTION_RECORD)
__attribute__ ((noinline, regparm (3)));
void __reg3
rtl_unwind (exception_list *frame, PEXCEPTION_RECORD e)
{
__asm__ ("\n\
pushl %%ebx \n\
pushl %%edi \n\
pushl %%esi \n\
pushl $0 \n\
pushl %1 \n\
pushl $1f \n\
pushl %0 \n\
call _RtlUnwind@16 \n\
1: \n\
popl %%esi \n\
popl %%edi \n\
popl %%ebx \n\
": : "r" (frame), "r" (e));
}
#endif /* __x86_64 */
#ifdef __x86_64__
/* myfault exception handler. */
EXCEPTION_DISPOSITION
exception::myfault (EXCEPTION_RECORD *e, exception_list *frame, CONTEXT *in,
PDISPATCHER_CONTEXT dispatch)
{
PSCOPE_TABLE table = (PSCOPE_TABLE) dispatch->HandlerData;
RtlUnwindEx (frame,
(char *) dispatch->ImageBase + table->ScopeRecord[0].JumpTarget,
e, 0, in, dispatch->HistoryTable);
/* NOTREACHED, make gcc happy. */
return ExceptionContinueSearch;
}
/* If another exception occurs while running a signal handler on an alternate
signal stack, the normal SEH handlers are skipped, because the OS exception
handling considers the current (alternate) stack "broken". However, it
still calls vectored exception handlers.
TODO: What we do here is to handle only __try/__except blocks in Cygwin.
"Normal" exceptions will simply exit the process. Still, better
than nothing... */
LONG WINAPI
myfault_altstack_handler (EXCEPTION_POINTERS *exc)
{
_cygtls& me = _my_tls;
if (me.andreas)
{
CONTEXT *c = exc->ContextRecord;
/* Unwind the stack manually and call RtlRestoreContext. This
is necessary because RtlUnwindEx checks the stack for validity,
which, as outlined above, fails for the alternate stack. */
while (c->Rsp < me.andreas->frame)
__unwind_single_frame (c);
c->Rip = me.andreas->ret;
RtlRestoreContext (c, NULL);
}
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
/* Main exception handler. */
EXCEPTION_DISPOSITION
exception::handle (EXCEPTION_RECORD *e, exception_list *frame, CONTEXT *in,
PDISPATCHER_CONTEXT dispatch)
{
static int NO_COPY debugging = 0;
_cygtls& me = _my_tls;
#ifndef __x86_64__
if (me.andreas)
me.andreas->leave (); /* Return from a "san" caught fault */
#endif
if (debugging && ++debugging < 500000)
{
SetThreadPriority (hMainThread, THREAD_PRIORITY_NORMAL);
return ExceptionContinueExecution;
}
/* If we're exiting, tell Windows to keep looking for an
exception handler. */
if (exit_state || e->ExceptionFlags)
return ExceptionContinueSearch;
siginfo_t si = {};
si.si_code = SI_KERNEL;
/* Coerce win32 value to posix value. */
switch (e->ExceptionCode)
{
case STATUS_FLOAT_DENORMAL_OPERAND:
case STATUS_FLOAT_DIVIDE_BY_ZERO:
case STATUS_FLOAT_INVALID_OPERATION:
case STATUS_FLOAT_STACK_CHECK:
si.si_signo = SIGFPE;
si.si_code = FPE_FLTSUB;
break;
case STATUS_FLOAT_INEXACT_RESULT:
si.si_signo = SIGFPE;
si.si_code = FPE_FLTRES;
break;
case STATUS_FLOAT_OVERFLOW:
si.si_signo = SIGFPE;
si.si_code = FPE_FLTOVF;
break;
case STATUS_FLOAT_UNDERFLOW:
si.si_signo = SIGFPE;
si.si_code = FPE_FLTUND;
break;
case STATUS_INTEGER_DIVIDE_BY_ZERO:
si.si_signo = SIGFPE;
si.si_code = FPE_INTDIV;
break;
case STATUS_INTEGER_OVERFLOW:
si.si_signo = SIGFPE;
si.si_code = FPE_INTOVF;
break;
case STATUS_ILLEGAL_INSTRUCTION:
si.si_signo = SIGILL;
si.si_code = ILL_ILLOPC;
break;
case STATUS_PRIVILEGED_INSTRUCTION:
si.si_signo = SIGILL;
si.si_code = ILL_PRVOPC;
break;
case STATUS_NONCONTINUABLE_EXCEPTION:
si.si_signo = SIGILL;
si.si_code = ILL_ILLADR;
break;
case STATUS_TIMEOUT:
si.si_signo = SIGALRM;
break;
case STATUS_GUARD_PAGE_VIOLATION:
si.si_signo = SIGBUS;
si.si_code = BUS_OBJERR;
break;
case STATUS_DATATYPE_MISALIGNMENT:
si.si_signo = SIGBUS;
si.si_code = BUS_ADRALN;
break;
case STATUS_ACCESS_VIOLATION:
switch (mmap_is_attached_or_noreserve ((void *)e->ExceptionInformation[1],
1))
{
case MMAP_NORESERVE_COMMITED:
return ExceptionContinueExecution;
case MMAP_RAISE_SIGBUS: /* MAP_NORESERVE page, commit failed, or
access to mmap page beyond EOF. */
si.si_signo = SIGBUS;
si.si_code = BUS_OBJERR;
break;
default:
MEMORY_BASIC_INFORMATION m;
VirtualQuery ((PVOID) e->ExceptionInformation[1], &m, sizeof m);
si.si_signo = SIGSEGV;
si.si_code = m.State == MEM_FREE ? SEGV_MAPERR : SEGV_ACCERR;
break;
}
break;
case STATUS_STACK_OVERFLOW:
/* If we encounter a stack overflow, and if the thread has no alternate
stack, don't even try to call a signal handler. This is in line with
Linux behaviour and also makes a lot of sense on Windows. */
if (me.altstack.ss_flags)
global_sigs[SIGSEGV].sa_handler = SIG_DFL;
/*FALLTHRU*/
case STATUS_ARRAY_BOUNDS_EXCEEDED:
case STATUS_IN_PAGE_ERROR:
case STATUS_NO_MEMORY:
case STATUS_INVALID_DISPOSITION:
si.si_signo = SIGSEGV;
si.si_code = SEGV_MAPERR;
break;
case STATUS_CONTROL_C_EXIT:
si.si_signo = SIGINT;
break;
case STATUS_INVALID_HANDLE:
/* CloseHandle will throw this exception if it is given an
invalid handle. We don't care about the exception; we just
want CloseHandle to return an error. This can be revisited
if gcc ever supports Windows style structured exception
handling. */
return ExceptionContinueExecution;
default:
/* If we don't recognize the exception, we have to assume that
we are doing structured exception handling, and we let
something else handle it. */
return ExceptionContinueSearch;
}
debug_printf ("In cygwin_except_handler exception %y at %p sp %p",
e->ExceptionCode, in->_GR(ip), in->_GR(sp));
debug_printf ("In cygwin_except_handler signal %d at %p",
si.si_signo, in->_GR(ip));
#ifdef __x86_64__
PUINT_PTR framep = (PUINT_PTR) in->Rbp;
/* Sometimes, when a stack is screwed up, Rbp tends to be NULL. In that
case, base the stacktrace on Rsp. In most cases, it allows to generate
useful stack trace. */
if (!framep)
framep = (PUINT_PTR) in->Rsp;
#else
PUINT_PTR framep = (PUINT_PTR) in->_GR(sp);
for (PUINT_PTR bpend = (PUINT_PTR) __builtin_frame_address (0);
framep > bpend;
framep--)
if (*framep == in->SegCs && framep[-1] == in->_GR(ip))
{
framep -= 2;
break;
}
/* Temporarily replace windows top level SEH with our own handler.
We don't want any Windows magic kicking in. This top level frame
will be removed automatically after our exception handler returns. */
_except_list->handler = handle;
#endif
if (exit_state >= ES_SIGNAL_EXIT
&& (NTSTATUS) e->ExceptionCode != STATUS_CONTROL_C_EXIT)
api_fatal ("Exception during process exit");
else if (!try_to_debug (0))
rtl_unwind (frame, e);
else
{
debugging = 1;
return ExceptionContinueExecution;
}
/* FIXME: Probably should be handled in signal processing code */
if ((NTSTATUS) e->ExceptionCode == STATUS_ACCESS_VIOLATION)
{
int error_code = 0;
if (si.si_code == SEGV_ACCERR) /* Address present */
error_code |= 1;
if (e->ExceptionInformation[0]) /* Write access */
error_code |= 2;
if (!me.inside_kernel (in)) /* User space */
error_code |= 4;
klog (LOG_INFO,
#ifdef __x86_64__
"%s[%d]: segfault at %011X rip %011X rsp %011X error %d",
#else
"%s[%d]: segfault at %08x rip %08x rsp %08x error %d",
#endif
__progname, myself->pid,
e->ExceptionInformation[1], in->_GR(ip), in->_GR(sp),
error_code);
}
cygwin_exception exc (framep, in, e);
si.si_cyg = (void *) &exc;
/* POSIX requires that for SIGSEGV and SIGBUS, si_addr should be set to the
address of faulting memory reference. For SIGILL and SIGFPE these should
be the address of the faulting instruction. Other signals are apparently
undefined so we just set those to the faulting instruction too. */
si.si_addr = (si.si_signo == SIGSEGV || si.si_signo == SIGBUS)
? (void *) e->ExceptionInformation[1] : (void *) in->_GR(ip);
me.incyg++;
sig_send (NULL, si, &me); /* Signal myself */
if ((NTSTATUS) e->ExceptionCode == STATUS_STACK_OVERFLOW)
{
/* If we catched a stack overflow, and if the signal handler didn't exit
or longjmp, we're back here and about to continue, supposed to run the
offending instruction again. That works on Linux, but not on Windows.
In case of a stack overflow we're not immediately returning to the
system exception handler, but to NTDLL::__stkchk. __stkchk will then
terminate the applicaton. So what we do here is to signal our current
process again, but this time with SIG_DFL action. This creates a
stackdump and then exits through our own means. */
global_sigs[SIGSEGV].sa_handler = SIG_DFL;
sig_send (NULL, si, &me);
}
me.incyg--;
e->ExceptionFlags = 0;
return ExceptionContinueExecution;
}
/* Utilities to call a user supplied exception handler. */
#define SIG_NONMASKABLE (SIGTOMASK (SIGKILL) | SIGTOMASK (SIGSTOP))
/* Non-raceable sigsuspend
Note: This implementation is based on the Single UNIX Specification
man page. This indicates that sigsuspend always returns -1 and that
attempts to block unblockable signals will be silently ignored.
This is counter to what appears to be documented in some UNIX
man pages, e.g. Linux. */
int __stdcall
handle_sigsuspend (sigset_t tempmask)
{
sigset_t oldmask = _my_tls.sigmask; // Remember for restoration
set_signal_mask (_my_tls.sigmask, tempmask);
sigproc_printf ("oldmask %ly, newmask %ly", oldmask, tempmask);
pthread_testcancel ();
cygwait (NULL, cw_infinite, cw_cancel | cw_cancel_self | cw_sig_eintr);
set_sig_errno (EINTR); // Per POSIX
/* A signal dispatch function will have been added to our stack and will
be hit eventually. Set the old mask to be restored when the signal
handler returns and indicate its presence by modifying deltamask. */
_my_tls.deltamask |= SIG_NONMASKABLE;
_my_tls.oldmask = oldmask; // Will be restored by signal handler
return -1;
}
extern DWORD exec_exit; // Possible exit value for exec
extern "C" {
static void
sig_handle_tty_stop (int sig, siginfo_t *, void *)
{
/* Silently ignore attempts to suspend if there is no accommodating
cygwin parent to deal with this behavior. */
if (!myself->cygstarted)
myself->process_state &= ~PID_STOPPED;
else
{
_my_tls.incyg = 1;
myself->stopsig = sig;
myself->alert_parent (sig);
sigproc_printf ("process %d stopped by signal %d", myself->pid, sig);
/* FIXME! This does nothing to suspend anything other than the main
thread. */
/* Use special cygwait parameter to handle SIGCONT. _main_tls.sig will
be cleared under lock when SIGCONT is detected. */
DWORD res = cygwait (NULL, cw_infinite, cw_sig_cont);
switch (res)
{
case WAIT_SIGNALED:
myself->stopsig = SIGCONT;
myself->alert_parent (SIGCONT);
break;
default:
api_fatal ("WaitSingleObject returned %d", res);
break;
}
_my_tls.incyg = 0;
}
}
} /* end extern "C" */
bool
_cygtls::interrupt_now (CONTEXT *cx, siginfo_t& si, void *handler,
struct sigaction& siga)
{
bool interrupted;
/* Delay the interrupt if we are
1) somehow inside the DLL
2) in _sigfe (spinning is true) and about to enter cygwin DLL
3) in a Windows DLL. */
if (incyg || spinning || inside_kernel (cx))
interrupted = false;
else
{
_ADDR &ip = cx->_GR(ip);
push (ip);
interrupt_setup (si, handler, siga);
ip = pop ();
SetThreadContext (*this, cx); /* Restart the thread in a new location */
interrupted = true;
}
return interrupted;
}
void __reg3
_cygtls::interrupt_setup (siginfo_t& si, void *handler, struct sigaction& siga)
{
push ((__tlsstack_t) sigdelayed);
deltamask = siga.sa_mask & ~SIG_NONMASKABLE;
sa_flags = siga.sa_flags;
func = (void (*) (int, siginfo_t *, void *)) handler;
if (siga.sa_flags & SA_RESETHAND)
siga.sa_handler = SIG_DFL;
saved_errno = -1; // Flag: no errno to save
if (handler == sig_handle_tty_stop)
{
myself->stopsig = 0;
myself->process_state |= PID_STOPPED;
}
infodata = si;
this->sig = si.si_signo; /* Should always be last thing set to avoid race */
if (incyg)
set_signal_arrived ();
if (!have_execed)
proc_subproc (PROC_CLEARWAIT, 1);
sigproc_printf ("armed signal_arrived %p, signal %d",
signal_arrived, si.si_signo);
}
extern "C" void __stdcall
set_sig_errno (int e)
{
*_my_tls.errno_addr = e;
_my_tls.saved_errno = e;
}
int
sigpacket::setup_handler (void *handler, struct sigaction& siga, _cygtls *tls)
{
CONTEXT cx;
bool interrupted = false;
if (tls->sig)
{
sigproc_printf ("trying to send signal %d but signal %d already armed",
si.si_signo, tls->sig);
goto out;
}
for (int n = 0; n < CALL_HANDLER_RETRY_OUTER; n++)
{
for (int i = 0; i < CALL_HANDLER_RETRY_INNER; i++)
{
tls->lock ();
if (tls->incyg)
{
sigproc_printf ("controlled interrupt. stackptr %p, stack %p, "
"stackptr[-1] %p",