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