Source file src/runtime/signal_windows.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/runtime/sys"
    10  	"internal/runtime/syscall/windows"
    11  	"unsafe"
    12  )
    13  
    14  func preventErrorDialogs() {
    15  	errormode := stdcall(_GetErrorMode)
    16  	stdcall(_SetErrorMode, errormode|windows.SEM_FAILCRITICALERRORS|windows.SEM_NOGPFAULTERRORBOX|windows.SEM_NOOPENFILEERRORBOX)
    17  
    18  	// Disable WER fault reporting UI.
    19  	// Do this even if WER is disabled as a whole,
    20  	// as WER might be enabled later with setTraceback("wer")
    21  	// and we still want the fault reporting UI to be disabled if this happens.
    22  	var werflags uintptr
    23  	stdcall(_WerGetFlags, windows.CurrentProcess, uintptr(unsafe.Pointer(&werflags)))
    24  	stdcall(_WerSetFlags, werflags|windows.WER_FAULT_REPORTING_NO_UI)
    25  }
    26  
    27  // enableWER re-enables Windows error reporting without fault reporting UI.
    28  func enableWER() {
    29  	// re-enable Windows Error Reporting
    30  	errormode := stdcall(_GetErrorMode)
    31  	if errormode&windows.SEM_NOGPFAULTERRORBOX != 0 {
    32  		stdcall(_SetErrorMode, errormode^windows.SEM_NOGPFAULTERRORBOX)
    33  	}
    34  }
    35  
    36  // in sys_windows_386.s, sys_windows_amd64.s, and sys_windows_arm64.s
    37  func exceptiontramp()
    38  func firstcontinuetramp()
    39  func lastcontinuetramp()
    40  func sehtramp()
    41  func sigresume()
    42  
    43  func initExceptionHandler() {
    44  	stdcall(_AddVectoredExceptionHandler, 1, abi.FuncPCABI0(exceptiontramp))
    45  	if GOARCH == "386" {
    46  		// use SetUnhandledExceptionFilter for windows-386.
    47  		// note: SetUnhandledExceptionFilter handler won't be called, if debugging.
    48  		stdcall(_SetUnhandledExceptionFilter, abi.FuncPCABI0(lastcontinuetramp))
    49  	} else {
    50  		stdcall(_AddVectoredContinueHandler, 1, abi.FuncPCABI0(firstcontinuetramp))
    51  		stdcall(_AddVectoredContinueHandler, 0, abi.FuncPCABI0(lastcontinuetramp))
    52  	}
    53  }
    54  
    55  // isAbort returns true, if context r describes exception raised
    56  // by calling runtime.abort function.
    57  //
    58  //go:nosplit
    59  func isAbort(r *windows.Context) bool {
    60  	pc := r.PC()
    61  	if GOARCH == "386" || GOARCH == "amd64" {
    62  		// In the case of an abort, the exception IP is one byte after
    63  		// the INT3 (this differs from UNIX OSes).
    64  		pc--
    65  	}
    66  	return isAbortPC(pc)
    67  }
    68  
    69  // isgoexception reports whether this exception should be translated
    70  // into a Go panic or throw.
    71  //
    72  // It is nosplit to avoid growing the stack in case we're aborting
    73  // because of a stack overflow.
    74  //
    75  //go:nosplit
    76  func isgoexception(info *windows.ExceptionRecord, r *windows.Context) bool {
    77  	// Only handle exception if executing instructions in Go binary
    78  	// (not Windows library code).
    79  	// TODO(mwhudson): needs to loop to support shared libs
    80  	if r.PC() < firstmoduledata.text || firstmoduledata.etext < r.PC() {
    81  		return false
    82  	}
    83  
    84  	// Go will only handle some exceptions.
    85  	switch info.ExceptionCode {
    86  	default:
    87  		return false
    88  	case windows.EXCEPTION_ACCESS_VIOLATION:
    89  	case windows.EXCEPTION_IN_PAGE_ERROR:
    90  	case windows.EXCEPTION_INT_DIVIDE_BY_ZERO:
    91  	case windows.EXCEPTION_INT_OVERFLOW:
    92  	case windows.EXCEPTION_FLT_DENORMAL_OPERAND:
    93  	case windows.EXCEPTION_FLT_DIVIDE_BY_ZERO:
    94  	case windows.EXCEPTION_FLT_INEXACT_RESULT:
    95  	case windows.EXCEPTION_FLT_OVERFLOW:
    96  	case windows.EXCEPTION_FLT_UNDERFLOW:
    97  	case windows.EXCEPTION_BREAKPOINT:
    98  	case windows.EXCEPTION_ILLEGAL_INSTRUCTION: // breakpoint arrives this way on arm64
    99  	}
   100  	return true
   101  }
   102  
   103  const (
   104  	callbackVEH = iota
   105  	callbackFirstVCH
   106  	callbackLastVCH
   107  )
   108  
   109  // sigFetchGSafe is like getg() but without panicking
   110  // when TLS is not set.
   111  // Only implemented on windows/386, which is the only
   112  // arch that loads TLS when calling getg(). Others
   113  // use a dedicated register.
   114  func sigFetchGSafe() *g
   115  
   116  func sigFetchG() *g {
   117  	if GOARCH == "386" {
   118  		return sigFetchGSafe()
   119  	}
   120  	return getg()
   121  }
   122  
   123  // sigtrampgo is called from the exception handler function, sigtramp,
   124  // written in assembly code.
   125  // Return EXCEPTION_CONTINUE_EXECUTION if the exception is handled,
   126  // else return EXCEPTION_CONTINUE_SEARCH.
   127  //
   128  // It is nosplit for the same reason as exceptionhandler.
   129  //
   130  //go:nosplit
   131  func sigtrampgo(ep *windows.ExceptionPointers, kind int) int32 {
   132  	gp := sigFetchG()
   133  	if gp == nil {
   134  		return windows.EXCEPTION_CONTINUE_SEARCH
   135  	}
   136  
   137  	// Windows delivers exceptions on the faulting goroutine's own stack. If the
   138  	// OS wrote past the bottom of that stack, the neighboring goroutine's stack
   139  	// is already corrupted, so crash now instead of running on bad memory.
   140  	if gp != gp.m.g0 && gp.stack.lo != 0 && sys.GetCallerSP() < gp.stack.lo {
   141  		throw("exception dispatched below goroutine stack bottom")
   142  	}
   143  
   144  	var fn func(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32
   145  	switch kind {
   146  	case callbackVEH:
   147  		fn = exceptionhandler
   148  	case callbackFirstVCH:
   149  		fn = firstcontinuehandler
   150  	case callbackLastVCH:
   151  		fn = lastcontinuehandler
   152  	default:
   153  		throw("unknown sigtramp callback")
   154  	}
   155  
   156  	// Check if we are running on g0 stack, and if we are,
   157  	// call fn directly instead of creating the closure.
   158  	// for the systemstack argument.
   159  	//
   160  	// A closure can't be marked as nosplit, so it might
   161  	// call morestack if we are at the g0 stack limit.
   162  	// If that happens, the runtime will call abort
   163  	// and end up in sigtrampgo again.
   164  	// TODO: revisit this workaround if/when closures
   165  	// can be compiled as nosplit.
   166  	//
   167  	// Note that this scenario should only occur on
   168  	// TestG0StackOverflow. Any other occurrence should
   169  	// be treated as a bug.
   170  	var ret int32
   171  	if gp != gp.m.g0 {
   172  		systemstack(func() {
   173  			ret = fn(ep.Record, ep.Context, gp)
   174  		})
   175  	} else {
   176  		ret = fn(ep.Record, ep.Context, gp)
   177  	}
   178  	if ret == windows.EXCEPTION_CONTINUE_SEARCH {
   179  		return ret
   180  	}
   181  
   182  	// Check if we need to set up the control flow guard workaround.
   183  	// On Windows, the stack pointer in the context must lie within
   184  	// system stack limits when we resume from exception.
   185  	// Store the resume SP and PC in alternate registers
   186  	// and return to sigresume on the g0 stack.
   187  	// sigresume makes no use of the stack at all,
   188  	// loading SP from RX and jumping to RY, being RX and RY two scratch registers.
   189  	// Note that blindly smashing RX and RY is only safe because we know sigpanic
   190  	// will not actually return to the original frame, so the registers
   191  	// are effectively dead. But this does mean we can't use the
   192  	// same mechanism for async preemption.
   193  	if ep.Context.PC() == abi.FuncPCABI0(sigresume) {
   194  		// sigresume has already been set up by a previous exception.
   195  		return ret
   196  	}
   197  	prepareContextForSigResume(ep.Context)
   198  	ep.Context.SetSP(gp.m.g0.sched.sp)
   199  	ep.Context.SetPC(abi.FuncPCABI0(sigresume))
   200  	return ret
   201  }
   202  
   203  // Called by sigtramp from Windows VEH handler.
   204  // Return value signals whether the exception has been handled (EXCEPTION_CONTINUE_EXECUTION)
   205  // or should be made available to other handlers in the chain (EXCEPTION_CONTINUE_SEARCH).
   206  //
   207  // This is nosplit to avoid growing the stack until we've checked for
   208  // _EXCEPTION_BREAKPOINT, which is raised by abort() if we overflow the g0 stack.
   209  //
   210  //go:nosplit
   211  func exceptionhandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   212  	if !isgoexception(info, r) {
   213  		return windows.EXCEPTION_CONTINUE_SEARCH
   214  	}
   215  
   216  	if gp.throwsplit || isAbort(r) {
   217  		// We can't safely sigpanic because it may grow the stack.
   218  		// Or this is a call to abort.
   219  		// Don't go through any more of the Windows handler chain.
   220  		// Crash now.
   221  		winthrow(info, r, gp)
   222  	}
   223  
   224  	// After this point, it is safe to grow the stack.
   225  
   226  	// Make it look like a call to the signal func.
   227  	// Have to pass arguments out of band since
   228  	// augmenting the stack frame would break
   229  	// the unwinding code.
   230  	gp.sig = info.ExceptionCode
   231  	gp.sigcode0 = info.ExceptionInformation[0]
   232  	gp.sigcode1 = info.ExceptionInformation[1]
   233  	gp.sigpc = r.PC()
   234  
   235  	// Only push runtime·sigpanic if r.ip() != 0.
   236  	// If r.ip() == 0, probably panicked because of a
   237  	// call to a nil func. Not pushing that onto sp will
   238  	// make the trace look like a call to runtime·sigpanic instead.
   239  	// (Otherwise the trace will end at runtime·sigpanic and we
   240  	// won't get to see who faulted.)
   241  	// Also don't push a sigpanic frame if the faulting PC
   242  	// is the entry of asyncPreempt. In this case, we suspended
   243  	// the thread right between the fault and the exception handler
   244  	// starting to run, and we have pushed an asyncPreempt call.
   245  	// The exception is not from asyncPreempt, so not to push a
   246  	// sigpanic call to make it look like that. Instead, just
   247  	// overwrite the PC. (See issue #35773)
   248  	if r.PC() != 0 && r.PC() != abi.FuncPCABI0(asyncPreempt) {
   249  		r.PushCall(abi.FuncPCABI0(sigpanic0), r.PC())
   250  	} else {
   251  		// Not safe to push the call. Just clobber the frame.
   252  		r.SetPC(abi.FuncPCABI0(sigpanic0))
   253  	}
   254  	return windows.EXCEPTION_CONTINUE_EXECUTION
   255  }
   256  
   257  // sehhandler is reached as part of the SEH chain.
   258  //
   259  // It is nosplit for the same reason as exceptionhandler.
   260  //
   261  //go:nosplit
   262  func sehhandler(_ *windows.ExceptionRecord, _ uint64, _ *windows.Context, dctxt *windows.DISPATCHER_CONTEXT) int32 {
   263  	g0 := getg()
   264  	if g0 == nil || g0.m.curg == nil {
   265  		// No g available, nothing to do here.
   266  		return windows.EXCEPTION_CONTINUE_SEARCH_SEH
   267  	}
   268  	// The Windows SEH machinery will unwind the stack until it finds
   269  	// a frame with a handler for the exception or until the frame is
   270  	// outside the stack boundaries, in which case it will call the
   271  	// UnhandledExceptionFilter. Unfortunately, it doesn't know about
   272  	// the goroutine stack, so it will stop unwinding when it reaches the
   273  	// first frame not running in g0. As a result, neither non-Go exceptions
   274  	// handlers higher up the stack nor UnhandledExceptionFilter will be called.
   275  	//
   276  	// To work around this, manually unwind the stack until the top of the goroutine
   277  	// stack is reached, and then pass the control back to Windows.
   278  	gp := g0.m.curg
   279  	ctxt := dctxt.Ctx()
   280  	var base, sp uintptr
   281  	for {
   282  		entry := stdcall(_RtlLookupFunctionEntry, ctxt.PC(), uintptr(unsafe.Pointer(&base)), 0)
   283  		if entry == 0 {
   284  			break
   285  		}
   286  		stdcall(_RtlVirtualUnwind, 0, base, ctxt.PC(), entry, uintptr(unsafe.Pointer(ctxt)), 0, uintptr(unsafe.Pointer(&sp)), 0)
   287  		if sp < gp.stack.lo || gp.stack.hi <= sp {
   288  			break
   289  		}
   290  	}
   291  	return windows.EXCEPTION_CONTINUE_SEARCH_SEH
   292  }
   293  
   294  // It seems Windows searches ContinueHandler's list even
   295  // if ExceptionHandler returns EXCEPTION_CONTINUE_EXECUTION.
   296  // firstcontinuehandler will stop that search,
   297  // if exceptionhandler did the same earlier.
   298  //
   299  // It is nosplit for the same reason as exceptionhandler.
   300  //
   301  //go:nosplit
   302  func firstcontinuehandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   303  	if !isgoexception(info, r) {
   304  		return windows.EXCEPTION_CONTINUE_SEARCH
   305  	}
   306  	return windows.EXCEPTION_CONTINUE_EXECUTION
   307  }
   308  
   309  // lastcontinuehandler is reached, because runtime cannot handle
   310  // current exception. lastcontinuehandler will print crash info and exit.
   311  //
   312  // It is nosplit for the same reason as exceptionhandler.
   313  //
   314  //go:nosplit
   315  func lastcontinuehandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   316  	if islibrary || isarchive {
   317  		// Go DLL/archive has been loaded in a non-go program.
   318  		// If the exception does not originate from go, the go runtime
   319  		// should not take responsibility of crashing the process.
   320  		return windows.EXCEPTION_CONTINUE_SEARCH
   321  	}
   322  
   323  	// VEH is called before SEH, but arm64 MSVC DLLs use SEH to trap
   324  	// illegal instructions during runtime initialization to determine
   325  	// CPU features, so if we make it to the last handler and we're
   326  	// arm64 and it's an illegal instruction and this is coming from
   327  	// non-Go code, then assume it's this runtime probing happen, and
   328  	// pass that onward to SEH.
   329  	if GOARCH == "arm64" && info.ExceptionCode == windows.EXCEPTION_ILLEGAL_INSTRUCTION &&
   330  		(r.PC() < firstmoduledata.text || firstmoduledata.etext < r.PC()) {
   331  		return windows.EXCEPTION_CONTINUE_SEARCH
   332  	}
   333  
   334  	winthrow(info, r, gp)
   335  	return 0 // not reached
   336  }
   337  
   338  // Always called on g0. gp is the G where the exception occurred.
   339  //
   340  //go:nosplit
   341  func winthrow(info *windows.ExceptionRecord, r *windows.Context, gp *g) {
   342  	g0 := getg()
   343  
   344  	if panicking.Load() != 0 { // traceback already printed
   345  		exit(2)
   346  	}
   347  	panicking.Store(1)
   348  
   349  	// In case we're handling a g0 stack overflow, blow away the
   350  	// g0 stack bounds so we have room to print the traceback. If
   351  	// this somehow overflows the stack, the OS will trap it.
   352  	g0.stack.lo = 0
   353  	g0.stackguard0 = g0.stack.lo + stackGuard
   354  	g0.stackguard1 = g0.stackguard0
   355  
   356  	print("Exception ", hex(info.ExceptionCode), " ", hex(info.ExceptionInformation[0]), " ", hex(info.ExceptionInformation[1]), " ", hex(r.PC()), "\n")
   357  
   358  	print("PC=", hex(r.PC()), "\n")
   359  	if g0.m.incgo && gp == g0.m.g0 && g0.m.curg != nil {
   360  		if iscgo {
   361  			print("signal arrived during external code execution\n")
   362  		}
   363  		gp = g0.m.curg
   364  	}
   365  	print("\n")
   366  
   367  	g0.m.throwing = throwTypeRuntime
   368  	g0.m.caughtsig.set(gp)
   369  
   370  	level, _, docrash := gotraceback()
   371  	if level > 0 {
   372  		tracebacktrap(r.PC(), r.SP(), r.LR(), gp)
   373  		tracebackothers(gp)
   374  		dumpregs(r)
   375  	}
   376  
   377  	if docrash {
   378  		dieFromException(info, r)
   379  	}
   380  
   381  	exit(2)
   382  }
   383  
   384  func sigpanic() {
   385  	gp := getg()
   386  	if !canpanic() {
   387  		throw("unexpected signal during runtime execution")
   388  	}
   389  
   390  	switch gp.sig {
   391  	case windows.EXCEPTION_ACCESS_VIOLATION, windows.EXCEPTION_IN_PAGE_ERROR:
   392  		if gp.sigcode1 < 0x1000 {
   393  			panicmem()
   394  		}
   395  		if gp.paniconfault {
   396  			panicmemAddr(gp.sigcode1)
   397  		}
   398  		if inUserArenaChunk(gp.sigcode1) {
   399  			// We could check that the arena chunk is explicitly set to fault,
   400  			// but the fact that we faulted on accessing it is enough to prove
   401  			// that it is.
   402  			print("accessed data from freed user arena ", hex(gp.sigcode1), "\n")
   403  		} else {
   404  			print("unexpected fault address ", hex(gp.sigcode1), "\n")
   405  		}
   406  		throw("fault")
   407  	case windows.EXCEPTION_INT_DIVIDE_BY_ZERO:
   408  		panicdivide()
   409  	case windows.EXCEPTION_INT_OVERFLOW:
   410  		panicoverflow()
   411  	case windows.EXCEPTION_FLT_DENORMAL_OPERAND,
   412  		windows.EXCEPTION_FLT_DIVIDE_BY_ZERO,
   413  		windows.EXCEPTION_FLT_INEXACT_RESULT,
   414  		windows.EXCEPTION_FLT_OVERFLOW,
   415  		windows.EXCEPTION_FLT_UNDERFLOW:
   416  		panicfloat()
   417  	}
   418  	throw("fault")
   419  }
   420  
   421  // Following are not implemented.
   422  
   423  func initsig(preinit bool) {
   424  }
   425  
   426  func sigenable(sig uint32) {
   427  }
   428  
   429  func sigdisable(sig uint32) {
   430  }
   431  
   432  func sigignore(sig uint32) {
   433  }
   434  
   435  func signame(sig uint32) string {
   436  	return ""
   437  }
   438  
   439  //go:nosplit
   440  func crash() {
   441  	dieFromException(nil, nil)
   442  }
   443  
   444  // dieFromException raises an exception that bypasses all exception handlers.
   445  // This provides the expected exit status for the shell.
   446  //
   447  //go:nosplit
   448  func dieFromException(info *windows.ExceptionRecord, r *windows.Context) {
   449  	if info == nil {
   450  		gp := getg()
   451  		if gp.sig != 0 {
   452  			// Try to reconstruct an exception record from
   453  			// the exception information stored in gp.
   454  			info = &windows.ExceptionRecord{
   455  				ExceptionAddress: gp.sigpc,
   456  				ExceptionCode:    gp.sig,
   457  				NumberParameters: 2,
   458  			}
   459  			info.ExceptionInformation[0] = gp.sigcode0
   460  			info.ExceptionInformation[1] = gp.sigcode1
   461  		} else {
   462  			// By default, a failing Go application exits with exit code 2.
   463  			// Use this value when gp does not contain exception info.
   464  			info = &windows.ExceptionRecord{
   465  				ExceptionCode: 2,
   466  			}
   467  		}
   468  	}
   469  	stdcall(_RaiseFailFastException, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(r)), windows.FAIL_FAST_GENERATE_EXCEPTION_ADDRESS)
   470  }
   471  
   472  // gsignalStack is unused on Windows.
   473  type gsignalStack struct{}
   474  

View as plain text