TianoCore EDK2 master
Loading...
Searching...
No Matches
BaseMemAllocation.c
Go to the documentation of this file.
1
10#include <CrtLibSupport.h>
12
13//
14// Extra header to record the memory buffer size from malloc routine.
15//
16#define CRYPTMEM_HEAD_SIGNATURE SIGNATURE_32('c','m','h','d')
17typedef struct {
18 UINT32 Signature;
19 UINT32 Reserved;
20 UINTN Size;
22
23#define CRYPTMEM_OVERHEAD sizeof(CRYPTMEM_HEAD)
24
25//
26// -- Memory-Allocation Routines --
27//
28
29/* Allocates memory blocks */
30void *
31malloc (
32 size_t size
33 )
34{
35 CRYPTMEM_HEAD *PoolHdr;
36 UINTN NewSize;
37 VOID *Data;
38
39 //
40 // Adjust the size by the buffer header overhead
41 //
42 NewSize = (UINTN)(size) + CRYPTMEM_OVERHEAD;
43
44 Data = AllocatePool (NewSize);
45 if (Data != NULL) {
46 PoolHdr = (CRYPTMEM_HEAD *)Data;
47 //
48 // Record the memory brief information
49 //
50 PoolHdr->Signature = CRYPTMEM_HEAD_SIGNATURE;
51 PoolHdr->Size = size;
52
53 return (VOID *)(PoolHdr + 1);
54 } else {
55 //
56 // The buffer allocation failed.
57 //
58 return NULL;
59 }
60}
61
62/* Reallocate memory blocks */
63void *
64realloc (
65 void *ptr,
66 size_t size
67 )
68{
69 CRYPTMEM_HEAD *OldPoolHdr;
70 CRYPTMEM_HEAD *NewPoolHdr;
71 UINTN OldSize;
72 UINTN NewSize;
73 VOID *Data;
74
75 NewSize = (UINTN)size + CRYPTMEM_OVERHEAD;
76 Data = AllocatePool (NewSize);
77 if (Data != NULL) {
78 NewPoolHdr = (CRYPTMEM_HEAD *)Data;
79 NewPoolHdr->Signature = CRYPTMEM_HEAD_SIGNATURE;
80 NewPoolHdr->Size = size;
81 if (ptr != NULL) {
82 //
83 // Retrieve the original size from the buffer header.
84 //
85 OldPoolHdr = (CRYPTMEM_HEAD *)ptr - 1;
86 ASSERT (OldPoolHdr->Signature == CRYPTMEM_HEAD_SIGNATURE);
87 OldSize = OldPoolHdr->Size;
88
89 //
90 // Duplicate the buffer content.
91 //
92 CopyMem ((VOID *)(NewPoolHdr + 1), ptr, MIN (OldSize, size));
93 FreePool ((VOID *)OldPoolHdr);
94 }
95
96 return (VOID *)(NewPoolHdr + 1);
97 } else {
98 //
99 // The buffer allocation failed.
100 //
101 return NULL;
102 }
103}
104
105/* De-allocates or frees a memory block */
106void
107free (
108 void *ptr
109 )
110{
111 CRYPTMEM_HEAD *PoolHdr;
112
113 //
114 // In Standard C, free() handles a null pointer argument transparently. This
115 // is not true of FreePool() below, so protect it.
116 //
117 if (ptr != NULL) {
118 PoolHdr = (CRYPTMEM_HEAD *)ptr - 1;
119 ASSERT (PoolHdr->Signature == CRYPTMEM_HEAD_SIGNATURE);
120 FreePool (PoolHdr);
121 }
122}
UINT64 UINTN
VOID *EFIAPI CopyMem(OUT VOID *DestinationBuffer, IN CONST VOID *SourceBuffer, IN UINTN Length)
VOID EFIAPI FreePool(IN VOID *Buffer)
#define NULL
Definition: Base.h:319
#define MIN(a, b)
Definition: Base.h:1007
VOID *EFIAPI AllocatePool(IN UINTN AllocationSize)