我正在扩展一个程序,它接受跟踪函数的参数并打印它。数字参数和短字符串一切正常。但目前尚不清楚如何处理长于 eBPF 中堆栈大小的长字符串(限制为 512 字节)。
在下面的例子中,字符串被限制为 80 字节,当然最多可以增加到 512,但是如何跟踪更长的字符串呢?
带有被称为“ameba”的跟踪函数的 C 程序示例
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
char * ameba(char * s1);
int main(void) {
printf("%s\n", ameba("verylonglongstring...1111111111111111111111111111111111111111111111111111111111111111111111111111"));
}
char * ameba(char * s1) {
char *s;
s = (char *) malloc(128);
sleep(1);
snprintf(s, 128, "ameba: %s", s1);
return s;
}
Go 代码示例
package main
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"os/signal"
"unsafe"
bpf "github.com/iovisor/gobpf/bcc"
)
const source string = `
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct ameba_event_t {
u32 pid;
char comm[TASK_COMM_LEN];
char arg1[80];
} __attribute__((packed));
BPF_PERF_OUTPUT(ameba_events);
int get_input_args(struct pt_regs *ctx) {
struct ameba_event_t event = {};
if (!PT_REGS_PARM1(ctx))
return 0;
event.pid = bpf_get_current_pid_tgid();
bpf_get_current_comm(&event.comm, sizeof(event.comm));
bpf_probe_read(&event.arg1, sizeof(event.arg1), (void *)PT_REGS_PARM1(ctx));
ameba_events.perf_submit(ctx, &event, sizeof(event));
return 0;
}
`
type amebaEvent struct {
Pid uint32
Comm [16]byte
Arg1 [80]byte
}
func main() {
m := bpf.NewModule(source, []string{})
defer m.Close()
amebaUprobe, err := m.LoadUprobe("get_input_args")
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load get_input_args: %s\n", err)
os.Exit(1)
}
err = m.AttachUprobe("/home/lesovsky/Git/sandbox/ameba", "ameba", amebaUprobe, -1)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to attach input_args: %s\n", err)
os.Exit(1)
}
table := bpf.NewTable(m.TableId("ameba_events"), m)
channel := make(chan []byte)
perfMap, err := bpf.InitPerfMap(table, channel)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to init perf map: %s\n", err)
os.Exit(1)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
fmt.Printf("%10s\t%s\t%s\n", "PID", "COMMAND", "ARG1")
go func() {
var event amebaEvent
for {
data := <-channel
err := binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &event)
if err != nil {
fmt.Printf("failed to decode received data: %s\n", err)
continue
}
comm := (*C.char)(unsafe.Pointer(&event.Comm))
query := (*C.char)(unsafe.Pointer(&event.Query))
fmt.Printf("%10d\t%s\t%s\n", event.Pid, C.GoString(comm), C.GoString(query))
}
}()
perfMap.Start()
<-sig
perfMap.Stop()
}
我读到了 BPF_MAP_TYPE_PERCPU_ARRAY 在这种情况下可能会有所帮助,但我不清楚如何使用它。
编辑:Go 程序已修改为使用“C”和“不安全”。