Skip to content

Commit

Permalink
GH-33 Add p4StackResize() to encapsulate stack growth and guards.
Browse files Browse the repository at this point in the history
  • Loading branch information
SirWumpus committed Sep 7, 2024
1 parent f3725c4 commit d724b65
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
34 changes: 27 additions & 7 deletions jni/Post4.c
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,32 @@ jBoxArray(P4_Ctx *ctx)
P4_PUSH(ctx->ds, (void *) arr);
}

static int
p4StackResize(P4_Stack *stk, unsigned newsize)
{
if (newsize <= stk->size) {
/* Nothing but growth potential. */
return 0;
}
size_t depth = P4_PLENGTH(stk);
P4_Cell *newbase = realloc(stk->base - P4_GUARD_CELLS/2, (newsize + P4_GUARD_CELLS) * sizeof (*stk->base));
if (newbase == NULL) {
return -1;
}
/* Set stack just above lower guards. */
stk->base = newbase + P4_GUARD_CELLS/2;
/* Clear new memory to make Valgrind happy. */
(void) memset(stk->base + depth, 0, (newsize - stk->size) * sizeof (*stk->base));
/* Set the guards. */
stk->base[newsize].u = P4_SENTINEL;
stk->base[-1].u = P4_SENTINEL;
stk->base[newsize+1].u = 0;
stk->base[-2].u = 0;
stk->size = newsize;
P4_PSET(stk, depth);
return 0;
}

/*
* jUnboxArray ( jarray -- x*i i )
*/
Expand All @@ -287,16 +313,10 @@ jUnboxArray(P4_Ctx *ctx)
/* Enough stack space to hold array items? */
if (ctx->ds.size <= ds_depth + size + 1) {
/* Grow data stack with some extra work space. */
size_t ds_size = ds_depth + size + P4_DATA_STACK_SIZE;
P4_Cell *ds_base = realloc(ctx->ds.base, ds_size);
if (ds_base == NULL) {
if (p4StackResize(&ctx->ds, ctx->ds.size + size + P4_STACK_EXTRA)) {
/* Frick'n'ell. */
LONGJMP(ctx->longjmp, P4_THROW_DS_OVER);
}
ctx->ds.base = ds_base;
ctx->ds.size = ds_size - 1;
ctx->ds.base[ds_size - 1].u = P4_SENTINEL;
P4_SET(ctx->ds, ds_depth);
}
/* Get each array item and push. */
for (jsize i = size - 1; 0 <= i; i--) {
Expand Down
4 changes: 4 additions & 0 deletions src/post4.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ extern "C" {
#define P4_FLOAT_STACK_SIZE 6 /* in CELLS */
#endif

#ifndef P4_STACK_EXTRA
#define P4_STACK_EXTRA 16 /* in CELLS */
#endif

#ifndef P4_STRING_SIZE
#define P4_STRING_SIZE 256 /* in bytes */
#endif
Expand Down

0 comments on commit d724b65

Please sign in to comment.