diff --git a/libbpf-tools/.gitignore b/libbpf-tools/.gitignore index 92882260a948..7ec996c6d654 100644 --- a/libbpf-tools/.gitignore +++ b/libbpf-tools/.gitignore @@ -31,6 +31,7 @@ /klockstat /ksnoop /llcstat +/lsan /memleak /mdflush /mountsnoop diff --git a/libbpf-tools/Makefile b/libbpf-tools/Makefile index 9171dacd3df3..abcefc54fa6e 100644 --- a/libbpf-tools/Makefile +++ b/libbpf-tools/Makefile @@ -62,6 +62,7 @@ APPS = \ klockstat \ ksnoop \ llcstat \ + lsan \ mdflush \ mountsnoop \ numamove \ diff --git a/libbpf-tools/cvector.h b/libbpf-tools/cvector.h new file mode 100644 index 000000000000..3b3df2bd5aea --- /dev/null +++ b/libbpf-tools/cvector.h @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2015 Evan Teran + * + * License: The MIT License (MIT) + */ + +#ifndef CVECTOR_H_ +#define CVECTOR_H_ + +#include /* for assert */ +#include /* for malloc/realloc/free */ +#include /* for memcpy/memmove */ + +/* cvector heap implemented using C library malloc() */ + +/* in case C library malloc() needs extra protection, + * allow these defines to be overridden. + */ +#ifndef cvector_clib_free +#define cvector_clib_free free +#endif +#ifndef cvector_clib_malloc +#define cvector_clib_malloc malloc +#endif +#ifndef cvector_clib_calloc +#define cvector_clib_calloc calloc +#endif +#ifndef cvector_clib_realloc +#define cvector_clib_realloc realloc +#endif + +typedef void (*cvector_elem_destructor_t)(void *elem); + +/** + * @brief cvector_vector_type - The vector type used in this library + */ +#define cvector_vector_type(type) type * + +/** + * @brief cvector_capacity - gets the current capacity of the vector + * @param vec - the vector + * @return the capacity as a size_t + */ +#define cvector_capacity(vec) \ + ((vec) ? ((size_t *)(vec))[-1] : (size_t)0) + +/** + * @brief cvector_size - gets the current size of the vector + * @param vec - the vector + * @return the size as a size_t + */ +#define cvector_size(vec) \ + ((vec) ? ((size_t *)(vec))[-2] : (size_t)0) + +/** + * @brief cvector_set_elem_destructor - set the element destructor function + * used to clean up removed elements + * @param vec - the vector + * @return elem_destructor_fn - function pointer of type cvector_elem_destructor_t + * @return the function pointer elem_destructor_fn or NULL on error + */ +#define cvector_set_elem_destructor(vec, elem_destructor_fn) \ + do { \ + if (!(vec)) { \ + cvector_grow((vec), 0); \ + } \ + ((cvector_elem_destructor_t *)&(((size_t *)(vec))[-2]))[-1] = (elem_destructor_fn); \ + } while (0) + +/** + * @brief cvector_elem_destructor - get the element destructor function used + * to clean up elements + * @param vec - the vector + * @return the function pointer as cvector_elem_destructor_t + */ +#define cvector_elem_destructor(vec) \ + ((vec) ? (((cvector_elem_destructor_t *)&(((size_t *)(vec))[-2]))[-1]) : NULL) + +/** + * @brief cvector_empty - returns non-zero if the vector is empty + * @param vec - the vector + * @return non-zero if empty, zero if non-empty + */ +#define cvector_empty(vec) \ + (cvector_size(vec) == 0) + +/** + * @brief cvector_reserve - Requests that the vector capacity be at least enough + * to contain n elements. If n is greater than the current vector capacity, the + * function causes the container to reallocate its storage increasing its + * capacity to n (or greater). + * @param vec - the vector + * @param n - Minimum capacity for the vector. + * @return void + */ +#define cvector_reserve(vec, capacity) \ + do { \ + size_t cv_cap__ = cvector_capacity(vec); \ + if (cv_cap__ < (capacity)) { \ + cvector_grow((vec), (capacity)); \ + } \ + } while (0) + +/** + * @brief cvector_erase - removes the element at index i from the vector + * @param vec - the vector + * @param i - index of element to remove + * @return void + */ +#define cvector_erase(vec, i) \ + do { \ + if ((vec)) { \ + const size_t cv_sz__ = cvector_size(vec); \ + if ((i) < cv_sz__) { \ + cvector_set_size((vec), cv_sz__ - 1); \ + memmove((vec) + (i), (vec) + (i) + 1, sizeof(*(vec)) * (cv_sz__ - 1 - (i))); \ + } \ + } \ + } while (0) + +/** + * @brief cvector_free - frees all memory associated with the vector + * @param vec - the vector + * @return void + */ +#define cvector_free(vec) \ + do { \ + if ((vec)) { \ + size_t *p1__ = (size_t *)&(((cvector_elem_destructor_t *)&(((size_t *)(vec))[-2]))[-1]); \ + cvector_elem_destructor_t elem_destructor__ = cvector_elem_destructor((vec)); \ + if (elem_destructor__) { \ + size_t i__; \ + for (i__ = 0; i__ < cvector_size(vec); ++i__) \ + elem_destructor__(&vec[i__]); \ + } \ + cvector_clib_free(p1__); \ + } \ + } while (0) + +/** + * @brief cvector_begin - returns an iterator to first element of the vector + * @param vec - the vector + * @return a pointer to the first element (or NULL) + */ +#define cvector_begin(vec) \ + (vec) + +/** + * @brief cvector_end - returns an iterator to one past the last element of the vector + * @param vec - the vector + * @return a pointer to one past the last element (or NULL) + */ +#define cvector_end(vec) \ + ((vec) ? &((vec)[cvector_size(vec)]) : NULL) + +/* user request to use logarithmic growth algorithm */ +#ifdef CVECTOR_LOGARITHMIC_GROWTH + +/** + * @brief cvector_compute_next_grow - returns an the computed size in next vector grow + * size is increased by multiplication of 2 + * @param size - current size + * @return size after next vector grow + */ +#define cvector_compute_next_grow(size) \ + ((size) ? ((size) << 1) : 1) + +#else + +/** + * @brief cvector_compute_next_grow - returns an the computed size in next vector grow + * size is increased by 1 + * @param size - current size + * @return size after next vector grow + */ +#define cvector_compute_next_grow(size) \ + ((size) + 1) + +#endif /* CVECTOR_LOGARITHMIC_GROWTH */ + +/** + * @brief cvector_push_back - adds an element to the end of the vector + * @param vec - the vector + * @param value - the value to add + * @return void + */ +#define cvector_push_back(vec, value) \ + do { \ + size_t cv_cap__ = cvector_capacity(vec); \ + if (cv_cap__ <= cvector_size(vec)) { \ + cvector_grow((vec), cvector_compute_next_grow(cv_cap__)); \ + } \ + (vec)[cvector_size(vec)] = (value); \ + cvector_set_size((vec), cvector_size(vec) + 1); \ + } while (0) + +/** + * @brief cvector_insert - insert element at position pos to the vector + * @param vec - the vector + * @param pos - position in the vector where the new elements are inserted. + * @param val - value to be copied (or moved) to the inserted elements. + * @return void + */ +#define cvector_insert(vec, pos, val) \ + do { \ + if (cvector_capacity(vec) <= cvector_size(vec) + 1) { \ + cvector_grow((vec), cvector_compute_next_grow(cvector_capacity((vec)))); \ + } \ + if ((pos) < cvector_size(vec)) { \ + memmove((vec) + (pos) + 1, (vec) + (pos), sizeof(*(vec)) * ((cvector_size(vec) + 1) - (pos))); \ + } \ + (vec)[(pos)] = (val); \ + cvector_set_size((vec), cvector_size(vec) + 1); \ + } while (0) + +/** + * @brief cvector_pop_back - removes the last element from the vector + * @param vec - the vector + * @return void + */ +#define cvector_pop_back(vec) \ + do { \ + cvector_elem_destructor_t elem_destructor__ = cvector_elem_destructor((vec)); \ + if (elem_destructor__) \ + elem_destructor__(&(vec)[cvector_size(vec) - 1]); \ + cvector_set_size((vec), cvector_size(vec) - 1); \ + } while (0) + +/** + * @brief cvector_copy - copy a vector + * @param from - the original vector + * @param to - destination to which the function copy to + * @return void + */ +#define cvector_copy(from, to) \ + do { \ + if ((from)) { \ + cvector_grow(to, cvector_size(from)); \ + cvector_set_size(to, cvector_size(from)); \ + memcpy((to), (from), cvector_size(from) * sizeof(*(from))); \ + } \ + } while (0) + +/** + * @brief cvector_set_capacity - For internal use, sets the capacity variable of the vector + * @param vec - the vector + * @param size - the new capacity to set + * @return void + */ +#define cvector_set_capacity(vec, size) \ + do { \ + if ((vec)) { \ + ((size_t *)(vec))[-1] = (size); \ + } \ + } while (0) + +/** + * @brief cvector_set_size - For internal use, sets the size variable of the vector + * @param vec - the vector + * @param size - the new capacity to set + * @return void + */ +#define cvector_set_size(vec, size) \ + do { \ + if ((vec)) { \ + ((size_t *)(vec))[-2] = (size); \ + } \ + } while (0) + +/** + * @brief cvector_grow - For internal use, ensures that the vector is at least elements big + * @param vec - the vector + * @param count - the new capacity to set + * @return void + */ +#define cvector_grow(vec, count) \ + do { \ + const size_t cv_sz__ = (count) * sizeof(*(vec)) + sizeof(size_t) * 2 + sizeof(cvector_elem_destructor_t); \ + if ((vec)) { \ + cvector_elem_destructor_t *cv_p1__ = &((cvector_elem_destructor_t *)&((size_t *)(vec))[-2])[-1]; \ + cvector_elem_destructor_t *cv_p2__ = cvector_clib_realloc(cv_p1__, cv_sz__); \ + assert(cv_p2__); \ + (vec) = (void *)&((size_t *)&cv_p2__[1])[2]; \ + } else { \ + cvector_elem_destructor_t *cv_p__ = cvector_clib_malloc(cv_sz__); \ + assert(cv_p__); \ + (vec) = (void *)&((size_t *)&cv_p__[1])[2]; \ + cvector_set_size((vec), 0); \ + ((cvector_elem_destructor_t *)&(((size_t *)(vec))[-2]))[-1] = NULL; \ + } \ + cvector_set_capacity((vec), (count)); \ + } while (0) + +#endif /* CVECTOR_H_ */ diff --git a/libbpf-tools/lsan.bpf.c b/libbpf-tools/lsan.bpf.c new file mode 100644 index 000000000000..913fc5c6e220 --- /dev/null +++ b/libbpf-tools/lsan.bpf.c @@ -0,0 +1,214 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* Copyright (c) 2022 LG Electronics */ +#include +#include +#include +#include +#include "lsan.h" + +const volatile bool kernel_threads_only = false; +const volatile bool user_threads_only = false; +const volatile pid_t targ_tgid = -1; +const volatile pid_t targ_pid = -1; + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 64); + __type(key, u64); + __type(value, u64); +} sizes SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, MAX_ENTRIES); + __type(key, u64); + __type(value, struct lsan_info_t); +} allocs SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, MAX_ENTRIES); + __type(key, u64); + __type(value, u64); +} memptrs SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_STACK_TRACE); + __uint(max_entries, MAX_ENTRIES); + __uint(key_size, sizeof(u32)); +} stack_traces SEC(".maps"); + +int gen_alloc_enter(struct pt_regs *ctx, size_t size) +{ + u64 pid = bpf_get_current_pid_tgid(); + u64 size64 = size; + + bpf_map_update_elem(&sizes, &pid, &size64, BPF_ANY); + return 0; +} + +int gen_alloc_exit2(struct pt_regs *ctx, u64 address) +{ + u64 pid = bpf_get_current_pid_tgid(); + u64 *size64 = bpf_map_lookup_elem(&sizes, &pid); + struct lsan_info_t info = {0, }; + + if (size64 == NULL) + return 0; + + info.size = *size64; + bpf_map_delete_elem(&sizes, &pid); + if (address != 0) { + info.stack_id = bpf_get_stackid(ctx, &stack_traces, BPF_F_USER_STACK); + info.tag = DIRECTLY_LEAKED; + bpf_map_update_elem(&allocs, &address, &info, BPF_ANY); + } + return 0; +} + +int gen_alloc_exit(struct pt_regs *ctx) +{ + return gen_alloc_exit2(ctx, PT_REGS_RC(ctx)); +} + +int gen_free_enter(struct pt_regs *ctx, void *address) +{ + u64 addr = (u64)address; + + bpf_map_delete_elem(&allocs, &addr); + return 0; +} + +SEC("kprobe/dummy_malloc") +int BPF_KPROBE(malloc_entry, size_t size) +{ + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_malloc") +int BPF_KRETPROBE(malloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_free") +int BPF_KPROBE(free_entry, void *address) +{ + return gen_free_enter(ctx, address); +} + +SEC("kprobe/dummy_calloc") +int BPF_KPROBE(calloc_entry, size_t nmemb, size_t size) +{ + return gen_alloc_enter(ctx, nmemb * size); +} + +SEC("kretprobe/dummy_calloc") +int BPF_KRETPROBE(calloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_realloc") +int BPF_KPROBE(realloc_entry, void *ptr, size_t size) +{ + gen_free_enter(ctx, ptr); + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_realloc") +int BPF_KRETPROBE(realloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_posix_memalign") +int BPF_KPROBE(posix_memalign_entry, void **memptr, size_t alignment, size_t size) +{ + u64 memptr64 = (u64)(size_t)memptr; + u64 pid = bpf_get_current_pid_tgid(); + + bpf_map_update_elem(&memptrs, &pid, &memptr64, BPF_ANY); + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_posix_memalign") +int BPF_KRETPROBE(posix_memalign_return) +{ + void *addr = NULL; + u64 pid = bpf_get_current_pid_tgid(); + u64 *memptr64 = bpf_map_lookup_elem(&memptrs, &pid); + + if (memptr64 == NULL) + return 0; + + bpf_map_delete_elem(&memptrs, &pid); + if (bpf_probe_read_user(&addr, sizeof(void *), (void *)(size_t)*memptr64)) + return 0; + + u64 addr64 = (u64)(size_t)addr; + return gen_alloc_exit2(ctx, addr64); +} + +SEC("kprobe/dummy_aligned_alloc") +int BPF_KPROBE(aligned_alloc_entry, size_t alignment, size_t size) +{ + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_aligned_alloc") +int BPF_KRETPROBE(aligned_alloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_valloc") +int BPF_KPROBE(valloc_entry, size_t size) +{ + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_valloc") +int BPF_KRETPROBE(valloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_memalign") +int BPF_KPROBE(memalign_entry, size_t alignment, size_t size) +{ + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_memalign") +int BPF_KRETPROBE(memalign_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_pvalloc") +int BPF_KPROBE(pvalloc_entry, size_t size) +{ + return gen_alloc_enter(ctx, size); +} + +SEC("kretprobe/dummy_pvalloc") +int BPF_KRETPROBE(pvalloc_return) +{ + return gen_alloc_exit(ctx); +} + +SEC("kprobe/dummy_reallocarray") +int BPF_KPROBE(reallocarray_entry, void *ptr, size_t nmemb, size_t size) +{ + gen_free_enter(ctx, ptr); + return gen_alloc_enter(ctx, nmemb * size); +} + +SEC("kretprobe/dummy_reallocarray") +int BPF_KRETPROBE(reallocarray_return) +{ + return gen_alloc_exit(ctx); +} + +char _license[] SEC("license") = "GPL"; diff --git a/libbpf-tools/lsan.c b/libbpf-tools/lsan.c new file mode 100644 index 000000000000..38ab7b204c71 --- /dev/null +++ b/libbpf-tools/lsan.c @@ -0,0 +1,1168 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* Copyright (c) 2022 LG Electronics */ + +// 19-Jul-2022 Bojun Seo Created this. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "lsan.h" +#include "lsan.skel.h" +#include "trace_helpers.h" +#include "uprobe_helpers.h" +#include "cvector.h" +#include "uthash.h" + +enum log_level { + DEBUG, + INFO, + WARN, + ERROR, +}; + +void __p(enum log_level level, char *level_str, char *fmt, ...); +void set_log_level(enum log_level level); + +#define p_debug(fmt, ...) __p(DEBUG, "Debug", fmt, ##__VA_ARGS__) +#define p_info(fmt, ...) __p(INFO, "Info", fmt, ##__VA_ARGS__) +#define p_warn(fmt, ...) __p(WARN, "Warn", fmt, ##__VA_ARGS__) +#define p_err(fmt, ...) __p(ERROR, "Error", fmt, ##__VA_ARGS__) + +pid_t execute_process(char *); + +#define ON_MEM_FAILURE(buf) \ +if (NULL == buf) { \ + p_err("FATAL: Failed to allocate memory on %s", __func__); \ + exit(-1); \ +} + +#define GET_PID_LIB_PATH 1 +#define LIBC_FILE "c" +#define LIBC_PATH_SIZE 32 + +#define GET_LIBC_PATH() ({ \ + static char libc_path[PATH_MAX]; \ + get_pid_lib_path(GET_PID_LIB_PATH, LIBC_FILE, libc_path, PATH_MAX); \ + libc_path; \ +}) + +#define get_elf_func_offset_impl(func) \ +({ \ + char *libc_path = GET_LIBC_PATH(); \ + off_t func_off = get_elf_func_offset(libc_path, func); \ + if (func_off < 0) { \ + p_warn("could not find %s in %s", func, libc_path); \ + return -1; \ + } \ + func_off; \ +}) + +#define __attach_uprobe(obj, func_name, uretprobe, func_off, pid) \ +({ \ + char *libc_path = GET_LIBC_PATH(); \ + obj->links.func_name = \ + bpf_program__attach_uprobe(obj->progs.func_name, uretprobe, \ + pid ? : -1, libc_path, func_off); \ + int err = libbpf_get_error(obj->links.func_name); \ + if (err) { \ + p_warn("failed to attach %s: %d", #func_name, err); \ + return -1; \ + } \ +}) + +#define _attach_uprobe(obj, func_name_str, func_name, pid) \ +({ \ + off_t func_off = get_elf_func_offset_impl(func_name_str); \ + __attach_uprobe(obj, func_name##_entry, false, func_off, pid); \ + __attach_uprobe(obj, func_name##_return, true, func_off, pid); \ +}) + +/* default */ +static enum log_level log_level = ERROR; + +void sig_handler(int signo) +{ + if (signo == SIGINT || signo == SIGTERM) + kill(0, SIGKILL); +} + +void __p(enum log_level level, char *level_str, char *fmt, ...) +{ + va_list ap; + + if (level < log_level) + return; + va_start(ap, fmt); + fprintf(stderr, "%s: ", level_str); + vfprintf(stderr, fmt, ap); + fprintf(stderr, "\n"); + va_end(ap); + fflush(stderr); +} + +void set_log_level(enum log_level level) +{ + log_level = level; +} + +pid_t execute_process(char *cmd) +{ + const char *delim = " "; + char **argv, *ptr, *filepath; + pid_t pid = 0; + int i; + + if (cmd == NULL) { + p_warn("Invalid argument: command not found"); + exit(-1); + } else + p_info("Execute child process: %s", cmd); + + argv = calloc(sizeof(char *), strlen(cmd)); + if (argv == NULL) { + p_err("failed to alloc memory"); + goto cleanup; + } + + ptr = strtok(cmd, delim); + if (ptr != NULL) { + filepath = ptr; + ptr = strtok(NULL, delim); + } else { + p_err("failed to exec %s", cmd); + goto cleanup; + } + + i = 0; + argv[i++] = filepath; + while (ptr != NULL) { + argv[i++] = ptr; + ptr = strtok(NULL, delim); + } + + pid = fork(); + if (pid == 0) { + execve(filepath, argv, NULL); + } else if (pid > 0) { + signal(SIGINT, sig_handler); + free(argv); + return pid; + } else { + p_err("failed to exec %s", cmd); + exit(-1); + } + +cleanup: + free(argv); + return -1; +} + +int get_tasks(pid_t pid, int *tasks, size_t len) +{ + int nr_task = 0; + char path[PATH_MAX]; + struct dirent *ent; + DIR *dp; + + snprintf(path, sizeof(path), "/proc/%d/task", pid); + + dp = opendir(path); + if (dp == NULL) + return -errno; + + while ((ent = readdir(dp)) != NULL) { + if (nr_task >= len) + return -ENOMEM; + + if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) + continue; + + tasks[nr_task++] = strtol(ent->d_name, NULL, 10); + } + + closedir(dp); + + return nr_task; +} + +//#define USE_PROCESS_VM_READV +#define LSAN_OPTIMIZED +#define STACK_MAX 127 +#define BUF_MAX (STACK_MAX * LINE_MAX * 2) + +enum maps { + MAPS_ADDRESS = 0, + MAPS_PERMISSIONS = 1, + MAPS_OFFSET = 2, + MAPS_DEVICE = 3, + MAPS_INODE = 4, + MAPS_PATH = 5, + MAPS_COLUMN_MAX = 6 +}; + +static struct env { + /* main process's tid */ + pid_t pid; + /* thread group id(pid) */ + pid_t tgid; + int stack_storage_size; + int perf_max_stack_depth; + /* unit: second */ + int interval; + int top; + bool verbose; + bool stop_the_world; + char* command; + char* suppr; +} env = { + .pid = -1, + .tgid = -1, + .stack_storage_size = MAX_ENTRIES, + .perf_max_stack_depth = STACK_MAX, + .interval = 10, + .top = -1, + .verbose = false, + .stop_the_world = false, + .command = NULL, + .suppr = "/usr/etc/suppr.txt", +}; + +typedef unsigned long long uptr; +struct lsan_hash_t { + __u64 size; + int stack_id; + enum chunk_tag tag; + uptr id; + UT_hash_handle hh; +}; + +struct report_info_t { + __u64 size; + int count; + int id; + UT_hash_handle hh; +}; + +struct root_region_t { + uptr end; + bool is_heap; + /* begin */ + uptr id; + UT_hash_handle hh; +}; + +struct lsan_hash_t *copied = NULL; +struct report_info_t *direct = NULL; +struct report_info_t *indirect = NULL; +struct root_region_t *certain = NULL; +struct root_region_t *uncertain = NULL; + +const char *argp_program_version = "lsan 0.1"; +const char *argp_program_bug_address = + "https://github.com/iovisor/bcc/tree/master/libbpf-tools"; +const char argp_program_doc[] = "Detect memory leak resulting from dangling pointers.\n" +"\n" +"Either -c or -p is a mandatory option\n" +"EXAMPLES:\n" +" lsan -p 1234 # Detect leaks on process id 1234\n" +" lsan -c a.out # Detect leaks on a.out\n" +" lsan -c 'a.out arg' # Detect leaks on a.out with argument\n" +" lsan -c \"a.out arg\" # Detect leaks on a.out with argument\n"; +static const struct argp_option opts[] = { + { "verbose", 'v', NULL, 0, "Verbose debug output" }, + { "help", 'h', NULL, OPTION_HIDDEN, "Show the full help" }, + { "pid", 'p', "PID", 0, "Set pid" }, + { "stop-the-world", 'w', NULL, 0, "Stop the world during tracing" }, + { "command", 'c', "COMMAND", 0, "Execute and trace the specified command" }, + { "interval", 'i', "INTERVAL", 0, "Set interval in second to detect leak" }, + { "top", 'T', "TOP", 0, "Report only specified amount of backtraces"}, + { "suppressions", 's', "SUPPRESSIONS", 0, "Suppressions file name"}, + {}, +}; +const char *rw_permission = "rw"; +const char *heap_str = "[heap]"; +const char *stack_str = "[stack]"; +const size_t word_size = sizeof(void*); +struct lsan_bpf *obj = NULL; +cvector_vector_type(uptr) frontier = NULL; +cvector_vector_type(uptr) key_table = NULL; +cvector_vector_type(pid_t) tids = NULL; +cvector_vector_type(char*) suppression = NULL; +FILE *fp_mem = NULL; + +typedef void (*for_each_chunk_callback)(uptr chunk); + +static int libbpf_print_fn(enum libbpf_print_level level, + const char *format, va_list args) +{ + if (level == LIBBPF_DEBUG && !env.verbose) + return 0; + return vfprintf(stderr, format, args); +} + +static error_t parse_arg(int key, char *arg, struct argp_state *state) +{ + switch (key) { + case 'h': + argp_state_help(state, stderr, ARGP_HELP_STD_HELP); + break; + case 'v': + env.verbose = true; + break; + case 'p': + errno = 0; + env.pid = strtol(arg, NULL, 10); + if (errno || env.pid <= 0) { + p_err("Invalid PID: %s", arg); + argp_usage(state); + } + break; + case 'w': + env.stop_the_world = true; + break; + case 'c': + env.command = strdup(arg); + ON_MEM_FAILURE(env.command); + break; + case 'i': + errno = 0; + env.interval = strtol(arg, NULL, 10); + if (errno || env.interval <= 0) { + p_err("Invalid interval: %s", arg); + argp_usage(state); + } + break; + case 'T': + errno = 0; + env.top = strtol(arg, NULL, 10); + if (errno || env.top <= 0) { + p_err("Invalid interval: %s", arg); + argp_usage(state); + } + break; + case 's': + env.suppr = strdup(arg); + ON_MEM_FAILURE(env.suppr); + break; + default: + return ARGP_ERR_UNKNOWN; + } + return 0; +} + +static int attach_uprobes(struct lsan_bpf *obj) +{ + int func_off = get_elf_func_offset_impl("free"); + __attach_uprobe(obj, free_entry, false, func_off, env.pid); + _attach_uprobe(obj, "malloc", malloc, env.pid); + _attach_uprobe(obj, "calloc", calloc, env.pid); + _attach_uprobe(obj, "realloc", realloc, env.pid); + _attach_uprobe(obj, "posix_memalign", posix_memalign, env.pid); + _attach_uprobe(obj, "aligned_alloc", aligned_alloc, env.pid); + _attach_uprobe(obj, "valloc", valloc, env.pid); + _attach_uprobe(obj, "memalign", memalign, env.pid); + _attach_uprobe(obj, "pvalloc", pvalloc, env.pid); + _attach_uprobe(obj, "reallocarray", reallocarray, env.pid); + return 0; +} + +static int attach_probes(struct lsan_bpf *obj) +{ + /* Support only uprobes currently */ + return attach_uprobes(obj); +} + +static void for_each_chunk(for_each_chunk_callback callback) +{ + struct lsan_hash_t *curr = NULL; + struct lsan_hash_t *next = NULL; + + HASH_ITER(hh, copied, curr, next) { + callback(curr->id); + } +} + +static uptr dereference(uptr pp, size_t size) +{ + char *buf = (char*)malloc(sizeof(char) * size); + ON_MEM_FAILURE(buf); + uptr rst = 0; + size_t sz = 0; + int i = 0; + uptr mask = 0xff; +#ifdef USE_PROCESS_VM_READV + struct iovec local; + struct iovec remote; + + local.iov_base = buf; + local.iov_len = size; + remote.iov_base = (void*)pp; + remote.iov_len = size; + sz = process_vm_readv(env.pid, &local, 1, &remote, 1, 0); +#else + fseek(fp_mem, pp, SEEK_SET); + sz = fread(buf, sizeof(char), size, fp_mem); +#endif + if (size != sz) { + if (getpgid(env.pid) < 0) { + p_warn("Is this process alive? pid: %d", env.pid); + exit(0); + } + free(buf); + return rst; + } + for (i = size - 1; i >= 0; --i) { +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + rst <<= size; + rst += ((uptr)buf[i] & mask); +#else + rst += ((uptr)buf[i] << (i*size)); +#endif + } + free(buf); + return rst; +} + +static uptr find_key(uptr start, uptr end, uptr ptr) +{ + struct lsan_hash_t *val = NULL; + uptr key = 0; + uptr mid = 0; + + while (1) { + if (start >= end) + return 0; + + if (end - start == 1) { + key = key_table[start]; + HASH_FIND(hh, copied, &key, sizeof(uptr), val); + if (key <= ptr && ptr < key + val->size) + return key; + + return 0; + } + mid = (start + end) / 2; + if (ptr < key_table[mid]) { + end = mid; + } else { + start = mid; + } + } +} + +static uptr points_into_chunk(uptr ptr) +{ +#ifndef LSAN_OPTIMIZED + struct lsan_hash_t *curr = NULL; + struct lsan_hash_t *next = NULL; + + HASH_ITER(hh, copied, curr, next) { + if (curr->id <= ptr && ptr < curr->id + curr->size) { + return curr->id; + } + } + return 0; +#else + return find_key(0, cvector_size(key_table), ptr); +#endif +} + +static void scan_range_for_pointers(uptr begin, uptr end, enum chunk_tag tag) +{ + /* TODO: Need to increase this value for speed */ + int alignment = 1; + uptr pp = begin; + uptr p = 0; + uptr chunk = 0; + struct lsan_hash_t *val = NULL; + + if (pp % alignment != 0) { + pp = pp + alignment - pp % alignment; + } + while (pp + word_size <= end) { + p = dereference(pp, word_size); + pp += alignment; + chunk = points_into_chunk(p); + if (chunk == 0) + continue; + + if (chunk == begin) + continue; + + HASH_FIND(hh, copied, &chunk, sizeof(uptr), val); + if (val == NULL) + continue; + + if (val->tag == REACHABLE || val->tag == IGNORED) + continue; + val->tag = tag; + if (tag == REACHABLE) { + cvector_push_back(frontier, p); + } + } +} + +static void update_report_info(struct report_info_t **hash, struct lsan_hash_t *val) +{ + struct report_info_t *old = NULL; + struct report_info_t *item = NULL; + int stack_id = val->stack_id; + + HASH_FIND(hh, *hash, &stack_id, sizeof(int), old); + if (old == NULL) { + item = (struct report_info_t*)malloc(sizeof(struct report_info_t)); + ON_MEM_FAILURE(item); + item->size = val->size; + item->id = val->stack_id; + item->count = 1; + HASH_ADD(hh, *hash, id, sizeof(int), item); + } else { + ++old->count; + } +} + +static void collect_leaks_cb(uptr chunk) +{ + struct lsan_hash_t *val = NULL; + + chunk = points_into_chunk(chunk); + if (chunk == 0) + return; + + HASH_FIND(hh, copied, &chunk, sizeof(uptr), val); + if (val == NULL) + return; + + if (val->tag == DIRECTLY_LEAKED) { + update_report_info(&direct, val); + } else if (val->tag == INDIRECTLY_LEAKED) { + update_report_info(&indirect, val); + } +} + +static void collect_ignore_cb(uptr chunk) +{ + /* TODO: Not mandatory function */ +} + +static void mark_indirectly_leaked_cb(uptr chunk) +{ + struct lsan_hash_t *val = NULL; + + chunk = points_into_chunk(chunk); + if (chunk == 0) + return; + + HASH_FIND(hh, copied, &chunk, sizeof(uptr), val); + if (val == NULL) + return; + if (val->tag != REACHABLE) { + scan_range_for_pointers(val->id, val->id + val->size, + INDIRECTLY_LEAKED); + } +} + +int compare(const void* a, const void* b) +{ + uptr aa = *(uptr*)a; + uptr bb = *(uptr*)b; + + if (aa < bb) + return -1; + + if (aa > bb) + return 1; + + return 0; +} + +static int read_table() +{ + struct lsan_info_t val; + struct root_region_t *curr = NULL; + struct root_region_t *next = NULL; + struct lsan_hash_t *item = NULL; + unsigned long lookup_key = 0; + unsigned long next_key = 0; + int err = 0; + int afd = bpf_map__fd(obj->maps.allocs); + + lookup_key = -1; + while (!bpf_map_get_next_key(afd, &lookup_key, &next_key)) { + err = bpf_map_lookup_elem(afd, &next_key, &val); + if (err < 0) { + return err; + } + item = (struct lsan_hash_t*)malloc(sizeof(struct lsan_hash_t)); + ON_MEM_FAILURE(item); + item->size = val.size; + item->stack_id = val.stack_id; + item->tag = val.tag; + item->id = next_key; + HASH_ADD(hh, copied, id, sizeof(uptr), item); + cvector_push_back(key_table, next_key); + HASH_ITER(hh, uncertain, curr, next) { + if (curr->id <= next_key && next_key < curr->end) { + curr->is_heap = true; + break; + } + } + lookup_key = next_key; + } + qsort(key_table, cvector_size(key_table), sizeof(uptr), compare); + return 0; +} + +static bool is_uncertain(char* map_str) +{ + /* if path name does not exist */ + if (0 == strlen(map_str)) + return true; + + /* Usually map_str value is "\n" if path name does not exist */ + return 0 == strncmp("\n", map_str, strlen("\n")); +} + +static bool is_certain(char* map_str) +{ + /* if path name does not exist */ + if (0 == strlen(map_str)) + return false; + + /* Not including '[' starting path except "[stack]" */ + bool is_heap = (0 == strncmp(heap_str, map_str, strlen(heap_str))); + bool is_sqr_start = ('[' == map_str[0]); + bool is_stack = (0 == strncmp(stack_str, map_str, strlen(stack_str))); + return !is_heap && (!is_sqr_start || is_stack); +} + +static void save_roots() +{ + char file_name[FILENAME_MAX] = {0, }; + char line[LINE_MAX] = {0, }; + FILE *fp = NULL; + char* v[MAPS_COLUMN_MAX] = {NULL, }; + int i = 0; + char *ptr = NULL; + uptr begin = 0; + uptr end = 0; + const int hex = 16; + struct root_region_t *item = NULL; + struct root_region_t *val = NULL; + + snprintf(file_name, sizeof(file_name), "/proc/%d/maps", env.pid); + fp = fopen(file_name, "rt"); + if (fp == NULL) { + p_err("Failed to open : %s", file_name); + return; + } + while (fgets(line, sizeof(line), fp) != NULL) { + i = 0; + ptr = strtok(line, " "); + while (ptr != NULL) { + v[i] = strdup(ptr); + ON_MEM_FAILURE(v[i]); + ++i; + ptr = strtok(NULL, " "); + } + /* root should have rw permission */ + if (strncmp(rw_permission, v[MAPS_PERMISSIONS], strlen(rw_permission))) + goto release; + + ptr = strtok(v[MAPS_ADDRESS], "-"); + begin = strtoull(ptr, NULL, hex); + ptr = strtok(NULL, "-"); + end = strtoull(ptr, NULL, hex); + item = (struct root_region_t*)malloc(sizeof(struct root_region_t)); + ON_MEM_FAILURE(item); + item->end = end; + item->id = begin; + item->is_heap = false; + if (is_uncertain(v[MAPS_PATH])) { + HASH_REPLACE(hh, uncertain, id, sizeof(uptr), item, val); + } else if (is_certain(v[MAPS_PATH])) { + HASH_REPLACE(hh, certain, id, sizeof(uptr), item, val); + } + free(val); + +release: + for (i = 0; i < MAPS_COLUMN_MAX; ++i) { + free(v[i]); + } + } + fclose(fp); +} + +static void process_roots(struct root_region_t *roots) { + struct root_region_t *curr = NULL; + struct root_region_t *next = NULL; + + HASH_ITER(hh, roots, curr, next) { + if (!(curr->is_heap)) { + p_debug("root: %lx - %lx", curr->id, curr->end); + scan_range_for_pointers(curr->id, curr->end, REACHABLE); + } + } +} + +static void flood_fill_tag(enum chunk_tag tag) +{ + struct lsan_hash_t *val = NULL; + uptr next_chunk = 0; + uptr origin = 0; + + while (!cvector_empty(frontier)) { + next_chunk = frontier[cvector_size(frontier) - 1]; + cvector_pop_back(frontier); + origin = points_into_chunk(next_chunk); + HASH_FIND(hh, copied, &origin, sizeof(uptr), val); + if (val == NULL) + continue; + + scan_range_for_pointers(origin, origin + val->size, tag); + } +} + +static pid_t get_tgid(const char *path) +{ + __u64 tmp = 0; + char buf[BUF_MAX] = {0, }; + FILE* f = fopen(path, "r"); + + if (!f) { + return 0; + } + while(fscanf(f, "%s %lld\n", buf, &tmp) != EOF) { + if (!strcmp(buf, "Tgid:")) { + fclose(f); + return tmp; + } + } + // Failed to get tgid + fclose(f); + return 0; +} + +static void process_registers() +{ +#ifdef __arm__ + struct user_regs regs; +#else + struct user_regs_struct regs; +#endif + struct iovec io; + long ret = 0; + int i = 0; + int j __attribute__((unused)) = 0; + + /* Stop the world is a mandatory option to read registers */ + if (!env.stop_the_world) + return; + + for (i = 0; i < cvector_size(tids); ++i) { + io.iov_base = ®s; + io.iov_len = sizeof(regs); + ret = ptrace(PTRACE_GETREGSET, tids[i], (void*)NT_PRSTATUS, (void*)&io); + if (ret == -1) { + p_warn("ptrace failed to get regset from tid: %d, reason: %s", tids[i], strerror(errno)); + continue; + } +#ifdef __aarch64__ + /* + * aarch64 user_regs_struct definition + * struct user_regs_struct + * { + * unsigned long long regs[31]; + * unsigned long long sp; + * unsigned long long pc; + * unsigned long long pstate; + * }; + */ + for (j = 0; j < 31; ++j) { + p_debug("root: %lx - %lx", regs.regs[j], regs.regs[j] + word_size); + scan_range_for_pointers(regs.regs[j], + regs.regs[j] + word_size, REACHABLE); + } +#else + /* TODO: x86_64 implementation is needed */ +#endif + } +} + +static void process_platform_specific_allocations() +{ + /* TODO: Not a mandatory function */ +} + +static void classify_all_chunks() +{ + for_each_chunk(collect_ignore_cb); + process_roots(certain); + process_roots(uncertain); + flood_fill_tag(REACHABLE); + process_registers(); + process_platform_specific_allocations(); + flood_fill_tag(REACHABLE); + for_each_chunk(mark_indirectly_leaked_cb); +} + +/* Decending order */ +static int report_info_sort(struct report_info_t *a, struct report_info_t *b) +{ + return b->size * b->count - a->size * a->count; +} + +static const char* demangle(const char* name) +{ + /* + * TODO + * return demangled function name + * return name if it's not mangled + */ + return name; +} + +static void leak_printer(struct report_info_t *curr, unsigned long *ip, + const struct syms *syms, const char *kind) +{ + const struct sym *sym = NULL; + char report_buf[BUF_MAX] = {0, }; + char str[LINE_MAX] = {0, }; + size_t i = 0; + size_t j = 0; + char* dso_name = NULL; + uint64_t dso_offset = 0; + + snprintf(report_buf, sizeof(report_buf), + "%lld bytes %s leak found in %d allocations from stack id(%d)\n", + curr->size * curr->count, kind, curr->count, curr->id); + for (i = 0; i < env.perf_max_stack_depth && ip[i]; ++i) { + snprintf(str, sizeof(str), "\t#%ld %#016lx", i+1, ip[i]); + strcat(report_buf, str); + sym = syms__map_addr_dso(syms, ip[i], &dso_name, &dso_offset); + if (sym) { + snprintf(str, sizeof(str), " %s+%#lx", demangle(sym->name), sym->offset); + strcat(report_buf, str); + } + if (dso_name) { + snprintf(str, sizeof(str), " (%s+%#lx)", dso_name, dso_offset); + strcat(report_buf, str); + } + if (i == 0 || i == 1) { + for (j = 0; j < cvector_size(suppression); ++j) { + if (strstr(report_buf, suppression[j]) != NULL) { + return; + } + } + } + strcat(report_buf, "\n"); + } + printf("%s\n", report_buf); +} + +static void report_leaks(struct syms_cache *syms_cache) +{ + struct report_info_t *curr = NULL; + struct report_info_t *next = NULL; + const struct syms *syms = NULL; + int rst = 0; + int count = 0; + time_t t = time(NULL); + struct tm tm = *localtime(&t); + int sfd = 0; + unsigned long *ip = calloc(env.perf_max_stack_depth, sizeof(*ip)); + + if (!ip) { + p_err("Failed to alloc ip"); + return; + } + printf("\n[%04d-%02d-%02d %02d:%02d:%02d] Print leaks:\n", + tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + sfd = bpf_map__fd(obj->maps.stack_traces); + /* Report direct */ + HASH_SORT(direct, report_info_sort); + HASH_ITER(hh, direct, curr, next) { + if (count == env.top) { + break; + } + ++count; + if (curr->id < 0) { + printf("%lld bytes direct leak found in %d allocations from unknown stack\n\n", + curr->size * curr->count, curr->count); + continue; + } + rst = bpf_map_lookup_elem(sfd, &(curr->id), ip); + syms = syms_cache__get_syms(syms_cache, env.pid); + if (rst == 0 && syms != NULL) { + leak_printer(curr, ip, syms, "direct"); + } + } + /* Report indirect */ + curr = NULL; + next = NULL; + HASH_SORT(indirect, report_info_sort); + HASH_ITER(hh, indirect, curr, next) { + if (count == env.top) { + break; + } + ++count; + if (curr->id < 0) { + printf("%lld bytes indirect leak found in %d allocations from unknown stack\n\n", + curr->size * curr->count, curr->count); + continue; + } + rst = bpf_map_lookup_elem(sfd, &(curr->id), ip); + syms = syms_cache__get_syms(syms_cache, env.pid); + if (rst == 0 && syms != NULL) { + leak_printer(curr, ip, syms, "indirect"); + } + } + free(ip); +} + +static void delete_hash_lsan_hash(struct lsan_hash_t* hash) { + struct lsan_hash_t *curr = NULL; + struct lsan_hash_t *next = NULL; + + HASH_ITER(hh, hash, curr, next) { + HASH_DEL(hash, curr); + free(curr); + } +} + +static void delete_hash_report_info(struct report_info_t* hash) { + struct report_info_t *curr = NULL; + struct report_info_t *next = NULL; + + HASH_ITER(hh, hash, curr, next) { + HASH_DEL(hash, curr); + free(curr); + } +} + +static void delete_hash_root_region(struct root_region_t* hash) { + struct root_region_t *curr = NULL; + struct root_region_t *next = NULL; + + HASH_ITER(hh, hash, curr, next) { + HASH_DEL(hash, curr); + free(curr); + } +} + +static void empty_table() +{ + cvector_free(frontier); + cvector_free(key_table); + cvector_free(tids); + delete_hash_lsan_hash(copied); + delete_hash_report_info(direct); + delete_hash_report_info(indirect); + delete_hash_root_region(certain); + delete_hash_root_region(uncertain); + frontier = NULL; + key_table = NULL; + tids = NULL; + copied = NULL; + direct = NULL; + indirect = NULL; + certain = NULL; + uncertain = NULL; +} + +static void for_each_tid_ptrace(enum __ptrace_request request) +{ + int i = 0; + long ret = 0; + + if (!env.stop_the_world) + return; + + for (i = 0; i < cvector_size(tids); ++i) { + ret = ptrace(request, tids[i], NULL, NULL); + if (ret == -1) { + p_warn("ptrace failed to request %d, reason: %s", request, strerror(errno)); + p_warn("May failed to stop tid: %d, could cause false alarms", tids[i]); + } + } +} + +static void for_each_tid_waitpid() +{ + int i = 0; + int status = 0; + pid_t ret = 0; + + if (!env.stop_the_world) + return; + + for (i = 0; i < cvector_size(tids); ++i) { + ret = waitpid(tids[i], &status, __WALL); + if (ret == -1) { + p_warn("waitpid failed, reason: %s", strerror(errno)); + p_warn("May failed to stop tid: %d, could cause false alarms", tids[i]); + } + } +} + +static int do_leak_check(struct syms_cache *syms_cache) +{ + static int MAX_THREADS = 100; + int ret = 0; + int nr_thread; + int i; + int tasks[MAX_THREADS]; + + nr_thread = get_tasks(env.pid, tasks, MAX_THREADS); + if (nr_thread < 0) { + p_warn("Failed to get thread id list"); + } else { + for (i = 0; i < nr_thread; ++i) { + cvector_push_back(tids, tasks[i]); + } + for_each_tid_ptrace(PTRACE_SEIZE); + for_each_tid_ptrace(PTRACE_INTERRUPT); + for_each_tid_waitpid(); + } + save_roots(); + ret = read_table(); + if (ret < 0) { + p_warn("Failed to read_table, retry after %d seconds", env.interval); + for_each_tid_ptrace(PTRACE_DETACH); + return 0; + } + classify_all_chunks(); + for_each_chunk(collect_leaks_cb); + for_each_tid_ptrace(PTRACE_DETACH); + report_leaks(syms_cache); + return 0; +} + +int main(int argc, char **argv) +{ + struct syms_cache *syms_cache = NULL; + int err = 0; + char path[PATH_MAX] = {0, }; + FILE *fp_suppression = NULL; + char line[LINE_MAX] = {0, }; + int i = 0; + char *ptr = NULL; + char *str = NULL; + + set_log_level(INFO); +#ifdef __arm__ + p_err("lsan is not supported on arm32 systems"); + exit(0); +#endif + static const struct argp argp = { + .options = opts, + .parser = parse_arg, + .doc = argp_program_doc, + }; + err = argp_parse(&argp, argc, argv, 0, NULL, NULL); + if (err) + return err; + + if (env.verbose) { + set_log_level(DEBUG); + } + if (env.command != NULL) { + env.pid = execute_process(env.command); + if (env.pid > 0) { + p_info("execute command: %s(pid %d)", env.command, env.pid); + } + } + if (env.pid == -1) { + p_err("Either -c or -p is a mandatory option"); + return -1; + } + libbpf_set_print(libbpf_print_fn); + obj = lsan_bpf__open(); + if (!obj) { + p_err("Failed to open BPF object"); + return -1; + } + bpf_map__set_value_size(obj->maps.stack_traces, + env.perf_max_stack_depth * sizeof(unsigned long)); + bpf_map__set_max_entries(obj->maps.stack_traces, + env.stack_storage_size); + err = lsan_bpf__load(obj); + if (err) { + p_err("Failed to load BPF object: %d", err); + return -1; + } + err = attach_probes(obj); + if (err) { + p_err("Failed to attach BPF programs"); + p_err("Is this process alive? pid: %d", env.pid); + return -1; + } + syms_cache = syms_cache__new(0); + if (!syms_cache) { + p_err("Failed to load syms"); + return -1; + } + snprintf(path, sizeof(path), "/proc/%d/mem", env.pid); + fp_mem = fopen(path, "rb"); + if (fp_mem == NULL) { + p_err("Failed to open: %s", path); + return -1; + } + fp_suppression = fopen(env.suppr, "rt"); + if (fp_suppression == NULL) { + p_warn("Failed to open: %s", env.suppr); + } else { + while (fgets(line, sizeof(line), fp_suppression) != NULL) { + /* suppression line format "kind:string" */ + /* suppression line example1 "leak:/usr/lib/libglib.so" */ + /* suppression line example2 "leak:_dl_init" */ + i = 0; + ptr = strtok(line, ":"); + if (strcmp("leak", ptr) != 0) { + continue; + } + ptr = strtok(NULL, ":"); + str = strdup(ptr); + ON_MEM_FAILURE(str); + ptr = strchr(str, '\n'); + if (ptr != NULL) { + *ptr = '\0'; + } + cvector_push_back(suppression, str); + } + } + snprintf(path, sizeof(path), "/proc/%d/status", env.pid); + env.tgid = get_tgid(path); + do { + sleep(env.interval); + if (getpgid(env.pid) < 0) { + p_warn("Is this process alive? pid: %d", env.pid); + exit(0); + } + empty_table(); + } while (do_leak_check(syms_cache) == 0); + + /* cleanup */ + for (i = 0; i < cvector_size(suppression); ++i) { + free(suppression[i]); + } + cvector_free(suppression); + suppression = NULL; + fclose(fp_mem); + syms_cache__free(syms_cache); + lsan_bpf__destroy(obj); + empty_table(); + free(env.command); + free(env.suppr); + return 0; +} diff --git a/libbpf-tools/lsan.h b/libbpf-tools/lsan.h new file mode 100644 index 000000000000..0d2b534b1d0e --- /dev/null +++ b/libbpf-tools/lsan.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* Copyright (c) 2022 LG Electronics */ +#ifndef __LSAN_H +#define __LSAN_H + +#define MAX_ENTRIES 65536 + +enum chunk_tag { + DIRECTLY_LEAKED = 0, + INDIRECTLY_LEAKED = 1, + REACHABLE = 2, + IGNORED = 3 +}; + +struct lsan_info_t { + __u64 size; + int stack_id; + enum chunk_tag tag; +}; + +#endif /* __LSAN_H */ diff --git a/libbpf-tools/uthash.h b/libbpf-tools/uthash.h new file mode 100644 index 000000000000..9a396b6179fc --- /dev/null +++ b/libbpf-tools/uthash.h @@ -0,0 +1,1136 @@ +/* +Copyright (c) 2003-2021, Troy D. Hanson http://troydhanson.github.io/uthash/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#define UTHASH_VERSION 2.3.0 + +#include /* memcmp, memset, strlen */ +#include /* ptrdiff_t */ +#include /* exit */ + +#if defined(HASH_DEFINE_OWN_STDINT) && HASH_DEFINE_OWN_STDINT +/* This codepath is provided for backward compatibility, but I plan to remove it. */ +#warning "HASH_DEFINE_OWN_STDINT is deprecated; please use HASH_NO_STDINT instead" +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#elif defined(HASH_NO_STDINT) && HASH_NO_STDINT +#else +#include /* uint8_t, uint32_t */ +#endif + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if !defined(DECLTYPE) && !defined(NO_DECLTYPE) +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE(x) +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while (0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while (0) +#endif + +#ifndef uthash_malloc +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ +#endif +#ifndef uthash_bzero +#define uthash_bzero(a,n) memset(a,'\0',n) +#endif +#ifndef uthash_strlen +#define uthash_strlen(s) strlen(s) +#endif + +#ifndef HASH_FUNCTION +#define HASH_FUNCTION(keyptr,keylen,hashv) HASH_JEN(keyptr, keylen, hashv) +#endif + +#ifndef HASH_KEYCMP +#define HASH_KEYCMP(a,b,n) memcmp(a,b,n) +#endif + +#ifndef uthash_noexpand_fyi +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif + +#ifndef HASH_NONFATAL_OOM +#define HASH_NONFATAL_OOM 0 +#endif + +#if HASH_NONFATAL_OOM +/* malloc failures can be recovered from */ + +#ifndef uthash_nonfatal_oom +#define uthash_nonfatal_oom(obj) do {} while (0) /* non-fatal OOM error */ +#endif + +#define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0) +#define IF_HASH_NONFATAL_OOM(x) x + +#else +/* malloc failures result in lost memory, hash tables are unusable */ + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal OOM error */ +#endif + +#define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory") +#define IF_HASH_NONFATAL_OOM(x) + +#endif + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhp */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) +/* calculate the hash handle from element address elp */ +#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle*)(void*)(((char*)(elp)) + ((tbl)->hho))) + +#define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \ +do { \ + struct UT_hash_handle *_hd_hh_item = (itemptrhh); \ + unsigned _hd_bkt; \ + HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + (head)->hh.tbl->buckets[_hd_bkt].count++; \ + _hd_hh_item->hh_next = NULL; \ + _hd_hh_item->hh_prev = NULL; \ +} while (0) + +#define HASH_VALUE(keyptr,keylen,hashv) \ +do { \ + HASH_FUNCTION(keyptr, keylen, hashv); \ +} while (0) + +#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ +do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_bkt; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ + } \ + } \ +} while (0) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_hashv; \ + HASH_VALUE(keyptr, keylen, _hf_hashv); \ + HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ + } \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) +#define HASH_BLOOM_MAKE(tbl,oomed) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!(tbl)->bloom_bv) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ + } \ +} while (0) + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0) + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#else +#define HASH_BLOOM_MAKE(tbl,oomed) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#define HASH_BLOOM_BYTELEN 0U +#endif + +#define HASH_MAKE_TABLE(hh,head,oomed) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \ + if (!(head)->hh.tbl) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ + if (!(head)->hh.tbl->buckets) { \ + HASH_RECORD_OOM(oomed); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + } else { \ + uthash_bzero((head)->hh.tbl->buckets, \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \ + IF_HASH_NONFATAL_OOM( \ + if (oomed) { \ + uthash_free((head)->hh.tbl->buckets, \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + } \ + ) \ + } \ + } \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ +} while (0) + +#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ +} while (0) + +#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ +} while (0) + +#define HASH_APPEND_LIST(hh, head, add) \ +do { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail->next = (add); \ + (head)->hh.tbl->tail = &((add)->hh); \ +} while (0) + +#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ +do { \ + do { \ + if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ + break; \ + } \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ +} while (0) + +#ifdef NO_DECLTYPE +#undef HASH_AKBI_INNER_LOOP +#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ +do { \ + char *_hs_saved_head = (char*)(head); \ + do { \ + DECLTYPE_ASSIGN(head, _hs_iter); \ + if (cmpfcn(head, add) > 0) { \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + break; \ + } \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ +} while (0) +#endif + +#if HASH_NONFATAL_OOM + +#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ +do { \ + if (!(oomed)) { \ + unsigned _ha_bkt; \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ + if (oomed) { \ + HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \ + HASH_DELETE_HH(hh, head, &(add)->hh); \ + (add)->hh.tbl = NULL; \ + uthash_nonfatal_oom(add); \ + } else { \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + } \ + } else { \ + (add)->hh.tbl = NULL; \ + uthash_nonfatal_oom(add); \ + } \ +} while (0) + +#else + +#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ +do { \ + unsigned _ha_bkt; \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ +} while (0) + +#endif + + +#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ +do { \ + IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (char*) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh, add, _ha_oomed); \ + IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ + (head) = (add); \ + IF_HASH_NONFATAL_OOM( } ) \ + } else { \ + void *_hs_iter = (head); \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ + if (_hs_iter) { \ + (add)->hh.next = _hs_iter; \ + if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ + HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ + } else { \ + (head) = (add); \ + } \ + HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ + } else { \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + } \ + HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ +} while (0) + +#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ +do { \ + unsigned _hs_hashv; \ + HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) + +#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ + HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) + +#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ +do { \ + IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (const void*) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh, add, _ha_oomed); \ + IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ + (head) = (add); \ + IF_HASH_NONFATAL_OOM( } ) \ + } else { \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ +} while (0) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_hashv; \ + HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) + +#define HASH_TO_BKT(hashv,num_bkts,bkt) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1U)); \ +} while (0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ + HASH_DELETE_HH(hh, head, &(delptr)->hh) + +#define HASH_DELETE_HH(hh,head,delptrhh) \ +do { \ + struct UT_hash_handle *_hd_hh_del = (delptrhh); \ + if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } else { \ + unsigned _hd_bkt; \ + if (_hd_hh_del == (head)->hh.tbl->tail) { \ + (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ + } \ + if (_hd_hh_del->prev != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ + } else { \ + DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ + } \ + if (_hd_hh_del->next != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ + } \ + HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh, head, "HASH_DELETE_HH"); \ +} while (0) + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ +do { \ + unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr); \ + HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \ +} while (0) +#define HASH_ADD_STR(head,strfield,add) \ +do { \ + unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield); \ + HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \ +} while (0) +#define HASH_REPLACE_STR(head,strfield,add,replaced) \ +do { \ + unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield); \ + HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \ +} while (0) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_REPLACE_INT(head,intfield,add,replaced) \ + HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ + HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#include /* fprintf, stderr */ +#define HASH_OOPS(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head,where) \ +do { \ + struct UT_hash_handle *_thh; \ + if (head) { \ + unsigned _bkt_i; \ + unsigned _count = 0; \ + char *_prev; \ + for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ + unsigned _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ + (where), (void*)_thh->hh_prev, (void*)_prev); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \ + (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \ + (where), (head)->hh.tbl->num_items, _count); \ + } \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev != (char*)_thh->prev) { \ + HASH_OOPS("%s: invalid prev %p, actual %p\n", \ + (where), (void*)_thh->prev, (void*)_prev); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid app item count %u, actual %u\n", \ + (where), (head)->hh.tbl->num_items, _count); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head,where) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ +#define HASH_BER(key,keylen,hashv) \ +do { \ + unsigned _hb_keylen = (unsigned)keylen; \ + const unsigned char *_hb_key = (const unsigned char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen-- != 0U) { \ + (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ + } \ +} while (0) + + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,hashv) \ +do { \ + unsigned _sx_i; \ + const unsigned char *_hs_key = (const unsigned char*)(key); \ + hashv = 0; \ + for (_sx_i=0; _sx_i < keylen; _sx_i++) { \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + } \ +} while (0) +/* FNV-1a variation */ +#define HASH_FNV(key,keylen,hashv) \ +do { \ + unsigned _fn_i; \ + const unsigned char *_hf_key = (const unsigned char*)(key); \ + (hashv) = 2166136261U; \ + for (_fn_i=0; _fn_i < keylen; _fn_i++) { \ + hashv = hashv ^ _hf_key[_fn_i]; \ + hashv = hashv * 16777619U; \ + } \ +} while (0) + +#define HASH_OAT(key,keylen,hashv) \ +do { \ + unsigned _ho_i; \ + const unsigned char *_ho_key=(const unsigned char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ +} while (0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,hashv) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + unsigned const char *_hj_key=(unsigned const char*)(key); \ + hashv = 0xfeedbeefu; \ + _hj_i = _hj_j = 0x9e3779b9u; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12U) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12U; \ + } \ + hashv += (unsigned)(keylen); \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ + case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ + case 1: _hj_i += _hj_key[0]; /* FALLTHROUGH */ \ + default: ; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ +} while (0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,hashv) \ +do { \ + unsigned const char *_sfh_key=(unsigned const char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ + \ + unsigned _sfh_rem = _sfh_len & 3U; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabeu; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0U; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2U*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + break; \ + default: ; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ +} while (0) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ +do { \ + if ((head).hh_head != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ + } else { \ + (out) = NULL; \ + } \ + while ((out) != NULL) { \ + if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ + if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) { \ + break; \ + } \ + } \ + if ((out)->hh.hh_next != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ + } else { \ + (out) = NULL; \ + } \ + } \ +} while (0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,hh,addhh,oomed) \ +do { \ + UT_hash_bucket *_ha_head = &(head); \ + _ha_head->count++; \ + (addhh)->hh_next = _ha_head->hh_head; \ + (addhh)->hh_prev = NULL; \ + if (_ha_head->hh_head != NULL) { \ + _ha_head->hh_head->hh_prev = (addhh); \ + } \ + _ha_head->hh_head = (addhh); \ + if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ + && !(addhh)->tbl->noexpand) { \ + HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \ + IF_HASH_NONFATAL_OOM( \ + if (oomed) { \ + HASH_DEL_IN_BKT(head,addhh); \ + } \ + ) \ + } \ +} while (0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(head,delhh) \ +do { \ + UT_hash_bucket *_hd_head = &(head); \ + _hd_head->count--; \ + if (_hd_head->hh_head == (delhh)) { \ + _hd_head->hh_head = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_prev) { \ + (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_next) { \ + (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ + } \ +} while (0) + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(hh,tbl,oomed) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ + if (!_he_new_buckets) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero(_he_new_buckets, \ + sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ + (tbl)->ideal_chain_maxlen = \ + ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \ + ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ + (tbl)->nonideal_items = 0; \ + for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \ + _he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh != NULL) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[_he_bkt]); \ + if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ + (tbl)->nonideal_items++; \ + if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \ + _he_newbkt->expand_mult++; \ + } \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head != NULL) { \ + _he_newbkt->hh_head->hh_prev = _he_thh; \ + } \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ + (tbl)->num_buckets *= 2U; \ + (tbl)->log2_num_buckets++; \ + (tbl)->buckets = _he_new_buckets; \ + (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \ + ((tbl)->ineff_expands+1U) : 0U; \ + if ((tbl)->ineff_expands > 1U) { \ + (tbl)->noexpand = 1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ + } \ +} while (0) + + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head != NULL) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping != 0U) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p != NULL) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ + _hs_psize++; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + if (_hs_q == NULL) { \ + break; \ + } \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ + if (_hs_psize == 0U) { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else if ((cmpfcn( \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)) \ + )) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail != NULL ) { \ + _hs_tail->next = ((_hs_e != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e != NULL) { \ + _hs_e->prev = ((_hs_tail != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail != NULL) { \ + _hs_tail->next = NULL; \ + } \ + if (_hs_nmerges <= 1U) { \ + _hs_looping = 0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2U; \ + } \ + HASH_FSCK(hh, head, "HASH_SRT"); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt = NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if ((src) != NULL) { \ + for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh != NULL; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \ + _dst_hh = (UT_hash_handle*)(void*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh != NULL) { \ + _last_elt_hh->next = _elt; \ + } \ + if ((dst) == NULL) { \ + DECLTYPE_ASSIGN(dst, _elt); \ + HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \ + IF_HASH_NONFATAL_OOM( \ + if (_hs_oomed) { \ + uthash_nonfatal_oom(_elt); \ + (dst) = NULL; \ + continue; \ + } \ + ) \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \ + (dst)->hh_dst.tbl->num_items++; \ + IF_HASH_NONFATAL_OOM( \ + if (_hs_oomed) { \ + HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \ + HASH_DELETE_HH(hh_dst, dst, _dst_hh); \ + _dst_hh->tbl = NULL; \ + uthash_nonfatal_oom(_elt); \ + continue; \ + } \ + ) \ + HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if ((head) != NULL) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } \ +} while (0) + +#define HASH_OVERHEAD(hh,head) \ + (((head) != NULL) ? ( \ + (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ + sizeof(UT_hash_table) + \ + (HASH_BLOOM_BYTELEN))) : 0U) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1u +#define HASH_BLOOM_SIGNATURE 0xb12220f2u + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + uint8_t bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + const void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */