hc
2024-05-10 37f49e37ab4cb5d0bc4c60eb5c6d4dd57db767bb
kernel/samples/bpf/test_probe_write_user_user.c
....@@ -1,21 +1,22 @@
11 // SPDX-License-Identifier: GPL-2.0
22 #include <stdio.h>
33 #include <assert.h>
4
-#include <linux/bpf.h>
54 #include <unistd.h>
65 #include <bpf/bpf.h>
7
-#include "bpf_load.h"
6
+#include <bpf/libbpf.h>
87 #include <sys/socket.h>
9
-#include <string.h>
108 #include <netinet/in.h>
119 #include <arpa/inet.h>
1210
1311 int main(int ac, char **argv)
1412 {
15
- int serverfd, serverconnfd, clientfd;
16
- socklen_t sockaddr_len;
17
- struct sockaddr serv_addr, mapped_addr, tmp_addr;
1813 struct sockaddr_in *serv_addr_in, *mapped_addr_in, *tmp_addr_in;
14
+ struct sockaddr serv_addr, mapped_addr, tmp_addr;
15
+ int serverfd, serverconnfd, clientfd, map_fd;
16
+ struct bpf_link *link = NULL;
17
+ struct bpf_program *prog;
18
+ struct bpf_object *obj;
19
+ socklen_t sockaddr_len;
1920 char filename[256];
2021 char *ip;
2122
....@@ -24,10 +25,35 @@
2425 tmp_addr_in = (struct sockaddr_in *)&tmp_addr;
2526
2627 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
28
+ obj = bpf_object__open_file(filename, NULL);
29
+ if (libbpf_get_error(obj)) {
30
+ fprintf(stderr, "ERROR: opening BPF object file failed\n");
31
+ return 0;
32
+ }
2733
28
- if (load_bpf_file(filename)) {
29
- printf("%s", bpf_log_buf);
30
- return 1;
34
+ prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
35
+ if (libbpf_get_error(prog)) {
36
+ fprintf(stderr, "ERROR: finding a prog in obj file failed\n");
37
+ goto cleanup;
38
+ }
39
+
40
+ /* load BPF program */
41
+ if (bpf_object__load(obj)) {
42
+ fprintf(stderr, "ERROR: loading BPF object file failed\n");
43
+ goto cleanup;
44
+ }
45
+
46
+ map_fd = bpf_object__find_map_fd_by_name(obj, "dnat_map");
47
+ if (map_fd < 0) {
48
+ fprintf(stderr, "ERROR: finding a map in obj file failed\n");
49
+ goto cleanup;
50
+ }
51
+
52
+ link = bpf_program__attach(prog);
53
+ if (libbpf_get_error(link)) {
54
+ fprintf(stderr, "ERROR: bpf_program__attach failed\n");
55
+ link = NULL;
56
+ goto cleanup;
3157 }
3258
3359 assert((serverfd = socket(AF_INET, SOCK_STREAM, 0)) > 0);
....@@ -51,7 +77,7 @@
5177 mapped_addr_in->sin_port = htons(5555);
5278 mapped_addr_in->sin_addr.s_addr = inet_addr("255.255.255.255");
5379
54
- assert(!bpf_map_update_elem(map_fd[0], &mapped_addr, &serv_addr, BPF_ANY));
80
+ assert(!bpf_map_update_elem(map_fd, &mapped_addr, &serv_addr, BPF_ANY));
5581
5682 assert(listen(serverfd, 5) == 0);
5783
....@@ -75,5 +101,8 @@
75101 /* Is the server's getsockname = the socket getpeername */
76102 assert(memcmp(&serv_addr, &tmp_addr, sizeof(struct sockaddr_in)) == 0);
77103
104
+cleanup:
105
+ bpf_link__destroy(link);
106
+ bpf_object__close(obj);
78107 return 0;
79108 }