1717import android .os .RemoteException ;
1818import io .sentry .DateUtils ;
1919import io .sentry .ILogger ;
20+ import io .sentry .ISentryExecutorService ;
2021import io .sentry .SentryEnvelope ;
2122import io .sentry .SentryEnvelopeItem ;
2223import io .sentry .SentryEvent ;
4243import java .util .ArrayList ;
4344import java .util .Date ;
4445import java .util .List ;
45- import java .util .concurrent .CountDownLatch ;
46+ import java .util .concurrent .RejectedExecutionException ;
4647import java .util .concurrent .TimeUnit ;
48+ import java .util .concurrent .atomic .AtomicBoolean ;
4749import org .jetbrains .annotations .ApiStatus ;
4850import org .jetbrains .annotations .NotNull ;
4951import 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}
0 commit comments