Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,20 @@ public final class io/sentry/android/core/NetworkBreadcrumbsIntegration : io/sen
public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
}

public final class io/sentry/android/core/NonFatalAnrHint : io/sentry/hints/DiskFlushNotification {
public fun <init> (ZLjava/lang/Runnable;)V
public fun isFlushable (Lio/sentry/protocol/SentryId;)Z
public fun isMainThreadBlocked ()Z
public fun markFlushed ()V
public fun setFlushable (Lio/sentry/protocol/SentryId;)V
}

public final class io/sentry/android/core/NonFatalAnrIntegration : io/sentry/Integration, java/io/Closeable {
public fun <init> ()V
public fun close ()V
public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
}

public final class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver {
public fun <init> (Lio/sentry/ILogger;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Ljava/util/function/Supplier;)V
public fun close (Z)V
Expand Down Expand Up @@ -450,6 +464,8 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun getNativeSdkName ()Ljava/lang/String;
public fun getNdkAppHangTimeoutIntervalMillis ()J
public fun getNdkHandlerStrategy ()I
public fun getNonFatalAnrSampleRate ()Ljava/lang/Double;
public fun getNonFatalAnrThresholdMs ()J
public fun getScreenshot ()Lio/sentry/android/core/SentryScreenshotOptions;
public fun getStartupCrashDurationThresholdMillis ()J
public fun getTombstoneMergeTimeThresholdMillis ()J
Expand Down Expand Up @@ -521,6 +537,8 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun setNativeHandlerStrategy (Lio/sentry/android/core/NdkHandlerStrategy;)V
public fun setNativeSdkName (Ljava/lang/String;)V
public fun setNdkAppHangTimeoutIntervalMillis (J)V
public fun setNonFatalAnrSampleRate (Ljava/lang/Double;)V
public fun setNonFatalAnrThresholdMs (J)V
public fun setReportHistoricalAnrs (Z)V
public fun setReportHistoricalMemoryLimiterExits (Z)V
public fun setReportHistoricalTombstones (Z)V
Expand Down Expand Up @@ -789,6 +807,14 @@ public final class io/sentry/android/core/anr/AnrStackTrace : java/lang/Comparab
public fun serialize (Ljava/io/DataOutputStream;)V
}

public final class io/sentry/android/core/anr/NonFatalAnrMarker {
public static final field FILE_NAME Ljava/lang/String;
public static fun delete (Lio/sentry/SentryOptions;)V
public fun matches (IJ)Z
public static fun read (Lio/sentry/SentryOptions;)Lio/sentry/android/core/anr/NonFatalAnrMarker;
public static fun write (Lio/sentry/SentryOptions;IJJ)V
}

public final class io/sentry/android/core/anr/StackTraceConverter {
public fun <init> ()V
public static fun convert (Lio/sentry/android/core/anr/AnrProfile;)Lio/sentry/protocol/profiling/SentryProfile;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,10 @@ static void installDefaultIntegrations(
options.addIntegration(AnrIntegrationFactory.create(context, buildInfoProvider));

options.addIntegration(new AnrProfilingIntegration());
// Below API 30, AnrIntegration reports the same hangs, and nothing reads the marker.
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.R) {
options.addIntegration(new NonFatalAnrIntegration());
}

// registerActivityLifecycleCallbacks is only available if Context is an AppContext
if (context instanceof Application) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ final class ManifestMetadataReader {
static final String SCREENSHOT_MASK_ALL_IMAGES = "io.sentry.screenshot.mask-all-images";

static final String ANR_PROFILING_SAMPLE_RATE = "io.sentry.anr.profiling.sample-rate";
static final String NON_FATAL_ANR_SAMPLE_RATE = "io.sentry.anr.non-fatal.sample-rate";
static final String NON_FATAL_ANR_THRESHOLD_MS = "io.sentry.anr.non-fatal.threshold-ms";

static final String ENABLE_ANR_FINGERPRINTING = "io.sentry.anr.enable-fingerprinting";

Expand Down Expand Up @@ -825,6 +827,20 @@ static void applyMetadata(
}
}

if (options.getNonFatalAnrSampleRate() == null) {
final double nonFatalAnrSampleRate =
readDouble(metadata, logger, NON_FATAL_ANR_SAMPLE_RATE);
if (nonFatalAnrSampleRate != -1) {
options.setNonFatalAnrSampleRate(nonFatalAnrSampleRate);
}
}

final long nonFatalAnrThresholdMs =
readLong(metadata, logger, NON_FATAL_ANR_THRESHOLD_MS, -1);
if (nonFatalAnrThresholdMs != -1) {
options.setNonFatalAnrThresholdMs(nonFatalAnrThresholdMs);
}

options.setEnableAnrFingerprinting(
readBool(
metadata, logger, ENABLE_ANR_FINGERPRINTING, options.isEnableAnrFingerprinting()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package io.sentry.android.core;

import io.sentry.hints.DiskFlushNotification;
import io.sentry.protocol.SentryId;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Type-check hint of non-fatal ANR events. Of the {@code io.sentry.hints} interfaces it implements
* only {@link DiskFlushNotification}, so the session is not ended as abnormal for it.
*/
@ApiStatus.Internal
public final class NonFatalAnrHint implements DiskFlushNotification {

private final boolean mainThreadBlocked;
private final @Nullable Runnable onStoredOnDisk;
private final @NotNull AtomicBoolean flushed = new AtomicBoolean(false);

/**
* @param onStoredOnDisk runs once, on the transport thread, after the envelope of the event was
* stored on disk. The transport also calls it when a rate limit drops the event. Null if the
* event needs no action on disk.
*/
public NonFatalAnrHint(final boolean mainThreadBlocked, final @Nullable Runnable onStoredOnDisk) {
this.mainThreadBlocked = mainThreadBlocked;
this.onStoredOnDisk = onStoredOnDisk;
}

/**
* Whether the main thread is still blocked when the event is captured, because the hang was cut
* at the maximum recording time. Anything that waits for the main thread must then skip its work.
*/
public boolean isMainThreadBlocked() {
return mainThreadBlocked;
}

@Override
public void markFlushed() {
if (onStoredOnDisk != null && flushed.compareAndSet(false, true)) {
onStoredOnDisk.run();
}
}

@Override
public boolean isFlushable(final @Nullable SentryId eventId) {
return true;
}

@Override
public void setFlushable(final @NotNull SentryId eventId) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
package io.sentry.android.core;

import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion;

import android.os.Looper;
import android.os.Process;
import io.sentry.Breadcrumb;
import io.sentry.DateUtils;
import io.sentry.ILogger;
import io.sentry.IScopes;
import io.sentry.Integration;
import io.sentry.SentryEvent;
import io.sentry.SentryExceptionFactory;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.SentryStackTraceFactory;
import io.sentry.android.core.anr.AggregatedStackTrace;
import io.sentry.android.core.anr.AnrCulpritEventHelper;
import io.sentry.android.core.anr.AnrCulpritIdentifier;
import io.sentry.android.core.anr.AnrStackTrace;
import io.sentry.android.core.anr.NonFatalAnrMarker;
import io.sentry.android.core.hang.HangRecord;
import io.sentry.android.core.hang.HangRecorder;
import io.sentry.android.core.hang.HangRecorderListener;
import io.sentry.android.core.internal.util.AndroidThreadChecker;
import io.sentry.protocol.Mechanism;
import io.sentry.protocol.SentryException;
import io.sentry.protocol.SentryThread;
import io.sentry.util.HintUtils;
import io.sentry.util.Objects;
import io.sentry.util.SentryRandom;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Reports main-thread hangs as non-fatal ANR events: hangs that recover, before or after Android
* shows the ANR dialog, and hangs that still block the main thread after 8 s, which are cut there.
*
* <p>If sampled, subscribes to the {@link HangRecorder} of the options for the SDK lifetime.
* Installed from Android 11 (API 30), where {@link AnrV2Integration} skips the fatal ANRs that this
* integration already reported.
*
* <p>Enable via {@link SentryAndroidOptions#setNonFatalAnrSampleRate(Double)} or the {@code
* io.sentry.anr.non-fatal.sample-rate} manifest metadata.
*/
@ApiStatus.Internal
public final class NonFatalAnrIntegration implements Integration, Closeable {

/**
* Android reports an input ANR after 5 s at the earliest, so a shorter hang cannot be a fatal ANR
* and gets no marker.
*/
static final long MIN_FATAL_ANR_DURATION_MS = 5_000;

private final @NotNull AtomicReference<HangRecorder> subscribedRecorder = new AtomicReference<>();
private final @NotNull AtomicReference<HangRecorderListener> subscription =
new AtomicReference<>();

@Override
public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) {
final @NotNull SentryAndroidOptions androidOptions =
Objects.requireNonNull(
(options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
"SentryAndroidOptions is required");
if (!androidOptions.isAnrEnabled() || !androidOptions.isNonFatalAnrEnabled()) {
return;
}
final @NotNull ILogger logger = options.getLogger();
final @Nullable HangRecorder recorder = androidOptions.getHangRecorder();
if (recorder == null) {
logger.log(SentryLevel.WARNING, "Non-fatal ANR is enabled but there is no hang recorder");
return;
}
final @Nullable Double sampleRate = androidOptions.getNonFatalAnrSampleRate();
if (sampleRate == null || SentryRandom.current().nextDouble() >= sampleRate) {
logger.log(SentryLevel.DEBUG, "Non-fatal ANR is not sampled");
return;
}
if (!subscribedRecorder.compareAndSet(null, recorder)) {
return;
}
final @NotNull HangRecorderListener listener = new Reporter(scopes, androidOptions);
subscription.set(listener);
recorder.subscribe(listener);
addIntegrationToSdkVersion("NonFatalAnr");
}

@Override
public void close() throws IOException {
final @Nullable HangRecorder recorder = subscribedRecorder.getAndSet(null);
final @Nullable HangRecorderListener listener = subscription.getAndSet(null);
if (recorder != null && listener != null) {
recorder.unsubscribe(listener);
}
}

private static final class Reporter implements HangRecorderListener {

private final @NotNull IScopes scopes;
private final @NotNull SentryAndroidOptions options;
private final @NotNull AnrCulpritEventHelper culpritEventHelper;

Reporter(final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) {
this.scopes = scopes;
this.options = options;
this.culpritEventHelper =
new AnrCulpritEventHelper(
new SentryExceptionFactory(new SentryStackTraceFactory(options)));
}

@Override
public void onHangRecorded(final @NotNull HangRecord record) {
if (record.getDurationMs() < options.getNonFatalAnrThresholdMs()) {
return;
}
final long startTimestampMs = record.getStartTimestampMs();
final long endTimestampMs = startTimestampMs + record.getDurationMs();

// Only once the event is on disk: a kill before that must not suppress the fatal ANR.
final @Nullable Runnable writeMarker;
if (record.hasEndedAtMaxRecordingTime()
|| record.getDurationMs() >= MIN_FATAL_ANR_DURATION_MS) {
final int pid = Process.myPid();
writeMarker = () -> NonFatalAnrMarker.write(options, pid, startTimestampMs, endTimestampMs);
} else {
writeMarker = null;
}

final @NotNull SentryEvent event = buildEvent(record, endTimestampMs);
scopes.captureEvent(
event,
HintUtils.createWithTypeCheckHint(
new NonFatalAnrHint(record.hasEndedAtMaxRecordingTime(), writeMarker)));

final @NotNull Breadcrumb breadcrumb = new Breadcrumb();
breadcrumb.setCategory("anr");
breadcrumb.setType("error");
breadcrumb.setLevel(SentryLevel.WARNING);
breadcrumb.setMessage("Non-fatal ANR");
breadcrumb.setData("duration_ms", record.getDurationMs());
scopes.addBreadcrumb(breadcrumb);
}

private @NotNull SentryEvent buildEvent(
final @NotNull HangRecord record, final long endTimestampMs) {
final @NotNull List<AnrStackTrace> samples = record.getSamples();
final @Nullable AggregatedStackTrace culprit =
samples.isEmpty() ? null : AnrCulpritIdentifier.identify(samples);

final @NotNull Mechanism mechanism = new Mechanism();
mechanism.setType("NonFatalANR");
mechanism.setHandled(true);

@Nullable
List<SentryException> exceptions =
culprit == null ? null : culpritEventHelper.toSentryExceptions(culprit, mechanism);
if (exceptions == null) {
final @NotNull SentryException exception = new SentryException();
exception.setType(ApplicationNotResponding.class.getName());
exception.setValue("Non-fatal ANR");
exception.setMechanism(mechanism);
exceptions = Arrays.asList(exception);
}
final long mainThreadId =
AndroidThreadChecker.getThreadId(Looper.getMainLooper().getThread());
for (final @NotNull SentryException exception : exceptions) {
exception.setThreadId(mainThreadId);
}

final @NotNull SentryEvent event = new SentryEvent(DateUtils.getDateTime(endTimestampMs));
event.setLevel(SentryLevel.ERROR);
event.setExceptions(exceptions);
event.setThreads(Arrays.asList(mainThread(mainThreadId, samples, culprit, exceptions)));

final @NotNull Map<String, Object> context = new HashMap<>();
context.put("duration_ms", record.getDurationMs());
context.put("sample_count", samples.size());
event.getContexts().put("non_fatal_anr", context);

if (event.getFingerprints() == null) {
if (options.isEnableAnrFingerprinting()
&& AnrCulpritEventHelper.hasOnlySystemFrames(exceptions)) {
event.setFingerprints(Arrays.asList("system-frames-only-anr", "non-fatal-anr"));
} else {
event.setFingerprints(Arrays.asList("{{ default }}", "non-fatal-anr"));
}
}
return event;
}

private static @NotNull SentryThread mainThread(
final long mainThreadId,
final @NotNull List<AnrStackTrace> samples,
final @Nullable AggregatedStackTrace culprit,
final @NotNull List<SentryException> exceptions) {
final @NotNull SentryThread thread = new SentryThread();
thread.setId(mainThreadId);
thread.setName("main");
thread.setCurrent(true);
thread.setMain(true);
final @Nullable Thread.State state = culpritState(samples, culprit);
if (state != null) {
thread.setState(state.name());
}
if (culprit != null) {
thread.setStacktrace(exceptions.get(0).getStacktrace());
}
return thread;
}

private static @Nullable Thread.State culpritState(
final @NotNull List<AnrStackTrace> samples, final @Nullable AggregatedStackTrace culprit) {
if (samples.isEmpty()) {
return null;
}
if (culprit != null) {
final @NotNull StackTraceElement[] culpritStack = culprit.getStack();
for (int i = samples.size() - 1; i >= 0; i--) {
if (containsRun(samples.get(i).stack, culpritStack)) {
return samples.get(i).state;
}
}
}
return samples.get(samples.size() - 1).state;
}

private static boolean containsRun(
final @NotNull StackTraceElement[] stack, final @NotNull StackTraceElement[] run) {
for (int start = 0; start + run.length <= stack.length; start++) {
int offset = 0;
while (offset < run.length && stack[start + offset].equals(run[offset])) {
offset++;
}
if (offset == run.length) {
return true;
}
}
return false;
}
}
}
Loading
Loading