xref: /aosp_15_r20/external/bcc/libbpf-tools/compat.h (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2022 Hengqi Chen */
3 
4 #ifndef __COMPAT_H
5 #define __COMPAT_H
6 
7 #include <stdlib.h>
8 #include <limits.h>
9 #include <sys/types.h>
10 #include <linux/bpf.h>
11 
12 #define POLL_TIMEOUT_MS 100
13 
14 struct bpf_buffer;
15 struct bpf_map;
16 
17 typedef int (*bpf_buffer_sample_fn)(void *ctx, void *data, size_t size);
18 typedef void (*bpf_buffer_lost_fn)(void *ctx, int cpu, __u64 cnt);
19 
20 struct bpf_buffer *bpf_buffer__new(struct bpf_map *events, struct bpf_map *heap);
21 int bpf_buffer__open(struct bpf_buffer *buffer, bpf_buffer_sample_fn sample_cb,
22 		     bpf_buffer_lost_fn lost_cb, void *ctx);
23 int bpf_buffer__poll(struct bpf_buffer *, int timeout_ms);
24 void bpf_buffer__free(struct bpf_buffer *);
25 
26 /* taken from libbpf */
27 #ifndef __has_builtin
28 #define __has_builtin(x) 0
29 #endif
30 
libbpf_reallocarray(void * ptr,size_t nmemb,size_t size)31 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
32 {
33 	size_t total;
34 
35 #if __has_builtin(__builtin_mul_overflow)
36 	if (__builtin_mul_overflow(nmemb, size, &total))
37 		return NULL;
38 #else
39 	if (size == 0 || nmemb > ULONG_MAX / size)
40 		return NULL;
41 	total = nmemb * size;
42 #endif
43 	return realloc(ptr, total);
44 }
45 
46 #endif /* __COMPAT_H */
47