如何将“图像查找 -v 地址”结果存储在变量中?

问题描述

我可以通过以下 lldb 命令来符号化符号地址:

image lookup --address $SYMBOL_ADDRRESS

但是在编写 shell 脚本进行解析时,我找不到将上述命令的输出存储到变量或文件中的方法

解决方法

首先,如果您的脚本的工作主要是驱动 lldb 并且您碰巧知道 Python,那么在 Python 中使用 lldb 模块会比让 lldb 生成文本输出更快乐,在那里您可以直接驱动调试器你在 shell 脚本中解析。

lldb Python 模块提供了 SBTarget.ResolveSymbolContextForAddress 之类的 API,它运行与 image lookup --address 相同的查找,但将结果作为 Python lldb.SBSymbolContext 对象返回,您可以查询模块/文件/line 等在对象上使用 API。因此,使用 lldd API 可以更轻松地从该结果中获取一些信息。

但是如果您必须使用 shell 脚本,那么最简单的方法可能是将命令输出写入文件并将其读回 shell 脚本。 lldb 尚不支持将 tee-ing 命令输出到日志文件中,但 lldb Python 模块允许您运行命令行命令并以编程方式捕获输出。

所以你可以通过 lldb 的 Python 脚本解释器轻松完成:

(lldb) script
Python Interactive Interpreter. To exit,type 'quit()','exit()' or Ctrl-D.
>>> result = lldb.SBCommandReturnObject()
>>> lldb.debugger.GetCommandInterpreter().HandleCommand("image lookup -va $pc",result)
2
>>> fh = open("/tmp/out.txt","w")
>>> fh.write(result.GetOutput())
>>> fh.close()
>>> quit
(lldb) plat shell cat /tmp/out.txt
      Address: foo[0x0000000100003f6f] (foo.__TEXT.__text + 15)
      Summary: foo`main + 15 at foo.c:6:3
       Module: file = "/tmp/foo",arch = "x86_64"
  CompileUnit: id = {0x00000000},file = "/tmp/foo.c",language = "c99"
     Function: id = {0x7fffffff00000032},name = "main",range = [0x0000000100003f60-0x0000000100003f8a)
     FuncType: id = {0x7fffffff00000032},byte-size = 0,decl = foo.c:4,compiler_type = "int (void)"
       Blocks: id = {0x7fffffff00000032},range = [0x100003f60-0x100003f8a)
    LineEntry: [0x0000000100003f6f-0x0000000100003f82): /tmp/foo.c:6:3
       Symbol: id = {0x00000005},range = [0x0000000100003f60-0x0000000100003f8a),name="main"

你也可以用 Python 写一个 lldb 命令来封装这点业务,这样会更容易使用。详情请见:

https://lldb.llvm.org/use/python-reference.html#create-a-new-lldb-command-using-a-python-function

您甚至可以采用混合方法,并通过自定义 Python 命令使所有 lldb 工作。这将允许您使用 lldb Python API 来获取您需要的信息并以您方便的任何格式将其写出,并且将简化您的 shell 脚本中的 lldb 调用并有助于恢复 lldb 提供的信息......>