@@ -113,12 +113,17 @@ class EvallingGlobalManager {
113113 }
114114};
115115
116- enum {
117- // put the stack in some ridiculously high location
118- STACK_START = 0x40000000 ,
119- // use a ridiculously large stack size
120- STACK_SIZE = 32 * 1024 * 1024
121- };
116+ // Use a ridiculously large stack size.
117+ static Index STACK_SIZE = 32 * 1024 * 1024 ;
118+
119+ // Start the stack at a ridiculously large location, and do so in
120+ // a way that works regardless if the stack goes up or down.
121+ static Index STACK_START = 1024 * 1024 * 1024 + STACK_SIZE;
122+
123+ // Bound the stack location in both directions, so we have bounds
124+ // that do not depend on the direction it grows.
125+ static Index STACK_LOWER_LIMIT = STACK_START - STACK_SIZE;
126+ static Index STACK_UPPER_LIMIT = STACK_START + STACK_SIZE;
122127
123128class EvallingModuleInstance : public ModuleInstanceBase <EvallingGlobalManager, EvallingModuleInstance> {
124129public:
@@ -151,7 +156,7 @@ class EvallingModuleInstance : public ModuleInstanceBase<EvallingGlobalManager,
151156 // but it should not be read afterwards, doing so would be undefined behavior
152157 void setupEnvironment () {
153158 // prepare scratch memory
154- stack.resize (STACK_SIZE);
159+ stack.resize (2 * STACK_SIZE);
155160 // tell the module to accept writes up to the stack end
156161 auto total = STACK_START + STACK_SIZE;
157162 memorySize = total / Memory::kPageSize ;
@@ -266,11 +271,11 @@ struct CtorEvalExternalInterface : EvallingModuleInstance::ExternalInterface {
266271 template <typename T>
267272 T* getMemory (Address address) {
268273 // if memory is on the stack, use the stack
269- if (address >= STACK_START) {
270- Address relative = address - STACK_START;
271- if (relative + sizeof (T) > STACK_SIZE) {
274+ if (address >= STACK_LOWER_LIMIT) {
275+ if (address >= STACK_UPPER_LIMIT) {
272276 throw FailToEvalException (" stack usage too high" );
273277 }
278+ Address relative = address - STACK_LOWER_LIMIT;
274279 // in range, all is good, use the stack
275280 return (T*)(&instance->stack [relative]);
276281 }
0 commit comments