Skip to content

Commit

Permalink
compiler: support panics inside indirect deferred functions
Browse files Browse the repository at this point in the history
Found this bug while working on WebAssembly recover support.
  • Loading branch information
aykevl committed Aug 14, 2024
1 parent a47ff02 commit 2f7952f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
4 changes: 2 additions & 2 deletions compiler/defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ func (b *builder) createRunDefers() {
forwardParams = append(forwardParams, llvm.Undef(b.dataPtrType))
}

b.createCall(fnType, fnPtr, forwardParams, "")
b.createInvoke(fnType, fnPtr, forwardParams, "")

case *ssa.Function:
// Direct call.
Expand Down Expand Up @@ -583,7 +583,7 @@ func (b *builder) createRunDefers() {

// Call deferred function.
fnType, llvmFn := b.getFunction(fn)
b.createCall(fnType, llvmFn, forwardParams, "")
b.createInvoke(fnType, llvmFn, forwardParams, "")
case *ssa.Builtin:
db := b.deferBuiltinFuncs[callback]

Expand Down
27 changes: 27 additions & 0 deletions testdata/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ func main() {
println("\n# panic inside defer")
panicInsideDefer()

println("\n# panic inside indirect defer")
panicInsideIndirectDefer(callPanic)

println("\n# panic inside closure")
panicInsideClosure()

println("\n# panic replace")
panicReplace()
}
Expand Down Expand Up @@ -77,6 +83,27 @@ func panicInsideDefer() {
}()
}

func panicInsideIndirectDefer(callback func()) {
defer func() {
printitf("recovered:", recover())
}()
defer callback()
}

func callPanic() {
panic("panic")
}

func panicInsideClosure() {
msg := "panic"
defer func() {
printitf("recovered:", recover())
}()
defer func() {
panic(msg)
}()
}

func panicReplace() {
defer func() {
printitf("recovered:", recover())
Expand Down
6 changes: 6 additions & 0 deletions testdata/recover.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ recovered 2: foo
# panic inside defer
recovered: panic

# panic inside indirect defer
recovered: panic

# panic inside closure
recovered: panic

# panic replace
panic 1
panic 2
Expand Down

0 comments on commit 2f7952f

Please sign in to comment.