aboutsummaryrefslogtreecommitdiff
path: root/winsup/cygwin/exceptions.cc
blob: 152210ff33088a8294003ddbca67c43a0db2307b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
/* exceptions.cc

   Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
   2005 Red Hat, Inc.

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. */

#include "winsup.h"
#include <wingdi.h>
#include <winuser.h>
#include <imagehlp.h>
#include <stdlib.h>
#include <setjmp.h>
#include <assert.h>

#include "exceptions.h"
#include "sync.h"
#include "pinfo.h"
#include "cygtls.h"
#include "sigproc.h"
#include "cygerrno.h"
#include "shared_info.h"
#include "perprocess.h"
#include "security.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"

#define CALL_HANDLER_RETRY 20

char debugger_command[2 * CYG_MAX_PATH + 20];

extern "C" {
extern void sigdelayed ();
};

extern NO_COPY DWORD dwExeced;
int NO_COPY sigExeced;

static BOOL WINAPI ctrl_c_handler (DWORD);
static void signal_exit (int) __attribute__ ((noreturn));
char windows_system_directory[1024];
static size_t windows_system_directory_length;

/* This is set to indicate that we have already exited.  */

static NO_COPY int exit_already = 0;
static NO_COPY muto mask_sync;

NO_COPY static struct
{
  unsigned int 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.  */

BOOL WINAPI
dummy_ctrl_c_handler (DWORD dwCtrlType)
{
  return TRUE;
}

void
init_console_handler (BOOL install_handler)
{
  BOOL res;
  while (SetConsoleCtrlHandler (ctrl_c_handler, FALSE))
    continue;
  if (install_handler)
    res = SetConsoleCtrlHandler (ctrl_c_handler, TRUE);
  else if (wincap.has_null_console_handler_routine ())
    res = SetConsoleCtrlHandler (NULL, TRUE);
  else
    res = SetConsoleCtrlHandler (dummy_ctrl_c_handler, TRUE);
  if (!res)
    system_printf ("SetConsoleCtrlHandler failed, %E");
}

extern "C" void
error_start_init (const char *buf)
{
  if (!buf || !*buf)
    {
      debugger_command[0] = '\0';
      return;
    }

  char pgm[CYG_MAX_PATH];
  if (!GetModuleFileName (NULL, pgm, CYG_MAX_PATH))
    strcpy (pgm, "cygwin1.dll");
  for (char *p = strchr (pgm, '\\'); p; p = strchr (p, '\\'))
    *p = '/';

  __small_sprintf (debugger_command, "%s \"%s\"", buf, pgm);
}

static void
open_stackdumpfile ()
{
  if (myself->progname[0])
    {
      const char *p;
      /* write to progname.stackdump if possible */
      if (!myself->progname[0])
	p = "unknown";
      else if ((p = strrchr (myself->progname, '\\')))
	p++;
      else
	p = myself->progname;
      char corefile[strlen (p) + sizeof (".stackdump")];
      __small_sprintf (corefile, "%s.stackdump", p);
      HANDLE h = CreateFile (corefile, GENERIC_WRITE, 0, &sec_none_nih,
			     CREATE_ALWAYS, 0, 0);
      if (h != INVALID_HANDLE_VALUE)
	{
	  if (!myself->cygstarted)
	    system_printf ("Dumping stack trace to %s", corefile);
	  else
	    debug_printf ("Dumping stack trace to %s", corefile);
	  SetStdHandle (STD_ERROR_HANDLE, h);
	}
    }
}

/* Utilities for dumping the stack, etc.  */

static void
exception (EXCEPTION_RECORD *e,  CONTEXT *in)
{
  const char *exception_name = NULL;

  if (e)
    {
      for (int i = 0; status_info[i].name; i++)
	{
	  if (status_info[i].code == e->ExceptionCode)
	    {
	      exception_name = status_info[i].name;
	      break;
	    }
	}
    }

  if (exception_name)
    small_printf ("Exception: %s at eip=%08x\r\n", exception_name, in->Eip);
  else
    small_printf ("Exception %d at eip=%08x\r\n", e->ExceptionCode, in->Eip);
  small_printf ("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\r\n",
		in->Eax, in->Ebx, in->Ecx, in->Edx, in->Esi, in->Edi);
  small_printf ("ebp=%08x esp=%08x program=%s, pid %u, thread %s\r\n",
		in->Ebp, in->Esp, myself->progname, myself->pid, cygthread::name ());
  small_printf ("cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x\r\n",
		in->SegCs, in->SegDs, in->SegEs, in->SegFs, in->SegGs, in->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;
  DWORD dummy_frame;
public:
  STACKFRAME sf;		 /* For storing the stack information */
  void init (DWORD, bool, bool); /* 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 (DWORD ebp, bool wantargs, bool goodframe)
{
# define debp ((DWORD *) ebp)
  memset (&sf, 0, sizeof (sf));
  if (!goodframe)
    sf.AddrFrame.Offset = ebp;
  else
    {
      dummy_frame = ebp;
      sf.AddrFrame.Offset = (DWORD) &dummy_frame;
    }
  sf.AddrReturn.Offset = debp[1];
  sf.AddrFrame.Mode = AddrModeFlat;
  needargs = wantargs;
# undef debp
}

/* Walk the stack by looking at successive stored 'bp' frames.
   This is not foolproof. */
int
stack_info::walk ()
{
  char **ebp;
  if ((ebp = (char **) next_offset ()) == NULL)
    return 0;

  sf.AddrFrame.Offset = (DWORD) ebp;
  sf.AddrPC.Offset = sf.AddrReturn.Offset;

  if (!sf.AddrPC.Offset)
    return 0;		/* stack frames are exhausted */

  /* The return address always follows the stack pointer */
  sf.AddrReturn.Offset = (DWORD) *++ebp;

  if (needargs)
    /* The arguments follow the return address */
    for (unsigned i = 0; i < NPARAMS; i++)
      sf.Params[i] = (DWORD) *++ebp;

  return 1;
}

static void
stackdump (DWORD ebp, int open_file, bool isexception)
{
  extern unsigned long rlim_core;

  if (rlim_core == 0UL)
    return;

  if (open_file)
    open_stackdumpfile ();

  int i;

  thestack.init (ebp, 1, !isexception);	/* Initialize from the input CONTEXT */
  small_printf ("Stack trace:\r\nFrame     Function  Args\r\n");
  for (i = 0; i < 16 && thestack++; i++)
    {
      small_printf ("%08x  %08x ", thestack.sf.AddrFrame.Offset,
		    thestack.sf.AddrPC.Offset);
      for (unsigned j = 0; j < NPARAMS; j++)
	small_printf ("%s%08x", 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)" : "");
}

/* Temporary (?) function for external callers to get a stack dump */
extern "C" void
cygwin_stackdump ()
{
  CONTEXT c;
  c.ContextFlags = CONTEXT_FULL;
  GetThreadContext (GetCurrentThread (), &c);
  stackdump (c.Ebp, 0, 0);
}

#define TIME_TO_WAIT_FOR_DEBUGGER 10000

extern "C" int
try_to_debug (bool waitloop)
{
  debug_printf ("debugger_command '%s'", debugger_command);
  if (*debugger_command == '\0')
    return 0;
  if (being_debugged ())
    {
      DebugBreak ();
      return 0;
    }

  __small_sprintf (strchr (debugger_command, '\0'), " %u", GetCurrentProcessId ());

  LONG prio = GetThreadPriority (GetCurrentThread ());
  SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);
  PROCESS_INFORMATION pi = {NULL, 0, 0, 0};

  STARTUPINFO 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 any of these mutexes is owned, we will fail to start any cygwin app
     until trapped app exits */

  ReleaseMutex (tty_mutex);

  /* prevent recursive exception handling */
  char* rawenv = GetEnvironmentStrings () ;
  for (char* p = rawenv; *p != '\0'; p = strchr (p, '\0') + 1)
    {
      if (strncmp (p, "CYGWIN=", strlen ("CYGWIN=")) == 0)
	{
	  char* q = strstr (p, "error_start") ;
	  /* replace 'error_start=...' with '_rror_start=...' */
	  if (q)
	    {
	      *q = '_' ;
	      SetEnvironmentVariable ("CYGWIN", p + strlen ("CYGWIN=")) ;
	    }
	  break ;
	}
    }

  console_printf ("*** starting debugger for pid %u, tid %u\n",
		  cygwin_pid (GetCurrentProcessId ()), GetCurrentThreadId ());
  BOOL dbg;
  dbg = CreateProcess (NULL,
		       debugger_command,
		       NULL,
		       NULL,
		       FALSE,
		       CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
		       NULL,
		       NULL,
		       &si,
		       &pi);

  if (!dbg)
    system_printf ("Failed to start debugger, %E");
  else
    {
      if (!waitloop)
	return dbg;
      SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_IDLE);
      while (!being_debugged ())
	low_priority_sleep (0);
      Sleep (2000);
    }

  console_printf ("*** continuing pid %u from debugger call (%d)\n",
		  cygwin_pid (GetCurrentProcessId ()), dbg);

  SetThreadPriority (GetCurrentThread (), prio);
  return dbg;
}

extern "C" DWORD __stdcall RtlUnwind (void *, void *, void *, DWORD);
static void __stdcall rtl_unwind (exception_list *, PEXCEPTION_RECORD) __attribute__ ((noinline, regparm (3)));
void __stdcall
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));
}

/* Main exception handler. */

int
_cygtls::handle_exceptions (EXCEPTION_RECORD *e, exception_list *frame, CONTEXT *in, void *)
{
  static bool NO_COPY debugging;
  static int NO_COPY recursed;
  _cygtls& me = _my_tls;

  if (debugging && ++debugging < 500000)
    {
      SetThreadPriority (hMainThread, THREAD_PRIORITY_NORMAL);
      return 0;
    }

  /* If we've already exited, don't do anything here.  Returning 1
     tells Windows to keep looking for an exception handler.  */
  if (exit_already || e->ExceptionFlags)
    return 1;

  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_ACCESS_VIOLATION:
      if (mmap_is_attached_page (e->ExceptionInformation[1]))
	{
	  si.si_signo = SIGBUS;
	  si.si_code = BUS_OBJERR;
	  break;
	}
      /*FALLTHRU*/
    case STATUS_DATATYPE_MISALIGNMENT:
    case STATUS_ARRAY_BOUNDS_EXCEEDED:
    case STATUS_IN_PAGE_ERROR:
    case STATUS_NO_MEMORY:
    case STATUS_INVALID_DISPOSITION:
    case STATUS_STACK_OVERFLOW:
      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 0;

    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 1;
    }

  rtl_unwind (frame, e);

  debug_printf ("In cygwin_except_handler exc %p at %p sp %p", e->ExceptionCode, in->Eip, in->Esp);
  debug_printf ("In cygwin_except_handler sig %d at %p", si.si_signo, in->Eip);

  if (global_sigs[si.si_signo].sa_mask & SIGTOMASK (si.si_signo))
    syscall_printf ("signal %d, masked %p", si.si_signo,
		    global_sigs[si.si_signo].sa_mask);

  debug_printf ("In cygwin_except_handler calling %p",
		 global_sigs[si.si_signo].sa_handler);

  DWORD *ebp = (DWORD *) in->Esp;
  for (DWORD *bpend = (DWORD *) __builtin_frame_address (0); ebp > bpend; ebp--)
    if (*ebp == in->SegCs && ebp[-1] == in->Eip)
      {
	ebp -= 2;
	break;
      }

  if (!me.fault_guarded ()
      && (!cygwin_finished_initializing
	  || &me == _sig_tls
	  || (void *) global_sigs[si.si_signo].sa_handler == (void *) SIG_DFL
	  || (void *) global_sigs[si.si_signo].sa_handler == (void *) SIG_IGN
	  || (void *) global_sigs[si.si_signo].sa_handler == (void *) SIG_ERR))
    {
      /* Print the exception to the console */
      if (!myself->cygstarted)
	for (int i = 0; status_info[i].name; i++)
	  if (status_info[i].code == e->ExceptionCode)
	    {
	      system_printf ("Exception: %s", status_info[i].name);
	      break;
	    }

      /* Another exception could happen while tracing or while exiting.
	 Only do this once.  */
      if (recursed++)
	system_printf ("Error while dumping state (probably corrupted stack)");
      else
	{
	  if (try_to_debug (0))
	    {
	      debugging = true;
	      return 0;
	    }

	  open_stackdumpfile ();
	  exception (e, in);
	  stackdump ((DWORD) ebp, 0, 1);
	}

      signal_exit (0x80 | si.si_signo);	// Flag signal + core dump
    }

  if (me.fault_guarded ())
    me.return_from_fault ();

  si.si_addr = (void *) in->Eip;
  si.si_errno = si.si_pid = si.si_uid = 0;
  me.incyg++;
  sig_send (NULL, si, &me);	// Signal myself
  me.incyg--;
  e->ExceptionFlags = 0;
  return 0;
}

/* 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)
{
  if (&_my_tls != _main_tls)
    {
      cancelable_wait (signal_arrived, INFINITE, cw_cancel_self);
      return -1;
    }

  sigset_t oldmask = myself->getsigmask ();	// Remember for restoration

  set_signal_mask (tempmask, myself->getsigmask ());
  sigproc_printf ("oldmask %p, newmask %p", oldmask, tempmask);

  pthread_testcancel ();
  cancelable_wait (signal_arrived, INFINITE);

  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)
{
  _my_tls.incyg = 1;
  /* 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;
      return;
    }

  myself->stopsig = sig;
  myself->alert_parent (sig);
  sigproc_printf ("process %d stopped by signal %d", myself->pid, sig);
  HANDLE w4[2];
  w4[0] = sigCONT;
  w4[1] = signal_arrived;
  switch (WaitForMultipleObjects (2, w4, TRUE, INFINITE))
    {
    case WAIT_OBJECT_0:
    case WAIT_OBJECT_0 + 1:
      reset_signal_arrived ();
      myself->alert_parent (SIGCONT);
      break;
    default:
      api_fatal ("WaitSingleObject failed, %E");
      break;
    }
  _my_tls.incyg = 0;
}
}

bool
_cygtls::interrupt_now (CONTEXT *cx, int sig, void *handler,
			struct sigaction& siga)
{
  int res;
  bool interrupted;
  MEMORY_BASIC_INFORMATION m;

  memset (&m, 0, sizeof m);
  if (!VirtualQuery ((LPCVOID) cx->Eip, &m, sizeof m))
    sigproc_printf ("couldn't get memory info, pc %p, %E", cx->Eip);

  char *checkdir = (char *) alloca (windows_system_directory_length + 4);
  memset (checkdir, 0, sizeof (checkdir));

# define h ((HMODULE) m.AllocationBase)
  /* Apparently Windows 95 can sometimes return bogus addresses from
     GetThreadContext.  These resolve to a strange allocation base.
     These should *never* be treated as interruptible. */
  if (!h || m.State != MEM_COMMIT)
    res = false;
  else if (h == user_data->hmodule)
    res = true;
  else if (!GetModuleFileName (h, checkdir, windows_system_directory_length + 2))
    res = false;
  else
    res = !strncasematch (windows_system_directory, checkdir,
			  windows_system_directory_length);
  sigproc_printf ("pc %p, h %p, interruptible %d", cx->Eip, h, res);
# undef h

  if (!res || (incyg || spinning || locked ()))
    interrupted = false;
  else
    {
      push ((__stack_t) cx->Eip);
      interrupt_setup (sig, handler, siga);
      cx->Eip = pop ();
      SetThreadContext (*this, cx); /* Restart the thread in a new location */
      interrupted = true;
    }
  return interrupted;
}

void __stdcall
_cygtls::interrupt_setup (int sig, void *handler, struct sigaction& siga)
{
  push ((__stack_t) sigdelayed);
  deltamask = (siga.sa_mask | SIGTOMASK (sig)) & ~SIG_NONMASKABLE;
  sa_flags = siga.sa_flags;
  func = (void (*) (int)) handler;
  saved_errno = -1;		// Flag: no errno to save
  if (handler == sig_handle_tty_stop)
    {
      myself->stopsig = 0;
      myself->process_state |= PID_STOPPED;
    }

  this->sig = sig;			// Should always be last thing set to avoid a race

  /* Clear any waiting threads prior to dispatching to handler function */
  int res = SetEvent (signal_arrived);	// For an EINTR case
  proc_subproc (PROC_CLEARWAIT, 1);
  sigproc_printf ("armed signal_arrived %p, sig %d, res %d", signal_arrived,
		  sig, res);
}

extern "C" void __stdcall
set_sig_errno (int e)
{
  *_my_tls.errno_addr = e;
  _my_tls.saved_errno = e;
  // sigproc_printf ("errno %d", e);
}

static int setup_handler (int, void *, struct sigaction&, _cygtls *tls)
  __attribute__((regparm(3)));
static int
setup_handler (int sig, void *handler, struct sigaction& siga, _cygtls *tls)
{
  CONTEXT cx;
  bool interrupted = false;

  if (tls->sig)
    {
      sigproc_printf ("trying to send sig %d but signal %d already armed",
		      sig, tls->sig);
      goto out;
    }

  for (int i = 0; i < CALL_HANDLER_RETRY; i++)
    {
      tls->lock ();
      if (tls->incyg)
	{
	  sigproc_printf ("controlled interrupt. stackptr %p, stack %p, stackptr[-1] %p",
			  tls->stackptr, tls->stack, tls->stackptr[-1]);
	  tls->interrupt_setup (sig, handler, siga);
	  interrupted = true;
	  tls->unlock ();
	  break;
	}

      tls->unlock ();
      DWORD res;
      HANDLE hth = (HANDLE) *tls;

      /* Suspend the thread which will receive the signal.
	 For Windows 95, we also have to ensure that the addresses returned by
	 GetThreadContext are valid.
	 If one of these conditions is not true we loop for a fixed number of times
	 since we don't want to stall the signal handler.  FIXME: Will this result in
	 noticeable delays?
	 If the thread is already suspended (which can occur when a program has called
	 SuspendThread on itself) then just queue the signal. */

#ifndef DEBUGGING
      sigproc_printf ("suspending mainthread");
#else
      cx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
      if (!GetThreadContext (hth, &cx))
	memset (&cx, 0, sizeof cx);
      sigproc_printf ("suspending mainthread PC %p", cx.Eip);
#endif
      res = SuspendThread (hth);
      /* Just set pending if thread is already suspended */
      if (res)
	{
	  ResumeThread (hth);
	  break;
	}
      cx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
      if (!GetThreadContext (hth, &cx))
	system_printf ("couldn't get context of main thread, %E");
      else
	interrupted = tls->interrupt_now (&cx, sig, handler, siga);

      res = ResumeThread (hth);
      if (interrupted)
	break;

      sigproc_printf ("couldn't interrupt.  trying again.");
      low_priority_sleep (0);
    }

out:
  if (interrupted && tls->event)
    {
      HANDLE h = tls->event;
      tls->event = NULL;
      SetEvent (h);
    }
  sigproc_printf ("signal %d %sdelivered", sig, interrupted ? "" : "not ");
  return interrupted;
}

static inline bool
has_visible_window_station ()
{
  HWINSTA station_hdl;
  USEROBJECTFLAGS uof;
  DWORD len;

  /* Check if the process is associated with a visible window station.
     These are processes running on the local desktop as well as processes
     running in terminal server sessions.
     Processes running in a service session not explicitely associated
     with the desktop (using the "Allow service to interact with desktop"
     property) are running in an invisible window station. */
  if ((station_hdl = GetProcessWindowStation ())
      && GetUserObjectInformationA (station_hdl, UOI_FLAGS, &uof,
				    sizeof uof, &len)
      && (uof.dwFlags & WSF_VISIBLE))
    return true;
  return false;
}

/* Keyboard interrupt handler.  */
static BOOL WINAPI
ctrl_c_handler (DWORD type)
{
  static bool saw_close;

  if (!cygwin_finished_initializing)
    {
      if (myself->cygstarted)	/* Was this process created by a cygwin process? */
	return TRUE;		/* Yes.  Let the parent eventually handle CTRL-C issues. */
      debug_printf ("exiting with status %p", STATUS_CONTROL_C_EXIT);
      ExitProcess (STATUS_CONTROL_C_EXIT);
    }

  _my_tls.remove (INFINITE);

#if 0
  if (type == CTRL_C_EVENT || type == CTRL_BREAK_EVENT)
    proc_subproc (PROC_KILLFORKED, 0);
#endif

  /* Return FALSE to prevent an "End task" dialog box from appearing
     for each Cygwin process window that's open when the computer
     is shut down or console window is closed. */

  if (type == CTRL_SHUTDOWN_EVENT)
    {
#if 0
      /* Don't send a signal.  Only NT service applications and their child
	 processes will receive this event and the services typically already
	 handle the shutdown action when getting the SERVICE_CONTROL_SHUTDOWN
	 control message. */
      sig_send (NULL, SIGTERM);
#endif
      return FALSE;
    }

  if (myself->ctty != -1)
    {
      if (type == CTRL_CLOSE_EVENT)
	{
	  sig_send (NULL, SIGHUP);
	  saw_close = true;
	  return FALSE;
	}
      if (!saw_close && type == CTRL_LOGOFF_EVENT)
	{
#if 0
	  /* CV, 2005-09-08: The CTRL_LOGOFF_EVENT is only send to services.
	     It's send when *any* user logs off.  Services generally have
	     a modified console handler which allows services to survive
	     also after a user logged out, even if the service has a console
	     window attached to the visible window station of the user
	     ("Interact with desktop").  The below code contradicts this
	     standard behaviour, so for now, we disable it and just return
	     FALSE to get the default behaviour or the one the application's
	     own console handler (if any) requires.
	     In other words: We never send SIGHUP to services and their
	     child processes on a LOGOFF event. */

	  /* Check if the process is actually associated with a visible
	     window station, one which actually represents a visible desktop.
	     If not, the CTRL_LOGOFF_EVENT doesn't concern this process. */
	  if (has_visible_window_station ())
	    sig_send (myself_nowait, SIGHUP);
#endif
	  return FALSE;
	}
    }

  /* If we are a stub and the new process has a pinfo structure, let it
     handle this signal. */
  if (dwExeced && pinfo (dwExeced))
    return TRUE;

  /* We're only the process group leader when we have a valid pinfo structure.
     If we don't have one, then the parent "stub" will handle the signal. */
  if (!pinfo (cygwin_pid (GetCurrentProcessId ())))
    return TRUE;

  tty_min *t = cygwin_shared->tty.get_tty (myself->ctty);
  /* Ignore this if we're not the process group leader since it should be handled
     *by* the process group leader. */
  if (myself->ctty != -1 && t->getpgid () == myself->pid &&
       (GetTickCount () - t->last_ctrl_c) >= MIN_CTRL_C_SLOP)
    /* Otherwise we just send a SIGINT to the process group and return TRUE (to indicate
       that we have handled the signal).  At this point, type should be
       a CTRL_C_EVENT or CTRL_BREAK_EVENT. */
    {
      int sig = SIGINT;
      /* If intr and quit are both mapped to ^C, send SIGQUIT on ^BREAK */
      if (type == CTRL_BREAK_EVENT
	  && t->ti.c_cc[VINTR] == 3 && t->ti.c_cc[VQUIT] == 3)
	sig = SIGQUIT;
      t->last_ctrl_c = GetTickCount ();
      killsys (-myself->pid, sig);
      t->last_ctrl_c = GetTickCount ();
      return TRUE;
    }

  return TRUE;
}

/* Function used by low level sig wrappers. */
extern "C" void __stdcall
set_process_mask (sigset_t newmask)
{
  set_signal_mask (newmask, myself->getsigmask ());
sigproc_printf ("mask now %p\n", myself->getsigmask ());
}

extern "C" int
sighold (int sig)
{
  /* check that sig is in right range */
  if (sig < 0 || sig >= NSIG)
    {
      set_errno (EINVAL);
      syscall_printf ("signal %d out of range", sig);
      return -1;
    }
  mask_sync.acquire (INFINITE);
  sigset_t mask = myself->getsigmask ();
  sigaddset (&mask, sig);
  set_signal_mask (mask, myself->getsigmask ());
  mask_sync.release ();
  return 0;
}

extern "C" int
sigrelse (int sig)
{
  /* check that sig is in right range */
  if (sig < 0 || sig >= NSIG)
    {
      set_errno (EINVAL);
      syscall_printf ("signal %d out of range", sig);
      return -1;
    }
  mask_sync.acquire (INFINITE);
  sigset_t mask = myself->getsigmask ();
  sigdelset (&mask, sig);
  set_signal_mask (mask, myself->getsigmask ());
  mask_sync.release ();
  return 0;
}

/* Update the signal mask for this process
   and return the old mask.
   Called from sigdelayed */
extern "C" sigset_t
set_process_mask_delta ()
{
  mask_sync.acquire (INFINITE);
  sigset_t newmask, oldmask;

  if (_my_tls.deltamask & SIG_NONMASKABLE)
    oldmask = _my_tls.oldmask; /* from handle_sigsuspend */
  else
    oldmask = myself->getsigmask ();
  newmask = (oldmask | _my_tls.deltamask) & ~SIG_NONMASKABLE;
  sigproc_printf ("oldmask %p, newmask %p, deltamask %p", oldmask, newmask,
		  _my_tls.deltamask);
  myself->setsigmask (newmask);
  mask_sync.release ();
  return oldmask;
}

/* Set the signal mask for this process.
   Note that some signals are unmaskable, as in UNIX.  */
extern "C" void __stdcall
set_signal_mask (sigset_t newmask, sigset_t& oldmask)
{
#ifdef CGF
  if (&_my_tls == _sig_tls)
    small_printf ("********* waiting in signal thread\n");
#endif
  mask_sync.acquire (INFINITE);
  newmask &= ~SIG_NONMASKABLE;
  sigset_t mask_bits = oldmask & ~newmask;
  sigproc_printf ("oldmask %p, newmask %p, mask_bits %p", oldmask, newmask,
		  mask_bits);
  oldmask = newmask;
  if (mask_bits)
    sig_dispatch_pending (true);
  else
    sigproc_printf ("not calling sig_dispatch_pending");
  mask_sync.release ();
}

int __stdcall
sigpacket::process ()
{
  DWORD continue_now;
  if (si.si_signo != SIGCONT)
    continue_now = false;
  else
    {
      continue_now = myself->process_state & PID_STOPPED;
      myself->stopsig = 0;
      myself->process_state &= ~PID_STOPPED;
      /* Clear pending stop signals */
      sig_clear (SIGSTOP);
      sig_clear (SIGTSTP);
      sig_clear (SIGTTIN);
      sig_clear (SIGTTOU);
    }

  int rc = 1;

  sigproc_printf ("signal %d processing", si.si_signo);
  struct sigaction thissig = global_sigs[si.si_signo];

  myself->rusage_self.ru_nsignals++;

  bool masked;
  void *handler;
  if (!hExeced || (void *) thissig.sa_handler == (void *) SIG_IGN)
    handler = (void *) thissig.sa_handler;
  else if (tls)
    return 1;
  else
    handler = NULL;

  if (si.si_signo == SIGKILL)
    goto exit_sig;
  if (si.si_signo == SIGSTOP)
    {
      sig_clear (SIGCONT);
      if (!tls)
	tls = _main_tls;
      goto stop;
    }

  bool insigwait_mask;
  if ((masked = ISSTATE (myself, PID_STOPPED)))
    insigwait_mask = false;
  else if (!tls)
    insigwait_mask = !handler && (tls = _cygtls::find_tls (si.si_signo));
  else
    insigwait_mask = sigismember (&tls->sigwait_mask, si.si_signo);

  if (insigwait_mask)
    goto thread_specific;

  if (masked)
    /* nothing to do */;
  else if (sigismember (mask, si.si_signo))
    masked = true;
  else if (tls)
    masked  = sigismember (&tls->sigmask, si.si_signo);

  if (!tls)
    tls = _main_tls;

  if (masked)
    {
      sigproc_printf ("signal %d blocked", si.si_signo);
      rc = -1;
      goto done;
    }

  /* Clear pending SIGCONT on stop signals */
  if (si.si_signo == SIGTSTP || si.si_signo == SIGTTIN || si.si_signo == SIGTTOU)
    sig_clear (SIGCONT);

#ifdef CGF
  if (being_debugged ())
    {
      char sigmsg[sizeof (_CYGWIN_SIGNAL_STRING " 0xffffffff")];
      __small_sprintf (sigmsg, _CYGWIN_SIGNAL_STRING " %p", si.si_signo);
      OutputDebugString (sigmsg);
    }
#endif

  if (handler == (void *) SIG_DFL)
    {
      if (insigwait_mask)
	goto thread_specific;
      if (si.si_signo == SIGCHLD || si.si_signo == SIGIO || si.si_signo == SIGCONT || si.si_signo == SIGWINCH
	  || si.si_signo == SIGURG)
	{
	  sigproc_printf ("default signal %d ignored", si.si_signo);
	  if (continue_now)
	    SetEvent (signal_arrived);
	  goto done;
	}

      if (si.si_signo == SIGTSTP || si.si_signo == SIGTTIN || si.si_signo == SIGTTOU)
	goto stop;

      goto exit_sig;
    }

  if (handler == (void *) SIG_IGN)
    {
      sigproc_printf ("signal %d ignored", si.si_signo);
      goto done;
    }

  if (handler == (void *) SIG_ERR)
    goto exit_sig;

  tls->set_siginfo (this);
  goto dosig;

stop:
  /* Eat multiple attempts to STOP */
  if (ISSTATE (myself, PID_STOPPED))
    goto done;
  handler = (void *) sig_handle_tty_stop;
  thissig = global_sigs[SIGSTOP];

dosig:
  /* Dispatch to the appropriate function. */
  sigproc_printf ("signal %d, about to call %p", si.si_signo, handler);
  rc = setup_handler (si.si_signo, handler, thissig, tls);

done:
  if (continue_now)
    SetEvent (sigCONT);
  sigproc_printf ("returning %d", rc);
  return rc;

thread_specific:
  tls->sig = si.si_signo;
  tls->set_siginfo (this);
  sigproc_printf ("releasing sigwait for thread");
  SetEvent (tls->event);
  goto done;

exit_sig:
  if (si.si_signo == SIGQUIT || si.si_signo == SIGABRT)
    {
      CONTEXT c;
      c.ContextFlags = CONTEXT_FULL;
      GetThreadContext (hMainThread, &c);
      if (!try_to_debug ())
	stackdump (c.Ebp, 1, 1);
      si.si_signo |= 0x80;
    }
  sigproc_printf ("signal %d, about to call do_exit", si.si_signo);
  signal_exit (si.si_signo);	/* never returns */
}

/* Cover function to `do_exit' to handle exiting even in presence of more
   exceptions.  We used to call exit, but a SIGSEGV shouldn't cause atexit
   routines to run.  */
static void
signal_exit (int rc)
{
  if (hExeced)
    {
      sigproc_printf ("terminating captive process");
      TerminateProcess (hExeced, sigExeced = rc);
    }

  lock_process until_exit (true);
  if (hExeced || exit_state)
    myself.exit (rc);

  /* Starve other threads in a vain attempt to stop them from doing something
     stupid. */
  SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);

  user_data->resourcelocks->Delete ();
  user_data->resourcelocks->Init ();

  sigproc_printf ("about to call do_exit (%x)", rc);
  SetEvent (signal_arrived);
  do_exit (rc);
}

HANDLE NO_COPY tty_mutex = NULL;

void
events_init ()
{
  char *name;
  char mutex_name[CYG_MAX_PATH];
  /* tty_mutex is on while searching for a tty slot. It's necessary
     while finding console window handle */

  if (!(tty_mutex = CreateMutex (&sec_all_nih, FALSE,
				   name = shared_name (mutex_name,
						       "tty_mutex", 0))))
    api_fatal ("can't create title mutex '%s', %E", name);

  ProtectHandle (tty_mutex);
  mask_sync.init ("mask_sync");
  windows_system_directory[0] = '\0';
  GetSystemDirectory (windows_system_directory, sizeof (windows_system_directory) - 2);
  char *end = strchr (windows_system_directory, '\0');
  if (end == windows_system_directory)
    api_fatal ("can't find windows system directory");
  if (end[-1] != '\\')
    {
      *end++ = '\\';
      *end = '\0';
    }
  windows_system_directory_length = end - windows_system_directory;
  debug_printf ("windows_system_directory '%s', windows_system_directory_length %d",
		windows_system_directory, windows_system_directory_length);
}

void
events_terminate ()
{
  exit_already = 1;
}

int
_cygtls::call_signal_handler ()
{
  int this_sa_flags = 0;
  /* Call signal handler.  */
  while (sig)
    {
      lock (); unlock ();	// make sure synchronized
      this_sa_flags = sa_flags;
      int thissig = sig;

      pop ();
      reset_signal_arrived ();
      sigset_t this_oldmask = set_process_mask_delta ();
      int this_errno = saved_errno;
      incyg--;
      sig = 0;
      if (!(this_sa_flags & SA_SIGINFO))
	{
	  void (*sigfunc) (int) = func;
	  sigfunc (thissig);
	}
      else
	{
	  siginfo_t thissi = infodata;
	  void (*sigact) (int, siginfo_t *, void *) = (void (*) (int, siginfo_t *, void *)) func;
	  /* no ucontext_t information provided yet */
	  sigact (thissig, &thissi, NULL);
	}
      incyg++;
      set_signal_mask (this_oldmask, myself->getsigmask ());
      if (this_errno >= 0)
	set_errno (this_errno);
    }

  return this_sa_flags & SA_RESTART;
}

extern "C" void __stdcall
reset_signal_arrived ()
{
  // NEEDED? WaitForSingleObject (signal_arrived, 10);
  ResetEvent (signal_arrived);
  sigproc_printf ("reset signal_arrived");
  if (_my_tls.stackptr > _my_tls.stack)
    debug_printf ("stackptr[-1] %p", _my_tls.stackptr[-1]);
}