Skip to content

Commit

Permalink
add kprobe
Browse files Browse the repository at this point in the history
  • Loading branch information
chaolihf committed Feb 16, 2024
1 parent 3740c6b commit 63d66dc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions pkg/ebpf/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
https://docs.kernel.org/bpf/index.html
7 changes: 7 additions & 0 deletions pkg/ebpf/uretprobe.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,10 @@ int count_packets() {
return XDP_PASS;
}

SEC("kprobe/sys_execve")
int helloWorld(void *context){
char message[]="hello world";
bpf_trace_printk(message,sizeof(message));
return 0;
}

16 changes: 13 additions & 3 deletions pkg/ebpf/uretprobe.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"golang.org/x/sys/unix"
)

//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -target amd64 -type event bpf uretprobe.c -- -I ./headers
//go:generate sh -c "env BPF2GO_FLAGS=\"-O2 -g -Wall\" go run github.com/cilium/ebpf/cmd/bpf2go -target amd64 -type event bpf uretprobe.c -- -I ./headers"

const (
// The path to the ELF binary containing the function to trace.
Expand Down Expand Up @@ -71,14 +71,14 @@ func main() {
}

// Attach count_packets to the network interface.
link, err := link.AttachXDP(link.XDPOptions{
xdpLink, err := link.AttachXDP(link.XDPOptions{
Program: objs.CountPackets,
Interface: iface.Index,
})
if err != nil {
log.Fatal("Attaching XDP:", err)
}
defer link.Close()
defer xdpLink.Close()

log.Printf("Counting incoming packets on %s..", ifname)

Expand Down Expand Up @@ -107,6 +107,15 @@ func main() {
}
}()

/*
处理kprobe事件
*/
kp, err := link.Kprobe("sys_execve", objs.HelloWorld, nil)
if err != nil {
log.Fatalf("opening kprobe: %s", err)
}
defer kp.Close()

go func() {
for {
select {
Expand All @@ -117,6 +126,7 @@ func main() {
log.Fatal("Map lookup:", err)
}
log.Printf("Received %d packets", count)

case <-stop:
log.Print("Received signal, exiting..")
return
Expand Down

0 comments on commit 63d66dc

Please sign in to comment.