add missing tools/pngdump to the repo
[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         emuprint("iwram brk: %p (sp: %p)", addr, get_sp());
21         if(addr > get_sp()) {
22                 /*return -1;*/
23                 panic(get_pc(), "iwram_brk (%p) >= sp", addr);
24         }
25         top = addr;
26         return 0;
27 }
28
29 void *iwram_sbrk(intptr_t delta)
30 {
31         void *prev = top;
32         iwram_brk(top + delta);
33         return prev;
34 }
35
36 int ispow2(unsigned int x)
37 {
38         int cnt = 0;
39         while(x) {
40                 if(x & 1) cnt++;
41                 x >>= 1;
42         }
43         return cnt == 1;
44 }
45
46
47
48 void *malloc_nf_impl(size_t sz, const char *file, int line)
49 {
50         void *p;
51         if(!(p = malloc(sz))) {
52                 panic(get_pc(), "%s:%d malloc %lu\n", file, line, (unsigned long)sz);
53         }
54         return p;
55 }
56
57 void *calloc_nf_impl(size_t num, size_t sz, const char *file, int line)
58 {
59         void *p;
60         if(!(p = calloc(num, sz))) {
61                 panic(get_pc(), "%s:%d calloc %lu\n", file, line, (unsigned long)(num * sz));
62         }
63         return p;
64 }
65
66 void *realloc_nf_impl(void *p, size_t sz, const char *file, int line)
67 {
68         if(!(p = realloc(p, sz))) {
69                 panic(get_pc(), "%s:%d realloc %lu\n", file, line, (unsigned long)sz);
70         }
71         return p;
72 }
73
74 char *strdup_nf_impl(const char *s, const char *file, int line)
75 {
76         int len;
77         char *res;
78
79         len = strlen(s);
80         if(!(res = malloc(len + 1))) {
81                 panic(get_pc(), "%s:%d strdup\n", file, line);
82         }
83         memcpy(res, s, len + 1);
84         return res;
85 }
86
87 #ifndef BUILD_GBA
88 /* utility functions which are implemented in assembly on GBA builds */
89
90 void fillblock_16byte(void *dest, uint32_t val, int count)
91 {
92         int i;
93         uint32_t *p = dest;
94
95         for(i=0; i<count; i++) {
96                 p[0] = val;
97                 p[1] = val;
98                 p[2] = val;
99                 p[3] = val;
100                 p += 4;
101         }
102 }
103
104 void *get_pc(void)
105 {
106         return 0;       /* not useful on PC builds */
107 }
108
109 void *get_sp(void)
110 {
111         return (void*)-1;       /* not useful on PC builds */
112 }
113 #endif