Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/jsc/VM.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ impl VM {
JSC__VM__setControlFlowProfiler(self, enabled)
}

/// Whether a `node:vm` evaluation with the `timeout` option is currently
/// running on this VM.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn has_execution_time_limit(&self) -> bool {
JSC__VM__hasExecutionTimeLimit(self)
}
Expand Down Expand Up @@ -114,7 +116,7 @@ impl VM {
JSC__VM__executionForbidden(self)
}

// These four functions fire VM traps. To understand what that means, see VMTraps.h for a giant explainer.
// These functions fire VM traps. To understand what that means, see VMTraps.h for a giant explainer.
// These may be called concurrently from another thread.

/// Fires NeedTermination Trap. Thread safe. See jsc's "VMTraps.h" for explaination on traps.
Expand Down
9 changes: 9 additions & 0 deletions src/jsc/bindings/BunClientData.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ namespace Zig {
class GlobalObject;
}

namespace Bun {
class NodeVMEvalTimeout;
}

namespace WebCore {
using namespace JSC;
using namespace Zig;
Expand Down Expand Up @@ -127,6 +131,11 @@ class JSVMClientData : public JSC::VM::ClientData {
void* bunVM;
Bun::JSCTaskScheduler deferredWorkTimer;

// Innermost armed `node:vm` evaluation deadline on this VM, forming an
// intrusive stack through NodeVMEvalTimeout::m_enclosing (evaluations
// nest strictly). Read by JSC__VM__hasExecutionTimeLimit.
Comment thread
robobun marked this conversation as resolved.
Resolved
Bun::NodeVMEvalTimeout* nodeVMEvalTimeouts { nullptr };

// Backing storage for Bun::IsolatedModuleCache (see IsolatedModuleCache.h).
// All access should go through that class. Stored as the JSC base type to
// avoid pulling ZigSourceProvider.h into this header; the cache class
Expand Down
41 changes: 41 additions & 0 deletions src/jsc/bindings/NodeVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
#include "NodeVMScriptFetcher.h"
#include "wtf/FileHandle.h"

#include "../vm/NodeVMEvalTimeout.h"
#include "../vm/SigintWatcher.h"

#include "JavaScriptCore/GetterSetter.h"
Expand Down Expand Up @@ -640,6 +641,46 @@ void decorateParseErrorStack(JSGlobalObject* globalObject, VM& vm, JSObject* err
writeArrowHeaderStack(vm, errorInstance, url, reportedLine, sourceLineText, caretColumn, stack);
}

bool checkForTermination(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSGlobalObject* evaluationGlobalObject, JSC::ThrowScope& scope, SigintReceiver* receiver, NodeVMEvalTimeout* deadline)
{
bool timedOut = deadline && deadline->expired();
bool sigintReceived = receiver->getSigintReceived();

if (vm.hasTerminationRequest()) {
// The termination was requested by something other than this
// evaluation's deadline or SIGINT watcher (e.g. Worker.terminate()).
// Leave it in place so it keeps propagating.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (!sigintReceived && !timedOut)
return false;
// Discard microtasks the terminated evaluation already scheduled;
// clearForGlobalObject(nullptr) is a no-op.
Comment thread
robobun marked this conversation as resolved.
Resolved
vm.drainMicrotasksForGlobalObject(evaluationGlobalObject);
// The termination may have fired inside an afterEvaluate microtask
// checkpoint, leaving the termination exception pending; clear it so
// the ERR_SCRIPT_EXECUTION_* error below replaces it.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (vm.hasPendingTerminationException())
DECLARE_TOP_EXCEPTION_SCOPE(vm).clearException();
vm.clearHasTerminationRequest();
} else if (!timedOut) {
return false;
}
// Reaching here with no termination request means the deadline expired
// after the evaluation's last trap check; Node reports a timeout anyway.
Comment thread
robobun marked this conversation as resolved.
Resolved

if (sigintReceived) {
receiver->setSigintReceived(false);
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED, "Script execution was interrupted by `SIGINT`"_s);
} else {
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_TIMEOUT, makeString("Script execution timed out after "_s, deadline->milliseconds(), "ms"_s));
}
// Now that this evaluation's own error has been thrown, hand the shared
// termination signal back to any enclosing deadline that already expired.
// This is not gated on `deadline`: a breakOnSigint evaluation with no (or
// an unexpired) deadline consumes the same coalesced signal.
Comment thread
robobun marked this conversation as resolved.
Resolved
NodeVMEvalTimeout::raiseExpiredDeadline(vm);
return true;
}

// Returns an encoded exception if the options are invalid.
// Otherwise, returns an empty optional.
std::optional<JSC::EncodedJSValue> getNodeVMContextOptions(JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSValue optionsArg, NodeVMContextOptions& outOptions, ASCIILiteral codeGenerationKey, JSValue* importer)
Expand Down
14 changes: 14 additions & 0 deletions src/jsc/bindings/NodeVM.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ namespace Bun {
class NodeVMGlobalObject;
class NodeVMContextOptions;
class CompileFunctionOptions;
class NodeVMEvalTimeout;
class SigintReceiver;

namespace NodeVM {

Expand All @@ -42,6 +44,18 @@ JSPromise* importModule(JSGlobalObject* globalObject, JSString* moduleNameValue,
bool isContext(JSC::JSGlobalObject* globalObject, JSValue);
bool getContextArg(JSC::JSGlobalObject* globalObject, JSValue& contextArg);
bool isUseMainContextDefaultLoaderConstant(JSC::JSGlobalObject* globalObject, JSValue value);
// Post-evaluation check shared by every `node:vm` evaluation entry point.
// Converts a termination raised by this evaluation's own `timeout` deadline or
// SIGINT watcher into the matching ERR_SCRIPT_EXECUTION_* error (created in
// `globalObject`'s realm) and returns true. A termination requested by
// anything else (e.g. Worker.terminate()) is left in place so it keeps
// propagating, and false is returned.
// `evaluationGlobalObject` is the vm context global whose still-queued
// microtasks are discarded on termination. Pass null when the evaluation ran
// in the caller's own global (runInThisContext, or a module without its own
// context) so the caller's unrelated microtasks are not dropped.
// `deadline` must already be disarmed.
Comment thread
robobun marked this conversation as resolved.
Resolved
bool checkForTermination(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSGlobalObject* evaluationGlobalObject, JSC::ThrowScope& scope, SigintReceiver* receiver, NodeVMEvalTimeout* deadline);

} // namespace NodeVM

Expand Down
65 changes: 22 additions & 43 deletions src/jsc/bindings/NodeVMModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
#include "JavaScriptCore/Exception.h"
#include "JavaScriptCore/JSModuleRecord.h"
#include "JavaScriptCore/JSPromise.h"
#include "JavaScriptCore/Watchdog.h"

#include "../vm/NodeVMEvalTimeout.h"
#include "../vm/SigintWatcher.h"

namespace Bun {
Expand Down Expand Up @@ -50,8 +50,6 @@ JSArray* NodeVMModuleRequest::toJS(JSGlobalObject* globalObject) const
return array;
}

void setupWatchdog(VM& vm, double timeout, double* oldTimeout, double* newTimeout);

void NodeVMModule::reconcileEvaluationState(JSC::VM& vm)
{
if (m_status != Status::Evaluating)
Expand Down Expand Up @@ -93,29 +91,21 @@ JSValue NodeVMModule::evaluate(JSGlobalObject* globalObject, uint32_t timeout, b
NodeVMGlobalObject* nodeVmGlobalObject = NodeVM::getGlobalObjectFromContext(globalObject, m_context.get(), false);
RETURN_IF_EXCEPTION(scope, {});
if (nodeVmGlobalObject && nodeVmGlobalObject->hasOwnMicrotaskQueue()) {
std::optional<double> oldLimit;
std::optional<NodeVMEvalTimeout> deadline;
if (timeout != 0)
setupWatchdog(vm, timeout, &oldLimit.emplace(), nullptr);
deadline.emplace(vm, timeout);
nodeVmGlobalObject->drainOwnMicrotasks();
if (timeout != 0)
vm.watchdog()->setTimeLimit(WTF::Seconds::fromMilliseconds(*oldLimit));
if (deadline)
deadline->disarm();
// The drain may legitimately leave the termination exception
// pending (watchdog fired mid-checkpoint); observe it so the
// pending (the deadline fired mid-checkpoint); observe it so the
// exception-check validator is satisfied before the TOP scope
// below, then convert it to ERR_SCRIPT_EXECUTION_*.
// inside checkForTermination, which converts it to
// ERR_SCRIPT_EXECUTION_*.
Comment thread
robobun marked this conversation as resolved.
Resolved
std::ignore = scope.exception();
if (vm.hasTerminationRequest() || vm.hasPendingTerminationException()) {
vm.drainMicrotasksForGlobalObject(nodeVmGlobalObject);
DECLARE_TOP_EXCEPTION_SCOPE(vm).clearException();
vm.clearHasTerminationRequest();
if (getSigintReceived()) {
setSigintReceived(false);
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED, "Script execution was interrupted by `SIGINT`"_s);
} else {
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_TIMEOUT, makeString("Script execution timed out after "_s, timeout, "ms"_s));
}
if (NodeVM::checkForTermination(vm, globalObject, nodeVmGlobalObject, scope, this, deadline ? &*deadline : nullptr))
return {};
}
RETURN_IF_EXCEPTION(scope, {});
}
return m_evaluationResult.get();
}
Expand Down Expand Up @@ -188,7 +178,7 @@ JSValue NodeVMModule::evaluate(JSGlobalObject* globalObject, uint32_t timeout, b
// (awaiting it from the outer context would enqueue the thenable job on
// the inner queue, which is not drained automatically). Wrap the result
// in an outer-context promise and checkpoint the inner queue — still
// inside the watchdog scope so `timeout` bounds the microtask drain too.
// inside the deadline scope so `timeout` bounds the microtask drain too.
auto drainAfterEvaluate = [&] {
if (scope.exception() || vm.hasTerminationRequest())
return;
Expand Down Expand Up @@ -220,10 +210,9 @@ JSValue NodeVMModule::evaluate(JSGlobalObject* globalObject, uint32_t timeout, b

setSigintReceived(false);

std::optional<double> oldLimit, newLimit;

std::optional<NodeVMEvalTimeout> deadline;
if (timeout != 0) {
setupWatchdog(vm, timeout, &oldLimit.emplace(), &newLimit.emplace());
deadline.emplace(vm, timeout);
}

if (breakOnSigint) {
Expand All @@ -235,28 +224,18 @@ JSValue NodeVMModule::evaluate(JSGlobalObject* globalObject, uint32_t timeout, b
drainAfterEvaluate();
}

if (timeout != 0) {
vm.watchdog()->setTimeLimit(WTF::Seconds::fromMilliseconds(*oldLimit));
if (deadline) {
deadline->disarm();
}

// Evaluation (or the afterEvaluate drain) may leave an exception pending
// — a regular one is rethrown by VM_RETURN_IF_EXCEPTION below, a
// termination one is converted to ERR_SCRIPT_EXECUTION_* here. Observe it
// so the exception-check validator is satisfied before the TOP scope.
// Evaluation (or the afterEvaluate drain) may leave an exception pending.
// A regular one is rethrown by VM_RETURN_IF_EXCEPTION below; a
// termination raised by this evaluation's own deadline or SIGINT watcher
// is converted to ERR_SCRIPT_EXECUTION_* here, and any other termination
// keeps propagating. Observe it so the exception-check validator is
// satisfied before the TOP scope.
Comment thread
robobun marked this conversation as resolved.
Resolved
std::ignore = scope.exception();
if (vm.hasTerminationRequest() || vm.hasPendingTerminationException()) {
vm.drainMicrotasksForGlobalObject(nodeVmGlobalObject);
DECLARE_TOP_EXCEPTION_SCOPE(vm).clearException();
vm.clearHasTerminationRequest();
if (getSigintReceived()) {
setSigintReceived(false);
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED, "Script execution was interrupted by `SIGINT`"_s);
} else if (timeout != 0) {
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_TIMEOUT, makeString("Script execution timed out after "_s, timeout, "ms"_s));
} else {
RELEASE_ASSERT_NOT_REACHED_WITH_MESSAGE("vm.SourceTextModule evaluation terminated due neither to SIGINT nor to timeout");
}
} else {
if (!NodeVM::checkForTermination(vm, globalObject, nodeVmGlobalObject, scope, this, deadline ? &*deadline : nullptr)) {
setSigintReceived(false);
}

Expand Down
75 changes: 15 additions & 60 deletions src/jsc/bindings/NodeVMScript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "JavaScriptCore/SourceCodeKey.h"

#include "NodeVMScriptFetcher.h"
#include "../vm/NodeVMEvalTimeout.h"
#include "../vm/SigintWatcher.h"

#include <bit>
Expand Down Expand Up @@ -306,53 +307,6 @@ void NodeVMScript::destroy(JSCell* cell)
static_cast<NodeVMScript*>(cell)->NodeVMScript::~NodeVMScript();
}

static bool checkForTermination(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::ThrowScope& scope, NodeVMScript* script, std::optional<double> timeout)
{
if (vm.hasTerminationRequest()) {
vm.drainMicrotasksForGlobalObject(globalObject);
// The termination may have fired inside an afterEvaluate microtask
// checkpoint, leaving the termination exception pending; clear it so
// the ERR_SCRIPT_EXECUTION_* error below replaces it.
if (vm.hasPendingTerminationException())
DECLARE_TOP_EXCEPTION_SCOPE(vm).clearException();
vm.clearHasTerminationRequest();
if (script->getSigintReceived()) {
script->setSigintReceived(false);
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED, "Script execution was interrupted by `SIGINT`"_s);
} else if (timeout) {
throwError(globalObject, scope, ErrorCode::ERR_SCRIPT_EXECUTION_TIMEOUT, makeString("Script execution timed out after "_s, *timeout, "ms"_s));
} else {
RELEASE_ASSERT_NOT_REACHED_WITH_MESSAGE("vm.Script terminated due neither to SIGINT nor to timeout");
}
return true;
}

return false;
}

void setupWatchdog(VM& vm, double timeout, double* oldTimeout, double* newTimeout)
{
JSC::JSLockHolder locker(vm);
JSC::Watchdog& dog = vm.ensureWatchdog();
dog.enteredVM();

Seconds oldLimit = dog.getTimeLimit();

if (oldTimeout) {
*oldTimeout = oldLimit.milliseconds();
}

if (oldLimit.isInfinity() || timeout < oldLimit.milliseconds()) {
dog.setTimeLimit(WTF::Seconds::fromMilliseconds(timeout));
} else {
timeout = oldLimit.milliseconds();
}

if (newTimeout) {
*newTimeout = timeout;
}
}

static JSC::EncodedJSValue runInContext(NodeVMGlobalObject* globalObject, NodeVMScript* script, JSObject* contextifiedObject, JSValue optionsArg, bool allowStringInPlaceOfOptions = false)
{
VM& vm = JSC::getVM(globalObject);
Expand All @@ -379,16 +333,15 @@ static JSC::EncodedJSValue runInContext(NodeVMGlobalObject* globalObject, NodeVM
result = JSC::evaluate(globalObject, script->source(), globalObject, exception);
};

std::optional<double> oldLimit, newLimit;

std::optional<NodeVMEvalTimeout> deadline;
if (options.timeout) {
setupWatchdog(vm, *options.timeout, &oldLimit.emplace(), &newLimit.emplace());
deadline.emplace(vm, *options.timeout);
}

script->setSigintReceived(false);

// Node performs the afterEvaluate microtask checkpoint inside the
// watchdog/SIGINT scope, so a `timeout` also bounds microtasks the script
// deadline/SIGINT scope, so a `timeout` also bounds microtasks the script
// scheduled on the context's own queue (e.g. promise jobs).
auto drainAfterEvaluate = [&] {
if (!exception && !vm.hasTerminationRequest() && globalObject->hasOwnMicrotaskQueue())
Expand All @@ -404,11 +357,11 @@ static JSC::EncodedJSValue runInContext(NodeVMGlobalObject* globalObject, NodeVM
drainAfterEvaluate();
}

if (options.timeout) {
vm.watchdog()->setTimeLimit(WTF::Seconds::fromMilliseconds(*oldLimit));
if (deadline) {
deadline->disarm();
}

if (checkForTermination(vm, globalObject, scope, script, newLimit)) {
if (checkForTermination(vm, globalObject, globalObject, scope, script, deadline ? &*deadline : nullptr)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return {};
}

Expand Down Expand Up @@ -455,10 +408,9 @@ JSC_DEFINE_HOST_FUNCTION(scriptRunInThisContext, (JSGlobalObject * globalObject,
result = JSC::evaluate(globalObject, script->source(), globalObject, exception);
};

std::optional<double> oldLimit, newLimit;

std::optional<NodeVMEvalTimeout> deadline;
if (options.timeout) {
setupWatchdog(vm, *options.timeout, &oldLimit.emplace(), &newLimit.emplace());
deadline.emplace(vm, *options.timeout);
}

script->setSigintReceived(false);
Expand All @@ -471,11 +423,14 @@ JSC_DEFINE_HOST_FUNCTION(scriptRunInThisContext, (JSGlobalObject * globalObject,
run();
}

if (options.timeout) {
vm.watchdog()->setTimeLimit(WTF::Seconds::fromMilliseconds(*oldLimit));
if (deadline) {
Comment thread
robobun marked this conversation as resolved.
Resolved
deadline->disarm();
}

if (checkForTermination(vm, globalObject, scope, script, newLimit)) {
// runInThisContext evaluates in the caller's own global: there is no
// separate context whose microtasks could be discarded without also
// dropping the caller's, so pass null for evaluationGlobalObject.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (checkForTermination(vm, globalObject, nullptr, scope, script, deadline ? &*deadline : nullptr)) {
return {};
}

Expand Down
1 change: 0 additions & 1 deletion src/jsc/bindings/NodeVMSyntheticModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
#include "JavaScriptCore/ModuleProgramCodeBlock.h"
#include "JavaScriptCore/Parser.h"
#include "JavaScriptCore/SourceCodeKey.h"
#include "JavaScriptCore/Watchdog.h"

#include "../vm/SigintWatcher.h"

Expand Down
Loading
Loading