Skip to content

Commit f532ea3

Browse files
committed
fix(android): Start the NDK crash service without waiting for it
`SentryNdkCrashService.start` waited up to 10 s for the service to connect and configure, on the thread that calls `SentryAndroid.init`, usually the main thread. It now hands the app's ends to native right away, and the service takes its ends when it connects. If it doesn't connect within 10 s, its ends are closed so that native sends and the crash handler fail at once, and a later connection reattaches. Native init in sentry-native 1.0.0-beta.1 still waits for the daemon.
1 parent 4970543 commit f532ea3

2 files changed

Lines changed: 145 additions & 44 deletions

File tree

‎sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java‎

Lines changed: 86 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import android.os.RemoteException;
1818
import io.sentry.DateUtils;
1919
import io.sentry.ILogger;
20+
import io.sentry.ISentryExecutorService;
2021
import io.sentry.SentryEnvelope;
2122
import io.sentry.SentryEnvelopeItem;
2223
import io.sentry.SentryEvent;
@@ -42,8 +43,9 @@
4243
import java.util.ArrayList;
4344
import java.util.Date;
4445
import java.util.List;
45-
import java.util.concurrent.CountDownLatch;
46+
import java.util.concurrent.RejectedExecutionException;
4647
import java.util.concurrent.TimeUnit;
48+
import java.util.concurrent.atomic.AtomicBoolean;
4749
import org.jetbrains.annotations.ApiStatus;
4850
import org.jetbrains.annotations.NotNull;
4951
import org.jetbrains.annotations.Nullable;
@@ -58,6 +60,7 @@ public final class SentryNdkCrashService extends Service {
5860
private static final @NotNull String MERGED_SUFFIX = ".merged";
5961
private static final long POLL_INTERVAL_MILLIS = 250;
6062
private static final long MATCH_TOLERANCE_MILLIS = 30000;
63+
private static final long CONNECT_TIMEOUT_MILLIS = 10000;
6164

6265
private final @NotNull IBinder binder =
6366
new Binder() {
@@ -150,6 +153,7 @@ protected boolean onTransact(
150153
ParcelFileDescriptor readyWrite = null;
151154
ParcelFileDescriptor messageWrite = null;
152155
ParcelFileDescriptor messageRead = null;
156+
@Nullable ServiceEnds ends = null;
153157
try {
154158
final ParcelFileDescriptor[] notifyPipe = ParcelFileDescriptor.createPipe();
155159
final ParcelFileDescriptor[] readyPipe = ParcelFileDescriptor.createPipe();
@@ -160,42 +164,45 @@ protected boolean onTransact(
160164
final ParcelFileDescriptor[] messageSocket = ParcelFileDescriptor.createSocketPair();
161165
messageWrite = messageSocket[0];
162166
messageRead = messageSocket[1];
167+
ends = new ServiceEnds(shm.dup(), notifyRead, readyWrite, messageRead);
168+
notifyRead = null;
169+
readyWrite = null;
170+
messageRead = null;
163171

164172
final Intent intent = new Intent(context, SentryNdkCrashService.class);
165173
final @Nullable ServiceConnection connection =
166174
configureService(
167175
context,
168176
intent,
169177
options.getLogger(),
178+
options.getExecutorService(),
170179
nativeDatabaseDir.getPath(),
171180
context.getApplicationInfo().nativeLibraryDir,
172-
shm,
173181
Process.myPid(),
174182
Process.myTid(),
175183
options.isTombstoneEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S,
176184
options.isDebug(),
177185
options.getShutdownTimeoutMillis(),
178186
new ArrayList<>(options.getInAppIncludes()),
179187
new ArrayList<>(options.getInAppExcludes()),
180-
notifyRead,
181-
readyWrite,
182-
messageRead);
188+
ends);
189+
ends = null;
183190
if (connection == null) {
184-
options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not configure.");
191+
options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not bind.");
185192
return null;
186193
}
187194

195+
// the daemon attaches once the service connects
188196
io.sentry.ndk.SentryNdk.initCrashDaemon(
189197
shm.detachFd(), notifyWrite.detachFd(), readyRead.detachFd(), messageWrite.detachFd());
190198
return connection;
191-
} catch (InterruptedException e) {
192-
Thread.currentThread().interrupt();
193-
options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service.");
194-
return null;
195199
} catch (IOException | SecurityException e) {
196200
options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service.");
197201
return null;
198202
} finally {
203+
if (ends != null) {
204+
ends.close();
205+
}
199206
closeQuietly(shm);
200207
closeQuietly(notifyRead);
201208
closeQuietly(notifyWrite);
@@ -225,34 +232,29 @@ private static void closeQuietly(final @Nullable Closeable closeable) {
225232
final @NotNull Context context,
226233
final @NotNull Intent intent,
227234
final @NotNull ILogger logger,
235+
final @NotNull ISentryExecutorService executorService,
228236
final @NotNull String nativeDatabasePath,
229237
final @Nullable String nativeLibraryDir,
230-
final @NotNull ParcelFileDescriptor shm,
231238
final int appPid,
232239
final long appTid,
233240
final boolean tombstoneEnabled,
234241
final boolean debug,
235242
final long shutdownTimeoutMillis,
236243
final @NotNull ArrayList<String> includes,
237244
final @NotNull ArrayList<String> excludes,
238-
final @NotNull ParcelFileDescriptor notifyRead,
239-
final @NotNull ParcelFileDescriptor readyWrite,
240-
final @NotNull ParcelFileDescriptor messageRead)
241-
throws InterruptedException {
242-
final CountDownLatch latch = new CountDownLatch(1);
243-
final boolean[] configured = new boolean[] {false};
245+
final @NotNull ServiceEnds ends) {
244246
// a foreground app raises the service process only to visible without BIND_IMPORTANT
245247
final int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;
246248

247249
final ServiceConnection connection =
248250
new ServiceConnection() {
249-
private boolean connected;
251+
private volatile boolean configured;
250252

251253
@Override
252254
public void onServiceConnected(
253255
final @NotNull ComponentName name, final @NotNull IBinder service) {
254-
if (connected) {
255-
// a restarted service process has no daemon for this app
256+
if (!ends.take()) {
257+
// a restarted or late service process has no daemon for this app
256258
reattach(
257259
service,
258260
logger,
@@ -267,57 +269,70 @@ public void onServiceConnected(
267269
excludes);
268270
return;
269271
}
270-
connected = true;
271-
configured[0] =
272+
configured =
272273
transactConfigure(
273274
service,
274275
nativeDatabasePath,
275276
nativeLibraryDir,
276-
shm,
277+
ends.shm,
277278
appPid,
278279
appTid,
279280
tombstoneEnabled,
280281
debug,
281282
shutdownTimeoutMillis,
282283
includes,
283284
excludes,
284-
notifyRead,
285-
readyWrite,
286-
messageRead);
287-
latch.countDown();
285+
ends.notifyRead,
286+
ends.readyWrite,
287+
ends.messageRead);
288+
ends.close();
289+
if (!configured) {
290+
logger.log(SentryLevel.ERROR, "NDK crash service did not configure.");
291+
}
288292
}
289293

290294
@Override
291295
public void onServiceDisconnected(final @NotNull ComponentName name) {
292296
logger.log(SentryLevel.ERROR, "NDK crash service disconnected.");
293-
latch.countDown();
294297
}
295298

296299
@Override
297300
public void onBindingDied(final @NotNull ComponentName name) {
298301
logger.log(SentryLevel.ERROR, "NDK crash service binding died.");
299-
latch.countDown();
300302
// a dead binding does not reconnect, it must be bound again
301-
if (configured[0]) {
303+
if (configured) {
302304
context.unbindService(this);
303305
bind(context, intent, flags, this);
304306
}
305307
}
306308
};
307309

308-
if (!bind(context, intent, flags, connection)) {
309-
return null;
310-
}
311-
boolean ready = false;
310+
boolean bound = false;
312311
try {
313-
ready = latch.await(10000, TimeUnit.MILLISECONDS) && configured[0];
314-
// stay bound, so the service process keeps the app's importance and is not frozen
315-
return ready ? connection : null;
312+
bound = bind(context, intent, flags, connection);
316313
} finally {
317-
if (!ready) {
318-
context.unbindService(connection);
314+
if (!bound) {
315+
ends.close();
319316
}
320317
}
318+
if (!bound) {
319+
return null;
320+
}
321+
try {
322+
executorService.schedule(
323+
() -> {
324+
if (ends.take()) {
325+
// without a reader, native sends and the crash handler fail at once
326+
ends.close();
327+
logger.log(SentryLevel.ERROR, "NDK crash service did not connect in time.");
328+
}
329+
},
330+
CONNECT_TIMEOUT_MILLIS);
331+
} catch (RejectedExecutionException e) {
332+
logger.log(SentryLevel.DEBUG, e, "Failed to schedule the NDK crash service timeout.");
333+
}
334+
// stay bound, so the service process keeps the app's importance and is not frozen
335+
return connection;
321336
}
322337

323338
private static boolean bind(
@@ -326,7 +341,7 @@ private static boolean bind(
326341
final int flags,
327342
final @NotNull ServiceConnection connection) {
328343
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
329-
// deliver callbacks on the binder thread, the caller blocks on the latch
344+
// deliver callbacks on the binder thread instead of the main thread
330345
return context.bindService(intent, flags, Runnable::run, connection);
331346
}
332347
return context.bindService(intent, connection, flags);
@@ -810,4 +825,35 @@ private DaemonConfig(
810825
this.debug = debug;
811826
}
812827
}
828+
829+
// the service's ends of the crash IPC, handed over on the first connection or closed
830+
private static final class ServiceEnds {
831+
private final @NotNull AtomicBoolean taken = new AtomicBoolean();
832+
private final @NotNull ParcelFileDescriptor shm;
833+
private final @NotNull ParcelFileDescriptor notifyRead;
834+
private final @NotNull ParcelFileDescriptor readyWrite;
835+
private final @NotNull ParcelFileDescriptor messageRead;
836+
837+
private ServiceEnds(
838+
final @NotNull ParcelFileDescriptor shm,
839+
final @NotNull ParcelFileDescriptor notifyRead,
840+
final @NotNull ParcelFileDescriptor readyWrite,
841+
final @NotNull ParcelFileDescriptor messageRead) {
842+
this.shm = shm;
843+
this.notifyRead = notifyRead;
844+
this.readyWrite = readyWrite;
845+
this.messageRead = messageRead;
846+
}
847+
848+
private boolean take() {
849+
return taken.compareAndSet(false, true);
850+
}
851+
852+
private void close() {
853+
closeQuietly(shm);
854+
closeQuietly(notifyRead);
855+
closeQuietly(readyWrite);
856+
closeQuietly(messageRead);
857+
}
858+
}
813859
}

‎sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt‎

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import android.app.ActivityManager
44
import android.app.ApplicationExitInfo
55
import android.content.ComponentName
66
import android.content.Context
7+
import android.content.ContextWrapper
8+
import android.content.Intent
9+
import android.content.ServiceConnection
710
import android.os.Binder
811
import android.os.Parcel
912
import android.os.ParcelFileDescriptor
@@ -15,10 +18,12 @@ import io.sentry.android.core.SentryAndroidOptions
1518
import io.sentry.android.core.cache.AndroidEnvelopeCache
1619
import io.sentry.ndk.NdkOptions
1720
import io.sentry.ndk.SentryNdk.CrashDaemon
21+
import io.sentry.test.DeferredExecutorService
1822
import java.io.File
1923
import java.io.InputStream
2024
import java.util.Date
2125
import java.util.concurrent.CountDownLatch
26+
import java.util.concurrent.Executor
2227
import java.util.concurrent.LinkedBlockingQueue
2328
import java.util.concurrent.TimeUnit
2429
import java.util.zip.GZIPInputStream
@@ -66,13 +71,48 @@ class SentryNdkCrashServiceTest {
6671
}
6772

6873
@Test
69-
fun `unbinds when the service does not configure`() {
74+
fun `stays bound when the service does not configure`() {
7075
configure(false)
7176
Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use {
72-
assertThat(SentryNdkCrashService.start(app, options)).isNull()
77+
val connection = SentryNdkCrashService.start(app, options)
7378

74-
assertThat(shadowOf(app).boundServiceConnections).isEmpty()
75-
assertThat(shadowOf(app).unboundServiceConnections).hasSize(1)
79+
assertThat(connection).isNotNull()
80+
assertThat(shadowOf(app).boundServiceConnections).containsExactly(connection)
81+
assertThat(shadowOf(app).unboundServiceConnections).isEmpty()
82+
}
83+
}
84+
85+
@Test
86+
fun `starts before the service connects`() {
87+
val context = UnconnectedContext()
88+
options.executorService = DeferredExecutorService()
89+
Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native ->
90+
val connection = SentryNdkCrashService.start(context, options)
91+
92+
assertThat(connection).isNotNull()
93+
assertThat(context.connections).containsExactly(connection)
94+
native.verify { io.sentry.ndk.SentryNdk.initCrashDaemon(any(), any(), any(), any()) }
95+
}
96+
}
97+
98+
@Test
99+
fun `reattaches a service that connects after the timeout`() {
100+
val binder = configure(true)
101+
val context = UnconnectedContext()
102+
val executor = DeferredExecutorService()
103+
options.executorService = executor
104+
Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native ->
105+
native.`when`<Int> { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(42)
106+
native
107+
.`when`<Boolean> { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) }
108+
.thenReturn(true)
109+
val connection = SentryNdkCrashService.start(context, options)!!
110+
111+
executor.runAll()
112+
connection.onServiceConnected(component, binder)
113+
114+
assertThat(binder.transactions).isEqualTo(1)
115+
native.verify { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) }
76116
}
77117
}
78118

@@ -439,6 +479,21 @@ class SentryNdkCrashServiceTest {
439479

440480
private fun descriptor(fd: Int): ParcelFileDescriptor = mock { on { detachFd() } doReturn fd }
441481

482+
// binds without connecting, as a service process that is still starting
483+
private inner class UnconnectedContext : ContextWrapper(app) {
484+
val connections = mutableListOf<ServiceConnection>()
485+
486+
override fun bindService(
487+
service: Intent,
488+
flags: Int,
489+
executor: Executor,
490+
conn: ServiceConnection,
491+
): Boolean {
492+
connections += conn
493+
return true
494+
}
495+
}
496+
442497
private fun configure(configured: Boolean) =
443498
object : Binder() {
444499
var transactions = 0

0 commit comments

Comments
 (0)