如果获取lua vm(loadstring)里面lua函数的调用链呢?

147 views
Skip to first unread message

cheng ye

unread,
Jun 19, 2017, 7:35:24 AM6/19/17
to openresty
遇到个问题,我想获取lua函数的调用链,但是用loadstring执行产生的lua函数调用链获取不到,想问下大家有什么解决方法么。

Zexuan Luo

unread,
Jun 19, 2017, 11:12:45 AM6/19/17
to openresty
获取不到,具体是什么情况呢?简单试了下,用 debug.traceback() 是可以的。
local level1 = loadstring([[

   
local function level3()
        ngx
.say(debug.traceback())
   
end

   
local function level2()
        level3
()
   
end

    level2
()]])
level1
()

$ curl localhost:8080  
stack traceback
:
   
[string "..."]:3: in function 'level3'
   
[string "..."]:7: in function 'level2'
   
[string "..."]:10: in function 'level1'
   
./src/a.lua:12: in function <./src/a.lua:1>



在 2017年6月19日星期一 UTC+8下午7:35:24,cheng ye写道:
遇到个问题,我想获取lua函数的调用链,但是用loadstring执行产生的lua函数调用链获取不到,想问下大家有什么解决方法么。

cheng ye

unread,
Jun 19, 2017, 9:41:04 PM6/19/17
to openresty
就是loadstring里面执行的是用户代码,但是我想获取到用户在里面执行函数的调用链,而且想知道用户代码那些函数耗是比较严重的。

在 2017年6月19日星期一 UTC+8下午11:12:45,Zexuan Luo写道:

Zexuan Luo

unread,
Jun 20, 2017, 9:38:43 AM6/20/17
to openresty
可以在用户代码前后添加 sethook 函数,像这样:
local function hook(event_type)
    ngx
.say(event_type, ' ', debug.getinfo(2).name)
end


local level1 = loadstring([[
   
local function level3()

        ngx
.say("I am in level3")

   
end

   
local function level2()
        level3
()
   
end

    level2
()
]])


debug
.sethook(hook, "cr")
level1
()
debug
.sethook()

$ curl localhost:8080
call level1
call level2
call level3
call say
I am
in level3
return level3
return level2
return level1
call sethook
在这个粗糙的输出之上做些加工,应该能获取调用链和调用用时了。


在 2017年6月20日星期二 UTC+8上午9:41:04,cheng ye写道:

cheng ye

unread,
Jun 21, 2017, 4:37:14 AM6/21/17
to openresty
嗯嗯,这倒是个好办法。可以一试,但是对性能有一定的损坏了

在 2017年6月20日星期二 UTC+8下午9:38:43,Zexuan Luo写道:
Reply all
Reply to author
Forward
0 new messages