1 /*
2  * Copyright (c) 2015-2016, Freescale Semiconductor, Inc.
3  * Copyright 2016-2021 NXP
4  * All rights reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  */
8 
9 #include "fsl_common.h"
10 
11 #define SDK_MEM_MAGIC_NUMBER 12345U
12 
13 typedef struct _mem_align_control_block
14 {
15     uint16_t identifier; /*!< Identifier for the memory control block. */
16     uint16_t offset;     /*!< offset from aligned address to real address */
17 } mem_align_cb_t;
18 
19 /* Component ID definition, used by tools. */
20 #ifndef FSL_COMPONENT_ID
21 #define FSL_COMPONENT_ID "platform.drivers.common"
22 #endif
23 
SDK_Malloc(size_t size,size_t alignbytes)24 void *SDK_Malloc(size_t size, size_t alignbytes)
25 {
26     mem_align_cb_t *p_cb = NULL;
27     uint32_t alignedsize;
28 
29     /* Check overflow. */
30     alignedsize = SDK_SIZEALIGN(size, alignbytes);
31     if (alignedsize < size)
32     {
33         return NULL;
34     }
35 
36     if (alignedsize > SIZE_MAX - alignbytes - sizeof(mem_align_cb_t))
37     {
38         return NULL;
39     }
40 
41     alignedsize += alignbytes + sizeof(mem_align_cb_t);
42 
43     union
44     {
45         void *pointer_value;
46         uint32_t unsigned_value;
47     } p_align_addr, p_addr;
48 
49     p_addr.pointer_value = malloc(alignedsize);
50 
51     if (p_addr.pointer_value == NULL)
52     {
53         return NULL;
54     }
55 
56     p_align_addr.unsigned_value = SDK_SIZEALIGN(p_addr.unsigned_value + sizeof(mem_align_cb_t), alignbytes);
57 
58     p_cb             = (mem_align_cb_t *)(p_align_addr.unsigned_value - 4U);
59     p_cb->identifier = SDK_MEM_MAGIC_NUMBER;
60     p_cb->offset     = (uint16_t)(p_align_addr.unsigned_value - p_addr.unsigned_value);
61 
62     return p_align_addr.pointer_value;
63 }
64 
SDK_Free(void * ptr)65 void SDK_Free(void *ptr)
66 {
67     union
68     {
69         void *pointer_value;
70         uint32_t unsigned_value;
71     } p_free;
72     p_free.pointer_value = ptr;
73     mem_align_cb_t *p_cb = (mem_align_cb_t *)(p_free.unsigned_value - 4U);
74 
75     if (p_cb->identifier != SDK_MEM_MAGIC_NUMBER)
76     {
77         return;
78     }
79 
80     p_free.unsigned_value = p_free.unsigned_value - p_cb->offset;
81 
82     free(p_free.pointer_value);
83 }
84