Blender  V2.93
mallocn_inline.h
Go to the documentation of this file.
1 /*
2  * Adapted from jemalloc, to protect against buffer overflow vulnerabilities.
3  *
4  * Copyright (C) 2002-2017 Jason Evans <jasone@canonware.com>.
5  * All rights reserved.
6  * Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
7  * Copyright (C) 2009-2017 Facebook, Inc. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are met:
11  * 1. Redistributions of source code must retain the above copyright notice(s),
12  * this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright notice(s),
14  * this list of conditions and the following disclaimer in the documentation
15  * and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20  * EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
25  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
33 #ifndef __MALLOCN_INLINE_H__
34 #define __MALLOCN_INLINE_H__
35 
36 #ifdef __cplusplus
37 extern "C" {
38 #endif
39 
40 MEM_INLINE bool MEM_size_safe_multiply(size_t a, size_t b, size_t *result)
41 {
42  /* A size_t with its high-half bits all set to 1. */
43  const size_t high_bits = SIZE_MAX << (sizeof(size_t) * 8 / 2);
44  *result = a * b;
45 
46  if (UNLIKELY(*result == 0)) {
47  return (a == 0 || b == 0);
48  }
49 
50  /*
51  * We got a non-zero size, but we don't know if we overflowed to get
52  * there. To avoid having to do a divide, we'll be clever and note that
53  * if both A and B can be represented in N/2 bits, then their product
54  * can be represented in N bits (without the possibility of overflow).
55  */
56  return ((high_bits & (a | b)) == 0 || (*result / b == a));
57 }
58 
59 #ifdef __cplusplus
60 }
61 #endif
62 
63 #endif /* __MALLOCN_INLINE_H__ */
#define UNLIKELY(x)
MEM_INLINE bool MEM_size_safe_multiply(size_t a, size_t b, size_t *result)
#define MEM_INLINE
static unsigned a[3]
Definition: RandGen.cpp:92
#define SIZE_MAX
Definition: stdint.h:209