4f8b1d6f77fc40717922e2fa8baad0e54aef5f20
[openjpeg.git] / src / lib / openjp2 / opj_malloc.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses
3  * BSD License, included below. This software may be subject to other third
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2015, Mathieu Malaterre <mathieu.malaterre@gmail.com>
8  * Copyright (c) 2015, Matthieu Darbois
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 #define OPJ_SKIP_POISON
33 #include "opj_includes.h"
34
35 #if defined(OPJ_HAVE_MALLOC_H) && defined(OPJ_HAVE_MEMALIGN)
36 # include <malloc.h>
37 #endif
38
39 #ifndef SIZE_MAX
40 # define SIZE_MAX ((size_t) -1)
41 #endif
42
43 static INLINE void *opj_aligned_alloc_n(size_t alignment, size_t size)
44 {
45   void* ptr;
46
47   /* alignment shall be power of 2 */
48   assert( (alignment != 0U) && ((alignment & (alignment - 1U)) == 0U));
49   /* alignment shall be at least sizeof(void*) */
50   assert( alignment >= sizeof(void*));
51
52   if (size == 0U) { /* prevent implementation defined behavior of realloc */
53     return NULL;
54   }
55
56 #if defined(OPJ_HAVE_POSIX_MEMALIGN)
57   /* aligned_alloc requires c11, restrict to posix_memalign for now. Quote:
58    * This function was introduced in POSIX 1003.1d. Although this function is
59    * superseded by aligned_alloc, it is more portable to older POSIX systems
60    * that do not support ISO C11.  */
61   if (posix_memalign (&ptr, alignment, size))
62   {
63     ptr = NULL;
64   }
65   /* older linux */
66 #elif defined(OPJ_HAVE_MEMALIGN)
67   ptr = memalign( alignment, size );
68 /* _MSC_VER */
69 #elif defined(OPJ_HAVE__ALIGNED_MALLOC)
70   ptr = _aligned_malloc(size, alignment);
71 #else
72   /*
73    * Generic aligned malloc implementation.
74    * Uses size_t offset for the integer manipulation of the pointer,
75    * as uintptr_t is not available in C89 to do
76    * bitwise operations on the pointer itself.
77    */
78   alignment--;
79   {
80     size_t offset;
81     OPJ_UINT8 *mem;
82
83     /* Room for padding and extra pointer stored in front of allocated area */
84     size_t overhead = alignment + sizeof(void *);
85
86     /* let's be extra careful */
87     assert(alignment <= (SIZE_MAX - sizeof(void *)));
88
89     /* Avoid integer overflow */
90     if (size > (SIZE_MAX - overhead)) {
91       return NULL;
92     }
93
94     mem = (OPJ_UINT8*)malloc(size + overhead);
95     if (mem == NULL) {
96       return mem;
97     }
98     /* offset = ((alignment + 1U) - ((size_t)(mem + sizeof(void*)) & alignment)) & alignment; */
99     /* Use the fact that alignment + 1U is a power of 2 */
100     offset = ((alignment ^ ((size_t)(mem + sizeof(void*)) & alignment)) + 1U) & alignment;
101     ptr = (void *)(mem + sizeof(void*) + offset);
102     ((void**) ptr)[-1] = mem;
103   }
104 #endif
105   return ptr;
106 }
107 static INLINE void *opj_aligned_realloc_n(void *ptr, size_t alignment, size_t new_size)
108 {
109   void *r_ptr;
110
111   /* alignment shall be power of 2 */
112   assert( (alignment != 0U) && ((alignment & (alignment - 1U)) == 0U));
113   /* alignment shall be at least sizeof(void*) */
114   assert( alignment >= sizeof(void*));
115
116   if (new_size == 0U) { /* prevent implementation defined behavior of realloc */
117     return NULL;
118   }
119
120 /* no portable aligned realloc */
121 #if defined(OPJ_HAVE_POSIX_MEMALIGN) || defined(OPJ_HAVE_MEMALIGN)
122   /* glibc doc states one can mix aligned malloc with realloc */
123   r_ptr = realloc( ptr, new_size ); /* fast path */
124   /* we simply use `size_t` to cast, since we are only interest in binary AND
125    * operator */
126   if( ((size_t)r_ptr & (alignment - 1U)) != 0U ) {
127     /* this is non-trivial to implement a portable aligned realloc, so use a
128      * simple approach where we do not need a function that return the size of an
129      * allocated array (eg. _msize on Windows, malloc_size on MacOS,
130      * malloc_usable_size on systems with glibc) */
131     void *a_ptr = opj_aligned_alloc_n(alignment, new_size);
132     if (a_ptr != NULL) {
133       memcpy(a_ptr, r_ptr, new_size);
134     }
135     free( r_ptr );
136     r_ptr = a_ptr;
137   }
138 /* _MSC_VER */
139 #elif defined(OPJ_HAVE__ALIGNED_MALLOC)
140   r_ptr = _aligned_realloc( ptr, new_size, alignment );
141 #else
142   if (ptr == NULL) {
143     return opj_aligned_alloc_n(alignment, new_size);
144   }
145   alignment--;
146   {
147     void *oldmem;
148     OPJ_UINT8 *newmem;
149     size_t overhead = alignment + sizeof(void *);
150
151     /* let's be extra careful */
152     assert(alignment <= (SIZE_MAX - sizeof(void *)));
153
154     /* Avoid integer overflow */
155     if (new_size > SIZE_MAX - overhead) {
156       return NULL;
157     }
158
159     oldmem = ((void**) ptr)[-1];
160     newmem = (OPJ_UINT8*)realloc(oldmem, new_size + overhead);
161     if (newmem == NULL) {
162       return newmem;
163     }
164
165     if (newmem == oldmem) {
166       r_ptr = ptr;
167     }
168     else {
169       size_t old_offset;
170       size_t new_offset;
171
172       /* realloc created a new copy, realign the copied memory block */
173       old_offset = (size_t)((OPJ_UINT8*)ptr - (OPJ_UINT8*)oldmem);
174
175       /* offset = ((alignment + 1U) - ((size_t)(mem + sizeof(void*)) & alignment)) & alignment; */
176       /* Use the fact that alignment + 1U is a power of 2 */
177       new_offset  = ((alignment ^ ((size_t)(newmem + sizeof(void*)) & alignment)) + 1U) & alignment;
178                         new_offset += sizeof(void*);
179       r_ptr = (void *)(newmem + new_offset);
180
181       if (new_offset != old_offset) {
182         memmove(newmem + new_offset, newmem + old_offset, new_size);
183       }
184       ((void**) r_ptr)[-1] = newmem;
185     }
186   }
187 #endif
188         return r_ptr;
189 }
190 void * opj_malloc(size_t size)
191 {
192   if (size == 0U) { /* prevent implementation defined behavior of realloc */
193     return NULL;
194   }
195   return malloc(size);
196 }
197 void * opj_calloc(size_t num, size_t size)
198 {
199   if (num == 0 || size == 0) {
200     /* prevent implementation defined behavior of realloc */
201     return NULL;
202   }
203   return calloc(num, size);
204 }
205
206 void *opj_aligned_malloc(size_t size)
207 {
208   return opj_aligned_alloc_n(16U, size);
209 }
210 void * opj_aligned_realloc(void *ptr, size_t size)
211 {
212   return opj_aligned_realloc_n(ptr, 16U, size);
213 }
214
215 void opj_aligned_free(void* ptr)
216 {
217 #if defined(OPJ_HAVE_POSIX_MEMALIGN) || defined(OPJ_HAVE_MEMALIGN)
218   free( ptr );
219 #elif defined(OPJ_HAVE__ALIGNED_MALLOC)
220   _aligned_free( ptr );
221 #else
222   /* Generic implementation has malloced pointer stored in front of used area */
223   if (ptr != NULL) {
224     free(((void**) ptr)[-1]);
225   }
226 #endif
227 }
228
229 void * opj_realloc(void *ptr, size_t new_size)
230 {
231   if (new_size == 0U) { /* prevent implementation defined behavior of realloc */
232     return NULL;
233   }
234   return realloc(ptr, new_size);
235 }
236 void opj_free(void *ptr)
237 {
238   free(ptr);
239 }