1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 
4 void test_probe_user(void)
5 {
6 	const char *prog_name = "kprobe/__sys_connect";
7 	const char *obj_file = "./test_probe_user.o";
8 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts, );
9 	int err, results_map_fd, sock_fd, duration = 0;
10 	struct sockaddr curr, orig, tmp;
11 	struct sockaddr_in *in = (struct sockaddr_in *)&curr;
12 	struct bpf_link *kprobe_link = NULL;
13 	struct bpf_program *kprobe_prog;
14 	struct bpf_object *obj;
15 	static const int zero = 0;
16 
17 	obj = bpf_object__open_file(obj_file, &opts);
18 	if (!ASSERT_OK_PTR(obj, "obj_open_file"))
19 		return;
20 
21 	kprobe_prog = bpf_object__find_program_by_title(obj, prog_name);
22 	if (CHECK(!kprobe_prog, "find_probe",
23 		  "prog '%s' not found\n", prog_name))
24 		goto cleanup;
25 
26 	err = bpf_object__load(obj);
27 	if (CHECK(err, "obj_load", "err %d\n", err))
28 		goto cleanup;
29 
30 	results_map_fd = bpf_find_map(__func__, obj, "test_pro.bss");
31 	if (CHECK(results_map_fd < 0, "find_bss_map",
32 		  "err %d\n", results_map_fd))
33 		goto cleanup;
34 
35 	kprobe_link = bpf_program__attach(kprobe_prog);
36 	if (!ASSERT_OK_PTR(kprobe_link, "attach_kprobe"))
37 		goto cleanup;
38 
39 	memset(&curr, 0, sizeof(curr));
40 	in->sin_family = AF_INET;
41 	in->sin_port = htons(5555);
42 	in->sin_addr.s_addr = inet_addr("255.255.255.255");
43 	memcpy(&orig, &curr, sizeof(curr));
44 
45 	sock_fd = socket(AF_INET, SOCK_STREAM, 0);
46 	if (CHECK(sock_fd < 0, "create_sock_fd", "err %d\n", sock_fd))
47 		goto cleanup;
48 
49 	connect(sock_fd, &curr, sizeof(curr));
50 	close(sock_fd);
51 
52 	err = bpf_map_lookup_elem(results_map_fd, &zero, &tmp);
53 	if (CHECK(err, "get_kprobe_res",
54 		  "failed to get kprobe res: %d\n", err))
55 		goto cleanup;
56 
57 	in = (struct sockaddr_in *)&tmp;
58 	if (CHECK(memcmp(&tmp, &orig, sizeof(orig)), "check_kprobe_res",
59 		  "wrong kprobe res from probe read: %s:%u\n",
60 		  inet_ntoa(in->sin_addr), ntohs(in->sin_port)))
61 		goto cleanup;
62 
63 	memset(&tmp, 0xab, sizeof(tmp));
64 
65 	in = (struct sockaddr_in *)&curr;
66 	if (CHECK(memcmp(&curr, &tmp, sizeof(tmp)), "check_kprobe_res",
67 		  "wrong kprobe res from probe write: %s:%u\n",
68 		  inet_ntoa(in->sin_addr), ntohs(in->sin_port)))
69 		goto cleanup;
70 cleanup:
71 	bpf_link__destroy(kprobe_link);
72 	bpf_object__close(obj);
73 }
74