分享
一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述
imiskolee · · 1245 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
背景
在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。
步骤
实现函数RecursiveDepthChecker
func RecursiveDepthChecker(max int) bool {
//注意,这里我们跳过了本函数自己的栈,找到父调用的函数名
caller, _, _, _ := runtime.Caller(1)
currentFuncName := runtime.FuncForPC(caller).Name()
stack := make([]byte, 65535*1) //max 1MB stack traceback
//由于Golang Runtime中很多关于栈的函数未导出,无法使用。因此使用最肮脏的字符串检测方法
runtime.Stack(stack, false)
start := 0
depth := 0
for {
count := strings.Index(string(stack[start:]), currentFuncName)
if count >= 0 {
start += count + len(currentFuncName)
depth++
} else {
break
}
}
if depth > max {
return false
}
return true
}
在需要进行检测的函数用引入检查即可
func TFunc() {
fmt.Println("Start Caller...")
if !RecursiveDepthChecker(5) {
fmt.Println("Stack Overflow")
return
}
TFunc()
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1245 次点击
下一篇:学习记录
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
背景
在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。
步骤
实现函数RecursiveDepthChecker
func RecursiveDepthChecker(max int) bool {
//注意,这里我们跳过了本函数自己的栈,找到父调用的函数名
caller, _, _, _ := runtime.Caller(1)
currentFuncName := runtime.FuncForPC(caller).Name()
stack := make([]byte, 65535*1) //max 1MB stack traceback
//由于Golang Runtime中很多关于栈的函数未导出,无法使用。因此使用最肮脏的字符串检测方法
runtime.Stack(stack, false)
start := 0
depth := 0
for {
count := strings.Index(string(stack[start:]), currentFuncName)
if count >= 0 {
start += count + len(currentFuncName)
depth++
} else {
break
}
}
if depth > max {
return false
}
return true
}
在需要进行检测的函数用引入检查即可
func TFunc() {
fmt.Println("Start Caller...")
if !RecursiveDepthChecker(5) {
fmt.Println("Stack Overflow")
return
}
TFunc()
}