Merge branch 'master' into blender2.8

This commit is contained in:
2018-01-18 00:58:54 +01:00
81 changed files with 1007 additions and 677 deletions

View File

@@ -38,6 +38,7 @@ set(SRC
./intern/mallocn_lockfree_impl.c ./intern/mallocn_lockfree_impl.c
MEM_guardedalloc.h MEM_guardedalloc.h
./intern/mallocn_inline.h
./intern/mallocn_intern.h ./intern/mallocn_intern.h
# only so the header is known by cmake # only so the header is known by cmake

View File

@@ -113,12 +113,26 @@ extern "C" {
* pointer to it is stored ! */ * pointer to it is stored ! */
extern void *(*MEM_callocN)(size_t len, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); extern void *(*MEM_callocN)(size_t len, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
/**
* Allocate a block of memory of size (len * size), with tag name
* str, aborting in case of integer overflows to prevent vulnerabilities.
* The memory is cleared. The name must be static, because only a
* pointer to it is stored ! */
extern void *(*MEM_calloc_arrayN)(size_t len, size_t size, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
/** /**
* Allocate a block of memory of size len, with tag name str. The * Allocate a block of memory of size len, with tag name str. The
* name must be a static, because only a pointer to it is stored ! * name must be a static, because only a pointer to it is stored !
* */ * */
extern void *(*MEM_mallocN)(size_t len, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); extern void *(*MEM_mallocN)(size_t len, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
/**
* Allocate a block of memory of size (len * size), with tag name str,
* aborting in case of integer overflow to prevent vulnerabilities. The
* name must be a static, because only a pointer to it is stored !
* */
extern void *(*MEM_malloc_arrayN)(size_t len, size_t size, const char *str) /* ATTR_MALLOC */ ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
/** /**
* Allocate an aligned block of memory of size len, with tag name str. The * Allocate an aligned block of memory of size len, with tag name str. The
* name must be a static, because only a pointer to it is stored ! * name must be a static, because only a pointer to it is stored !

View File

@@ -43,7 +43,9 @@ void *(*MEM_dupallocN)(const void *vmemh) = MEM_lockfree_dupallocN;
void *(*MEM_reallocN_id)(void *vmemh, size_t len, const char *str) = MEM_lockfree_reallocN_id; void *(*MEM_reallocN_id)(void *vmemh, size_t len, const char *str) = MEM_lockfree_reallocN_id;
void *(*MEM_recallocN_id)(void *vmemh, size_t len, const char *str) = MEM_lockfree_recallocN_id; void *(*MEM_recallocN_id)(void *vmemh, size_t len, const char *str) = MEM_lockfree_recallocN_id;
void *(*MEM_callocN)(size_t len, const char *str) = MEM_lockfree_callocN; void *(*MEM_callocN)(size_t len, const char *str) = MEM_lockfree_callocN;
void *(*MEM_calloc_arrayN)(size_t len, size_t size, const char *str) = MEM_lockfree_calloc_arrayN;
void *(*MEM_mallocN)(size_t len, const char *str) = MEM_lockfree_mallocN; void *(*MEM_mallocN)(size_t len, const char *str) = MEM_lockfree_mallocN;
void *(*MEM_malloc_arrayN)(size_t len, size_t size, const char *str) = MEM_lockfree_malloc_arrayN;
void *(*MEM_mallocN_aligned)(size_t len, size_t alignment, const char *str) = MEM_lockfree_mallocN_aligned; void *(*MEM_mallocN_aligned)(size_t len, size_t alignment, const char *str) = MEM_lockfree_mallocN_aligned;
void *(*MEM_mapallocN)(size_t len, const char *str) = MEM_lockfree_mapallocN; void *(*MEM_mapallocN)(size_t len, const char *str) = MEM_lockfree_mapallocN;
void (*MEM_printmemlist_pydict)(void) = MEM_lockfree_printmemlist_pydict; void (*MEM_printmemlist_pydict)(void) = MEM_lockfree_printmemlist_pydict;
@@ -107,7 +109,9 @@ void MEM_use_guarded_allocator(void)
MEM_reallocN_id = MEM_guarded_reallocN_id; MEM_reallocN_id = MEM_guarded_reallocN_id;
MEM_recallocN_id = MEM_guarded_recallocN_id; MEM_recallocN_id = MEM_guarded_recallocN_id;
MEM_callocN = MEM_guarded_callocN; MEM_callocN = MEM_guarded_callocN;
MEM_calloc_arrayN = MEM_guarded_calloc_arrayN;
MEM_mallocN = MEM_guarded_mallocN; MEM_mallocN = MEM_guarded_mallocN;
MEM_malloc_arrayN = MEM_guarded_malloc_arrayN;
MEM_mallocN_aligned = MEM_guarded_mallocN_aligned; MEM_mallocN_aligned = MEM_guarded_mallocN_aligned;
MEM_mapallocN = MEM_guarded_mapallocN; MEM_mapallocN = MEM_guarded_mapallocN;
MEM_printmemlist_pydict = MEM_guarded_printmemlist_pydict; MEM_printmemlist_pydict = MEM_guarded_printmemlist_pydict;

View File

@@ -542,6 +542,21 @@ void *MEM_guarded_mallocN(size_t len, const char *str)
return NULL; return NULL;
} }
void *MEM_guarded_malloc_arrayN(size_t len, size_t size, const char *str)
{
size_t total_size;
if (UNLIKELY(!MEM_size_safe_multiply(len, size, &total_size))) {
print_error("Malloc array aborted due to integer overflow: "
"len=" SIZET_FORMAT "x" SIZET_FORMAT " in %s, total %u\n",
SIZET_ARG(len), SIZET_ARG(size), str,
(unsigned int) mem_in_use);
abort();
return NULL;
}
return MEM_guarded_mallocN(total_size, str);
}
void *MEM_guarded_mallocN_aligned(size_t len, size_t alignment, const char *str) void *MEM_guarded_mallocN_aligned(size_t len, size_t alignment, const char *str)
{ {
MemHead *memh; MemHead *memh;
@@ -612,6 +627,21 @@ void *MEM_guarded_callocN(size_t len, const char *str)
return NULL; return NULL;
} }
void *MEM_guarded_calloc_arrayN(size_t len, size_t size, const char *str)
{
size_t total_size;
if (UNLIKELY(!MEM_size_safe_multiply(len, size, &total_size))) {
print_error("Calloc array aborted due to integer overflow: "
"len=" SIZET_FORMAT "x" SIZET_FORMAT " in %s, total %u\n",
SIZET_ARG(len), SIZET_ARG(size), str,
(unsigned int) mem_in_use);
abort();
return NULL;
}
return MEM_guarded_callocN(total_size, str);
}
/* note; mmap returns zero'd memory */ /* note; mmap returns zero'd memory */
void *MEM_guarded_mapallocN(size_t len, const char *str) void *MEM_guarded_mapallocN(size_t len, const char *str)
{ {

View File

@@ -0,0 +1,56 @@
/*
* Adapted from jemalloc, to protect against buffer overflow vulnerabilities.
*
* Copyright (C) 2002-2017 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2017 Facebook, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file guardedalloc/intern/mallocn_inline.h
* \ingroup MEM
*/
#ifndef __MALLOCN_INLINE_H__
#define __MALLOCN_INLINE_H__
MEM_INLINE bool MEM_size_safe_multiply(size_t a, size_t b, size_t *result)
{
/* A size_t with its high-half bits all set to 1. */
const size_t high_bits = SIZE_MAX << (sizeof(size_t) * 8 / 2);
*result = a * b;
if (UNLIKELY(*result == 0)) {
return (a == 0 || b == 0);
}
/*
* We got a non-zero size, but we don't know if we overflowed to get
* there. To avoid having to do a divide, we'll be clever and note that
* if both A and B can be represented in N/2 bits, then their product
* can be represented in N bits (without the possibility of overflow).
*/
return ((high_bits & (a | b)) == 0 || (*result / b == a));
}
#endif /* __MALLOCN_INLINE_H__ */

View File

@@ -115,6 +115,8 @@ size_t malloc_usable_size(void *ptr);
/* Real pointer returned by the malloc or aligned_alloc. */ /* Real pointer returned by the malloc or aligned_alloc. */
#define MEMHEAD_REAL_PTR(memh) ((char *)memh - MEMHEAD_ALIGN_PADDING(memh->alignment)) #define MEMHEAD_REAL_PTR(memh) ((char *)memh - MEMHEAD_ALIGN_PADDING(memh->alignment))
#include "mallocn_inline.h"
void *aligned_malloc(size_t size, size_t alignment); void *aligned_malloc(size_t size, size_t alignment);
void aligned_free(void *ptr); void aligned_free(void *ptr);
@@ -125,7 +127,9 @@ void *MEM_lockfree_dupallocN(const void *vmemh) ATTR_MALLOC ATTR_WARN_UNUSED_RES
void *MEM_lockfree_reallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2); void *MEM_lockfree_reallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2);
void *MEM_lockfree_recallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2); void *MEM_lockfree_recallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2);
void *MEM_lockfree_callocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_lockfree_callocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void *MEM_lockfree_calloc_arrayN(size_t len, size_t size, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
void *MEM_lockfree_mallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_lockfree_mallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void *MEM_lockfree_malloc_arrayN(size_t len, size_t size, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
void *MEM_lockfree_mallocN_aligned(size_t len, size_t alignment, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3); void *MEM_lockfree_mallocN_aligned(size_t len, size_t alignment, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3);
void *MEM_lockfree_mapallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_lockfree_mapallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void MEM_lockfree_printmemlist_pydict(void); void MEM_lockfree_printmemlist_pydict(void);
@@ -152,7 +156,9 @@ void *MEM_guarded_dupallocN(const void *vmemh) ATTR_MALLOC ATTR_WARN_UNUSED_RESU
void *MEM_guarded_reallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2); void *MEM_guarded_reallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2);
void *MEM_guarded_recallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2); void *MEM_guarded_recallocN_id(void *vmemh, size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(2);
void *MEM_guarded_callocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_guarded_callocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void *MEM_guarded_calloc_arrayN(size_t len, size_t size, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
void *MEM_guarded_mallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_guarded_mallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void *MEM_guarded_malloc_arrayN(size_t len, size_t size, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1,2) ATTR_NONNULL(3);
void *MEM_guarded_mallocN_aligned(size_t len, size_t alignment, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3); void *MEM_guarded_mallocN_aligned(size_t len, size_t alignment, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3);
void *MEM_guarded_mapallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2); void *MEM_guarded_mapallocN(size_t len, const char *UNUSED(str)) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2);
void MEM_guarded_printmemlist_pydict(void); void MEM_guarded_printmemlist_pydict(void);

View File

@@ -293,6 +293,21 @@ void *MEM_lockfree_callocN(size_t len, const char *str)
return NULL; return NULL;
} }
void *MEM_lockfree_calloc_arrayN(size_t len, size_t size, const char *str)
{
size_t total_size;
if (UNLIKELY(!MEM_size_safe_multiply(len, size, &total_size))) {
print_error("Calloc array aborted due to integer overflow: "
"len=" SIZET_FORMAT "x" SIZET_FORMAT " in %s, total %u\n",
SIZET_ARG(len), SIZET_ARG(size), str,
(unsigned int) mem_in_use);
abort();
return NULL;
}
return MEM_lockfree_callocN(total_size, str);
}
void *MEM_lockfree_mallocN(size_t len, const char *str) void *MEM_lockfree_mallocN(size_t len, const char *str)
{ {
MemHead *memh; MemHead *memh;
@@ -318,6 +333,21 @@ void *MEM_lockfree_mallocN(size_t len, const char *str)
return NULL; return NULL;
} }
void *MEM_lockfree_malloc_arrayN(size_t len, size_t size, const char *str)
{
size_t total_size;
if (UNLIKELY(!MEM_size_safe_multiply(len, size, &total_size))) {
print_error("Malloc array aborted due to integer overflow: "
"len=" SIZET_FORMAT "x" SIZET_FORMAT " in %s, total %u\n",
SIZET_ARG(len), SIZET_ARG(size), str,
(unsigned int) mem_in_use);
abort();
return NULL;
}
return MEM_lockfree_mallocN(total_size, str);
}
void *MEM_lockfree_mallocN_aligned(size_t len, size_t alignment, const char *str) void *MEM_lockfree_mallocN_aligned(size_t len, size_t alignment, const char *str)
{ {
MemHeadAligned *memh; MemHeadAligned *memh;

View File

@@ -26,6 +26,7 @@
set(INC set(INC
. .
../blenlib ../blenlib
../imbuf
../../../intern/guardedalloc ../../../intern/guardedalloc
) )

View File

@@ -285,13 +285,15 @@ bool AVI_is_avi(const char *name)
fseek(movie.fp, movie.header->size - 14 * 4, SEEK_CUR); fseek(movie.fp, movie.header->size - 14 * 4, SEEK_CUR);
if (movie.header->Streams < 1) { /* Limit number of streams to some reasonable amount to prevent
DEBUG_PRINT("streams less than 1\n"); * buffer oveflow vulnerabilities. */
if (movie.header->Streams < 1 || movie.header->Streams > 65536) {
DEBUG_PRINT("Number of streams should be in range 1-65536\n");
fclose(movie.fp); fclose(movie.fp);
return 0; return 0;
} }
movie.streams = (AviStreamRec *) MEM_callocN(sizeof(AviStreamRec) * movie.header->Streams, "moviestreams"); movie.streams = (AviStreamRec *) MEM_calloc_arrayN(movie.header->Streams, sizeof(AviStreamRec), "moviestreams");
for (temp = 0; temp < movie.header->Streams; temp++) { for (temp = 0; temp < movie.header->Streams; temp++) {
@@ -486,12 +488,14 @@ AviError AVI_open_movie(const char *name, AviMovie *movie)
fseek(movie->fp, movie->header->size - 14 * 4, SEEK_CUR); fseek(movie->fp, movie->header->size - 14 * 4, SEEK_CUR);
if (movie->header->Streams < 1) { /* Limit number of streams to some reasonable amount to prevent
DEBUG_PRINT("streams less than 1\n"); * buffer oveflow vulnerabilities. */
if (movie->header->Streams < 1 || movie->header->Streams > 65536) {
DEBUG_PRINT("Number of streams should be in range 1-65536\n");
return AVI_ERROR_FORMAT; return AVI_ERROR_FORMAT;
} }
movie->streams = (AviStreamRec *) MEM_callocN(sizeof(AviStreamRec) * movie->header->Streams, "moviestreams"); movie->streams = (AviStreamRec *) MEM_calloc_arrayN(movie->header->Streams, sizeof(AviStreamRec), "moviestreams");
for (temp = 0; temp < movie->header->Streams; temp++) { for (temp = 0; temp < movie->header->Streams; temp++) {
@@ -689,7 +693,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie)
void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream) void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream)
{ {
int cur_frame = -1, temp, i = 0, rewind = 1; int cur_frame = -1, i = 0, rewind = 1;
void *buffer; void *buffer;
/* Retrieve the record number of the desired frame in the index /* Retrieve the record number of the desired frame in the index
@@ -720,16 +724,16 @@ void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream)
fseek(movie->fp, movie->read_offset + movie->entries[i - 1].Offset, SEEK_SET); fseek(movie->fp, movie->read_offset + movie->entries[i - 1].Offset, SEEK_SET);
temp = GET_FCC(movie->fp); size_t size = GET_FCC(movie->fp);
buffer = MEM_mallocN(temp, "readbuffer"); buffer = MEM_mallocN(size, "readbuffer");
if (fread(buffer, 1, temp, movie->fp) != temp) { if (fread(buffer, 1, size, movie->fp) != size) {
MEM_freeN(buffer); MEM_freeN(buffer);
return NULL; return NULL;
} }
buffer = avi_format_convert(movie, stream, buffer, movie->streams[stream].format, format, &temp); buffer = avi_format_convert(movie, stream, buffer, movie->streams[stream].format, format, &size);
return buffer; return buffer;
} }
@@ -801,6 +805,13 @@ AviError AVI_open_compress(char *name, AviMovie *movie, int streams, ...)
movie->header->Reserved[2] = 0; movie->header->Reserved[2] = 0;
movie->header->Reserved[3] = 0; movie->header->Reserved[3] = 0;
/* Limit number of streams to some reasonable amount to prevent
* buffer oveflow vulnerabilities. */
if (movie->header->Streams < 0 || movie->header->Streams > 65536) {
DEBUG_PRINT("Number of streams should be in range 0-65536\n");
return AVI_ERROR_FORMAT;
}
movie->streams = (AviStreamRec *) MEM_mallocN(sizeof(AviStreamRec) * movie->header->Streams, "moviestreams"); movie->streams = (AviStreamRec *) MEM_mallocN(sizeof(AviStreamRec) * movie->header->Streams, "moviestreams");
va_start(ap, streams); va_start(ap, streams);
@@ -968,7 +979,6 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...)
int64_t rec_off; int64_t rec_off;
AviFormat format; AviFormat format;
void *buffer; void *buffer;
int size;
if (frame_num < 0) if (frame_num < 0)
return AVI_ERROR_OPTION; return AVI_ERROR_OPTION;
@@ -1002,7 +1012,7 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...)
format = va_arg(ap, AviFormat); format = va_arg(ap, AviFormat);
buffer = va_arg(ap, void *); buffer = va_arg(ap, void *);
size = va_arg(ap, int); size_t size = va_arg(ap, int);
/* Convert the buffer into the output format */ /* Convert the buffer into the output format */
buffer = avi_format_convert(movie, stream, buffer, format, movie->streams[stream].format, &size); buffer = avi_format_convert(movie, stream, buffer, format, movie->streams[stream].format, &size);

View File

@@ -39,7 +39,7 @@
#include "avi_mjpeg.h" #include "avi_mjpeg.h"
#include "avi_rgb32.h" #include "avi_rgb32.h"
void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, int *size) void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, size_t *size)
{ {
if (from == to) if (from == to)
return buffer; return buffer;

View File

@@ -59,7 +59,7 @@ unsigned int GET_TCC(FILE *fp);
putc(ch2[1], fp); \ putc(ch2[1], fp); \
} (void)0 } (void)0
void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, int *size); void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, size_t *size);
int avi_get_data_id(AviFormat format, int stream); int avi_get_data_id(AviFormat format, int stream);
int avi_get_format_type(AviFormat format); int avi_get_format_type(AviFormat format);

View File

@@ -39,15 +39,17 @@
#include "MEM_guardedalloc.h" #include "MEM_guardedalloc.h"
#include "IMB_imbuf.h"
#include "jpeglib.h" #include "jpeglib.h"
#include "jerror.h" #include "jerror.h"
#include "avi_mjpeg.h" #include "avi_mjpeg.h"
static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, int bufsize); static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, size_t bufsize);
static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, int bufsize); static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, size_t bufsize);
static int numbytes; static size_t numbytes;
static void add_huff_table(j_decompress_ptr dinfo, JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val) static void add_huff_table(j_decompress_ptr dinfo, JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
{ {
@@ -151,10 +153,8 @@ static void std_huff_tables(j_decompress_ptr dinfo)
bits_ac_chrominance, val_ac_chrominance); bits_ac_chrominance, val_ac_chrominance);
} }
static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsigned int width, unsigned int height, int bufsize) static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsigned int width, unsigned int height, size_t bufsize)
{ {
int rowstride;
unsigned int y;
struct jpeg_decompress_struct dinfo; struct jpeg_decompress_struct dinfo;
struct jpeg_error_mgr jerr; struct jpeg_error_mgr jerr;
@@ -174,8 +174,8 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
jpeg_start_decompress(&dinfo); jpeg_start_decompress(&dinfo);
rowstride = dinfo.output_width * dinfo.output_components; size_t rowstride = dinfo.output_width * dinfo.output_components;
for (y = 0; y < dinfo.output_height; y++) { for (size_t y = 0; y < dinfo.output_height; y++) {
jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1); jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1);
outBuffer += rowstride; outBuffer += rowstride;
} }
@@ -194,7 +194,7 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
jpeg_start_decompress(&dinfo); jpeg_start_decompress(&dinfo);
rowstride = dinfo.output_width * dinfo.output_components; rowstride = dinfo.output_width * dinfo.output_components;
for (y = 0; y < dinfo.output_height; y++) { for (size_t y = 0; y < dinfo.output_height; y++) {
jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1); jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1);
outBuffer += rowstride; outBuffer += rowstride;
} }
@@ -204,10 +204,8 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
return 1; return 1;
} }
static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned char *inBuffer, int width, int height, int bufsize) static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned char *inBuffer, int width, int height, size_t bufsize)
{ {
int i, rowstride;
unsigned int y;
struct jpeg_compress_struct cinfo; struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr; struct jpeg_error_mgr jerr;
unsigned char marker[60]; unsigned char marker[60];
@@ -240,7 +238,7 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
jpeg_start_compress(&cinfo, false); jpeg_start_compress(&cinfo, false);
i = 0; int i = 0;
marker[i++] = 'A'; marker[i++] = 'A';
marker[i++] = 'V'; marker[i++] = 'V';
marker[i++] = 'I'; marker[i++] = 'I';
@@ -257,8 +255,8 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
jpeg_write_marker(&cinfo, JPEG_COM, marker, 60); jpeg_write_marker(&cinfo, JPEG_COM, marker, 60);
rowstride = cinfo.image_width * cinfo.input_components; size_t rowstride = cinfo.image_width * cinfo.input_components;
for (y = 0; y < cinfo.image_height; y++) { for (size_t y = 0; y < cinfo.image_height; y++) {
jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &inBuffer, 1); jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &inBuffer, 1);
inBuffer += rowstride; inBuffer += rowstride;
} }
@@ -268,7 +266,7 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
static void interlace(unsigned char *to, unsigned char *from, int width, int height) static void interlace(unsigned char *to, unsigned char *from, int width, int height)
{ {
int i, rowstride = width * 3; size_t i, rowstride = width * 3;
for (i = 0; i < height; i++) { for (i = 0; i < height; i++) {
if (i & 1) if (i & 1)
@@ -280,7 +278,7 @@ static void interlace(unsigned char *to, unsigned char *from, int width, int hei
static void deinterlace(int odd, unsigned char *to, unsigned char *from, int width, int height) static void deinterlace(int odd, unsigned char *to, unsigned char *from, int width, int height)
{ {
int i, rowstride = width * 3; size_t i, rowstride = width * 3;
for (i = 0; i < height; i++) { for (i = 0; i < height; i++) {
if ((i & 1) == odd) if ((i & 1) == odd)
@@ -290,22 +288,27 @@ static void deinterlace(int odd, unsigned char *to, unsigned char *from, int wid
} }
} }
void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
int deint; int deint;
unsigned char *buf; unsigned char *buf;
(void)stream; /* unused */ (void)stream; /* unused */
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_from_mjpeg 1"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_from_mjpeg 1");
if (!buf) {
return NULL;
}
deint = Decode_JPEG(buffer, buf, movie->header->Width, movie->header->Height, *size); deint = Decode_JPEG(buffer, buf, movie->header->Width, movie->header->Height, *size);
MEM_freeN(buffer); MEM_freeN(buffer);
if (deint) { if (deint) {
buffer = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_from_mjpeg 2"); buffer = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_from_mjpeg 2");
if (buffer) {
interlace(buffer, buf, movie->header->Width, movie->header->Height); interlace(buffer, buf, movie->header->Width, movie->header->Height);
}
MEM_freeN(buf); MEM_freeN(buf);
buf = buffer; buf = buffer;
@@ -314,29 +317,35 @@ void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffe
return buf; return buf;
} }
void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
unsigned char *buf; unsigned char *buf;
int bufsize = *size; size_t bufsize = *size;
numbytes = 0; numbytes = 0;
*size = 0; *size = 0;
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_to_mjpeg 1"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_to_mjpeg 1");
if (!buf) {
return NULL;
}
if (!movie->interlace) { if (!movie->interlace) {
Compress_JPEG(movie->streams[stream].sh.Quality / 100, Compress_JPEG(movie->streams[stream].sh.Quality / 100,
buf, buffer, buf, buffer,
movie->header->Width, movie->header->Width,
movie->header->Height, movie->header->Height,
bufsize); bufsize);
*size += numbytes;
} }
else { else {
deinterlace(movie->odd_fields, buf, buffer, movie->header->Width, movie->header->Height); deinterlace(movie->odd_fields, buf, buffer, movie->header->Width, movie->header->Height);
MEM_freeN(buffer); MEM_freeN(buffer);
buffer = buf; buffer = buf;
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_to_mjpeg 2"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_to_mjpeg 1");
if (buf) {
Compress_JPEG(movie->streams[stream].sh.Quality / 100, Compress_JPEG(movie->streams[stream].sh.Quality / 100,
buf, buffer, buf, buffer,
movie->header->Width, movie->header->Width,
@@ -345,12 +354,13 @@ void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer,
*size += numbytes; *size += numbytes;
numbytes = 0; numbytes = 0;
Compress_JPEG(movie->streams[stream].sh.Quality / 100, Compress_JPEG(movie->streams[stream].sh.Quality / 100,
buf + *size, buffer + (movie->header->Height / 2) * movie->header->Width * 3, buf + *size, buffer + (size_t)(movie->header->Height / 2) * (size_t)movie->header->Width * 3,
movie->header->Width, movie->header->Width,
movie->header->Height / 2, movie->header->Height / 2,
bufsize / 2); bufsize / 2);
}
*size += numbytes; *size += numbytes;
}
}
MEM_freeN(buffer); MEM_freeN(buffer);
return buf; return buf;
@@ -377,7 +387,7 @@ static void jpegmemdestmgr_term_destination(j_compress_ptr cinfo)
MEM_freeN(cinfo->dest); MEM_freeN(cinfo->dest);
} }
static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, int bufsize) static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, size_t bufsize)
{ {
cinfo->dest = MEM_mallocN(sizeof(*(cinfo->dest)), "avi.jpegmemdestmgr_build"); cinfo->dest = MEM_mallocN(sizeof(*(cinfo->dest)), "avi.jpegmemdestmgr_build");
@@ -430,7 +440,7 @@ static void jpegmemsrcmgr_term_source(j_decompress_ptr dinfo)
MEM_freeN(dinfo->src); MEM_freeN(dinfo->src);
} }
static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, int bufsize) static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, size_t bufsize)
{ {
dinfo->src = MEM_mallocN(sizeof(*(dinfo->src)), "avi.jpegmemsrcmgr_build"); dinfo->src = MEM_mallocN(sizeof(*(dinfo->src)), "avi.jpegmemsrcmgr_build");

View File

@@ -32,7 +32,7 @@
#ifndef __AVI_MJPEG_H__ #ifndef __AVI_MJPEG_H__
#define __AVI_MJPEG_H__ #define __AVI_MJPEG_H__
void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_MJPEG_H__ */ #endif /* __AVI_MJPEG_H__ */

View File

@@ -40,11 +40,12 @@
#include "AVI_avi.h" #include "AVI_avi.h"
#include "avi_rgb.h" #include "avi_rgb.h"
#include "IMB_imbuf.h"
/* implementation */ /* implementation */
void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
int x, y, i, rowstride;
unsigned char *buf; unsigned char *buf;
AviBitmapInfoHeader *bi; AviBitmapInfoHeader *bi;
short bits = 32; short bits = 32;
@@ -61,9 +62,10 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
unsigned char *pxla; unsigned char *pxla;
#endif #endif
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromavirgbbuf"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromavirgbbuf");
y = movie->header->Height; if (buf) {
size_t y = movie->header->Height;
to = buf; to = buf;
while (y--) { while (y--) {
@@ -73,10 +75,10 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
pxla = (unsigned char *)pxl; pxla = (unsigned char *)pxl;
#endif #endif
x = movie->header->Width; size_t x = movie->header->Width;
while (x--) { while (x--) {
#ifdef __BIG_ENDIAN__ #ifdef __BIG_ENDIAN__
i = pxla[0]; int i = pxla[0];
pxla[0] = pxla[1]; pxla[0] = pxla[1];
pxla[1] = i; pxla[1] = i;
@@ -89,26 +91,29 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
pxl++; pxl++;
} }
} }
}
MEM_freeN(buffer); MEM_freeN(buffer);
return buf; return buf;
} }
else { else {
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromavirgbbuf"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromavirgbbuf");
rowstride = movie->header->Width * 3; if (buf) {
size_t rowstride = movie->header->Width * 3;
if ((bits != 16) && (movie->header->Width % 2)) rowstride++; if ((bits != 16) && (movie->header->Width % 2)) rowstride++;
for (y = 0; y < movie->header->Height; y++) { for (size_t y = 0; y < movie->header->Height; y++) {
memcpy(&buf[y * movie->header->Width * 3], &buffer[((movie->header->Height - 1) - y) * rowstride], movie->header->Width * 3); memcpy(&buf[y * movie->header->Width * 3], &buffer[((movie->header->Height - 1) - y) * rowstride], movie->header->Width * 3);
} }
for (y = 0; y < movie->header->Height * movie->header->Width * 3; y += 3) { for (size_t y = 0; y < (size_t)movie->header->Height * (size_t)movie->header->Width * 3; y += 3) {
i = buf[y]; int i = buf[y];
buf[y] = buf[y + 2]; buf[y] = buf[y + 2];
buf[y + 2] = i; buf[y + 2] = i;
} }
}
MEM_freeN(buffer); MEM_freeN(buffer);
@@ -116,27 +121,26 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
} }
} }
void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
int y, x, i, rowstride;
unsigned char *buf; unsigned char *buf;
(void)stream; /* unused */ (void)stream; /* unused */
rowstride = movie->header->Width * 3; size_t rowstride = movie->header->Width * 3;
/* AVI files has uncompressed lines 4-byte aligned */ /* AVI files has uncompressed lines 4-byte aligned */
rowstride = (rowstride + 3) & ~3; rowstride = (rowstride + 3) & ~3;
*size = movie->header->Height * rowstride; *size = movie->header->Height * rowstride;
buf = MEM_mallocN(*size, "toavirgbbuf"); buf = MEM_mallocN(*size, "toavirgbbuf");
for (y = 0; y < movie->header->Height; y++) { for (size_t y = 0; y < movie->header->Height; y++) {
memcpy(&buf[y * rowstride], &buffer[((movie->header->Height - 1) - y) * movie->header->Width * 3], movie->header->Width * 3); memcpy(&buf[y * rowstride], &buffer[((movie->header->Height - 1) - y) * movie->header->Width * 3], movie->header->Width * 3);
} }
for (y = 0; y < movie->header->Height; y++) { for (size_t y = 0; y < movie->header->Height; y++) {
for (x = 0; x < movie->header->Width * 3; x += 3) { for (size_t x = 0; x < movie->header->Width * 3; x += 3) {
i = buf[y * rowstride + x]; int i = buf[y * rowstride + x];
buf[y * rowstride + x] = buf[y * rowstride + x + 2]; buf[y * rowstride + x] = buf[y * rowstride + x + 2];
buf[y * rowstride + x + 2] = i; buf[y * rowstride + x + 2] = i;
} }

View File

@@ -32,7 +32,7 @@
#ifndef __AVI_RGB_H__ #ifndef __AVI_RGB_H__
#define __AVI_RGB_H__ #define __AVI_RGB_H__
void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_RGB_H__ */ #endif /* __AVI_RGB_H__ */

View File

@@ -37,24 +37,28 @@
#include "MEM_guardedalloc.h" #include "MEM_guardedalloc.h"
#include "IMB_imbuf.h"
#include "AVI_avi.h" #include "AVI_avi.h"
#include "avi_rgb32.h" #include "avi_rgb32.h"
void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
int y, x, rowstridea, rowstrideb;
unsigned char *buf; unsigned char *buf;
(void)stream; /* unused */ (void)stream; /* unused */
buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromrgb32buf"); *size = (size_t)movie->header->Height * (size_t)movie->header->Width * 3;
*size = movie->header->Height * movie->header->Width * 3; buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromrgb32buf");
if (!buf) {
return NULL;
}
rowstridea = movie->header->Width * 3; size_t rowstridea = movie->header->Width * 3;
rowstrideb = movie->header->Width * 4; size_t rowstrideb = movie->header->Width * 4;
for (y = 0; y < movie->header->Height; y++) { for (size_t y = 0; y < movie->header->Height; y++) {
for (x = 0; x < movie->header->Width; x++) { for (size_t x = 0; x < movie->header->Width; x++) {
buf[y * rowstridea + x * 3 + 0] = buffer[y * rowstrideb + x * 4 + 3]; buf[y * rowstridea + x * 3 + 0] = buffer[y * rowstrideb + x * 4 + 3];
buf[y * rowstridea + x * 3 + 1] = buffer[y * rowstrideb + x * 4 + 2]; buf[y * rowstridea + x * 3 + 1] = buffer[y * rowstrideb + x * 4 + 2];
buf[y * rowstridea + x * 3 + 2] = buffer[y * rowstrideb + x * 4 + 1]; buf[y * rowstridea + x * 3 + 2] = buffer[y * rowstrideb + x * 4 + 1];
@@ -66,21 +70,23 @@ void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffe
return buf; return buf;
} }
void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size) void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{ {
int i;
unsigned char *buf; unsigned char *buf;
unsigned char *to, *from; unsigned char *to, *from;
(void)stream; /* unused */ (void)stream; /* unused */
*size = movie->header->Height * movie->header->Width * 4; *size = (size_t)movie->header->Height * (size_t)movie->header->Width * 4;
buf = MEM_mallocN(*size, "torgb32buf"); buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "torgb32buf");
if (!buf) {
return NULL;
}
memset(buf, 255, *size); memset(buf, 255, *size);
to = buf; from = buffer; to = buf; from = buffer;
i = movie->header->Height * movie->header->Width; size_t i = (size_t)movie->header->Height * (size_t)movie->header->Width;
while (i--) { while (i--) {
memcpy(to, from, 3); memcpy(to, from, 3);

View File

@@ -32,7 +32,7 @@
#ifndef __AVI_RGB32_H__ #ifndef __AVI_RGB32_H__
#define __AVI_RGB32_H__ #define __AVI_RGB32_H__
void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size); void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_RGB32_H__ */ #endif /* __AVI_RGB32_H__ */

View File

@@ -147,7 +147,8 @@ typedef struct Main {
#define BLEN_THUMB_SIZE 128 #define BLEN_THUMB_SIZE 128
#define BLEN_THUMB_MEMSIZE(_x, _y) (sizeof(BlendThumbnail) + (size_t)((_x) * (_y)) * sizeof(int)) #define BLEN_THUMB_MEMSIZE(_x, _y) (sizeof(BlendThumbnail) + ((size_t)(_x) * (size_t)(_y)) * sizeof(int))
#define BLEN_THUMB_SAFE_MEMSIZE(_x, _y) ((uint64_t)_x * (uint64_t)_y < (SIZE_MAX / (sizeof(int) * 4)))
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -246,7 +246,8 @@ typedef struct ParticleDrawData {
float *cdata, *cd; /* color data */ float *cdata, *cd; /* color data */
float *vedata, *ved; /* velocity data */ float *vedata, *ved; /* velocity data */
float *ma_col; float *ma_col;
int tot_vec_size, flag; int totpart, partsize;
int flag;
int totpoint, totve; int totpoint, totve;
} ParticleDrawData; } ParticleDrawData;

View File

@@ -187,7 +187,7 @@ static MPoly *dm_getPolyArray(DerivedMesh *dm)
static MVert *dm_dupVertArray(DerivedMesh *dm) static MVert *dm_dupVertArray(DerivedMesh *dm)
{ {
MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm), MVert *tmp = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(*tmp),
"dm_dupVertArray tmp"); "dm_dupVertArray tmp");
if (tmp) dm->copyVertArray(dm, tmp); if (tmp) dm->copyVertArray(dm, tmp);
@@ -197,7 +197,7 @@ static MVert *dm_dupVertArray(DerivedMesh *dm)
static MEdge *dm_dupEdgeArray(DerivedMesh *dm) static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
{ {
MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm), MEdge *tmp = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(*tmp),
"dm_dupEdgeArray tmp"); "dm_dupEdgeArray tmp");
if (tmp) dm->copyEdgeArray(dm, tmp); if (tmp) dm->copyEdgeArray(dm, tmp);
@@ -207,7 +207,7 @@ static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
static MFace *dm_dupFaceArray(DerivedMesh *dm) static MFace *dm_dupFaceArray(DerivedMesh *dm)
{ {
MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm), MFace *tmp = MEM_malloc_arrayN(dm->getNumTessFaces(dm), sizeof(*tmp),
"dm_dupFaceArray tmp"); "dm_dupFaceArray tmp");
if (tmp) dm->copyTessFaceArray(dm, tmp); if (tmp) dm->copyTessFaceArray(dm, tmp);
@@ -217,7 +217,7 @@ static MFace *dm_dupFaceArray(DerivedMesh *dm)
static MLoop *dm_dupLoopArray(DerivedMesh *dm) static MLoop *dm_dupLoopArray(DerivedMesh *dm)
{ {
MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm), MLoop *tmp = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(*tmp),
"dm_dupLoopArray tmp"); "dm_dupLoopArray tmp");
if (tmp) dm->copyLoopArray(dm, tmp); if (tmp) dm->copyLoopArray(dm, tmp);
@@ -227,7 +227,7 @@ static MLoop *dm_dupLoopArray(DerivedMesh *dm)
static MPoly *dm_dupPolyArray(DerivedMesh *dm) static MPoly *dm_dupPolyArray(DerivedMesh *dm)
{ {
MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm), MPoly *tmp = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(*tmp),
"dm_dupPolyArray tmp"); "dm_dupPolyArray tmp");
if (tmp) dm->copyPolyArray(dm, tmp); if (tmp) dm->copyPolyArray(dm, tmp);
@@ -529,7 +529,7 @@ void DM_ensure_looptri_data(DerivedMesh *dm)
if (totpoly) { if (totpoly) {
if (dm->looptris.array_wip == NULL) { if (dm->looptris.array_wip == NULL) {
dm->looptris.array_wip = MEM_mallocN(sizeof(*dm->looptris.array_wip) * looptris_num, __func__); dm->looptris.array_wip = MEM_malloc_arrayN(looptris_num, sizeof(*dm->looptris.array_wip), __func__);
dm->looptris.num_alloc = looptris_num; dm->looptris.num_alloc = looptris_num;
} }
@@ -577,7 +577,7 @@ void DM_update_tessface_data(DerivedMesh *dm)
CustomData_has_layer(fdata, CD_TESSLOOPNORMAL) || CustomData_has_layer(fdata, CD_TESSLOOPNORMAL) ||
CustomData_has_layer(fdata, CD_TANGENT)) CustomData_has_layer(fdata, CD_TANGENT))
{ {
loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__); loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) { for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
const int mf_len = mf->v4 ? 4 : 3; const int mf_len = mf->v4 ? 4 : 3;
@@ -637,7 +637,7 @@ void DM_generate_tangent_tessface_data(DerivedMesh *dm, bool generate)
CustomData_bmesh_update_active_layers(fdata, ldata); CustomData_bmesh_update_active_layers(fdata, ldata);
if (!loopindex) { if (!loopindex) {
loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__); loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) { for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
const int mf_len = mf->v4 ? 4 : 3; const int mf_len = mf->v4 ? 4 : 3;
unsigned int *ml_idx = loopindex[mf_idx]; unsigned int *ml_idx = loopindex[mf_idx];
@@ -682,7 +682,7 @@ void DM_update_materials(DerivedMesh *dm, Object *ob)
if (dm->mat) if (dm->mat)
MEM_freeN(dm->mat); MEM_freeN(dm->mat);
dm->mat = MEM_mallocN(totmat * sizeof(*dm->mat), "DerivedMesh.mat"); dm->mat = MEM_malloc_arrayN(totmat, sizeof(*dm->mat), "DerivedMesh.mat");
} }
/* we leave last material as empty - rationale here is being able to index /* we leave last material as empty - rationale here is being able to index
@@ -872,7 +872,7 @@ void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
} }
if (kb->data) MEM_freeN(kb->data); if (kb->data) MEM_freeN(kb->data);
kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data"); kb->data = MEM_malloc_arrayN(me->key->elemsize, me->totvert, "kb->data");
kb->totelem = totvert; kb->totelem = totvert;
fp = kb->data; fp = kb->data;
@@ -1208,7 +1208,7 @@ static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
/* these may not really be the orco's, but it's only for preview. /* these may not really be the orco's, but it's only for preview.
* could be solver better once, but isn't simple */ * could be solver better once, but isn't simple */
orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco"); orco = MEM_malloc_arrayN(em->bm->totvert, sizeof(float) * 3, "BMEditMesh Orco");
BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) { BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(orco[i], eve->co); copy_v3_v3(orco[i], eve->co);
@@ -1282,7 +1282,7 @@ static void add_orco_dm(
totvert = dm->getNumVerts(dm); totvert = dm->getNumVerts(dm);
if (orcodm) { if (orcodm) {
orco = MEM_callocN(sizeof(float[3]) * totvert, "dm orco"); orco = MEM_calloc_arrayN(totvert, sizeof(float[3]), "dm orco");
free = 1; free = 1;
if (orcodm->getNumVerts(orcodm) == totvert) if (orcodm->getNumVerts(orcodm) == totvert)
@@ -1564,7 +1564,7 @@ void DM_update_weight_mcol(
wtcol_v = em->derivedVertColor; wtcol_v = em->derivedVertColor;
} }
else { else {
wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__); wtcol_v = MEM_malloc_arrayN(numVerts, sizeof(*wtcol_v), __func__);
} }
/* Weights are given by caller. */ /* Weights are given by caller. */
@@ -1573,7 +1573,7 @@ void DM_update_weight_mcol(
/* If indices is not NULL, it means we do not have weights for all vertices, /* If indices is not NULL, it means we do not have weights for all vertices,
* so we must create them (and set them to zero)... */ * so we must create them (and set them to zero)... */
if (indices) { if (indices) {
w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol"); w = MEM_calloc_arrayN(numVerts, sizeof(float), "Temp weight array DM_update_weight_mcol");
i = num; i = num;
while (i--) while (i--)
w[indices[i]] = weights[i]; w[indices[i]] = weights[i];
@@ -1605,7 +1605,7 @@ void DM_update_weight_mcol(
/* now add to loops, so the data can be passed through the modifier stack /* now add to loops, so the data can be passed through the modifier stack
* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */ * If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
if (!wtcol_l) { if (!wtcol_l) {
wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__); wtcol_l = MEM_malloc_arrayN(dm_totloop, sizeof(*wtcol_l), __func__);
CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop); CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
} }
@@ -1660,7 +1660,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i); cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
kb->totelem = dm->numVertData; kb->totelem = dm->numVertData;
kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c"); kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, sizeof(float), "kbcos DerivedMesh.c");
if (kb->uid == actshape_uid) { if (kb->uid == actshape_uid) {
MVert *mvert = dm->getVertArray(dm); MVert *mvert = dm->getVertArray(dm);
@@ -1681,7 +1681,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
MEM_freeN(kb->data); MEM_freeN(kb->data);
kb->totelem = dm->numVertData; kb->totelem = dm->numVertData;
kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c"); kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c");
fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name); fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
} }
} }
@@ -1692,7 +1692,6 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
KeyBlock *kb; KeyBlock *kb;
Key *key = me->key; Key *key = me->key;
int i; int i;
const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
if (!me->key) if (!me->key)
return; return;
@@ -1713,11 +1712,11 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
fprintf(stderr, fprintf(stderr,
"%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n", "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
__func__, me->id.name + 2, me->totvert, kb->name, kb->totelem); __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
array = MEM_callocN(shape_alloc_len, __func__); array = MEM_calloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
} }
else { else {
array = MEM_mallocN(shape_alloc_len, __func__); array = MEM_malloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
memcpy(array, kb->data, shape_alloc_len); memcpy(array, kb->data, (size_t)me->totvert * 3 * sizeof(float));
} }
CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name); CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
@@ -1990,7 +1989,7 @@ static void mesh_calc_modifiers(
*/ */
numVerts = dm->getNumVerts(dm); numVerts = dm->getNumVerts(dm);
deformedVerts = deformedVerts =
MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv"); MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
dm->getVertCos(dm, deformedVerts); dm->getVertCos(dm, deformedVerts);
} }
else { else {
@@ -2283,7 +2282,7 @@ float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *r_numVerts))[3]
*r_numVerts = em->bm->totvert; *r_numVerts = em->bm->totvert;
cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos"); cos = MEM_malloc_arrayN(em->bm->totvert, 3 * sizeof(float), "vertexcos");
BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) { BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(cos[i], eve->co); copy_v3_v3(cos[i], eve->co);
@@ -2389,7 +2388,7 @@ static void editbmesh_calc_modifiers(
*/ */
numVerts = dm->getNumVerts(dm); numVerts = dm->getNumVerts(dm);
deformedVerts = deformedVerts =
MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv"); MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
dm->getVertCos(dm, deformedVerts); dm->getVertCos(dm, deformedVerts);
} }
else { else {
@@ -3010,11 +3009,11 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX); dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
if (dm->foreachMappedVert) { if (dm->foreachMappedVert) {
vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map"); vertexcosnos = MEM_calloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos); dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
} }
else { else {
DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map"); DMCoNo *v_co_no = vertexcosnos = MEM_malloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
int a; int a;
for (a = 0; a < me->totvert; a++, v_co_no++) { for (a = 0; a < me->totvert; a++, v_co_no++) {
dm->getVertCo(dm, a, v_co_no->co); dm->getVertCo(dm, a, v_co_no->co);
@@ -3907,7 +3906,7 @@ MVert *DM_get_vert_array(DerivedMesh *dm, bool *allocated)
*allocated = false; *allocated = false;
if (mvert == NULL) { if (mvert == NULL) {
mvert = MEM_mallocN(sizeof(MVert) * dm->getNumVerts(dm), "dmvh vert data array"); mvert = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(MVert), "dmvh vert data array");
dm->copyVertArray(dm, mvert); dm->copyVertArray(dm, mvert);
*allocated = true; *allocated = true;
} }
@@ -3922,7 +3921,7 @@ MEdge *DM_get_edge_array(DerivedMesh *dm, bool *allocated)
*allocated = false; *allocated = false;
if (medge == NULL) { if (medge == NULL) {
medge = MEM_mallocN(sizeof(MEdge) * dm->getNumEdges(dm), "dm medge data array"); medge = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(MEdge), "dm medge data array");
dm->copyEdgeArray(dm, medge); dm->copyEdgeArray(dm, medge);
*allocated = true; *allocated = true;
} }
@@ -3937,7 +3936,7 @@ MLoop *DM_get_loop_array(DerivedMesh *dm, bool *r_allocated)
*r_allocated = false; *r_allocated = false;
if (mloop == NULL) { if (mloop == NULL) {
mloop = MEM_mallocN(sizeof(MLoop) * dm->getNumLoops(dm), "dm loop data array"); mloop = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(MLoop), "dm loop data array");
dm->copyLoopArray(dm, mloop); dm->copyLoopArray(dm, mloop);
*r_allocated = true; *r_allocated = true;
} }
@@ -3952,7 +3951,7 @@ MPoly *DM_get_poly_array(DerivedMesh *dm, bool *r_allocated)
*r_allocated = false; *r_allocated = false;
if (mpoly == NULL) { if (mpoly == NULL) {
mpoly = MEM_mallocN(sizeof(MPoly) * dm->getNumPolys(dm), "dm poly data array"); mpoly = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(MPoly), "dm poly data array");
dm->copyPolyArray(dm, mpoly); dm->copyPolyArray(dm, mpoly);
*r_allocated = true; *r_allocated = true;
} }
@@ -3970,7 +3969,7 @@ MFace *DM_get_tessface_array(DerivedMesh *dm, bool *r_allocated)
int numTessFaces = dm->getNumTessFaces(dm); int numTessFaces = dm->getNumTessFaces(dm);
if (numTessFaces > 0) { if (numTessFaces > 0) {
mface = MEM_mallocN(sizeof(MFace) * numTessFaces, "bvh mface data array"); mface = MEM_malloc_arrayN(numTessFaces, sizeof(MFace), "bvh mface data array");
dm->copyTessFaceArray(dm, mface); dm->copyTessFaceArray(dm, mface);
*r_allocated = true; *r_allocated = true;
} }

View File

@@ -304,7 +304,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
cddm->pbvh = BKE_pbvh_new(); cddm->pbvh = BKE_pbvh_new();
cddm->pbvh_draw = can_pbvh_draw(ob, dm); cddm->pbvh_draw = can_pbvh_draw(ob, dm);
looptri = MEM_mallocN(sizeof(*looptri) * looptris_num, __func__); looptri = MEM_malloc_arrayN(looptris_num, sizeof(*looptri), __func__);
BKE_mesh_recalc_looptri( BKE_mesh_recalc_looptri(
me->mloop, me->mpoly, me->mloop, me->mpoly,
@@ -329,7 +329,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
int totvert; int totvert;
totvert = deformdm->getNumVerts(deformdm); totvert = deformdm->getNumVerts(deformdm);
vertCos = MEM_mallocN(totvert * sizeof(float[3]), "cdDM_getPBVH vertCos"); vertCos = MEM_malloc_arrayN(totvert, sizeof(float[3]), "cdDM_getPBVH vertCos");
deformdm->getVertCos(deformdm, vertCos); deformdm->getVertCos(deformdm, vertCos);
BKE_pbvh_apply_vertCos(cddm->pbvh, vertCos); BKE_pbvh_apply_vertCos(cddm->pbvh, vertCos);
MEM_freeN(vertCos); MEM_freeN(vertCos);
@@ -893,9 +893,9 @@ static void cdDM_drawMappedFacesGLSL(
tot_active_mat = dm->drawObject->totmaterial; tot_active_mat = dm->drawObject->totmaterial;
matconv = MEM_callocN(sizeof(*matconv) * tot_active_mat, matconv = MEM_calloc_arrayN(tot_active_mat, sizeof(*matconv),
"cdDM_drawMappedFacesGLSL.matconv"); "cdDM_drawMappedFacesGLSL.matconv");
mat_orig_to_new = MEM_mallocN(sizeof(*mat_orig_to_new) * dm->totmat, mat_orig_to_new = MEM_malloc_arrayN(dm->totmat, sizeof(*mat_orig_to_new),
"cdDM_drawMappedFacesGLSL.mat_orig_to_new"); "cdDM_drawMappedFacesGLSL.mat_orig_to_new");
/* part one, check what attributes are needed per material */ /* part one, check what attributes are needed per material */
@@ -1184,7 +1184,7 @@ static void cdDM_buffer_copy_triangles(
const MLoopTri *lt = dm->getLoopTriArray(dm); const MLoopTri *lt = dm->getLoopTriArray(dm);
const int totpoly = dm->getNumPolys(dm); const int totpoly = dm->getNumPolys(dm);
FaceCount *fc = MEM_mallocN(sizeof(*fc) * gpu_totmat, "gpumaterial.facecount"); FaceCount *fc = MEM_malloc_arrayN(gpu_totmat, sizeof(*fc), "gpumaterial.facecount");
for (i = 0; i < gpu_totmat; i++) { for (i = 0; i < gpu_totmat; i++) {
fc[i].i_visible = 0; fc[i].i_visible = 0;
@@ -1365,7 +1365,7 @@ static void cdDM_buffer_copy_uv_texpaint(
/* should have been checked for before, reassert */ /* should have been checked for before, reassert */
BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV)); BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV));
uv_base = MEM_mallocN(totmaterial * sizeof(*uv_base), "texslots"); uv_base = MEM_malloc_arrayN(totmaterial, sizeof(*uv_base), "texslots");
for (i = 0; i < totmaterial; i++) { for (i = 0; i < totmaterial; i++) {
uv_base[i] = DM_paint_uvlayer_active_get(dm, i); uv_base[i] = DM_paint_uvlayer_active_get(dm, i);
@@ -1579,10 +1579,10 @@ static void cdDM_drawobject_init_vert_points(
int tot_loops = 0; int tot_loops = 0;
/* allocate the array and space for links */ /* allocate the array and space for links */
gdo->vert_points = MEM_mallocN(sizeof(GPUVertPointLink) * gdo->totvert, gdo->vert_points = MEM_malloc_arrayN(gdo->totvert, sizeof(GPUVertPointLink),
"GPUDrawObject.vert_points"); "GPUDrawObject.vert_points");
#ifdef USE_GPU_POINT_LINK #ifdef USE_GPU_POINT_LINK
gdo->vert_points_mem = MEM_callocN(sizeof(GPUVertPointLink) * gdo->totvert, gdo->vert_points_mem = MEM_calloc_arrayN(gdo->totvert, sizeof(GPUVertPointLink),
"GPUDrawObject.vert_points_mem"); "GPUDrawObject.vert_points_mem");
gdo->vert_points_usage = 0; gdo->vert_points_usage = 0;
#endif #endif
@@ -1637,7 +1637,7 @@ static GPUDrawObject *cdDM_GPUobject_new(DerivedMesh *dm)
/* get the number of points used by each material, treating /* get the number of points used by each material, treating
* each quad as two triangles */ * each quad as two triangles */
mat_info = MEM_callocN(sizeof(*mat_info) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new"); mat_info = MEM_calloc_arrayN(dm_totmat, sizeof(*mat_info), "GPU_drawobject_new.mat_orig_to_new");
for (i = 0; i < totpolys; i++) { for (i = 0; i < totpolys; i++) {
const short mat_nr = ME_MAT_NR_TEST(mpoly[i].mat_nr, dm_totmat); const short mat_nr = ME_MAT_NR_TEST(mpoly[i].mat_nr, dm_totmat);
@@ -2476,7 +2476,7 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const bool only_face_normals)
} }
#endif #endif
face_nors = MEM_mallocN(sizeof(*face_nors) * dm->numPolyData, "face_nors"); face_nors = MEM_malloc_arrayN(dm->numPolyData, sizeof(*face_nors), "face_nors");
/* calculate face normals */ /* calculate face normals */
BKE_mesh_calc_normals_poly( BKE_mesh_calc_normals_poly(
@@ -2857,31 +2857,31 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
const int totvert_final = totvert - tot_vtargetmap; const int totvert_final = totvert - tot_vtargetmap;
MVert *mv, *mvert = MEM_mallocN(sizeof(*mvert) * totvert_final, __func__); MVert *mv, *mvert = MEM_malloc_arrayN(totvert_final, sizeof(*mvert), __func__);
int *oldv = MEM_mallocN(sizeof(*oldv) * totvert_final, __func__); int *oldv = MEM_malloc_arrayN(totvert_final, sizeof(*oldv), __func__);
int *newv = MEM_mallocN(sizeof(*newv) * totvert, __func__); int *newv = MEM_malloc_arrayN(totvert, sizeof(*newv), __func__);
STACK_DECLARE(mvert); STACK_DECLARE(mvert);
STACK_DECLARE(oldv); STACK_DECLARE(oldv);
/* Note: create (totedge + totloop) elements because partially invalid polys due to merge may require /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may require
* generating new edges, and while in 99% cases we'll still end with less final edges than totedge, * generating new edges, and while in 99% cases we'll still end with less final edges than totedge,
* cases can be forged that would end requiring more... */ * cases can be forged that would end requiring more... */
MEdge *med, *medge = MEM_mallocN(sizeof(*medge) * (totedge + totloop), __func__); MEdge *med, *medge = MEM_malloc_arrayN((totedge + totloop), sizeof(*medge), __func__);
int *olde = MEM_mallocN(sizeof(*olde) * (totedge + totloop), __func__); int *olde = MEM_malloc_arrayN((totedge + totloop), sizeof(*olde), __func__);
int *newe = MEM_mallocN(sizeof(*newe) * (totedge + totloop), __func__); int *newe = MEM_malloc_arrayN((totedge + totloop), sizeof(*newe), __func__);
STACK_DECLARE(medge); STACK_DECLARE(medge);
STACK_DECLARE(olde); STACK_DECLARE(olde);
MLoop *ml, *mloop = MEM_mallocN(sizeof(*mloop) * totloop, __func__); MLoop *ml, *mloop = MEM_malloc_arrayN(totloop, sizeof(*mloop), __func__);
int *oldl = MEM_mallocN(sizeof(*oldl) * totloop, __func__); int *oldl = MEM_malloc_arrayN(totloop, sizeof(*oldl), __func__);
#ifdef USE_LOOPS #ifdef USE_LOOPS
int newl = MEM_mallocN(sizeof(*newl) * totloop, __func__); int newl = MEM_malloc_arrayN(totloop, sizeof(*newl), __func__);
#endif #endif
STACK_DECLARE(mloop); STACK_DECLARE(mloop);
STACK_DECLARE(oldl); STACK_DECLARE(oldl);
MPoly *mp, *mpoly = MEM_mallocN(sizeof(*medge) * totpoly, __func__); MPoly *mp, *mpoly = MEM_malloc_arrayN(totpoly, sizeof(*medge), __func__);
int *oldp = MEM_mallocN(sizeof(*oldp) * totpoly, __func__); int *oldp = MEM_malloc_arrayN(totpoly, sizeof(*oldp), __func__);
STACK_DECLARE(mpoly); STACK_DECLARE(mpoly);
STACK_DECLARE(oldp); STACK_DECLARE(oldp);
@@ -2959,7 +2959,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
/* if the targets already make up a poly, in which case the new poly is dropped */ /* if the targets already make up a poly, in which case the new poly is dropped */
/* This poly equality check is rather complex. We use a BLI_ghash to speed it up with a first level check */ /* This poly equality check is rather complex. We use a BLI_ghash to speed it up with a first level check */
PolyKey *mpgh; PolyKey *mpgh;
poly_keys = MEM_mallocN(sizeof(PolyKey) * totpoly, __func__); poly_keys = MEM_malloc_arrayN(totpoly, sizeof(PolyKey), __func__);
poly_gset = BLI_gset_new_ex(poly_gset_hash_fn, poly_gset_compare_fn, __func__, totpoly); poly_gset = BLI_gset_new_ex(poly_gset_hash_fn, poly_gset_compare_fn, __func__, totpoly);
/* Duplicates allowed because our compare function is not pure equality */ /* Duplicates allowed because our compare function is not pure equality */
BLI_gset_flag_set(poly_gset, GHASH_FLAG_ALLOW_DUPES); BLI_gset_flag_set(poly_gset, GHASH_FLAG_ALLOW_DUPES);

View File

@@ -169,12 +169,12 @@ void BKE_curve_init(Curve *cu)
if (cu->type == OB_FONT) { if (cu->type == OB_FONT) {
cu->vfont = cu->vfontb = cu->vfonti = cu->vfontbi = BKE_vfont_builtin_get(); cu->vfont = cu->vfontb = cu->vfonti = cu->vfontbi = BKE_vfont_builtin_get();
cu->vfont->id.us += 4; cu->vfont->id.us += 4;
cu->str = MEM_mallocN(12, "str"); cu->str = MEM_malloc_arrayN(12, sizeof(unsigned char), "str");
BLI_strncpy(cu->str, "Text", 12); BLI_strncpy(cu->str, "Text", 12);
cu->len = cu->len_wchar = cu->pos = 4; cu->len = cu->len_wchar = cu->pos = 4;
cu->strinfo = MEM_callocN(12 * sizeof(CharInfo), "strinfo new"); cu->strinfo = MEM_calloc_arrayN(12, sizeof(CharInfo), "strinfo new");
cu->totbox = cu->actbox = 1; cu->totbox = cu->actbox = 1;
cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "textbox"); cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "textbox");
cu->tb[0].w = cu->tb[0].h = 0.0; cu->tb[0].w = cu->tb[0].h = 0.0;
} }
} }
@@ -481,13 +481,13 @@ Nurb *BKE_nurb_duplicate(const Nurb *nu)
if (nu->bezt) { if (nu->bezt) {
newnu->bezt = newnu->bezt =
(BezTriple *)MEM_mallocN((nu->pntsu) * sizeof(BezTriple), "duplicateNurb2"); (BezTriple *)MEM_malloc_arrayN(nu->pntsu, sizeof(BezTriple), "duplicateNurb2");
memcpy(newnu->bezt, nu->bezt, nu->pntsu * sizeof(BezTriple)); memcpy(newnu->bezt, nu->bezt, nu->pntsu * sizeof(BezTriple));
} }
else { else {
len = nu->pntsu * nu->pntsv; len = nu->pntsu * nu->pntsv;
newnu->bp = newnu->bp =
(BPoint *)MEM_mallocN((len) * sizeof(BPoint), "duplicateNurb3"); (BPoint *)MEM_malloc_arrayN(len, sizeof(BPoint), "duplicateNurb3");
memcpy(newnu->bp, nu->bp, len * sizeof(BPoint)); memcpy(newnu->bp, nu->bp, len * sizeof(BPoint));
newnu->knotsu = newnu->knotsv = NULL; newnu->knotsu = newnu->knotsv = NULL;
@@ -495,14 +495,14 @@ Nurb *BKE_nurb_duplicate(const Nurb *nu)
if (nu->knotsu) { if (nu->knotsu) {
len = KNOTSU(nu); len = KNOTSU(nu);
if (len) { if (len) {
newnu->knotsu = MEM_mallocN(len * sizeof(float), "duplicateNurb4"); newnu->knotsu = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb4");
memcpy(newnu->knotsu, nu->knotsu, sizeof(float) * len); memcpy(newnu->knotsu, nu->knotsu, sizeof(float) * len);
} }
} }
if (nu->pntsv > 1 && nu->knotsv) { if (nu->pntsv > 1 && nu->knotsv) {
len = KNOTSV(nu); len = KNOTSV(nu);
if (len) { if (len) {
newnu->knotsv = MEM_mallocN(len * sizeof(float), "duplicateNurb5"); newnu->knotsv = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb5");
memcpy(newnu->knotsv, nu->knotsv, sizeof(float) * len); memcpy(newnu->knotsv, nu->knotsv, sizeof(float) * len);
} }
} }
@@ -525,10 +525,10 @@ Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv)
newnu->knotsv = NULL; newnu->knotsv = NULL;
if (src->bezt) { if (src->bezt) {
newnu->bezt = (BezTriple *)MEM_mallocN(pntsu * pntsv * sizeof(BezTriple), "copyNurb2"); newnu->bezt = (BezTriple *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BezTriple), "copyNurb2");
} }
else { else {
newnu->bp = (BPoint *)MEM_mallocN(pntsu * pntsv * sizeof(BPoint), "copyNurb3"); newnu->bp = (BPoint *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BPoint), "copyNurb3");
} }
return newnu; return newnu;
@@ -975,7 +975,7 @@ static void makeknots(Nurb *nu, short uv)
if (nu->knotsu) if (nu->knotsu)
MEM_freeN(nu->knotsu); MEM_freeN(nu->knotsu);
if (BKE_nurb_check_valid_u(nu)) { if (BKE_nurb_check_valid_u(nu)) {
nu->knotsu = MEM_callocN(4 + sizeof(float) * KNOTSU(nu), "makeknots"); nu->knotsu = MEM_calloc_arrayN(KNOTSU(nu) + 1, sizeof(float), "makeknots");
if (nu->flagu & CU_NURB_CYCLIC) { if (nu->flagu & CU_NURB_CYCLIC) {
calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0); /* cyclic should be uniform */ calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0); /* cyclic should be uniform */
makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu); makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
@@ -991,7 +991,7 @@ static void makeknots(Nurb *nu, short uv)
if (nu->knotsv) if (nu->knotsv)
MEM_freeN(nu->knotsv); MEM_freeN(nu->knotsv);
if (BKE_nurb_check_valid_v(nu)) { if (BKE_nurb_check_valid_v(nu)) {
nu->knotsv = MEM_callocN(4 + sizeof(float) * KNOTSV(nu), "makeknots"); nu->knotsv = MEM_calloc_arrayN(KNOTSV(nu) + 1, sizeof(float), "makeknots");
if (nu->flagv & CU_NURB_CYCLIC) { if (nu->flagv & CU_NURB_CYCLIC) {
calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0); /* cyclic should be uniform */ calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0); /* cyclic should be uniform */
makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv); makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
@@ -1108,7 +1108,7 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
if (len == 0) if (len == 0)
return; return;
sum = (float *)MEM_callocN(sizeof(float) * len, "makeNurbfaces1"); sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbfaces1");
bp = nu->bp; bp = nu->bp;
i = nu->pntsu * nu->pntsv; i = nu->pntsu * nu->pntsv;
@@ -1129,7 +1129,7 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
uend = fp[nu->pntsu]; uend = fp[nu->pntsu];
ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1); ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1);
basisu = (float *)MEM_mallocN(sizeof(float) * KNOTSU(nu), "makeNurbfaces3"); basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbfaces3");
fp = nu->knotsv; fp = nu->knotsv;
vstart = fp[nu->orderv - 1]; vstart = fp[nu->orderv - 1];
@@ -1141,9 +1141,9 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1); vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1);
len = KNOTSV(nu); len = KNOTSV(nu);
basisv = (float *)MEM_mallocN(sizeof(float) * len * totv, "makeNurbfaces3"); basisv = (float *)MEM_malloc_arrayN(len * totv, sizeof(float), "makeNurbfaces3");
jstart = (int *)MEM_mallocN(sizeof(float) * totv, "makeNurbfaces4"); jstart = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces4");
jend = (int *)MEM_mallocN(sizeof(float) * totv, "makeNurbfaces5"); jend = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces5");
/* precalculation of basisv and jstart, jend */ /* precalculation of basisv and jstart, jend */
if (nu->flagv & CU_NURB_CYCLIC) if (nu->flagv & CU_NURB_CYCLIC)
@@ -1281,7 +1281,7 @@ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *
len = nu->pntsu; len = nu->pntsu;
if (len == 0) if (len == 0)
return; return;
sum = (float *)MEM_callocN(sizeof(float) * len, "makeNurbcurve1"); sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbcurve1");
resolu = (resolu * SEGMENTSU(nu)); resolu = (resolu * SEGMENTSU(nu));
@@ -1298,7 +1298,7 @@ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *
uend = fp[nu->pntsu]; uend = fp[nu->pntsu];
ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1)); ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1));
basisu = (float *)MEM_mallocN(sizeof(float) * KNOTSU(nu), "makeNurbcurve3"); basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbcurve3");
if (nu->flagu & CU_NURB_CYCLIC) if (nu->flagu & CU_NURB_CYCLIC)
cycl = nu->orderu - 1; cycl = nu->orderu - 1;
@@ -1549,7 +1549,7 @@ float *BKE_curve_surf_make_orco(Object *ob)
nu = nu->next; nu = nu->next;
} }
/* makeNurbfaces wants zeros */ /* makeNurbfaces wants zeros */
fp = coord_array = MEM_callocN(3 * sizeof(float) * tot, "make_orco"); fp = coord_array = MEM_calloc_arrayN(tot, 3 * sizeof(float), "make_orco");
nu = cu->nurb.first; nu = cu->nurb.first;
while (nu) { while (nu) {
@@ -1660,7 +1660,7 @@ float *BKE_curve_make_orco(const EvaluationContext *eval_ctx, Scene *scene, Obje
if (r_numVerts) if (r_numVerts)
*r_numVerts = numVerts; *r_numVerts = numVerts;
fp = coord_array = MEM_mallocN(3 * sizeof(float) * numVerts, "cu_orco"); fp = coord_array = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "cu_orco");
for (dl = disp.first; dl; dl = dl->next) { for (dl = disp.first; dl; dl = dl->next) {
if (dl->type == DL_INDEX3) { if (dl->type == DL_INDEX3) {
for (u = 0; u < dl->nr; u++, fp += 3) { for (u = 0; u < dl->nr; u++, fp += 3) {
@@ -1764,7 +1764,7 @@ void BKE_curve_bevel_make(
if (ELEM(dl->type, DL_POLY, DL_SEGM)) { if (ELEM(dl->type, DL_POLY, DL_SEGM)) {
dlnew = MEM_mallocN(sizeof(DispList), "makebevelcurve1"); dlnew = MEM_mallocN(sizeof(DispList), "makebevelcurve1");
*dlnew = *dl; *dlnew = *dl;
dlnew->verts = MEM_mallocN(3 * sizeof(float) * dl->parts * dl->nr, "makebevelcurve1"); dlnew->verts = MEM_malloc_arrayN(dl->parts * dl->nr, 3 * sizeof(float), "makebevelcurve1");
memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr); memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr);
if (dlnew->type == DL_SEGM) if (dlnew->type == DL_SEGM)
@@ -1791,7 +1791,7 @@ void BKE_curve_bevel_make(
} }
else if (cu->ext2 == 0.0f) { else if (cu->ext2 == 0.0f) {
dl = MEM_callocN(sizeof(DispList), "makebevelcurve2"); dl = MEM_callocN(sizeof(DispList), "makebevelcurve2");
dl->verts = MEM_mallocN(2 * sizeof(float[3]), "makebevelcurve2"); dl->verts = MEM_malloc_arrayN(2, sizeof(float[3]), "makebevelcurve2");
BLI_addtail(disp, dl); BLI_addtail(disp, dl);
dl->type = DL_SEGM; dl->type = DL_SEGM;
dl->parts = 1; dl->parts = 1;
@@ -1808,7 +1808,7 @@ void BKE_curve_bevel_make(
nr = 4 + 2 * cu->bevresol; nr = 4 + 2 * cu->bevresol;
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1"); dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p1"); dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
BLI_addtail(disp, dl); BLI_addtail(disp, dl);
dl->type = DL_POLY; dl->type = DL_POLY;
dl->parts = 1; dl->parts = 1;
@@ -1840,7 +1840,7 @@ void BKE_curve_bevel_make(
nr = 3 + 2 * cu->bevresol; nr = 3 + 2 * cu->bevresol;
} }
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1"); dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p1"); dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
BLI_addtail(disp, dl); BLI_addtail(disp, dl);
dl->type = DL_SEGM; dl->type = DL_SEGM;
dl->parts = 1; dl->parts = 1;
@@ -1866,7 +1866,7 @@ void BKE_curve_bevel_make(
nr = 2; nr = 2;
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p2"); dl = MEM_callocN(sizeof(DispList), "makebevelcurve p2");
dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p2"); dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p2");
BLI_addtail(disp, dl); BLI_addtail(disp, dl);
dl->type = DL_SEGM; dl->type = DL_SEGM;
dl->parts = 1; dl->parts = 1;
@@ -1898,7 +1898,7 @@ void BKE_curve_bevel_make(
nr = 3 + 2 * cu->bevresol; nr = 3 + 2 * cu->bevresol;
} }
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p3"); dl = MEM_callocN(sizeof(DispList), "makebevelcurve p3");
dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p3"); dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p3");
BLI_addtail(disp, dl); BLI_addtail(disp, dl);
dl->type = DL_SEGM; dl->type = DL_SEGM;
dl->flag = DL_FRONT_CURVE; dl->flag = DL_FRONT_CURVE;
@@ -2692,7 +2692,8 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* check we are a single point? also check we are not a surface and that the orderu is sane, /* check we are a single point? also check we are not a surface and that the orderu is sane,
* enforced in the UI but can go wrong possibly */ * enforced in the UI but can go wrong possibly */
if (!BKE_nurb_check_valid_u(nu)) { if (!BKE_nurb_check_valid_u(nu)) {
bl = MEM_callocN(sizeof(BevList) + 1 * sizeof(BevPoint), "makeBevelList1"); bl = MEM_callocN(sizeof(BevList), "makeBevelList1");
bl->bevpoints = MEM_calloc_arrayN(1, sizeof(BevPoint), "makeBevelPoints1");
BLI_addtail(bev, bl); BLI_addtail(bev, bl);
bl->nr = 0; bl->nr = 0;
bl->charidx = nu->charidx; bl->charidx = nu->charidx;
@@ -2709,10 +2710,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
if (nu->type == CU_POLY) { if (nu->type == CU_POLY) {
len = nu->pntsu; len = nu->pntsu;
bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelList2"); bl = MEM_callocN(sizeof(BevList), "makeBevelList2");
bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints2");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) { if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelList2_seglen"); bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList2_seglen");
bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelList2_segbevcount"); bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList2_segbevcount");
} }
BLI_addtail(bev, bl); BLI_addtail(bev, bl);
@@ -2755,10 +2757,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* in case last point is not cyclic */ /* in case last point is not cyclic */
len = segcount * resolu + 1; len = segcount * resolu + 1;
bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelBPoints"); bl = MEM_callocN(sizeof(BevList), "makeBevelBPoints");
bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelBPointsPoints");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) { if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelBPoints_seglen"); bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelBPoints_seglen");
bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelBPoints_segbevcount"); bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelBPoints_segbevcount");
} }
BLI_addtail(bev, bl); BLI_addtail(bev, bl);
@@ -2891,10 +2894,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
if (nu->pntsv == 1) { if (nu->pntsv == 1) {
len = (resolu * segcount); len = (resolu * segcount);
bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelList3"); bl = MEM_callocN(sizeof(BevList), "makeBevelList3");
bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints3");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) { if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelList3_seglen"); bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList3_seglen");
bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelList3_segbevcount"); bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList3_segbevcount");
} }
BLI_addtail(bev, bl); BLI_addtail(bev, bl);
bl->nr = len; bl->nr = len;
@@ -2989,8 +2993,13 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
blnext = bl->next; blnext = bl->next;
if (bl->nr && bl->dupe_nr) { if (bl->nr && bl->dupe_nr) {
nr = bl->nr - bl->dupe_nr + 1; /* +1 because vectorbezier sets flag too */ nr = bl->nr - bl->dupe_nr + 1; /* +1 because vectorbezier sets flag too */
blnew = MEM_mallocN(sizeof(BevList) + nr * sizeof(BevPoint), "makeBevelList4"); blnew = MEM_callocN(sizeof(BevList), "makeBevelList4");
memcpy(blnew, bl, sizeof(BevList)); memcpy(blnew, bl, sizeof(BevList));
blnew->bevpoints = MEM_calloc_arrayN(nr, sizeof(BevPoint), "makeBevelPoints4");
if (!blnew->bevpoints) {
MEM_freeN(blnew);
break;
}
blnew->segbevcount = bl->segbevcount; blnew->segbevcount = bl->segbevcount;
blnew->seglen = bl->seglen; blnew->seglen = bl->seglen;
blnew->nr = 0; blnew->nr = 0;
@@ -3007,6 +3016,9 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
} }
bevp0++; bevp0++;
} }
if (bl->bevpoints != NULL) {
MEM_freeN(bl->bevpoints);
}
MEM_freeN(bl); MEM_freeN(bl);
blnew->dupe_nr = 0; blnew->dupe_nr = 0;
} }
@@ -3027,7 +3039,7 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* find extreme left points, also test (turning) direction */ /* find extreme left points, also test (turning) direction */
if (poly > 0) { if (poly > 0) {
sd = sortdata = MEM_mallocN(sizeof(struct BevelSort) * poly, "makeBevelList5"); sd = sortdata = MEM_malloc_arrayN(poly, sizeof(struct BevelSort), "makeBevelList5");
bl = bev->first; bl = bev->first;
while (bl) { while (bl) {
if (bl->poly > 0) { if (bl->poly > 0) {
@@ -3445,7 +3457,7 @@ static void calchandlesNurb_intern(Nurb *nu, bool skip_align)
*/ */
static void *allocate_arrays(int count, float ***floats, char ***chars, const char *name) static void *allocate_arrays(int count, float ***floats, char ***chars, const char *name)
{ {
int num_floats = 0, num_chars = 0; size_t num_floats = 0, num_chars = 0;
while (floats && floats[num_floats]) { while (floats && floats[num_floats]) {
num_floats++; num_floats++;
@@ -3455,7 +3467,7 @@ static void *allocate_arrays(int count, float ***floats, char ***chars, const ch
num_chars++; num_chars++;
} }
void *buffer = (float *)MEM_mallocN(count * (sizeof(float) * num_floats + num_chars), name); void *buffer = (float *)MEM_malloc_arrayN(count, (sizeof(float) * num_floats + num_chars), name);
if (!buffer) if (!buffer)
return NULL; return NULL;
@@ -4429,7 +4441,7 @@ void BKE_nurb_direction_switch(Nurb *nu)
/* and make in increasing order again */ /* and make in increasing order again */
a = KNOTSU(nu); a = KNOTSU(nu);
fp1 = nu->knotsu; fp1 = nu->knotsu;
fp2 = tempf = MEM_mallocN(sizeof(float) * a, "switchdirect"); fp2 = tempf = MEM_malloc_arrayN(a, sizeof(float), "switchdirect");
a--; a--;
fp2[a] = fp1[a]; fp2[a] = fp1[a];
while (a--) { while (a--) {
@@ -4473,7 +4485,7 @@ void BKE_nurb_direction_switch(Nurb *nu)
float (*BKE_curve_nurbs_vertexCos_get(ListBase *lb, int *r_numVerts))[3] float (*BKE_curve_nurbs_vertexCos_get(ListBase *lb, int *r_numVerts))[3]
{ {
int i, numVerts = *r_numVerts = BKE_nurbList_verts_count(lb); int i, numVerts = *r_numVerts = BKE_nurbList_verts_count(lb);
float *co, (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "cu_vcos"); float *co, (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "cu_vcos");
Nurb *nu; Nurb *nu;
co = cos[0]; co = cos[0];
@@ -4530,7 +4542,7 @@ void BK_curve_nurbs_vertexCos_apply(ListBase *lb, float (*vertexCos)[3])
float (*BKE_curve_nurbs_keyVertexCos_get(ListBase *lb, float *key))[3] float (*BKE_curve_nurbs_keyVertexCos_get(ListBase *lb, float *key))[3]
{ {
int i, numVerts = BKE_nurbList_verts_count(lb); int i, numVerts = BKE_nurbList_verts_count(lb);
float *co, (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "cu_vcos"); float *co, (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "cu_vcos");
Nurb *nu; Nurb *nu;
co = cos[0]; co = cos[0];
@@ -4677,7 +4689,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
if (nu->type == CU_POLY) { if (nu->type == CU_POLY) {
if (type == CU_BEZIER) { /* to Bezier with vecthandles */ if (type == CU_BEZIER) { /* to Bezier with vecthandles */
nr = nu->pntsu; nr = nu->pntsu;
bezt = (BezTriple *)MEM_callocN(nr * sizeof(BezTriple), "setsplinetype2"); bezt = (BezTriple *)MEM_calloc_arrayN(nr, sizeof(BezTriple), "setsplinetype2");
nu->bezt = bezt; nu->bezt = bezt;
a = nr; a = nr;
bp = nu->bp; bp = nu->bp;
@@ -4713,7 +4725,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
else if (nu->type == CU_BEZIER) { /* Bezier */ else if (nu->type == CU_BEZIER) { /* Bezier */
if (type == CU_POLY || type == CU_NURBS) { if (type == CU_POLY || type == CU_NURBS) {
nr = use_handles ? (3 * nu->pntsu) : nu->pntsu; nr = use_handles ? (3 * nu->pntsu) : nu->pntsu;
nu->bp = MEM_callocN(nr * sizeof(BPoint), "setsplinetype"); nu->bp = MEM_calloc_arrayN(nr, sizeof(BPoint), "setsplinetype");
a = nu->pntsu; a = nu->pntsu;
bezt = nu->bezt; bezt = nu->bezt;
bp = nu->bp; bp = nu->bp;
@@ -4776,7 +4788,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
return false; /* conversion impossible */ return false; /* conversion impossible */
} }
else { else {
bezt = MEM_callocN(nr * sizeof(BezTriple), "setsplinetype2"); bezt = MEM_calloc_arrayN(nr, sizeof(BezTriple), "setsplinetype2");
nu->bezt = bezt; nu->bezt = bezt;
a = nr; a = nr;
bp = nu->bp; bp = nu->bp;

View File

@@ -157,7 +157,7 @@ static void layerCopy_mdeformvert(const void *source, void *dest,
MDeformVert *dvert = POINTER_OFFSET(dest, i * size); MDeformVert *dvert = POINTER_OFFSET(dest, i * size);
if (dvert->totweight) { if (dvert->totweight) {
MDeformWeight *dw = MEM_mallocN(dvert->totweight * sizeof(*dw), MDeformWeight *dw = MEM_malloc_arrayN(dvert->totweight, sizeof(*dw),
"layerCopy_mdeformvert dw"); "layerCopy_mdeformvert dw");
memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw)); memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
@@ -281,7 +281,7 @@ static void layerInterp_mdeformvert(
} }
if (totweight) { if (totweight) {
dvert->dw = MEM_mallocN(sizeof(*dvert->dw) * totweight, __func__); dvert->dw = MEM_malloc_arrayN(totweight, sizeof(*dvert->dw), __func__);
} }
} }
@@ -518,11 +518,11 @@ static void layerSwap_mdisps(void *data, const int *ci)
MEM_freeN(s->disps); MEM_freeN(s->disps);
s->totdisp = (s->totdisp / corners) * nverts; s->totdisp = (s->totdisp / corners) * nverts;
s->disps = MEM_callocN(s->totdisp * sizeof(float) * 3, "mdisp swap"); s->disps = MEM_calloc_arrayN(s->totdisp, sizeof(float) * 3, "mdisp swap");
return; return;
} }
d = MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap"); d = MEM_calloc_arrayN(s->totdisp, 3 * sizeof(float), "mdisps swap");
for (S = 0; S < corners; S++) for (S = 0; S < corners; S++)
memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float)); memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float));
@@ -578,7 +578,7 @@ static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
for (i = 0; i < count; ++i) { for (i = 0; i < count; ++i) {
if (!d[i].disps) if (!d[i].disps)
d[i].disps = MEM_callocN(sizeof(float) * 3 * d[i].totdisp, "mdisps read"); d[i].disps = MEM_calloc_arrayN(d[i].totdisp, 3 * sizeof(float), "mdisps read");
if (!cdf_read_data(cdf, d[i].totdisp * 3 * sizeof(float), d[i].disps)) { if (!cdf_read_data(cdf, d[i].totdisp * 3 * sizeof(float), d[i].disps)) {
printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp); printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
@@ -1796,7 +1796,7 @@ void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
static int customData_resize(CustomData *data, int amount) static int customData_resize(CustomData *data, int amount)
{ {
CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp) * (data->maxlayer + amount), CustomDataLayer *tmp = MEM_calloc_arrayN((data->maxlayer + amount), sizeof(*tmp),
"CustomData->layers"); "CustomData->layers");
if (!tmp) return 0; if (!tmp) return 0;
@@ -1814,7 +1814,6 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
int totelem, const char *name) int totelem, const char *name)
{ {
const LayerTypeInfo *typeInfo = layerType_getInfo(type); const LayerTypeInfo *typeInfo = layerType_getInfo(type);
const size_t size = (size_t)totelem * typeInfo->size;
int flag = 0, index = data->totlayer; int flag = 0, index = data->totlayer;
void *newlayerdata = NULL; void *newlayerdata = NULL;
@@ -1831,12 +1830,12 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
if ((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) { if ((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
newlayerdata = layerdata; newlayerdata = layerdata;
} }
else if (size > 0) { else if (totelem > 0 && typeInfo->size > 0) {
if (alloctype == CD_DUPLICATE && layerdata) { if (alloctype == CD_DUPLICATE && layerdata) {
newlayerdata = MEM_mallocN(size, layerType_getName(type)); newlayerdata = MEM_malloc_arrayN((size_t)totelem, typeInfo->size, layerType_getName(type));
} }
else { else {
newlayerdata = MEM_callocN(size, layerType_getName(type)); newlayerdata = MEM_calloc_arrayN((size_t)totelem, typeInfo->size, layerType_getName(type));
} }
if (!newlayerdata) if (!newlayerdata)
@@ -1847,7 +1846,7 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
if (typeInfo->copy) if (typeInfo->copy)
typeInfo->copy(layerdata, newlayerdata, totelem); typeInfo->copy(layerdata, newlayerdata, totelem);
else else
memcpy(newlayerdata, layerdata, size); memcpy(newlayerdata, layerdata, (size_t)totelem * typeInfo->size);
} }
else if (alloctype == CD_DEFAULT) { else if (alloctype == CD_DEFAULT) {
if (typeInfo->set_default) if (typeInfo->set_default)
@@ -2038,7 +2037,7 @@ static void *customData_duplicate_referenced_layer_index(CustomData *data, const
const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type); const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
if (typeInfo->copy) { if (typeInfo->copy) {
void *dst_data = MEM_mallocN((size_t)totelem * typeInfo->size, "CD duplicate ref layer"); void *dst_data = MEM_malloc_arrayN((size_t)totelem, typeInfo->size, "CD duplicate ref layer");
typeInfo->copy(layer->data, dst_data, totelem); typeInfo->copy(layer->data, dst_data, totelem);
layer->data = dst_data; layer->data = dst_data;
} }
@@ -2267,7 +2266,7 @@ void CustomData_interp(const CustomData *source, CustomData *dest,
* elements * elements
*/ */
if (count > SOURCE_BUF_SIZE) if (count > SOURCE_BUF_SIZE)
sources = MEM_mallocN(sizeof(*sources) * count, __func__); sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__);
/* interpolates a layer at a time */ /* interpolates a layer at a time */
dest_i = 0; dest_i = 0;
@@ -3122,7 +3121,7 @@ void CustomData_bmesh_interp(
* elements * elements
*/ */
if (count > SOURCE_BUF_SIZE) if (count > SOURCE_BUF_SIZE)
sources = MEM_mallocN(sizeof(*sources) * count, __func__); sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__);
/* interpolates a layer at a time */ /* interpolates a layer at a time */
for (i = 0; i < data->totlayer; ++i) { for (i = 0; i < data->totlayer; ++i) {
@@ -3312,7 +3311,7 @@ void CustomData_file_write_prepare(
else { else {
if (UNLIKELY((size_t)j >= write_layers_size)) { if (UNLIKELY((size_t)j >= write_layers_size)) {
if (write_layers == write_layers_buff) { if (write_layers == write_layers_buff) {
write_layers = MEM_mallocN(sizeof(*write_layers) * (write_layers_size + chunk_size), __func__); write_layers = MEM_malloc_arrayN((write_layers_size + chunk_size), sizeof(*write_layers), __func__);
if (write_layers_buff) { if (write_layers_buff) {
memcpy(write_layers, write_layers_buff, sizeof(*write_layers) * write_layers_size); memcpy(write_layers, write_layers_buff, sizeof(*write_layers) * write_layers_size);
} }
@@ -3980,7 +3979,7 @@ void CustomData_data_transfer(const MeshPairRemap *me_remap, const CustomDataTra
} }
if (data_src) { if (data_src) {
tmp_data_src = MEM_mallocN(sizeof(*tmp_data_src) * tmp_buff_size, __func__); tmp_data_src = MEM_malloc_arrayN(tmp_buff_size, sizeof(*tmp_data_src), __func__);
} }
if (data_type & CD_FAKE) { if (data_type & CD_FAKE) {

View File

@@ -210,9 +210,13 @@ static int cdf_read_header(CDataFile *cdf)
if (fseek(f, offset, SEEK_SET) != 0) if (fseek(f, offset, SEEK_SET) != 0)
return 0; return 0;
cdf->layer = MEM_callocN(sizeof(CDataFileLayer) * header->totlayer, "CDataFileLayer"); cdf->layer = MEM_calloc_arrayN(header->totlayer, sizeof(CDataFileLayer), "CDataFileLayer");
cdf->totlayer = header->totlayer; cdf->totlayer = header->totlayer;
if (!cdf->layer) {
return 0;
}
for (a = 0; a < header->totlayer; a++) { for (a = 0; a < header->totlayer; a++) {
layer = &cdf->layer[a]; layer = &cdf->layer[a];
@@ -429,7 +433,7 @@ CDataFileLayer *cdf_layer_add(CDataFile *cdf, int type, const char *name, size_t
CDataFileLayer *newlayer, *layer; CDataFileLayer *newlayer, *layer;
/* expand array */ /* expand array */
newlayer = MEM_callocN(sizeof(CDataFileLayer) * (cdf->totlayer + 1), "CDataFileLayer"); newlayer = MEM_calloc_arrayN((cdf->totlayer + 1), sizeof(CDataFileLayer), "CDataFileLayer");
memcpy(newlayer, cdf->layer, sizeof(CDataFileLayer) * cdf->totlayer); memcpy(newlayer, cdf->layer, sizeof(CDataFileLayer) * cdf->totlayer);
cdf->layer = newlayer; cdf->layer = newlayer;

View File

@@ -382,7 +382,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect,
nu2->orderv = 1; nu2->orderv = 1;
nu2->flagu = CU_NURB_CYCLIC; nu2->flagu = CU_NURB_CYCLIC;
bp = (BPoint *)MEM_callocN(4 * sizeof(BPoint), "underline_bp"); bp = (BPoint *)MEM_calloc_arrayN(4, sizeof(BPoint), "underline_bp");
copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f); copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f);
copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f); copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f);
@@ -481,7 +481,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha
/* nu2->trim.last = 0; */ /* nu2->trim.last = 0; */
i = nu2->pntsu; i = nu2->pntsu;
bezt2 = (BezTriple *)MEM_mallocN(i * sizeof(BezTriple), "duplichar_bezt2"); bezt2 = (BezTriple *)MEM_malloc_arrayN(i, sizeof(BezTriple), "duplichar_bezt2");
if (bezt2 == NULL) { if (bezt2 == NULL) {
MEM_freeN(nu2); MEM_freeN(nu2);
break; break;
@@ -692,20 +692,26 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas
slen = cu->len_wchar; slen = cu->len_wchar;
/* Create unicode string */ /* Create unicode string */
mem_tmp = MEM_mallocN(((slen + 1) * sizeof(wchar_t)), "convertedmem"); mem_tmp = MEM_malloc_arrayN((slen + 1), sizeof(wchar_t), "convertedmem");
if (!mem_tmp) {
return ok;
}
BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1); BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1);
if (cu->strinfo == NULL) { /* old file */ if (cu->strinfo == NULL) { /* old file */
cu->strinfo = MEM_callocN((slen + 4) * sizeof(CharInfo), "strinfo compat"); cu->strinfo = MEM_calloc_arrayN((slen + 4), sizeof(CharInfo), "strinfo compat");
} }
custrinfo = cu->strinfo; custrinfo = cu->strinfo;
if (!custrinfo) {
return ok;
}
mem = mem_tmp; mem = mem_tmp;
} }
if (cu->tb == NULL) if (cu->tb == NULL)
cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "TextBox compat"); cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBox compat");
if (ef != NULL && ob != NULL) { if (ef != NULL && ob != NULL) {
if (ef->selboxes) if (ef->selboxes)
@@ -713,7 +719,7 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas
if (BKE_vfont_select_get(ob, &selstart, &selend)) { if (BKE_vfont_select_get(ob, &selstart, &selend)) {
ef->selboxes_len = (selend - selstart) + 1; ef->selboxes_len = (selend - selstart) + 1;
ef->selboxes = MEM_callocN(ef->selboxes_len * sizeof(EditFontSelBox), "font selboxes"); ef->selboxes = MEM_calloc_arrayN(ef->selboxes_len, sizeof(EditFontSelBox), "font selboxes");
} }
else { else {
ef->selboxes_len = 0; ef->selboxes_len = 0;
@@ -724,10 +730,10 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas
} }
/* calc offset and rotation of each char */ /* calc offset and rotation of each char */
ct = chartransdata = MEM_callocN((slen + 1) * sizeof(struct CharTrans), "buildtext"); ct = chartransdata = MEM_calloc_arrayN((slen + 1), sizeof(struct CharTrans), "buildtext");
/* We assume the worst case: 1 character per line (is freed at end anyway) */ /* We assume the worst case: 1 character per line (is freed at end anyway) */
lineinfo = MEM_mallocN(sizeof(*lineinfo) * (slen * 2 + 1), "lineinfo"); lineinfo = MEM_malloc_arrayN((slen * 2 + 1), sizeof(*lineinfo), "lineinfo");
linedist = cu->linedist; linedist = cu->linedist;
@@ -1373,12 +1379,12 @@ void BKE_vfont_clipboard_set(const wchar_t *text_buf, const CharInfo *info_buf,
/* clean previous buffers*/ /* clean previous buffers*/
BKE_vfont_clipboard_free(); BKE_vfont_clipboard_free();
text = MEM_mallocN((len + 1) * sizeof(wchar_t), __func__); text = MEM_malloc_arrayN((len + 1), sizeof(wchar_t), __func__);
if (text == NULL) { if (text == NULL) {
return; return;
} }
info = MEM_mallocN(len * sizeof(CharInfo), __func__); info = MEM_malloc_arrayN(len, sizeof(CharInfo), __func__);
if (info == NULL) { if (info == NULL) {
MEM_freeN(text); MEM_freeN(text);
return; return;

View File

@@ -823,7 +823,7 @@ float (*BKE_mesh_orco_verts_get(Object *ob))[3]
float (*vcos)[3] = NULL; float (*vcos)[3] = NULL;
/* Get appropriate vertex coordinates */ /* Get appropriate vertex coordinates */
vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh"); vcos = MEM_calloc_arrayN(me->totvert, sizeof(*vcos), "orco mesh");
mvert = tme->mvert; mvert = tme->mvert;
totvert = min_ii(tme->totvert, me->totvert); totvert = min_ii(tme->totvert, me->totvert);
@@ -1062,7 +1062,7 @@ static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge,
unsigned int e_index = totedge; unsigned int e_index = totedge;
*r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) : *r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) :
MEM_callocN(sizeof(MEdge) * totedge_new, __func__)); MEM_calloc_arrayN(totedge_new, sizeof(MEdge), __func__));
medge += totedge; medge += totedge;
totedge += totedge_new; totedge += totedge_new;
@@ -1182,13 +1182,13 @@ int BKE_mesh_nurbs_displist_to_mdata(
return -1; return -1;
} }
*r_allvert = mvert = MEM_callocN(sizeof(MVert) * totvert, "nurbs_init mvert"); *r_allvert = mvert = MEM_calloc_arrayN(totvert, sizeof(MVert), "nurbs_init mvert");
*r_alledge = medge = MEM_callocN(sizeof(MEdge) * totedge, "nurbs_init medge"); *r_alledge = medge = MEM_calloc_arrayN(totedge, sizeof(MEdge), "nurbs_init medge");
*r_allloop = mloop = MEM_callocN(sizeof(MLoop) * totvlak * 4, "nurbs_init mloop"); // totloop *r_allloop = mloop = MEM_calloc_arrayN(totvlak, 4 * sizeof(MLoop), "nurbs_init mloop"); // totloop
*r_allpoly = mpoly = MEM_callocN(sizeof(MPoly) * totvlak, "nurbs_init mloop"); *r_allpoly = mpoly = MEM_calloc_arrayN(totvlak, sizeof(MPoly), "nurbs_init mloop");
if (r_alluv) if (r_alluv)
*r_alluv = mloopuv = MEM_callocN(sizeof(MLoopUV) * totvlak * 4, "nurbs_init mloopuv"); *r_alluv = mloopuv = MEM_calloc_arrayN(totvlak, 4 * sizeof(MLoopUV), "nurbs_init mloopuv");
/* verts and faces */ /* verts and faces */
vertcount = 0; vertcount = 0;
@@ -1527,7 +1527,7 @@ void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int e
ListBase edges = {NULL, NULL}; ListBase edges = {NULL, NULL};
/* get boundary edges */ /* get boundary edges */
edge_users = MEM_callocN(sizeof(int) * dm_totedge, __func__); edge_users = MEM_calloc_arrayN(dm_totedge, sizeof(int), __func__);
for (i = 0, mp = mpoly; i < dm_totpoly; i++, mp++) { for (i = 0, mp = mpoly; i < dm_totpoly; i++, mp++) {
MLoop *ml = &mloop[mp->loopstart]; MLoop *ml = &mloop[mp->loopstart];
int j; int j;
@@ -1623,7 +1623,7 @@ void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int e
nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0); /* endpoint */ nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0); /* endpoint */
nu->resolu = 12; nu->resolu = 12;
nu->bp = (BPoint *)MEM_callocN(sizeof(BPoint) * totpoly, "bpoints"); nu->bp = (BPoint *)MEM_calloc_arrayN(totpoly, sizeof(BPoint), "bpoints");
/* add points */ /* add points */
vl = polyline.first; vl = polyline.first;
@@ -1779,7 +1779,7 @@ void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth)
float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_numVerts))[3] float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_numVerts))[3]
{ {
int i, numVerts = me->totvert; int i, numVerts = me->totvert;
float (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "vertexcos1"); float (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "vertexcos1");
if (r_numVerts) *r_numVerts = numVerts; if (r_numVerts) *r_numVerts = numVerts;
for (i = 0; i < numVerts; i++) for (i = 0; i < numVerts; i++)
@@ -1915,7 +1915,7 @@ void BKE_mesh_ensure_navmesh(Mesh *me)
int i; int i;
int numFaces = me->totpoly; int numFaces = me->totpoly;
int *recastData; int *recastData;
recastData = (int *)MEM_mallocN(numFaces * sizeof(int), __func__); recastData = (int *)MEM_malloc_arrayN(numFaces, sizeof(int), __func__);
for (i = 0; i < numFaces; i++) { for (i = 0; i < numFaces; i++) {
recastData[i] = i + 1; recastData[i] = i + 1;
} }
@@ -2003,7 +2003,7 @@ void BKE_mesh_mselect_validate(Mesh *me)
return; return;
mselect_src = me->mselect; mselect_src = me->mselect;
mselect_dst = MEM_mallocN(sizeof(MSelect) * (me->totselect), "Mesh selection history"); mselect_dst = MEM_malloc_arrayN((me->totselect), sizeof(MSelect), "Mesh selection history");
for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) { for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
int index = mselect_src[i_src].index; int index = mselect_src[i_src].index;
@@ -2146,7 +2146,7 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac
free_polynors = false; free_polynors = false;
} }
else { else {
polynors = MEM_mallocN(sizeof(float[3]) * mesh->totpoly, __func__); polynors = MEM_malloc_arrayN(mesh->totpoly, sizeof(float[3]), __func__);
BKE_mesh_calc_normals_poly( BKE_mesh_calc_normals_poly(
mesh->mvert, NULL, mesh->totvert, mesh->mvert, NULL, mesh->totvert,
mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false); mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false);

View File

@@ -127,8 +127,8 @@ void BKE_mesh_calc_normals_mapping_ex(
return; return;
} }
if (!pnors) pnors = MEM_callocN(sizeof(float[3]) * (size_t)numPolys, __func__); if (!pnors) pnors = MEM_calloc_arrayN((size_t)numPolys, sizeof(float[3]), __func__);
/* if (!fnors) fnors = MEM_callocN(sizeof(float[3]) * numFaces, "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */ /* if (!fnors) fnors = MEM_calloc_arrayN(numFaces, sizeof(float[3]), "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */
if (only_face_normals == false) { if (only_face_normals == false) {
@@ -306,12 +306,12 @@ void BKE_mesh_calc_normals_poly(
} }
float (*vnors)[3] = r_vertnors; float (*vnors)[3] = r_vertnors;
float (*lnors_weighted)[3] = MEM_mallocN(sizeof(*lnors_weighted) * (size_t)numLoops, __func__); float (*lnors_weighted)[3] = MEM_malloc_arrayN((size_t)numLoops, sizeof(*lnors_weighted), __func__);
bool free_vnors = false; bool free_vnors = false;
/* first go through and calculate normals for all the polys */ /* first go through and calculate normals for all the polys */
if (vnors == NULL) { if (vnors == NULL) {
vnors = MEM_callocN(sizeof(*vnors) * (size_t)numVerts, __func__); vnors = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vnors), __func__);
free_vnors = true; free_vnors = true;
} }
else { else {
@@ -356,10 +356,14 @@ void BKE_mesh_calc_normals_tessface(
const MFace *mfaces, int numFaces, const MFace *mfaces, int numFaces,
float (*r_faceNors)[3]) float (*r_faceNors)[3])
{ {
float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms"); float (*tnorms)[3] = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms");
float (*fnors)[3] = (r_faceNors) ? r_faceNors : MEM_callocN(sizeof(*fnors) * (size_t)numFaces, "meshnormals"); float (*fnors)[3] = (r_faceNors) ? r_faceNors : MEM_calloc_arrayN((size_t)numFaces, sizeof(*fnors), "meshnormals");
int i; int i;
if (!tnorms || !fnors) {
goto cleanup;
}
for (i = 0; i < numFaces; i++) { for (i = 0; i < numFaces; i++) {
const MFace *mf = &mfaces[i]; const MFace *mf = &mfaces[i];
float *f_no = fnors[i]; float *f_no = fnors[i];
@@ -388,6 +392,7 @@ void BKE_mesh_calc_normals_tessface(
normal_float_to_short_v3(mv->no, no); normal_float_to_short_v3(mv->no, no);
} }
cleanup:
MEM_freeN(tnorms); MEM_freeN(tnorms);
if (fnors != r_faceNors) if (fnors != r_faceNors)
@@ -400,10 +405,14 @@ void BKE_mesh_calc_normals_looptri(
const MLoopTri *looptri, int looptri_num, const MLoopTri *looptri, int looptri_num,
float (*r_tri_nors)[3]) float (*r_tri_nors)[3])
{ {
float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms"); float (*tnorms)[3] = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms");
float (*fnors)[3] = (r_tri_nors) ? r_tri_nors : MEM_callocN(sizeof(*fnors) * (size_t)looptri_num, "meshnormals"); float (*fnors)[3] = (r_tri_nors) ? r_tri_nors : MEM_calloc_arrayN((size_t)looptri_num, sizeof(*fnors), "meshnormals");
int i; int i;
if (!tnorms || !fnors) {
goto cleanup;
}
for (i = 0; i < looptri_num; i++) { for (i = 0; i < looptri_num; i++) {
const MLoopTri *lt = &looptri[i]; const MLoopTri *lt = &looptri[i];
float *f_no = fnors[i]; float *f_no = fnors[i];
@@ -434,6 +443,7 @@ void BKE_mesh_calc_normals_looptri(
normal_float_to_short_v3(mv->no, no); normal_float_to_short_v3(mv->no, no);
} }
cleanup:
MEM_freeN(tnorms); MEM_freeN(tnorms);
if (fnors != r_tri_nors) if (fnors != r_tri_nors)
@@ -1174,7 +1184,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common
if (pool) { if (pool) {
if (data_idx == 0) { if (data_idx == 0) {
data_buff = MEM_callocN(sizeof(*data_buff) * LOOP_SPLIT_TASK_BLOCK_SIZE, __func__); data_buff = MEM_calloc_arrayN(LOOP_SPLIT_TASK_BLOCK_SIZE, sizeof(*data_buff), __func__);
} }
data = &data_buff[data_idx]; data = &data_buff[data_idx];
} }
@@ -1304,10 +1314,10 @@ void BKE_mesh_normals_loop_split(
* store the negated value of loop index instead of INDEX_INVALID to retrieve the real value later in code). * store the negated value of loop index instead of INDEX_INVALID to retrieve the real value later in code).
* Note also that lose edges always have both values set to 0! * Note also that lose edges always have both values set to 0!
*/ */
int (*edge_to_loops)[2] = MEM_callocN(sizeof(*edge_to_loops) * (size_t)numEdges, __func__); int (*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__);
/* Simple mapping from a loop to its polygon index. */ /* Simple mapping from a loop to its polygon index. */
int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : MEM_mallocN(sizeof(*loop_to_poly) * (size_t)numLoops, __func__); int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__);
MPoly *mp; MPoly *mp;
int mp_index; int mp_index;
@@ -1461,8 +1471,8 @@ static void mesh_normals_loop_custom_set(
*/ */
MLoopNorSpaceArray lnors_spacearr = {NULL}; MLoopNorSpaceArray lnors_spacearr = {NULL};
BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__); BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__);
float (*lnors)[3] = MEM_callocN(sizeof(*lnors) * (size_t)numLoops, __func__); float (*lnors)[3] = MEM_calloc_arrayN((size_t)numLoops, sizeof(*lnors), __func__);
int *loop_to_poly = MEM_mallocN(sizeof(int) * (size_t)numLoops, __func__); int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(int), __func__);
/* In this case we always consider split nors as ON, and do not want to use angle to define smooth fans! */ /* In this case we always consider split nors as ON, and do not want to use angle to define smooth fans! */
const bool use_split_normals = true; const bool use_split_normals = true;
const float split_angle = (float)M_PI; const float split_angle = (float)M_PI;
@@ -1677,7 +1687,7 @@ void BKE_mesh_normals_loop_to_vertex(
const MLoop *ml; const MLoop *ml;
int i; int i;
int *vert_loops_nbr = MEM_callocN(sizeof(*vert_loops_nbr) * (size_t)numVerts, __func__); int *vert_loops_nbr = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vert_loops_nbr), __func__);
copy_vn_fl((float *)r_vert_clnors, 3 * numVerts, 0.0f); copy_vn_fl((float *)r_vert_clnors, 3 * numVerts, 0.0f);
@@ -2516,9 +2526,9 @@ int BKE_mesh_recalc_tessellation(
/* allocate the length of totfaces, avoid many small reallocs, /* allocate the length of totfaces, avoid many small reallocs,
* if all faces are tri's it will be correct, quads == 2x allocs */ * if all faces are tri's it will be correct, quads == 2x allocs */
/* take care. we are _not_ calloc'ing so be sure to initialize each field */ /* take care. we are _not_ calloc'ing so be sure to initialize each field */
mface_to_poly_map = MEM_mallocN(sizeof(*mface_to_poly_map) * (size_t)looptri_num, __func__); mface_to_poly_map = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*mface_to_poly_map), __func__);
mface = MEM_mallocN(sizeof(*mface) * (size_t)looptri_num, __func__); mface = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*mface), __func__);
lindices = MEM_mallocN(sizeof(*lindices) * (size_t)looptri_num, __func__); lindices = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*lindices), __func__);
mface_index = 0; mface_index = 0;
mp = mpoly; mp = mpoly;
@@ -2898,7 +2908,7 @@ int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata,
const bool hasLNor = CustomData_has_layer(ldata, CD_NORMAL); const bool hasLNor = CustomData_has_layer(ldata, CD_NORMAL);
/* over-alloc, ngons will be skipped */ /* over-alloc, ngons will be skipped */
mface = MEM_mallocN(sizeof(*mface) * (size_t)totpoly, __func__); mface = MEM_malloc_arrayN((size_t)totpoly, sizeof(*mface), __func__);
mpoly = CustomData_get_layer(pdata, CD_MPOLY); mpoly = CustomData_get_layer(pdata, CD_MPOLY);
mloop = CustomData_get_layer(ldata, CD_MLOOP); mloop = CustomData_get_layer(ldata, CD_MLOOP);
@@ -3065,7 +3075,6 @@ static void bm_corners_to_loops_ex(
else { else {
const int side = (int)sqrtf((float)(fd->totdisp / corners)); const int side = (int)sqrtf((float)(fd->totdisp / corners));
const int side_sq = side * side; const int side_sq = side * side;
const size_t disps_size = sizeof(float[3]) * (size_t)side_sq;
for (i = 0; i < tot; i++, disps += side_sq, ld++) { for (i = 0; i < tot; i++, disps += side_sq, ld++) {
ld->totdisp = side_sq; ld->totdisp = side_sq;
@@ -3074,12 +3083,12 @@ static void bm_corners_to_loops_ex(
if (ld->disps) if (ld->disps)
MEM_freeN(ld->disps); MEM_freeN(ld->disps);
ld->disps = MEM_mallocN(disps_size, "converted loop mdisps"); ld->disps = MEM_malloc_arrayN((size_t)side_sq, sizeof(float[3]), "converted loop mdisps");
if (fd->disps) { if (fd->disps) {
memcpy(ld->disps, disps, disps_size); memcpy(ld->disps, disps, (size_t)side_sq * sizeof(float[3]));
} }
else { else {
memset(ld->disps, 0, disps_size); memset(ld->disps, 0, (size_t)side_sq * sizeof(float[3]));
} }
} }
} }
@@ -3141,7 +3150,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
CustomData_free(pdata, totpoly_i); CustomData_free(pdata, totpoly_i);
totpoly = totface_i; totpoly = totface_i;
mpoly = MEM_callocN(sizeof(MPoly) * (size_t)totpoly, "mpoly converted"); mpoly = MEM_calloc_arrayN((size_t)totpoly, sizeof(MPoly), "mpoly converted");
CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, totpoly); CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, totpoly);
numTex = CustomData_number_of_layers(fdata, CD_MTFACE); numTex = CustomData_number_of_layers(fdata, CD_MTFACE);
@@ -3153,7 +3162,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
totloop += mf->v4 ? 4 : 3; totloop += mf->v4 ? 4 : 3;
} }
mloop = MEM_callocN(sizeof(MLoop) * (size_t)totloop, "mloop converted"); mloop = MEM_calloc_arrayN((size_t)totloop, sizeof(MLoop), "mloop converted");
CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop); CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop);
@@ -3552,7 +3561,7 @@ void BKE_mesh_calc_relative_deform(
const MPoly *mp; const MPoly *mp;
int i; int i;
int *vert_accum = MEM_callocN(sizeof(*vert_accum) * (size_t)totvert, __func__); int *vert_accum = MEM_calloc_arrayN((size_t)totvert, sizeof(*vert_accum), __func__);
memset(vert_cos_new, '\0', sizeof(*vert_cos_new) * (size_t)totvert); memset(vert_cos_new, '\0', sizeof(*vert_cos_new) * (size_t)totvert);

View File

@@ -440,7 +440,7 @@ int multiresModifier_reshapeFromDeformMod(const struct EvaluationContext *eval_c
/* Create DerivedMesh for deformation modifier */ /* Create DerivedMesh for deformation modifier */
dm = get_multires_dm(eval_ctx, scene, mmd, ob); dm = get_multires_dm(eval_ctx, scene, mmd, ob);
numVerts = dm->getNumVerts(dm); numVerts = dm->getNumVerts(dm);
deformedVerts = MEM_mallocN(sizeof(float[3]) * numVerts, "multiresReshape_deformVerts"); deformedVerts = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "multiresReshape_deformVerts");
dm->getVertCos(dm, deformedVerts); dm->getVertCos(dm, deformedVerts);
mti->deformVerts(md, eval_ctx, ob, dm, deformedVerts, numVerts, 0); mti->deformVerts(md, eval_ctx, ob, dm, deformedVerts, numVerts, 0);
@@ -533,7 +533,7 @@ static void multires_reallocate_mdisps(int totloop, MDisps *mdisps, int lvl)
/* reallocate displacements to be filled in */ /* reallocate displacements to be filled in */
for (i = 0; i < totloop; ++i) { for (i = 0; i < totloop; ++i) {
int totdisp = multires_grid_tot[lvl]; int totdisp = multires_grid_tot[lvl];
float (*disps)[3] = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps"); float (*disps)[3] = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disps");
if (mdisps[i].disps) if (mdisps[i].disps)
MEM_freeN(mdisps[i].disps); MEM_freeN(mdisps[i].disps);
@@ -597,7 +597,7 @@ static void multires_grid_paint_mask_downsample(GridPaintMask *gpm, int level)
{ {
if (level < gpm->level) { if (level < gpm->level) {
int gridsize = BKE_ccg_gridsize(level); int gridsize = BKE_ccg_gridsize(level);
float *data = MEM_callocN(sizeof(float) * SQUARE(gridsize), float *data = MEM_calloc_arrayN(SQUARE(gridsize), sizeof(float),
"multires_grid_paint_mask_downsample"); "multires_grid_paint_mask_downsample");
int x, y; int x, y;
@@ -642,7 +642,7 @@ static void multires_del_higher(MultiresModifierData *mmd, Object *ob, int lvl)
float (*disps)[3], (*ndisps)[3], (*hdisps)[3]; float (*disps)[3], (*ndisps)[3], (*hdisps)[3];
int totdisp = multires_grid_tot[lvl]; int totdisp = multires_grid_tot[lvl];
disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps"); disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disps");
ndisps = disps; ndisps = disps;
hdisps = mdisp->disps; hdisps = mdisp->disps;
@@ -785,7 +785,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob)
cddm = CDDM_from_mesh(me); cddm = CDDM_from_mesh(me);
pmap = cddm->getPolyMap(ob, cddm); pmap = cddm->getPolyMap(ob, cddm);
origco = MEM_callocN(sizeof(float) * 3 * me->totvert, "multires apply base origco"); origco = MEM_calloc_arrayN(me->totvert, 3 * sizeof(float), "multires apply base origco");
for (i = 0; i < me->totvert; ++i) for (i = 0; i < me->totvert; ++i)
copy_v3_v3(origco[i], me->mvert[i].co); copy_v3_v3(origco[i], me->mvert[i].co);
@@ -825,8 +825,8 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob)
* BKE_mesh_calc_poly_normal_coords() */ * BKE_mesh_calc_poly_normal_coords() */
fake_poly.totloop = p->totloop; fake_poly.totloop = p->totloop;
fake_poly.loopstart = 0; fake_poly.loopstart = 0;
fake_loops = MEM_mallocN(sizeof(MLoop) * p->totloop, "fake_loops"); fake_loops = MEM_malloc_arrayN(p->totloop, sizeof(MLoop), "fake_loops");
fake_co = MEM_mallocN(sizeof(float) * 3 * p->totloop, "fake_co"); fake_co = MEM_malloc_arrayN(p->totloop, 3 * sizeof(float), "fake_co");
for (k = 0; k < p->totloop; ++k) { for (k = 0; k < p->totloop; ++k) {
int vndx = me->mloop[p->loopstart + k].v; int vndx = me->mloop[p->loopstart + k].v;
@@ -923,11 +923,11 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl
lowGridData = lowdm->getGridData(lowdm); lowGridData = lowdm->getGridData(lowdm);
lowdm->getGridKey(lowdm, &lowGridKey); lowdm->getGridKey(lowdm, &lowGridKey);
subGridData = MEM_callocN(sizeof(float *) * numGrids, "subGridData*"); subGridData = MEM_calloc_arrayN(numGrids, sizeof(float *), "subGridData*");
for (i = 0; i < numGrids; ++i) { for (i = 0; i < numGrids; ++i) {
/* backup subsurf grids */ /* backup subsurf grids */
subGridData[i] = MEM_callocN(highGridKey.elem_size * highGridSize * highGridSize, "subGridData"); subGridData[i] = MEM_calloc_arrayN(highGridKey.elem_size, highGridSize * highGridSize, "subGridData");
memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize); memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize);
/* overwrite with current displaced grids */ /* overwrite with current displaced grids */
@@ -1054,7 +1054,7 @@ static void multires_disp_run_cb(
if (gpm->data) { if (gpm->data) {
MEM_freeN(gpm->data); MEM_freeN(gpm->data);
} }
gpm->data = MEM_callocN(sizeof(float) * key->grid_area, "gpm.data"); gpm->data = MEM_calloc_arrayN(key->grid_area, sizeof(float), "gpm.data");
} }
for (y = 0; y < gridSize; y++) { for (y = 0; y < gridSize; y++) {
@@ -1247,12 +1247,12 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm)
BLI_assert(highGridKey.elem_size == lowGridKey.elem_size); BLI_assert(highGridKey.elem_size == lowGridKey.elem_size);
subGridData = MEM_callocN(sizeof(CCGElem *) * numGrids, "subGridData*"); subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
diffGrid = MEM_callocN(lowGridKey.elem_size * lowGridSize * lowGridSize, "diff"); diffGrid = MEM_calloc_arrayN(lowGridKey.elem_size, lowGridSize * lowGridSize, "diff");
for (i = 0; i < numGrids; ++i) { for (i = 0; i < numGrids; ++i) {
/* backup subsurf grids */ /* backup subsurf grids */
subGridData[i] = MEM_callocN(highGridKey.elem_size * highGridSize * highGridSize, "subGridData"); subGridData[i] = MEM_calloc_arrayN(highGridKey.elem_size, highGridSize * highGridSize, "subGridData");
memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize); memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize);
/* write difference of subsurf and displaced low level into high subsurf */ /* write difference of subsurf and displaced low level into high subsurf */
@@ -1363,10 +1363,10 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
gridData = subsurf->getGridData(subsurf); gridData = subsurf->getGridData(subsurf);
subsurf->getGridKey(subsurf, &key); subsurf->getGridKey(subsurf, &key);
subGridData = MEM_callocN(sizeof(CCGElem *) * numGrids, "subGridData*"); subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
for (i = 0; i < numGrids; i++) { for (i = 0; i < numGrids; i++) {
subGridData[i] = MEM_callocN(key.elem_size * gridSize * gridSize, "subGridData"); subGridData[i] = MEM_calloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData");
memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize); memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize);
} }
@@ -1395,7 +1395,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
if (!mdisp->disps) { if (!mdisp->disps) {
mdisp->totdisp = gridSize * gridSize; mdisp->totdisp = gridSize * gridSize;
mdisp->level = totlvl; mdisp->level = totlvl;
mdisp->disps = MEM_callocN(sizeof(float) * 3 * mdisp->totdisp, "disp in multires_set_space"); mdisp->disps = MEM_calloc_arrayN(mdisp->totdisp, 3 * sizeof(float), "disp in multires_set_space");
} }
dispgrid = mdisp->disps; dispgrid = mdisp->disps;
@@ -1510,10 +1510,10 @@ DerivedMesh *multires_make_derived_from_derived(DerivedMesh *dm,
gridData = result->getGridData(result); gridData = result->getGridData(result);
result->getGridKey(result, &key); result->getGridKey(result, &key);
subGridData = MEM_mallocN(sizeof(CCGElem *) * numGrids, "subGridData*"); subGridData = MEM_malloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
for (i = 0; i < numGrids; i++) { for (i = 0; i < numGrids; i++) {
subGridData[i] = MEM_mallocN(key.elem_size * gridSize * gridSize, "subGridData"); subGridData[i] = MEM_malloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData");
memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize); memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize);
} }
@@ -1603,7 +1603,7 @@ static void old_mdisps_convert(MFace *mface, MDisps *mdisp)
int x, y, S; int x, y, S;
float (*disps)[3], (*out)[3], u = 0.0f, v = 0.0f; /* Quite gcc barking. */ float (*disps)[3], (*out)[3], u = 0.0f, v = 0.0f; /* Quite gcc barking. */
disps = MEM_callocN(sizeof(float) * 3 * newtotdisp, "multires disps"); disps = MEM_calloc_arrayN(newtotdisp, 3 * sizeof(float), "multires disps");
out = disps; out = disps;
for (S = 0; S < nvert; S++) { for (S = 0; S < nvert; S++) {
@@ -1650,7 +1650,7 @@ void multires_load_old_250(Mesh *me)
int totdisp = mdisps[i].totdisp / nvert; int totdisp = mdisps[i].totdisp / nvert;
for (j = 0; j < nvert; j++, k++) { for (j = 0; j < nvert; j++, k++) {
mdisps2[k].disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disp in conversion"); mdisps2[k].disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disp in conversion");
mdisps2[k].totdisp = totdisp; mdisps2[k].totdisp = totdisp;
mdisps2[k].level = mdisps[i].level; mdisps2[k].level = mdisps[i].level;
memcpy(mdisps2[k].disps, mdisps[i].disps + totdisp * j, totdisp); memcpy(mdisps2[k].disps, mdisps[i].disps + totdisp * j, totdisp);
@@ -1710,8 +1710,8 @@ static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const Mult
int i, j; int i, j;
IndexNode *node = NULL; IndexNode *node = NULL;
(*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert face map"); (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert face map");
(*mem) = MEM_callocN(sizeof(IndexNode) * totface * 4, "vert face map mem"); (*mem) = MEM_calloc_arrayN(totface, 4 * sizeof(IndexNode), "vert face map mem");
node = *mem; node = *mem;
/* Find the users */ /* Find the users */
@@ -1729,8 +1729,8 @@ static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const Mult
int i, j; int i, j;
IndexNode *node = NULL; IndexNode *node = NULL;
(*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert edge map"); (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert edge map");
(*mem) = MEM_callocN(sizeof(IndexNode) * totedge * 2, "vert edge map mem"); (*mem) = MEM_calloc_arrayN(totedge, 2 * sizeof(IndexNode), "vert edge map mem");
node = *mem; node = *mem;
/* Find the users */ /* Find the users */
@@ -1912,7 +1912,11 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl)
vsrc = mr->verts; vsrc = mr->verts;
vdst = dm->getVertArray(dm); vdst = dm->getVertArray(dm);
totvert = (unsigned int)dm->getNumVerts(dm); totvert = (unsigned int)dm->getNumVerts(dm);
vvmap = MEM_callocN(sizeof(int) * totvert, "multires vvmap"); vvmap = MEM_calloc_arrayN(totvert, sizeof(int), "multires vvmap");
if (!vvmap) {
return;
}
lvl1 = mr->levels.first; lvl1 = mr->levels.first;
/* Load base verts */ /* Load base verts */
@@ -1997,10 +2001,10 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl)
} }
/* calculate vert to edge/face maps for each level (except the last) */ /* calculate vert to edge/face maps for each level (except the last) */
fmap = MEM_callocN(sizeof(ListBase *) * (mr->level_count - 1), "multires fmap"); fmap = MEM_calloc_arrayN((mr->level_count - 1), sizeof(ListBase *), "multires fmap");
emap = MEM_callocN(sizeof(ListBase *) * (mr->level_count - 1), "multires emap"); emap = MEM_calloc_arrayN((mr->level_count - 1), sizeof(ListBase *), "multires emap");
fmem = MEM_callocN(sizeof(IndexNode *) * (mr->level_count - 1), "multires fmem"); fmem = MEM_calloc_arrayN((mr->level_count - 1), sizeof(IndexNode *), "multires fmem");
emem = MEM_callocN(sizeof(IndexNode *) * (mr->level_count - 1), "multires emem"); emem = MEM_calloc_arrayN((mr->level_count - 1), sizeof(IndexNode *), "multires emem");
lvl = lvl1; lvl = lvl1;
for (i = 0; i < (unsigned int)mr->level_count - 1; ++i) { for (i = 0; i < (unsigned int)mr->level_count - 1; ++i) {
create_old_vert_face_map(fmap + i, fmem + i, lvl->faces, lvl->totvert, lvl->totface); create_old_vert_face_map(fmap + i, fmem + i, lvl->faces, lvl->totvert, lvl->totface);
@@ -2302,7 +2306,7 @@ static void multires_apply_smat(const struct EvaluationContext *eval_ctx, Scene
cddm = mesh_get_derived_deform(eval_ctx, scene, ob, CD_MASK_BAREMESH); cddm = mesh_get_derived_deform(eval_ctx, scene, ob, CD_MASK_BAREMESH);
totvert = cddm->getNumVerts(cddm); totvert = cddm->getNumVerts(cddm);
vertCos = MEM_mallocN(sizeof(*vertCos) * totvert, "multiresScale vertCos"); vertCos = MEM_malloc_arrayN(totvert, sizeof(*vertCos), "multiresScale vertCos");
cddm->getVertCos(cddm, vertCos); cddm->getVertCos(cddm, vertCos);
for (i = 0; i < totvert; i++) for (i = 0; i < totvert; i++)
mul_m3_v3(smat, vertCos[i]); mul_m3_v3(smat, vertCos[i]);
@@ -2410,7 +2414,7 @@ void multires_topology_changed(Mesh *me)
if (!mdisp->totdisp || !mdisp->disps) { if (!mdisp->totdisp || !mdisp->disps) {
if (grid) { if (grid) {
mdisp->totdisp = grid; mdisp->totdisp = grid;
mdisp->disps = MEM_callocN(3 * mdisp->totdisp * sizeof(float), "mdisp topology"); mdisp->disps = MEM_calloc_arrayN(3 * sizeof(float), mdisp->totdisp, "mdisp topology");
} }
continue; continue;

View File

@@ -555,7 +555,8 @@ void psys_free_pdd(ParticleSystem *psys)
psys->pdd->vedata = NULL; psys->pdd->vedata = NULL;
psys->pdd->totpoint = 0; psys->pdd->totpoint = 0;
psys->pdd->tot_vec_size = 0; psys->pdd->totpart = 0;
psys->pdd->partsize = 0;
} }
} }
/* free everything */ /* free everything */

View File

@@ -75,6 +75,6 @@ enum {
ENDB = BLEND_MAKE_ID('E', 'N', 'D', 'B'), ENDB = BLEND_MAKE_ID('E', 'N', 'D', 'B'),
}; };
#define BLEN_THUMB_MEMSIZE_FILE(_x, _y) (sizeof(int) * (size_t)(2 + (_x) * (_y))) #define BLEN_THUMB_MEMSIZE_FILE(_x, _y) (sizeof(int) * (2 + (size_t)(_x) * (size_t)(_y)))
#endif /* __BLO_BLEND_DEFS_H__ */ #endif /* __BLO_BLEND_DEFS_H__ */

View File

@@ -304,7 +304,7 @@ static OldNewMap *oldnewmap_new(void)
OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap"); OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
onm->entriessize = 1024; onm->entriessize = 1024;
onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries"); onm->entries = MEM_malloc_arrayN(onm->entriessize, sizeof(*onm->entries), "OldNewMap.entries");
return onm; return onm;
} }
@@ -551,7 +551,7 @@ void blo_split_main(ListBase *mainlist, Main *main)
/* (Library.temp_index -> Main), lookup table */ /* (Library.temp_index -> Main), lookup table */
const unsigned int lib_main_array_len = BLI_listbase_count(&main->library); const unsigned int lib_main_array_len = BLI_listbase_count(&main->library);
Main **lib_main_array = MEM_mallocN(lib_main_array_len * sizeof(*lib_main_array), __func__); Main **lib_main_array = MEM_malloc_arrayN(lib_main_array_len, sizeof(*lib_main_array), __func__);
int i = 0; int i = 0;
for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) { for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) {
@@ -997,7 +997,13 @@ static int *read_file_thumbnail(FileData *fd)
BLI_endian_switch_int32(&data[1]); BLI_endian_switch_int32(&data[1]);
} }
if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(data[0], data[1])) { int width = data[0];
int height = data[1];
if (!BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
break;
}
if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(width, height)) {
break; break;
} }
@@ -1436,23 +1442,28 @@ bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, cha
BlendThumbnail *BLO_thumbnail_from_file(const char *filepath) BlendThumbnail *BLO_thumbnail_from_file(const char *filepath)
{ {
FileData *fd; FileData *fd;
BlendThumbnail *data; BlendThumbnail *data = NULL;
int *fd_data; int *fd_data;
fd = blo_openblenderfile_minimal(filepath); fd = blo_openblenderfile_minimal(filepath);
fd_data = fd ? read_file_thumbnail(fd) : NULL; fd_data = fd ? read_file_thumbnail(fd) : NULL;
if (fd_data) { if (fd_data) {
const size_t sz = BLEN_THUMB_MEMSIZE(fd_data[0], fd_data[1]); int width = fd_data[0];
int height = fd_data[1];
/* Protect against buffer overflow vulnerability. */
if (BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
const size_t sz = BLEN_THUMB_MEMSIZE(width, height);
data = MEM_mallocN(sz, __func__); data = MEM_mallocN(sz, __func__);
BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(fd_data[0], fd_data[1]) - (sizeof(*fd_data) * 2))); if (data) {
data->width = fd_data[0]; BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(width, height) - (sizeof(*fd_data) * 2)));
data->height = fd_data[1]; data->width = width;
data->height = height;
memcpy(data->rect, &fd_data[2], sz - sizeof(*data)); memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
} }
else { }
data = NULL;
} }
blo_freefiledata(fd); blo_freefiledata(fd);
@@ -1998,7 +2009,7 @@ static void test_pointer_array(FileData *fd, void **mat)
len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen; len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) { if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
ipoin=imat= MEM_mallocN(len * 4, "newmatar"); ipoin=imat= MEM_malloc_arrayN(len, 4, "newmatar");
lpoin= *mat; lpoin= *mat;
while (len-- > 0) { while (len-- > 0) {
@@ -2013,7 +2024,7 @@ static void test_pointer_array(FileData *fd, void **mat)
} }
if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) { if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
lpoin = lmat = MEM_mallocN(len * 8, "newmatar"); lpoin = lmat = MEM_malloc_arrayN(len, 8, "newmatar");
ipoin = *mat; ipoin = *mat;
while (len-- > 0) { while (len-- > 0) {
@@ -4000,6 +4011,9 @@ static void direct_link_curve(FileData *fd, Curve *cu)
cu->adt= newdataadr(fd, cu->adt); cu->adt= newdataadr(fd, cu->adt);
direct_link_animdata(fd, cu->adt); direct_link_animdata(fd, cu->adt);
/* Protect against integer overflow vulnerability. */
CLAMP(cu->len_wchar, 0, INT_MAX - 4);
cu->mat = newdataadr(fd, cu->mat); cu->mat = newdataadr(fd, cu->mat);
test_pointer_array(fd, (void **)&cu->mat); test_pointer_array(fd, (void **)&cu->mat);
cu->str = newdataadr(fd, cu->str); cu->str = newdataadr(fd, cu->str);
@@ -4012,7 +4026,7 @@ static void direct_link_curve(FileData *fd, Curve *cu)
else { else {
cu->nurb.first=cu->nurb.last= NULL; cu->nurb.first=cu->nurb.last= NULL;
tb = MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread"); tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBoxread");
if (cu->tb) { if (cu->tb) {
memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox)); memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
MEM_freeN(cu->tb); MEM_freeN(cu->tb);
@@ -4415,6 +4429,9 @@ static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
for (a = 0; a < MAX_MTEX; a++) { for (a = 0; a < MAX_MTEX; a++) {
part->mtex[a] = newdataadr(fd, part->mtex[a]); part->mtex[a] = newdataadr(fd, part->mtex[a]);
} }
/* Protect against integer overflow vulnerability. */
CLAMP(part->trail_count, 1, 100000);
} }
static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles) static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
@@ -5362,9 +5379,9 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
collmd->xnew = newdataadr(fd, collmd->xnew); collmd->xnew = newdataadr(fd, collmd->xnew);
collmd->mfaces = newdataadr(fd, collmd->mfaces); collmd->mfaces = newdataadr(fd, collmd->mfaces);
collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts, "current_x"); collmd->current_x = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_x");
collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts, "current_xnew"); collmd->current_xnew = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_xnew");
collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts, "current_v"); collmd->current_v = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_v");
#endif #endif
collmd->x = NULL; collmd->x = NULL;
@@ -8491,7 +8508,7 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
id = read_struct(fd, bhead, "lib block"); id = read_struct(fd, bhead, "lib block");
if (id) { if (id) {
const short idcode = (bhead->code == ID_ID) ? GS(id->name) : bhead->code; const short idcode = GS(id->name);
/* do after read_struct, for dna reconstruct */ /* do after read_struct, for dna reconstruct */
lb = which_libbase(main, idcode); lb = which_libbase(main, idcode);
if (lb) { if (lb) {
@@ -8928,16 +8945,22 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
const int *data = read_file_thumbnail(fd); const int *data = read_file_thumbnail(fd);
if (data) { if (data) {
const size_t sz = BLEN_THUMB_MEMSIZE(data[0], data[1]); int width = data[0];
int height = data[1];
/* Protect against buffer overflow vulnerability. */
if (BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
const size_t sz = BLEN_THUMB_MEMSIZE(width, height);
bfd->main->blen_thumb = MEM_mallocN(sz, __func__); bfd->main->blen_thumb = MEM_mallocN(sz, __func__);
BLI_assert((sz - sizeof(*bfd->main->blen_thumb)) == BLI_assert((sz - sizeof(*bfd->main->blen_thumb)) ==
(BLEN_THUMB_MEMSIZE_FILE(data[0], data[1]) - (sizeof(*data) * 2))); (BLEN_THUMB_MEMSIZE_FILE(width, height) - (sizeof(*data) * 2)));
bfd->main->blen_thumb->width = data[0]; bfd->main->blen_thumb->width = width;
bfd->main->blen_thumb->height = data[1]; bfd->main->blen_thumb->height = height;
memcpy(bfd->main->blen_thumb->rect, &data[2], sz - sizeof(*bfd->main->blen_thumb)); memcpy(bfd->main->blen_thumb->rect, &data[2], sz - sizeof(*bfd->main->blen_thumb));
} }
} }
}
while (bhead) { while (bhead) {
switch (bhead->code) { switch (bhead->code) {
@@ -9056,7 +9079,7 @@ static void sort_bhead_old_map(FileData *fd)
fd->tot_bheadmap = tot; fd->tot_bheadmap = tot;
if (tot == 0) return; if (tot == 0) return;
bhs = fd->bheadmap = MEM_mallocN(tot * sizeof(struct BHeadSort), "BHeadSort"); bhs = fd->bheadmap = MEM_malloc_arrayN(tot, sizeof(struct BHeadSort), "BHeadSort");
for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead), bhs++) { for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead), bhs++) {
bhs->bhead = bhead; bhs->bhead = bhead;

View File

@@ -951,7 +951,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
if (ob->totcol && ob->matbits == NULL) { if (ob->totcol && ob->matbits == NULL) {
int a; int a;
ob->matbits = MEM_callocN(sizeof(char)*ob->totcol, "ob->matbits"); ob->matbits = MEM_calloc_arrayN(ob->totcol, sizeof(char), "ob->matbits");
for (a = 0; a < ob->totcol; a++) for (a = 0; a < ob->totcol; a++)
ob->matbits[a] = (ob->colbits & (1<<a)) != 0; ob->matbits[a] = (ob->colbits & (1<<a)) != 0;
} }

View File

@@ -113,7 +113,7 @@ static void vcol_to_fcol(Mesh *me)
if (me->totface == 0 || me->mcol == NULL) if (me->totface == 0 || me->mcol == NULL)
return; return;
mcoln = mcolmain = MEM_mallocN(4*sizeof(int)*me->totface, "mcoln"); mcoln = mcolmain = MEM_malloc_arrayN(me->totface, 4 * sizeof(int), "mcoln");
mcol = (unsigned int *)me->mcol; mcol = (unsigned int *)me->mcol;
mface = me->mface; mface = me->mface;
for (a = me->totface; a > 0; a--, mface++) { for (a = me->totface; a > 0; a--, mface++) {

View File

@@ -213,7 +213,7 @@ bool DepsgraphRelationBuilder::is_same_shapekey_dependency(
return false; return false;
} }
/* Check if this is actually a shape key datablock. */ /* Check if this is actually a shape key datablock. */
if (GS(op_from->owner->owner->id->name) != ID_KE) { if (GS(op_from->owner->owner->id_orig->name) != ID_KE) {
return false; return false;
} }
/* Different key data blocks. */ /* Different key data blocks. */

View File

@@ -762,7 +762,15 @@ static int loopcut_modal(bContext *C, wmOperator *op, const wmEvent *event)
handled = true; handled = true;
break; break;
case MOUSEMOVE: /* mouse moved somewhere to select another loop */ case MOUSEMOVE: /* mouse moved somewhere to select another loop */
if (!has_numinput) {
/* This is normally disabled for all modal operators.
* This is an exception since mouse movement doesn't relate to numeric input.
*
* If numeric input changes we'll need to add this back see: D2973 */
#if 0
if (!has_numinput)
#endif
{
lcd->vc.mval[0] = event->mval[0]; lcd->vc.mval[0] = event->mval[0];
lcd->vc.mval[1] = event->mval[1]; lcd->vc.mval[1] = event->mval[1];
loopcut_mouse_move(&eval_ctx, lcd, (int)lcd->cuts); loopcut_mouse_move(&eval_ctx, lcd, (int)lcd->cuts);

View File

@@ -6096,46 +6096,46 @@ static void draw_new_particle_system(
/* 4. */ /* 4. */
if (draw_as && ELEM(draw_as, PART_DRAW_PATH, PART_DRAW_CIRC) == 0) { if (draw_as && ELEM(draw_as, PART_DRAW_PATH, PART_DRAW_CIRC) == 0) {
int tot_vec_size = (totpart + totchild) * 3 * sizeof(float); int partsize = 3 * sizeof(float);
int create_ndata = 0; int create_ndata = 0;
if (!pdd) if (!pdd)
pdd = psys->pdd = MEM_callocN(sizeof(ParticleDrawData), "ParticleDrawData"); pdd = psys->pdd = MEM_callocN(sizeof(ParticleDrawData), "ParticleDrawData");
if (part->draw_as == PART_DRAW_REND && part->trail_count > 1) { if (part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
tot_vec_size *= part->trail_count; partsize *= part->trail_count;
psys_make_temp_pointcache(ob, psys); psys_make_temp_pointcache(ob, psys);
} }
switch (draw_as) { switch (draw_as) {
case PART_DRAW_AXIS: case PART_DRAW_AXIS:
case PART_DRAW_CROSS: case PART_DRAW_CROSS:
tot_vec_size *= 6; partsize *= 6;
if (draw_as != PART_DRAW_CROSS) if (draw_as != PART_DRAW_CROSS)
create_cdata = 1; create_cdata = 1;
break; break;
case PART_DRAW_LINE: case PART_DRAW_LINE:
tot_vec_size *= 2; partsize *= 2;
break; break;
case PART_DRAW_BB: case PART_DRAW_BB:
tot_vec_size *= 6; /* New OGL only understands tris, no choice here. */ partsize *= 6; /* New OGL only understands tris, no choice here. */
create_ndata = 1; create_ndata = 1;
break; break;
} }
if (pdd->tot_vec_size != tot_vec_size) if (pdd->totpart != totpart + totchild || pdd->partsize != partsize)
psys_free_pdd(psys); psys_free_pdd(psys);
if (!pdd->vdata) if (!pdd->vdata)
pdd->vdata = MEM_callocN(tot_vec_size, "particle_vdata"); pdd->vdata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_vdata");
if (create_cdata && !pdd->cdata) if (create_cdata && !pdd->cdata)
pdd->cdata = MEM_callocN(tot_vec_size, "particle_cdata"); pdd->cdata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_cdata");
if (create_ndata && !pdd->ndata) if (create_ndata && !pdd->ndata)
pdd->ndata = MEM_callocN(tot_vec_size, "particle_ndata"); pdd->ndata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_ndata");
if (part->draw & PART_DRAW_VEL && draw_as != PART_DRAW_LINE) { if (part->draw & PART_DRAW_VEL && draw_as != PART_DRAW_LINE) {
if (!pdd->vedata) if (!pdd->vedata)
pdd->vedata = MEM_callocN(2 * (totpart + totchild) * 3 * sizeof(float), "particle_vedata"); pdd->vedata = MEM_calloc_arrayN(totpart + totchild, 2 * 3 * sizeof(float), "particle_vedata");
need_v = 1; need_v = 1;
} }
@@ -6149,7 +6149,8 @@ static void draw_new_particle_system(
pdd->ved = pdd->vedata; pdd->ved = pdd->vedata;
pdd->cd = pdd->cdata; pdd->cd = pdd->cdata;
pdd->nd = pdd->ndata; pdd->nd = pdd->ndata;
pdd->tot_vec_size = tot_vec_size; pdd->totpart = totpart + totchild;
pdd->partsize = partsize;
} }
else if (psys->pdd) { else if (psys->pdd) {
psys_free_pdd(psys); psys_free_pdd(psys);
@@ -6628,7 +6629,7 @@ static void draw_ptcache_edit(Scene *scene, View3D *v3d, PTCacheEdit *edit)
const int totkeys = (*edit->pathcache)->segments + 1; const int totkeys = (*edit->pathcache)->segments + 1;
glEnable(GL_BLEND); glEnable(GL_BLEND);
float *pathcol = MEM_callocN(totkeys * 4 * sizeof(float), "particle path color data"); float *pathcol = MEM_calloc_arrayN(totkeys, 4 * sizeof(float), "particle path color data");
if (pset->brushtype == PE_BRUSH_WEIGHT) if (pset->brushtype == PE_BRUSH_WEIGHT)
glLineWidth(2.0f); glLineWidth(2.0f);
@@ -6705,8 +6706,8 @@ static void draw_ptcache_edit(Scene *scene, View3D *v3d, PTCacheEdit *edit)
if (totkeys_visible) { if (totkeys_visible) {
if (edit->points && !(edit->points->keys->flag & PEK_USE_WCO)) if (edit->points && !(edit->points->keys->flag & PEK_USE_WCO))
pd = pdata = MEM_callocN(totkeys_visible * 3 * sizeof(float), "particle edit point data"); pd = pdata = MEM_calloc_arrayN(totkeys_visible, 3 * sizeof(float), "particle edit point data");
cd = cdata = MEM_callocN(totkeys_visible * (timed ? 4 : 3) * sizeof(float), "particle edit color data"); cd = cdata = MEM_calloc_arrayN(totkeys_visible, (timed ? 4 : 3) * sizeof(float), "particle edit color data");
} }
for (i = 0, point = edit->points; i < totpoint; i++, point++) { for (i = 0, point = edit->points; i < totpoint; i++, point++) {

View File

@@ -583,6 +583,12 @@ bool IMB_metadata_change_field(struct ImBuf *img, const char *key, const char *f
void IMB_metadata_copy(struct ImBuf *dimb, struct ImBuf *simb); void IMB_metadata_copy(struct ImBuf *dimb, struct ImBuf *simb);
/* exported for image tools in blender, to quickly allocate 32 bits rect */ /* exported for image tools in blender, to quickly allocate 32 bits rect */
void *imb_alloc_pixels(unsigned int x,
unsigned int y,
unsigned int channels,
size_t typesize,
const char *name);
bool imb_addrectImBuf(struct ImBuf *ibuf); bool imb_addrectImBuf(struct ImBuf *ibuf);
void imb_freerectImBuf(struct ImBuf *ibuf); void imb_freerectImBuf(struct ImBuf *ibuf);

View File

@@ -265,15 +265,11 @@ ImBuf *IMB_makeSingleUser(ImBuf *ibuf)
bool addzbufImBuf(ImBuf *ibuf) bool addzbufImBuf(ImBuf *ibuf)
{ {
size_t size;
if (ibuf == NULL) return false; if (ibuf == NULL) return false;
IMB_freezbufImBuf(ibuf); IMB_freezbufImBuf(ibuf);
size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(unsigned int); if ((ibuf->zbuf = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(unsigned int), __func__))) {
if ((ibuf->zbuf = MEM_mapallocN(size, __func__))) {
ibuf->mall |= IB_zbuf; ibuf->mall |= IB_zbuf;
ibuf->flags |= IB_zbuf; ibuf->flags |= IB_zbuf;
return true; return true;
@@ -284,15 +280,11 @@ bool addzbufImBuf(ImBuf *ibuf)
bool addzbuffloatImBuf(ImBuf *ibuf) bool addzbuffloatImBuf(ImBuf *ibuf)
{ {
size_t size;
if (ibuf == NULL) return false; if (ibuf == NULL) return false;
IMB_freezbuffloatImBuf(ibuf); IMB_freezbuffloatImBuf(ibuf);
size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(float); if ((ibuf->zbuf_float = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(float), __func__))) {
if ((ibuf->zbuf_float = MEM_mapallocN(size, __func__))) {
ibuf->mall |= IB_zbuffloat; ibuf->mall |= IB_zbuffloat;
ibuf->flags |= IB_zbuffloat; ibuf->flags |= IB_zbuffloat;
return true; return true;
@@ -361,19 +353,31 @@ bool imb_enlargeencodedbufferImBuf(ImBuf *ibuf)
return true; return true;
} }
void *imb_alloc_pixels(unsigned int x,
unsigned int y,
unsigned int channels,
size_t typesize,
const char *name)
{
/* Protect against buffer overflow vulnerabilities from files specifying
* a width and height that overflow and alloc too little memory. */
if (!((uint64_t)x * (uint64_t)y < (SIZE_MAX / (channels * typesize)))) {
return NULL;
}
size_t size = (size_t)x * (size_t)y * (size_t)channels * typesize;
return MEM_mapallocN(size, name);
}
bool imb_addrectfloatImBuf(ImBuf *ibuf) bool imb_addrectfloatImBuf(ImBuf *ibuf)
{ {
size_t size;
if (ibuf == NULL) return false; if (ibuf == NULL) return false;
if (ibuf->rect_float) if (ibuf->rect_float)
imb_freerectfloatImBuf(ibuf); /* frees mipmap too, hrm */ imb_freerectfloatImBuf(ibuf); /* frees mipmap too, hrm */
size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(float[4]);
ibuf->channels = 4; ibuf->channels = 4;
if ((ibuf->rect_float = MEM_mapallocN(size, __func__))) { if ((ibuf->rect_float = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(float), __func__))) {
ibuf->mall |= IB_rectfloat; ibuf->mall |= IB_rectfloat;
ibuf->flags |= IB_rectfloat; ibuf->flags |= IB_rectfloat;
return true; return true;
@@ -385,8 +389,6 @@ bool imb_addrectfloatImBuf(ImBuf *ibuf)
/* question; why also add zbuf? */ /* question; why also add zbuf? */
bool imb_addrectImBuf(ImBuf *ibuf) bool imb_addrectImBuf(ImBuf *ibuf)
{ {
size_t size;
if (ibuf == NULL) return false; if (ibuf == NULL) return false;
/* don't call imb_freerectImBuf, it frees mipmaps, this call is used only too give float buffers display */ /* don't call imb_freerectImBuf, it frees mipmaps, this call is used only too give float buffers display */
@@ -394,9 +396,7 @@ bool imb_addrectImBuf(ImBuf *ibuf)
MEM_freeN(ibuf->rect); MEM_freeN(ibuf->rect);
ibuf->rect = NULL; ibuf->rect = NULL;
size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(unsigned int); if ((ibuf->rect = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(unsigned char), __func__))) {
if ((ibuf->rect = MEM_mapallocN(size, __func__))) {
ibuf->mall |= IB_rect; ibuf->mall |= IB_rect;
ibuf->flags |= IB_rect; ibuf->flags |= IB_rect;
if (ibuf->planes > 32) { if (ibuf->planes > 32) {

View File

@@ -124,7 +124,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
{ {
struct ImBuf *ibuf = NULL; struct ImBuf *ibuf = NULL;
BMPINFOHEADER bmi; BMPINFOHEADER bmi;
int x, y, depth, ibuf_depth, skip, i, j; int x, y, depth, ibuf_depth, skip;
const unsigned char *bmp; const unsigned char *bmp;
unsigned char *rect; unsigned char *rect;
unsigned short col; unsigned short col;
@@ -179,13 +179,17 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
} }
else { else {
ibuf = IMB_allocImBuf(x, y, ibuf_depth, IB_rect); ibuf = IMB_allocImBuf(x, y, ibuf_depth, IB_rect);
if (!ibuf) {
return NULL;
}
rect = (unsigned char *) ibuf->rect; rect = (unsigned char *) ibuf->rect;
if (depth <= 8) { if (depth <= 8) {
const int rowsize = (depth * x + 31) / 32 * 4; const int rowsize = (depth * x + 31) / 32 * 4;
const char (*palette)[4] = (void *)(mem + skip); const char (*palette)[4] = (void *)(mem + skip);
const int startmask = ((1 << depth) - 1) << 8; const int startmask = ((1 << depth) - 1) << 8;
for (i = y; i > 0; i--) { for (size_t i = y; i > 0; i--) {
int index; int index;
int bitoffs = 8; int bitoffs = 8;
int bitmask = startmask; int bitmask = startmask;
@@ -194,7 +198,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
if (top_to_bottom) { if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x]; rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
} }
for (j = x; j > 0; j--) { for (size_t j = x; j > 0; j--) {
bitoffs -= depth; bitoffs -= depth;
bitmask >>= depth; bitmask >>= depth;
index = (bmp[0] & bitmask) >> bitoffs; index = (bmp[0] & bitmask) >> bitoffs;
@@ -219,11 +223,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
} }
} }
else if (depth == 16) { else if (depth == 16) {
for (i = y; i > 0; i--) { for (size_t i = y; i > 0; i--) {
if (top_to_bottom) { if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x]; rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
} }
for (j = x; j > 0; j--) { for (size_t j = x; j > 0; j--) {
col = bmp[0] + (bmp[1] << 8); col = bmp[0] + (bmp[1] << 8);
rect[0] = ((col >> 10) & 0x1f) << 3; rect[0] = ((col >> 10) & 0x1f) << 3;
rect[1] = ((col >> 5) & 0x1f) << 3; rect[1] = ((col >> 5) & 0x1f) << 3;
@@ -236,11 +240,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
} }
else if (depth == 24) { else if (depth == 24) {
const int x_pad = x % 4; const int x_pad = x % 4;
for (i = y; i > 0; i--) { for (size_t i = y; i > 0; i--) {
if (top_to_bottom) { if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x]; rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
} }
for (j = x; j > 0; j--) { for (size_t j = x; j > 0; j--) {
rect[0] = bmp[2]; rect[0] = bmp[2];
rect[1] = bmp[1]; rect[1] = bmp[1];
rect[2] = bmp[0]; rect[2] = bmp[0];
@@ -253,11 +257,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
} }
} }
else if (depth == 32) { else if (depth == 32) {
for (i = y; i > 0; i--) { for (size_t i = y; i > 0; i--) {
if (top_to_bottom) { if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x]; rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
} }
for (j = x; j > 0; j--) { for (size_t j = x; j > 0; j--) {
rect[0] = bmp[2]; rect[0] = bmp[2];
rect[1] = bmp[1]; rect[1] = bmp[1];
rect[2] = bmp[0]; rect[2] = bmp[0];
@@ -299,7 +303,7 @@ static int putShortLSB(unsigned short us, FILE *ofile)
int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags) int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags)
{ {
BMPINFOHEADER infoheader; BMPINFOHEADER infoheader;
int bytesize, extrabytes, x, y, t, ptr; size_t bytesize, extrabytes, ptr;
uchar *data; uchar *data;
FILE *ofile; FILE *ofile;
@@ -331,15 +335,15 @@ int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags)
putIntLSB(0, ofile); putIntLSB(0, ofile);
/* Need to write out padded image data in bgr format */ /* Need to write out padded image data in bgr format */
for (y = 0; y < ibuf->y; y++) { for (size_t y = 0; y < ibuf->y; y++) {
for (x = 0; x < ibuf->x; x++) { for (size_t x = 0; x < ibuf->x; x++) {
ptr = (x + y * ibuf->x) * 4; ptr = (x + y * ibuf->x) * 4;
if (putc(data[ptr + 2], ofile) == EOF) return 0; if (putc(data[ptr + 2], ofile) == EOF) return 0;
if (putc(data[ptr + 1], ofile) == EOF) return 0; if (putc(data[ptr + 1], ofile) == EOF) return 0;
if (putc(data[ptr], ofile) == EOF) return 0; if (putc(data[ptr], ofile) == EOF) return 0;
} }
/* add padding here */ /* add padding here */
for (t = 0; t < extrabytes; t++) { for (size_t t = 0; t < extrabytes; t++) {
if (putc(0, ofile) == EOF) return 0; if (putc(0, ofile) == EOF) return 0;
} }
} }

View File

@@ -193,7 +193,8 @@ LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t buf
dpx->srcFormat = format_DPX; dpx->srcFormat = format_DPX;
dpx->numElements = swap_ushort(header.imageHeader.elements_per_image, dpx->isMSB); dpx->numElements = swap_ushort(header.imageHeader.elements_per_image, dpx->isMSB);
if (dpx->numElements == 0) { size_t max_elements = sizeof(header.imageHeader.element)/sizeof(header.imageHeader.element[0]);
if (dpx->numElements == 0 || dpx->numElements >= max_elements) {
if (verbose) printf("DPX: Wrong number of elements: %d\n", dpx->numElements); if (verbose) printf("DPX: Wrong number of elements: %d\n", dpx->numElements);
logImageClose(dpx); logImageClose(dpx);
return NULL; return NULL;

View File

@@ -38,6 +38,8 @@
#include "BLI_fileops.h" #include "BLI_fileops.h"
#include "BLI_utildefines.h" #include "BLI_utildefines.h"
#include "IMB_imbuf.h"
#include "MEM_guardedalloc.h" #include "MEM_guardedalloc.h"
/* /*
@@ -162,7 +164,7 @@ void logImageGetSize(LogImageFile *logImage, int *width, int *height, int *depth
* Helper * Helper
*/ */
unsigned int getRowLength(int width, LogImageElement logElement) size_t getRowLength(size_t width, LogImageElement logElement)
{ {
/* return the row length in bytes according to width and packing method */ /* return the row length in bytes according to width and packing method */
switch (logElement.bitsPerSample) { switch (logElement.bitsPerSample) {
@@ -201,7 +203,7 @@ int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
float *elementData; float *elementData;
int returnValue; int returnValue;
elementData = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->depth * sizeof(float), __func__); elementData = (float *)imb_alloc_pixels(logImage->width, logImage->height, logImage->depth, sizeof(float), __func__);
if (elementData == NULL) if (elementData == NULL)
return 1; return 1;
@@ -238,9 +240,8 @@ int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned char *row; unsigned char *row;
int x, y;
row = (unsigned char *)MEM_mallocN(rowLength, __func__); row = (unsigned char *)MEM_mallocN(rowLength, __func__);
if (row == NULL) { if (row == NULL) {
@@ -249,8 +250,8 @@ static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement,
} }
memset(row, 0, rowLength); memset(row, 0, rowLength);
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
for (x = 0; x < logImage->width * logImage->depth; x++) for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = (unsigned char)float_uint(data[y * logImage->width * logImage->depth + x], 255); row[x] = (unsigned char)float_uint(data[y * logImage->width * logImage->depth + x], 255);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) { if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -265,10 +266,9 @@ static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, index; unsigned int pixel, index;
unsigned int *row; unsigned int *row;
int x, y, offset;
row = (unsigned int *)MEM_mallocN(rowLength, __func__); row = (unsigned int *)MEM_mallocN(rowLength, __func__);
if (row == NULL) { if (row == NULL) {
@@ -276,12 +276,12 @@ static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement,
return 1; return 1;
} }
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
offset = 22; int offset = 22;
index = 0; index = 0;
pixel = 0; pixel = 0;
for (x = 0; x < logImage->width * logImage->depth; x++) { for (size_t x = 0; x < logImage->width * logImage->depth; x++) {
pixel |= (unsigned int)float_uint(data[y * logImage->width * logImage->depth + x], 1023) << offset; pixel |= (unsigned int)float_uint(data[y * logImage->width * logImage->depth + x], 1023) << offset;
offset -= 10; offset -= 10;
if (offset < 0) { if (offset < 0) {
@@ -308,9 +308,8 @@ static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned short *row; unsigned short *row;
int x, y;
row = (unsigned short *)MEM_mallocN(rowLength, __func__); row = (unsigned short *)MEM_mallocN(rowLength, __func__);
if (row == NULL) { if (row == NULL) {
@@ -318,8 +317,8 @@ static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement,
return 1; return 1;
} }
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
for (x = 0; x < logImage->width * logImage->depth; x++) for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = swap_ushort(((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 4095)) << 4, logImage->isMSB); row[x] = swap_ushort(((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 4095)) << 4, logImage->isMSB);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) { if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -334,9 +333,8 @@ static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned short *row; unsigned short *row;
int x, y;
row = (unsigned short *)MEM_mallocN(rowLength, __func__); row = (unsigned short *)MEM_mallocN(rowLength, __func__);
if (row == NULL) { if (row == NULL) {
@@ -344,8 +342,8 @@ static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement,
return 1; return 1;
} }
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
for (x = 0; x < logImage->width * logImage->depth; x++) for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = swap_ushort((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 65535), logImage->isMSB); row[x] = swap_ushort((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 65535), logImage->isMSB);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) { if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -382,7 +380,7 @@ int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
/* descriptor_Depth and descriptor_Composite are not supported */ /* descriptor_Depth and descriptor_Composite are not supported */
if (logImage->element[i].descriptor != descriptor_Depth && logImage->element[i].descriptor != descriptor_Composite) { if (logImage->element[i].descriptor != descriptor_Depth && logImage->element[i].descriptor != descriptor_Composite) {
/* Allocate memory */ /* Allocate memory */
elementData[i] = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->element[i].depth * sizeof(float), __func__); elementData[i] = imb_alloc_pixels(logImage->width, logImage->height, logImage->element[i].depth, sizeof(float), __func__);
if (elementData[i] == NULL) { if (elementData[i] == NULL) {
if (verbose) printf("DPX/Cineon: Cannot allocate memory for elementData[%d]\n.", i); if (verbose) printf("DPX/Cineon: Cannot allocate memory for elementData[%d]\n.", i);
for (j = 0; j < i; j++) for (j = 0; j < i; j++)
@@ -530,7 +528,7 @@ int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
} }
} }
mergedData = (float *)MEM_mallocN(logImage->width * logImage->height * mergedElement.depth * sizeof(float), __func__); mergedData = (float *)imb_alloc_pixels(logImage->width, logImage->height, mergedElement.depth, sizeof(float), __func__);
if (mergedData == NULL) { if (mergedData == NULL) {
if (verbose) printf("DPX/Cineon: Cannot allocate mergedData.\n"); if (verbose) printf("DPX/Cineon: Cannot allocate mergedData.\n");
for (i = 0; i < logImage->numElements; i++) for (i = 0; i < logImage->numElements; i++)
@@ -590,7 +588,6 @@ static int logImageElementGetData(LogImageFile *logImage, LogImageElement logEle
static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int pixel; unsigned int pixel;
int x, y, offset;
/* seek at the right place */ /* seek at the right place */
if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) { if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
@@ -599,14 +596,14 @@ static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logEl
} }
/* read 1 bit data padded to 32 bits */ /* read 1 bit data padded to 32 bits */
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
for (x = 0; x < logImage->width * logElement.depth; x += 32) { for (size_t x = 0; x < logImage->width * logElement.depth; x += 32) {
if (logimage_read_uint(&pixel, logImage) != 0) { if (logimage_read_uint(&pixel, logImage) != 0) {
if (verbose) printf("DPX/Cineon: EOF reached\n"); if (verbose) printf("DPX/Cineon: EOF reached\n");
return 1; return 1;
} }
pixel = swap_uint(pixel, logImage->isMSB); pixel = swap_uint(pixel, logImage->isMSB);
for (offset = 0; offset < 32 && x + offset < logImage->width; offset++) for (int offset = 0; offset < 32 && x + offset < logImage->width; offset++)
data[y * logImage->width * logElement.depth + x + offset] = (float)((pixel >> offset) & 0x01); data[y * logImage->width * logElement.depth + x + offset] = (float)((pixel >> offset) & 0x01);
} }
} }
@@ -615,19 +612,18 @@ static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logEl
static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned char pixel; unsigned char pixel;
int x, y;
/* extract required pixels */ /* extract required pixels */
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
/* 8 bits are 32-bits padded so we need to seek at each row */ /* 8 bits are 32-bits padded so we need to seek at each row */
if (logimage_fseek(logImage, logElement.dataOffset + y * rowLength, SEEK_SET) != 0) { if (logimage_fseek(logImage, logElement.dataOffset + y * rowLength, SEEK_SET) != 0) {
if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset + y * (int)rowLength); if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", (int)(logElement.dataOffset + y * rowLength));
return 1; return 1;
} }
for (x = 0; x < logImage->width * logElement.depth; x++) { for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (logimage_read_uchar(&pixel, logImage) != 0) { if (logimage_read_uchar(&pixel, logImage) != 0) {
if (verbose) printf("DPX/Cineon: EOF reached\n"); if (verbose) printf("DPX/Cineon: EOF reached\n");
return 1; return 1;
@@ -641,7 +637,6 @@ static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logEl
static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int pixel; unsigned int pixel;
int x, y, offset;
/* seek to data */ /* seek to data */
if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) { if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
@@ -650,9 +645,9 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
} }
if (logImage->depth == 1 && logImage->srcFormat == format_DPX) { if (logImage->depth == 1 && logImage->srcFormat == format_DPX) {
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
offset = 32; int offset = 32;
for (x = 0; x < logImage->width * logElement.depth; x++) { for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
/* we need to read the next long */ /* we need to read the next long */
if (offset >= 30) { if (offset >= 30) {
if (logElement.packing == 1) if (logElement.packing == 1)
@@ -672,9 +667,9 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
} }
} }
else { else {
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
offset = -1; int offset = -1;
for (x = 0; x < logImage->width * logElement.depth; x++) { for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
/* we need to read the next long */ /* we need to read the next long */
if (offset < 0) { if (offset < 0) {
if (logElement.packing == 1) if (logElement.packing == 1)
@@ -699,23 +694,22 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
static int logImageElementGetData10Packed(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageElementGetData10Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, oldPixel; unsigned int pixel, oldPixel;
int offset, offset2, x, y;
/* converting bytes to pixels */ /* converting bytes to pixels */
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
/* seek to data */ /* seek to data */
if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) { if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset); if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", (unsigned int)(y * rowLength + logElement.dataOffset));
return 1; return 1;
} }
oldPixel = 0; oldPixel = 0;
offset = 0; int offset = 0;
offset2 = 0; int offset2 = 0;
for (x = 0; x < logImage->width * logElement.depth; x++) { for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (offset2 != 0) { if (offset2 != 0) {
offset = 10 - offset2; offset = 10 - offset2;
offset2 = 0; offset2 = 0;
@@ -778,23 +772,22 @@ static int logImageElementGetData12(LogImageFile *logImage, LogImageElement logE
static int logImageElementGetData12Packed(LogImageFile *logImage, LogImageElement logElement, float *data) static int logImageElementGetData12Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
{ {
unsigned int rowLength = getRowLength(logImage->width, logElement); size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, oldPixel; unsigned int pixel, oldPixel;
int offset, offset2, x, y;
/* converting bytes to pixels */ /* converting bytes to pixels */
for (y = 0; y < logImage->height; y++) { for (size_t y = 0; y < logImage->height; y++) {
/* seek to data */ /* seek to data */
if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) { if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset); if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", (unsigned int)(y * rowLength + logElement.dataOffset));
return 1; return 1;
} }
oldPixel = 0; oldPixel = 0;
offset = 0; int offset = 0;
offset2 = 0; int offset2 = 0;
for (x = 0; x < logImage->width * logElement.depth; x++) { for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (offset2 != 0) { if (offset2 != 0) {
offset = 12 - offset2; offset = 12 - offset2;
offset2 = 0; offset2 = 0;
@@ -1119,7 +1112,7 @@ static int convertRGBA_RGBA(float *src, float *dst, LogImageFile *logImage,
case transfer_UserDefined: case transfer_UserDefined:
case transfer_Linear: case transfer_Linear:
case transfer_Logarithmic: { case transfer_Logarithmic: {
memcpy(dst, src, 4 * logImage->width * logImage->height * sizeof(float)); memcpy(dst, src, 4 * (size_t)logImage->width * (size_t)logImage->height * sizeof(float));
return 0; return 0;
} }
@@ -1434,11 +1427,11 @@ static int convertRGBAToLogElement(float *src, float *dst, LogImageFile *logImag
if (srcIsLinearRGB != 0) { if (srcIsLinearRGB != 0) {
/* we need to convert src to sRGB */ /* we need to convert src to sRGB */
srgbSrc = (float *)MEM_mallocN(4 * logImage->width * logImage->height * sizeof(float), __func__); srgbSrc = (float *)imb_alloc_pixels(logImage->width, logImage->height, 4, sizeof(float), __func__);
if (srgbSrc == NULL) if (srgbSrc == NULL)
return 1; return 1;
memcpy(srgbSrc, src, 4 * logImage->width * logImage->height * sizeof(float)); memcpy(srgbSrc, src, 4 * (size_t)logImage->width * (size_t)logImage->height * sizeof(float));
srgbSrc_ptr = srgbSrc; srgbSrc_ptr = srgbSrc;
/* convert data from Linear RGB to sRGB via lut */ /* convert data from Linear RGB to sRGB via lut */

View File

@@ -196,7 +196,7 @@ LogImageFile *logImageCreate(const char *filename, int cineon, int width, int he
void logImageClose(LogImageFile *logImage); void logImageClose(LogImageFile *logImage);
/* Data handling */ /* Data handling */
unsigned int getRowLength(int width, LogImageElement logElement); size_t getRowLength(size_t width, LogImageElement logElement);
int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB); int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);
int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB); int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);

View File

@@ -260,9 +260,8 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
const uchar *mem_end = mem + size; const uchar *mem_end = mem + size;
MFileOffset _inf_data = {mem, 0}, *inf = &_inf_data; MFileOffset _inf_data = {mem, 0}, *inf = &_inf_data;
IMAGE image; IMAGE image;
int x, y, z, tablen;
int bpp, rle, cur, badorder; int bpp, rle, cur, badorder;
ImBuf *ibuf; ImBuf *ibuf = NULL;
uchar dirty_flag = 0; uchar dirty_flag = 0;
if (size < HEADER_SIZE) { if (size < HEADER_SIZE) {
@@ -304,7 +303,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
} }
if (rle) { if (rle) {
tablen = ysize * zsize * sizeof(int); size_t tablen = (size_t)ysize * (size_t)zsize * sizeof(int);
MFILE_SEEK(inf, HEADER_SIZE); MFILE_SEEK(inf, HEADER_SIZE);
uint *starttab = MEM_mallocN(tablen, "iris starttab"); uint *starttab = MEM_mallocN(tablen, "iris starttab");
@@ -321,8 +320,8 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
/* check data order */ /* check data order */
cur = 0; cur = 0;
badorder = 0; badorder = 0;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
if (starttab[y + z * ysize] < cur) { if (starttab[y + z * ysize] < cur) {
badorder = 1; badorder = 1;
break; break;
@@ -336,14 +335,17 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
if (bpp == 1) { if (bpp == 1) {
ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect); ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect);
if (!ibuf) {
goto fail_rle;
}
if (ibuf->planes > 32) ibuf->planes = 32; if (ibuf->planes > 32) ibuf->planes = 32;
base = ibuf->rect; base = ibuf->rect;
zbase = (uint *)ibuf->zbuf; zbase = (uint *)ibuf->zbuf;
if (badorder) { if (badorder) {
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
lptr = base; lptr = base;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
MFILE_SEEK(inf, starttab[y + z * ysize]); MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]); MFILE_STEP(inf, lengthtab[y + z * ysize]);
@@ -358,12 +360,12 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
else { else {
lptr = base; lptr = base;
zptr = zbase; zptr = zbase;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
uint *lptr_next = lptr + xsize; uint *lptr_next = lptr + xsize;
uint *zptr_next = zptr + xsize; uint *zptr_next = zptr + xsize;
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
MFILE_SEEK(inf, starttab[y + z * ysize]); MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]); MFILE_STEP(inf, lengthtab[y + z * ysize]);
@@ -386,13 +388,16 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
else { /* bpp == 2 */ else { /* bpp == 2 */
ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat); ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat);
if (!ibuf) {
goto fail_rle;
}
fbase = ibuf->rect_float; fbase = ibuf->rect_float;
if (badorder) { if (badorder) {
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
fptr = fbase; fptr = fbase;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
MFILE_SEEK(inf, starttab[y + z * ysize]); MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]); MFILE_STEP(inf, lengthtab[y + z * ysize]);
@@ -408,9 +413,9 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
fptr = fbase; fptr = fbase;
float *fptr_next = fptr + (xsize * 4); float *fptr_next = fptr + (xsize * 4);
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
MFILE_SEEK(inf, starttab[y + z * ysize]); MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]); MFILE_STEP(inf, lengthtab[y + z * ysize]);
@@ -426,6 +431,10 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors
fail_rle: fail_rle:
MEM_freeN(starttab); MEM_freeN(starttab);
MEM_freeN(lengthtab); MEM_freeN(lengthtab);
if (!ibuf) {
return NULL;
}
} }
else { else {
@@ -435,6 +444,9 @@ fail_rle:
if (bpp == 1) { if (bpp == 1) {
ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect); ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect);
if (!ibuf) {
goto fail_uncompressed;
}
if (ibuf->planes > 32) ibuf->planes = 32; if (ibuf->planes > 32) ibuf->planes = 32;
base = ibuf->rect; base = ibuf->rect;
@@ -443,12 +455,12 @@ fail_rle:
MFILE_SEEK(inf, HEADER_SIZE); MFILE_SEEK(inf, HEADER_SIZE);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
if (z < 4) lptr = base; if (z < 4) lptr = base;
else if (z < 8) lptr = zbase; else if (z < 8) lptr = zbase;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
const uchar *rledat_next = rledat + xsize; const uchar *rledat_next = rledat + xsize;
const int z_ofs = 3 - z; const int z_ofs = 3 - z;
MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs); MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs);
@@ -462,17 +474,20 @@ fail_rle:
else { /* bpp == 2 */ else { /* bpp == 2 */
ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat); ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat);
if (!ibuf) {
goto fail_uncompressed;
}
fbase = ibuf->rect_float; fbase = ibuf->rect_float;
MFILE_SEEK(inf, HEADER_SIZE); MFILE_SEEK(inf, HEADER_SIZE);
rledat = MFILE_DATA(inf); rledat = MFILE_DATA(inf);
for (z = 0; z < zsize; z++) { for (size_t z = 0; z < zsize; z++) {
fptr = fbase; fptr = fbase;
for (y = 0; y < ysize; y++) { for (size_t y = 0; y < ysize; y++) {
const uchar *rledat_next = rledat + xsize * 2; const uchar *rledat_next = rledat + xsize * 2;
const int z_ofs = 3 - z; const int z_ofs = 3 - z;
MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs); MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs);
@@ -485,7 +500,9 @@ fail_rle:
} }
#undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL #undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL
fail_uncompressed: fail_uncompressed:
(void)0; if (!ibuf) {
return NULL;
}
} }
if (bpp == 1) { if (bpp == 1) {
@@ -493,7 +510,7 @@ fail_uncompressed:
if (image.zsize == 1) { if (image.zsize == 1) {
rect = (uchar *) ibuf->rect; rect = (uchar *) ibuf->rect;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = 255; rect[0] = 255;
rect[1] = rect[2] = rect[3]; rect[1] = rect[2] = rect[3];
rect += 4; rect += 4;
@@ -502,7 +519,7 @@ fail_uncompressed:
else if (image.zsize == 2) { else if (image.zsize == 2) {
/* grayscale with alpha */ /* grayscale with alpha */
rect = (uchar *) ibuf->rect; rect = (uchar *) ibuf->rect;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = rect[2]; rect[0] = rect[2];
rect[1] = rect[2] = rect[3]; rect[1] = rect[2] = rect[3];
rect += 4; rect += 4;
@@ -511,7 +528,7 @@ fail_uncompressed:
else if (image.zsize == 3) { else if (image.zsize == 3) {
/* add alpha */ /* add alpha */
rect = (uchar *) ibuf->rect; rect = (uchar *) ibuf->rect;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = 255; rect[0] = 255;
rect += 4; rect += 4;
} }
@@ -522,7 +539,7 @@ fail_uncompressed:
if (image.zsize == 1) { if (image.zsize == 1) {
fbase = ibuf->rect_float; fbase = ibuf->rect_float;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = 1; fbase[0] = 1;
fbase[1] = fbase[2] = fbase[3]; fbase[1] = fbase[2] = fbase[3];
fbase += 4; fbase += 4;
@@ -531,7 +548,7 @@ fail_uncompressed:
else if (image.zsize == 2) { else if (image.zsize == 2) {
/* grayscale with alpha */ /* grayscale with alpha */
fbase = ibuf->rect_float; fbase = ibuf->rect_float;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = fbase[2]; fbase[0] = fbase[2];
fbase[1] = fbase[2] = fbase[3]; fbase[1] = fbase[2] = fbase[3];
fbase += 4; fbase += 4;
@@ -540,7 +557,7 @@ fail_uncompressed:
else if (image.zsize == 3) { else if (image.zsize == 3) {
/* add alpha */ /* add alpha */
fbase = ibuf->rect_float; fbase = ibuf->rect_float;
for (x = ibuf->x * ibuf->y; x > 0; x--) { for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = 1; fbase[0] = 1;
fbase += 4; fbase += 4;
} }

View File

@@ -526,7 +526,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
unsigned char *from, *to; unsigned char *from, *to;
unsigned short *from16; unsigned short *from16;
float *to_float; float *to_float;
int i, bytesperpixel; unsigned int channels;
if (imb_is_a_png(mem) == 0) return(NULL); if (imb_is_a_png(mem) == 0) return(NULL);
@@ -571,7 +571,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
&color_type, NULL, NULL, NULL); &color_type, NULL, NULL, NULL);
bytesperpixel = png_get_channels(png_ptr, info_ptr); channels = png_get_channels(png_ptr, info_ptr);
switch (color_type) { switch (color_type) {
case PNG_COLOR_TYPE_RGB: case PNG_COLOR_TYPE_RGB:
@@ -580,10 +580,10 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
case PNG_COLOR_TYPE_PALETTE: case PNG_COLOR_TYPE_PALETTE:
png_set_palette_to_rgb(png_ptr); png_set_palette_to_rgb(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
bytesperpixel = 4; channels = 4;
} }
else { else {
bytesperpixel = 3; channels = 3;
} }
break; break;
case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_GRAY:
@@ -593,7 +593,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
bit_depth = 8; bit_depth = 8;
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
/* PNG_COLOR_TYPE_GRAY may also have alpha 'values', like with palette. */ /* PNG_COLOR_TYPE_GRAY may also have alpha 'values', like with palette. */
bytesperpixel = 2; channels = 2;
} }
} }
break; break;
@@ -602,7 +602,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
longjmp(png_jmpbuf(png_ptr), 1); longjmp(png_jmpbuf(png_ptr), 1);
} }
ibuf = IMB_allocImBuf(width, height, 8 * bytesperpixel, 0); ibuf = IMB_allocImBuf(width, height, 8 * channels, 0);
if (ibuf) { if (ibuf) {
ibuf->ftype = IMB_FTYPE_PNG; ibuf->ftype = IMB_FTYPE_PNG;
@@ -630,23 +630,23 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
imb_addrectfloatImBuf(ibuf); imb_addrectfloatImBuf(ibuf);
png_set_swap(png_ptr); png_set_swap(png_ptr);
pixels16 = MEM_mallocN(ibuf->x * ibuf->y * bytesperpixel * sizeof(png_uint_16), "pixels"); pixels16 = imb_alloc_pixels(ibuf->x, ibuf->y, channels, sizeof(png_uint_16), "pixels");
if (pixels16 == NULL) { if (pixels16 == NULL || ibuf->rect_float == NULL) {
printf("Cannot allocate pixels array\n"); printf("Cannot allocate pixels array\n");
longjmp(png_jmpbuf(png_ptr), 1); longjmp(png_jmpbuf(png_ptr), 1);
} }
/* allocate memory for an array of row-pointers */ /* allocate memory for an array of row-pointers */
row_pointers = (png_bytepp) MEM_mallocN(ibuf->y * sizeof(png_uint_16p), "row_pointers"); row_pointers = (png_bytepp) MEM_mallocN((size_t)ibuf->y * sizeof(png_uint_16p), "row_pointers");
if (row_pointers == NULL) { if (row_pointers == NULL) {
printf("Cannot allocate row-pointers array\n"); printf("Cannot allocate row-pointers array\n");
longjmp(png_jmpbuf(png_ptr), 1); longjmp(png_jmpbuf(png_ptr), 1);
} }
/* set the individual row-pointers to point at the correct offsets */ /* set the individual row-pointers to point at the correct offsets */
for (i = 0; i < ibuf->y; i++) { for (size_t i = 0; i < ibuf->y; i++) {
row_pointers[ibuf->y - 1 - i] = (png_bytep) row_pointers[ibuf->y - 1 - i] = (png_bytep)
((png_uint_16 *)pixels16 + (i * ibuf->x) * bytesperpixel); ((png_uint_16 *)pixels16 + (i * ibuf->x) * channels);
} }
png_read_image(png_ptr, row_pointers); png_read_image(png_ptr, row_pointers);
@@ -656,9 +656,9 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
to_float = ibuf->rect_float; to_float = ibuf->rect_float;
from16 = pixels16; from16 = pixels16;
switch (bytesperpixel) { switch (channels) {
case 4: case 4:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = from16[0] / 65535.0; to_float[0] = from16[0] / 65535.0;
to_float[1] = from16[1] / 65535.0; to_float[1] = from16[1] / 65535.0;
to_float[2] = from16[2] / 65535.0; to_float[2] = from16[2] / 65535.0;
@@ -667,7 +667,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
} }
break; break;
case 3: case 3:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = from16[0] / 65535.0; to_float[0] = from16[0] / 65535.0;
to_float[1] = from16[1] / 65535.0; to_float[1] = from16[1] / 65535.0;
to_float[2] = from16[2] / 65535.0; to_float[2] = from16[2] / 65535.0;
@@ -676,14 +676,14 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
} }
break; break;
case 2: case 2:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0; to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0;
to_float[3] = from16[1] / 65535.0; to_float[3] = from16[1] / 65535.0;
to_float += 4; from16 += 2; to_float += 4; from16 += 2;
} }
break; break;
case 1: case 1:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0; to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0;
to_float[3] = 1.0; to_float[3] = 1.0;
to_float += 4; from16++; to_float += 4; from16++;
@@ -694,23 +694,23 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
else { else {
imb_addrectImBuf(ibuf); imb_addrectImBuf(ibuf);
pixels = MEM_mallocN(((size_t)ibuf->x) * ibuf->y * bytesperpixel * sizeof(unsigned char), "pixels"); pixels = imb_alloc_pixels(ibuf->x, ibuf->y, channels, sizeof(unsigned char), "pixels");
if (pixels == NULL) { if (pixels == NULL || ibuf->rect == NULL) {
printf("Cannot allocate pixels array\n"); printf("Cannot allocate pixels array\n");
longjmp(png_jmpbuf(png_ptr), 1); longjmp(png_jmpbuf(png_ptr), 1);
} }
/* allocate memory for an array of row-pointers */ /* allocate memory for an array of row-pointers */
row_pointers = (png_bytepp) MEM_mallocN(ibuf->y * sizeof(png_bytep), "row_pointers"); row_pointers = (png_bytepp) MEM_mallocN((size_t)ibuf->y * sizeof(png_bytep), "row_pointers");
if (row_pointers == NULL) { if (row_pointers == NULL) {
printf("Cannot allocate row-pointers array\n"); printf("Cannot allocate row-pointers array\n");
longjmp(png_jmpbuf(png_ptr), 1); longjmp(png_jmpbuf(png_ptr), 1);
} }
/* set the individual row-pointers to point at the correct offsets */ /* set the individual row-pointers to point at the correct offsets */
for (i = 0; i < ibuf->y; i++) { for (int i = 0; i < ibuf->y; i++) {
row_pointers[ibuf->y - 1 - i] = (png_bytep) row_pointers[ibuf->y - 1 - i] = (png_bytep)
((unsigned char *)pixels + (((size_t)i) * ibuf->x) * bytesperpixel * sizeof(unsigned char)); ((unsigned char *)pixels + (((size_t)i) * ibuf->x) * channels * sizeof(unsigned char));
} }
png_read_image(png_ptr, row_pointers); png_read_image(png_ptr, row_pointers);
@@ -720,9 +720,9 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
to = (unsigned char *) ibuf->rect; to = (unsigned char *) ibuf->rect;
from = pixels; from = pixels;
switch (bytesperpixel) { switch (channels) {
case 4: case 4:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = from[0]; to[0] = from[0];
to[1] = from[1]; to[1] = from[1];
to[2] = from[2]; to[2] = from[2];
@@ -731,7 +731,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
} }
break; break;
case 3: case 3:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = from[0]; to[0] = from[0];
to[1] = from[1]; to[1] = from[1];
to[2] = from[2]; to[2] = from[2];
@@ -740,14 +740,14 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
} }
break; break;
case 2: case 2:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = to[1] = to[2] = from[0]; to[0] = to[1] = to[2] = from[0];
to[3] = from[1]; to[3] = from[1];
to += 4; from += 2; to += 4; from += 2;
} }
break; break;
case 1: case 1:
for (i = ibuf->x * ibuf->y; i > 0; i--) { for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = to[1] = to[2] = from[0]; to[0] = to[1] = to[2] = from[0];
to[3] = 0xff; to[3] = 0xff;
to += 4; from++; to += 4; from++;
@@ -759,7 +759,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
if (flags & IB_metadata) { if (flags & IB_metadata) {
png_text *text_chunks; png_text *text_chunks;
int count = png_get_text(png_ptr, info_ptr, &text_chunks, NULL); int count = png_get_text(png_ptr, info_ptr, &text_chunks, NULL);
for (i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
IMB_metadata_add_field(ibuf, text_chunks[i].key, text_chunks[i].text); IMB_metadata_add_field(ibuf, text_chunks[i].key, text_chunks[i].text);
ibuf->flags |= IB_metadata; ibuf->flags |= IB_metadata;
} }

View File

@@ -71,7 +71,7 @@ typedef float fCOLOR[3];
/* read routines */ /* read routines */
static const unsigned char *oldreadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof) static const unsigned char *oldreadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof)
{ {
int i, rshift = 0, len = xmax; size_t i, rshift = 0, len = xmax;
while (len > 0) { while (len > 0) {
if (UNLIKELY(mem_eof - mem < 4)) { if (UNLIKELY(mem_eof - mem < 4)) {
return NULL; return NULL;
@@ -99,8 +99,6 @@ static const unsigned char *oldreadcolrs(RGBE *scan, const unsigned char *mem, i
static const unsigned char *freadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof) static const unsigned char *freadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof)
{ {
int i, j, code, val;
if (UNLIKELY(mem_eof - mem < 4)) { if (UNLIKELY(mem_eof - mem < 4)) {
return NULL; return NULL;
} }
@@ -109,32 +107,32 @@ static const unsigned char *freadcolrs(RGBE *scan, const unsigned char *mem, int
return oldreadcolrs(scan, mem, xmax, mem_eof); return oldreadcolrs(scan, mem, xmax, mem_eof);
} }
i = *mem++; int val = *mem++;
if (i != 2) { if (val != 2) {
return oldreadcolrs(scan, mem - 1, xmax, mem_eof); return oldreadcolrs(scan, mem - 1, xmax, mem_eof);
} }
scan[0][GRN] = *mem++; scan[0][GRN] = *mem++;
scan[0][BLU] = *mem++; scan[0][BLU] = *mem++;
i = *mem++; val = *mem++;
if (scan[0][GRN] != 2 || scan[0][BLU] & 128) { if (scan[0][GRN] != 2 || scan[0][BLU] & 128) {
scan[0][RED] = 2; scan[0][RED] = 2;
scan[0][EXP] = i; scan[0][EXP] = val;
return oldreadcolrs(scan + 1, mem, xmax - 1, mem_eof); return oldreadcolrs(scan + 1, mem, xmax - 1, mem_eof);
} }
if (UNLIKELY(((scan[0][BLU] << 8) | i) != xmax)) { if (UNLIKELY(((scan[0][BLU] << 8) | val) != xmax)) {
return NULL; return NULL;
} }
for (i = 0; i < 4; i++) { for (size_t i = 0; i < 4; i++) {
if (UNLIKELY(mem_eof - mem < 2)) { if (UNLIKELY(mem_eof - mem < 2)) {
return NULL; return NULL;
} }
for (j = 0; j < xmax; ) { for (size_t j = 0; j < xmax; ) {
code = *mem++; int code = *mem++;
if (code > 128) { if (code > 128) {
code &= 127; code &= 127;
if (UNLIKELY(code + j > xmax)) { if (UNLIKELY(code + j > xmax)) {
@@ -215,7 +213,6 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
float *rect_float; float *rect_float;
int found = 0; int found = 0;
int width = 0, height = 0; int width = 0, height = 0;
int x, y;
const unsigned char *ptr, *mem_eof = mem + size; const unsigned char *ptr, *mem_eof = mem + size;
char oriY[80], oriX[80]; char oriY[80], oriX[80];
@@ -223,6 +220,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_FLOAT); colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_FLOAT);
/* find empty line, next line is resolution info */ /* find empty line, next line is resolution info */
size_t x;
for (x = 1; x < size; x++) { for (x = 1; x < size; x++) {
if ((mem[x - 1] == '\n') && (mem[x] == '\n')) { if ((mem[x - 1] == '\n') && (mem[x] == '\n')) {
found = 1; found = 1;
@@ -259,7 +257,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
sline = (RGBE *)MEM_mallocN(sizeof(*sline) * width, __func__); sline = (RGBE *)MEM_mallocN(sizeof(*sline) * width, __func__);
rect_float = ibuf->rect_float; rect_float = ibuf->rect_float;
for (y = 0; y < height; y++) { for (size_t y = 0; y < height; y++) {
ptr = freadcolrs(sline, ptr, width, mem_eof); ptr = freadcolrs(sline, ptr, width, mem_eof);
if (ptr == NULL) { if (ptr == NULL) {
printf("WARNING! HDR decode error, image may be just truncated, or completely wrong...\n"); printf("WARNING! HDR decode error, image may be just truncated, or completely wrong...\n");
@@ -293,7 +291,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
/* ImBuf write */ /* ImBuf write */
static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufscan, float *fpscan) static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufscan, float *fpscan)
{ {
int x, i, j, beg, c2, cnt = 0; int beg, c2, cnt = 0;
fCOLOR fcol; fCOLOR fcol;
RGBE rgbe, *rgbe_scan; RGBE rgbe, *rgbe_scan;
@@ -304,8 +302,7 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
rgbe_scan = (RGBE *)MEM_mallocN(sizeof(RGBE) * width, "radhdr_write_tmpscan"); rgbe_scan = (RGBE *)MEM_mallocN(sizeof(RGBE) * width, "radhdr_write_tmpscan");
/* convert scanline */ /* convert scanline */
j = 0; for (size_t i = 0, j = 0; i < width; i++) {
for (i = 0; i < width; i++) {
if (fpscan) { if (fpscan) {
fcol[RED] = fpscan[j]; fcol[RED] = fpscan[j];
fcol[GRN] = (channels >= 2) ? fpscan[j + 1] : fpscan[j]; fcol[GRN] = (channels >= 2) ? fpscan[j + 1] : fpscan[j];
@@ -322,7 +319,7 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
} }
if ((width < MINELEN) | (width > MAXELEN)) { /* OOBs, write out flat */ if ((width < MINELEN) | (width > MAXELEN)) { /* OOBs, write out flat */
x = fwrite((char *)rgbe_scan, sizeof(RGBE), width, file) - width; int x = fwrite((char *)rgbe_scan, sizeof(RGBE), width, file) - width;
MEM_freeN(rgbe_scan); MEM_freeN(rgbe_scan);
return x; return x;
} }
@@ -332,8 +329,8 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
putc((unsigned char)(width >> 8), file); putc((unsigned char)(width >> 8), file);
putc((unsigned char)(width & 255), file); putc((unsigned char)(width & 255), file);
/* put components separately */ /* put components separately */
for (i = 0; i < 4; i++) { for (size_t i = 0; i < 4; i++) {
for (j = 0; j < width; j += cnt) { /* find next run */ for (size_t j = 0; j < width; j += cnt) { /* find next run */
for (beg = j; beg < width; beg += cnt) { for (beg = j; beg < width; beg += cnt) {
for (cnt = 1; (cnt < 127) && ((beg + cnt) < width) && (rgbe_scan[beg + cnt][i] == rgbe_scan[beg][i]); cnt++) ; for (cnt = 1; (cnt < 127) && ((beg + cnt) < width) && (rgbe_scan[beg + cnt][i] == rgbe_scan[beg][i]); cnt++) ;
if (cnt >= MINRUN) break; /* long enough */ if (cnt >= MINRUN) break; /* long enough */
@@ -386,7 +383,7 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags)
{ {
FILE *file = BLI_fopen(name, "wb"); FILE *file = BLI_fopen(name, "wb");
float *fp = NULL; float *fp = NULL;
int y, width = ibuf->x, height = ibuf->y; size_t width = ibuf->x, height = ibuf->y;
unsigned char *cp = NULL; unsigned char *cp = NULL;
(void)flags; /* unused */ (void)flags; /* unused */
@@ -402,7 +399,7 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags)
if (ibuf->rect_float) if (ibuf->rect_float)
fp = ibuf->rect_float + ibuf->channels * (height - 1) * width; fp = ibuf->rect_float + ibuf->channels * (height - 1) * width;
for (y = height - 1; y >= 0; y--) { for (size_t y = 0; y < height; y++) {
if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) { if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) {
fclose(file); fclose(file);
printf("HDR write error\n"); printf("HDR write error\n");

View File

@@ -376,7 +376,7 @@ static void imb_read_tiff_resolution(ImBuf *ibuf, TIFF *image)
*/ */
static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
{ {
ImBuf *tmpibuf; ImBuf *tmpibuf = NULL;
int success = 0; int success = 0;
short bitspersample, spp, config; short bitspersample, spp, config;
size_t scanline; size_t scanline;
@@ -412,16 +412,25 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
if (bitspersample == 32) { if (bitspersample == 32) {
ib_flag = IB_rectfloat; ib_flag = IB_rectfloat;
fbuf = (float *)_TIFFmalloc(scanline); fbuf = (float *)_TIFFmalloc(scanline);
if (!fbuf) {
goto cleanup;
}
} }
else if (bitspersample == 16) { else if (bitspersample == 16) {
ib_flag = IB_rectfloat; ib_flag = IB_rectfloat;
sbuf = (unsigned short *)_TIFFmalloc(scanline); sbuf = (unsigned short *)_TIFFmalloc(scanline);
if (!sbuf) {
goto cleanup;
}
} }
else { else {
ib_flag = IB_rect; ib_flag = IB_rect;
} }
tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ib_flag); tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ib_flag);
if (!tmpibuf) {
goto cleanup;
}
/* simple RGBA image */ /* simple RGBA image */
if (!(bitspersample == 32 || bitspersample == 16)) { if (!(bitspersample == 32 || bitspersample == 16)) {
@@ -430,7 +439,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
/* contiguous channels: RGBRGBRGB */ /* contiguous channels: RGBRGBRGB */
else if (config == PLANARCONFIG_CONTIG) { else if (config == PLANARCONFIG_CONTIG) {
for (row = 0; row < ibuf->y; row++) { for (row = 0; row < ibuf->y; row++) {
int ib_offset = ibuf->x * ibuf->y * 4 - ibuf->x * 4 * (row + 1); size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1));
if (bitspersample == 32) { if (bitspersample == 32) {
success |= TIFFReadScanline(image, fbuf, row, 0); success |= TIFFReadScanline(image, fbuf, row, 0);
@@ -450,7 +459,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
* but only fill in from the TIFF scanline where necessary. */ * but only fill in from the TIFF scanline where necessary. */
for (chan = 0; chan < 4; chan++) { for (chan = 0; chan < 4; chan++) {
for (row = 0; row < ibuf->y; row++) { for (row = 0; row < ibuf->y; row++) {
int ib_offset = ibuf->x * ibuf->y * 4 - ibuf->x * 4 * (row + 1); size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1));
if (bitspersample == 32) { if (bitspersample == 32) {
if (chan == 3 && spp == 3) /* fill alpha if only RGB TIFF */ if (chan == 3 && spp == 3) /* fill alpha if only RGB TIFF */
@@ -476,11 +485,6 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
} }
} }
if (bitspersample == 32)
_TIFFfree(fbuf);
else if (bitspersample == 16)
_TIFFfree(sbuf);
if (success) { if (success) {
/* Code seems to be not needed for 16 bits tif, on PPC G5 OSX (ton) */ /* Code seems to be not needed for 16 bits tif, on PPC G5 OSX (ton) */
if (bitspersample < 16) if (bitspersample < 16)
@@ -498,6 +502,12 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
tmpibuf->mall &= ~ib_flag; tmpibuf->mall &= ~ib_flag;
} }
cleanup:
if (bitspersample == 32)
_TIFFfree(fbuf);
else if (bitspersample == 16)
_TIFFfree(sbuf);
IMB_freeImBuf(tmpibuf); IMB_freeImBuf(tmpibuf);
return success; return success;

View File

@@ -87,9 +87,7 @@ typedef struct BevList {
int charidx; int charidx;
int *segbevcount; int *segbevcount;
float *seglen; float *seglen;
BevPoint *bevpoints;
/* over-alloc */
BevPoint bevpoints[0];
} BevList; } BevList;
/** /**

View File

@@ -173,7 +173,9 @@ void DNA_sdna_free(SDNA *sdna)
MEM_freeN(sdna->structs); MEM_freeN(sdna->structs);
#ifdef WITH_DNA_GHASH #ifdef WITH_DNA_GHASH
if (sdna->structs_map) {
BLI_ghash_free(sdna->structs_map, NULL, NULL); BLI_ghash_free(sdna->structs_map, NULL, NULL);
}
#endif #endif
MEM_freeN(sdna); MEM_freeN(sdna);

View File

@@ -177,8 +177,8 @@ static void dm_mvert_map_doubles(
source_end = source_start + source_num_verts; source_end = source_start + source_num_verts;
/* build array of MVerts to be tested for merging */ /* build array of MVerts to be tested for merging */
sorted_verts_target = MEM_mallocN(sizeof(SortVertsElem) * target_num_verts, __func__); sorted_verts_target = MEM_malloc_arrayN(target_num_verts, sizeof(SortVertsElem), __func__);
sorted_verts_source = MEM_mallocN(sizeof(SortVertsElem) * source_num_verts, __func__); sorted_verts_source = MEM_malloc_arrayN(source_num_verts, sizeof(SortVertsElem), __func__);
/* Copy target vertices index and cos into SortVertsElem array */ /* Copy target vertices index and cos into SortVertsElem array */
svert_from_mvert(sorted_verts_target, mverts + target_start, target_start, target_end); svert_from_mvert(sorted_verts_target, mverts + target_start, target_start, target_end);
@@ -491,7 +491,7 @@ static DerivedMesh *arrayModifier_doArray(
if (use_merge) { if (use_merge) {
/* Will need full_doubles_map for handling merge */ /* Will need full_doubles_map for handling merge */
full_doubles_map = MEM_mallocN(sizeof(int) * result_nverts, "mod array doubles map"); full_doubles_map = MEM_malloc_arrayN(result_nverts, sizeof(int), "mod array doubles map");
copy_vn_i(full_doubles_map, result_nverts, -1); copy_vn_i(full_doubles_map, result_nverts, -1);
} }

View File

@@ -239,7 +239,7 @@ static DerivedMesh *applyModifier_bmesh(
int tottri; int tottri;
BMLoop *(*looptris)[3]; BMLoop *(*looptris)[3];
looptris = MEM_mallocN(sizeof(*looptris) * looptris_tot, __func__); looptris = MEM_malloc_arrayN(looptris_tot, sizeof(*looptris), __func__);
BM_mesh_calc_tessellation_beauty(bm, looptris, &tottri); BM_mesh_calc_tessellation_beauty(bm, looptris, &tottri);

View File

@@ -104,9 +104,9 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
MVert *mvert_src = dm->getVertArray(dm); MVert *mvert_src = dm->getVertArray(dm);
vertMap = MEM_mallocN(sizeof(*vertMap) * numVert_src, "build modifier vertMap"); vertMap = MEM_malloc_arrayN(numVert_src, sizeof(*vertMap), "build modifier vertMap");
edgeMap = MEM_mallocN(sizeof(*edgeMap) * numEdge_src, "build modifier edgeMap"); edgeMap = MEM_malloc_arrayN(numEdge_src, sizeof(*edgeMap), "build modifier edgeMap");
faceMap = MEM_mallocN(sizeof(*faceMap) * numPoly_src, "build modifier faceMap"); faceMap = MEM_malloc_arrayN(numPoly_src, sizeof(*faceMap), "build modifier faceMap");
range_vn_i(vertMap, numVert_src, 0); range_vn_i(vertMap, numVert_src, 0);
range_vn_i(edgeMap, numEdge_src, 0); range_vn_i(edgeMap, numEdge_src, 0);

View File

@@ -158,7 +158,7 @@ static void deformVerts(ModifierData *md, const struct EvaluationContext *UNUSED
{ {
const MLoop *mloop = dm->getLoopArray(dm); const MLoop *mloop = dm->getLoopArray(dm);
const MLoopTri *looptri = dm->getLoopTriArray(dm); const MLoopTri *looptri = dm->getLoopTriArray(dm);
MVertTri *tri = MEM_mallocN(sizeof(*tri) * collmd->tri_num, __func__); MVertTri *tri = MEM_malloc_arrayN(collmd->tri_num, sizeof(*tri), __func__);
DM_verttri_from_looptri(tri, mloop, looptri, collmd->tri_num); DM_verttri_from_looptri(tri, mloop, looptri, collmd->tri_num);
collmd->tri = tri; collmd->tri = tri;
} }

View File

@@ -156,7 +156,7 @@ static void dm_get_boundaries(DerivedMesh *dm, float *smooth_weights)
mpoly_num = (unsigned int)dm->getNumPolys(dm); mpoly_num = (unsigned int)dm->getNumPolys(dm);
medge_num = (unsigned int)dm->getNumEdges(dm); medge_num = (unsigned int)dm->getNumEdges(dm);
boundaries = MEM_callocN(medge_num * sizeof(*boundaries), __func__); boundaries = MEM_calloc_arrayN(medge_num, sizeof(*boundaries), __func__);
/* count the number of adjacent faces */ /* count the number of adjacent faces */
for (i = 0; i < mpoly_num; i++) { for (i = 0; i < mpoly_num; i++) {
@@ -199,9 +199,9 @@ static void smooth_iter__simple(
struct SmoothingData_Simple { struct SmoothingData_Simple {
float delta[3]; float delta[3];
} *smooth_data = MEM_callocN((size_t)numVerts * sizeof(*smooth_data), __func__); } *smooth_data = MEM_calloc_arrayN(numVerts, sizeof(*smooth_data), __func__);
vertex_edge_count_div = MEM_callocN((size_t)numVerts * sizeof(float), __func__); vertex_edge_count_div = MEM_calloc_arrayN(numVerts, sizeof(float), __func__);
/* calculate as floats to avoid int->float conversion in #smooth_iter */ /* calculate as floats to avoid int->float conversion in #smooth_iter */
for (i = 0; i < numEdges; i++) { for (i = 0; i < numEdges; i++) {
@@ -277,11 +277,11 @@ static void smooth_iter__length_weight(
struct SmoothingData_Weighted { struct SmoothingData_Weighted {
float delta[3]; float delta[3];
float edge_length_sum; float edge_length_sum;
} *smooth_data = MEM_callocN((size_t)numVerts * sizeof(*smooth_data), __func__); } *smooth_data = MEM_calloc_arrayN(numVerts, sizeof(*smooth_data), __func__);
/* calculate as floats to avoid int->float conversion in #smooth_iter */ /* calculate as floats to avoid int->float conversion in #smooth_iter */
vertex_edge_count = MEM_callocN((size_t)numVerts * sizeof(float), __func__); vertex_edge_count = MEM_calloc_arrayN(numVerts, sizeof(float), __func__);
for (i = 0; i < numEdges; i++) { for (i = 0; i < numEdges; i++) {
vertex_edge_count[edges[i].v1] += 1.0f; vertex_edge_count[edges[i].v1] += 1.0f;
vertex_edge_count[edges[i].v2] += 1.0f; vertex_edge_count[edges[i].v2] += 1.0f;
@@ -382,7 +382,7 @@ static void smooth_verts(
if (dvert || (csmd->flag & MOD_CORRECTIVESMOOTH_PIN_BOUNDARY)) { if (dvert || (csmd->flag & MOD_CORRECTIVESMOOTH_PIN_BOUNDARY)) {
smooth_weights = MEM_mallocN(numVerts * sizeof(float), __func__); smooth_weights = MEM_malloc_arrayN(numVerts, sizeof(float), __func__);
if (dvert) { if (dvert) {
dm_get_weights( dm_get_weights(
@@ -530,7 +530,7 @@ static void calc_deltas(
float (*tangent_spaces)[3][3]; float (*tangent_spaces)[3][3];
unsigned int i; unsigned int i;
tangent_spaces = MEM_callocN((size_t)(numVerts) * sizeof(float[3][3]), __func__); tangent_spaces = MEM_calloc_arrayN(numVerts, sizeof(float[3][3]), __func__);
if (csmd->delta_cache_num != numVerts) { if (csmd->delta_cache_num != numVerts) {
MEM_SAFE_FREE(csmd->delta_cache); MEM_SAFE_FREE(csmd->delta_cache);
@@ -539,7 +539,7 @@ static void calc_deltas(
/* allocate deltas if they have not yet been allocated, otheriwse we will just write over them */ /* allocate deltas if they have not yet been allocated, otheriwse we will just write over them */
if (!csmd->delta_cache) { if (!csmd->delta_cache) {
csmd->delta_cache_num = numVerts; csmd->delta_cache_num = numVerts;
csmd->delta_cache = MEM_mallocN((size_t)numVerts * sizeof(float[3]), __func__); csmd->delta_cache = MEM_malloc_arrayN(numVerts, sizeof(float[3]), __func__);
} }
smooth_verts(csmd, dm, dvert, defgrp_index, smooth_vertex_coords, numVerts); smooth_verts(csmd, dm, dvert, defgrp_index, smooth_vertex_coords, numVerts);
@@ -680,7 +680,7 @@ static void correctivesmooth_modifier_do(
float (*tangent_spaces)[3][3]; float (*tangent_spaces)[3][3];
/* calloc, since values are accumulated */ /* calloc, since values are accumulated */
tangent_spaces = MEM_callocN((size_t)numVerts * sizeof(float[3][3]), __func__); tangent_spaces = MEM_calloc_arrayN(numVerts, sizeof(float[3][3]), __func__);
calc_tangent_spaces(dm, vertexCos, tangent_spaces); calc_tangent_spaces(dm, vertexCos, tangent_spaces);

View File

@@ -142,7 +142,7 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
const unsigned int vert_tot = dm->getNumVerts(dm); const unsigned int vert_tot = dm->getNumVerts(dm);
unsigned int i; unsigned int i;
vweights = MEM_mallocN(vert_tot * sizeof(float), __func__); vweights = MEM_malloc_arrayN(vert_tot, sizeof(float), __func__);
if (dmd->flag & MOD_DECIM_FLAG_INVERT_VGROUP) { if (dmd->flag & MOD_DECIM_FLAG_INVERT_VGROUP) {
for (i = 0; i < vert_tot; i++) { for (i = 0; i < vert_tot; i++) {

View File

@@ -308,7 +308,7 @@ static void displaceModifier_do(
modifier_get_vgroup(ob, dm, dmd->defgrp_name, &dvert, &defgrp_index); modifier_get_vgroup(ob, dm, dmd->defgrp_name, &dvert, &defgrp_index);
if (dmd->texture) { if (dmd->texture) {
tex_co = MEM_callocN(sizeof(*tex_co) * numVerts, tex_co = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tex_co),
"displaceModifier_do tex_co"); "displaceModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)dmd, ob, dm, vertexCos, tex_co, numVerts); get_texture_coords((MappingInfoModifierData *)dmd, ob, dm, vertexCos, tex_co, numVerts);
@@ -329,7 +329,7 @@ static void displaceModifier_do(
} }
clnors = CustomData_get_layer(ldata, CD_NORMAL); clnors = CustomData_get_layer(ldata, CD_NORMAL);
vert_clnors = MEM_mallocN(sizeof(*vert_clnors) * (size_t)numVerts, __func__); vert_clnors = MEM_malloc_arrayN(numVerts, sizeof(*vert_clnors), __func__);
BKE_mesh_normals_loop_to_vertex(numVerts, dm->getLoopArray(dm), dm->getNumLoops(dm), BKE_mesh_normals_loop_to_vertex(numVerts, dm->getLoopArray(dm), dm->getNumLoops(dm),
(const float (*)[3])clnors, vert_clnors); (const float (*)[3])clnors, vert_clnors);
} }

View File

@@ -119,9 +119,9 @@ static void createFacepa(ExplodeModifierData *emd,
if (emd->facepa) if (emd->facepa)
MEM_freeN(emd->facepa); MEM_freeN(emd->facepa);
facepa = emd->facepa = MEM_callocN(sizeof(int) * totface, "explode_facepa"); facepa = emd->facepa = MEM_calloc_arrayN(totface, sizeof(int), "explode_facepa");
vertpa = MEM_callocN(sizeof(int) * totvert, "explode_vertpa"); vertpa = MEM_calloc_arrayN(totvert, sizeof(int), "explode_vertpa");
/* initialize all faces & verts to no particle */ /* initialize all faces & verts to no particle */
for (i = 0; i < totface; i++) for (i = 0; i < totface; i++)
@@ -557,8 +557,8 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm)
int totvert = dm->getNumVerts(dm); int totvert = dm->getNumVerts(dm);
int totface = dm->getNumTessFaces(dm); int totface = dm->getNumTessFaces(dm);
int *facesplit = MEM_callocN(sizeof(int) * totface, "explode_facesplit"); int *facesplit = MEM_calloc_arrayN(totface, sizeof(int), "explode_facesplit");
int *vertpa = MEM_callocN(sizeof(int) * totvert, "explode_vertpa2"); int *vertpa = MEM_calloc_arrayN(totvert, sizeof(int), "explode_vertpa2");
int *facepa = emd->facepa; int *facepa = emd->facepa;
int *fs, totesplit = 0, totfsplit = 0, curdupface = 0; int *fs, totesplit = 0, totfsplit = 0, curdupface = 0;
int i, v1, v2, v3, v4, esplit, int i, v1, v2, v3, v4, esplit,
@@ -656,7 +656,7 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm)
* later interpreted as tri's, for this to work right I think we probably * later interpreted as tri's, for this to work right I think we probably
* have to stop using tessface - campbell */ * have to stop using tessface - campbell */
facepa = MEM_callocN(sizeof(int) * (totface + (totfsplit * 2)), "explode_facepa"); facepa = MEM_calloc_arrayN((totface + (totfsplit * 2)), sizeof(int), "explode_facepa");
//memcpy(facepa, emd->facepa, totface*sizeof(int)); //memcpy(facepa, emd->facepa, totface*sizeof(int));
emd->facepa = facepa; emd->facepa = facepa;

View File

@@ -239,7 +239,7 @@ static DerivedMesh *fluidsim_read_obj(const char *filename, const MPoly *mp_exam
return NULL; return NULL;
} }
normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals"); normals = MEM_calloc_arrayN(numverts, 3 * sizeof(short), "fluid_tmp_normals");
if (!normals) { if (!normals) {
if (dm) if (dm)
dm->release(dm); dm->release(dm);
@@ -384,7 +384,7 @@ static void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *
if (fss->domainNovecgen > 0) return; if (fss->domainNovecgen > 0) return;
fss->meshVelocities = MEM_callocN(sizeof(FluidVertexVelocity) * dm->getNumVerts(dm), "Fluidsim_velocities"); fss->meshVelocities = MEM_calloc_arrayN(dm->getNumVerts(dm), sizeof(FluidVertexVelocity), "Fluidsim_velocities");
fss->totvert = totvert; fss->totvert = totvert;
velarray = fss->meshVelocities; velarray = fss->meshVelocities;

View File

@@ -108,12 +108,12 @@ static LaplacianSystem *initLaplacianSystem(
sys->total_anchors = totalAnchors; sys->total_anchors = totalAnchors;
sys->repeat = iterations; sys->repeat = iterations;
BLI_strncpy(sys->anchor_grp_name, defgrpName, sizeof(sys->anchor_grp_name)); BLI_strncpy(sys->anchor_grp_name, defgrpName, sizeof(sys->anchor_grp_name));
sys->co = MEM_mallocN(sizeof(float[3]) * totalVerts, "DeformCoordinates"); sys->co = MEM_malloc_arrayN(totalVerts, sizeof(float[3]), "DeformCoordinates");
sys->no = MEM_callocN(sizeof(float[3]) * totalVerts, "DeformNormals"); sys->no = MEM_calloc_arrayN(totalVerts, sizeof(float[3]), "DeformNormals");
sys->delta = MEM_callocN(sizeof(float[3]) * totalVerts, "DeformDeltas"); sys->delta = MEM_calloc_arrayN(totalVerts, sizeof(float[3]), "DeformDeltas");
sys->tris = MEM_mallocN(sizeof(int[3]) * totalTris, "DeformFaces"); sys->tris = MEM_malloc_arrayN(totalTris, sizeof(int[3]), "DeformFaces");
sys->index_anchors = MEM_mallocN(sizeof(int) * (totalAnchors), "DeformAnchors"); sys->index_anchors = MEM_malloc_arrayN((totalAnchors), sizeof(int), "DeformAnchors");
sys->unit_verts = MEM_callocN(sizeof(int) * totalVerts, "DeformUnitVerts"); sys->unit_verts = MEM_calloc_arrayN(totalVerts, sizeof(int), "DeformUnitVerts");
return sys; return sys;
} }
@@ -142,7 +142,7 @@ static void createFaceRingMap(
{ {
int i, j, totalr = 0; int i, j, totalr = 0;
int *indices, *index_iter; int *indices, *index_iter;
MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * mvert_tot, "DeformRingMap"); MeshElemMap *map = MEM_calloc_arrayN(mvert_tot, sizeof(MeshElemMap), "DeformRingMap");
const MLoopTri *mlt; const MLoopTri *mlt;
for (i = 0, mlt = mlooptri; i < mtri_tot; i++, mlt++) { for (i = 0, mlt = mlooptri; i < mtri_tot; i++, mlt++) {
@@ -153,7 +153,7 @@ static void createFaceRingMap(
totalr++; totalr++;
} }
} }
indices = MEM_callocN(sizeof(int) * totalr, "DeformRingIndex"); indices = MEM_calloc_arrayN(totalr, sizeof(int), "DeformRingIndex");
index_iter = indices; index_iter = indices;
for (i = 0; i < mvert_tot; i++) { for (i = 0; i < mvert_tot; i++) {
map[i].indices = index_iter; map[i].indices = index_iter;
@@ -175,7 +175,7 @@ static void createVertRingMap(
const int mvert_tot, const MEdge *medge, const int medge_tot, const int mvert_tot, const MEdge *medge, const int medge_tot,
MeshElemMap **r_map, int **r_indices) MeshElemMap **r_map, int **r_indices)
{ {
MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * mvert_tot, "DeformNeighborsMap"); MeshElemMap *map = MEM_calloc_arrayN(mvert_tot, sizeof(MeshElemMap), "DeformNeighborsMap");
int i, vid[2], totalr = 0; int i, vid[2], totalr = 0;
int *indices, *index_iter; int *indices, *index_iter;
const MEdge *me; const MEdge *me;
@@ -187,7 +187,7 @@ static void createVertRingMap(
map[vid[1]].count++; map[vid[1]].count++;
totalr += 2; totalr += 2;
} }
indices = MEM_callocN(sizeof(int) * totalr, "DeformNeighborsIndex"); indices = MEM_calloc_arrayN(totalr, sizeof(int), "DeformNeighborsIndex");
index_iter = indices; index_iter = indices;
for (i = 0; i < mvert_tot; i++) { for (i = 0; i < mvert_tot; i++) {
map[i].indices = index_iter; map[i].indices = index_iter;
@@ -521,7 +521,7 @@ static void initSystem(LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh
LaplacianSystem *sys; LaplacianSystem *sys;
if (isValidVertexGroup(lmd, ob, dm)) { if (isValidVertexGroup(lmd, ob, dm)) {
int *index_anchors = MEM_mallocN(sizeof(int) * numVerts, __func__); /* over-alloc */ int *index_anchors = MEM_malloc_arrayN(numVerts, sizeof(int), __func__); /* over-alloc */
const MLoopTri *mlooptri; const MLoopTri *mlooptri;
const MLoop *mloop; const MLoop *mloop;
@@ -547,7 +547,7 @@ static void initSystem(LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh
memcpy(sys->index_anchors, index_anchors, sizeof(int) * total_anchors); memcpy(sys->index_anchors, index_anchors, sizeof(int) * total_anchors);
memcpy(sys->co, vertexCos, sizeof(float[3]) * numVerts); memcpy(sys->co, vertexCos, sizeof(float[3]) * numVerts);
MEM_freeN(index_anchors); MEM_freeN(index_anchors);
lmd->vertexco = MEM_mallocN(sizeof(float[3]) * numVerts, "ModDeformCoordinates"); lmd->vertexco = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "ModDeformCoordinates");
memcpy(lmd->vertexco, vertexCos, sizeof(float[3]) * numVerts); memcpy(lmd->vertexco, vertexCos, sizeof(float[3]) * numVerts);
lmd->total_verts = numVerts; lmd->total_verts = numVerts;
@@ -631,7 +631,7 @@ static void LaplacianDeformModifier_do(
sys = lmd->cache_system; sys = lmd->cache_system;
if (sysdif) { if (sysdif) {
if (sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_ANCHORS || sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_GROUP) { if (sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_ANCHORS || sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_GROUP) {
filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempModDeformCoordinates"); filevertexCos = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "TempModDeformCoordinates");
memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts); memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
MEM_SAFE_FREE(lmd->vertexco); MEM_SAFE_FREE(lmd->vertexco);
lmd->total_verts = 0; lmd->total_verts = 0;
@@ -667,7 +667,7 @@ static void LaplacianDeformModifier_do(
lmd->flag &= ~MOD_LAPLACIANDEFORM_BIND; lmd->flag &= ~MOD_LAPLACIANDEFORM_BIND;
} }
else if (lmd->total_verts > 0 && lmd->total_verts == numVerts) { else if (lmd->total_verts > 0 && lmd->total_verts == numVerts) {
filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempDeformCoordinates"); filevertexCos = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "TempDeformCoordinates");
memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts); memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
MEM_SAFE_FREE(lmd->vertexco); MEM_SAFE_FREE(lmd->vertexco);
lmd->total_verts = 0; lmd->total_verts = 0;

View File

@@ -132,14 +132,14 @@ static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numPolys, in
sys->numLoops = a_numLoops; sys->numLoops = a_numLoops;
sys->numVerts = a_numVerts; sys->numVerts = a_numVerts;
sys->eweights = MEM_callocN(sizeof(float) * sys->numEdges, __func__); sys->eweights = MEM_calloc_arrayN(sys->numEdges, sizeof(float), __func__);
sys->fweights = MEM_callocN(sizeof(float[3]) * sys->numLoops, __func__); sys->fweights = MEM_calloc_arrayN(sys->numLoops, sizeof(float[3]), __func__);
sys->numNeEd = MEM_callocN(sizeof(short) * sys->numVerts, __func__); sys->numNeEd = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
sys->numNeFa = MEM_callocN(sizeof(short) * sys->numVerts, __func__); sys->numNeFa = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
sys->ring_areas = MEM_callocN(sizeof(float) * sys->numVerts, __func__); sys->ring_areas = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
sys->vlengths = MEM_callocN(sizeof(float) * sys->numVerts, __func__); sys->vlengths = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
sys->vweights = MEM_callocN(sizeof(float) * sys->numVerts, __func__); sys->vweights = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
sys->zerola = MEM_callocN(sizeof(short) * sys->numVerts, __func__); sys->zerola = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
return sys; return sys;
} }

View File

@@ -162,7 +162,7 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
* - each cell is a boolean saying whether bone corresponding to the ith group is selected * - each cell is a boolean saying whether bone corresponding to the ith group is selected
* - groups that don't match a bone are treated as not existing (along with the corresponding ungrouped verts) * - groups that don't match a bone are treated as not existing (along with the corresponding ungrouped verts)
*/ */
bone_select_array = MEM_mallocN((size_t)defbase_tot * sizeof(char), "mask array"); bone_select_array = MEM_malloc_arrayN((size_t)defbase_tot, sizeof(char), "mask array");
for (i = 0, def = ob->defbase.first; def; def = def->next, i++) { for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
pchan = BKE_pose_channel_find_name(oba->pose, def->name); pchan = BKE_pose_channel_find_name(oba->pose, def->name);
@@ -246,7 +246,7 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
mloop_src = dm->getLoopArray(dm); mloop_src = dm->getLoopArray(dm);
/* overalloc, assume all polys are seen */ /* overalloc, assume all polys are seen */
loop_mapping = MEM_mallocN(sizeof(int) * (size_t)maxPolys, "mask loopmap"); loop_mapping = MEM_malloc_arrayN((size_t)maxPolys, sizeof(int), "mask loopmap");
/* loop over edges and faces, and do the same thing to /* loop over edges and faces, and do the same thing to
* ensure that they only reference existing verts * ensure that they only reference existing verts

View File

@@ -94,7 +94,7 @@ static void meshcache_do(
{ {
const bool use_factor = mcmd->factor < 1.0f; const bool use_factor = mcmd->factor < 1.0f;
float (*vertexCos_Store)[3] = (use_factor || (mcmd->deform_mode == MOD_MESHCACHE_DEFORM_INTEGRATE)) ? float (*vertexCos_Store)[3] = (use_factor || (mcmd->deform_mode == MOD_MESHCACHE_DEFORM_INTEGRATE)) ?
MEM_mallocN(sizeof(*vertexCos_Store) * numVerts, __func__) : NULL; MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_Store), __func__) : NULL;
float (*vertexCos)[3] = vertexCos_Store ? vertexCos_Store : vertexCos_Real; float (*vertexCos)[3] = vertexCos_Store ? vertexCos_Store : vertexCos_Real;
Scene *scene = mcmd->modifier.scene; Scene *scene = mcmd->modifier.scene;
@@ -197,8 +197,8 @@ static void meshcache_do(
/* the moons align! */ /* the moons align! */
int i; int i;
float (*vertexCos_Source)[3] = MEM_mallocN(sizeof(*vertexCos_Source) * numVerts, __func__); float (*vertexCos_Source)[3] = MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_Source), __func__);
float (*vertexCos_New)[3] = MEM_mallocN(sizeof(*vertexCos_New) * numVerts, __func__); float (*vertexCos_New)[3] = MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_New), __func__);
MVert *mv = me->mvert; MVert *mv = me->mvert;
for (i = 0; i < numVerts; i++, mv++) { for (i = 0; i < numVerts; i++, mv++) {

View File

@@ -361,7 +361,7 @@ static void meshdeformModifier_do(
return; return;
} }
cagecos = MEM_mallocN(sizeof(*cagecos) * totcagevert, "meshdeformModifier vertCos"); cagecos = MEM_malloc_arrayN(totcagevert, sizeof(*cagecos), "meshdeformModifier vertCos");
/* setup deformation data */ /* setup deformation data */
cagedm->getVertCos(cagedm, cagecos); cagedm->getVertCos(cagedm, cagecos);
@@ -370,7 +370,7 @@ static void meshdeformModifier_do(
/* We allocate 1 element extra to make it possible to /* We allocate 1 element extra to make it possible to
* load the values to SSE registers, which are float4. * load the values to SSE registers, which are float4.
*/ */
dco = MEM_callocN(sizeof(*dco) * (totcagevert + 1), "MDefDco"); dco = MEM_calloc_arrayN((totcagevert + 1), sizeof(*dco), "MDefDco");
zero_v3(dco[totcagevert]); zero_v3(dco[totcagevert]);
for (a = 0; a < totcagevert; a++) { for (a = 0; a < totcagevert; a++) {
/* get cage vertex in world space with binding transform */ /* get cage vertex in world space with binding transform */
@@ -467,8 +467,8 @@ void modifier_mdef_compact_influences(ModifierData *md)
} }
/* allocate bind influences */ /* allocate bind influences */
mmd->bindinfluences = MEM_callocN(sizeof(MDefInfluence) * mmd->totinfluence, "MDefBindInfluence"); mmd->bindinfluences = MEM_calloc_arrayN(mmd->totinfluence, sizeof(MDefInfluence), "MDefBindInfluence");
mmd->bindoffsets = MEM_callocN(sizeof(int) * (totvert + 1), "MDefBindOffset"); mmd->bindoffsets = MEM_calloc_arrayN((totvert + 1), sizeof(int), "MDefBindOffset");
/* write influences */ /* write influences */
totinfluence = 0; totinfluence = 0;

View File

@@ -167,7 +167,7 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
if (do_vtargetmap) { if (do_vtargetmap) {
/* second half is filled with -1 */ /* second half is filled with -1 */
vtargetmap = MEM_mallocN(sizeof(int) * maxVerts * 2, "MOD_mirror tarmap"); vtargetmap = MEM_malloc_arrayN(maxVerts, 2 * sizeof(int), "MOD_mirror tarmap");
vtmap_a = vtargetmap; vtmap_a = vtargetmap;
vtmap_b = vtargetmap + maxVerts; vtmap_b = vtargetmap + maxVerts;

View File

@@ -117,7 +117,7 @@ static void mix_normals(
int i; int i;
if (dvert) { if (dvert) {
facs = MEM_mallocN(sizeof(*facs) * (size_t)num_loops, __func__); facs = MEM_malloc_arrayN((size_t)num_loops, sizeof(*facs), __func__);
BKE_defvert_extract_vgroup_to_loopweights( BKE_defvert_extract_vgroup_to_loopweights(
dvert, defgrp_index, num_verts, mloop, num_loops, facs, use_invert_vgroup); dvert, defgrp_index, num_verts, mloop, num_loops, facs, use_invert_vgroup);
} }
@@ -195,8 +195,8 @@ static void normalEditModifier_do_radial(
{ {
int i; int i;
float (*cos)[3] = MEM_mallocN(sizeof(*cos) * num_verts, __func__); float (*cos)[3] = MEM_malloc_arrayN((size_t)num_verts, sizeof(*cos), __func__);
float (*nos)[3] = MEM_mallocN(sizeof(*nos) * num_loops, __func__); float (*nos)[3] = MEM_malloc_arrayN((size_t)num_loops, sizeof(*nos), __func__);
float size[3]; float size[3];
BLI_bitmap *done_verts = BLI_BITMAP_NEW((size_t)num_verts, __func__); BLI_bitmap *done_verts = BLI_BITMAP_NEW((size_t)num_verts, __func__);
@@ -294,8 +294,8 @@ static void normalEditModifier_do_directional(
{ {
const bool use_parallel_normals = (enmd->flag & MOD_NORMALEDIT_USE_DIRECTION_PARALLEL) != 0; const bool use_parallel_normals = (enmd->flag & MOD_NORMALEDIT_USE_DIRECTION_PARALLEL) != 0;
float (*cos)[3] = MEM_mallocN(sizeof(*cos) * num_verts, __func__); float (*cos)[3] = MEM_malloc_arrayN((size_t)num_verts, sizeof(*cos), __func__);
float (*nos)[3] = MEM_mallocN(sizeof(*nos) * num_loops, __func__); float (*nos)[3] = MEM_malloc_arrayN((size_t)num_loops, sizeof(*nos), __func__);
float target_co[3]; float target_co[3];
int i; int i;
@@ -434,7 +434,7 @@ static DerivedMesh *normalEditModifier_do(NormalEditModifierData *enmd, Object *
polynors = dm->getPolyDataArray(dm, CD_NORMAL); polynors = dm->getPolyDataArray(dm, CD_NORMAL);
if (!polynors) { if (!polynors) {
polynors = MEM_mallocN(sizeof(*polynors) * num_polys, __func__); polynors = MEM_malloc_arrayN((size_t)num_polys, sizeof(*polynors), __func__);
BKE_mesh_calc_normals_poly(mvert, NULL, num_verts, mloop, mpoly, num_loops, num_polys, polynors, false); BKE_mesh_calc_normals_poly(mvert, NULL, num_verts, mloop, mpoly, num_loops, num_polys, polynors, false);
free_polynors = true; free_polynors = true;
} }

View File

@@ -220,7 +220,7 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
if (pimd->flag & eParticleInstanceFlag_UseSize) { if (pimd->flag & eParticleInstanceFlag_UseSize) {
float *si; float *si;
si = size = MEM_callocN(totpart * sizeof(float), "particle size array"); si = size = MEM_calloc_arrayN(totpart, sizeof(float), "particle size array");
if (pimd->flag & eParticleInstanceFlag_Parents) { if (pimd->flag & eParticleInstanceFlag_Parents) {
for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++, si++) for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++, si++)

View File

@@ -139,7 +139,7 @@ static DerivedMesh *dm_remove_doubles_on_axis(
if (tot_doubles != 0) { if (tot_doubles != 0) {
uint tot = totvert * step_tot; uint tot = totvert * step_tot;
int *full_doubles_map = MEM_mallocN(sizeof(int) * tot, __func__); int *full_doubles_map = MEM_malloc_arrayN(tot, sizeof(int), __func__);
copy_vn_i(full_doubles_map, (int)tot, -1); copy_vn_i(full_doubles_map, (int)tot, -1);
uint tot_doubles_left = tot_doubles; uint tot_doubles_left = tot_doubles;
@@ -448,10 +448,10 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
mpoly_orig = dm->getPolyArray(dm); mpoly_orig = dm->getPolyArray(dm);
mloop_orig = dm->getLoopArray(dm); mloop_orig = dm->getLoopArray(dm);
edge_poly_map = MEM_mallocN(sizeof(*edge_poly_map) * totedge, __func__); edge_poly_map = MEM_malloc_arrayN(totedge, sizeof(*edge_poly_map), __func__);
memset(edge_poly_map, 0xff, sizeof(*edge_poly_map) * totedge); memset(edge_poly_map, 0xff, sizeof(*edge_poly_map) * totedge);
vert_loop_map = MEM_mallocN(sizeof(*vert_loop_map) * totvert, __func__); vert_loop_map = MEM_malloc_arrayN(totvert, sizeof(*vert_loop_map), __func__);
memset(vert_loop_map, 0xff, sizeof(*vert_loop_map) * totvert); memset(vert_loop_map, 0xff, sizeof(*vert_loop_map) * totvert);
for (i = 0, mp_orig = mpoly_orig; i < totpoly; i++, mp_orig++) { for (i = 0, mp_orig = mpoly_orig; i < totpoly; i++, mp_orig++) {
@@ -497,7 +497,7 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
* This makes the modifier faster with one less alloc. * This makes the modifier faster with one less alloc.
*/ */
vert_connect = MEM_mallocN(sizeof(ScrewVertConnect) * totvert, "ScrewVertConnect"); vert_connect = MEM_malloc_arrayN(totvert, sizeof(ScrewVertConnect), "ScrewVertConnect");
//vert_connect = (ScrewVertConnect *) &medge_new[totvert]; /* skip the first slice of verts */ //vert_connect = (ScrewVertConnect *) &medge_new[totvert]; /* skip the first slice of verts */
vc = vert_connect; vc = vert_connect;

View File

@@ -419,7 +419,7 @@ static Frame **collect_hull_frames(int v, SkinNode *frames,
int nbr, i; int nbr, i;
(*tothullframe) = emap[v].count; (*tothullframe) = emap[v].count;
hull_frames = MEM_callocN(sizeof(Frame *) * (*tothullframe), hull_frames = MEM_calloc_arrayN((*tothullframe), sizeof(Frame *),
"hull_from_frames.hull_frames"); "hull_from_frames.hull_frames");
i = 0; i = 0;
for (nbr = 0; nbr < emap[v].count; nbr++) { for (nbr = 0; nbr < emap[v].count; nbr++) {
@@ -600,7 +600,7 @@ static SkinNode *build_frames(const MVert *mvert, int totvert,
SkinNode *skin_nodes; SkinNode *skin_nodes;
int v; int v;
skin_nodes = MEM_callocN(sizeof(SkinNode) * totvert, "build_frames.skin_nodes"); skin_nodes = MEM_calloc_arrayN(totvert, sizeof(SkinNode), "build_frames.skin_nodes");
for (v = 0; v < totvert; v++) { for (v = 0; v < totvert; v++) {
if (emap[v].count <= 1) if (emap[v].count <= 1)
@@ -722,7 +722,7 @@ static EMat *build_edge_mats(const MVertSkin *vs,
stack = BLI_stack_new(sizeof(stack_elem), "build_edge_mats.stack"); stack = BLI_stack_new(sizeof(stack_elem), "build_edge_mats.stack");
visited_e = BLI_BITMAP_NEW(totedge, "build_edge_mats.visited_e"); visited_e = BLI_BITMAP_NEW(totedge, "build_edge_mats.visited_e");
emat = MEM_callocN(sizeof(EMat) * totedge, "build_edge_mats.emat"); emat = MEM_calloc_arrayN(totedge, sizeof(EMat), "build_edge_mats.emat");
/* Edge matrices are built from the root nodes, add all roots with /* Edge matrices are built from the root nodes, add all roots with
* children to the stack */ * children to the stack */
@@ -836,14 +836,14 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig)
totorigedge = orig->getNumEdges(orig); totorigedge = orig->getNumEdges(orig);
/* Get degree of all vertices */ /* Get degree of all vertices */
degree = MEM_callocN(sizeof(int) * totorigvert, "degree"); degree = MEM_calloc_arrayN(totorigvert, sizeof(int), "degree");
for (i = 0; i < totorigedge; i++) { for (i = 0; i < totorigedge; i++) {
degree[origedge[i].v1]++; degree[origedge[i].v1]++;
degree[origedge[i].v2]++; degree[origedge[i].v2]++;
} }
/* Per edge, store how many subdivisions are needed */ /* Per edge, store how many subdivisions are needed */
edge_subd = MEM_callocN(sizeof(int) * totorigedge, "edge_subd"); edge_subd = MEM_calloc_arrayN(totorigedge, sizeof(int), "edge_subd");
for (i = 0, totsubd = 0; i < totorigedge; i++) { for (i = 0, totsubd = 0; i < totorigedge; i++) {
edge_subd[i] += calc_edge_subdivisions(origvert, orignode, edge_subd[i] += calc_edge_subdivisions(origvert, orignode,
&origedge[i], degree); &origedge[i], degree);
@@ -882,7 +882,7 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig)
if (origdvert) { if (origdvert) {
const MDeformVert *dv1 = &origdvert[e->v1]; const MDeformVert *dv1 = &origdvert[e->v1];
const MDeformVert *dv2 = &origdvert[e->v2]; const MDeformVert *dv2 = &origdvert[e->v2];
vgroups = MEM_callocN(sizeof(*vgroups) * dv1->totweight, "vgroup"); vgroups = MEM_calloc_arrayN(dv1->totweight, sizeof(*vgroups), "vgroup");
/* Only want vertex groups used by both vertices */ /* Only want vertex groups used by both vertices */
for (j = 0; j < dv1->totweight; j++) { for (j = 0; j < dv1->totweight; j++) {

View File

@@ -102,10 +102,10 @@ static void smoothModifier_do(
unsigned char *uctmp; unsigned char *uctmp;
float *ftmp, fac, facm; float *ftmp, fac, facm;
ftmp = (float *)MEM_callocN(3 * sizeof(float) * numVerts, ftmp = (float *)MEM_calloc_arrayN(numVerts, 3 * sizeof(float),
"smoothmodifier_f"); "smoothmodifier_f");
if (!ftmp) return; if (!ftmp) return;
uctmp = (unsigned char *)MEM_callocN(sizeof(unsigned char) * numVerts, uctmp = (unsigned char *)MEM_calloc_arrayN(numVerts, sizeof(unsigned char),
"smoothmodifier_uc"); "smoothmodifier_uc");
if (!uctmp) { if (!uctmp) {
if (ftmp) MEM_freeN(ftmp); if (ftmp) MEM_freeN(ftmp);

View File

@@ -101,7 +101,7 @@ static void dm_calc_normal(DerivedMesh *dm, float (*face_nors)[3], float (*r_ver
mp = mpoly; mp = mpoly;
{ {
EdgeFaceRef *edge_ref_array = MEM_callocN(sizeof(EdgeFaceRef) * (size_t)numEdges, "Edge Connectivity"); EdgeFaceRef *edge_ref_array = MEM_calloc_arrayN((size_t)numEdges, sizeof(EdgeFaceRef), "Edge Connectivity");
EdgeFaceRef *edge_ref; EdgeFaceRef *edge_ref;
float edge_normal[3]; float edge_normal[3];
@@ -235,7 +235,7 @@ static DerivedMesh *applyModifier(
unsigned int *new_edge_arr = NULL; unsigned int *new_edge_arr = NULL;
STACK_DECLARE(new_edge_arr); STACK_DECLARE(new_edge_arr);
unsigned int *old_vert_arr = MEM_callocN(sizeof(*old_vert_arr) * (size_t)numVerts, "old_vert_arr in solidify"); unsigned int *old_vert_arr = MEM_calloc_arrayN(numVerts, sizeof(*old_vert_arr), "old_vert_arr in solidify");
unsigned int *edge_users = NULL; unsigned int *edge_users = NULL;
char *edge_order = NULL; char *edge_order = NULL;
@@ -270,7 +270,7 @@ static DerivedMesh *applyModifier(
if (need_face_normals) { if (need_face_normals) {
/* calculate only face normals */ /* calculate only face normals */
face_nors = MEM_mallocN(sizeof(*face_nors) * (size_t)numFaces, __func__); face_nors = MEM_malloc_arrayN(numFaces, sizeof(*face_nors), __func__);
BKE_mesh_calc_normals_poly( BKE_mesh_calc_normals_poly(
orig_mvert, NULL, (int)numVerts, orig_mvert, NULL, (int)numVerts,
orig_mloop, orig_mpoly, orig_mloop, orig_mpoly,
@@ -289,11 +289,11 @@ static DerivedMesh *applyModifier(
#define INVALID_UNUSED ((unsigned int)-1) #define INVALID_UNUSED ((unsigned int)-1)
#define INVALID_PAIR ((unsigned int)-2) #define INVALID_PAIR ((unsigned int)-2)
new_vert_arr = MEM_mallocN(sizeof(*new_vert_arr) * (size_t)(numVerts * 2), __func__); new_vert_arr = MEM_malloc_arrayN(numVerts, 2 * sizeof(*new_vert_arr), __func__);
new_edge_arr = MEM_mallocN(sizeof(*new_edge_arr) * (size_t)((numEdges * 2) + numVerts), __func__); new_edge_arr = MEM_malloc_arrayN(((numEdges * 2) + numVerts), sizeof(*new_edge_arr), __func__);
edge_users = MEM_mallocN(sizeof(*edge_users) * (size_t)numEdges, "solid_mod edges"); edge_users = MEM_malloc_arrayN(numEdges, sizeof(*edge_users), "solid_mod edges");
edge_order = MEM_mallocN(sizeof(*edge_order) * (size_t)numEdges, "solid_mod eorder"); edge_order = MEM_malloc_arrayN(numEdges, sizeof(*edge_order), "solid_mod eorder");
/* save doing 2 loops here... */ /* save doing 2 loops here... */
@@ -366,7 +366,7 @@ static DerivedMesh *applyModifier(
} }
if (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) { if (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) {
vert_nors = MEM_callocN(sizeof(float) * (size_t)numVerts * 3, "mod_solid_vno_hq"); vert_nors = MEM_calloc_arrayN(numVerts, 3 * sizeof(float), "mod_solid_vno_hq");
dm_calc_normal(dm, face_nors, vert_nors); dm_calc_normal(dm, face_nors, vert_nors);
} }
@@ -517,7 +517,7 @@ static DerivedMesh *applyModifier(
if (do_clamp) { if (do_clamp) {
unsigned int i; unsigned int i;
vert_lens = MEM_mallocN(sizeof(float) * numVerts, "vert_lens"); vert_lens = MEM_malloc_arrayN(numVerts, sizeof(float), "vert_lens");
copy_vn_fl(vert_lens, (int)numVerts, FLT_MAX); copy_vn_fl(vert_lens, (int)numVerts, FLT_MAX);
for (i = 0; i < numEdges; i++) { for (i = 0; i < numEdges; i++) {
const float ed_len_sq = len_squared_v3v3(mvert[medge[i].v1].co, mvert[medge[i].v2].co); const float ed_len_sq = len_squared_v3v3(mvert[medge[i].v1].co, mvert[medge[i].v2].co);
@@ -596,13 +596,13 @@ static DerivedMesh *applyModifier(
const bool check_non_manifold = (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) != 0; const bool check_non_manifold = (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) != 0;
#endif #endif
/* same as EM_solidify() in editmesh_lib.c */ /* same as EM_solidify() in editmesh_lib.c */
float *vert_angles = MEM_callocN(sizeof(float) * numVerts * 2, "mod_solid_pair"); /* 2 in 1 */ float *vert_angles = MEM_calloc_arrayN(numVerts, 2 * sizeof(float), "mod_solid_pair"); /* 2 in 1 */
float *vert_accum = vert_angles + numVerts; float *vert_accum = vert_angles + numVerts;
unsigned int vidx; unsigned int vidx;
unsigned int i; unsigned int i;
if (vert_nors == NULL) { if (vert_nors == NULL) {
vert_nors = MEM_mallocN(sizeof(float) * numVerts * 3, "mod_solid_vno"); vert_nors = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "mod_solid_vno");
for (i = 0, mv = mvert; i < numVerts; i++, mv++) { for (i = 0, mv = mvert; i < numVerts; i++, mv++) {
normal_short_to_float_v3(vert_nors[i], mv->no); normal_short_to_float_v3(vert_nors[i], mv->no);
} }
@@ -682,7 +682,7 @@ static DerivedMesh *applyModifier(
} }
if (do_clamp) { if (do_clamp) {
float *vert_lens_sq = MEM_mallocN(sizeof(float) * numVerts, "vert_lens"); float *vert_lens_sq = MEM_malloc_arrayN(numVerts, sizeof(float), "vert_lens");
const float offset = fabsf(smd->offset) * smd->offset_clamp; const float offset = fabsf(smd->offset) * smd->offset_clamp;
const float offset_sq = offset * offset; const float offset_sq = offset * offset;
copy_vn_fl(vert_lens_sq, (int)numVerts, FLT_MAX); copy_vn_fl(vert_lens_sq, (int)numVerts, FLT_MAX);
@@ -765,7 +765,7 @@ static DerivedMesh *applyModifier(
#ifdef SOLIDIFY_SIDE_NORMALS #ifdef SOLIDIFY_SIDE_NORMALS
const bool do_side_normals = !(result->dirty & DM_DIRTY_NORMALS); const bool do_side_normals = !(result->dirty & DM_DIRTY_NORMALS);
/* annoying to allocate these since we only need the edge verts, */ /* annoying to allocate these since we only need the edge verts, */
float (*edge_vert_nos)[3] = do_side_normals ? MEM_callocN(sizeof(float) * numVerts * 3, __func__) : NULL; float (*edge_vert_nos)[3] = do_side_normals ? MEM_calloc_arrayN(numVerts, 3 * sizeof(float), __func__) : NULL;
float nor[3]; float nor[3];
#endif #endif
const unsigned char crease_rim = smd->crease_rim * 255.0f; const unsigned char crease_rim = smd->crease_rim * 255.0f;

View File

@@ -130,8 +130,8 @@ static void deformVerts(ModifierData *md, const struct EvaluationContext *UNUSED
surmd->v = NULL; surmd->v = NULL;
} }
surmd->x = MEM_callocN(numverts * sizeof(MVert), "MVert"); surmd->x = MEM_calloc_arrayN(numverts, sizeof(MVert), "MVert");
surmd->v = MEM_callocN(numverts * sizeof(MVert), "MVert"); surmd->v = MEM_calloc_arrayN(numverts, sizeof(MVert), "MVert");
surmd->numverts = numverts; surmd->numverts = numverts;

View File

@@ -388,7 +388,7 @@ BLI_INLINE SDefBindWeightData *computeBindWeights(SDefBindCalcData * const data,
bwdata->numpoly = data->vert_edges[nearest].num / 2; bwdata->numpoly = data->vert_edges[nearest].num / 2;
bpoly = MEM_callocN(sizeof(*bpoly) * bwdata->numpoly, "SDefBindPoly"); bpoly = MEM_calloc_arrayN(bwdata->numpoly, sizeof(*bpoly), "SDefBindPoly");
if (bpoly == NULL) { if (bpoly == NULL) {
freeBindData(bwdata); freeBindData(bwdata);
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
@@ -431,14 +431,14 @@ BLI_INLINE SDefBindWeightData *computeBindWeights(SDefBindCalcData * const data,
bpoly->numverts = poly->totloop; bpoly->numverts = poly->totloop;
bpoly->loopstart = poly->loopstart; bpoly->loopstart = poly->loopstart;
bpoly->coords = MEM_mallocN(sizeof(*bpoly->coords) * poly->totloop, "SDefBindPolyCoords"); bpoly->coords = MEM_malloc_arrayN(poly->totloop, sizeof(*bpoly->coords), "SDefBindPolyCoords");
if (bpoly->coords == NULL) { if (bpoly->coords == NULL) {
freeBindData(bwdata); freeBindData(bwdata);
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return NULL; return NULL;
} }
bpoly->coords_v2 = MEM_mallocN(sizeof(*bpoly->coords_v2) * poly->totloop, "SDefBindPolyCoords_v2"); bpoly->coords_v2 = MEM_malloc_arrayN(poly->totloop, sizeof(*bpoly->coords_v2), "SDefBindPolyCoords_v2");
if (bpoly->coords_v2 == NULL) { if (bpoly->coords_v2 == NULL) {
freeBindData(bwdata); freeBindData(bwdata);
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
@@ -765,7 +765,7 @@ static void bindVert(
return; return;
} }
sdvert->binds = MEM_callocN(sizeof(*sdvert->binds) * bwdata->numbinds, "SDefVertBindData"); sdvert->binds = MEM_calloc_arrayN(bwdata->numbinds, sizeof(*sdvert->binds), "SDefVertBindData");
if (sdvert->binds == NULL) { if (sdvert->binds == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
sdvert->numbinds = 0; sdvert->numbinds = 0;
@@ -787,13 +787,13 @@ static void bindVert(
sdbind->numverts = bpoly->numverts; sdbind->numverts = bpoly->numverts;
sdbind->mode = MOD_SDEF_MODE_NGON; sdbind->mode = MOD_SDEF_MODE_NGON;
sdbind->vert_weights = MEM_mallocN(sizeof(*sdbind->vert_weights) * bpoly->numverts, "SDefNgonVertWeights"); sdbind->vert_weights = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_weights), "SDefNgonVertWeights");
if (sdbind->vert_weights == NULL) { if (sdbind->vert_weights == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
} }
sdbind->vert_inds = MEM_mallocN(sizeof(*sdbind->vert_inds) * bpoly->numverts, "SDefNgonVertInds"); sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefNgonVertInds");
if (sdbind->vert_inds == NULL) { if (sdbind->vert_inds == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
@@ -823,13 +823,13 @@ static void bindVert(
sdbind->numverts = bpoly->numverts; sdbind->numverts = bpoly->numverts;
sdbind->mode = MOD_SDEF_MODE_CENTROID; sdbind->mode = MOD_SDEF_MODE_CENTROID;
sdbind->vert_weights = MEM_mallocN(sizeof(*sdbind->vert_weights) * 3, "SDefCentVertWeights"); sdbind->vert_weights = MEM_malloc_arrayN(3, sizeof(*sdbind->vert_weights), "SDefCentVertWeights");
if (sdbind->vert_weights == NULL) { if (sdbind->vert_weights == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
} }
sdbind->vert_inds = MEM_mallocN(sizeof(*sdbind->vert_inds) * bpoly->numverts, "SDefCentVertInds"); sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefCentVertInds");
if (sdbind->vert_inds == NULL) { if (sdbind->vert_inds == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
@@ -866,13 +866,13 @@ static void bindVert(
sdbind->numverts = bpoly->numverts; sdbind->numverts = bpoly->numverts;
sdbind->mode = MOD_SDEF_MODE_LOOPTRI; sdbind->mode = MOD_SDEF_MODE_LOOPTRI;
sdbind->vert_weights = MEM_mallocN(sizeof(*sdbind->vert_weights) * 3, "SDefTriVertWeights"); sdbind->vert_weights = MEM_malloc_arrayN(3, sizeof(*sdbind->vert_weights), "SDefTriVertWeights");
if (sdbind->vert_weights == NULL) { if (sdbind->vert_weights == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
} }
sdbind->vert_inds = MEM_mallocN(sizeof(*sdbind->vert_inds) * bpoly->numverts, "SDefTriVertInds"); sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefTriVertInds");
if (sdbind->vert_inds == NULL) { if (sdbind->vert_inds == NULL) {
data->success = MOD_SDEF_BIND_RESULT_MEM_ERR; data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
return; return;
@@ -923,20 +923,20 @@ static bool surfacedeformBind(SurfaceDeformModifierData *smd, float (*vertexCos)
SDefAdjacency *adj_array; SDefAdjacency *adj_array;
SDefEdgePolys *edge_polys; SDefEdgePolys *edge_polys;
vert_edges = MEM_callocN(sizeof(*vert_edges) * tnumverts, "SDefVertEdgeMap"); vert_edges = MEM_calloc_arrayN(tnumverts, sizeof(*vert_edges), "SDefVertEdgeMap");
if (vert_edges == NULL) { if (vert_edges == NULL) {
modifier_setError((ModifierData *)smd, "Out of memory"); modifier_setError((ModifierData *)smd, "Out of memory");
return false; return false;
} }
adj_array = MEM_mallocN(sizeof(*adj_array) * tnumedges * 2, "SDefVertEdge"); adj_array = MEM_malloc_arrayN(tnumedges, 2 * sizeof(*adj_array), "SDefVertEdge");
if (adj_array == NULL) { if (adj_array == NULL) {
modifier_setError((ModifierData *)smd, "Out of memory"); modifier_setError((ModifierData *)smd, "Out of memory");
MEM_freeN(vert_edges); MEM_freeN(vert_edges);
return false; return false;
} }
edge_polys = MEM_callocN(sizeof(*edge_polys) * tnumedges, "SDefEdgeFaceMap"); edge_polys = MEM_calloc_arrayN(tnumedges, sizeof(*edge_polys), "SDefEdgeFaceMap");
if (edge_polys == NULL) { if (edge_polys == NULL) {
modifier_setError((ModifierData *)smd, "Out of memory"); modifier_setError((ModifierData *)smd, "Out of memory");
MEM_freeN(vert_edges); MEM_freeN(vert_edges);
@@ -944,7 +944,7 @@ static bool surfacedeformBind(SurfaceDeformModifierData *smd, float (*vertexCos)
return false; return false;
} }
smd->verts = MEM_mallocN(sizeof(*smd->verts) * numverts, "SDefBindVerts"); smd->verts = MEM_malloc_arrayN(numverts, sizeof(*smd->verts), "SDefBindVerts");
if (smd->verts == NULL) { if (smd->verts == NULL) {
modifier_setError((ModifierData *)smd, "Out of memory"); modifier_setError((ModifierData *)smd, "Out of memory");
freeAdjacencyMap(vert_edges, adj_array, edge_polys); freeAdjacencyMap(vert_edges, adj_array, edge_polys);
@@ -981,7 +981,7 @@ static bool surfacedeformBind(SurfaceDeformModifierData *smd, float (*vertexCos)
.medge = medge, .medge = medge,
.mloop = mloop, .mloop = mloop,
.looptri = tdm->getLoopTriArray(tdm), .looptri = tdm->getLoopTriArray(tdm),
.targetCos = MEM_mallocN(sizeof(float[3]) * tnumverts, "SDefTargetBindVertArray"), .targetCos = MEM_malloc_arrayN(tnumverts, sizeof(float[3]), "SDefTargetBindVertArray"),
.bind_verts = smd->verts, .bind_verts = smd->verts,
.vertexCos = vertexCos, .vertexCos = vertexCos,
.falloff = smd->falloff, .falloff = smd->falloff,
@@ -1054,7 +1054,7 @@ static void deformVert(
for (int j = 0; j < data->bind_verts[index].numbinds; j++, sdbind++) { for (int j = 0; j < data->bind_verts[index].numbinds; j++, sdbind++) {
/* Mode-generic operations (allocate poly coordinates) */ /* Mode-generic operations (allocate poly coordinates) */
float (*coords)[3] = MEM_mallocN(sizeof(*coords) * sdbind->numverts, "SDefDoPolyCoords"); float (*coords)[3] = MEM_malloc_arrayN(sdbind->numverts, sizeof(*coords), "SDefDoPolyCoords");
for (int k = 0; k < sdbind->numverts; k++) { for (int k = 0; k < sdbind->numverts; k++) {
copy_v3_v3(coords[k], data->targetCos[sdbind->vert_inds[k]]); copy_v3_v3(coords[k], data->targetCos[sdbind->vert_inds[k]]);
@@ -1152,7 +1152,7 @@ static void surfacedeformModifier_do(ModifierData *md, float (*vertexCos)[3], un
/* Actual vertex location update starts here */ /* Actual vertex location update starts here */
SDefDeformData data = { SDefDeformData data = {
.bind_verts = smd->verts, .bind_verts = smd->verts,
.targetCos = MEM_mallocN(sizeof(float[3]) * tnumverts, "SDefTargetVertArray"), .targetCos = MEM_malloc_arrayN(tnumverts, sizeof(float[3]), "SDefTargetVertArray"),
.vertexCos = vertexCos, .vertexCos = vertexCos,
}; };

View File

@@ -87,7 +87,7 @@ void get_texture_coords(MappingInfoModifierData *dmd, Object *ob,
MPoly *mpoly = dm->getPolyArray(dm); MPoly *mpoly = dm->getPolyArray(dm);
MPoly *mp; MPoly *mp;
MLoop *mloop = dm->getLoopArray(dm); MLoop *mloop = dm->getLoopArray(dm);
char *done = MEM_callocN(sizeof(*done) * numVerts, char *done = MEM_calloc_arrayN(numVerts, sizeof(*done),
"get_texture_coords done"); "get_texture_coords done");
int numPolys = dm->getNumPolys(dm); int numPolys = dm->getNumPolys(dm);
char uvname[MAX_CUSTOMDATA_LAYER_NAME]; char uvname[MAX_CUSTOMDATA_LAYER_NAME];

View File

@@ -226,7 +226,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
numVerts = dm->getNumVerts(dm); numVerts = dm->getNumVerts(dm);
coords = MEM_mallocN(sizeof(*coords) * numVerts, coords = MEM_malloc_arrayN(numVerts, sizeof(*coords),
"uvprojectModifier_do coords"); "uvprojectModifier_do coords");
dm->getVertCos(dm, coords); dm->getVertCos(dm, coords);

View File

@@ -214,7 +214,7 @@ static void warpModifier_do(WarpModifierData *wmd, Object *ob,
weight = strength; weight = strength;
if (wmd->texture) { if (wmd->texture) {
tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts, "warpModifier_do tex_co"); tex_co = MEM_malloc_arrayN(numVerts, sizeof(*tex_co), "warpModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts); get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts);
modifier_init_texture(wmd->modifier.scene, wmd->texture); modifier_init_texture(wmd->modifier.scene, wmd->texture);

View File

@@ -206,7 +206,7 @@ static void waveModifier_do(WaveModifierData *md,
} }
if (wmd->texture) { if (wmd->texture) {
tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts, tex_co = MEM_malloc_arrayN(numVerts, sizeof(*tex_co),
"waveModifier_do tex_co"); "waveModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts); get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts);

View File

@@ -143,9 +143,9 @@ void weightvg_do_mask(int num, const int *indices, float *org_w, const float *ne
t_map.map_object = tex_map_object; t_map.map_object = tex_map_object;
BLI_strncpy(t_map.uvlayer_name, tex_uvlayer_name, sizeof(t_map.uvlayer_name)); BLI_strncpy(t_map.uvlayer_name, tex_uvlayer_name, sizeof(t_map.uvlayer_name));
t_map.texmapping = tex_mapping; t_map.texmapping = tex_mapping;
v_co = MEM_mallocN(sizeof(*v_co) * numVerts, "WeightVG Modifier, TEX mode, v_co"); v_co = MEM_malloc_arrayN(numVerts, sizeof(*v_co), "WeightVG Modifier, TEX mode, v_co");
dm->getVertCos(dm, v_co); dm->getVertCos(dm, v_co);
tex_co = MEM_callocN(sizeof(*tex_co) * numVerts, "WeightVG Modifier, TEX mode, tex_co"); tex_co = MEM_calloc_arrayN(numVerts, sizeof(*tex_co), "WeightVG Modifier, TEX mode, tex_co");
get_texture_coords(&t_map, ob, dm, v_co, tex_co, num); get_texture_coords(&t_map, ob, dm, v_co, tex_co, num);
MEM_freeN(v_co); MEM_freeN(v_co);

View File

@@ -213,9 +213,9 @@ static DerivedMesh *applyModifier(ModifierData *md,
} }
/* Get org weights, assuming 0.0 for vertices not in given vgroup. */ /* Get org weights, assuming 0.0 for vertices not in given vgroup. */
org_w = MEM_mallocN(sizeof(float) * numVerts, "WeightVGEdit Modifier, org_w"); org_w = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGEdit Modifier, org_w");
new_w = MEM_mallocN(sizeof(float) * numVerts, "WeightVGEdit Modifier, new_w"); new_w = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGEdit Modifier, new_w");
dw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGEdit Modifier, dw"); dw = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGEdit Modifier, dw");
for (i = 0; i < numVerts; i++) { for (i = 0; i < numVerts; i++) {
dw[i] = defvert_find_index(&dvert[i], defgrp_index); dw[i] = defvert_find_index(&dvert[i], defgrp_index);
if (dw[i]) { if (dw[i]) {

View File

@@ -265,9 +265,9 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
return dm; return dm;
} }
/* Find out which vertices to work on. */ /* Find out which vertices to work on. */
tidx = MEM_mallocN(sizeof(int) * numVerts, "WeightVGMix Modifier, tidx"); tidx = MEM_malloc_arrayN(numVerts, sizeof(int), "WeightVGMix Modifier, tidx");
tdw1 = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGMix Modifier, tdw1"); tdw1 = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGMix Modifier, tdw1");
tdw2 = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGMix Modifier, tdw2"); tdw2 = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGMix Modifier, tdw2");
switch (wmd->mix_set) { switch (wmd->mix_set) {
case MOD_WVG_SET_A: case MOD_WVG_SET_A:
/* All vertices in first vgroup. */ /* All vertices in first vgroup. */
@@ -333,12 +333,12 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
return dm; return dm;
} }
if (numIdx != -1) { if (numIdx != -1) {
indices = MEM_mallocN(sizeof(int) * numIdx, "WeightVGMix Modifier, indices"); indices = MEM_malloc_arrayN(numIdx, sizeof(int), "WeightVGMix Modifier, indices");
memcpy(indices, tidx, sizeof(int) * numIdx); memcpy(indices, tidx, sizeof(int) * numIdx);
dw1 = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGMix Modifier, dw1"); dw1 = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGMix Modifier, dw1");
memcpy(dw1, tdw1, sizeof(MDeformWeight *) * numIdx); memcpy(dw1, tdw1, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tdw1); MEM_freeN(tdw1);
dw2 = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGMix Modifier, dw2"); dw2 = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGMix Modifier, dw2");
memcpy(dw2, tdw2, sizeof(MDeformWeight *) * numIdx); memcpy(dw2, tdw2, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tdw2); MEM_freeN(tdw2);
} }
@@ -351,8 +351,8 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
} }
MEM_freeN(tidx); MEM_freeN(tidx);
org_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGMix Modifier, org_w"); org_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGMix Modifier, org_w");
new_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGMix Modifier, new_w"); new_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGMix Modifier, new_w");
/* Mix weights. */ /* Mix weights. */
for (i = 0; i < numIdx; i++) { for (i = 0; i < numIdx; i++) {

View File

@@ -433,9 +433,9 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
/* Find out which vertices to work on (all vertices in vgroup), and get their relevant weight. /* Find out which vertices to work on (all vertices in vgroup), and get their relevant weight.
*/ */
tidx = MEM_mallocN(sizeof(int) * numVerts, "WeightVGProximity Modifier, tidx"); tidx = MEM_malloc_arrayN(numVerts, sizeof(int), "WeightVGProximity Modifier, tidx");
tw = MEM_mallocN(sizeof(float) * numVerts, "WeightVGProximity Modifier, tw"); tw = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGProximity Modifier, tw");
tdw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGProximity Modifier, tdw"); tdw = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGProximity Modifier, tdw");
for (i = 0; i < numVerts; i++) { for (i = 0; i < numVerts; i++) {
MDeformWeight *_dw = defvert_find_index(&dvert[i], defgrp_index); MDeformWeight *_dw = defvert_find_index(&dvert[i], defgrp_index);
if (_dw) { if (_dw) {
@@ -452,11 +452,11 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
return dm; return dm;
} }
if (numIdx != numVerts) { if (numIdx != numVerts) {
indices = MEM_mallocN(sizeof(int) * numIdx, "WeightVGProximity Modifier, indices"); indices = MEM_malloc_arrayN(numIdx, sizeof(int), "WeightVGProximity Modifier, indices");
memcpy(indices, tidx, sizeof(int) * numIdx); memcpy(indices, tidx, sizeof(int) * numIdx);
org_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGProximity Modifier, org_w"); org_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGProximity Modifier, org_w");
memcpy(org_w, tw, sizeof(float) * numIdx); memcpy(org_w, tw, sizeof(float) * numIdx);
dw = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGProximity Modifier, dw"); dw = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGProximity Modifier, dw");
memcpy(dw, tdw, sizeof(MDeformWeight *) * numIdx); memcpy(dw, tdw, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tw); MEM_freeN(tw);
MEM_freeN(tdw); MEM_freeN(tdw);
@@ -465,16 +465,16 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
org_w = tw; org_w = tw;
dw = tdw; dw = tdw;
} }
new_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGProximity Modifier, new_w"); new_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGProximity Modifier, new_w");
MEM_freeN(tidx); MEM_freeN(tidx);
/* Get our vertex coordinates. */ /* Get our vertex coordinates. */
v_cos = MEM_mallocN(sizeof(float[3]) * numIdx, "WeightVGProximity Modifier, v_cos"); v_cos = MEM_malloc_arrayN(numIdx, sizeof(float[3]), "WeightVGProximity Modifier, v_cos");
if (numIdx != numVerts) { if (numIdx != numVerts) {
/* XXX In some situations, this code can be up to about 50 times more performant /* XXX In some situations, this code can be up to about 50 times more performant
* than simply using getVertCo for each affected vertex... * than simply using getVertCo for each affected vertex...
*/ */
float (*tv_cos)[3] = MEM_mallocN(sizeof(float[3]) * numVerts, "WeightVGProximity Modifier, tv_cos"); float (*tv_cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "WeightVGProximity Modifier, tv_cos");
dm->getVertCos(dm, tv_cos); dm->getVertCos(dm, tv_cos);
for (i = 0; i < numIdx; i++) for (i = 0; i < numIdx; i++)
copy_v3_v3(v_cos[i], tv_cos[indices[i]]); copy_v3_v3(v_cos[i], tv_cos[indices[i]]);
@@ -513,9 +513,9 @@ static DerivedMesh *applyModifier(ModifierData *md, const struct EvaluationConte
/* We must check that we do have a valid target_dm! */ /* We must check that we do have a valid target_dm! */
if (target_dm) { if (target_dm) {
SpaceTransform loc2trgt; SpaceTransform loc2trgt;
float *dists_v = use_trgt_verts ? MEM_mallocN(sizeof(float) * numIdx, "dists_v") : NULL; float *dists_v = use_trgt_verts ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_v") : NULL;
float *dists_e = use_trgt_edges ? MEM_mallocN(sizeof(float) * numIdx, "dists_e") : NULL; float *dists_e = use_trgt_edges ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_e") : NULL;
float *dists_f = use_trgt_faces ? MEM_mallocN(sizeof(float) * numIdx, "dists_f") : NULL; float *dists_f = use_trgt_faces ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_f") : NULL;
BLI_SPACE_TRANSFORM_SETUP(&loc2trgt, ob, obr); BLI_SPACE_TRANSFORM_SETUP(&loc2trgt, ob, obr);
get_vert2geom_distance(numIdx, v_cos, dists_v, dists_e, dists_f, get_vert2geom_distance(numIdx, v_cos, dists_v, dists_e, dists_f,

View File

@@ -35,3 +35,4 @@ set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} ${PLATFORM_LIN
BLENDER_TEST(guardedalloc_alignment "") BLENDER_TEST(guardedalloc_alignment "")
BLENDER_TEST(guardedalloc_overflow "")

View File

@@ -0,0 +1,61 @@
/* Apache License, Version 2.0 */
#include "testing/testing.h"
#include "MEM_guardedalloc.h"
/* We expect to abort on integer overflow, to prevent possible exploits. */
#ifdef _WIN32
#define ABORT_PREDICATE ::testing::ExitedWithCode(3)
#else
#define ABORT_PREDICATE ::testing::KilledBySignal(SIGABRT)
#endif
namespace {
void MallocArray(size_t len, size_t size)
{
void *mem = MEM_malloc_arrayN(len, size, "MallocArray");
if (mem) {
MEM_freeN(mem);
}
}
void CallocArray(size_t len, size_t size)
{
void *mem = MEM_calloc_arrayN(len, size, "CallocArray");
if (mem) {
MEM_freeN(mem);
}
}
} // namespace
TEST(guardedalloc, LockfreeIntegerOverflow)
{
MallocArray(1, SIZE_MAX);
CallocArray(SIZE_MAX, 1);
MallocArray(SIZE_MAX / 2, 2);
CallocArray(SIZE_MAX / 1234567, 1234567);
EXPECT_EXIT(MallocArray(SIZE_MAX, 2), ABORT_PREDICATE, "");
EXPECT_EXIT(CallocArray(7, SIZE_MAX), ABORT_PREDICATE, "");
EXPECT_EXIT(MallocArray(SIZE_MAX, 12345567), ABORT_PREDICATE, "");
EXPECT_EXIT(CallocArray(SIZE_MAX, SIZE_MAX), ABORT_PREDICATE, "");
}
TEST(guardedalloc, GuardedIntegerOverflow)
{
MEM_use_guarded_allocator();
MallocArray(1, SIZE_MAX);
CallocArray(SIZE_MAX, 1);
MallocArray(SIZE_MAX / 2, 2);
CallocArray(SIZE_MAX / 1234567, 1234567);
EXPECT_EXIT(MallocArray(SIZE_MAX, 2), ABORT_PREDICATE, "");
EXPECT_EXIT(CallocArray(7, SIZE_MAX), ABORT_PREDICATE, "");
EXPECT_EXIT(MallocArray(SIZE_MAX, 12345567), ABORT_PREDICATE, "");
EXPECT_EXIT(CallocArray(SIZE_MAX, SIZE_MAX), ABORT_PREDICATE, "");
}