From 862c5fe0b4a102bf74f2387b706d0b5d1c58149e Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Sun, 8 May 2022 14:59:09 -0700 Subject: [PATCH 01/12] Optimization: replace limited allocation calls There are a large number of allocations for fix sized buffers using the `cli_malloc` and `cli_calloc` calls that check if the requested size is larger than our allocation threshold for allocations based on untrusted input. These allocations will *always* be higher than the threshold, so the extra stack frame and check for these calls is a waste of CPU. This commit replaces needless calls with A -> B: - cli_malloc -> malloc - cli_calloc -> calloc - CLI_MALLOC -> MALLOC - CLI_CALLOC -> CALLOC I also noticed that our MPOOL_MALLOC / MPOOL_CALLOC are not limited by the max-allocation threshold, when MMAP is found/enabled. But the alternative was set to cli_malloc / cli_calloc when disabled. I changed those as well. I didn't change the cli_realloc/2 calls because our version of realloc not only implements a threshold but also stabilizes the undefined behavior in realloc to protect against accidental double-free's. It may be worth implementing a cli_realloc that doesn't have the threshold built-in, however, so as to allow reallocaitons for things like buffers for loading signatures, which aren't subject to the same concern as allocations for scanning possible malware. There was one case in mbox.c where I changed MALLOC -> CLI_MALLOC, because it appears to be allocating based on untrusted input. --- clamonacc/clamonacc.c | 2 +- clamonacc/fanotif/fanotif.c | 4 +-- clamonacc/inotif/hash.c | 10 +++---- clamonacc/inotif/inotif.c | 2 +- clamonacc/misc/utils.c | 2 +- libclamav/aspack.c | 2 +- libclamav/blob.c | 8 +++--- libclamav/bytecode.c | 41 +++++++++++++++++++--------- libclamav/bytecode_vm.c | 2 +- libclamav/crtmgr.c | 2 +- libclamav/cvd.c | 2 +- libclamav/dmg.c | 2 +- libclamav/egg.c | 14 +++++----- libclamav/entconv.c | 6 ++-- libclamav/events.c | 2 +- libclamav/fmap.c | 6 ++-- libclamav/hfsplus.c | 2 +- libclamav/htmlnorm.c | 6 ++-- libclamav/inflate64.c | 2 +- libclamav/ishield.c | 2 +- libclamav/jsparse/js-norm.c | 6 ++-- libclamav/lzw/lzwdec.c | 2 +- libclamav/matcher-ac.c | 6 ++-- libclamav/matcher-byte-comp.c | 2 +- libclamav/matcher-pcre.c | 4 +-- libclamav/mbox.c | 6 ++-- libclamav/message.c | 30 ++++++++++---------- libclamav/mew.c | 2 +- libclamav/mpool.h | 4 +-- libclamav/msdoc.c | 2 +- libclamav/ole2_extract.c | 6 ++-- libclamav/openioc.c | 2 +- libclamav/others.c | 4 +-- libclamav/others_common.c | 4 +-- libclamav/partition_intersection.c | 2 +- libclamav/pdf.c | 16 +++++------ libclamav/pdfdecode.c | 8 +++--- libclamav/pdfng.c | 6 ++-- libclamav/pe.c | 22 +++++++-------- libclamav/phish_domaincheck_db.c | 2 +- libclamav/readdb.c | 18 ++++++------ libclamav/regex_list.c | 6 ++-- libclamav/regex_pcre.c | 2 +- libclamav/regex_suffix.c | 14 +++++----- libclamav/rtf.c | 4 +-- libclamav/scanners.c | 4 +-- libclamav/table.c | 6 ++-- libclamav/text.c | 10 +++---- libclamav/uniq.c | 2 +- libclamav/unzip.c | 2 +- libclamav/vba_extract.c | 2 +- libclamav/yara_parser.c | 2 +- libfreshclam/libfreshclam_internal.c | 4 +-- unit_tests/check_clamav.c | 2 +- unit_tests/check_regex.c | 24 ++++++++-------- 55 files changed, 186 insertions(+), 171 deletions(-) diff --git a/clamonacc/clamonacc.c b/clamonacc/clamonacc.c index 2c6b886542..c8e6e030d7 100644 --- a/clamonacc/clamonacc.c +++ b/clamonacc/clamonacc.c @@ -291,7 +291,7 @@ static void onas_handle_signals(void) struct onas_context *onas_init_context(void) { - struct onas_context *ctx = (struct onas_context *)cli_malloc(sizeof(struct onas_context)); + struct onas_context *ctx = (struct onas_context *)malloc(sizeof(struct onas_context)); if (NULL == ctx) { return NULL; } diff --git a/clamonacc/fanotif/fanotif.c b/clamonacc/fanotif/fanotif.c index f85b1d9faf..0e1a89e06d 100644 --- a/clamonacc/fanotif/fanotif.c +++ b/clamonacc/fanotif/fanotif.c @@ -234,7 +234,7 @@ int onas_fan_eloop(struct onas_context **ctx) if (scan) { struct onas_scan_event *event_data; - event_data = cli_calloc(1, sizeof(struct onas_scan_event)); + event_data = calloc(1, sizeof(struct onas_scan_event)); if (NULL == event_data) { close(fmd->fd); logg(LOGG_ERROR, "ClamFanotif: could not allocate memory for event data struct\n"); @@ -247,7 +247,7 @@ int onas_fan_eloop(struct onas_context **ctx) /* fanotify specific stuffs */ event_data->bool_opts |= ONAS_SCTH_B_FANOTIFY; - event_data->fmd = cli_malloc(sizeof(struct fanotify_event_metadata)); + event_data->fmd = malloc(sizeof(struct fanotify_event_metadata)); if (NULL == event_data->fmd) { close(fmd->fd); free(event_data); diff --git a/clamonacc/inotif/hash.c b/clamonacc/inotif/hash.c index ce82b00d69..e57b513bd2 100644 --- a/clamonacc/inotif/hash.c +++ b/clamonacc/inotif/hash.c @@ -136,7 +136,7 @@ int onas_ht_init(struct onas_ht **ht, uint32_t size) if (size == 0 || (size & (~size + 1)) != size) return CL_EARG; - *ht = (struct onas_ht *)cli_malloc(sizeof(struct onas_ht)); + *ht = (struct onas_ht *)malloc(sizeof(struct onas_ht)); if (!(*ht)) return CL_EMEM; **ht = (struct onas_ht){ @@ -180,7 +180,7 @@ void onas_free_ht(struct onas_ht *ht) static struct onas_bucket *onas_bucket_init() { - struct onas_bucket *bckt = (struct onas_bucket *)cli_malloc(sizeof(struct onas_bucket)); + struct onas_bucket *bckt = (struct onas_bucket *)malloc(sizeof(struct onas_bucket)); if (!bckt) return NULL; *bckt = (struct onas_bucket){ @@ -216,7 +216,7 @@ static void onas_free_bucket(struct onas_bucket *bckt) struct onas_element *onas_element_init(struct onas_hnode *value, const char *key, size_t klen) { - struct onas_element *elem = (struct onas_element *)cli_malloc(sizeof(struct onas_element)); + struct onas_element *elem = (struct onas_element *)malloc(sizeof(struct onas_element)); if (!elem) return NULL; *elem = (struct onas_element){ @@ -392,7 +392,7 @@ static int onas_bucket_remove(struct onas_bucket *bckt, struct onas_element *ele static struct onas_hnode *onas_hashnode_init(void) { struct onas_hnode *hnode = NULL; - if (!(hnode = (struct onas_hnode *)cli_malloc(sizeof(struct onas_hnode)))) { + if (!(hnode = (struct onas_hnode *)malloc(sizeof(struct onas_hnode)))) { return NULL; } @@ -428,7 +428,7 @@ static struct onas_hnode *onas_hashnode_init(void) static struct onas_lnode *onas_listnode_init(void) { struct onas_lnode *lnode = NULL; - if (!(lnode = (struct onas_lnode *)cli_malloc(sizeof(struct onas_lnode)))) { + if (!(lnode = (struct onas_lnode *)malloc(sizeof(struct onas_lnode)))) { return NULL; } diff --git a/clamonacc/inotif/inotif.c b/clamonacc/inotif/inotif.c index 6cc9ee00cc..c2d3a1b0af 100644 --- a/clamonacc/inotif/inotif.c +++ b/clamonacc/inotif/inotif.c @@ -814,7 +814,7 @@ static void onas_ddd_handle_extra_scanning(struct onas_context *ctx, const char struct onas_scan_event *event_data; - event_data = (struct onas_scan_event *)cli_calloc(1, sizeof(struct onas_scan_event)); + event_data = (struct onas_scan_event *)calloc(1, sizeof(struct onas_scan_event)); if (NULL == event_data) { logg(LOGG_ERROR, "ClamInotif: could not allocate memory for event data struct\n"); } diff --git a/clamonacc/misc/utils.c b/clamonacc/misc/utils.c index dda42ca067..f231a957e3 100644 --- a/clamonacc/misc/utils.c +++ b/clamonacc/misc/utils.c @@ -159,7 +159,7 @@ char **onas_get_opt_list(const char *fname, int *num_entries, cl_error_t *err) *num_entries = 0; - opt_list = cli_malloc(sizeof(char *)); + opt_list = malloc(sizeof(char *)); if (NULL == opt_list) { *err = CL_EMEM; return NULL; diff --git a/libclamav/aspack.c b/libclamav/aspack.c index 134713e70b..662b8973fe 100644 --- a/libclamav/aspack.c +++ b/libclamav/aspack.c @@ -399,7 +399,7 @@ int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections blocks = image + ep + blocks_offset; - if (!(wrkbuf = cli_calloc(0x1800, sizeof(uint8_t)))) { + if (!(wrkbuf = calloc(0x1800, sizeof(uint8_t)))) { cli_dbgmsg("Aspack: Unable to allocate dictionary\n"); return 0; } diff --git a/libclamav/blob.c b/libclamav/blob.c index 6f16052c8d..6fc3fc5f39 100644 --- a/libclamav/blob.c +++ b/libclamav/blob.c @@ -65,13 +65,13 @@ blob * blobCreate(void) { #ifdef CL_DEBUG - blob *b = (blob *)cli_calloc(1, sizeof(blob)); + blob *b = (blob *)calloc(1, sizeof(blob)); if (b) b->magic = BLOBCLASS; cli_dbgmsg("blobCreate\n"); return b; #else - return (blob *)cli_calloc(1, sizeof(blob)); + return (blob *)calloc(1, sizeof(blob)); #endif } @@ -404,13 +404,13 @@ fileblob * fileblobCreate(void) { #ifdef CL_DEBUG - fileblob *fb = (fileblob *)cli_calloc(1, sizeof(fileblob)); + fileblob *fb = (fileblob *)calloc(1, sizeof(fileblob)); if (fb) fb->b.magic = BLOBCLASS; cli_dbgmsg("blobCreate\n"); return fb; #else - return (fileblob *)cli_calloc(1, sizeof(fileblob)); + return (fileblob *)calloc(1, sizeof(fileblob)); #endif } diff --git a/libclamav/bytecode.c b/libclamav/bytecode.c index 7c430363df..528c967530 100644 --- a/libclamav/bytecode.c +++ b/libclamav/bytecode.c @@ -102,6 +102,22 @@ static void context_safe(struct cli_bc_ctx *ctx) ctx->hooks.pedata = &nopedata; } +void cli_bytecode_context_destroy(struct cli_bc_ctx *ctx) +{ + cli_bytecode_context_clear(ctx); + free(ctx); +} + +int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilename) +{ + int fd; + *tempfilename = ctx->tempfile; + fd = ctx->outfd; + ctx->tempfile = NULL; + ctx->outfd = 0; + return fd; +} + /** * @brief Reset bytecode state, so you can run another bytecode with same ctx. * @@ -109,7 +125,7 @@ static void context_safe(struct cli_bc_ctx *ctx) * * @param ctx */ -static void bytecode_context_reset(struct cli_bc_ctx *ctx) +static int bytecode_context_reset(struct cli_bc_ctx *ctx) { unsigned i; @@ -253,14 +269,13 @@ static inline void bytecode_context_initialize(struct cli_bc_ctx *ctx) struct cli_bc_ctx *cli_bytecode_context_alloc(void) { - struct cli_bc_ctx *ctx = cli_malloc(sizeof(*ctx)); + struct cli_bc_ctx *ctx = calloc(1, sizeof(*ctx)); if (!ctx) { cli_errmsg("Failed to allocate bytecode context\n"); return NULL; } bytecode_context_initialize(ctx); - bytecode_context_reset(ctx); return ctx; } @@ -825,7 +840,7 @@ static cl_error_t parseTypes(struct cli_bc *bc, unsigned char *buffer) ty->kind = DPointerType; ty->numElements = 1; } - ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes)); + ty->containedTypes = malloc(sizeof(*ty->containedTypes)); if (!ty->containedTypes) { cli_errmsg("Out of memory allocating containedType\n"); return CL_EMALFDB; @@ -2418,17 +2433,17 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) bc->trusted = 1; bc->num_globals = 1; - bc->globals = cli_calloc(1, sizeof(*bc->globals)); + bc->globals = calloc(1, sizeof(*bc->globals)); if (!bc->globals) { cli_errmsg("Failed to allocate memory for globals\n"); return CL_EMEM; } - bc->globals[0] = cli_calloc(1, sizeof(*bc->globals[0])); + bc->globals[0] = calloc(1, sizeof(*bc->globals[0])); if (!bc->globals[0]) { cli_errmsg("Failed to allocate memory for globals\n"); return CL_EMEM; } - bc->globaltys = cli_calloc(1, sizeof(*bc->globaltys)); + bc->globaltys = calloc(1, sizeof(*bc->globaltys)); if (!bc->globaltys) { cli_errmsg("Failed to allocate memory for globaltypes\n"); return CL_EMEM; @@ -2439,7 +2454,7 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) bc->kind = 0; bc->num_types = 5; bc->num_func = 1; - bc->funcs = cli_calloc(1, sizeof(*bc->funcs)); + bc->funcs = calloc(1, sizeof(*bc->funcs)); if (!bc->funcs) { cli_errmsg("Failed to allocate memory for func\n"); return CL_EMEM; @@ -2451,25 +2466,25 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) func->numConstants = 1; func->numBB = 1; func->returnType = 32; - func->types = cli_calloc(1, sizeof(*func->types)); + func->types = calloc(1, sizeof(*func->types)); if (!func->types) { cli_errmsg("Failed to allocate memory for types\n"); return CL_EMEM; } func->types[0] = 32; - func->BB = cli_calloc(1, sizeof(*func->BB)); + func->BB = calloc(1, sizeof(*func->BB)); if (!func->BB) { cli_errmsg("Failed to allocate memory for BB\n"); return CL_EMEM; } - func->allinsts = cli_calloc(2, sizeof(*func->allinsts)); + func->allinsts = calloc(2, sizeof(*func->allinsts)); if (!func->allinsts) { cli_errmsg("Failed to allocate memory for insts\n"); return CL_EMEM; } func->BB->numInsts = 2; func->BB->insts = func->allinsts; - func->constants = cli_calloc(1, sizeof(*func->constants)); + func->constants = calloc(1, sizeof(*func->constants)); if (!func->constants) { cli_errmsg("Failed to allocate memory for constants\n"); return CL_EMEM; @@ -2480,7 +2495,7 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) inst->opcode = OP_BC_CALL_API; inst->u.ops.numOps = 1; inst->u.ops.opsizes = NULL; - inst->u.ops.ops = cli_calloc(1, sizeof(*inst->u.ops.ops)); + inst->u.ops.ops = calloc(1, sizeof(*inst->u.ops.ops)); if (!inst->u.ops.ops) { cli_errmsg("Failed to allocate memory for instructions\n"); return CL_EMEM; diff --git a/libclamav/bytecode_vm.c b/libclamav/bytecode_vm.c index fcae6f7f9b..45f11634a2 100644 --- a/libclamav/bytecode_vm.c +++ b/libclamav/bytecode_vm.c @@ -171,7 +171,7 @@ static always_inline void *cli_stack_alloc(struct stack *stack, unsigned bytes) return NULL; } /* not enough room here, allocate new chunk */ - chunk = cli_malloc(sizeof(*stack->chunk)); + chunk = malloc(sizeof(*stack->chunk)); if (!chunk) { cli_warnmsg("cli_stack_alloc: Unable to allocate memory for stack-chunk: bytes: %zu!\n", sizeof(*stack->chunk)); return NULL; diff --git a/libclamav/crtmgr.c b/libclamav/crtmgr.c index d8660c3ede..b350770b0c 100644 --- a/libclamav/crtmgr.c +++ b/libclamav/crtmgr.c @@ -229,7 +229,7 @@ bool crtmgr_add(crtmgr *m, cli_crt *x509) } } - i = cli_malloc(sizeof(*i)); + i = malloc(sizeof(*i)); if (i == NULL) { goto done; } diff --git a/libclamav/cvd.c b/libclamav/cvd.c index d2fcb85d57..fabb568aee 100644 --- a/libclamav/cvd.c +++ b/libclamav/cvd.c @@ -407,7 +407,7 @@ struct cl_cvd *cl_cvdparse(const char *head) return NULL; } - if (!(cvd = (struct cl_cvd *)cli_malloc(sizeof(struct cl_cvd)))) { + if (!(cvd = (struct cl_cvd *)malloc(sizeof(struct cl_cvd)))) { cli_errmsg("cl_cvdparse: Can't allocate memory for cvd\n"); return NULL; } diff --git a/libclamav/dmg.c b/libclamav/dmg.c index 3c6b5a58d5..d9d1369a69 100644 --- a/libclamav/dmg.c +++ b/libclamav/dmg.c @@ -279,7 +279,7 @@ int cli_scandmg(cli_ctx *ctx) continue; } /* Have encoded mish block */ - mish_set = cli_malloc(sizeof(struct dmg_mish_with_stripes)); + mish_set = malloc(sizeof(struct dmg_mish_with_stripes)); if (mish_set == NULL) { ret = CL_EMEM; xmlFree(textValue); diff --git a/libclamav/egg.c b/libclamav/egg.c index 42aaa5f212..6738571e73 100644 --- a/libclamav/egg.c +++ b/libclamav/egg.c @@ -517,7 +517,7 @@ static cl_error_t egg_parse_encrypt_header(const uint8_t* index, size_t size, eg goto done; } - encrypt = (egg_encrypt*)cli_calloc(1, sizeof(egg_encrypt)); + encrypt = (egg_encrypt*)calloc(1, sizeof(egg_encrypt)); if (NULL == encrypt) { cli_errmsg("egg_parse_encrypt_header: Failed to allocate memory for egg_encrypt.\n"); status = CL_EMEM; @@ -687,7 +687,7 @@ static cl_error_t egg_parse_block_headers(egg_handle* handle, egg_block** block) goto done; } - eggBlock = (egg_block*)cli_calloc(1, sizeof(egg_block)); + eggBlock = (egg_block*)calloc(1, sizeof(egg_block)); if (NULL == eggBlock) { cli_errmsg("egg_parse_block_headers: Failed to allocate memory for egg_block.\n"); status = CL_EMEM; @@ -1369,7 +1369,7 @@ static cl_error_t egg_parse_file_headers(egg_handle* handle, egg_file** file) goto done; } - eggFile = (egg_file*)cli_calloc(1, sizeof(egg_file)); + eggFile = (egg_file*)calloc(1, sizeof(egg_file)); if (NULL == eggFile) { cli_errmsg("egg_parse_file_headers: Failed to allocate memory for egg_file.\n"); status = CL_EMEM; @@ -1603,7 +1603,7 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t *comments = NULL; *nComments = 0; - handle = (egg_handle*)cli_calloc(1, sizeof(egg_handle)); + handle = (egg_handle*)calloc(1, sizeof(egg_handle)); if (NULL == handle) { cli_errmsg("cli_egg_open: Failed to allocate memory for egg_handle.\n"); status = CL_EMEM; @@ -1936,7 +1936,7 @@ cl_error_t cli_egg_deflate_decompress(char* compressed, size_t compressed_size, *decompressed = NULL; *decompressed_size = 0; - if (!(decoded = (uint8_t*)cli_calloc(BUFSIZ, sizeof(uint8_t)))) { + if (!(decoded = (uint8_t*)calloc(BUFSIZ, sizeof(uint8_t)))) { cli_errmsg("cli_egg_deflate_decompress: cannot allocate memory for decompressed output\n"); status = CL_EMEM; goto done; @@ -2060,7 +2060,7 @@ cl_error_t cli_egg_bzip2_decompress(char* compressed, size_t compressed_size, ch *decompressed = NULL; *decompressed_size = 0; - if (!(decoded = (char*)cli_calloc(BUFSIZ, sizeof(Bytef)))) { + if (!(decoded = (char*)calloc(BUFSIZ, sizeof(Bytef)))) { cli_errmsg("cli_egg_bzip2_decompress: cannot allocate memory for decompressed output\n"); status = CL_EMEM; goto done; @@ -2175,7 +2175,7 @@ cl_error_t cli_egg_lzma_decompress(char* compressed, size_t compressed_size, cha *decompressed = NULL; *decompressed_size = 0; - if (!(decoded = (uint8_t*)cli_calloc(BUFSIZ, sizeof(char)))) { + if (!(decoded = (uint8_t*)calloc(BUFSIZ, sizeof(char)))) { cli_errmsg("cli_egg_lzma_decompress: cannot allocate memory for decompressed output\n"); status = CL_EMEM; goto done; diff --git a/libclamav/entconv.c b/libclamav/entconv.c index e7e365a182..1eab80c30e 100644 --- a/libclamav/entconv.c +++ b/libclamav/entconv.c @@ -157,7 +157,7 @@ static iconv_t iconv_open(const char* tocode, const char* fromcode) { UNUSEDPARAM(tocode); - iconv_t iconv = cli_malloc(sizeof(*iconv)); + iconv_t iconv = malloc(sizeof(*iconv)); if (!iconv) return NULL; @@ -584,7 +584,7 @@ static inline struct iconv_cache* cache_get_tls_instance(void) { struct iconv_cache* cache = pthread_getspecific(iconv_pool_tls_key); if (!cache) { - cache = cli_calloc(1, sizeof(*cache)); + cache = calloc(1, sizeof(*cache)); if (!cache) { cli_dbgmsg(MODULE_NAME "!Out of memory allocating TLS iconv instance\n"); return NULL; @@ -608,7 +608,7 @@ static void iconv_cache_cleanup_main(void) static inline void init_iconv_pool_ifneeded() { if (!iconv_global_inited) { - global_iconv_cache = cli_calloc(1, sizeof(*global_iconv_cache)); + global_iconv_cache = calloc(1, sizeof(*global_iconv_cache)); if (global_iconv_cache) { iconv_cache_init(global_iconv_cache); atexit(iconv_cache_cleanup_main); diff --git a/libclamav/events.c b/libclamav/events.c index 298fbd4f49..2011bb7852 100644 --- a/libclamav/events.c +++ b/libclamav/events.c @@ -50,7 +50,7 @@ struct cli_events { cli_events_t *cli_events_new(unsigned max_event) { - struct cli_events *ev = cli_calloc(1, sizeof(*ev)); + struct cli_events *ev = calloc(1, sizeof(*ev)); if (!ev) return NULL; ev->max = max_event; diff --git a/libclamav/fmap.c b/libclamav/fmap.c index 9a63193753..65228647f5 100644 --- a/libclamav/fmap.c +++ b/libclamav/fmap.c @@ -243,7 +243,7 @@ fmap_t *fmap_duplicate(cl_fmap_t *map, size_t offset, size_t length, const char goto done; } - duplicate_map = cli_malloc(sizeof(cl_fmap_t)); + duplicate_map = malloc(sizeof(cl_fmap_t)); if (!duplicate_map) { cli_warnmsg("fmap_duplicate: map allocation failed\n"); goto done; @@ -375,7 +375,7 @@ extern cl_fmap_t *cl_fmap_open_handle(void *handle, size_t offset, size_t len, bitmap_size = pages * sizeof(uint64_t); mapsz = pages * pgsz; - m = cli_calloc(1, sizeof(fmap_t)); + m = calloc(1, sizeof(fmap_t)); if (!m) { cli_warnmsg("fmap: map header allocation failed\n"); goto done; @@ -844,7 +844,7 @@ fmap_t *fmap_open_memory(const void *start, size_t len, const char *name) cl_error_t status = CL_ERROR; int pgsz = cli_getpagesize(); - cl_fmap_t *m = cli_calloc(1, sizeof(*m)); + cl_fmap_t *m = calloc(1, sizeof(*m)); if (!m) { cli_warnmsg("fmap: map allocation failed\n"); goto done; diff --git a/libclamav/hfsplus.c b/libclamav/hfsplus.c index c0c1ad7ac6..b7f439b981 100644 --- a/libclamav/hfsplus.c +++ b/libclamav/hfsplus.c @@ -149,7 +149,7 @@ static cl_error_t hfsplus_volumeheader(cli_ctx *ctx, hfsPlusVolumeHeader **heade return CL_EMAP; } - volHeader = cli_malloc(sizeof(hfsPlusVolumeHeader)); + volHeader = malloc(sizeof(hfsPlusVolumeHeader)); if (!volHeader) { cli_errmsg("hfsplus_volumeheader: header malloc failed\n"); return CL_EMEM; diff --git a/libclamav/htmlnorm.c b/libclamav/htmlnorm.c index 3e90ea7ab8..129dc8b5bd 100644 --- a/libclamav/htmlnorm.c +++ b/libclamav/htmlnorm.c @@ -720,7 +720,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha tag_args.value = NULL; tag_args.contents = NULL; if (dirname) { - file_buff_o2 = (file_buff_t *)cli_malloc(sizeof(file_buff_t)); + file_buff_o2 = (file_buff_t *)malloc(sizeof(file_buff_t)); if (!file_buff_o2) { cli_errmsg("cli_html_normalise: Unable to allocate memory for file_buff_o2\n"); file_buff_o2 = file_buff_text = NULL; @@ -737,7 +737,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha goto done; } - file_buff_text = (file_buff_t *)cli_malloc(sizeof(file_buff_t)); + file_buff_text = (file_buff_t *)malloc(sizeof(file_buff_t)); if (!file_buff_text) { close(file_buff_o2->fd); free(file_buff_o2); @@ -1671,7 +1671,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha free(file_tmp_o1); } - file_tmp_o1 = (file_buff_t *)cli_malloc(sizeof(file_buff_t)); + file_tmp_o1 = (file_buff_t *)malloc(sizeof(file_buff_t)); if (!file_tmp_o1) { cli_errmsg("cli_html_normalise: Unable to allocate memory for file_tmp_o1\n"); goto done; diff --git a/libclamav/inflate64.c b/libclamav/inflate64.c index 903aba9b8e..22a209c50f 100644 --- a/libclamav/inflate64.c +++ b/libclamav/inflate64.c @@ -69,7 +69,7 @@ int windowBits; struct inflate_state FAR *state; if (strm == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)cli_calloc(1, sizeof(struct inflate_state)); + state = (struct inflate_state FAR *)calloc(1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; diff --git a/libclamav/ishield.c b/libclamav/ishield.c index aecf8308a3..5a93695118 100644 --- a/libclamav/ishield.c +++ b/libclamav/ishield.c @@ -746,7 +746,7 @@ static cl_error_t is_extract_cab(cli_ctx *ctx, uint64_t off, uint64_t size, uint int success = 0; fmap_t *map = ctx->fmap; - if (!(outbuf = cli_malloc(IS_CABBUFSZ))) { + if (!(outbuf = malloc(IS_CABBUFSZ))) { cli_errmsg("is_extract_cab: Unable to allocate memory for outbuf\n"); return CL_EMEM; } diff --git a/libclamav/jsparse/js-norm.c b/libclamav/jsparse/js-norm.c index e417ac4b45..83b01337da 100644 --- a/libclamav/jsparse/js-norm.c +++ b/libclamav/jsparse/js-norm.c @@ -117,7 +117,7 @@ struct parser_state { static struct scope *scope_new(struct parser_state *state) { struct scope *parent = state->current; - struct scope *s = cli_calloc(1, sizeof(*s)); + struct scope *s = calloc(1, sizeof(*s)); if (!s) return NULL; if (cli_hashtab_init(&s->id_map, 10) < 0) { @@ -1209,7 +1209,7 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n struct parser_state *cli_js_init(void) { - struct parser_state *state = cli_calloc(1, sizeof(*state)); + struct parser_state *state = calloc(1, sizeof(*state)); if (!state) return NULL; if (!scope_new(state)) { @@ -1720,7 +1720,7 @@ static int parseOperator(YYSTYPE *lvalp, yyscan_t scanner) static int yylex_init(yyscan_t *scanner) { - *scanner = cli_calloc(1, sizeof(**scanner)); + *scanner = calloc(1, sizeof(**scanner)); return *scanner ? 0 : -1; } diff --git a/libclamav/lzw/lzwdec.c b/libclamav/lzw/lzwdec.c index 40d2d16ff7..b9aac5d016 100644 --- a/libclamav/lzw/lzwdec.c +++ b/libclamav/lzw/lzwdec.c @@ -160,7 +160,7 @@ int lzwInit(lzw_streamp strm) struct lzw_internal_state *state; hcode_t code; - state = cli_malloc(sizeof(struct lzw_internal_state)); + state = malloc(sizeof(struct lzw_internal_state)); if (state == NULL) { strm->msg = "failed to allocate state"; return LZW_MEM_ERROR; diff --git a/libclamav/matcher-ac.c b/libclamav/matcher-ac.c index ff102f5001..877d95dc96 100644 --- a/libclamav/matcher-ac.c +++ b/libclamav/matcher-ac.c @@ -494,7 +494,7 @@ static int bfs_enqueue(struct bfs_list **bfs, struct bfs_list **last, struct cli { struct bfs_list *new; - new = (struct bfs_list *)cli_malloc(sizeof(struct bfs_list)); + new = (struct bfs_list *)malloc(sizeof(struct bfs_list)); if (!new) { cli_errmsg("bfs_enqueue: Can't allocate memory for bfs_list\n"); return CL_EMEM; @@ -1637,7 +1637,7 @@ inline static int ac_addtype(struct cli_matched_type **list, cli_file_t type, of return CL_SUCCESS; } - if (!(tnode = cli_calloc(1, sizeof(struct cli_matched_type)))) { + if (!(tnode = calloc(1, sizeof(struct cli_matched_type)))) { cli_errmsg("cli_ac_addtype: Can't allocate memory for new type node\n"); return CL_EMEM; } @@ -1714,7 +1714,7 @@ cl_error_t lsig_sub_matched(const struct cli_matcher *root, struct cli_ac_data * } ss_matches = ls_matches->matches[subsig_id]; if (ss_matches == NULL) { /* allocate cli_subsig_matches */ - ss_matches = ls_matches->matches[subsig_id] = cli_malloc(sizeof(struct cli_subsig_matches)); + ss_matches = ls_matches->matches[subsig_id] = malloc(sizeof(struct cli_subsig_matches)); if (ss_matches == NULL) { cli_errmsg("lsig_sub_matched: cli_malloc failed for cli_subsig_matches struct\n"); return CL_EMEM; diff --git a/libclamav/matcher-byte-comp.c b/libclamav/matcher-byte-comp.c index 1fa294ea03..7e101e2908 100644 --- a/libclamav/matcher-byte-comp.c +++ b/libclamav/matcher-byte-comp.c @@ -496,7 +496,7 @@ cl_error_t cli_bcomp_scanbuf(const unsigned char *buffer, size_t buffer_length, } else { /* mdata isn't populated in sigtool so run the raw matcher stuffs */ if (res) { - newres = (struct cli_ac_result *)cli_calloc(1, sizeof(struct cli_ac_result)); + newres = (struct cli_ac_result *)calloc(1, sizeof(struct cli_ac_result)); if (!newres) { cli_errmsg("cli_bcomp_scanbuf: can't allocate memory for new result\n"); ret = CL_EMEM; diff --git a/libclamav/matcher-pcre.c b/libclamav/matcher-pcre.c index 63534b4eed..08f9dc8e08 100644 --- a/libclamav/matcher-pcre.c +++ b/libclamav/matcher-pcre.c @@ -90,7 +90,7 @@ static void pcre_perf_events_init(struct cli_pcre_meta *pm, const char *virname) } /* set the name */ - pm->statname = (char *)cli_calloc(1, namelen); + pm->statname = (char *)calloc(1, namelen); if (!pm->statname) { return; } @@ -719,7 +719,7 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const } else { /* for raw match data - sigtool only */ if (res) { - newres = (struct cli_ac_result *)cli_calloc(1, sizeof(struct cli_ac_result)); + newres = (struct cli_ac_result *)calloc(1, sizeof(struct cli_ac_result)); if (!newres) { cli_errmsg("cli_pcre_scanbuff: Can't allocate memory for new result\n"); ret = CL_EMEM; diff --git a/libclamav/mbox.c b/libclamav/mbox.c index 6221824a72..295d467fb6 100644 --- a/libclamav/mbox.c +++ b/libclamav/mbox.c @@ -624,7 +624,7 @@ appendReadStruct(ReadStruct *rs, const char *const buffer) strncpy(&(rs->buffer[rs->bufferLen]), buffer, part); rs->bufferLen += part; - CLI_CALLOC(next, 1, sizeof(ReadStruct)); + CALLOC(next, 1, sizeof(ReadStruct)); rs->next = next; strcpy(next->buffer, &(buffer[part])); @@ -654,7 +654,7 @@ getMallocedBufferFromList(const ReadStruct *head) rs = rs->next; } - MALLOC(working, bufferLen); + CLI_MALLOC(working, bufferLen); rs = head; bufferLen = 0; @@ -844,7 +844,7 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first if (ret == NULL) return NULL; - CLI_CALLOC(head, 1, sizeof(ReadStruct)); + CALLOC(head, 1, sizeof(ReadStruct)); curr = head; strncpy(buffer, firstLine, sizeof(buffer) - 1); diff --git a/libclamav/message.c b/libclamav/message.c index 21ca798c42..7d1e25969d 100644 --- a/libclamav/message.c +++ b/libclamav/message.c @@ -140,7 +140,7 @@ static const unsigned char base64Table[256] = { message * messageCreate(void) { - message *m = (message *)cli_calloc(1, sizeof(message)); + message *m = (message *)calloc(1, sizeof(message)); if (m) m->mimeType = NOMIME; @@ -920,9 +920,9 @@ int messageAddLine(message *m, line_t *line) } if (m->body_first == NULL) - m->body_last = m->body_first = (text *)cli_malloc(sizeof(text)); + m->body_last = m->body_first = (text *)malloc(sizeof(text)); else { - m->body_last->t_next = (text *)cli_malloc(sizeof(text)); + m->body_last->t_next = (text *)malloc(sizeof(text)); m->body_last = m->body_last->t_next; } @@ -982,7 +982,7 @@ int messageAddStr(message *m, const char *data) } if (m->body_first == NULL) - m->body_last = m->body_first = (text *)cli_malloc(sizeof(text)); + m->body_last = m->body_first = (text *)malloc(sizeof(text)); else { if (m->body_last == NULL) { cli_errmsg("Internal email parser error: message 'body_last' pointer should not be NULL if 'body_first' is set.\n"); @@ -997,10 +997,10 @@ int messageAddStr(message *m, const char *data) /* don't save two blank lines in succession */ return 1; - m->body_last->t_next = (text *)cli_malloc(sizeof(text)); + m->body_last->t_next = (text *)malloc(sizeof(text)); if (m->body_last->t_next == NULL) { messageDedup(m); - m->body_last->t_next = (text *)cli_malloc(sizeof(text)); + m->body_last->t_next = (text *)malloc(sizeof(text)); if (m->body_last->t_next == NULL) { cli_errmsg("messageAddStr: out of memory\n"); return -1; @@ -1550,9 +1550,9 @@ messageToText(message *m) */ for (t_line = messageGetBody(m); t_line; t_line = t_line->t_next) { if (first == NULL) - first = last = cli_malloc(sizeof(text)); + first = last = malloc(sizeof(text)); else { - last->t_next = cli_malloc(sizeof(text)); + last->t_next = malloc(sizeof(text)); last = last->t_next; } @@ -1590,9 +1590,9 @@ messageToText(message *m) */ for (t_line = messageGetBody(m); t_line; t_line = t_line->t_next) { if (first == NULL) - first = last = cli_malloc(sizeof(text)); + first = last = malloc(sizeof(text)); else if (last) { - last->t_next = cli_malloc(sizeof(text)); + last->t_next = malloc(sizeof(text)); last = last->t_next; } @@ -1665,9 +1665,9 @@ messageToText(message *m) } if (first == NULL) - first = last = cli_malloc(sizeof(text)); + first = last = malloc(sizeof(text)); else if (last) { - last->t_next = cli_malloc(sizeof(text)); + last->t_next = malloc(sizeof(text)); last = last->t_next; } @@ -1703,9 +1703,9 @@ messageToText(message *m) memset(data, '\0', sizeof(data)); if (decode(m, NULL, data, base64, false) && data[0]) { if (first == NULL) - first = last = cli_malloc(sizeof(text)); + first = last = malloc(sizeof(text)); else if (last) { - last->t_next = cli_malloc(sizeof(text)); + last->t_next = malloc(sizeof(text)); last = last->t_next; } @@ -2627,7 +2627,7 @@ push(LINK1 *top, const char *string) { LINK1 element; - if ((element = (LINK1)cli_malloc(sizeof(ELEMENT1))) == NULL) + if ((element = (LINK1)malloc(sizeof(ELEMENT1))) == NULL) return OUT_OF_MEMORY; if ((element->d1 = cli_strdup(string)) == NULL) { free(element); diff --git a/libclamav/mew.c b/libclamav/mew.c index a23f17d306..f2d230d56e 100644 --- a/libclamav/mew.c +++ b/libclamav/mew.c @@ -898,7 +898,7 @@ int unmew11(char *src, uint32_t off, uint32_t ssize, uint32_t dsize, uint32_t ba } loc_ds = PESALIGN(loc_ds, 0x1000); - section = cli_calloc(1, sizeof(struct cli_exe_section)); + section = calloc(1, sizeof(struct cli_exe_section)); if (!section) { cli_dbgmsg("MEW: Out of memory\n"); return -1; diff --git a/libclamav/mpool.h b/libclamav/mpool.h index 37271ac72a..bac983f698 100644 --- a/libclamav/mpool.h +++ b/libclamav/mpool.h @@ -66,9 +66,9 @@ int mpool_getstats(const struct cl_engine *engine, size_t *used, size_t *total); typedef void mpool_t; -#define MPOOL_MALLOC(a, b) cli_malloc(b) +#define MPOOL_MALLOC(a, b) malloc(b) #define MPOOL_FREE(a, b) free(b) -#define MPOOL_CALLOC(a, b, c) cli_calloc(b, c) +#define MPOOL_CALLOC(a, b, c) calloc(b, c) #define MPOOL_REALLOC(a, b, c) cli_realloc(b, c) #define MPOOL_REALLOC2(a, b, c) cli_realloc2(b, c) #define CLI_MPOOL_HEX2STR(mpool, src) cli_hex2str(src) diff --git a/libclamav/msdoc.c b/libclamav/msdoc.c index 759ad8386d..d0800e0090 100644 --- a/libclamav/msdoc.c +++ b/libclamav/msdoc.c @@ -72,7 +72,7 @@ ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const char *encodi if (sz == 0) { cli_dbgmsg("ole2_convert_utf: converting empty string\n"); - return cli_calloc(1, 1); // Just send back an empty NULL-terminated string. + return calloc(1, 1); // Just send back an empty NULL-terminated string. } /* applies in the both case */ diff --git a/libclamav/ole2_extract.c b/libclamav/ole2_extract.c index ea212b7a80..a29874e7cd 100644 --- a/libclamav/ole2_extract.c +++ b/libclamav/ole2_extract.c @@ -196,8 +196,8 @@ int ole2_list_push(ole2_list_t *list, uint32_t val) ole2_list_node_t *new_node = NULL; int status = CL_EMEM; - CLI_MALLOC(new_node, sizeof(ole2_list_node_t), - cli_dbgmsg("OLE2: could not allocate new node for worklist!\n")); + MALLOC(new_node, sizeof(ole2_list_node_t), + cli_dbgmsg("OLE2: could not allocate new node for worklist!\n")); new_node->Val = val; new_node->Next = list->Head; @@ -1316,7 +1316,7 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char #if HAVE_JSON cli_jsonstr(ctx->wrkproperty, "FileType", "CL_TYPE_HWP5"); #endif - CLI_CALLOC(hwp_new, 1, sizeof(hwp5_header_t), status = CL_EMEM); + CALLOC(hwp_new, 1, sizeof(hwp5_header_t), status = CL_EMEM); /* * Copy the header information into our header struct. diff --git a/libclamav/openioc.c b/libclamav/openioc.c index 0b25b4df98..7192abc853 100644 --- a/libclamav/openioc.c +++ b/libclamav/openioc.c @@ -100,7 +100,7 @@ static int openioc_parse_content(xmlTextReaderPtr reader, struct openioc_hash ** if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) { xmlval = xmlTextReaderConstValue(reader); if (xmlval) { - elem = cli_calloc(1, sizeof(struct openioc_hash)); + elem = calloc(1, sizeof(struct openioc_hash)); if (NULL == elem) { cli_dbgmsg("openioc_parse: calloc fails for openioc_hash.\n"); return CL_EMEM; diff --git a/libclamav/others.c b/libclamav/others.c index 339936d6f5..375245bc7c 100644 --- a/libclamav/others.c +++ b/libclamav/others.c @@ -453,7 +453,7 @@ struct cl_engine *cl_engine_new(void) struct cl_engine *new; cli_intel_t *intel; - new = (struct cl_engine *)cli_calloc(1, sizeof(struct cl_engine)); + new = (struct cl_engine *)calloc(1, sizeof(struct cl_engine)); if (!new) { cli_errmsg("cl_engine_new: Can't allocate memory for cl_engine\n"); return NULL; @@ -1814,7 +1814,7 @@ bitset_t *cli_bitset_init(void) { bitset_t *bs; - bs = cli_malloc(sizeof(bitset_t)); + bs = malloc(sizeof(bitset_t)); if (!bs) { cli_errmsg("cli_bitset_init: Unable to allocate memory for bs %llu\n", (long long unsigned)sizeof(bitset_t)); return NULL; diff --git a/libclamav/others_common.c b/libclamav/others_common.c index 65f3740669..4ae751f8a0 100644 --- a/libclamav/others_common.c +++ b/libclamav/others_common.c @@ -476,7 +476,7 @@ int cli_filecopy(const char *src, const char *dest) return -1; } - if (!(buffer = cli_malloc(FILEBUFF))) { + if (!(buffer = malloc(FILEBUFF))) { close(s); close(d); return -1; @@ -856,7 +856,7 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ } if (stated && (flags & CLI_FTW_NEED_STAT)) { - statbufp = cli_malloc(sizeof(*statbufp)); + statbufp = malloc(sizeof(*statbufp)); if (!statbufp) { ret = callback(stated ? &statbuf : NULL, NULL, fname, error_mem, data); free(fname); diff --git a/libclamav/partition_intersection.c b/libclamav/partition_intersection.c index 4f6ffe6d17..b22f4f5855 100644 --- a/libclamav/partition_intersection.c +++ b/libclamav/partition_intersection.c @@ -68,7 +68,7 @@ cl_error_t partition_intersection_list_check(partition_intersection_list_t* list } /* allocate new node for partition bounds */ - new_node = (partition_intersection_node_t*)cli_malloc(sizeof(partition_intersection_node_t)); + new_node = (partition_intersection_node_t*)malloc(sizeof(partition_intersection_node_t)); if (!new_node) { cli_dbgmsg("PRTN_INTXN: could not allocate new node for checklist!\n"); partition_intersection_list_free(list); diff --git a/libclamav/pdf.c b/libclamav/pdf.c index 059101c19c..3f39fb84ce 100644 --- a/libclamav/pdf.c +++ b/libclamav/pdf.c @@ -4351,7 +4351,7 @@ static void Author_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfnam const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.author = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.author = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.author)) return; @@ -4381,7 +4381,7 @@ static void Creator_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfna const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.creator = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.creator = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.creator)) return; @@ -4411,7 +4411,7 @@ static void ModificationDate_cb(struct pdf_struct *pdf, struct pdf_obj *obj, str const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.modificationdate = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.modificationdate = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.modificationdate)) return; @@ -4441,7 +4441,7 @@ static void CreationDate_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.creationdate = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.creationdate = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.creationdate)) return; @@ -4471,7 +4471,7 @@ static void Producer_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.producer = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.producer = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.producer)) return; @@ -4501,7 +4501,7 @@ static void Title_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.title = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.title = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.title)) return; @@ -4531,7 +4531,7 @@ static void Keywords_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.keywords = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.keywords = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.keywords)) return; @@ -4561,7 +4561,7 @@ static void Subject_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfna const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - pdf->stats.subject = cli_calloc(1, sizeof(struct pdf_stats_entry)); + pdf->stats.subject = calloc(1, sizeof(struct pdf_stats_entry)); if (!(pdf->stats.subject)) return; diff --git a/libclamav/pdfdecode.c b/libclamav/pdfdecode.c index e6c5ef6162..e1703c8bd6 100644 --- a/libclamav/pdfdecode.c +++ b/libclamav/pdfdecode.c @@ -135,7 +135,7 @@ size_t pdf_decodestream( pdf_print_dict(params, 0); #endif - token = cli_malloc(sizeof(struct pdf_token)); + token = malloc(sizeof(struct pdf_token)); if (!token) { *status = CL_EMEM; goto done; @@ -511,7 +511,7 @@ static cl_error_t filter_rldecode(struct pdf_struct *pdf, struct pdf_obj *obj, s capacity = INFLATE_CHUNK_SIZE; - if (!(decoded = (uint8_t *)cli_malloc(capacity))) { + if (!(decoded = (uint8_t *)malloc(capacity))) { cli_errmsg("cli_pdf: cannot allocate memory for decoded output\n"); return CL_EMEM; } @@ -648,7 +648,7 @@ static cl_error_t filter_flatedecode(struct pdf_struct *pdf, struct pdf_obj *obj capacity = INFLATE_CHUNK_SIZE; - if (!(decoded = (uint8_t *)cli_malloc(capacity))) { + if (!(decoded = (uint8_t *)malloc(capacity))) { cli_errmsg("cli_pdf: cannot allocate memory for decoded output\n"); return CL_EMEM; } @@ -930,7 +930,7 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, capacity = INFLATE_CHUNK_SIZE; - if (!(decoded = (uint8_t *)cli_malloc(capacity))) { + if (!(decoded = (uint8_t *)malloc(capacity))) { cli_errmsg("cli_pdf: cannot allocate memory for decoded output\n"); return CL_EMEM; } diff --git a/libclamav/pdfng.c b/libclamav/pdfng.c index 00cfaee5cd..43204c589b 100644 --- a/libclamav/pdfng.c +++ b/libclamav/pdfng.c @@ -802,7 +802,7 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz if (end[0] != '>' || end[1] != '>') return NULL; - res = cli_calloc(1, sizeof(struct pdf_dict)); + res = calloc(1, sizeof(struct pdf_dict)); if (!(res)) return NULL; @@ -959,7 +959,7 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz } if (!(res->nodes)) { - res->nodes = res->tail = node = cli_calloc(1, sizeof(struct pdf_dict_node)); + res->nodes = res->tail = node = calloc(1, sizeof(struct pdf_dict_node)); if (!(node)) { free(key); if (dict) @@ -1078,7 +1078,7 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s if (*end != ']') return NULL; - res = cli_calloc(1, sizeof(struct pdf_array)); + res = calloc(1, sizeof(struct pdf_array)); if (!(res)) return NULL; diff --git a/libclamav/pe.c b/libclamav/pe.c index 85ac529291..beaac64af5 100644 --- a/libclamav/pe.c +++ b/libclamav/pe.c @@ -572,9 +572,9 @@ static cl_error_t scan_pe_mdb(cli_ctx *ctx, struct cli_exe_section *exe_section) foundsize[type] = cli_hm_have_size(mdb_sect, type, exe_section->rsz); foundwild[type] = cli_hm_have_wild(mdb_sect, type); if (foundsize[type] || foundwild[type]) { - hashset[type] = cli_malloc(hashlen[type]); + hashset[type] = malloc(hashlen[type]); if (!hashset[type]) { - cli_errmsg("scan_pe_mdb: cli_malloc failed!\n"); + cli_errmsg("scan_pe_mdb: malloc failed!\n"); for (; type > 0;) free(hashset[--type]); return CL_EMEM; @@ -602,9 +602,9 @@ static cl_error_t scan_pe_mdb(cli_ctx *ctx, struct cli_exe_section *exe_section) goto end; } - md5 = cli_malloc(16); + md5 = malloc(16); if (!(md5)) { - cli_errmsg("scan_pe_mdb: cli_malloc failed!\n"); + cli_errmsg("scan_pe_mdb: malloc failed!\n"); ret = CL_EMEM; goto end; } @@ -2588,9 +2588,9 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { genhash[type] = cli_hm_have_any(imp, type); if (genhash[type]) { - hashset[type] = cli_malloc(hashlen[type]); + hashset[type] = malloc(hashlen[type]); if (!hashset[type]) { - cli_errmsg("scan_pe: cli_malloc failed!\n"); + cli_errmsg("scan_pe: malloc failed!\n"); for (; type > 0;) free(hashset[--type]); return CL_EMEM; @@ -2607,9 +2607,9 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) if (cli_debug_flag && !genhash[CLI_HASH_MD5]) { #endif genhash[CLI_HASH_MD5] = 1; - hashset[CLI_HASH_MD5] = cli_calloc(hashlen[CLI_HASH_MD5], sizeof(char)); + hashset[CLI_HASH_MD5] = calloc(hashlen[CLI_HASH_MD5], sizeof(char)); if (!hashset[CLI_HASH_MD5]) { - cli_errmsg("scan_pe: cli_malloc failed!\n"); + cli_errmsg("scan_pe: calloc failed!\n"); for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) free(hashset[type]); return CL_EMEM; @@ -3267,7 +3267,7 @@ int cli_scanpe(cli_ctx *ctx) /* Trojan.Swizzor.Gen */ if (SCAN_HEURISTICS && (DCONF & PE_CONF_SWIZZOR) && peinfo->nsections > 1 && fsize > 64 * 1024 && fsize < 4 * 1024 * 1024) { if (peinfo->dirs[2].Size) { - struct swizz_stats *stats = cli_calloc(1, sizeof(*stats)); + struct swizz_stats *stats = calloc(1, sizeof(*stats)); unsigned int m = 1000; ret = CL_CLEAN; @@ -5606,7 +5606,7 @@ cl_error_t cli_check_auth_header(cli_ctx *ctx, struct cli_exe_info *peinfo) // We'll build a list of the regions that need to be hashed and pass it to // asn1_check_mscat to do hash verification there (the hash algorithm is // specified in the PKCS7 structure). We need to hash up to 4 regions - regions = (struct cli_mapped_region *)cli_calloc(4, sizeof(struct cli_mapped_region)); + regions = (struct cli_mapped_region *)calloc(4, sizeof(struct cli_mapped_region)); if (!regions) { ret = CL_EMEM; goto finish; @@ -5864,7 +5864,7 @@ cl_error_t cli_genhash_pe(cli_ctx *ctx, unsigned int class, int type, stats_sect } if (!hash) { - cli_errmsg("cli_genhash_pe: cli_malloc failed!\n"); + cli_errmsg("cli_genhash_pe: cli_calloc failed!\n"); cli_exe_info_destroy(peinfo); return CL_EMEM; } diff --git a/libclamav/phish_domaincheck_db.c b/libclamav/phish_domaincheck_db.c index b228dba313..d2b9e71ae8 100644 --- a/libclamav/phish_domaincheck_db.c +++ b/libclamav/phish_domaincheck_db.c @@ -51,7 +51,7 @@ int domain_list_match(const struct cl_engine* engine, char* real_url, const char int init_domain_list(struct cl_engine* engine) { if (engine) { - engine->domain_list_matcher = (struct regex_matcher*)cli_malloc(sizeof(struct regex_matcher)); + engine->domain_list_matcher = (struct regex_matcher*)malloc(sizeof(struct regex_matcher)); if (!engine->domain_list_matcher) { cli_errmsg("Phishcheck: Unable to allocate memory for init_domain_list\n"); return CL_EMEM; diff --git a/libclamav/readdb.c b/libclamav/readdb.c index f47b24d1ed..13be5abcd2 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -1256,7 +1256,7 @@ static cl_error_t cli_loaddb(FILE *fs, struct cl_engine *engine, unsigned int *s root = engine->root[0]; if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loaddb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -1331,7 +1331,7 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * return CL_EMEM; if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadidb: Can't allocate memory for buffer_cpy\n"); MPOOL_FREE(engine->mempool, matcher); return CL_EMEM; @@ -1607,7 +1607,7 @@ static int cli_loadndb(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadndb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -2254,7 +2254,7 @@ static int cli_loadldb(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; if (engine->ignored) { - if (!(buffer_cpy = cli_malloc(sizeof(buffer)))) { + if (!(buffer_cpy = malloc(sizeof(buffer)))) { cli_errmsg("cli_loadldb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -2837,7 +2837,7 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, } if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadhash: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -2965,7 +2965,7 @@ static int cli_loadmd(FILE *fs, struct cl_engine *engine, unsigned int *signo, i UNUSEDPARAM(dbname); if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadmd: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -3119,7 +3119,7 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, struct cli_cdb *new; if (engine->ignored) - if (!(buffer_cpy = cli_malloc(FILEBUFF))) { + if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadcdb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } @@ -3741,7 +3741,7 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) if (!ytable || !hexsig) return CL_ENULLARG; - new = cli_calloc(1, sizeof(struct cli_ytable_entry)); + new = calloc(1, sizeof(struct cli_ytable_entry)); if (!new) { cli_yaramsg("ytable_add_string: out of memory for new ytable entry\n"); return CL_EMEM; @@ -4354,7 +4354,7 @@ struct _yara_global { cl_error_t cli_yara_init(struct cl_engine *engine) { /* Initialize YARA */ - engine->yara_global = cli_calloc(1, sizeof(struct _yara_global)); + engine->yara_global = calloc(1, sizeof(struct _yara_global)); if (NULL == engine->yara_global) { cli_errmsg("cli_yara_init: failed to create YARA global\n"); return CL_EMEM; diff --git a/libclamav/regex_list.c b/libclamav/regex_list.c index 171f0ddd04..99ae9e2d76 100644 --- a/libclamav/regex_list.c +++ b/libclamav/regex_list.c @@ -774,9 +774,9 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su goto done; } - CLI_MALLOC(regex, sizeof(*regex), - cli_errmsg("add_pattern_suffix: Unable to allocate memory for regex\n"); - ret = CL_EMEM); + MALLOC(regex, sizeof(*regex), + cli_errmsg("add_pattern_suffix: Unable to allocate memory for regex\n"); + ret = CL_EMEM); if (NULL == iregex->pattern) { regex->pattern = NULL; diff --git a/libclamav/regex_pcre.c b/libclamav/regex_pcre.c index 1045866f1d..61eaa98f90 100644 --- a/libclamav/regex_pcre.c +++ b/libclamav/regex_pcre.c @@ -216,7 +216,7 @@ cl_error_t cli_pcre_compile(struct cli_pcre_data *pd, long long unsigned match_l /* now study it... (section totally not from snort) */ pd->ex = pcre_study(pd->re, 0, &error); if (!(pd->ex)) { - pd->ex = (pcre_extra *)cli_calloc(1, sizeof(*(pd->ex))); + pd->ex = (pcre_extra *)calloc(1, sizeof(*(pd->ex))); if (!(pd->ex)) { cli_errmsg("cli_pcre_compile: Unable to allocate memory for extra data\n"); return CL_EMEM; diff --git a/libclamav/regex_suffix.c b/libclamav/regex_suffix.c index c07f6de8e2..bce26a0613 100644 --- a/libclamav/regex_suffix.c +++ b/libclamav/regex_suffix.c @@ -76,7 +76,7 @@ static struct node *make_node(enum node_type type, struct node *left, struct nod if (right == NULL) return left; } - n = cli_malloc(sizeof(*n)); + n = malloc(sizeof(*n)); if (!n) { cli_errmsg("make_node: Unable to allocate memory for new node\n"); return NULL; @@ -99,7 +99,7 @@ static struct node *dup_node(struct node *p) if (!p) return NULL; - d = cli_malloc(sizeof(*d)); + d = malloc(sizeof(*d)); if (!d) { cli_errmsg("dup_node: Unable to allocate memory for duplicate node\n"); return NULL; @@ -111,7 +111,7 @@ static struct node *dup_node(struct node *p) d->u.leaf_char = p->u.leaf_char; break; case leaf_class: - d->u.leaf_class_bitmap = cli_malloc(32); + d->u.leaf_class_bitmap = malloc(32); if (!d->u.leaf_class_bitmap) { cli_errmsg("make_node: Unable to allocate memory for leaf class\n"); free(d); @@ -140,7 +140,7 @@ static struct node *make_charclass(uint8_t *bitmap) return NULL; } - v = cli_malloc(sizeof(*v)); + v = malloc(sizeof(*v)); if (!v) { cli_errmsg("make_charclass: Unable to allocate memory for character class\n"); return NULL; @@ -153,7 +153,7 @@ static struct node *make_charclass(uint8_t *bitmap) static struct node *make_leaf(char c) { - struct node *v = cli_malloc(sizeof(*v)); + struct node *v = malloc(sizeof(*v)); if (!v) return NULL; v->type = leaf; @@ -207,8 +207,8 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos int hasprev = 0; uint8_t *bitmap = NULL; - CLI_MALLOC(bitmap, 32, - cli_errmsg("parse_char_class: Unable to allocate memory for bitmap\n")); + MALLOC(bitmap, 32, + cli_errmsg("parse_char_class: Unable to allocate memory for bitmap\n")); if (pat[*pos] == '^') { memset(bitmap, 0xFF, 32); /*match chars not in brackets*/ diff --git a/libclamav/rtf.c b/libclamav/rtf.c index 2f003cd4a8..6d3c2b35ff 100644 --- a/libclamav/rtf.c +++ b/libclamav/rtf.c @@ -218,7 +218,7 @@ static int load_actions(table_t* t) static int rtf_object_begin(struct rtf_state* state, cli_ctx* ctx, const char* tmpdir) { - struct rtf_object_data* data = cli_malloc(sizeof(*data)); + struct rtf_object_data* data = malloc(sizeof(*data)); if (!data) { cli_errmsg("rtf_object_begin: Unable to allocate memory for object data\n"); return CL_EMEM; @@ -331,7 +331,7 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu data->bread = 0; if (data->desc_len > 64) { cli_dbgmsg("Description length too big (%lu), showing only 64 bytes of it\n", (unsigned long int)data->desc_len); - data->desc_name = cli_malloc(65); + data->desc_name = malloc(65); } else data->desc_name = cli_malloc(data->desc_len + 1); if (!data->desc_name) { diff --git a/libclamav/scanners.c b/libclamav/scanners.c index 5793219e0a..2f3bc1fb19 100644 --- a/libclamav/scanners.c +++ b/libclamav/scanners.c @@ -1354,7 +1354,7 @@ static cl_error_t cli_scanxz(cli_ctx *ctx) size_t avail; unsigned char *buf; - buf = cli_malloc(CLI_XZ_OBUF_SIZE); + buf = malloc(CLI_XZ_OBUF_SIZE); if (buf == NULL) { cli_errmsg("cli_scanxz: nomemory for decompress buffer.\n"); return CL_EMEM; @@ -2772,7 +2772,7 @@ static cl_error_t cli_scancryptff(cli_ctx *ctx) /* Skip the CryptFF file header */ pos = 0x10; - if ((dest = (unsigned char *)cli_malloc(FILEBUFF)) == NULL) { + if ((dest = (unsigned char *)malloc(FILEBUFF)) == NULL) { cli_dbgmsg("CryptFF: Can't allocate memory\n"); return CL_EMEM; } diff --git a/libclamav/table.c b/libclamav/table.c index 21cd0b326d..865843423b 100644 --- a/libclamav/table.c +++ b/libclamav/table.c @@ -41,7 +41,7 @@ struct table * tableCreate(void) { - return (struct table *)cli_calloc(1, sizeof(struct table)); + return (struct table *)calloc(1, sizeof(struct table)); } void tableDestroy(table_t *table) @@ -78,7 +78,7 @@ int tableInsert(table_t *table, const char *key, int value) assert(value != -1); /* that would confuse us */ if (table->tableHead == NULL) - table->tableLast = table->tableHead = (tableEntry *)cli_malloc(sizeof(tableEntry)); + table->tableLast = table->tableHead = (tableEntry *)malloc(sizeof(tableEntry)); else { /* * Re-use deleted items @@ -100,7 +100,7 @@ int tableInsert(table_t *table, const char *key, int value) } table->tableLast = table->tableLast->next = - (tableEntry *)cli_malloc(sizeof(tableEntry)); + (tableEntry *)malloc(sizeof(tableEntry)); } if (table->tableLast == NULL) { diff --git a/libclamav/text.c b/libclamav/text.c index 5eaf1e2891..f56de27723 100644 --- a/libclamav/text.c +++ b/libclamav/text.c @@ -140,9 +140,9 @@ textCopy(const text *t_head) while (t_head) { if (first == NULL) - last = first = (text *)cli_malloc(sizeof(text)); + last = first = (text *)malloc(sizeof(text)); else { - last->t_next = (text *)cli_malloc(sizeof(text)); + last->t_next = (text *)malloc(sizeof(text)); last = last->t_next; } @@ -198,7 +198,7 @@ textAdd(text *t_head, const text *t) cli_dbgmsg("textAdd: count = %d\n", count); while (t) { - t_head->t_next = (text *)cli_malloc(sizeof(text)); + t_head->t_next = (text *)malloc(sizeof(text)); t_head = t_head->t_next; assert(t_head != NULL); @@ -253,7 +253,7 @@ textMove(text *t_head, text *t) cli_errmsg("textMove fails sanity check\n"); return NULL; } - t_head = (text *)cli_malloc(sizeof(text)); + t_head = (text *)malloc(sizeof(text)); if (t_head == NULL) { cli_errmsg("textMove: Unable to allocate memory for head\n"); return NULL; @@ -277,7 +277,7 @@ textMove(text *t_head, text *t) * Move the first line manually so that the caller is left clean but * empty, the rest is moved by a simple pointer reassignment */ - t_head->t_next = (text *)cli_malloc(sizeof(text)); + t_head->t_next = (text *)malloc(sizeof(text)); if (t_head->t_next == NULL) { cli_errmsg("textMove: Unable to allocate memory for head->next\n"); return NULL; diff --git a/libclamav/uniq.c b/libclamav/uniq.c index 8255945cb5..7f34e61d83 100644 --- a/libclamav/uniq.c +++ b/libclamav/uniq.c @@ -39,7 +39,7 @@ struct uniq *uniq_init(uint32_t count) struct uniq *U; if (!count) return NULL; - U = cli_calloc(1, sizeof(*U)); + U = calloc(1, sizeof(*U)); if (!U) return NULL; U->md5s = cli_malloc(count * sizeof(*U->md5s)); diff --git a/libclamav/unzip.c b/libclamav/unzip.c index 96fabfa754..2c3b6ecc24 100644 --- a/libclamav/unzip.c +++ b/libclamav/unzip.c @@ -998,7 +998,7 @@ cl_error_t index_the_central_directory( *catalogue = NULL; *num_records = 0; - zip_catalogue = (struct zip_record *)cli_malloc(sizeof(struct zip_record) * ZIP_RECORDS_CHECK_BLOCKSIZE); + zip_catalogue = (struct zip_record *)malloc(sizeof(struct zip_record) * ZIP_RECORDS_CHECK_BLOCKSIZE); if (NULL == zip_catalogue) { status = CL_EMEM; goto done; diff --git a/libclamav/vba_extract.c b/libclamav/vba_extract.c index d96e5945a6..8c83054c79 100644 --- a/libclamav/vba_extract.c +++ b/libclamav/vba_extract.c @@ -2425,7 +2425,7 @@ create_vba_project(int record_count, const char *dir, struct uniq *U) { vba_project_t *ret; - ret = (vba_project_t *)cli_calloc(1, sizeof(struct vba_project_tag)); + ret = (vba_project_t *)calloc(1, sizeof(struct vba_project_tag)); if (ret == NULL) { cli_errmsg("create_vba_project: Unable to allocate memory for vba project structure\n"); diff --git a/libclamav/yara_parser.c b/libclamav/yara_parser.c index 964ee2f2e6..a579cff390 100644 --- a/libclamav/yara_parser.c +++ b/libclamav/yara_parser.c @@ -874,7 +874,7 @@ YR_STRING* yr_parser_reduce_string_declaration( return meta; #if 0 // meta w.i.p. - meta = cli_calloc(1, sizeof(YR_META)); + meta = calloc(1, sizeof(YR_META)); if (meta == NULL) { cli_errmsg("yara_parser: no mem for YR_META.\n"); compiler->last_result = CL_EMEM; diff --git a/libfreshclam/libfreshclam_internal.c b/libfreshclam/libfreshclam_internal.c index 77625b1c82..fe39222173 100644 --- a/libfreshclam/libfreshclam_internal.c +++ b/libfreshclam/libfreshclam_internal.c @@ -969,8 +969,8 @@ static fc_error_t remote_cvdhead( logg(LOGG_ERROR, "remote_cvdhead: Failed to set CURLOPT_RANGE CVD_HEADER_SIZE for curl session.\n"); } - receivedData.buffer = cli_malloc(1); /* will be grown as needed by the realloc above */ - receivedData.size = 0; /* no data at this point */ + receivedData.buffer = malloc(1); /* will be grown as needed by the realloc above */ + receivedData.size = 0; /* no data at this point */ /* Send all data to this function */ if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)) { diff --git a/unit_tests/check_clamav.c b/unit_tests/check_clamav.c index 692c092de4..a62d3a83b6 100644 --- a/unit_tests/check_clamav.c +++ b/unit_tests/check_clamav.c @@ -79,7 +79,7 @@ START_TEST(test_cl_build) // ck_assert_msg(engine, "cl_build calloc"); // ck_assert_msg(CL_ENULLARG == cl_build(engine), "cl_build(engine) with null ->root"); - // engine->root = cli_calloc(CL_TARGET_TABLE_SIZE, sizeof(struct cli_matcher *)); + // engine->root = calloc(CL_TARGET_TABLE_SIZE, sizeof(struct cli_matcher *)); } END_TEST diff --git a/unit_tests/check_regex.c b/unit_tests/check_regex.c index c12126000f..650ffa5384 100644 --- a/unit_tests/check_regex.c +++ b/unit_tests/check_regex.c @@ -397,13 +397,13 @@ static void do_phishing_test(const struct rtest *rtest) ck_assert_msg(!!realurl, "cli_strdup"); hrefs.count = 1; - hrefs.value = cli_malloc(sizeof(*hrefs.value)); - ck_assert_msg(!!hrefs.value, "cli_malloc"); + hrefs.value = malloc(sizeof(*hrefs.value)); + ck_assert_msg(!!hrefs.value, "malloc"); hrefs.value[0] = (unsigned char *)realurl; - hrefs.contents = cli_malloc(sizeof(*hrefs.contents)); - ck_assert_msg(!!hrefs.contents, "cli_malloc"); - hrefs.tag = cli_malloc(sizeof(*hrefs.tag)); - ck_assert_msg(!!hrefs.tag, "cli_malloc"); + hrefs.contents = malloc(sizeof(*hrefs.contents)); + ck_assert_msg(!!hrefs.contents, "malloc"); + hrefs.tag = malloc(sizeof(*hrefs.tag)); + ck_assert_msg(!!hrefs.tag, "malloc"); hrefs.tag[0] = (unsigned char *)cli_strdup("href"); hrefs.contents[0] = (unsigned char *)cli_strdup(rtest->displayurl); @@ -484,13 +484,13 @@ static void do_phishing_test_allscan(const struct rtest *rtest) ck_assert_msg(!!realurl, "cli_strdup"); hrefs.count = 1; - hrefs.value = cli_malloc(sizeof(*hrefs.value)); - ck_assert_msg(!!hrefs.value, "cli_malloc"); + hrefs.value = malloc(sizeof(*hrefs.value)); + ck_assert_msg(!!hrefs.value, "malloc"); hrefs.value[0] = (unsigned char *)realurl; - hrefs.contents = cli_malloc(sizeof(*hrefs.contents)); - ck_assert_msg(!!hrefs.contents, "cli_malloc"); - hrefs.tag = cli_malloc(sizeof(*hrefs.tag)); - ck_assert_msg(!!hrefs.tag, "cli_malloc"); + hrefs.contents = malloc(sizeof(*hrefs.contents)); + ck_assert_msg(!!hrefs.contents, "malloc"); + hrefs.tag = malloc(sizeof(*hrefs.tag)); + ck_assert_msg(!!hrefs.tag, "malloc"); hrefs.tag[0] = (unsigned char *)cli_strdup("href"); hrefs.contents[0] = (unsigned char *)cli_strdup(rtest->displayurl); From 65862b4f163c25089daee8ec868cf4f88b109a8f Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 9 May 2022 14:28:34 -0700 Subject: [PATCH 02/12] Rename clamav memory allocation functions We have some special functions to wrap malloc, calloc, and realloc to make sure we don't allocate more than some limit, similar to the max-filesize and max-scansize limits. Our wrappers are really only needed when allocating memory for scans based on untrusted user input, where a scan file could have bytes that claim you need to allocate some ridiculous amount of memory. Right now they're named: - cli_malloc - cli_calloc - cli_realloc - cli_realloc2 ... and these names do not convey their purpose This commit renames them to: - cli_max_malloc - cli_max_calloc - cli_max_realloc - cli_max_realloc2 The realloc ones also have an additional feature in that they will not free your pointer if you try to realloc to 0 bytes. Freeing the memory is undefined by the C spec, and only done with some realloc implementations, so this stabilizes on the behavior of not doing that, which should prevent accidental double-free's. So for the case where you may want to realloc and do not need to have a maximum, this commit adds the following functions: - cli_safer_realloc - cli_safer_realloc2 These are used for the MPOOL_REALLOC and MPOOL_REALLOC2 macros when MPOOL is disabled (e.g. because mmap-support is not found), so as to match the behavior in the mpool_realloc/2 functions that do not make use of the allocation-limit. --- clambc/bcrun.c | 2 +- clamonacc/inotif/hash.c | 4 +- clamonacc/inotif/inotif.c | 10 +-- clamonacc/misc/utils.c | 2 +- common/scanmem.c | 2 +- freshclam/freshclam.c | 6 +- libclamav/7z_iface.c | 2 +- libclamav/aspack.c | 4 +- libclamav/autoit.c | 26 +++---- libclamav/blob.c | 14 ++-- libclamav/bytecode.c | 72 ++++++++------------ libclamav/bytecode_api.c | 32 ++++----- libclamav/bytecode_vm.c | 4 +- libclamav/cvd.c | 4 +- libclamav/dmg.c | 4 +- libclamav/dsig.c | 2 +- libclamav/egg.c | 110 +++++++++++++++--------------- libclamav/elf.c | 12 ++-- libclamav/entconv.c | 22 +++--- libclamav/events.c | 8 +-- libclamav/fmap.c | 4 +- libclamav/hashtab.c | 18 ++--- libclamav/hfsplus.c | 6 +- libclamav/htmlnorm.c | 18 ++--- libclamav/hwp.c | 8 +-- libclamav/inflate64.c | 2 +- libclamav/ishield.c | 2 +- libclamav/json_api.c | 2 +- libclamav/jsparse/js-norm.c | 8 +-- libclamav/jsparse/textbuf.h | 2 +- libclamav/libclamav.map | 7 +- libclamav/line.c | 2 +- libclamav/lzma_iface.c | 2 +- libclamav/lzw/lzwdec.c | 4 +- libclamav/macho.c | 2 +- libclamav/matcher-ac.c | 38 +++++------ libclamav/matcher-bm.c | 4 +- libclamav/matcher-byte-comp.c | 6 +- libclamav/matcher-pcre.c | 4 +- libclamav/mbox.c | 18 ++--- libclamav/message.c | 14 ++-- libclamav/mew.c | 2 +- libclamav/mpool.h | 4 +- libclamav/msdoc.c | 12 ++-- libclamav/nsis/bzlib.c | 2 +- libclamav/ole2_extract.c | 20 +++--- libclamav/others.c | 12 ++-- libclamav/others.h | 123 +++++++++++++++++++++++++++------- libclamav/others_common.c | 110 ++++++++++++++++++++++-------- libclamav/pdf.c | 32 ++++----- libclamav/pdfdecode.c | 20 +++--- libclamav/pdfng.c | 29 ++++---- libclamav/pe.c | 48 ++++++------- libclamav/pe_icons.c | 8 +-- libclamav/petite.c | 2 +- libclamav/phishcheck.c | 6 +- libclamav/readdb.c | 48 ++++++------- libclamav/rebuildpe.c | 2 +- libclamav/regex/engine.c | 6 +- libclamav/regex/regcomp.c | 14 ++-- libclamav/regex/regexec.c | 2 +- libclamav/regex_list.c | 12 ++-- libclamav/regex_pcre.c | 6 +- libclamav/regex_suffix.c | 2 +- libclamav/rtf.c | 6 +- libclamav/scanners.c | 14 ++-- libclamav/sis.c | 12 ++-- libclamav/spin.c | 12 ++-- libclamav/str.c | 16 ++--- libclamav/tnef.c | 4 +- libclamav/udf.c | 12 ++-- libclamav/unarj.c | 12 ++-- libclamav/uniq.c | 2 +- libclamav/unsp.c | 2 +- libclamav/unzip.c | 2 +- libclamav/upx.c | 4 +- libclamav/vba_extract.c | 24 +++---- libclamav/wwunpack.c | 2 +- libclamav/www.c | 4 +- libclamav/xar.c | 4 +- libclamav/xlm_extract.c | 4 +- libclamav/xz_iface.c | 2 +- libclamav/yara_clam.h | 4 +- libfreshclam/libfreshclam.c | 2 +- sigtool/sigtool.c | 18 ++--- unit_tests/check_bytecode.c | 8 +-- unit_tests/check_clamav.c | 12 ++-- unit_tests/check_matchers.c | 8 +-- 88 files changed, 667 insertions(+), 558 deletions(-) diff --git a/clambc/bcrun.c b/clambc/bcrun.c index b0acafbc58..43edc8adf3 100644 --- a/clambc/bcrun.c +++ b/clambc/bcrun.c @@ -399,7 +399,7 @@ int main(int argc, char *argv[]) cctx.evidence = evidence_new(); cctx.recursion_stack_size = cctx.engine->max_recursion_level; - cctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); + cctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); if (!cctx.recursion_stack) { fprintf(stderr, "Out of memory\n"); exit(3); diff --git a/clamonacc/inotif/hash.c b/clamonacc/inotif/hash.c index e57b513bd2..d1a32b79a2 100644 --- a/clamonacc/inotif/hash.c +++ b/clamonacc/inotif/hash.c @@ -145,7 +145,7 @@ int onas_ht_init(struct onas_ht **ht, uint32_t size) .nbckts = 0, }; - if (!((*ht)->htable = (struct onas_bucket **)cli_calloc(size, sizeof(struct onas_bucket *)))) { + if (!((*ht)->htable = (struct onas_bucket **)cli_max_calloc(size, sizeof(struct onas_bucket *)))) { onas_free_ht(*ht); return CL_EMEM; } @@ -794,7 +794,7 @@ int onas_ht_rm_hierarchy(struct onas_ht *ht, const char *pathname, size_t len, i curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_malloc(size); + char *child_path = (char *)cli_max_malloc(size); if (child_path == NULL) return CL_EMEM; if (hnode->pathname[len - 1] == '/') diff --git a/clamonacc/inotif/inotif.c b/clamonacc/inotif/inotif.c index c2d3a1b0af..904fc241f2 100644 --- a/clamonacc/inotif/inotif.c +++ b/clamonacc/inotif/inotif.c @@ -105,7 +105,7 @@ static int onas_ddd_init_wdlt(uint64_t nwatches) if (nwatches <= 0) return CL_EARG; - wdlt = (char **)cli_calloc(nwatches << 1, sizeof(char *)); + wdlt = (char **)cli_max_calloc(nwatches << 1, sizeof(char *)); if (!wdlt) return CL_EMEM; wdlt_len = nwatches << 1; @@ -121,7 +121,7 @@ static int onas_ddd_grow_wdlt(void) char **ptr = NULL; - ptr = (char **)cli_realloc(wdlt, wdlt_len << 1); + ptr = (char **)cli_max_realloc(wdlt, wdlt_len << 1); if (ptr) { wdlt = ptr; memset(&ptr[wdlt_len], 0, sizeof(char *) * (wdlt_len - 1)); @@ -243,7 +243,7 @@ static int onas_ddd_watch_hierarchy(const char *pathname, size_t len, int fd, ui curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_malloc(size); + char *child_path = (char *)cli_max_malloc(size); if (child_path == NULL) { logg(LOGG_ERROR, "ClamInotif: out of memory when adding child for %s\n", hnode->pathname); return CL_EMEM; @@ -330,7 +330,7 @@ static int onas_ddd_unwatch_hierarchy(const char *pathname, size_t len, int fd, curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_malloc(size); + char *child_path = (char *)cli_max_malloc(size); if (child_path == NULL) return CL_EMEM; if (hnode->pathname[len - 1] == '/') @@ -679,7 +679,7 @@ void *onas_ddd_th(void *arg) } else { len = strlen(path); size_t size = strlen(child) + len + 2; - char *child_path = (char *)cli_malloc(size); + char *child_path = (char *)cli_max_malloc(size); if (child_path == NULL) { logg(LOGG_DEBUG, "ClamInotif: could not allocate space for child path ... aborting\n"); return NULL; diff --git a/clamonacc/misc/utils.c b/clamonacc/misc/utils.c index f231a957e3..d219250b7f 100644 --- a/clamonacc/misc/utils.c +++ b/clamonacc/misc/utils.c @@ -206,7 +206,7 @@ char **onas_get_opt_list(const char *fname, int *num_entries, cl_error_t *err) } (*num_entries)++; - rlc_ptr = cli_realloc(opt_list, sizeof(char *) * (*num_entries + 1)); + rlc_ptr = cli_max_realloc(opt_list, sizeof(char *) * (*num_entries + 1)); if (rlc_ptr) { opt_list = rlc_ptr; opt_list[*num_entries] = NULL; diff --git a/common/scanmem.c b/common/scanmem.c index 593e189acb..3797f32d4e 100644 --- a/common/scanmem.c +++ b/common/scanmem.c @@ -101,7 +101,7 @@ static inline char *wc2mb(const wchar_t *wc, DWORD flags) return NULL; } - mb = cli_malloc(len + 1); + mb = cli_max_malloc(len + 1); if (!mb) return NULL; res = WideCharToMultiByte(CP_ACP, flags, wc, -1, mb, len, NULL, &invalid); diff --git a/freshclam/freshclam.c b/freshclam/freshclam.c index c20218b1a1..69a0bda0d2 100644 --- a/freshclam/freshclam.c +++ b/freshclam/freshclam.c @@ -535,7 +535,7 @@ static fc_error_t string_list_add(const char *item, char ***stringList, uint32_t } nItems = *nListItems + 1; - newList = (char **)cli_realloc(*stringList, nItems * sizeof(char *)); + newList = (char **)cli_max_realloc(*stringList, nItems * sizeof(char *)); if (newList == NULL) { mprintf(LOGG_ERROR, "string_list_add: Failed to allocate memory for optional database list entry.\n"); status = FC_EMEM; @@ -1142,7 +1142,7 @@ fc_error_t select_from_official_databases( goto done; } - selectedDatabases = cli_calloc(nStandardDatabases + nOptionalDatabases, sizeof(char *)); + selectedDatabases = cli_max_calloc(nStandardDatabases + nOptionalDatabases, sizeof(char *)); /* * Select desired standard databases. @@ -1261,7 +1261,7 @@ fc_error_t select_specific_databases( *databaseList = NULL; *nDatabases = 0; - selectedDatabases = cli_calloc(nSpecificDatabases, sizeof(char *)); + selectedDatabases = cli_max_calloc(nSpecificDatabases, sizeof(char *)); /* * Get lists of available databases. diff --git a/libclamav/7z_iface.c b/libclamav/7z_iface.c index da14e52137..f3dbb1627a 100644 --- a/libclamav/7z_iface.c +++ b/libclamav/7z_iface.c @@ -144,7 +144,7 @@ int cli_7unz(cli_ctx *ctx, size_t offset) if (newnamelen > namelen) { if (namelen > UTFBUFSZ) free(utf16name); - utf16name = cli_malloc(newnamelen * 2); + utf16name = cli_max_malloc(newnamelen * 2); if (!utf16name) { found = CL_EMEM; break; diff --git a/libclamav/aspack.c b/libclamav/aspack.c index 662b8973fe..2f27c0f3f0 100644 --- a/libclamav/aspack.c +++ b/libclamav/aspack.c @@ -426,7 +426,7 @@ int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections while (CLI_ISCONTAINED(image, size, blocks, 8) && (block_rva = cli_readint32(blocks)) && (block_size = cli_readint32(blocks + 4)) && CLI_ISCONTAINED(image, size, image + block_rva, block_size)) { cli_dbgmsg("Aspack: unpacking block rva:%x - sz:%x\n", block_rva, block_size); - wrkbuf = (uint8_t *)cli_calloc(block_size + 0x10e, sizeof(uint8_t)); + wrkbuf = (uint8_t *)cli_max_calloc(block_size + 0x10e, sizeof(uint8_t)); if (!wrkbuf) { cli_dbgmsg("Aspack: Null work buff\n"); @@ -484,7 +484,7 @@ int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections if (sectcount > 2 && ep == sections[sectcount - 2].rva && !sections[sectcount - 1].rsz) { sectcount -= 2; } - if (!(outsects = cli_malloc(sizeof(struct cli_exe_section) * sectcount))) { + if (!(outsects = cli_max_malloc(sizeof(struct cli_exe_section) * sectcount))) { cli_dbgmsg("Aspack: OOM - rebuild failed\n"); cli_writen(f, image, size); return 1; /* No whatsoheader - won't infloop in pe.c */ diff --git a/libclamav/autoit.c b/libclamav/autoit.c index eeec5d3ac1..e95f20d25f 100644 --- a/libclamav/autoit.c +++ b/libclamav/autoit.c @@ -741,7 +741,7 @@ static cl_error_t ea05(cli_ctx *ctx, const uint8_t *base, char *tmpd) continue; } - if (!(UNP.inputbuf = cli_malloc(UNP.csize))) { + if (!(UNP.inputbuf = cli_max_malloc(UNP.csize))) { status = CL_EMEM; goto done; } @@ -780,7 +780,7 @@ static cl_error_t ea05(cli_ctx *ctx, const uint8_t *base, char *tmpd) continue; } - if (!(UNP.outputbuf = cli_malloc(UNP.usize))) { + if (!(UNP.outputbuf = cli_max_malloc(UNP.usize))) { status = CL_EMEM; goto done; } @@ -1144,7 +1144,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) files++; - if (!(UNP.inputbuf = cli_malloc(UNP.csize))) { + if (!(UNP.inputbuf = cli_max_malloc(UNP.csize))) { return CL_EMEM; } @@ -1177,7 +1177,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) continue; } - if (!(UNP.outputbuf = cli_malloc(UNP.usize))) { + if (!(UNP.outputbuf = cli_max_malloc(UNP.usize))) { free(UNP.inputbuf); return CL_EMEM; } @@ -1256,7 +1256,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) /* From here on, we'll reuse csize to be the size of the * output buffer */ UNP.csize = UNP.usize; - if (!(buf = cli_malloc(UNP.csize))) { + if (!(buf = cli_max_malloc(UNP.csize))) { free(UNP.outputbuf); return CL_EMEM; } @@ -1294,7 +1294,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + keyword_len + 2 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1333,7 +1333,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + function_len + 2 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1360,7 +1360,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + 12 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1384,7 +1384,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + 20 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1410,7 +1410,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + 40 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1467,7 +1467,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + chars + 3 >= UNP.csize) { uint8_t *newout; UNP.csize += chars + 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1526,7 +1526,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + 4 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } @@ -1547,7 +1547,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (UNP.cur_output + 1 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; - if (!(newout = cli_realloc(buf, UNP.csize))) { + if (!(newout = cli_max_realloc(buf, UNP.csize))) { UNP.error = 1; break; } diff --git a/libclamav/blob.c b/libclamav/blob.c index 6fc3fc5f39..a75ff43f64 100644 --- a/libclamav/blob.c +++ b/libclamav/blob.c @@ -225,13 +225,13 @@ int blobAddData(blob *b, const unsigned char *data, size_t len) assert(b->size == 0); b->size = growth; - b->data = cli_malloc(growth); + b->data = cli_max_malloc(growth); if (NULL == b->data) { b->size = 0; return -1; } } else if (b->size < b->len + (off_t)len) { - unsigned char *p = cli_realloc(b->data, b->size + growth); + unsigned char *p = cli_max_realloc(b->data, b->size + growth); if (p == NULL) return -1; @@ -245,13 +245,13 @@ int blobAddData(blob *b, const unsigned char *data, size_t len) assert(b->size == 0); b->size = (off_t)len * 4; - b->data = cli_malloc(b->size); + b->data = cli_max_malloc(b->size); if (NULL == b->data) { b->size = 0; return -1; } } else if (b->size < b->len + (off_t)len) { - unsigned char *p = cli_realloc(b->data, b->size + (len * 4)); + unsigned char *p = cli_max_realloc(b->data, b->size + (len * 4)); if (p == NULL) return -1; @@ -319,7 +319,7 @@ void blobClose(blob *b) (unsigned long)b->size); b->size = 0; } else { - unsigned char *ptr = cli_realloc(b->data, b->len); + unsigned char *ptr = cli_max_realloc(b->data, b->len); if (ptr == NULL) { return; @@ -385,11 +385,11 @@ int blobGrow(blob *b, size_t len) assert(b->len == 0); assert(b->size == 0); - b->data = cli_malloc(len); + b->data = cli_max_malloc(len); if (b->data) b->size = (off_t)len; } else { - unsigned char *ptr = cli_realloc(b->data, b->size + len); + unsigned char *ptr = cli_max_realloc(b->data, b->size + len); if (ptr) { b->size += (off_t)len; diff --git a/libclamav/bytecode.c b/libclamav/bytecode.c index 528c967530..e449eb5572 100644 --- a/libclamav/bytecode.c +++ b/libclamav/bytecode.c @@ -102,22 +102,6 @@ static void context_safe(struct cli_bc_ctx *ctx) ctx->hooks.pedata = &nopedata; } -void cli_bytecode_context_destroy(struct cli_bc_ctx *ctx) -{ - cli_bytecode_context_clear(ctx); - free(ctx); -} - -int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilename) -{ - int fd; - *tempfilename = ctx->tempfile; - fd = ctx->outfd; - ctx->tempfile = NULL; - ctx->outfd = 0; - return fd; -} - /** * @brief Reset bytecode state, so you can run another bytecode with same ctx. * @@ -125,7 +109,7 @@ int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilen * * @param ctx */ -static int bytecode_context_reset(struct cli_bc_ctx *ctx) +static void bytecode_context_reset(struct cli_bc_ctx *ctx) { unsigned i; @@ -356,12 +340,12 @@ cl_error_t cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct c ctx->numParams = func->numArgs; ctx->funcid = funcid; if (func->numArgs) { - ctx->operands = cli_malloc(sizeof(*ctx->operands) * func->numArgs); + ctx->operands = cli_max_malloc(sizeof(*ctx->operands) * func->numArgs); if (!ctx->operands) { cli_errmsg("bytecode: error allocating memory for parameters\n"); return CL_EMEM; } - ctx->opsizes = cli_malloc(sizeof(*ctx->opsizes) * func->numArgs); + ctx->opsizes = cli_max_malloc(sizeof(*ctx->opsizes) * func->numArgs); if (!ctx->opsizes) { cli_errmsg("bytecode: error allocating memory for opsizes\n"); return CL_EMEM; @@ -375,7 +359,7 @@ cl_error_t cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct c } s += 8; /* return value */ ctx->bytes = s; - ctx->values = cli_malloc(s); + ctx->values = cli_max_malloc(s); if (!ctx->values) { cli_errmsg("bytecode: error allocating memory for parameters\n"); return CL_EMEM; @@ -523,7 +507,7 @@ static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p, uint16_t ty; p[*off] |= 0x20; /* TODO: unique constants */ - func->constants = cli_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); + func->constants = cli_max_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); if (!func->constants) { *ok = false; return MAX_OP; @@ -581,7 +565,7 @@ static inline char *readData(const unsigned char *p, unsigned *off, unsigned len *ok = false; return 0; } - dat = cli_malloc(l); + dat = cli_max_malloc(l); if (!dat) { cli_errmsg("Cannot allocate memory for data\n"); *ok = false; @@ -695,12 +679,12 @@ static cl_error_t parseHeader(struct cli_bc *bc, unsigned char *buffer, unsigned return CL_EMALFDB; } - bc->funcs = cli_calloc(bc->num_func, sizeof(*bc->funcs)); + bc->funcs = cli_max_calloc(bc->num_func, sizeof(*bc->funcs)); if (!bc->funcs) { cli_errmsg("Out of memory allocating %u functions\n", bc->num_func); return CL_EMEM; } - bc->types = cli_calloc(bc->num_types, sizeof(*bc->types)); + bc->types = cli_max_calloc(bc->num_types, sizeof(*bc->types)); if (!bc->types) { cli_errmsg("Out of memory allocating %u types\n", bc->num_types); return CL_EMEM; @@ -753,7 +737,7 @@ static void parseType(struct cli_bc *bc, struct cli_bc_type *ty, *ok = false; return; } - ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes) * ty->numElements); + ty->containedTypes = cli_max_malloc(sizeof(*ty->containedTypes) * ty->numElements); if (!ty->containedTypes) { cli_errmsg("Out of memory allocating %u types\n", ty->numElements); *ok = false; @@ -942,7 +926,7 @@ static cl_error_t parseApis(struct cli_bc *bc, unsigned char *buffer) cli_errmsg("Out of memory allocating apis bitset\n"); return CL_EMEM; } - apity2ty = cli_calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types)); + apity2ty = cli_max_calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types)); if (!apity2ty) { cli_errmsg("Out of memory allocating apity2ty\n"); return CL_EMEM; @@ -1057,12 +1041,12 @@ static cl_error_t parseGlobals(struct cli_bc *bc, unsigned char *buffer) return CL_BREAK; } numglobals = readNumber(buffer, &offset, len, &ok); - bc->globals = cli_calloc(numglobals, sizeof(*bc->globals)); + bc->globals = cli_max_calloc(numglobals, sizeof(*bc->globals)); if (!bc->globals) { cli_errmsg("bytecode: OOM allocating memory for %u globals\n", numglobals); return CL_EMEM; } - bc->globaltys = cli_calloc(numglobals, sizeof(*bc->globaltys)); + bc->globaltys = cli_max_calloc(numglobals, sizeof(*bc->globaltys)); if (!bc->globaltys) { cli_errmsg("bytecode: OOM allocating memory for %u global types\n", numglobals); return CL_EMEM; @@ -1076,7 +1060,7 @@ static cl_error_t parseGlobals(struct cli_bc *bc, unsigned char *buffer) comp = type_components(bc, bc->globaltys[i], &ok); if (!ok) return CL_EMALFDB; - bc->globals[i] = cli_malloc(sizeof(*bc->globals[0]) * comp); + bc->globals[i] = cli_max_malloc(sizeof(*bc->globals[0]) * comp); if (!bc->globals[i]) return CL_EMEM; readConstant(bc, i, comp, buffer, &offset, len, &ok); @@ -1105,7 +1089,7 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) } b = bc->dbgnode_cnt; bc->dbgnode_cnt += numMD; - bc->dbgnodes = cli_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes)); + bc->dbgnodes = cli_max_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes)); if (!bc->dbgnodes) return CL_EMEM; for (i = 0; i < numMD; i++) { @@ -1117,7 +1101,7 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) return CL_EMALFDB; } bc->dbgnodes[b + i].numelements = el; - bc->dbgnodes[b + i].elements = elts = cli_calloc(el, sizeof(*elts)); + bc->dbgnodes[b + i].elements = elts = cli_max_calloc(el, sizeof(*elts)); if (!elts) return CL_EMEM; for (j = 0; j < el; j++) { @@ -1177,7 +1161,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c if (!all_locals) { func->types = NULL; } else { - func->types = cli_calloc(all_locals, sizeof(*func->types)); + func->types = cli_max_calloc(all_locals, sizeof(*func->types)); if (!func->types) { cli_errmsg("Out of memory allocating function arguments\n"); return CL_EMEM; @@ -1205,7 +1189,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c func->numValues = func->numArgs + func->numLocals; func->insn_idx = 0; func->numConstants = 0; - func->allinsts = cli_calloc(func->numInsts, sizeof(*func->allinsts)); + func->allinsts = cli_max_calloc(func->numInsts, sizeof(*func->allinsts)); if (!func->allinsts) { cli_errmsg("Out of memory allocating instructions\n"); return CL_EMEM; @@ -1215,7 +1199,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c cli_errmsg("Invalid basic block count\n"); return CL_EMALFDB; } - func->BB = cli_calloc(func->numBB, sizeof(*func->BB)); + func->BB = cli_max_calloc(func->numBB, sizeof(*func->BB)); if (!func->BB) { cli_errmsg("Out of memory allocating basic blocks\n"); return CL_EMEM; @@ -1319,7 +1303,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne if (!numOp) { inst.u.ops.ops = NULL; } else { - inst.u.ops.ops = cli_calloc(numOp, sizeof(*inst.u.ops.ops)); + inst.u.ops.ops = cli_max_calloc(numOp, sizeof(*inst.u.ops.ops)); if (!inst.u.ops.ops) { cli_errmsg("Out of memory allocating operands\n"); return CL_EMEM; @@ -1364,7 +1348,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne if (ok) { inst.u.ops.numOps = numOp + 2; inst.u.ops.opsizes = NULL; - inst.u.ops.ops = cli_calloc(numOp + 2, sizeof(*inst.u.ops.ops)); + inst.u.ops.ops = cli_max_calloc(numOp + 2, sizeof(*inst.u.ops.ops)); if (!inst.u.ops.ops) { cli_errmsg("Out of memory allocating operands\n"); return CL_EMEM; @@ -1484,7 +1468,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne cli_errmsg("invalid number of dbg nodes, expected: %u, got: %u\n", bcfunc->numInsts, num); return CL_EMALFDB; } - bcfunc->dbgnodes = cli_malloc(num * sizeof(*bcfunc->dbgnodes)); + bcfunc->dbgnodes = cli_max_malloc(num * sizeof(*bcfunc->dbgnodes)); if (!bcfunc->dbgnodes) { cli_errmsg("Unable to allocate memory for dbg nodes: %u\n", num * (uint32_t)sizeof(*bcfunc->dbgnodes)); return CL_EMEM; @@ -1675,7 +1659,7 @@ cl_error_t cli_bytecode_load(struct cli_bc *bc, FILE *f, struct cli_dbio *dbio, cli_errmsg("Error at bytecode line %u\n", row); return rc; } - buffer = cli_malloc(linelength); + buffer = cli_max_malloc(linelength); if (!buffer) { cli_errmsg("Out of memory allocating line of length %u\n", linelength); return CL_EMEM; @@ -2151,7 +2135,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) unsigned bcglobalid = cli_apicall_maxglobal - _FIRST_GLOBAL + 2; cl_error_t ret = CL_SUCCESS; bc->numGlobalBytes = 0; - gmap = cli_malloc(bc->num_globals * sizeof(*gmap)); + gmap = cli_max_malloc(bc->num_globals * sizeof(*gmap)); if (!gmap) { cli_errmsg("interpreter: Unable to allocate memory for global map: %zu\n", bc->num_globals * sizeof(*gmap)); return CL_EMEM; @@ -2165,7 +2149,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) bc->numGlobalBytes += typesize(bc, ty); } if (bc->numGlobalBytes) { - bc->globalBytes = cli_calloc(1, bc->numGlobalBytes); + bc->globalBytes = cli_max_calloc(1, bc->numGlobalBytes); if (!bc->globalBytes) { cli_errmsg("interpreter: Unable to allocate memory for globalBytes: %u\n", bc->numGlobalBytes); free(gmap); @@ -2231,7 +2215,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) for (i = 0; i < bc->num_func && ret == CL_SUCCESS; i++) { struct cli_bc_func *bcfunc = &bc->funcs[i]; unsigned totValues = bcfunc->numValues + bcfunc->numConstants + bc->num_globals; - unsigned *map = cli_malloc(sizeof(*map) * (size_t)totValues); + unsigned *map = cli_max_malloc(sizeof(*map) * (size_t)totValues); if (!map) { cli_errmsg("interpreter: Unable to allocate memory for map: %zu\n", sizeof(*map) * (size_t)totValues); free(gmap); @@ -2327,7 +2311,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) if (ret != CL_SUCCESS) break; if (inst->u.ops.numOps > 0) { - inst->u.ops.opsizes = cli_malloc(sizeof(*inst->u.ops.opsizes) * inst->u.ops.numOps); + inst->u.ops.opsizes = cli_max_malloc(sizeof(*inst->u.ops.opsizes) * inst->u.ops.numOps); if (!inst->u.ops.opsizes) { cli_errmsg("Out of memory when allocating operand sizes\n"); ret = CL_EMEM; @@ -2423,7 +2407,7 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) struct cli_bc_inst *inst; struct cli_bc *bc; - bcs->all_bcs = cli_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_max_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; @@ -2624,7 +2608,7 @@ static cl_error_t run_builtin_or_loaded(struct cli_all_bc *bcs, uint8_t kind, co if (!bc) { /* no loaded bytecode found, load the builtin one! */ struct cli_dbio dbio; - bc = cli_calloc(1, sizeof(*bc)); + bc = cli_max_calloc(1, sizeof(*bc)); if (!bc) { cli_errmsg("Out of memory allocating bytecode\n"); return CL_EMEM; diff --git a/libclamav/bytecode_api.c b/libclamav/bytecode_api.c index 7a44f7080c..33a1be49be 100644 --- a/libclamav/bytecode_api.c +++ b/libclamav/bytecode_api.c @@ -474,7 +474,7 @@ uint8_t *cli_bcapi_malloc(struct cli_bc_ctx *ctx, uint32_t size) #else /* TODO: implement using a list of pointers we allocated! */ cli_errmsg("cli_bcapi_malloc not implemented for systems without mmap yet!\n"); - v = cli_malloc(size); + v = cli_max_malloc(size); #endif if (!v) cli_event_error_oom(EV, size); @@ -600,7 +600,7 @@ int32_t cli_bcapi_read_number(struct cli_bc_ctx *ctx, uint32_t radix) int32_t cli_bcapi_hashset_new(struct cli_bc_ctx *ctx) { unsigned n = ctx->nhashsets + 1; - struct cli_hashset *s = cli_realloc(ctx->hashsets, sizeof(*ctx->hashsets) * n); + struct cli_hashset *s = cli_max_realloc(ctx->hashsets, sizeof(*ctx->hashsets) * n); if (!s) { cli_event_error_oom(EV, 0); return -1; @@ -663,7 +663,7 @@ int32_t cli_bcapi_hashset_done(struct cli_bc_ctx *ctx, int32_t id) free(ctx->hashsets); ctx->hashsets = NULL; } else { - s = cli_realloc(ctx->hashsets, ctx->nhashsets * sizeof(*s)); + s = cli_max_realloc(ctx->hashsets, ctx->nhashsets * sizeof(*s)); if (s) ctx->hashsets = s; } @@ -677,10 +677,10 @@ int32_t cli_bcapi_buffer_pipe_new(struct cli_bc_ctx *ctx, uint32_t size) struct bc_buffer *b; unsigned n = ctx->nbuffers + 1; - data = cli_calloc(1, size); + data = cli_max_calloc(1, size); if (!data) return -1; - b = cli_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); + b = cli_max_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); if (!b) { free(data); return -1; @@ -703,7 +703,7 @@ int32_t cli_bcapi_buffer_pipe_new_fromfile(struct cli_bc_ctx *ctx, uint32_t at) if (at >= ctx->file_size) return -1; - b = cli_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); + b = cli_max_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); if (!b) { return -1; } @@ -830,7 +830,7 @@ int32_t cli_bcapi_inflate_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to, cli_dbgmsg("bytecode api: inflate_init: invalid buffers!\n"); return -1; } - b = cli_realloc(ctx->inflates, sizeof(*ctx->inflates) * n); + b = cli_max_realloc(ctx->inflates, sizeof(*ctx->inflates) * n); if (!b) { return -1; } @@ -961,7 +961,7 @@ int32_t cli_bcapi_lzma_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to) return -1; } - b = cli_realloc(ctx->lzmas, sizeof(*ctx->lzmas) * n); + b = cli_max_realloc(ctx->lzmas, sizeof(*ctx->lzmas) * n); if (!b) { return -1; } @@ -1049,7 +1049,7 @@ int32_t cli_bcapi_bzip2_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to) cli_dbgmsg("bytecode api: bzip2_init: invalid buffers!\n"); return -1; } - b = cli_realloc(ctx->bzip2s, sizeof(*ctx->bzip2s) * n); + b = cli_max_realloc(ctx->bzip2s, sizeof(*ctx->bzip2s) * n); if (!b) { return -1; } @@ -1168,7 +1168,7 @@ int32_t cli_bcapi_jsnorm_init(struct cli_bc_ctx *ctx, int32_t from) state = cli_js_init(); if (!state) return -1; - b = cli_realloc(ctx->jsnorms, sizeof(*ctx->jsnorms) * n); + b = cli_max_realloc(ctx->jsnorms, sizeof(*ctx->jsnorms) * n); if (!b) { cli_js_destroy(state); return -1; @@ -1396,7 +1396,7 @@ int32_t cli_bcapi_map_new(struct cli_bc_ctx *ctx, int32_t keysize, int32_t value struct cli_map *s; if (!keysize) return -1; - s = cli_realloc(ctx->maps, sizeof(*ctx->maps) * n); + s = cli_max_realloc(ctx->maps, sizeof(*ctx->maps) * n); if (!s) return -1; ctx->maps = s; @@ -1523,7 +1523,7 @@ int32_t cli_bcapi_map_done(struct cli_bc_ctx *ctx, int32_t id) free(ctx->maps); ctx->maps = NULL; } else { - s = cli_realloc(ctx->maps, ctx->nmaps * (sizeof(*s))); + s = cli_max_realloc(ctx->maps, ctx->nmaps * (sizeof(*s))); if (s) ctx->maps = s; } @@ -2037,7 +2037,7 @@ static int32_t cli_bcapi_json_objs_init(struct cli_bc_ctx *ctx) json_object **j, **jobjs = (json_object **)(ctx->jsonobjs); cli_ctx *cctx = (cli_ctx *)ctx->ctx; - j = cli_realloc(jobjs, sizeof(json_object *) * n); + j = cli_max_realloc(jobjs, sizeof(json_object *) * n); if (!j) { /* memory allocation failure */ cli_event_error_oom(EV, 0); return -1; @@ -2085,7 +2085,7 @@ int32_t cli_bcapi_json_get_object(struct cli_bc_ctx *ctx, const int8_t *name, in jobj = jobjs[objid]; if (!jobj) /* shouldn't be possible */ return -1; - namep = (char *)cli_malloc(sizeof(char) * (name_len + 1)); + namep = (char *)cli_max_malloc(sizeof(char) * (name_len + 1)); if (!namep) return -1; strncpy(namep, (char *)name, name_len); @@ -2096,7 +2096,7 @@ int32_t cli_bcapi_json_get_object(struct cli_bc_ctx *ctx, const int8_t *name, in return 0; } - j = cli_realloc(jobjs, sizeof(json_object *) * n); + j = cli_max_realloc(jobjs, sizeof(json_object *) * n); if (!j) { /* memory allocation failure */ free(namep); cli_event_error_oom(EV, 0); @@ -2220,7 +2220,7 @@ int32_t cli_bcapi_json_get_array_idx(struct cli_bc_ctx *ctx, int32_t idx, int32_ return 0; } - j = cli_realloc(jobjs, sizeof(json_object *) * n); + j = cli_max_realloc(jobjs, sizeof(json_object *) * n); if (!j) { /* memory allocation failure */ cli_event_error_oom(EV, 0); return -1; diff --git a/libclamav/bytecode_vm.c b/libclamav/bytecode_vm.c index 45f11634a2..43997ec693 100644 --- a/libclamav/bytecode_vm.c +++ b/libclamav/bytecode_vm.c @@ -596,7 +596,7 @@ static inline int64_t ptr_register_stack(struct ptr_infos *infos, uint32_t off, uint32_t size) { unsigned n = infos->nstacks + 1; - struct ptr_info *sinfos = cli_realloc(infos->stack_infos, + struct ptr_info *sinfos = cli_max_realloc(infos->stack_infos, sizeof(*sinfos) * n); if (!sinfos) return 0; @@ -613,7 +613,7 @@ static inline int64_t ptr_register_glob_fixedid(struct ptr_infos *infos, { struct ptr_info *sinfos; if (n > infos->nglobs) { - sinfos = cli_realloc(infos->glob_infos, sizeof(*sinfos) * n); + sinfos = cli_max_realloc(infos->glob_infos, sizeof(*sinfos) * n); if (!sinfos) return 0; memset(sinfos + infos->nglobs, 0, (n - infos->nglobs) * sizeof(*sinfos)); diff --git a/libclamav/cvd.c b/libclamav/cvd.c index fabb568aee..70d8383568 100644 --- a/libclamav/cvd.c +++ b/libclamav/cvd.c @@ -88,7 +88,7 @@ static int cli_untgz(int fd, const char *destdir) return -1; } - path = (char *)cli_calloc(sizeof(char), pathlen); + path = (char *)cli_max_calloc(sizeof(char), pathlen); if (!path) { cli_errmsg("cli_untgz: Can't allocate memory for path\n"); cli_untgz_cleanup(NULL, infile, NULL, fdd); @@ -259,7 +259,7 @@ static int cli_tgzload(int fd, struct cl_engine *engine, unsigned int *signo, un } dbio->bufsize = CLI_DEFAULT_DBIO_BUFSIZE; - dbio->buf = cli_malloc(dbio->bufsize); + dbio->buf = cli_max_malloc(dbio->bufsize); if (!dbio->buf) { cli_errmsg("cli_tgzload: Can't allocate memory for dbio->buf\n"); cli_tgzload_cleanup(compr, dbio, fdd); diff --git a/libclamav/dmg.c b/libclamav/dmg.c index d9d1369a69..61696c2024 100644 --- a/libclamav/dmg.c +++ b/libclamav/dmg.c @@ -485,7 +485,7 @@ static int dmg_decode_mish(cli_ctx *ctx, unsigned int *mishblocknum, xmlChar *mi /* speed vs memory, could walk the encoded data and skip whitespace in calculation */ buff_size = 3 * base64_len / 4 + 4; dmg_parsemsg("dmg_decode_mish: buffer for mish block %u is %lu\n", *mishblocknum, (unsigned long)buff_size); - decoded = cli_malloc(buff_size); + decoded = cli_max_malloc(buff_size); if (!decoded) return CL_EMEM; @@ -1108,7 +1108,7 @@ static int dmg_extract_xml(cli_ctx *ctx, char *dir, struct dmg_koly_block *hdr) } namelen = strlen(dir) + 1 + 7 + 1; - if (!(xmlfile = cli_malloc(namelen))) { + if (!(xmlfile = cli_max_malloc(namelen))) { return CL_EMEM; } snprintf(xmlfile, namelen, "%s" PATHSEP "toc.xml", dir); diff --git a/libclamav/dsig.c b/libclamav/dsig.c index 8d5a25d32d..77dbc6d494 100644 --- a/libclamav/dsig.c +++ b/libclamav/dsig.c @@ -139,7 +139,7 @@ static unsigned char *cli_decodesig(const char *sig, unsigned int plen, BIGNUM * bn_bytes, plen); goto done; } - plain = cli_calloc(plen, sizeof(unsigned char)); + plain = cli_max_calloc(plen, sizeof(unsigned char)); if (!plain) { cli_errmsg("cli_decodesig: Can't allocate memory for 'plain'\n"); goto done; diff --git a/libclamav/egg.c b/libclamav/egg.c index 6738571e73..4ca8918971 100644 --- a/libclamav/egg.c +++ b/libclamav/egg.c @@ -1221,10 +1221,10 @@ static cl_error_t egg_parse_file_extra_field(egg_handle* handle, egg_file* eggFi /* * Comment found. Add comment to our list. */ - CLI_REALLOC(eggFile->comments, - sizeof(char*) * (eggFile->nComments + 1), - free(comment), - status = CL_EMEM); + CLI_SAFER_REALLOC(eggFile->comments, + sizeof(char*) * (eggFile->nComments + 1), + free(comment), + status = CL_EMEM); eggFile->comments[eggFile->nComments] = comment; eggFile->nComments++; } @@ -1667,10 +1667,10 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t goto done; } else { /* Add file to list. */ - CLI_REALLOC(handle->files, - sizeof(egg_file*) * (handle->nFiles + 1), - egg_free_egg_file(found_file), - status = CL_EMEM); + CLI_SAFER_REALLOC(handle->files, + sizeof(egg_file*) * (handle->nFiles + 1), + egg_free_egg_file(found_file), + status = CL_EMEM); handle->files[handle->nFiles] = found_file; handle->nFiles++; } @@ -1689,10 +1689,10 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t } else { /* Add block to list. */ if (handle->bSolid) { - CLI_REALLOC(handle->blocks, - sizeof(egg_block*) * (handle->nBlocks + 1), - egg_free_egg_block(found_block), - status = CL_EMEM); + CLI_SAFER_REALLOC(handle->blocks, + sizeof(egg_block*) * (handle->nBlocks + 1), + egg_free_egg_block(found_block), + status = CL_EMEM); handle->blocks[handle->nBlocks] = found_block; handle->nBlocks++; } else { @@ -1707,10 +1707,10 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t } else { eggFile = handle->files[handle->nFiles - 1]; - CLI_REALLOC(eggFile->blocks, - sizeof(egg_block*) * (eggFile->nBlocks + 1), - egg_free_egg_block(found_block), - status = CL_EMEM); + CLI_SAFER_REALLOC(eggFile->blocks, + sizeof(egg_block*) * (eggFile->nBlocks + 1), + egg_free_egg_block(found_block), + status = CL_EMEM); eggFile->blocks[eggFile->nBlocks] = found_block; eggFile->nBlocks++; } @@ -1785,10 +1785,10 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t /* * Comment found. Add comment to our list. */ - CLI_REALLOC(handle->comments, - sizeof(char*) * (handle->nComments + 1), - free(comment), - status = CL_EMEM); + CLI_SAFER_REALLOC(handle->comments, + sizeof(char*) * (handle->nComments + 1), + free(comment), + status = CL_EMEM); handle->comments[handle->nComments] = comment; handle->nComments++; } @@ -1972,10 +1972,10 @@ cl_error_t cli_egg_deflate_decompress(char* compressed, size_t compressed_size, while (zstat == Z_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_REALLOC(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_deflate_decompress: cannot reallocate memory for decompressed output\n"), - status = CL_EMEM); + CLI_SAFER_REALLOC(decoded, + capacity + BUFSIZ, + cli_errmsg("cli_egg_deflate_decompress: cannot reallocate memory for decompressed output\n"), + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2094,10 +2094,10 @@ cl_error_t cli_egg_bzip2_decompress(char* compressed, size_t compressed_size, ch while (bzstat == BZ_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_REALLOC(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_bzip2_decompress: cannot reallocate memory for decompressed output\n"); - status = CL_EMEM); + CLI_SAFER_REALLOC(decoded, + capacity + BUFSIZ, + cli_errmsg("cli_egg_bzip2_decompress: cannot reallocate memory for decompressed output\n"); + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2211,10 +2211,10 @@ cl_error_t cli_egg_lzma_decompress(char* compressed, size_t compressed_size, cha while (lzmastat == LZMA_RESULT_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_REALLOC(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_lzma_decompress: cannot reallocate memory for decompressed output\n"); - status = CL_EMEM); + CLI_SAFER_REALLOC(decoded, + capacity + BUFSIZ, + cli_errmsg("cli_egg_lzma_decompress: cannot reallocate memory for decompressed output\n"); + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2361,11 +2361,11 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha break; } - CLI_REALLOC(decompressed, - (size_t)decompressed_size + currBlock->blockHeader->compress_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - status = CL_EMEM); + CLI_SAFER_REALLOC(decompressed, + (size_t)decompressed_size + currBlock->blockHeader->compress_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + status = CL_EMEM); memcpy(decompressed + decompressed_size, currBlock->compressedData, currBlock->blockHeader->compress_size); decompressed_size += currBlock->blockHeader->compress_size; @@ -2386,12 +2386,12 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha goto done; } /* Decompressed block. Add it to the file data */ - CLI_REALLOC(decompressed, - (size_t)decompressed_size + decompressed_block_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - free(decompressed_block), - status = CL_EMEM); + CLI_SAFER_REALLOC(decompressed, + (size_t)decompressed_size + decompressed_block_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + free(decompressed_block), + status = CL_EMEM); memcpy(decompressed + decompressed_size, decompressed_block, decompressed_block_size); decompressed_size += decompressed_block_size; @@ -2415,12 +2415,12 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha goto done; } /* Decompressed block. Add it to the file data */ - CLI_REALLOC(decompressed, - (size_t)decompressed_size + decompressed_block_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - free(decompressed_block), - status = CL_EMEM); + CLI_SAFER_REALLOC(decompressed, + (size_t)decompressed_size + decompressed_block_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + free(decompressed_block), + status = CL_EMEM); memcpy(decompressed + decompressed_size, decompressed_block, decompressed_block_size); decompressed_size += decompressed_block_size; @@ -2454,12 +2454,12 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha // goto done; // } // /* Decompressed block. Add it to the file data */ - // CLI_REALLOC(decompressed, - // (size_t)decompressed_size + decompressed_block_size, - // cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - // decompressed_size), - // free(decompressed_block), - // status = CL_EMEM); + // CLI_SAFER_REALLOC(decompressed, + // (size_t)decompressed_size + decompressed_block_size, + // cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + // decompressed_size), + // free(decompressed_block), + // status = CL_EMEM); // memcpy(decompressed + decompressed_size, decompressed_block, decompressed_block_size); // decompressed_size += decompressed_block_size; diff --git a/libclamav/elf.c b/libclamav/elf.c index 294d64e869..75c2d98941 100644 --- a/libclamav/elf.c +++ b/libclamav/elf.c @@ -244,7 +244,7 @@ static int cli_elf_ph32(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, } if (phnum) { - program_hdr = (struct elf_program_hdr32 *)cli_calloc(phnum, sizeof(struct elf_program_hdr32)); + program_hdr = (struct elf_program_hdr32 *)cli_max_calloc(phnum, sizeof(struct elf_program_hdr32)); if (!program_hdr) { cli_errmsg("ELF: Can't allocate memory for program headers\n"); return CL_EMEM; @@ -344,7 +344,7 @@ static cl_error_t cli_elf_ph64(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *e } if (phnum) { - program_hdr = (struct elf_program_hdr64 *)cli_calloc(phnum, sizeof(struct elf_program_hdr64)); + program_hdr = (struct elf_program_hdr64 *)cli_max_calloc(phnum, sizeof(struct elf_program_hdr64)); if (!program_hdr) { cli_errmsg("ELF: Can't allocate memory for program headers\n"); return CL_EMEM; @@ -445,7 +445,7 @@ static int cli_elf_sh32(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, cli_dbgmsg("ELF: Section header table offset: %d\n", shoff); if (elfinfo) { - elfinfo->sections = (struct cli_exe_section *)cli_calloc(shnum, sizeof(struct cli_exe_section)); + elfinfo->sections = (struct cli_exe_section *)cli_max_calloc(shnum, sizeof(struct cli_exe_section)); if (!elfinfo->sections) { cli_dbgmsg("ELF: Can't allocate memory for section headers\n"); return CL_EMEM; @@ -453,7 +453,7 @@ static int cli_elf_sh32(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, } if (shnum) { - section_hdr = (struct elf_section_hdr32 *)cli_calloc(shnum, shentsize); + section_hdr = (struct elf_section_hdr32 *)cli_max_calloc(shnum, shentsize); if (!section_hdr) { cli_errmsg("ELF: Can't allocate memory for section headers\n"); return CL_EMEM; @@ -544,7 +544,7 @@ static int cli_elf_sh64(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, cli_dbgmsg("ELF: Section header table offset: " STDu64 "\n", shoff); if (elfinfo) { - elfinfo->sections = (struct cli_exe_section *)cli_calloc(shnum, sizeof(struct cli_exe_section)); + elfinfo->sections = (struct cli_exe_section *)cli_max_calloc(shnum, sizeof(struct cli_exe_section)); if (!elfinfo->sections) { cli_dbgmsg("ELF: Can't allocate memory for section headers\n"); return CL_EMEM; @@ -552,7 +552,7 @@ static int cli_elf_sh64(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, } if (shnum) { - section_hdr = (struct elf_section_hdr64 *)cli_calloc(shnum, shentsize); + section_hdr = (struct elf_section_hdr64 *)cli_max_calloc(shnum, shentsize); if (!section_hdr) { cli_errmsg("ELF: Can't allocate memory for section headers\n"); return CL_EMEM; diff --git a/libclamav/entconv.c b/libclamav/entconv.c index 1eab80c30e..13345078b4 100644 --- a/libclamav/entconv.c +++ b/libclamav/entconv.c @@ -495,7 +495,7 @@ static char* normalize_encoding(const unsigned char* enc) if (!encname_chars[enc[i]]) return NULL; } - norm = cli_malloc(len + 1); + norm = cli_max_malloc(len + 1); if (!norm) return NULL; for (i = 0; i < len; i++) @@ -656,7 +656,7 @@ static iconv_t iconv_open_cached(const char* fromcode) idx = cache->last++; if (idx >= cache->len) { cache->len += 16; - cache->tab = cli_realloc2(cache->tab, cache->len * sizeof(cache->tab[0])); + cache->tab = cli_max_realloc2(cache->tab, cache->len * sizeof(cache->tab[0])); if (!cache->tab) { cli_dbgmsg(MODULE_NAME "!Out of mem in iconv-pool\n"); errno = ENOMEM; @@ -803,7 +803,7 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha int byte_count, sigbit_count; out_utf8_size = in_size; - out_utf8 = cli_calloc(1, out_utf8_size + 1); + out_utf8 = cli_max_calloc(1, out_utf8_size + 1); if (NULL == out_utf8) { cli_errmsg("cli_codepage_to_utf8: Failure allocating buffer for utf8 filename.\n"); status = CL_EMEM; @@ -863,7 +863,7 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha uint16_t* pCodeUnits = (uint16_t*)in; cchWideChar = (int)in_size / 2; - lpWideCharStr = cli_malloc((cchWideChar) * sizeof(WCHAR)); /* No need for a null terminator here, we'll deal with the exact size */ + lpWideCharStr = cli_max_malloc((cchWideChar) * sizeof(WCHAR)); /* No need for a null terminator here, we'll deal with the exact size */ if (NULL == lpWideCharStr) { cli_dbgmsg("cli_codepage_to_utf8: failed to allocate memory for wide char string.\n"); status = CL_EMEM; @@ -892,7 +892,7 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha goto done; } - lpWideCharStr = cli_malloc((cchWideChar) * sizeof(WCHAR)); /* No need for a null terminator here, we'll deal with the exact size */ + lpWideCharStr = cli_max_malloc((cchWideChar) * sizeof(WCHAR)); /* No need for a null terminator here, we'll deal with the exact size */ if (NULL == lpWideCharStr) { cli_dbgmsg("cli_codepage_to_utf8: failed to allocate memory for wide char string.\n"); status = CL_EMEM; @@ -935,7 +935,7 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha goto done; } - out_utf8 = cli_malloc(out_utf8_size + 1); /* Add a null terminator to this string */ + out_utf8 = cli_max_malloc(out_utf8_size + 1); /* Add a null terminator to this string */ if (NULL == out_utf8) { cli_dbgmsg("cli_codepage_to_utf8: failed to allocate memory for wide char to utf-8 string.\n"); status = CL_EMEM; @@ -994,7 +994,7 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha outbytesleft = out_utf8_size; - out_utf8 = cli_calloc(1, out_utf8_size + 1); + out_utf8 = cli_max_calloc(1, out_utf8_size + 1); if (NULL == out_utf8) { cli_errmsg("cli_codepage_to_utf8: Failure allocating buffer for utf8 data.\n"); status = CL_EMEM; @@ -1037,9 +1037,9 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha } /* iconv succeeded, but probably didn't use the whole buffer. Free up the extra memory. */ - out_utf8_tmp = cli_realloc(out_utf8, out_utf8_size - outbytesleft + 1); + out_utf8_tmp = cli_max_realloc(out_utf8, out_utf8_size - outbytesleft + 1); if (NULL == out_utf8_tmp) { - cli_errmsg("cli_codepage_to_utf8: failure cli_realloc'ing converted filename.\n"); + cli_errmsg("cli_codepage_to_utf8: failure cli_max_realloc'ing converted filename.\n"); status = CL_EMEM; goto done; } @@ -1100,7 +1100,7 @@ char* cli_utf16toascii(const char* str, unsigned int length) if (length % 2) length--; - if (!(decoded = cli_calloc(length / 2 + 1, sizeof(char)))) + if (!(decoded = cli_max_calloc(length / 2 + 1, sizeof(char)))) return NULL; for (i = 0, j = 0; i < length; i += 2, j++) { @@ -1127,7 +1127,7 @@ char* cli_utf16_to_utf8(const char* utf16, size_t length, encoding_t type) length--; } - s2 = cli_malloc(needed); + s2 = cli_max_malloc(needed); if (!s2) return NULL; diff --git a/libclamav/events.c b/libclamav/events.c index 2011bb7852..6a72158ef1 100644 --- a/libclamav/events.c +++ b/libclamav/events.c @@ -54,7 +54,7 @@ cli_events_t *cli_events_new(unsigned max_event) if (!ev) return NULL; ev->max = max_event; - ev->events = cli_calloc(max_event, sizeof(*ev->events)); + ev->events = cli_max_calloc(max_event, sizeof(*ev->events)); if (!ev->events) { free(ev); return NULL; @@ -132,7 +132,7 @@ static inline void ev_chain(cli_events_t *ctx, struct cli_event *ev, union ev_va union ev_val *chain; uint32_t siz = sizeof(*chain) * (ev->count + 1); - chain = cli_realloc(ev->u.v_chain, siz); + chain = cli_max_realloc(ev->u.v_chain, siz); if (!chain) { cli_event_error_oom(ctx, siz); return; @@ -294,7 +294,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l } switch (ev->multiple) { case multiple_last: { - void *v_data = cli_realloc2(ev->u.v_data, len); + void *v_data = cli_max_realloc2(ev->u.v_data, len); if (v_data) { ev->u.v_data = v_data; memcpy(v_data, data, len); @@ -305,7 +305,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l break; } case multiple_concat: { - void *v_data = cli_realloc2(ev->u.v_data, ev->count + len); + void *v_data = cli_max_realloc2(ev->u.v_data, ev->count + len); if (v_data) { ev->u.v_data = v_data; memcpy((char *)v_data + ev->count, data, len); diff --git a/libclamav/fmap.c b/libclamav/fmap.c index 65228647f5..38350efa00 100644 --- a/libclamav/fmap.c +++ b/libclamav/fmap.c @@ -381,7 +381,7 @@ extern cl_fmap_t *cl_fmap_open_handle(void *handle, size_t offset, size_t len, goto done; } - m->bitmap = cli_calloc(1, bitmap_size); + m->bitmap = cli_max_calloc(1, bitmap_size); if (!m->bitmap) { cli_warnmsg("fmap: map header allocation failed\n"); goto done; @@ -408,7 +408,7 @@ extern cl_fmap_t *cl_fmap_open_handle(void *handle, size_t offset, size_t len, } #endif /* ANONYMOUS_MAP */ if (!use_aging) { - m->data = (fmap_t *)cli_malloc(mapsz); + m->data = (fmap_t *)cli_max_malloc(mapsz); } if (!m->data) { cli_warnmsg("fmap: map allocation failed\n"); diff --git a/libclamav/hashtab.c b/libclamav/hashtab.c index fc13f72244..fdc2d6cbf6 100644 --- a/libclamav/hashtab.c +++ b/libclamav/hashtab.c @@ -180,7 +180,7 @@ cl_error_t cli_hashtab_init(struct cli_hashtable *s, size_t capacity) PROFILE_INIT(s); capacity = nearest_power(capacity); - s->htable = cli_calloc(capacity, sizeof(*s->htable)); + s->htable = cli_max_calloc(capacity, sizeof(*s->htable)); if (!s->htable) { return CL_EMEM; } @@ -332,7 +332,7 @@ static cl_error_t cli_hashtab_grow(struct cli_hashtable *s) cli_errmsg("hashtab.c: capacity problem growing from: %zu\n", s->capacity); return CL_EMEM; } - htable = cli_calloc(new_capacity, sizeof(*s->htable)); + htable = cli_max_calloc(new_capacity, sizeof(*s->htable)); if (!htable) { return CL_EMEM; } @@ -451,7 +451,7 @@ const struct cli_element *cli_hashtab_insert(struct cli_hashtable *s, const char } else { PROFILE_INSERT(s, tries); } - thekey = cli_malloc(len + 1); + thekey = cli_max_malloc(len + 1); if (!thekey) { cli_errmsg("hashtab.c: Unable to allocate memory for thekey\n"); return NULL; @@ -652,13 +652,13 @@ cl_error_t cli_hashset_init(struct cli_hashset *hs, size_t initial_capacity, uin hs->capacity = initial_capacity; hs->mask = initial_capacity - 1; hs->count = 0; - hs->keys = cli_malloc(initial_capacity * sizeof(*hs->keys)); + hs->keys = cli_max_malloc(initial_capacity * sizeof(*hs->keys)); hs->mempool = NULL; if (!hs->keys) { cli_errmsg("hashtab.c: Unable to allocate memory for hs->keys\n"); return CL_EMEM; } - hs->bitmap = cli_calloc(initial_capacity >> 5, sizeof(*hs->bitmap)); + hs->bitmap = cli_max_calloc(initial_capacity >> 5, sizeof(*hs->bitmap)); if (!hs->bitmap) { free(hs->keys); cli_errmsg("hashtab.c: Unable to allocate memory for hs->bitmap\n"); @@ -818,7 +818,7 @@ ssize_t cli_hashset_toarray(const struct cli_hashset *hs, uint32_t **array) return -1; } - *array = arr = cli_malloc(hs->count * sizeof(*arr)); + *array = arr = cli_max_malloc(hs->count * sizeof(*arr)); if (!arr) { cli_errmsg("hashtab.c: Unable to allocate memory for array\n"); return -1; @@ -889,7 +889,7 @@ cl_error_t cli_map_addkey(struct cli_map *m, const void *key, int32_t keysize) if (m->valuesize) { void *v; - v = cli_realloc(m->u.sized_values, n * m->valuesize); + v = cli_max_realloc(m->u.sized_values, n * m->valuesize); if (!v) { return CL_EMEM; } @@ -899,7 +899,7 @@ cl_error_t cli_map_addkey(struct cli_map *m, const void *key, int32_t keysize) } else { struct cli_map_value *v; - v = cli_realloc(m->u.unsized_values, n * sizeof(*m->u.unsized_values)); + v = cli_max_realloc(m->u.unsized_values, n * sizeof(*m->u.unsized_values)); if (!v) { return CL_EMEM; } @@ -965,7 +965,7 @@ cl_error_t cli_map_setvalue(struct cli_map *m, const void *value, int32_t values free(v->value); } - v->value = cli_malloc(valuesize); + v->value = cli_max_malloc(valuesize); if (!v->value) { cli_errmsg("hashtab.c: Unable to allocate memory for v->value\n"); return CL_EMEM; diff --git a/libclamav/hfsplus.c b/libclamav/hfsplus.c index b7f439b981..d9b510c1b8 100644 --- a/libclamav/hfsplus.c +++ b/libclamav/hfsplus.c @@ -523,7 +523,7 @@ static cl_error_t hfsplus_check_attribute(cli_ctx *ctx, hfsPlusVolumeHeader *vol nodeSize = attrHeader->nodeSize; /* Need to buffer current node, map will keep moving */ - nodeBuf = cli_malloc(nodeSize); + nodeBuf = cli_max_malloc(nodeSize); if (!nodeBuf) { cli_dbgmsg("hfsplus_check_attribute: failed to acquire node buffer, " "size " STDu32 "\n", @@ -894,7 +894,7 @@ static cl_error_t hfsplus_read_block_table(int fd, uint32_t *numBlocks, hfsPlusR } *numBlocks = le32_to_host(*numBlocks); // Let's do a little little endian just for fun, shall we? - *table = cli_malloc(sizeof(hfsPlusResourceBlockTable) * *numBlocks); + *table = cli_max_malloc(sizeof(hfsPlusResourceBlockTable) * *numBlocks); if (!*table) { cli_dbgmsg("hfsplus_read_block_table: Failed to allocate memory for block table\n"); status = CL_EMEM; @@ -948,7 +948,7 @@ static cl_error_t hfsplus_walk_catalog(cli_ctx *ctx, hfsPlusVolumeHeader *volHea nodeSize = catHeader->nodeSize; /* Need to buffer current node, map will keep moving */ - nodeBuf = cli_malloc(nodeSize); + nodeBuf = cli_max_malloc(nodeSize); if (!nodeBuf) { cli_dbgmsg("hfsplus_walk_catalog: failed to acquire node buffer, " "size " STDu32 "\n", diff --git a/libclamav/htmlnorm.c b/libclamav/htmlnorm.c index 129dc8b5bd..786d57dfa8 100644 --- a/libclamav/htmlnorm.c +++ b/libclamav/htmlnorm.c @@ -182,7 +182,7 @@ static unsigned char *cli_readchunk(FILE *stream, m_area_t *m_area, unsigned int unsigned char *chunk, *start, *ptr, *end; unsigned int chunk_len, count; - chunk = (unsigned char *)cli_malloc(max_len); + chunk = (unsigned char *)cli_max_malloc(max_len); if (!chunk) { cli_errmsg("readchunk: Unable to allocate memory for chunk\n"); return NULL; @@ -371,18 +371,18 @@ void html_tag_arg_add(tag_arguments_t *tags, { int len, i; tags->count++; - tags->tag = (unsigned char **)cli_realloc2(tags->tag, + tags->tag = (unsigned char **)cli_max_realloc2(tags->tag, tags->count * sizeof(char *)); if (!tags->tag) { goto done; } - tags->value = (unsigned char **)cli_realloc2(tags->value, + tags->value = (unsigned char **)cli_max_realloc2(tags->value, tags->count * sizeof(char *)); if (!tags->value) { goto done; } if (tags->scanContents) { - tags->contents = (unsigned char **)cli_realloc2(tags->contents, + tags->contents = (unsigned char **)cli_max_realloc2(tags->contents, tags->count * sizeof(*tags->contents)); if (!tags->contents) { goto done; @@ -527,7 +527,7 @@ static inline void html_tag_contents_done(tag_arguments_t *tags, int idx, struct { unsigned char *p; cont->contents[cont->pos++] = '\0'; - p = cli_malloc(cont->pos); + p = cli_max_malloc(cont->pos); if (!p) { cli_errmsg("html_tag_contents_done: Unable to allocate memory for p\n"); return; @@ -1201,9 +1201,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha chunk_size = style_end - style_begin; if (style_buff == NULL) { - CLI_MALLOC(style_buff, chunk_size + 1); + CLI_MAX_MALLOC(style_buff, chunk_size + 1); } else { - CLI_REALLOC(style_buff, style_buff_size + chunk_size + 1); + CLI_MAX_REALLOC(style_buff, style_buff_size + chunk_size + 1); } memcpy(style_buff + style_buff_size, style_begin, chunk_size); @@ -1837,9 +1837,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha size_t chunk_size = ptr - style_begin; if (style_buff == NULL) { - CLI_MALLOC(style_buff, chunk_size + 1); + CLI_MAX_MALLOC(style_buff, chunk_size + 1); } else { - CLI_REALLOC(style_buff, style_buff_size + chunk_size + 1); + CLI_MAX_REALLOC(style_buff, style_buff_size + chunk_size + 1); } memcpy(style_buff + style_buff_size, style_begin, chunk_size); diff --git a/libclamav/hwp.c b/libclamav/hwp.c index f7958daec4..fc497add51 100644 --- a/libclamav/hwp.c +++ b/libclamav/hwp.c @@ -206,14 +206,14 @@ static char *convert_hstr_to_utf8(const char *begin, size_t sz, const char *pare iconv_t cd; do { - p1 = inbuf = cli_calloc(1, sz + 1); + p1 = inbuf = cli_max_calloc(1, sz + 1); if (!inbuf) { cli_errmsg("%s: Failed to allocate memory for encoding conversion buffer\n", parent); rc = CL_EMEM; break; } memcpy(inbuf, begin, sz); - p2 = outbuf = cli_calloc(1, sz + 1); + p2 = outbuf = cli_max_calloc(1, sz + 1); if (!outbuf) { cli_errmsg("%s: Failed to allocate memory for encoding conversion buffer\n", parent); rc = CL_EMEM; @@ -254,7 +254,7 @@ static char *convert_hstr_to_utf8(const char *begin, size_t sz, const char *pare if (!res && (rc == CL_SUCCESS)) { char *tmpbuf; - tmpbuf = cli_calloc(1, sz + 1); + tmpbuf = cli_max_calloc(1, sz + 1); if (tmpbuf) { memcpy(tmpbuf, begin, sz); @@ -626,7 +626,7 @@ static inline cl_error_t parsehwp3_docsummary(cli_ctx *ctx, size_t offset) if (iret == CL_VIRUS) { char *b64; size_t b64len = strlen(hwp3_docsummary_fields[i].name) + 8; - b64 = cli_calloc(1, b64len); + b64 = cli_max_calloc(1, b64len); if (!b64) { cli_errmsg("HWP3.x: Failed to allocate memory for b64 boolean\n"); free(str); diff --git a/libclamav/inflate64.c b/libclamav/inflate64.c index 22a209c50f..0abef0cdbc 100644 --- a/libclamav/inflate64.c +++ b/libclamav/inflate64.c @@ -181,7 +181,7 @@ unsigned out; /* if it hasn't been done already, allocate space for the window */ if (state->window == Z_NULL) { - state->window = (unsigned char FAR *)cli_calloc(1U << state->wbits, sizeof(unsigned char)); + state->window = (unsigned char FAR *)cli_max_calloc(1U << state->wbits, sizeof(unsigned char)); if (state->window == Z_NULL) return 1; } diff --git a/libclamav/ishield.c b/libclamav/ishield.c index 5a93695118..e43979706c 100644 --- a/libclamav/ishield.c +++ b/libclamav/ishield.c @@ -432,7 +432,7 @@ cl_error_t cli_scanishield(cli_ctx *ctx, off_t off, size_t sz) } if (i == c.cabcnt) { c.cabcnt++; - if (!(c.cabs = cli_realloc2(c.cabs, sizeof(struct CABARRAY) * c.cabcnt))) { + if (!(c.cabs = cli_max_realloc2(c.cabs, sizeof(struct CABARRAY) * c.cabcnt))) { ret = CL_EMEM; break; } diff --git a/libclamav/json_api.c b/libclamav/json_api.c index ae93799e66..56a297eefa 100644 --- a/libclamav/json_api.c +++ b/libclamav/json_api.c @@ -487,7 +487,7 @@ cl_error_t cli_jsonstr_nojson(const char* key, const char* s) cl_error_t cli_jsonstrlen_nojson(const char* key, const char* s, int len) { - char* sp = cli_malloc(len + 1); + char* sp = cli_max_malloc(len + 1); if (NULL == sp) { cli_errmsg("json: no memory for json strlen object.\n"); return CL_EMEM; diff --git a/libclamav/jsparse/js-norm.c b/libclamav/jsparse/js-norm.c index 83b01337da..ac8d06fe57 100644 --- a/libclamav/jsparse/js-norm.c +++ b/libclamav/jsparse/js-norm.c @@ -287,7 +287,7 @@ static cl_error_t tokens_ensure_capacity(struct tokens *tokens, size_t cap) yystype *data; cap += 1024; /* Keep old data if OOM */ - data = cli_realloc(tokens->data, cap * sizeof(*tokens->data)); + data = cli_max_realloc(tokens->data, cap * sizeof(*tokens->data)); if (!data) return CL_EMEM; tokens->data = data; @@ -516,7 +516,7 @@ static const char *de_packer_2[] = {"p", "a", "c", "k", "e", "d"}; static inline char *textbuffer_done(yyscan_t scanner) { - char *str = cli_realloc(scanner->buf.data, scanner->buf.pos); + char *str = cli_max_realloc(scanner->buf.data, scanner->buf.pos); if (!str) { str = scanner->buf.data; } @@ -1181,7 +1181,7 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n /* delete TOK_PLUS */ free_token(&state->tokens.data[--state->tokens.cnt]); - str = cli_realloc(str, str_len + leng + 1); + str = cli_max_realloc(str, str_len + leng + 1); if (!str) break; strncpy(str + str_len, text, leng); @@ -1553,7 +1553,7 @@ static const enum char_class id_ctype[256] = { static void textbuf_clean(struct text_buffer *buf) { if (buf->capacity > BUF_KEEP_SIZE) { - char *data = cli_realloc(buf->data, BUF_KEEP_SIZE); + char *data = cli_max_realloc(buf->data, BUF_KEEP_SIZE); if (data) buf->data = data; buf->capacity = BUF_KEEP_SIZE; diff --git a/libclamav/jsparse/textbuf.h b/libclamav/jsparse/textbuf.h index 7ff03fa01a..776290ef6a 100644 --- a/libclamav/jsparse/textbuf.h +++ b/libclamav/jsparse/textbuf.h @@ -44,7 +44,7 @@ static inline int textbuffer_ensure_capacity(struct text_buffer *txtbuf, size_t if (txtbuf->pos + len > txtbuf->capacity) { char *d; unsigned capacity = MAX(txtbuf->pos + len, txtbuf->capacity + 4096); - d = cli_realloc(txtbuf->data, capacity); + d = cli_max_realloc(txtbuf->data, capacity); if (!d) return -1; txtbuf->capacity = capacity; diff --git a/libclamav/libclamav.map b/libclamav/libclamav.map index e9b6ba4114..ff36187032 100644 --- a/libclamav/libclamav.map +++ b/libclamav/libclamav.map @@ -107,7 +107,6 @@ CLAMAV_PRIVATE { cli_chomp; cli_rndnum; - cli_calloc; cli_ole2_extract; cli_errmsg; cli_debug_flag; @@ -127,10 +126,12 @@ CLAMAV_PRIVATE { html_normalise_map; cli_utf16toascii; - cli_malloc; cli_memstr; cli_strdup; - cli_realloc; + cli_max_calloc; + cli_max_malloc; + cli_max_realloc; + cli_safer_realloc; cli_ctime; tableCreate; tableDestroy; diff --git a/libclamav/line.c b/libclamav/line.c index 35915bc2dc..b604667686 100644 --- a/libclamav/line.c +++ b/libclamav/line.c @@ -70,7 +70,7 @@ line_t * lineCreate(const char *data) { const size_t size = strlen(data); - line_t *ret = (line_t *)cli_malloc(size + 2); + line_t *ret = (line_t *)cli_max_malloc(size + 2); if (ret == NULL) { cli_errmsg("lineCreate: Unable to allocate memory for ret\n"); diff --git a/libclamav/lzma_iface.c b/libclamav/lzma_iface.c index f719f90f07..163a9327b2 100644 --- a/libclamav/lzma_iface.c +++ b/libclamav/lzma_iface.c @@ -41,7 +41,7 @@ void *__lzma_wrap_alloc(void *unused, size_t size) return NULL; } - return cli_calloc(1, size); + return cli_max_calloc(1, size); } void __lzma_wrap_free(void *unused, void *freeme) { diff --git a/libclamav/lzw/lzwdec.c b/libclamav/lzw/lzwdec.c index b9aac5d016..788b140898 100644 --- a/libclamav/lzw/lzwdec.c +++ b/libclamav/lzw/lzwdec.c @@ -172,7 +172,7 @@ int lzwInit(lzw_streamp strm) state->nextbits = 0; /* dictionary setup */ - state->dec_codetab = cli_calloc(CSIZE, sizeof(code_t)); + state->dec_codetab = cli_max_calloc(CSIZE, sizeof(code_t)); if (state->dec_codetab == NULL) { free(state); strm->msg = "failed to allocate code table"; @@ -431,7 +431,7 @@ static void code_print(code_t *code) uint8_t *string; int i = 0; - string = cli_calloc(code->length + 1, sizeof(uint8_t)); + string = cli_max_calloc(code->length + 1, sizeof(uint8_t)); if (!string) return; diff --git a/libclamav/macho.c b/libclamav/macho.c index a4030fca77..c1558bbcb3 100644 --- a/libclamav/macho.c +++ b/libclamav/macho.c @@ -375,7 +375,7 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) cli_dbgmsg("MACHO: ------------------\n"); continue; } - sections = (struct cli_exe_section *)cli_realloc2(sections, (sect + nsects) * sizeof(struct cli_exe_section)); + sections = (struct cli_exe_section *)cli_max_realloc2(sections, (sect + nsects) * sizeof(struct cli_exe_section)); if (!sections) { cli_errmsg("cli_scanmacho: Can't allocate memory for 'sections'\n"); return CL_EMEM; diff --git a/libclamav/matcher-ac.c b/libclamav/matcher-ac.c index 877d95dc96..11f9469562 100644 --- a/libclamav/matcher-ac.c +++ b/libclamav/matcher-ac.c @@ -1412,7 +1412,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->reloffsigs = reloffsigs; if (reloffsigs) { - data->offset = (uint32_t *)cli_malloc(reloffsigs * 2 * sizeof(uint32_t)); + data->offset = (uint32_t *)cli_max_malloc(reloffsigs * 2 * sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_ac_init: Can't allocate memory for data->offset\n"); return CL_EMEM; @@ -1423,7 +1423,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->partsigs = partsigs; if (partsigs) { - data->offmatrix = (uint32_t ***)cli_calloc(partsigs, sizeof(uint32_t **)); + data->offmatrix = (uint32_t ***)cli_max_calloc(partsigs, sizeof(uint32_t **)); if (!data->offmatrix) { cli_errmsg("cli_ac_init: Can't allocate memory for data->offmatrix\n"); @@ -1436,7 +1436,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->lsigs = lsigs; if (lsigs) { - data->lsigcnt = (uint32_t **)cli_malloc(lsigs * sizeof(uint32_t *)); + data->lsigcnt = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); if (!data->lsigcnt) { if (partsigs) free(data->offmatrix); @@ -1447,7 +1447,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigcnt\n"); return CL_EMEM; } - data->lsigcnt[0] = (uint32_t *)cli_calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigcnt[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); if (!data->lsigcnt[0]) { free(data->lsigcnt); if (partsigs) @@ -1461,7 +1461,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t } for (i = 1; i < lsigs; i++) data->lsigcnt[i] = data->lsigcnt[0] + 64 * i; - data->yr_matches = (uint8_t *)cli_calloc(lsigs, sizeof(uint8_t)); + data->yr_matches = (uint8_t *)cli_max_calloc(lsigs, sizeof(uint8_t)); if (data->yr_matches == NULL) { free(data->lsigcnt[0]); free(data->lsigcnt); @@ -1474,7 +1474,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t } /* subsig offsets */ - data->lsig_matches = (struct cli_lsig_matches **)cli_calloc(lsigs, sizeof(struct cli_lsig_matches *)); + data->lsig_matches = (struct cli_lsig_matches **)cli_max_calloc(lsigs, sizeof(struct cli_lsig_matches *)); if (!data->lsig_matches) { free(data->yr_matches); free(data->lsigcnt[0]); @@ -1488,8 +1488,8 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsig_matches\n"); return CL_EMEM; } - data->lsigsuboff_last = (uint32_t **)cli_malloc(lsigs * sizeof(uint32_t *)); - data->lsigsuboff_first = (uint32_t **)cli_malloc(lsigs * sizeof(uint32_t *)); + data->lsigsuboff_last = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); + data->lsigsuboff_first = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); if (!data->lsigsuboff_last || !data->lsigsuboff_first) { free(data->lsig_matches); free(data->lsigsuboff_last); @@ -1506,8 +1506,8 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigsuboff_(last|first)\n"); return CL_EMEM; } - data->lsigsuboff_last[0] = (uint32_t *)cli_calloc(lsigs * 64, sizeof(uint32_t)); - data->lsigsuboff_first[0] = (uint32_t *)cli_calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigsuboff_last[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigsuboff_first[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); if (!data->lsigsuboff_last[0] || !data->lsigsuboff_first[0]) { free(data->lsig_matches); free(data->lsigsuboff_last[0]); @@ -1704,10 +1704,10 @@ cl_error_t lsig_sub_matched(const struct cli_matcher *root, struct cli_ac_data * ls_matches = mdata->lsig_matches[lsig_id]; if (ls_matches == NULL) { /* allocate cli_lsig_matches */ - ls_matches = mdata->lsig_matches[lsig_id] = (struct cli_lsig_matches *)cli_calloc(1, sizeof(struct cli_lsig_matches) + + ls_matches = mdata->lsig_matches[lsig_id] = (struct cli_lsig_matches *)cli_max_calloc(1, sizeof(struct cli_lsig_matches) + (ac_lsig->tdb.subsigs - 1) * sizeof(struct cli_subsig_matches *)); if (ls_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_calloc failed for cli_lsig_matches\n"); + cli_errmsg("lsig_sub_matched: cli_max_calloc failed for cli_lsig_matches\n"); return CL_EMEM; } ls_matches->subsigs = ac_lsig->tdb.subsigs; @@ -1716,16 +1716,16 @@ cl_error_t lsig_sub_matched(const struct cli_matcher *root, struct cli_ac_data * if (ss_matches == NULL) { /* allocate cli_subsig_matches */ ss_matches = ls_matches->matches[subsig_id] = malloc(sizeof(struct cli_subsig_matches)); if (ss_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_malloc failed for cli_subsig_matches struct\n"); + cli_errmsg("lsig_sub_matched: cli_max_malloc failed for cli_subsig_matches struct\n"); return CL_EMEM; } ss_matches->next = 0; ss_matches->last = sizeof(ss_matches->offsets) / sizeof(uint32_t) - 1; } if (ss_matches->next > ss_matches->last) { /* cli_matches out of space? realloc */ - ss_matches = ls_matches->matches[subsig_id] = cli_realloc(ss_matches, sizeof(struct cli_subsig_matches) + sizeof(uint32_t) * ss_matches->last * 2); + ss_matches = ls_matches->matches[subsig_id] = cli_max_realloc(ss_matches, sizeof(struct cli_subsig_matches) + sizeof(uint32_t) * ss_matches->last * 2); if (ss_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_realloc failed for cli_subsig_matches struct\n"); + cli_errmsg("lsig_sub_matched: cli_max_realloc failed for cli_subsig_matches struct\n"); return CL_EMEM; } ss_matches->last = sizeof(ss_matches->offsets) / sizeof(uint32_t) + ss_matches->last * 2 - 1; @@ -1926,13 +1926,13 @@ cl_error_t cli_ac_scanbuff( /* sparsely populated matrix, so allocate and initialize if NULL */ if (!mdata->offmatrix[pt->sigid - 1]) { - mdata->offmatrix[pt->sigid - 1] = cli_malloc(pt->parts * sizeof(int32_t *)); + mdata->offmatrix[pt->sigid - 1] = cli_max_malloc(pt->parts * sizeof(int32_t *)); if (!mdata->offmatrix[pt->sigid - 1]) { cli_errmsg("cli_ac_scanbuff: Can't allocate memory for mdata->offmatrix[%u]\n", pt->sigid - 1); return CL_EMEM; } - mdata->offmatrix[pt->sigid - 1][0] = cli_malloc(pt->parts * (CLI_DEFAULT_AC_TRACKLEN + 2) * sizeof(uint32_t)); + mdata->offmatrix[pt->sigid - 1][0] = cli_max_malloc(pt->parts * (CLI_DEFAULT_AC_TRACKLEN + 2) * sizeof(uint32_t)); if (!mdata->offmatrix[pt->sigid - 1][0]) { cli_errmsg("cli_ac_scanbuff: Can't allocate memory for mdata->offmatrix[%u][0]\n", pt->sigid - 1); free(mdata->offmatrix[pt->sigid - 1]); @@ -2589,7 +2589,7 @@ inline static int ac_special_altstr(const char *hexpr, uint8_t sigopts, struct c special->type = AC_SPECIAL_ALT_STR; /* allocate reusable subexpr */ - if (!(subexpr = cli_calloc(slen + 1, sizeof(char)))) { + if (!(subexpr = cli_max_calloc(slen + 1, sizeof(char)))) { cli_errmsg("ac_special_altstr: Can't allocate subexpr container\n"); free(hexprcpy); return CL_EMEM; @@ -2751,7 +2751,7 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch } hexnewsz = strlen(hexsig) + 1; - if (!(hexnew = (char *)cli_calloc(1, hexnewsz))) { + if (!(hexnew = (char *)cli_max_calloc(1, hexnewsz))) { MPOOL_FREE(root->mempool, new); free(hexcpy); return CL_EMEM; diff --git a/libclamav/matcher-bm.c b/libclamav/matcher-bm.c index 75f6e887bc..f6cac830fd 100644 --- a/libclamav/matcher-bm.c +++ b/libclamav/matcher-bm.c @@ -168,12 +168,12 @@ cl_error_t cli_bm_initoff(const struct cli_matcher *root, struct cli_bm_off *dat } data->cnt = data->pos = 0; - data->offtab = (uint32_t *)cli_malloc(root->bm_patterns * sizeof(uint32_t)); + data->offtab = (uint32_t *)cli_max_malloc(root->bm_patterns * sizeof(uint32_t)); if (!data->offtab) { cli_errmsg("cli_bm_initoff: Can't allocate memory for data->offtab\n"); return CL_EMEM; } - data->offset = (uint32_t *)cli_malloc(root->bm_patterns * sizeof(uint32_t)); + data->offset = (uint32_t *)cli_max_malloc(root->bm_patterns * sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_bm_initoff: Can't allocate memory for data->offset\n"); free(data->offtab); diff --git a/libclamav/matcher-byte-comp.c b/libclamav/matcher-byte-comp.c index 7e101e2908..7c974b58e4 100644 --- a/libclamav/matcher-byte-comp.c +++ b/libclamav/matcher-byte-comp.c @@ -894,7 +894,7 @@ unsigned char *cli_bcomp_normalize_buffer(const unsigned char *buffer, uint32_t } /* keep in mind byte_len is a stack variable so this won't change byte_len in our calling functioning */ byte_len = byte_len - pad; - tmp_buffer = cli_calloc(byte_len + 1, sizeof(char)); + tmp_buffer = cli_max_calloc(byte_len + 1, sizeof(char)); if (NULL == tmp_buffer) { cli_errmsg("cli_bcomp_compare_check: unable to allocate memory for whitespace normalized temp buffer\n"); return NULL; @@ -912,13 +912,13 @@ unsigned char *cli_bcomp_normalize_buffer(const unsigned char *buffer, uint32_t if (opt_val & CLI_BCOMP_HEX || opt_val & CLI_BCOMP_AUTO) { unsigned char *hex_buffer; norm_len = (byte_len % 2) == 0 ? byte_len : byte_len + 1; - tmp_buffer = cli_calloc(norm_len + 1, sizeof(char)); + tmp_buffer = cli_max_calloc(norm_len + 1, sizeof(char)); if (NULL == tmp_buffer) { cli_errmsg("cli_bcomp_compare_check: unable to allocate memory for normalized temp buffer\n"); return NULL; } - hex_buffer = cli_calloc(norm_len + 1, sizeof(char)); + hex_buffer = cli_max_calloc(norm_len + 1, sizeof(char)); if (NULL == hex_buffer) { free(tmp_buffer); cli_errmsg("cli_bcomp_compare_check: unable to reallocate memory for hex buffer\n"); diff --git a/libclamav/matcher-pcre.c b/libclamav/matcher-pcre.c index 08f9dc8e08..4cbeb97a40 100644 --- a/libclamav/matcher-pcre.c +++ b/libclamav/matcher-pcre.c @@ -471,12 +471,12 @@ cl_error_t cli_pcre_recaloff(struct cli_matcher *root, struct cli_pcre_off *data } /* allocate data structures */ - data->shift = (uint32_t *)cli_calloc(root->pcre_metas, sizeof(uint32_t)); + data->shift = (uint32_t *)cli_max_calloc(root->pcre_metas, sizeof(uint32_t)); if (!data->shift) { cli_errmsg("cli_pcre_initoff: cannot allocate memory for data->shift\n"); return CL_EMEM; } - data->offset = (uint32_t *)cli_calloc(root->pcre_metas, sizeof(uint32_t)); + data->offset = (uint32_t *)cli_max_calloc(root->pcre_metas, sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_pcre_initoff: cannot allocate memory for data->offset\n"); free(data->shift); diff --git a/libclamav/mbox.c b/libclamav/mbox.c index 295d467fb6..60a0afd740 100644 --- a/libclamav/mbox.c +++ b/libclamav/mbox.c @@ -654,7 +654,7 @@ getMallocedBufferFromList(const ReadStruct *head) rs = rs->next; } - CLI_MALLOC(working, bufferLen); + CLI_MAX_MALLOC(working, bufferLen); rs = head; bufferLen = 0; @@ -1230,7 +1230,7 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) fulllinelength = strlen(line) + 1; } else if (line) { fulllinelength += strlen(line) + 1; - ptr = cli_realloc(fullline, fulllinelength); + ptr = cli_max_realloc(fullline, fulllinelength); if (ptr == NULL) continue; fullline = ptr; @@ -1875,7 +1875,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re message **m; mbox_status old_rc; - m = cli_realloc(messages, ((multiparts + 1) * sizeof(message *))); + m = cli_max_realloc(messages, ((multiparts + 1) * sizeof(message *))); if (m == NULL) break; messages = m; @@ -2091,7 +2091,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re } datasz = strlen(fullline) + strlen(data) + 1; - ptr = cli_realloc(fullline, datasz); + ptr = cli_max_realloc(fullline, datasz); if (ptr == NULL) break; @@ -3199,7 +3199,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c else { int i; - buf = cli_malloc(strlen(ptr) + 1); + buf = cli_max_malloc(strlen(ptr) + 1); if (buf == NULL) { cli_errmsg("parseMimeHeader: Unable to allocate memory for buf %llu\n", (long long unsigned)(strlen(ptr) + 1)); if (copy) @@ -3312,7 +3312,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c messageSetEncoding(m, ptr); break; case CONTENT_DISPOSITION: - buf = cli_malloc(strlen(ptr) + 1); + buf = cli_max_malloc(strlen(ptr) + 1); if (buf == NULL) { cli_errmsg("parseMimeHeader: Unable to allocate memory for buf %llu\n", (long long unsigned)(strlen(ptr) + 1)); if (copy) @@ -3392,7 +3392,7 @@ rfc822comments(const char *in, char *out) } if (out == NULL) { - out = cli_malloc(strlen(in) + 1); + out = cli_max_malloc(strlen(in) + 1); if (out == NULL) { cli_errmsg("rfc822comments: Unable to allocate memory for out %llu\n", (long long unsigned)(strlen(in) + 1)); return NULL; @@ -3460,7 +3460,7 @@ rfc2047(const char *in) return cli_strdup(in); cli_dbgmsg("rfc2047 '%s'\n", in); - out = cli_malloc(strlen(in) + 1); + out = cli_max_malloc(strlen(in) + 1); if (out == NULL) { cli_errmsg("rfc2047: Unable to allocate memory for out %llu\n", (long long unsigned)(strlen(in) + 1)); @@ -3631,7 +3631,7 @@ rfc1341(mbox_ctx *mctx, message *m) oldfilename = messageGetFilename(m); - arg = cli_malloc(10 + strlen(id) + strlen(number)); + arg = cli_max_malloc(10 + strlen(id) + strlen(number)); if (arg) { sprintf(arg, "filename=%s%s", id, number); messageAddArgument(m, arg); diff --git a/libclamav/message.c b/libclamav/message.c index 7d1e25969d..02af52b790 100644 --- a/libclamav/message.c +++ b/libclamav/message.c @@ -430,7 +430,7 @@ void messageAddArgument(message *m, const char *arg) char **q; m->numberOfArguments++; - q = (char **)cli_realloc(m->mimeArguments, m->numberOfArguments * sizeof(char *)); + q = (char **)cli_max_realloc(m->mimeArguments, m->numberOfArguments * sizeof(char *)); if (q == NULL) { m->numberOfArguments--; return; @@ -613,7 +613,7 @@ void messageAddArguments(message *m, const char *s) *ptr = '\0'; datasz = strlen(kcopy) + strlen(data) + 2; - field = cli_realloc(kcopy, strlen(kcopy) + strlen(data) + 2); + field = cli_max_realloc(kcopy, strlen(kcopy) + strlen(data) + 2); if (field) { cli_strlcat(field, "=", datasz); cli_strlcat(field, data, datasz); @@ -637,7 +637,7 @@ void messageAddArguments(message *m, const char *s) string++; len = (size_t)string - (size_t)key + 1; - field = cli_malloc(len); + field = cli_max_malloc(len); if (field) { memcpy(field, key, len - 1); @@ -857,7 +857,7 @@ void messageSetEncoding(message *m, const char *enctype) break; } - et = (encoding_type *)cli_realloc(m->encodingTypes, (m->numberOfEncTypes + 1) * sizeof(encoding_type)); + et = (encoding_type *)cli_max_realloc(m->encodingTypes, (m->numberOfEncTypes + 1) * sizeof(encoding_type)); if (et == NULL) break; @@ -1375,7 +1375,7 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy datasize = (line) ? strlen(line) + 2 : 0; if (datasize >= sizeof(smallbuf)) { - data = bigbuf = (unsigned char *)cli_malloc(datasize); + data = bigbuf = (unsigned char *)cli_max_malloc(datasize); if (NULL == data) { cli_dbgmsg("Failed to allocate data buffer of size %zu\n", datasize); break; @@ -2338,7 +2338,7 @@ rfc2231(const char *in) char *p; /* Don't handle continuations, decode what we can */ - p = ret = cli_malloc(strlen(in) + 16); + p = ret = cli_max_malloc(strlen(in) + 16); if (ret == NULL) { cli_errmsg("rfc2331: out of memory, unable to proceed\n"); return NULL; @@ -2394,7 +2394,7 @@ rfc2231(const char *in) cli_dbgmsg("rfc2231 '%s'\n", in); - ret = cli_malloc(strlen(in) + 1); + ret = cli_max_malloc(strlen(in) + 1); if (ret == NULL) { cli_errmsg("rfc2331: out of memory for ret\n"); diff --git a/libclamav/mew.c b/libclamav/mew.c index f2d230d56e..adc9cb794e 100644 --- a/libclamav/mew.c +++ b/libclamav/mew.c @@ -845,7 +845,7 @@ int unmew11(char *src, uint32_t off, uint32_t ssize, uint32_t dsize, uint32_t ba return -1; } - if (!(newsect = cli_realloc(section, (i + 2) * sizeof(struct cli_exe_section)))) { + if (!(newsect = cli_max_realloc(section, (i + 2) * sizeof(struct cli_exe_section)))) { cli_dbgmsg("MEW: Out of memory\n"); free(section); return -1; diff --git a/libclamav/mpool.h b/libclamav/mpool.h index bac983f698..d4c12f2c15 100644 --- a/libclamav/mpool.h +++ b/libclamav/mpool.h @@ -69,8 +69,8 @@ typedef void mpool_t; #define MPOOL_MALLOC(a, b) malloc(b) #define MPOOL_FREE(a, b) free(b) #define MPOOL_CALLOC(a, b, c) calloc(b, c) -#define MPOOL_REALLOC(a, b, c) cli_realloc(b, c) -#define MPOOL_REALLOC2(a, b, c) cli_realloc2(b, c) +#define MPOOL_REALLOC(a, b, c) cli_safer_realloc(b, c) +#define MPOOL_REALLOC2(a, b, c) cli_safer_realloc2(b, c) #define CLI_MPOOL_HEX2STR(mpool, src) cli_hex2str(src) #define CLI_MPOOL_STRDUP(mpool, s) cli_strdup(s) #define CLI_MPOOL_STRNDUP(mpool, s, n) cli_strdup(s, n) diff --git a/libclamav/msdoc.c b/libclamav/msdoc.c index d0800e0090..8e996f6bea 100644 --- a/libclamav/msdoc.c +++ b/libclamav/msdoc.c @@ -80,7 +80,7 @@ ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const char *encodi char *track; size_t bcnt, scnt; - outbuf = cli_calloc(1, sz + 1); + outbuf = cli_max_calloc(1, sz + 1); if (!(outbuf)) return NULL; memcpy(outbuf, begin, sz); @@ -110,7 +110,7 @@ ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const char *encodi } #if HAVE_ICONV - p1 = buf = cli_calloc(1, sz); + p1 = buf = cli_max_calloc(1, sz); if (!(buf)) return NULL; @@ -147,8 +147,8 @@ ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const char *encodi for (attempt = 1; attempt <= 3; ++attempt) { /* charset to UTF-8 should never exceed sz*6 */ sz2 = (attempt * 2) * sz; - /* use cli_realloc, reuse the buffer that has already been translated */ - outbuf = (char *)cli_realloc(outbuf, sz2 + 1); + /* use cli_max_realloc, reuse the buffer that has already been translated */ + outbuf = (char *)cli_max_realloc(outbuf, sz2 + 1); if (!outbuf) { free(buf); iconv_close(cd); @@ -428,7 +428,7 @@ ole2_process_property(summary_ctx_t *sctx, unsigned char *databuf, uint32_t offs strsize = PROPSTRLIMIT; } - outstr = cli_calloc(strsize + 1, 1); /* last char must be NULL */ + outstr = cli_max_calloc(strsize + 1, 1); /* last char must be NULL */ if (!outstr) { return CL_EMEM; } @@ -487,7 +487,7 @@ ole2_process_property(summary_ctx_t *sctx, unsigned char *databuf, uint32_t offs sctx->flags |= OLE2_SUMMARY_ERROR_OOB; return CL_EFORMAT; } - outstr = cli_calloc(strsize + 2, 1); /* last two chars must be NULL */ + outstr = cli_max_calloc(strsize + 2, 1); /* last two chars must be NULL */ if (!outstr) { return CL_EMEM; } diff --git a/libclamav/nsis/bzlib.c b/libclamav/nsis/bzlib.c index d8ccbb690f..0e14088f3b 100644 --- a/libclamav/nsis/bzlib.c +++ b/libclamav/nsis/bzlib.c @@ -990,7 +990,7 @@ int bz_config_ok ( void ) static void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) { - void* v = cli_malloc ( items * size ); + void* v = cli_max_malloc ( items * size ); UNUSEDPARAM(opaque); return v; } diff --git a/libclamav/ole2_extract.c b/libclamav/ole2_extract.c index a29874e7cd..d693c8cbab 100644 --- a/libclamav/ole2_extract.c +++ b/libclamav/ole2_extract.c @@ -256,7 +256,7 @@ cli_ole2_get_property_name2(const char *name, int size) if ((name[0] == 0 && name[1] == 0) || size <= 0 || size > 128) { return NULL; } - CLI_MALLOC(newname, size * 7, + CLI_MAX_MALLOC(newname, size * 7, cli_errmsg("OLE2 [cli_ole2_get_property_name2]: Unable to allocate memory for newname: %u\n", size * 7)); j = 0; @@ -304,7 +304,7 @@ get_property_name(char *name, int size) return NULL; } - CLI_MALLOC(newname, size, + CLI_MAX_MALLOC(newname, size, cli_errmsg("OLE2 [get_property_name]: Unable to allocate memory for newname %u\n", size)); cname = newname; @@ -778,7 +778,7 @@ static int ole2_walk_property_tree(ole2_header_t *hdr, const char *dir, int32_t } } #endif - dirname = (char *)cli_malloc(strlen(dir) + 8); + dirname = (char *)cli_max_malloc(strlen(dir) + 8); if (!dirname) { ole2_listmsg("OLE2: malloc failed for dirname\n"); ole2_list_delete(&node_list); @@ -888,7 +888,7 @@ static cl_error_t handler_writefile(ole2_header_t *hdr, property_t *prop, const current_block = prop->start_block; len = prop->size; - CLI_MALLOC(buff, 1 << hdr->log2_big_block_size, + CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, cli_errmsg("OLE2 [handler_writefile]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); ret = CL_EMEM); @@ -1157,7 +1157,7 @@ static cl_error_t scan_for_xlm_macros_and_images(ole2_header_t *hdr, property_t current_block = prop->start_block; len = prop->size; - CLI_MALLOC(buff, 1 << hdr->log2_big_block_size, + CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, cli_errmsg("OLE2 [scan_for_xlm_macros_and_images]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); status = CL_EMEM); @@ -1282,7 +1282,7 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char } if (name) { if (!strcmp(name, "fileheader")) { - CLI_CALLOC(hwp_check, 1, 1 << hdr->log2_big_block_size, status = CL_EMEM); + CLI_MAX_CALLOC(hwp_check, 1, 1 << hdr->log2_big_block_size, status = CL_EMEM); /* reading safety checks; do-while used for breaks */ do { @@ -1567,7 +1567,7 @@ static cl_error_t handler_otf(ole2_header_t *hdr, property_t *prop, const char * cli_dbgmsg("OLE2 [handler_otf]: Dumping '%s' to '%s'\n", name, tempfile); } - CLI_MALLOC(buff, 1 << hdr->log2_big_block_size, ret = CL_EMEM); + CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, ret = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { @@ -1746,7 +1746,7 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co goto done; } - CLI_MALLOC(rk, RKLENGTH(key->key_length_bits) * sizeof(uint64_t), ret = CL_EMEM); + CLI_MAX_MALLOC(rk, RKLENGTH(key->key_length_bits) * sizeof(uint64_t), ret = CL_EMEM); print_ole2_property(prop); @@ -1774,8 +1774,8 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co } uint32_t blockSize = 1 << hdr->log2_big_block_size; - CLI_MALLOC(buff, blockSize + sizeof(uint64_t), ret = CL_EMEM); - CLI_MALLOC(decryptDst, blockSize, ret = CL_EMEM); + CLI_MAX_MALLOC(buff, blockSize + sizeof(uint64_t), ret = CL_EMEM); + CLI_MAX_MALLOC(decryptDst, blockSize, ret = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { diff --git a/libclamav/others.c b/libclamav/others.c index 375245bc7c..21d0361fca 100644 --- a/libclamav/others.c +++ b/libclamav/others.c @@ -539,7 +539,7 @@ struct cl_engine *cl_engine_new(void) } /* Set up default stats/intel gathering callbacks */ - intel = cli_calloc(1, sizeof(cli_intel_t)); + intel = cli_max_calloc(1, sizeof(cli_intel_t)); if ((intel)) { #ifdef CL_THREAD_SAFE if (pthread_mutex_init(&(intel->mutex), NULL)) { @@ -1279,7 +1279,7 @@ char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type) cl_finish_hash(ctx, digest); - if (!(hashstr = (char *)cli_calloc(size * 2 + 1, sizeof(char)))) + if (!(hashstr = (char *)cli_max_calloc(size * 2 + 1, sizeof(char)))) return NULL; pt = hashstr; @@ -1696,7 +1696,7 @@ int cli_rmdirs(const char *name) if (strcmp(dent->d_name, "..") == 0) continue; - path = cli_malloc(strlen(name) + strlen(dent->d_name) + 2); + path = cli_max_malloc(strlen(name) + strlen(dent->d_name) + 2); if (path == NULL) { cli_errmsg("cli_rmdirs: Unable to allocate memory for path %u\n", strlen(name) + strlen(dent->d_name) + 2); @@ -1742,7 +1742,7 @@ int cli_rmdirs(const char *dirname) while ((dent = readdir(dd))) { if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) { - path = cli_malloc(strlen(dirname) + strlen(dent->d_name) + 2); + path = cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (!path) { cli_errmsg("cli_rmdirs: Unable to allocate memory for path %llu\n", (long long unsigned)(strlen(dirname) + strlen(dent->d_name) + 2)); closedir(dd); @@ -1820,7 +1820,7 @@ bitset_t *cli_bitset_init(void) return NULL; } bs->length = BITSET_DEFAULT_SIZE; - bs->bitset = cli_calloc(BITSET_DEFAULT_SIZE, 1); + bs->bitset = cli_max_calloc(BITSET_DEFAULT_SIZE, 1); if (!bs->bitset) { cli_errmsg("cli_bitset_init: Unable to allocate memory for bs->bitset %u\n", BITSET_DEFAULT_SIZE); free(bs); @@ -1846,7 +1846,7 @@ static bitset_t *bitset_realloc(bitset_t *bs, unsigned long min_size) unsigned char *new_bitset; new_length = nearest_power(min_size); - new_bitset = (unsigned char *)cli_realloc(bs->bitset, new_length); + new_bitset = (unsigned char *)cli_max_realloc(bs->bitset, new_length); if (!new_bitset) { return NULL; } diff --git a/libclamav/others.h b/libclamav/others.h index 28deb94f3b..5874b119a9 100644 --- a/libclamav/others.h +++ b/libclamav/others.h @@ -938,13 +938,32 @@ static inline int cli_getpagesize(void) #endif /* HAVE_SYSCONF_SC_PAGESIZE */ #endif /* _WIN32 */ -void *cli_malloc(size_t nmemb); -void *cli_calloc(size_t nmemb, size_t size); +/** + * @brief Wrapper around malloc that limits how much may be allocated to CLI_MAX_ALLOCATION. + * + * Please use CLI_MAX_MALLOC() with `goto done;` error handling instead. + * + * @param ptr + * @param size + * @return void* + */ +void *cli_max_malloc(size_t nmemb); + +/** + * @brief Wrapper around Calloc that limits how much may be allocated to CLI_MAX_ALLOCATION. + * + * Please use CLI_MAX_CALLOC() with `goto done;` error handling instead. + * + * @param ptr + * @param size + * @return void* + */ +void *cli_max_calloc(size_t nmemb, size_t size); /** * @brief Wrapper around realloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_REALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * @@ -952,23 +971,52 @@ void *cli_calloc(size_t nmemb, size_t size); * @param size * @return void* */ -void *cli_realloc(void *ptr, size_t size); +void *cli_max_realloc(void *ptr, size_t size); /** * @brief Wrapper around realloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_REALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * - * WARNING: This differs from cli_realloc() in that it will free the ptr if the allocation fails. + * WARNING: This differs from cli_max_realloc() in that it will free the ptr if the allocation fails. * If you're using `goto done;` error handling, this may result in a double-free!! * * @param ptr * @param size * @return void* */ -void *cli_realloc2(void *ptr, size_t size); +void *cli_max_realloc2(void *ptr, size_t size); + +/** + * @brief Wrapper around realloc that, unlike some variants of realloc, will not free the ptr if size==0. + * + * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. + * + * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. + * + * @param ptr + * @param size + * @return void* + */ +void *cli_safer_realloc(void *ptr, size_t size); + +/** + * @brief Wrapper around realloc that, unlike some variants of realloc, will not free the ptr if size==0. + * + * Please use CLI_SAFER_REALLOC() with `goto done;` error handling instead. + * + * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. + * + * WARNING: This differs from cli_safer_realloc() in that it will free the ptr if the allocation fails. + * If you're using `goto done;` error handling, this may result in a double-free!! + * + * @param ptr + * @param size + * @return void* + */ +void *cli_safer_realloc2(void *ptr, size_t size); char *cli_strdup(const char *s); int cli_rmdirs(const char *dirname); @@ -1292,10 +1340,10 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); } while (0) #endif -#ifndef CLI_MALLOC -#define CLI_MALLOC(var, size, ...) \ +#ifndef CLI_MAX_MALLOC +#define CLI_MAX_MALLOC(var, size, ...) \ do { \ - var = cli_malloc(size); \ + var = cli_max_malloc(size); \ if (NULL == var) { \ do { \ __VA_ARGS__; \ @@ -1318,10 +1366,10 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); } while (0) #endif -#ifndef CLI_CALLOC -#define CLI_CALLOC(var, nmemb, size, ...) \ +#ifndef CLI_MAX_CALLOC +#define CLI_MAX_CALLOC(var, nmemb, size, ...) \ do { \ - (var) = cli_calloc(nmemb, size); \ + (var) = cli_max_calloc(nmemb, size); \ if (NULL == var) { \ do { \ __VA_ARGS__; \ @@ -1348,23 +1396,48 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * - * NOTE: cli_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. + * NOTE: cli_max_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. + * + * @param ptr + * @param size + * @return void* + */ +#ifndef CLI_MAX_REALLOC +#define CLI_MAX_REALLOC(ptr, size, ...) \ + do { \ + void *vTmp = cli_max_realloc(ptr, size); \ + if (NULL == vTmp) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ + ptr = vTmp; \ + } while (0) +#endif + +/** + * @brief Wrapper around realloc that, unlike some variants of realloc, will not free the ptr if size==0. + * + * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. + * + * NOTE: cli_safer_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. * * @param ptr * @param size * @return void* */ -#ifndef CLI_REALLOC -#define CLI_REALLOC(ptr, size, ...) \ - do { \ - void *vTmp = cli_realloc(ptr, size); \ - if (NULL == vTmp) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ - ptr = vTmp; \ +#ifndef CLI_SAFER_REALLOC +#define CLI_SAFER_REALLOC(ptr, size, ...) \ + do { \ + void *vTmp = cli_safer_realloc(ptr, size); \ + if (NULL == vTmp) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ + ptr = vTmp; \ } while (0) #endif diff --git a/libclamav/others_common.c b/libclamav/others_common.c index 4ae751f8a0..e60858b27a 100644 --- a/libclamav/others_common.c +++ b/libclamav/others_common.c @@ -216,12 +216,12 @@ int cli_matchregex(const char *str, const char *regex) return 0; } -void *cli_malloc(size_t size) +void *cli_max_malloc(size_t size) { void *alloc; - if (!size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_malloc(): File or section is too large to scan (%zu bytes). \ + if (0 == size || size > CLI_MAX_ALLOCATION) { + cli_warnmsg("cli_max_malloc(): File or section is too large to scan (%zu bytes). \ For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; @@ -231,18 +231,19 @@ void *cli_malloc(size_t size) if (!alloc) { perror("malloc_problem"); - cli_errmsg("cli_malloc(): Can't allocate memory (%zu bytes).\n", size); + cli_errmsg("cli_max_malloc(): Can't allocate memory (%zu bytes).\n", size); return NULL; - } else + } else { return alloc; + } } -void *cli_calloc(size_t nmemb, size_t size) +void *cli_max_calloc(size_t nmemb, size_t size) { void *alloc; - if (!nmemb || !size || size > CLI_MAX_ALLOCATION || nmemb > CLI_MAX_ALLOCATION || (nmemb * size > CLI_MAX_ALLOCATION)) { - cli_warnmsg("cli_calloc2(): File or section is too large to scan (%zu bytes). \ + if (!nmemb || 0 == size || size > CLI_MAX_ALLOCATION || nmemb > CLI_MAX_ALLOCATION || (nmemb * size > CLI_MAX_ALLOCATION)) { + cli_warnmsg("cli_max_calloc(): File or section is too large to scan (%zu bytes). \ For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; @@ -252,18 +253,65 @@ void *cli_calloc(size_t nmemb, size_t size) if (!alloc) { perror("calloc_problem"); - cli_errmsg("cli_calloc(): Can't allocate memory (%zu bytes).\n", (nmemb * size)); + cli_errmsg("cli_max_calloc(): Can't allocate memory (%lu bytes).\n", (unsigned long int)(nmemb * size)); + return NULL; + } else { + return alloc; + } +} + +void *cli_safer_realloc(void *ptr, size_t size) +{ + void *alloc; + + if (0 == size) { + cli_errmsg("cli_max_realloc(): Attempt to allocate 0 bytes. Please report to https://github.com/Cisco-Talos/clamav/issues\n"); + return NULL; + } + + alloc = realloc(ptr, size); + + if (!alloc) { + perror("realloc_problem"); + cli_errmsg("cli_max_realloc(): Can't re-allocate memory to %lu bytes.\n", (unsigned long int)size); return NULL; - } else + } else { return alloc; + } } -void *cli_realloc(void *ptr, size_t size) +void *cli_safer_realloc2(void *ptr, size_t size) { void *alloc; - if (!size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_realloc(): File or section is too large to scan (%zu bytes). \ + if (0 == size) { + cli_errmsg("cli_max_realloc2(): Attempt to allocate 0 bytes. Please report to https://github.com/Cisco-Talos/clamav/issues\n"); + return NULL; + } + + alloc = realloc(ptr, size); + + if (!alloc) { + perror("realloc_problem"); + cli_errmsg("cli_max_realloc2(): Can't re-allocate memory to %lu bytes.\n", (unsigned long int)size); + + // free the original pointer + if (ptr) { + free(ptr); + } + + return NULL; + } else { + return alloc; + } +} + +void *cli_max_realloc(void *ptr, size_t size) +{ + void *alloc; + + if (0 == size || size > CLI_MAX_ALLOCATION) { + cli_warnmsg("cli_max_realloc(): File or section is too large to scan (%zu bytes). \ For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; @@ -273,18 +321,19 @@ void *cli_realloc(void *ptr, size_t size) if (!alloc) { perror("realloc_problem"); - cli_errmsg("cli_realloc(): Can't re-allocate memory to %zu bytes.\n", size); + cli_errmsg("cli_max_realloc(): Can't re-allocate memory to %zu bytes.\n", size); return NULL; - } else + } else { return alloc; + } } -void *cli_realloc2(void *ptr, size_t size) +void *cli_max_realloc2(void *ptr, size_t size) { void *alloc; - if (!size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_realloc2(): File or section is too large to scan (%zu bytes). \ + if (0 == size || size > CLI_MAX_ALLOCATION) { + cli_warnmsg("cli_max_realloc2(): File or section is too large to scan (%zu bytes). \ For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; @@ -294,12 +343,17 @@ void *cli_realloc2(void *ptr, size_t size) if (!alloc) { perror("realloc_problem"); - cli_errmsg("cli_realloc2(): Can't re-allocate memory to %zu bytes.\n", size); - if (ptr) + cli_errmsg("cli_max_realloc2(): Can't re-allocate memory to %zu bytes.\n", size); + + // free the original pointer + if (ptr) { free(ptr); + } + return NULL; - } else + } else { return alloc; + } } char *cli_strdup(const char *s) @@ -826,7 +880,7 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ #else ft = ft_unknown; #endif - fname = (char *)cli_malloc(strlen(dirname) + strlen(dent->d_name) + 2); + fname = (char *)cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (!fname) { ret = callback(NULL, NULL, dirname, error_mem, data); if (ret != CL_SUCCESS) @@ -873,7 +927,7 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ } entries_cnt++; - entries = cli_realloc(entries, entries_cnt * sizeof(*entries)); + entries = cli_max_realloc(entries, entries_cnt * sizeof(*entries)); if (!entries) { ret = callback(stated ? &statbuf : NULL, NULL, fname, error_mem, data); free(fname); @@ -954,7 +1008,7 @@ static char *cli_md5buff(const unsigned char *buffer, unsigned int len, unsigned if (dig) memcpy(dig, digest, 16); - if (!(md5str = (char *)cli_calloc(32 + 1, sizeof(char)))) + if (!(md5str = (char *)cli_max_calloc(32 + 1, sizeof(char)))) return NULL; pt = md5str; @@ -993,7 +1047,7 @@ char *cli_sanitize_filepath(const char *filepath, size_t filepath_len, char **sa *sanitized_filebase = NULL; } - sanitized_filepath = cli_calloc(filepath_len + 1, sizeof(unsigned char)); + sanitized_filepath = cli_max_calloc(filepath_len + 1, sizeof(unsigned char)); if (NULL == sanitized_filepath) { cli_dbgmsg("cli_sanitize_filepath: out of memory\n"); goto done; @@ -1146,7 +1200,7 @@ char *cli_genfname(const char *prefix) len = strlen("clamav-") + 48 + strlen(".tmp") + 1; /* clamav-{48}.tmp\0 */ } - fname = (char *)cli_calloc(len, sizeof(char)); + fname = (char *)cli_max_calloc(len, sizeof(char)); if (!fname) { cli_dbgmsg("cli_genfname: no memory left for fname\n"); if (NULL != sanitized_prefix) { @@ -1207,7 +1261,7 @@ char *cli_newfilepath(const char *dir, const char *fname) } len = strlen(mdir) + strlen(PATHSEP) + strlen(fname) + 1; /* mdir/fname\0 */ - fullpath = (char *)cli_calloc(len, sizeof(char)); + fullpath = (char *)cli_max_calloc(len, sizeof(char)); if (NULL == fullpath) { cli_dbgmsg("cli_newfilepath('%s'): out of memory\n", mdir); return NULL; @@ -1262,7 +1316,7 @@ char *cli_gentemp_with_prefix(const char *dir, const char *prefix) } len = strlen(mdir) + strlen(PATHSEP) + strlen(fname) + 1; /* mdir/fname\0 */ - fullpath = (char *)cli_calloc(len, sizeof(char)); + fullpath = (char *)cli_max_calloc(len, sizeof(char)); if (!fullpath) { free(fname); cli_dbgmsg("cli_gentemp_with_prefix('%s'): out of memory\n", mdir); diff --git a/libclamav/pdf.c b/libclamav/pdf.c index 3f39fb84ce..9f4f46badd 100644 --- a/libclamav/pdf.c +++ b/libclamav/pdf.c @@ -480,9 +480,9 @@ int pdf_findobj_in_objstm(struct pdf_struct *pdf, struct objstm_struct *objstm, /* Success! Add the object to the list of all objects found. */ pdf->nobjs++; - CLI_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, - cli_warnmsg("pdf_findobj_in_objstm: out of memory finding objects in stream\n"), - status = CL_EMEM); + CLI_MAX_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, + cli_warnmsg("pdf_findobj_in_objstm: out of memory finding objects in stream\n"), + status = CL_EMEM); pdf->objs[pdf->nobjs - 1] = obj; *obj_found = obj; @@ -545,7 +545,7 @@ cl_error_t pdf_findobj(struct pdf_struct *pdf) goto done; } pdf->nobjs++; - CLI_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, status = CL_EMEM); + CLI_MAX_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, status = CL_EMEM); obj = malloc(sizeof(struct pdf_obj)); if (!obj) { @@ -1238,7 +1238,7 @@ char *decrypt_any(struct pdf_struct *pdf, uint32_t id, const char *in, size_t *l if (enc_method == ENC_AESV2) n += 4; - key = cli_malloc(n); + key = cli_max_malloc(n); if (!key) { noisy_warnmsg("decrypt_any: malloc failed\n"); return NULL; @@ -1261,7 +1261,7 @@ char *decrypt_any(struct pdf_struct *pdf, uint32_t id, const char *in, size_t *l if (n > 16) n = 16; - q = cli_calloc(*length, sizeof(char)); + q = cli_max_calloc(*length, sizeof(char)); if (!q) { noisy_warnmsg("decrypt_any: malloc failed\n"); return NULL; @@ -1627,7 +1627,7 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t } else { /* Add objstm to pdf struct, so it can be freed eventually */ pdf->nobjstms++; - pdf->objstms = cli_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); + pdf->objstms = cli_max_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); if (!pdf->objstms) { cli_warnmsg("pdf_extract_obj: out of memory parsing object stream (%u)\n", pdf->nobjstms); pdf_free_dict(dparams); @@ -1692,7 +1692,7 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t free(pdf->objstms); pdf->objstms = NULL; } else { - pdf->objstms = cli_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); + pdf->objstms = cli_max_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); if (!pdf->objstms) { cli_warnmsg("pdf_extract_obj: out of memory when shrinking down objstm array\n"); @@ -2620,7 +2620,7 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * q--; len = q - start; - s0 = s = cli_malloc(len + 1); + s0 = s = cli_max_malloc(len + 1); if (!s) { cli_errmsg("pdf_readstring: Unable to allocate buffer\n"); return NULL; @@ -2713,7 +2713,7 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * if (qend) *qend = q; - s = cli_malloc((q - start) / 2 + 1); + s = cli_max_malloc((q - start) / 2 + 1); if (s == NULL) { /* oops, couldn't allocate memory */ cli_dbgmsg("pdf_readstring: unable to allocate memory...\n"); return NULL; @@ -2769,7 +2769,7 @@ static char *pdf_readval(const char *q, int len, const char *key) len++; } - s = cli_malloc(end - q + 1); + s = cli_max_malloc(end - q + 1); if (!s) return NULL; @@ -2976,7 +2976,7 @@ static void check_owner_password(struct pdf_struct *pdf, int R, noisy_warnmsg("check_owner_password: OE length is not 32: %zu\n", OE_len); } else { pdf->keylen = 32; - pdf->key = cli_malloc(pdf->keylen); + pdf->key = cli_max_malloc(pdf->keylen); if (!pdf->key) { cli_errmsg("check_owner_password: Cannot allocate memory for pdf->key\n"); goto done; @@ -3063,7 +3063,7 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, length = 40; pdf->keylen = length / 8; - pdf->key = cli_malloc(pdf->keylen); + pdf->key = cli_max_malloc(pdf->keylen); if (!pdf->key) goto done; @@ -3141,7 +3141,7 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, noisy_warnmsg("check_user_password: UE length is not 32: %zu\n", UE_len); } else { pdf->keylen = 32; - pdf->key = cli_malloc(pdf->keylen); + pdf->key = cli_max_malloc(pdf->keylen); if (!pdf->key) { cli_errmsg("check_user_password: Cannot allocate memory for pdf->key\n"); goto done; @@ -3203,7 +3203,7 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, noisy_warnmsg("check_user_password: UE length is not 32: %zu\n", UE_len); } else { pdf->keylen = 32; - pdf->key = cli_malloc(pdf->keylen); + pdf->key = cli_max_malloc(pdf->keylen); if (!pdf->key) { cli_errmsg("check_user_password: Cannot allocate memory for pdf->key\n"); goto done; @@ -3760,7 +3760,7 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) begin = (char *)(pdfver + 5); end = begin + 2; strtoul(end, &end, 10); - p1 = cli_calloc((end - begin) + 2, 1); + p1 = cli_max_calloc((end - begin) + 2, 1); if (p1) { strncpy(p1, begin, end - begin); p1[end - begin] = '\0'; diff --git a/libclamav/pdfdecode.c b/libclamav/pdfdecode.c index e1703c8bd6..0e2f4592e2 100644 --- a/libclamav/pdfdecode.c +++ b/libclamav/pdfdecode.c @@ -147,7 +147,7 @@ size_t pdf_decodestream( token->success = 0; - token->content = cli_malloc(streamlen); + token->content = cli_max_malloc(streamlen); if (!token->content) { *status = CL_EMEM; goto done; @@ -406,7 +406,7 @@ static cl_error_t filter_ascii85decode(struct pdf_struct *pdf, struct pdf_obj *o uint64_t sum = 0; /* 5:4 decoding ratio, with 1:4 expansion sequences => (4*length)+1 */ - if (!(dptr = decoded = (uint8_t *)cli_malloc((4 * remaining) + 1))) { + if (!(dptr = decoded = (uint8_t *)cli_max_malloc((4 * remaining) + 1))) { cli_errmsg("cli_pdf: cannot allocate memory for decoded output\n"); return CL_EMEM; } @@ -531,7 +531,7 @@ static cl_error_t filter_rldecode(struct pdf_struct *pdf, struct pdf_obj *obj, s if ((rc = cli_checklimits("pdf", pdf->ctx, capacity + INFLATE_CHUNK_SIZE, 0, 0)) != CL_SUCCESS) break; - if (!(temp = cli_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { + if (!(temp = cli_max_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; break; @@ -557,7 +557,7 @@ static cl_error_t filter_rldecode(struct pdf_struct *pdf, struct pdf_obj *obj, s break; } - if (!(temp = cli_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { + if (!(temp = cli_max_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; break; @@ -581,7 +581,7 @@ static cl_error_t filter_rldecode(struct pdf_struct *pdf, struct pdf_obj *obj, s if (declen == 0) { cli_dbgmsg("cli_pdf: empty stream after inflation completed.\n"); rc = CL_BREAK; - } else if (!(temp = cli_realloc(decoded, declen))) { + } else if (!(temp = cli_max_realloc(decoded, declen))) { /* Shrink output buffer to final the decoded data length to minimize RAM usage */ cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; @@ -704,7 +704,7 @@ static cl_error_t filter_flatedecode(struct pdf_struct *pdf, struct pdf_obj *obj break; } - if (!(temp = cli_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { + if (!(temp = cli_max_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; break; @@ -763,7 +763,7 @@ static cl_error_t filter_flatedecode(struct pdf_struct *pdf, struct pdf_obj *obj if (declen == 0) { cli_dbgmsg("cli_pdf: empty stream after inflation completed.\n"); rc = CL_BREAK; - } else if (!(temp = cli_realloc(decoded, declen))) { + } else if (!(temp = cli_max_realloc(decoded, declen))) { /* Shrink output buffer to final the decoded data length to minimize RAM usage */ cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; @@ -795,7 +795,7 @@ static cl_error_t filter_asciihexdecode(struct pdf_struct *pdf, struct pdf_obj * uint32_t i, j; cl_error_t rc = CL_SUCCESS; - if (!(decoded = (uint8_t *)cli_calloc(length / 2 + 1, sizeof(uint8_t)))) { + if (!(decoded = (uint8_t *)cli_max_calloc(length / 2 + 1, sizeof(uint8_t)))) { cli_errmsg("cli_pdf: cannot allocate memory for decoded output\n"); return CL_EMEM; } @@ -988,7 +988,7 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, break; } - if (!(temp = cli_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { + if (!(temp = cli_max_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; break; @@ -1048,7 +1048,7 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, if (declen == 0) { cli_dbgmsg("cli_pdf: empty stream after inflation completed.\n"); rc = CL_BREAK; - } else if (!(temp = cli_realloc(decoded, declen))) { + } else if (!(temp = cli_max_realloc(decoded, declen))) { /* Shrink output buffer to final the decoded data length to minimize RAM usage */ cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); rc = CL_EMEM; diff --git a/libclamav/pdfng.c b/libclamav/pdfng.c index 43204c589b..8aae0b1ce3 100644 --- a/libclamav/pdfng.c +++ b/libclamav/pdfng.c @@ -86,7 +86,7 @@ char *pdf_convert_utf(char *begin, size_t sz) iconv_t cd; #endif - buf = cli_calloc(1, sz + 1); + buf = cli_max_calloc(1, sz + 1); if (!(buf)) return NULL; memcpy(buf, begin, sz); @@ -94,7 +94,7 @@ char *pdf_convert_utf(char *begin, size_t sz) #if HAVE_ICONV p1 = buf; - p2 = outbuf = cli_calloc(1, sz + 1); + p2 = outbuf = cli_max_calloc(1, sz + 1); if (!(outbuf)) { free(buf); return NULL; @@ -268,10 +268,7 @@ static char *pdf_decrypt_string(struct pdf_struct *pdf, struct pdf_obj *obj, con bin_length = *length / 2; // Convert the hex string to binary - decoded_bin = cli_calloc(1, bin_length); - if (!decoded_bin) { - return NULL; - } + CLI_MAX_CALLOC(decoded_bin, 1, bin_length); hex2str_ret = cli_hex2str_to(hex, decoded_bin, *length); if (hex2str_ret != 0) { @@ -314,7 +311,7 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha return NULL; /* get a working copy */ - wrkstr = cli_calloc(len + 1, sizeof(char)); + wrkstr = cli_max_calloc(len + 1, sizeof(char)); if (!wrkstr) return NULL; memcpy(wrkstr, in, len); @@ -324,7 +321,7 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha /* convert PDF specific escape sequences, like octal sequences */ /* TODO: replace the escape sequences directly in the wrkstr */ if (strchr(wrkstr, '\\')) { - output = cli_calloc(wrklen + 1, sizeof(char)); + output = cli_max_calloc(wrklen + 1, sizeof(char)); if (!output) { free(wrkstr); return NULL; @@ -386,7 +383,7 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha } free(wrkstr); - wrkstr = cli_calloc(outlen + 1, sizeof(char)); + wrkstr = cli_max_calloc(outlen + 1, sizeof(char)); if (!wrkstr) { free(output); return NULL; @@ -405,7 +402,7 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha outlen = tmpsz; free(wrkstr); if (output) { - wrkstr = cli_calloc(outlen + 1, sizeof(char)); + wrkstr = cli_max_calloc(outlen + 1, sizeof(char)); if (!wrkstr) { free(output); return NULL; @@ -599,7 +596,7 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * default: res = pdf_finalize_string(pdf, obj, begin, objsize2); if (!res) { - res = cli_calloc(1, objsize2 + 1); + res = cli_max_calloc(1, objsize2 + 1); if (!(res)) { close(fd); cli_unlink(newobj->path); @@ -649,7 +646,7 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * res = pdf_finalize_string(pdf, obj, p1, (p2 - p1) + 1); if (!res) { - res = cli_calloc(1, (p2 - p1) + 2); + res = cli_max_calloc(1, (p2 - p1) + 2); if (!(res)) return NULL; memcpy(res, p1, (p2 - p1) + 1); @@ -706,7 +703,7 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * res = pdf_finalize_string(pdf, obj, p1, len); if (!res) { - res = cli_calloc(1, len + 1); + res = cli_max_calloc(1, len + 1); if (!(res)) return NULL; memcpy(res, p1, len); @@ -859,7 +856,7 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz if (p1 == end) break; - key = cli_calloc((p1 - begin) + 2, 1); + key = cli_max_calloc((p1 - begin) + 2, 1); if (!(key)) break; @@ -938,7 +935,7 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz is_object_reference(begin, &p1, NULL); - val = cli_calloc((p1 - begin) + 2, 1); + val = cli_max_calloc((p1 - begin) + 2, 1); if (!(val)) break; @@ -1126,7 +1123,7 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s p1++; } - val = cli_calloc((p1 - begin) + 2, 1); + val = cli_max_calloc((p1 - begin) + 2, 1); if (!(val)) break; diff --git a/libclamav/pe.c b/libclamav/pe.c index beaac64af5..dae6c89aff 100644 --- a/libclamav/pe.c +++ b/libclamav/pe.c @@ -2297,7 +2297,7 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str break; \ } \ \ - fname = cli_calloc(funclen + dlllen + 3, sizeof(char)); \ + fname = cli_max_calloc(funclen + dlllen + 3, sizeof(char)); \ if (fname == NULL) { \ cli_dbgmsg("scan_pe: cannot allocate memory for imphash string\n"); \ ret = CL_EMEM; \ @@ -3218,7 +3218,7 @@ int cli_scanpe(cli_ctx *ctx) if (xsjs == 1280) break; - if (!(jumps = (uint32_t *)cli_realloc2(jumps, (xsjs + 128) * sizeof(uint32_t)))) { + if (!(jumps = (uint32_t *)cli_max_realloc2(jumps, (xsjs + 128) * sizeof(uint32_t)))) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -3373,7 +3373,7 @@ int cli_scanpe(cli_ctx *ctx) } /* allocate needed buffer */ - if (!(src = cli_calloc(ssize + dsize, sizeof(char)))) { + if (!(src = cli_max_calloc(ssize + dsize, sizeof(char)))) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -3489,7 +3489,7 @@ int cli_scanpe(cli_ctx *ctx) break; } - if ((dest = (char *)cli_calloc(dsize, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize, sizeof(char))) == NULL) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -3591,7 +3591,7 @@ int cli_scanpe(cli_ctx *ctx) newedx = cli_readint32(newebx + 12 - peinfo->sections[i + 1].rva + src) - EC32(peinfo->pe_opt.opt32.ImageBase); cli_dbgmsg("cli_scanpe: FSG: found old EP @%x\n", newedx); - if ((dest = (char *)cli_calloc(dsize, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize, sizeof(char))) == NULL) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -3677,7 +3677,7 @@ int cli_scanpe(cli_ctx *ctx) break; } - if ((sections = (struct cli_exe_section *)cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { + if ((sections = (struct cli_exe_section *)cli_max_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { cli_errmsg("cli_scanpe: FSG: Unable to allocate memory for sections %llu\n", (long long unsigned)((sectcnt + 1) * sizeof(struct cli_exe_section))); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -3694,7 +3694,7 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if ((dest = (char *)cli_calloc(dsize, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize, sizeof(char))) == NULL) { cli_exe_info_destroy(peinfo); free(sections); return CL_EMEM; @@ -3779,7 +3779,7 @@ int cli_scanpe(cli_ctx *ctx) if (t >= gp - 10 || cli_readint32(support + t + 6) != 2) break; - if ((sections = (struct cli_exe_section *)cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { + if ((sections = (struct cli_exe_section *)cli_max_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { cli_errmsg("cli_scanpe: FSG: Unable to allocate memory for sections %llu\n", (long long unsigned)((sectcnt + 1) * sizeof(struct cli_exe_section))); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -3796,7 +3796,7 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if ((dest = (char *)cli_calloc(dsize, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize, sizeof(char))) == NULL) { cli_exe_info_destroy(peinfo); free(sections); return CL_EMEM; @@ -3842,7 +3842,7 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if ((dest = (char *)cli_calloc(dsize + 8192, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize + 8192, sizeof(char))) == NULL) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -4021,7 +4021,7 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPSIZELIMITS("cli_scanpe: Petite", dsize); - if ((dest = (char *)cli_calloc(dsize, sizeof(char))) == NULL) { + if ((dest = (char *)cli_max_calloc(dsize, sizeof(char))) == NULL) { cli_dbgmsg("cli_scanpe: Petite: Can't allocate %d bytes\n", dsize); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -4073,7 +4073,7 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPSIZELIMITS("cli_scanpe: PEspin", fsize); - if ((spinned = (char *)cli_malloc(fsize)) == NULL) { + if ((spinned = (char *)cli_max_malloc(fsize)) == NULL) { cli_errmsg("cli_scanpe: PESping: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -4142,7 +4142,7 @@ int cli_scanpe(cli_ctx *ctx) size_t num_alerts; char *spinned; - if ((spinned = (char *)cli_malloc(fsize)) == NULL) { + if ((spinned = (char *)cli_max_malloc(fsize)) == NULL) { cli_errmsg("cli_scanpe: yC: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -4207,7 +4207,7 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPSIZELIMITS("cli_scanpe: WWPack", ssize); - if (!(src = (char *)cli_calloc(ssize, sizeof(char)))) { + if (!(src = (char *)cli_max_calloc(ssize, sizeof(char)))) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -4236,7 +4236,7 @@ int cli_scanpe(cli_ctx *ctx) break; } - if ((packer = (uint8_t *)cli_calloc(peinfo->sections[peinfo->nsections - 1].rsz, sizeof(char))) == NULL) { + if ((packer = (uint8_t *)cli_max_calloc(peinfo->sections[peinfo->nsections - 1].rsz, sizeof(char))) == NULL) { free(src); cli_exe_info_destroy(peinfo); return CL_EMEM; @@ -4291,7 +4291,7 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPSIZELIMITS("cli_scanpe: Aspack", ssize); - if (!(src = (char *)cli_calloc(ssize, sizeof(char)))) { + if (!(src = (char *)cli_max_calloc(ssize, sizeof(char)))) { cli_exe_info_destroy(peinfo); return CL_EMEM; } @@ -4369,7 +4369,7 @@ int cli_scanpe(cli_ctx *ctx) if (!ssize || !dsize || dsize != peinfo->sections[0].vsz) break; - if (!(dest = cli_malloc(dsize))) { + if (!(dest = cli_max_malloc(dsize))) { cli_errmsg("cli_scanpe: NsPack: Unable to allocate memory for dest %u\n", dsize); break; } @@ -5098,14 +5098,14 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, // TODO in cli_checkpe_fp this aligned to falign, elsewhere it aligned to salign peinfo->hdr_size = PESALIGN(peinfo->hdr_size, salign); - peinfo->sections = (struct cli_exe_section *)cli_calloc(peinfo->nsections, sizeof(struct cli_exe_section)); + peinfo->sections = (struct cli_exe_section *)cli_max_calloc(peinfo->nsections, sizeof(struct cli_exe_section)); if (!peinfo->sections) { cli_dbgmsg("cli_peheader: Can't allocate memory for section headers\n"); goto done; } - section_hdrs = (struct pe_image_section_hdr *)cli_calloc(peinfo->nsections, sizeof(struct pe_image_section_hdr)); + section_hdrs = (struct pe_image_section_hdr *)cli_max_calloc(peinfo->nsections, sizeof(struct pe_image_section_hdr)); if (!section_hdrs) { cli_dbgmsg("cli_peheader: Can't allocate memory for section headers\n"); @@ -5849,29 +5849,29 @@ cl_error_t cli_genhash_pe(cli_ctx *ctx, unsigned int class, int type, stats_sect case 1: genhash[CLI_HASH_MD5] = 1; hlen = hashlen[CLI_HASH_MD5]; - hash = hashset[CLI_HASH_MD5] = cli_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_MD5] = cli_max_calloc(hlen, sizeof(char)); break; case 2: genhash[CLI_HASH_SHA1] = 1; hlen = hashlen[CLI_HASH_SHA1]; - hash = hashset[CLI_HASH_SHA1] = cli_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_SHA1] = cli_max_calloc(hlen, sizeof(char)); break; default: genhash[CLI_HASH_SHA256] = 1; hlen = hashlen[CLI_HASH_SHA256]; - hash = hashset[CLI_HASH_SHA256] = cli_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_SHA256] = cli_max_calloc(hlen, sizeof(char)); break; } if (!hash) { - cli_errmsg("cli_genhash_pe: cli_calloc failed!\n"); + cli_errmsg("cli_genhash_pe: cli_max_calloc failed!\n"); cli_exe_info_destroy(peinfo); return CL_EMEM; } if (hashes) { hashes->nsections = peinfo->nsections; - hashes->sections = cli_calloc(peinfo->nsections, sizeof(struct cli_section_hash)); + hashes->sections = cli_max_calloc(peinfo->nsections, sizeof(struct cli_section_hash)); if (!(hashes->sections)) { cli_exe_info_destroy(peinfo); diff --git a/libclamav/pe_icons.c b/libclamav/pe_icons.c index dba41124ca..5feb7b97cd 100644 --- a/libclamav/pe_icons.c +++ b/libclamav/pe_icons.c @@ -901,7 +901,7 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr unsigned int edge_avg[6], edge_x[6] = {0, 0, 0, 0, 0, 0}, edge_y[6] = {0, 0, 0, 0, 0, 0}, noedge_avg[6], noedge_x[6] = {0, 0, 0, 0, 0, 0}, noedge_y[6] = {0, 0, 0, 0, 0, 0}; double *sobel; - if (!(tmp = cli_malloc(side * side * 4 * 2))) { + if (!(tmp = cli_max_malloc(side * side * 4 * 2))) { cli_errmsg("getmetrics: Unable to allocate memory for tmp %u\n", (side * side * 4 * 2)); return CL_EMEM; } @@ -1067,7 +1067,7 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr /* Sobel 1 - gradients */ i = 0; #ifdef USE_FLOATS - sobel = cli_malloc(side * side * sizeof(double)); + sobel = cli_max_malloc(side * side * sizeof(double)); if (!sobel) { cli_errmsg("getmetrics: Unable to allocate memory for edge detection %llu\n", (long long unsigned)(side * side * sizeof(double))); free(tmp); @@ -1457,7 +1457,7 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) fmap_unneed_ptr(map, palette, (1 << depth) * sizeof(int)); return CL_SUCCESS; } - if (!(imagedata = cli_malloc(width * height * sizeof(*imagedata)))) { + if (!(imagedata = cli_max_malloc(width * height * sizeof(*imagedata)))) { if (palette) fmap_unneed_ptr(map, palette, (1 << depth) * sizeof(int)); return CL_SUCCESS; @@ -1601,7 +1601,7 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) newsize = 16; scalex = (double)width / newsize; scaley = (double)height / newsize; - if (!(newdata = cli_malloc(newsize * newsize * sizeof(*newdata)))) { + if (!(newdata = cli_max_malloc(newsize * newsize * sizeof(*newdata)))) { cli_errmsg("parseicon: Unable to allocate memory for scaling image\n"); return CL_EMEM; } diff --git a/libclamav/petite.c b/libclamav/petite.c index abdd0ca920..9fa5fc2e3d 100644 --- a/libclamav/petite.c +++ b/libclamav/petite.c @@ -299,7 +299,7 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli return 1; } /* Alloc 1 more struct */ - if (!(tmpsct = cli_realloc(usects, sizeof(struct cli_exe_section) * (j + 1)))) { + if (!(tmpsct = cli_max_realloc(usects, sizeof(struct cli_exe_section) * (j + 1)))) { if (usects) free(usects); return 1; diff --git a/libclamav/phishcheck.c b/libclamav/phishcheck.c index 6dd425cb57..eb81aed7b8 100644 --- a/libclamav/phishcheck.c +++ b/libclamav/phishcheck.c @@ -260,7 +260,7 @@ static void string_init_c(struct string* dest, char* data) static int string_assign_concatenated(struct string* dest, const char* prefix, const char* begin, const char* end) { const size_t prefix_len = strlen(prefix); - char* ret = cli_malloc(prefix_len + end - begin + 1); + char* ret = cli_max_malloc(prefix_len + end - begin + 1); if (!ret) { cli_errmsg("Phishcheck: Unable to allocate memory for string_assign_concatenated\n"); return CL_EMEM; @@ -276,7 +276,7 @@ static int string_assign_concatenated(struct string* dest, const char* prefix, c /* make a copy of the string between start -> end*/ static int string_assign_dup(struct string* dest, const char* start, const char* end) { - char* ret = cli_malloc(end - start + 1); + char* ret = cli_max_malloc(end - start + 1); if (!ret) { cli_errmsg("Phishcheck: Unable to allocate memory for string_assign_dup\n"); return CL_EMEM; @@ -324,7 +324,7 @@ static int build_regex(regex_t* preg, const char* regex, int nosub) if (rc) { size_t buflen = cli_regerror(rc, preg, NULL, 0); - char* errbuf = cli_malloc(buflen); + char* errbuf = cli_max_malloc(buflen); if (errbuf) { cli_regerror(rc, preg, errbuf, buflen); diff --git a/libclamav/readdb.c b/libclamav/readdb.c index 13be5abcd2..925ae674f2 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -116,7 +116,7 @@ char *cli_virname(const char *virname, unsigned int official) if (official) return cli_strdup(virname); - newname = (char *)cli_malloc(strlen(virname) + 11 + 1); + newname = (char *)cli_max_malloc(strlen(virname) + 11 + 1); if (!newname) { cli_errmsg("cli_virname: Can't allocate memory for newname\n"); return NULL; @@ -156,7 +156,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co /* FULLWORD regex sigopt handling */ if (sigopts & ACPATT_OPTION_FULLWORD) { size_t ovrlen = strlen(hexcpy) + 21; - char *hexovr = cli_calloc(ovrlen, sizeof(char)); + char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -173,7 +173,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co /* NOCASE sigopt is passed onto the regex-opt handler */ if (sigopts & ACPATT_OPTION_NOCASE) { size_t ovrlen = strlen(hexcpy) + 2; - char *hexovr = cli_calloc(ovrlen, sizeof(char)); + char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -213,7 +213,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co if (sigopts & ACPATT_OPTION_FULLWORD) { char *rechar; size_t ovrlen = strlen(hexcpy) + 7; - char *hexovr = cli_calloc(ovrlen, sizeof(char)); + char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -245,7 +245,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co if (sigopts & ACPATT_OPTION_WIDE) { size_t hexcpylen = strlen(hexcpy); size_t ovrlen = 2 * hexcpylen + 1; - char *hexovr = cli_calloc(ovrlen, sizeof(char)); + char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -729,7 +729,7 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v * Parse "{n}" wildcard - Not a "{n-m}" range-style one. * Replaces it with: "??" * n and then re-parses the modified hexsig with recursion. */ - hexcpy = cli_calloc(hexlen + 2 * range, sizeof(char)); + hexcpy = cli_max_calloc(hexlen + 2 * range, sizeof(char)); if (!hexcpy) return CL_EMEM; @@ -1144,7 +1144,7 @@ static char *cli_signorm(const char *signame) nsz = 3; } - new_signame = cli_calloc((nsz + 1), sizeof(char)); + new_signame = cli_max_calloc((nsz + 1), sizeof(char)); if (!new_signame) return NULL; @@ -1731,7 +1731,7 @@ struct lsig_attrib { /* TODO: rework this */ static int lsigattribs(char *attribs, struct cli_lsig_tdb *tdb) { -// clang-format off + // clang-format off #define ATTRIB_TOKENS 10 #define EXPR_TOKEN_MAX 16 struct lsig_attrib attrtab[] = { @@ -2330,7 +2330,7 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, return CL_SUCCESS; } - bcs->all_bcs = cli_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_max_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; @@ -2401,8 +2401,8 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, if (bc->kind >= _BC_START_HOOKS && bc->kind < _BC_LAST_HOOK) { unsigned hook = bc->kind - _BC_START_HOOKS; unsigned cnt = ++engine->hooks_cnt[hook]; - engine->hooks[hook] = cli_realloc2(engine->hooks[hook], - sizeof(*engine->hooks[0]) * cnt); + engine->hooks[hook] = cli_max_realloc2(engine->hooks[hook], + sizeof(*engine->hooks[0]) * cnt); if (!engine->hooks[hook]) { cli_errmsg("Out of memory allocating memory for hook %u", hook); return CL_EMEM; @@ -3581,7 +3581,7 @@ static char *parse_yara_hex_string(YR_STRING *string, int *ret) } reslen++; - res = cli_calloc(reslen, 1); + res = cli_max_calloc(reslen, 1); if (!(res)) { if (ret) *ret = CL_EMEM; return NULL; @@ -3755,7 +3755,7 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) } ytable->tbl_cnt++; - newtable = cli_realloc(ytable->table, ytable->tbl_cnt * sizeof(struct cli_ytable_entry *)); + newtable = cli_max_realloc(ytable->table, ytable->tbl_cnt * sizeof(struct cli_ytable_entry *)); if (!newtable) { cli_yaramsg("ytable_add_string: failed to reallocate new ytable table\n"); free(new->hexstr); @@ -3861,7 +3861,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns return CL_SUCCESS; } - newident = cli_malloc(strlen(rule->identifier) + 5 + 1); + newident = cli_max_malloc(strlen(rule->identifier) + 5 + 1); if (!newident) { cli_errmsg("cli_loadyara(): newident == NULL\n"); return CL_EMEM; @@ -4030,7 +4030,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns #if HAVE_PCRE size_t length = strlen(PCRE_BYPASS) + string->length + 3; - substr = cli_calloc(length, sizeof(char)); + substr = cli_max_calloc(length, sizeof(char)); if (!substr) { cli_errmsg("load_oneyara: cannot allocate memory for converted regex string\n"); str_error++; @@ -4063,7 +4063,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns continue; } - substr = cli_calloc(totsize, sizeof(char)); + substr = cli_max_calloc(totsize, sizeof(char)); if (!substr) { cli_errmsg("load_oneyara: cannot allocate memory for converted generic string\n"); str_error++; @@ -4195,7 +4195,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns #if 0 if (rule->cl_flags & RULE_ALL || rule->cl_flags & RULE_ANY) { lsize = 3*ytable.tbl_cnt; - logic = cli_calloc(lsize, sizeof(char)); + logic = cli_max_calloc(lsize, sizeof(char)); if (!logic) { cli_errmsg("load_oneyara: cannot allocate memory for logic statement\n"); ytable_delete(&ytable); @@ -4600,7 +4600,7 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options } } else { size_t attlen = strlen(tokens[1]) + 10; - attribs = cli_calloc(attlen, sizeof(char)); + attribs = cli_max_calloc(attlen, sizeof(char)); if (!attribs) { cli_errmsg("cli_loadpwdb: Can't allocate memory for attributes\n"); ret = CL_EMEM; @@ -5081,7 +5081,7 @@ static cl_error_t cli_loaddbdir(const char *dirname, struct cl_engine *engine, u continue; } - dbfile = (char *)cli_malloc(strlen(dent->d_name) + dirname_len + 2); + dbfile = (char *)cli_max_malloc(strlen(dent->d_name) + dirname_len + 2); if (!dbfile) { cli_errmsg("cli_loaddbdir: dbfile == NULL\n"); ret = CL_EMEM; @@ -5415,7 +5415,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..") && CLI_DBEXT(dent->d_name)) { dbstat->entries++; - dbstat->stattab = (STATBUF *)cli_realloc2(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); + dbstat->stattab = (STATBUF *)cli_max_realloc2(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); if (!dbstat->stattab) { cl_statfree(dbstat); closedir(dd); @@ -5423,7 +5423,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } #ifdef _WIN32 - dbstat->statdname = (char **)cli_realloc2(dbstat->statdname, dbstat->entries * sizeof(char *)); + dbstat->statdname = (char **)cli_max_realloc2(dbstat->statdname, dbstat->entries * sizeof(char *)); if (!dbstat->statdname) { cli_errmsg("cl_statinidir: Can't allocate memory for dbstat->statdname\n"); cl_statfree(dbstat); @@ -5432,7 +5432,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } #endif - fname = cli_malloc(strlen(dirname) + strlen(dent->d_name) + 32); + fname = cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 32); if (!fname) { cli_errmsg("cl_statinidir: Cant' allocate memory for fname\n"); cl_statfree(dbstat); @@ -5441,7 +5441,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } sprintf(fname, "%s" PATHSEP "%s", dirname, dent->d_name); #ifdef _WIN32 - dbstat->statdname[dbstat->entries - 1] = (char *)cli_malloc(strlen(dent->d_name) + 1); + dbstat->statdname[dbstat->entries - 1] = (char *)cli_max_malloc(strlen(dent->d_name) + 1); if (!dbstat->statdname[dbstat->entries - 1]) { cli_errmsg("cli_statinidir: Can't allocate memory for dbstat->statdname\n"); cl_statfree(dbstat); @@ -5484,7 +5484,7 @@ int cl_statchkdir(const struct cl_stat *dbstat) while ((dent = readdir(dd))) { if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..") && CLI_DBEXT(dent->d_name)) { - fname = cli_malloc(strlen(dbstat->dir) + strlen(dent->d_name) + 32); + fname = cli_max_malloc(strlen(dbstat->dir) + strlen(dent->d_name) + 32); if (!fname) { cli_errmsg("cl_statchkdir: can't allocate memory for fname\n"); closedir(dd); diff --git a/libclamav/rebuildpe.c b/libclamav/rebuildpe.c index 5cd4d8da5b..23f290a990 100644 --- a/libclamav/rebuildpe.c +++ b/libclamav/rebuildpe.c @@ -146,7 +146,7 @@ int cli_rebuildpe_align(char *buffer, struct cli_exe_section *sections, int sect if (datasize > CLI_MAX_ALLOCATION) return 0; - pefile = (char *)cli_calloc(rawbase + datasize, 1); + pefile = (char *)cli_max_calloc(rawbase + datasize, 1); if (!pefile) return 0; diff --git a/libclamav/regex/engine.c b/libclamav/regex/engine.c index ed359c3d6a..68a1767fb7 100644 --- a/libclamav/regex/engine.c +++ b/libclamav/regex/engine.c @@ -209,7 +209,7 @@ matcher(struct re_guts *g, const char *string, size_t nmatch, /* oh my, he wants the subexpressions... */ if (m->pmatch == NULL) - m->pmatch = (regmatch_t *)cli_malloc((m->g->nsub + 1) * + m->pmatch = (regmatch_t *)cli_max_malloc((m->g->nsub + 1) * sizeof(regmatch_t)); if (m->pmatch == NULL) { free(m->lastpos); @@ -223,7 +223,7 @@ matcher(struct re_guts *g, const char *string, size_t nmatch, dp = dissect(m, m->coldp, endp, gf, gl); } else { if (g->nplus > 0 && m->lastpos == NULL) - m->lastpos = (char **)cli_malloc((g->nplus+1) * + m->lastpos = (char **)cli_max_malloc((g->nplus+1) * sizeof(char *)); if (g->nplus > 0 && m->lastpos == NULL) { free(m->pmatch); @@ -983,7 +983,7 @@ print(struct match *m, const char *caption, states st, int ch, FILE *d) (void)fprintf(d, "\n"); } -/* +/* - at - print current situation */ static void diff --git a/libclamav/regex/regcomp.c b/libclamav/regex/regcomp.c index ae9cde0cce..6fa1dbbaa2 100644 --- a/libclamav/regex/regcomp.c +++ b/libclamav/regex/regcomp.c @@ -165,7 +165,7 @@ cli_regcomp_real(regex_t *preg, const char *pattern, int cflags) len = strlen((char *)pattern); /* do the mallocs early so failure handling is easy */ - g = (struct re_guts *)cli_malloc(sizeof(struct re_guts) + + g = (struct re_guts *)cli_max_malloc(sizeof(struct re_guts) + (NC-1)*sizeof(unsigned char)); if (g == NULL) return(REG_ESPACE); @@ -190,7 +190,7 @@ cli_regcomp_real(regex_t *preg, const char *pattern, int cflags) return(REG_ESPACE); } - p->strip = (sop *)cli_calloc(p->ssize, sizeof(sop)); + p->strip = (sop *)cli_max_calloc(p->ssize, sizeof(sop)); p->slen = 0; if (p->strip == NULL) { free(g); @@ -1047,12 +1047,12 @@ allocset(struct parse *p) assert(nc % CHAR_BIT == 0); nbytes = nc / CHAR_BIT *css; - ptr = (cset *)cli_realloc((char*)p->g->sets, nc * sizeof(cset)); + ptr = (cset *)cli_max_realloc((char*)p->g->sets, nc * sizeof(cset)); if (ptr == NULL) goto nomem; p->g->sets = ptr; - ptr = (uch *)cli_realloc((char*)p->g->setbits, nbytes); + ptr = (uch *)cli_max_realloc((char*)p->g->setbits, nbytes); if (ptr == NULL) goto nomem; nbytes = (nc / CHAR_BIT) * css; @@ -1279,7 +1279,7 @@ enlarge(struct parse *p, sopno size) if (p->ssize >= size) return 1; - sp = (sop *)cli_realloc(p->strip, size * sizeof(sop)); + sp = (sop *)cli_max_realloc(p->strip, size * sizeof(sop)); if (sp == NULL) { SETERROR(REG_ESPACE); return 0; @@ -1296,7 +1296,7 @@ static void stripsnug(struct parse *p, struct re_guts *g) { g->nstates = p->slen; - g->strip = (sop *)cli_realloc((char *)p->strip, p->slen * sizeof(sop)); + g->strip = (sop *)cli_max_realloc((char *)p->strip, p->slen * sizeof(sop)); if (g->strip == NULL) { SETERROR(REG_ESPACE); g->strip = p->strip; @@ -1374,7 +1374,7 @@ findmust(struct parse *p, struct re_guts *g) } /* turn it into a character string */ - g->must = cli_malloc((size_t)g->mlen + 1); + g->must = cli_max_malloc((size_t)g->mlen + 1); if (g->must == NULL) { /* argh; just forget it */ g->mlen = 0; return; diff --git a/libclamav/regex/regexec.c b/libclamav/regex/regexec.c index 0c210a3c1b..51a5ee43ef 100644 --- a/libclamav/regex/regexec.c +++ b/libclamav/regex/regexec.c @@ -110,7 +110,7 @@ #define ASSIGN(d, s) memcpy(d, s, m->g->nstates) #define EQ(a, b) (memcmp(a, b, m->g->nstates) == 0) #define STATEVARS long vn; char *space -#define STATESETUP(m, nv) { (m)->space = cli_malloc((nv)*(m)->g->nstates); \ +#define STATESETUP(m, nv) { (m)->space = cli_max_malloc((nv)*(m)->g->nstates); \ if ((m)->space == NULL) return(REG_ESPACE); \ (m)->vn = 0; } #define STATETEARDOWN(m) { free((m)->space); } diff --git a/libclamav/regex_list.c b/libclamav/regex_list.c index 99ae9e2d76..b94f04a6ac 100644 --- a/libclamav/regex_list.c +++ b/libclamav/regex_list.c @@ -200,7 +200,7 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const /* too short, no match possible */ return CL_SUCCESS; } - buffer = cli_malloc(buffer_len + 1); + buffer = cli_max_malloc(buffer_len + 1); if (!buffer) { cli_errmsg("regex_list_match: Unable to allocate memory for buffer\n"); return CL_EMEM; @@ -802,10 +802,10 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su /* new suffix */ size_t n = matcher->suffix_cnt; el = cli_hashtab_insert(&matcher->suffix_hash, suffix, suffix_len, (cli_element_data)n); - CLI_REALLOC(matcher->suffix_regexes, - (n + 1) * sizeof(*matcher->suffix_regexes), - cli_errmsg("add_pattern_suffix: Unable to reallocate memory for matcher->suffix_regexes\n"); - ret = CL_EMEM); + CLI_MAX_REALLOC(matcher->suffix_regexes, + (n + 1) * sizeof(*matcher->suffix_regexes), + cli_errmsg("add_pattern_suffix: Unable to reallocate memory for matcher->suffix_regexes\n"); + ret = CL_EMEM); matcher->suffix_regexes[n].tail = regex; matcher->suffix_regexes[n].head = regex; if (suffix[0] == '/' && suffix[1] == '\0') { @@ -817,7 +817,7 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su if (CL_SUCCESS != ret) { cli_hashtab_delete(&matcher->suffix_hash, suffix, suffix_len); /*shrink the size back to what it was.*/ - CLI_REALLOC(matcher->suffix_regexes, n * sizeof(*matcher->suffix_regexes)); + CLI_MAX_REALLOC(matcher->suffix_regexes, n * sizeof(*matcher->suffix_regexes)); } else { matcher->suffix_cnt++; } diff --git a/libclamav/regex_pcre.c b/libclamav/regex_pcre.c index 61eaa98f90..9c0e2c0819 100644 --- a/libclamav/regex_pcre.c +++ b/libclamav/regex_pcre.c @@ -42,7 +42,7 @@ void *cli_pcre_malloc(size_t size, void *ext) { UNUSEDPARAM(ext); - return cli_malloc(size); + return cli_max_malloc(size); } void cli_pcre_free(void *ptr, void *ext) @@ -56,9 +56,9 @@ void cli_pcre_free(void *ptr, void *ext) cl_error_t cli_pcre_init_internal() { #if !USING_PCRE2 - pcre_malloc = cli_malloc; + pcre_malloc = cli_max_malloc; pcre_free = free; - pcre_stack_malloc = cli_malloc; + pcre_stack_malloc = cli_max_malloc; pcre_stack_free = free; #endif diff --git a/libclamav/regex_suffix.c b/libclamav/regex_suffix.c index bce26a0613..5f99ddb1ed 100644 --- a/libclamav/regex_suffix.c +++ b/libclamav/regex_suffix.c @@ -490,7 +490,7 @@ cl_error_t cli_regex2suffix(const char *pattern, regex_t *preg, suffix_callback rc = cli_regcomp(regex.preg, pattern, REG_EXTENDED); if (rc) { size_t buflen = cli_regerror(rc, regex.preg, NULL, 0); - char *errbuf = cli_malloc(buflen); + char *errbuf = cli_max_malloc(buflen); if (errbuf) { cli_regerror(rc, regex.preg, errbuf, buflen); cli_errmsg(MODULE "Error compiling regular expression %s: %s\n", pattern, errbuf); diff --git a/libclamav/rtf.c b/libclamav/rtf.c index 6d3c2b35ff..7f75bbfc0b 100644 --- a/libclamav/rtf.c +++ b/libclamav/rtf.c @@ -167,7 +167,7 @@ static int push_state(struct stack* stack, struct rtf_state* state) /* grow stack */ struct rtf_state* states; stack->stack_size += 128; - states = cli_realloc(stack->states, stack->stack_size * sizeof(*stack->states)); + states = cli_max_realloc(stack->states, stack->stack_size * sizeof(*stack->states)); if (!states) { // Realloc failed. Note that stack->states has not been freed and must still be cleaned up by the caller. return CL_EMEM; @@ -333,7 +333,7 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu cli_dbgmsg("Description length too big (%lu), showing only 64 bytes of it\n", (unsigned long int)data->desc_len); data->desc_name = malloc(65); } else - data->desc_name = cli_malloc(data->desc_len + 1); + data->desc_name = cli_max_malloc(data->desc_len + 1); if (!data->desc_name) { cli_errmsg("rtf_object_process: Unable to allocate memory for data->desc_name\n"); return CL_EMEM; @@ -525,7 +525,7 @@ int cli_scanrtf(cli_ctx* ctx) stack.stack_size = 16; stack.elements = 0; stack.warned = 0; - stack.states = cli_malloc(stack.stack_size * sizeof(*stack.states)); + stack.states = cli_max_malloc(stack.stack_size * sizeof(*stack.states)); if (!stack.states) { cli_errmsg("ScanRTF: Unable to allocate memory for stack states\n"); diff --git a/libclamav/scanners.c b/libclamav/scanners.c index 2f3bc1fb19..ae0149dbd3 100644 --- a/libclamav/scanners.c +++ b/libclamav/scanners.c @@ -141,7 +141,7 @@ cl_error_t cli_magic_scan_dir(const char *dir, cli_ctx *ctx, uint32_t attributes if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) { /* build the full name */ - fname = cli_malloc(strlen(dir) + strlen(dent->d_name) + 2); + fname = malloc(strlen(dir) + strlen(dent->d_name) + 2); if (!fname) { cli_dbgmsg("cli_magic_scan_dir: Unable to allocate memory for filename\n"); status = CL_EMEM; @@ -2256,7 +2256,7 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) goto done; } - if (!(normalized = cli_malloc(SCANBUFF + maxpatlen))) { + if (!(normalized = cli_max_malloc(SCANBUFF + maxpatlen))) { cli_dbgmsg("cli_scanscript: Unable to malloc %u bytes\n", SCANBUFF); ret = CL_EMEM; goto done; @@ -2584,7 +2584,7 @@ static cl_error_t cli_ole2_scan_tempdir( if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) { /* build the full name */ - subdirectory = cli_malloc(strlen(dir) + strlen(dent->d_name) + 2); + subdirectory = malloc(strlen(dir) + strlen(dent->d_name) + 2); if (!subdirectory) { cli_dbgmsg("cli_ole2_tempdir_scan_vba: Unable to allocate memory for subdirectory path\n"); status = CL_EMEM; @@ -4014,7 +4014,7 @@ static cl_error_t dispatch_file_inspection_callback(clcb_file_inspection cb, cli fmap = ctx->recursion_stack[fmap_index].fmap; fd = fmap_fd(fmap); - CLI_CALLOC(ancestors, ctx->recursion_level + 1, sizeof(char *), status = CL_EMEM); + CLI_MAX_CALLOC(ancestors, ctx->recursion_level + 1, sizeof(char *), status = CL_EMEM); file_name = fmap->name; file_buffer = fmap_need_off_once_len(fmap, 0, fmap->len, &file_size); @@ -5421,7 +5421,7 @@ static cl_error_t scan_common(cl_fmap_t *map, const char *filepath, const char * } ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); if (!ctx.recursion_stack) { status = CL_EMEM; goto done; @@ -5480,7 +5480,7 @@ static cl_error_t scan_common(cl_fmap_t *map, const char *filepath, const char * (CL_SUCCESS == cli_basename(ctx.target_filepath, strlen(ctx.target_filepath), &target_basename))) { /* Include the basename in the temp directory */ new_temp_prefix_len = strlen("YYYYMMDD_HHMMSS-") + strlen(target_basename); - new_temp_prefix = cli_calloc(1, new_temp_prefix_len + 1); + new_temp_prefix = cli_max_calloc(1, new_temp_prefix_len + 1); if (!new_temp_prefix) { cli_errmsg("scan_common: Failed to allocate memory for temp directory name.\n"); status = CL_EMEM; @@ -5491,7 +5491,7 @@ static cl_error_t scan_common(cl_fmap_t *map, const char *filepath, const char * } else { /* Just use date */ new_temp_prefix_len = strlen("YYYYMMDD_HHMMSS-scantemp"); - new_temp_prefix = cli_calloc(1, new_temp_prefix_len + 1); + new_temp_prefix = cli_max_calloc(1, new_temp_prefix_len + 1); if (!new_temp_prefix) { cli_errmsg("scan_common: Failed to allocate memory for temp directory name.\n"); status = CL_EMEM; diff --git a/libclamav/sis.c b/libclamav/sis.c index b22fef43ec..fb8b57ed48 100644 --- a/libclamav/sis.c +++ b/libclamav/sis.c @@ -190,7 +190,7 @@ static char *getsistring(fmap_t *map, uint32_t ptr, uint32_t len) if (!len) return NULL; if (len > 400) len = 400; - name = cli_malloc(len + 1); + name = cli_max_malloc(len + 1); if (!name) { cli_dbgmsg("SIS: OOM\n"); return NULL; @@ -303,7 +303,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) goto done; } pos += sis.langs * sizeof(uint16_t); - if (!(alangs = cli_malloc(sis.langs * sizeof(char *)))) { + if (!(alangs = cli_max_malloc(sis.langs * sizeof(char *)))) { cli_dbgmsg("SIS: OOM\n"); goto done; } @@ -431,7 +431,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) FREE(install_filepath); } - if (!(ptrs = cli_malloc(fcount * sizeof(uint32_t) * 3))) { + if (!(ptrs = cli_max_malloc(fcount * sizeof(uint32_t) * 3))) { cli_dbgmsg("\tOOM\n"); status = CL_EMEM; goto done; @@ -486,7 +486,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) continue; } - if (!(decomp = cli_malloc(olen))) { + if (!(decomp = cli_max_malloc(olen))) { cli_dbgmsg("\tOOM\n"); goto done; } @@ -790,7 +790,7 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) s->sleft = s->smax = 0; if (cli_checklimits("sis", ctx, ALIGN4(s->fsize[s->level]), 0, 0) != CL_CLEAN) break; - if (!(src = cli_malloc(ALIGN4(s->fsize[s->level])))) break; + if (!(src = cli_max_malloc(ALIGN4(s->fsize[s->level])))) break; len = ALIGN4(s->fsize[s->level]); if ((uint32_t)fmap_readn(s->map, src, s->pos, len) != len) { @@ -811,7 +811,7 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) break; } - if (!(dst = cli_malloc(uusize))) { + if (!(dst = cli_max_malloc(uusize))) { cli_dbgmsg("SIS: OOM\n"); free(src); break; diff --git a/libclamav/spin.c b/libclamav/spin.c index 4b5b4ee45a..a741fb83be 100644 --- a/libclamav/spin.c +++ b/libclamav/spin.c @@ -171,7 +171,7 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, cli_dbgmsg("in unspin\n"); - if ((spinned = (char *)cli_malloc(sections[sectcnt].rsz)) == NULL) { + if ((spinned = (char *)cli_max_malloc(sections[sectcnt].rsz)) == NULL) { cli_dbgmsg("spin: Unable to allocate memory for spinned\n"); return 1; } @@ -394,7 +394,7 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, } cli_dbgmsg("spin: Compression bitmap is %x\n", bitmap); - if ((sects = (char **)cli_malloc(sectcnt * sizeof(char *))) == NULL) { + if ((sects = (char **)cli_max_malloc(sectcnt * sizeof(char *))) == NULL) { cli_dbgmsg("spin: malloc(%zu) failed\n", (size_t)sectcnt * sizeof(char *)); return 1; } @@ -402,7 +402,7 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, len = 0; for (j = 0; j < sectcnt; j++) { if (bitmap & 1) { - if ((sects[j] = (char *)cli_malloc(sections[j].vsz)) == NULL) { + if ((sects[j] = (char *)cli_max_malloc(sections[j].vsz)) == NULL) { cli_dbgmsg("spin: malloc(%u) failed\n", sections[j].vsz); len = 1; break; @@ -447,7 +447,7 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, if (j != sectcnt && ((bitman & (1 << j)) == 0)) { /* FIXME: not really sure either the res sect is lamed or just compressed, but this'll save some major headaches */ cli_dbgmsg("spin: Resources (sect%d) appear to be compressed\n\tuncompressed offset %x, len %x\n\tcompressed offset %x, len %x\n", j, sections[j].rva, key32 - sections[j].rva, key32, sections[j].vsz - (key32 - sections[j].rva)); - if ((curr = (char *)cli_malloc(sections[j].vsz)) != NULL) { + if ((curr = (char *)cli_max_malloc(sections[j].vsz)) != NULL) { memcpy(curr, src + sections[j].raw, key32 - sections[j].rva); /* Uncompressed part */ memset(curr + key32 - sections[j].rva, 0, sections[j].vsz - (key32 - sections[j].rva)); /* bzero */ if (cli_unfsg(src + sections[j].raw + key32 - sections[j].rva, curr + key32 - sections[j].rva, sections[j].rsz - (key32 - sections[j].rva), sections[j].vsz - (key32 - sections[j].rva), NULL, NULL)) { @@ -473,9 +473,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, bitmap = bitman; /* save as a free() bitmap */ - if ((ep = (char *)cli_malloc(blobsz)) != NULL) { + if ((ep = (char *)cli_max_malloc(blobsz)) != NULL) { struct cli_exe_section *rebhlp; - if ((rebhlp = (struct cli_exe_section *)cli_malloc(sizeof(struct cli_exe_section) * (sectcnt))) != NULL) { + if ((rebhlp = (struct cli_exe_section *)cli_max_malloc(sizeof(struct cli_exe_section) * (sectcnt))) != NULL) { char *to = ep; int retval = 0; diff --git a/libclamav/str.c b/libclamav/str.c index d75e6b12ca..acadaa9912 100644 --- a/libclamav/str.c +++ b/libclamav/str.c @@ -134,7 +134,7 @@ uint16_t *cli_hex2ui(const char *hex) return NULL; } - str = cli_calloc((len / 2) + 1, sizeof(uint16_t)); + str = cli_max_calloc((len / 2) + 1, sizeof(uint16_t)); if (!str) return NULL; @@ -158,7 +158,7 @@ char *cli_hex2str(const char *hex) return NULL; } - str = cli_calloc((len / 2) + 1, sizeof(char)); + str = cli_max_calloc((len / 2) + 1, sizeof(char)); if (!str) return NULL; @@ -224,9 +224,9 @@ int cli_xtoi(const char *hex) if (len % 2 == 0) return cli_hex2num(hex); - hexbuf = cli_calloc(len + 2, sizeof(char)); + hexbuf = cli_max_calloc(len + 2, sizeof(char)); if (hexbuf == NULL) { - cli_errmsg("cli_xtoi(): cli_malloc fails.\n"); + cli_errmsg("cli_xtoi(): cli_max_malloc fails.\n"); return -1; } @@ -244,7 +244,7 @@ char *cli_str2hex(const char *string, unsigned int len) '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; unsigned int i, j; - if ((hexstr = (char *)cli_calloc(2 * len + 1, sizeof(char))) == NULL) + if ((hexstr = (char *)cli_max_calloc(2 * len + 1, sizeof(char))) == NULL) return NULL; for (i = 0, j = 0; i < len; i++, j += 2) { @@ -332,7 +332,7 @@ char *cli_strtok(const char *line, int fieldno, const char *delim) if (i == j) { return NULL; } - buffer = cli_malloc(j - i + 1); + buffer = cli_max_malloc(j - i + 1); if (!buffer) { cli_errmsg("cli_strtok: Unable to allocate memory for buffer\n"); return NULL; @@ -940,7 +940,7 @@ char *cli_unescape(const char *str) const size_t len = strlen(str); /* unescaped string is at most as long as original, * it will usually be shorter */ - R = cli_malloc(len + 1); + R = cli_max_malloc(len + 1); if (!R) { cli_errmsg("cli_unescape: Unable to allocate memory for string\n"); return NULL; @@ -974,7 +974,7 @@ char *cli_unescape(const char *str) R[i++] = c; } R[i++] = '\0'; - R = cli_realloc2(R, i); + R = cli_max_realloc2(R, i); return R; } diff --git a/libclamav/tnef.c b/libclamav/tnef.c index d3669d6cbb..703b19cd9b 100644 --- a/libclamav/tnef.c +++ b/libclamav/tnef.c @@ -246,7 +246,7 @@ tnef_message(fmap_t *map, off_t *pos, uint16_t type, uint16_t tag, int32_t lengt case attMSGCLASS: if (length <= 0) return -1; - string = cli_malloc(length + 1); + string = cli_max_malloc(length + 1); if (string == NULL) { cli_errmsg("tnef_message: Unable to allocate memory for string\n"); return -1; @@ -296,7 +296,7 @@ tnef_attachment(fmap_t *map, off_t *pos, uint16_t type, uint16_t tag, int32_t le case attATTACHTITLE: if (length <= 0) return -1; - string = cli_malloc(length + 1); + string = cli_max_malloc(length + 1); if (string == NULL) { cli_errmsg("tnef_attachment: Unable to allocate memory for string\n"); return -1; diff --git a/libclamav/udf.c b/libclamav/udf.c index b01117f7e2..f7b7d5a1b1 100644 --- a/libclamav/udf.c +++ b/libclamav/udf.c @@ -633,9 +633,9 @@ static cl_error_t initPointerList(PointerList *pl) uint32_t capacity = POINTER_LIST_INCREMENT; freePointerList(pl); - CLI_CALLOC(pl->idxs, capacity, sizeof(uint8_t *), - cli_errmsg("initPointerList: Can't allocate memory\n"); - ret = CL_EMEM); + CALLOC(pl->idxs, capacity, sizeof(uint8_t *), + cli_errmsg("initPointerList: Can't allocate memory\n"); + ret = CL_EMEM); pl->capacity = capacity; done: @@ -648,9 +648,9 @@ static cl_error_t insertPointer(PointerList *pl, const uint8_t *pointer) if (pl->cnt == (pl->capacity - 1)) { uint32_t newCapacity = pl->capacity + POINTER_LIST_INCREMENT; - CLI_REALLOC(pl->idxs, newCapacity * sizeof(uint8_t *), - cli_errmsg("insertPointer: Can't allocate memory\n"); - ret = CL_EMEM); + CLI_SAFER_REALLOC(pl->idxs, newCapacity * sizeof(uint8_t *), + cli_errmsg("insertPointer: Can't allocate memory\n"); + ret = CL_EMEM); pl->capacity = newCapacity; } diff --git a/libclamav/unarj.c b/libclamav/unarj.c index 65489f8ac9..ddeb97710c 100644 --- a/libclamav/unarj.c +++ b/libclamav/unarj.c @@ -551,7 +551,7 @@ static cl_error_t decode(arj_metadata_t *metadata) int16_t chr, i, j; memset(&decode_data, 0, sizeof(decode_data)); - decode_data.text = (unsigned char *)cli_calloc(DDICSIZ, 1); + decode_data.text = (unsigned char *)cli_max_calloc(DDICSIZ, 1); if (!decode_data.text) { return CL_EMEM; } @@ -706,7 +706,7 @@ static cl_error_t decode_f(arj_metadata_t *metadata) dd = &decode_data; memset(&decode_data, 0, sizeof(decode_data)); - decode_data.text = (unsigned char *)cli_calloc(DDICSIZ, 1); + decode_data.text = (unsigned char *)cli_max_calloc(DDICSIZ, 1); if (!decode_data.text) { return CL_EMEM; } @@ -899,7 +899,7 @@ static int arj_read_main_header(arj_metadata_t *metadata) goto done; } if (filename_max_len > 0) { - fnnorm = cli_calloc(sizeof(unsigned char), filename_max_len + 1); + fnnorm = cli_max_calloc(sizeof(unsigned char), filename_max_len + 1); filename = fmap_need_offstr(metadata->map, metadata->offset, filename_max_len + 1); if (!filename || !fnnorm) { cli_dbgmsg("UNARJ: Unable to allocate memory for filename\n"); @@ -917,7 +917,7 @@ static int arj_read_main_header(arj_metadata_t *metadata) goto done; } if (comment_max_len > 0) { - comnorm = cli_calloc(sizeof(unsigned char), comment_max_len + 1); + comnorm = cli_max_calloc(sizeof(unsigned char), comment_max_len + 1); comment = fmap_need_offstr(metadata->map, metadata->offset, comment_max_len + 1); if (!comment || !comnorm) { cli_dbgmsg("UNARJ: Unable to allocate memory for comment\n"); @@ -1044,7 +1044,7 @@ static cl_error_t arj_read_file_header(arj_metadata_t *metadata) goto done; } if (filename_max_len > 0) { - fnnorm = cli_calloc(sizeof(unsigned char), filename_max_len + 1); + fnnorm = cli_max_calloc(sizeof(unsigned char), filename_max_len + 1); if (!fnnorm) { cli_dbgmsg("UNARJ: Unable to allocate memory for filename\n"); ret = CL_EMEM; @@ -1067,7 +1067,7 @@ static cl_error_t arj_read_file_header(arj_metadata_t *metadata) goto done; } if (comment_max_len > 0) { - comnorm = cli_calloc(sizeof(unsigned char), comment_max_len + 1); + comnorm = cli_max_calloc(sizeof(unsigned char), comment_max_len + 1); if (!comnorm) { cli_dbgmsg("UNARJ: Unable to allocate memory for comment\n"); ret = CL_EMEM; diff --git a/libclamav/uniq.c b/libclamav/uniq.c index 7f34e61d83..7b2be934cb 100644 --- a/libclamav/uniq.c +++ b/libclamav/uniq.c @@ -42,7 +42,7 @@ struct uniq *uniq_init(uint32_t count) U = calloc(1, sizeof(*U)); if (!U) return NULL; - U->md5s = cli_malloc(count * sizeof(*U->md5s)); + U->md5s = cli_max_malloc(count * sizeof(*U->md5s)); if (!U->md5s) { uniq_free(U); return NULL; diff --git a/libclamav/unsp.c b/libclamav/unsp.c index d82803c53b..44e2d49d81 100644 --- a/libclamav/unsp.c +++ b/libclamav/unsp.c @@ -155,7 +155,7 @@ uint32_t unspack(const char *start_of_stuff, char *dest, cli_ctx *ctx, uint32_t return 1; /* Should be ~15KB, if it's so big it's prolly just not nspacked */ cli_dbgmsg("unsp: table size = %d\n", tablesz); - if (!(table = cli_malloc(tablesz))) { + if (!(table = cli_max_malloc(tablesz))) { cli_dbgmsg("unspack: Unable to allocate memory for table\n"); return 1; } diff --git a/libclamav/unzip.c b/libclamav/unzip.c index 2c3b6ecc24..189ce72461 100644 --- a/libclamav/unzip.c +++ b/libclamav/unzip.c @@ -1065,7 +1065,7 @@ cl_error_t index_the_central_directory( goto done; } - zip_catalogue_new = cli_realloc(zip_catalogue, sizeof(struct zip_record) * ZIP_RECORDS_CHECK_BLOCKSIZE * (num_record_blocks + 1)); + zip_catalogue_new = cli_max_realloc(zip_catalogue, sizeof(struct zip_record) * ZIP_RECORDS_CHECK_BLOCKSIZE * (num_record_blocks + 1)); if (NULL == zip_catalogue_new) { status = CL_EMEM; goto done; diff --git a/libclamav/upx.c b/libclamav/upx.c index 478aaea7e4..3971936ab3 100644 --- a/libclamav/upx.c +++ b/libclamav/upx.c @@ -187,7 +187,7 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize if (!pehdr) { uint32_t rebsz = PESALIGN(dend, 0x1000); cli_dbgmsg("UPX: no luck - brutally crafting a reasonable PE\n"); - if (!(newbuf = (char *)cli_calloc(rebsz + 0x200, sizeof(char)))) { + if (!(newbuf = (char *)cli_max_calloc(rebsz + 0x200, sizeof(char)))) { cli_dbgmsg("UPX: malloc failed - giving up rebuild\n"); return 0; } @@ -234,7 +234,7 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize cli_writeint32(pehdr + 8, 0x4d414c43); cli_writeint32(pehdr + 0x3c, valign); - if (!(newbuf = (char *)cli_calloc(foffset, sizeof(char)))) { + if (!(newbuf = (char *)cli_max_calloc(foffset, sizeof(char)))) { cli_dbgmsg("UPX: malloc failed - giving up rebuild\n"); return 0; } diff --git a/libclamav/vba_extract.c b/libclamav/vba_extract.c index 8c83054c79..4e00098e57 100644 --- a/libclamav/vba_extract.c +++ b/libclamav/vba_extract.c @@ -109,7 +109,7 @@ get_unicode_name(const char *name, int size, int big_endian) if ((name == NULL) || (*name == '\0') || (size <= 0)) return NULL; - newname = (char *)cli_malloc(size * 7 + 1); + newname = (char *)cli_max_malloc(size * 7 + 1); if (newname == NULL) { cli_errmsg("get_unicode_name: Unable to allocate memory for newname\n"); return NULL; @@ -150,7 +150,7 @@ get_unicode_name(const char *name, int size, int big_endian) *ret = '\0'; /* Saves a lot of memory */ - ret = cli_realloc(newname, (ret - newname) + 1); + ret = cli_max_realloc(newname, (ret - newname) + 1); return ret ? ret : newname; } @@ -211,7 +211,7 @@ vba_read_project_strings(int fd, int big_endian) } /* ensure buffer is large enough */ if (length > buflen) { - unsigned char *newbuf = (unsigned char *)cli_realloc(buf, length); + unsigned char *newbuf = (unsigned char *)cli_max_realloc(buf, length); if (newbuf == NULL) { ret = 0; break; @@ -1539,7 +1539,7 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) break; } if (length > buflen) { - unsigned char *newbuf = (unsigned char *)cli_realloc(buf, length); + unsigned char *newbuf = (unsigned char *)cli_max_realloc(buf, length); if (newbuf == NULL) break; buflen = length; @@ -2034,7 +2034,7 @@ word_read_macro_entry(int fd, macro_info_t *macro_info) return TRUE; msize = count * sizeof(struct macro); - m = cli_malloc(msize); + m = cli_max_malloc(msize); if (m == NULL) { cli_errmsg("word_read_macro_entry: Unable to allocate memory for 'm'\n"); return FALSE; @@ -2069,7 +2069,7 @@ word_read_macro_info(int fd, macro_info_t *macro_info) cli_dbgmsg("macro count: %d\n", macro_info->count); if (macro_info->count == 0) return NULL; - macro_info->entries = (macro_entry_t *)cli_malloc(sizeof(macro_entry_t) * macro_info->count); + macro_info->entries = (macro_entry_t *)cli_max_malloc(sizeof(macro_entry_t) * macro_info->count); if (macro_info->entries == NULL) { macro_info->count = 0; cli_errmsg("word_read_macro_info: Unable to allocate memory for macro_info->entries\n"); @@ -2290,8 +2290,8 @@ cli_wm_readdir(int fd) vba_project = create_vba_project(macro_info.count, "", NULL); if (vba_project) { - vba_project->length = (uint32_t *)cli_malloc(sizeof(uint32_t) * macro_info.count); - vba_project->key = (unsigned char *)cli_malloc(sizeof(unsigned char) * macro_info.count); + vba_project->length = (uint32_t *)cli_max_malloc(sizeof(uint32_t) * macro_info.count); + vba_project->key = (unsigned char *)cli_max_malloc(sizeof(unsigned char) * macro_info.count); if ((vba_project->length != NULL) && (vba_project->key != NULL)) { int i; @@ -2333,7 +2333,7 @@ cli_wm_decrypt_macro(int fd, off_t offset, uint32_t len, unsigned char key) if (fd < 0) return NULL; - buff = (unsigned char *)cli_malloc(len); + buff = (unsigned char *)cli_max_malloc(len); if (buff == NULL) { cli_errmsg("cli_wm_decrypt_macro: Unable to allocate memory for buff\n"); return NULL; @@ -2432,10 +2432,10 @@ create_vba_project(int record_count, const char *dir, struct uniq *U) return NULL; } - ret->name = (char **)cli_malloc(sizeof(char *) * record_count); - ret->colls = (uint32_t *)cli_malloc(sizeof(uint32_t) * record_count); + ret->name = (char **)cli_max_malloc(sizeof(char *) * record_count); + ret->colls = (uint32_t *)cli_max_malloc(sizeof(uint32_t) * record_count); ret->dir = cli_strdup(dir); - ret->offset = (uint32_t *)cli_malloc(sizeof(uint32_t) * record_count); + ret->offset = (uint32_t *)cli_max_malloc(sizeof(uint32_t) * record_count); if ((ret->colls == NULL) || (ret->name == NULL) || (ret->dir == NULL) || (ret->offset == NULL)) { cli_free_vba_project(ret); diff --git a/libclamav/wwunpack.c b/libclamav/wwunpack.c index 744b3961a9..ff81459cca 100644 --- a/libclamav/wwunpack.c +++ b/libclamav/wwunpack.c @@ -96,7 +96,7 @@ cl_error_t wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_ex break; } cli_dbgmsg("WWP: src: %x, szd: %x, srcend: %x - %x\n", src, szd, srcend, srcend + 4 - szd); - if (!(compd = cli_malloc(szd))) { + if (!(compd = cli_max_malloc(szd))) { cli_dbgmsg("WWPack: Unable to allocate memory for compd\n"); break; } diff --git a/libclamav/www.c b/libclamav/www.c index 90a0340d00..55cbac411e 100644 --- a/libclamav/www.c +++ b/libclamav/www.c @@ -173,7 +173,7 @@ char *encode_data(const char *postdata) if (bufsz == 0) return NULL; - buf = cli_calloc(1, bufsz + 1); + buf = cli_max_calloc(1, bufsz + 1); if (!(buf)) return NULL; @@ -231,7 +231,7 @@ void submit_post(const char *host, const char *port, const char *method, const c bufsz += strlen(encoded); } - buf = cli_calloc(1, bufsz); + buf = cli_max_calloc(1, bufsz); if (!(buf)) { if ((encoded)) free(encoded); diff --git a/libclamav/xar.c b/libclamav/xar.c index c9a0c2804d..7d195ab098 100644 --- a/libclamav/xar.c +++ b/libclamav/xar.c @@ -473,9 +473,9 @@ int cli_scanxar(cli_ctx *ctx) return CL_EREAD; } strm.avail_in = hdr.toc_length_compressed; - toc = cli_malloc(hdr.toc_length_decompressed + 1); + toc = cli_max_malloc(hdr.toc_length_decompressed + 1); if (toc == NULL) { - cli_dbgmsg("cli_scanxar: cli_malloc fails on TOC decompress buffer.\n"); + cli_dbgmsg("cli_scanxar: cli_max_malloc fails on TOC decompress buffer.\n"); return CL_EMEM; } toc[hdr.toc_length_decompressed] = '\0'; diff --git a/libclamav/xlm_extract.c b/libclamav/xlm_extract.c index 4148cdf782..ac96cac1cd 100644 --- a/libclamav/xlm_extract.c +++ b/libclamav/xlm_extract.c @@ -4790,7 +4790,7 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char } else { /* already found the beginning of a drawing group, extract the remaining chunks */ drawinggroup_len += biff_header.length; - CLI_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); + CLI_MAX_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); memcpy(drawinggroup + (drawinggroup_len - biff_header.length), data, biff_header.length); // cli_dbgmsg("Collected %d drawing group bytes\n", biff_header.length); } @@ -4801,7 +4801,7 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char (NULL != drawinggroup)) { /* already found the beginning of an image, extract the remaining chunks */ drawinggroup_len += biff_header.length; - CLI_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); + CLI_MAX_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); memcpy(drawinggroup + (drawinggroup_len - biff_header.length), data, biff_header.length); // cli_dbgmsg("Collected %d image bytes\n", biff_header.length); } diff --git a/libclamav/xz_iface.c b/libclamav/xz_iface.c index 8bb9d6b499..0565f8e532 100644 --- a/libclamav/xz_iface.c +++ b/libclamav/xz_iface.c @@ -40,7 +40,7 @@ void *__xz_wrap_alloc(void *unused, size_t size) (unsigned long int)size); return NULL; } - return cli_malloc(size); + return cli_max_malloc(size); } void __xz_wrap_free(void *unused, void *freeme) { diff --git a/libclamav/yara_clam.h b/libclamav/yara_clam.h index 8b31f85a29..eaa0814c2b 100644 --- a/libclamav/yara_clam.h +++ b/libclamav/yara_clam.h @@ -453,8 +453,8 @@ struct RE { * YARA to ClamAV function mappings */ #define yr_strdup cli_strdup -#define yr_malloc cli_malloc -#define yr_realloc cli_realloc +#define yr_malloc cli_max_malloc +#define yr_realloc cli_max_realloc #define yr_free free #define xtoi cli_xtoi diff --git a/libfreshclam/libfreshclam.c b/libfreshclam/libfreshclam.c index 04f95347a1..0d0ff64ad7 100644 --- a/libfreshclam/libfreshclam.c +++ b/libfreshclam/libfreshclam.c @@ -227,7 +227,7 @@ fc_error_t fc_initialize(fc_config *fcConfig) #else if (fcConfig->databaseDirectory[strlen(fcConfig->databaseDirectory) - 1] != '/') { #endif - g_databaseDirectory = cli_malloc(strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1); + g_databaseDirectory = cli_max_malloc(strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1); snprintf( g_databaseDirectory, strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1, diff --git a/sigtool/sigtool.c b/sigtool/sigtool.c index 003fa79b6a..e4a6faa010 100644 --- a/sigtool/sigtool.c +++ b/sigtool/sigtool.c @@ -219,7 +219,7 @@ static int hashpe(const char *filename, unsigned int class, int type) ctx.dconf = (struct cli_dconf *)engine->dconf; ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ctx.recursion_stack = calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); if (!ctx.recursion_stack) { goto done; } @@ -473,7 +473,7 @@ static cli_ctx *convenience_ctx(int fd) } /* prepare context */ - ctx = cli_calloc(1, sizeof(cli_ctx)); + ctx = calloc(1, sizeof(cli_ctx)); if (!ctx) { printf("convenience_ctx: ctx allocation failed\n"); goto done; @@ -486,7 +486,7 @@ static cli_ctx *convenience_ctx(int fd) ctx->dconf = (struct cli_dconf *)engine->dconf; ctx->recursion_stack_size = ctx->engine->max_recursion_level; - ctx->recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx->recursion_stack_size); + ctx->recursion_stack = calloc(sizeof(recursion_level_t), ctx->recursion_stack_size); if (!ctx->recursion_stack) { status = CL_EMEM; goto done; @@ -499,7 +499,7 @@ static cli_ctx *convenience_ctx(int fd) ctx->fmap = ctx->recursion_stack[ctx->recursion_level].fmap; - ctx->options = cli_calloc(1, sizeof(struct cl_scan_options)); + ctx->options = calloc(1, sizeof(struct cl_scan_options)); if (!ctx->options) { printf("convenience_ctx: scan options allocation failed\n"); goto done; @@ -2367,7 +2367,7 @@ static void matchsig(char *sig, const char *offset, int fd) ctx.dconf = (struct cli_dconf *)engine->dconf; ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ctx.recursion_stack = calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); if (!ctx.recursion_stack) { goto done; } @@ -2753,7 +2753,7 @@ static int decodehex(const char *hexsig) clen = hexlen - tlen - rlen - 2; /* 2 from regex boundaries '/' */ /* get the trigger statement */ - trigger = cli_calloc(tlen + 1, sizeof(char)); + trigger = calloc(tlen + 1, sizeof(char)); if (!trigger) { mprintf(LOGG_ERROR, "cannot allocate memory for trigger string\n"); return -1; @@ -2762,7 +2762,7 @@ static int decodehex(const char *hexsig) trigger[tlen] = '\0'; /* get the regex expression */ - regex = cli_calloc(rlen + 1, sizeof(char)); + regex = cli_max_calloc(rlen + 1, sizeof(char)); if (!regex) { mprintf(LOGG_ERROR, "cannot allocate memory for regex expression\n"); free(trigger); @@ -2773,7 +2773,7 @@ static int decodehex(const char *hexsig) /* get the compile flags */ if (clen) { - cflags = cli_calloc(clen + 1, sizeof(char)); + cflags = cli_max_calloc(clen + 1, sizeof(char)); if (!cflags) { mprintf(LOGG_ERROR, "cannot allocate memory for compile flags\n"); free(trigger); @@ -3578,7 +3578,7 @@ static int dumpcerts(const struct optstruct *opts) ctx.dconf = (struct cli_dconf *)engine->dconf; ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ctx.recursion_stack = calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); if (!ctx.recursion_stack) { goto done; } diff --git a/unit_tests/check_bytecode.c b/unit_tests/check_bytecode.c index 75b851e9da..0ec9816e1f 100644 --- a/unit_tests/check_bytecode.c +++ b/unit_tests/check_bytecode.c @@ -83,8 +83,8 @@ static void runtest(const char *file, uint64_t expected, int fail, int nojit, cctx.dconf = cctx.engine->dconf; cctx.recursion_stack_size = cctx.engine->max_recursion_level; - cctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); - ck_assert_msg(!!cctx.recursion_stack, "cli_calloc() for recursion_stack failed"); + cctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); + ck_assert_msg(!!cctx.recursion_stack, "cli_max_calloc() for recursion_stack failed"); // ctx was memset, so recursion_level starts at 0. cctx.recursion_stack[cctx.recursion_level].fmap = NULL; @@ -509,8 +509,8 @@ static void runload(const char *dbname, struct cl_engine *engine, unsigned signo /* when run from automake srcdir is set, but if run manually then not */ srcdir = SRCDIR; } - str = cli_malloc(strlen(srcdir) + 1 + strlen(dbname) + 1); - ck_assert_msg(!!str, "cli_malloc"); + str = cli_max_malloc(strlen(srcdir) + 1 + strlen(dbname) + 1); + ck_assert_msg(!!str, "cli_max_malloc"); sprintf(str, "%s" PATHSEP "%s", srcdir, dbname); rc = cl_load(str, engine, &signo, CL_DB_STDOPT); diff --git a/unit_tests/check_clamav.c b/unit_tests/check_clamav.c index a62d3a83b6..6f0d39e862 100644 --- a/unit_tests/check_clamav.c +++ b/unit_tests/check_clamav.c @@ -581,8 +581,8 @@ static void init_testfiles(void) if (strncmp(dirent->d_name, "clam", 4)) continue; i++; - testfiles = cli_realloc(testfiles, i * sizeof(*testfiles)); - ck_assert_msg(!!testfiles, "cli_realloc"); + testfiles = cli_max_realloc(testfiles, i * sizeof(*testfiles)); + ck_assert_msg(!!testfiles, "cli_max_realloc"); testfiles[i - 1] = strdup(dirent->d_name); } testfiles_n = i; @@ -1921,8 +1921,8 @@ int open_testfile(const char *name, int flags) srcdir = SRCDIR; } - str = cli_malloc(strlen(name) + strlen(srcdir) + 2); - ck_assert_msg(!!str, "cli_malloc"); + str = cli_max_malloc(strlen(name) + strlen(srcdir) + 2); + ck_assert_msg(!!str, "cli_max_malloc"); sprintf(str, "%s" PATHSEP "%s", srcdir, name); fd = open(str, flags); @@ -1935,7 +1935,7 @@ void diff_file_mem(int fd, const char *ref, size_t len) { char c1, c2; size_t p, reflen = len; - char *buf = cli_malloc(len); + char *buf = cli_max_malloc(len); ck_assert_msg(!!buf, "unable to malloc buffer: %zu", len); p = read(fd, buf, len); @@ -1964,7 +1964,7 @@ void diff_files(int fd, int ref_fd) off_t siz = lseek(ref_fd, 0, SEEK_END); ck_assert_msg(siz != -1, "lseek failed"); - ref = cli_malloc(siz); + ref = cli_max_malloc(siz); ck_assert_msg(!!ref, "unable to malloc buffer: " STDi64, (int64_t)siz); ck_assert_msg(lseek(ref_fd, 0, SEEK_SET) == 0, "lseek failed"); diff --git a/unit_tests/check_matchers.c b/unit_tests/check_matchers.c index c2b5ac153b..c84aee5c34 100644 --- a/unit_tests/check_matchers.c +++ b/unit_tests/check_matchers.c @@ -178,8 +178,8 @@ static void setup(void) ctx.dconf = ctx.engine->dconf; ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); - ck_assert_msg(!!ctx.recursion_stack, "cli_calloc() for recursion_stack failed"); + ctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ck_assert_msg(!!ctx.recursion_stack, "cli_max_calloc() for recursion_stack failed"); // ctx was memset, so recursion_level starts at 0. ctx.recursion_stack[ctx.recursion_level].fmap = &thefmap; @@ -478,7 +478,7 @@ START_TEST(test_pcre_scanbuff) for (i = 0; pcre_testdata[i].data; i++) { hexlen = strlen(PCRE_BYPASS) + strlen(pcre_testdata[i].hexsig) + 1; - hexsig = cli_calloc(hexlen, sizeof(char)); + hexsig = cli_max_calloc(hexlen, sizeof(char)); ck_assert_msg(hexsig != NULL, "[pcre] failed to prepend bypass (out-of-memory)"); strncat(hexsig, PCRE_BYPASS, hexlen); @@ -532,7 +532,7 @@ START_TEST(test_pcre_scanbuff_allscan) for (i = 0; pcre_testdata[i].data; i++) { hexlen = strlen(PCRE_BYPASS) + strlen(pcre_testdata[i].hexsig) + 1; - hexsig = cli_calloc(hexlen, sizeof(char)); + hexsig = cli_max_calloc(hexlen, sizeof(char)); ck_assert_msg(hexsig != NULL, "[pcre] failed to prepend bypass (out-of-memory)"); strncat(hexsig, PCRE_BYPASS, hexlen); From 120ad48088caea147f90032c6080ee298f38ceff Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 8 Jan 2024 17:20:05 -0500 Subject: [PATCH 03/12] Use regular malloc instead of max_alloc for utf16->8 conversion Should be safe to allocate a smaller string than one we already have. --- common/scanmem.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/scanmem.c b/common/scanmem.c index 3797f32d4e..a0b4d4b5c2 100644 --- a/common/scanmem.c +++ b/common/scanmem.c @@ -101,7 +101,7 @@ static inline char *wc2mb(const wchar_t *wc, DWORD flags) return NULL; } - mb = cli_max_malloc(len + 1); + mb = malloc(len + 1); if (!mb) return NULL; res = WideCharToMultiByte(CP_ACP, flags, wc, -1, mb, len, NULL, &invalid); From c98a7b8e11ed1c634ef620dbd2f4e363a4f43535 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 8 Jan 2024 22:48:28 -0500 Subject: [PATCH 04/12] Remove max-allocation limits where not required The cli_max_malloc, cli_max_calloc, and cli_max_realloc functions provide a way to protect against allocating too much memory when the size of the allocation is derived from the untrusted input. Specifically, we worry about values in the file being scanned being manipulated to exhaust the RAM and crash the application. There is no need to check the limits if the size of the allocation is fixed, or if the size of the allocation is necessary for signature loading, or the general operation of the applications. E.g. checking the max-allocation limit for the size of a hash, or for the size of the scan recursion stack, is a complete waste of time. Although we significantly increased the max-allocation limit in a recent release, it is best not to check an allocation if the allocation will be safe. It would be a waste of time. I am also hopeful that if we can reduce the number allocations that require a limit-check to those that require it for the safe scan of a file, then eventually we can store the limit in the scan- context, and make it configurable. --- clambc/bcrun.c | 2 +- clamonacc/inotif/hash.c | 4 ++-- clamonacc/inotif/inotif.c | 10 +++++----- clamonacc/misc/utils.c | 2 +- freshclam/freshclam.c | 6 +++--- libclamav/cvd.c | 4 ++-- libclamav/dsig.c | 2 +- libclamav/others.c | 25 ++++++++++++------------- libclamav/others_common.c | 12 ++++-------- libclamav/pe.c | 12 ++++++------ libfreshclam/libfreshclam.c | 2 +- sigtool/sigtool.c | 4 ++-- unit_tests/check_bytecode.c | 8 ++++---- unit_tests/check_clamav.c | 12 ++++++------ unit_tests/check_matchers.c | 8 ++++---- 15 files changed, 54 insertions(+), 59 deletions(-) diff --git a/clambc/bcrun.c b/clambc/bcrun.c index 43edc8adf3..efb167b069 100644 --- a/clambc/bcrun.c +++ b/clambc/bcrun.c @@ -399,7 +399,7 @@ int main(int argc, char *argv[]) cctx.evidence = evidence_new(); cctx.recursion_stack_size = cctx.engine->max_recursion_level; - cctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); + cctx.recursion_stack = calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); if (!cctx.recursion_stack) { fprintf(stderr, "Out of memory\n"); exit(3); diff --git a/clamonacc/inotif/hash.c b/clamonacc/inotif/hash.c index d1a32b79a2..5b6c9381b5 100644 --- a/clamonacc/inotif/hash.c +++ b/clamonacc/inotif/hash.c @@ -145,7 +145,7 @@ int onas_ht_init(struct onas_ht **ht, uint32_t size) .nbckts = 0, }; - if (!((*ht)->htable = (struct onas_bucket **)cli_max_calloc(size, sizeof(struct onas_bucket *)))) { + if (!((*ht)->htable = (struct onas_bucket **)calloc(size, sizeof(struct onas_bucket *)))) { onas_free_ht(*ht); return CL_EMEM; } @@ -794,7 +794,7 @@ int onas_ht_rm_hierarchy(struct onas_ht *ht, const char *pathname, size_t len, i curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_max_malloc(size); + char *child_path = (char *)malloc(size); if (child_path == NULL) return CL_EMEM; if (hnode->pathname[len - 1] == '/') diff --git a/clamonacc/inotif/inotif.c b/clamonacc/inotif/inotif.c index 904fc241f2..ec0afb4f6c 100644 --- a/clamonacc/inotif/inotif.c +++ b/clamonacc/inotif/inotif.c @@ -105,7 +105,7 @@ static int onas_ddd_init_wdlt(uint64_t nwatches) if (nwatches <= 0) return CL_EARG; - wdlt = (char **)cli_max_calloc(nwatches << 1, sizeof(char *)); + wdlt = (char **)calloc(nwatches << 1, sizeof(char *)); if (!wdlt) return CL_EMEM; wdlt_len = nwatches << 1; @@ -121,7 +121,7 @@ static int onas_ddd_grow_wdlt(void) char **ptr = NULL; - ptr = (char **)cli_max_realloc(wdlt, wdlt_len << 1); + ptr = (char **)cli_safer_realloc(wdlt, wdlt_len << 1); if (ptr) { wdlt = ptr; memset(&ptr[wdlt_len], 0, sizeof(char *) * (wdlt_len - 1)); @@ -243,7 +243,7 @@ static int onas_ddd_watch_hierarchy(const char *pathname, size_t len, int fd, ui curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_max_malloc(size); + char *child_path = (char *)malloc(size); if (child_path == NULL) { logg(LOGG_ERROR, "ClamInotif: out of memory when adding child for %s\n", hnode->pathname); return CL_EMEM; @@ -330,7 +330,7 @@ static int onas_ddd_unwatch_hierarchy(const char *pathname, size_t len, int fd, curr = curr->next; size_t size = len + strlen(curr->dirname) + 2; - char *child_path = (char *)cli_max_malloc(size); + char *child_path = (char *)malloc(size); if (child_path == NULL) return CL_EMEM; if (hnode->pathname[len - 1] == '/') @@ -679,7 +679,7 @@ void *onas_ddd_th(void *arg) } else { len = strlen(path); size_t size = strlen(child) + len + 2; - char *child_path = (char *)cli_max_malloc(size); + char *child_path = (char *)malloc(size); if (child_path == NULL) { logg(LOGG_DEBUG, "ClamInotif: could not allocate space for child path ... aborting\n"); return NULL; diff --git a/clamonacc/misc/utils.c b/clamonacc/misc/utils.c index d219250b7f..70e132eeff 100644 --- a/clamonacc/misc/utils.c +++ b/clamonacc/misc/utils.c @@ -206,7 +206,7 @@ char **onas_get_opt_list(const char *fname, int *num_entries, cl_error_t *err) } (*num_entries)++; - rlc_ptr = cli_max_realloc(opt_list, sizeof(char *) * (*num_entries + 1)); + rlc_ptr = cli_safer_realloc(opt_list, sizeof(char *) * (*num_entries + 1)); if (rlc_ptr) { opt_list = rlc_ptr; opt_list[*num_entries] = NULL; diff --git a/freshclam/freshclam.c b/freshclam/freshclam.c index 69a0bda0d2..da2dbd0299 100644 --- a/freshclam/freshclam.c +++ b/freshclam/freshclam.c @@ -535,7 +535,7 @@ static fc_error_t string_list_add(const char *item, char ***stringList, uint32_t } nItems = *nListItems + 1; - newList = (char **)cli_max_realloc(*stringList, nItems * sizeof(char *)); + newList = (char **)cli_safer_realloc(*stringList, nItems * sizeof(char *)); if (newList == NULL) { mprintf(LOGG_ERROR, "string_list_add: Failed to allocate memory for optional database list entry.\n"); status = FC_EMEM; @@ -1142,7 +1142,7 @@ fc_error_t select_from_official_databases( goto done; } - selectedDatabases = cli_max_calloc(nStandardDatabases + nOptionalDatabases, sizeof(char *)); + selectedDatabases = calloc(nStandardDatabases + nOptionalDatabases, sizeof(char *)); /* * Select desired standard databases. @@ -1261,7 +1261,7 @@ fc_error_t select_specific_databases( *databaseList = NULL; *nDatabases = 0; - selectedDatabases = cli_max_calloc(nSpecificDatabases, sizeof(char *)); + selectedDatabases = calloc(nSpecificDatabases, sizeof(char *)); /* * Get lists of available databases. diff --git a/libclamav/cvd.c b/libclamav/cvd.c index 70d8383568..88f94d024d 100644 --- a/libclamav/cvd.c +++ b/libclamav/cvd.c @@ -88,7 +88,7 @@ static int cli_untgz(int fd, const char *destdir) return -1; } - path = (char *)cli_max_calloc(sizeof(char), pathlen); + path = (char *)calloc(sizeof(char), pathlen); if (!path) { cli_errmsg("cli_untgz: Can't allocate memory for path\n"); cli_untgz_cleanup(NULL, infile, NULL, fdd); @@ -259,7 +259,7 @@ static int cli_tgzload(int fd, struct cl_engine *engine, unsigned int *signo, un } dbio->bufsize = CLI_DEFAULT_DBIO_BUFSIZE; - dbio->buf = cli_max_malloc(dbio->bufsize); + dbio->buf = malloc(dbio->bufsize); if (!dbio->buf) { cli_errmsg("cli_tgzload: Can't allocate memory for dbio->buf\n"); cli_tgzload_cleanup(compr, dbio, fdd); diff --git a/libclamav/dsig.c b/libclamav/dsig.c index 77dbc6d494..b0cf212f07 100644 --- a/libclamav/dsig.c +++ b/libclamav/dsig.c @@ -139,7 +139,7 @@ static unsigned char *cli_decodesig(const char *sig, unsigned int plen, BIGNUM * bn_bytes, plen); goto done; } - plain = cli_max_calloc(plen, sizeof(unsigned char)); + plain = calloc(plen, sizeof(unsigned char)); if (!plain) { cli_errmsg("cli_decodesig: Can't allocate memory for 'plain'\n"); goto done; diff --git a/libclamav/others.c b/libclamav/others.c index 21d0361fca..37b9327f8b 100644 --- a/libclamav/others.c +++ b/libclamav/others.c @@ -269,7 +269,7 @@ static void *get_module_function(HMODULE handle, const char *name) static void *get_module_function(void *handle, const char *name) { void *procAddress = NULL; - procAddress = dlsym(handle, name); + procAddress = dlsym(handle, name); if (NULL == procAddress) { const char *err = dlerror(); if (NULL == err) { @@ -1665,7 +1665,7 @@ size_t cli_recursion_stack_get_size(cli_ctx *ctx, int index) /* * Windows doesn't allow you to delete a directory while it is still open */ -int cli_rmdirs(const char *name) +int cli_rmdirs(const char *dirname) { int rc; STATBUF statb; @@ -1673,17 +1673,17 @@ int cli_rmdirs(const char *name) struct dirent *dent; char err[128]; - if (CLAMSTAT(name, &statb) < 0) { - cli_warnmsg("cli_rmdirs: Can't locate %s: %s\n", name, cli_strerror(errno, err, sizeof(err))); + if (CLAMSTAT(dirname, &statb) < 0) { + cli_warnmsg("cli_rmdirs: Can't locate %s: %s\n", dirname, cli_strerror(errno, err, sizeof(err))); return -1; } if (!S_ISDIR(statb.st_mode)) { - if (cli_unlink(name)) return -1; + if (cli_unlink(dirname)) return -1; return 0; } - if ((dd = opendir(name)) == NULL) + if ((dd = opendir(dirname)) == NULL) return -1; rc = 0; @@ -1696,15 +1696,14 @@ int cli_rmdirs(const char *name) if (strcmp(dent->d_name, "..") == 0) continue; - path = cli_max_malloc(strlen(name) + strlen(dent->d_name) + 2); - + path = malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (path == NULL) { - cli_errmsg("cli_rmdirs: Unable to allocate memory for path %u\n", strlen(name) + strlen(dent->d_name) + 2); + cli_errmsg("cli_rmdirs: Unable to allocate memory for path %u\n", strlen(dirname) + strlen(dent->d_name) + 2); closedir(dd); return -1; } - sprintf(path, "%s\\%s", name, dent->d_name); + sprintf(path, "%s\\%s", dirname, dent->d_name); rc = cli_rmdirs(path); free(path); if (rc != 0) @@ -1713,8 +1712,8 @@ int cli_rmdirs(const char *name) closedir(dd); - if (rmdir(name) < 0) { - cli_errmsg("cli_rmdirs: Can't remove temporary directory %s: %s\n", name, cli_strerror(errno, err, sizeof(err))); + if (rmdir(dirname) < 0) { + cli_errmsg("cli_rmdirs: Can't remove temporary directory %s: %s\n", dirname, cli_strerror(errno, err, sizeof(err))); return -1; } @@ -1742,7 +1741,7 @@ int cli_rmdirs(const char *dirname) while ((dent = readdir(dd))) { if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) { - path = cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 2); + path = malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (!path) { cli_errmsg("cli_rmdirs: Unable to allocate memory for path %llu\n", (long long unsigned)(strlen(dirname) + strlen(dent->d_name) + 2)); closedir(dd); diff --git a/libclamav/others_common.c b/libclamav/others_common.c index e60858b27a..6700cd1fca 100644 --- a/libclamav/others_common.c +++ b/libclamav/others_common.c @@ -221,8 +221,7 @@ void *cli_max_malloc(size_t size) void *alloc; if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_max_malloc(): File or section is too large to scan (%zu bytes). \ - For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_max_malloc(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; } @@ -243,8 +242,7 @@ void *cli_max_calloc(size_t nmemb, size_t size) void *alloc; if (!nmemb || 0 == size || size > CLI_MAX_ALLOCATION || nmemb > CLI_MAX_ALLOCATION || (nmemb * size > CLI_MAX_ALLOCATION)) { - cli_warnmsg("cli_max_calloc(): File or section is too large to scan (%zu bytes). \ - For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_max_calloc(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; } @@ -311,8 +309,7 @@ void *cli_max_realloc(void *ptr, size_t size) void *alloc; if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_max_realloc(): File or section is too large to scan (%zu bytes). \ - For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_max_realloc(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; } @@ -333,8 +330,7 @@ void *cli_max_realloc2(void *ptr, size_t size) void *alloc; if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_max_realloc2(): File or section is too large to scan (%zu bytes). \ - For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_max_realloc2(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; } diff --git a/libclamav/pe.c b/libclamav/pe.c index dae6c89aff..a2decd941d 100644 --- a/libclamav/pe.c +++ b/libclamav/pe.c @@ -2297,7 +2297,7 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str break; \ } \ \ - fname = cli_max_calloc(funclen + dlllen + 3, sizeof(char)); \ + fname = cli_max_calloc(funclen + dlllen + 3, sizeof(char)); \ if (fname == NULL) { \ cli_dbgmsg("scan_pe: cannot allocate memory for imphash string\n"); \ ret = CL_EMEM; \ @@ -2335,7 +2335,7 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str thuoff += sizeof(struct pe_image_thunk32); - temp = EC32(thunk32.u.Ordinal); + temp = EC32(thunk32.u.Ordinal); thunk32.u.Ordinal = temp; if (!(thunk32.u.Ordinal & PE_IMAGEDIR_ORDINAL_FLAG32)) { @@ -5849,22 +5849,22 @@ cl_error_t cli_genhash_pe(cli_ctx *ctx, unsigned int class, int type, stats_sect case 1: genhash[CLI_HASH_MD5] = 1; hlen = hashlen[CLI_HASH_MD5]; - hash = hashset[CLI_HASH_MD5] = cli_max_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_MD5] = calloc(hlen, sizeof(char)); break; case 2: genhash[CLI_HASH_SHA1] = 1; hlen = hashlen[CLI_HASH_SHA1]; - hash = hashset[CLI_HASH_SHA1] = cli_max_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_SHA1] = calloc(hlen, sizeof(char)); break; default: genhash[CLI_HASH_SHA256] = 1; hlen = hashlen[CLI_HASH_SHA256]; - hash = hashset[CLI_HASH_SHA256] = cli_max_calloc(hlen, sizeof(char)); + hash = hashset[CLI_HASH_SHA256] = calloc(hlen, sizeof(char)); break; } if (!hash) { - cli_errmsg("cli_genhash_pe: cli_max_calloc failed!\n"); + cli_errmsg("cli_genhash_pe: calloc failed!\n"); cli_exe_info_destroy(peinfo); return CL_EMEM; } diff --git a/libfreshclam/libfreshclam.c b/libfreshclam/libfreshclam.c index 0d0ff64ad7..2b1a39c258 100644 --- a/libfreshclam/libfreshclam.c +++ b/libfreshclam/libfreshclam.c @@ -227,7 +227,7 @@ fc_error_t fc_initialize(fc_config *fcConfig) #else if (fcConfig->databaseDirectory[strlen(fcConfig->databaseDirectory) - 1] != '/') { #endif - g_databaseDirectory = cli_max_malloc(strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1); + g_databaseDirectory = malloc(strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1); snprintf( g_databaseDirectory, strlen(fcConfig->databaseDirectory) + strlen(PATHSEP) + 1, diff --git a/sigtool/sigtool.c b/sigtool/sigtool.c index e4a6faa010..c3720740f6 100644 --- a/sigtool/sigtool.c +++ b/sigtool/sigtool.c @@ -2762,7 +2762,7 @@ static int decodehex(const char *hexsig) trigger[tlen] = '\0'; /* get the regex expression */ - regex = cli_max_calloc(rlen + 1, sizeof(char)); + regex = calloc(rlen + 1, sizeof(char)); if (!regex) { mprintf(LOGG_ERROR, "cannot allocate memory for regex expression\n"); free(trigger); @@ -2773,7 +2773,7 @@ static int decodehex(const char *hexsig) /* get the compile flags */ if (clen) { - cflags = cli_max_calloc(clen + 1, sizeof(char)); + cflags = calloc(clen + 1, sizeof(char)); if (!cflags) { mprintf(LOGG_ERROR, "cannot allocate memory for compile flags\n"); free(trigger); diff --git a/unit_tests/check_bytecode.c b/unit_tests/check_bytecode.c index 0ec9816e1f..a07e3b0a5f 100644 --- a/unit_tests/check_bytecode.c +++ b/unit_tests/check_bytecode.c @@ -83,8 +83,8 @@ static void runtest(const char *file, uint64_t expected, int fail, int nojit, cctx.dconf = cctx.engine->dconf; cctx.recursion_stack_size = cctx.engine->max_recursion_level; - cctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); - ck_assert_msg(!!cctx.recursion_stack, "cli_max_calloc() for recursion_stack failed"); + cctx.recursion_stack = calloc(sizeof(recursion_level_t), cctx.recursion_stack_size); + ck_assert_msg(!!cctx.recursion_stack, "calloc() for recursion_stack failed"); // ctx was memset, so recursion_level starts at 0. cctx.recursion_stack[cctx.recursion_level].fmap = NULL; @@ -509,8 +509,8 @@ static void runload(const char *dbname, struct cl_engine *engine, unsigned signo /* when run from automake srcdir is set, but if run manually then not */ srcdir = SRCDIR; } - str = cli_max_malloc(strlen(srcdir) + 1 + strlen(dbname) + 1); - ck_assert_msg(!!str, "cli_max_malloc"); + str = malloc(strlen(srcdir) + 1 + strlen(dbname) + 1); + ck_assert_msg(!!str, "malloc"); sprintf(str, "%s" PATHSEP "%s", srcdir, dbname); rc = cl_load(str, engine, &signo, CL_DB_STDOPT); diff --git a/unit_tests/check_clamav.c b/unit_tests/check_clamav.c index 6f0d39e862..0a46e7d45d 100644 --- a/unit_tests/check_clamav.c +++ b/unit_tests/check_clamav.c @@ -581,8 +581,8 @@ static void init_testfiles(void) if (strncmp(dirent->d_name, "clam", 4)) continue; i++; - testfiles = cli_max_realloc(testfiles, i * sizeof(*testfiles)); - ck_assert_msg(!!testfiles, "cli_max_realloc"); + testfiles = cli_safer_realloc(testfiles, i * sizeof(*testfiles)); + ck_assert_msg(!!testfiles, "cli_safer_realloc"); testfiles[i - 1] = strdup(dirent->d_name); } testfiles_n = i; @@ -1921,8 +1921,8 @@ int open_testfile(const char *name, int flags) srcdir = SRCDIR; } - str = cli_max_malloc(strlen(name) + strlen(srcdir) + 2); - ck_assert_msg(!!str, "cli_max_malloc"); + str = malloc(strlen(name) + strlen(srcdir) + 2); + ck_assert_msg(!!str, "malloc"); sprintf(str, "%s" PATHSEP "%s", srcdir, name); fd = open(str, flags); @@ -1935,7 +1935,7 @@ void diff_file_mem(int fd, const char *ref, size_t len) { char c1, c2; size_t p, reflen = len; - char *buf = cli_max_malloc(len); + char *buf = malloc(len); ck_assert_msg(!!buf, "unable to malloc buffer: %zu", len); p = read(fd, buf, len); @@ -1964,7 +1964,7 @@ void diff_files(int fd, int ref_fd) off_t siz = lseek(ref_fd, 0, SEEK_END); ck_assert_msg(siz != -1, "lseek failed"); - ref = cli_max_malloc(siz); + ref = malloc(siz); ck_assert_msg(!!ref, "unable to malloc buffer: " STDi64, (int64_t)siz); ck_assert_msg(lseek(ref_fd, 0, SEEK_SET) == 0, "lseek failed"); diff --git a/unit_tests/check_matchers.c b/unit_tests/check_matchers.c index c84aee5c34..ec27cceb9d 100644 --- a/unit_tests/check_matchers.c +++ b/unit_tests/check_matchers.c @@ -178,8 +178,8 @@ static void setup(void) ctx.dconf = ctx.engine->dconf; ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); - ck_assert_msg(!!ctx.recursion_stack, "cli_max_calloc() for recursion_stack failed"); + ctx.recursion_stack = calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ck_assert_msg(!!ctx.recursion_stack, "calloc() for recursion_stack failed"); // ctx was memset, so recursion_level starts at 0. ctx.recursion_stack[ctx.recursion_level].fmap = &thefmap; @@ -478,7 +478,7 @@ START_TEST(test_pcre_scanbuff) for (i = 0; pcre_testdata[i].data; i++) { hexlen = strlen(PCRE_BYPASS) + strlen(pcre_testdata[i].hexsig) + 1; - hexsig = cli_max_calloc(hexlen, sizeof(char)); + hexsig = calloc(hexlen, sizeof(char)); ck_assert_msg(hexsig != NULL, "[pcre] failed to prepend bypass (out-of-memory)"); strncat(hexsig, PCRE_BYPASS, hexlen); @@ -532,7 +532,7 @@ START_TEST(test_pcre_scanbuff_allscan) for (i = 0; pcre_testdata[i].data; i++) { hexlen = strlen(PCRE_BYPASS) + strlen(pcre_testdata[i].hexsig) + 1; - hexsig = cli_max_calloc(hexlen, sizeof(char)); + hexsig = calloc(hexlen, sizeof(char)); ck_assert_msg(hexsig != NULL, "[pcre] failed to prepend bypass (out-of-memory)"); strncat(hexsig, PCRE_BYPASS, hexlen); From 42145e8a7ba3eb33dd557b07df81938e937fba06 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 8 Jan 2024 22:50:17 -0500 Subject: [PATCH 05/12] Remove duplicate max-alloc checks for lzma and 7z alloc functions Some sort of code merge way-back-when resulted in two identical max-allocation checks. I removed the noisy ones. --- libclamav/lzma_iface.c | 4 +--- libclamav/xz_iface.c | 6 ++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/libclamav/lzma_iface.c b/libclamav/lzma_iface.c index 163a9327b2..3f4dc17bdd 100644 --- a/libclamav/lzma_iface.c +++ b/libclamav/lzma_iface.c @@ -34,10 +34,8 @@ void *__lzma_wrap_alloc(void *unused, size_t size) { UNUSEDPARAM(unused); - if (!size || size > CLI_MAX_ALLOCATION) - return NULL; + if (!size || size > CLI_MAX_ALLOCATION) { - cli_dbgmsg("lzma_wrap_alloc(): Attempt to allocate %lu bytes.\n", (unsigned long int)size); return NULL; } diff --git a/libclamav/xz_iface.c b/libclamav/xz_iface.c index 0565f8e532..7b52abc672 100644 --- a/libclamav/xz_iface.c +++ b/libclamav/xz_iface.c @@ -33,13 +33,11 @@ void __xz_wrap_free(void *unused, void *freeme); void *__xz_wrap_alloc(void *unused, size_t size) { UNUSEDPARAM(unused); - if (!size || size > CLI_MAX_ALLOCATION) - return NULL; + if (!size || size > CLI_MAX_ALLOCATION) { - cli_dbgmsg("xz_iface: Attempt to allocate %lu bytes exceeds CLI_MAX_ALLOCATION.\n", - (unsigned long int)size); return NULL; } + return cli_max_malloc(size); } void __xz_wrap_free(void *unused, void *freeme) From 5255d678a56f81703d0cca7c327bf53a8d56a3cb Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 8 Jan 2024 22:51:17 -0500 Subject: [PATCH 06/12] Remove duplicate copy of CLI_STRDUP macro A code merge resulted in a duplicate copy of the CLI_STRDUP macro. Also fixed formatting. --- libclamav/others.h | 65 +++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/libclamav/others.h b/libclamav/others.h index 5874b119a9..f2f1a54d0a 100644 --- a/libclamav/others.h +++ b/libclamav/others.h @@ -1018,7 +1018,14 @@ void *cli_safer_realloc(void *ptr, size_t size); */ void *cli_safer_realloc2(void *ptr, size_t size); +/** + * @brief Wrapper around strdup that does a NULL check. + * + * @param s + * @return char* Returns the allocated string or NULL if allocation failed. This includes if allocation fails because s==NULL. + */ char *cli_strdup(const char *s); + int cli_rmdirs(const char *dirname); char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type); char *cli_hashfile(const char *filename, int type); @@ -1342,14 +1349,14 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); #ifndef CLI_MAX_MALLOC #define CLI_MAX_MALLOC(var, size, ...) \ - do { \ + do { \ var = cli_max_malloc(size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif @@ -1368,14 +1375,14 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); #ifndef CLI_MAX_CALLOC #define CLI_MAX_CALLOC(var, nmemb, size, ...) \ - do { \ + do { \ (var) = cli_max_calloc(nmemb, size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif @@ -1429,29 +1436,15 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); */ #ifndef CLI_SAFER_REALLOC #define CLI_SAFER_REALLOC(ptr, size, ...) \ - do { \ + do { \ void *vTmp = cli_safer_realloc(ptr, size); \ - if (NULL == vTmp) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ - ptr = vTmp; \ - } while (0) -#endif - -/*This is a duplicate from other PR's.*/ -#ifndef CLI_STRDUP -#define CLI_STRDUP(buf, var, ...) \ - do { \ - var = cli_strdup(buf); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ + if (NULL == vTmp) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ + ptr = vTmp; \ } while (0) #endif From 6d354ca50be4fefea64e83d284d60883f7dfd4e0 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Mon, 8 Jan 2024 22:53:42 -0500 Subject: [PATCH 07/12] Add max-allocation limit to bytecode API's malloc function Bytecode signature's are able to allocate buffers, but should probably adhere to clamav's max allocation limit. This adds a check to make sure they don't accidentally alloc too much based on untrusted user input. --- libclamav/bytecode_api.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/libclamav/bytecode_api.c b/libclamav/bytecode_api.c index 33a1be49be..827e28decd 100644 --- a/libclamav/bytecode_api.c +++ b/libclamav/bytecode_api.c @@ -470,7 +470,14 @@ uint8_t *cli_bcapi_malloc(struct cli_bc_ctx *ctx, uint32_t size) return NULL; } } - v = MPOOL_MALLOC(ctx->mpool, size); + + if (0 == size || size > CLI_MAX_ALLOCATION) { + cli_warnmsg("cli_bcapi_malloc(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + size, CLI_MAX_ALLOCATION); + v = NULL; + } else { + v = MPOOL_MALLOC(ctx->mpool, size); + } #else /* TODO: implement using a list of pointers we allocated! */ cli_errmsg("cli_bcapi_malloc not implemented for systems without mmap yet!\n"); From 0deced4351da4b3d559a06fd254e65829c597ec9 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Tue, 9 Jan 2024 16:28:51 -0500 Subject: [PATCH 08/12] Remove unnecessary max-allocation limit checks from bytecode runtime Allocations for bytecode signatures to work need not check against the memory allocation limit, as bytecode signatures are considered trusted user input. You may note that I did not remove allocation limits from the bytecode API functions that may be called by the signatures such as adding json objects, hashsets, lzma and bz2 decompressors, etc. This is because it is likely that a bytecode signature may call them more times based on the structure of the file being scanned - particularly for the json objects. --- libclamav/bytecode.c | 54 ++++++++++++++++++++--------------------- libclamav/bytecode_vm.c | 38 ++++++++++++++--------------- libclamav/events.c | 8 +++--- 3 files changed, 50 insertions(+), 50 deletions(-) diff --git a/libclamav/bytecode.c b/libclamav/bytecode.c index e449eb5572..c15336941b 100644 --- a/libclamav/bytecode.c +++ b/libclamav/bytecode.c @@ -340,12 +340,12 @@ cl_error_t cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct c ctx->numParams = func->numArgs; ctx->funcid = funcid; if (func->numArgs) { - ctx->operands = cli_max_malloc(sizeof(*ctx->operands) * func->numArgs); + ctx->operands = malloc(sizeof(*ctx->operands) * func->numArgs); if (!ctx->operands) { cli_errmsg("bytecode: error allocating memory for parameters\n"); return CL_EMEM; } - ctx->opsizes = cli_max_malloc(sizeof(*ctx->opsizes) * func->numArgs); + ctx->opsizes = malloc(sizeof(*ctx->opsizes) * func->numArgs); if (!ctx->opsizes) { cli_errmsg("bytecode: error allocating memory for opsizes\n"); return CL_EMEM; @@ -359,7 +359,7 @@ cl_error_t cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct c } s += 8; /* return value */ ctx->bytes = s; - ctx->values = cli_max_malloc(s); + ctx->values = malloc(s); if (!ctx->values) { cli_errmsg("bytecode: error allocating memory for parameters\n"); return CL_EMEM; @@ -507,7 +507,7 @@ static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p, uint16_t ty; p[*off] |= 0x20; /* TODO: unique constants */ - func->constants = cli_max_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); + func->constants = cli_safer_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); if (!func->constants) { *ok = false; return MAX_OP; @@ -565,7 +565,7 @@ static inline char *readData(const unsigned char *p, unsigned *off, unsigned len *ok = false; return 0; } - dat = cli_max_malloc(l); + dat = malloc(l); if (!dat) { cli_errmsg("Cannot allocate memory for data\n"); *ok = false; @@ -679,12 +679,12 @@ static cl_error_t parseHeader(struct cli_bc *bc, unsigned char *buffer, unsigned return CL_EMALFDB; } - bc->funcs = cli_max_calloc(bc->num_func, sizeof(*bc->funcs)); + bc->funcs = calloc(bc->num_func, sizeof(*bc->funcs)); if (!bc->funcs) { cli_errmsg("Out of memory allocating %u functions\n", bc->num_func); return CL_EMEM; } - bc->types = cli_max_calloc(bc->num_types, sizeof(*bc->types)); + bc->types = calloc(bc->num_types, sizeof(*bc->types)); if (!bc->types) { cli_errmsg("Out of memory allocating %u types\n", bc->num_types); return CL_EMEM; @@ -737,7 +737,7 @@ static void parseType(struct cli_bc *bc, struct cli_bc_type *ty, *ok = false; return; } - ty->containedTypes = cli_max_malloc(sizeof(*ty->containedTypes) * ty->numElements); + ty->containedTypes = malloc(sizeof(*ty->containedTypes) * ty->numElements); if (!ty->containedTypes) { cli_errmsg("Out of memory allocating %u types\n", ty->numElements); *ok = false; @@ -926,7 +926,7 @@ static cl_error_t parseApis(struct cli_bc *bc, unsigned char *buffer) cli_errmsg("Out of memory allocating apis bitset\n"); return CL_EMEM; } - apity2ty = cli_max_calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types)); + apity2ty = calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types)); if (!apity2ty) { cli_errmsg("Out of memory allocating apity2ty\n"); return CL_EMEM; @@ -1041,12 +1041,12 @@ static cl_error_t parseGlobals(struct cli_bc *bc, unsigned char *buffer) return CL_BREAK; } numglobals = readNumber(buffer, &offset, len, &ok); - bc->globals = cli_max_calloc(numglobals, sizeof(*bc->globals)); + bc->globals = calloc(numglobals, sizeof(*bc->globals)); if (!bc->globals) { cli_errmsg("bytecode: OOM allocating memory for %u globals\n", numglobals); return CL_EMEM; } - bc->globaltys = cli_max_calloc(numglobals, sizeof(*bc->globaltys)); + bc->globaltys = calloc(numglobals, sizeof(*bc->globaltys)); if (!bc->globaltys) { cli_errmsg("bytecode: OOM allocating memory for %u global types\n", numglobals); return CL_EMEM; @@ -1060,7 +1060,7 @@ static cl_error_t parseGlobals(struct cli_bc *bc, unsigned char *buffer) comp = type_components(bc, bc->globaltys[i], &ok); if (!ok) return CL_EMALFDB; - bc->globals[i] = cli_max_malloc(sizeof(*bc->globals[0]) * comp); + bc->globals[i] = malloc(sizeof(*bc->globals[0]) * comp); if (!bc->globals[i]) return CL_EMEM; readConstant(bc, i, comp, buffer, &offset, len, &ok); @@ -1089,7 +1089,7 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) } b = bc->dbgnode_cnt; bc->dbgnode_cnt += numMD; - bc->dbgnodes = cli_max_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes)); + bc->dbgnodes = cli_safer_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes)); if (!bc->dbgnodes) return CL_EMEM; for (i = 0; i < numMD; i++) { @@ -1101,7 +1101,7 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) return CL_EMALFDB; } bc->dbgnodes[b + i].numelements = el; - bc->dbgnodes[b + i].elements = elts = cli_max_calloc(el, sizeof(*elts)); + bc->dbgnodes[b + i].elements = elts = calloc(el, sizeof(*elts)); if (!elts) return CL_EMEM; for (j = 0; j < el; j++) { @@ -1161,7 +1161,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c if (!all_locals) { func->types = NULL; } else { - func->types = cli_max_calloc(all_locals, sizeof(*func->types)); + func->types = calloc(all_locals, sizeof(*func->types)); if (!func->types) { cli_errmsg("Out of memory allocating function arguments\n"); return CL_EMEM; @@ -1189,7 +1189,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c func->numValues = func->numArgs + func->numLocals; func->insn_idx = 0; func->numConstants = 0; - func->allinsts = cli_max_calloc(func->numInsts, sizeof(*func->allinsts)); + func->allinsts = calloc(func->numInsts, sizeof(*func->allinsts)); if (!func->allinsts) { cli_errmsg("Out of memory allocating instructions\n"); return CL_EMEM; @@ -1199,7 +1199,7 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c cli_errmsg("Invalid basic block count\n"); return CL_EMALFDB; } - func->BB = cli_max_calloc(func->numBB, sizeof(*func->BB)); + func->BB = calloc(func->numBB, sizeof(*func->BB)); if (!func->BB) { cli_errmsg("Out of memory allocating basic blocks\n"); return CL_EMEM; @@ -1303,7 +1303,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne if (!numOp) { inst.u.ops.ops = NULL; } else { - inst.u.ops.ops = cli_max_calloc(numOp, sizeof(*inst.u.ops.ops)); + inst.u.ops.ops = calloc(numOp, sizeof(*inst.u.ops.ops)); if (!inst.u.ops.ops) { cli_errmsg("Out of memory allocating operands\n"); return CL_EMEM; @@ -1348,7 +1348,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne if (ok) { inst.u.ops.numOps = numOp + 2; inst.u.ops.opsizes = NULL; - inst.u.ops.ops = cli_max_calloc(numOp + 2, sizeof(*inst.u.ops.ops)); + inst.u.ops.ops = calloc(numOp + 2, sizeof(*inst.u.ops.ops)); if (!inst.u.ops.ops) { cli_errmsg("Out of memory allocating operands\n"); return CL_EMEM; @@ -1468,7 +1468,7 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne cli_errmsg("invalid number of dbg nodes, expected: %u, got: %u\n", bcfunc->numInsts, num); return CL_EMALFDB; } - bcfunc->dbgnodes = cli_max_malloc(num * sizeof(*bcfunc->dbgnodes)); + bcfunc->dbgnodes = malloc(num * sizeof(*bcfunc->dbgnodes)); if (!bcfunc->dbgnodes) { cli_errmsg("Unable to allocate memory for dbg nodes: %u\n", num * (uint32_t)sizeof(*bcfunc->dbgnodes)); return CL_EMEM; @@ -1659,7 +1659,7 @@ cl_error_t cli_bytecode_load(struct cli_bc *bc, FILE *f, struct cli_dbio *dbio, cli_errmsg("Error at bytecode line %u\n", row); return rc; } - buffer = cli_max_malloc(linelength); + buffer = malloc(linelength); if (!buffer) { cli_errmsg("Out of memory allocating line of length %u\n", linelength); return CL_EMEM; @@ -2135,7 +2135,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) unsigned bcglobalid = cli_apicall_maxglobal - _FIRST_GLOBAL + 2; cl_error_t ret = CL_SUCCESS; bc->numGlobalBytes = 0; - gmap = cli_max_malloc(bc->num_globals * sizeof(*gmap)); + gmap = malloc(bc->num_globals * sizeof(*gmap)); if (!gmap) { cli_errmsg("interpreter: Unable to allocate memory for global map: %zu\n", bc->num_globals * sizeof(*gmap)); return CL_EMEM; @@ -2149,7 +2149,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) bc->numGlobalBytes += typesize(bc, ty); } if (bc->numGlobalBytes) { - bc->globalBytes = cli_max_calloc(1, bc->numGlobalBytes); + bc->globalBytes = calloc(1, bc->numGlobalBytes); if (!bc->globalBytes) { cli_errmsg("interpreter: Unable to allocate memory for globalBytes: %u\n", bc->numGlobalBytes); free(gmap); @@ -2215,7 +2215,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) for (i = 0; i < bc->num_func && ret == CL_SUCCESS; i++) { struct cli_bc_func *bcfunc = &bc->funcs[i]; unsigned totValues = bcfunc->numValues + bcfunc->numConstants + bc->num_globals; - unsigned *map = cli_max_malloc(sizeof(*map) * (size_t)totValues); + unsigned *map = malloc(sizeof(*map) * (size_t)totValues); if (!map) { cli_errmsg("interpreter: Unable to allocate memory for map: %zu\n", sizeof(*map) * (size_t)totValues); free(gmap); @@ -2311,7 +2311,7 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) if (ret != CL_SUCCESS) break; if (inst->u.ops.numOps > 0) { - inst->u.ops.opsizes = cli_max_malloc(sizeof(*inst->u.ops.opsizes) * inst->u.ops.numOps); + inst->u.ops.opsizes = malloc(sizeof(*inst->u.ops.opsizes) * inst->u.ops.numOps); if (!inst->u.ops.opsizes) { cli_errmsg("Out of memory when allocating operand sizes\n"); ret = CL_EMEM; @@ -2407,7 +2407,7 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) struct cli_bc_inst *inst; struct cli_bc *bc; - bcs->all_bcs = cli_max_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_safer_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; @@ -2608,7 +2608,7 @@ static cl_error_t run_builtin_or_loaded(struct cli_all_bc *bcs, uint8_t kind, co if (!bc) { /* no loaded bytecode found, load the builtin one! */ struct cli_dbio dbio; - bc = cli_max_calloc(1, sizeof(*bc)); + bc = calloc(1, sizeof(*bc)); if (!bc) { cli_errmsg("Out of memory allocating bytecode\n"); return CL_EMEM; diff --git a/libclamav/bytecode_vm.c b/libclamav/bytecode_vm.c index 43997ec693..ac0d784896 100644 --- a/libclamav/bytecode_vm.c +++ b/libclamav/bytecode_vm.c @@ -286,17 +286,17 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, *(uint8_t *)&values[p] = x #define WRITE16(p, x) \ CHECK_GT(func->numBytes, p + 1); \ - CHECK_EQ((p)&1, 0); \ + CHECK_EQ((p) & 1, 0); \ TRACE_W(x, p, 16); \ *(uint16_t *)&values[p] = x #define WRITE32(p, x) \ CHECK_GT(func->numBytes, p + 3); \ - CHECK_EQ((p)&3, 0); \ + CHECK_EQ((p) & 3, 0); \ TRACE_W(x, p, 32); \ *(uint32_t *)&values[p] = x #define WRITE64(p, x) \ CHECK_GT(func->numBytes, p + 7); \ - CHECK_EQ((p)&7, 0); \ + CHECK_EQ((p) & 7, 0); \ TRACE_W(x, p, 64); \ *(uint64_t *)&values[p] = x #define WRITEP(x, p) \ @@ -346,16 +346,16 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, } \ TRACE_R(x) \ } -#define READPOP(x, p, asize) \ - { \ - if ((p)&0x40000000) { \ - unsigned ptr__ = (p)&0xbfffffff; \ - CHECK_GT(func->numBytes, ptr__); \ - TRACE_PTR(ptr__, asize); \ - x = (void *)&values[ptr__]; \ - } else { \ - READP(x, p, asize) \ - } \ +#define READPOP(x, p, asize) \ + { \ + if ((p) & 0x40000000) { \ + unsigned ptr__ = (p) & 0xbfffffff; \ + CHECK_GT(func->numBytes, ptr__); \ + TRACE_PTR(ptr__, asize); \ + x = (void *)&values[ptr__]; \ + } else { \ + READP(x, p, asize) \ + } \ } #define READOLD8(x, p) \ @@ -364,17 +364,17 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, TRACE_R(x) #define READOLD16(x, p) \ CHECK_GT(func->numBytes, p + 1); \ - CHECK_EQ((p)&1, 0); \ + CHECK_EQ((p) & 1, 0); \ x = *(uint16_t *)&old_values[p]; \ TRACE_R(x) #define READOLD32(x, p) \ CHECK_GT(func->numBytes, p + 3); \ - CHECK_EQ((p)&3, 0); \ + CHECK_EQ((p) & 3, 0); \ x = *(uint32_t *)&old_values[p]; \ TRACE_R(x) #define READOLD64(x, p) \ CHECK_GT(func->numBytes, p + 7); \ - CHECK_EQ((p)&7, 0); \ + CHECK_EQ((p) & 7, 0); \ x = *(uint64_t *)&old_values[p]; \ TRACE_R(x) @@ -596,8 +596,8 @@ static inline int64_t ptr_register_stack(struct ptr_infos *infos, uint32_t off, uint32_t size) { unsigned n = infos->nstacks + 1; - struct ptr_info *sinfos = cli_max_realloc(infos->stack_infos, - sizeof(*sinfos) * n); + struct ptr_info *sinfos = cli_safer_realloc(infos->stack_infos, + sizeof(*sinfos) * n); if (!sinfos) return 0; infos->stack_infos = sinfos; @@ -613,7 +613,7 @@ static inline int64_t ptr_register_glob_fixedid(struct ptr_infos *infos, { struct ptr_info *sinfos; if (n > infos->nglobs) { - sinfos = cli_max_realloc(infos->glob_infos, sizeof(*sinfos) * n); + sinfos = cli_safer_realloc(infos->glob_infos, sizeof(*sinfos) * n); if (!sinfos) return 0; memset(sinfos + infos->nglobs, 0, (n - infos->nglobs) * sizeof(*sinfos)); diff --git a/libclamav/events.c b/libclamav/events.c index 6a72158ef1..60e8785a59 100644 --- a/libclamav/events.c +++ b/libclamav/events.c @@ -54,7 +54,7 @@ cli_events_t *cli_events_new(unsigned max_event) if (!ev) return NULL; ev->max = max_event; - ev->events = cli_max_calloc(max_event, sizeof(*ev->events)); + ev->events = calloc(max_event, sizeof(*ev->events)); if (!ev->events) { free(ev); return NULL; @@ -132,7 +132,7 @@ static inline void ev_chain(cli_events_t *ctx, struct cli_event *ev, union ev_va union ev_val *chain; uint32_t siz = sizeof(*chain) * (ev->count + 1); - chain = cli_max_realloc(ev->u.v_chain, siz); + chain = cli_safer_realloc(ev->u.v_chain, siz); if (!chain) { cli_event_error_oom(ctx, siz); return; @@ -294,7 +294,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l } switch (ev->multiple) { case multiple_last: { - void *v_data = cli_max_realloc2(ev->u.v_data, len); + void *v_data = cli_safer_realloc2(ev->u.v_data, len); if (v_data) { ev->u.v_data = v_data; memcpy(v_data, data, len); @@ -305,7 +305,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l break; } case multiple_concat: { - void *v_data = cli_max_realloc2(ev->u.v_data, ev->count + len); + void *v_data = cli_safer_realloc2(ev->u.v_data, ev->count + len); if (v_data) { ev->u.v_data = v_data; memcpy((char *)v_data + ev->count, data, len); From 4ad8a9aa9eda7601148ce3250761848d1a7168bd Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Tue, 9 Jan 2024 17:17:48 -0500 Subject: [PATCH 09/12] Remove additional memory allocation limits relating to signature load Variables like the number of signature parts are considered trusted user input and so allocations based on those values need not check the memory allocation limit. Specifically for the allocation of the normalized buffer in cli_scanscript, I determined that the size of SCANBUFF is fixed and so safe, and the maxpatlen comes from the signature load and is therefore also trusted, so we do not need to check the allocation limit. --- libclamav/bytecode_api.c | 2 +- libclamav/matcher-ac.c | 40 +++++++++++++++--------------- libclamav/matcher-bm.c | 4 +-- libclamav/matcher-byte-comp.c | 4 +-- libclamav/matcher-pcre.c | 6 ++--- libclamav/others.c | 6 ++--- libclamav/phishcheck.c | 2 +- libclamav/readdb.c | 46 +++++++++++++++++------------------ libclamav/scanners.c | 4 +-- 9 files changed, 57 insertions(+), 57 deletions(-) diff --git a/libclamav/bytecode_api.c b/libclamav/bytecode_api.c index 827e28decd..9d136387a3 100644 --- a/libclamav/bytecode_api.c +++ b/libclamav/bytecode_api.c @@ -472,7 +472,7 @@ uint8_t *cli_bcapi_malloc(struct cli_bc_ctx *ctx, uint32_t size) } if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_bcapi_malloc(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_bcapi_malloc(): File or section is too large to scan (%u bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); v = NULL; } else { diff --git a/libclamav/matcher-ac.c b/libclamav/matcher-ac.c index 11f9469562..c9feb8f09e 100644 --- a/libclamav/matcher-ac.c +++ b/libclamav/matcher-ac.c @@ -1412,7 +1412,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->reloffsigs = reloffsigs; if (reloffsigs) { - data->offset = (uint32_t *)cli_max_malloc(reloffsigs * 2 * sizeof(uint32_t)); + data->offset = (uint32_t *)malloc(reloffsigs * 2 * sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_ac_init: Can't allocate memory for data->offset\n"); return CL_EMEM; @@ -1423,7 +1423,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->partsigs = partsigs; if (partsigs) { - data->offmatrix = (uint32_t ***)cli_max_calloc(partsigs, sizeof(uint32_t **)); + data->offmatrix = (uint32_t ***)calloc(partsigs, sizeof(uint32_t **)); if (!data->offmatrix) { cli_errmsg("cli_ac_init: Can't allocate memory for data->offmatrix\n"); @@ -1436,7 +1436,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->lsigs = lsigs; if (lsigs) { - data->lsigcnt = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); + data->lsigcnt = (uint32_t **)malloc(lsigs * sizeof(uint32_t *)); if (!data->lsigcnt) { if (partsigs) free(data->offmatrix); @@ -1447,7 +1447,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigcnt\n"); return CL_EMEM; } - data->lsigcnt[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigcnt[0] = (uint32_t *)calloc(lsigs * 64, sizeof(uint32_t)); if (!data->lsigcnt[0]) { free(data->lsigcnt); if (partsigs) @@ -1461,7 +1461,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t } for (i = 1; i < lsigs; i++) data->lsigcnt[i] = data->lsigcnt[0] + 64 * i; - data->yr_matches = (uint8_t *)cli_max_calloc(lsigs, sizeof(uint8_t)); + data->yr_matches = (uint8_t *)calloc(lsigs, sizeof(uint8_t)); if (data->yr_matches == NULL) { free(data->lsigcnt[0]); free(data->lsigcnt); @@ -1474,7 +1474,7 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t } /* subsig offsets */ - data->lsig_matches = (struct cli_lsig_matches **)cli_max_calloc(lsigs, sizeof(struct cli_lsig_matches *)); + data->lsig_matches = (struct cli_lsig_matches **)calloc(lsigs, sizeof(struct cli_lsig_matches *)); if (!data->lsig_matches) { free(data->yr_matches); free(data->lsigcnt[0]); @@ -1488,8 +1488,8 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsig_matches\n"); return CL_EMEM; } - data->lsigsuboff_last = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); - data->lsigsuboff_first = (uint32_t **)cli_max_malloc(lsigs * sizeof(uint32_t *)); + data->lsigsuboff_last = (uint32_t **)malloc(lsigs * sizeof(uint32_t *)); + data->lsigsuboff_first = (uint32_t **)malloc(lsigs * sizeof(uint32_t *)); if (!data->lsigsuboff_last || !data->lsigsuboff_first) { free(data->lsig_matches); free(data->lsigsuboff_last); @@ -1506,8 +1506,8 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigsuboff_(last|first)\n"); return CL_EMEM; } - data->lsigsuboff_last[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); - data->lsigsuboff_first[0] = (uint32_t *)cli_max_calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigsuboff_last[0] = (uint32_t *)calloc(lsigs * 64, sizeof(uint32_t)); + data->lsigsuboff_first[0] = (uint32_t *)calloc(lsigs * 64, sizeof(uint32_t)); if (!data->lsigsuboff_last[0] || !data->lsigsuboff_first[0]) { free(data->lsig_matches); free(data->lsigsuboff_last[0]); @@ -1704,10 +1704,10 @@ cl_error_t lsig_sub_matched(const struct cli_matcher *root, struct cli_ac_data * ls_matches = mdata->lsig_matches[lsig_id]; if (ls_matches == NULL) { /* allocate cli_lsig_matches */ - ls_matches = mdata->lsig_matches[lsig_id] = (struct cli_lsig_matches *)cli_max_calloc(1, sizeof(struct cli_lsig_matches) + - (ac_lsig->tdb.subsigs - 1) * sizeof(struct cli_subsig_matches *)); + ls_matches = mdata->lsig_matches[lsig_id] = (struct cli_lsig_matches *)calloc(1, sizeof(struct cli_lsig_matches) + + (ac_lsig->tdb.subsigs - 1) * sizeof(struct cli_subsig_matches *)); if (ls_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_max_calloc failed for cli_lsig_matches\n"); + cli_errmsg("lsig_sub_matched: calloc failed for cli_lsig_matches\n"); return CL_EMEM; } ls_matches->subsigs = ac_lsig->tdb.subsigs; @@ -1716,16 +1716,16 @@ cl_error_t lsig_sub_matched(const struct cli_matcher *root, struct cli_ac_data * if (ss_matches == NULL) { /* allocate cli_subsig_matches */ ss_matches = ls_matches->matches[subsig_id] = malloc(sizeof(struct cli_subsig_matches)); if (ss_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_max_malloc failed for cli_subsig_matches struct\n"); + cli_errmsg("lsig_sub_matched: malloc failed for cli_subsig_matches struct\n"); return CL_EMEM; } ss_matches->next = 0; ss_matches->last = sizeof(ss_matches->offsets) / sizeof(uint32_t) - 1; } if (ss_matches->next > ss_matches->last) { /* cli_matches out of space? realloc */ - ss_matches = ls_matches->matches[subsig_id] = cli_max_realloc(ss_matches, sizeof(struct cli_subsig_matches) + sizeof(uint32_t) * ss_matches->last * 2); + ss_matches = ls_matches->matches[subsig_id] = realloc(ss_matches, sizeof(struct cli_subsig_matches) + sizeof(uint32_t) * ss_matches->last * 2); if (ss_matches == NULL) { - cli_errmsg("lsig_sub_matched: cli_max_realloc failed for cli_subsig_matches struct\n"); + cli_errmsg("lsig_sub_matched: realloc failed for cli_subsig_matches struct\n"); return CL_EMEM; } ss_matches->last = sizeof(ss_matches->offsets) / sizeof(uint32_t) + ss_matches->last * 2 - 1; @@ -1926,13 +1926,13 @@ cl_error_t cli_ac_scanbuff( /* sparsely populated matrix, so allocate and initialize if NULL */ if (!mdata->offmatrix[pt->sigid - 1]) { - mdata->offmatrix[pt->sigid - 1] = cli_max_malloc(pt->parts * sizeof(int32_t *)); + mdata->offmatrix[pt->sigid - 1] = malloc(pt->parts * sizeof(int32_t *)); if (!mdata->offmatrix[pt->sigid - 1]) { cli_errmsg("cli_ac_scanbuff: Can't allocate memory for mdata->offmatrix[%u]\n", pt->sigid - 1); return CL_EMEM; } - mdata->offmatrix[pt->sigid - 1][0] = cli_max_malloc(pt->parts * (CLI_DEFAULT_AC_TRACKLEN + 2) * sizeof(uint32_t)); + mdata->offmatrix[pt->sigid - 1][0] = malloc(pt->parts * (CLI_DEFAULT_AC_TRACKLEN + 2) * sizeof(uint32_t)); if (!mdata->offmatrix[pt->sigid - 1][0]) { cli_errmsg("cli_ac_scanbuff: Can't allocate memory for mdata->offmatrix[%u][0]\n", pt->sigid - 1); free(mdata->offmatrix[pt->sigid - 1]); @@ -2589,7 +2589,7 @@ inline static int ac_special_altstr(const char *hexpr, uint8_t sigopts, struct c special->type = AC_SPECIAL_ALT_STR; /* allocate reusable subexpr */ - if (!(subexpr = cli_max_calloc(slen + 1, sizeof(char)))) { + if (!(subexpr = calloc(slen + 1, sizeof(char)))) { cli_errmsg("ac_special_altstr: Can't allocate subexpr container\n"); free(hexprcpy); return CL_EMEM; @@ -2751,7 +2751,7 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch } hexnewsz = strlen(hexsig) + 1; - if (!(hexnew = (char *)cli_max_calloc(1, hexnewsz))) { + if (!(hexnew = (char *)calloc(1, hexnewsz))) { MPOOL_FREE(root->mempool, new); free(hexcpy); return CL_EMEM; diff --git a/libclamav/matcher-bm.c b/libclamav/matcher-bm.c index f6cac830fd..9af983ecf5 100644 --- a/libclamav/matcher-bm.c +++ b/libclamav/matcher-bm.c @@ -168,12 +168,12 @@ cl_error_t cli_bm_initoff(const struct cli_matcher *root, struct cli_bm_off *dat } data->cnt = data->pos = 0; - data->offtab = (uint32_t *)cli_max_malloc(root->bm_patterns * sizeof(uint32_t)); + data->offtab = (uint32_t *)malloc(root->bm_patterns * sizeof(uint32_t)); if (!data->offtab) { cli_errmsg("cli_bm_initoff: Can't allocate memory for data->offtab\n"); return CL_EMEM; } - data->offset = (uint32_t *)cli_max_malloc(root->bm_patterns * sizeof(uint32_t)); + data->offset = (uint32_t *)malloc(root->bm_patterns * sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_bm_initoff: Can't allocate memory for data->offset\n"); free(data->offtab); diff --git a/libclamav/matcher-byte-comp.c b/libclamav/matcher-byte-comp.c index 7c974b58e4..d1b299762d 100644 --- a/libclamav/matcher-byte-comp.c +++ b/libclamav/matcher-byte-comp.c @@ -36,7 +36,7 @@ #include "str.h" /* DEBUGGING */ -//#define MATCHER_BCOMP_DEBUG +// #define MATCHER_BCOMP_DEBUG #ifdef MATCHER_BCOMP_DEBUG #define bcm_dbgmsg(...) cli_dbgmsg(__VA_ARGS__) #else @@ -855,7 +855,7 @@ uint16_t cli_bcomp_chk_hex(const unsigned char *buffer, uint16_t opt, uint32_t l } /** - * @brief multipurpose buffer normalization support function for bytecompare + * @brief multipurpose buffer normalization support function for byte-compare * * Currently can be used to normalize a little endian hex buffer to big endian. * Can also be used to trim whitespace from the front of the buffer. diff --git a/libclamav/matcher-pcre.c b/libclamav/matcher-pcre.c index 4cbeb97a40..f2606450fc 100644 --- a/libclamav/matcher-pcre.c +++ b/libclamav/matcher-pcre.c @@ -46,7 +46,7 @@ #endif /* DEBUGGING */ -//#define MATCHER_PCRE_DEBUG +// #define MATCHER_PCRE_DEBUG #ifdef MATCHER_PCRE_DEBUG #define pm_dbgmsg(...) cli_dbgmsg(__VA_ARGS__) #else @@ -471,12 +471,12 @@ cl_error_t cli_pcre_recaloff(struct cli_matcher *root, struct cli_pcre_off *data } /* allocate data structures */ - data->shift = (uint32_t *)cli_max_calloc(root->pcre_metas, sizeof(uint32_t)); + data->shift = (uint32_t *)calloc(root->pcre_metas, sizeof(uint32_t)); if (!data->shift) { cli_errmsg("cli_pcre_initoff: cannot allocate memory for data->shift\n"); return CL_EMEM; } - data->offset = (uint32_t *)cli_max_calloc(root->pcre_metas, sizeof(uint32_t)); + data->offset = (uint32_t *)calloc(root->pcre_metas, sizeof(uint32_t)); if (!data->offset) { cli_errmsg("cli_pcre_initoff: cannot allocate memory for data->offset\n"); free(data->shift); diff --git a/libclamav/others.c b/libclamav/others.c index 37b9327f8b..d032840c28 100644 --- a/libclamav/others.c +++ b/libclamav/others.c @@ -539,7 +539,7 @@ struct cl_engine *cl_engine_new(void) } /* Set up default stats/intel gathering callbacks */ - intel = cli_max_calloc(1, sizeof(cli_intel_t)); + intel = calloc(1, sizeof(cli_intel_t)); if ((intel)) { #ifdef CL_THREAD_SAFE if (pthread_mutex_init(&(intel->mutex), NULL)) { @@ -1279,7 +1279,7 @@ char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type) cl_finish_hash(ctx, digest); - if (!(hashstr = (char *)cli_max_calloc(size * 2 + 1, sizeof(char)))) + if (!(hashstr = (char *)calloc(size * 2 + 1, sizeof(char)))) return NULL; pt = hashstr; @@ -1819,7 +1819,7 @@ bitset_t *cli_bitset_init(void) return NULL; } bs->length = BITSET_DEFAULT_SIZE; - bs->bitset = cli_max_calloc(BITSET_DEFAULT_SIZE, 1); + bs->bitset = calloc(BITSET_DEFAULT_SIZE, 1); if (!bs->bitset) { cli_errmsg("cli_bitset_init: Unable to allocate memory for bs->bitset %u\n", BITSET_DEFAULT_SIZE); free(bs); diff --git a/libclamav/phishcheck.c b/libclamav/phishcheck.c index eb81aed7b8..7173639fc8 100644 --- a/libclamav/phishcheck.c +++ b/libclamav/phishcheck.c @@ -324,7 +324,7 @@ static int build_regex(regex_t* preg, const char* regex, int nosub) if (rc) { size_t buflen = cli_regerror(rc, preg, NULL, 0); - char* errbuf = cli_max_malloc(buflen); + char* errbuf = malloc(buflen); if (errbuf) { cli_regerror(rc, preg, errbuf, buflen); diff --git a/libclamav/readdb.c b/libclamav/readdb.c index 925ae674f2..7b63989187 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -116,7 +116,7 @@ char *cli_virname(const char *virname, unsigned int official) if (official) return cli_strdup(virname); - newname = (char *)cli_max_malloc(strlen(virname) + 11 + 1); + newname = (char *)malloc(strlen(virname) + 11 + 1); if (!newname) { cli_errmsg("cli_virname: Can't allocate memory for newname\n"); return NULL; @@ -156,7 +156,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co /* FULLWORD regex sigopt handling */ if (sigopts & ACPATT_OPTION_FULLWORD) { size_t ovrlen = strlen(hexcpy) + 21; - char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); + char *hexovr = calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -173,7 +173,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co /* NOCASE sigopt is passed onto the regex-opt handler */ if (sigopts & ACPATT_OPTION_NOCASE) { size_t ovrlen = strlen(hexcpy) + 2; - char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); + char *hexovr = calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -213,7 +213,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co if (sigopts & ACPATT_OPTION_FULLWORD) { char *rechar; size_t ovrlen = strlen(hexcpy) + 7; - char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); + char *hexovr = calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -245,7 +245,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co if (sigopts & ACPATT_OPTION_WIDE) { size_t hexcpylen = strlen(hexcpy); size_t ovrlen = 2 * hexcpylen + 1; - char *hexovr = cli_max_calloc(ovrlen, sizeof(char)); + char *hexovr = calloc(ovrlen, sizeof(char)); if (!hexovr) { free(hexcpy); return CL_EMEM; @@ -729,7 +729,7 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v * Parse "{n}" wildcard - Not a "{n-m}" range-style one. * Replaces it with: "??" * n and then re-parses the modified hexsig with recursion. */ - hexcpy = cli_max_calloc(hexlen + 2 * range, sizeof(char)); + hexcpy = calloc(hexlen + 2 * range, sizeof(char)); if (!hexcpy) return CL_EMEM; @@ -1144,7 +1144,7 @@ static char *cli_signorm(const char *signame) nsz = 3; } - new_signame = cli_max_calloc((nsz + 1), sizeof(char)); + new_signame = calloc((nsz + 1), sizeof(char)); if (!new_signame) return NULL; @@ -2330,7 +2330,7 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, return CL_SUCCESS; } - bcs->all_bcs = cli_max_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_safer_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; @@ -2401,8 +2401,8 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, if (bc->kind >= _BC_START_HOOKS && bc->kind < _BC_LAST_HOOK) { unsigned hook = bc->kind - _BC_START_HOOKS; unsigned cnt = ++engine->hooks_cnt[hook]; - engine->hooks[hook] = cli_max_realloc2(engine->hooks[hook], - sizeof(*engine->hooks[0]) * cnt); + engine->hooks[hook] = cli_safer_realloc2(engine->hooks[hook], + sizeof(*engine->hooks[0]) * cnt); if (!engine->hooks[hook]) { cli_errmsg("Out of memory allocating memory for hook %u", hook); return CL_EMEM; @@ -3581,7 +3581,7 @@ static char *parse_yara_hex_string(YR_STRING *string, int *ret) } reslen++; - res = cli_max_calloc(reslen, 1); + res = calloc(reslen, 1); if (!(res)) { if (ret) *ret = CL_EMEM; return NULL; @@ -3755,7 +3755,7 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) } ytable->tbl_cnt++; - newtable = cli_max_realloc(ytable->table, ytable->tbl_cnt * sizeof(struct cli_ytable_entry *)); + newtable = cli_safer_realloc(ytable->table, ytable->tbl_cnt * sizeof(struct cli_ytable_entry *)); if (!newtable) { cli_yaramsg("ytable_add_string: failed to reallocate new ytable table\n"); free(new->hexstr); @@ -3861,7 +3861,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns return CL_SUCCESS; } - newident = cli_max_malloc(strlen(rule->identifier) + 5 + 1); + newident = malloc(strlen(rule->identifier) + 5 + 1); if (!newident) { cli_errmsg("cli_loadyara(): newident == NULL\n"); return CL_EMEM; @@ -4030,7 +4030,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns #if HAVE_PCRE size_t length = strlen(PCRE_BYPASS) + string->length + 3; - substr = cli_max_calloc(length, sizeof(char)); + substr = calloc(length, sizeof(char)); if (!substr) { cli_errmsg("load_oneyara: cannot allocate memory for converted regex string\n"); str_error++; @@ -4063,7 +4063,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns continue; } - substr = cli_max_calloc(totsize, sizeof(char)); + substr = calloc(totsize, sizeof(char)); if (!substr) { cli_errmsg("load_oneyara: cannot allocate memory for converted generic string\n"); str_error++; @@ -4195,7 +4195,7 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns #if 0 if (rule->cl_flags & RULE_ALL || rule->cl_flags & RULE_ANY) { lsize = 3*ytable.tbl_cnt; - logic = cli_max_calloc(lsize, sizeof(char)); + logic = calloc(lsize, sizeof(char)); if (!logic) { cli_errmsg("load_oneyara: cannot allocate memory for logic statement\n"); ytable_delete(&ytable); @@ -4600,7 +4600,7 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options } } else { size_t attlen = strlen(tokens[1]) + 10; - attribs = cli_max_calloc(attlen, sizeof(char)); + attribs = calloc(attlen, sizeof(char)); if (!attribs) { cli_errmsg("cli_loadpwdb: Can't allocate memory for attributes\n"); ret = CL_EMEM; @@ -5081,7 +5081,7 @@ static cl_error_t cli_loaddbdir(const char *dirname, struct cl_engine *engine, u continue; } - dbfile = (char *)cli_max_malloc(strlen(dent->d_name) + dirname_len + 2); + dbfile = (char *)malloc(strlen(dent->d_name) + dirname_len + 2); if (!dbfile) { cli_errmsg("cli_loaddbdir: dbfile == NULL\n"); ret = CL_EMEM; @@ -5415,7 +5415,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..") && CLI_DBEXT(dent->d_name)) { dbstat->entries++; - dbstat->stattab = (STATBUF *)cli_max_realloc2(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); + dbstat->stattab = (STATBUF *)cli_safer_realloc2(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); if (!dbstat->stattab) { cl_statfree(dbstat); closedir(dd); @@ -5423,7 +5423,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } #ifdef _WIN32 - dbstat->statdname = (char **)cli_max_realloc2(dbstat->statdname, dbstat->entries * sizeof(char *)); + dbstat->statdname = (char **)cli_safer_realloc2(dbstat->statdname, dbstat->entries * sizeof(char *)); if (!dbstat->statdname) { cli_errmsg("cl_statinidir: Can't allocate memory for dbstat->statdname\n"); cl_statfree(dbstat); @@ -5432,7 +5432,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } #endif - fname = cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 32); + fname = malloc(strlen(dirname) + strlen(dent->d_name) + 32); if (!fname) { cli_errmsg("cl_statinidir: Cant' allocate memory for fname\n"); cl_statfree(dbstat); @@ -5441,7 +5441,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } sprintf(fname, "%s" PATHSEP "%s", dirname, dent->d_name); #ifdef _WIN32 - dbstat->statdname[dbstat->entries - 1] = (char *)cli_max_malloc(strlen(dent->d_name) + 1); + dbstat->statdname[dbstat->entries - 1] = (char *)malloc(strlen(dent->d_name) + 1); if (!dbstat->statdname[dbstat->entries - 1]) { cli_errmsg("cli_statinidir: Can't allocate memory for dbstat->statdname\n"); cl_statfree(dbstat); @@ -5484,7 +5484,7 @@ int cl_statchkdir(const struct cl_stat *dbstat) while ((dent = readdir(dd))) { if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..") && CLI_DBEXT(dent->d_name)) { - fname = cli_max_malloc(strlen(dbstat->dir) + strlen(dent->d_name) + 32); + fname = malloc(strlen(dbstat->dir) + strlen(dent->d_name) + 32); if (!fname) { cli_errmsg("cl_statchkdir: can't allocate memory for fname\n"); closedir(dd); diff --git a/libclamav/scanners.c b/libclamav/scanners.c index ae0149dbd3..a9d169bed8 100644 --- a/libclamav/scanners.c +++ b/libclamav/scanners.c @@ -2256,7 +2256,7 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) goto done; } - if (!(normalized = cli_max_malloc(SCANBUFF + maxpatlen))) { + if (!(normalized = malloc(SCANBUFF + maxpatlen))) { cli_dbgmsg("cli_scanscript: Unable to malloc %u bytes\n", SCANBUFF); ret = CL_EMEM; goto done; @@ -5421,7 +5421,7 @@ static cl_error_t scan_common(cl_fmap_t *map, const char *filepath, const char * } ctx.recursion_stack_size = ctx.engine->max_recursion_level; - ctx.recursion_stack = cli_max_calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); + ctx.recursion_stack = calloc(sizeof(recursion_level_t), ctx.recursion_stack_size); if (!ctx.recursion_stack) { status = CL_EMEM; goto done; From 7e53819601215f7f742b954a1b395cf1a6f034d7 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Tue, 9 Jan 2024 17:44:33 -0500 Subject: [PATCH 10/12] Refine max-allocation and safer-allocation function and macro names We add the _OR_GOTO_DONE suffix to the macros that go to done if the allocation fails. This makes it obvious what is different about the macro versus the equivalent function, and that error handling is built-in. Renamed the cli_strdup to safer_strdup to make it obvious that it exists because it is safer than regular strdup. Regular strdup doesn't have the NULL check before trying to dup, and so may result in a NULL-deref crash. Also remove unused STRDUP (_OR_GOTO_DONE) macro, since the one with the NULL-check is preferred. --- clamdscan/client.c | 2 +- clamonacc/client/client.c | 2 +- clamonacc/fanotif/fanotif.c | 2 +- clamonacc/inotif/inotif.c | 2 +- freshclam/freshclam.c | 8 +- libclamav/blob.c | 4 +- libclamav/bytecode.c | 8 +- libclamav/crtmgr.c | 2 +- libclamav/cvd.c | 2 +- libclamav/egg.c | 24 +-- libclamav/entconv.c | 4 +- libclamav/events.c | 4 +- libclamav/fmap.c | 8 +- libclamav/htmlnorm.c | 32 +-- libclamav/ishield.c | 4 +- libclamav/jsparse/js-norm.c | 6 +- libclamav/libclamav.map | 2 +- libclamav/macho.c | 2 +- libclamav/matcher-ac.c | 8 +- libclamav/matcher-byte-comp.c | 2 +- libclamav/mbox.c | 42 ++-- libclamav/message.c | 26 +-- libclamav/mpool.h | 6 +- libclamav/ole2_extract.c | 48 ++--- libclamav/others.h | 285 ++++++++++++++++----------- libclamav/others_common.c | 26 +-- libclamav/pdf.c | 8 +- libclamav/pe.c | 4 +- libclamav/phishcheck.c | 4 +- libclamav/readdb.c | 32 +-- libclamav/regex_list.c | 18 +- libclamav/regex_suffix.c | 20 +- libclamav/scanners.c | 6 +- libclamav/sis.c | 18 +- libclamav/str.c | 2 +- libclamav/table.c | 4 +- libclamav/udf.c | 8 +- libclamav/vba_extract.c | 2 +- libclamav/xlm_extract.c | 10 +- libclamav/yara_clam.h | 2 +- libclamav/yara_parser.c | 4 +- libfreshclam/libfreshclam.c | 18 +- libfreshclam/libfreshclam_internal.c | 24 +-- unit_tests/check_regex.c | 22 +-- 44 files changed, 409 insertions(+), 358 deletions(-) diff --git a/clamdscan/client.c b/clamdscan/client.c index 665847162d..57570a1bd7 100644 --- a/clamdscan/client.c +++ b/clamdscan/client.c @@ -188,7 +188,7 @@ int16_t ping_clamd(const struct optstruct *opts) /* ping command takes the form --ping [attempts[:interval]] */ if (NULL != (opt = optget(opts, "ping"))) { if (NULL != opt->strarg) { - if (NULL == (attempt_str = cli_strdup(opt->strarg))) { + if (NULL == (attempt_str = cli_safer_strdup(opt->strarg))) { logg(LOGG_ERROR, "could not allocate memory for string\n"); ret = -1; goto done; diff --git a/clamonacc/client/client.c b/clamonacc/client/client.c index f7cddc33fc..d87914ab29 100644 --- a/clamonacc/client/client.c +++ b/clamonacc/client/client.c @@ -208,7 +208,7 @@ int16_t onas_ping_clamd(struct onas_context **ctx) opt = optget((*ctx)->opts, "ping"); if (opt->enabled) { - attempt_str = cli_strdup(opt->strarg); + attempt_str = cli_safer_strdup(opt->strarg); if (attempt_str) { if (NULL == attempt_str) { logg(LOGG_ERROR, "could not allocate memory for string\n"); diff --git a/clamonacc/fanotif/fanotif.c b/clamonacc/fanotif/fanotif.c index 0e1a89e06d..1b29cbbaa5 100644 --- a/clamonacc/fanotif/fanotif.c +++ b/clamonacc/fanotif/fanotif.c @@ -255,7 +255,7 @@ int onas_fan_eloop(struct onas_context **ctx) return 2; } memcpy(event_data->fmd, fmd, sizeof(struct fanotify_event_metadata)); - event_data->pathname = cli_strdup(fname); + event_data->pathname = cli_safer_strdup(fname); if (NULL == event_data->pathname) { close(fmd->fd); free(event_data->fmd); diff --git a/clamonacc/inotif/inotif.c b/clamonacc/inotif/inotif.c index ec0afb4f6c..bb25363e98 100644 --- a/clamonacc/inotif/inotif.c +++ b/clamonacc/inotif/inotif.c @@ -821,7 +821,7 @@ static void onas_ddd_handle_extra_scanning(struct onas_context *ctx, const char /* general mapping */ onas_map_context_info_to_event_data(ctx, &event_data); - event_data->pathname = cli_strdup(pathname); + event_data->pathname = cli_safer_strdup(pathname); event_data->bool_opts |= ONAS_SCTH_B_SCAN; /* inotify specific stuffs */ diff --git a/freshclam/freshclam.c b/freshclam/freshclam.c index da2dbd0299..407833e014 100644 --- a/freshclam/freshclam.c +++ b/freshclam/freshclam.c @@ -480,7 +480,7 @@ static fc_error_t get_server_node( * Ensure that URL contains protocol. */ if (!strncmp(server, "db.", 3) && strstr(server, ".clamav.net")) { - url = cli_strdup("https://database.clamav.net"); + url = cli_safer_strdup("https://database.clamav.net"); if (NULL == url) { logg(LOGG_ERROR, "get_server_node: Failed to duplicate string for database.clamav.net url.\n"); status = FC_EMEM; @@ -497,7 +497,7 @@ static fc_error_t get_server_node( snprintf(url, urlLen + 1, "%s://%s", defaultProtocol, server); } else { urlLen = strlen(server); - url = cli_strdup(server); + url = cli_safer_strdup(server); if (NULL == url) { logg(LOGG_ERROR, "get_server_node: Failed to duplicate string for server url.\n"); status = FC_EMEM; @@ -544,7 +544,7 @@ static fc_error_t string_list_add(const char *item, char ***stringList, uint32_t *stringList = newList; - newList[nItems - 1] = cli_strdup(item); + newList[nItems - 1] = cli_safer_strdup(item); if (newList[nItems - 1] == NULL) { mprintf(LOGG_ERROR, "string_list_add: Failed to allocate memory for optional database list item.\n"); status = FC_EMEM; @@ -1663,7 +1663,7 @@ int main(int argc, char **argv) /* * Parse the config file. */ - cfgfile = cli_strdup(optget(opts, "config-file")->strarg); + cfgfile = cli_safer_strdup(optget(opts, "config-file")->strarg); if ((opts = optparse(cfgfile, 0, NULL, 1, OPT_FRESHCLAM, 0, opts)) == NULL) { fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", cfgfile); status = FC_EINIT; diff --git a/libclamav/blob.c b/libclamav/blob.c index a75ff43f64..fc7b1e9489 100644 --- a/libclamav/blob.c +++ b/libclamav/blob.c @@ -154,7 +154,7 @@ void blobSetFilename(blob *b, const char *dir, const char *filename) if (b->name) free(b->name); - b->name = cli_strdup(filename); + b->name = cli_safer_strdup(filename); if (b->name) sanitiseName(b->name); @@ -526,7 +526,7 @@ void fileblobPartialSet(fileblob *fb, const char *fullname, const char *arg) fb->b.len = fb->b.size = 0; fb->isNotEmpty = 1; } - fb->fullname = cli_strdup(fullname); + fb->fullname = cli_safer_strdup(fullname); } void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename) diff --git a/libclamav/bytecode.c b/libclamav/bytecode.c index c15336941b..faf8dbb3b1 100644 --- a/libclamav/bytecode.c +++ b/libclamav/bytecode.c @@ -507,7 +507,7 @@ static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p, uint16_t ty; p[*off] |= 0x20; /* TODO: unique constants */ - func->constants = cli_safer_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); + func->constants = cli_safer_realloc_or_free(func->constants, (func->numConstants + 1) * sizeof(*func->constants)); if (!func->constants) { *ok = false; return MAX_OP; @@ -698,13 +698,13 @@ static cl_error_t parseLSig(struct cli_bc *bc, char *buffer) // char *vnames; char *vend = strchr(buffer, ';'); if (vend) { - bc->lsig = cli_strdup(buffer); + bc->lsig = cli_safer_strdup(buffer); *vend++ = '\0'; // prefix = buffer; // vnames = strchr(vend, '{'); } else { /* Not a logical signature, but we still have a virusname */ - bc->hook_name = cli_strdup(buffer); + bc->hook_name = cli_safer_strdup(buffer); bc->lsig = NULL; } @@ -2407,7 +2407,7 @@ static cl_error_t add_selfcheck(struct cli_all_bc *bcs) struct cli_bc_inst *inst; struct cli_bc *bc; - bcs->all_bcs = cli_safer_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_safer_realloc_or_free(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; diff --git a/libclamav/crtmgr.c b/libclamav/crtmgr.c index b350770b0c..cc3fc84a92 100644 --- a/libclamav/crtmgr.c +++ b/libclamav/crtmgr.c @@ -415,7 +415,7 @@ static cl_error_t crtmgr_get_recov_data(BIGNUM *sig, cli_crt *x509, if (!x) goto done; - MALLOC(d, keylen); + CLI_MALLOC_OR_GOTO_DONE(d, keylen); if (!BN_mod_exp(x, sig, x509->e, x509->n, bnctx)) { cli_warnmsg("crtmgr_rsa_verify: verification failed: BN_mod_exp failed.\n"); diff --git a/libclamav/cvd.c b/libclamav/cvd.c index 88f94d024d..5003de9ce4 100644 --- a/libclamav/cvd.c +++ b/libclamav/cvd.c @@ -633,7 +633,7 @@ cl_error_t cli_cvdload(FILE *fs, struct cl_engine *engine, unsigned int *signo, if (dbtype <= 1) { /* check for duplicate db */ - dupname = cli_strdup(filename); + dupname = cli_safer_strdup(filename); if (!dupname) return CL_EMEM; dupname[strlen(dupname) - 2] = (dbtype == 1 ? 'v' : 'l'); diff --git a/libclamav/egg.c b/libclamav/egg.c index 4ca8918971..7c076f3d5d 100644 --- a/libclamav/egg.c +++ b/libclamav/egg.c @@ -1221,7 +1221,7 @@ static cl_error_t egg_parse_file_extra_field(egg_handle* handle, egg_file* eggFi /* * Comment found. Add comment to our list. */ - CLI_SAFER_REALLOC(eggFile->comments, + CLI_SAFER_REALLOC_OR_GOTO_DONE(eggFile->comments, sizeof(char*) * (eggFile->nComments + 1), free(comment), status = CL_EMEM); @@ -1667,7 +1667,7 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t goto done; } else { /* Add file to list. */ - CLI_SAFER_REALLOC(handle->files, + CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->files, sizeof(egg_file*) * (handle->nFiles + 1), egg_free_egg_file(found_file), status = CL_EMEM); @@ -1689,7 +1689,7 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t } else { /* Add block to list. */ if (handle->bSolid) { - CLI_SAFER_REALLOC(handle->blocks, + CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->blocks, sizeof(egg_block*) * (handle->nBlocks + 1), egg_free_egg_block(found_block), status = CL_EMEM); @@ -1707,7 +1707,7 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t } else { eggFile = handle->files[handle->nFiles - 1]; - CLI_SAFER_REALLOC(eggFile->blocks, + CLI_SAFER_REALLOC_OR_GOTO_DONE(eggFile->blocks, sizeof(egg_block*) * (eggFile->nBlocks + 1), egg_free_egg_block(found_block), status = CL_EMEM); @@ -1785,7 +1785,7 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t /* * Comment found. Add comment to our list. */ - CLI_SAFER_REALLOC(handle->comments, + CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->comments, sizeof(char*) * (handle->nComments + 1), free(comment), status = CL_EMEM); @@ -1972,7 +1972,7 @@ cl_error_t cli_egg_deflate_decompress(char* compressed, size_t compressed_size, while (zstat == Z_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_SAFER_REALLOC(decoded, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, capacity + BUFSIZ, cli_errmsg("cli_egg_deflate_decompress: cannot reallocate memory for decompressed output\n"), status = CL_EMEM); @@ -2094,7 +2094,7 @@ cl_error_t cli_egg_bzip2_decompress(char* compressed, size_t compressed_size, ch while (bzstat == BZ_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_SAFER_REALLOC(decoded, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, capacity + BUFSIZ, cli_errmsg("cli_egg_bzip2_decompress: cannot reallocate memory for decompressed output\n"); status = CL_EMEM); @@ -2211,7 +2211,7 @@ cl_error_t cli_egg_lzma_decompress(char* compressed, size_t compressed_size, cha while (lzmastat == LZMA_RESULT_OK && stream.avail_in) { /* extend output capacity if needed,*/ if (stream.avail_out == 0) { - CLI_SAFER_REALLOC(decoded, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, capacity + BUFSIZ, cli_errmsg("cli_egg_lzma_decompress: cannot reallocate memory for decompressed output\n"); status = CL_EMEM); @@ -2361,7 +2361,7 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha break; } - CLI_SAFER_REALLOC(decompressed, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, (size_t)decompressed_size + currBlock->blockHeader->compress_size, cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", decompressed_size), @@ -2386,7 +2386,7 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha goto done; } /* Decompressed block. Add it to the file data */ - CLI_SAFER_REALLOC(decompressed, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, (size_t)decompressed_size + decompressed_block_size, cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", decompressed_size), @@ -2415,7 +2415,7 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha goto done; } /* Decompressed block. Add it to the file data */ - CLI_SAFER_REALLOC(decompressed, + CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, (size_t)decompressed_size + decompressed_block_size, cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", decompressed_size), @@ -2454,7 +2454,7 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha // goto done; // } // /* Decompressed block. Add it to the file data */ - // CLI_SAFER_REALLOC(decompressed, + // CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, // (size_t)decompressed_size + decompressed_block_size, // cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", // decompressed_size), diff --git a/libclamav/entconv.c b/libclamav/entconv.c index 13345078b4..bb58215fa4 100644 --- a/libclamav/entconv.c +++ b/libclamav/entconv.c @@ -656,7 +656,7 @@ static iconv_t iconv_open_cached(const char* fromcode) idx = cache->last++; if (idx >= cache->len) { cache->len += 16; - cache->tab = cli_max_realloc2(cache->tab, cache->len * sizeof(cache->tab[0])); + cache->tab = cli_max_realloc_or_free(cache->tab, cache->len * sizeof(cache->tab[0])); if (!cache->tab) { cli_dbgmsg(MODULE_NAME "!Out of mem in iconv-pool\n"); errno = ENOMEM; @@ -1121,7 +1121,7 @@ char* cli_utf16_to_utf8(const char* utf16, size_t length, encoding_t type) char* s2; if (length < 2) - return cli_strdup(""); + return cli_safer_strdup(""); if (length % 2) { cli_warnmsg("utf16 length is not multiple of two: %lu\n", (long)length); length--; diff --git a/libclamav/events.c b/libclamav/events.c index 60e8785a59..142cd38f44 100644 --- a/libclamav/events.c +++ b/libclamav/events.c @@ -294,7 +294,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l } switch (ev->multiple) { case multiple_last: { - void *v_data = cli_safer_realloc2(ev->u.v_data, len); + void *v_data = cli_safer_realloc_or_free(ev->u.v_data, len); if (v_data) { ev->u.v_data = v_data; memcpy(v_data, data, len); @@ -305,7 +305,7 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l break; } case multiple_concat: { - void *v_data = cli_safer_realloc2(ev->u.v_data, ev->count + len); + void *v_data = cli_safer_realloc_or_free(ev->u.v_data, ev->count + len); if (v_data) { ev->u.v_data = v_data; memcpy((char *)v_data + ev->count, data, len); diff --git a/libclamav/fmap.c b/libclamav/fmap.c index 38350efa00..c380d8bcd8 100644 --- a/libclamav/fmap.c +++ b/libclamav/fmap.c @@ -135,7 +135,7 @@ fmap_t *fmap_check_empty(int fd, off_t offset, size_t len, int *empty, const cha m->mtime = (uint64_t)st.st_mtime; if (NULL != name) { - m->name = cli_strdup(name); + m->name = cli_safer_strdup(name); if (NULL == m->name) { funmap(m); return NULL; @@ -220,7 +220,7 @@ fmap_t *fmap_check_empty(int fd, off_t offset, size_t len, int *empty, const cha m->unmap = unmap_win32; if (NULL != name) { - m->name = cli_strdup(name); + m->name = cli_safer_strdup(name); if (NULL == m->name) { funmap(m); return NULL; @@ -293,7 +293,7 @@ fmap_t *fmap_duplicate(cl_fmap_t *map, size_t offset, size_t length, const char } if (NULL != name) { - duplicate_map->name = cli_strdup(name); + duplicate_map->name = cli_safer_strdup(name); if (NULL == duplicate_map->name) { status = CL_EMEM; goto done; @@ -862,7 +862,7 @@ fmap_t *fmap_open_memory(const void *start, size_t len, const char *name) if (NULL != name) { /* Copy the name, if one is given */ - m->name = cli_strdup(name); + m->name = cli_safer_strdup(name); if (NULL == m->name) { cli_warnmsg("fmap: failed to duplicate map name\n"); goto done; diff --git a/libclamav/htmlnorm.c b/libclamav/htmlnorm.c index 786d57dfa8..f197f36da0 100644 --- a/libclamav/htmlnorm.c +++ b/libclamav/htmlnorm.c @@ -360,7 +360,7 @@ static void html_tag_arg_set(tag_arguments_t *tags, const char *tag, const char for (i = 0; i < tags->count; i++) { if (strcmp((const char *)tags->tag[i], tag) == 0) { free(tags->value[i]); - tags->value[i] = (unsigned char *)cli_strdup(value); + tags->value[i] = (unsigned char *)cli_safer_strdup(value); return; } } @@ -371,34 +371,34 @@ void html_tag_arg_add(tag_arguments_t *tags, { int len, i; tags->count++; - tags->tag = (unsigned char **)cli_max_realloc2(tags->tag, + tags->tag = (unsigned char **)cli_max_realloc_or_free(tags->tag, tags->count * sizeof(char *)); if (!tags->tag) { goto done; } - tags->value = (unsigned char **)cli_max_realloc2(tags->value, + tags->value = (unsigned char **)cli_max_realloc_or_free(tags->value, tags->count * sizeof(char *)); if (!tags->value) { goto done; } if (tags->scanContents) { - tags->contents = (unsigned char **)cli_max_realloc2(tags->contents, + tags->contents = (unsigned char **)cli_max_realloc_or_free(tags->contents, tags->count * sizeof(*tags->contents)); if (!tags->contents) { goto done; } tags->contents[tags->count - 1] = NULL; } - tags->tag[tags->count - 1] = (unsigned char *)cli_strdup(tag); + tags->tag[tags->count - 1] = (unsigned char *)cli_safer_strdup(tag); if (value) { if (*value == '"') { - tags->value[tags->count - 1] = (unsigned char *)cli_strdup(value + 1); + tags->value[tags->count - 1] = (unsigned char *)cli_safer_strdup(value + 1); len = strlen((const char *)value + 1); if (len > 0) { tags->value[tags->count - 1][len - 1] = '\0'; } } else { - tags->value[tags->count - 1] = (unsigned char *)cli_strdup(value); + tags->value[tags->count - 1] = (unsigned char *)cli_safer_strdup(value); } } else { tags->value[tags->count - 1] = NULL; @@ -1201,9 +1201,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha chunk_size = style_end - style_begin; if (style_buff == NULL) { - CLI_MAX_MALLOC(style_buff, chunk_size + 1); + CLI_MAX_MALLOC_OR_GOTO_DONE(style_buff, chunk_size + 1); } else { - CLI_MAX_REALLOC(style_buff, style_buff_size + chunk_size + 1); + CLI_MAX_REALLOC_OR_GOTO_DONE(style_buff, style_buff_size + chunk_size + 1); } memcpy(style_buff + style_buff_size, style_begin, chunk_size); @@ -1312,7 +1312,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha if (arg_action_value) { if (in_form_action) free(in_form_action); - in_form_action = (unsigned char *)cli_strdup(arg_action_value); + in_form_action = (unsigned char *)cli_safer_strdup(arg_action_value); } } else if (strcmp(tag, "img") == 0) { arg_value = html_tag_arg_value(&tag_args, "src"); @@ -1320,7 +1320,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha html_tag_arg_add(hrefs, "src", arg_value); if (hrefs->scanContents && in_ahref) /* "contents" of an img tag, is the URL of its parent tag */ - hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_strdup((const char *)hrefs->value[in_ahref - 1]); + hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1335,7 +1335,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha html_tag_arg_add(hrefs, "dynsrc", arg_value); if (hrefs->scanContents && in_ahref) /* see above */ - hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_strdup((const char *)hrefs->value[in_ahref - 1]); + hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1351,7 +1351,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha html_tag_arg_add(hrefs, "iframe", arg_value); if (hrefs->scanContents && in_ahref) /* see above */ - hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_strdup((const char *)hrefs->value[in_ahref - 1]); + hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1367,7 +1367,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha html_tag_arg_add(hrefs, "area", arg_value); if (hrefs->scanContents && in_ahref) /* see above */ - hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_strdup((const char *)hrefs->value[in_ahref - 1]); + hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1837,9 +1837,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha size_t chunk_size = ptr - style_begin; if (style_buff == NULL) { - CLI_MAX_MALLOC(style_buff, chunk_size + 1); + CLI_MAX_MALLOC_OR_GOTO_DONE(style_buff, chunk_size + 1); } else { - CLI_MAX_REALLOC(style_buff, style_buff_size + chunk_size + 1); + CLI_MAX_REALLOC_OR_GOTO_DONE(style_buff, style_buff_size + chunk_size + 1); } memcpy(style_buff + style_buff_size, style_begin, chunk_size); diff --git a/libclamav/ishield.c b/libclamav/ishield.c index e43979706c..171ac773ab 100644 --- a/libclamav/ishield.c +++ b/libclamav/ishield.c @@ -246,7 +246,7 @@ cl_error_t cli_scanishield_msi(cli_ctx *ctx, off_t off) return CL_SUCCESS; } - filename = cli_strdup((const char *)key); + filename = cli_safer_strdup((const char *)key); /* FIXMEISHIELD: cleanup the spam below */ cli_dbgmsg("ishield-msi: File %s (csize: %llx, unk1:%x unk2:%x unk3:%x unk4:%x unk5:%x unk6:%x unk7:%x unk8:%x unk9:%x unk10:%x unk11:%x)\n", key, (long long)csize, fb.unk1, fb.unk2, fb.unk3, fb.unk4, fb.unk5, fb.unk6, fb.unk7, fb.unk8, fb.unk9, fb.unk10, fb.unk11); @@ -432,7 +432,7 @@ cl_error_t cli_scanishield(cli_ctx *ctx, off_t off, size_t sz) } if (i == c.cabcnt) { c.cabcnt++; - if (!(c.cabs = cli_max_realloc2(c.cabs, sizeof(struct CABARRAY) * c.cabcnt))) { + if (!(c.cabs = cli_max_realloc_or_free(c.cabs, sizeof(struct CABARRAY) * c.cabcnt))) { ret = CL_EMEM; break; } diff --git a/libclamav/jsparse/js-norm.c b/libclamav/jsparse/js-norm.c index ac8d06fe57..bdbd15df7b 100644 --- a/libclamav/jsparse/js-norm.c +++ b/libclamav/jsparse/js-norm.c @@ -881,7 +881,7 @@ static void run_decoders(struct parser_state *state) cli_js_process_buffer(state, res.txtbuf.data, res.txtbuf.pos); --state->rec; } - FREE(res.txtbuf.data); + CLI_FREE_AND_SET_NULL(res.txtbuf.data); /* state->tokens still refers to the embedded/nested context here */ if (!res.append) { if (CL_EARG == replace_token_range(&parent_tokens, res.pos_begin, res.pos_end, &state->tokens)) { @@ -1044,7 +1044,7 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n if (current->last_token == TOK_DOT) { /* this is a member name, don't normalize */ - TOKEN_SET(&val, string, cli_strdup(text)); + TOKEN_SET(&val, string, cli_safer_strdup(text)); val.type = TOK_UNNORM_IDENTIFIER; } else { switch (current->fsm_state) { @@ -1197,7 +1197,7 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n } if (val.vtype == vtype_undefined) { text = yyget_text(state->scanner); - TOKEN_SET(&val, string, cli_strdup(text)); + TOKEN_SET(&val, string, cli_safer_strdup(text)); abort(); } add_token(state, &val); diff --git a/libclamav/libclamav.map b/libclamav/libclamav.map index ff36187032..9433a8c0ec 100644 --- a/libclamav/libclamav.map +++ b/libclamav/libclamav.map @@ -127,7 +127,7 @@ CLAMAV_PRIVATE { cli_utf16toascii; cli_memstr; - cli_strdup; + cli_safer_strdup; cli_max_calloc; cli_max_malloc; cli_max_realloc; diff --git a/libclamav/macho.c b/libclamav/macho.c index c1558bbcb3..25f70554fc 100644 --- a/libclamav/macho.c +++ b/libclamav/macho.c @@ -375,7 +375,7 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) cli_dbgmsg("MACHO: ------------------\n"); continue; } - sections = (struct cli_exe_section *)cli_max_realloc2(sections, (sect + nsects) * sizeof(struct cli_exe_section)); + sections = (struct cli_exe_section *)cli_max_realloc_or_free(sections, (sect + nsects) * sizeof(struct cli_exe_section)); if (!sections) { cli_errmsg("cli_scanmacho: Can't allocate memory for 'sections'\n"); return CL_EMEM; diff --git a/libclamav/matcher-ac.c b/libclamav/matcher-ac.c index c9feb8f09e..e273c33d70 100644 --- a/libclamav/matcher-ac.c +++ b/libclamav/matcher-ac.c @@ -2519,7 +2519,7 @@ inline static int ac_special_altstr(const char *hexpr, uint8_t sigopts, struct c char *hexprcpy, *h, *c; int i, ret, num, fixed, slen; - if (!(hexprcpy = cli_strdup(hexpr))) { + if (!(hexprcpy = cli_safer_strdup(hexpr))) { cli_errmsg("ac_special_altstr: Can't duplicate alternate expression\n"); return CL_EDUP; } @@ -2646,7 +2646,7 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch } if (strchr(hexsig, '[')) { - if (!(hexcpy = cli_strdup(hexsig))) { + if (!(hexcpy = cli_safer_strdup(hexsig))) { MPOOL_FREE(root->mempool, new); return CL_EMEM; } @@ -2730,7 +2730,7 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch return error; } - hex = cli_strdup(hex); + hex = cli_safer_strdup(hex); free(hexcpy); if (!hex) { MPOOL_FREE(root->mempool, new); @@ -2745,7 +2745,7 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch if (hex) { hexcpy = hex; - } else if (!(hexcpy = cli_strdup(hexsig))) { + } else if (!(hexcpy = cli_safer_strdup(hexsig))) { MPOOL_FREE(root->mempool, new); return CL_EMEM; } diff --git a/libclamav/matcher-byte-comp.c b/libclamav/matcher-byte-comp.c index d1b299762d..a5dd92c322 100644 --- a/libclamav/matcher-byte-comp.c +++ b/libclamav/matcher-byte-comp.c @@ -317,7 +317,7 @@ cl_error_t cli_bcomp_addpatt(struct cli_matcher *root, const char *virname, cons bcomp->byte_len = byte_length; /* we can have up to two comparison eval statements, each separated by a comma, let's parse them in a separate string */ - comp_buf = cli_strdup(tokens[2]); + comp_buf = cli_safer_strdup(tokens[2]); if (!comp_buf) { cli_errmsg("cli_bcomp_addpatt: Unable to allocate memory for comparison buffer\n"); cli_bcomp_freemeta(root, bcomp); diff --git a/libclamav/mbox.c b/libclamav/mbox.c index 60a0afd740..530bb84cd7 100644 --- a/libclamav/mbox.c +++ b/libclamav/mbox.c @@ -624,7 +624,7 @@ appendReadStruct(ReadStruct *rs, const char *const buffer) strncpy(&(rs->buffer[rs->bufferLen]), buffer, part); rs->bufferLen += part; - CALLOC(next, 1, sizeof(ReadStruct)); + CLI_CALLOC_OR_GOTO_DONE(next, 1, sizeof(ReadStruct)); rs->next = next; strcpy(next->buffer, &(buffer[part])); @@ -654,7 +654,7 @@ getMallocedBufferFromList(const ReadStruct *head) rs = rs->next; } - CLI_MAX_MALLOC(working, bufferLen); + CLI_MAX_MALLOC_OR_GOTO_DONE(working, bufferLen); rs = head; bufferLen = 0; @@ -668,7 +668,7 @@ getMallocedBufferFromList(const ReadStruct *head) ret = working; done: if (NULL == ret) { - FREE(working); + CLI_FREE_AND_SET_NULL(working); } return ret; @@ -679,7 +679,7 @@ freeList(ReadStruct *head) { while (head) { ReadStruct *rs = head->next; - FREE(head); + CLI_FREE_AND_SET_NULL(head); head = rs; } } @@ -844,7 +844,7 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first if (ret == NULL) return NULL; - CALLOC(head, 1, sizeof(ReadStruct)); + CLI_CALLOC_OR_GOTO_DONE(head, 1, sizeof(ReadStruct)); curr = head; strncpy(buffer, firstLine, sizeof(buffer) - 1); @@ -906,20 +906,20 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first if (head->bufferLen) { char *header = getMallocedBufferFromList(head); int needContinue = 0; - VERIFY_POINTER(header); + CLI_VERIFY_POINTER_OR_GOTO_DONE(header); totalHeaderCnt++; if (haveTooManyEmailHeaders(totalHeaderCnt, ctx, heuristicFound)) { - FREE(header); + CLI_FREE_AND_SET_NULL(header); break; } needContinue = (parseEmailHeader(ret, header, rfc821, ctx, heuristicFound) < 0); if (*heuristicFound) { - FREE(header); + CLI_FREE_AND_SET_NULL(header); break; } - FREE(header); + CLI_FREE_AND_SET_NULL(header); FREELIST_REALLOC(head, curr); if (needContinue) { @@ -1023,7 +1023,7 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first { char *header = getMallocedBufferFromList(head); /*This is the issue */ int needContinue = 0; - VERIFY_POINTER(header); + CLI_VERIFY_POINTER_OR_GOTO_DONE(header); needContinue = (header[strlen(header) - 1] == ';'); if (0 == needContinue) { @@ -1033,18 +1033,18 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first if (0 == needContinue) { totalHeaderCnt++; if (haveTooManyEmailHeaders(totalHeaderCnt, ctx, heuristicFound)) { - FREE(header); + CLI_FREE_AND_SET_NULL(header); break; } needContinue = (parseEmailHeader(ret, header, rfc821, ctx, heuristicFound) < 0); if (*heuristicFound) { - FREE(header); + CLI_FREE_AND_SET_NULL(header); break; } /*Check total headers here;*/ } - FREE(header); + CLI_FREE_AND_SET_NULL(header); if (needContinue) { continue; } @@ -1100,7 +1100,7 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first ret->isTruncated = true; } - FREE(boundary); + CLI_FREE_AND_SET_NULL(boundary); freeList(head); @@ -1226,7 +1226,7 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) anyHeadersFound = usefulHeader(commandNumber, cmd); continue; } - fullline = cli_strdup(line); + fullline = cli_safer_strdup(line); fulllinelength = strlen(line) + 1; } else if (line) { fulllinelength += strlen(line) + 1; @@ -1363,7 +1363,7 @@ parseEmailHeader(message *m, const char *line, const table_t *rfc821, cli_ctx *c copy = rfc2047(line); if (copy == NULL) { /* an RFC checker would return -1 here */ - copy = cli_strdup(line); + copy = cli_safer_strdup(line); if (NULL == copy) { goto done; } @@ -1397,7 +1397,7 @@ parseEmailHeader(message *m, const char *line, const table_t *rfc821, cli_ctx *c } } done: - FREE(copy); + CLI_FREE_AND_SET_NULL(copy); return ret; } @@ -2058,7 +2058,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re fullline = rfc822comments(line, NULL); if (fullline == NULL) - fullline = cli_strdup(line); + fullline = cli_safer_strdup(line); /*quotes = count_quotes(fullline);*/ @@ -3241,7 +3241,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * Content-Type: multipart/mixed foo/bar */ if (s && *s) { - char *buf2 = cli_strdup(buf); + char *buf2 = cli_safer_strdup(buf); if (buf2 == NULL) { if (copy) @@ -3457,7 +3457,7 @@ rfc2047(const char *in) size_t len; if ((strstr(in, "=?") == NULL) || (strstr(in, "?=") == NULL)) - return cli_strdup(in); + return cli_safer_strdup(in); cli_dbgmsg("rfc2047 '%s'\n", in); out = cli_max_malloc(strlen(in) + 1); @@ -3503,7 +3503,7 @@ rfc2047(const char *in) if (*++in == '\0') break; - enctext = cli_strdup(in); + enctext = cli_safer_strdup(in); if (enctext == NULL) { free(out); out = NULL; diff --git a/libclamav/message.c b/libclamav/message.c index 02af52b790..2369f371a9 100644 --- a/libclamav/message.c +++ b/libclamav/message.c @@ -343,7 +343,7 @@ void messageSetMimeSubtype(message *m, const char *subtype) if (m->mimeSubtype) free(m->mimeSubtype); - m->mimeSubtype = cli_strdup(subtype); + m->mimeSubtype = cli_safer_strdup(subtype); } const char * @@ -375,7 +375,7 @@ void messageSetDispositionType(message *m, const char *disptype) while (*disptype && isspace((int)*disptype)) disptype++; if (*disptype) { - m->mimeDispositionType = cli_strdup(disptype); + m->mimeDispositionType = cli_safer_strdup(disptype); if (m->mimeDispositionType) strstrip(m->mimeDispositionType); } else @@ -558,7 +558,7 @@ void messageAddArguments(message *m, const char *s) * The field is in quotes, so look for the * closing quotes */ - kcopy = cli_strdup(key); + kcopy = cli_safer_strdup(key); if (kcopy == NULL) return; @@ -588,7 +588,7 @@ void messageAddArguments(message *m, const char *s) continue; } - data = cli_strdup(cptr); + data = cli_safer_strdup(cptr); if (!data) { cli_dbgmsg("Can't parse header \"%s\" - if you believe this file contains a missed virus, report it to bugs@clamav.net\n", s); @@ -704,7 +704,7 @@ messageFindArgument(const message *m, const char *variable) ptr++; if ((strlen(ptr) > 1) && (*ptr == '"') && (strchr(&ptr[1], '"') != NULL)) { /* Remove any quote characters */ - char *ret = cli_strdup(++ptr); + char *ret = cli_safer_strdup(++ptr); char *p; if (ret == NULL) @@ -725,7 +725,7 @@ messageFindArgument(const message *m, const char *variable) } return ret; } - return cli_strdup(ptr); + return cli_safer_strdup(ptr); } } return NULL; @@ -1278,7 +1278,7 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy f = lineGetData(t_line->t_line); if ((filename = strstr(f, " name=")) != NULL) { - filename = cli_strdup(&filename[6]); + filename = cli_safer_strdup(&filename[6]); if (filename) { cli_chomp(filename); strstrip(filename); @@ -1903,7 +1903,7 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s strcpy(base64buf, line); copy = base64buf; } else { - copy = cli_strdup(line); + copy = cli_safer_strdup(line); if (copy == NULL) break; } @@ -2386,7 +2386,7 @@ rfc2231(const char *in) } if (ptr == NULL) { /* quick return */ - out = ret = cli_strdup(in); + out = ret = cli_safer_strdup(in); while (*out) *out++ &= 0x7F; return ret; @@ -2461,7 +2461,7 @@ rfc2231(const char *in) if (field != CONTENTS) { free(ret); cli_dbgmsg("Invalid RFC2231 header: '%s'\n", in); - return cli_strdup(""); + return cli_safer_strdup(""); } *out = '\0'; @@ -2509,9 +2509,9 @@ simil(const char *str1, const char *str2) if (strcasecmp(str1, str2) == 0) return 100; - if ((s1 = cli_strdup(str1)) == NULL) + if ((s1 = cli_safer_strdup(str1)) == NULL) return OUT_OF_MEMORY; - if ((s2 = cli_strdup(str2)) == NULL) { + if ((s2 = cli_safer_strdup(str2)) == NULL) { free(s1); return OUT_OF_MEMORY; } @@ -2629,7 +2629,7 @@ push(LINK1 *top, const char *string) if ((element = (LINK1)malloc(sizeof(ELEMENT1))) == NULL) return OUT_OF_MEMORY; - if ((element->d1 = cli_strdup(string)) == NULL) { + if ((element->d1 = cli_safer_strdup(string)) == NULL) { free(element); return OUT_OF_MEMORY; } diff --git a/libclamav/mpool.h b/libclamav/mpool.h index d4c12f2c15..887b480674 100644 --- a/libclamav/mpool.h +++ b/libclamav/mpool.h @@ -70,10 +70,10 @@ typedef void mpool_t; #define MPOOL_FREE(a, b) free(b) #define MPOOL_CALLOC(a, b, c) calloc(b, c) #define MPOOL_REALLOC(a, b, c) cli_safer_realloc(b, c) -#define MPOOL_REALLOC2(a, b, c) cli_safer_realloc2(b, c) +#define MPOOL_REALLOC2(a, b, c) cli_safer_realloc_or_free(b, c) #define CLI_MPOOL_HEX2STR(mpool, src) cli_hex2str(src) -#define CLI_MPOOL_STRDUP(mpool, s) cli_strdup(s) -#define CLI_MPOOL_STRNDUP(mpool, s, n) cli_strdup(s, n) +#define CLI_MPOOL_STRDUP(mpool, s) cli_safer_strdup(s) +#define CLI_MPOOL_STRNDUP(mpool, s, n) cli_safer_strdup(s, n) #define CLI_MPOOL_VIRNAME(mpool, a, b) cli_virname(a, b) #define CLI_MPOOL_HEX2UI(mpool, hex) cli_hex2ui(hex) #define MPOOL_FLUSH(val) diff --git a/libclamav/ole2_extract.c b/libclamav/ole2_extract.c index d693c8cbab..dd13c1733c 100644 --- a/libclamav/ole2_extract.c +++ b/libclamav/ole2_extract.c @@ -196,7 +196,7 @@ int ole2_list_push(ole2_list_t *list, uint32_t val) ole2_list_node_t *new_node = NULL; int status = CL_EMEM; - MALLOC(new_node, sizeof(ole2_list_node_t), + CLI_MALLOC_OR_GOTO_DONE(new_node, sizeof(ole2_list_node_t), cli_dbgmsg("OLE2: could not allocate new node for worklist!\n")); new_node->Val = val; @@ -256,7 +256,7 @@ cli_ole2_get_property_name2(const char *name, int size) if ((name[0] == 0 && name[1] == 0) || size <= 0 || size > 128) { return NULL; } - CLI_MAX_MALLOC(newname, size * 7, + CLI_MAX_MALLOC_OR_GOTO_DONE(newname, size * 7, cli_errmsg("OLE2 [cli_ole2_get_property_name2]: Unable to allocate memory for newname: %u\n", size * 7)); j = 0; @@ -304,7 +304,7 @@ get_property_name(char *name, int size) return NULL; } - CLI_MAX_MALLOC(newname, size, + CLI_MAX_MALLOC_OR_GOTO_DONE(newname, size, cli_errmsg("OLE2 [get_property_name]: Unable to allocate memory for newname %u\n", size)); cname = newname; @@ -313,7 +313,7 @@ get_property_name(char *name, int size) oname += 2; if (u > 0x1040) { - FREE(newname); + CLI_FREE_AND_SET_NULL(newname); return cli_ole2_get_property_name2(name, size); } lo = u % 64; @@ -888,7 +888,7 @@ static cl_error_t handler_writefile(ole2_header_t *hdr, property_t *prop, const current_block = prop->start_block; len = prop->size; - CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, + CLI_MAX_MALLOC_OR_GOTO_DONE(buff, 1 << hdr->log2_big_block_size, cli_errmsg("OLE2 [handler_writefile]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); ret = CL_EMEM); @@ -956,11 +956,11 @@ static cl_error_t handler_writefile(ole2_header_t *hdr, property_t *prop, const ret = CL_SUCCESS; done: - FREE(name); + CLI_FREE_AND_SET_NULL(name); if (-1 != ofd) { close(ofd); } - FREE(buff); + CLI_FREE_AND_SET_NULL(buff); if (NULL != blk_bitset) { cli_bitset_free(blk_bitset); } @@ -1157,7 +1157,7 @@ static cl_error_t scan_for_xlm_macros_and_images(ole2_header_t *hdr, property_t current_block = prop->start_block; len = prop->size; - CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, + CLI_MAX_MALLOC_OR_GOTO_DONE(buff, 1 << hdr->log2_big_block_size, cli_errmsg("OLE2 [scan_for_xlm_macros_and_images]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); status = CL_EMEM); @@ -1207,7 +1207,7 @@ static cl_error_t scan_for_xlm_macros_and_images(ole2_header_t *hdr, property_t status = CL_SUCCESS; done: - FREE(buff); + CLI_FREE_AND_SET_NULL(buff); if (blk_bitset) { cli_bitset_free(blk_bitset); @@ -1282,7 +1282,7 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char } if (name) { if (!strcmp(name, "fileheader")) { - CLI_MAX_CALLOC(hwp_check, 1, 1 << hdr->log2_big_block_size, status = CL_EMEM); + CLI_MAX_CALLOC_OR_GOTO_DONE(hwp_check, 1, 1 << hdr->log2_big_block_size, status = CL_EMEM); /* reading safety checks; do-while used for breaks */ do { @@ -1316,7 +1316,7 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char #if HAVE_JSON cli_jsonstr(ctx->wrkproperty, "FileType", "CL_TYPE_HWP5"); #endif - CALLOC(hwp_new, 1, sizeof(hwp5_header_t), status = CL_EMEM); + CLI_CALLOC_OR_GOTO_DONE(hwp_new, 1, sizeof(hwp5_header_t), status = CL_EMEM); /* * Copy the header information into our header struct. @@ -1349,8 +1349,8 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char status = CL_SUCCESS; done: - FREE(name); - FREE(hwp_check); + CLI_FREE_AND_SET_NULL(name); + CLI_FREE_AND_SET_NULL(hwp_check); return status; } @@ -1567,7 +1567,7 @@ static cl_error_t handler_otf(ole2_header_t *hdr, property_t *prop, const char * cli_dbgmsg("OLE2 [handler_otf]: Dumping '%s' to '%s'\n", name, tempfile); } - CLI_MAX_MALLOC(buff, 1 << hdr->log2_big_block_size, ret = CL_EMEM); + CLI_MAX_MALLOC_OR_GOTO_DONE(buff, 1 << hdr->log2_big_block_size, ret = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { @@ -1677,11 +1677,11 @@ static cl_error_t handler_otf(ole2_header_t *hdr, property_t *prop, const char * ret = ret == CL_VIRUS ? CL_VIRUS : CL_SUCCESS; done: - FREE(name); + CLI_FREE_AND_SET_NULL(name); if (-1 != ofd) { close(ofd); } - FREE(buff); + CLI_FREE_AND_SET_NULL(buff); if (NULL != blk_bitset) { cli_bitset_free(blk_bitset); } @@ -1746,7 +1746,7 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co goto done; } - CLI_MAX_MALLOC(rk, RKLENGTH(key->key_length_bits) * sizeof(uint64_t), ret = CL_EMEM); + CLI_MAX_MALLOC_OR_GOTO_DONE(rk, RKLENGTH(key->key_length_bits) * sizeof(uint64_t), ret = CL_EMEM); print_ole2_property(prop); @@ -1774,8 +1774,8 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co } uint32_t blockSize = 1 << hdr->log2_big_block_size; - CLI_MAX_MALLOC(buff, blockSize + sizeof(uint64_t), ret = CL_EMEM); - CLI_MAX_MALLOC(decryptDst, blockSize, ret = CL_EMEM); + CLI_MAX_MALLOC_OR_GOTO_DONE(buff, blockSize + sizeof(uint64_t), ret = CL_EMEM); + CLI_MAX_MALLOC_OR_GOTO_DONE(decryptDst, blockSize, ret = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { @@ -1921,11 +1921,11 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co ret = ret == CL_VIRUS ? CL_VIRUS : CL_SUCCESS; done: - FREE(name); + CLI_FREE_AND_SET_NULL(name); if (-1 != ofd) { close(ofd); } - FREE(buff); + CLI_FREE_AND_SET_NULL(buff); if (NULL != blk_bitset) { cli_bitset_free(blk_bitset); } @@ -1938,8 +1938,8 @@ static cl_error_t handler_otf_encrypted(ole2_header_t *hdr, property_t *prop, co free(tempfile); tempfile = NULL; } - FREE(decryptDst); - FREE(rk); + CLI_FREE_AND_SET_NULL(decryptDst); + CLI_FREE_AND_SET_NULL(rk); return ret; } @@ -2136,7 +2136,7 @@ static cl_error_t generate_key_aes(const char *const password, encryption_key_t memcpy(key->key, doubleSha, tmp); ret = CL_SUCCESS; done: - FREE(buffer); + CLI_FREE_AND_SET_NULL(buffer); return ret; } diff --git a/libclamav/others.h b/libclamav/others.h index f2f1a54d0a..6c44edb6f2 100644 --- a/libclamav/others.h +++ b/libclamav/others.h @@ -941,7 +941,7 @@ static inline int cli_getpagesize(void) /** * @brief Wrapper around malloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_MAX_MALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_MALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. * * @param ptr * @param size @@ -950,9 +950,9 @@ static inline int cli_getpagesize(void) void *cli_max_malloc(size_t nmemb); /** - * @brief Wrapper around Calloc that limits how much may be allocated to CLI_MAX_ALLOCATION. + * @brief Wrapper around calloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_MAX_CALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_CALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. * * @param ptr * @param size @@ -963,7 +963,9 @@ void *cli_max_calloc(size_t nmemb, size_t size); /** * @brief Wrapper around realloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_REALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. + * + * NOTE: cli_max_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * @@ -976,7 +978,7 @@ void *cli_max_realloc(void *ptr, size_t size); /** * @brief Wrapper around realloc that limits how much may be allocated to CLI_MAX_ALLOCATION. * - * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_REALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * @@ -987,12 +989,12 @@ void *cli_max_realloc(void *ptr, size_t size); * @param size * @return void* */ -void *cli_max_realloc2(void *ptr, size_t size); +void *cli_max_realloc_or_free(void *ptr, size_t size); /** * @brief Wrapper around realloc that, unlike some variants of realloc, will not free the ptr if size==0. * - * Please use CLI_MAX_REALLOC() with `goto done;` error handling instead. + * Please use CLI_MAX_REALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * @@ -1005,7 +1007,7 @@ void *cli_safer_realloc(void *ptr, size_t size); /** * @brief Wrapper around realloc that, unlike some variants of realloc, will not free the ptr if size==0. * - * Please use CLI_SAFER_REALLOC() with `goto done;` error handling instead. + * Please use CLI_SAFER_REALLOC_OR_GOTO_DONE() with `goto done;` error handling instead. * * IMPORTANT: This differs from realloc() in that if size==0, it will NOT free the ptr. * @@ -1016,15 +1018,17 @@ void *cli_safer_realloc(void *ptr, size_t size); * @param size * @return void* */ -void *cli_safer_realloc2(void *ptr, size_t size); +void *cli_safer_realloc_or_free(void *ptr, size_t size); /** * @brief Wrapper around strdup that does a NULL check. * + * Please use CLI_STRDUP_OR_GOTO_DONE() with `goto done;` error handling instead. + * * @param s * @return char* Returns the allocated string or NULL if allocation failed. This includes if allocation fails because s==NULL. */ -char *cli_strdup(const char *s); +char *cli_safer_strdup(const char *s); int cli_rmdirs(const char *dirname); char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type); @@ -1298,103 +1302,150 @@ uint8_t cli_get_debug_flag(void); */ uint8_t cli_set_debug_flag(uint8_t debug_flag); -#ifndef STRDUP -#define STRDUP(buf, var, ...) \ - do { \ - var = strdup(buf); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ - } while (0) -#endif - -#ifndef CLI_STRDUP -#define CLI_STRDUP(buf, var, ...) \ - do { \ - var = cli_strdup(buf); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_SAFER_STRDUP_OR_GOTO_DONE +/** + * @brief Wrapper around strdup that does a NULL check. + * + * This macro requires `goto done;` error handling. + * + * @param buf The string to duplicate. + * @param var The variable to assign the allocated string to. + * @param ... The error handling code to execute if the allocation fails. + */ +#define CLI_SAFER_STRDUP_OR_GOTO_DONE(buf, var, ...) \ + do { \ + var = cli_safer_strdup(buf); \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif -#ifndef FREE -#define FREE(var) \ - do { \ - if (NULL != var) { \ - free(var); \ - var = NULL; \ - } \ +#ifndef CLI_FREE_AND_SET_NULL +/** + * @brief Wrapper around `free()` to ensure you reset the variable to NULL so as to prevent a double-free. + * + * @param var The variable to free and set to NULL. + */ +#define CLI_FREE_AND_SET_NULL(var) \ + do { \ + if (NULL != var) { \ + free(var); \ + var = NULL; \ + } \ } while (0) #endif -#ifndef MALLOC -#define MALLOC(var, size, ...) \ - do { \ - var = malloc(size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_MALLOC_OR_GOTO_DONE +/** + * @brief Wrapper around malloc that will `goto done;` if the allocation fails. + * + * This macro requires `goto done;` error handling. + * + * @param ptr The variable to assign the allocated memory to. + * @param size The size of the memory to allocate. + * @param ... The error handling code to execute if the allocation fails. + */ +#define CLI_MALLOC_OR_GOTO_DONE(var, size, ...) \ + do { \ + var = malloc(size); \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif -#ifndef CLI_MAX_MALLOC -#define CLI_MAX_MALLOC(var, size, ...) \ - do { \ - var = cli_max_malloc(size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_MAX_MALLOC_OR_GOTO_DONE +/** + * @brief Wrapper around malloc that limits how much may be allocated to CLI_MAX_ALLOCATION. + * + * This macro requires `goto done;` error handling. + * + * @param var The variable to assign the allocated memory to. + * @param size The size of the memory to allocate. + * @param ... The error handling code to execute if the allocation fails. + */ +#define CLI_MAX_MALLOC_OR_GOTO_DONE(var, size, ...) \ + do { \ + var = cli_max_malloc(size); \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif -#ifndef CALLOC -#define CALLOC(var, nmemb, size, ...) \ - do { \ - (var) = calloc(nmemb, size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_CALLOC_OR_GOTO_DONE +/** + * @brief Wrapper around calloc that will `goto done;` if the allocation fails. + * + * This macro requires `goto done;` error handling. + * + * @param var The variable to assign the allocated memory to. + * @param nmemb The number of elements to allocate. + * @param size The size of each element. + * @param ... The error handling code to execute if the allocation fails. + */ +#define CLI_CALLOC_OR_GOTO_DONE(var, nmemb, size, ...) \ + do { \ + (var) = calloc(nmemb, size); \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif -#ifndef CLI_MAX_CALLOC -#define CLI_MAX_CALLOC(var, nmemb, size, ...) \ - do { \ - (var) = cli_max_calloc(nmemb, size); \ - if (NULL == var) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_MAX_CALLOC_OR_GOTO_DONE +/** + * @brief Wrapper around calloc that limits how much may be allocated to CLI_MAX_ALLOCATION. + * + * This macro requires `goto done;` error handling. + * + * @param var The variable to assign the allocated memory to. + * @param nmemb The number of elements to allocate. + * @param size The size of each element. + * @param ... The error handling code to execute if the allocation fails. + */ +#define CLI_MAX_CALLOC_OR_GOTO_DONE(var, nmemb, size, ...) \ + do { \ + (var) = cli_max_calloc(nmemb, size); \ + if (NULL == var) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif -#ifndef VERIFY_POINTER -#define VERIFY_POINTER(ptr, ...) \ - do { \ - if (NULL == ptr) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ +#ifndef CLI_VERIFY_POINTER_OR_GOTO_DONE +/** + * @brief Wrapper around a NULL-check that will `goto done;` if the pointer is NULL. + * + * This macro requires `goto done;` error handling. + * + * @param ptr The pointer to verify. + * @param ... The error handling code to execute if the pointer is NULL. + */ +#define CLI_VERIFY_POINTER_OR_GOTO_DONE(ptr, ...) \ + do { \ + if (NULL == ptr) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ } while (0) #endif @@ -1405,21 +1456,21 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); * * NOTE: cli_max_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. * - * @param ptr - * @param size - * @return void* + * @param ptr The pointer to realloc. + * @param size The size of the memory to allocate. + * @param ... The error handling code to execute if the allocation fails. */ -#ifndef CLI_MAX_REALLOC -#define CLI_MAX_REALLOC(ptr, size, ...) \ - do { \ - void *vTmp = cli_max_realloc(ptr, size); \ - if (NULL == vTmp) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ - ptr = vTmp; \ +#ifndef CLI_MAX_REALLOC_OR_GOTO_DONE +#define CLI_MAX_REALLOC_OR_GOTO_DONE(ptr, size, ...) \ + do { \ + void *vTmp = cli_max_realloc(ptr, size); \ + if (NULL == vTmp) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ + ptr = vTmp; \ } while (0) #endif @@ -1430,21 +1481,21 @@ uint8_t cli_set_debug_flag(uint8_t debug_flag); * * NOTE: cli_safer_realloc() will NOT free ptr if size==0. It is safe to free ptr after `done:`. * - * @param ptr - * @param size - * @return void* + * @param ptr The pointer to realloc. + * @param size The size of the memory to allocate. + * @param ... The error handling code to execute if the allocation fails. */ -#ifndef CLI_SAFER_REALLOC -#define CLI_SAFER_REALLOC(ptr, size, ...) \ - do { \ - void *vTmp = cli_safer_realloc(ptr, size); \ - if (NULL == vTmp) { \ - do { \ - __VA_ARGS__; \ - } while (0); \ - goto done; \ - } \ - ptr = vTmp; \ +#ifndef CLI_SAFER_REALLOC_OR_GOTO_DONE +#define CLI_SAFER_REALLOC_OR_GOTO_DONE(ptr, size, ...) \ + do { \ + void *vTmp = cli_safer_realloc(ptr, size); \ + if (NULL == vTmp) { \ + do { \ + __VA_ARGS__; \ + } while (0); \ + goto done; \ + } \ + ptr = vTmp; \ } while (0) #endif diff --git a/libclamav/others_common.c b/libclamav/others_common.c index 6700cd1fca..ce549f0787 100644 --- a/libclamav/others_common.c +++ b/libclamav/others_common.c @@ -278,12 +278,12 @@ void *cli_safer_realloc(void *ptr, size_t size) } } -void *cli_safer_realloc2(void *ptr, size_t size) +void *cli_safer_realloc_or_free(void *ptr, size_t size) { void *alloc; if (0 == size) { - cli_errmsg("cli_max_realloc2(): Attempt to allocate 0 bytes. Please report to https://github.com/Cisco-Talos/clamav/issues\n"); + cli_errmsg("cli_max_realloc_or_free(): Attempt to allocate 0 bytes. Please report to https://github.com/Cisco-Talos/clamav/issues\n"); return NULL; } @@ -291,7 +291,7 @@ void *cli_safer_realloc2(void *ptr, size_t size) if (!alloc) { perror("realloc_problem"); - cli_errmsg("cli_max_realloc2(): Can't re-allocate memory to %lu bytes.\n", (unsigned long int)size); + cli_errmsg("cli_max_realloc_or_free(): Can't re-allocate memory to %lu bytes.\n", (unsigned long int)size); // free the original pointer if (ptr) { @@ -325,12 +325,12 @@ void *cli_max_realloc(void *ptr, size_t size) } } -void *cli_max_realloc2(void *ptr, size_t size) +void *cli_max_realloc_or_free(void *ptr, size_t size) { void *alloc; if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_max_realloc2(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_max_realloc_or_free(): File or section is too large to scan (%zu bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); return NULL; } @@ -339,7 +339,7 @@ void *cli_max_realloc2(void *ptr, size_t size) if (!alloc) { perror("realloc_problem"); - cli_errmsg("cli_max_realloc2(): Can't re-allocate memory to %zu bytes.\n", size); + cli_errmsg("cli_max_realloc_or_free(): Can't re-allocate memory to %zu bytes.\n", size); // free the original pointer if (ptr) { @@ -352,12 +352,12 @@ void *cli_max_realloc2(void *ptr, size_t size) } } -char *cli_strdup(const char *s) +char *cli_safer_strdup(const char *s) { char *alloc; if (s == NULL) { - cli_errmsg("cli_strdup(): passed reference is NULL, nothing to duplicate\n"); + cli_errmsg("cli_safer_strdup(): passed reference is NULL, nothing to duplicate\n"); return NULL; } @@ -365,7 +365,7 @@ char *cli_strdup(const char *s) if (!alloc) { perror("strdup_problem"); - cli_errmsg("cli_strdup(): Can't allocate memory (%u bytes).\n", (unsigned int)strlen(s)); + cli_errmsg("cli_safer_strdup(): Can't allocate memory (%u bytes).\n", (unsigned int)strlen(s)); return NULL; } @@ -687,7 +687,7 @@ static cl_error_t handle_filetype(const char *fname, int flags, if (*stated == -1) { /* we failed a stat() or lstat() */ - char *fname_copy = cli_strdup(fname); + char *fname_copy = cli_safer_strdup(fname); if (NULL == fname_copy) { goto done; } @@ -699,7 +699,7 @@ static cl_error_t handle_filetype(const char *fname, int flags, *ft = ft_unknown; } else if (*ft == ft_skipped_link || *ft == ft_skipped_special) { /* skipped filetype */ - char *fname_copy = cli_strdup(fname); + char *fname_copy = cli_safer_strdup(fname); if (NULL == fname_copy) { goto done; } @@ -777,7 +777,7 @@ cl_error_t cli_ftw(char *path, int flags, int maxdepth, cli_ftw_cb callback, str */ if (entry.is_dir) { /* Allocate the filename for the callback function. TODO: this FTW code is spaghetti, refactor. */ - filename_for_callback = cli_strdup(path); + filename_for_callback = cli_safer_strdup(path); if (NULL == filename_for_callback) { goto done; } @@ -800,7 +800,7 @@ cl_error_t cli_ftw(char *path, int flags, int maxdepth, cli_ftw_cb callback, str entry.dirname = path; } else { /* Allocate the filename for the callback function within the handle_entry function. TODO: this FTW code is spaghetti, refactor. */ - filename_for_handleentry = cli_strdup(path); + filename_for_handleentry = cli_safer_strdup(path); if (NULL == filename_for_handleentry) { goto done; } diff --git a/libclamav/pdf.c b/libclamav/pdf.c index 9f4f46badd..a364aad56e 100644 --- a/libclamav/pdf.c +++ b/libclamav/pdf.c @@ -480,7 +480,7 @@ int pdf_findobj_in_objstm(struct pdf_struct *pdf, struct objstm_struct *objstm, /* Success! Add the object to the list of all objects found. */ pdf->nobjs++; - CLI_MAX_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, + CLI_MAX_REALLOC_OR_GOTO_DONE(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, cli_warnmsg("pdf_findobj_in_objstm: out of memory finding objects in stream\n"), status = CL_EMEM); pdf->objs[pdf->nobjs - 1] = obj; @@ -545,7 +545,7 @@ cl_error_t pdf_findobj(struct pdf_struct *pdf) goto done; } pdf->nobjs++; - CLI_MAX_REALLOC(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, status = CL_EMEM); + CLI_MAX_REALLOC_OR_GOTO_DONE(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, status = CL_EMEM); obj = malloc(sizeof(struct pdf_obj)); if (!obj) { @@ -1627,7 +1627,7 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t } else { /* Add objstm to pdf struct, so it can be freed eventually */ pdf->nobjstms++; - pdf->objstms = cli_max_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); + pdf->objstms = cli_max_realloc_or_free(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); if (!pdf->objstms) { cli_warnmsg("pdf_extract_obj: out of memory parsing object stream (%u)\n", pdf->nobjstms); pdf_free_dict(dparams); @@ -1692,7 +1692,7 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t free(pdf->objstms); pdf->objstms = NULL; } else { - pdf->objstms = cli_max_realloc2(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); + pdf->objstms = cli_max_realloc_or_free(pdf->objstms, sizeof(struct objstm_struct *) * pdf->nobjstms); if (!pdf->objstms) { cli_warnmsg("pdf_extract_obj: out of memory when shrinking down objstm array\n"); diff --git a/libclamav/pe.c b/libclamav/pe.c index a2decd941d..b0cc9f4a9b 100644 --- a/libclamav/pe.c +++ b/libclamav/pe.c @@ -2211,7 +2211,7 @@ static char *pe_ordinal(const char *dll, uint16_t ord) if (name[0] == '\0') sprintf(name, "ord%u", ord); - return cli_strdup(name); + return cli_safer_strdup(name); } static int validate_impname(const char *name, uint32_t length, int dll) @@ -3218,7 +3218,7 @@ int cli_scanpe(cli_ctx *ctx) if (xsjs == 1280) break; - if (!(jumps = (uint32_t *)cli_max_realloc2(jumps, (xsjs + 128) * sizeof(uint32_t)))) { + if (!(jumps = (uint32_t *)cli_max_realloc_or_free(jumps, (xsjs + 128) * sizeof(uint32_t)))) { cli_exe_info_destroy(peinfo); return CL_EMEM; } diff --git a/libclamav/phishcheck.c b/libclamav/phishcheck.c index 7173639fc8..56861ac8c7 100644 --- a/libclamav/phishcheck.c +++ b/libclamav/phishcheck.c @@ -1537,13 +1537,13 @@ static enum phish_status phishingCheck(cli_ctx* ctx, struct url_check* urls) */ /* Provide copies of the original URL's, because domain_list_match() may modify the buffer, and we don't want that to happen in this case. */ - realData = cli_strdup(urls->realLink.data); + realData = cli_safer_strdup(urls->realLink.data); if (!realData) { cli_errmsg("Phishcheck: Failed to allocate memory for temporary real link string.\n"); phishing_verdict = CL_PHISH_CLEAN; goto done; } - displayData = cli_strdup(urls->displayLink.data); + displayData = cli_safer_strdup(urls->displayLink.data); if (!displayData) { cli_errmsg("Phishcheck: Failed to allocate memory for temporary display link string.\n"); phishing_verdict = CL_PHISH_CLEAN; diff --git a/libclamav/readdb.c b/libclamav/readdb.c index 7b63989187..4dbe539efe 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -114,7 +114,7 @@ char *cli_virname(const char *virname, unsigned int official) } if (official) - return cli_strdup(virname); + return cli_safer_strdup(virname); newname = (char *)malloc(strlen(virname) + 11 + 1); if (!newname) { @@ -142,7 +142,7 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co return CL_EPARSE; } - hexcpy = cli_strdup(hexsig); + hexcpy = cli_safer_strdup(hexsig); if (!hexcpy) return CL_EMEM; @@ -373,7 +373,7 @@ static cl_error_t readdb_load_regex_subsignature(struct cli_matcher *root, const } /* get copied */ - hexcpy = cli_strdup(sig); + hexcpy = cli_safer_strdup(sig); if (!hexcpy) { status = CL_EMEM; goto done; @@ -420,7 +420,7 @@ static cl_error_t readdb_load_regex_subsignature(struct cli_matcher *root, const done: - FREE(hexcpy); + CLI_FREE_AND_SET_NULL(hexcpy); return status; } @@ -634,7 +634,7 @@ cl_error_t readdb_parse_ldb_subsignature(struct cli_matcher *root, const char *v ffierror_free(fuzzy_hash_load_error); } - FREE(hexcpy); + CLI_FREE_AND_SET_NULL(hexcpy); return status; } @@ -795,7 +795,7 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v // Make a copy of the whole pattern so that we can NULL-terminate the hexsig // and pass it to cli_ac_addsig() without having to pass the part-length. - if (!(hexcpy = cli_strdup(hexsig))) + if (!(hexcpy = cli_safer_strdup(hexsig))) return CL_EMEM; start = pt = hexcpy; @@ -2330,7 +2330,7 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, return CL_SUCCESS; } - bcs->all_bcs = cli_safer_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); + bcs->all_bcs = cli_safer_realloc_or_free(bcs->all_bcs, sizeof(*bcs->all_bcs) * (bcs->count + 1)); if (!bcs->all_bcs) { cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n"); return CL_EMEM; @@ -2401,7 +2401,7 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, if (bc->kind >= _BC_START_HOOKS && bc->kind < _BC_LAST_HOOK) { unsigned hook = bc->kind - _BC_START_HOOKS; unsigned cnt = ++engine->hooks_cnt[hook]; - engine->hooks[hook] = cli_safer_realloc2(engine->hooks[hook], + engine->hooks[hook] = cli_safer_realloc_or_free(engine->hooks[hook], sizeof(*engine->hooks[0]) * cnt); if (!engine->hooks[hook]) { cli_errmsg("Out of memory allocating memory for hook %u", hook); @@ -3720,7 +3720,7 @@ static cl_error_t ytable_add_attrib(struct cli_ytable *ytable, const char *hexsi if (ytable->table[lookup]->offset) free(ytable->table[lookup]->offset); - ytable->table[lookup]->offset = cli_strdup(value); + ytable->table[lookup]->offset = cli_safer_strdup(value); if (!ytable->table[lookup]->offset) { cli_yaramsg("ytable_add_attrib: ran out of memory for offset\n"); @@ -3747,7 +3747,7 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) return CL_EMEM; } - new->hexstr = cli_strdup(hexsig); + new->hexstr = cli_safer_strdup(hexsig); if (!new->hexstr) { cli_yaramsg("ytable_add_string: out of memory for hexsig copy\n"); free(new); @@ -4221,10 +4221,10 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns /* TDB */ if (rule->cl_flags & RULE_EP && ytable.tbl_cnt == 1) - target_str = cli_strdup(YARATARGET1); + target_str = cli_safer_strdup(YARATARGET1); else #endif - target_str = cli_strdup(YARATARGET0); + target_str = cli_safer_strdup(YARATARGET0); memset(&tdb, 0, sizeof(tdb)); if (CL_SUCCESS != (ret = init_tdb(&tdb, engine, target_str, newident))) { @@ -4592,7 +4592,7 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options /* append target type 0 to tdb string if needed */ if ((tokens[1][0] == '\0') || (strstr(tokens[1], "Target:") != NULL)) { - attribs = cli_strdup(tokens[1]); + attribs = cli_safer_strdup(tokens[1]); if (!attribs) { cli_errmsg("cli_loadpwdb: Can't allocate memory for attributes\n"); ret = CL_EMEM; @@ -5397,7 +5397,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) dbstat->entries = 0; dbstat->stattab = NULL; dbstat->statdname = NULL; - dbstat->dir = cli_strdup(dirname); + dbstat->dir = cli_safer_strdup(dirname); } else { cli_errmsg("cl_statdbdir(): Null argument passed.\n"); return CL_ENULLARG; @@ -5415,7 +5415,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) if (dent->d_ino) { if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..") && CLI_DBEXT(dent->d_name)) { dbstat->entries++; - dbstat->stattab = (STATBUF *)cli_safer_realloc2(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); + dbstat->stattab = (STATBUF *)cli_safer_realloc_or_free(dbstat->stattab, dbstat->entries * sizeof(STATBUF)); if (!dbstat->stattab) { cl_statfree(dbstat); closedir(dd); @@ -5423,7 +5423,7 @@ cl_error_t cl_statinidir(const char *dirname, struct cl_stat *dbstat) } #ifdef _WIN32 - dbstat->statdname = (char **)cli_safer_realloc2(dbstat->statdname, dbstat->entries * sizeof(char *)); + dbstat->statdname = (char **)cli_safer_realloc_or_free(dbstat->statdname, dbstat->entries * sizeof(char *)); if (!dbstat->statdname) { cli_errmsg("cl_statinidir: Can't allocate memory for dbstat->statdname\n"); cl_statfree(dbstat); diff --git a/libclamav/regex_list.c b/libclamav/regex_list.c index b94f04a6ac..3fda1abc59 100644 --- a/libclamav/regex_list.c +++ b/libclamav/regex_list.c @@ -224,7 +224,7 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const if (CL_SUCCESS != (rc = cli_ac_initdata(&mdata, 0, 0, 0, CLI_DEFAULT_AC_TRACKLEN))) return rc; - bufrev = cli_strdup(buffer); + bufrev = cli_safer_strdup(buffer); if (!bufrev) return CL_EMEM; @@ -774,14 +774,14 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su goto done; } - MALLOC(regex, sizeof(*regex), + CLI_MALLOC_OR_GOTO_DONE(regex, sizeof(*regex), cli_errmsg("add_pattern_suffix: Unable to allocate memory for regex\n"); ret = CL_EMEM); if (NULL == iregex->pattern) { regex->pattern = NULL; } else { - CLI_STRDUP(iregex->pattern, regex->pattern, + CLI_SAFER_STRDUP_OR_GOTO_DONE(iregex->pattern, regex->pattern, cli_errmsg("add_pattern_suffix: unable to strdup iregex->pattern"); ret = CL_EMEM); } @@ -802,7 +802,7 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su /* new suffix */ size_t n = matcher->suffix_cnt; el = cli_hashtab_insert(&matcher->suffix_hash, suffix, suffix_len, (cli_element_data)n); - CLI_MAX_REALLOC(matcher->suffix_regexes, + CLI_MAX_REALLOC_OR_GOTO_DONE(matcher->suffix_regexes, (n + 1) * sizeof(*matcher->suffix_regexes), cli_errmsg("add_pattern_suffix: Unable to reallocate memory for matcher->suffix_regexes\n"); ret = CL_EMEM); @@ -817,7 +817,7 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su if (CL_SUCCESS != ret) { cli_hashtab_delete(&matcher->suffix_hash, suffix, suffix_len); /*shrink the size back to what it was.*/ - CLI_MAX_REALLOC(matcher->suffix_regexes, n * sizeof(*matcher->suffix_regexes)); + CLI_MAX_REALLOC_OR_GOTO_DONE(matcher->suffix_regexes, n * sizeof(*matcher->suffix_regexes)); } else { matcher->suffix_cnt++; } @@ -825,8 +825,8 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su done: if (CL_SUCCESS != ret) { - FREE(regex->pattern); - FREE(regex); + CLI_FREE_AND_SET_NULL(regex->pattern); + CLI_FREE_AND_SET_NULL(regex); } return ret; @@ -869,13 +869,13 @@ static cl_error_t add_static_pattern(struct regex_matcher *matcher, char *patter len = reverse_string(pattern); regex.nxt = NULL; - CLI_STRDUP(pattern, regex.pattern, + CLI_SAFER_STRDUP_OR_GOTO_DONE(pattern, regex.pattern, cli_errmsg("add_static_pattern: Cannot allocate memory for regex.pattern\n"); rc = CL_EMEM); regex.preg = NULL; rc = add_pattern_suffix(matcher, pattern, len, ®ex); done: - FREE(regex.pattern); + CLI_FREE_AND_SET_NULL(regex.pattern); return rc; } diff --git a/libclamav/regex_suffix.c b/libclamav/regex_suffix.c index 5f99ddb1ed..0dffaa268a 100644 --- a/libclamav/regex_suffix.c +++ b/libclamav/regex_suffix.c @@ -175,13 +175,13 @@ static void destroy_tree(struct node *n) break; case leaf_class: if (n->u.leaf_class_bitmap != dot_bitmap) - FREE(n->u.leaf_class_bitmap); + CLI_FREE_AND_SET_NULL(n->u.leaf_class_bitmap); break; case root: case leaf: break; } - FREE(n); + CLI_FREE_AND_SET_NULL(n); } static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos) @@ -193,7 +193,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos do { \ if (((*posPtr) + incVal) >= posMax) { \ cli_warnmsg("parse_char_class: Invalid char class\n"); \ - FREE(bitmap); \ + CLI_FREE_AND_SET_NULL(bitmap); \ goto done; \ } \ (*posPtr)++; \ @@ -207,7 +207,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos int hasprev = 0; uint8_t *bitmap = NULL; - MALLOC(bitmap, 32, + CLI_MALLOC_OR_GOTO_DONE(bitmap, 32, cli_errmsg("parse_char_class: Unable to allocate memory for bitmap\n")); if (pat[*pos] == '^') { @@ -222,7 +222,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos unsigned char range_end; unsigned int c; if (0 == range_start) { - FREE(bitmap); + CLI_FREE_AND_SET_NULL(bitmap); cli_errmsg("parse_char_class: range_start not initialized\n"); goto done; } @@ -230,7 +230,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos if (pat[*pos] == '[') if (pat[*pos + 1] == '.') { /* collating sequence not handled */ - FREE(bitmap); + CLI_FREE_AND_SET_NULL(bitmap); /* we are parsing the regex for a * filter, be conservative and * tell the filter that anything could @@ -248,7 +248,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos hasprev = 0; } else if (pat[*pos] == '[' && pat[*pos] == ':') { /* char class */ - FREE(bitmap); + CLI_FREE_AND_SET_NULL(bitmap); while (pat[*pos] != ']') INC_POS(pos, patSize); INC_POS(pos, patSize); while (pat[*pos] != ']') INC_POS(pos, patSize); @@ -501,7 +501,7 @@ cl_error_t cli_regex2suffix(const char *pattern, regex_t *preg, suffix_callback return rc; } regex.nxt = NULL; - CLI_STRDUP(pattern, regex.pattern, + CLI_SAFER_STRDUP_OR_GOTO_DONE(pattern, regex.pattern, cli_errmsg("cli_regex2suffix: unable to strdup regex.pattern\n"); rc = REG_ESPACE); @@ -517,8 +517,8 @@ cl_error_t cli_regex2suffix(const char *pattern, regex_t *preg, suffix_callback rc = build_suffixtree_descend(n, &buf, cb, cbdata, ®ex); done: - FREE(regex.pattern); - FREE(buf.data); + CLI_FREE_AND_SET_NULL(regex.pattern); + CLI_FREE_AND_SET_NULL(buf.data); destroy_tree(n); return rc; } diff --git a/libclamav/scanners.c b/libclamav/scanners.c index a9d169bed8..e5152da56b 100644 --- a/libclamav/scanners.c +++ b/libclamav/scanners.c @@ -4014,7 +4014,7 @@ static cl_error_t dispatch_file_inspection_callback(clcb_file_inspection cb, cli fmap = ctx->recursion_stack[fmap_index].fmap; fd = fmap_fd(fmap); - CLI_MAX_CALLOC(ancestors, ctx->recursion_level + 1, sizeof(char *), status = CL_EMEM); + CLI_MAX_CALLOC_OR_GOTO_DONE(ancestors, ctx->recursion_level + 1, sizeof(char *), status = CL_EMEM); file_name = fmap->name; file_buffer = fmap_need_off_once_len(fmap, 0, fmap->len, &file_size); @@ -4056,7 +4056,7 @@ static cl_error_t dispatch_file_inspection_callback(clcb_file_inspection cb, cli done: - FREE(ancestors); + CLI_FREE_AND_SET_NULL(ancestors); return status; } @@ -5406,7 +5406,7 @@ static cl_error_t scan_common(cl_fmap_t *map, const char *filepath, const char * ctx.engine = engine; ctx.scanned = scanned; - MALLOC(ctx.options, sizeof(struct cl_scan_options), status = CL_EMEM); + CLI_MALLOC_OR_GOTO_DONE(ctx.options, sizeof(struct cl_scan_options), status = CL_EMEM); memcpy(ctx.options, scanoptions, sizeof(struct cl_scan_options)); diff --git a/libclamav/sis.c b/libclamav/sis.c index fb8b57ed48..7c277b4358 100644 --- a/libclamav/sis.c +++ b/libclamav/sis.c @@ -428,7 +428,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) } if ((install_filepath = getsistring(map, pdname, sdname))) { cli_dbgmsg("\tInstalled to: %s\n", install_filepath); - FREE(install_filepath); + CLI_FREE_AND_SET_NULL(install_filepath); } if (!(ptrs = cli_max_malloc(fcount * sizeof(uint32_t) * 3))) { @@ -492,7 +492,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) } if (uncompress(decomp, &olen, comp, lens[j]) != Z_OK) { cli_dbgmsg("\tUnpacking failure\n"); - FREE(decomp); + CLI_FREE_AND_SET_NULL(decomp); continue; } decompp = decomp; @@ -515,7 +515,7 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) goto done; } - FREE(decomp); + CLI_FREE_AND_SET_NULL(decomp); status = cli_magic_scan_desc(fd, ofn, ctx, original_filepath, LAYER_ATTRIBUTES_NONE); if (CL_SUCCESS != status) { @@ -529,8 +529,8 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) } } - FREE(original_filepath); - FREE(ptrs); + CLI_FREE_AND_SET_NULL(original_filepath); + CLI_FREE_AND_SET_NULL(ptrs); fcount = 2 * sizeof(uint32_t); break; @@ -569,10 +569,10 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) if (-1 != fd) { close(fd); } - FREE(original_filepath); - FREE(decomp); - FREE(ptrs); - FREE(alangs); + CLI_FREE_AND_SET_NULL(original_filepath); + CLI_FREE_AND_SET_NULL(decomp); + CLI_FREE_AND_SET_NULL(ptrs); + CLI_FREE_AND_SET_NULL(alangs); return status; } diff --git a/libclamav/str.c b/libclamav/str.c index acadaa9912..5ccc9e882f 100644 --- a/libclamav/str.c +++ b/libclamav/str.c @@ -974,7 +974,7 @@ char *cli_unescape(const char *str) R[i++] = c; } R[i++] = '\0'; - R = cli_max_realloc2(R, i); + R = cli_max_realloc_or_free(R, i); return R; } diff --git a/libclamav/table.c b/libclamav/table.c index 865843423b..7cf8e0835e 100644 --- a/libclamav/table.c +++ b/libclamav/table.c @@ -91,7 +91,7 @@ int tableInsert(table_t *table, const char *key, int value) for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) if (tableItem->key == NULL) { /* This item has been deleted */ - tableItem->key = cli_strdup(key); + tableItem->key = cli_safer_strdup(key); tableItem->value = value; return value; } @@ -109,7 +109,7 @@ int tableInsert(table_t *table, const char *key, int value) } table->tableLast->next = NULL; - table->tableLast->key = cli_strdup(key); + table->tableLast->key = cli_safer_strdup(key); table->tableLast->value = value; return value; diff --git a/libclamav/udf.c b/libclamav/udf.c index f7b7d5a1b1..895bb8d515 100644 --- a/libclamav/udf.c +++ b/libclamav/udf.c @@ -100,7 +100,7 @@ static cl_error_t writeWholeFile(cli_ctx *ctx, const char *const fileName, const } } - FREE(tmpf); + CLI_FREE_AND_SET_NULL(tmpf); return status; } @@ -623,7 +623,7 @@ typedef struct { static void freePointerList(PointerList *pl) { - FREE(pl->idxs); + CLI_FREE_AND_SET_NULL(pl->idxs); memset(pl, 0, sizeof(PointerList)); } @@ -633,7 +633,7 @@ static cl_error_t initPointerList(PointerList *pl) uint32_t capacity = POINTER_LIST_INCREMENT; freePointerList(pl); - CALLOC(pl->idxs, capacity, sizeof(uint8_t *), + CLI_CALLOC_OR_GOTO_DONE(pl->idxs, capacity, sizeof(uint8_t *), cli_errmsg("initPointerList: Can't allocate memory\n"); ret = CL_EMEM); @@ -648,7 +648,7 @@ static cl_error_t insertPointer(PointerList *pl, const uint8_t *pointer) if (pl->cnt == (pl->capacity - 1)) { uint32_t newCapacity = pl->capacity + POINTER_LIST_INCREMENT; - CLI_SAFER_REALLOC(pl->idxs, newCapacity * sizeof(uint8_t *), + CLI_SAFER_REALLOC_OR_GOTO_DONE(pl->idxs, newCapacity * sizeof(uint8_t *), cli_errmsg("insertPointer: Can't allocate memory\n"); ret = CL_EMEM); diff --git a/libclamav/vba_extract.c b/libclamav/vba_extract.c index 4e00098e57..1af402d66e 100644 --- a/libclamav/vba_extract.c +++ b/libclamav/vba_extract.c @@ -2434,7 +2434,7 @@ create_vba_project(int record_count, const char *dir, struct uniq *U) ret->name = (char **)cli_max_malloc(sizeof(char *) * record_count); ret->colls = (uint32_t *)cli_max_malloc(sizeof(uint32_t) * record_count); - ret->dir = cli_strdup(dir); + ret->dir = cli_safer_strdup(dir); ret->offset = (uint32_t *)cli_max_malloc(sizeof(uint32_t) * record_count); if ((ret->colls == NULL) || (ret->name == NULL) || (ret->dir == NULL) || (ret->offset == NULL)) { diff --git a/libclamav/xlm_extract.c b/libclamav/xlm_extract.c index ac96cac1cd..6a09d22985 100644 --- a/libclamav/xlm_extract.c +++ b/libclamav/xlm_extract.c @@ -4790,7 +4790,7 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char } else { /* already found the beginning of a drawing group, extract the remaining chunks */ drawinggroup_len += biff_header.length; - CLI_MAX_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); + CLI_MAX_REALLOC_OR_GOTO_DONE(drawinggroup, drawinggroup_len, status = CL_EMEM); memcpy(drawinggroup + (drawinggroup_len - biff_header.length), data, biff_header.length); // cli_dbgmsg("Collected %d drawing group bytes\n", biff_header.length); } @@ -4801,7 +4801,7 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char (NULL != drawinggroup)) { /* already found the beginning of an image, extract the remaining chunks */ drawinggroup_len += biff_header.length; - CLI_MAX_REALLOC(drawinggroup, drawinggroup_len, status = CL_EMEM); + CLI_MAX_REALLOC_OR_GOTO_DONE(drawinggroup, drawinggroup_len, status = CL_EMEM); memcpy(drawinggroup + (drawinggroup_len - biff_header.length), data, biff_header.length); // cli_dbgmsg("Collected %d image bytes\n", biff_header.length); } @@ -4977,7 +4977,7 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char status = CL_SUCCESS; done: - FREE(drawinggroup); + CLI_FREE_AND_SET_NULL(drawinggroup); if (in_fd != -1) { close(in_fd); @@ -4992,12 +4992,12 @@ cl_error_t cli_extract_xlm_macros_and_images(const char *dir, cli_ctx *ctx, char out_fd = -1; } - FREE(data); + CLI_FREE_AND_SET_NULL(data); if (tempfile && !ctx->engine->keeptmp) { remove(tempfile); } - FREE(tempfile); + CLI_FREE_AND_SET_NULL(tempfile); return status; } diff --git a/libclamav/yara_clam.h b/libclamav/yara_clam.h index eaa0814c2b..3b67278915 100644 --- a/libclamav/yara_clam.h +++ b/libclamav/yara_clam.h @@ -452,7 +452,7 @@ struct RE { /* * YARA to ClamAV function mappings */ -#define yr_strdup cli_strdup +#define yr_strdup cli_safer_strdup #define yr_malloc cli_max_malloc #define yr_realloc cli_max_realloc #define yr_free free diff --git a/libclamav/yara_parser.c b/libclamav/yara_parser.c index a579cff390..cee6f082e7 100644 --- a/libclamav/yara_parser.c +++ b/libclamav/yara_parser.c @@ -882,7 +882,7 @@ YR_STRING* yr_parser_reduce_string_declaration( } if (identifier != NULL) { - meta->identifier = cli_strdup(identifier); + meta->identifier = cli_safer_strdup(identifier); if (meta->identifier == NULL) { cli_errmsg("yara_parser: no mem for meta->identifier.\n"); compiler->last_result = CL_EMEM; @@ -890,7 +890,7 @@ YR_STRING* yr_parser_reduce_string_declaration( } } if (string != NULL) { - meta->string = cli_strdup(string); + meta->string = cli_safer_strdup(string); if (meta->string == NULL) { cli_errmsg("yara_parser: no mem for meta->string.\n"); compiler->last_result = CL_EMEM; diff --git a/libfreshclam/libfreshclam.c b/libfreshclam/libfreshclam.c index 2b1a39c258..f12776f7a5 100644 --- a/libfreshclam/libfreshclam.c +++ b/libfreshclam/libfreshclam.c @@ -158,7 +158,7 @@ fc_error_t fc_initialize(fc_config *fcConfig) logg_size = fcConfig->maxLogSize; /* Set a log file if requested, and is not already set */ if ((NULL == logg_file) && (NULL != fcConfig->logFile)) { - logg_file = cli_strdup(fcConfig->logFile); + logg_file = cli_safer_strdup(fcConfig->logFile); if (0 != logg(LOGG_INFO_NF, "--------------------------------------\n")) { mprintf(LOGG_ERROR, "Problem with internal logger (UpdateLogFile = %s).\n", logg_file); status = FC_ELOGGING; @@ -188,14 +188,14 @@ fc_error_t fc_initialize(fc_config *fcConfig) mprintf(LOGG_ERROR, "Your installation was built with libcurl version %u.%u.%u.\n", LIBCURL_VERSION_MAJOR, LIBCURL_VERSION_MINOR, LIBCURL_VERSION_PATCH); mprintf(LOGG_ERROR, "LocalIP requires libcurl version 7.33.0 or higher and must include the c-ares optional dependency.\n"); #else - g_localIP = cli_strdup(fcConfig->localIP); + g_localIP = cli_safer_strdup(fcConfig->localIP); #endif } if (NULL != fcConfig->userAgent) { - g_userAgent = cli_strdup(fcConfig->userAgent); + g_userAgent = cli_safer_strdup(fcConfig->userAgent); } if (NULL != fcConfig->proxyServer) { - g_proxyServer = cli_strdup(fcConfig->proxyServer); + g_proxyServer = cli_safer_strdup(fcConfig->proxyServer); if (0 != fcConfig->proxyPort) { g_proxyPort = fcConfig->proxyPort; } else { @@ -215,10 +215,10 @@ fc_error_t fc_initialize(fc_config *fcConfig) } } if (NULL != fcConfig->proxyUsername) { - g_proxyUsername = cli_strdup(fcConfig->proxyUsername); + g_proxyUsername = cli_safer_strdup(fcConfig->proxyUsername); } if (NULL != fcConfig->proxyPassword) { - g_proxyPassword = cli_strdup(fcConfig->proxyPassword); + g_proxyPassword = cli_safer_strdup(fcConfig->proxyPassword); } #ifdef _WIN32 @@ -234,7 +234,7 @@ fc_error_t fc_initialize(fc_config *fcConfig) "%s" PATHSEP, fcConfig->databaseDirectory); } else { - g_databaseDirectory = cli_strdup(fcConfig->databaseDirectory); + g_databaseDirectory = cli_safer_strdup(fcConfig->databaseDirectory); } /* Validate that the database directory exists, and store it. */ @@ -249,7 +249,7 @@ fc_error_t fc_initialize(fc_config *fcConfig) goto done; } - g_tempDirectory = cli_strdup(fcConfig->tempDirectory); + g_tempDirectory = cli_safer_strdup(fcConfig->tempDirectory); g_maxAttempts = fcConfig->maxAttempts; g_connectTimeout = fcConfig->connectTimeout; @@ -573,7 +573,7 @@ fc_error_t fc_dns_query_update_info( logg(LOGG_WARNING, "Your ClamAV installation is OUTDATED!\n"); logg(LOGG_WARNING, "Local version: %s Recommended version: %s\n", version_string, reply_token); logg(LOGG_INFO, "DON'T PANIC! Read https://docs.clamav.net/manual/Installing.html\n"); - *newVersion = cli_strdup(reply_token); + *newVersion = cli_safer_strdup(reply_token); } } } diff --git a/libfreshclam/libfreshclam_internal.c b/libfreshclam/libfreshclam_internal.c index fe39222173..8ec1a111d4 100644 --- a/libfreshclam/libfreshclam_internal.c +++ b/libfreshclam/libfreshclam_internal.c @@ -1722,7 +1722,7 @@ static struct cl_cvd *currentdb(const char *database, char **localname) } if (localname) { - *localname = cli_strdup(filename); + *localname = cli_safer_strdup(filename); } done: @@ -2045,9 +2045,9 @@ static fc_error_t query_remote_database_version( } if (remote_is_cld) { - *remoteFilename = cli_strdup(cldfile); + *remoteFilename = cli_safer_strdup(cldfile); } else { - *remoteFilename = cli_strdup(cvdfile); + *remoteFilename = cli_safer_strdup(cvdfile); } *remoteVersion = newVersion; @@ -2174,7 +2174,7 @@ static fc_error_t check_for_new_database_version( *remoteVersion = remotever; if (NULL != remotename) { - *remoteFilename = cli_strdup(remotename); + *remoteFilename = cli_safer_strdup(remotename); if (NULL == *remoteFilename) { logg(LOGG_ERROR, "check_for_new_database_version: Failed to allocate memory for remote filename.\n"); status = FC_EMEM; @@ -2183,7 +2183,7 @@ static fc_error_t check_for_new_database_version( } if (NULL != localname) { *localVersion = localver; - *localFilename = cli_strdup(localname); + *localFilename = cli_safer_strdup(localname); if (NULL == *localFilename) { logg(LOGG_ERROR, "check_for_new_database_version: Failed to allocate memory for local filename.\n"); status = FC_EMEM; @@ -2268,7 +2268,7 @@ fc_error_t updatedb( } if ((localVersion >= remoteVersion) && (NULL != localFilename)) { - *dbFilename = cli_strdup(localFilename); + *dbFilename = cli_safer_strdup(localFilename); goto up_to_date; } @@ -2288,7 +2288,7 @@ fc_error_t updatedb( logg(LOGG_WARNING, "Expected newer version of %s database but the server's copy is not newer than our local file (version %d).\n", database, localVersion); if (NULL != localFilename) { /* Received a 304 (not modified), must be up-to-date after all */ - *dbFilename = cli_strdup(localFilename); + *dbFilename = cli_safer_strdup(localFilename); } goto up_to_date; } else if (FC_EMIRRORNOTSYNC == ret) { @@ -2302,7 +2302,7 @@ fc_error_t updatedb( goto done; } - newLocalFilename = cli_strdup(remoteFilename); + newLocalFilename = cli_safer_strdup(remoteFilename); } else { /* * Attempt scripted/CDIFF incremental update. @@ -2387,10 +2387,10 @@ fc_error_t updatedb( } } - newLocalFilename = cli_strdup(remoteFilename); + newLocalFilename = cli_safer_strdup(remoteFilename); } else if (0 == numPatchesReceived) { logg(LOGG_INFO, "The database server doesn't have the latest patch for the %s database (version %u). The server will likely have updated if you check again in a few hours.\n", database, remoteVersion); - *dbFilename = cli_strdup(localFilename); + *dbFilename = cli_safer_strdup(localFilename); goto up_to_date; } else { /* @@ -2488,7 +2488,7 @@ fc_error_t updatedb( *signo = cvd->sigs; *bUpdated = 1; - *dbFilename = cli_strdup(newLocalFilename); + *dbFilename = cli_safer_strdup(newLocalFilename); if (NULL == *dbFilename) { logg(LOGG_ERROR, "updatedb: Failed to allocate memory for database filename.\n"); status = FC_EMEM; @@ -2709,7 +2709,7 @@ fc_error_t updatecustomdb( up_to_date: - *dbFilename = cli_strdup(databaseName); + *dbFilename = cli_safer_strdup(databaseName); if (NULL == *dbFilename) { logg(LOGG_ERROR, "Failed to allocate memory for database filename.\n"); status = FC_EMEM; diff --git a/unit_tests/check_regex.c b/unit_tests/check_regex.c index 650ffa5384..56593dee72 100644 --- a/unit_tests/check_regex.c +++ b/unit_tests/check_regex.c @@ -273,8 +273,8 @@ START_TEST(regex_list_match_test) ck_assert_msg(rtest->result == RTR_PHISH || rtest->result == RTR_ALLOWED || rtest->result == RTR_INVALID_REGEX, "Allow list test result must be either RTR_PHISH or RTR_ALLOWED or RTR_INVALID_REGEX"); - pattern = cli_strdup(rtest->pattern); - ck_assert_msg(!!pattern, "cli_strdup"); + pattern = cli_safer_strdup(rtest->pattern); + ck_assert_msg(!!pattern, "cli_safer_strdup"); rc = regex_list_add_pattern(&matcher, pattern); if (rtest->result == RTR_INVALID_REGEX) { @@ -292,7 +292,7 @@ START_TEST(regex_list_match_test) ck_assert_msg(is_regex_ok(&matcher), "is_regex_ok"); - realurl = cli_strdup(rtest->realurl); + realurl = cli_safer_strdup(rtest->realurl); rc = regex_list_match(&matcher, realurl, rtest->displayurl, NULL, 1, &info, 1); ck_assert_msg(rc == rtest->result, "regex_list_match"); /* regex_list_match is not supposed to modify realurl in this case */ @@ -393,8 +393,8 @@ static void do_phishing_test(const struct rtest *rtest) memset(&options, 0, sizeof(struct cl_scan_options)); ctx.options = &options; - realurl = cli_strdup(rtest->realurl); - ck_assert_msg(!!realurl, "cli_strdup"); + realurl = cli_safer_strdup(rtest->realurl); + ck_assert_msg(!!realurl, "cli_safer_strdup"); hrefs.count = 1; hrefs.value = malloc(sizeof(*hrefs.value)); @@ -404,8 +404,8 @@ static void do_phishing_test(const struct rtest *rtest) ck_assert_msg(!!hrefs.contents, "malloc"); hrefs.tag = malloc(sizeof(*hrefs.tag)); ck_assert_msg(!!hrefs.tag, "malloc"); - hrefs.tag[0] = (unsigned char *)cli_strdup("href"); - hrefs.contents[0] = (unsigned char *)cli_strdup(rtest->displayurl); + hrefs.tag[0] = (unsigned char *)cli_safer_strdup("href"); + hrefs.contents[0] = (unsigned char *)cli_safer_strdup(rtest->displayurl); ctx.engine = engine; ctx.evidence = evidence_new(); @@ -480,8 +480,8 @@ static void do_phishing_test_allscan(const struct rtest *rtest) memset(&options, 0, sizeof(struct cl_scan_options)); ctx.options = &options; - realurl = cli_strdup(rtest->realurl); - ck_assert_msg(!!realurl, "cli_strdup"); + realurl = cli_safer_strdup(rtest->realurl); + ck_assert_msg(!!realurl, "cli_safer_strdup"); hrefs.count = 1; hrefs.value = malloc(sizeof(*hrefs.value)); @@ -491,8 +491,8 @@ static void do_phishing_test_allscan(const struct rtest *rtest) ck_assert_msg(!!hrefs.contents, "malloc"); hrefs.tag = malloc(sizeof(*hrefs.tag)); ck_assert_msg(!!hrefs.tag, "malloc"); - hrefs.tag[0] = (unsigned char *)cli_strdup("href"); - hrefs.contents[0] = (unsigned char *)cli_strdup(rtest->displayurl); + hrefs.tag[0] = (unsigned char *)cli_safer_strdup("href"); + hrefs.contents[0] = (unsigned char *)cli_safer_strdup(rtest->displayurl); ctx.engine = engine; ctx.evidence = evidence_new(); From 143040c0cb05d89d0090155ed4ba2c726c79ff56 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Tue, 9 Jan 2024 19:40:22 -0500 Subject: [PATCH 11/12] Fix GitHub code scan issues --- libclamav/bytecode_api.c | 2 +- libclamav/hashtab.c | 2 +- libclamav/nsis/bzlib.c | 2 +- libclamav/pe_icons.c | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libclamav/bytecode_api.c b/libclamav/bytecode_api.c index 9d136387a3..5a77fb0aa1 100644 --- a/libclamav/bytecode_api.c +++ b/libclamav/bytecode_api.c @@ -472,7 +472,7 @@ uint8_t *cli_bcapi_malloc(struct cli_bc_ctx *ctx, uint32_t size) } if (0 == size || size > CLI_MAX_ALLOCATION) { - cli_warnmsg("cli_bcapi_malloc(): File or section is too large to scan (%u bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", + cli_warnmsg("cli_bcapi_malloc(): File or section is too large to scan (" STDu32 " bytes). For your safety, ClamAV limits how much memory an operation can allocate to %d bytes\n", size, CLI_MAX_ALLOCATION); v = NULL; } else { diff --git a/libclamav/hashtab.c b/libclamav/hashtab.c index fdc2d6cbf6..75213217eb 100644 --- a/libclamav/hashtab.c +++ b/libclamav/hashtab.c @@ -889,7 +889,7 @@ cl_error_t cli_map_addkey(struct cli_map *m, const void *key, int32_t keysize) if (m->valuesize) { void *v; - v = cli_max_realloc(m->u.sized_values, n * m->valuesize); + v = cli_max_realloc(m->u.sized_values, (size_t)n * (size_t)m->valuesize); if (!v) { return CL_EMEM; } diff --git a/libclamav/nsis/bzlib.c b/libclamav/nsis/bzlib.c index 0e14088f3b..b67d97a83b 100644 --- a/libclamav/nsis/bzlib.c +++ b/libclamav/nsis/bzlib.c @@ -990,7 +990,7 @@ int bz_config_ok ( void ) static void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) { - void* v = cli_max_malloc ( items * size ); + void* v = cli_max_malloc ( (size_t)items * (size_t)size ); UNUSEDPARAM(opaque); return v; } diff --git a/libclamav/pe_icons.c b/libclamav/pe_icons.c index 5feb7b97cd..023b346a6b 100644 --- a/libclamav/pe_icons.c +++ b/libclamav/pe_icons.c @@ -901,7 +901,7 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr unsigned int edge_avg[6], edge_x[6] = {0, 0, 0, 0, 0, 0}, edge_y[6] = {0, 0, 0, 0, 0, 0}, noedge_avg[6], noedge_x[6] = {0, 0, 0, 0, 0, 0}, noedge_y[6] = {0, 0, 0, 0, 0, 0}; double *sobel; - if (!(tmp = cli_max_malloc(side * side * 4 * 2))) { + if (!(tmp = cli_max_malloc((size_t)side * (size_t)side * 4 * 2))) { cli_errmsg("getmetrics: Unable to allocate memory for tmp %u\n", (side * side * 4 * 2)); return CL_EMEM; } @@ -1067,7 +1067,7 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr /* Sobel 1 - gradients */ i = 0; #ifdef USE_FLOATS - sobel = cli_max_malloc(side * side * sizeof(double)); + sobel = cli_max_malloc((size_t)side * (size_t)side * sizeof(double)); if (!sobel) { cli_errmsg("getmetrics: Unable to allocate memory for edge detection %llu\n", (long long unsigned)(side * side * sizeof(double))); free(tmp); @@ -1457,7 +1457,7 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) fmap_unneed_ptr(map, palette, (1 << depth) * sizeof(int)); return CL_SUCCESS; } - if (!(imagedata = cli_max_malloc(width * height * sizeof(*imagedata)))) { + if (!(imagedata = cli_max_malloc((size_t)width * (size_t)height * sizeof(*imagedata)))) { if (palette) fmap_unneed_ptr(map, palette, (1 << depth) * sizeof(int)); return CL_SUCCESS; From b3c9a5605bce152779798444a9319c03aebe687b Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Tue, 9 Jan 2024 19:41:17 -0500 Subject: [PATCH 12/12] Clang-format touchup --- clamdscan/proto.c | 2 +- libclamav/apm.c | 2 +- libclamav/bytecode_api.h | 4 +- libclamav/bytecode_vm.c | 32 ++++++------- libclamav/c++/bytecode2llvm.cpp | 2 +- libclamav/crtmgr.c | 2 +- libclamav/egg.c | 76 ++++++++++++++--------------- libclamav/entconv.c | 2 +- libclamav/gpt.c | 4 +- libclamav/htmlnorm.c | 6 +-- libclamav/ishield.c | 2 +- libclamav/jpeg.c | 2 +- libclamav/jsparse/js-norm.c | 2 +- libclamav/mbox.c | 4 +- libclamav/mbr.c | 4 +- libclamav/ole2_extract.c | 14 +++--- libclamav/others.h | 24 +++++----- libclamav/pdf.c | 7 +-- libclamav/pdfng.c | 2 +- libclamav/pe_icons.c | 2 +- libclamav/readdb.c | 2 +- libclamav/regex_list.c | 22 ++++----- libclamav/regex_suffix.c | 8 ++-- libclamav/sf_base64decode.h | 2 +- libclamav/udf.c | 8 ++-- libclamav/udf.h | 24 +++++----- libclamav/vba_extract.c | 84 ++++++++++++++++----------------- win32/compat/dirent.c | 6 +-- win32/compat/strptime.c | 4 +- 29 files changed, 178 insertions(+), 177 deletions(-) diff --git a/clamdscan/proto.c b/clamdscan/proto.c index c3965d2eea..2d6e966a5e 100644 --- a/clamdscan/proto.c +++ b/clamdscan/proto.c @@ -212,7 +212,7 @@ struct client_parallel_data { unsigned int id; const char *file; struct SCANID *next; - } * ids; + } *ids; }; /* Sends a proper scan request to clamd and parses its replies diff --git a/libclamav/apm.c b/libclamav/apm.c index b33c057998..3cc79b08c5 100644 --- a/libclamav/apm.c +++ b/libclamav/apm.c @@ -37,7 +37,7 @@ #include "scanners.h" #include "dconf.h" -//#define DEBUG_APM_PARSE +// #define DEBUG_APM_PARSE #ifdef DEBUG_APM_PARSE #define apm_parsemsg(...) cli_dbgmsg(__VA_ARGS__) diff --git a/libclamav/bytecode_api.h b/libclamav/bytecode_api.h index 51f3e360be..6d9ba85db1 100644 --- a/libclamav/bytecode_api.h +++ b/libclamav/bytecode_api.h @@ -172,12 +172,12 @@ enum FunctionalityLevels { FUNC_LEVEL_1_0_4 = 164, /**< LibClamAV release 1.0.4 */ FUNC_LEVEL_1_0_5 = 165, /**< LibClamAV release 1.0.5 */ - FUNC_LEVEL_1_1 = 180, /**< LibClamAV release 1.1.0 */ + FUNC_LEVEL_1_1 = 180, /**< LibClamAV release 1.1.0 */ FUNC_LEVEL_1_1_1 = 181, /**< LibClamAV release 1.1.1 */ FUNC_LEVEL_1_1_2 = 182, /**< LibClamAV release 1.1.2 */ FUNC_LEVEL_1_1_3 = 183, /**< LibClamAV release 1.1.3 */ - FUNC_LEVEL_1_2 = 190, /**< LibClamAV release 1.2.0 */ + FUNC_LEVEL_1_2 = 190, /**< LibClamAV release 1.2.0 */ FUNC_LEVEL_1_2_1 = 191, /**< LibClamAV release 1.2.1 */ FUNC_LEVEL_1_2_2 = 192, /**< LibClamAV release 1.2.2 */ diff --git a/libclamav/bytecode_vm.c b/libclamav/bytecode_vm.c index ac0d784896..6c4d46c236 100644 --- a/libclamav/bytecode_vm.c +++ b/libclamav/bytecode_vm.c @@ -286,17 +286,17 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, *(uint8_t *)&values[p] = x #define WRITE16(p, x) \ CHECK_GT(func->numBytes, p + 1); \ - CHECK_EQ((p) & 1, 0); \ + CHECK_EQ((p)&1, 0); \ TRACE_W(x, p, 16); \ *(uint16_t *)&values[p] = x #define WRITE32(p, x) \ CHECK_GT(func->numBytes, p + 3); \ - CHECK_EQ((p) & 3, 0); \ + CHECK_EQ((p)&3, 0); \ TRACE_W(x, p, 32); \ *(uint32_t *)&values[p] = x #define WRITE64(p, x) \ CHECK_GT(func->numBytes, p + 7); \ - CHECK_EQ((p) & 7, 0); \ + CHECK_EQ((p)&7, 0); \ TRACE_W(x, p, 64); \ *(uint64_t *)&values[p] = x #define WRITEP(x, p) \ @@ -346,16 +346,16 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, } \ TRACE_R(x) \ } -#define READPOP(x, p, asize) \ - { \ - if ((p) & 0x40000000) { \ - unsigned ptr__ = (p) & 0xbfffffff; \ - CHECK_GT(func->numBytes, ptr__); \ - TRACE_PTR(ptr__, asize); \ - x = (void *)&values[ptr__]; \ - } else { \ - READP(x, p, asize) \ - } \ +#define READPOP(x, p, asize) \ + { \ + if ((p)&0x40000000) { \ + unsigned ptr__ = (p)&0xbfffffff; \ + CHECK_GT(func->numBytes, ptr__); \ + TRACE_PTR(ptr__, asize); \ + x = (void *)&values[ptr__]; \ + } else { \ + READP(x, p, asize) \ + } \ } #define READOLD8(x, p) \ @@ -364,17 +364,17 @@ static always_inline struct stack_entry *pop_stack(struct stack *stack, TRACE_R(x) #define READOLD16(x, p) \ CHECK_GT(func->numBytes, p + 1); \ - CHECK_EQ((p) & 1, 0); \ + CHECK_EQ((p)&1, 0); \ x = *(uint16_t *)&old_values[p]; \ TRACE_R(x) #define READOLD32(x, p) \ CHECK_GT(func->numBytes, p + 3); \ - CHECK_EQ((p) & 3, 0); \ + CHECK_EQ((p)&3, 0); \ x = *(uint32_t *)&old_values[p]; \ TRACE_R(x) #define READOLD64(x, p) \ CHECK_GT(func->numBytes, p + 7); \ - CHECK_EQ((p) & 7, 0); \ + CHECK_EQ((p)&7, 0); \ x = *(uint64_t *)&old_values[p]; \ TRACE_R(x) diff --git a/libclamav/c++/bytecode2llvm.cpp b/libclamav/c++/bytecode2llvm.cpp index 462c02e50f..0f43146984 100644 --- a/libclamav/c++/bytecode2llvm.cpp +++ b/libclamav/c++/bytecode2llvm.cpp @@ -106,7 +106,7 @@ void LLVMInitializePowerPCAsmPrinter(); #include "llvm/IR/Dominators.h" -//#define TIMING +// #define TIMING #undef TIMING #include "llvm/Config/llvm-config.h" diff --git a/libclamav/crtmgr.c b/libclamav/crtmgr.c index cc3fc84a92..62002ae982 100644 --- a/libclamav/crtmgr.c +++ b/libclamav/crtmgr.c @@ -398,7 +398,7 @@ static cl_error_t crtmgr_get_recov_data(BIGNUM *sig, cli_crt *x509, int pad_size; int keylen; uint8_t *d = NULL; - BIGNUM *x = NULL; + BIGNUM *x = NULL; cl_error_t ret; *buffer = NULL; diff --git a/libclamav/egg.c b/libclamav/egg.c index 7c076f3d5d..2d74ff4d30 100644 --- a/libclamav/egg.c +++ b/libclamav/egg.c @@ -1222,9 +1222,9 @@ static cl_error_t egg_parse_file_extra_field(egg_handle* handle, egg_file* eggFi * Comment found. Add comment to our list. */ CLI_SAFER_REALLOC_OR_GOTO_DONE(eggFile->comments, - sizeof(char*) * (eggFile->nComments + 1), - free(comment), - status = CL_EMEM); + sizeof(char*) * (eggFile->nComments + 1), + free(comment), + status = CL_EMEM); eggFile->comments[eggFile->nComments] = comment; eggFile->nComments++; } @@ -1668,9 +1668,9 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t } else { /* Add file to list. */ CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->files, - sizeof(egg_file*) * (handle->nFiles + 1), - egg_free_egg_file(found_file), - status = CL_EMEM); + sizeof(egg_file*) * (handle->nFiles + 1), + egg_free_egg_file(found_file), + status = CL_EMEM); handle->files[handle->nFiles] = found_file; handle->nFiles++; } @@ -1690,9 +1690,9 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t /* Add block to list. */ if (handle->bSolid) { CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->blocks, - sizeof(egg_block*) * (handle->nBlocks + 1), - egg_free_egg_block(found_block), - status = CL_EMEM); + sizeof(egg_block*) * (handle->nBlocks + 1), + egg_free_egg_block(found_block), + status = CL_EMEM); handle->blocks[handle->nBlocks] = found_block; handle->nBlocks++; } else { @@ -1708,9 +1708,9 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t eggFile = handle->files[handle->nFiles - 1]; CLI_SAFER_REALLOC_OR_GOTO_DONE(eggFile->blocks, - sizeof(egg_block*) * (eggFile->nBlocks + 1), - egg_free_egg_block(found_block), - status = CL_EMEM); + sizeof(egg_block*) * (eggFile->nBlocks + 1), + egg_free_egg_block(found_block), + status = CL_EMEM); eggFile->blocks[eggFile->nBlocks] = found_block; eggFile->nBlocks++; } @@ -1786,9 +1786,9 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t * Comment found. Add comment to our list. */ CLI_SAFER_REALLOC_OR_GOTO_DONE(handle->comments, - sizeof(char*) * (handle->nComments + 1), - free(comment), - status = CL_EMEM); + sizeof(char*) * (handle->nComments + 1), + free(comment), + status = CL_EMEM); handle->comments[handle->nComments] = comment; handle->nComments++; } @@ -1973,9 +1973,9 @@ cl_error_t cli_egg_deflate_decompress(char* compressed, size_t compressed_size, /* extend output capacity if needed,*/ if (stream.avail_out == 0) { CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_deflate_decompress: cannot reallocate memory for decompressed output\n"), - status = CL_EMEM); + capacity + BUFSIZ, + cli_errmsg("cli_egg_deflate_decompress: cannot reallocate memory for decompressed output\n"), + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2095,9 +2095,9 @@ cl_error_t cli_egg_bzip2_decompress(char* compressed, size_t compressed_size, ch /* extend output capacity if needed,*/ if (stream.avail_out == 0) { CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_bzip2_decompress: cannot reallocate memory for decompressed output\n"); - status = CL_EMEM); + capacity + BUFSIZ, + cli_errmsg("cli_egg_bzip2_decompress: cannot reallocate memory for decompressed output\n"); + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2212,9 +2212,9 @@ cl_error_t cli_egg_lzma_decompress(char* compressed, size_t compressed_size, cha /* extend output capacity if needed,*/ if (stream.avail_out == 0) { CLI_SAFER_REALLOC_OR_GOTO_DONE(decoded, - capacity + BUFSIZ, - cli_errmsg("cli_egg_lzma_decompress: cannot reallocate memory for decompressed output\n"); - status = CL_EMEM); + capacity + BUFSIZ, + cli_errmsg("cli_egg_lzma_decompress: cannot reallocate memory for decompressed output\n"); + status = CL_EMEM); stream.next_out = decoded + capacity; stream.avail_out = BUFSIZ; declen += BUFSIZ; @@ -2362,10 +2362,10 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha } CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, - (size_t)decompressed_size + currBlock->blockHeader->compress_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - status = CL_EMEM); + (size_t)decompressed_size + currBlock->blockHeader->compress_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + status = CL_EMEM); memcpy(decompressed + decompressed_size, currBlock->compressedData, currBlock->blockHeader->compress_size); decompressed_size += currBlock->blockHeader->compress_size; @@ -2387,11 +2387,11 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha } /* Decompressed block. Add it to the file data */ CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, - (size_t)decompressed_size + decompressed_block_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - free(decompressed_block), - status = CL_EMEM); + (size_t)decompressed_size + decompressed_block_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + free(decompressed_block), + status = CL_EMEM); memcpy(decompressed + decompressed_size, decompressed_block, decompressed_block_size); decompressed_size += decompressed_block_size; @@ -2416,11 +2416,11 @@ cl_error_t cli_egg_extract_file(void* hArchive, const char** filename, const cha } /* Decompressed block. Add it to the file data */ CLI_SAFER_REALLOC_OR_GOTO_DONE(decompressed, - (size_t)decompressed_size + decompressed_block_size, - cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", - decompressed_size), - free(decompressed_block), - status = CL_EMEM); + (size_t)decompressed_size + decompressed_block_size, + cli_errmsg("cli_egg_extract_file: Failed to allocate %" PRIu64 " bytes for decompressed file!\n", + decompressed_size), + free(decompressed_block), + status = CL_EMEM); memcpy(decompressed + decompressed_size, decompressed_block, decompressed_block_size); decompressed_size += decompressed_block_size; diff --git a/libclamav/entconv.c b/libclamav/entconv.c index bb58215fa4..200f4eb9fc 100644 --- a/libclamav/entconv.c +++ b/libclamav/entconv.c @@ -57,7 +57,7 @@ typedef struct { enum encodings encoding; size_t size; -} * iconv_t; +}* iconv_t; #endif static unsigned char tohex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; diff --git a/libclamav/gpt.c b/libclamav/gpt.c index 3ed7a54de8..c92cf6bc97 100644 --- a/libclamav/gpt.c +++ b/libclamav/gpt.c @@ -41,8 +41,8 @@ #include "scanners.h" #include "dconf.h" -//#define DEBUG_GPT_PARSE -//#define DEBUG_GPT_PRINT +// #define DEBUG_GPT_PARSE +// #define DEBUG_GPT_PRINT #ifdef DEBUG_GPT_PARSE #define gpt_parsemsg(...) cli_dbgmsg(__VA_ARGS__) diff --git a/libclamav/htmlnorm.c b/libclamav/htmlnorm.c index f197f36da0..7064a32346 100644 --- a/libclamav/htmlnorm.c +++ b/libclamav/htmlnorm.c @@ -372,18 +372,18 @@ void html_tag_arg_add(tag_arguments_t *tags, int len, i; tags->count++; tags->tag = (unsigned char **)cli_max_realloc_or_free(tags->tag, - tags->count * sizeof(char *)); + tags->count * sizeof(char *)); if (!tags->tag) { goto done; } tags->value = (unsigned char **)cli_max_realloc_or_free(tags->value, - tags->count * sizeof(char *)); + tags->count * sizeof(char *)); if (!tags->value) { goto done; } if (tags->scanContents) { tags->contents = (unsigned char **)cli_max_realloc_or_free(tags->contents, - tags->count * sizeof(*tags->contents)); + tags->count * sizeof(*tags->contents)); if (!tags->contents) { goto done; } diff --git a/libclamav/ishield.c b/libclamav/ishield.c index 171ac773ab..3ea28e3d5e 100644 --- a/libclamav/ishield.c +++ b/libclamav/ishield.c @@ -358,7 +358,7 @@ struct IS_CABSTUFF { unsigned int cabno; off_t off; size_t sz; - } * cabs; + } *cabs; off_t hdr; size_t hdrsz; unsigned int cabcnt; diff --git a/libclamav/jpeg.c b/libclamav/jpeg.c index 3bf5ec6afc..34ac79b8b8 100644 --- a/libclamav/jpeg.c +++ b/libclamav/jpeg.c @@ -313,7 +313,7 @@ cl_error_t cli_parsejpeg(cli_ctx *ctx) { cl_error_t status = CL_SUCCESS; - fmap_t *map = NULL; + fmap_t *map = NULL; jpeg_marker_t marker = JPEG_MARKER_NOT_A_MARKER_0x00, prev_marker, prev_segment = JPEG_MARKER_NOT_A_MARKER_0x00; uint8_t buff[50]; /* 50 should be sufficient for now */ uint16_t len_u16; diff --git a/libclamav/jsparse/js-norm.c b/libclamav/jsparse/js-norm.c index bdbd15df7b..2a6d8354d3 100644 --- a/libclamav/jsparse/js-norm.c +++ b/libclamav/jsparse/js-norm.c @@ -67,7 +67,7 @@ typedef struct scanner { size_t lastpos; enum tokenizer_state state; enum tokenizer_state last_state; -} * yyscan_t; +} *yyscan_t; static int yylex(YYSTYPE *lvalp, yyscan_t); static void yy_scan_bytes(const char *, size_t, yyscan_t scanner); diff --git a/libclamav/mbox.c b/libclamav/mbox.c index 530bb84cd7..9bc6fe0456 100644 --- a/libclamav/mbox.c +++ b/libclamav/mbox.c @@ -162,7 +162,7 @@ typedef enum { * Slows things down a lot and only catches unencoded copies * of EICAR within bounces, which don't matter */ -//#define SCAN_UNENCODED_BOUNCES +// #define SCAN_UNENCODED_BOUNCES typedef struct mbox_ctx { const char *dir; @@ -265,7 +265,7 @@ static bool haveTooManyMIMEArguments(size_t argCnt, cli_ctx *ctx, bool *heuristi * protocol="application/pgp-encrypted" \ */ #define X_BFILE RELATED /* \ - * BeOS, expert two parts: the file and its \ + * BeOS, expert two parts: the file and its \ * attributes. The attributes part comes as \ * Content-Type: application/x-be_attribute \ * name="foo" \ diff --git a/libclamav/mbr.c b/libclamav/mbr.c index 1d0e95532b..f99d375580 100644 --- a/libclamav/mbr.c +++ b/libclamav/mbr.c @@ -38,8 +38,8 @@ #include "scanners.h" #include "dconf.h" -//#define DEBUG_MBR_PARSE -//#define DEBUG_EBR_PARSE +// #define DEBUG_MBR_PARSE +// #define DEBUG_EBR_PARSE #ifdef DEBUG_MBR_PARSE #define mbr_parsemsg(...) cli_dbgmsg(__VA_ARGS__) diff --git a/libclamav/ole2_extract.c b/libclamav/ole2_extract.c index dd13c1733c..38af43a541 100644 --- a/libclamav/ole2_extract.c +++ b/libclamav/ole2_extract.c @@ -197,7 +197,7 @@ int ole2_list_push(ole2_list_t *list, uint32_t val) int status = CL_EMEM; CLI_MALLOC_OR_GOTO_DONE(new_node, sizeof(ole2_list_node_t), - cli_dbgmsg("OLE2: could not allocate new node for worklist!\n")); + cli_dbgmsg("OLE2: could not allocate new node for worklist!\n")); new_node->Val = val; new_node->Next = list->Head; @@ -257,7 +257,7 @@ cli_ole2_get_property_name2(const char *name, int size) return NULL; } CLI_MAX_MALLOC_OR_GOTO_DONE(newname, size * 7, - cli_errmsg("OLE2 [cli_ole2_get_property_name2]: Unable to allocate memory for newname: %u\n", size * 7)); + cli_errmsg("OLE2 [cli_ole2_get_property_name2]: Unable to allocate memory for newname: %u\n", size * 7)); j = 0; /* size-2 to ignore trailing NULL */ @@ -305,7 +305,7 @@ get_property_name(char *name, int size) } CLI_MAX_MALLOC_OR_GOTO_DONE(newname, size, - cli_errmsg("OLE2 [get_property_name]: Unable to allocate memory for newname %u\n", size)); + cli_errmsg("OLE2 [get_property_name]: Unable to allocate memory for newname %u\n", size)); cname = newname; while (--csize) { @@ -889,8 +889,8 @@ static cl_error_t handler_writefile(ole2_header_t *hdr, property_t *prop, const len = prop->size; CLI_MAX_MALLOC_OR_GOTO_DONE(buff, 1 << hdr->log2_big_block_size, - cli_errmsg("OLE2 [handler_writefile]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); - ret = CL_EMEM); + cli_errmsg("OLE2 [handler_writefile]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); + ret = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { @@ -1158,8 +1158,8 @@ static cl_error_t scan_for_xlm_macros_and_images(ole2_header_t *hdr, property_t len = prop->size; CLI_MAX_MALLOC_OR_GOTO_DONE(buff, 1 << hdr->log2_big_block_size, - cli_errmsg("OLE2 [scan_for_xlm_macros_and_images]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); - status = CL_EMEM); + cli_errmsg("OLE2 [scan_for_xlm_macros_and_images]: Unable to allocate memory for buff: %u\n", 1 << hdr->log2_big_block_size); + status = CL_EMEM); blk_bitset = cli_bitset_init(); if (!blk_bitset) { diff --git a/libclamav/others.h b/libclamav/others.h index 6c44edb6f2..4c12d6ea30 100644 --- a/libclamav/others.h +++ b/libclamav/others.h @@ -593,16 +593,16 @@ extern LIBCLAMAV_EXPORT int have_rar; /* based on macros from A. Melnikoff */ #define cbswap16(v) (((v & 0xff) << 8) | (((v) >> 8) & 0xff)) -#define cbswap32(v) ((((v) & 0x000000ff) << 24) | (((v) & 0x0000ff00) << 8) | \ - (((v) & 0x00ff0000) >> 8) | (((v) & 0xff000000) >> 24)) -#define cbswap64(v) ((((v) & 0x00000000000000ffULL) << 56) | \ - (((v) & 0x000000000000ff00ULL) << 40) | \ - (((v) & 0x0000000000ff0000ULL) << 24) | \ - (((v) & 0x00000000ff000000ULL) << 8) | \ - (((v) & 0x000000ff00000000ULL) >> 8) | \ - (((v) & 0x0000ff0000000000ULL) >> 24) | \ - (((v) & 0x00ff000000000000ULL) >> 40) | \ - (((v) & 0xff00000000000000ULL) >> 56)) +#define cbswap32(v) ((((v)&0x000000ff) << 24) | (((v)&0x0000ff00) << 8) | \ + (((v)&0x00ff0000) >> 8) | (((v)&0xff000000) >> 24)) +#define cbswap64(v) ((((v)&0x00000000000000ffULL) << 56) | \ + (((v)&0x000000000000ff00ULL) << 40) | \ + (((v)&0x0000000000ff0000ULL) << 24) | \ + (((v)&0x00000000ff000000ULL) << 8) | \ + (((v)&0x000000ff00000000ULL) >> 8) | \ + (((v)&0x0000ff0000000000ULL) >> 24) | \ + (((v)&0x00ff000000000000ULL) >> 40) | \ + (((v)&0xff00000000000000ULL) >> 56)) #ifndef HAVE_ATTRIB_PACKED #define __attribute__(x) @@ -828,8 +828,8 @@ size_t cli_recursion_stack_get_size(cli_ctx *ctx, int index); /* used by: spin, yc (C) aCaB */ #define __SHIFTBITS(a) (sizeof(a) << 3) #define __SHIFTMASK(a) (__SHIFTBITS(a) - 1) -#define CLI_ROL(a, b) a = (a << ((b) & __SHIFTMASK(a))) | (a >> ((__SHIFTBITS(a) - (b)) & __SHIFTMASK(a))) -#define CLI_ROR(a, b) a = (a >> ((b) & __SHIFTMASK(a))) | (a << ((__SHIFTBITS(a) - (b)) & __SHIFTMASK(a))) +#define CLI_ROL(a, b) a = (a << ((b)&__SHIFTMASK(a))) | (a >> ((__SHIFTBITS(a) - (b)) & __SHIFTMASK(a))) +#define CLI_ROR(a, b) a = (a >> ((b)&__SHIFTMASK(a))) | (a << ((__SHIFTBITS(a) - (b)) & __SHIFTMASK(a))) /* Implementation independent sign-extended signed right shift */ #ifdef HAVE_SAR diff --git a/libclamav/pdf.c b/libclamav/pdf.c index a364aad56e..7f1e506e4f 100644 --- a/libclamav/pdf.c +++ b/libclamav/pdf.c @@ -481,8 +481,8 @@ int pdf_findobj_in_objstm(struct pdf_struct *pdf, struct objstm_struct *objstm, /* Success! Add the object to the list of all objects found. */ pdf->nobjs++; CLI_MAX_REALLOC_OR_GOTO_DONE(pdf->objs, sizeof(struct pdf_obj *) * pdf->nobjs, - cli_warnmsg("pdf_findobj_in_objstm: out of memory finding objects in stream\n"), - status = CL_EMEM); + cli_warnmsg("pdf_findobj_in_objstm: out of memory finding objects in stream\n"), + status = CL_EMEM); pdf->objs[pdf->nobjs - 1] = obj; *obj_found = obj; @@ -3032,7 +3032,8 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, case 3: case 4: { unsigned char *d; - size_t sz = 68 + pdf->fileIDlen + (R >= 4 && !EM ? 4 : 0); d = calloc(1, sz); + size_t sz = 68 + pdf->fileIDlen + (R >= 4 && !EM ? 4 : 0); + d = calloc(1, sz); if (!(d)) goto done; diff --git a/libclamav/pdfng.c b/libclamav/pdfng.c index 8aae0b1ce3..575cece831 100644 --- a/libclamav/pdfng.c +++ b/libclamav/pdfng.c @@ -268,7 +268,7 @@ static char *pdf_decrypt_string(struct pdf_struct *pdf, struct pdf_obj *obj, con bin_length = *length / 2; // Convert the hex string to binary - CLI_MAX_CALLOC(decoded_bin, 1, bin_length); + CLI_MAX_CALLOC_OR_GOTO_DONE(decoded_bin, 1, bin_length); hex2str_ret = cli_hex2str_to(hex, decoded_bin, *length); if (hex2str_ret != 0) { diff --git a/libclamav/pe_icons.c b/libclamav/pe_icons.c index 023b346a6b..0269f7759a 100644 --- a/libclamav/pe_icons.c +++ b/libclamav/pe_icons.c @@ -188,7 +188,7 @@ int cli_groupiconscan(struct ICON_ENV *icon_env, uint32_t rva) uint16_t depth; uint32_t sz; uint16_t id; - } * dir; + } *dir; raddr = cli_rawaddr(cli_readint32(grp), peinfo->sections, peinfo->nsections, (unsigned int *)(&err), map->len, peinfo->hdr_size); cli_dbgmsg("cli_scanicon: icon group @%x\n", raddr); diff --git a/libclamav/readdb.c b/libclamav/readdb.c index 4dbe539efe..29c4782a3b 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -2402,7 +2402,7 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, unsigned hook = bc->kind - _BC_START_HOOKS; unsigned cnt = ++engine->hooks_cnt[hook]; engine->hooks[hook] = cli_safer_realloc_or_free(engine->hooks[hook], - sizeof(*engine->hooks[0]) * cnt); + sizeof(*engine->hooks[0]) * cnt); if (!engine->hooks[hook]) { cli_errmsg("Out of memory allocating memory for hook %u", hook); return CL_EMEM; diff --git a/libclamav/regex_list.c b/libclamav/regex_list.c index 3fda1abc59..588c5d478a 100644 --- a/libclamav/regex_list.c +++ b/libclamav/regex_list.c @@ -235,8 +235,8 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const free(buffer); free(bufrev); /* filter says this suffix doesn't match. - * The filter has false positives, but no false - * negatives */ + * The filter has false positives, but no false + * negatives */ return CL_SUCCESS; } @@ -775,15 +775,15 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su } CLI_MALLOC_OR_GOTO_DONE(regex, sizeof(*regex), - cli_errmsg("add_pattern_suffix: Unable to allocate memory for regex\n"); - ret = CL_EMEM); + cli_errmsg("add_pattern_suffix: Unable to allocate memory for regex\n"); + ret = CL_EMEM); if (NULL == iregex->pattern) { regex->pattern = NULL; } else { CLI_SAFER_STRDUP_OR_GOTO_DONE(iregex->pattern, regex->pattern, - cli_errmsg("add_pattern_suffix: unable to strdup iregex->pattern"); - ret = CL_EMEM); + cli_errmsg("add_pattern_suffix: unable to strdup iregex->pattern"); + ret = CL_EMEM); } regex->preg = iregex->preg; regex->nxt = NULL; @@ -803,9 +803,9 @@ static cl_error_t add_pattern_suffix(void *cbdata, const char *suffix, size_t su size_t n = matcher->suffix_cnt; el = cli_hashtab_insert(&matcher->suffix_hash, suffix, suffix_len, (cli_element_data)n); CLI_MAX_REALLOC_OR_GOTO_DONE(matcher->suffix_regexes, - (n + 1) * sizeof(*matcher->suffix_regexes), - cli_errmsg("add_pattern_suffix: Unable to reallocate memory for matcher->suffix_regexes\n"); - ret = CL_EMEM); + (n + 1) * sizeof(*matcher->suffix_regexes), + cli_errmsg("add_pattern_suffix: Unable to reallocate memory for matcher->suffix_regexes\n"); + ret = CL_EMEM); matcher->suffix_regexes[n].tail = regex; matcher->suffix_regexes[n].head = regex; if (suffix[0] == '/' && suffix[1] == '\0') { @@ -870,8 +870,8 @@ static cl_error_t add_static_pattern(struct regex_matcher *matcher, char *patter len = reverse_string(pattern); regex.nxt = NULL; CLI_SAFER_STRDUP_OR_GOTO_DONE(pattern, regex.pattern, - cli_errmsg("add_static_pattern: Cannot allocate memory for regex.pattern\n"); - rc = CL_EMEM); + cli_errmsg("add_static_pattern: Cannot allocate memory for regex.pattern\n"); + rc = CL_EMEM); regex.preg = NULL; rc = add_pattern_suffix(matcher, pattern, len, ®ex); done: diff --git a/libclamav/regex_suffix.c b/libclamav/regex_suffix.c index 0dffaa268a..8deb7eaec7 100644 --- a/libclamav/regex_suffix.c +++ b/libclamav/regex_suffix.c @@ -193,7 +193,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos do { \ if (((*posPtr) + incVal) >= posMax) { \ cli_warnmsg("parse_char_class: Invalid char class\n"); \ - CLI_FREE_AND_SET_NULL(bitmap); \ + CLI_FREE_AND_SET_NULL(bitmap); \ goto done; \ } \ (*posPtr)++; \ @@ -208,7 +208,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos uint8_t *bitmap = NULL; CLI_MALLOC_OR_GOTO_DONE(bitmap, 32, - cli_errmsg("parse_char_class: Unable to allocate memory for bitmap\n")); + cli_errmsg("parse_char_class: Unable to allocate memory for bitmap\n")); if (pat[*pos] == '^') { memset(bitmap, 0xFF, 32); /*match chars not in brackets*/ @@ -502,8 +502,8 @@ cl_error_t cli_regex2suffix(const char *pattern, regex_t *preg, suffix_callback } regex.nxt = NULL; CLI_SAFER_STRDUP_OR_GOTO_DONE(pattern, regex.pattern, - cli_errmsg("cli_regex2suffix: unable to strdup regex.pattern\n"); - rc = REG_ESPACE); + cli_errmsg("cli_regex2suffix: unable to strdup regex.pattern\n"); + rc = REG_ESPACE); n = parse_regex((const uint8_t *)pattern, strlen(pattern), &last); if (!n) { diff --git a/libclamav/sf_base64decode.h b/libclamav/sf_base64decode.h index 5ba333097a..9ea5a17448 100644 --- a/libclamav/sf_base64decode.h +++ b/libclamav/sf_base64decode.h @@ -27,6 +27,6 @@ #include #include "clamav-types.h" -int sf_base64decode(uint8_t*, size_t, uint8_t*, size_t, size_t*); +int sf_base64decode(uint8_t *, size_t, uint8_t *, size_t, size_t *); #endif diff --git a/libclamav/udf.c b/libclamav/udf.c index 895bb8d515..14a1c0a88b 100644 --- a/libclamav/udf.c +++ b/libclamav/udf.c @@ -634,8 +634,8 @@ static cl_error_t initPointerList(PointerList *pl) freePointerList(pl); CLI_CALLOC_OR_GOTO_DONE(pl->idxs, capacity, sizeof(uint8_t *), - cli_errmsg("initPointerList: Can't allocate memory\n"); - ret = CL_EMEM); + cli_errmsg("initPointerList: Can't allocate memory\n"); + ret = CL_EMEM); pl->capacity = capacity; done: @@ -649,8 +649,8 @@ static cl_error_t insertPointer(PointerList *pl, const uint8_t *pointer) if (pl->cnt == (pl->capacity - 1)) { uint32_t newCapacity = pl->capacity + POINTER_LIST_INCREMENT; CLI_SAFER_REALLOC_OR_GOTO_DONE(pl->idxs, newCapacity * sizeof(uint8_t *), - cli_errmsg("insertPointer: Can't allocate memory\n"); - ret = CL_EMEM); + cli_errmsg("insertPointer: Can't allocate memory\n"); + ret = CL_EMEM); pl->capacity = newCapacity; } diff --git a/libclamav/udf.h b/libclamav/udf.h index bc94c4aecf..471dae0c2a 100644 --- a/libclamav/udf.h +++ b/libclamav/udf.h @@ -66,7 +66,7 @@ typedef struct __attribute__((packed)) { } lb_addr; typedef struct __attribute__((packed)) { - uint32_t length; //4/14.14.1.1 + uint32_t length; // 4/14.14.1.1 /*30 least significant bits are length in bytes. * * 2 most significant bits are described in figure 4/42 @@ -77,7 +77,7 @@ typedef struct __attribute__((packed)) { * 3 the extent is the next extent of allocation descriptors. * */ - lb_addr extentLocation; //logical block number. (CAN be zero) + lb_addr extentLocation; // logical block number. (CAN be zero) uint8_t implementationUse[6]; @@ -155,8 +155,8 @@ typedef struct __attribute__((packed)) { uint16_t partitionReferenceNumber; } LBAddr; -//https://www.ecma-international.org/wp-content/uploads/ECMA-167_3rd_edition_june_1997.pdf -//section 4/23 +// https://www.ecma-international.org/wp-content/uploads/ECMA-167_3rd_edition_june_1997.pdf +// section 4/23 typedef struct __attribute__((packed)) { uint32_t priorRecordedNumberOfDirectEntries; uint16_t strategyType; @@ -252,7 +252,7 @@ typedef struct __attribute__((packed)) { uint32_t allocationDescLen; /* Variable length stuff here, need to handle; - */ + */ uint8_t rest[1]; } FileEntryDescriptor; @@ -284,7 +284,7 @@ typedef struct __attribute__((packed)) { uint64_t infoLength; - uint64_t objectSize; //different + uint64_t objectSize; // different uint64_t logicalBlocksRecorded; @@ -292,17 +292,17 @@ typedef struct __attribute__((packed)) { timestamp modificationDateTime; - timestamp creationDateTime; //different + timestamp creationDateTime; // different timestamp attributeDateTime; uint32_t checkpoint; - uint32_t reserved; //different + uint32_t reserved; // different long_ad extendedAttrICB; - long_ad streamDirectoryICB; //different + long_ad streamDirectoryICB; // different regid implementationId; @@ -313,7 +313,7 @@ typedef struct __attribute__((packed)) { uint32_t allocationDescLen; /* Variable length stuff here, need to handle; - */ + */ } ExtendedFileEntryDescriptor; @@ -462,7 +462,7 @@ typedef struct __attribute__((packed)) { charspec descriptorCharSet; - uint8_t logicalVolumeIdentifier[128]; //TODO: handle dstring + uint8_t logicalVolumeIdentifier[128]; // TODO: handle dstring uint32_t logicalBlockSize; @@ -480,7 +480,7 @@ typedef struct __attribute__((packed)) { ext_ad integritySequenceExtent; - uint8_t partitionMaps[1]; //actual length of mapTableLength above; + uint8_t partitionMaps[1]; // actual length of mapTableLength above; } LogicalVolumeDescriptor; diff --git a/libclamav/vba_extract.c b/libclamav/vba_extract.c index 1af402d66e..c810c3d8c4 100644 --- a/libclamav/vba_extract.c +++ b/libclamav/vba_extract.c @@ -470,7 +470,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); data_offset += sizeof(uint16_t); @@ -479,7 +479,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -497,7 +497,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t sys_kind = le32_to_host(val32); data_offset += sizeof(uint32_t); CLI_WRITEN("REM PROJECTSYSKIND: ", 20); @@ -534,7 +534,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t lcid = le32_to_host(val32); char buf[64]; data_offset += size; @@ -552,7 +552,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t lcid_invoke = le32_to_host(val32); char buf[64]; data_offset += sizeof(uint32_t); @@ -570,7 +570,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); codepage = le16_to_host(val16); char buf[64]; data_offset += sizeof(uint16_t); @@ -640,7 +640,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); if (id != 0x003d) { cli_warnmsg("vba_readdir_new: PROJECTHELPFILEPATH is not followed by PROJECTHELPFILEPATH2\n"); @@ -655,7 +655,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } uint32_t size2; - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size2 = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -692,7 +692,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t context = le32_to_host(val32); char buf[64]; data_offset += size; @@ -710,7 +710,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t libflags = le32_to_host(val32); char buf[64]; data_offset += sizeof(uint32_t); @@ -729,7 +729,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t major = le32_to_host(val32); data_offset += size; @@ -738,7 +738,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); uint16_t minor = le16_to_host(val16); data_offset += sizeof(uint16_t); char buf[64]; @@ -756,7 +756,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); uint16_t modules = le16_to_host(val16); data_offset += sizeof(uint16_t); char buf[64]; @@ -774,7 +774,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co ret = CL_EREAD; goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); uint16_t cookie = le16_to_host(val16); data_offset += sizeof(uint16_t); char buf[64]; @@ -808,7 +808,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x0047) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULENAMEUNICODE (0x47) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -816,7 +816,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); CLI_WRITEN("\nREM MODULENAMEUNICODE: ", 24); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -859,7 +859,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x001a) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULESTREAMNAME (0x1a) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -867,7 +867,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); CLI_WRITEN("\nREM MODULESTREAMNAME: ", 23); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -894,7 +894,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x0032) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULESTREAMNAMEUNICODE (0x32) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -902,7 +902,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); CLI_WRITEN("\nREM MODULESTREAMNAMEUNICODE: ", 30); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t module_stream_name_size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -946,7 +946,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x001c) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULEDOCSTRING (0x1c) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -954,7 +954,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); CLI_WRITEN("\nREM MODULEDOCSTRING: ", 22); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -981,7 +981,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x0048) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULEDOCSTRINGUNICODE (0x32) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -989,7 +989,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); CLI_WRITEN("\nREM MODULEDOCSTRINGUNICODE: ", 29); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); @@ -1032,14 +1032,14 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x0031) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULEOFFSET (0x31) record, but got 0x%04x\n", id); ret = CL_EREAD; goto done; } data_offset += sizeof(uint16_t); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != sizeof(uint32_t)) { @@ -1054,7 +1054,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t module_offset = le32_to_host(val32); data_offset += size; char buffer[64]; @@ -1071,7 +1071,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x001e) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULEHELPCONTEXT (0x1e) record, but got 0x%04x\n", id); ret = CL_EREAD; @@ -1079,7 +1079,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co } data_offset += sizeof(uint16_t); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != sizeof(uint32_t)) { @@ -1094,7 +1094,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); uint32_t help_context = le32_to_host(val32); data_offset += size; buffer_size = snprintf(buffer, sizeof(buffer), "\nREM MODULEHELPCONTEXT: 0x%08x", help_context); @@ -1110,14 +1110,14 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); if ((id = le16_to_host(val16)) != 0x002c) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULECOOKIE (0x2c) record, but got 0x%04x\n", id); ret = CL_EREAD; goto done; } data_offset += sizeof(uint16_t); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != sizeof(uint16_t)) { @@ -1132,7 +1132,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); uint16_t cookie = le16_to_host(val16); data_offset += size; buffer_size = snprintf(buffer, sizeof(buffer), "\nREM MODULECOOKIE: 0x%04x", cookie); @@ -1147,7 +1147,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); if (id != 0x0021 && id != 0x0022) { cli_dbgmsg("cli_vba_readdir_new: Expected MODULETYPE (0x21/0x22) record, but got 0x%04x\n", id); @@ -1155,7 +1155,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } data_offset += sizeof(uint16_t); - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != 0) { @@ -1176,7 +1176,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); data_offset += sizeof(uint16_t); @@ -1187,7 +1187,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != 0) { @@ -1203,7 +1203,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); data_offset += sizeof(uint16_t); } @@ -1216,7 +1216,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != 0) { @@ -1232,7 +1232,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val16, &data[data_offset], sizeof (uint16_t)); + memcpy(&val16, &data[data_offset], sizeof(uint16_t)); id = le16_to_host(val16); data_offset += sizeof(uint16_t); } @@ -1250,7 +1250,7 @@ cl_error_t cli_vba_readdir_new(cli_ctx *ctx, const char *dir, struct uniq *U, co goto done; } - memcpy(&val32, &data[data_offset], sizeof (uint32_t)); + memcpy(&val32, &data[data_offset], sizeof(uint32_t)); size = le32_to_host(val32); data_offset += sizeof(uint32_t); if (size != 0) { @@ -2021,7 +2021,7 @@ word_read_macro_entry(int fd, macro_info_t *macro_info) uint32_t len __attribute__((packed)); uint32_t state __attribute__((packed)); uint32_t offset __attribute__((packed)); - } * m; + } *m; const struct macro *n; #ifdef HAVE_PRAGMA_PACK #pragma pack() diff --git a/win32/compat/dirent.c b/win32/compat/dirent.c index 2e64fe79e5..d1973e2cde 100644 --- a/win32/compat/dirent.c +++ b/win32/compat/dirent.c @@ -22,11 +22,11 @@ #include #include -//#include "clamav.h" -//#include "others.h" +// #include "clamav.h" +// #include "others.h" #include "dirent.h" #include "w32_stat.h" -//#include "misc.h" +// #include "misc.h" DIR *opendir(const char *name) { diff --git a/win32/compat/strptime.c b/win32/compat/strptime.c index 9ffbeb0176..a35c5b393a 100644 --- a/win32/compat/strptime.c +++ b/win32/compat/strptime.c @@ -19,7 +19,7 @@ #define strncasecmp _strnicmp #ifndef _LIBC -//# include +// # include #endif #include @@ -31,7 +31,7 @@ #endif #include #include -//#include +// #include #ifdef _LIBC #include "../locale/localeinfo.h"