/* -- -- CANCEL.C -- -- Lane cancellation support -- -- Author: Benoit Germain -- --[[ =============================================================================== Copyright (C) 2011-2019 Benoit Germain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== ]]-- */ #include #include #include "threading.h" #include "cancel.h" #include "tools.h" #include "lanes_private.h" // ################################################################################################ // ################################################################################################ /* * Check if the thread in question ('L') has been signalled for cancel. * * Called by cancellation hooks and/or pending Linda operations (because then * the check won't affect performance). * * Returns CANCEL_SOFT/HARD if any locks are to be exited, and 'raise_cancel_error()' called, * to make execution of the lane end. */ static inline CancelRequest cancel_test(lua_State* L) { Lane* const lane{ LANE_POINTER_REGKEY.readLightUserDataValue(L) }; // 'lane' is nullptr for the original main state (and no-one can cancel that) return lane ? lane->cancel_request : CancelRequest::None; } // ################################################################################################ //--- // bool = cancel_test() // // Available inside the global namespace of lanes // returns a boolean saying if a cancel request is pending // LUAG_FUNC( cancel_test) { CancelRequest test{ cancel_test(L) }; lua_pushboolean(L, test != CancelRequest::None); return 1; } // ################################################################################################ // ################################################################################################ static void cancel_hook(lua_State* L, [[maybe_unused]] lua_Debug* ar) { DEBUGSPEW_CODE(fprintf(stderr, "cancel_hook\n")); if (cancel_test(L) != CancelRequest::None) { lua_sethook(L, nullptr, 0, 0); raise_cancel_error(L); } } // ################################################################################################ // ################################################################################################ //--- // = thread_cancel( lane_ud [,timeout_secs=0.0] [,force_kill_bool=false] ) // // The originator thread asking us specifically to cancel the other thread. // // 'timeout': <0: wait forever, until the lane is finished // 0.0: just signal it to cancel, no time waited // >0: time to wait for the lane to detect cancellation // // 'force_kill': if true, and lane does not detect cancellation within timeout, // it is forcefully killed. Using this with 0.0 timeout means just kill // (unless the lane is already finished). // // Returns: true if the lane was already finished (DONE/ERROR_ST/CANCELLED) or if we // managed to cancel it. // false if the cancellation timed out, or a kill was needed. // // ################################################################################################ static CancelResult thread_cancel_soft(Lane* lane_, double secs_, bool wake_lindas_) { lane_->cancel_request = CancelRequest::Soft; // it's now signaled to stop // negative timeout: we don't want to truly abort the lane, we just want it to react to cancel_test() on its own if (wake_lindas_) // wake the thread so that execution returns from any pending linda operation if desired { SIGNAL_T* const waiting_on{ lane_->waiting_on }; if (lane_->status == WAITING && waiting_on != nullptr) { SIGNAL_ALL( waiting_on); } } return THREAD_WAIT(&lane_->thread, secs_, &lane_->done_signal, &lane_->done_lock, &lane_->status) ? CancelResult::Cancelled : CancelResult::Timeout; } // ################################################################################################ static CancelResult thread_cancel_hard(lua_State* L, Lane* lane_, double secs_, bool force_, double waitkill_timeout_) { lane_->cancel_request = CancelRequest::Hard; // it's now signaled to stop { SIGNAL_T* waiting_on = lane_->waiting_on; if (lane_->status == WAITING && waiting_on != nullptr) { SIGNAL_ALL( waiting_on); } } CancelResult result{ THREAD_WAIT(&lane_->thread, secs_, &lane_->done_signal, &lane_->done_lock, &lane_->status) ? CancelResult::Cancelled : CancelResult::Timeout }; if ((result == CancelResult::Timeout) && force_) { // Killing is asynchronous; we _will_ wait for it to be done at // GC, to make sure the data structure can be released (alternative // would be use of "cancellation cleanup handlers" that at least // PThread seems to have). // THREAD_KILL(&lane_->thread); #if THREADAPI == THREADAPI_PTHREAD // pthread: make sure the thread is really stopped! // note that this may block forever if the lane doesn't call a cancellation point and pthread doesn't honor PTHREAD_CANCEL_ASYNCHRONOUS result = THREAD_WAIT(&lane_->thread, waitkill_timeout_, &lane_->done_signal, &lane_->done_lock, &lane_->status) ? CancelResult::Killed : CancelResult::Timeout; if (result == CancelResult::Timeout) { std::ignore = luaL_error( L, "force-killed lane failed to terminate within %f second%s", waitkill_timeout_, waitkill_timeout_ > 1 ? "s" : ""); } #else (void) waitkill_timeout_; // unused (void) L; // unused #endif // THREADAPI == THREADAPI_PTHREAD lane_->mstatus = Lane::Killed; // mark 'gc' to wait for it // note that lane_->status value must remain to whatever it was at the time of the kill // because we need to know if we can lua_close() the Lua State or not. result = CancelResult::Killed; } return result; } // ################################################################################################ CancelResult thread_cancel(lua_State* L, Lane* lane_, CancelOp op_, double secs_, bool force_, double waitkill_timeout_) { // remember that lanes are not transferable: only one thread can cancel a lane, so no multithreading issue here // We can read 'lane_->status' without locks, but not wait for it (if Posix no PTHREAD_TIMEDJOIN) if (lane_->mstatus == Lane::Killed) { return CancelResult::Killed; } if (lane_->status >= DONE) { // say "ok" by default, including when lane is already done return CancelResult::Cancelled; } // signal the linda the wake up the thread so that it can react to the cancel query // let us hope we never land here with a pointer on a linda that has been destroyed... if (op_ == CancelOp::Soft) { return thread_cancel_soft(lane_, secs_, force_); } return thread_cancel_hard(L, lane_, secs_, force_, waitkill_timeout_); } // ################################################################################################ // ################################################################################################ // > 0: the mask // = 0: soft // < 0: hard static CancelOp which_op(lua_State* L, int idx_) { if (lua_type(L, idx_) == LUA_TSTRING) { CancelOp op{ CancelOp::Invalid }; char const* str = lua_tostring(L, idx_); if (strcmp(str, "hard") == 0) { op = CancelOp::Hard; } else if (strcmp(str, "soft") == 0) { op = CancelOp::Soft; } else if (strcmp(str, "call") == 0) { op = CancelOp::MaskCall; } else if (strcmp(str, "ret") == 0) { op = CancelOp::MaskRet; } else if (strcmp(str, "line") == 0) { op = CancelOp::MaskLine; } else if (strcmp(str, "count") == 0) { op = CancelOp::MaskCount; } lua_remove(L, idx_); // argument is processed, remove it if (op == CancelOp::Invalid) { std::ignore = luaL_error(L, "invalid hook option %s", str); } return op; } return CancelOp::Hard; } // ################################################################################################ // bool[,reason] = lane_h:cancel( [mode, hookcount] [, timeout] [, force [, forcekill_timeout]]) LUAG_FUNC(thread_cancel) { Lane* const lane{ lua_toLane(L, 1) }; CancelOp const op{ which_op(L, 2) }; // this removes the op string from the stack if (static_cast(op) > static_cast(CancelOp::Soft)) // hook is requested { int const hook_count{ static_cast(lua_tointeger(L, 2)) }; lua_remove(L, 2); // argument is processed, remove it if (hook_count < 1) { return luaL_error(L, "hook count cannot be < 1"); } lua_sethook(lane->L, cancel_hook, static_cast(op), hook_count); } double secs{ 0.0 }; if (lua_type(L, 2) == LUA_TNUMBER) { secs = lua_tonumber(L, 2); lua_remove(L, 2); // argument is processed, remove it if (secs < 0.0) { return luaL_error(L, "cancel timeout cannot be < 0"); } } bool const force{ lua_toboolean(L, 2) ? true : false }; // false if nothing there double const forcekill_timeout{ luaL_optnumber(L, 3, 0.0) }; switch (thread_cancel(L, lane, op, secs, force, forcekill_timeout)) { case CancelResult::Timeout: lua_pushboolean(L, 0); lua_pushstring(L, "timeout"); return 2; case CancelResult::Cancelled: lua_pushboolean(L, 1); push_thread_status(L, lane); return 2; case CancelResult::Killed: lua_pushboolean(L, 1); push_thread_status(L, lane); return 2; } // should never happen, only here to prevent the compiler from complaining of "not all control paths returning a value" return 0; }