github.com/llvm-mirror/llgo@v0.0.0-20190322182713-bf6f0a60fce1/third_party/gofrontend/libgo/runtime/go-deferred-recover.c (about) 1 /* go-deferred-recover.c -- support for a deferred recover function. 2 3 Copyright 2010 The Go Authors. All rights reserved. 4 Use of this source code is governed by a BSD-style 5 license that can be found in the LICENSE file. */ 6 7 #include <stddef.h> 8 9 #include "runtime.h" 10 #include "go-panic.h" 11 #include "go-defer.h" 12 13 /* This is called when a call to recover is deferred. That is, 14 something like 15 defer recover() 16 17 We need to handle this specially. In 6g/8g, the recover function 18 looks up the stack frame. In particular, that means that a 19 deferred recover will not recover a panic thrown in the same 20 function that defers the recover. It will only recover a panic 21 thrown in a function that defers the deferred call to recover. 22 23 In other words: 24 25 func f1() { 26 defer recover() // does not stop panic 27 panic(0) 28 } 29 30 func f2() { 31 defer func() { 32 defer recover() // stops panic(0) 33 }() 34 panic(0) 35 } 36 37 func f3() { 38 defer func() { 39 defer recover() // does not stop panic 40 panic(0) 41 }() 42 panic(1) 43 } 44 45 func f4() { 46 defer func() { 47 defer func() { 48 defer recover() // stops panic(0) 49 }() 50 panic(0) 51 }() 52 panic(1) 53 } 54 55 The interesting case here is f3. As can be seen from f2, the 56 deferred recover could pick up panic(1). However, this does not 57 happen because it is blocked by the panic(0). 58 59 When a function calls recover, then when we invoke it we pass a 60 hidden parameter indicating whether it should recover something. 61 This parameter is set based on whether the function is being 62 invoked directly from defer. The parameter winds up determining 63 whether __go_recover or __go_deferred_recover is called at all. 64 65 In the case of a deferred recover, the hidden parameter which 66 controls the call is actually the one set up for the function which 67 runs the defer recover() statement. That is the right thing in all 68 the cases above except for f3. In f3 the function is permitted to 69 call recover, but the deferred recover call is not. We address 70 that here by checking for that specific case before calling 71 recover. If this function was deferred when there is already a 72 panic on the panic stack, then we can only recover that panic, not 73 any other. 74 75 Note that we can get away with using a special function here 76 because you are not permitted to take the address of a predeclared 77 function like recover. */ 78 79 struct __go_empty_interface 80 __go_deferred_recover () 81 { 82 G *g; 83 84 g = runtime_g (); 85 if (g->defer == NULL || g->defer->__panic != g->panic) 86 { 87 struct __go_empty_interface ret; 88 89 ret.__type_descriptor = NULL; 90 ret.__object = NULL; 91 return ret; 92 } 93 return __go_recover (); 94 }