xref: /linux/tools/testing/selftests/bpf/progs/load_bytes_relative.c (revision 48dea9a700c8728cc31a1dd44588b97578de86ee)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /*
4  * Copyright 2020 Google LLC.
5  */
6 
7 #include <errno.h>
8 #include <linux/bpf.h>
9 #include <linux/if_ether.h>
10 #include <linux/ip.h>
11 #include <bpf/bpf_helpers.h>
12 
13 struct {
14 	__uint(type, BPF_MAP_TYPE_ARRAY);
15 	__uint(max_entries, 1);
16 	__type(key, __u32);
17 	__type(value, __u32);
18 } test_result SEC(".maps");
19 
20 SEC("cgroup_skb/egress")
21 int load_bytes_relative(struct __sk_buff *skb)
22 {
23 	struct ethhdr eth;
24 	struct iphdr iph;
25 
26 	__u32 map_key = 0;
27 	__u32 test_passed = 0;
28 
29 	/* MAC header is not set by the time cgroup_skb/egress triggers */
30 	if (bpf_skb_load_bytes_relative(skb, 0, &eth, sizeof(eth),
31 					BPF_HDR_START_MAC) != -EFAULT)
32 		goto fail;
33 
34 	if (bpf_skb_load_bytes_relative(skb, 0, &iph, sizeof(iph),
35 					BPF_HDR_START_NET))
36 		goto fail;
37 
38 	if (bpf_skb_load_bytes_relative(skb, 0xffff, &iph, sizeof(iph),
39 					BPF_HDR_START_NET) != -EFAULT)
40 		goto fail;
41 
42 	test_passed = 1;
43 
44 fail:
45 	bpf_map_update_elem(&test_result, &map_key, &test_passed, BPF_ANY);
46 
47 	return 1;
48 }
49