From a7b417881d9e9d9f8fa7ae47841df2d063847de9 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 12:06:37 +0100 Subject: [PATCH] ref(android): Rethrow fatal errors at sentry-android-core boundaries The broad catches left in sentry-android-core guard Binder calls into system services, the app's own views and contexts, data parceled by other processes, files written by crashing processes, and the configuration callback. Call ExceptionUtils.rethrowIfFatal first in each of them, so OutOfMemoryError, StackOverflowError and LinkageError are no longer swallowed, and say why the catch is broad and what happens on failure. getProcessesInErrorState keeps swallowing OutOfMemoryError: unparceling its reply can fail to allocate without the app being out of memory (#2114). Sites whose failures are known are narrowed instead: the native envelope parsing in NativeEventCollector, the DeviceInfoUtil future in DefaultAndroidEventProcessor, the Build reads in getFamily and isEmulator, and the envelope item reads in TombstoneIntegration. The catch around the cached split APK info guarded nothing and is removed. SentryAndroid.init now documents what happens when the configuration handler throws. Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../io/sentry/android/core/ANRWatchDog.java | 10 ++- .../sentry/android/core/AnrV2Integration.java | 5 ++ .../AppComponentsBreadcrumbsIntegration.java | 14 +++- .../ApplicationExitInfoEventProcessor.java | 10 +++ .../android/core/BuildInfoProvider.java | 3 +- .../io/sentry/android/core/ContextUtils.java | 52 +++++++++--- .../core/DefaultAndroidEventProcessor.java | 20 ++++- .../sentry/android/core/DeviceInfoUtil.java | 16 ++++ .../core/EnvelopeFileObserverIntegration.java | 6 +- .../core/FeedbackShakeIntegration.java | 4 + .../android/core/InternalSentrySdk.java | 8 ++ .../android/core/ManifestMetadataReader.java | 8 ++ .../android/core/NativeEventCollector.java | 13 ++- .../sentry/android/core/PerfettoProfiler.java | 4 + .../core/SendCachedEnvelopeIntegration.java | 5 ++ .../io/sentry/android/core/SentryAndroid.java | 15 +++- .../core/SentryPerformanceProvider.java | 6 ++ .../SystemEventsBreadcrumbsIntegration.java | 13 +++ .../android/core/TombstoneIntegration.java | 12 ++- .../core/ViewHierarchyEventProcessor.java | 4 +- .../core/anr/AnrProfilingIntegration.java | 4 + .../util/AndroidConnectionStatusProvider.java | 17 ++++ .../core/internal/util/ScreenshotUtils.java | 14 +++- .../util/SentryFrameMetricsCollector.java | 12 +++ .../core/performance/AppStartMetrics.java | 7 +- .../io/sentry/android/core/ANRWatchDogTest.kt | 83 +++++++++++++++++++ .../android/core/NativeEventCollectorTest.kt | 20 +++++ .../sentry/android/core/SentryAndroidTest.kt | 13 +++ 28 files changed, 366 insertions(+), 32 deletions(-) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java index c109855daa7..62309dfc276 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java @@ -34,6 +34,7 @@ import io.sentry.SentryLevel; import io.sentry.time.Deadline; import io.sentry.time.MonotonicTicker; +import io.sentry.util.ExceptionUtils; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -174,9 +175,16 @@ private boolean isProcessNotResponding() { if (am != null) { List processesInErrorState = null; try { - // It can throw RuntimeException or OutOfMemoryError processesInErrorState = am.getProcessesInErrorState(); + } catch (OutOfMemoryError e) { + // Unparceling the reply, which lists every process in an error state, can fail to + // allocate even when the app itself has memory left, so it's not treated as fatal here + // (#2114). The process is treated as responding normally, so no ANR is reported. + logger.log(SentryLevel.ERROR, "Error getting ActivityManager#getProcessesInErrorState.", e); } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from + // the other side. The process is treated as responding normally, so no ANR is reported. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting ActivityManager#getProcessesInErrorState.", e); } // if list is null, there's no process in ANR state. diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java index 19de22c9a87..129b5799be8 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java @@ -30,6 +30,7 @@ import io.sentry.protocol.SentryThread; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.ICurrentDateProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.BufferedReader; @@ -229,6 +230,10 @@ public void markReported(final long timestamp) { } return new ParseResult(ParseResult.Type.DUMP, dump, threads, debugImages, artContext); } catch (Throwable e) { + // The dump is written by ART in a format that changes between Android versions and + // vendors, so we can't know how the parser fails on unexpected input. The ANR is still + // reported, with a message asking to attach the raw dump. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.WARNING, "Failed to parse ANR thread dump", e); return new ParseResult(ParseResult.Type.ERROR, dump); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java index 66afe6033a3..f6dfded853d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java @@ -15,6 +15,7 @@ import io.sentry.android.core.internal.util.Debouncer; import io.sentry.android.core.internal.util.DeviceOrientations; import io.sentry.protocol.Device; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.Closeable; import java.io.IOException; @@ -66,6 +67,10 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions .log(SentryLevel.DEBUG, "AppComponentsBreadcrumbsIntegration installed."); addIntegrationToSdkVersion("AppComponentsBreadcrumbs"); } catch (Throwable e) { + // The context may be the app's own subclass, or a ContextImpl that doesn't support + // component callbacks on older versions, so we can't know what this throws. App + // component breadcrumbs are disabled. + ExceptionUtils.rethrowIfFatal(e); this.options.setEnableAppComponentBreadcrumbs(false); options.getLogger().log(SentryLevel.INFO, e, "ComponentCallbacks2 is not available."); } @@ -77,12 +82,15 @@ public void close() throws IOException { try { // if its a ContextImpl, unregisterComponentCallbacks can't be used context.unregisterComponentCallbacks(this); - } catch (Throwable ignored) { - // fine, might throw on older versions + } catch (Throwable e) { + // The context may be the app's own subclass, or a ContextImpl that doesn't support + // component callbacks on older versions, so we can't know what this throws. The callbacks + // may stay registered until the process ends. + ExceptionUtils.rethrowIfFatal(e); if (options != null) { options .getLogger() - .log(SentryLevel.DEBUG, ignored, "It was not possible to unregisterComponentCallbacks"); + .log(SentryLevel.DEBUG, e, "It was not possible to unregisterComponentCallbacks"); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java index 63b08cb9b73..6bbe26ae7a1 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java @@ -69,6 +69,7 @@ import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.User; import io.sentry.protocol.profiling.SentryProfile; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.SentryRandom; import java.io.File; @@ -447,6 +448,9 @@ private void setApp(final @NotNull SentryBaseEvent event) { } } } catch (Throwable e) { + // The first DeviceInfoUtil.getInstance call queries the package manager over Binder, which + // can rethrow any runtime exception from the other side. The split APK info is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting split apks info.", e); } @@ -716,6 +720,9 @@ private void setSideLoadedInfo(final @NotNull SentryBaseEvent event) { } } } catch (Throwable e) { + // The first DeviceInfoUtil.getInstance call queries the package manager over Binder, which + // can rethrow any runtime exception from the other side. The side-loaded tags are left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting side loaded info.", e); } } @@ -975,6 +982,9 @@ private void applyAnrProfile( options.getLogger().log(SentryLevel.DEBUG, "No ANR profile file found"); } } catch (Throwable t) { + // The profile file was written by the previous process, possibly while it was being + // killed, so we can't know how reading it fails. The ANR is sent without a profile. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.INFO, "Could not retrieve ANR profile", t); } finally { if (!AnrProfileRotationHelper.deleteLastFile(cacheDir)) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/BuildInfoProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/BuildInfoProvider.java index 5b0786ffb7f..2024402768b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/BuildInfoProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/BuildInfoProvider.java @@ -67,7 +67,8 @@ public int getSdkInfoVersion() { || Build.PRODUCT.contains("vbox86p") || Build.PRODUCT.contains("emulator") || Build.PRODUCT.contains("simulator"); - } catch (Throwable e) { + } catch (NullPointerException e) { + // Build fields are only null off-device, e.g. in unit tests against the android.jar stubs logger.log( SentryLevel.ERROR, "Error checking whether application is running in an emulator.", e); return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java index 22938712faf..437e5dded7a 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java @@ -22,6 +22,7 @@ import io.sentry.SentryOptions; import io.sentry.android.core.util.AndroidLazyEvaluator; import io.sentry.protocol.App; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -104,6 +105,9 @@ private ContextUtils() {} .getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0)); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -113,6 +117,9 @@ private ContextUtils() {} try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -131,6 +138,9 @@ private ContextUtils() {} return context.getString(stringId); } } catch (Throwable e) { + // getApplicationLabel is a Binder call into the package manager, and the context may be + // the app's own subclass, so we can't know what this throws. The app name is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -150,6 +160,9 @@ private ContextUtils() {} context.getPackageName(), PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA)); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The application info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -161,6 +174,9 @@ private ContextUtils() {} .getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The application info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -202,6 +218,9 @@ static PackageInfo getPackageInfo( return context.getPackageManager().getPackageInfo(context.getPackageName(), flags); } } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from the + // other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting package info.", e); return null; } @@ -269,8 +288,10 @@ public static boolean isForegroundImportance() { new ActivityManager.RunningAppProcessInfo(); ActivityManager.getMyMemoryState(appProcessInfo); return appProcessInfo.importance == IMPORTANCE_FOREGROUND; - } catch (Throwable ignored) { - // should never happen + } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from the + // other side. The process is treated as not in the foreground. + ExceptionUtils.rethrowIfFatal(e); } return false; } @@ -299,7 +320,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte } } } catch (Throwable t) { - // ignored + // getAppTasks is a Binder call into the activity manager, which can rethrow any runtime + // exception from the other side. The app is treated as not running a Compose Preview. + ExceptionUtils.rethrowIfFatal(t); } } return false; @@ -398,6 +421,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte try { return context.getResources().getDisplayMetrics(); } catch (Throwable e) { + // The context may be the app's own subclass that overrides getResources(), so we can't know + // what it throws. The display metrics are left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting DisplayMetrics.", e); return null; } @@ -412,7 +438,8 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte static @Nullable String getFamily(final @NotNull ILogger logger) { try { return Build.MODEL.split(" ", -1)[0]; - } catch (Throwable e) { + } catch (NullPointerException e) { + // Build fields are only null off-device, e.g. in unit tests against the android.jar stubs logger.log(SentryLevel.ERROR, "Error getting device family.", e); return null; } @@ -440,6 +467,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte logger.log(SentryLevel.INFO, "Error getting MemoryInfo."); return null; } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from the + // other side. The memory info is left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting MemoryInfo.", e); return null; } @@ -506,16 +536,12 @@ static void setAppPackageInfo( app.setPermissions(permissions); if (deviceInfoUtil != null) { - try { - final ContextUtils.SplitApksInfo splitApksInfo = deviceInfoUtil.getSplitApksInfo(); - if (splitApksInfo != null) { - app.setSplitApks(splitApksInfo.isSplitApks()); - if (splitApksInfo.getSplitNames() != null) { - app.setSplitNames(Arrays.asList(splitApksInfo.getSplitNames())); - } + final ContextUtils.SplitApksInfo splitApksInfo = deviceInfoUtil.getSplitApksInfo(); + if (splitApksInfo != null) { + app.setSplitApks(splitApksInfo.isSplitApks()); + if (splitApksInfo.getSplitNames() != null) { + app.setSplitNames(Arrays.asList(splitApksInfo.getSplitNames())); } - } catch (Throwable e) { - // Split APK info is optional, the app context is still complete without it. } } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java index 5c28ccaf488..bb5c416cc68 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java @@ -17,12 +17,14 @@ import io.sentry.protocol.SentryThread; import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -193,6 +195,9 @@ private void setDevice( .getContexts() .setDevice(deviceInfoUtil.get().collectDeviceInformation(errorEvent, applyScopeData)); } catch (Throwable e) { + // Collecting the device info makes Binder calls into several system services, which can + // rethrow any runtime exception from the other side. The device context is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); } } else { @@ -210,7 +215,10 @@ private void mergeOS(final @NotNull SentryBaseEvent event) { final OperatingSystem androidOS = deviceInfoUtil.get().getOperatingSystem(); // make Android OS the main OS using the 'os' key event.getContexts().setOperatingSystem(androidOS); - } catch (Throwable e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve os system", e); + } catch (ExecutionException e) { options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve os system", e); } } else { @@ -310,7 +318,10 @@ private void setPackageInfo(final @NotNull SentryBaseEvent event, final @NotNull if (this.deviceInfoUtil != null) { try { deviceInfoUtil = this.deviceInfoUtil.get(); - } catch (Throwable e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); + } catch (ExecutionException e) { options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); } } else { @@ -367,7 +378,10 @@ private void setSideLoadedInfo(final @NotNull SentryBaseEvent event) { event.setTag(entry.getKey(), entry.getValue()); } } - } catch (Throwable e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + options.getLogger().log(SentryLevel.ERROR, "Error getting side loaded info.", e); + } catch (ExecutionException e) { options.getLogger().log(SentryLevel.ERROR, "Error getting side loaded info.", e); } } else { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java b/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java index 19113768ef3..784a8746ef0 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java @@ -25,6 +25,7 @@ import io.sentry.android.core.internal.util.RootChecker; import io.sentry.protocol.Device; import io.sentry.protocol.OperatingSystem; +import io.sentry.util.ExceptionUtils; import java.io.File; import java.util.Calendar; import java.util.Collections; @@ -303,6 +304,9 @@ public static Float getBatteryLevel( return ((float) level / (float) scale) * percentMultiplier; } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The battery level is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device battery level.", e); return null; } @@ -321,6 +325,9 @@ public static Boolean isCharging( return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The charging state is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device charging state.", e); return null; } @@ -334,6 +341,9 @@ private Float getBatteryTemperature(final @NotNull Intent batteryIntent) { return ((float) temperature) / 10; // celsius } } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The temperature is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting battery temperature.", e); } return null; @@ -359,6 +369,9 @@ private Device.DeviceOrientation getOrientation() { return null; } } catch (Throwable e) { + // The context may be the app's own subclass that overrides getResources(), so we can't know + // what it throws. The orientation is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device orientation.", e); } return deviceOrientation; @@ -394,6 +407,9 @@ private StatFs getExternalStorageStat(final @Nullable File internalStorage) { return new StatFs(path.getPath()); } } catch (Throwable e) { + // getExternalFilesDirs asks the storage service over Binder to create the directories, so + // we can't know what it throws. The external storage sizes are left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.INFO, "Not possible to read external files directory"); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java index e81577cfd4b..fd60edfd50f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java @@ -10,6 +10,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.FileUtils; import io.sentry.util.Objects; import java.io.Closeable; @@ -92,7 +93,10 @@ private void startOutboxSender( options.getLogger().log(SentryLevel.DEBUG, "EnvelopeFileObserverIntegration installed."); addIntegrationToSdkVersion("EnvelopeFileObserver"); } catch (Throwable e) { - // it could throw eg NoSuchFileException or NullPointerException + // startWatching() sets up inotify through native code, which can throw e.g. + // NoSuchFileException or NullPointerException, so we can't know what it throws. Envelopes + // written to the outbox, e.g. by the NDK, are not picked up while the process runs. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(SentryLevel.ERROR, "Failed to initialize EnvelopeFileObserverIntegration.", e); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java index 677678b2438..8fce55f5079 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java @@ -11,6 +11,7 @@ import io.sentry.SentryFeedbackOptions; import io.sentry.SentryLevel; import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.Closeable; import java.io.IOException; @@ -298,6 +299,9 @@ private void startShakeDetection(final @NotNull Activity activity) { dialog = dialogFactory.create(active); dialog.show(); } catch (Throwable e) { + // show() adds a window over Binder and the dialog inflates with the app's theme, so + // we can't know what this throws. No dialog is shown for this shake. + ExceptionUtils.rethrowIfFatal(e); if (dialog != null) { onDialogGone(dialog); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 7c2e72031bb..84835bcb93c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java @@ -30,6 +30,7 @@ import io.sentry.protocol.Device; import io.sentry.protocol.SentryId; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.MapObjectWriter; import io.sentry.util.TracingUtils; import java.io.ByteArrayInputStream; @@ -139,6 +140,10 @@ public static Map serializeScope( writer.name("level").value(logger, scope.getLevel()); writer.name("breadcrumbs").value(logger, scope.getBreadcrumbs()); } catch (Throwable e) { + // An entry point for hybrid SDKs. Serializing the scope reaches into the device and package + // manager over Binder and into whatever objects the app put in extras, so we can't know what + // it throws. The caller gets an empty map. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Could not serialize scope.", e); return new HashMap<>(); } @@ -204,6 +209,9 @@ public static SentryId captureEnvelope( new SentryEnvelope(envelope.getHeader(), envelopeItems); return scopes.captureEnvelope(repackagedEnvelope); } catch (Throwable t) { + // An entry point for hybrid SDKs, which hand over an envelope we didn't build, so we can't + // know what processing it throws. The envelope is dropped and the caller gets null. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.ERROR, "Failed to capture envelope", t); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java index 411546a80b5..c24a2a8f6a9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java @@ -15,6 +15,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryReplayOptions; import io.sentry.protocol.SdkVersion; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.util.ArrayList; import java.util.Arrays; @@ -842,6 +843,10 @@ static void applyMetadata( .getLogger() .log(SentryLevel.INFO, "Retrieving configuration from AndroidManifest.xml"); } catch (Throwable e) { + // A metadata bundle from the package manager is unparceled on first access, and its values + // are whatever the app put in its manifest, so we can't know what reading it throws. The + // options keep their defaults for every key not read yet. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1134,6 +1139,9 @@ static boolean isAutoInit(final @NotNull Context context, final @NotNull ILogger autoInit = readBool(metadata, logger, AUTO_INIT, true); } } catch (Throwable e) { + // A metadata bundle from the package manager is unparceled on first access, so we can't know + // what reading it throws. Auto-init stays enabled. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to read auto-init from android manifest metadata.", e); } return autoInit; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java index bb7811ce594..d88e19b8ca9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java @@ -285,7 +285,7 @@ public boolean deleteNativeEventFile(final @NotNull NativeEventData nativeEventD break; } } - } catch (Throwable e) { + } catch (IOException e) { options .getLogger() .log( @@ -337,7 +337,8 @@ public boolean deleteNativeEventFile(final @NotNull NativeEventData nativeEventD if (NATIVE_PLATFORM.equals(platform) && timestamp != null) { result = new NativeEnvelopeMetadata(file, timestamp.getTime()); } - } catch (Throwable e) { + } catch (IOException | IllegalStateException e) { + // IllegalStateException is how the JSON reader reports an unexpected token options .getLogger() .log(SentryLevel.DEBUG, e, "Error parsing event JSON from: %s", file.getName()); @@ -369,7 +370,9 @@ public boolean deleteNativeEventFile(final @NotNull NativeEventData nativeEventD } } } - } catch (Throwable e) { + } catch (Exception e) { + // EnvelopeReader reports a malformed envelope with IllegalArgumentException, and getData() + // is declared to throw Exception for items that are created lazily options .getLogger() .log(SentryLevel.DEBUG, e, "Error loading envelope file: %s", file.getAbsolutePath()); @@ -420,7 +423,9 @@ private static final class ItemHeaderInfo { if (length >= 0) { return new ItemHeaderInfo(type, length); } - } catch (Throwable e) { + } catch (IOException | IllegalStateException | NumberFormatException e) { + // the JSON reader reports an unexpected token with IllegalStateException, and a length that + // isn't an int with NumberFormatException options.getLogger().log(SentryLevel.DEBUG, e, "Error parsing item header"); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java index 4a64359aa44..c2df1e63137 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java @@ -13,6 +13,7 @@ import io.sentry.SentryLevel; import io.sentry.android.core.internal.profiling.ChunkRecord; import io.sentry.profiling.ProfileRecordingState; +import io.sentry.util.ExceptionUtils; import java.io.File; import java.util.concurrent.RejectedExecutionException; import java.util.function.Consumer; @@ -109,6 +110,9 @@ boolean start(final @NotNull ChunkRecord chunkRecord, final long durationMs) { Runnable::run, this::onProfilingResult); } catch (Throwable e) { + // A Binder call into the profiling service, which can rethrow any runtime exception from + // the other side. This chunk is not profiled. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to request Profiling.", e); // No profiling was requested, so a late result from the OS must not write into the record this.chunkRecord = null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java index 1f3dc572792..9f40d7c4506 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java @@ -12,6 +12,7 @@ import io.sentry.SentryOptions; import io.sentry.transport.RateLimiter; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; import java.io.Closeable; @@ -136,6 +137,10 @@ private void sendCachedEnvelopes( sender.send(); } catch (Throwable e) { + // send() reads every envelope earlier processes left in the cache and hands them + // to the transport, so we can't know what it throws. The envelopes stay cached + // and are retried on the next connection change or app start. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(SentryLevel.ERROR, "Failed trying to send cached events.", e); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index bffbf75b980..77542d7c044 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -20,6 +20,7 @@ import io.sentry.android.fragment.FragmentLifecycleIntegration; import io.sentry.android.timber.SentryTimberIntegration; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LoadClass; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -79,6 +80,11 @@ public static void init(@NotNull final Context context, @NotNull ILogger logger) /** * Sentry initialization with a configuration handler that may override the default options * + *

If the configuration handler throws, init continues with the options it set before it + * failed. Fatal errors such as {@link OutOfMemoryError} are rethrown instead. The failure is only + * logged at ERROR level through the SDK logger, which prints only when debug is enabled, e.g. + * through the {@code io.sentry.debug} manifest entry. + * * @param context Application. context * @param configuration Sentry.OptionsConfiguration configuration handler */ @@ -91,6 +97,11 @@ public static void init( /** * Sentry initialization with a configuration handler and custom logger * + *

If the configuration handler throws, init continues with the options it set before it + * failed. Fatal errors such as {@link OutOfMemoryError} are rethrown instead. The failure is only + * logged at ERROR level through the SDK logger, which prints only when debug is enabled, e.g. + * through the {@code io.sentry.debug} manifest entry. + * * @param context Application. context * @param logger your custom logger that implements ILogger * @param configuration Sentry.OptionsConfiguration configuration handler @@ -151,7 +162,9 @@ public static void init( try { configuration.configure(options); } catch (Throwable t) { - // let it slip, but log it + // The configuration callback is the app's own code, so we can't know what it + // throws. Init continues with the options set before it failed. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java index d156b00fa5a..c9c72f9d8d2 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java @@ -22,6 +22,7 @@ import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -160,6 +161,11 @@ private void launchAppStartProfiler(final @NotNull AppStartMetrics appStartMetri } catch (FileNotFoundException e) { logger.log(SentryLevel.ERROR, "App start profiling config file not found. ", e); } catch (Throwable e) { + // Runs in a ContentProvider before Application.onCreate: it parses a config file written by + // the previous launch and starts a profiler through the platform's tracing, so we can't + // know what it throws, and it must not stop the app from starting. App start profiling + // doesn't start. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error reading app start profiling config file. ", e); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java index b3caf622c37..e1c4966efb6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java @@ -37,6 +37,7 @@ import io.sentry.SentryOptions; import io.sentry.android.core.internal.util.Debouncer; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.util.StringUtils; import java.io.Closeable; @@ -173,6 +174,10 @@ private void registerReceiver( addIntegrationToSdkVersion("SystemEventsBreadcrumbs"); } } catch (Throwable e) { + // registerReceiver is a Binder call into the activity manager, which can rethrow + // any runtime exception from the other side. System event breadcrumbs are + // disabled. + ExceptionUtils.rethrowIfFatal(e); options.setEnableSystemEventBreadcrumbs(false); options .getLogger() @@ -221,6 +226,10 @@ private void unregisterReceiver(final @NotNull SentryAndroidOptions options) { try { context.unregisterReceiver(receiverRef); } catch (Throwable exception) { + // unregisterReceiver is a Binder call into the activity manager, which can rethrow any + // runtime exception from the other side. The receiver may stay registered until the + // process ends. + ExceptionUtils.rethrowIfFatal(exception); options .getLogger() .log( @@ -409,6 +418,10 @@ String getStringAfterDotFast(final @Nullable String str) { newExtras.put(item, value.toString()); } } catch (Throwable exception) { + // The extras were parceled by the broadcast's sender and are unparceled here, and the + // value's class implements toString(), so we can't know what this throws. The extra + // is left out of the breadcrumb. + ExceptionUtils.rethrowIfFatal(exception); options .getLogger() .log( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java index 88f83fd2993..eabd7ada8c6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java @@ -35,6 +35,7 @@ import io.sentry.protocol.SentryThread; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.ICurrentDateProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.ByteArrayInputStream; @@ -189,6 +190,10 @@ public void markReported(final long timestamp) { } } } catch (Throwable e) { + // getTraceInputStream() is a Binder call into system_server, and the tombstone was written + // by debuggerd for a crashing process, so we can't know what reading and parsing it + // throws. This tombstone is not reported. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -218,6 +223,10 @@ public void markReported(final long timestamp) { event = mergedEvent; } } catch (Throwable e) { + // The native events were written by sentry-native while the process was crashing, so we + // can't know what parsing and merging them throws. The tombstone is reported without + // them. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -282,7 +291,8 @@ private void addNativeAttachmentsToTombstoneHint( item.getHeader().getContentType(), item.getHeader().getAttachmentType(), false)); - } catch (Throwable e) { + } catch (Exception e) { + // getData() is declared to throw Exception for items that are created lazily options .getLogger() .log(SentryLevel.DEBUG, "Failed to process envelope item: %s", e.getMessage()); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java index 99fe0d98cd4..f5c9c04615b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java @@ -282,7 +282,9 @@ private static ViewHierarchyNode viewToNode(@NotNull final View view) { node.setIdentifier(identifier); } } catch (Throwable e) { - // ignored + // The lookup goes through the view's context and resources, which the app's views can + // override, so we can't know what it throws. The node is sent without an identifier. + ExceptionUtils.rethrowIfFatal(e); } node.setX((double) view.getX()); node.setY((double) view.getY()); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index 018fd49f6fd..0c7d3b39505 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java @@ -17,6 +17,7 @@ import io.sentry.time.MonotonicTicker; import io.sentry.time.Stopwatch; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.util.SentryRandom; import java.io.Closeable; @@ -224,6 +225,9 @@ public void run() { } } } catch (Throwable t) { + // The root of the profiling thread: anything escaping run() would reach the default + // uncaught exception handler and crash the app. Profiling stops until the next foreground. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "Failed to execute AnrStacktraceIntegration", t); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index de5a90c9067..45096ecce79 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java @@ -23,6 +23,7 @@ import io.sentry.time.Deadline; import io.sentry.time.MonotonicTicker; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; @@ -553,6 +554,9 @@ private boolean hasSignificantTransportChanges( ? connectivityManager.getNetworkCapabilities(activeNetwork) : null; } catch (Throwable t) { + // Binder calls into the connectivity service, which can rethrow any runtime exception from + // the other side. The connection status stays unknown until the next refresh. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.WARNING, "Failed to update connection status cache", t); return null; } @@ -722,6 +726,9 @@ public NetworkCapabilities getCachedNetworkCapabilities() { ? ConnectionStatus.CONNECTED : ConnectionStatus.DISCONNECTED; } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side. The status is reported as unknown. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "Could not retrieve Connection Status", t); return ConnectionStatus.UNKNOWN; } @@ -787,6 +794,9 @@ public NetworkCapabilities getCachedNetworkCapabilities() { return "cellular"; } } catch (Throwable exception) { + // Binder calls into the connectivity service, which can rethrow any runtime exception from + // the other side. The connection type is left out. + ExceptionUtils.rethrowIfFatal(exception); logger.log(SentryLevel.ERROR, "Failed to retrieve network info", exception); } @@ -877,6 +887,10 @@ static boolean registerNetworkCallback( connectivityManager.registerDefaultNetworkCallback(networkCallback); } } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side, e.g. when the app has too many callbacks registered. Network changes are + // not observed. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "registerDefaultNetworkCallback failed", t); return false; } @@ -895,6 +909,9 @@ static void unregisterNetworkCallback( try { connectivityManager.unregisterNetworkCallback(networkCallback); } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side. The callback may stay registered until the process ends. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "unregisterNetworkCallback failed", t); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java index 1b17f28d5ed..7369ed3a00f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java @@ -15,6 +15,7 @@ import io.sentry.SentryLevel; import io.sentry.android.core.BuildInfoProvider; import io.sentry.android.core.SentryAndroidOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.thread.IThreadChecker; import java.io.ByteArrayOutputStream; import java.util.concurrent.CountDownLatch; @@ -183,7 +184,9 @@ public final class ScreenshotUtils { final boolean completed = latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS); success = completed && copyResultCode.get() == PixelCopy.SUCCESS; } catch (Throwable e) { - // ignored + // PixelCopy reads the window's surface through the system compositor, so we can't know + // what it throws. No screenshot is attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot using PixelCopy failed.", e); } finally { thread.quit(); @@ -206,6 +209,9 @@ public final class ScreenshotUtils { try { view.draw(canvas); } catch (Throwable e) { + // draw() runs the app's own views, so we can't know what it throws. No screenshot is + // attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot failed (view.draw).", e); } finally { latch.countDown(); @@ -219,6 +225,9 @@ public final class ScreenshotUtils { } return bitmap; } catch (Throwable e) { + // On the main thread, draw() runs the app's own views, so we can't know what it throws. No + // screenshot is attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot failed.", e); } return null; @@ -251,6 +260,9 @@ public final class ScreenshotUtils { // screenshot png is around ~100-150 kb return byteArrayOutputStream.toByteArray(); } catch (Throwable e) { + // compress() runs the native image encoder, so we can't know what it throws. No screenshot is + // attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Compressing bitmap failed.", e); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java index 80d0ea08c1f..eccc20d59ad 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java @@ -21,6 +21,7 @@ import io.sentry.android.core.ContextUtils; import io.sentry.android.core.SentryFramesDelayResult; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.lang.ref.WeakReference; import java.lang.reflect.Field; @@ -129,6 +130,10 @@ public SentryFrameMetricsCollector( try { choreographer = Choreographer.getInstance(); } catch (Throwable e) { + // The first call creates the Choreographer, which connects to the display's vsync + // through native code, so we can't know what it throws. Slow and frozen frames are not + // reported. + ExceptionUtils.rethrowIfFatal(e); logger.log( SentryLevel.ERROR, "Error retrieving Choreographer instance. Slow and frozen frames will not be reported.", @@ -358,6 +363,9 @@ private void stopTrackingWindow(final @NotNull Window window) { window, frameMetricsAvailableListener); } } catch (Throwable e) { + // The window hands the listener to its native renderer, so we can't know what this + // throws. The listener may stay attached until the window is gone. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to remove frameMetricsAvailableListener", e); } }); @@ -393,6 +401,10 @@ private void trackCurrentWindow() { windowFrameMetricsManager.addOnFrameMetricsAvailableListener( window, frameMetricsAvailableListener, handler); } catch (Throwable e) { + // The window hands the listener to its native renderer, so we can't know what this + // throws, e.g. for a window that isn't hardware accelerated. Frames of this window + // are not measured. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to add frameMetricsAvailableListener", e); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java index 2eff6ffc787..50cb31d9fb4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java @@ -29,6 +29,7 @@ import io.sentry.android.core.internal.util.FirstDrawDoneListener; import io.sentry.protocol.SentryId; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -626,8 +627,10 @@ private void resolveHeadlessAppStartEndTime() { stopHeadlessAppStartAt(onCreateStartUptimeMs); return; } - } catch (Throwable ignored) { - // Best effort: never let optional startup timestamp enrichment break app startup. + } catch (Throwable e) { + // The start info came from system_server over Binder and the timestamp is optional, so a + // malformed record must not break app startup. The process init time is used instead. + ExceptionUtils.rethrowIfFatal(e); } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt index fa0f8a7b2fa..dad5fa9c290 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt @@ -4,20 +4,27 @@ import android.app.ActivityManager import android.app.ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING import android.app.ActivityManager.ProcessErrorStateInfo.NO_ERROR import android.content.Context +import com.google.common.truth.Truth.assertThat import io.sentry.time.TestMonotonicTicker import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.Before import org.mockito.kotlin.any +import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.mockingDetails +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class ANRWatchDogTest { @@ -229,6 +236,82 @@ class ANRWatchDogTest { } } + @Test + fun `when getProcessesInErrorState runs out of memory, keeps watching without reporting`() { + var anr: ApplicationNotResponding? = null + val am = mock() + whenever(am.processesInErrorState).thenThrow(OutOfMemoryError("large reply")) + val posted = CountDownLatch(1) + val sut = watchDog(am, posted) { a -> anr = a } + val es = Executors.newSingleThreadExecutor() + try { + val running = es.submit { sut.run() } + assertTrue(posted.await(10L, TimeUnit.SECONDS)) + + var waitCount = 0 + do { + ticker.advance(100, MILLISECONDS) + Thread.sleep(100L) + } while (mockingDetails(am).invocations.isEmpty() && waitCount++ < 100) + + verify(am, atLeastOnce()).processesInErrorState + assertNull(anr) + assertFalse(running.isDone) + } finally { + sut.interrupt() + es.shutdown() + } + } + + @Test + fun `when getProcessesInErrorState throws a fatal error, the watchdog stops`() { + val am = mock() + whenever(am.processesInErrorState).thenThrow(StackOverflowError()) + val posted = CountDownLatch(1) + val sut = watchDog(am, posted) {} + val es = Executors.newSingleThreadExecutor() + try { + val running = es.submit { sut.run() } + assertTrue(posted.await(10L, TimeUnit.SECONDS)) + + var waitCount = 0 + do { + ticker.advance(100, MILLISECONDS) + Thread.sleep(100L) + } while (!running.isDone && waitCount++ < 100) + + val error = assertFailsWith { running.get() } + assertThat(error.cause).isInstanceOf(StackOverflowError::class.java) + } finally { + sut.interrupt() + es.shutdown() + } + } + + private fun watchDog( + am: ActivityManager, + posted: CountDownLatch, + listener: ANRWatchDog.ANRListener, + ): ANRWatchDog { + val handler = mock() + // the posted runnable never runs, so the main thread looks blocked + whenever(handler.post(any())).then { posted.countDown() } + whenever(handler.thread).thenReturn(mock()) + val context = mock() + whenever(context.getSystemService(eq(Context.ACTIVITY_SERVICE))).thenReturn(am) + return ANRWatchDog( + ticker, + 10L, + 1L, + true, + listener, + mock(), + handler, + context, + AndroidDebugManager(), + ) + } + @Test fun `measures the ANR threshold on the ticker, not on wall time`() { var anr: ApplicationNotResponding? = null diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/NativeEventCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/NativeEventCollectorTest.kt index 490847b3182..16191e0e7eb 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/NativeEventCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/NativeEventCollectorTest.kt @@ -88,6 +88,26 @@ class NativeEventCollectorTest { assertNull(match) } + @Test + fun `handles an item header with a non-numeric length without throwing`() { + val sut = fixture.getSut(tmpDir) + File(fixture.outboxDir, "bad-length.envelope") + .writeText("{}\n{\"type\":\"event\",\"length\":\"abc\"}\n{}\n") + + val match = sut.findAndRemoveMatchingNativeEvent(0L) + assertNull(match) + } + + @Test + fun `handles an event payload that is not a JSON object without throwing`() { + val sut = fixture.getSut(tmpDir) + File(fixture.outboxDir, "array-payload.envelope") + .writeText("{}\n{\"type\":\"event\",\"length\":3}\n[1]\n") + + val match = sut.findAndRemoveMatchingNativeEvent(0L) + assertNull(match) + } + @Test fun `handles envelope with event and attachments without throwing`() { val sut = fixture.getSut(tmpDir) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index dc2472e6a6d..b400bb4707c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -217,6 +217,19 @@ class SentryAndroidTest { assertTrue(Sentry.isEnabled()) } + @Test + fun `when the configuration handler throws, init continues with the options it set`() { + var refOptions: SentryAndroidOptions? = null + fixture.initSut { + it.anrTimeoutIntervalMillis = 3000 + refOptions = it + throw IllegalStateException("configuration failed") + } + + assertEquals(3000, refOptions!!.anrTimeoutIntervalMillis) + assertTrue(Sentry.isEnabled()) + } + @Test fun `init won't throw exception`() { val logger = mock()