1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 #include <network_helpers.h>
4 
serial_test_flow_dissector_load_bytes(void)5 void serial_test_flow_dissector_load_bytes(void)
6 {
7 	struct bpf_flow_keys flow_keys;
8 	struct bpf_insn prog[] = {
9 		// BPF_REG_1 - 1st argument: context
10 		// BPF_REG_2 - 2nd argument: offset, start at first byte
11 		BPF_MOV64_IMM(BPF_REG_2, 0),
12 		// BPF_REG_3 - 3rd argument: destination, reserve byte on stack
13 		BPF_ALU64_REG(BPF_MOV, BPF_REG_3, BPF_REG_10),
14 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_3, -1),
15 		// BPF_REG_4 - 4th argument: copy one byte
16 		BPF_MOV64_IMM(BPF_REG_4, 1),
17 		// bpf_skb_load_bytes(ctx, sizeof(pkt_v4), ptr, 1)
18 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
19 			     BPF_FUNC_skb_load_bytes),
20 		BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 2),
21 		// if (ret == 0) return BPF_DROP (2)
22 		BPF_MOV64_IMM(BPF_REG_0, BPF_DROP),
23 		BPF_EXIT_INSN(),
24 		// if (ret != 0) return BPF_OK (0)
25 		BPF_MOV64_IMM(BPF_REG_0, BPF_OK),
26 		BPF_EXIT_INSN(),
27 	};
28 	int fd, err;
29 	LIBBPF_OPTS(bpf_test_run_opts, topts,
30 		.data_in = &pkt_v4,
31 		.data_size_in = sizeof(pkt_v4),
32 		.data_out = &flow_keys,
33 		.data_size_out = sizeof(flow_keys),
34 		.repeat = 1,
35 	);
36 
37 	/* make sure bpf_skb_load_bytes is not allowed from skb-less context
38 	 */
39 	fd = bpf_test_load_program(BPF_PROG_TYPE_FLOW_DISSECTOR, prog,
40 			      ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
41 	ASSERT_GE(fd, 0, "bpf_test_load_program good fd");
42 
43 	err = bpf_prog_test_run_opts(fd, &topts);
44 	ASSERT_OK(err, "test_run");
45 	ASSERT_EQ(topts.data_size_out, sizeof(flow_keys),
46 		  "test_run data_size_out");
47 	ASSERT_EQ(topts.retval, BPF_OK, "test_run retval");
48 
49 	if (fd >= -1)
50 		close(fd);
51 }
52