Skip to content

Commit

Permalink
Route JS errors from UI runtime throught RN's LogBox module (software…
Browse files Browse the repository at this point in the history
…-mansion#3846)

This PR changes the way we report errors in development. Previously we'd
use RCTLog native module which would result in a relatively ugly red
screen displaying an error. In addition the stack trace wouldn't be
symbolicated so it was difficult to reason about the root cause of the
problem when the crash happened on the UI runtime.

With this change we provide a symbolicated version of trace to ErroUtil
module which results in the crash being displayed in the same way as it
were to occur on the regular RN runtime.

## Summary

The main motivation is to provide better guidance for developers about
the crashes on the UI JS runtime as well as to use a familiar UI for
displaying those.

In a nutshell, the method we use relies on an extended version of "eval"
for processing the javascript code when loading on the UI runtime. We
now expose `evalWithSourceUrl` that beside the code also allows for
assiging the source url that is then included in the traces, and
`evalWithSourceMap` (only on hermes) that allows to provide JSON encoded
source map that is then used by the javascript engine to symbolicate the
stack trace.

For JS engines that does not support source maps (JSC), what we do
instead, is that we provide the worklet hash as a part of the source
url, this allows us to recognize which worklet a given stack entry is
coming from and allows us to map the provided line from that worklet
into a line of the whole JS bundle. In order to do so, we now generate
an "error" object in the place where worklet is generated such that we
can get its position in the Javascript bundle.

Below is a summary of changes this PR makes:
1) Changes in plugin focus on removing location metadata (we now use a
string in a format "worklet_7263" where the number is worklet's hash),
adding source maps in a form of JSON encoded string, and adding new
error object to the worklet object which is used to remap worklet line
number into the bundle line number
2) For the latter, we added some additional logic that replaces entries
in the provided error and replaces "worklet_23746:16:2" with the bundle
URL along with the remapped line numbers
3) We now route all JS calls via a new method "guardCall" that adds a
catch statement and passes the exception back to the main JS runtime
where we use ErrorUtils module to trigger the default React Native's
LogBox
4) We extend hermes runtime by exposing `evalWithSourceMap` method
– this method is only added for debug builds and only on hermes.
5) On other runtimes we register additional global method
`evalWIthSourceURL` that makes it possible to provide URLs along the
code that needs to be evaluated.

## Test plan

Run method "something" from the following snippet and expect an error
that should result in a redbox being desplayed. Note that the presented
stack trace should have correct line numbers. See the expected result on
iOS under the snippet. On Android the errors aren't as nicely formatted
but should contain valid trace entries. This needs to be tested on both
JSC and Hermes configurations.


```
function makeWorklet() {
  return () => {
    'worklet';
    throw new Error('Randomly crashing');
  };
}

const crashRandomly = makeWorklet();

function anotherWorklet() {
  'worklet';
  crashRandomly();
}

function something() {
  runOnUI(() => {
    'worklet';
    anotherWorklet();
  })();
}
```

![simulator_screenshot_3CECE7D6-DA04-4661-93C3-C25EF4A19423](https://user-images.githubusercontent.com/726445/206585057-e3d74c5f-bd02-4e9b-a4ae-ea8cd6fbb709.png)

Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
Co-authored-by: Krzysztof Piaskowy <krzysztof.piaskowy@swmansion.com>
Co-authored-by: Juliusz Wajgelt <49338439+jwajgelt@users.noreply.github.com>
  • Loading branch information
4 people authored and fluiddot committed Jun 5, 2023
1 parent a40d12c commit 09ffd85
Show file tree
Hide file tree
Showing 19 changed files with 525 additions and 162 deletions.
21 changes: 13 additions & 8 deletions Common/cpp/NativeModules/NativeReanimatedModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,11 @@ NativeReanimatedModule::NativeReanimatedModule(
platformDepMethodsHolder.configurePropsFunction)
#endif
{
auto requestAnimationFrame = [=](FrameCallback callback) {
frameCallbacks.push_back(callback);
auto requestAnimationFrame = [=](jsi::Runtime &rt, const jsi::Value &fn) {
auto jsFunction = std::make_shared<jsi::Value>(rt, fn);
frameCallbacks.push_back([=](double timestamp) {
runtimeHelper->runOnUIGuarded(*jsFunction, jsi::Value(timestamp));
});
maybeRequestRender();
};

Expand Down Expand Up @@ -174,20 +177,23 @@ NativeReanimatedModule::NativeReanimatedModule(

void NativeReanimatedModule::installCoreFunctions(
jsi::Runtime &rt,
const jsi::Value &valueUnpacker,
const jsi::Value &layoutAnimationStartFunction) {
const jsi::Value &callGuard,
const jsi::Value &valueUnpacker) {
if (!runtimeHelper) {
// initialize runtimeHelper here if not already present. We expect only one
// instace of the helper to exists.
runtimeHelper =
std::make_shared<JSRuntimeHelper>(&rt, this->runtime.get(), scheduler);
}
runtimeHelper->callGuard =
std::make_unique<CoreFunction>(runtimeHelper.get(), callGuard);
runtimeHelper->valueUnpacker =
std::make_shared<CoreFunction>(runtimeHelper.get(), valueUnpacker);
std::make_unique<CoreFunction>(runtimeHelper.get(), valueUnpacker);
}

NativeReanimatedModule::~NativeReanimatedModule() {
if (runtimeHelper) {
runtimeHelper->callGuard = nullptr;
runtimeHelper->valueUnpacker = nullptr;
// event handler registry and frame callbacks store some JSI values from UI
// runtime, so they have to go away before we tear down the runtime
Expand All @@ -206,11 +212,10 @@ void NativeReanimatedModule::scheduleOnUI(
assert(
shareableWorklet->valueType() == Shareable::WorkletType &&
"only worklets can be scheduled to run on UI");
auto uiRuntime = runtimeHelper->uiRuntime();
frameCallbacks.push_back([=](double timestamp) {
jsi::Runtime &rt = *uiRuntime;
jsi::Runtime &rt = *runtimeHelper->uiRuntime();
auto workletValue = shareableWorklet->getJSValue(rt);
workletValue.asObject(rt).asFunction(rt).call(rt);
runtimeHelper->runOnUIGuarded(workletValue);
});
maybeRequestRender();
}
Expand Down
4 changes: 2 additions & 2 deletions Common/cpp/NativeModules/NativeReanimatedModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class NativeReanimatedModule : public NativeReanimatedModuleSpec,

void installCoreFunctions(
jsi::Runtime &rt,
const jsi::Value &workletMaker,
const jsi::Value &layoutAnimationStartFunction) override;
const jsi::Value &callGuard,
const jsi::Value &valueUnpacker) override;

jsi::Value makeShareableClone(jsi::Runtime &rt, const jsi::Value &value)
override;
Expand Down
4 changes: 2 additions & 2 deletions Common/cpp/NativeModules/NativeReanimatedModuleSpec.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class JSI_EXPORT NativeReanimatedModuleSpec : public TurboModule {
public:
virtual void installCoreFunctions(
jsi::Runtime &rt,
const jsi::Value &valueUnpacker,
const jsi::Value &layoutAnimationStartFunction) = 0;
const jsi::Value &callGuard,
const jsi::Value &valueUnpacker) = 0;

// SharedValue
virtual jsi::Value makeShareableClone(
Expand Down
30 changes: 30 additions & 0 deletions Common/cpp/ReanimatedRuntime/ReanimatedHermesRuntime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <jsi/jsi.h>

#include <memory>
#include <string>
#include <utility>

#if __has_include(<reacthermes/HermesExecutorFactory.h>)
Expand Down Expand Up @@ -79,6 +80,35 @@ ReanimatedHermesRuntime::ReanimatedHermesRuntime(
// that the thread was indeed `quit` before
jsQueue->quitSynchronous();
#endif

#ifdef DEBUG
facebook::hermes::HermesRuntime *wrappedRuntime = runtime_.get();
jsi::Value evalWithSourceMap = jsi::Function::createFromHostFunction(
*runtime_,
jsi::PropNameID::forAscii(*runtime_, "evalWithSourceMap"),
3,
[wrappedRuntime](
jsi::Runtime &rt,
const jsi::Value &thisValue,
const jsi::Value *args,
size_t count) -> jsi::Value {
auto code = std::make_shared<const jsi::StringBuffer>(
args[0].asString(rt).utf8(rt));
std::string sourceURL;
if (count > 1 && args[1].isString()) {
sourceURL = args[1].asString(rt).utf8(rt);
}
std::shared_ptr<const jsi::Buffer> sourceMap;
if (count > 2 && args[2].isString()) {
sourceMap = std::make_shared<const jsi::StringBuffer>(
args[2].asString(rt).utf8(rt));
}
return wrappedRuntime->evaluateJavaScriptWithSourceMap(
code, sourceMap, sourceURL);
});
runtime_->global().setProperty(
*runtime_, "evalWithSourceMap", evalWithSourceMap);
#endif // DEBUG
}

ReanimatedHermesRuntime::~ReanimatedHermesRuntime() {
Expand Down
2 changes: 1 addition & 1 deletion Common/cpp/ReanimatedRuntime/ReanimatedHermesRuntime.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class ReanimatedHermesRuntime
~ReanimatedHermesRuntime();

private:
std::shared_ptr<facebook::hermes::HermesRuntime> runtime_;
std::unique_ptr<facebook::hermes::HermesRuntime> runtime_;
ReanimatedReentrancyCheck reentrancyCheck_;
};

Expand Down
4 changes: 3 additions & 1 deletion Common/cpp/SharedItems/Shareables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ CoreFunction::CoreFunction(
rnFunction_ = std::make_unique<jsi::Function>(workletObject.asFunction(rt));
functionBody_ =
workletObject.getProperty(rt, "asString").asString(rt).utf8(rt);
location_ = workletObject.getProperty(rt, "__location").asString(rt).utf8(rt);
location_ = "worklet_" +
std::to_string(static_cast<unsigned long long>(
workletObject.getProperty(rt, "__workletHash").getNumber()));
}

std::unique_ptr<jsi::Function> &CoreFunction::getFunction(jsi::Runtime &rt) {
Expand Down
57 changes: 36 additions & 21 deletions Common/cpp/SharedItems/Shareables.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,29 @@ using namespace facebook;

namespace reanimated {

class CoreFunction;
class JSRuntimeHelper;

// Core functions are not allowed to capture outside variables, otherwise they'd
// try to access _closure variable which is something we want to avoid for
// simplicity reasons.
class CoreFunction {
private:
std::unique_ptr<jsi::Function> rnFunction_;
std::unique_ptr<jsi::Function> uiFunction_;
std::string functionBody_;
std::string location_;
JSRuntimeHelper
*runtimeHelper_; // runtime helper holds core function references, so we
// use normal pointer here to avoid ref cycles.
std::unique_ptr<jsi::Function> &getFunction(jsi::Runtime &rt);

public:
CoreFunction(JSRuntimeHelper *runtimeHelper, const jsi::Value &workletObject);
template <typename... Args>
jsi::Value call(jsi::Runtime &rt, Args &&...args) {
return getFunction(rt)->call(rt, args...);
}
};

class JSRuntimeHelper {
private:
Expand All @@ -36,7 +58,8 @@ class JSRuntimeHelper {
: rnRuntime_(rnRuntime), uiRuntime_(uiRuntime), scheduler_(scheduler) {}

volatile bool uiRuntimeDestroyed;
std::shared_ptr<CoreFunction> valueUnpacker;
std::unique_ptr<CoreFunction> callGuard;
std::unique_ptr<CoreFunction> valueUnpacker;

inline jsi::Runtime *uiRuntime() const {
return uiRuntime_;
Expand All @@ -61,27 +84,19 @@ class JSRuntimeHelper {
void scheduleOnJS(std::function<void()> job) {
scheduler_->scheduleOnJS(job);
}
};

// Core functions are not allowed to capture outside variables, otherwise they'd
// try to access _closure variable which is something we want to avoid for
// simplicity reasons.
class CoreFunction {
private:
std::unique_ptr<jsi::Function> rnFunction_;
std::unique_ptr<jsi::Function> uiFunction_;
std::string functionBody_;
std::string location_;
JSRuntimeHelper
*runtimeHelper_; // runtime helper holds core function references, so we
// use normal pointer here to avoid ref cycles.
std::unique_ptr<jsi::Function> &getFunction(jsi::Runtime &rt);

public:
CoreFunction(JSRuntimeHelper *runtimeHelper, const jsi::Value &workletObject);
template <typename... Args>
jsi::Value call(jsi::Runtime &rt, Args &&...args) {
return getFunction(rt)->call(rt, args...);
inline void runOnUIGuarded(const jsi::Value &function, Args &&...args) {
// We only use callGuard in debug mode, otherwise we call the provided
// function directly. CallGuard provides a way of capturing exceptions in
// JavaScript and propagating them to the main React Native thread such that
// they can be presented using RN's LogBox.
jsi::Runtime &rt = *uiRuntime_;
#ifdef DEBUG
callGuard->call(rt, function, args...);
#else
function.asObject(rt).asFunction(rt).call(rt, args...);
#endif
}
};

Expand Down
31 changes: 25 additions & 6 deletions Common/cpp/Tools/RuntimeDecorator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,30 @@ void RuntimeDecorator::decorateRuntime(

rt.global().setProperty(rt, "global", rt.global());

rt.global().setProperty(rt, "jsThis", jsi::Value::undefined());
#ifdef DEBUG
auto evalWithSourceUrl = [](jsi::Runtime &rt,
const jsi::Value &thisValue,
const jsi::Value *args,
size_t count) -> jsi::Value {
auto code = std::make_shared<const jsi::StringBuffer>(
args[0].asString(rt).utf8(rt));
std::string url;
if (count > 1 && args[1].isString()) {
url = args[1].asString(rt).utf8(rt);
}

return rt.evaluateJavaScript(code, url);
};

rt.global().setProperty(
rt,
"evalWithSourceUrl",
jsi::Function::createFromHostFunction(
rt,
jsi::PropNameID::forAscii(rt, "evalWithSourceUrl"),
1,
evalWithSourceUrl));
#endif // DEBUG

auto callback = [](jsi::Runtime &rt,
const jsi::Value &thisValue,
Expand Down Expand Up @@ -208,11 +231,7 @@ void RuntimeDecorator::decorateUIRuntime(
const jsi::Value &thisValue,
const jsi::Value *args,
const size_t count) -> jsi::Value {
auto fun =
std::make_shared<jsi::Function>(args[0].asObject(rt).asFunction(rt));
requestFrame([&rt, fun](double timestampMs) {
fun->call(rt, jsi::Value(timestampMs));
});
requestFrame(rt, std::move(args[0]));
return jsi::Value::undefined();
};
jsi::Value requestAnimationFrame = jsi::Function::createFromHostFunction(
Expand Down
3 changes: 2 additions & 1 deletion Common/cpp/Tools/RuntimeDecorator.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ using namespace facebook;

namespace reanimated {

using RequestFrameFunction = std::function<void(std::function<void(double)>)>;
using RequestFrameFunction =
std::function<void(jsi::Runtime &, const jsi::Value &)>;
using ScheduleOnJSFunction =
std::function<void(jsi::Runtime &, const jsi::Value &, const jsi::Value &)>;
using MakeShareableCloneFunction =
Expand Down
Loading

0 comments on commit 09ffd85

Please sign in to comment.