USDT¶
-
https://www.cxyzjd.com/article/Longyu_wlz/109902171
1 安装依赖包¶
- rocky9 上:
dnf install systemtap-sdt-devel
- 其它 linux 版包名可能是
systemtap-sdt-dev
2 程序插入 USDT 锚点¶
- 代码:
//hello-usdt.c
#include "sys/sdt.h"
int main() {
DTRACE_PROBE(hello_usdt, hello_enter);
int reval = 0;
DTRACE_PROBE1(hello_usdt, hello_exit, reval);
}
- 编译:
➜ gcc hello-usdt.c -o hello-usdt
- 添加usdt
➜ perf buildid-cache --add ./hello-usdt
- 查看 usdt
➜ perf list sdt
List of pre-defined events (to be used in -e):
sdt_hello_usdt:hello_enter [SDT event]
sdt_hello_usdt:hello_exit [SDT event]
- 注册 trace-point
➜ perf probe sdt_hello_usdt:hello_enter
Added new event:
sdt_hello_usdt:hello_enter (on %hello_enter in /home/shw/code/hello-usdt)
You can now use it in all perf tools, such as:
perf record -e sdt_hello_usdt:hello_enter -aR sleep 1
- 采集信息:采集信息过程,执行下上面生成的 ./hello-usdt
➜ perf record -e sdt_hello_usdt:hello_enter -aR sleep 4
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.178 MB perf.data ]
- 查看采集数据
➜ perf script
hello-usdt 3337 [003] 2619.484083: sdt_hello_usdt:hello_enter: (40110a)
2.1 使用 bcc 修改 USDT 内容¶
- 编写 bpf代码
from bcc import BPF, USDT
bpf_source = """
#include <uapi/linux/ptrace.h>
int trace_binary_exec(struct pt_regs *ctx) {
u64 pid = bpf_get_current_pid_tgid();
bpf_trace_printk("New hello_usdt process running with PID: %d", pid);
}
"""
usdt = USDT(path = "./hello_usdt")
usdt.enable_probe(probe = "probe-main", fn_name = "trace_binary_exec")
bpf = BPF(text = bpf_source, usdt_contexts = [usdt])
bpf.trace_print()