summaryrefslogtreecommitdiff
path: root/src/common/util.c
diff options
context:
space:
mode:
authorNick Mathewson <nickm@torproject.org>2010-12-13 18:40:21 -0500
committerNick Mathewson <nickm@torproject.org>2010-12-13 18:40:21 -0500
commit785086cfbaf15a78a921f5589a76517b1d4840b1 (patch)
tree452b47f3da27025aea6193ba045a6e97a0851a65 /src/common/util.c
parent649ee99846966c87350cd3282639326f8b4ee4af (diff)
downloadtor-785086cfbaf15a78a921f5589a76517b1d4840b1.tar.gz
tor-785086cfbaf15a78a921f5589a76517b1d4840b1.zip
Have all of our allocation functions and a few others check for underflow
It's all too easy in C to convert an unsigned value to a signed one, which will (on all modern computers) give you a huge signed value. If you have a size_t value of size greater than SSIZE_T_MAX, that is way likelier to be an underflow than it is to be an actual request for more than 2gb of memory in one go. (There's nothing in Tor that should be trying to allocate >2gb chunks.)
Diffstat (limited to 'src/common/util.c')
-rw-r--r--src/common/util.c11
1 files changed, 9 insertions, 2 deletions
diff --git a/src/common/util.c b/src/common/util.c
index 34bb9cc376..0571a532cd 100644
--- a/src/common/util.c
+++ b/src/common/util.c
@@ -115,6 +115,8 @@ _tor_malloc(size_t size DMALLOC_PARAMS)
{
void *result;
+ tor_assert(size < SIZE_T_CEILING);
+
#ifndef MALLOC_ZERO_WORKS
/* Some libc mallocs don't work when size==0. Override them. */
if (size==0) {
@@ -211,6 +213,7 @@ _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
{
char *dup;
tor_assert(s);
+ tor_assert(n < SIZE_T_CEILING);
dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
/* Performance note: Ordinarily we prefer strlcpy to strncpy. But
* this function gets called a whole lot, and platform strncpy is
@@ -227,6 +230,7 @@ void *
_tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
{
char *dup;
+ tor_assert(len < SIZE_T_CEILING);
tor_assert(mem);
dup = _tor_malloc(len DMALLOC_FN_ARGS);
memcpy(dup, mem, len);
@@ -256,12 +260,15 @@ void *
_tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
{
#ifdef HAVE_MALLOC_GOOD_SIZE
+ tor_assert(*sizep < SIZE_T_CEILING);
*sizep = malloc_good_size(*sizep);
return _tor_malloc(*sizep DMALLOC_FN_ARGS);
#elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
/* Never use malloc_usable_size(); it makes valgrind really unhappy,
* and doesn't win much in terms of usable space where it exists. */
- void *result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
+ void *result;
+ tor_assert(*sizep < SIZE_T_CEILING);
+ result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
*sizep = malloc_usable_size(result);
return result;
#else
@@ -1927,7 +1934,7 @@ read_file_to_str(const char *filename, int flags, struct stat *stat_out)
return NULL;
}
- if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
+ if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_CEILING)
return NULL;
string = tor_malloc((size_t)(statbuf.st_size+1));