Linux动态观测神器bpftrace的5种探针、7个常见内置变量和常见操作?

简介

bpftrace使用 LLVM 作为后端将脚本编译为 BPF 字节码,利用 BCC(BPF Compiler Collection)与 Linux BPF 系统进行交互。

5种探针

kprobe:跟踪内核函数的入口。
kretprobe:跟踪内核函数的返回。
uprobe:跟踪用户空间函数的入口。
uretprobe:跟踪用户空间函数的返回。
tracepoint:跟踪内核中的 tracepoint。

内置变量:

arg0 到 argN:代表内核或用户空间探针的参数。
retval:代表内核或用户空间探针的返回值。
pid:当前进程的进程 ID。
tid:当前线程的线程 ID。
comm:当前进程的命令名称。
cpu:当前进程所在的 CPU。
nsecs:自系统启动以来的纳秒数。

安装

添加 BPFtools 仓库:

curl https://repos.baslab.org/rhel/7/bpftools/bpftools.repo --output /etc/yum.repos.d/bpftools.repo

安装 bpftrace:

sudo yum install bpftrace bpftrace-tools bpftrace-doc bcc-static bcc-tools

实操

内核态:

bpftrace -e 'kprobe:ib_umem_get { printf("ib_umem_get called with args: %d %d\n", arg0, arg1); }'

返回值:

bpftrace -e 'kretprobe:ib_umem_get { printf("ib_umem_get returned %d\n", retval); }'

多个函数

执行:bpftrace test.bt
test.bt内容:

#!/usr/bin/env bpftrace

// 跟踪函数 func1,并打印前四个参数
kprobe:func1
{
    printf("func1 called with args: %d %d %d %d\n", arg0, arg1, arg2, arg3);
}

// 跟踪函数 func2,并打印前四个参数
kprobe:func2
{
    printf("func2 called with args: %d %d %d %d\n", arg0, arg1, arg2, arg3);
}

用户态

bpftrace -e 'uprobe:/path/to/my/exec:test_esec { printf("test_esec started\\n"); }'

so等无法直接访问

if语句

bpftrace -e 'uprobe:/path/to/my/exec:test_esec { if (comm == "exec") {printf("test_esec started\\n"); }}'

查看支持的观测点

bpftrace -l

可以用grep部分头部,进而设置更多观测函数,比如 bpftrace -l | grep :ib_ bpftrace -l | grep mlx5_ib_ 等。

其他

  • 访问参数字符串:printf("%s", str(arg1)); 根据arg1是否是指针可能需要转换
  • 根据参数偏移访问:`printf(“%s”, str(*(arg1+100)));``
  • 根据每种应用写bt脚本,既有app,也有kernel,观测效果不错
  • bt脚本观测解析arg的时候要注意偏移,可以结合crash、gdb等方法。
  • crash中struct的方式 ptype -o struct xxx,gdb中struct的方式 ptype /o struct xxx。详细参考兄弟篇:https://blog.csdn.net/essencelite/article/details/132074198

参考

源码路径:https://github.com/iovisor/bpftrace.git

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值