Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Route JS errors from UI runtime throught RN's LogBox module #3846

Merged
merged 24 commits into from
Dec 15, 2022

Conversation

kmagiera
Copy link
Member

@kmagiera kmagiera commented Dec 8, 2022

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

Common/cpp/ReanimatedRuntime/ReanimatedHermesRuntime.cpp Outdated Show resolved Hide resolved
plugin.js Outdated Show resolved Hide resolved
Common/cpp/Tools/RuntimeDecorator.cpp Show resolved Hide resolved
Common/cpp/Tools/RuntimeDecorator.cpp Outdated Show resolved Hide resolved
Common/cpp/SharedItems/Shareables.cpp Outdated Show resolved Hide resolved
plugin.js Outdated Show resolved Hide resolved
plugin.js Outdated Show resolved Hide resolved
src/reanimated2/initializers.ts Outdated Show resolved Hide resolved
src/reanimated2/initializers.ts Outdated Show resolved Hide resolved
src/reanimated2/initializers.ts Outdated Show resolved Hide resolved
kmagiera and others added 8 commits December 13, 2022 09:41
Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
…#3837)

## Summary

This PR fixes an iOS crash with Hermes on app reload that occurs only if some animation is still running:

<img width="1512" alt="crash" src="https://user-images.githubusercontent.com/20516055/205723759-1ed56999-64e7-4ce6-a4ae-baa686f2b2a4.png">

## Test plan

1. Build and launch Example app on iOS simulator
2. Open Animated Style Update Example
3. Increase duration to 5000 ms
4. Click "Toggle" button
5. Press <kbd>r</kbd> in simulator
6. Make sure the app reloads correctly
## Summary

This PR enables weak object implementation for shareables when using V8 runtime.

As @Kudo mentioned in #3722 (comment), react-native-v8 exposes weak objects API via JSI (see [here](https://github.com/Kudo/react-native-v8/blob/96a1a2c8a35349967a3ad7219106a3475b85433a/src/v8runtime/V8Runtime.cpp#L982-L997)).

## Test plan

Run Example app with react-native-v8 and check if everything works.
… registry (#3824)

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please follow the template so that the reviewers can easily understand what the code changes affect. -->

## Summary
Currently, when views with an `exiting` animation are unmounted, any deleted in that transaction aren't removed from the UIManager's view registry (the mapping of react tags to native views).
This can cause memory leaks of removed views.

This PR restores the original behaviour of UIManager when removing views, allowing it to clean them up properly, and reattaches the views with `exiting` animations after the transaction removing the views has completed.

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if applicable. -->

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to test out this change along with instructions how to run it and a description of the expected behavior. -->
- In example app, go to "Entering and Exiting with Layout"
- Set a breakpoint somewhere in `RCTUIManager`, for example `_manageChildren`.
- Press "Toggle" to create the animated views, and note the number of entries in `_viewRegistry`.
- Disable the breakpoint, resume the app and start spamming the toggle button.
- Enable the breakpoint again, and press toggle one more time.
- The number of entries in `_viewRegistry` should be the same as before spamming toggle.
After #3838 we can now access the main global object via `global`
variable. This eliminates a need for _setGlobalConsole JSI method that
we'd install in the UI runtime only so that we can set the console
object as global on the UI runtime. In this PR we change the call to
_setGlobalConsole with just reassigning global.console.

Add some logs in worklets, run the app, see the logs appear on the
output, also that console.warn displays in the log box.

Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
Common/cpp/SharedItems/Shareables.cpp Outdated Show resolved Hide resolved
plugin.js Outdated Show resolved Hide resolved
src/reanimated2/initializers.ts Outdated Show resolved Hide resolved
src/reanimated2/initializers.ts Show resolved Hide resolved
Common/cpp/SharedItems/Shareables.h Outdated Show resolved Hide resolved
Common/cpp/SharedItems/Shareables.h Outdated Show resolved Hide resolved
kmagiera and others added 2 commits December 14, 2022 12:05
Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
@tomekzaw
Copy link
Member

tomekzaw commented Dec 14, 2022

Tested fbb3110 on WorkletExample.tsx:

  • iOS / Paper / debug → works like charm, all errors thrown in worklets (except those from gesture handler callbacks) are presented in a relatively nice LogBox ✅
  • iOS / Paper / release → works as expected, all errors are silently ignored and the app runs later on (fun fact is that throwing an error on main RN JS runtime crashes the app) ✅
  • Android / Paper / debug → same as iOS / Paper / debug ✅
  • Android / Paper / release → each error in worklet crashes the app (@kmagiera says this is okay) ✅
  • iOS / Fabric / debug → same as iOS / Paper / debug, however some worklets are labeled as "_f" instead of "anonymous" in the stack trace ✅
  • iOS / Fabric / release → didn't check yet ⌛
  • Android / Fabric / debug → all errors thrown in worklets are presented in LogBox, except for errors in gesture handler callbacks which crash the app (this might be related to NDK version since FabricExample uses NDK 24 where exception handling is broken, use NDK 21 instead, see Fix Android crash when worklet throws error #3558 for details) ✅
  • Android / Fabric / release → didn't check yet ⌛

TODO later:

  1. Update docs on debugging worklets in Flipper → this PR removes sourcemaps from worklets (//# sourceMappingURL=) and thus the possibility to debug worklet runtime with Flipper. The reason was that sourcemaps contained the source code of the whole file which significantly increased bundle size as well as JS runtime memory usage. As discussed offline, we won't fix it in this PR - instead we will add the instructions in the docs on how to patch plugin.js to restore sourcemaps.
  2. Show errors from gesture-handler callbacks in LogBox as well → use callGuard in WorkletEventHandler, check if we still need to use callWithThis
  3. Adapt Reanimated SWC plugin to the changes from this PR (and also shareable_rewrite in general)

Copy link
Member

@tomekzaw tomekzaw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👏

@kmagiera kmagiera merged commit 4707481 into main Dec 15, 2022
@kmagiera kmagiera deleted the better_errors branch December 15, 2022 11:30
kmagiera added a commit that referenced this pull request Dec 15, 2022
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.

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.

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>
kmagiera added a commit that referenced this pull request Dec 15, 2022
## Summary

This PR fixes crashes related to concurrent writes to a non-thread-safe
frameCallbacks vector. The primary role of frameCallbacks vector was to
facilitate requestAnimationFrame calls and hence it has not been
designed to allow for other than the main thread to append their
callbacks. However, after recent rewrite #3722 we introduced a new
methods "scheduleOnUI" that was originally meant to interface with a
thread-safe scheduler API but was later updated (see
c8a77da) to use frameCallbacks in order
for errors to be handled using the same code-path the rAF uses. That
change introduces a bug in which we'd access and modify that vector from
different threads which is undesirable. This PR reverts that change and
since #3846 provides a better way of handling JS-errors there is no
longer need for scheduleOnUI callbacks to go throught the
requestAnimationFrame codepath.

## Test plan

The easiest way to reproduce the crash we could find was by using
BokehExample.tsx on Android. This would normally result in a crash after
a couple of seconds of running. With the increased number of circles in
that example (e.g. 400) the crash would be almost immediate. This change
was tested on that example with 400 circles and the crash would not
appear even after some time after launch (few minutes).

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>
fluiddot pushed a commit to wordpress-mobile/react-native-reanimated that referenced this pull request Jun 5, 2023
…-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>
fluiddot pushed a commit to wordpress-mobile/react-native-reanimated that referenced this pull request Jun 5, 2023
…-mansion#3859)

## Summary

This PR fixes crashes related to concurrent writes to a non-thread-safe
frameCallbacks vector. The primary role of frameCallbacks vector was to
facilitate requestAnimationFrame calls and hence it has not been
designed to allow for other than the main thread to append their
callbacks. However, after recent rewrite software-mansion#3722 we introduced a new
methods "scheduleOnUI" that was originally meant to interface with a
thread-safe scheduler API but was later updated (see
c8a77da) to use frameCallbacks in order
for errors to be handled using the same code-path the rAF uses. That
change introduces a bug in which we'd access and modify that vector from
different threads which is undesirable. This PR reverts that change and
since software-mansion#3846 provides a better way of handling JS-errors there is no
longer need for scheduleOnUI callbacks to go throught the
requestAnimationFrame codepath.

## Test plan

The easiest way to reproduce the crash we could find was by using
BokehExample.tsx on Android. This would normally result in a crash after
a couple of seconds of running. With the increased number of circles in
that example (e.g. 400) the crash would be almost immediate. This change
was tested on that example with 400 circles and the crash would not
appear even after some time after launch (few minutes).

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>
github-merge-queue bot pushed a commit that referenced this pull request Dec 22, 2023
…n` enabled (#5464)

## Summary

This option was added back when source maps were not included in
#3141.

Source map addition for better LogBox experience was added in
#3846 -
but it didn't take into account `relativeSourceLocation`. This PR fixes
this and there is no more absolute location in the source map while
`relativeSourceLocation` is on.

I haven't found a way to generate the source map with relative location
out-of-the-box.

## Test plan

In `WorkletExample` see that LogBox is working as intended. Also plugin
tests maybe.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants