2bd0338be4e7697cde7d97ef64d9aebba008466a
[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 }
85
86 #ifndef BUILD_GBA
87 /* utility functions which are implemented in assembly on GBA builds */
88
89 void fillblock_16byte(void *dest, uint32_t val, int count)
90 {
91         int i;
92         uint32_t *p = dest;
93
94         for(i=0; i<count; i++) {
95                 p[0] = val;
96                 p[1] = val;
97                 p[2] = val;
98                 p[3] = val;
99                 p += 4;
100         }
101 }
102
103 void *get_pc(void)
104 {
105         return 0;       /* not useful on PC builds */
106 }
107
108 void *get_sp(void)
109 {
110         return (void*)-1;       /* not useful on PC builds */
111 }
112 #endif