alloc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. #include "alloc.h"
  2. #include <malloc.h>
  3. #include <stdint.h>
  4. #include "stream.h"
  5. void* byte_heap;
  6. Cell* cell_heap;
  7. uint32_t cells_used;
  8. uint32_t byte_heap_used;
  9. Cell** free_list;
  10. uint32_t free_list_avail;
  11. uint32_t free_list_consumed;
  12. Cell oom_cell;
  13. //#define DEBUG_GC
  14. // TODO define in machine specs
  15. #define MAX_CELLS 10000000
  16. #define MAX_BYTE_HEAP 1024*1024*8
  17. static struct MemStats mem_stats;
  18. void init_allocator() {
  19. oom_cell.tag = TAG_ERROR;
  20. oom_cell.value = ERR_OUT_OF_MEMORY;
  21. byte_heap_used = 0;
  22. cells_used = 0;
  23. free_list_avail = 0;
  24. free_list_consumed = 0;
  25. byte_heap = NULL;
  26. uint32_t cell_mem_reserved = MAX_CELLS * sizeof(Cell);
  27. cell_heap = malloc(cell_mem_reserved);
  28. printf("\r\n++ cell heap at %p, %d bytes reserved\r\n",cell_heap,cell_mem_reserved);
  29. memset(cell_heap,0,cell_mem_reserved);
  30. free_list = malloc(MAX_CELLS*sizeof(Cell*));
  31. printf("[allocator] initialized.\r\n");
  32. //byte_heap = malloc(MAX_BYTE_HEAP);
  33. }
  34. Cell* get_cell_heap() {
  35. return cell_heap;
  36. }
  37. // FIXME header?
  38. env_t* get_global_env();
  39. Cell* cell_alloc() {
  40. if (free_list_avail>free_list_consumed) {
  41. // serve from free list
  42. int idx = free_list_consumed;
  43. free_list_consumed++;
  44. Cell* res = free_list[idx];
  45. return res;
  46. } else {
  47. // grow heap
  48. Cell* res = &cell_heap[cells_used];
  49. cells_used++;
  50. if (cells_used>MAX_CELLS) {
  51. // out of memory
  52. printf("[cell_alloc] failed: MAX_CELLS used.\n");
  53. exit(1);
  54. }
  55. return res;
  56. }
  57. }
  58. void* bytes_alloc(int num_bytes) {
  59. //#ifdef SLEDGE_MALLOC
  60. void* new_mem = malloc(num_bytes);
  61. //printf("bytes_alloc: %p +%d\r\n",new_mem,num_bytes);
  62. memset(new_mem, 0, num_bytes);
  63. return new_mem;
  64. //#endif
  65. /*void* new_mem = byte_heap + byte_heap_used;
  66. if (byte_heap_used + num_bytes < MAX_BYTE_HEAP) {
  67. byte_heap_used += num_bytes;
  68. //printf("++ byte_alloc: %d (+%d) \r\n",byte_heap_used,num_bytes);
  69. return new_mem;
  70. } else {
  71. printf("~~ bytes_alloc: out of memory: %d (%d)\r\n",byte_heap,byte_heap_used);
  72. exit(1);
  73. return NULL;
  74. }*/
  75. }
  76. void mark_tree(Cell* c) {
  77. if (!c) {
  78. //printf("~! warning: mark_tree encountered NULL cell.\n");
  79. return;
  80. }
  81. if (!(c->tag & TAG_MARK)) {
  82. /*char buf[80];
  83. lisp_write(c, buf, 79);
  84. printf("~~ marking live: %p %s\n",c,buf);*/
  85. c->tag |= TAG_MARK;
  86. if (c->tag & TAG_CONS) {
  87. if (c->addr) mark_tree((Cell*)c->addr);
  88. if (c->next) mark_tree((Cell*)c->next);
  89. }
  90. else if (c->tag & TAG_SYM) {
  91. // TODO: mark bytes in heap
  92. // also for STR, BYTES
  93. }
  94. else if (c->tag & TAG_LAMBDA) {
  95. /*static char buf[512];
  96. lisp_write((Cell*)c->addr, buf, 511);
  97. printf("~~ mark lambda args: %s\n",buf);*/
  98. mark_tree((Cell*)c->addr); // function arguments
  99. //mark_tree((Cell*)c->next); // function body
  100. // TODO: mark compiled code / free unused compiled code
  101. // -- keep all compiled blobs in a list
  102. }
  103. else if (c->tag & TAG_BUILTIN) {
  104. mark_tree((Cell*)c->next); // builtin signature
  105. }
  106. else if (c->tag & TAG_STREAM) {
  107. Stream* s = (Stream*)c->addr;
  108. //mark_tree(s->path);
  109. }
  110. else if (c->tag & TAG_FS) {
  111. Filesystem* fs = (Filesystem*)c->next;
  112. mark_tree(fs->mount_point);
  113. mark_tree(fs->open_fn);
  114. mark_tree(fs->close_fn);
  115. mark_tree(fs->read_fn);
  116. mark_tree(fs->write_fn);
  117. mark_tree(fs->delete_fn);
  118. mark_tree(fs->mmap_fn);
  119. }
  120. }
  121. }
  122. static Cell* _symbols_list;
  123. void list_symbols_iter(const char *key, void *value, const void *obj)
  124. {
  125. env_entry* e = (env_entry*)value;
  126. _symbols_list = alloc_cons(alloc_sym(e->name), _symbols_list);
  127. }
  128. Cell* list_symbols(env_t* global_env) {
  129. _symbols_list = alloc_nil();
  130. sm_enum(global_env, list_symbols_iter, NULL);
  131. return _symbols_list;
  132. }
  133. void collect_garbage_iter(const char *key, void *value, const void *obj)
  134. {
  135. env_entry* e = (env_entry*)value;
  136. //printf("key: %s value: %s\n", key, value);
  137. mark_tree(e->cell);
  138. }
  139. Cell* collect_garbage(env_t* global_env, void* stack_end, void* stack_pointer) {
  140. // mark
  141. // check all symbols in the environment
  142. // and look where they lead (cons trees, bytes, strings)
  143. // mark all of them as usable
  144. // (def foo (fn (do (let a 1) (let b 2) (+ a b) (gc))))
  145. //printf("[gc] stack at: %p, stack end: %p\r\n",stack_pointer,stack_end);
  146. // FIXME: how low can we safely go?
  147. int sw_state = 0;
  148. for (jit_word_t* a=(jit_word_t*)stack_end; a>=(jit_word_t*)stack_pointer; a--) {
  149. jit_word_t item = *a;
  150. jit_word_t next_item = *(a-1);
  151. if (next_item&STACK_FRAME_MARKER) {
  152. sw_state=2;
  153. } else {
  154. if (sw_state==2) {
  155. sw_state=1;
  156. } else if (sw_state==1) {
  157. // FIXME total hack, need type information for stack
  158. // maybe type/signature byte frame header?
  159. if ((Cell*)item>cell_heap) {
  160. //printf("[gc] stack %p\r\n",item);
  161. mark_tree((Cell*)item);
  162. }
  163. }
  164. }
  165. /*if (sw_state==2) {
  166. printf(KMAG "%p: 0x%08lx\r\n" KWHT,a,item);
  167. }
  168. else if (sw_state==1) {
  169. printf(KCYN "%p: 0x%08lx\r\n" KWHT,a,item);
  170. }
  171. else {
  172. printf(KWHT "%p: 0x%08lx\r\n" KWHT,a,item);
  173. }*/
  174. }
  175. //printf("[gc] stack walk complete -------------------------------\r\n");
  176. sm_enum(global_env, collect_garbage_iter, NULL);
  177. mark_tree(get_fs_list());
  178. /*for (env_entry* e=global_env; e != NULL; e=e->hh.next) {
  179. //printf("env entry: %s pointing to %p\n",e->name,e->cell);
  180. if (!e->cell) {
  181. //printf("~! warning: NULL env entry %s.\n",e->name);
  182. }
  183. mark_tree(e->cell);
  184. }*/
  185. // sweep -- free all things that are not marked
  186. int gc = 0;
  187. char buf[300];
  188. free_list_avail = 0;
  189. free_list_consumed = 0;
  190. int highwater = 0;
  191. #ifdef DEBUG_GC
  192. printf("\e[1;1H\e[2J");
  193. printf("~~ cell memory: ");
  194. #endif
  195. for (int i=0; i<cells_used; i++) {
  196. Cell* c = &cell_heap[i];
  197. // FIXME: we cannot free LAMBDAS currently
  198. // because nobody points to anonymous closures.
  199. // this has to be fixed by introducing metadata to their callers. (?)
  200. if (!(c->tag & TAG_MARK) && c->tag!=TAG_LAMBDA) {
  201. #ifdef DEBUG_GC
  202. printf(".");
  203. #endif
  204. if (c->tag == TAG_BYTES || c->tag == TAG_STR) {
  205. free(c->addr);
  206. }
  207. c->tag = TAG_FREED;
  208. free_list[free_list_avail] = c;
  209. free_list_avail++;
  210. gc++;
  211. } else {
  212. highwater = i;
  213. #ifdef DEBUG_GC
  214. printf("o");
  215. #endif
  216. }
  217. // unset mark bit
  218. cell_heap[i].tag &= ~TAG_MARK;
  219. }
  220. //printf("[gc] highwater %d fl_avail %d \r\n",highwater,free_list_avail);
  221. // FIXME on x64, this line causes corruption over time
  222. //cells_used = highwater+1;
  223. #ifdef DEBUG_GC
  224. printf("\n\n");
  225. printf("~~ %d of %d cells were garbage.\r\n",gc,cells_used);
  226. #endif
  227. //printf("-- %d high water mark.\n\n",cells_used);
  228. return alloc_int(cells_used);
  229. }
  230. void* cell_realloc(void* old_addr, unsigned int old_size, unsigned int num_bytes) {
  231. // FIXME
  232. //cell_free(old_addr, old_size);
  233. void* new = bytes_alloc(num_bytes+1);
  234. memcpy(new, old_addr, old_size);
  235. return new;
  236. }
  237. MemStats* alloc_stats() {
  238. mem_stats.byte_heap_used = byte_heap_used;
  239. mem_stats.byte_heap_max = MAX_BYTE_HEAP;
  240. mem_stats.cells_used = cells_used;
  241. mem_stats.cells_max = MAX_CELLS;
  242. return &mem_stats;
  243. }
  244. Cell* alloc_cons(Cell* ar, Cell* dr) {
  245. Cell* cons = cell_alloc();
  246. cons->tag = TAG_CONS;
  247. cons->addr = ar; //?alloc_clone(ar):ar;
  248. cons->next = dr; //?alloc_clone(dr):dr;
  249. return cons;
  250. }
  251. Cell* alloc_list(Cell** items, int num) {
  252. Cell* list = alloc_nil();
  253. for (int i=num-1; i>=0; i--) {
  254. list = alloc_cons(items[i], list);
  255. }
  256. return list;
  257. }
  258. //extern void uart_puts(char* str);
  259. extern void memdump(jit_word_t start,uint32_t len,int raw);
  260. Cell* alloc_sym(char* str) {
  261. Cell* sym = cell_alloc();
  262. //printf("++ alloc sym at %p %p %d\r\n",sym,sym->addr,sym->size);
  263. sym->tag = TAG_SYM;
  264. if (str) {
  265. int sz = strlen(str)+1;
  266. sym->size = sz;
  267. //printf("alloc_sym: %s (%d)\r\n",str,sz);
  268. //memdump(sym,sizeof(Cell),0);
  269. sym->addr = bytes_alloc(sz+1);
  270. //memdump(sym,sizeof(Cell),0);
  271. memcpy(sym->addr, str, sz);
  272. //memdump(sym,sizeof(Cell),0);
  273. } else {
  274. sym->addr = 0;
  275. sym->size = 0;
  276. }
  277. return sym;
  278. }
  279. Cell* alloc_int(int i) {
  280. //printf("++ alloc_int %d\r\n",i);
  281. Cell* num = cell_alloc();
  282. num->tag = TAG_INT;
  283. num->value = i;
  284. return num;
  285. }
  286. Cell* alloc_num_bytes(unsigned int num_bytes) {
  287. Cell* cell = cell_alloc();
  288. cell->addr = bytes_alloc(num_bytes+1); // 1 zeroed byte more to defeat clib-str overflows
  289. cell->tag = TAG_BYTES;
  290. cell->size = num_bytes;
  291. return cell;
  292. }
  293. Cell* alloc_bytes() {
  294. return alloc_num_bytes(SYM_INIT_BUFFER_SIZE);
  295. }
  296. Cell* alloc_num_string(unsigned int num_bytes) {
  297. Cell* cell = cell_alloc();
  298. cell->addr = bytes_alloc(num_bytes+1); // 1 zeroed byte more to defeat clib-str overflows
  299. cell->tag = TAG_STR;
  300. cell->size = num_bytes;
  301. return cell;
  302. }
  303. Cell* alloc_substr(Cell* str, unsigned int from, unsigned int len) {
  304. if (!str) return alloc_string_copy("");
  305. if (str->tag!=TAG_BYTES && str->tag!=TAG_STR) return alloc_string_copy("");
  306. if (from>=str->size) from=str->size-1;
  307. if (len+from>str->size) len=str->size-from; // FIXME TEST
  308. Cell* cell = cell_alloc();
  309. cell->addr = bytes_alloc(len+1); // 1 zeroed byte more to defeat clib-str overflows
  310. cell->tag = TAG_STR;
  311. cell->size = len;
  312. memcpy(cell->addr, (uint8_t*)str->addr+from, len);
  313. return cell;
  314. }
  315. Cell* alloc_string() {
  316. return alloc_num_string(SYM_INIT_BUFFER_SIZE);
  317. }
  318. // FIXME: max size?
  319. Cell* alloc_string_copy(char* str) {
  320. Cell* cell = cell_alloc();
  321. cell->addr = bytes_alloc(strlen(str)+1);
  322. strcpy(cell->addr, str);
  323. cell->tag = TAG_STR;
  324. cell->size = strlen(str)+1;
  325. return cell;
  326. }
  327. Cell* alloc_string_from_bytes(Cell* bytes) {
  328. if (!bytes) return alloc_string_copy("");
  329. if (bytes->tag!=TAG_BYTES && bytes->tag!=TAG_STR) return alloc_string_copy("");
  330. if (bytes->size<1) return alloc_string_copy("");
  331. Cell* cell = cell_alloc();
  332. cell->addr = bytes_alloc(bytes->size+1);
  333. memcpy(cell->addr, bytes->addr, bytes->size);
  334. ((char*)cell->addr)[bytes->size]=0;
  335. cell->tag = TAG_STR;
  336. cell->size = bytes->size+1;
  337. return cell;
  338. }
  339. Cell* alloc_concat(Cell* str1, Cell* str2) {
  340. if (!str1 || !str2) return alloc_string_copy("");
  341. if (str1->tag!=TAG_BYTES && str1->tag!=TAG_STR) return alloc_string_copy("");
  342. if (str2->tag!=TAG_BYTES && str2->tag!=TAG_STR) return alloc_string_copy("");
  343. //printf("### str1: #%s#\n",str1->addr);
  344. //printf("### str2: #%s#\n",str2->addr);
  345. Cell* cell = cell_alloc();
  346. int size1 = strlen(str1->addr); // ,str2->size
  347. int size2 = strlen(str2->addr);
  348. int newsize = size1+size2+1;
  349. cell->addr = bytes_alloc(newsize+1);
  350. cell->size = newsize;
  351. cell->tag = TAG_STR;
  352. strncpy(cell->addr, str1->addr, size1);
  353. strncpy(cell->addr+size1, str2->addr, 1+cell->size-size1);
  354. ((char*)cell->addr)[newsize]=0;
  355. return cell;
  356. }
  357. Cell* alloc_builtin(unsigned int b, Cell* signature) {
  358. Cell* num = cell_alloc();
  359. num->tag = TAG_BUILTIN;
  360. num->value = b;
  361. num->next = signature;
  362. return num;
  363. }
  364. Cell* alloc_lambda(Cell* args) {
  365. Cell* l = cell_alloc();
  366. l->tag = TAG_LAMBDA;
  367. l->addr = args; // arguments
  368. //l->next = cdr(def); // body
  369. return l;
  370. }
  371. Cell* alloc_nil() {
  372. return alloc_cons(0,0);
  373. }
  374. int is_nil(Cell* c) {
  375. return (!c || (c->addr==0 && c->next==0));
  376. }
  377. Cell* alloc_error(unsigned int code) {
  378. Cell* c = cell_alloc();
  379. c->tag = TAG_ERROR;
  380. c->value = code;
  381. c->next = 0;
  382. return c;
  383. }
  384. Cell* alloc_clone(Cell* orig) {
  385. if (!orig) return 0;
  386. Cell* clone = cell_alloc();
  387. clone->tag = orig->tag;
  388. clone->addr = 0;
  389. clone->next = 0;
  390. clone->size = orig->size;
  391. //printf("cloning a %d (value %d)\n",orig->tag,orig->value);
  392. if (orig->tag == TAG_SYM || orig->tag == TAG_STR || orig->tag == TAG_BYTES) {
  393. clone->addr = bytes_alloc(orig->size+1);
  394. memcpy(clone->addr, orig->addr, orig->size);
  395. } else if (orig->tag == TAG_CONS) {
  396. if (orig->addr) {
  397. clone->addr = alloc_clone(orig->addr);
  398. }
  399. if (orig->next) {
  400. clone->next = alloc_clone(orig->next);
  401. }
  402. } else {
  403. clone->addr = orig->addr;
  404. clone->next = orig->next;
  405. }
  406. return clone;
  407. }