Debian Codegraph @

src/c/memory.d

raw
1 /* -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /* vim: set filetype=c tabstop=2 shiftwidth=2 expandtab: */
3
4 /*
5 * memory.c - manual memory managament
6 *
7 * Copyright (c) 2024 Daniel Kochmański
8 *
9 * See file 'LICENSE' for the copyright details.
10 *
11 */
12
13 /* -- imports --------------------------------------------------------------- */
14
15 #include <ecl/ecl.h>
16 #include <ecl/ecl-inl.h>
17 #include <ecl/internal.h>
18 #include <ecl/external.h>
19
20 #include <stdlib.h>
21 #include <string.h>
22
23 /* -- implementation -------------------------------------------------------- */
24
25 static void
26 out_of_memory()
27 {
28 /* FIXME we should signal the STORAGE-EXHAUSTED and allow a potential handler
29 an attempt to release some memory:
30
31 ecl_cerror(ecl_ct_oom_tag);
32 goto AGAIN;
33
34 For now let's crash with an appropriate error. */
35 ecl_internal_error("*** manual memory allocator: out of memory\n");
36 }
37
38 void *
39 ecl_malloc(cl_index n)
40 {
41 /* GC-free equivalent of ecl_alloc_atomic. */
42 const cl_env_ptr the_env = ecl_process_env_unsafe();
43 void *ptr;
44 if (!the_env) {
45 ptr = malloc(n);
46 } else {
47 ecl_disable_interrupts_env(the_env);
48 ptr = malloc(n);
49 ecl_enable_interrupts_env(the_env);
50 }
51 if (ptr == NULL) out_of_memory();
52 return ptr;
53 }
54
55 void
56 ecl_free(void *ptr)
57 {
58 const cl_env_ptr the_env = ecl_process_env_unsafe();
59 if (!the_env) {
60 free(ptr);
61 } else {
62 ecl_disable_interrupts_env(the_env);
63 free(ptr);
64 ecl_enable_interrupts_env(the_env);
65 }
66 }
67
68 void *
69 ecl_realloc(void *ptr, cl_index osize, cl_index nsize)
70 {
71 void *p = ecl_malloc(nsize);
72 ecl_copy(p, ptr, (osize < nsize) ? osize : nsize);
73 ecl_free(ptr);
74 return p;
75 }
76
77 void
78 ecl_copy(void *dst, void *src, cl_index ndx)
79 {
80 memcpy(dst, src, ndx);
81 }