basic: replace size_multiply_overflow() with MUL_ASSIGN_SAFE where applicable

This commit is contained in:
Mike Yuan
2024-09-20 21:39:15 +02:00
parent 175de2c28e
commit 34fb408f8b
3 changed files with 23 additions and 25 deletions

View File

@@ -43,7 +43,7 @@ void* greedy_realloc(
size_t need,
size_t size) {
size_t a, newalloc;
size_t newalloc;
void *q;
assert(p);
@@ -60,14 +60,13 @@ void* greedy_realloc(
return NULL;
newalloc = need * 2;
if (size_multiply_overflow(newalloc, size))
if (!MUL_ASSIGN_SAFE(&newalloc, size))
return NULL;
a = newalloc * size;
if (a < 64) /* Allocate at least 64 bytes */
a = 64;
if (newalloc < 64) /* Allocate at least 64 bytes */
newalloc = 64;
q = realloc(*p, a);
q = realloc(*p, newalloc);
if (!q)
return NULL;

View File

@@ -26,23 +26,23 @@ typedef void* (*mfree_func_t)(void *p);
#define alloca_safe(n) \
({ \
size_t _nn_ = n; \
size_t _nn_ = (n); \
assert(_nn_ <= ALLOCA_MAX); \
alloca(_nn_ == 0 ? 1 : _nn_); \
}) \
#define newa(t, n) \
({ \
size_t _n_ = n; \
assert(!size_multiply_overflow(sizeof(t), _n_)); \
(t*) alloca_safe(sizeof(t)*_n_); \
size_t _n_ = (n); \
assert_se(MUL_ASSIGN_SAFE(&_n_, sizeof(t))); \
(t*) alloca_safe(_n_); \
})
#define newa0(t, n) \
({ \
size_t _n_ = n; \
assert(!size_multiply_overflow(sizeof(t), _n_)); \
(t*) alloca0((sizeof(t)*_n_)); \
size_t _n_ = (n); \
assert_se(MUL_ASSIGN_SAFE(&_n_, sizeof(t))); \
(t*) alloca0(_n_); \
})
#define newdup(t, p, n) ((t*) memdup_multiply(p, n, sizeof(t)))

View File

@@ -201,18 +201,17 @@ int strextendf_with_separator(char **x, const char *separator, const char *forma
char* strrep(const char *s, unsigned n);
#define strrepa(s, n) \
({ \
const char *_sss_ = (s); \
size_t _nnn_ = (n), _len_ = strlen(_sss_); \
assert(!size_multiply_overflow(_len_, _nnn_)); \
_len_ *= _nnn_; \
char *_d_, *_p_; \
_p_ = _d_ = newa(char, _len_ + 1); \
for (size_t _i_ = 0; _i_ < _nnn_; _i_++) \
_p_ = stpcpy(_p_, _sss_); \
*_p_ = 0; \
_d_; \
#define strrepa(s, n) \
({ \
const char *_sss_ = (s); \
size_t _nnn_ = (n), _len_ = strlen(_sss_); \
assert_se(MUL_ASSIGN_SAFE(&_len_, _nnn_)); \
char *_d_, *_p_; \
_p_ = _d_ = newa(char, _len_ + 1); \
for (size_t _i_ = 0; _i_ < _nnn_; _i_++) \
_p_ = stpcpy(_p_, _sss_); \
*_p_ = 0; \
_d_; \
})
int split_pair(const char *s, const char *sep, char **l, char **r);