xref: /aosp_15_r20/external/bcc/tests/lua/test_uprobes.lua (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1local suite = require("test_helper")
2local ffi = require("ffi")
3local TestUprobes = {}
4
5ffi.cdef[[
6  int getpid(void);
7  void malloc_stats(void);
8]]
9
10function TestUprobes:test_simple_library()
11  local text = [[
12#include <uapi/linux/ptrace.h>
13BPF_ARRAY(stats, u64, 1);
14static void incr(int idx) {
15    u64 *ptr = stats.lookup(&idx);
16    if (ptr)
17        ++(*ptr);
18}
19int count(struct pt_regs *ctx) {
20    u32 pid = bpf_get_current_pid_tgid();
21    if (pid == PID)
22        incr(0);
23    return 0;
24}]]
25
26  local pid = tonumber(ffi.C.getpid())
27  local text = text:gsub("PID", tostring(pid))
28
29  local b = BPF:new{text=text}
30  b:attach_uprobe{name="c", sym="malloc_stats", fn_name="count", pid=pid}
31  b:attach_uprobe{name="c", sym="malloc_stats", fn_name="count", pid=pid, retprobe=true}
32
33  assert_equals(BPF.num_open_uprobes(), 2)
34
35  ffi.C.malloc_stats()
36
37  local stats = b:get_table("stats")
38  assert_equals(tonumber(stats:get(0)), 2)
39end
40
41function TestUprobes:test_simple_binary()
42  local text = [[
43#include <uapi/linux/ptrace.h>
44BPF_ARRAY(stats, u64, 1);
45static void incr(int idx) {
46    u64 *ptr = stats.lookup(&idx);
47    if (ptr)
48        ++(*ptr);
49}
50int count(struct pt_regs *ctx) {
51    u32 pid = bpf_get_current_pid_tgid();
52    incr(0);
53    return 0;
54}]]
55
56  local b = BPF:new{text=text}
57  local pythonpath = "/usr/bin/python3"
58  local symname = "_start"
59  b:attach_uprobe{name=pythonpath, sym=symname, fn_name="count"}
60  b:attach_uprobe{name=pythonpath, sym=symname, fn_name="count", retprobe=true}
61
62  os.spawn(pythonpath .. " -V")
63
64  local stats = b:get_table("stats")
65  assert_true(tonumber(stats:get(0)) >= 2)
66end
67
68function TestUprobes:teardown()
69  BPF.cleanup()
70end
71
72suite("TestUprobes", TestUprobes)
73