2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % M M EEEEE M M OOO RRRR Y Y %
7 % MM MM E MM MM O O R R Y Y %
8 % M M M EEE M M M O O RRRR Y %
9 % M M E M M O O R R Y %
10 % M M EEEEE M M OOO R R Y %
13 % MagickCore Memory Allocation Methods %
20 % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Segregate our memory requirements from any program that calls our API. This
37 % should help reduce the risk of others changing our program state or causing
40 % Our custom memory allocation manager implements a best-fit allocation policy
41 % using segregated free lists. It uses a linear distribution of size classes
42 % for lower sizes and a power of two distribution of size classes at higher
43 % sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits."
44 % written by Yoo C. Chung.
46 % By default, ANSI memory methods are called (e.g. malloc). Use the
47 % custom memory allocator by defining MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT
48 % to allocate memory with private anonymous mapping rather than from the
56 #include "MagickCore/studio.h"
57 #include "MagickCore/blob.h"
58 #include "MagickCore/blob-private.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/memory_.h"
62 #include "MagickCore/memory-private.h"
63 #include "MagickCore/resource_.h"
64 #include "MagickCore/semaphore.h"
65 #include "MagickCore/string_.h"
66 #include "MagickCore/utility-private.h"
71 #define BlockFooter(block,size) \
72 ((size_t *) ((char *) (block)+(size)-2*sizeof(size_t)))
73 #define BlockHeader(block) ((size_t *) (block)-1)
74 #define BlockSize 4096
75 #define BlockThreshold 1024
76 #define MaxBlockExponent 16
77 #define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1)
78 #define MaxSegments 1024
79 #define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed)
80 #define NextBlock(block) ((char *) (block)+SizeOfBlock(block))
81 #define NextBlockInList(block) (*(void **) (block))
82 #define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2)))
83 #define PreviousBlockBit 0x01
84 #define PreviousBlockInList(block) (*((void **) (block)+1))
85 #define SegmentSize (2*1024*1024)
86 #define SizeMask (~0x01)
87 #define SizeOfBlock(block) (*BlockHeader(block) & SizeMask)
94 UndefinedVirtualMemory,
97 UnalignedVirtualMemory
100 typedef struct _DataSegmentInfo
112 struct _DataSegmentInfo
117 typedef struct _MagickMemoryMethods
120 acquire_memory_handler;
123 resize_memory_handler;
126 destroy_memory_handler;
127 } MagickMemoryMethods;
132 filename[MagickPathExtent];
147 typedef struct _MemoryPool
153 *blocks[MaxBlocks+1];
159 *segments[MaxSegments],
160 segment_pool[MaxSegments];
167 static void* MSCMalloc(size_t size)
171 static void* MSCRealloc(void* ptr, size_t size)
173 return realloc(ptr, size);
175 static void MSCFree(void* ptr)
181 static MagickMemoryMethods
185 (AcquireMemoryHandler) MSCMalloc,
186 (ResizeMemoryHandler) MSCRealloc,
187 (DestroyMemoryHandler) MSCFree
189 (AcquireMemoryHandler) malloc,
190 (ResizeMemoryHandler) realloc,
191 (DestroyMemoryHandler) free
194 #if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
199 *memory_semaphore = (SemaphoreInfo *) NULL;
201 static volatile DataSegmentInfo
202 *free_segments = (DataSegmentInfo *) NULL;
205 Forward declarations.
207 static MagickBooleanType
212 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
216 % A c q u i r e A l i g n e d M e m o r y %
220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
222 % AcquireAlignedMemory() returns a pointer to a block of memory at least size
223 % bytes whose address is a multiple of 16*sizeof(void *).
225 % The format of the AcquireAlignedMemory method is:
227 % void *AcquireAlignedMemory(const size_t count,const size_t quantum)
229 % A description of each parameter follows:
231 % o count: the number of quantum elements to allocate.
233 % o quantum: the number of bytes in each quantum.
236 MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
238 #define AlignedExtent(size,alignment) \
239 (((size)+((alignment)-1)) & ~((alignment)-1))
249 if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
250 return((void *) NULL);
252 alignment=CACHE_LINE_SIZE;
254 extent=AlignedExtent(size,alignment);
255 if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))
256 return((void *) NULL);
257 #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
258 if (posix_memalign(&memory,alignment,extent) != 0)
260 #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
261 memory=_aligned_malloc(extent,alignment);
267 extent=(size+alignment-1)+sizeof(void *);
273 memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);
274 *((void **) memory-1)=p;
282 #if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
284 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
288 + A c q u i r e B l o c k %
292 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
294 % AcquireBlock() returns a pointer to a block of memory at least size bytes
295 % suitably aligned for any use.
297 % The format of the AcquireBlock method is:
299 % void *AcquireBlock(const size_t size)
301 % A description of each parameter follows:
303 % o size: the size of the memory in bytes to allocate.
307 static inline size_t AllocationPolicy(size_t size)
313 The linear distribution.
316 assert(size % (4*sizeof(size_t)) == 0);
317 if (size <= BlockThreshold)
318 return(size/(4*sizeof(size_t)));
320 Check for the largest block size.
322 if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L))))
323 return(MaxBlocks-1L);
325 Otherwise use a power of two distribution.
327 blocksize=BlockThreshold/(4*sizeof(size_t));
328 for ( ; size > BlockThreshold; size/=2)
330 assert(blocksize > (BlockThreshold/(4*sizeof(size_t))));
331 assert(blocksize < (MaxBlocks-1L));
335 static inline void InsertFreeBlock(void *block,const size_t i)
344 size=SizeOfBlock(block);
345 previous=(void *) NULL;
346 next=memory_pool.blocks[i];
347 while ((next != (void *) NULL) && (SizeOfBlock(next) < size))
350 next=NextBlockInList(next);
352 PreviousBlockInList(block)=previous;
353 NextBlockInList(block)=next;
354 if (previous != (void *) NULL)
355 NextBlockInList(previous)=block;
357 memory_pool.blocks[i]=block;
358 if (next != (void *) NULL)
359 PreviousBlockInList(next)=block;
362 static inline void RemoveFreeBlock(void *block,const size_t i)
368 next=NextBlockInList(block);
369 previous=PreviousBlockInList(block);
370 if (previous == (void *) NULL)
371 memory_pool.blocks[i]=next;
373 NextBlockInList(previous)=next;
374 if (next != (void *) NULL)
375 PreviousBlockInList(next)=previous;
378 static void *AcquireBlock(size_t size)
389 size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t));
390 i=AllocationPolicy(size);
391 block=memory_pool.blocks[i];
392 while ((block != (void *) NULL) && (SizeOfBlock(block) < size))
393 block=NextBlockInList(block);
394 if (block == (void *) NULL)
397 while (memory_pool.blocks[i] == (void *) NULL)
399 block=memory_pool.blocks[i];
401 return((void *) NULL);
403 assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0);
404 assert(SizeOfBlock(block) >= size);
405 RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block)));
406 if (SizeOfBlock(block) > size)
417 next=(char *) block+size;
418 blocksize=SizeOfBlock(block)-size;
419 *BlockHeader(next)=blocksize;
420 *BlockFooter(next,blocksize)=blocksize;
421 InsertFreeBlock(next,AllocationPolicy(blocksize));
422 *BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask);
424 assert(size == SizeOfBlock(block));
425 *BlockHeader(NextBlock(block))|=PreviousBlockBit;
426 memory_pool.allocation+=size;
432 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
436 % A c q u i r e M a g i c k M e m o r y %
440 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
442 % AcquireMagickMemory() returns a pointer to a block of memory at least size
443 % bytes suitably aligned for any use.
445 % The format of the AcquireMagickMemory method is:
447 % void *AcquireMagickMemory(const size_t size)
449 % A description of each parameter follows:
451 % o size: the size of the memory in bytes to allocate.
454 MagickExport void *AcquireMagickMemory(const size_t size)
459 #if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
460 memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size);
462 if (memory_semaphore == (SemaphoreInfo *) NULL)
463 ActivateSemaphoreInfo(&memory_semaphore);
464 if (free_segments == (DataSegmentInfo *) NULL)
466 LockSemaphoreInfo(memory_semaphore);
467 if (free_segments == (DataSegmentInfo *) NULL)
472 assert(2*sizeof(size_t) > (size_t) (~SizeMask));
473 (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
474 memory_pool.allocation=SegmentSize;
475 memory_pool.blocks[MaxBlocks]=(void *) (-1);
476 for (i=0; i < MaxSegments; i++)
479 memory_pool.segment_pool[i].previous=
480 (&memory_pool.segment_pool[i-1]);
481 if (i != (MaxSegments-1))
482 memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]);
484 free_segments=(&memory_pool.segment_pool[0]);
486 UnlockSemaphoreInfo(memory_semaphore);
488 LockSemaphoreInfo(memory_semaphore);
489 memory=AcquireBlock(size == 0 ? 1UL : size);
490 if (memory == (void *) NULL)
492 if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse)
493 memory=AcquireBlock(size == 0 ? 1UL : size);
495 UnlockSemaphoreInfo(memory_semaphore);
501 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
505 % A c q u i r e Q u a n t u m M e m o r y %
509 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
511 % AcquireQuantumMemory() returns a pointer to a block of memory at least
512 % count * quantum bytes suitably aligned for any use.
514 % The format of the AcquireQuantumMemory method is:
516 % void *AcquireQuantumMemory(const size_t count,const size_t quantum)
518 % A description of each parameter follows:
520 % o count: the number of quantum elements to allocate.
522 % o quantum: the number of bytes in each quantum.
525 MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)
530 if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
531 return((void *) NULL);
532 extent=count*quantum;
533 return(AcquireMagickMemory(extent));
537 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
541 % A c q u i r e V i r t u a l M e m o r y %
545 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
547 % AcquireVirtualMemory() allocates a pointer to a block of memory at least size
548 % bytes suitably aligned for any use.
550 % The format of the AcquireVirtualMemory method is:
552 % MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum)
554 % A description of each parameter follows:
556 % o count: the number of quantum elements to allocate.
558 % o quantum: the number of bytes in each quantum.
561 MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
562 const size_t quantum)
570 if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
571 return((MemoryInfo *) NULL);
572 memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
573 sizeof(*memory_info)));
574 if (memory_info == (MemoryInfo *) NULL)
575 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
576 (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
577 extent=count*quantum;
578 memory_info->length=extent;
579 memory_info->signature=MagickCoreSignature;
580 if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
582 memory_info->blob=AcquireAlignedMemory(1,extent);
583 if (memory_info->blob != NULL)
585 memory_info->type=AlignedVirtualMemory;
589 RelinquishMagickResource(MemoryResource,extent);
590 if (AcquireMagickResource(MapResource,extent) != MagickFalse)
593 Heap memory failed, try anonymous memory mapping.
595 memory_info->blob=MapBlob(-1,IOMode,0,extent);
596 if (memory_info->blob != NULL)
598 memory_info->type=MapVirtualMemory;
601 if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
607 Anonymous memory mapping failed, try file-backed memory mapping.
608 If the MapResource request failed, there is no point in trying
609 file-backed memory mapping.
611 file=AcquireUniqueFileResource(memory_info->filename);
617 offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
618 if ((offset == (MagickOffsetType) (extent-1)) &&
619 (write(file,"",1) == 1))
621 memory_info->blob=MapBlob(file,IOMode,0,extent);
622 if (memory_info->blob != NULL)
625 memory_info->type=MapVirtualMemory;
630 File-backed memory mapping failed, delete the temporary file.
633 (void) RelinquishUniqueFileResource(memory_info->filename);
634 *memory_info->filename = '\0';
637 RelinquishMagickResource(DiskResource,extent);
639 RelinquishMagickResource(MapResource,extent);
640 if (memory_info->blob == NULL)
642 memory_info->blob=AcquireMagickMemory(extent);
643 if (memory_info->blob != NULL)
644 memory_info->type=UnalignedVirtualMemory;
646 if (memory_info->blob == NULL)
647 memory_info=RelinquishVirtualMemory(memory_info);
652 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656 % C o p y M a g i c k M e m o r y %
660 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
662 % CopyMagickMemory() copies size bytes from memory area source to the
663 % destination. Copying between objects that overlap will take place
664 % correctly. It returns destination.
666 % The format of the CopyMagickMemory method is:
668 % void *CopyMagickMemory(void *destination,const void *source,
671 % A description of each parameter follows:
673 % o destination: the destination.
675 % o source: the source.
677 % o size: the size of the memory in bytes to allocate.
680 MagickExport void *CopyMagickMemory(void *destination,const void *source,
683 register const unsigned char
686 register unsigned char
689 assert(destination != (void *) NULL);
690 assert(source != (const void *) NULL);
691 p=(const unsigned char *) source;
692 q=(unsigned char *) destination;
693 if (((q+size) < p) || (q > (p+size)))
696 default: return(memcpy(destination,source,size));
705 case 0: return(destination);
707 return(memmove(destination,source,size));
711 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
715 + D e s t r o y M a g i c k M e m o r y %
719 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
721 % DestroyMagickMemory() deallocates memory associated with the memory manager.
723 % The format of the DestroyMagickMemory method is:
725 % DestroyMagickMemory(void)
728 MagickExport void DestroyMagickMemory(void)
730 #if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
734 if (memory_semaphore == (SemaphoreInfo *) NULL)
735 ActivateSemaphoreInfo(&memory_semaphore);
736 LockSemaphoreInfo(memory_semaphore);
737 for (i=0; i < (ssize_t) memory_pool.number_segments; i++)
738 if (memory_pool.segments[i]->mapped == MagickFalse)
739 memory_methods.destroy_memory_handler(
740 memory_pool.segments[i]->allocation);
742 (void) UnmapBlob(memory_pool.segments[i]->allocation,
743 memory_pool.segments[i]->length);
744 free_segments=(DataSegmentInfo *) NULL;
745 (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
746 UnlockSemaphoreInfo(memory_semaphore);
747 RelinquishSemaphoreInfo(&memory_semaphore);
751 #if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
753 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
757 + E x p a n d H e a p %
761 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
763 % ExpandHeap() get more memory from the system. It returns MagickTrue on
764 % success otherwise MagickFalse.
766 % The format of the ExpandHeap method is:
768 % MagickBooleanType ExpandHeap(size_t size)
770 % A description of each parameter follows:
772 % o size: the size of the memory in bytes we require.
775 static MagickBooleanType ExpandHeap(size_t size)
795 blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize;
796 assert(memory_pool.number_segments < MaxSegments);
797 segment=MapBlob(-1,IOMode,0,blocksize);
798 mapped=segment != (void *) NULL ? MagickTrue : MagickFalse;
799 if (segment == (void *) NULL)
800 segment=(void *) memory_methods.acquire_memory_handler(blocksize);
801 if (segment == (void *) NULL)
803 segment_info=(DataSegmentInfo *) free_segments;
804 free_segments=segment_info->next;
805 segment_info->mapped=mapped;
806 segment_info->length=blocksize;
807 segment_info->allocation=segment;
808 segment_info->bound=(char *) segment+blocksize;
809 i=(ssize_t) memory_pool.number_segments-1;
810 for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--)
811 memory_pool.segments[i+1]=memory_pool.segments[i];
812 memory_pool.segments[i+1]=segment_info;
813 memory_pool.number_segments++;
814 size=blocksize-12*sizeof(size_t);
815 block=(char *) segment_info->allocation+4*sizeof(size_t);
816 *BlockHeader(block)=size | PreviousBlockBit;
817 *BlockFooter(block,size)=size;
818 InsertFreeBlock(block,AllocationPolicy(size));
819 block=NextBlock(block);
820 assert(block < segment_info->bound);
821 *BlockHeader(block)=2*sizeof(size_t);
822 *BlockHeader(NextBlock(block))=PreviousBlockBit;
828 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
832 % G e t M a g i c k M e m o r y M e t h o d s %
836 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
838 % GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy
841 % The format of the GetMagickMemoryMethods() method is:
843 % void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler,
844 % ResizeMemoryHandler *resize_memory_handler,
845 % DestroyMemoryHandler *destroy_memory_handler)
847 % A description of each parameter follows:
849 % o acquire_memory_handler: method to acquire memory (e.g. malloc).
851 % o resize_memory_handler: method to resize memory (e.g. realloc).
853 % o destroy_memory_handler: method to destroy memory (e.g. free).
856 MagickExport void GetMagickMemoryMethods(
857 AcquireMemoryHandler *acquire_memory_handler,
858 ResizeMemoryHandler *resize_memory_handler,
859 DestroyMemoryHandler *destroy_memory_handler)
861 assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL);
862 assert(resize_memory_handler != (ResizeMemoryHandler *) NULL);
863 assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL);
864 *acquire_memory_handler=memory_methods.acquire_memory_handler;
865 *resize_memory_handler=memory_methods.resize_memory_handler;
866 *destroy_memory_handler=memory_methods.destroy_memory_handler;
870 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
874 % G e t V i r t u a l M e m o r y B l o b %
878 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
880 % GetVirtualMemoryBlob() returns the virtual memory blob associated with the
881 % specified MemoryInfo structure.
883 % The format of the GetVirtualMemoryBlob method is:
885 % void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
887 % A description of each parameter follows:
889 % o memory_info: The MemoryInfo structure.
891 MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
893 assert(memory_info != (const MemoryInfo *) NULL);
894 assert(memory_info->signature == MagickCoreSignature);
895 return(memory_info->blob);
899 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
903 + H e a p O v e r f l o w S a n i t y C h e c k %
907 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
909 % HeapOverflowSanityCheck() returns MagickTrue if the heap allocation request
910 % does not exceed the maximum limits of a size_t otherwise MagickFalse.
912 % The format of the HeapOverflowSanityCheck method is:
914 % MagickBooleanType HeapOverflowSanityCheck(const size_t count,
915 % const size_t quantum)
917 % A description of each parameter follows:
919 % o size: the size of the memory in bytes we require.
922 MagickExport MagickBooleanType HeapOverflowSanityCheck(const size_t count,
923 const size_t quantum)
929 if ((count == 0) || (quantum != (size/count)))
938 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
942 % R e l i n q u i s h A l i g n e d M e m o r y %
946 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
948 % RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory()
951 % The format of the RelinquishAlignedMemory method is:
953 % void *RelinquishAlignedMemory(void *memory)
955 % A description of each parameter follows:
957 % o memory: A pointer to a block of memory to free for reuse.
960 MagickExport void *RelinquishAlignedMemory(void *memory)
962 if (memory == (void *) NULL)
963 return((void *) NULL);
964 #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
966 #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
967 _aligned_free(memory);
969 free(*((void **) memory-1));
975 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
979 % R e l i n q u i s h M a g i c k M e m o r y %
983 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
985 % RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory()
986 % or AcquireQuantumMemory() for reuse.
988 % The format of the RelinquishMagickMemory method is:
990 % void *RelinquishMagickMemory(void *memory)
992 % A description of each parameter follows:
994 % o memory: A pointer to a block of memory to free for reuse.
997 MagickExport void *RelinquishMagickMemory(void *memory)
999 if (memory == (void *) NULL)
1000 return((void *) NULL);
1001 #if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1002 memory_methods.destroy_memory_handler(memory);
1004 LockSemaphoreInfo(memory_semaphore);
1005 assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0);
1006 assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0);
1007 if ((*BlockHeader(memory) & PreviousBlockBit) == 0)
1013 Coalesce with previous adjacent block.
1015 previous=PreviousBlock(memory);
1016 RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous)));
1017 *BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) |
1018 (*BlockHeader(previous) & ~SizeMask);
1021 if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0)
1027 Coalesce with next adjacent block.
1029 next=NextBlock(memory);
1030 RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next)));
1031 *BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) |
1032 (*BlockHeader(memory) & ~SizeMask);
1034 *BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory);
1035 *BlockHeader(NextBlock(memory))&=(~PreviousBlockBit);
1036 InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory)));
1037 UnlockSemaphoreInfo(memory_semaphore);
1039 return((void *) NULL);
1043 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1047 % R e l i n q u i s h V i r t u a l M e m o r y %
1051 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1053 % RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory().
1055 % The format of the RelinquishVirtualMemory method is:
1057 % MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
1059 % A description of each parameter follows:
1061 % o memory_info: A pointer to a block of memory to free for reuse.
1064 MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
1066 assert(memory_info != (MemoryInfo *) NULL);
1067 assert(memory_info->signature == MagickCoreSignature);
1068 if (memory_info->blob != (void *) NULL)
1069 switch (memory_info->type)
1071 case AlignedVirtualMemory:
1073 memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
1074 RelinquishMagickResource(MemoryResource,memory_info->length);
1077 case MapVirtualMemory:
1079 (void) UnmapBlob(memory_info->blob,memory_info->length);
1080 memory_info->blob=NULL;
1081 RelinquishMagickResource(MapResource,memory_info->length);
1082 if (*memory_info->filename != '\0')
1084 (void) RelinquishUniqueFileResource(memory_info->filename);
1085 RelinquishMagickResource(DiskResource,memory_info->length);
1089 case UnalignedVirtualMemory:
1092 memory_info->blob=RelinquishMagickMemory(memory_info->blob);
1096 memory_info->signature=(~MagickCoreSignature);
1097 memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
1098 return(memory_info);
1102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1106 % R e s e t M a g i c k M e m o r y %
1110 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1112 % ResetMagickMemory() fills the first size bytes of the memory area pointed to
1113 % by memory with the constant byte c.
1115 % The format of the ResetMagickMemory method is:
1117 % void *ResetMagickMemory(void *memory,int byte,const size_t size)
1119 % A description of each parameter follows:
1121 % o memory: a pointer to a memory allocation.
1123 % o byte: set the memory to this value.
1125 % o size: size of the memory to reset.
1128 MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size)
1130 assert(memory != (void *) NULL);
1131 return(memset(memory,byte,size));
1135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1139 % R e s i z e M a g i c k M e m o r y %
1143 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1145 % ResizeMagickMemory() changes the size of the memory and returns a pointer to
1146 % the (possibly moved) block. The contents will be unchanged up to the
1147 % lesser of the new and old sizes.
1149 % The format of the ResizeMagickMemory method is:
1151 % void *ResizeMagickMemory(void *memory,const size_t size)
1153 % A description of each parameter follows:
1155 % o memory: A pointer to a memory allocation.
1157 % o size: the new size of the allocated memory.
1161 #if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1162 static inline void *ResizeBlock(void *block,size_t size)
1167 if (block == (void *) NULL)
1168 return(AcquireBlock(size));
1169 memory=AcquireBlock(size);
1170 if (memory == (void *) NULL)
1171 return((void *) NULL);
1172 if (size <= (SizeOfBlock(block)-sizeof(size_t)))
1173 (void) memcpy(memory,block,size);
1175 (void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t));
1176 memory_pool.allocation+=size;
1181 MagickExport void *ResizeMagickMemory(void *memory,const size_t size)
1186 if (memory == (void *) NULL)
1187 return(AcquireMagickMemory(size));
1188 #if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1189 block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size);
1190 if (block == (void *) NULL)
1191 memory=RelinquishMagickMemory(memory);
1193 LockSemaphoreInfo(memory_semaphore);
1194 block=ResizeBlock(memory,size == 0 ? 1UL : size);
1195 if (block == (void *) NULL)
1197 if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse)
1199 UnlockSemaphoreInfo(memory_semaphore);
1200 memory=RelinquishMagickMemory(memory);
1201 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1203 block=ResizeBlock(memory,size == 0 ? 1UL : size);
1204 assert(block != (void *) NULL);
1206 UnlockSemaphoreInfo(memory_semaphore);
1207 memory=RelinquishMagickMemory(memory);
1213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1217 % R e s i z e Q u a n t u m M e m o r y %
1221 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1223 % ResizeQuantumMemory() changes the size of the memory and returns a pointer
1224 % to the (possibly moved) block. The contents will be unchanged up to the
1225 % lesser of the new and old sizes.
1227 % The format of the ResizeQuantumMemory method is:
1229 % void *ResizeQuantumMemory(void *memory,const size_t count,
1230 % const size_t quantum)
1232 % A description of each parameter follows:
1234 % o memory: A pointer to a memory allocation.
1236 % o count: the number of quantum elements to allocate.
1238 % o quantum: the number of bytes in each quantum.
1241 MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
1242 const size_t quantum)
1247 if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
1249 memory=RelinquishMagickMemory(memory);
1250 return((void *) NULL);
1252 extent=count*quantum;
1253 return(ResizeMagickMemory(memory,extent));
1257 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1261 % S e t M a g i c k M e m o r y M e t h o d s %
1265 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1267 % SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy
1268 % memory. Your custom memory methods must be set prior to the
1269 % MagickCoreGenesis() method.
1271 % The format of the SetMagickMemoryMethods() method is:
1273 % SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler,
1274 % ResizeMemoryHandler resize_memory_handler,
1275 % DestroyMemoryHandler destroy_memory_handler)
1277 % A description of each parameter follows:
1279 % o acquire_memory_handler: method to acquire memory (e.g. malloc).
1281 % o resize_memory_handler: method to resize memory (e.g. realloc).
1283 % o destroy_memory_handler: method to destroy memory (e.g. free).
1286 MagickExport void SetMagickMemoryMethods(
1287 AcquireMemoryHandler acquire_memory_handler,
1288 ResizeMemoryHandler resize_memory_handler,
1289 DestroyMemoryHandler destroy_memory_handler)
1294 if (acquire_memory_handler != (AcquireMemoryHandler) NULL)
1295 memory_methods.acquire_memory_handler=acquire_memory_handler;
1296 if (resize_memory_handler != (ResizeMemoryHandler) NULL)
1297 memory_methods.resize_memory_handler=resize_memory_handler;
1298 if (destroy_memory_handler != (DestroyMemoryHandler) NULL)
1299 memory_methods.destroy_memory_handler=destroy_memory_handler;