-
How are the items in struct of go associated with the items in struct of c? By the order of the items in struct or by the name of the items in the struct. When I try to use struct ip_tcp_rule{
__u8 flag;
__u32 src_ip;
__u8 src_ip_mask;
__u32 dst_ip;
__u8 dst_ip_mask;
__u8 min_ttl;
__u8 max_ttl;
__u16 src_port_min;
__u16 src_port_max;
__u16 dst_port_min;
__u16 dst_port_max;
};
struct bpf_map_def SEC("maps") ip_tcp_rules_0 =
{
.type = BPF_MAP_TYPE_ARRAY,
.key_size = sizeof(__u32),
.value_size = sizeof(struct ip_tcp_rule),
.max_entries = MAX_RULE_IP_TCP_NUM
}; code in go type ruleIpTcp struct {
Flag uint8 `json:"flag"`
SrcIp uint32 `json:"src_ip"`
SrcIpMask uint8 `json:"src_ip_mask"`
DstIp uint32 `json:"dst_ip"`
DstIpMask uint8 `json:"dst_ip_mask"`
MinTTL uint8 `json:"min_ttl"`
MaxTTL uint8 `json:"max_ttl"`
SrcPortMin uint16 `json:"src_port_min"`
SrcPortMax uint16 `json:"src_port_max"`
DstPortMin uint16 `json:"dst_port_min"`
DstPortMax uint16 `json:"dst_port_max"`
}
// ...
var v ruleIpTcp
ui := uint32(1)
// ...
err = opt_map.Update(ui, v, ebpf.UpdateAny) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I find the problem. I think that the size of the struct in go is 21, but the size of the struct in c is 28. So the items in struct of go associated with the items in struct of c by the order of items. When the struct is padded both in c and go, it works well. |
Beta Was this translation helpful? Give feedback.
-
There are many resources and tools available to work with Go struct alignment, and yes, it's something you need to pay attention to when sharing them between C and Go. The Go struct you pasted here seems to be 28 bytes long on a 64-bit architecture: https://go.dev/play/p/u4X0Vn-finI. Hint: run it through The following C program also evaluates to 28: #include <stdio.h>
typedef unsigned char __u8;
typedef short unsigned int __u16;
typedef unsigned int __u32;
typedef long long unsigned int __u64;
struct ip_tcp_rule{
__u8 flag;
__u32 src_ip;
__u8 src_ip_mask;
__u32 dst_ip;
__u8 dst_ip_mask;
__u8 min_ttl;
__u8 max_ttl;
__u16 src_port_min;
__u16 src_port_max;
__u16 dst_port_min;
__u16 dst_port_max;
};
int main() {
printf("%ld", sizeof(struct ip_tcp_rule));
return 0;
}
Clang's bpf backend may align fields differently for some reason, I'm not exactly sure why. You can use |
Beta Was this translation helpful? Give feedback.
There are many resources and tools available to work with Go struct alignment, and yes, it's something you need to pay attention to when sharing them between C and Go. The Go struct you pasted here seems to be 28 bytes long on a 64-bit architecture: https://go.dev/play/p/u4X0Vn-finI. Hint: run it through
structslop
to optimize its size.The following C program also evaluates to 28: