From 66cdfb015b75ad8f2a56b516e173b316a956fea6 Mon Sep 17 00:00:00 2001 From: Iampete1 Date: Wed, 20 Apr 2022 00:34:23 +0100 Subject: [PATCH] AP_Scripting: always free the heap and remove scripts --- libraries/AP_Scripting/lua_scripts.cpp | 19 +++++++++++++++++++ libraries/AP_Scripting/lua_scripts.h | 6 +++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/libraries/AP_Scripting/lua_scripts.cpp b/libraries/AP_Scripting/lua_scripts.cpp index a5313f27ee..09c398cb74 100644 --- a/libraries/AP_Scripting/lua_scripts.cpp +++ b/libraries/AP_Scripting/lua_scripts.cpp @@ -37,6 +37,10 @@ lua_scripts::lua_scripts(const AP_Int32 &vm_steps, const AP_Int32 &heap_size, co _heap = hal.util->allocate_heap_memory(heap_size); } +lua_scripts::~lua_scripts() { + free(_heap); +} + void lua_scripts::hook(lua_State *L, lua_Debug *ar) { lua_scripts::overtime = true; @@ -535,4 +539,19 @@ void lua_scripts::run(void) { } } } + + // make sure all scripts have been removed + while (scripts != nullptr) { + remove_script(lua_state, scripts); + } + + if (lua_state != nullptr) { + lua_close(lua_state); // shutdown the old state + lua_state = nullptr; + } + + if (error_msg_buf != nullptr) { + hal.util->heap_realloc(_heap, error_msg_buf, 0); + error_msg_buf = nullptr; + } } diff --git a/libraries/AP_Scripting/lua_scripts.h b/libraries/AP_Scripting/lua_scripts.h index 258fd20654..f8e39bd496 100644 --- a/libraries/AP_Scripting/lua_scripts.h +++ b/libraries/AP_Scripting/lua_scripts.h @@ -53,9 +53,9 @@ class lua_scripts public: lua_scripts(const AP_Int32 &vm_steps, const AP_Int32 &heap_size, const AP_Int8 &debug_options, struct AP_Scripting::terminal_s &_terminal); - /* Do not allow copies */ - lua_scripts(const lua_scripts &other) = delete; - lua_scripts &operator=(const lua_scripts&) = delete; + ~lua_scripts(); + + CLASS_NO_COPY(lua_scripts); // return true if initialisation failed bool heap_allocated() const { return _heap != nullptr; }