尝试 运行 BPF 程序时缺少右括号和引号

Missing closing bracket and quotes when trying to run BPF programs

我的代码中一直出现缺少终止符的错误。我的目标是逐字打印字符串。这是代码。

bpfprogram = """

int helloworld2(void *ctx)
{

    const char *str = "here are some words";
    int length = sizeof(str);
    int start = 0;
    for (int i = 0; i < length; i++) {
        if (str[i] == ' ') {
            bpf_trace_printk("%.*s\n", i - start, str + start);
            start = i + 1;
        }
    }
    bpf_trace_printk("%.*s\n", length - start, str + start);

    return 0;
}
"""
# This compiles the program defined by the bpfprogram string into bpf bytecode and
#loads it to the kernel BPF verifier.
b = BPF(text=bpfprogram)
# This attaches the compiled BPF program to a kernel event of your choosing,
#in this case to the sys_clone syscall which will cause the BPF program to run
#everytime the sys_clone call occurs.
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="helloworld2")
# Capture and print the BPF program's trace output
b.trace_print()

这是我一直遇到的终止错误。我确信引号没问题,但我不确定此时我的错误在哪里。

> /virtual/main.c:11:30: warning: missing terminating '"' character [-Winvalid-pp-token]
            bpf_trace_printk("%.*s
                             ^
/virtual/main.c:11:30: error: expected expression
/virtual/main.c:12:1: warning: missing terminating '"' character [-Winvalid-pp-token]
", i - start, str + start);
^
/virtual/main.c:16:22: warning: missing terminating '"' character [-Winvalid-pp-token]
    bpf_trace_printk("%.*s
                     ^
/virtual/main.c:16:22: error: expected expression
/virtual/main.c:17:1: warning: missing terminating '"' character [-Winvalid-pp-token]
", length - start, str + start);
^
/virtual/main.c:20:2: error: expected '}'
}
 ^
/virtual/main.c:9:38: note: to match this '{'
    for (int i = 0; i < length; i++) {
                                     ^
/virtual/main.c:20:2: error: expected '}'
}
 ^
/virtual/main.c:4:1: note: to match this '{'
{
^
4 warnings and 4 errors generated.
Traceback (most recent call last):
  File "BPFHelloWorld.py", line 26, in <module>
    b = BPF(text=bpfprogram)
  File "/usr/lib/python3/dist-packages/bcc/__init__.py", line 347, in __init__
    raise Exception("Failed to compile BPF module %s" % (src_file or "<text>"))
Exception: Failed to compile BPF module <te

xt>

I am sure the quotes are fine

但他们不是:)

您所有的 eBPF 代码都在 Python 多行字符串(""" 块)中。在这个字符串中,换行符(\n)被正常解释,这意味着当Python使用它时插入一个换行符,传递给clang的行是:

bpf_trace_printk("%.*s

...确实缺少结尾引号。就像在其他 BCC 示例中一样,只需转义此反斜杠即可:

bpf_trace_printk("%.*s\n", ...);