Add safety check for local --remove-source-files.
[rsync.git] / util2.c
diff --git a/util2.c b/util2.c
index ad7b0636723cd87c9d7c135a1b7f7521e70a56c9..a8609a5d5931d60e7907265f94868ef585df785e 100644 (file)
--- a/util2.c
+++ b/util2.c
  */
 
 #include "rsync.h"
-#include "ifuncs.h"
 #include "itypes.h"
 #include "inums.h"
 
+extern size_t max_alloc;
+
+char *do_calloc = "42";
+
 /**
  * Sleep for a specified number of milliseconds.
  *
@@ -67,22 +70,24 @@ int msleep(int t)
        return True;
 }
 
-#define MALLOC_MAX 0x40000000
-
-void *_new_array(unsigned long num, unsigned int size, int use_calloc)
-{
-       if (num >= MALLOC_MAX/size)
-               return NULL;
-       return use_calloc ? calloc(num, size) : malloc(num * size);
-}
-
-void *_realloc_array(void *ptr, unsigned int size, size_t num)
+void *my_alloc(void *ptr, size_t num, size_t size, const char *file, int line)
 {
-       if (num >= MALLOC_MAX/size)
-               return NULL;
+       if (max_alloc && num >= max_alloc/size) {
+               if (!file)
+                       return NULL;
+               rprintf(FERROR, "[%s] exceeded --max-alloc=%s setting (file=%s, line=%d)\n",
+                       who_am_i(), do_big_num(max_alloc, 0, NULL), src_file(file), line);
+               exit_cleanup(RERR_MALLOC);
+       }
        if (!ptr)
-               return malloc(size * num);
-       return realloc(ptr, size * num);
+               ptr = malloc(num * size);
+       else if (ptr == do_calloc)
+               ptr = calloc(num, size);
+       else
+               ptr = realloc(ptr, num * size);
+       if (!ptr && file)
+               _out_of_memory("my_alloc caller", file, line);
+       return ptr;
 }
 
 const char *sum_as_hex(int csum_type, const char *sum, int flist_csum)
@@ -112,14 +117,29 @@ const char *sum_as_hex(int csum_type, const char *sum, int flist_csum)
        return buf;
 }
 
-NORETURN void out_of_memory(const char *str)
+NORETURN void _out_of_memory(const char *msg, const char *file, int line)
 {
-       rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
+       rprintf(FERROR, "[%s] out of memory: %s (file=%s, line=%d)\n", who_am_i(), msg, src_file(file), line);
        exit_cleanup(RERR_MALLOC);
 }
 
-NORETURN void overflow_exit(const char *str)
+NORETURN void _overflow_exit(const char *msg, const char *file, int line)
 {
-       rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
+       rprintf(FERROR, "[%s] buffer overflow: %s (file=%s, line=%d)\n", who_am_i(), msg, src_file(file), line);
        exit_cleanup(RERR_MALLOC);
 }
+
+const char *src_file(const char *file)
+{
+       static const char *util2 = __FILE__;
+       static int prefix = -1;
+
+       if (prefix < 0) {
+               const char *cp = strrchr(util2, '/');
+               prefix = cp ? cp - util2 + 1 : 0;
+       }
+
+       if (prefix && strncmp(file, util2, prefix) == 0)
+               return file + prefix;
+       return file;
+}