探究 Go 源码中 panic & recover 有哪些坑?
阅读原文时间:2021年11月22日阅读:1

转载请声明出处哦~,本篇文章发布于luozhiyun的博客: https://www.luozhiyun.com/archives/627

本文使用的go的源码1.17.3

写这一篇文章的原因是最近在工作中有位小伙伴在写代码的时候直接用 Go 关键字起了一个 Goroutine,然后发生了空指针的问题,由于没有 recover 导致了整个程序宕掉的问题。代码类似这样:

func main() {
    defer func() {
        if err := recover(); err !=nil{
            fmt.Println(err)
        }
    }()
    go func() {
        fmt.Println("======begin work======")
        panic("nil pointer exception")
    }()
    time.Sleep(time.Second*100)
    fmt.Println("======after work======")
}

返回的结果:

======begin work======
panic: nil pointer exception

goroutine 18 [running]:
...
Process finished with the exit code 2

需要注意的是,当时在 Goroutine 的外层是做了统一的异常处理的,但是很明显的是 Goroutine 的外层的 defer 并没有 cover 住这个异常。

之所以会出现上面的情况,还是因为我们对 Go 源码不甚了解导致的。panic & recover 是有其作用范围的:

  • recover 只有在 defer 中调用才会生效;
  • panic 允许在 defer 中嵌套多次调用;
  • panic 只会对当前 Goroutine 的 defer 有效

之所以 panic 只会对当前 Goroutine 的 defer 有效是因为在 newdefer 分配 _defer 结构体对象的时,会把分配到的对象链入当前 Goroutine 的 _defer 链表的表头。具体的可以再去 深入 Go 语言 defer 实现原理 这篇文章里面回顾一下。

_panic 结构体

type _panic struct {
    argp      unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink
    arg       interface{}    // argument to panic
    link      *_panic        // link to earlier panic
    pc        uintptr        // where to return to in runtime if this panic is bypassed
    sp        unsafe.Pointer // where to return to in runtime if this panic is bypassed
    recovered bool           // whether this panic is over
    aborted   bool           // the panic was aborted
    goexit    bool
}
  • argp 是指向 defer 调用时参数的指针;
  • arg 是我们调用 panic 时传入的参数;
  • link 指向的是更早调用 runtime._panic 结构,也就是说 painc 可以被连续调用,他们之间形成链表;
  • recovered 表示当前 runtime._panic 是否被 recover 恢复;
  • aborted 表示当前的 panic 是否被强行终止;

对于 pc、sp、goexit 这三个关键字的主要作用就是有可能在 defer 中发生 panic,然后在上层的 defer 中通过 recover 对其进行了恢复,那么恢复进程实际上将恢复在Goexit框架之上的正常执行,因此中止Goexit。

pc、sp、goexit 三个字段的讨论以及代码提交可以看看这里:https://github.com/golang/go/commit/7dcd343ed641d3b70c09153d3b041ca3fe83b25e 以及这个讨论 runtime: panic + recover can cancel a call to Goexit

panic 流程

  1. 编译器会将关键字 panic 转换成 runtime.gopanic 并调用,然后在循环中不断从当前 Goroutine 的 defer 链表获取 defer 并执行;
  2. 如果在调用的 defer 函数中有 recover ,那么就会调用到 runtime.gorecover,它会修改 runtime._panic 的 recovered 字段为 true;
  3. 调用完 defer 函数之后回到 runtime.gopanic 主逻辑中,检查 recovered 字段为 true 会从 runtime._defer 结构体中取出程序计数器pc和栈指针sp并调用runtime.recovery函数恢复程序。runtime.recvoery 在调度过程中会将函数的返回值设置成 1;
  4. runtime.deferproc 函数的返回值是 1 时,编译器生成的代码会直接跳转到调用方函数返回之前并执行 runtime.deferreturn,然后程序就已经从 panic 中恢复了并执行正常的逻辑;
  5. runtime.gopanic 执行完所有的 _defer 并且也没有遇到 recover,那么就会执行runtime.fatalpanic终止程序,并返回错误码2;

所以整个过程分为两部分:1. 有recover ,panic 能恢复的逻辑;2. 无recover,panic 直接崩溃;

触发 panic 直接崩溃

func gopanic(e interface{}) {
    gp := getg()
    ...
    var p _panic
    // 创建新的 runtime._panic 并添加到所在 Goroutine 的 _panic 链表的最前面
    p.link = gp._panic
    gp._panic = (*_panic)(noescape(unsafe.Pointer(&p))) 

    for {
        // 获取当前gorourine的 defer
        d := gp._defer
        if d == nil {
            break
        }
        ...
        d._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
        // 运行defer调用函数
        reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz), uint32(d.siz), &regs)
        d._panic = nil
        d.fn = nil
        gp._defer = d.link
        // 将defer从当前goroutine移除
        freedefer(d)
        // recover 恢复程序
        if p.recovered {
            ...
        }
    }
    // 打印出全部的 panic 消息以及调用时传入的参数
    preprintpanics(gp._panic)
    // fatalpanic实现了无法被恢复的程序崩溃
    fatalpanic(gp._panic)
    *(*int)(nil) = 0
}

我们先来看看这段逻辑:

  1. 首先会获取当前的 Goroutine ,并创建新的 runtime._panic 并添加到所在 Goroutine 的 _panic 链表的最前面;

  2. 接着会进入到循环获取当前 Goroutine 的 defer 链表,并调用 reflectcall 运行 defer 函数;

  3. 运行完之后会将 defer 从当前 Goroutine 移除,因为我们这里假设没有 recover 逻辑,那么,会调用 fatalpanic 中止整个程序;

    func fatalpanic(msgs *_panic) {
    pc := getcallerpc()
    sp := getcallersp()
    gp := getg()
    var docrash bool
    systemstack(func() {
    if startpanic_m() && msgs != nil {
    printpanics(msgs)
    }

        docrash = dopanic_m(gp, pc, sp)
    })
    if docrash {
        crash()
    }
    systemstack(func() {
        exit(2)
    })
    *(*int)(nil) = 0 // not reached

    }

fatalpanic 它在中止程序之前会通过 printpanics 打印出全部的 panic 消息以及调用时传入的参数,然后调用 exit 并返回错误码 2。

触发 panic 恢复

recover 关键字会被调用到 runtime.gorecover中:

func gorecover(argp uintptr) interface{} {
    gp := getg()
    p := gp._panic
    if p != nil && !p.goexit && !p.recovered && argp == uintptr(p.argp) {
        p.recovered = true
        return p.arg
    }
    return nil
}

如果当前 Goroutine 没有调用 panic,那么该函数会直接返回 nil;p.Goexit判断当前是否是 goexit 触发的,上面的例子也说过,recover 是不能阻断 goexit 的;

如果条件符合,那么最终会将 recovered 字段修改为 ture,然后在 runtime.gopanic 中执行恢复。

func gopanic(e interface{}) {
    gp := getg()
    ...
    var p _panic
    // 创建新的 runtime._panic 并添加到所在 Goroutine 的 _panic 链表的最前面
    p.link = gp._panic
    gp._panic = (*_panic)(noescape(unsafe.Pointer(&p))) 

    for {
        // 获取当前gorourine的 defer
        d := gp._defer
        ...
        pc := d.pc
        sp := unsafe.Pointer(d.sp)
        // recover 恢复程序
        if p.recovered {
            // 获取下一个 panic
            gp._panic = p.link
            // 如果该panic是 goexit 触发的,那么会恢复到 goexit 逻辑代码中执行 exit
            if gp._panic != nil && gp._panic.goexit && gp._panic.aborted {
                gp.sigcode0 = uintptr(gp._panic.sp)
                gp.sigcode1 = uintptr(gp._panic.pc)
                mcall(recovery)
                throw("bypassed recovery failed") // mcall 会恢复正常的代码逻辑,不会走到这里
            }
            ...

            gp._panic = p.link
            for gp._panic != nil && gp._panic.aborted {
                gp._panic = gp._panic.link
            }
            if gp._panic == nil {
                gp.sig = 0
            }
            gp.sigcode0 = uintptr(sp)
            gp.sigcode1 = pc
            mcall(recovery)
            throw("recovery failed") // mcall 会恢复正常的代码逻辑,不会走到这里
        }
    }
    ...
}

这里包含了两段 mcall(recovery) 调用恢复。

第一部分 if gp._panic != nil && gp._panic.goexit && gp._panic.aborted判断主要是针对 Goexit,保证 Goexit 也会被 recover 住恢复到 Goexit 执行时,执行 exit;

第二部分是做 panic 的 recover,从runtime._defer中取出了程序计数器 pc 和 sp 并调用 recovery 触发程序恢复;

func recovery(gp *g) {
    sp := gp.sigcode0
    pc := gp.sigcode1
    ...
    gp.sched.sp = sp
    gp.sched.pc = pc
    gp.sched.lr = 0
    gp.sched.ret = 1
    gogo(&gp.sched)
}

这里的 recovery 会将函数的返回值设置成 1,然后调用 gogo 会跳回 defer 关键字调用的位置,Goroutine 继续执行;

func deferproc(siz int32, fn *funcval) {
    ...
    // deferproc returns 0 normally.
    // a deferred func that stops a panic
    // makes the deferproc return 1.
    // the code the compiler generates always
    // checks the return value and jumps to the
    // end of the function if deferproc returns != 0.
    return0()
}

通过注释我们知道,deferproc 返回返回值是 1 时,编译器生成的代码会直接跳转到调用方函数返回之前并执行runtime.deferreturn

panic 我们在实现业务的时候是不推荐使用的,但是并不代表 runtime 里面不会用到,对于不了解 Go 底层实现的新人来说,这无疑是挖了一堆深坑。如果不熟悉这些坑,是不可能写出健壮的 Go 代码。

下面我将 runtime 中的异常分一下类,有一些异常是 recover 也捕获不到的,有一些是正常的 panic 可以被捕获到。

无法捕获的异常

内存溢出

func main() {
    defer errorHandler()
    _ = make([]int64, 1<<40)
    fmt.Println("can recover")
}

func errorHandler() {
    if r := recover(); r != nil {
        fmt.Println(r)
    }
}

在调用 alloc 进行内存分配的时候内存不够会调用 grow 从系统申请新的内存,通过调用 mmap 申请内存返回 _ENOMEM 的时候会抛出 runtime: out of memory异常,throw 会调用到 exit 导致整个程序退出。

func sysMap(v unsafe.Pointer, n uintptr, sysStat *sysMemStat) {
    sysStat.add(int64(n))

    p, err := mmap(v, n, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_FIXED|_MAP_PRIVATE, -1, 0)
    if err == _ENOMEM {
        throw("runtime: out of memory")
    }
    if p != v || err != 0 {
        throw("runtime: cannot map pages in arena address space")
    }
}

func throw(s string) {
    ...
    fatalthrow()
    *(*int)(nil) = 0 // not reached
}

func fatalthrow() {
    systemstack(func() {
        ...
        exit(2)
    })

}

map 并发读写

func main() {
    defer errorHandler()
    m := map[string]int{}

    go func() {
        for {
            m["x"] = 1
        }
    }()
    for {
        _ = m["x"]
    }
}

func errorHandler() {
    if r := recover(); r != nil {
        fmt.Println(r)
    }
}

map 由于不是线程安全的,所以在遇到并发读写的时候会抛出 concurrent map read and map write异常,从而使程序直接退出。

func mapaccess1_faststr(t *maptype, h *hmap, ky string) unsafe.Pointer {
    ...
    if h.flags&hashWriting != 0 {
        throw("concurrent map read and map write")
    }
    ...
}

这里的 throw 和上面一样,最终会调用到 exit 执行退出。

这里其实是很奇怪的,我以前是做 java 的,用 hashmap 遇到并发的竟态问题的时候也只是抛了个异常,并不会导致程序 crash。对于这一点官方是这样解释的:

The runtime has added lightweight, best-effort detection of concurrent misuse of maps. As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. If the runtime detects this condition, it prints a diagnosis and crashes the program. The best way to find out more about the problem is to run the program under the race detector, which will more reliably identify the race and give more detail.

栈内存耗尽

func main() {
    defer errorHandler()
    var f func(a [1000]int64)
    f = func(a [1000]int64) {
        f(a)
    }
    f([1000]int64{})
}

这个例子中会返回:

runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc0200e1be8 stack=[0xc0200e0000, 0xc0400e0000]
fatal error: stack overflow

对于栈不熟悉的同学可以看我这篇文章: 一文教你搞懂 Go 中栈操作 。下面我简单说一下,栈的基本机制。

在Go中,Goroutines 没有固定的堆栈大小。相反,它们开始时很小(比如4KB),在需要时增长/缩小,似乎给人一种 "无限 "堆栈的感觉。但是增长总是有限的,但是这个限制并不是来自于调用深度的限制,而是来自于堆栈内存的限制,在Linux 64位机器上,它是1GB。

var maxstacksize uintptr = 1 << 20 // enough until runtime.main sets it for real

func newstack() {
    ...
    if newsize > maxstacksize || newsize > maxstackceiling {
        throw("stack overflow")
    }
    ...
}

在栈的扩张中,会校验新的栈大小是否超过阈值 1 << 20,超过了同样会调用 throw("stack overflow")执行 exit 导致整个程序 crash。

尝试将 nil 函数交给 goroutine 启动

func main() {
    defer errorHandler()
    var f func()
    go f()
}

这里也会直接 crash 掉。

所有线程都休眠了

正常情况下,程序中不会所有线程都休眠,总是会有线程在运行处理我们的任务,例如:

func main() {
    defer errorHandler()
    go func() {
        for true {
            fmt.Println("alive")
            time.Sleep(time.Second*1)
        }
    }()
    <-make(chan int)
}

但是也有些同学搞了一些骚操作,例如没有很好的处理我们的代码逻辑,在逻辑里加入了一些会永久阻塞的代码:

func main() {
    defer errorHandler()
    go func() {
        for true {
            fmt.Println("alive")
            time.Sleep(time.Second*1)
            select {}
        }
    }()
    <-make(chan int)
}

例如这里在 Goroutine 里面加入了一个 select 这样就会造成永久阻塞,go 检测出没有 goroutine 可以运行了,就会直接将程序 crash 掉:

fatal error: all goroutines are asleep - deadlock!

能够被捕获的异常

数组 ( slice ) 下标越界

func foo(){
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    var bar = []int{1}
    fmt.Println(bar[1])
}

func main(){
    foo()
    fmt.Println("exit")
}

返回:

runtime error: index out of range [1] with length 1
exit

因为代码中用了 recover ,程序得以恢复,输出 exit

空指针异常

func foo(){
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    var bar *int
    fmt.Println(*bar)
}

func main(){
    foo()
    fmt.Println("exit")
}

返回:

runtime error: invalid memory address or nil pointer dereference
exit

除了上面这种情况以外,还有一种常见的就是我们的变量是初始化了,但是却被置空了,但是 Receiver 是一个指针:

type Shark struct {
    Name string
}

func (s *Shark) SayHello() {
    fmt.Println("Hi! My name is", s.Name)
}

func main() {
    s := &Shark{"Sammy"}
    s = nil
    s.SayHello()
}

往已经 close 的 chan 中发送数据

func foo(){
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    var bar = make(chan int, 1)
    close(bar)
    bar<-1
}

func main(){
    foo()
    fmt.Println("exit")
}

返回:

send on closed channel
exit

这个异常我们在 多图详解Go中的Channel源码 这篇文章里面讨论过了:

func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
    ...
    //加锁
    lock(&c.lock)
    // 是否关闭的判断
    if c.closed != 0 {
        unlock(&c.lock)
        panic(plainError("send on closed channel"))
    }
    // 从 recvq 中取出一个接收者
    if sg := c.recvq.dequeue(); sg != nil {
        // 如果接收者存在,直接向该接收者发送数据,绕过buffer
        send(c, sg, ep, func() { unlock(&c.lock) }, 3)
        return true
    }
    ...
}

发送的时候会判断一下 chan 是否已被关闭。

类型断言

func foo(){
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    var i interface{} = "abc"
    _ = i.([]string)
}

func main(){
    foo()
    fmt.Println("exit")
}

返回:

interface conversion: interface {} is string, not []string
exit

所以断言的时候我们需要使用带有两个返回值的断言:

    var i interface{} = "hello" 

    f, ok := i.(float64) //  no runtime panic
    fmt.Println(f, ok)

    f = i.(float64) // panic
    fmt.Println(f)

类似上面的错误还是挺多的,具体想要深究的话可以去 stackoverflow 上面看一下:https://stackoverflow.com/search?q=Runtime+Panic+in+Go

本篇文章从一个例子出发,然后讲解了 panic & recover 的源码。总结了一下实际开发中可能会出现的异常,runtime 包中经常会抛出一些异常,有一些异常是 recover 也捕获不到的,有一些是正常的 panic 可以被捕获到的,需要我们开发中时常注意,防止应用 crash。

https://stackoverflow.com/questions/57486620/are-all-runtime-errors-recoverable-in-go

https://xiaomi-info.github.io/2020/01/20/go-trample-panic-recover/

https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-panic-recover/

https://zhuanlan.zhihu.com/p/346514343

https://stackoverflow.com/questions/39288741/how-to-recover-from-concurrent-map-writes/39289246#39289246

https://www.digitalocean.com/community/tutorials/handling-panics-in-go

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章