Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /* Copyright (c) 2015 PLUMgrid, http://plumgrid.com
0003  */
0004 #include <stdio.h>
0005 #include <stdlib.h>
0006 #include <signal.h>
0007 #include <unistd.h>
0008 #include <stdbool.h>
0009 #include <string.h>
0010 #include <time.h>
0011 
0012 #include <bpf/bpf.h>
0013 #include <bpf/libbpf.h>
0014 
0015 struct pair {
0016     long long val;
0017     __u64 ip;
0018 };
0019 
0020 static __u64 time_get_ns(void)
0021 {
0022     struct timespec ts;
0023 
0024     clock_gettime(CLOCK_MONOTONIC, &ts);
0025     return ts.tv_sec * 1000000000ull + ts.tv_nsec;
0026 }
0027 
0028 static void print_old_objects(int fd)
0029 {
0030     long long val = time_get_ns();
0031     __u64 key, next_key;
0032     struct pair v;
0033 
0034     key = write(1, "\e[1;1H\e[2J", 11); /* clear screen */
0035 
0036     key = -1;
0037     while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
0038         bpf_map_lookup_elem(fd, &next_key, &v);
0039         key = next_key;
0040         if (val - v.val < 1000000000ll)
0041             /* object was allocated more then 1 sec ago */
0042             continue;
0043         printf("obj 0x%llx is %2lldsec old was allocated at ip %llx\n",
0044                next_key, (val - v.val) / 1000000000ll, v.ip);
0045     }
0046 }
0047 
0048 int main(int ac, char **argv)
0049 {
0050     struct bpf_link *links[2];
0051     struct bpf_program *prog;
0052     struct bpf_object *obj;
0053     char filename[256];
0054     int map_fd, i, j = 0;
0055 
0056     snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
0057     obj = bpf_object__open_file(filename, NULL);
0058     if (libbpf_get_error(obj)) {
0059         fprintf(stderr, "ERROR: opening BPF object file failed\n");
0060         return 0;
0061     }
0062 
0063     /* load BPF program */
0064     if (bpf_object__load(obj)) {
0065         fprintf(stderr, "ERROR: loading BPF object file failed\n");
0066         goto cleanup;
0067     }
0068 
0069     map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
0070     if (map_fd < 0) {
0071         fprintf(stderr, "ERROR: finding a map in obj file failed\n");
0072         goto cleanup;
0073     }
0074 
0075     bpf_object__for_each_program(prog, obj) {
0076         links[j] = bpf_program__attach(prog);
0077         if (libbpf_get_error(links[j])) {
0078             fprintf(stderr, "ERROR: bpf_program__attach failed\n");
0079             links[j] = NULL;
0080             goto cleanup;
0081         }
0082         j++;
0083     }
0084 
0085     for (i = 0; ; i++) {
0086         print_old_objects(map_fd);
0087         sleep(1);
0088     }
0089 
0090 cleanup:
0091     for (j--; j >= 0; j--)
0092         bpf_link__destroy(links[j]);
0093 
0094     bpf_object__close(obj);
0095     return 0;
0096 }