bitmap: Use g_try_new0/g_new0/g_renew

Avoids an explicit use of sizeof().  The GLib allocation macros
ensure that the multiplication by the size of the element
uses the right type and does not overflow.

While at it, change bitmap_new() to use g_new0 directly.  Its current
impl of calling bitmap_try_new() followed by a plain abort() has
worse diagnostics than g_new0, which uses g_error to report the actual
allocation size that failed.

Cc: qemu-trivial@nongnu.org
Cc: Roman Kiryanov <rkir@google.com>
Reviewed-by: Daniel Berrange <berrange@redhat.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
This commit is contained in:
Paolo Bonzini 2024-05-02 16:18:18 +02:00
parent b10b248173
commit 5e9efe31f1

View file

@ -92,17 +92,14 @@ long slow_bitmap_count_one(const unsigned long *bitmap, long nbits);
static inline unsigned long *bitmap_try_new(long nbits) static inline unsigned long *bitmap_try_new(long nbits)
{ {
long len = BITS_TO_LONGS(nbits) * sizeof(unsigned long); long nelem = BITS_TO_LONGS(nbits);
return g_try_malloc0(len); return g_try_new0(unsigned long, nelem);
} }
static inline unsigned long *bitmap_new(long nbits) static inline unsigned long *bitmap_new(long nbits)
{ {
unsigned long *ptr = bitmap_try_new(nbits); long nelem = BITS_TO_LONGS(nbits);
if (ptr == NULL) { return g_new0(unsigned long, nelem);
abort();
}
return ptr;
} }
static inline void bitmap_zero(unsigned long *dst, long nbits) static inline void bitmap_zero(unsigned long *dst, long nbits)
@ -265,10 +262,10 @@ unsigned long bitmap_find_next_zero_area(unsigned long *map,
static inline unsigned long *bitmap_zero_extend(unsigned long *old, static inline unsigned long *bitmap_zero_extend(unsigned long *old,
long old_nbits, long new_nbits) long old_nbits, long new_nbits)
{ {
long new_len = BITS_TO_LONGS(new_nbits) * sizeof(unsigned long); long new_nelem = BITS_TO_LONGS(new_nbits);
unsigned long *new = g_realloc(old, new_len); unsigned long *ptr = g_renew(unsigned long, old, new_nelem);
bitmap_clear(new, old_nbits, new_nbits - old_nbits); bitmap_clear(ptr, old_nbits, new_nbits - old_nbits);
return new; return ptr;
} }
void bitmap_to_le(unsigned long *dst, const unsigned long *src, void bitmap_to_le(unsigned long *dst, const unsigned long *src,