libdrgn: move alloc_or_reuse() to util.h

Preparation for using it elsewhere. Also make it take a size_t instead
of uint64_t.

Signed-off-by: Omar Sandoval <osandov@osandov.com>
This commit is contained in:
Omar Sandoval 2022-06-01 05:11:58 -07:00
parent 3595c81a8c
commit c9265ef6d6
2 changed files with 18 additions and 19 deletions

View File

@ -635,9 +635,9 @@ DEFINE_HASH_MAP(drgn_mapped_files, const char *,
struct userspace_core_report_state {
struct drgn_mapped_files files;
char *phdr_buf;
void *phdr_buf;
size_t phdr_buf_capacity;
char *segment_buf;
void *segment_buf;
size_t segment_buf_capacity;
};
@ -878,22 +878,6 @@ not_loaded:
return NULL;
}
static bool alloc_or_reuse(char **buf, size_t *capacity, uint64_t size)
{
if (size > *capacity) {
if (size > SIZE_MAX)
return false;
free(*buf);
*buf = malloc(size);
if (!*buf) {
*capacity = 0;
return false;
}
*capacity = size;
}
return true;
}
/* ehdr_buf must be aligned as Elf64_Ehdr. */
static void read_ehdr(const void *ehdr_buf, GElf_Ehdr *ret, bool *is_64_bit_ret,
bool *bswap_ret)
@ -1161,7 +1145,8 @@ userspace_core_identify_file(struct drgn_program *prog,
GElf_Phdr phdr;
core_get_phdr(&arg, i, &phdr);
if (phdr.p_type == PT_NOTE) {
if (!alloc_or_reuse(&core->segment_buf,
if (phdr.p_filesz > SIZE_MAX ||
!alloc_or_reuse(&core->segment_buf,
&core->segment_buf_capacity,
phdr.p_filesz))
return &drgn_enomem;

View File

@ -123,6 +123,20 @@ static inline void *memdup(const void *ptr, size_t size)
return copy;
}
static inline bool alloc_or_reuse(void **buf, size_t *capacity, size_t size)
{
if (size > *capacity) {
free(*buf);
*buf = malloc(size);
if (!*buf) {
*capacity = 0;
return false;
}
*capacity = size;
}
return true;
}
/** Return the maximum value of an @p n-byte unsigned integer. */
static inline uint64_t uint_max(int n)
{