Help us shape the future of Go! Take the 2026 Go Developer Survey

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  // sigtrampgo is called from the exception handler function, sigtramp,
   110  // written in assembly code.
   111  // Return EXCEPTION_CONTINUE_EXECUTION if the exception is handled,
   112  // else return EXCEPTION_CONTINUE_SEARCH.
   113  //
   114  // It is nosplit for the same reason as exceptionhandler.
   115  //
   116  //go:nosplit
   117  func sigtrampgo(ep *windows.ExceptionPointers, kind int) int32 {
   118  	gp := getg()
   119  	if gp == nil {
   120  		return windows.EXCEPTION_CONTINUE_SEARCH
   121  	}
   122  
   123  	// Windows delivers exceptions on the faulting goroutine's own stack. If the
   124  	// OS wrote past the bottom of that stack, the neighboring goroutine's stack
   125  	// is already corrupted, so crash now instead of running on bad memory.
   126  	if gp != gp.m.g0 && gp.stack.lo != 0 && sys.GetCallerSP() < gp.stack.lo {
   127  		throw("exception dispatched below goroutine stack bottom")
   128  	}
   129  
   130  	var fn func(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32
   131  	switch kind {
   132  	case callbackVEH:
   133  		fn = exceptionhandler
   134  	case callbackFirstVCH:
   135  		fn = firstcontinuehandler
   136  	case callbackLastVCH:
   137  		fn = lastcontinuehandler
   138  	default:
   139  		throw("unknown sigtramp callback")
   140  	}
   141  
   142  	// Check if we are running on g0 stack, and if we are,
   143  	// call fn directly instead of creating the closure.
   144  	// for the systemstack argument.
   145  	//
   146  	// A closure can't be marked as nosplit, so it might
   147  	// call morestack if we are at the g0 stack limit.
   148  	// If that happens, the runtime will call abort
   149  	// and end up in sigtrampgo again.
   150  	// TODO: revisit this workaround if/when closures
   151  	// can be compiled as nosplit.
   152  	//
   153  	// Note that this scenario should only occur on
   154  	// TestG0StackOverflow. Any other occurrence should
   155  	// be treated as a bug.
   156  	var ret int32
   157  	if gp != gp.m.g0 {
   158  		systemstack(func() {
   159  			ret = fn(ep.Record, ep.Context, gp)
   160  		})
   161  	} else {
   162  		ret = fn(ep.Record, ep.Context, gp)
   163  	}
   164  	if ret == windows.EXCEPTION_CONTINUE_SEARCH {
   165  		return ret
   166  	}
   167  
   168  	// Check if we need to set up the control flow guard workaround.
   169  	// On Windows, the stack pointer in the context must lie within
   170  	// system stack limits when we resume from exception.
   171  	// Store the resume SP and PC in alternate registers
   172  	// and return to sigresume on the g0 stack.
   173  	// sigresume makes no use of the stack at all,
   174  	// loading SP from RX and jumping to RY, being RX and RY two scratch registers.
   175  	// Note that blindly smashing RX and RY is only safe because we know sigpanic
   176  	// will not actually return to the original frame, so the registers
   177  	// are effectively dead. But this does mean we can't use the
   178  	// same mechanism for async preemption.
   179  	if ep.Context.PC() == abi.FuncPCABI0(sigresume) {
   180  		// sigresume has already been set up by a previous exception.
   181  		return ret
   182  	}
   183  	prepareContextForSigResume(ep.Context)
   184  	ep.Context.SetSP(gp.m.g0.sched.sp)
   185  	ep.Context.SetPC(abi.FuncPCABI0(sigresume))
   186  	return ret
   187  }
   188  
   189  // Called by sigtramp from Windows VEH handler.
   190  // Return value signals whether the exception has been handled (EXCEPTION_CONTINUE_EXECUTION)
   191  // or should be made available to other handlers in the chain (EXCEPTION_CONTINUE_SEARCH).
   192  //
   193  // This is nosplit to avoid growing the stack until we've checked for
   194  // _EXCEPTION_BREAKPOINT, which is raised by abort() if we overflow the g0 stack.
   195  //
   196  //go:nosplit
   197  func exceptionhandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   198  	if !isgoexception(info, r) {
   199  		return windows.EXCEPTION_CONTINUE_SEARCH
   200  	}
   201  
   202  	if gp.throwsplit || isAbort(r) {
   203  		// We can't safely sigpanic because it may grow the stack.
   204  		// Or this is a call to abort.
   205  		// Don't go through any more of the Windows handler chain.
   206  		// Crash now.
   207  		winthrow(info, r, gp)
   208  	}
   209  
   210  	// After this point, it is safe to grow the stack.
   211  
   212  	// Make it look like a call to the signal func.
   213  	// Have to pass arguments out of band since
   214  	// augmenting the stack frame would break
   215  	// the unwinding code.
   216  	gp.sig = info.ExceptionCode
   217  	gp.sigcode0 = info.ExceptionInformation[0]
   218  	gp.sigcode1 = info.ExceptionInformation[1]
   219  	gp.sigpc = r.PC()
   220  
   221  	// Only push runtime·sigpanic if r.ip() != 0.
   222  	// If r.ip() == 0, probably panicked because of a
   223  	// call to a nil func. Not pushing that onto sp will
   224  	// make the trace look like a call to runtime·sigpanic instead.
   225  	// (Otherwise the trace will end at runtime·sigpanic and we
   226  	// won't get to see who faulted.)
   227  	// Also don't push a sigpanic frame if the faulting PC
   228  	// is the entry of asyncPreempt. In this case, we suspended
   229  	// the thread right between the fault and the exception handler
   230  	// starting to run, and we have pushed an asyncPreempt call.
   231  	// The exception is not from asyncPreempt, so not to push a
   232  	// sigpanic call to make it look like that. Instead, just
   233  	// overwrite the PC. (See issue #35773)
   234  	if r.PC() != 0 && r.PC() != abi.FuncPCABI0(asyncPreempt) {
   235  		r.PushCall(abi.FuncPCABI0(sigpanic0), r.PC())
   236  	} else {
   237  		// Not safe to push the call. Just clobber the frame.
   238  		r.SetPC(abi.FuncPCABI0(sigpanic0))
   239  	}
   240  	return windows.EXCEPTION_CONTINUE_EXECUTION
   241  }
   242  
   243  // sehhandler is reached as part of the SEH chain.
   244  //
   245  // It is nosplit for the same reason as exceptionhandler.
   246  //
   247  //go:nosplit
   248  func sehhandler(_ *windows.ExceptionRecord, _ uint64, _ *windows.Context, dctxt *windows.DISPATCHER_CONTEXT) int32 {
   249  	g0 := getg()
   250  	if g0 == nil || g0.m.curg == nil {
   251  		// No g available, nothing to do here.
   252  		return windows.EXCEPTION_CONTINUE_SEARCH_SEH
   253  	}
   254  	// The Windows SEH machinery will unwind the stack until it finds
   255  	// a frame with a handler for the exception or until the frame is
   256  	// outside the stack boundaries, in which case it will call the
   257  	// UnhandledExceptionFilter. Unfortunately, it doesn't know about
   258  	// the goroutine stack, so it will stop unwinding when it reaches the
   259  	// first frame not running in g0. As a result, neither non-Go exceptions
   260  	// handlers higher up the stack nor UnhandledExceptionFilter will be called.
   261  	//
   262  	// To work around this, manually unwind the stack until the top of the goroutine
   263  	// stack is reached, and then pass the control back to Windows.
   264  	gp := g0.m.curg
   265  	ctxt := dctxt.Ctx()
   266  	var base, sp uintptr
   267  	for {
   268  		entry := stdcall(_RtlLookupFunctionEntry, ctxt.PC(), uintptr(unsafe.Pointer(&base)), 0)
   269  		if entry == 0 {
   270  			break
   271  		}
   272  		stdcall(_RtlVirtualUnwind, 0, base, ctxt.PC(), entry, uintptr(unsafe.Pointer(ctxt)), 0, uintptr(unsafe.Pointer(&sp)), 0)
   273  		if sp < gp.stack.lo || gp.stack.hi <= sp {
   274  			break
   275  		}
   276  	}
   277  	return windows.EXCEPTION_CONTINUE_SEARCH_SEH
   278  }
   279  
   280  // It seems Windows searches ContinueHandler's list even
   281  // if ExceptionHandler returns EXCEPTION_CONTINUE_EXECUTION.
   282  // firstcontinuehandler will stop that search,
   283  // if exceptionhandler did the same earlier.
   284  //
   285  // It is nosplit for the same reason as exceptionhandler.
   286  //
   287  //go:nosplit
   288  func firstcontinuehandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   289  	if !isgoexception(info, r) {
   290  		return windows.EXCEPTION_CONTINUE_SEARCH
   291  	}
   292  	return windows.EXCEPTION_CONTINUE_EXECUTION
   293  }
   294  
   295  // lastcontinuehandler is reached, because runtime cannot handle
   296  // current exception. lastcontinuehandler will print crash info and exit.
   297  //
   298  // It is nosplit for the same reason as exceptionhandler.
   299  //
   300  //go:nosplit
   301  func lastcontinuehandler(info *windows.ExceptionRecord, r *windows.Context, gp *g) int32 {
   302  	if islibrary || isarchive {
   303  		// Go DLL/archive has been loaded in a non-go program.
   304  		// If the exception does not originate from go, the go runtime
   305  		// should not take responsibility of crashing the process.
   306  		return windows.EXCEPTION_CONTINUE_SEARCH
   307  	}
   308  
   309  	// VEH is called before SEH, but arm64 MSVC DLLs use SEH to trap
   310  	// illegal instructions during runtime initialization to determine
   311  	// CPU features, so if we make it to the last handler and we're
   312  	// arm64 and it's an illegal instruction and this is coming from
   313  	// non-Go code, then assume it's this runtime probing happen, and
   314  	// pass that onward to SEH.
   315  	if GOARCH == "arm64" && info.ExceptionCode == windows.EXCEPTION_ILLEGAL_INSTRUCTION &&
   316  		(r.PC() < firstmoduledata.text || firstmoduledata.etext < r.PC()) {
   317  		return windows.EXCEPTION_CONTINUE_SEARCH
   318  	}
   319  
   320  	winthrow(info, r, gp)
   321  	return 0 // not reached
   322  }
   323  
   324  // Always called on g0. gp is the G where the exception occurred.
   325  //
   326  //go:nosplit
   327  func winthrow(info *windows.ExceptionRecord, r *windows.Context, gp *g) {
   328  	g0 := getg()
   329  
   330  	if panicking.Load() != 0 { // traceback already printed
   331  		exit(2)
   332  	}
   333  	panicking.Store(1)
   334  
   335  	// In case we're handling a g0 stack overflow, blow away the
   336  	// g0 stack bounds so we have room to print the traceback. If
   337  	// this somehow overflows the stack, the OS will trap it.
   338  	g0.stack.lo = 0
   339  	g0.stackguard0 = g0.stack.lo + stackGuard
   340  	g0.stackguard1 = g0.stackguard0
   341  
   342  	print("Exception ", hex(info.ExceptionCode), " ", hex(info.ExceptionInformation[0]), " ", hex(info.ExceptionInformation[1]), " ", hex(r.PC()), "\n")
   343  
   344  	print("PC=", hex(r.PC()), "\n")
   345  	if g0.m.incgo && gp == g0.m.g0 && g0.m.curg != nil {
   346  		if iscgo {
   347  			print("signal arrived during external code execution\n")
   348  		}
   349  		gp = g0.m.curg
   350  	}
   351  	print("\n")
   352  
   353  	g0.m.throwing = throwTypeRuntime
   354  	g0.m.caughtsig.set(gp)
   355  
   356  	level, _, docrash := gotraceback()
   357  	if level > 0 {
   358  		tracebacktrap(r.PC(), r.SP(), r.LR(), gp)
   359  		tracebackothers(gp)
   360  		dumpregs(r)
   361  	}
   362  
   363  	if docrash {
   364  		dieFromException(info, r)
   365  	}
   366  
   367  	exit(2)
   368  }
   369  
   370  func sigpanic() {
   371  	gp := getg()
   372  	if !canpanic() {
   373  		throw("unexpected signal during runtime execution")
   374  	}
   375  
   376  	switch gp.sig {
   377  	case windows.EXCEPTION_ACCESS_VIOLATION, windows.EXCEPTION_IN_PAGE_ERROR:
   378  		if gp.sigcode1 < 0x1000 {
   379  			panicmem()
   380  		}
   381  		if gp.paniconfault {
   382  			panicmemAddr(gp.sigcode1)
   383  		}
   384  		if inUserArenaChunk(gp.sigcode1) {
   385  			// We could check that the arena chunk is explicitly set to fault,
   386  			// but the fact that we faulted on accessing it is enough to prove
   387  			// that it is.
   388  			print("accessed data from freed user arena ", hex(gp.sigcode1), "\n")
   389  		} else {
   390  			print("unexpected fault address ", hex(gp.sigcode1), "\n")
   391  		}
   392  		throw("fault")
   393  	case windows.EXCEPTION_INT_DIVIDE_BY_ZERO:
   394  		panicdivide()
   395  	case windows.EXCEPTION_INT_OVERFLOW:
   396  		panicoverflow()
   397  	case windows.EXCEPTION_FLT_DENORMAL_OPERAND,
   398  		windows.EXCEPTION_FLT_DIVIDE_BY_ZERO,
   399  		windows.EXCEPTION_FLT_INEXACT_RESULT,
   400  		windows.EXCEPTION_FLT_OVERFLOW,
   401  		windows.EXCEPTION_FLT_UNDERFLOW:
   402  		panicfloat()
   403  	}
   404  	throw("fault")
   405  }
   406  
   407  // Following are not implemented.
   408  
   409  func initsig(preinit bool) {
   410  }
   411  
   412  func sigenable(sig uint32) {
   413  }
   414  
   415  func sigdisable(sig uint32) {
   416  }
   417  
   418  func sigignore(sig uint32) {
   419  }
   420  
   421  func signame(sig uint32) string {
   422  	return ""
   423  }
   424  
   425  //go:nosplit
   426  func crash() {
   427  	dieFromException(nil, nil)
   428  }
   429  
   430  // dieFromException raises an exception that bypasses all exception handlers.
   431  // This provides the expected exit status for the shell.
   432  //
   433  //go:nosplit
   434  func dieFromException(info *windows.ExceptionRecord, r *windows.Context) {
   435  	if info == nil {
   436  		gp := getg()
   437  		if gp.sig != 0 {
   438  			// Try to reconstruct an exception record from
   439  			// the exception information stored in gp.
   440  			info = &windows.ExceptionRecord{
   441  				ExceptionAddress: gp.sigpc,
   442  				ExceptionCode:    gp.sig,
   443  				NumberParameters: 2,
   444  			}
   445  			info.ExceptionInformation[0] = gp.sigcode0
   446  			info.ExceptionInformation[1] = gp.sigcode1
   447  		} else {
   448  			// By default, a failing Go application exits with exit code 2.
   449  			// Use this value when gp does not contain exception info.
   450  			info = &windows.ExceptionRecord{
   451  				ExceptionCode: 2,
   452  			}
   453  		}
   454  	}
   455  	stdcall(_RaiseFailFastException, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(r)), windows.FAIL_FAST_GENERATE_EXCEPTION_ADDRESS)
   456  }
   457  
   458  // gsignalStack is unused on Windows.
   459  type gsignalStack struct{}
   460  

View as plain text