Debian Codegraph @

src/runtime/signal_windows.go

raw
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 "unsafe"
10 )
11
12 const (
13 _SEM_FAILCRITICALERRORS = 0x0001
14 _SEM_NOGPFAULTERRORBOX = 0x0002
15 _SEM_NOOPENFILEERRORBOX = 0x8000
16
17 _WER_FAULT_REPORTING_NO_UI = 0x0020
18 )
19
20 func preventErrorDialogs() {
21 errormode := stdcall0(_GetErrorMode)
22 stdcall1(_SetErrorMode, errormode|_SEM_FAILCRITICALERRORS|_SEM_NOGPFAULTERRORBOX|_SEM_NOOPENFILEERRORBOX)
23
24 // Disable WER fault reporting UI.
25 // Do this even if WER is disabled as a whole,
26 // as WER might be enabled later with setTraceback("wer")
27 // and we still want the fault reporting UI to be disabled if this happens.
28 var werflags uintptr
29 stdcall2(_WerGetFlags, currentProcess, uintptr(unsafe.Pointer(&werflags)))
30 stdcall1(_WerSetFlags, werflags|_WER_FAULT_REPORTING_NO_UI)
31 }
32
33 // enableWER re-enables Windows error reporting without fault reporting UI.
34 func enableWER() {
35 // re-enable Windows Error Reporting
36 errormode := stdcall0(_GetErrorMode)
37 if errormode&_SEM_NOGPFAULTERRORBOX != 0 {
38 stdcall1(_SetErrorMode, errormode^_SEM_NOGPFAULTERRORBOX)
39 }
40 }
41
42 // in sys_windows_386.s, sys_windows_amd64.s, sys_windows_arm.s, and sys_windows_arm64.s
43 func exceptiontramp()
44 func firstcontinuetramp()
45 func lastcontinuetramp()
46 func sehtramp()
47 func sigresume()
48
49 func initExceptionHandler() {
50 stdcall2(_AddVectoredExceptionHandler, 1, abi.FuncPCABI0(exceptiontramp))
51 if GOARCH == "386" {
52 // use SetUnhandledExceptionFilter for windows-386.
53 // note: SetUnhandledExceptionFilter handler won't be called, if debugging.
54 stdcall1(_SetUnhandledExceptionFilter, abi.FuncPCABI0(lastcontinuetramp))
55 } else {
56 stdcall2(_AddVectoredContinueHandler, 1, abi.FuncPCABI0(firstcontinuetramp))
57 stdcall2(_AddVectoredContinueHandler, 0, abi.FuncPCABI0(lastcontinuetramp))
58 }
59 }
60
61 // isAbort returns true, if context r describes exception raised
62 // by calling runtime.abort function.
63 //
64 //go:nosplit
65 func isAbort(r *context) bool {
66 pc := r.ip()
67 if GOARCH == "386" || GOARCH == "amd64" || GOARCH == "arm" {
68 // In the case of an abort, the exception IP is one byte after
69 // the INT3 (this differs from UNIX OSes). Note that on ARM,
70 // this means that the exception IP is no longer aligned.
71 pc--
72 }
73 return isAbortPC(pc)
74 }
75
76 // isgoexception reports whether this exception should be translated
77 // into a Go panic or throw.
78 //
79 // It is nosplit to avoid growing the stack in case we're aborting
80 // because of a stack overflow.
81 //
82 //go:nosplit
83 func isgoexception(info *exceptionrecord, r *context) bool {
84 // Only handle exception if executing instructions in Go binary
85 // (not Windows library code).
86 // TODO(mwhudson): needs to loop to support shared libs
87 if r.ip() < firstmoduledata.text || firstmoduledata.etext < r.ip() {
88 return false
89 }
90
91 // Go will only handle some exceptions.
92 switch info.exceptioncode {
93 default:
94 return false
95 case _EXCEPTION_ACCESS_VIOLATION:
96 case _EXCEPTION_IN_PAGE_ERROR:
97 case _EXCEPTION_INT_DIVIDE_BY_ZERO:
98 case _EXCEPTION_INT_OVERFLOW:
99 case _EXCEPTION_FLT_DENORMAL_OPERAND:
100 case _EXCEPTION_FLT_DIVIDE_BY_ZERO:
101 case _EXCEPTION_FLT_INEXACT_RESULT:
102 case _EXCEPTION_FLT_OVERFLOW:
103 case _EXCEPTION_FLT_UNDERFLOW:
104 case _EXCEPTION_BREAKPOINT:
105 case _EXCEPTION_ILLEGAL_INSTRUCTION: // breakpoint arrives this way on arm64
106 }
107 return true
108 }
109
110 const (
111 callbackVEH = iota
112 callbackFirstVCH
113 callbackLastVCH
114 )
115
116 // sigFetchGSafe is like getg() but without panicking
117 // when TLS is not set.
118 // Only implemented on windows/386, which is the only
119 // arch that loads TLS when calling getg(). Others
120 // use a dedicated register.
121 func sigFetchGSafe() *g
122
123 func sigFetchG() *g {
124 if GOARCH == "386" {
125 return sigFetchGSafe()
126 }
127 return getg()
128 }
129
130 // sigtrampgo is called from the exception handler function, sigtramp,
131 // written in assembly code.
132 // Return EXCEPTION_CONTINUE_EXECUTION if the exception is handled,
133 // else return EXCEPTION_CONTINUE_SEARCH.
134 //
135 // It is nosplit for the same reason as exceptionhandler.
136 //
137 //go:nosplit
138 func sigtrampgo(ep *exceptionpointers, kind int) int32 {
139 gp := sigFetchG()
140 if gp == nil {
141 return _EXCEPTION_CONTINUE_SEARCH
142 }
143
144 var fn func(info *exceptionrecord, r *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 == _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.ip() == 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.set_sp(gp.m.g0.sched.sp)
199 ep.context.set_ip(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 *exceptionrecord, r *context, gp *g) int32 {
212 if !isgoexception(info, r) {
213 return _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.ip()
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.ip() != 0 && r.ip() != abi.FuncPCABI0(asyncPreempt) {
249 r.pushCall(abi.FuncPCABI0(sigpanic0), r.ip())
250 } else {
251 // Not safe to push the call. Just clobber the frame.
252 r.set_ip(abi.FuncPCABI0(sigpanic0))
253 }
254 return _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(_ *exceptionrecord, _ uint64, _ *context, dctxt *_DISPATCHER_CONTEXT) int32 {
263 g0 := getg()
264 if g0 == nil || g0.m.curg == nil {
265 // No g available, nothing to do here.
266 return _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 := stdcall3(_RtlLookupFunctionEntry, ctxt.ip(), uintptr(unsafe.Pointer(&base)), 0)
283 if entry == 0 {
284 break
285 }
286 stdcall8(_RtlVirtualUnwind, 0, base, ctxt.ip(), 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 _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 *exceptionrecord, r *context, gp *g) int32 {
303 if !isgoexception(info, r) {
304 return _EXCEPTION_CONTINUE_SEARCH
305 }
306 return _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 *exceptionrecord, r *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 _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 == _EXCEPTION_ILLEGAL_INSTRUCTION &&
330 (r.ip() < firstmoduledata.text || firstmoduledata.etext < r.ip()) {
331 return _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 *exceptionrecord, r *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.ip()), "\n")
357
358 print("PC=", hex(r.ip()), "\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.ip(), 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 _EXCEPTION_ACCESS_VIOLATION, _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 _EXCEPTION_INT_DIVIDE_BY_ZERO:
408 panicdivide()
409 case _EXCEPTION_INT_OVERFLOW:
410 panicoverflow()
411 case _EXCEPTION_FLT_DENORMAL_OPERAND,
412 _EXCEPTION_FLT_DIVIDE_BY_ZERO,
413 _EXCEPTION_FLT_INEXACT_RESULT,
414 _EXCEPTION_FLT_OVERFLOW,
415 _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 *exceptionrecord, r *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 = &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 = &exceptionrecord{
465 exceptioncode: 2,
466 }
467 }
468 }
469 const FAIL_FAST_GENERATE_EXCEPTION_ADDRESS = 0x1
470 stdcall3(_RaiseFailFastException, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(r)), FAIL_FAST_GENERATE_EXCEPTION_ADDRESS)
471 }
472
473 // gsignalStack is unused on Windows.
474 type gsignalStack struct{}