added SAFE_STACK flag

This commit is contained in:
CPunch 2021-01-01 20:02:36 -06:00
parent 509823e1bc
commit be7a291ff2
2 changed files with 11 additions and 0 deletions

View File

@ -90,10 +90,12 @@ void closeUpvalues(CState *state, CValue *local) {
} }
void pushCallFrame(CState *state, CObjClosure *closure, int args) { void pushCallFrame(CState *state, CObjClosure *closure, int args) {
#ifdef SAFE_STACK
if (state->frameCount >= FRAME_MAX) { if (state->frameCount >= FRAME_MAX) {
cosmoV_error(state, "Callframe overflow!"); cosmoV_error(state, "Callframe overflow!");
return; return;
} }
#endif
CCallFrame *frame = &state->callFrame[state->frameCount++]; CCallFrame *frame = &state->callFrame[state->frameCount++];
frame->base = state->top - args - 1; // - 1 for the function frame->base = state->top - args - 1; // - 1 for the function

View File

@ -6,6 +6,13 @@
#include "cosmo.h" #include "cosmo.h"
#include "cstate.h" #include "cstate.h"
/*
SAFE_STACK:
if undefined, the stack will not be checked for stack overflows. This may improve performance, however
this will produce undefined behavior as you reach the stack limit (and may cause a seg fault!). It is recommended to keep this enabled.
*/
#define SAFE_STACK
typedef enum { typedef enum {
COSMOVM_OK, COSMOVM_OK,
COSMOVM_RUNTIME_ERR, COSMOVM_RUNTIME_ERR,
@ -25,6 +32,7 @@ COSMO_API void cosmoV_error(CState *state, const char *format, ...);
// pushes value to the stack // pushes value to the stack
static inline void cosmoV_pushValue(CState *state, CValue val) { static inline void cosmoV_pushValue(CState *state, CValue val) {
#ifdef SAFE_STACK
ptrdiff_t stackSize = state->top - state->stack; ptrdiff_t stackSize = state->top - state->stack;
// we reserve 8 slots for the error string and whatever c api we might be in // we reserve 8 slots for the error string and whatever c api we might be in
@ -39,6 +47,7 @@ static inline void cosmoV_pushValue(CState *state, CValue val) {
cosmoV_error(state, "Stack overflow!"); cosmoV_error(state, "Stack overflow!");
return; return;
} }
#endif
*(state->top++) = val; *(state->top++) = val;
} }