Skip to content
Draft
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
80 changes: 80 additions & 0 deletions Documentation/guides/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,86 @@ And the output files should be found in the current directory. You can
use the `-o` switch if you would prefer to output them to a specific
directory.

## Activity tracing for Android apps

.NET for Android exposes the `Microsoft.Android.Runtime` `ActivitySource` for
in-process listeners, including an OpenTelemetry tracer provider. It does not
include an OpenTelemetry SDK or exporter. Register a listener for
`Android.Runtime.AndroidTelemetry.ActivitySourceName` before enabling activity
lifecycle tracing or replaying startup data, and keep the listener alive while
collecting. For example, from an `Application` instance:

```csharp
// Register an ActivityListener or an OpenTelemetry tracer provider first.
Android.Runtime.AndroidTelemetry.EnableActivityLifecycleTracing (this);
Android.Runtime.AndroidTelemetry.ReplayStartupActivities ();
```

`EnableActivityLifecycleTracing` registers application lifecycle callbacks once
per process and keeps them registered for the application lifetime. It emits
short `android.activity.created`, `started`, `resumed`, `paused`, `stopped`,
`save_instance_state`, and `destroyed` activities. Each has an
`android.activity.name` tag containing the managed activity type name. These
represent callback notifications, not the duration of an activity's overridden
lifecycle method or application-level OpenTelemetry lifecycle log events.
No intents, saved state, or other activity contents are recorded.

To retain managed runtime startup timings until the listener is available, opt
in at build time:

```xml
<ItemGroup>
<RuntimeHostConfigurationOption Include="Microsoft.Android.Runtime.RuntimeFeature.StartupTracing" Value="true" Trim="true" />
</ItemGroup>
```

`ReplayStartupActivities` emits the buffered trace at most once per process.
It returns the number of activities emitted, or zero when recording was not
enabled, initialization has not completed, no listener samples the root, or
the trace was already replayed. A call without a sampling listener does not
consume the buffer. Startup is represented by a root `android.runtime.initialize`
activity and child activities for managed type-map setup, JNI runtime creation,
GC bridge setup, native registration, and (on CoreCLR) startup hooks. The root
starts during managed initialization, not at process launch; native startup and
application initialization outside that interval are not measured. Recorded
timestamps use a wall-clock anchor and monotonic elapsed time. The root and
children carry `android.runtime.startup.buffered=true`; the root also carries
`android.runtime.startup.dropped`, the number of phases exceeding the bounded
buffer's 16-child capacity. The replay is a separate trace and does not inherit
the caller's current activity.

Lifecycle collection and startup recording are independent opt-ins. Optimized
builds may disable metrics, EventSource, and HTTP activity propagation by
default; enable those separately if the consumer also needs those signals.
`EventSourceSupport` and `EnableDiagnostics` are not required for this
in-process `ActivitySource`.

When a listener samples `Microsoft.Android.Runtime`, each managed GC bridge
pass also emits a root `android.runtime.gc_bridge.process` activity tagged with
`android.gc_bridge.components`, `android.gc_bridge.cross_references`,
`android.gc_bridge.collected`, and `android.gc_bridge.generation`. It is
emitted after bridge processing completes, so listener code never runs while
the bridge is in progress.

### Interop activities

Fine-grained Java interop activities use a separate source,
`Android.Runtime.AndroidTelemetry.InteropActivitySourceName`
(`Microsoft.Android.Runtime.Interop`). Traces have no levels, so listening to
this source is the opt-in for higher-volume data. It emits:

| Activity | When | Tags |
| --- | --- | --- |
| `android.runtime.interop.register_natives` | A Java class registers its native methods | `android.java.class` |
| `android.runtime.interop.create_peer` | The runtime creates a managed peer for a Java object | `android.managed.type`; when all data is requested, also `android.java.class` and `android.interop.target_type` |
| `android.runtime.type_map.java_to_managed` | A Java-to-managed type-map cache miss | `android.java.class`, `android.type_map.found` |
| `android.runtime.type_map.managed_to_java` | A managed-to-Java type-map cache miss | `android.managed.type`, `android.type_map.found`, and `android.java.class` when found |

Type-map lookups that hit the cache are not traced. Interop activities are not
buffered during startup, so activities occurring before a listener is
registered are not recorded. A listener that itself creates Java peers will
observe nested `create_peer` activities.

## .NET for Android runtime events

Runtime interop timing and JNI reference events use the `Microsoft.Android.Runtime` provider.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,20 +94,23 @@ static unsafe void init (IntPtr jnienv, IntPtr klass, IntPtr classLoader, IntPtr
}
// Seed DateTimeOffset.Now's fast path before managed runtime initialization or application code.
AppContext.SetData ("System.TimeZoneInfo.LocalDateTimeOffset", localDateTimeOffset.ToString (CultureInfo.InvariantCulture));
using var startup = RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupInitialization);
unsafe {
// SAFETY: the host returned process-lifetime remapping storage and runtime-lifetime global references.
JNIEnvInit.InitializeBeforeRuntimeCreation (initArgs);
}

var options = new NativeAotRuntimeOptions {
EnvironmentPointer = jnienv,
ClassLoader = new JniObjectReference (classLoader, JniObjectReferenceType.Global),
ObjectReferenceManager = new ManagedObjectReferenceManager (),
TypeManager = new TrimmableTypeMapTypeManager (),
ValueManager = new TrimmableTypeMapValueManager (),
};
// SAFETY: JNI retains this thread's environment and borrowed loader through the callback; creation duplicates the loader and the VM outlives the runtime.
runtime = unsafe (options.CreateJreVM ());
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupJniRuntime)) {
var options = new NativeAotRuntimeOptions {
EnvironmentPointer = jnienv,
ClassLoader = new JniObjectReference (classLoader, JniObjectReferenceType.Global),
ObjectReferenceManager = new ManagedObjectReferenceManager (),
TypeManager = new TrimmableTypeMapTypeManager (),
ValueManager = new TrimmableTypeMapValueManager (),
};
// SAFETY: JNI retains this thread's environment and borrowed loader through the callback; creation duplicates the loader and the VM outlives the runtime.
runtime = unsafe (options.CreateJreVM ());
}

// Entry point into Mono.Android.dll for NativeAOT-specific JNI runtime initialization.
unsafe {
Expand Down
55 changes: 55 additions & 0 deletions src/Mono.Android/Android.Runtime/AndroidTelemetry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System;

using Android.App;
using Android.OS;

using Microsoft.Android.Runtime;

namespace Android.Runtime;

public static class AndroidTelemetry
{
public const string ActivitySourceName = RuntimeTelemetry.ActivitySourceName;
public const string InteropActivitySourceName = RuntimeTelemetry.InteropActivitySourceName;

static readonly object lifecycleLock = new ();
static ActivityLifecycleCallbacks? lifecycleCallbacks;

public static int ReplayStartupActivities () => RuntimeTelemetry.ReplayStartupActivities ();

public static void EnableActivityLifecycleTracing (Application application)
{
ArgumentNullException.ThrowIfNull (application);

lock (lifecycleLock) {
if (lifecycleCallbacks != null)
return;

var callbacks = new ActivityLifecycleCallbacks ();
try {
application.RegisterActivityLifecycleCallbacks (callbacks);
} catch {
callbacks.Dispose ();
throw;
}
lifecycleCallbacks = callbacks;
}
}

sealed class ActivityLifecycleCallbacks : Java.Lang.Object, Application.IActivityLifecycleCallbacks
{
static void Record (string name, Activity activity)
{
using var recorded = RuntimeTelemetry.Source.StartActivity (name);
recorded?.SetTag ("android.activity.name", activity.GetType ().FullName);
}

public void OnActivityCreated (Activity activity, Bundle? savedInstanceState) => Record ("android.activity.created", activity);
public void OnActivityStarted (Activity activity) => Record ("android.activity.started", activity);
public void OnActivityResumed (Activity activity) => Record ("android.activity.resumed", activity);
public void OnActivityPaused (Activity activity) => Record ("android.activity.paused", activity);
public void OnActivityStopped (Activity activity) => Record ("android.activity.stopped", activity);
public void OnActivitySaveInstanceState (Activity activity, Bundle outState) => Record ("android.activity.save_instance_state", activity);
public void OnActivityDestroyed (Activity activity) => Record ("android.activity.destroyed", activity);
}
}
47 changes: 31 additions & 16 deletions src/Mono.Android/Android.Runtime/JNIEnvInit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ internal static unsafe void InitializeBeforeRuntimeCreation (JnienvInitializeArg
// SAFETY: the native host retains the remapping body and global references beyond initialization.
InitializeCommonState (args);
}
TypeMapLoader.Initialize ();
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupTypeMap)) {
TypeMapLoader.Initialize ();
}
}

internal static void InitializeMaxGrefCounts (JnienvInitializeArgs args)
Expand Down Expand Up @@ -94,11 +96,15 @@ internal static unsafe void InitializeNativeAotRuntime (JniRuntime runtime, Jnie
}
androidRuntime = runtime;
JniRuntime.SetCurrent (runtime);
unsafe {
// SAFETY: the caller retains the native host's process-lifetime initializer and matching runtime descriptor.
JavaMarshalGCBridge.Initialize (args);
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupGCBridge)) {
unsafe {
// SAFETY: the caller retains the native host's process-lifetime initializer and matching runtime descriptor.
JavaMarshalGCBridge.Initialize (args);
}
}
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupNativeMethods)) {
TrimmableTypeMap.RegisterNativeMethods ();
}
TrimmableTypeMap.RegisterNativeMethods ();
SetSynchronizationContext ();
}

Expand All @@ -121,26 +127,35 @@ internal static unsafe void Initialize (JnienvInitializeArgs* args)
throw new NotSupportedException ("Internal error: CoreCLR must be enabled.");
}

using var startup = RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupInitialization);
if (RuntimeFeature.StartupNoGCRegion) {
StartupNoGCRegion.Start ();
}

InitializeBeforeRuntimeCreation (*args);

androidRuntime = new AndroidRuntime (
args->env,
args->javaVm,
args->grefLoader,
new TrimmableTypeMapTypeManager (),
new TrimmableTypeMapValueManager ()
);
JniRuntime.SetCurrent (androidRuntime);
JavaMarshalGCBridge.Initialize (*args);
TrimmableTypeMap.RegisterNativeMethods ();
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupJniRuntime)) {
androidRuntime = new AndroidRuntime (
args->env,
args->javaVm,
args->grefLoader,
new TrimmableTypeMapTypeManager (),
new TrimmableTypeMapValueManager ()
);
JniRuntime.SetCurrent (androidRuntime);
}
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupGCBridge)) {
JavaMarshalGCBridge.Initialize (*args);
}
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupNativeMethods)) {
TrimmableTypeMap.RegisterNativeMethods ();
}

args->propagateUncaughtExceptionFn = (IntPtr)(delegate* unmanaged<IntPtr, IntPtr, IntPtr, void>)&PropagateUncaughtException;

RunStartupHooksIfNeeded ();
using (RuntimeTelemetry.StartStartupOperation (RuntimeTelemetry.StartupHooks)) {
RunStartupHooksIfNeeded ();
}
SetSynchronizationContext ();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -92,14 +93,19 @@ static void ProcessBridge (MarkCrossReferencesArgs* args)
// SAFETY: the registered CLR callback supplies args and all counted arrays until FinishCrossReferenceProcessing; identity checks do not validate their native bounds, and failures terminate the process.
try {
ArgumentNullException.ThrowIfNull (args);
long startTimestamp = Stopwatch.GetTimestamp ();
bool gcBridgeEventEnabled = RuntimeFeature.EventSourceSupport && RuntimeEventSource.GCBridgeStart ();
HandleContext.EnsureAllContextsAreOurs (args);
Process (args);
ReadOnlySpan<GCHandle> handlesToFree = ProcessCollectedContexts (args);
long components = (long) args->ComponentCount;
long crossReferences = (long) args->CrossReferenceCount;
int collected = handlesToFree.Length;

JavaMarshal.FinishCrossReferenceProcessing (args, handlesToFree);

Interlocked.Increment (ref bridgeProcessingGeneration);
int generation = Interlocked.Increment (ref bridgeProcessingGeneration);
RuntimeTelemetry.RecordGCBridgeProcessing (startTimestamp, components, crossReferences, collected, generation);
// Keep the switch here so ILLink removes the EventSource when it is disabled.
if (RuntimeFeature.EventSourceSupport) {
if (gcBridgeEventEnabled) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ static class RuntimeFeature
const bool IsNativeAotRuntimeEnabledByDefault = false;
const bool IsAssignableFromCheckEnabledByDefault = true;
const bool StartupNoGCRegionEnabledByDefault = true;
const bool StartupTracingEnabledByDefault = false;
const bool StartupHookSupportEnabledByDefault = true;
const bool UseTypeMapAttributesForJavaDictionaryValueTypeLookupsEnabledByDefault = false;
const bool GCBridgeLoggingEnabledByDefault = true;
Expand All @@ -34,6 +35,10 @@ static class RuntimeFeature
internal static bool StartupNoGCRegion { get; } =
AppContext.TryGetSwitch ($"{FeatureSwitchPrefix}{nameof (StartupNoGCRegion)}", out bool isEnabled) ? isEnabled : StartupNoGCRegionEnabledByDefault;

[FeatureSwitchDefinition ($"{FeatureSwitchPrefix}{nameof (StartupTracing)}")]
internal static bool StartupTracing { get; } =
AppContext.TryGetSwitch ($"{FeatureSwitchPrefix}{nameof (StartupTracing)}", out bool isEnabled) ? isEnabled : StartupTracingEnabledByDefault;

[FeatureSwitchDefinition (StartupHookProviderSwitch)]
[FeatureGuard (typeof (RequiresUnreferencedCodeAttribute))]
internal static bool StartupHookSupport { get; } =
Expand Down
Loading
Loading