fa5b4b586bf0228bf15d4951af95d68312e94733
[gbajam22] / src / util.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include "util.h"
4 #include "debug.h"
5
6 #ifdef BUILD_GBA
7 extern char __iheap_start;
8 #else
9 #define IWRAM_POOL_SZ   32768
10 #define __iheap_start   iwram[0]
11 static char iwram[IWRAM_POOL_SZ];
12 #endif
13 static char *top = &__iheap_start;
14
15 int iwram_brk(void *addr)
16 {
17         if((char*)addr < &__iheap_start) {
18                 addr = &__iheap_start;
19         }
20         if(addr > get_sp()) {
21                 /*return -1;*/
22                 panic(get_pc(), "iwram_brk (%p) >= sp", addr);
23         }
24         top = addr;
25         return 0;
26 }
27
28 void *iwram_sbrk(intptr_t delta)
29 {
30         void *prev = top;
31         iwram_brk(top + delta);
32         return prev;
33 }
34
35 int ispow2(unsigned int x)
36 {
37         int cnt = 0;
38         while(x) {
39                 if(x & 1) cnt++;
40                 x >>= 1;
41         }
42         return cnt == 1;
43 }
44
45
46
47 void *malloc_nf_impl(size_t sz, const char *file, int line)
48 {
49         void *p;
50         if(!(p = malloc(sz))) {
51                 panic(get_pc(), "%s:%d malloc %lu\n", file, line, (unsigned long)sz);
52         }
53         return p;
54 }
55
56 void *calloc_nf_impl(size_t num, size_t sz, const char *file, int line)
57 {
58         void *p;
59         if(!(p = calloc(num, sz))) {
60                 panic(get_pc(), "%s:%d calloc %lu\n", file, line, (unsigned long)(num * sz));
61         }
62         return p;
63 }
64
65 void *realloc_nf_impl(void *p, size_t sz, const char *file, int line)
66 {
67         if(!(p = realloc(p, sz))) {
68                 panic(get_pc(), "%s:%d realloc %lu\n", file, line, (unsigned long)sz);
69         }
70         return p;
71 }
72
73 char *strdup_nf_impl(const char *s, const char *file, int line)
74 {
75         int len;
76         char *res;
77
78         len = strlen(s);
79         if(!(res = malloc(len + 1))) {
80                 panic(get_pc(), "%s:%d strdup\n", file, line);
81         }
82         memcpy(res, s, len + 1);
83         return res;
84 }