LLDB的简单使用

LLDB是一种C/C++程序的调试器工具,可以监控程序的变量值和堆栈的变化情况。在没有IDE情况下调试程序非常实用。网上找到的资料大多都是help信息的简单翻译,要想熟练使用还得经常练习。

一次执行过程

测试代码

代码功能为获得C语言字符串的长度。

#include <stdio.h>

size_t strlen(const char *s) {
    const char *sc;
    for (sc = s; *sc != '\0'; ++sc) {}
    return sc - s;
}

int main() {
    char str[] = "Hello World, I'm R2-D2.";
    int length = strlen(str);
    printf("The length of str is %d\n", length);
    return 0;
}

编译过程

注意在编译过程中使用-g编译指令支持调试器的工作。

CC = gcc
CFLAGS = -g -std=c11 -Wall
SOURCE = test.c
OBJECT = $(SOURCE: .c=.o)

main: $(OBJECT)
    $(CC) $(CFLAGS) $(OBJECT) -o $@

clear:
    rm *.o

基本流程

# 开启调试器
$ lldb main
# 或者使用lldb开启调试器 使用file命令导入文件
#
# 在指定文件指定行添加断点
(lldb) b test.c:11
# breakpoint set --file test.c --line 11
# breakpoint set -f test.c -l 11
#
# 开始运行
(lldb) r
# run
#
# 查看当前函数和调用关系
(lldb) bt
# backtrace
#
# 查看本地变量(当前堆栈帧)
(lldb) frame variable
#
# 步进和运行
(lldb) next
(lldb) continue

常用的指令

断点操作

# 在指定文件指定行添加断点
(lldb) b test.c:11
# breakpoint set --file test.c --line 11
# breakpoint set -f test.c -l 11
# 为指定函数添加断点
(lldb) breakpoint set --name strlen
# 查看断点
(lldb) breakpoint list
# 设置断点命令 即触发断点时执行操作 1.1为断点编号
(lldb) breakpoint command add 1.1

启动和运行操作

# 开始运行 在断点停止
(lldb) r
# run
# 继续运行 下一个断点停止
(lldb) c
# continue
# 步进操作 运行下一行
(lldb) n
# next
# 进入当前行函数
(lldb) step

查看操作

# 查看跟踪栈 即函数调用关系
(lldb) bt
# backtrace
# 查看栈帧 即局部变量
(lldb) frame variable [variable_name]
# 选择栈帧 9为栈帧标号
(lldb) frame select 9

线程操作

上述各种操作在多线程的环境中都可以对某一个线程进行操作

(lldb) thread backtrace
(lldb) thread list
# 运行直到12行
(lldb) thread until 12

数据操作

# 修改程序中a的值
(lldb) exp a = 10

参考资料:

LLDB TUTORIAL

LLDB调试器的使用

LLDB 十分钟快速教程

LLDB使用

Lei Yang
Lei Yang
PhD candidate

My research interests include visual speech recognition and semantics segmentation.