1 /*
2  * Renesas SCP/MCP Software
3  * Copyright (c) 2020-2022, Renesas Electronics Corporation. All rights
4  * reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  */
8 
9 #include <fwk_arch.h>
10 #include <fwk_macros.h>
11 
12 #include <stdarg.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <string.h>
16 
17 #if FWK_HAS_INCLUDE(<sys / features.h>)
18 #    include <sys/features.h>
19 #endif
20 
21 extern char __HEAP_START__;
22 extern char __HEAP_END__;
23 
24 /*!
25  * \brief Architecture memory manager context.
26  */
27 static struct arch_mm_ctx {
28     uintptr_t heap_break;
29     uintptr_t heap_end;
30 } arch_mm_ctx = {
31     .heap_break = (uintptr_t)(&__HEAP_START__),
32     .heap_end = (uintptr_t)(&__HEAP_END__),
33 };
34 
_sbrk(intptr_t increment)35 void *_sbrk(intptr_t increment)
36 {
37     if (increment == 0) {
38         return (void *)arch_mm_ctx.heap_break;
39     } else {
40         uintptr_t heap_old = FWK_ALIGN_NEXT(arch_mm_ctx.heap_break, 16);
41         uintptr_t heap_new = heap_old + increment;
42 
43         if (heap_new > arch_mm_ctx.heap_end) {
44             return (void *)-1;
45         } else {
46             arch_mm_ctx.heap_break = heap_new;
47 
48             return (void *)heap_old;
49         }
50     }
51 }
52 
53 #ifndef USE_NEWLIB
malloc(size_t size)54 void *malloc(size_t size)
55 {
56     void *mem = _sbrk((intptr_t)size);
57 
58     if (mem == ((void *)-1))
59         mem = NULL;
60 
61     return mem;
62 }
63 
calloc(size_t nmemb,size_t size)64 void *calloc(size_t nmemb, size_t size)
65 {
66     void *mem = malloc(nmemb * size);
67 
68     if (mem)
69         memset(mem, 0, nmemb * size);
70 
71     return mem;
72 }
73 #endif
74