Merge pull request #644 from smuehlst/opj_aligned_malloc
[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 #ifndef SIZE_MAX
36 # define SIZE_MAX ((size_t) -1)
37 #endif
38
39 static INLINE void *opj_aligned_alloc_n(size_t alignment, size_t size)
40 {
41   void* ptr;
42
43   /* alignment shall be power of 2 */
44   assert( (alignment != 0U) && ((alignment & (alignment - 1U)) == 0U));
45   /* alignment shall be at least sizeof(void*) */
46   assert( alignment >= sizeof(void*));
47
48   if (size == 0U) { /* prevent implementation defined behavior of realloc */
49     return NULL;
50   }
51
52 #if defined(HAVE_POSIX_MEMALIGN)
53   /* aligned_alloc requires c11, restrict to posix_memalign for now. Quote:
54    * This function was introduced in POSIX 1003.1d. Although this function is
55    * superseded by aligned_alloc, it is more portable to older POSIX systems
56    * that do not support ISO C11.  */
57   if (posix_memalign (&ptr, alignment, size))
58   {
59     ptr = NULL;
60   }
61   /* older linux */
62 #elif defined(HAVE_MEMALIGN)
63   ptr = memalign( alignment, size );
64 /* _MSC_VER */
65 #elif defined(HAVE__ALIGNED_MALLOC)
66   ptr = _aligned_malloc(size, alignment);
67 #else
68   /*
69    * Generic aligned malloc implementation.
70    * Uses size_t offset for the integer manipulation of the pointer,
71    * as uintptr_t is not available in C89 to do 
72    * bitwise operations on the pointer itself.
73    */
74   alignment--;
75   {
76     size_t offset;
77     OPJ_UINT8 *mem;
78
79     /* Room for padding and extra pointer stored in front of allocated area */
80     size_t overhead = alignment + sizeof(void *);
81                 
82     /* let's be extra careful */
83     assert(alignment <= (SIZE_MAX - sizeof(void *)));
84
85     /* Avoid integer overflow */
86     if (size > (SIZE_MAX - overhead)) {
87       return NULL;
88     }
89
90     mem = (OPJ_UINT8*)malloc(size + overhead);
91     if (mem == NULL) {
92       return mem;
93     }
94     /* offset = ((alignment + 1U) - ((size_t)(mem + sizeof(void*)) & alignment)) & alignment; */
95     /* Use the fact that alignment + 1U is a power of 2 */
96     offset = ((alignment ^ ((size_t)(mem + sizeof(void*)) & alignment)) + 1U) & alignment;
97     ptr = (void *)(mem + sizeof(void*) + offset);
98     ((void**) ptr)[-1] = mem;
99   }
100 #endif
101   return ptr;
102 }
103 static INLINE void *opj_aligned_realloc_n(void *ptr, size_t alignment, size_t new_size)
104 {
105   void *r_ptr;
106
107   /* alignment shall be power of 2 */
108   assert( (alignment != 0U) && ((alignment & (alignment - 1U)) == 0U));
109   /* alignment shall be at least sizeof(void*) */
110   assert( alignment >= sizeof(void*));
111
112   if (new_size == 0U) { /* prevent implementation defined behavior of realloc */
113     return NULL;
114   }
115
116 /* no portable aligned realloc */
117 #if defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
118   /* glibc doc states one can mixed aligned malloc with realloc */
119   r_ptr = realloc( ptr, new_size ); /* fast path */
120   /* we simply use `size_t` to cast, since we are only interest in binary AND
121    * operator */
122   if( ((size_t)r_ptr & (alignment - 1U)) != 0U ) {
123     /* this is non-trivial to implement a portable aligned realloc, so use a
124      * simple approach where we do not need a function that return the size of an
125      * allocated array (eg. _msize on Windows, malloc_size on MacOS,
126      * malloc_usable_size on systems with glibc) */
127     void *a_ptr = opj_aligned_alloc_n(alignment, new_size);
128     if (a_ptr != NULL) {
129       memcpy(a_ptr, r_ptr, new_size);
130     }
131     free( r_ptr );
132     r_ptr = a_ptr;
133   }
134 /* _MSC_VER */
135 #elif defined(HAVE__ALIGNED_MALLOC)
136   r_ptr = _aligned_realloc( ptr, new_size, alignment );
137 #else
138   if (ptr == NULL) {
139     return opj_aligned_alloc_n(alignment, new_size);
140   }
141   alignment--;
142   {
143     void *oldmem;
144     OPJ_UINT8 *newmem;
145     size_t overhead = alignment + sizeof(void *);
146
147     /* let's be extra careful */
148     assert(alignment <= (SIZE_MAX - sizeof(void *)));
149
150     /* Avoid integer overflow */
151     if (new_size > SIZE_MAX - overhead) {
152       return NULL;
153     }
154                 
155     oldmem = ((void**) ptr)[-1];
156     newmem = (OPJ_UINT8*)realloc(oldmem, new_size + overhead);
157     if (newmem == NULL) {
158       return newmem;
159     }
160
161     if (newmem == oldmem) {
162       r_ptr = ptr;
163     }
164     else {
165       size_t old_offset;
166       size_t new_offset;
167
168       /* realloc created a new copy, realign the copied memory block */
169       old_offset = (size_t)((OPJ_UINT8*)ptr - (OPJ_UINT8*)oldmem);
170
171       /* offset = ((alignment + 1U) - ((size_t)(mem + sizeof(void*)) & alignment)) & alignment; */
172       /* Use the fact that alignment + 1U is a power of 2 */
173       new_offset  = ((alignment ^ ((size_t)(newmem + sizeof(void*)) & alignment)) + 1U) & alignment;
174                         new_offset += sizeof(void*);
175       r_ptr = (void *)(newmem + new_offset);
176
177       if (new_offset != old_offset) {
178         memmove(newmem + new_offset, newmem + old_offset, new_size);
179       }
180       ((void**) r_ptr)[-1] = newmem;
181     }
182   }
183 #endif
184         return r_ptr;
185 }
186 void * opj_malloc(size_t size)
187 {
188   if (size == 0U) { /* prevent implementation defined behavior of realloc */
189     return NULL;
190   }
191   return malloc(size);
192 }
193 void * opj_calloc(size_t num, size_t size)
194 {
195   if (size == 0U) { /* prevent implementation defined behavior of realloc */
196     return NULL;
197   }
198   /* according to C89 standard, num == 0 shall return a valid pointer */
199   return calloc(num, size);
200 }
201
202 void *opj_aligned_malloc(size_t size)
203 {
204   return opj_aligned_alloc_n(16U, size);
205 }
206 void * opj_aligned_realloc(void *ptr, size_t size)
207 {
208   return opj_aligned_realloc_n(ptr, 16U, size);
209 }
210
211 void opj_aligned_free(void* ptr)
212 {
213 #if defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
214   free( ptr );
215 #elif defined(HAVE__ALIGNED_MALLOC)
216   _aligned_free( ptr );
217 #else
218   /* Generic implementation has malloced pointer stored in front of used area */
219   if (ptr != NULL) {
220     free(((void**) ptr)[-1]);
221   }
222 #endif
223 }
224
225 void * opj_realloc(void *ptr, size_t new_size)
226 {
227   if (new_size == 0U) { /* prevent implementation defined behavior of realloc */
228     return NULL;
229   }
230   return realloc(ptr, new_size);
231 }
232 void opj_free(void *ptr)
233 {
234   free(ptr);
235 }