diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b90d639c8..5a16838d27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Fix a crash in the Hermes sampler thread (`invalid pthread_t passed to pthread_kill`) on Android when a profile runs during a reload on the New Architecture ([#7157](https://github.com/getsentry/sentry-react-native/pull/7157)) - Keep Hermes `InternalBytecode.js` frames out of app on sentry.io, so they no longer drive issue grouping ([#7138](https://github.com/getsentry/sentry-react-native/pull/7138)) - The frames are now sent as `app:///node_modules/hermes/InternalBytecode.js`. Issues whose grouping included these frames may regroup. diff --git a/packages/core/RNSentryAndroidTester/app/src/test/java/io/sentry/react/RNSentryBeforeDestroyListenerTest.kt b/packages/core/RNSentryAndroidTester/app/src/test/java/io/sentry/react/RNSentryBeforeDestroyListenerTest.kt new file mode 100644 index 0000000000..6307c7a1cb --- /dev/null +++ b/packages/core/RNSentryAndroidTester/app/src/test/java/io/sentry/react/RNSentryBeforeDestroyListenerTest.kt @@ -0,0 +1,131 @@ +package io.sentry.react + +import android.app.Application +import android.content.Context +import android.content.ContextWrapper +import io.sentry.NoOpLogger +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.util.concurrent.CopyOnWriteArrayList + +@RunWith(RobolectricTestRunner::class) +class RNSentryBeforeDestroyListenerTest { + class FakeReactHost { + val listeners = CopyOnWriteArrayList<() -> Unit>() + + fun addBeforeDestroyListener(onBeforeDestroy: () -> Unit) { + listeners.add(onBeforeDestroy) + } + + fun removeBeforeDestroyListener(onBeforeDestroy: () -> Unit) { + listeners.remove(onBeforeDestroy) + } + + fun destroy() { + listeners.forEach { it.invoke() } + } + } + + class FakeApplication( + private val host: FakeReactHost?, + ) : Application() { + fun getReactHost(): FakeReactHost? = host + } + + open class FakeReactContext( + private val application: Context, + ) : ContextWrapper(application) { + override fun getApplicationContext(): Context = application + } + + class BridgelessContext( + application: Context, + private val bridgeless: Boolean, + ) : FakeReactContext(application) { + fun isBridgeless(): Boolean = bridgeless + } + + private val host = FakeReactHost() + private var calls = 0 + + private fun register(context: Context): RNSentryBeforeDestroyListener? = + RNSentryBeforeDestroyListener.register(context, { calls++ }, NoOpLogger.getInstance()) + + @Test + fun `runs the action when the bridgeless React host is destroyed`() { + val listener = register(BridgelessContext(FakeApplication(host), true)) + + assertNotNull(listener) + assertEquals(1, host.listeners.size) + host.destroy() + assertEquals(1, calls) + } + + @Test + fun `unregister removes the listener from the React host`() { + val listener = register(BridgelessContext(FakeApplication(host), true)) + + listener!!.unregister() + + assertTrue(host.listeners.isEmpty()) + host.destroy() + assertEquals(0, calls) + } + + @Test + fun `unregister works from inside the listener`() { + var listener: RNSentryBeforeDestroyListener? = null + listener = + RNSentryBeforeDestroyListener.register( + BridgelessContext(FakeApplication(host), true), + { + calls++ + listener!!.unregister() + }, + NoOpLogger.getInstance(), + ) + + host.destroy() + + assertEquals(1, calls) + assertTrue(host.listeners.isEmpty()) + } + + @Test + fun `does not register on the bridge`() { + assertNull(register(BridgelessContext(FakeApplication(host), false))) + assertTrue(host.listeners.isEmpty()) + } + + @Test + fun `does not register before React Native has bridgeless mode`() { + assertNull(register(FakeReactContext(FakeApplication(host)))) + assertTrue(host.listeners.isEmpty()) + } + + @Test + fun `does not register without a React host`() { + assertNull(register(BridgelessContext(FakeApplication(null), true))) + } + + @Test + fun `does not register when the application has no React host getter`() { + assertNull(register(BridgelessContext(Application(), true))) + } + + @Test + fun `a throwing action does not reach React Native`() { + RNSentryBeforeDestroyListener.register( + BridgelessContext(FakeApplication(host), true), + { throw IllegalStateException("cleanup failed") }, + NoOpLogger.getInstance(), + ) + + host.destroy() + } +} diff --git a/packages/core/android/build.gradle b/packages/core/android/build.gradle index c6c3bc8b3d..be58f918f1 100644 --- a/packages/core/android/build.gradle +++ b/packages/core/android/build.gradle @@ -153,6 +153,7 @@ android { targetSdkVersion safeExtGet('targetSdkVersion', 31) versionCode 1 versionName "1.0" + consumerProguardFiles 'proguard-rules.pro' ndk { abiFilters(*reactNativeArchitectures()) } diff --git a/packages/core/android/proguard-rules.pro b/packages/core/android/proguard-rules.pro new file mode 100644 index 0000000000..e30ae87a12 --- /dev/null +++ b/packages/core/android/proguard-rules.pro @@ -0,0 +1,16 @@ +# RNSentryBeforeDestroyListener reaches these members through reflection, because the SDK compiles +# against the app's React Native version. +-keepclassmembers class * implements com.facebook.react.ReactHost { + public void addBeforeDestroyListener(kotlin.jvm.functions.Function0); + public void removeBeforeDestroyListener(kotlin.jvm.functions.Function0); +} +-keepclassmembers class * implements com.facebook.react.ReactApplication { + public com.facebook.react.ReactHost getReactHost(); +} +-keepclassmembers class * extends com.facebook.react.bridge.ReactContext { + public boolean isBridgeless(); +} +-keep interface kotlin.jvm.functions.Function0 +-keepclassmembers class kotlin.Unit { + public static final kotlin.Unit INSTANCE; +} diff --git a/packages/core/android/src/main/java/io/sentry/react/RNSentryBeforeDestroyListener.java b/packages/core/android/src/main/java/io/sentry/react/RNSentryBeforeDestroyListener.java new file mode 100644 index 0000000000..f1b3085bf7 --- /dev/null +++ b/packages/core/android/src/main/java/io/sentry/react/RNSentryBeforeDestroyListener.java @@ -0,0 +1,109 @@ +package io.sentry.react; + +import android.content.Context; +import io.sentry.ILogger; +import io.sentry.SentryLevel; +import java.lang.reflect.Proxy; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Runs an action before the bridgeless React instance is destroyed, while the JS thread still runs. + * + *
Bridgeless {@code ReactInstance.destroy()} quits and joins the JS thread before it invalidates + * the native modules, so {@code invalidate()} is too late to turn off the Hermes sampler + * (https://github.com/facebook/hermes/issues/1853). {@code ReactHost.addBeforeDestroyListener}, + * from React Native 0.73, runs before that on reload and on destroy. The SDK compiles against the + * app's React Native version, so it reaches the API through reflection. {@code proguard-rules.pro} + * keeps these members in minified apps. + */ +final class RNSentryBeforeDestroyListener { + private static final String FUNCTION0 = "kotlin.jvm.functions.Function0"; + + private final @NotNull Object reactHost; + private final @NotNull Object listener; + + private RNSentryBeforeDestroyListener( + final @NotNull Object reactHost, final @NotNull Object listener) { + this.reactHost = reactHost; + this.listener = listener; + } + + /** + * Registers {@code action} with the React host of a bridgeless {@code reactContext}. Returns null + * on the bridge, before React Native 0.73, or without a React host, where {@code invalidate()} is + * the only cleanup. + */ + static @Nullable RNSentryBeforeDestroyListener register( + final @NotNull Context reactContext, + final @NotNull Runnable action, + final @NotNull ILogger logger) { + if (!isBridgeless(reactContext)) { + return null; + } + try { + final @Nullable Context application = reactContext.getApplicationContext(); + if (application == null) { + return null; + } + final @Nullable Object reactHost = + application.getClass().getMethod("getReactHost").invoke(application); + if (reactHost == null) { + return null; + } + final Class> function0 = Class.forName(FUNCTION0); + final Object unit = Class.forName("kotlin.Unit").getField("INSTANCE").get(null); + final Object listener = + Proxy.newProxyInstance( + function0.getClassLoader(), + new Class>[] {function0}, + (proxy, method, args) -> { + switch (method.getName()) { + case "invoke": + try { + action.run(); + } catch (Throwable e) { // NOPMD - We don't want to crash in any case + logger.log(SentryLevel.WARNING, "Before destroy cleanup failed.", e); + } + return unit; + case "equals": + return proxy == args[0]; // NOPMD - A listener equals only itself. + case "hashCode": + return System.identityHashCode(proxy); + case "toString": + return "RNSentryBeforeDestroyListener"; + default: + return null; + } + }); + reactHost + .getClass() + .getMethod("addBeforeDestroyListener", function0) + .invoke(reactHost, listener); + return new RNSentryBeforeDestroyListener(reactHost, listener); + } catch (Throwable e) { // NOPMD - We don't want to crash in any case + logger.log(SentryLevel.WARNING, "Failed to register a before destroy listener.", e); + return null; + } + } + + /** Removes the listener, so the long-lived React host does not keep a destroyed module. */ + void unregister() { + try { + reactHost + .getClass() + .getMethod("removeBeforeDestroyListener", Class.forName(FUNCTION0)) + .invoke(reactHost, listener); + } catch (Throwable ignored) { // NOPMD - Best-effort cleanup. + } + } + + private static boolean isBridgeless(final @NotNull Context reactContext) { + try { + final Object result = reactContext.getClass().getMethod("isBridgeless").invoke(reactContext); + return Boolean.TRUE.equals(result); + } catch (Throwable e) { // NOPMD - React Native before 0.73 has no bridgeless mode. + return false; + } + } +} diff --git a/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java b/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java index ec43b78fae..4cc1f78031 100644 --- a/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java +++ b/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java @@ -166,12 +166,20 @@ public class RNSentryModuleImpl { private final @NotNull SentryDateProvider dateProvider; private final @NotNull LoadClass loadClass; + // Set when the React instance is destroyed. A profile must not start after the cleanup, or the + // Hermes sampler stays on while the JS thread exits. + private final AtomicBoolean isDestroyed = new AtomicBoolean(false); + + private final @Nullable RNSentryBeforeDestroyListener beforeDestroyListener; + public RNSentryModuleImpl(ReactApplicationContext reactApplicationContext) { packageInfo = getPackageInfo(reactApplicationContext); this.reactApplicationContext = reactApplicationContext; this.emitNewFrameEvent = createEmitNewFrameEvent(); this.dateProvider = new SentryAndroidDateProvider(); this.loadClass = new LoadClass(); + this.beforeDestroyListener = + RNSentryBeforeDestroyListener.register(reactApplicationContext, this::invalidate, logger); } private ReactApplicationContext getReactApplicationContext() { @@ -1157,6 +1165,11 @@ private void initializeAndroidProfiler() { public WritableMap startProfiling(boolean platformProfilers) { final WritableMap result = new WritableNativeMap(); + if (isDestroyed.get()) { + result.putBoolean("started", false); + result.putString("error", "React instance is destroyed"); + return result; + } if (androidProfiler.get() == null && platformProfilers) { initializeAndroidProfiler(); } @@ -1170,6 +1183,10 @@ public WritableMap startProfiling(boolean platformProfilers) { // Mark profiling active immediately after enable() succeeds so a concurrent // invalidate() observes the running state even if androidProfiler.start() below throws. isProfiling.set(true); + // invalidate() can run between the check above and set(true), and then it saw no profile. + if (isDestroyed.get()) { + throw new IllegalStateException("React instance is destroyed"); + } final AndroidProfiler profiler = androidProfiler.get(); if (profiler != null) { profiler.start(); @@ -1278,18 +1295,23 @@ public WritableMap stopProfiling() { } /** - * Cleanup hook invoked from the module wrappers when the React instance is destroyed (e.g. Metro - * reload, orderly Activity teardown). Calls HermesSamplingProfiler.disable(), which synchronously - * joins the sampler's timer thread, so no pthread_kill can fire after the JS thread is torn down. + * Cleanup hook invoked when the React instance is destroyed (e.g. Metro reload, orderly Activity + * teardown). Calls HermesSamplingProfiler.disable(), which synchronously joins the sampler's + * timer thread, so no pthread_kill can fire after the JS thread is torn down. * - *
Correctness depends on RN invoking module invalidate() before joining the JS message queue - * thread. That is the documented contract for both old-arch CatalystInstance shutdown and - * new-arch TurboModule teardown. + *
The cleanup must run before React Native joins the JS message queue thread. Bridgeless + * ReactInstance.destroy() joins the JS thread before it invalidates the native modules, so there + * the before destroy listener of the React host calls this method first. The module wrappers call + * it again from invalidate(), which is early enough on the bridge (old-arch CatalystInstance + * shutdown). * *
See https://github.com/getsentry/sentry-react-native/issues/5441 and * https://github.com/facebook/hermes/issues/1853. */ public void invalidate() { + if (!isDestroyed.getAndSet(true) && beforeDestroyListener != null) { + beforeDestroyListener.unregister(); + } // Atomic gate: only one caller (invalidate vs stopProfiling vs a re-entrant invalidate) // wins the right to clean up; the rest no-op. if (!isProfiling.getAndSet(false)) {