一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述

栏目: Go · 发布时间: 6年前

内容简介:在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

背景

在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

步骤

实现函数 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()
}

以上所述就是小编给大家介绍的《一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Security, Privacy and Commerce, 2nd Edition

Web Security, Privacy and Commerce, 2nd Edition

Simson Garfinkel / O'Reilly Media / 2002-01-15 / USD 44.95

Since the first edition of this classic reference was published, World Wide Web use has exploded and e-commerce has become a daily part of business and personal life. As Web use has grown, so have ......一起来看看 《Web Security, Privacy and Commerce, 2nd Edition》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具