1 /*
2  * Arm SCP/MCP Software
3  * Copyright (c) 2015-2022, Arm Limited and Contributors. All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Description:
8  *     Memory initialization.
9  */
10 
11 #include <fwk_macros.h>
12 
13 #include <stddef.h>
14 #include <stdint.h>
15 
16 #if FWK_HAS_INCLUDE(<sys/features.h>)
17 #    include <sys/features.h>
18 #endif
19 
20 #ifdef __NEWLIB__
21 #    include <errno.h>
22 #    include <malloc.h>
23 
24 extern char __stackheap_start__;
25 extern char __stackheap_end__;
26 
27 /*!
28  * \brief Architecture memory manager context.
29  */
30 static struct arch_mm_ctx_str {
31     /*!
32      * \brief Current heap break address.
33      */
34     uintptr_t heap_break;
35 } arch_mm_ctx = {
36     .heap_break = ((uintptr_t)&__stackheap_start__),
37 };
38 
posix_memalign(void ** memptr,size_t alignment,size_t size)39 int posix_memalign(void **memptr, size_t alignment, size_t size)
40 {
41     if (alignment == 0) {
42         return EINVAL;
43     }
44 
45     /* Enforce power-of-two alignment */
46     if ((alignment & (alignment - 1)) != 0) {
47         return EINVAL;
48     }
49 
50     if ((alignment % sizeof(void *)) != 0) {
51         return EINVAL;
52     }
53 
54     if (size == 0) {
55         *memptr = NULL;
56     } else {
57         *memptr = _memalign_r(_REENT, alignment, size);
58 
59         if (*memptr == NULL) {
60             return ENOMEM;
61         }
62     }
63 
64     return 0;
65 }
66 
_sbrk(intptr_t increment)67 void *_sbrk(intptr_t increment)
68 {
69     if (increment == 0) {
70         return (void *)arch_mm_ctx.heap_break;
71     } else {
72         uintptr_t heap_old = arch_mm_ctx.heap_break;
73         uintptr_t heap_new = arch_mm_ctx.heap_break + increment;
74 
75         if (heap_new > ((uintptr_t)&__stackheap_end__)) {
76             errno = ENOMEM;
77 
78             return (void *)-1;
79         } else {
80             arch_mm_ctx.heap_break = heap_new;
81 
82             return (void *)heap_old;
83         }
84     }
85 }
86 #endif
87