diff --git a/include/scratchcpp/executioncontext.h b/include/scratchcpp/executioncontext.h index 23f6ce73c..b3a71f57b 100644 --- a/include/scratchcpp/executioncontext.h +++ b/include/scratchcpp/executioncontext.h @@ -2,7 +2,10 @@ #pragma once -#include "global.h" +#include +#include + +#include "string_pool.h" #include "spimpl.h" namespace libscratchcpp @@ -13,6 +16,7 @@ class IEngine; class Promise; class IStackTimer; class IRandomGenerator; +struct StringPtr; class ExecutionContextPrivate; /*! \brief The ExecutionContext represents the execution context of a target (can be a clone) with variables, lists, etc. */ @@ -21,7 +25,7 @@ class LIBSCRATCHCPP_EXPORT ExecutionContext public: ExecutionContext(Thread *thread); ExecutionContext(const ExecutionContext &) = delete; - virtual ~ExecutionContext() { } + virtual ~ExecutionContext(); Thread *thread() const; IEngine *engine() const; @@ -35,8 +39,50 @@ class LIBSCRATCHCPP_EXPORT ExecutionContext IRandomGenerator *rng() const; void setRng(IRandomGenerator *newRng); + inline StringPtr **pushStringStack(size_t stringCount) + { + m_stringStackCleared = false; + m_stringStack.push({}); + + auto &strings = m_stringStack.top(); + + for (size_t i = 0; i < stringCount; i++) { + StringPtr *str = string_pool_new(); + strings.push_back(str); + } + + return strings.data(); + } + + inline void popStringStack() + { + if (m_stringStackCleared) // avoid UB when popping after killing a thread + return; + + assert(!m_stringStack.empty()); // check only in debug mode to maximize performance + + const auto &strings = m_stringStack.top(); + + for (StringPtr *str : strings) + string_pool_free(str); + + m_stringStack.pop(); + } + + inline void clearStringStack() + { + while (!m_stringStack.empty()) { + popStringStack(); + } + + m_stringStackCleared = true; + } + private: spimpl::unique_impl_ptr impl; + + std::stack> m_stringStack; + bool m_stringStackCleared = false; }; } // namespace libscratchcpp diff --git a/include/scratchcpp/thread.h b/include/scratchcpp/thread.h index 353d9aeed..7a61529f5 100644 --- a/include/scratchcpp/thread.h +++ b/include/scratchcpp/thread.h @@ -20,6 +20,7 @@ class LIBSCRATCHCPP_EXPORT Thread public: Thread(Target *target, IEngine *engine, Script *script); Thread(const Thread &) = delete; + ~Thread(); Target *target() const; IEngine *engine() const; diff --git a/src/engine/executioncontext.cpp b/src/engine/executioncontext.cpp index 06109d55d..c24ba0ccc 100644 --- a/src/engine/executioncontext.cpp +++ b/src/engine/executioncontext.cpp @@ -13,6 +13,13 @@ ExecutionContext::ExecutionContext(Thread *thread) : { } +/*! Destroys ExecutionContext. */ +ExecutionContext::~ExecutionContext() +{ + // Deallocate strings + clearStringStack(); +} + /*! Returns the thread of this context. */ Thread *ExecutionContext::thread() const { diff --git a/src/engine/internal/codegen/llvm/llvmbuildutils.cpp b/src/engine/internal/codegen/llvm/llvmbuildutils.cpp index 7eeb36683..e45cb64a8 100644 --- a/src/engine/internal/codegen/llvm/llvmbuildutils.cpp +++ b/src/engine/internal/codegen/llvm/llvmbuildutils.cpp @@ -79,14 +79,24 @@ void LLVMBuildUtils::init(llvm::Function *function, BlockPrototype *procedurePro reg->intValue = llvm::ConstantInt::get(m_builder.getInt64Ty(), reg->constValue().toDouble(), true); } + // Create string count variable (LLVM should optimize it into a constant later) + m_stringCountVar = m_builder.CreateAlloca(m_builder.getInt64Ty(), nullptr, "stringCount"); + + // Create string count block (string count is known after all instructions are processed) + m_stringCountBlock = llvm::BasicBlock::Create(m_llvmCtx, "getStringCount", m_function); + m_builder.CreateBr(m_stringCountBlock); + // NOTE: This block is terminated later + // Create string allocation block + m_builder.SetInsertPoint(m_stringCountBlock); m_stringAllocaBlock = llvm::BasicBlock::Create(m_llvmCtx, "stringAlloca", m_function); - m_builder.CreateBr(m_stringAllocaBlock); + // NOTE: This block is terminated later - // Get string array + // Push string stack (load string array) m_builder.SetInsertPoint(m_stringAllocaBlock); - m_stringArray = m_builder.CreateCall(m_functions.resolve_llvm_get_string_array(), { m_executionContextPtr, m_functionIdValue }); - // NOTE: This block is terminated later + + llvm::Value *stringCount = m_builder.CreateLoad(m_builder.getInt64Ty(), m_stringCountVar, "strCount"); + m_stringArray = m_builder.CreateCall(m_functions.resolve_llvm_push_string_stack(), { m_executionContextPtr, stringCount }); // Create next block m_stringAllocaNextBlock = llvm::BasicBlock::Create(m_llvmCtx, "entry.next", m_function); @@ -146,11 +156,13 @@ void LLVMBuildUtils::init(llvm::Function *function, BlockPrototype *procedurePro void LLVMBuildUtils::end(LLVMInstruction *lastInstruction, LLVMRegister *lastConstant) { - // Terminate string allocation block - if (m_stringCount == 0) - m_stringAllocaBlock->erase(m_stringAllocaBlock->begin(), m_stringAllocaBlock->end()); - + // Terminate string count and allocation blocks llvm::BasicBlock *previousBlock = m_builder.GetInsertBlock(); + m_builder.SetInsertPoint(m_stringCountBlock); + m_builder.CreateStore(m_builder.getInt64(m_stringCount), m_stringCountVar); + + m_builder.CreateBr(m_stringAllocaBlock); + m_builder.SetInsertPoint(m_stringAllocaBlock); m_builder.CreateBr(m_stringAllocaNextBlock); m_builder.SetInsertPoint(previousBlock); @@ -165,6 +177,7 @@ void LLVMBuildUtils::end(LLVMInstruction *lastInstruction, LLVMRegister *lastCon // End branch m_builder.SetInsertPoint(m_endBranch); + m_builder.CreateCall(m_functions.resolve_llvm_pop_string_stack(), { m_executionContextPtr }); llvm::PointerType *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(m_llvmCtx), 0); @@ -198,6 +211,7 @@ void LLVMBuildUtils::end(LLVMInstruction *lastInstruction, LLVMRegister *lastCon // Thread end branch (stop the entire thread, including procedure callers) m_builder.SetInsertPoint(m_endThreadBranch); + m_builder.CreateCall(m_functions.resolve_llvm_pop_string_stack(), { m_executionContextPtr }); switch (m_codeType) { case Compiler::CodeType::Script: @@ -497,7 +511,7 @@ llvm::Value *LLVMBuildUtils::addAlloca(llvm::Type *type) llvm::Value *LLVMBuildUtils::addStringAlloca() { - // All temporary strings are allocated before the script is called + // All temporary strings are allocated when the string stack is pushed llvm::BasicBlock *block = m_builder.GetInsertBlock(); m_builder.SetInsertPoint(m_stringAllocaBlock); @@ -1418,7 +1432,9 @@ void LLVMBuildUtils::createSuspend() } syncVariables(); + m_coroutine->createSuspend(); + reloadVariables(); reloadLists(); diff --git a/src/engine/internal/codegen/llvm/llvmbuildutils.h b/src/engine/internal/codegen/llvm/llvmbuildutils.h index 2dd8b2df9..febb86d83 100644 --- a/src/engine/internal/codegen/llvm/llvmbuildutils.h +++ b/src/engine/internal/codegen/llvm/llvmbuildutils.h @@ -194,8 +194,10 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMBuildUtils std::vector m_ifStatements; std::vector m_loops; + llvm::BasicBlock *m_stringCountBlock = nullptr; llvm::BasicBlock *m_stringAllocaBlock = nullptr; llvm::BasicBlock *m_stringAllocaNextBlock = nullptr; + llvm::Value *m_stringCountVar = nullptr; llvm::Value *m_stringArray = nullptr; size_t m_stringCount = 0; }; diff --git a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp index d2f6fd7f4..32d445ada 100644 --- a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp +++ b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp @@ -94,7 +94,7 @@ std::shared_ptr LLVMCodeBuilder::build() m_utils.end(m_instructions.empty() ? nullptr : m_instructions.last(), m_lastConstValue); verifyFunction(m_function); - return std::make_shared(m_ctx, m_utils.scriptFunctionId(), m_function->getName().str(), m_ctx->coroutineResumeFunction()->getName().str(), m_utils.stringCount(), m_codeType); + return std::make_shared(m_ctx, m_utils.scriptFunctionId(), m_function->getName().str(), m_ctx->coroutineResumeFunction()->getName().str(), m_codeType); } CompilerValue *LLVMCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) diff --git a/src/engine/internal/codegen/llvm/llvmexecutablecode.cpp b/src/engine/internal/codegen/llvm/llvmexecutablecode.cpp index ce645a007..d8a95c180 100644 --- a/src/engine/internal/codegen/llvm/llvmexecutablecode.cpp +++ b/src/engine/internal/codegen/llvm/llvmexecutablecode.cpp @@ -18,18 +18,11 @@ using namespace libscratchcpp; static const void *END_THREAD_SENTINEL = (void *)0x1; -LLVMExecutableCode::LLVMExecutableCode( - LLVMCompilerContext *ctx, - function_id_t functionId, - const std::string &mainFunctionName, - const std::string &resumeFunctionName, - size_t stringCount, - Compiler::CodeType codeType) : +LLVMExecutableCode::LLVMExecutableCode(LLVMCompilerContext *ctx, function_id_t functionId, const std::string &mainFunctionName, const std::string &resumeFunctionName, Compiler::CodeType codeType) : m_ctx(ctx), m_functionId(functionId), m_mainFunctionName(mainFunctionName), m_resumeFunctionName(resumeFunctionName), - m_stringCount(stringCount), m_codeType(codeType) { assert(m_ctx); @@ -153,11 +146,6 @@ function_id_t LLVMExecutableCode::functionId() const return m_functionId; } -size_t LLVMExecutableCode::stringCount() const -{ - return m_stringCount; -} - LLVMExecutionContext *LLVMExecutableCode::getContext(ExecutionContext *context) { assert(dynamic_cast(context)); diff --git a/src/engine/internal/codegen/llvm/llvmexecutablecode.h b/src/engine/internal/codegen/llvm/llvmexecutablecode.h index 62837597d..308180ae0 100644 --- a/src/engine/internal/codegen/llvm/llvmexecutablecode.h +++ b/src/engine/internal/codegen/llvm/llvmexecutablecode.h @@ -18,13 +18,7 @@ class LLVMExecutionContext; class LIBSCRATCHCPP_TEST_EXPORT LLVMExecutableCode : public ExecutableCode { public: - LLVMExecutableCode( - LLVMCompilerContext *ctx, - function_id_t functionId, - const std::string &mainFunctionName, - const std::string &resumeFunctionName, - size_t stringCount, - Compiler::CodeType codeType); + LLVMExecutableCode(LLVMCompilerContext *ctx, function_id_t functionId, const std::string &mainFunctionName, const std::string &resumeFunctionName, Compiler::CodeType codeType); void run(ExecutionContext *context) override; ValueData runReporter(ExecutionContext *context) override; @@ -37,7 +31,6 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMExecutableCode : public ExecutableCode std::shared_ptr createExecutionContext(Thread *thread) const override; function_id_t functionId() const; - size_t stringCount() const; private: using MainFunctionType = void *(*)(ExecutionContext *, Target *, ValueData **, List **); @@ -52,7 +45,6 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMExecutableCode : public ExecutableCode std::string m_mainFunctionName; std::string m_predicateFunctionName; std::string m_resumeFunctionName; - size_t m_stringCount = 0; Compiler::CodeType m_codeType; mutable std::variant m_mainFunction; diff --git a/src/engine/internal/codegen/llvm/llvmexecutioncontext.cpp b/src/engine/internal/codegen/llvm/llvmexecutioncontext.cpp index 40f35990f..7757c3e70 100644 --- a/src/engine/internal/codegen/llvm/llvmexecutioncontext.cpp +++ b/src/engine/internal/codegen/llvm/llvmexecutioncontext.cpp @@ -11,25 +11,6 @@ LLVMExecutionContext::LLVMExecutionContext(LLVMCompilerContext *compilerCtx, Thr ExecutionContext(thread), m_compilerCtx(compilerCtx) { - // Allocate strings for all scripts in the target - // TODO: Allocate strings for this script and procedures it calls - const auto &codeMap = compilerCtx->codeMap(); - - for (const auto &[functionId, code] : codeMap) { - size_t count = code->stringCount(); - - if (count > 0) { - m_stringVectors[functionId] = {}; - - auto &strings = m_stringVectors[functionId]; - strings.reserve(count); - - for (size_t i = 0; i < count; i++) - strings.push_back(string_pool_new()); - - m_stringArrays[functionId] = strings.data(); - } - } } LLVMExecutionContext::~LLVMExecutionContext() @@ -41,12 +22,6 @@ LLVMExecutionContext::~LLVMExecutionContext() } else assert(false); } - - // Deallocate strings - for (const auto &[functionId, strings] : m_stringVectors) { - for (StringPtr *str : strings) - string_pool_free(str); - } } void *LLVMExecutionContext::coroutineHandle() const diff --git a/src/engine/internal/codegen/llvm/llvmexecutioncontext.h b/src/engine/internal/codegen/llvm/llvmexecutioncontext.h index 4af3b8677..ac2f671da 100644 --- a/src/engine/internal/codegen/llvm/llvmexecutioncontext.h +++ b/src/engine/internal/codegen/llvm/llvmexecutioncontext.h @@ -24,19 +24,10 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMExecutionContext : public ExecutionContext bool finished() const; void setFinished(bool newFinished); - inline StringPtr **getStringArray(function_id_t functionId) - { - assert(m_stringArrays.find(functionId) != m_stringArrays.cend()); - return m_stringArrays[functionId]; - } - private: LLVMCompilerContext *m_compilerCtx = nullptr; void *m_coroutineHandle = nullptr; bool m_finished = false; - - std::unordered_map> m_stringVectors; - std::unordered_map m_stringArrays; }; } // namespace libscratchcpp diff --git a/src/engine/internal/codegen/llvm/llvmfunctions.cpp b/src/engine/internal/codegen/llvm/llvmfunctions.cpp index c0c6fd83f..98495db75 100644 --- a/src/engine/internal/codegen/llvm/llvmfunctions.cpp +++ b/src/engine/internal/codegen/llvm/llvmfunctions.cpp @@ -34,9 +34,14 @@ extern "C" return ctx->rng()->randint(from, to); } - LIBSCRATCHCPP_EXPORT StringPtr **llvm_get_string_array(ExecutionContext *ctx, function_id_t functionId) + LIBSCRATCHCPP_EXPORT StringPtr **llvm_push_string_stack(ExecutionContext *ctx, size_t stringCount) { - return static_cast(ctx)->getStringArray(functionId); + return ctx->pushStringStack(stringCount); + } + + LIBSCRATCHCPP_EXPORT void llvm_pop_string_stack(ExecutionContext *ctx) + { + return ctx->popStringStack(); } LIBSCRATCHCPP_EXPORT void llvm_mark_thread_as_finished(ExecutionContext *ctx) @@ -290,14 +295,22 @@ llvm::FunctionCallee LLVMFunctions::resolve_llvm_random_bool() return resolveFunction("llvm_random_bool", llvm::FunctionType::get(m_builder->getDoubleTy(), { pointerType, m_builder->getInt1Ty(), m_builder->getInt1Ty() }, false)); } -llvm::FunctionCallee LLVMFunctions::resolve_llvm_get_string_array() +llvm::FunctionCallee LLVMFunctions::resolve_llvm_push_string_stack() { llvm::Type *stringPtr = m_stringPtrType->getPointerTo(); llvm::Type *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(*m_ctx->llvmCtx()), 0); - llvm::FunctionCallee callee = resolveFunction("llvm_get_string_array", llvm::FunctionType::get(stringPtr->getPointerTo(), { pointerType, m_functionIdType }, false)); + llvm::FunctionCallee callee = resolveFunction("llvm_push_string_stack", llvm::FunctionType::get(stringPtr->getPointerTo(), { pointerType, m_builder->getInt64Ty() }, false)); + llvm::Function *func = llvm::cast(callee.getCallee()); + return callee; +} + +llvm::FunctionCallee LLVMFunctions::resolve_llvm_pop_string_stack() +{ + llvm::Type *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(*m_ctx->llvmCtx()), 0); + + llvm::FunctionCallee callee = resolveFunction("llvm_pop_string_stack", llvm::FunctionType::get(m_builder->getVoidTy(), { pointerType }, false)); llvm::Function *func = llvm::cast(callee.getCallee()); - func->addFnAttr(llvm::Attribute::ReadOnly); return callee; } diff --git a/src/engine/internal/codegen/llvm/llvmfunctions.h b/src/engine/internal/codegen/llvm/llvmfunctions.h index 7ead2168c..212e827b1 100644 --- a/src/engine/internal/codegen/llvm/llvmfunctions.h +++ b/src/engine/internal/codegen/llvm/llvmfunctions.h @@ -47,7 +47,8 @@ class LLVMFunctions llvm::FunctionCallee resolve_llvm_random_double(); llvm::FunctionCallee resolve_llvm_random_int64(); llvm::FunctionCallee resolve_llvm_random_bool(); - llvm::FunctionCallee resolve_llvm_get_string_array(); + llvm::FunctionCallee resolve_llvm_push_string_stack(); + llvm::FunctionCallee resolve_llvm_pop_string_stack(); llvm::FunctionCallee resolve_llvm_mark_thread_as_finished(); llvm::FunctionCallee resolve_llvm_is_thread_finished(); llvm::FunctionCallee resolve_llvm_print(); diff --git a/src/engine/thread.cpp b/src/engine/thread.cpp index 3ab120c54..4e554e703 100644 --- a/src/engine/thread.cpp +++ b/src/engine/thread.cpp @@ -25,6 +25,13 @@ Thread::Thread(Target *target, IEngine *engine, Script *script) : } } +/*! Destroys Thread. */ +Thread::~Thread() +{ + if (impl->executionContext) + impl->executionContext->clearStringStack(); +} + /*! Returns the Target of the script. */ Target *Thread::target() const { @@ -70,12 +77,14 @@ bool Thread::runPredicate() void Thread::kill() { impl->code->kill(impl->executionContext.get()); + impl->executionContext->clearStringStack(); } /*! Resets the script to run from the start. */ void Thread::reset() { impl->code->reset(impl->executionContext.get()); + impl->executionContext->clearStringStack(); } /*! Returns true if the script is stopped or finished. */ diff --git a/test/codegen/llvm/llvmexecutablecode_test.cpp b/test/codegen/llvm/llvmexecutablecode_test.cpp index 6f14485b8..b35bf16e0 100644 --- a/test/codegen/llvm/llvmexecutablecode_test.cpp +++ b/test/codegen/llvm/llvmexecutablecode_test.cpp @@ -119,29 +119,16 @@ class LLVMExecutableCodeTest : public testing::Test TEST_F(LLVMExecutableCodeTest, FunctionId) { { - auto code = std::make_shared(m_ctx.get(), 8, "script", "resume", 0, Compiler::CodeType::Script); + auto code = std::make_shared(m_ctx.get(), 8, "script", "resume", Compiler::CodeType::Script); ASSERT_EQ(code->functionId(), 8); } { - auto code = std::make_shared(m_ctx.get(), 3, "script", "resume", 0, Compiler::CodeType::Script); + auto code = std::make_shared(m_ctx.get(), 3, "script", "resume", Compiler::CodeType::Script); ASSERT_EQ(code->functionId(), 3); } } -TEST_F(LLVMExecutableCodeTest, StringCount) -{ - { - auto code = std::make_shared(m_ctx.get(), 0, "script", "resume", 2, Compiler::CodeType::Script); - ASSERT_EQ(code->stringCount(), 2); - } - - { - auto code = std::make_shared(m_ctx.get(), 1, "script", "resume", 56, Compiler::CodeType::Script); - ASSERT_EQ(code->stringCount(), 56); - } -} - TEST_F(LLVMExecutableCodeTest, CreateExecutionContext) { llvm::Function *mainFunc = beginMainFunction(); @@ -151,7 +138,7 @@ TEST_F(LLVMExecutableCodeTest, CreateExecutionContext) endFunction(m_builder->getInt1(true)); { - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::Script); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::Script); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -170,7 +157,7 @@ TEST_F(LLVMExecutableCodeTest, CreatePredicateExecutionContext) endFunction(m_builder->getInt1(true)); { - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::HatPredicate); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::HatPredicate); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -189,7 +176,7 @@ TEST_F(LLVMExecutableCodeTest, CreateReporterExecutionContext) endFunction(m_builder->getInt1(true)); { - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::Reporter); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::Reporter); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -211,7 +198,7 @@ TEST_F(LLVMExecutableCodeTest, MainFunction) llvm::Function *resumeFunc = beginResumeFunction(); endFunction(m_builder->getInt1(true)); - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::Script); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::Script); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -266,7 +253,7 @@ TEST_F(LLVMExecutableCodeTest, PredicateFunction) llvm::Function *resumeFunc = beginResumeFunction(); endFunction(m_builder->getInt1(true)); - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::HatPredicate); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::HatPredicate); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -295,7 +282,7 @@ TEST_F(LLVMExecutableCodeTest, ReporterFunction) llvm::Function *resumeFunc = beginResumeFunction(); endFunction(m_builder->getInt1(true)); - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::Reporter); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::Reporter); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); @@ -314,7 +301,7 @@ TEST_F(LLVMExecutableCodeTest, Promise) llvm::Function *resumeFunc = beginResumeFunction(); endFunction(m_builder->getInt1(true)); - auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), 0, Compiler::CodeType::Script); + auto code = std::make_shared(m_ctx.get(), 0, mainFunc->getName().str(), resumeFunc->getName().str(), Compiler::CodeType::Script); m_script->setCode(code); Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = code->createExecutionContext(&thread); diff --git a/test/engine/engine_test.cpp b/test/engine/engine_test.cpp index ebeab4a7d..fdc03fb48 100644 --- a/test/engine/engine_test.cpp +++ b/test/engine/engine_test.cpp @@ -2382,3 +2382,37 @@ TEST(EngineTest, ScriptsAreStoppedFromProcedureStoppingAll_Nested) ASSERT_VAR(stage, "passed"); ASSERT_TRUE(GET_VAR(stage, "passed")->value().toBool()); } + +TEST(EngineTest, NoStringStackRaceConditionInRecursiveProcedures) +{ + // Regtest for #704 + Project p("regtest_projects/704_string_stack_race_condition.sb3"); + ASSERT_TRUE(p.load()); + + auto engine = p.engine(); + + Stage *stage = engine->stage(); + ASSERT_TRUE(stage); + + engine->run(); + + ASSERT_VAR(stage, "passed"); + ASSERT_TRUE(GET_VAR(stage, "passed")->value().toBool()); +} + +TEST(EngineTest, NoStaleStringStackInNonWarpProceduresWithArguments) +{ + // Regtest for #704 + Project p("regtest_projects/704_string_stack_with_procedure_arguments.sb3"); + ASSERT_TRUE(p.load()); + + auto engine = p.engine(); + + Stage *stage = engine->stage(); + ASSERT_TRUE(stage); + + engine->run(); + + ASSERT_VAR(stage, "passed"); + ASSERT_TRUE(GET_VAR(stage, "passed")->value().toBool()); +} diff --git a/test/executioncontext/executioncontext_test.cpp b/test/executioncontext/executioncontext_test.cpp index f38191087..22635d235 100644 --- a/test/executioncontext/executioncontext_test.cpp +++ b/test/executioncontext/executioncontext_test.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include @@ -51,3 +53,28 @@ TEST(ExecutionContextTest, Rng) ctx.setRng(&rng); ASSERT_EQ(ctx.rng(), &rng); } + +TEST(ExecutionContextTest, StringStack) +{ + EngineMock engine; + ExecutionContext ctx(nullptr); + + StringPtr **frame1 = ctx.pushStringStack(3); + + for (int i = 0; i < 3; i++) { + string_assign_cstring(frame1[i], "test"); // address sanitizer will detect potential buffer overflow + } + + StringPtr **frame2 = ctx.pushStringStack(5); + + for (int i = 0; i < 5; i++) { + string_assign_cstring(frame2[i], "foo bar"); + } + + ctx.popStringStack(); + + StringPtr testString("test"); + ASSERT_EQ(string_compare_case_sensitive(frame1[2], &testString), 0); + + ctx.popStringStack(); +} diff --git a/test/regtest_projects/704_string_stack_race_condition.sb3 b/test/regtest_projects/704_string_stack_race_condition.sb3 new file mode 100644 index 000000000..377c7ca34 Binary files /dev/null and b/test/regtest_projects/704_string_stack_race_condition.sb3 differ diff --git a/test/regtest_projects/704_string_stack_with_procedure_arguments.sb3 b/test/regtest_projects/704_string_stack_with_procedure_arguments.sb3 new file mode 100644 index 000000000..eb1ef0221 Binary files /dev/null and b/test/regtest_projects/704_string_stack_with_procedure_arguments.sb3 differ