+ /* no portable aligned realloc */
+#if defined(OPJ_HAVE_POSIX_MEMALIGN) || defined(OPJ_HAVE_MEMALIGN)
+ /* glibc doc states one can mix aligned malloc with realloc */
+ r_ptr = realloc(ptr, new_size); /* fast path */
+ /* we simply use `size_t` to cast, since we are only interest in binary AND
+ * operator */
+ if (((size_t)r_ptr & (alignment - 1U)) != 0U) {
+ /* this is non-trivial to implement a portable aligned realloc, so use a
+ * simple approach where we do not need a function that return the size of an
+ * allocated array (eg. _msize on Windows, malloc_size on MacOS,
+ * malloc_usable_size on systems with glibc) */
+ void *a_ptr = opj_aligned_alloc_n(alignment, new_size);
+ if (a_ptr != NULL) {
+ memcpy(a_ptr, r_ptr, new_size);
+ }
+ free(r_ptr);
+ r_ptr = a_ptr;
+ }
+ /* _MSC_VER */
+#elif defined(OPJ_HAVE__ALIGNED_MALLOC)
+ r_ptr = _aligned_realloc(ptr, new_size, alignment);
+#else
+ if (ptr == NULL) {
+ return opj_aligned_alloc_n(alignment, new_size);
+ }
+ alignment--;
+ {
+ void *oldmem;
+ OPJ_UINT8 *newmem;
+ size_t overhead = alignment + sizeof(void *);
+
+ /* let's be extra careful */
+ assert(alignment <= (SIZE_MAX - sizeof(void *)));
+
+ /* Avoid integer overflow */
+ if (new_size > SIZE_MAX - overhead) {
+ return NULL;
+ }
+
+ oldmem = ((void**) ptr)[-1];
+ newmem = (OPJ_UINT8*)realloc(oldmem, new_size + overhead);
+ if (newmem == NULL) {
+ return newmem;
+ }
+
+ if (newmem == oldmem) {
+ r_ptr = ptr;
+ } else {
+ size_t old_offset;
+ size_t new_offset;
+
+ /* realloc created a new copy, realign the copied memory block */
+ old_offset = (size_t)((OPJ_UINT8*)ptr - (OPJ_UINT8*)oldmem);
+
+ /* offset = ((alignment + 1U) - ((size_t)(mem + sizeof(void*)) & alignment)) & alignment; */
+ /* Use the fact that alignment + 1U is a power of 2 */
+ new_offset = ((alignment ^ ((size_t)(newmem + sizeof(void*)) & alignment)) +
+ 1U) & alignment;
+ new_offset += sizeof(void*);
+ r_ptr = (void *)(newmem + new_offset);
+
+ if (new_offset != old_offset) {
+ memmove(newmem + new_offset, newmem + old_offset, new_size);
+ }
+ ((void**) r_ptr)[-1] = newmem;
+ }