2014-07-11 Edward Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / libgo / runtime / go-deferred-recover.c
blob78ef287cf00a05342ec65ac83b4f1ba19fe92971
1 /* go-deferred-recover.c -- support for a deferred recover function.
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. */
7 #include <stddef.h>
9 #include "runtime.h"
10 #include "go-panic.h"
11 #include "go-defer.h"
13 /* This is called when a call to recover is deferred. That is,
14 something like
15 defer recover()
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.
23 In other words:
25 func f1() {
26 defer recover() // does not stop panic
27 panic(0)
30 func f2() {
31 defer func() {
32 defer recover() // stops panic(0)
33 }()
34 panic(0)
37 func f3() {
38 defer func() {
39 defer recover() // does not stop panic
40 panic(0)
41 }()
42 panic(1)
45 func f4() {
46 defer func() {
47 defer func() {
48 defer recover() // stops panic(0)
49 }()
50 panic(0)
51 }()
52 panic(1)
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).
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.
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.
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. */
79 struct __go_empty_interface
80 __go_deferred_recover ()
82 G *g;
84 g = runtime_g ();
85 if (g->defer == NULL || g->defer->__panic != g->panic)
87 struct __go_empty_interface ret;
89 ret.__type_descriptor = NULL;
90 ret.__object = NULL;
91 return ret;
93 return __go_recover ();