Skip to content

Instantly share code, notes, and snippets.

@lizrice
Last active July 19, 2023 08:20
Show Gist options
  • Save lizrice/47ad44a15cce912502f8667a403f5649 to your computer and use it in GitHub Desktop.
Save lizrice/47ad44a15cce912502f8667a403f5649 to your computer and use it in GitHub Desktop.
eBPF hello world
#!/usr/bin/python
from bcc import BPF
from time import sleep
# This outputs a count of how many times the clone and execve syscalls have been made
# showing the use of an eBPF map (called syscall).
program = """
BPF_HASH(syscall);
int kprobe__sys_clone(void *ctx) {
u64 counter = 0;
u64 key = 56;
u64 *p;
p = syscall.lookup(&key);
// The verifier will reject access to a pointer if you don't check that it's non-null first
// Try commenting out the if test (and its closing brace) if you want to see the verifier do its thing
if (p != 0) {
counter = *p;
}
counter++;
syscall.update(&key, &counter);
return 0;
}
int kprobe__sys_execve(void *ctx) {
u64 counter = 0;
u64 key = 59;
u64 *p;
p = syscall.lookup(&key);
if (p != 0) {
counter = *p;
}
counter++;
syscall.update(&key, &counter);
return 0;
}
"""
b = BPF(text=program)
while True:
sleep(2)
line = ""
for k, v in b["syscall"].items():
line += "syscall {0}: {1}\t".format(k.value, v.value)
print(line)
#!/usr/bin/python
from bcc import BPF
prog = """
int hello(void *ctx) {
bpf_trace_printk("Hello world\\n");
return 0;
}
"""
b = BPF(text=prog)
clone = b.get_syscall_fnname("clone")
b.attach_kprobe(event=clone, fn_name="hello")
b.trace_print()
# This prints out a trace line every time the clone system call is called
# If you rename hello() to kprobe__sys_clone() you can delete the b.attach_kprobe() line, because bcc can work
# out what event to attach this to from the function name.
@lizrice
Copy link
Author

lizrice commented Nov 8, 2021

@rodolk a more portable way to do this is to use b.get_syscall_fnname("clone") - I've updated the gist to do that now

@rodolk
Copy link

rodolk commented Nov 10, 2021

@lizrice Thank you for taking the time to explain me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment