2 * duk_hthread allocation and freeing.
5 #include "duk_internal.h"
8 * Allocate initial stacks for a thread. Note that 'thr' must be reachable
9 * as a garbage collection may be triggered by the allocation attempts.
10 * Returns zero (without leaking memory) if init fails.
13 DUK_INTERNAL duk_bool_t
duk_hthread_init_stacks(duk_heap
*heap
, duk_hthread
*thr
) {
14 duk_size_t alloc_size
;
17 DUK_ASSERT(heap
!= NULL
);
18 DUK_ASSERT(thr
!= NULL
);
19 DUK_ASSERT(thr
->valstack
== NULL
);
20 DUK_ASSERT(thr
->valstack_end
== NULL
);
21 DUK_ASSERT(thr
->valstack_bottom
== NULL
);
22 DUK_ASSERT(thr
->valstack_top
== NULL
);
23 DUK_ASSERT(thr
->callstack
== NULL
);
24 DUK_ASSERT(thr
->catchstack
== NULL
);
27 alloc_size
= sizeof(duk_tval
) * DUK_VALSTACK_INITIAL_SIZE
;
28 thr
->valstack
= (duk_tval
*) DUK_ALLOC(heap
, alloc_size
);
32 DUK_MEMZERO(thr
->valstack
, alloc_size
);
33 thr
->valstack_end
= thr
->valstack
+ DUK_VALSTACK_INITIAL_SIZE
;
34 thr
->valstack_bottom
= thr
->valstack
;
35 thr
->valstack_top
= thr
->valstack
;
37 for (i
= 0; i
< DUK_VALSTACK_INITIAL_SIZE
; i
++) {
38 DUK_TVAL_SET_UNDEFINED_UNUSED(&thr
->valstack
[i
]);
42 alloc_size
= sizeof(duk_activation
) * DUK_CALLSTACK_INITIAL_SIZE
;
43 thr
->callstack
= (duk_activation
*) DUK_ALLOC(heap
, alloc_size
);
44 if (!thr
->callstack
) {
47 DUK_MEMZERO(thr
->callstack
, alloc_size
);
48 thr
->callstack_size
= DUK_CALLSTACK_INITIAL_SIZE
;
49 DUK_ASSERT(thr
->callstack_top
== 0);
52 alloc_size
= sizeof(duk_catcher
) * DUK_CATCHSTACK_INITIAL_SIZE
;
53 thr
->catchstack
= (duk_catcher
*) DUK_ALLOC(heap
, alloc_size
);
54 if (!thr
->catchstack
) {
57 DUK_MEMZERO(thr
->catchstack
, alloc_size
);
58 thr
->catchstack_size
= DUK_CATCHSTACK_INITIAL_SIZE
;
59 DUK_ASSERT(thr
->catchstack_top
== 0);
64 DUK_FREE(heap
, thr
->valstack
);
65 DUK_FREE(heap
, thr
->callstack
);
66 DUK_FREE(heap
, thr
->catchstack
);
69 thr
->callstack
= NULL
;
70 thr
->catchstack
= NULL
;
74 /* For indirect allocs. */
76 DUK_INTERNAL
void *duk_hthread_get_valstack_ptr(duk_heap
*heap
, void *ud
) {
77 duk_hthread
*thr
= (duk_hthread
*) ud
;
79 return (void *) thr
->valstack
;
82 DUK_INTERNAL
void *duk_hthread_get_callstack_ptr(duk_heap
*heap
, void *ud
) {
83 duk_hthread
*thr
= (duk_hthread
*) ud
;
85 return (void *) thr
->callstack
;
88 DUK_INTERNAL
void *duk_hthread_get_catchstack_ptr(duk_heap
*heap
, void *ud
) {
89 duk_hthread
*thr
= (duk_hthread
*) ud
;
91 return (void *) thr
->catchstack
;