溯源-查看方法堆栈 python/JS/OC

Python自定义打印 添加调用堆栈

def preInfoFromFrame(frame):
    fCode = frame.f_code
    baseFile = os.path.basename(fCode.co_filename)
    tmpStr = ''
    cls = ''
    for idx in range(fCode.co_argcount):
        key = fCode.co_varnames[idx]
        clsStr = type(frame.f_locals[key]).__name__  # 获取对象的类, 的名称字符串
        if idx == 0:
            cls = clsStr+'.'
        else:
            tmpStr += key+':'+clsStr+','
    if len(tmpStr):
        tmpStr = tmpStr[:-1]
    return '{} {}{}{}({})'.format(baseFile, # 文件名
                                cls,   # 类名,如果有的话
                                fCode.co_name,  # 方法名
                                str(fCode.co_firstlineno),  #第几行,位置
                                tmpStr)  # 参数

def zprint(*args, sep=' ', end='\n', file=None ,stack=False):
    frame = sys._getframe(1)
    arr = [preInfoFromFrame(frame),': ',type(args[0])]
    arr.extend(args)
    b = tuple(arr) # 往打印内容前面添加自定义str
    print(*b,sep=sep,end=end,file=file)
    if stack:
        frame = frame.f_back
        frameIdx = 2
        while frame:  # 遍历frame
            fCode = frame.f_code
            print('frame' + str(frameIdx) + ':', preInfoFromFrame(frame))
            frame = frame.f_back
            frameIdx += 1

zprint('这是测试调用',stack=True)
结果如下

MyVisitor.py MyVisitor.visitAddSub44(ctx:AddSubContext) :  <class 'str'> 这是测试调用
frame2: LabeledExprParser.py AddSubContext.accept325(visitor:MyVisitor)
frame3: Tree.py MyVisitor.visit33(tree:AddSubContext)
frame4: MyVisitor.py MyVisitor.visitPrintExpr23(ctx:PrintExprContext)
frame5: LabeledExprParser.py PrintExprContext.accept173(visitor:MyVisitor)
frame6: Tree.py MyVisitor.visitChildren36(node:ProgContext)
frame7: LabeledExprVisitor.py MyVisitor.visitProg13(ctx:ProgContext)
frame8: LabeledExprParser.py ProgContext.accept91(visitor:MyVisitor)
frame9: Tree.py MyVisitor.visit33(tree:ProgContext)
frame10: calc.py <module>1()

JS调用堆栈,通过错误堆栈打印出

//TODO:TEST
try{
    var a = {};
    a.b.c = 3;
}catch (e){
    console.log(e);
}

OC打印调用堆栈

  因为OC是使用messageSend的方式,一种消息发送的机制进行调用的.
  而iOS app发布后,符号已经被除掉了. 即使使用bt打印出来也是一堆看不懂的符号
不过由于消息发送机制的特点, 调用messageSend这个方法, 第一个参数x0是对象,第二个参数x1是SEL方法.
所以, 使用 po x0, po (SEL)x1, 是可以获取我们想要的信息的. 后面的参数
x2, x3, x4 对应我们方法的第1,2,3个参数,以此类推.
不过还有一个需要注意的点, 如果参数是浮点类型, float或者double, 是存在 s和 d寄存器的.

 比如 [(Person *)p  sendArg1:1 arg2:(float)2.0 arg3:(double)3.0 arg4:@"arg"]
 那么取值应该是
 po $x0  => (Person *)p
 po (SEL)$x1 =>  (SEL)sendArg1:arg2:arg3:arg4
 po $x2 =>  1
 po $s0 => (float) 2.0
 po $d1 => (double) 3.0
 po $x3 => @"arg"

  1. 在lldb里面, target->thread->frame->addr 可以通过这个过程获取堆栈每个frame 执行的方法对应的开始地址.
  2. LLDB这个插件库 sbt 这个命令, 就是通过映射获取所有的类的方法开始地址.
  3. 上面两者比较,获取原本的类对象和函数名称

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容