我正在玩 gobpf 并且在計算跟蹤用戶空間函數的持續時間時遇到了問題。我使用 bpf_ktime_get_ns() 讀取時間,然后嘗試計算增量,但得到了巨大的數字,盡管跟蹤函數僅休眠 1 秒。這是經過測試的 C 程序,它有一個名為“ameba”的函數。#include <stdio.h>#include <strings.h>#include <stdlib.h>#include <time.h>#include <unistd.h>char * ameba(char * s1, char * s2);int main(void) { time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); printf("enter: %s", asctime (timeinfo)); printf("%s\n", ameba("lessqqmorepewpew", "good luck, have fun")); time(&rawtime); timeinfo = localtime(&rawtime); printf("return: %s", asctime(timeinfo));}char * ameba(char * s1, char * s2) { char *s; s = (char *) malloc(128); sleep(1); snprintf(s, 128, "phrase1: %s, phrase2: %s", s1, s2); return s;}去代碼package mainimport ( "bytes" "encoding/binary" "fmt" "os" "os/signal" "time" bpf "github.com/iovisor/gobpf/bcc")const source string = `#include <uapi/linux/ptrace.h>#include <linux/sched.h>struct val_t { u32 pid; char comm[TASK_COMM_LEN]; u64 ts;};struct data_t { u32 pid; char comm[TASK_COMM_LEN]; u64 delta; };BPF_HASH(start, u32, struct val_t);BPF_PERF_OUTPUT(ameba_events);int do_entry(struct pt_regs *ctx) { if (!PT_REGS_PARM1(ctx)) return 0; struct val_t val = {}; u32 pid = bpf_get_current_pid_tgid(); if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) { val.pid = bpf_get_current_pid_tgid(); val.ts = bpf_ktime_get_ns(); start.update(&pid, &val); } return 0;}int do_return(struct pt_regs *ctx) { struct val_t *valp; struct data_t data = {}; u64 delta; u32 pid = bpf_get_current_pid_tgid(); u64 tsp = bpf_ktime_get_ns(); valp = start.lookup(&pid); if (valp == 0) return 0; // missed start bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm); data.pid = valp->pid; data.delta = tsp - valp->ts; ameba_events.perf_submit(ctx, &data, sizeof(data)); start.delete(&pid); return 0;}錯在哪里??
1 回答

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
這看起來是由內核和用戶端之間的填充不匹配引起的。該data_t結構實際上在編譯時被填充為等同于以下內容:
struct data_t {
? ?u32 pid;
? ?char padding[4];
? ?char comm[TASK_COMM_LEN];
? ?u64 delta;? ??
};
如果你明確地在 Go 端添加相同的填充,你的問題就會消失:
type amebaEvent struct {
? ? Pid uint32
? ? Pad [4]byte
? ? Comm [16]byte
? ? Delta uint64
}
生產:
PID COMMAND DURATION? ? RAW
8258? ? a? ?1.000179625s? ? 1000179625
8260? ? a? ?1.000158337s? ? 1000158337
- 1 回答
- 0 關注
- 208 瀏覽
添加回答
舉報
0/150
提交
取消