Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import io.sentry.ndk.INativeScope;
import io.sentry.ndk.NativeScope;
import io.sentry.protocol.User;
import io.sentry.util.ExceptionUtils;
import io.sentry.util.Objects;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -81,6 +82,10 @@ public void addBreadcrumb(final @NotNull Breadcrumb crumb) {
data = options.getSerializer().serialize(dataRef);
}
} catch (Throwable e) {
// The data can hold any object the app put there, and the serializer reads it
// reflectively, so we can't know what it throws. The breadcrumb is synced to the
// native scope without its data.
ExceptionUtils.rethrowIfFatal(e);
options.getLogger().log(SentryLevel.ERROR, e, "Breadcrumb data is not serializable.");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public static void init(
throw new IllegalStateException("Timeout waiting for Sentry NDK library to load");
}
} catch (InterruptedException e) {
// we don't own the calling thread, so keep its interrupt for the code that does
Thread.currentThread().interrupt();
throw new IllegalStateException(
"Thread interrupted while waiting for NDK libs to be loaded", e);
}
Expand All @@ -116,6 +118,8 @@ public static void close() {
throw new IllegalStateException("Timeout waiting for Sentry NDK library to load");
}
} catch (InterruptedException e) {
// we don't own the calling thread, so keep its interrupt for the code that does
Thread.currentThread().interrupt();
throw new IllegalStateException(
"Thread interrupted while waiting for NDK libs to be loaded", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.sentry.android.ndk
import io.sentry.android.core.SentryAndroidOptions
import io.sentry.ndk.NdkOptions
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
Expand Down Expand Up @@ -96,4 +97,34 @@ class SentryNdkTest {
assertEquals(2000L, fixture.capturedOptions!!.appHangTimeoutMillis)
}
}

@Test
fun `init keeps the interrupt when interrupted while waiting for the native libraries`() {
val options =
SentryAndroidOptions().apply {
dsn = "https://key@sentry.io/proj"
cacheDirPath = "/cache"
}

// CountDownLatch.await checks the interrupt before the count, so this throws right away
Thread.currentThread().interrupt()
try {
assertFailsWith<IllegalStateException> { SentryNdk.init(options) }
assertTrue(Thread.currentThread().isInterrupted)
} finally {
// don't leak the interrupt into other tests
Thread.interrupted()
}
}

@Test
fun `close keeps the interrupt when interrupted while waiting for the native libraries`() {
Thread.currentThread().interrupt()
try {
assertFailsWith<IllegalStateException> { SentryNdk.close() }
assertTrue(Thread.currentThread().isInterrupted)
} finally {
Thread.interrupted()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryId
import io.sentry.rrweb.RRWebEvent
import io.sentry.util.AutoClosableReentrantLock
import io.sentry.util.ExceptionUtils
import io.sentry.util.FileUtils
import java.io.Closeable
import java.io.File
Expand Down Expand Up @@ -232,6 +233,9 @@ public class ReplayCache(private val options: SentryOptions, private val replayI
bitmap.recycle()
true
} catch (e: Throwable) {
// The encoder goes through the device's MediaCodec, so we can't know what it throws. The
// frame is left out of the video.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(
WARNING,
"Unable to decode bitmap and encode it into a video, skipping frame",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import io.sentry.protocol.SentryId
import io.sentry.transport.ICurrentDateProvider
import io.sentry.transport.RateLimiter
import io.sentry.transport.RateLimiter.IRateLimitObserver
import io.sentry.util.ExceptionUtils
import io.sentry.util.FileUtils
import io.sentry.util.HintUtils
import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion
Expand Down Expand Up @@ -487,6 +488,9 @@ public class ReplayIntegration(
hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy)
observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen)
} catch (e: Throwable) {
// The observer is the app's own code, so we can't know what it throws. The copy is
// recycled and the frame is still recorded.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(ERROR, "Error in ReplayFrameObserver", e)
copy.recycle()
}
Expand All @@ -510,6 +514,9 @@ public class ReplayIntegration(
hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, bitmap)
observer.onMaskedFrameCaptured(hint, frameTimestamp, screen)
} catch (e: Throwable) {
// The observer is the app's own code, so we can't know what it throws. The bitmap is
// recycled and the frame is still recorded.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(ERROR, "Error in ReplayFrameObserver", e)
bitmap.recycle()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import io.sentry.android.replay.screenshot.ScreenshotStrategy
import io.sentry.android.replay.util.DebugOverlayDrawable
import io.sentry.android.replay.util.addOnDrawListenerSafe
import io.sentry.android.replay.util.removeOnDrawListenerSafe
import io.sentry.util.ExceptionUtils
import java.io.File
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicBoolean
Expand Down Expand Up @@ -92,6 +93,9 @@ internal class ScreenshotRecorder(
contentChanged.set(false)
screenshotStrategy.capture(root)
} catch (e: Throwable) {
// Capturing draws the app's own views and goes through the device's graphics stack, so we
// can't know what it throws. The frame is skipped.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(WARNING, "Failed to capture replay recording", e)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import io.sentry.android.replay.util.addOnPreDrawListenerSafe
import io.sentry.android.replay.util.hasSize
import io.sentry.android.replay.util.removeOnPreDrawListenerSafe
import io.sentry.util.AutoClosableReentrantLock
import io.sentry.util.ExceptionUtils
import java.lang.ref.WeakReference
import java.util.WeakHashMap
import java.util.concurrent.ScheduledExecutorService
Expand Down Expand Up @@ -96,6 +97,9 @@ internal class WindowRecorder(
}
recorder?.capture()
} catch (e: Throwable) {
// Capturing draws the app's own views and goes through the device's graphics stack, so we
// can't know what it throws. This frame is skipped, and the next one is still scheduled.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(ERROR, "Failed to capture a frame", e)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import io.sentry.time.Deadline
import io.sentry.time.MonotonicTicker
import io.sentry.transport.ICurrentDateProvider
import java.io.File
import java.io.IOException
import java.util.Date
import java.util.Deque
import java.util.concurrent.ConcurrentLinkedDeque
Expand Down Expand Up @@ -260,9 +261,13 @@ constructor(
if (options.threadChecker.isMainThread) {
persistingExecutor.submit(ReplayRunnable("$TAG.runInBackground") { task() })
} else {
// every task ends in ReplayCache.persistSegmentValues, which writes the segment file
try {
task()
} catch (e: Throwable) {
} catch (e: IOException) {
options.logger.log(ERROR, "Failed to execute task $TAG.runInBackground", e)
} catch (@Suppress("TooGenericExceptionCaught") e: IndexOutOfBoundsException) {
// a line of the segment file has no "=", so the file is corrupt
options.logger.log(ERROR, "Failed to execute task $TAG.runInBackground", e)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import io.sentry.android.replay.OnRootViewsChangedListener
import io.sentry.android.replay.phoneWindow
import io.sentry.android.replay.util.FixedWindowCallback
import io.sentry.util.AutoClosableReentrantLock
import io.sentry.util.ExceptionUtils
import java.lang.ref.WeakReference
import java.util.WeakHashMap

Expand Down Expand Up @@ -99,6 +100,10 @@ internal class GestureRecorder(
try {
touchRecorderCallback?.onTouchEvent(copy)
} catch (e: Throwable) {
// This runs inside the app's touch dispatch, so a failure while recording the gesture
// must not cost the app its touch. The gesture is missing from the replay, and the touch
// still reaches the app below.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(ERROR, "Error dispatching touch event", e)
} finally {
copy.recycle()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import io.sentry.android.replay.ScreenshotRecorderCallback
import io.sentry.android.replay.ScreenshotRecorderConfig
import io.sentry.android.replay.util.ReplayRunnable
import io.sentry.util.AutoClosableReentrantLock
import io.sentry.util.ExceptionUtils
import io.sentry.util.IntegrationUtils
import java.util.WeakHashMap
import java.util.concurrent.atomic.AtomicBoolean
Expand Down Expand Up @@ -144,6 +145,9 @@ internal class CanvasStrategy(
executor.getBackgroundHandler(),
)
} catch (t: Throwable) {
// Drawing into the hardware surface and PixelCopy go through the device's graphics stack,
// so we can't know what they throw. The frame is skipped.
ExceptionUtils.rethrowIfFatal(t)
// if the request itself threw, no callback will clear the flag
pixelCopyInFlight = false
options.logger.log(SentryLevel.ERROR, "Canvas Strategy: picture render failed", t)
Expand Down Expand Up @@ -209,13 +213,11 @@ internal class CanvasStrategy(
}

fun Handler.postSafely(runnable: ReplayRunnable) {
try {
post(runnable)
} catch (t: Throwable) {
// post() doesn't throw, it returns false when the handler thread's looper is quitting
if (!post(runnable)) {
options.logger.log(
SentryLevel.ERROR,
"Canvas Strategy: failed to post runnable ${runnable.taskName}",
t,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import io.sentry.android.replay.util.MaskRenderer
import io.sentry.android.replay.util.ReplayRunnable
import io.sentry.android.replay.util.traverse
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode
import io.sentry.util.ExceptionUtils
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.LazyThreadSafetyMode.NONE
Expand Down Expand Up @@ -177,6 +178,9 @@ internal class PixelCopyStrategy(
mainLooperHandler.handler,
)
} catch (e: Throwable) {
// PixelCopy goes through the device's graphics stack, so we can't know what it throws. The
// frame is skipped, and the frame gate is released for the next one.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(WARNING, "Failed to capture replay recording", e)
unstableCaptures.set(0)
lastCaptureSuccessful.set(false)
Expand Down Expand Up @@ -294,6 +298,9 @@ internal class PixelCopyStrategy(
// double-recycle if the recycle paths above already ran.
svBitmap = null
} catch (e: Throwable) {
// PixelCopy goes through the device's graphics stack, so we can't know what it throws.
// This SurfaceView is left out of the frame.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(WARNING, "Failed to capture SurfaceView", e)
svBitmap?.recycle()
onCaptureComplete()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.sentry.android.replay.util
import io.sentry.ISentryExecutorService
import io.sentry.SentryLevel.ERROR
import io.sentry.SentryOptions
import io.sentry.util.ExceptionUtils
import java.util.concurrent.Future

internal fun ISentryExecutorService.submitSafely(
Expand All @@ -15,6 +16,10 @@ internal fun ISentryExecutorService.submitSafely(
try {
task.run()
} catch (e: Throwable) {
// The tasks decode frames and encode video through the device's media stack, so we can't
// know what they throw. The failure is logged here because nobody reads the returned
// future, and the task's work is lost.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(ERROR, "Failed to execute task $taskName", e)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package io.sentry.android.replay.util

import io.sentry.SentryLevel.ERROR
import io.sentry.SentryOptions
import io.sentry.util.ExceptionUtils
import java.util.concurrent.Future
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
Expand Down Expand Up @@ -35,6 +36,10 @@ internal class ReplayExecutorService(
try {
task.run()
} catch (e: Throwable) {
// Replay's tasks mask frames, write the cache, and encode video through the device's
// graphics and media stacks, so we can't know what they throw. The failure is logged
// here because nobody reads the returned future, and that task's work is lost.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(
ERROR,
"Failed to execute task ${if (task is ReplayRunnable) task.taskName else ""}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import io.sentry.SentryLevel.DEBUG
import io.sentry.SentryLevel.WARNING
import io.sentry.SentryOptions
import io.sentry.android.replay.util.SystemProperties
import io.sentry.util.ExceptionUtils
import java.io.File
import java.nio.ByteBuffer
import kotlin.LazyThreadSafetyMode.NONE
Expand Down Expand Up @@ -100,6 +101,9 @@ internal class SimpleVideoEncoder(
bitRate = videoCapabilities.bitrateRange.clamp(bitRate)
}
} catch (e: Throwable) {
// The codec's capabilities come from the device's media framework, so we can't know what
// it throws. The bit rate is used without clamping it to the supported range.
ExceptionUtils.rethrowIfFatal(e)
options.logger.log(DEBUG, "Could not retrieve MediaCodec info", e)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import io.sentry.time.TestMonotonicTicker
import io.sentry.transport.CurrentDateProvider
import io.sentry.transport.ICurrentDateProvider
import java.io.File
import java.io.IOException
import java.util.Date
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit.MILLISECONDS
Expand Down Expand Up @@ -170,6 +171,20 @@ class SessionCaptureStrategyTest {
assertEquals(0, strategy.currentSegment)
}

@Test
fun `start does not fail when the segment values can't be written`() {
doAnswer { throw IOException("disk full") }
.whenever(fixture.replayCache)
.persistSegmentValues(any(), anyOrNull())
val strategy = fixture.getSut()
val replayId = SentryId()

strategy.start(0, replayId)

assertEquals(replayId, strategy.currentReplayId)
assertEquals(0, strategy.currentSegment)
}

@Test
fun `start persists the recording metadata`() {
fixture.options.release = "io.sentry.sample@1.0.0+1"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteDriver
import io.sentry.ScopesAdapter
import io.sentry.SentryLevel
import io.sentry.util.ExceptionUtils
import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion

/**
Expand Down Expand Up @@ -53,19 +54,31 @@ public class SentrySQLiteDriver private constructor(private val delegate: SQLite
// create() ensures delegate is unwrapped, so we don't need to protect against double-wrapping
// the connection.
SentrySQLiteConnection(connection, spans)
} catch (e: LinkageError) {
// androidx.sqlite is compileOnly, so the app's version may not match the SQLiteConnection
// that SentrySQLiteConnection implements. The connection is returned uninstrumented.
logInstrumentationFailure(e)
connection
} catch (t: Throwable) {
ScopesAdapter.getInstance()
.options
.logger
.log(
SentryLevel.ERROR,
"Failed to instrument SQLite connection; returning uninstrumented connection.",
t,
)
// Instrumenting must never stop the app from opening its database, so any other failure
// also returns the connection uninstrumented.
ExceptionUtils.rethrowIfFatal(t)
logInstrumentationFailure(t)
connection
}
}

private fun logInstrumentationFailure(t: Throwable) {
ScopesAdapter.getInstance()
.options
.logger
.log(
SentryLevel.ERROR,
"Failed to instrument SQLite connection; returning uninstrumented connection.",
t,
)
}

public companion object {

/**
Expand Down
Loading
Loading