如何确认根据 BTF 计算的 offsetof 是否正确?
直接用 clang 来编译一小段 C 代码,然后跑一下即可。
C 代码模板:
#include <stdio.h>
#include <stddef.h>
#include "/root/vmlinux.h"
#define PRINT_STRUCT(struct_type, member) \
do { \
printf("Offset of '" #member "': %zu\n", offsetof(struct_type, member)); \
printf("Size of '" #member "': %zu\n", sizeof(((struct_type *)0)->member)); \
} while (0)
int main() {
PRINT_STRUCT(struct {{struct}}, {{member}});
return 0;
}
直接使用 bpftool btf dump file /sys/kernel/btf/vmlinux format c > /root/vmlinux.h 生成的 vmlinux.h。
然后编译并跑起来:
vmlinuxoffsetof () {
struct="$1"
member="$2"
verbose="$3"
if [[ -z $struct ]] || [[ -z $member ]]
then
echo "vmlinuxoffsetof <struct> <member>"
return
fi
cat /root/offsetof.c | sed 's/{{struct}}/'"${struct}"'/g' | sed 's/{{member}}/'"${member}"'/g' > /tmp/offsetof.c
clang /tmp/offsetof.c -Wno-unknown-attributes -o /tmp/offsetof
if [[ -n $verbose ]]
then
echo "Generated offsetof.c:"
echo ""
cat /tmp/offsetof.c
echo ""
fi
/tmp/offsetof
/usr/bin/rm -rf /tmp/offsetof
/usr/bin/rm -rf /tmp/offsetof.c
}
其中 -Wno-unknown-attributes 是用来干掉 warning: unknown attribute 'preserve_access_index' ignored [-Wunknown-attributes] 的。
效果如下:
$ vmlinuxoffsetof sk_buff dev
Offset of 'dev': 16
Size of 'dev': 8
$ vmlinuxoffsetof net_device ifindex
Offset of 'ifindex': 208
Size of 'ifindex': 4
#pwru #bice
直接用 clang 来编译一小段 C 代码,然后跑一下即可。
C 代码模板:
#include <stdio.h>
#include <stddef.h>
#include "/root/vmlinux.h"
#define PRINT_STRUCT(struct_type, member) \
do { \
printf("Offset of '" #member "': %zu\n", offsetof(struct_type, member)); \
printf("Size of '" #member "': %zu\n", sizeof(((struct_type *)0)->member)); \
} while (0)
int main() {
PRINT_STRUCT(struct {{struct}}, {{member}});
return 0;
}
直接使用 bpftool btf dump file /sys/kernel/btf/vmlinux format c > /root/vmlinux.h 生成的 vmlinux.h。
然后编译并跑起来:
vmlinuxoffsetof () {
struct="$1"
member="$2"
verbose="$3"
if [[ -z $struct ]] || [[ -z $member ]]
then
echo "vmlinuxoffsetof <struct> <member>"
return
fi
cat /root/offsetof.c | sed 's/{{struct}}/'"${struct}"'/g' | sed 's/{{member}}/'"${member}"'/g' > /tmp/offsetof.c
clang /tmp/offsetof.c -Wno-unknown-attributes -o /tmp/offsetof
if [[ -n $verbose ]]
then
echo "Generated offsetof.c:"
echo ""
cat /tmp/offsetof.c
echo ""
fi
/tmp/offsetof
/usr/bin/rm -rf /tmp/offsetof
/usr/bin/rm -rf /tmp/offsetof.c
}
其中 -Wno-unknown-attributes 是用来干掉 warning: unknown attribute 'preserve_access_index' ignored [-Wunknown-attributes] 的。
效果如下:
$ vmlinuxoffsetof sk_buff dev
Offset of 'dev': 16
Size of 'dev': 8
$ vmlinuxoffsetof net_device ifindex
Offset of 'ifindex': 208
Size of 'ifindex': 4
#pwru #bice