Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions packages/react-native/ReactCommon/jsi/jsi/jsi.h
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,32 @@ class JSI_EXPORT ISerialization : public ICast {

#endif // JSI_UNSTABLE

/// Tells whether a Value was created by this runtime.
///
/// - Values without a pointer (undefined, null, booleans and numbers) are
/// always reported as own.
/// - False positives: a value of a runtime that was already destroyed can be
/// reported as own when this runtime reuses the memory of that runtime.
/// - False negatives: a value created by this runtime is reported as not own
/// when it was created through a wrapper of this runtime that replaces the
/// runtime's PointerValues with its own.
/// - In all other cases the answer is exact while the runtime that created the
/// value is alive.
class JSI_EXPORT IValueOwnership : public ICast {
public:
static constexpr jsi::UUID uuid{
0xf92f55b7,
0x3d5c,
0x441e,
0x8b2d,
0x7e88f267cd40};

virtual bool isOwnValue(const Value& value) = 0;

protected:
~IValueOwnership() = default;
};

/// An interface that provides various functionalities of the JS runtime.
/// The APIs must not be called from multiple threads concurrently. It is the
/// user's responsibility ensure thread safety when using IRuntime.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ inline uint64_t getNextId() noexcept {
return nextId++;
}

jsi::JSError recreateJSErrorInRuntime(
jsi::Runtime& runtime,
const jsi::JSError& error) {
auto errorObject =
jsi::JSError(runtime, error.getMessage()).value().getObject(runtime);
errorObject.setProperty(runtime, "stack", error.getStack());
return {
jsi::Value(std::move(errorObject)), error.getMessage(), error.getStack()};
}

bool isOwnValue(jsi::Runtime& runtime, const jsi::Value& value) {
auto* ownership = jsi::castInterface<jsi::IValueOwnership>(&runtime);
return ownership != nullptr && ownership->isOwnValue(value);
}

} // namespace

Task::Task(
Expand Down Expand Up @@ -57,7 +72,14 @@ jsi::Value Task::execute(jsi::Runtime& runtime, bool didUserCallbackTimeout) {
.call(runtime, {didUserCallbackTimeout});
} else {
// Calling a raw callback
std::get<RawCallback>(originalCallback)(runtime);
try {
std::get<RawCallback>(originalCallback)(runtime);
} catch (const jsi::JSError& error) {
if (isOwnValue(runtime, error.value())) {
throw;
}
throw recreateJSErrorInRuntime(runtime, error);
}
}

return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <gtest/gtest.h>
#include <hermes/hermes.h>
#include <jsi/decorator.h>
#include <jsi/hermes-interfaces.h>
#include <jsi/jsi.h>
#include <react/featureflags/ReactNativeFeatureFlags.h>
Expand Down Expand Up @@ -47,6 +48,31 @@ class RuntimeSchedulerTestFeatureFlags
bool enableEventLoop_;
};

enum class ValueOwnership { Own, Foreign, Unavailable };

class ValueOwnershipRuntime : public jsi::RuntimeDecorator<jsi::Runtime>,
public jsi::IValueOwnership {
public:
ValueOwnershipRuntime(jsi::Runtime& runtime, ValueOwnership ownership)
: RuntimeDecorator(runtime), ownership_(ownership) {}

jsi::ICast* castInterface(const jsi::UUID& interfaceUUID) override {
if (interfaceUUID == jsi::IValueOwnership::uuid) {
return ownership_ == ValueOwnership::Unavailable
? nullptr
: static_cast<jsi::IValueOwnership*>(this);
}
return RuntimeDecorator::castInterface(interfaceUUID);
}

bool isOwnValue(const jsi::Value& /*value*/) override {
return ownership_ == ValueOwnership::Own;
}

private:
ValueOwnership ownership_;
};

class RuntimeSchedulerTest : public testing::TestWithParam<bool> {
protected:
void SetUp() override {
Expand All @@ -67,7 +93,11 @@ class RuntimeSchedulerTest : public testing::TestWithParam<bool> {
[this](
std::function<void(facebook::jsi::Runtime & runtime)>&& callback) {
stubQueue_->runOnQueue([this, callback = std::move(callback)]() {
callback(*runtime_);
if (valueOwnershipRuntime_) {
callback(*valueOwnershipRuntime_);
} else {
callback(*runtime_);
}
});
};

Expand Down Expand Up @@ -113,6 +143,26 @@ class RuntimeSchedulerTest : public testing::TestWithParam<bool> {
});
}

void scheduleTaskThrowingOwnError() {
evaluate(R"(
var thrown = new TypeError('Own error');
thrown.custom = 42;
function throwOwn() { throw thrown; }
)");
runtimeScheduler_->scheduleTask(
SchedulerPriority::NormalPriority, [](jsi::Runtime& runtime) {
runtime.global()
.getPropertyAsFunction(runtime, "throwOwn")
.call(runtime);
});
}

bool evaluate(const char* code) {
auto result = runtime_->evaluateJavaScript(
std::make_shared<jsi::StringBuffer>(code), "test.js");
return result.isBool() && result.getBool();
}

void enqueueMicrotask(std::function<void(jsi::Runtime&)> callback) {
auto microtask = jsi::Function::createFromHostFunction(
*runtime_,
Expand All @@ -130,6 +180,7 @@ class RuntimeSchedulerTest : public testing::TestWithParam<bool> {
uint hostFunctionCallCount_{};

std::unique_ptr<facebook::hermes::HermesRuntime> runtime_;
std::unique_ptr<ValueOwnershipRuntime> valueOwnershipRuntime_;
std::unique_ptr<StubClock> stubClock_;
std::unique_ptr<StubQueue> stubQueue_;
std::unique_ptr<RuntimeScheduler> runtimeScheduler_;
Expand Down Expand Up @@ -924,6 +975,118 @@ TEST_P(RuntimeSchedulerTest, handlingError) {
EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
}

TEST_P(RuntimeSchedulerTest, handlingErrorOfAnotherRuntimeInRawCallback) {
auto anotherRuntime = facebook::hermes::makeHermesRuntime();
bool didRunTask = false;

runtimeScheduler_->scheduleTask(
SchedulerPriority::NormalPriority, [&](jsi::Runtime& /*unused*/) {
didRunTask = true;
anotherRuntime->evaluateJavaScript(
std::make_shared<jsi::StringBuffer>(
"throw new Error('Error of another runtime');"),
"anotherRuntime.js");
});

stubQueue_->tick();

EXPECT_TRUE(didRunTask);
EXPECT_EQ(stubQueue_->size(), 0);
EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(
stubErrorUtils_->getLastReportedErrorMessage(),
"Error of another runtime");
}

TEST_P(RuntimeSchedulerTest, handlingOwnErrorInRawCallbackKeepsTheError) {
valueOwnershipRuntime_ =
std::make_unique<ValueOwnershipRuntime>(*runtime_, ValueOwnership::Own);
scheduleTaskThrowingOwnError();

stubQueue_->tick();

EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error");
EXPECT_TRUE(evaluate(
"lastReportedError === thrown && "
"lastReportedError.name === 'TypeError' && "
"lastReportedError.custom === 42"));
}

TEST_P(
RuntimeSchedulerTest,
handlingErrorReportedAsForeignInRawCallbackRebuildsTheError) {
valueOwnershipRuntime_ = std::make_unique<ValueOwnershipRuntime>(
*runtime_, ValueOwnership::Foreign);
scheduleTaskThrowingOwnError();

stubQueue_->tick();

EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error");
EXPECT_TRUE(evaluate(
"lastReportedError !== thrown && "
"lastReportedError.name === 'Error' && "
"lastReportedError.custom === undefined"));
}

TEST_P(
RuntimeSchedulerTest,
handlingErrorOfAnotherRuntimeReportedAsForeignInRawCallback) {
valueOwnershipRuntime_ = std::make_unique<ValueOwnershipRuntime>(
*runtime_, ValueOwnership::Foreign);
auto anotherRuntime = facebook::hermes::makeHermesRuntime();

runtimeScheduler_->scheduleTask(
SchedulerPriority::NormalPriority, [&](jsi::Runtime& /*unused*/) {
anotherRuntime->evaluateJavaScript(
std::make_shared<jsi::StringBuffer>(
"throw new Error('Error of another runtime');"),
"anotherRuntime.js");
});

stubQueue_->tick();

EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(
stubErrorUtils_->getLastReportedErrorMessage(),
"Error of another runtime");
}

TEST_P(
RuntimeSchedulerTest,
handlingOwnErrorInRawCallbackWithoutValueOwnershipRebuildsTheError) {
valueOwnershipRuntime_ = std::make_unique<ValueOwnershipRuntime>(
*runtime_, ValueOwnership::Unavailable);
scheduleTaskThrowingOwnError();

stubQueue_->tick();

EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error");
EXPECT_TRUE(evaluate(
"lastReportedError !== thrown && "
"lastReportedError.name === 'Error' && "
"lastReportedError.custom === undefined"));
}

TEST_P(RuntimeSchedulerTest, handlingErrorInRawCallback) {
bool didRunTask = false;

runtimeScheduler_->scheduleTask(
SchedulerPriority::NormalPriority, [&](jsi::Runtime& runtime) {
didRunTask = true;
throw jsi::JSError(runtime, "Test error");
});

stubQueue_->tick();

EXPECT_TRUE(didRunTask);
EXPECT_EQ(stubQueue_->size(), 0);
EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Test error");
}

TEST_P(RuntimeSchedulerTest, clearsQueuesOnError) {
// Only for event loop
if (!GetParam()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
#include <glog/logging.h>
#include <jsi/jsi.h>

#include <string>

namespace facebook::react {

/*
Expand Down Expand Up @@ -48,6 +50,8 @@ class StubErrorUtils : public jsi::HostObject {
[this](
jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t) noexcept -> jsi::Value {
reportFatalCallCount_++;
lastReportedErrorMessage_ = getErrorMessage(runtime, arguments[0]);
runtime.global().setProperty(runtime, "lastReportedError", arguments[0]);
return jsi::Value::undefined();
});
}
Expand All @@ -60,8 +64,24 @@ class StubErrorUtils : public jsi::HostObject {
return reportFatalCallCount_;
}

const std::string &getLastReportedErrorMessage() const
{
return lastReportedErrorMessage_;
}

private:
static std::string getErrorMessage(jsi::Runtime &runtime, const jsi::Value &error)
{
if (!error.isObject() ||
!error.getObject(runtime).instanceOf(runtime, runtime.global().getPropertyAsFunction(runtime, "Error"))) {
return "";
}
auto message = error.getObject(runtime).getProperty(runtime, "message");
return message.isString() ? message.getString(runtime).utf8(runtime) : "";
}

int reportFatalCallCount_;
std::string lastReportedErrorMessage_;
};

} // namespace facebook::react
Loading
Loading