MagickCore 7.1.2-21
Convert, Edit, Or Compose Bitmap Images
Loading...
Searching...
No Matches
memory.c
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
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 %
11% %
12% %
13% MagickCore Memory Allocation Methods %
14% %
15% Software Design %
16% Cristy %
17% July 1998 %
18% %
19% %
20% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
21% dedicated to making software imaging solutions freely available. %
22% %
23% You may not use this file except in compliance with the License. You may %
24% obtain a copy of the License at %
25% %
26% https://imagemagick.org/license/ %
27% %
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. %
33% %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
36% We provide these memory allocators:
37%
38% AcquireCriticalMemory(): allocate a small memory request with
39% AcquireMagickMemory(), however, on fail throw a fatal exception and exit.
40% Free the memory reserve with RelinquishMagickMemory().
41% AcquireAlignedMemory(): allocate a small memory request that is aligned
42% on a cache line. On fail, return NULL for possible recovery.
43% Free the memory reserve with RelinquishMagickMemory().
44% AcquireMagickMemory()/ResizeMagickMemory(): allocate a small to medium
45% memory request, typically with malloc()/realloc(). On fail, return NULL
46% for possible recovery. Free the memory reserve with
47% RelinquishMagickMemory().
48% AcquireQuantumMemory()/ResizeQuantumMemory(): allocate a small to medium
49% memory request. This is a secure memory allocator as it accepts two
50% parameters, count and quantum, to ensure the request does not overflow.
51% It also check to ensure the request does not exceed the maximum memory
52% per the security policy. Free the memory reserve with
53% RelinquishMagickMemory().
54% AcquireVirtualMemory(): allocate a large memory request either in heap,
55% memory-mapped, or memory-mapped on disk depending on whether heap
56% allocation fails or if the request exceeds the maximum memory policy.
57% Free the memory reserve with RelinquishVirtualMemory().
58% ResetMagickMemory(): fills the bytes of the memory area with a constant
59% byte.
60%
61% In addition, we provide hooks for your own memory constructor/destructors.
62% You can also utilize our internal custom allocator as follows: Segregate
63% our memory requirements from any program that calls our API. This should
64% help reduce the risk of others changing our program state or causing memory
65% corruption.
66%
67% Our custom memory allocation manager implements a best-fit allocation policy
68% using segregated free lists. It uses a linear distribution of size classes
69% for lower sizes and a power of two distribution of size classes at higher
70% sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits."
71% written by Yoo C. Chung.
72%
73% By default, C's standard library is used (e.g. malloc); use the
74% custom memory allocator by defining MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT
75% to allocate memory with private anonymous mapping rather than from the
76% heap.
77%
78*/
79
80/*
81 Include declarations.
82*/
83#include "MagickCore/studio.h"
84#include "MagickCore/blob.h"
85#include "MagickCore/blob-private.h"
86#include "MagickCore/exception.h"
87#include "MagickCore/exception-private.h"
88#include "MagickCore/image-private.h"
89#include "MagickCore/memory_.h"
90#include "MagickCore/memory-private.h"
91#include "MagickCore/policy.h"
92#include "MagickCore/resource_.h"
93#include "MagickCore/semaphore.h"
94#include "MagickCore/string_.h"
95#include "MagickCore/string-private.h"
96#include "MagickCore/utility-private.h"
97
98/*
99 Define declarations.
100*/
101#define BlockFooter(block,size) \
102 ((size_t *) ((char *) (block)+(size)-2*sizeof(size_t)))
103#define BlockHeader(block) ((size_t *) (block)-1)
104#define BlockThreshold 1024
105#define MaxBlockExponent 16
106#define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1)
107#define MaxSegments 1024
108#define NextBlock(block) ((char *) (block)+SizeOfBlock(block))
109#define NextBlockInList(block) (*(void **) (block))
110#define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2)))
111#define PreviousBlockBit 0x01
112#define PreviousBlockInList(block) (*((void **) (block)+1))
113#define SegmentSize (2*1024*1024)
114#define SizeMask (~0x01)
115#define SizeOfBlock(block) (*BlockHeader(block) & SizeMask)
116
117/*
118 Typedef declarations.
119*/
120typedef enum
121{
122 UndefinedVirtualMemory,
123 AlignedVirtualMemory,
124 MapVirtualMemory,
125 UnalignedVirtualMemory
126} VirtualMemoryType;
127
128typedef struct _DataSegmentInfo
129{
130 void
131 *allocation,
132 *bound;
133
134 MagickBooleanType
135 mapped;
136
137 size_t
138 length;
139
140 struct _DataSegmentInfo
141 *previous,
142 *next;
143} DataSegmentInfo;
144
146{
147 AcquireMemoryHandler
148 acquire_memory_handler;
149
150 ResizeMemoryHandler
151 resize_memory_handler;
152
153 DestroyMemoryHandler
154 destroy_memory_handler;
155
156 AcquireAlignedMemoryHandler
157 acquire_aligned_memory_handler;
158
159 RelinquishAlignedMemoryHandler
160 relinquish_aligned_memory_handler;
161} MagickMemoryMethods;
162
164{
165 char
166 filename[MagickPathExtent];
167
168 VirtualMemoryType
169 type;
170
171 size_t
172 length;
173
174 void
175 *blob;
176
177 size_t
178 signature;
179};
180
181typedef struct _MemoryPool
182{
183 size_t
184 allocation;
185
186 void
187 *blocks[MaxBlocks+1];
188
189 size_t
190 number_segments;
191
192 DataSegmentInfo
193 *segments[MaxSegments],
194 segment_pool[MaxSegments];
195} MemoryPool;
196
197/*
198 Global declarations.
199*/
200static size_t
201 max_memory_request = 0,
202 max_profile_size = 0,
203 virtual_anonymous_memory = 0;
204
205static MagickMemoryMethods
206 memory_methods =
207 {
208 (AcquireMemoryHandler) malloc,
209 (ResizeMemoryHandler) realloc,
210 (DestroyMemoryHandler) free,
211 (AcquireAlignedMemoryHandler) NULL,
212 (RelinquishAlignedMemoryHandler) NULL
213 };
214#if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
215static MemoryPool
216 memory_pool;
217
218static SemaphoreInfo
219 *memory_semaphore = (SemaphoreInfo *) NULL;
220
221static volatile DataSegmentInfo
222 *free_segments = (DataSegmentInfo *) NULL;
223
224/*
225 Forward declarations.
226*/
227static MagickBooleanType
228 ExpandHeap(size_t);
229#endif
230
231/*
232%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
233% %
234% %
235% %
236% A c q u i r e A l i g n e d M e m o r y %
237% %
238% %
239% %
240%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
241%
242% AcquireAlignedMemory() returns a pointer to a block of memory whose size is
243% at least (count*quantum) bytes, and whose address is aligned on a cache line.
244%
245% The format of the AcquireAlignedMemory method is:
246%
247% void *AcquireAlignedMemory(const size_t count,const size_t quantum)
248%
249% A description of each parameter follows:
250%
251% o count: the number of objects to allocate contiguously.
252%
253% o quantum: the size (in bytes) of each object.
254%
255*/
256#if defined(MAGICKCORE_HAVE_ALIGNED_MALLOC)
257#define AcquireAlignedMemory_Actual AcquireAlignedMemory_STDC
258static inline void *AcquireAlignedMemory_STDC(const size_t size)
259{
260 size_t
261 extent = CACHE_ALIGNED(size);
262
263 if (extent < size)
264 {
265 errno=ENOMEM;
266 return(NULL);
267 }
268 return(aligned_alloc(CACHE_LINE_SIZE,extent));
269}
270#elif defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
271#define AcquireAlignedMemory_Actual AcquireAlignedMemory_POSIX
272static inline void *AcquireAlignedMemory_POSIX(const size_t size)
273{
274 void
275 *memory;
276
277 if (posix_memalign(&memory,CACHE_LINE_SIZE,size))
278 return(NULL);
279 return(memory);
280}
281#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
282#define AcquireAlignedMemory_Actual AcquireAlignedMemory_WinAPI
283static inline void *AcquireAlignedMemory_WinAPI(const size_t size)
284{
285 return(_aligned_malloc(size,CACHE_LINE_SIZE));
286}
287#else
288#define ALIGNMENT_OVERHEAD \
289 (MAGICKCORE_MAX_ALIGNMENT_PADDING(CACHE_LINE_SIZE) + MAGICKCORE_SIZEOF_VOID_P)
290static inline void *reserve_space_for_actual_base_address(void *const p)
291{
292 return((void **) p+1);
293}
294
295static inline void **pointer_to_space_for_actual_base_address(void *const p)
296{
297 return((void **) p-1);
298}
299
300static inline void *actual_base_address(void *const p)
301{
302 return(*pointer_to_space_for_actual_base_address(p));
303}
304
305static inline void *align_to_cache(void *const p)
306{
307 return((void *) CACHE_ALIGNED((MagickAddressType) p));
308}
309
310static inline void *adjust(void *const p)
311{
312 return(align_to_cache(reserve_space_for_actual_base_address(p)));
313}
314
315#define AcquireAlignedMemory_Actual AcquireAlignedMemory_Generic
316static inline void *AcquireAlignedMemory_Generic(const size_t size)
317{
318 size_t
319 extent;
320
321 void
322 *memory,
323 *p;
324
325 #if SIZE_MAX < ALIGNMENT_OVERHEAD
326 #error "CACHE_LINE_SIZE is way too big."
327 #endif
328 extent=(size+ALIGNMENT_OVERHEAD);
329 if (extent <= size)
330 {
331 errno=ENOMEM;
332 return(NULL);
333 }
334 p=AcquireMagickMemory(extent);
335 if (p == NULL)
336 return(NULL);
337 memory=adjust(p);
338 *pointer_to_space_for_actual_base_address(memory)=p;
339 return(memory);
340}
341#endif
342
343MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
344{
345 size_t
346 size;
347
348 if (HeapOverflowSanityCheckGetSize(count,quantum,&size) != MagickFalse)
349 {
350 errno=ENOMEM;
351 return(NULL);
352 }
353 if (memory_methods.acquire_aligned_memory_handler != (AcquireAlignedMemoryHandler) NULL)
354 return(memory_methods.acquire_aligned_memory_handler(size,CACHE_LINE_SIZE));
355 return(AcquireAlignedMemory_Actual(size));
356}
357
358#if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
359/*
360%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
361% %
362% %
363% %
364+ A c q u i r e B l o c k %
365% %
366% %
367% %
368%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
369%
370% AcquireBlock() returns a pointer to a block of memory at least size bytes
371% suitably aligned for any use.
372%
373% The format of the AcquireBlock method is:
374%
375% void *AcquireBlock(const size_t size)
376%
377% A description of each parameter follows:
378%
379% o size: the size of the memory in bytes to allocate.
380%
381*/
382
383static inline size_t AllocationPolicy(size_t size)
384{
385 size_t
386 blocksize;
387
388 /*
389 The linear distribution.
390 */
391 assert(size != 0);
392 assert(size % (4*sizeof(size_t)) == 0);
393 if (size <= BlockThreshold)
394 return(size/(4*sizeof(size_t)));
395 /*
396 Check for the largest block size.
397 */
398 if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L))))
399 return(MaxBlocks-1L);
400 /*
401 Otherwise use a power of two distribution.
402 */
403 blocksize=BlockThreshold/(4*sizeof(size_t));
404 for ( ; size > BlockThreshold; size/=2)
405 blocksize++;
406 assert(blocksize > (BlockThreshold/(4*sizeof(size_t))));
407 assert(blocksize < (MaxBlocks-1L));
408 return(blocksize);
409}
410
411static inline void InsertFreeBlock(void *block,const size_t i)
412{
413 void
414 *next,
415 *previous;
416
417 size_t
418 size;
419
420 size=SizeOfBlock(block);
421 previous=(void *) NULL;
422 next=memory_pool.blocks[i];
423 while ((next != (void *) NULL) && (SizeOfBlock(next) < size))
424 {
425 previous=next;
426 next=NextBlockInList(next);
427 }
428 PreviousBlockInList(block)=previous;
429 NextBlockInList(block)=next;
430 if (previous != (void *) NULL)
431 NextBlockInList(previous)=block;
432 else
433 memory_pool.blocks[i]=block;
434 if (next != (void *) NULL)
435 PreviousBlockInList(next)=block;
436}
437
438static inline void RemoveFreeBlock(void *block,const size_t i)
439{
440 void
441 *next,
442 *previous;
443
444 next=NextBlockInList(block);
445 previous=PreviousBlockInList(block);
446 if (previous == (void *) NULL)
447 memory_pool.blocks[i]=next;
448 else
449 NextBlockInList(previous)=next;
450 if (next != (void *) NULL)
451 PreviousBlockInList(next)=previous;
452}
453
454static void *AcquireBlock(size_t size)
455{
456 size_t
457 i;
458
459 void
460 *block;
461
462 /*
463 Find free block.
464 */
465 size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t));
466 i=AllocationPolicy(size);
467 block=memory_pool.blocks[i];
468 while ((block != (void *) NULL) && (SizeOfBlock(block) < size))
469 block=NextBlockInList(block);
470 if (block == (void *) NULL)
471 {
472 i++;
473 while (memory_pool.blocks[i] == (void *) NULL)
474 i++;
475 block=memory_pool.blocks[i];
476 if (i >= MaxBlocks)
477 return((void *) NULL);
478 }
479 assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0);
480 assert(SizeOfBlock(block) >= size);
481 RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block)));
482 if (SizeOfBlock(block) > size)
483 {
484 size_t
485 blocksize;
486
487 void
488 *next;
489
490 /*
491 Split block.
492 */
493 next=(char *) block+size;
494 blocksize=SizeOfBlock(block)-size;
495 *BlockHeader(next)=blocksize;
496 *BlockFooter(next,blocksize)=blocksize;
497 InsertFreeBlock(next,AllocationPolicy(blocksize));
498 *BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask);
499 }
500 assert(size == SizeOfBlock(block));
501 *BlockHeader(NextBlock(block))|=PreviousBlockBit;
502 memory_pool.allocation+=size;
503 return(block);
504}
505#endif
506
507/*
508%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
509% %
510% %
511% %
512% A c q u i r e M a g i c k M e m o r y %
513% %
514% %
515% %
516%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
517%
518% AcquireMagickMemory() returns a pointer to a block of memory at least size
519% bytes suitably aligned for any use.
520%
521% The format of the AcquireMagickMemory method is:
522%
523% void *AcquireMagickMemory(const size_t size)
524%
525% A description of each parameter follows:
526%
527% o size: the size of the memory in bytes to allocate.
528%
529*/
530MagickExport void *AcquireMagickMemory(const size_t size)
531{
532 void
533 *memory;
534
535#if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
536 memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size);
537#else
538 if (memory_semaphore == (SemaphoreInfo *) NULL)
539 ActivateSemaphoreInfo(&memory_semaphore);
540 if (free_segments == (DataSegmentInfo *) NULL)
541 {
542 LockSemaphoreInfo(memory_semaphore);
543 if (free_segments == (DataSegmentInfo *) NULL)
544 {
545 ssize_t
546 i;
547
548 assert(2*sizeof(size_t) > (size_t) (~SizeMask));
549 (void) memset(&memory_pool,0,sizeof(memory_pool));
550 memory_pool.allocation=SegmentSize;
551 memory_pool.blocks[MaxBlocks]=(void *) (-1);
552 for (i=0; i < MaxSegments; i++)
553 {
554 if (i != 0)
555 memory_pool.segment_pool[i].previous=
556 (&memory_pool.segment_pool[i-1]);
557 if (i != (MaxSegments-1))
558 memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]);
559 }
560 free_segments=(&memory_pool.segment_pool[0]);
561 }
562 UnlockSemaphoreInfo(memory_semaphore);
563 }
564 LockSemaphoreInfo(memory_semaphore);
565 memory=AcquireBlock(size == 0 ? 1UL : size);
566 if (memory == (void *) NULL)
567 {
568 if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse)
569 memory=AcquireBlock(size == 0 ? 1UL : size);
570 }
571 UnlockSemaphoreInfo(memory_semaphore);
572#endif
573 return(memory);
574}
575
576/*
577%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
578% %
579% %
580% %
581% A c q u i r e C r i t i c a l M e m o r y %
582% %
583% %
584% %
585%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
586%
587% AcquireCriticalMemory() is just like AcquireMagickMemory(), throws a fatal
588% exception if the memory cannot be acquired.
589%
590% That is, AcquireCriticalMemory() returns a pointer to a block of memory that
591% is at least size bytes, and that is suitably aligned for any use; however,
592% if this is not possible, it throws an exception and terminates the program
593% as unceremoniously as possible.
594%
595% The format of the AcquireCriticalMemory method is:
596%
597% void *AcquireCriticalMemory(const size_t size)
598%
599% A description of each parameter follows:
600%
601% o size: the size (in bytes) of the memory to allocate.
602%
603*/
604MagickExport void *AcquireCriticalMemory(const size_t size)
605{
606#if !defined(STDERR_FILENO)
607#define STDERR_FILENO 2
608#endif
609
610 static const char fatal_message[] =
611 "ImageMagick: fatal error: unable to acquire critical memory\n";
612
613 void
614 *memory;
615
616 /*
617 Fail if memory request cannot be fulfilled.
618 */
619 memory=AcquireMagickMemory(size);
620 if (memory != (void *) NULL)
621 return(memory);
622 (void) write(STDERR_FILENO,fatal_message,sizeof(fatal_message)-1);
623 MagickCoreTerminus();
624 _exit(EXIT_FAILURE);
625}
626
627/*
628%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
629% %
630% %
631% %
632% A c q u i r e Q u a n t u m M e m o r y %
633% %
634% %
635% %
636%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
637%
638% AcquireQuantumMemory() returns a pointer to a block of memory at least
639% count * quantum bytes suitably aligned for any use.
640%
641% The format of the AcquireQuantumMemory method is:
642%
643% void *AcquireQuantumMemory(const size_t count,const size_t quantum)
644%
645% A description of each parameter follows:
646%
647% o count: the number of objects to allocate contiguously.
648%
649% o quantum: the size (in bytes) of each object.
650%
651*/
652MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)
653{
654 size_t
655 size;
656
657 if ((HeapOverflowSanityCheckGetSize(count,quantum,&size) != MagickFalse) ||
658 (size > GetMaxMemoryRequest()))
659 {
660 errno=ENOMEM;
661 return(NULL);
662 }
663 return(AcquireMagickMemory(size));
664}
665
666/*
667%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
668% %
669% %
670% %
671% A c q u i r e V i r t u a l M e m o r y %
672% %
673% %
674% %
675%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
676%
677% AcquireVirtualMemory() allocates a pointer to a block of memory at least
678% size bytes suitably aligned for any use. In addition to heap, it also
679% supports memory-mapped and file-based memory-mapped memory requests.
680%
681% The format of the AcquireVirtualMemory method is:
682%
683% MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum)
684%
685% A description of each parameter follows:
686%
687% o count: the number of objects to allocate contiguously.
688%
689% o quantum: the size (in bytes) of each object.
690%
691*/
692MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
693 const size_t quantum)
694{
695 char
696 *value;
697
698 MemoryInfo
699 *memory_info;
700
701 size_t
702 size;
703
704 if (HeapOverflowSanityCheckGetSize(count,quantum,&size) != MagickFalse)
705 {
706 errno=ENOMEM;
707 return((MemoryInfo *) NULL);
708 }
709 if (virtual_anonymous_memory == 0)
710 {
711 virtual_anonymous_memory=1;
712 value=GetPolicyValue("system:memory-map");
713 if (LocaleCompare(value,"anonymous") == 0)
714 {
715 /*
716 The security policy sets anonymous mapping for the memory request.
717 */
718#if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS)
719 virtual_anonymous_memory=2;
720#endif
721 }
722 value=DestroyString(value);
723 }
724 memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
725 sizeof(*memory_info)));
726 if (memory_info == (MemoryInfo *) NULL)
727 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
728 (void) memset(memory_info,0,sizeof(*memory_info));
729 memory_info->length=size;
730 memory_info->signature=MagickCoreSignature;
731 if ((virtual_anonymous_memory == 1) && (size <= GetMaxMemoryRequest()))
732 {
733 memory_info->blob=AcquireAlignedMemory(1,size);
734 if (memory_info->blob != NULL)
735 memory_info->type=AlignedVirtualMemory;
736 }
737 if (memory_info->blob == NULL)
738 {
739 /*
740 Acquire anonymous memory map.
741 */
742 memory_info->blob=NULL;
743 if (size <= GetMaxMemoryRequest())
744 memory_info->blob=MapBlob(-1,IOMode,0,size);
745 if (memory_info->blob != NULL)
746 memory_info->type=MapVirtualMemory;
747 else
748 {
749 int
750 file;
751
752 /*
753 Anonymous memory mapping failed, try file-backed memory mapping.
754 */
755 file=AcquireUniqueFileResource(memory_info->filename);
756 if (file != -1)
757 {
758 MagickOffsetType
759 offset;
760
761 offset=(MagickOffsetType) lseek(file,(off_t) (size-1),SEEK_SET);
762 if ((offset == (MagickOffsetType) (size-1)) &&
763 (write(file,"",1) == 1))
764 {
765#if !defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
766 memory_info->blob=MapBlob(file,IOMode,0,size);
767#else
768 if (posix_fallocate(file,0,(MagickOffsetType) size) == 0)
769 memory_info->blob=MapBlob(file,IOMode,0,size);
770#endif
771 if (memory_info->blob != NULL)
772 memory_info->type=MapVirtualMemory;
773 else
774 {
775 (void) RelinquishUniqueFileResource(
776 memory_info->filename);
777 *memory_info->filename='\0';
778 }
779 }
780 (void) close_utf8(file);
781 }
782 }
783 }
784 if (memory_info->blob == NULL)
785 {
786 memory_info->blob=AcquireQuantumMemory(1,size);
787 if (memory_info->blob != NULL)
788 memory_info->type=UnalignedVirtualMemory;
789 }
790 if (memory_info->blob == NULL)
791 memory_info=RelinquishVirtualMemory(memory_info);
792 return(memory_info);
793}
794
795/*
796%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
797% %
798% %
799% %
800% C o p y M a g i c k M e m o r y %
801% %
802% %
803% %
804%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
805%
806% CopyMagickMemory() copies size bytes from memory area source to the
807% destination. Copying between objects that overlap will take place
808% correctly. It returns destination.
809%
810% The format of the CopyMagickMemory method is:
811%
812% void *CopyMagickMemory(void *magick_restrict destination,
813% const void *magick_restrict source,const size_t size)
814%
815% A description of each parameter follows:
816%
817% o destination: the destination.
818%
819% o source: the source.
820%
821% o size: the size of the memory in bytes to allocate.
822%
823*/
824MagickExport void *CopyMagickMemory(void *magick_restrict destination,
825 const void *magick_restrict source,const size_t size)
826{
827 const unsigned char
828 *p;
829
830 unsigned char
831 *q;
832
833 assert(destination != (void *) NULL);
834 assert(source != (const void *) NULL);
835 p=(const unsigned char *) source;
836 q=(unsigned char *) destination;
837 if (((q+size) < p) || (q > (p+size)))
838 switch (size)
839 {
840 default: return(memcpy(destination,source,size));
841 case 8: *q++=(*p++); magick_fallthrough;
842 case 7: *q++=(*p++); magick_fallthrough;
843 case 6: *q++=(*p++); magick_fallthrough;
844 case 5: *q++=(*p++); magick_fallthrough;
845 case 4: *q++=(*p++); magick_fallthrough;
846 case 3: *q++=(*p++); magick_fallthrough;
847 case 2: *q++=(*p++); magick_fallthrough;
848 case 1: *q++=(*p++); magick_fallthrough;
849 case 0: return(destination);
850 }
851 return(memmove(destination,source,size));
852}
853
854/*
855%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
856% %
857% %
858% %
859+ D e s t r o y M a g i c k M e m o r y %
860% %
861% %
862% %
863%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
864%
865% DestroyMagickMemory() deallocates memory associated with the memory manager.
866%
867% The format of the DestroyMagickMemory method is:
868%
869% DestroyMagickMemory(void)
870%
871*/
872MagickExport void DestroyMagickMemory(void)
873{
874#if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
875 ssize_t
876 i;
877
878 if (memory_semaphore == (SemaphoreInfo *) NULL)
879 ActivateSemaphoreInfo(&memory_semaphore);
880 LockSemaphoreInfo(memory_semaphore);
881 for (i=0; i < (ssize_t) memory_pool.number_segments; i++)
882 if (memory_pool.segments[i]->mapped == MagickFalse)
883 memory_methods.destroy_memory_handler(
884 memory_pool.segments[i]->allocation);
885 else
886 (void) UnmapBlob(memory_pool.segments[i]->allocation,
887 memory_pool.segments[i]->length);
888 free_segments=(DataSegmentInfo *) NULL;
889 (void) memset(&memory_pool,0,sizeof(memory_pool));
890 UnlockSemaphoreInfo(memory_semaphore);
891 RelinquishSemaphoreInfo(&memory_semaphore);
892#endif
893}
894
895#if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
896/*
897%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
898% %
899% %
900% %
901+ E x p a n d H e a p %
902% %
903% %
904% %
905%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
906%
907% ExpandHeap() get more memory from the system. It returns MagickTrue on
908% success otherwise MagickFalse.
909%
910% The format of the ExpandHeap method is:
911%
912% MagickBooleanType ExpandHeap(size_t size)
913%
914% A description of each parameter follows:
915%
916% o size: the size of the memory in bytes we require.
917%
918*/
919static MagickBooleanType ExpandHeap(size_t size)
920{
921 DataSegmentInfo
922 *segment_info;
923
924 MagickBooleanType
925 mapped;
926
927 ssize_t
928 i;
929
930 void
931 *block;
932
933 size_t
934 blocksize;
935
936 void
937 *segment;
938
939 blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize;
940 assert(memory_pool.number_segments < MaxSegments);
941 segment=MapBlob(-1,IOMode,0,blocksize);
942 mapped=segment != (void *) NULL ? MagickTrue : MagickFalse;
943 if (segment == (void *) NULL)
944 segment=(void *) memory_methods.acquire_memory_handler(blocksize);
945 if (segment == (void *) NULL)
946 return(MagickFalse);
947 segment_info=(DataSegmentInfo *) free_segments;
948 free_segments=segment_info->next;
949 segment_info->mapped=mapped;
950 segment_info->length=blocksize;
951 segment_info->allocation=segment;
952 segment_info->bound=(char *) segment+blocksize;
953 i=(ssize_t) memory_pool.number_segments-1;
954 for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--)
955 memory_pool.segments[i+1]=memory_pool.segments[i];
956 memory_pool.segments[i+1]=segment_info;
957 memory_pool.number_segments++;
958 size=blocksize-12*sizeof(size_t);
959 block=(char *) segment_info->allocation+4*sizeof(size_t);
960 *BlockHeader(block)=size | PreviousBlockBit;
961 *BlockFooter(block,size)=size;
962 InsertFreeBlock(block,AllocationPolicy(size));
963 block=NextBlock(block);
964 assert(block < segment_info->bound);
965 *BlockHeader(block)=2*sizeof(size_t);
966 *BlockHeader(NextBlock(block))=PreviousBlockBit;
967 return(MagickTrue);
968}
969#endif
970
971/*
972%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
973% %
974% %
975% %
976% G e t M a g i c k M e m o r y M e t h o d s %
977% %
978% %
979% %
980%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
981%
982% GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy
983% memory.
984%
985% The format of the GetMagickMemoryMethods() method is:
986%
987% void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler,
988% ResizeMemoryHandler *resize_memory_handler,
989% DestroyMemoryHandler *destroy_memory_handler)
990%
991% A description of each parameter follows:
992%
993% o acquire_memory_handler: method to acquire memory (e.g. malloc).
994%
995% o resize_memory_handler: method to resize memory (e.g. realloc).
996%
997% o destroy_memory_handler: method to destroy memory (e.g. free).
998%
999*/
1000MagickExport void GetMagickMemoryMethods(
1001 AcquireMemoryHandler *acquire_memory_handler,
1002 ResizeMemoryHandler *resize_memory_handler,
1003 DestroyMemoryHandler *destroy_memory_handler)
1004{
1005 assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL);
1006 assert(resize_memory_handler != (ResizeMemoryHandler *) NULL);
1007 assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL);
1008 *acquire_memory_handler=memory_methods.acquire_memory_handler;
1009 *resize_memory_handler=memory_methods.resize_memory_handler;
1010 *destroy_memory_handler=memory_methods.destroy_memory_handler;
1011}
1012
1013/*
1014%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1015% %
1016% %
1017% %
1018+ G e t M a x M e m o r y R e q u e s t %
1019% %
1020% %
1021% %
1022%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1023%
1024% GetMaxMemoryRequest() returns the max memory request value.
1025%
1026% The format of the GetMaxMemoryRequest method is:
1027%
1028% size_t GetMaxMemoryRequest(void)
1029%
1030*/
1031static size_t GetMaxMemoryRequestFromPolicy(void)
1032{
1033#define MinMemoryRequest "16MiB"
1034
1035 char
1036 *value;
1037
1038 size_t
1039 max_memory = (size_t) MAGICK_SSIZE_MAX;
1040
1041 value=GetPolicyValue("system:max-memory-request");
1042 if (value != (char *) NULL)
1043 {
1044 /*
1045 The security policy sets a max memory request limit.
1046 */
1047 max_memory=MagickMax(StringToSizeType(value,100.0),StringToSizeType(
1048 MinMemoryRequest,100.0));
1049 value=DestroyString(value);
1050 }
1051 return(MagickMin(max_memory,(size_t) MAGICK_SSIZE_MAX));
1052}
1053
1054MagickExport size_t GetMaxMemoryRequest(void)
1055{
1056 if (max_memory_request == 0)
1057 {
1058 /*
1059 Setting this to unlimited before we check the policy value to avoid
1060 recursive calls to GetMaxMemoryRequestFromPolicy()
1061 */
1062 max_memory_request=(size_t) MAGICK_SSIZE_MAX;
1063 max_memory_request=GetMaxMemoryRequestFromPolicy();
1064 }
1065 return(max_memory_request);
1066}
1067
1068/*
1069%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1070% %
1071% %
1072% %
1073+ G e t M a x P r o f i l e S i z e %
1074% %
1075% %
1076% %
1077%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1078%
1079% GetMaxProfileSize() returns the max profile size value.
1080%
1081% The format of the GetMaxMemoryRequest method is:
1082%
1083% size_t GetMaxProfileSize(void)
1084%
1085*/
1086static size_t GetMaxProfileSizeFromPolicy(void)
1087{
1088 char
1089 *value;
1090
1091 size_t
1092 max=(size_t) MAGICK_SSIZE_MAX;
1093
1094 value=GetPolicyValue("system:max-profile-size");
1095 if (value != (char *) NULL)
1096 {
1097 /*
1098 The security policy sets a max profile size limit.
1099 */
1100 max=StringToSizeType(value,100.0);
1101 value=DestroyString(value);
1102 }
1103 return(MagickMin(max,(size_t) MAGICK_SSIZE_MAX));
1104}
1105
1106MagickExport size_t GetMaxProfileSize(void)
1107{
1108 if (max_profile_size == 0)
1109 max_profile_size=GetMaxProfileSizeFromPolicy();
1110 return(max_profile_size);
1111}
1112
1113/*
1114%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1115% %
1116% %
1117% %
1118% G e t V i r t u a l M e m o r y B l o b %
1119% %
1120% %
1121% %
1122%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1123%
1124% GetVirtualMemoryBlob() returns the virtual memory blob associated with the
1125% specified MemoryInfo structure.
1126%
1127% The format of the GetVirtualMemoryBlob method is:
1128%
1129% void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
1130%
1131% A description of each parameter follows:
1132%
1133% o memory_info: The MemoryInfo structure.
1134*/
1135MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
1136{
1137 assert(memory_info != (const MemoryInfo *) NULL);
1138 assert(memory_info->signature == MagickCoreSignature);
1139 return(memory_info->blob);
1140}
1141
1142/*
1143%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1144% %
1145% %
1146% %
1147% R e l i n q u i s h A l i g n e d M e m o r y %
1148% %
1149% %
1150% %
1151%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1152%
1153% RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory()
1154% or reuse.
1155%
1156% The format of the RelinquishAlignedMemory method is:
1157%
1158% void *RelinquishAlignedMemory(void *memory)
1159%
1160% A description of each parameter follows:
1161%
1162% o memory: A pointer to a block of memory to free for reuse.
1163%
1164*/
1165MagickExport void *RelinquishAlignedMemory(void *memory)
1166{
1167 if (memory == (void *) NULL)
1168 return((void *) NULL);
1169 if (memory_methods.relinquish_aligned_memory_handler != (RelinquishAlignedMemoryHandler) NULL)
1170 {
1171 memory_methods.relinquish_aligned_memory_handler(memory);
1172 return(NULL);
1173 }
1174#if defined(MAGICKCORE_HAVE_ALIGNED_MALLOC) || defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
1175 free(memory);
1176#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
1177 _aligned_free(memory);
1178#else
1179 RelinquishMagickMemory(actual_base_address(memory));
1180#endif
1181 return(NULL);
1182}
1183
1184/*
1185%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1186% %
1187% %
1188% %
1189% R e l i n q u i s h M a g i c k M e m o r y %
1190% %
1191% %
1192% %
1193%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1194%
1195% RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory()
1196% or AcquireQuantumMemory() for reuse.
1197%
1198% The format of the RelinquishMagickMemory method is:
1199%
1200% void *RelinquishMagickMemory(void *memory)
1201%
1202% A description of each parameter follows:
1203%
1204% o memory: A pointer to a block of memory to free for reuse.
1205%
1206*/
1207MagickExport void *RelinquishMagickMemory(void *memory)
1208{
1209 if (memory == (void *) NULL)
1210 return((void *) NULL);
1211#if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1212 memory_methods.destroy_memory_handler(memory);
1213#else
1214 LockSemaphoreInfo(memory_semaphore);
1215 assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0);
1216 assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0);
1217 if ((*BlockHeader(memory) & PreviousBlockBit) == 0)
1218 {
1219 void
1220 *previous;
1221
1222 /*
1223 Coalesce with previous adjacent block.
1224 */
1225 previous=PreviousBlock(memory);
1226 RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous)));
1227 *BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) |
1228 (*BlockHeader(previous) & ~SizeMask);
1229 memory=previous;
1230 }
1231 if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0)
1232 {
1233 void
1234 *next;
1235
1236 /*
1237 Coalesce with next adjacent block.
1238 */
1239 next=NextBlock(memory);
1240 RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next)));
1241 *BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) |
1242 (*BlockHeader(memory) & ~SizeMask);
1243 }
1244 *BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory);
1245 *BlockHeader(NextBlock(memory))&=(~PreviousBlockBit);
1246 InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory)));
1247 UnlockSemaphoreInfo(memory_semaphore);
1248#endif
1249 return((void *) NULL);
1250}
1251
1252/*
1253%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1254% %
1255% %
1256% %
1257% R e l i n q u i s h V i r t u a l M e m o r y %
1258% %
1259% %
1260% %
1261%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1262%
1263% RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory().
1264%
1265% The format of the RelinquishVirtualMemory method is:
1266%
1267% MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
1268%
1269% A description of each parameter follows:
1270%
1271% o memory_info: A pointer to a block of memory to free for reuse.
1272%
1273*/
1274MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
1275{
1276 assert(memory_info != (MemoryInfo *) NULL);
1277 assert(memory_info->signature == MagickCoreSignature);
1278 if (memory_info->blob != (void *) NULL)
1279 switch (memory_info->type)
1280 {
1281 case AlignedVirtualMemory:
1282 {
1283 (void) ShredMagickMemory(memory_info->blob,memory_info->length);
1284 memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
1285 break;
1286 }
1287 case MapVirtualMemory:
1288 {
1289 (void) UnmapBlob(memory_info->blob,memory_info->length);
1290 memory_info->blob=NULL;
1291 if (*memory_info->filename != '\0')
1292 (void) RelinquishUniqueFileResource(memory_info->filename);
1293 break;
1294 }
1295 case UnalignedVirtualMemory:
1296 default:
1297 {
1298 (void) ShredMagickMemory(memory_info->blob,memory_info->length);
1299 memory_info->blob=RelinquishMagickMemory(memory_info->blob);
1300 break;
1301 }
1302 }
1303 memory_info->signature=(~MagickCoreSignature);
1304 memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
1305 return(memory_info);
1306}
1307
1308/*
1309%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1310% %
1311% %
1312% %
1313% R e s e t M a g i c k M e m o r y %
1314% %
1315% %
1316% %
1317%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1318%
1319% ResetMagickMemory() fills the first size bytes of the memory area pointed to % by memory with the constant byte c. We use a volatile pointer when
1320% updating the byte string. Most compilers will avoid optimizing away access
1321% to a volatile pointer, even if the pointer appears to be unused after the
1322% call.
1323%
1324% The format of the ResetMagickMemory method is:
1325%
1326% void *ResetMagickMemory(void *memory,int c,const size_t size)
1327%
1328% A description of each parameter follows:
1329%
1330% o memory: a pointer to a memory allocation.
1331%
1332% o c: set the memory to this value.
1333%
1334% o size: size of the memory to reset.
1335%
1336*/
1337MagickExport void *ResetMagickMemory(void *memory,int c,const size_t size)
1338{
1339 volatile unsigned char
1340 *p = (volatile unsigned char *) memory;
1341
1342 size_t
1343 n = size;
1344
1345 assert(memory != (void *) NULL);
1346 while (n-- != 0)
1347 *p++=(unsigned char) c;
1348 return(memory);
1349}
1350
1351/*
1352%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1353% %
1354% %
1355% %
1356+ R e s e t V i r t u a l A n o n y m o u s M e m o r y %
1357% %
1358% %
1359% %
1360%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1361%
1362% ResetVirtualAnonymousMemory() resets the virtual_anonymous_memory value.
1363%
1364% The format of the ResetVirtualAnonymousMemory method is:
1365%
1366% void ResetVirtualAnonymousMemory(void)
1367%
1368*/
1369MagickPrivate void ResetVirtualAnonymousMemory(void)
1370{
1371 virtual_anonymous_memory=0;
1372}
1373
1374/*
1375%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1376% %
1377% %
1378% %
1379% R e s i z e M a g i c k M e m o r y %
1380% %
1381% %
1382% %
1383%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1384%
1385% ResizeMagickMemory() changes the size of the memory and returns a pointer to
1386% the (possibly moved) block. The contents will be unchanged up to the
1387% lesser of the new and old sizes.
1388%
1389% The format of the ResizeMagickMemory method is:
1390%
1391% void *ResizeMagickMemory(void *memory,const size_t size)
1392%
1393% A description of each parameter follows:
1394%
1395% o memory: A pointer to a memory allocation.
1396%
1397% o size: the new size of the allocated memory.
1398%
1399*/
1400
1401#if defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1402static inline void *ResizeBlock(void *block,size_t size)
1403{
1404 void
1405 *memory;
1406
1407 if (block == (void *) NULL)
1408 return(AcquireBlock(size));
1409 memory=AcquireBlock(size);
1410 if (memory == (void *) NULL)
1411 return((void *) NULL);
1412 if (size <= (SizeOfBlock(block)-sizeof(size_t)))
1413 (void) memcpy(memory,block,size);
1414 else
1415 (void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t));
1416 memory_pool.allocation+=size;
1417 return(memory);
1418}
1419#endif
1420
1421MagickExport void *ResizeMagickMemory(void *memory,const size_t size)
1422{
1423 void
1424 *block;
1425
1426 if (memory == (void *) NULL)
1427 return(AcquireMagickMemory(size));
1428#if !defined(MAGICKCORE_ANONYMOUS_MEMORY_SUPPORT)
1429 block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size);
1430 if (block == (void *) NULL)
1431 memory=RelinquishMagickMemory(memory);
1432#else
1433 LockSemaphoreInfo(memory_semaphore);
1434 block=ResizeBlock(memory,size == 0 ? 1UL : size);
1435 if (block == (void *) NULL)
1436 {
1437 if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse)
1438 {
1439 UnlockSemaphoreInfo(memory_semaphore);
1440 memory=RelinquishMagickMemory(memory);
1441 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1442 }
1443 block=ResizeBlock(memory,size == 0 ? 1UL : size);
1444 assert(block != (void *) NULL);
1445 }
1446 UnlockSemaphoreInfo(memory_semaphore);
1447 memory=RelinquishMagickMemory(memory);
1448#endif
1449 return(block);
1450}
1451
1452/*
1453%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1454% %
1455% %
1456% %
1457% R e s i z e Q u a n t u m M e m o r y %
1458% %
1459% %
1460% %
1461%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1462%
1463% ResizeQuantumMemory() changes the size of the memory and returns a pointer
1464% to the (possibly moved) block. The contents will be unchanged up to the
1465% lesser of the new and old sizes.
1466%
1467% The format of the ResizeQuantumMemory method is:
1468%
1469% void *ResizeQuantumMemory(void *memory,const size_t count,
1470% const size_t quantum)
1471%
1472% A description of each parameter follows:
1473%
1474% o memory: A pointer to a memory allocation.
1475%
1476% o count: the number of objects to allocate contiguously.
1477%
1478% o quantum: the size (in bytes) of each object.
1479%
1480*/
1481MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
1482 const size_t quantum)
1483{
1484 size_t
1485 size;
1486
1487 if ((HeapOverflowSanityCheckGetSize(count,quantum,&size) != MagickFalse) ||
1488 (size > GetMaxMemoryRequest()))
1489 {
1490 errno=ENOMEM;
1491 memory=RelinquishMagickMemory(memory);
1492 return(NULL);
1493 }
1494 return(ResizeMagickMemory(memory,size));
1495}
1496
1497/*
1498%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1499% %
1500% %
1501% %
1502% S e t M a g i c k A l i g n e d M e m o r y M e t h o d s %
1503% %
1504% %
1505% %
1506%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1507%
1508% SetMagickAlignedMemoryMethods() sets the methods to acquire and relinquish
1509% aligned memory.
1510%
1511% The format of the SetMagickAlignedMemoryMethods() method is:
1512%
1513% void SetMagickAlignedMemoryMethods(
1514% AcquireAlignedMemoryHandler acquire_aligned_memory_handler,
1515% RelinquishAlignedMemoryHandler relinquish_aligned_memory_handler)
1516%
1517% A description of each parameter follows:
1518%
1519% o acquire_memory_handler: method to acquire aligned memory.
1520%
1521% o relinquish_aligned_memory_handler: method to relinquish aligned memory.
1522%
1523*/
1524MagickExport void SetMagickAlignedMemoryMethods(
1525 AcquireAlignedMemoryHandler acquire_aligned_memory_handler,
1526 RelinquishAlignedMemoryHandler relinquish_aligned_memory_handler)
1527{
1528 memory_methods.acquire_aligned_memory_handler=acquire_aligned_memory_handler;
1529 memory_methods.relinquish_aligned_memory_handler=
1530 relinquish_aligned_memory_handler;
1531}
1532
1533/*
1534%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1535% %
1536% %
1537% %
1538% S e t M a g i c k M e m o r y M e t h o d s %
1539% %
1540% %
1541% %
1542%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1543%
1544% SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy
1545% memory. Your custom memory methods must be set prior to the
1546% MagickCoreGenesis() method.
1547%
1548% The format of the SetMagickMemoryMethods() method is:
1549%
1550% void SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler,
1551% ResizeMemoryHandler resize_memory_handler,
1552% DestroyMemoryHandler destroy_memory_handler)
1553%
1554% A description of each parameter follows:
1555%
1556% o acquire_memory_handler: method to acquire memory (e.g. malloc).
1557%
1558% o resize_memory_handler: method to resize memory (e.g. realloc).
1559%
1560% o destroy_memory_handler: method to destroy memory (e.g. free).
1561%
1562*/
1563MagickExport void SetMagickMemoryMethods(
1564 AcquireMemoryHandler acquire_memory_handler,
1565 ResizeMemoryHandler resize_memory_handler,
1566 DestroyMemoryHandler destroy_memory_handler)
1567{
1568 /*
1569 Set memory methods.
1570 */
1571 if (acquire_memory_handler != (AcquireMemoryHandler) NULL)
1572 memory_methods.acquire_memory_handler=acquire_memory_handler;
1573 if (resize_memory_handler != (ResizeMemoryHandler) NULL)
1574 memory_methods.resize_memory_handler=resize_memory_handler;
1575 if (destroy_memory_handler != (DestroyMemoryHandler) NULL)
1576 memory_methods.destroy_memory_handler=destroy_memory_handler;
1577}
1578
1579/*
1580%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1581% %
1582% %
1583% %
1584+ S e t M a x M e m o r y R e q u e s t %
1585% %
1586% %
1587% %
1588%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1589%
1590% SetMaxMemoryRequest() sets the max memory request value.
1591%
1592% The format of the SetMaxMemoryRequest method is:
1593%
1594% void SetMaxMemoryRequest(const MagickSizeType limit)
1595%
1596% A description of each parameter follows:
1597%
1598% o limit: the maximum memory request limit.
1599%
1600*/
1601MagickPrivate void SetMaxMemoryRequest(const MagickSizeType limit)
1602{
1603 max_memory_request=(size_t) MagickMin(limit,GetMaxMemoryRequestFromPolicy());
1604}
1605
1606/*
1607%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1608% %
1609% %
1610% %
1611+ S e t M a x P r o f i l e S i z e %
1612% %
1613% %
1614% %
1615%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1616%
1617% SetMaxProfileSize() sets the max profile size value.
1618%
1619% The format of the SetMaxProfileSize method is:
1620%
1621% void SetMaxProfileSize(const MagickSizeType limit)
1622%
1623% A description of each parameter follows:
1624%
1625% o limit: the maximum profile size limit.
1626%
1627*/
1628MagickPrivate void SetMaxProfileSize(const MagickSizeType limit)
1629{
1630 max_profile_size=(size_t) MagickMin(limit,GetMaxProfileSizeFromPolicy());
1631}
1632
1633/*
1634%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1635% %
1636% %
1637% %
1638% S h r e d M a g i c k M e m o r y %
1639% %
1640% %
1641% %
1642%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1643%
1644% ShredMagickMemory() overwrites the specified memory buffer with random data.
1645% The overwrite is optional and is only required to help keep the contents of
1646% the memory buffer private.
1647%
1648% The format of the ShredMagickMemory method is:
1649%
1650% MagickBooleanType ShredMagickMemory(void *memory,const size_t length)
1651%
1652% A description of each parameter follows.
1653%
1654% o memory: Specifies the memory buffer.
1655%
1656% o length: Specifies the length of the memory buffer.
1657%
1658*/
1659MagickPrivate MagickBooleanType ShredMagickMemory(void *memory,
1660 const size_t length)
1661{
1662 RandomInfo
1663 *random_info;
1664
1665 size_t
1666 quantum;
1667
1668 ssize_t
1669 i;
1670
1671 static ssize_t
1672 passes = -1;
1673
1674 StringInfo
1675 *key;
1676
1677 if ((memory == NULL) || (length == 0))
1678 return(MagickFalse);
1679 if (passes == -1)
1680 {
1681 char
1682 *property;
1683
1684 passes=0;
1685 property=GetEnvironmentValue("MAGICK_SHRED_PASSES");
1686 if (property != (char *) NULL)
1687 {
1688 passes=(ssize_t) StringToInteger(property);
1689 property=DestroyString(property);
1690 }
1691 property=GetPolicyValue("system:shred");
1692 if (property != (char *) NULL)
1693 {
1694 passes=(ssize_t) StringToInteger(property);
1695 property=DestroyString(property);
1696 }
1697 }
1698 if (passes == 0)
1699 return(MagickTrue);
1700 /*
1701 Overwrite the memory buffer with random data.
1702 */
1703 quantum=(size_t) MagickMin(length,MagickMinBufferExtent);
1704 random_info=AcquireRandomInfo();
1705 key=GetRandomKey(random_info,quantum);
1706 for (i=0; i < passes; i++)
1707 {
1708 size_t
1709 j;
1710
1711 unsigned char
1712 *p = (unsigned char *) memory;
1713
1714 for (j=0; j < length; j+=quantum)
1715 {
1716 if (i != 0)
1717 SetRandomKey(random_info,quantum,GetStringInfoDatum(key));
1718 (void) memcpy(p,GetStringInfoDatum(key),(size_t)
1719 MagickMin(quantum,length-j));
1720 p+=(ptrdiff_t) quantum;
1721 }
1722 if (j < length)
1723 break;
1724 }
1725 key=DestroyStringInfo(key);
1726 random_info=DestroyRandomInfo(random_info);
1727 return(i < passes ? MagickFalse : MagickTrue);
1728}