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 c109855daa..62309dfc27 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 19de22c9a8..129b5799be 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 66afe6033a..f6dfded853 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 63b08cb9b7..6bbe26ae7a 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 5b0786ffb7..2024402768 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 22938712fa..437e5dded7 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 5c28ccaf48..bb5c416cc6 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 19113768ef..784a8746ef 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 e81577cfd4..fd60edfd50 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 677678b243..8fce55f507 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 7c2e72031b..84835bcb93 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 411546a80b..c24a2a8f6a 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 bb7811ce59..d88e19b8ca 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 4a64359aa4..c2df1e6313 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 1f3dc57279..9f40d7c450 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 bffbf75b98..77542d7c04 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 d156b00fa5..c9c72f9d8d 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 b3caf622c3..e1c4966efb 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 88f83fd299..eabd7ada8c 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 99fe0d98cd..f5c9c04615 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 018fd49f6f..0c7d3b3950 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 de5a90c906..45096ecce7 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 1b17f28d5e..7369ed3a00 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 80d0ea08c1..eccc20d59a 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 2eff6ffc78..50cb31d9fb 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 fa0f8a7b2f..dad5fa9c29 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 490847b318..16191e0e7e 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 dc2472e6a6..b400bb4707 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()