diff --git a/sample/kprobe_file_open_counter/build.sh b/sample/kprobe_file_open_counter/build.sh new file mode 100755 index 0000000..7658e27 --- /dev/null +++ b/sample/kprobe_file_open_counter/build.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +clang -O3 -emit-llvm -c kprobe_file_open_counter.c -o - | llc -march=bpf -filetype=obj -o kprobe_file_open_counter.o diff --git a/sample/kprobe_file_open_counter/kprobe_file_open_counter.c b/sample/kprobe_file_open_counter/kprobe_file_open_counter.c new file mode 100644 index 0000000..41cc916 --- /dev/null +++ b/sample/kprobe_file_open_counter/kprobe_file_open_counter.c @@ -0,0 +1,32 @@ +#include +#include + +#include + +char __license[] SEC("license") = "Dual MIT/GPL"; + +struct bpf_map_def SEC("maps") kprobe_map = { + .type = BPF_MAP_TYPE_HASH, + .key_size = sizeof(__u32), + .value_size = sizeof(__u64), + .max_entries = 1, +}; + +SEC("kprobe/sys_open") +int kprobe_sysopen() +{ + __u32 key = 1; + __u64 initval = 1, *valp; + + valp = bpf_map_lookup_elem(&kprobe_map, &key); + if (!valp) + { + bpf_map_update_elem(&kprobe_map, &key, &initval, BPF_ANY); + return 0; + } + __sync_fetch_and_add(valp, 1); + + return 0; +} + +char LICENSE[] SEC("license") = "GPL"; diff --git a/sample/kprobe_file_open_counter/kprobe_file_open_counter.pl b/sample/kprobe_file_open_counter/kprobe_file_open_counter.pl new file mode 100644 index 0000000..e92b217 --- /dev/null +++ b/sample/kprobe_file_open_counter/kprobe_file_open_counter.pl @@ -0,0 +1,42 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use utf8; +use lib '../../lib'; +use Sys::Ebpf::Loader; +use Sys::Ebpf::Link::Perf::Kprobe; + +my $file = "kprobe_file_open_counter.o"; +my $loader = Sys::Ebpf::Loader->new($file); +my $data = $loader->load_elf(); + +my $kprobe_fn = "kprobe/sys_open"; + +my ( $map_data, $prog_fd ) = $loader->load_bpf($kprobe_fn); +my $map_kprobe_map = $map_data->{kprobe_map}; +$map_kprobe_map->{key_schema} = [ [ 'kprobe_map_key', 'uint32' ] ]; +$map_kprobe_map->{value_schema} = [ [ 'kprobe_map_value', 'uint64' ] ]; + +my $kprobe_info + = Sys::Ebpf::Link::Perf::Kprobe::attach_kprobe( $prog_fd, $kprobe_fn ); + +print "Map FD: " . $map_kprobe_map->{map_fd} . "\n"; +print "Program FD: $prog_fd\n"; +sleep(1); +print "Counting file opens. Press Ctrl+C to stop.\n"; + +while (1) { + my $key = { kprobe_map_key => 1 }; + my $value = $map_kprobe_map->lookup($key); + if ( defined $value ) { + printf "Files opened: %d\n", $value->{kprobe_map_value}; + } + sleep(1); +} + +END { + if ($kprobe_info) { + Sys::Ebpf::Link::Perf::Kprobe::detach_kprobe($kprobe_info); + } +}