Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

perf tools: Add reallocarray_as_needed()

Add helper reallocarray_as_needed() to reallocate an array to a larger
size and initialize the extra entries to an arbitrary value.

Signed-off-by: Adrian Hunter <adrian.hunter@intel.com>
Cc: Andi Kleen <ak@linux.intel.com>
Cc: Ian Rogers <irogers@google.com>
Cc: Jiri Olsa <jolsa@kernel.org>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: kvm@vger.kernel.org
Link: https://lore.kernel.org/r/20220711093218.10967-24-adrian.hunter@intel.com
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>

authored by

Adrian Hunter and committed by
Arnaldo Carvalho de Melo
10d34700 a5367ecb

+48
+33
tools/perf/util/util.c
··· 18 18 #include <linux/kernel.h> 19 19 #include <linux/log2.h> 20 20 #include <linux/time64.h> 21 + #include <linux/overflow.h> 21 22 #include <unistd.h> 22 23 #include "cap.h" 23 24 #include "strlist.h" ··· 500 499 return NULL; 501 500 502 501 return new_name; 502 + } 503 + 504 + /* 505 + * Reallocate an array *arr of size *arr_sz so that it is big enough to contain 506 + * x elements of size msz, initializing new entries to *init_val or zero if 507 + * init_val is NULL 508 + */ 509 + int do_realloc_array_as_needed(void **arr, size_t *arr_sz, size_t x, size_t msz, const void *init_val) 510 + { 511 + size_t new_sz = *arr_sz; 512 + void *new_arr; 513 + size_t i; 514 + 515 + if (!new_sz) 516 + new_sz = msz >= 64 ? 1 : roundup(64, msz); /* Start with at least 64 bytes */ 517 + while (x >= new_sz) { 518 + if (check_mul_overflow(new_sz, (size_t)2, &new_sz)) 519 + return -ENOMEM; 520 + } 521 + if (new_sz == *arr_sz) 522 + return 0; 523 + new_arr = calloc(new_sz, msz); 524 + if (!new_arr) 525 + return -ENOMEM; 526 + memcpy(new_arr, *arr, *arr_sz * msz); 527 + if (init_val) { 528 + for (i = *arr_sz; i < new_sz; i++) 529 + memcpy(new_arr + (i * msz), init_val, msz); 530 + } 531 + *arr = new_arr; 532 + *arr_sz = new_sz; 533 + return 0; 503 534 }
+15
tools/perf/util/util.h
··· 79 79 void perf_debuginfod_setup(struct perf_debuginfod *di); 80 80 81 81 char *filename_with_chroot(int pid, const char *filename); 82 + 83 + int do_realloc_array_as_needed(void **arr, size_t *arr_sz, size_t x, 84 + size_t msz, const void *init_val); 85 + 86 + #define realloc_array_as_needed(a, n, x, v) ({ \ 87 + typeof(x) __x = (x); \ 88 + __x >= (n) ? \ 89 + do_realloc_array_as_needed((void **)&(a), \ 90 + &(n), \ 91 + __x, \ 92 + sizeof(*(a)), \ 93 + (const void *)(v)) : \ 94 + 0; \ 95 + }) 96 + 82 97 #endif /* GIT_COMPAT_UTIL_H */