探究 Go 源码中 panic & recover 有哪些坑?
转载请声明出处哦~,本篇文章发布于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 流程
- 编译器会将关键字 panic 转换成
runtime.gopanic
并调用,然后在循环中不断从当前 Goroutine 的 defer 链表获取 defer 并执行; - 如果在调用的 defer 函数中有 recover ,那么就会调用到
runtime.gorecover
,它会修改runtime._panic
的 recovered 字段为 true; - 调用完 defer 函数之后回到
runtime.gopanic
主逻辑中,检查 recovered 字段为 true 会从runtime._defer
结构体中取出程序计数器pc
和栈指针sp
并调用runtime.recovery
函数恢复程序。runtime.recvoery
在调度过程中会将函数的返回值设置成 1; - 当
runtime.deferproc
函数的返回值是 1 时,编译器生成的代码会直接跳转到调用方函数返回之前并执行runtime.deferreturn
,然后程序就已经从panic
中恢复了并执行正常的逻辑; - 在
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), ®s)
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
}
我们先来看看这段逻辑:
- 首先会获取当前的 Goroutine ,并创建新的
runtime._panic
并添加到所在 Goroutine 的 _panic 链表的最前面; - 接着会进入到循环获取当前 Goroutine 的 defer 链表,并调用 reflectcall 运行 defer 函数;
- 运行完之后会将 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
。
runtime 中有哪些坑?
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。
Reference
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://www.digitalocean.com/community/tutorials/handling-panics-in-go
探究 Go 源码中 panic & recover 有哪些坑?的更多相关文章
- 从express源码中探析其路由机制
引言 在web开发中,一个简化的处理流程就是:客户端发起请求,然后服务端进行处理,最后返回相关数据.不管对于哪种语言哪种框架,除去细节的处理,简化后的模型都是一样的.客户端要发起请求,首先需要一个标识 ...
- Android 网络框架之Retrofit2使用详解及从源码中解析原理
就目前来说Retrofit2使用的已相当的广泛,那么我们先来了解下两个问题: 1 . 什么是Retrofit? Retrofit是针对于Android/Java的.基于okHttp的.一种轻量级且安全 ...
- Eclipse与Android源码中ProGuard工具的使用
由于工作需要,这两天和同事在研究android下面的ProGuard工具的使用,通过查看android官网对该工具的介绍以及网络上其它相关资料,再加上自己的亲手实践,算是有了一个基本了解.下面将自己的 ...
- String源码中的"avoid getfield opcode"
引言: 之前一篇文章梳理了String的不变性原则,还提到了一段源码中注释"avoid getfield opcode",当时通过查阅资料发现,这是为了防止 getfield(获取 ...
- android源码中修改wifi热点默认始终开启
在项目\frameworks\base\wifi\java\android\net\wifi\WifiStateMachine.java里面,有如下的代码,是设置wifi热点保持状态的:如下: pri ...
- rxjava源码中的线程知识
rxjava源码中的线程知识 rx的最精简的总结就是:异步 这里说一下以下的五个类 1.Future2.ConcurrentLinkedQueue3.volatile关键字4.AtomicRefere ...
- MMS源码中异步处理简析
1,信息数据的查询,删除使用AsycnQueryHandler处理 AsycnQueryHandler继承了Handler public abstract class AsyncQueryHandle ...
- Jquery源码中的Javascript基础知识(三)
这篇主要说一下在源码中jquery对象是怎样设计实现的,下面是相关代码的简化版本: (function( window, undefined ) { // code 定义变量 jQuery = fun ...
- Jquery源码中的Javascript基础知识(一)
jquery源码中涉及了大量原生js中的知识和概念,文章是我在学习两者的过程中进行的整理和总结,有不对的地方欢迎大家指正. 本文使用的jq版本为2.0.3,附上压缩和未压缩版本地址: http://a ...
随机推荐
- hd-cg辉度通用代码生成器
HD-CG 辉度通用代码生成器 主要特点: 1. 自定义代码模板:通过简单的默认变量自行编写代码模板,如果默认变量不满足需求,也可增加自定义变量. 2. 自定义数据源:可自定义添加多个项目的数据库,数 ...
- Server Tools(服务器工具)
服务器工具 1.发布 # Process: MXD 转 Web 地图 arcpy.MXDToWebMap_server("", "", "" ...
- 题解 [HAOI2018]反色游戏
题目传送门 题目大意 给出一个 \(n\) 个点 \(m\) 条无向边的图,每个点都有一个 \(\in [0,1]\) 的权值,每次可以选择一条边,然后将该边相连两点权值异或上 \(1\).问有多少种 ...
- 分布式事物SAGA
目录 概述SAGA SAGA的执行方式 存在的问题 重试机制 SAGA VS TCC 实现SAGA的框架 概述SAGA SAGA是1987 Hector & Kenneth 发表的论文,主要是 ...
- vue3双向数据绑定原理_demo
<!DOCTYPE html> <head> <meta charset="UTF-8" /> <meta name="view ...
- LeetCode:数组专题
数组专题 有关数组的一些 leetcode 题,在此做一些记录,不然没几天就忘光光了 二分查找 双指针 滑动窗口 前缀和/差分数组 二分查找 本文内容摘录自公众号labuladong中有关二分查找的文 ...
- UltraSoft - Alpha - Scrum Meeting 8
Date: Apr 23th, 2020. Scrum 情况汇报 进度情况 组员 负责 昨日进度 后两日任务 CookieLau PM.后端 aliyun连接前后端,跑通demo 实现邮箱注册的验证码 ...
- 【二食堂】Alpha - Scrum Meeting 3
Scrum Meeting 3 例会时间:4.13 12:00 - 12:30 进度情况 组员 昨日进度 今日任务 李健 1. 继续学习前端知识,寻找一些可用的框架.issue 1. 搭建主页html ...
- 使用flink实现一个简单的wordcount
使用flink实现一个简单的wordcount 一.背景 二.需求 三.前置条件 1.jdk版本要求 2.maven版本要求 四.实现步骤 1.创建 flink 项目 2.编写程序步骤 1.创建Str ...
- 并发编程从零开始(九)-ConcurrentSkipListMap&Set
并发编程从零开始(九)-ConcurrentSkipListMap&Set CAS知识点补充: 我们都知道在使用 CAS 也就是使用 compareAndSet(current,next)方法 ...