diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 93ccc0f518..0ea0820ee9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,6 +30,20 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + # DO NOT MERGE (remove after releasing getsentry/sentry-native#2301) + - name: Checkout sentry-native + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: getsentry/sentry-native + ref: jpnurmi/fix/native-android-21 + path: sentry-native + submodules: 'recursive' + + # DO NOT MERGE (remove after releasing getsentry/sentry-native#2301) + - name: Publish sentry-native-ndk-outproc to Maven Local + working-directory: sentry-native/ndk + run: ./gradlew --no-daemon -PversionName=0.0.0-local :sentry-native-ndk-outproc:publishToMavenLocal + - name: Run Tests and Lint run: make preMerge diff --git a/CHANGELOG.md b/CHANGELOG.md index 9472ec4027..843957c43b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,16 @@ > [!WARNING] > SDK 9.0.0 will raise the minimum supported Java and Android versions: +> > - Java 8 support will be dropped. SDK 9.0.0 requires Java 11+. See [#6469](https://github.com/getsentry/sentry-java/issues/6469). > - The Android `minSdk` will be raised from 21 to 24. See [#5508](https://github.com/getsentry/sentry-java/issues/5508). +## Future (TODO: release sentry-native#2301) + +### Fixes + +- Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) + ## Unreleased ### Fixes @@ -495,7 +502,7 @@ - Use Android's `ProfilingManager` (Perfetto) for continuous profiling on API 35+ devices ([#5251](https://github.com/getsentry/sentry-java/pull/5251)) - On API 35+ devices, continuous profiling now automatically uses Android's system `ProfilingManager` with Perfetto-based stack sampling, providing lower-overhead and more accurate profiles. No configuration change is required. - Devices below API 35 keep using the legacy `Debug`-based profiler. - - Added an `enableLegacyProfiling` option (default `true`) to disable the legacy `Debug`-based profiler. Setting it to `false` disables continuous profiling on API < 35 devices as well as transaction-based profiling (`profilesSampleRate`/`profilesSampler`) on all devices, since transaction-based profiling is not supported by Perfetto. + - Added an `enableLegacyProfiling` option (default `true`) to disable the legacy `Debug`-based profiler. Setting it to `false` disables continuous profiling on API < 35 devices as well as transaction-based profiling (`profilesSampleRate`/`profilesSampler`) on all devices, since transaction-based profiling is not supported by Perfetto. - It can also be configured via the `io.sentry.profiling.enable-legacy-profiling` manifest flag. - See the [Android profiling docs](https://docs.sentry.io/platforms/android/profiling/) for details. @@ -637,6 +644,7 @@ Sentry.finishExtendedAppStart() ``` + - Add `trace_metric_byte` data category and record byte-level client reports when trace metrics are discarded ([#5626](https://github.com/getsentry/sentry-java/pull/5626)) - Expose sentry-native's heartbeat-based app-hang detection through `SentryAndroidOptions` ([#5623](https://github.com/getsentry/sentry-java/pull/5623)) - Enable via `setEnableNdkAppHangTracking(true)` (disabled by default) and tune the timeout with `setNdkAppHangTimeoutIntervalMillis(...)` (default `5000` ms), or the `io.sentry.ndk.app-hang.enable` / `io.sentry.ndk.app-hang.timeout-interval-millis` manifest entries @@ -830,6 +838,7 @@ } } ``` + - Parse ART memory and garbage collector info from ANR tombstones into ART context ([#5428](https://github.com/getsentry/sentry-java/pull/5428)) ## 8.42.0 @@ -839,7 +848,7 @@ - Add option to attach raw tombstone protobuf on native crash events ([#5446](https://github.com/getsentry/sentry-java/pull/5446)) - Enable via `options.isAttachRawTombstone = true` or manifest: `` - Add API to clear feature flags from scopes ([#5426](https://github.com/getsentry/sentry-java/pull/5426)) -- Add support to configure reporting historical ANRs via `AndroidManifest.xml` using the `io.sentry.anr.report-historical` attribute ([#5387](https://github.com/getsentry/sentry-java/pull/5387)) +- Add support to configure reporting historical ANRs via `AndroidManifest.xml` using the `io.sentry.anr.report-historical` attribute ([#5387](https://github.com/getsentry/sentry-java/pull/5387)) ### Dependencies diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 56c294c6ad..4a3223e9fc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -197,7 +197,7 @@ reactor-core = { module = "io.projectreactor:reactor-core", version = "3.5.3" } retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } retrofit-gson = { module = "com.squareup.retrofit2:converter-gson", version.ref = "retrofit" } sentry-native-ndk = { module = "io.sentry:sentry-native-ndk", version = "0.17.6" } -sentry-native-ndk-outproc = { module = "io.sentry:sentry-native-ndk-outproc", version = "1.0.0-beta.1" } +sentry-native-ndk-outproc = { module = "io.sentry:sentry-native-ndk-outproc", version = "0.0.0-local" } servlet-api = { module = "javax.servlet:javax.servlet-api", version = "3.1.0" } servlet4-api = { module = "javax.servlet:javax.servlet-api", version = "4.0.1" } servlet-jakarta-api = { module = "jakarta.servlet:jakarta.servlet-api", version = "6.1.0" } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index e3eb33af04..bdca5c59da 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -20,6 +20,9 @@ import io.sentry.android.fragment.FragmentLifecycleIntegration; import io.sentry.android.timber.SentryTimberIntegration; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.FileUtils; +import java.io.File; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -290,13 +293,30 @@ private static void deduplicateIntegrations( } } - // the crash service only runs on API 30+ @SuppressLint("NewApi") private static boolean isNdkCrashServiceProcess() { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + if (!new io.sentry.util.LoadClass() + .isClassAvailable(NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME, (ILogger) null)) { return false; } - final @Nullable String processName = Application.getProcessName(); + final @Nullable String processName = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ? Application.getProcessName() + : readProcessName(); return processName != null && processName.endsWith(NDK_CRASH_SERVICE_PROCESS_SUFFIX); } + + // argv[0] of an app process is its process name + private static @Nullable String readProcessName() { + try { + final @Nullable String cmdline = FileUtils.readText(new File("/proc/self/cmdline")); + if (cmdline == null) { + return null; + } + final int end = cmdline.indexOf('\0'); + return end >= 0 ? cmdline.substring(0, end) : cmdline; + } catch (IOException e) { + return null; + } + } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index 2717128af9..08eecc00c4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -49,6 +49,7 @@ import io.sentry.protocol.Contexts import io.sentry.spotlight.SpotlightIntegration import io.sentry.test.applyTestOptions import io.sentry.transport.NoOpEnvelopeCache +import io.sentry.util.LoadClass import io.sentry.util.StringUtils import java.io.ByteArrayOutputStream import java.io.File @@ -72,6 +73,7 @@ import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -580,12 +582,35 @@ class SentryAndroidTest { ShadowApplication.setProcessName("${context.packageName}.sentry_ndk_crash") var configured = false - fixture.initSut { configured = true } + Mockito.mockConstruction(LoadClass::class.java) { loadClass, _ -> + whenever( + loadClass.isClassAvailable( + eq(NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME), + anyOrNull(), + ), + ) + .thenReturn(true) + } + .use { fixture.initSut { configured = true } } assertFalse(configured) assertFalse(Sentry.isEnabled()) } + @Test + @Config(sdk = [30]) + fun `init runs in a process named like the NDK crash service without outproc`() { + ShadowApplication.setProcessName("${context.packageName}.sentry_ndk_crash") + var configured = false + + fixture.initSut { + it.dsn = "https://key@sentry.io/123" + configured = true + } + + assertTrue(configured) + } + private fun prefillScopeCache(options: SentryOptions, cacheDir: String) { val scopeDir = File(cacheDir, SCOPE_CACHE).also { it.mkdirs() } val queueFile = QueueFile.Builder(File(scopeDir, BREADCRUMBS_FILENAME)).build() diff --git a/sentry-android-ndk-outproc/README.md b/sentry-android-ndk-outproc/README.md index fefcd96da8..7ad125367e 100644 --- a/sentry-android-ndk-outproc/README.md +++ b/sentry-android-ndk-outproc/README.md @@ -16,6 +16,3 @@ configurations.configureEach { ``` Otherwise, the build fails because it contains both native backends. - -The crash service needs API 30+. On older versions, native crash reporting is -disabled. diff --git a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java index 985e3b1af5..0a08e8345f 100644 --- a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java @@ -17,6 +17,7 @@ import android.os.RemoteException; import io.sentry.DateUtils; import io.sentry.ILogger; +import io.sentry.ISentryExecutorService; import io.sentry.SentryEnvelope; import io.sentry.SentryEnvelopeItem; import io.sentry.SentryEvent; @@ -42,8 +43,9 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,6 +60,7 @@ public final class SentryNdkCrashService extends Service { private static final @NotNull String MERGED_SUFFIX = ".merged"; private static final long POLL_INTERVAL_MILLIS = 250; private static final long MATCH_TOLERANCE_MILLIS = 30000; + private static final long CONNECT_TIMEOUT_MILLIS = 10000; private final @NotNull IBinder binder = new Binder() { @@ -110,7 +113,7 @@ protected boolean onTransact( } }; - static @Nullable ServiceConnection start( + static @Nullable Connection start( final @NotNull Context context, final @NotNull SentryAndroidOptions options) { // fail before binding, the crash daemon can't attach without the native libraries io.sentry.ndk.SentryNdk.loadNativeLibraries(); @@ -137,7 +140,7 @@ protected boolean onTransact( return null; } - final int shmFd = io.sentry.ndk.SentryNdk.createCrashShm(); + final int shmFd = io.sentry.ndk.SentryNdk.createCrashShm(nativeDatabaseDir.getPath()); if (shmFd < 0) { options.getLogger().log(SentryLevel.DEBUG, "Failed to create NDK crash shared memory."); return null; @@ -150,6 +153,7 @@ protected boolean onTransact( ParcelFileDescriptor readyWrite = null; ParcelFileDescriptor messageWrite = null; ParcelFileDescriptor messageRead = null; + @Nullable ServiceEnds ends = null; try { final ParcelFileDescriptor[] notifyPipe = ParcelFileDescriptor.createPipe(); final ParcelFileDescriptor[] readyPipe = ParcelFileDescriptor.createPipe(); @@ -160,16 +164,20 @@ protected boolean onTransact( final ParcelFileDescriptor[] messageSocket = ParcelFileDescriptor.createSocketPair(); messageWrite = messageSocket[0]; messageRead = messageSocket[1]; + ends = new ServiceEnds(shm.dup(), notifyRead, readyWrite, messageRead); + notifyRead = null; + readyWrite = null; + messageRead = null; final Intent intent = new Intent(context, SentryNdkCrashService.class); - final @Nullable ServiceConnection connection = + final @Nullable Connection connection = configureService( context, intent, options.getLogger(), + options.getTimerExecutorService(), nativeDatabaseDir.getPath(), context.getApplicationInfo().nativeLibraryDir, - shm, Process.myPid(), Process.myTid(), options.isTombstoneEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S, @@ -177,25 +185,24 @@ protected boolean onTransact( options.getShutdownTimeoutMillis(), new ArrayList<>(options.getInAppIncludes()), new ArrayList<>(options.getInAppExcludes()), - notifyRead, - readyWrite, - messageRead); + ends); + ends = null; if (connection == null) { - options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not configure."); + options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not bind."); return null; } + // the daemon attaches once the service connects io.sentry.ndk.SentryNdk.initCrashDaemon( shm.detachFd(), notifyWrite.detachFd(), readyRead.detachFd(), messageWrite.detachFd()); return connection; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service."); - return null; } catch (IOException | SecurityException e) { options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service."); return null; } finally { + if (ends != null) { + ends.close(); + } closeQuietly(shm); closeQuietly(notifyRead); closeQuietly(notifyWrite); @@ -221,13 +228,13 @@ private static void closeQuietly(final @Nullable Closeable closeable) { } } - private static @Nullable ServiceConnection configureService( + private static @Nullable Connection configureService( final @NotNull Context context, final @NotNull Intent intent, final @NotNull ILogger logger, + final @NotNull ISentryExecutorService executorService, final @NotNull String nativeDatabasePath, final @Nullable String nativeLibraryDir, - final @NotNull ParcelFileDescriptor shm, final int appPid, final long appTid, final boolean tombstoneEnabled, @@ -235,25 +242,20 @@ private static void closeQuietly(final @Nullable Closeable closeable) { final long shutdownTimeoutMillis, final @NotNull ArrayList includes, final @NotNull ArrayList excludes, - final @NotNull ParcelFileDescriptor notifyRead, - final @NotNull ParcelFileDescriptor readyWrite, - final @NotNull ParcelFileDescriptor messageRead) - throws InterruptedException { - final CountDownLatch latch = new CountDownLatch(1); - final boolean[] configured = new boolean[] {false}; + final @NotNull ServiceEnds ends) { // a foreground app raises the service process only to visible without BIND_IMPORTANT final int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; - final ServiceConnection connection = - new ServiceConnection() { - private boolean connected; + final Connection connection = + new Connection() { + private volatile boolean configured; @Override public void onServiceConnected( final @NotNull ComponentName name, final @NotNull IBinder service) { - if (connected) { - // a restarted service process has no daemon for this app - reattach( + if (!ends.take()) { + // a restarted or late service process has no daemon for this app + if (reattach( service, logger, nativeDatabasePath, @@ -264,16 +266,17 @@ public void onServiceConnected( debug, shutdownTimeoutMillis, includes, - excludes); + excludes)) { + configured = true; + } return; } - connected = true; - configured[0] = + configured = transactConfigure( service, nativeDatabasePath, nativeLibraryDir, - shm, + ends.shm, appPid, appTid, tombstoneEnabled, @@ -281,43 +284,64 @@ public void onServiceConnected( shutdownTimeoutMillis, includes, excludes, - notifyRead, - readyWrite, - messageRead); - latch.countDown(); + ends.notifyRead, + ends.readyWrite, + ends.messageRead); + ends.close(); + if (!configured) { + logger.log(SentryLevel.ERROR, "NDK crash service did not configure."); + } } @Override public void onServiceDisconnected(final @NotNull ComponentName name) { logger.log(SentryLevel.ERROR, "NDK crash service disconnected."); - latch.countDown(); } @Override public void onBindingDied(final @NotNull ComponentName name) { logger.log(SentryLevel.ERROR, "NDK crash service binding died."); - latch.countDown(); // a dead binding does not reconnect, it must be bound again - if (configured[0]) { + if (configured) { context.unbindService(this); bind(context, intent, flags, this); } } + + @Override + public void close() { + if (ends.take()) { + ends.close(); + } + } }; - if (!bind(context, intent, flags, connection)) { - return null; - } - boolean ready = false; + boolean bound = false; try { - ready = latch.await(10000, TimeUnit.MILLISECONDS) && configured[0]; - // stay bound, so the service process keeps the app's importance and is not frozen - return ready ? connection : null; + bound = bind(context, intent, flags, connection); } finally { - if (!ready) { - context.unbindService(connection); + if (!bound) { + ends.close(); } } + if (!bound) { + return null; + } + try { + executorService.schedule( + () -> { + if (ends.take()) { + // without a reader, native sends and the crash handler fail at once + ends.close(); + logger.log(SentryLevel.ERROR, "NDK crash service did not connect in time."); + } + }, + CONNECT_TIMEOUT_MILLIS); + } catch (RejectedExecutionException e) { + logger.log(SentryLevel.DEBUG, e, "Failed to schedule the NDK crash service timeout."); + } + // stay bound, so the service process keeps the app's importance and is not frozen + return connection; } private static boolean bind( @@ -326,13 +350,13 @@ private static boolean bind( final int flags, final @NotNull ServiceConnection connection) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - // deliver callbacks on the binder thread, the caller blocks on the latch + // deliver callbacks on the binder thread instead of the main thread return context.bindService(intent, flags, Runnable::run, connection); } return context.bindService(intent, connection, flags); } - private static void reattach( + private static boolean reattach( final @NotNull IBinder service, final @NotNull ILogger logger, final @NotNull String nativeDatabasePath, @@ -347,7 +371,7 @@ private static void reattach( final int shmFd = io.sentry.ndk.SentryNdk.dupCrashShmFd(); if (shmFd < 0) { logger.log(SentryLevel.ERROR, "NDK crash service restarted, but the app can't reattach."); - return; + return false; } final ParcelFileDescriptor shm = ParcelFileDescriptor.adoptFd(shmFd); @@ -391,8 +415,10 @@ private static void reattach( } else { logger.log(SentryLevel.ERROR, "NDK crash service restarted, failed to reattach the app."); } + return reattached; } catch (IOException | SecurityException e) { logger.log(SentryLevel.ERROR, e, "Failed to reattach to the NDK crash service."); + return false; } finally { closeQuietly(shm); closeQuietly(notifyRead); @@ -810,4 +836,41 @@ private DaemonConfig( this.debug = debug; } } + + // closes the service's ends of the crash IPC unless a connection took them + abstract static class Connection implements ServiceConnection, Closeable { + @Override + public abstract void close(); + } + + // the service's ends of the crash IPC, handed over on the first connection or closed + private static final class ServiceEnds { + private final @NotNull AtomicBoolean taken = new AtomicBoolean(); + private final @NotNull ParcelFileDescriptor shm; + private final @NotNull ParcelFileDescriptor notifyRead; + private final @NotNull ParcelFileDescriptor readyWrite; + private final @NotNull ParcelFileDescriptor messageRead; + + private ServiceEnds( + final @NotNull ParcelFileDescriptor shm, + final @NotNull ParcelFileDescriptor notifyRead, + final @NotNull ParcelFileDescriptor readyWrite, + final @NotNull ParcelFileDescriptor messageRead) { + this.shm = shm; + this.notifyRead = notifyRead; + this.readyWrite = readyWrite; + this.messageRead = messageRead; + } + + private boolean take() { + return taken.compareAndSet(false, true); + } + + private void close() { + closeQuietly(shm); + closeQuietly(notifyRead); + closeQuietly(readyWrite); + closeQuietly(messageRead); + } + } } diff --git a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java index 0a18bf1966..38c158ce14 100644 --- a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java @@ -2,8 +2,6 @@ import android.annotation.SuppressLint; import android.content.Context; -import android.content.ServiceConnection; -import android.os.Build; import io.sentry.SentryIntegrationPackageStorage; import io.sentry.android.core.NdkHandlerStrategy; import io.sentry.android.core.SentryAndroidOptions; @@ -29,7 +27,7 @@ public final class SentryNdkOutproc { @SuppressLint("StaticFieldLeak") // the application context from NdkIntegration private static @Nullable Context serviceContext; - private static @Nullable ServiceConnection serviceConnection; + private static @Nullable SentryNdkCrashService.Connection serviceConnection; private SentryNdkOutproc() {} @@ -68,8 +66,8 @@ public static void init(@NotNull final SentryAndroidOptions options) { public static void init( @Nullable final Context context, @NotNull final SentryAndroidOptions options) { // no fork/exec fallback, the native crash daemon only runs in the crash service - if (context == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { - throw new IllegalStateException("The NDK crash service needs a context and API 30+"); + if (context == null) { + throw new IllegalStateException("The NDK crash service needs a context"); } addPackage(options.getSdkVersion()); @@ -107,7 +105,7 @@ public static void init( ndkOptions.setEnableAppHangTracking(options.isEnableNdkAppHangTracking()); ndkOptions.setAppHangTimeoutMillis(options.getNdkAppHangTimeoutIntervalMillis()); - final @Nullable ServiceConnection connection = + final @Nullable SentryNdkCrashService.Connection connection = SentryNdkCrashService.start(context, options); if (connection == null) { throw new IllegalStateException("Failed to start the NDK crash service"); @@ -168,11 +166,15 @@ private static void addPackage(final @Nullable SdkVersion sdkVersion) { private static void unbindCrashService() { final @Nullable Context context = serviceContext; - final @Nullable ServiceConnection connection = serviceConnection; + final @Nullable SentryNdkCrashService.Connection connection = serviceConnection; serviceContext = null; serviceConnection = null; if (context != null && connection != null) { - context.unbindService(connection); + try { + context.unbindService(connection); + } finally { + connection.close(); + } } } } diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt index 61d56f4236..8169bbc197 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt @@ -1,7 +1,6 @@ package io.sentry.android.ndk.outproc import android.content.Context -import android.content.ServiceConnection import com.google.common.truth.Truth.assertThat import io.sentry.android.core.SentryAndroidOptions import io.sentry.ndk.NdkOptions @@ -54,12 +53,6 @@ class NativeBackendTest { assertFailsWith { SentryNdkOutproc.init(options()) } } - @Test - @Config(sdk = [29]) - fun `fails below API 30`() { - assertFailsWith { SentryNdkOutproc.init(mock(), options()) } - } - private fun options() = SentryAndroidOptions().apply { dsn = "https://key@sentry.io/proj" @@ -79,8 +72,10 @@ class NativeBackendTest { .`when` { io.sentry.ndk.SentryNdk.init(any()) } .doAnswer { captured = it.arguments[0] as NdkOptions } service - .`when` { SentryNdkCrashService.start(context, options) } - .thenReturn(mock()) + .`when` { + SentryNdkCrashService.start(context, options) + } + .thenReturn(mock()) SentryNdkOutproc.init(context, options) diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt index 15f47d7078..701fc4d896 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt @@ -4,6 +4,9 @@ import android.app.ActivityManager import android.app.ApplicationExitInfo import android.content.ComponentName import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.ServiceConnection import android.os.Binder import android.os.Parcel import android.os.ParcelFileDescriptor @@ -15,10 +18,12 @@ import io.sentry.android.core.SentryAndroidOptions import io.sentry.android.core.cache.AndroidEnvelopeCache import io.sentry.ndk.NdkOptions import io.sentry.ndk.SentryNdk.CrashDaemon +import io.sentry.test.DeferredExecutorService import java.io.File import java.io.InputStream import java.util.Date import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream @@ -66,13 +71,48 @@ class SentryNdkCrashServiceTest { } @Test - fun `unbinds when the service does not configure`() { + fun `stays bound when the service does not configure`() { configure(false) Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { - assertThat(SentryNdkCrashService.start(app, options)).isNull() + val connection = SentryNdkCrashService.start(app, options) - assertThat(shadowOf(app).boundServiceConnections).isEmpty() - assertThat(shadowOf(app).unboundServiceConnections).hasSize(1) + assertThat(connection).isNotNull() + assertThat(shadowOf(app).boundServiceConnections).containsExactly(connection) + assertThat(shadowOf(app).unboundServiceConnections).isEmpty() + } + } + + @Test + fun `starts before the service connects`() { + val context = UnconnectedContext() + options.timerExecutorService = DeferredExecutorService() + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + val connection = SentryNdkCrashService.start(context, options) + + assertThat(connection).isNotNull() + assertThat(context.connections).containsExactly(connection) + native.verify { io.sentry.ndk.SentryNdk.initCrashDaemon(any(), any(), any(), any()) } + } + } + + @Test + fun `reattaches a service that connects after the timeout`() { + val binder = configure(true) + val context = UnconnectedContext() + val executor = DeferredExecutorService() + options.timerExecutorService = executor + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(42) + native + .`when` { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } + .thenReturn(true) + val connection = SentryNdkCrashService.start(context, options)!! + + executor.runAll() + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(1) + native.verify { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } } } @@ -105,6 +145,22 @@ class SentryNdkCrashServiceTest { } } + @Test + fun `close releases the service ends before the service connects`() { + val binder = configure(true) + val context = UnconnectedContext() + options.timerExecutorService = DeferredExecutorService() + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(-1) + val connection = SentryNdkCrashService.start(context, options)!! + + connection.close() + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(0) + } + } + @Test fun `init unbinds when native init fails`() { configure(true) @@ -179,11 +235,32 @@ class SentryNdkCrashServiceTest { } } + @Test + fun `binds again when the binding of a late service died`() { + val binder = configure(true) + val context = UnconnectedContext() + val executor = DeferredExecutorService() + options.timerExecutorService = executor + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(42) + native + .`when` { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } + .thenReturn(true) + val connection = SentryNdkCrashService.start(context, options)!! + executor.runAll() + connection.onServiceConnected(component, binder) + + connection.onBindingDied(component) + + assertThat(context.connections).containsExactly(connection, connection) + } + } + @Test fun `init fails without shared memory`() { configure(true) Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> - native.`when` { io.sentry.ndk.SentryNdk.createCrashShm() }.thenReturn(-1) + native.`when` { io.sentry.ndk.SentryNdk.createCrashShm(any()) }.thenReturn(-1) assertFailsWith { SentryNdkOutproc.init(app, options) } @@ -439,6 +516,21 @@ class SentryNdkCrashServiceTest { private fun descriptor(fd: Int): ParcelFileDescriptor = mock { on { detachFd() } doReturn fd } + // binds without connecting, as a service process that is still starting + private inner class UnconnectedContext : ContextWrapper(app) { + val connections = mutableListOf() + + override fun bindService( + service: Intent, + flags: Int, + executor: Executor, + conn: ServiceConnection, + ): Boolean { + connections += conn + return true + } + } + private fun configure(configured: Boolean) = object : Binder() { var transactions = 0