Skip to content

Commit

Permalink
feat: add sample kprobe_file_open_counter
Browse files Browse the repository at this point in the history
  • Loading branch information
takehaya committed Sep 27, 2024
1 parent 6dc7e1e commit 0afd7dd
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
3 changes: 3 additions & 0 deletions sample/kprobe_file_open_counter/build.sh
Original file line number Diff line number Diff line change
@@ -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
32 changes: 32 additions & 0 deletions sample/kprobe_file_open_counter/kprobe_file_open_counter.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <linux/bpf.h>
#include <linux/ptrace.h>

#include <bpf/bpf_helpers.h>

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";
42 changes: 42 additions & 0 deletions sample/kprobe_file_open_counter/kprobe_file_open_counter.pl
Original file line number Diff line number Diff line change
@@ -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);
}
}

0 comments on commit 0afd7dd

Please sign in to comment.