mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-06-27 14:58:30 +00:00
Expose public garbage collector API for C language
You can now do epic things like this: puts(_gc(xasprintf("%d", 123))); The _gc() API is shorthand for _defer() which works like Go's keyword: const char *s = xasprintf("%d", 123); _defer(free, s); puts(s); Be sure to always use -fno-omit-frame-pointer which makes code fast too. Enjoy! See also #114
This commit is contained in:
parent
0ad609268f
commit
33e8fc8687
26 changed files with 192 additions and 182 deletions
|
@ -31,23 +31,9 @@ forceinline bool PointerNotOwnedByParentStackFrame(struct StackFrame *frame,
|
|||
((intptr_t)ptr < (intptr_t)parent));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds destructor to garbage shadow stack.
|
||||
*
|
||||
* @param frame is passed automatically by wrapper macro
|
||||
* @param fn takes one argument
|
||||
* @param arg is passed to fn(arg)
|
||||
* @return arg
|
||||
*/
|
||||
void __defer(struct StackFrame *frame, void *fn, void *arg) {
|
||||
void __deferer(struct StackFrame *frame, void *fn, void *arg) {
|
||||
size_t n2;
|
||||
struct Garbage *p2;
|
||||
struct StackFrame *f2;
|
||||
if (!arg) return;
|
||||
f2 = __builtin_frame_address(0);
|
||||
assert(__garbage.n);
|
||||
assert(f2->next == frame);
|
||||
assert(PointerNotOwnedByParentStackFrame(f2, frame, arg));
|
||||
if (UNLIKELY(__garbage.i == __garbage.n)) {
|
||||
n2 = __garbage.n + (__garbage.n >> 1);
|
||||
p2 = malloc(n2 * sizeof(*__garbage.p));
|
||||
|
@ -63,3 +49,21 @@ void __defer(struct StackFrame *frame, void *fn, void *arg) {
|
|||
__garbage.i++;
|
||||
frame->addr = (intptr_t)__gc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds destructor to garbage shadow stack.
|
||||
*
|
||||
* @param frame is passed automatically by wrapper macro
|
||||
* @param fn takes one argument
|
||||
* @param arg is passed to fn(arg)
|
||||
* @return arg
|
||||
*/
|
||||
void __defer(struct StackFrame *frame, void *fn, void *arg) {
|
||||
struct StackFrame *f2;
|
||||
if (!arg) return;
|
||||
f2 = __builtin_frame_address(0);
|
||||
assert(__garbage.n);
|
||||
assert(f2->next == frame);
|
||||
assert(PointerNotOwnedByParentStackFrame(f2, frame, arg));
|
||||
__deferer(frame, fn, arg);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue