Skip to content

Commit 28c6417

Browse files
romtsnclaude
andauthored
fix(replay): Do not recycle the canvas screenshot during a pixel copy (#6342)
* fix(replay): Do not recycle the canvas screenshot during a pixel copy CanvasStrategy.close() recycled the screenshot bitmap and released the surface on the background handler even when a PixelCopy request was still writing into that bitmap on the RenderThread. libhwui then aborted the process with "cannot access an invalid/free'd bitmap". Track the in-flight copy on the background handler, which runs the render task, the copy callback and the cleanup. close() skips the cleanup while a copy is in flight, and the copy callback releases the resources once it sees the strategy is closed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 814ae44 commit 28c6417

4 files changed

Lines changed: 147 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Fixes
66

7+
- Session Replay: Fix a native crash (`SIGABRT` on the RenderThread) when stopping a replay that uses the canvas screenshot strategy ([#6342](https://github.com/getsentry/sentry-java/pull/6342))
78
- Report the number of dropped spans in client reports when a batched span envelope item is discarded, instead of a quantity of 1 (e.g. for Flutter span streaming) ([#6265](https://github.com/getsentry/sentry-java/pull/6265))
89
- Session Replay: Keep the flushed video and do not reuse its segment id when `stop()` is called right after `flush()` in buffer mode ([#6340](https://github.com/getsentry/sentry-java/pull/6340))
910
- Keep sending events from Android 7.1.0 and older devices after Sentry changes its TLS certificate authority ([#6227](https://github.com/getsentry/sentry-java/pull/6227))

‎sentry-android-replay/detekt-baseline.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@
159159
<ID>TooManyFunctions:WindowRecorder.kt$WindowRecorder : RecorderOnRootViewsChangedListenerExecutorProvider</ID>
160160
<ID>UnusedPrivateProperty:DebugOverlayDrawable.kt$DebugOverlayDrawable$private val padding = 6f</ID>
161161
<ID>UseCheckOrError:ReplayShadowMediaCodec.kt$ReplayShadowMediaCodec$throw IllegalStateException("Simulated codec start failure")</ID>
162+
<ID>UtilityClassWithPublicConstructor:CanvasStrategyTest.kt$DeferredSurfacePixelCopyShadow</ID>
162163
<ID>UtilityClassWithPublicConstructor:PixelCopyStrategyTest.kt$DeferredWindowPixelCopyShadow</ID>
163164
</CurrentIssues>
164165
</SmellBaseline>

‎sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ internal class CanvasStrategy(
5858
private val lastCaptureSuccessful = AtomicBoolean(false)
5959
private val textIgnoringCanvas = TextIgnoringDelegateCanvas()
6060
private val isClosed = AtomicBoolean(false)
61+
// Only accessed on the background handler, which runs the render task, the PixelCopy callback and
62+
// the cleanup, so it needs no synchronization
63+
private var pixelCopyInFlight = false
6164

6265
private val surfaceTexture =
6366
SurfaceTexture(false).apply {
@@ -110,15 +113,19 @@ internal class CanvasStrategy(
110113
)
111114
return@Runnable
112115
}
116+
pixelCopyInFlight = true
113117
PixelCopy.request(
114118
surface,
115119
screenshot!!,
116120
{ result ->
121+
pixelCopyInFlight = false
117122
if (isClosed.get()) {
118123
options.logger.log(
119124
SentryLevel.DEBUG,
120125
"CanvasStrategy is closed, ignoring capture result",
121126
)
127+
// close() skipped the cleanup while this copy was still writing into the screenshot
128+
releaseResources()
122129
return@request
123130
}
124131
if (result == PixelCopy.SUCCESS) {
@@ -138,6 +145,8 @@ internal class CanvasStrategy(
138145
executor.getBackgroundHandler(),
139146
)
140147
} catch (t: Throwable) {
148+
// if the request itself threw, no callback will clear the flag
149+
pixelCopyInFlight = false
141150
options.logger.log(SentryLevel.ERROR, "Canvas Strategy: picture render failed", t)
142151
lastCaptureSuccessful.set(false)
143152
}
@@ -174,14 +183,22 @@ internal class CanvasStrategy(
174183
.getBackgroundHandler()
175184
.postSafely(
176185
ReplayRunnable("CanvasStrategy.close") {
177-
screenshot?.let { synchronized(it) { if (!it.isRecycled) it.recycle() } }
178-
surface.release()
179-
surfaceTexture.release()
186+
// PixelCopy writes into the screenshot on the RenderThread; recycling it mid-copy aborts
187+
// the process, so an in-flight copy releases the resources from its callback instead
188+
if (!pixelCopyInFlight) {
189+
releaseResources()
190+
}
180191
}
181192
)
182193
unprocessedPictureRef.getAndSet(null)
183194
}
184195

196+
private fun releaseResources() {
197+
screenshot?.let { synchronized(it) { if (!it.isRecycled) it.recycle() } }
198+
surface.release()
199+
surfaceTexture.release()
200+
}
201+
185202
override fun lastCaptureSuccessful(): Boolean = lastCaptureSuccessful.get()
186203

187204
override fun emitLastScreenshot() {
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package io.sentry.android.replay.screenshot
2+
3+
import android.graphics.Bitmap
4+
import android.os.Handler
5+
import android.os.Looper
6+
import android.view.PixelCopy
7+
import android.view.Surface
8+
import android.view.View
9+
import androidx.test.core.app.ApplicationProvider
10+
import androidx.test.ext.junit.runners.AndroidJUnit4
11+
import com.google.common.truth.Truth.assertThat
12+
import io.sentry.SentryOptions
13+
import io.sentry.android.replay.ExecutorProvider
14+
import io.sentry.android.replay.ScreenshotRecorderConfig
15+
import io.sentry.android.replay.util.MainLooperHandler
16+
import java.util.concurrent.ScheduledExecutorService
17+
import kotlin.test.BeforeTest
18+
import kotlin.test.Test
19+
import org.junit.runner.RunWith
20+
import org.mockito.kotlin.mock
21+
import org.robolectric.Shadows.shadowOf
22+
import org.robolectric.annotation.Config
23+
import org.robolectric.annotation.Implementation
24+
import org.robolectric.annotation.Implements
25+
26+
@RunWith(AndroidJUnit4::class)
27+
@Config(sdk = [30], shadows = [DeferredSurfacePixelCopyShadow::class])
28+
class CanvasStrategyTest {
29+
30+
private class Fixture {
31+
val options = SentryOptions()
32+
val config = ScreenshotRecorderConfig(100, 100, 1f, 1f, 1, 1000)
33+
34+
fun getSut(): CanvasStrategy =
35+
CanvasStrategy(
36+
object : ExecutorProvider {
37+
override fun getExecutor(): ScheduledExecutorService = mock()
38+
39+
override fun getMainLooperHandler(): MainLooperHandler = MainLooperHandler()
40+
41+
// runs the render task, the PixelCopy callback and the cleanup, like production
42+
override fun getBackgroundHandler(): Handler = Handler(Looper.getMainLooper())
43+
},
44+
mock(),
45+
options,
46+
config,
47+
)
48+
}
49+
50+
private val fixture = Fixture()
51+
52+
@BeforeTest
53+
fun setup() {
54+
DeferredSurfacePixelCopyShadow.reset()
55+
}
56+
57+
@Test
58+
fun `close keeps the screenshot alive until the in-flight pixel copy finishes`() {
59+
val strategy = fixture.getSut()
60+
strategy.capture(View(ApplicationProvider.getApplicationContext()))
61+
shadowOf(Looper.getMainLooper()).idle()
62+
val screenshot = DeferredSurfacePixelCopyShadow.dest!!
63+
64+
strategy.close()
65+
shadowOf(Looper.getMainLooper()).idle()
66+
67+
// the copy is still writing into the screenshot, recycling it now would abort the RenderThread
68+
assertThat(screenshot.isRecycled).isFalse()
69+
70+
DeferredSurfacePixelCopyShadow.flush()
71+
shadowOf(Looper.getMainLooper()).idle()
72+
73+
assertThat(screenshot.isRecycled).isTrue()
74+
}
75+
76+
@Test
77+
fun `close recycles the screenshot right away when no pixel copy is in flight`() {
78+
val strategy = fixture.getSut()
79+
strategy.capture(View(ApplicationProvider.getApplicationContext()))
80+
shadowOf(Looper.getMainLooper()).idle()
81+
val screenshot = DeferredSurfacePixelCopyShadow.dest!!
82+
DeferredSurfacePixelCopyShadow.flush()
83+
shadowOf(Looper.getMainLooper()).idle()
84+
85+
strategy.close()
86+
shadowOf(Looper.getMainLooper()).idle()
87+
88+
assertThat(screenshot.isRecycled).isTrue()
89+
}
90+
}
91+
92+
/** Holds back the result of a [PixelCopy] from a [Surface] until [flush] is called. */
93+
@Implements(PixelCopy::class)
94+
class DeferredSurfacePixelCopyShadow {
95+
companion object {
96+
private val pendingCallbacks = mutableListOf<() -> Unit>()
97+
var dest: Bitmap? = null
98+
99+
fun reset() {
100+
pendingCallbacks.clear()
101+
dest = null
102+
}
103+
104+
fun flush() {
105+
val callbacks = pendingCallbacks.toList()
106+
pendingCallbacks.clear()
107+
callbacks.forEach { it.invoke() }
108+
}
109+
110+
@JvmStatic
111+
@Implementation
112+
@Suppress("UNUSED_PARAMETER")
113+
fun request(
114+
source: Surface,
115+
dest: Bitmap,
116+
listener: PixelCopy.OnPixelCopyFinishedListener,
117+
listenerThread: Handler,
118+
) {
119+
this.dest = dest
120+
pendingCallbacks.add {
121+
listenerThread.post { listener.onPixelCopyFinished(PixelCopy.SUCCESS) }
122+
}
123+
}
124+
}
125+
}

0 commit comments

Comments
 (0)