Skip to content
Merged
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
27 changes: 8 additions & 19 deletions docs/event-infrastructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,18 +427,7 @@ For **static events**, there's no object instance. Instead, the generated code u

```csharp
// Generated in the projected class
private static WindowsRuntimeObjectReference __IStaticsType
{
get
{
var ___IStaticsType = field;
if (___IStaticsType != null && ___IStaticsType.IsInCurrentContext)
{
return ___IStaticsType;
}
return field = WindowsRuntimeObjectReference.GetActivationFactory("TypeName", iid);
}
}
private static WindowsRuntimeObjectReference __IStaticsType => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "TypeName", iid);
```

And the event accessors pass this factory reference as the `thisObject`:
Expand Down Expand Up @@ -473,10 +462,10 @@ public static EventHandlerEventSource SomeStaticEvent(

### The Activation Factory Cache

The static property `__IStaticsType` uses a **semi-cached** pattern:
The static property `__IStaticsType` uses a **semi-cached** pattern (implemented by `WindowsRuntimeObjectReference.GetActivationFactory(ref ...)`):

1. On first access: calls `WindowsRuntimeObjectReference.GetActivationFactory(...)` and stores the result.
2. On subsequent accesses: checks `IsInCurrentContext`. If the current COM context matches the one where the factory was created, returns the cached value.
1. On first access: calls `WindowsRuntimeObjectReference.GetActivationFactory(...)` and stores the result in the backing field.
2. On subsequent accesses: returns the cached value, as long as it can be used from the current COM context (free-threaded factories always can, context-aware ones are checked with `IsInCurrentContext`).
3. If the context has changed (e.g., thread apartment transition): **re-fetches** the activation factory and **overwrites** the cached field.

This means the cached `WindowsRuntimeObjectReference` for the activation factory can be replaced at any time if there's a context switch.
Expand All @@ -492,7 +481,7 @@ private protected sealed override bool DerivedIsInCurrentContext()
}
```

When this returns `false`, the generated code discards the cached activation factory and creates a fresh one. This is where the concern about static events arises.
When this returns `false`, the cached activation factory is discarded and a fresh one is created. This is where the concern about static events arises.

### Static Event Lifecycle Analysis

Expand Down Expand Up @@ -520,11 +509,11 @@ MyRuntimeClass.StaticEvent += MyHandler;

- Code on a different thread (different COM apartment) accesses `__IStaticsType`.
- `IsInCurrentContext` returns `false` for `A`.
- A new activation factory `B` is fetched and stored in `field`, **replacing** `A`.
- A new activation factory `B` is fetched and stored in the static field, **replacing** `A`.

**Step 3: What happens to `A`?**

- `A` is no longer referenced by the static `field` (it was overwritten by `B`).
- `A` is no longer referenced by the static field (it was overwritten by `B`).
- The `ConditionalWeakTable` used `A` as a **weak key**. Once `A` has no strong references, it becomes eligible for GC.
- When `A` is collected, the `ConditionalWeakTable` automatically removes the entry, which means the `EventSource<T>` is also eligible for GC.
- The `EventSource<T>` held a `WeakReference<object>` to the `EventSourceState<T>`.
Expand Down Expand Up @@ -617,6 +606,6 @@ In short, changing the key alone is not the whole answer: it must be paired with

The root cause is that the activation factory object reference is an **unstable key** that can be replaced on context switches, yet it's also the key that keeps the `EventSource<T>` (and indirectly the `EventSourceState<T>` with its token) reachable. The fix must ensure the old activation factory (and therefore the old event source / state) remains reachable while subscriptions are active. This is safe because `EventSource<T>` already handles cross-context calls correctly — `WindowsRuntimeObjectReference.AsValue()` / `GetThisPtrWithContextUnsafe()` will marshal to the correct context via COM context callbacks when needed.

**Keep a strong reference to the activation factory while subscriptions are active** — The `EventSourceState<T>` (or the `EventSource<T>`) could hold a strong reference back to the activation factory object reference that was used during subscription. Because `ConditionalWeakTable` uses weak keys, keeping a strong reference to the old activation factory prevents it from being collected, which in turn prevents the table entry (and the `EventSource<T>`) from being evicted. When the activation factory property is later accessed from a different context, it will produce a new `WindowsRuntimeObjectReference` and cache it in `field`, but the old one remains alive (held by the state). The `ConditionalWeakTable` lookup from the new context won't find a match (different key identity), but the **`EventSourceCache`** (keyed by native pointer, not object identity) can reconnect a new `EventSource<T>` to the surviving `EventSourceState<T>` — provided the native object supports `IWeakReferenceSource`. If it doesn't (which is the common case for static factories), an additional mechanism would be needed — for instance, having the generated code also maintain a direct strong reference to the `EventSource<T>` in a static field while subscriptions are active, bypassing the `ConditionalWeakTable` for the reconnection step.
**Keep a strong reference to the activation factory while subscriptions are active** — The `EventSourceState<T>` (or the `EventSource<T>`) could hold a strong reference back to the activation factory object reference that was used during subscription. Because `ConditionalWeakTable` uses weak keys, keeping a strong reference to the old activation factory prevents it from being collected, which in turn prevents the table entry (and the `EventSource<T>`) from being evicted. When the activation factory property is later accessed from a different context, it will produce a new `WindowsRuntimeObjectReference` and cache it in the static field, but the old one remains alive (held by the state). The `ConditionalWeakTable` lookup from the new context won't find a match (different key identity), but the **`EventSourceCache`** (keyed by native pointer, not object identity) can reconnect a new `EventSource<T>` to the surviving `EventSourceState<T>` — provided the native object supports `IWeakReferenceSource`. If it doesn't (which is the common case for static factories), an additional mechanism would be needed — for instance, having the generated code also maintain a direct strong reference to the `EventSource<T>` in a static field while subscriptions are active, bypassing the `ConditionalWeakTable` for the reconnection step.

This approach is the most targeted fix: it only keeps the factory alive for the duration of active subscriptions, the existing `EventSource<T>` correctly handles cross-context marshalling for any native calls, and it naturally cleans up when all handlers are removed (the strong reference is released, the activation factory becomes collectible, and the `ConditionalWeakTable` entry is evicted).
6 changes: 6 additions & 0 deletions docs/runtime-class-projections.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ For sealed runtime classes like `WinRTClass`, the generated constructors are rel
```csharp
public sealed class WinRTClass : WindowsRuntimeObject
{
// Cached activation factory (resolved and managed by 'WindowsRuntimeObjectReference')
private static WindowsRuntimeObjectReference _objRef_global__MyLib_WinRTClass =>
WindowsRuntimeObjectReference.GetActivationFactory(ref field, "MyLib.WinRTClass");

// Default constructor - uses activation factory directly
public WinRTClass()
: base(_objRef_global__MyLib_WinRTClass, in IID_MyLib_WinRTClass)
Expand Down Expand Up @@ -47,6 +51,8 @@ public sealed class WinRTClass : WindowsRuntimeObject
}
```

The `_objRef_*` property for the activation factory is a one-liner over its own backing field (the C# `field` keyword): `WindowsRuntimeObjectReference.GetActivationFactory(ref field, ...)` resolves the activation factory on first use, and again whenever the cached one can't be used from the current COM context. The same pattern is used for the activation factories of static and factory interfaces (including composable factories), which also take the IID of the interface to resolve.

In this example, we have a parameterless constructor and one with a `string` parameter. Any additional constructors taking parameters would use the same callback pattern (see details below), where the parameters are passed via a `ReadOnlySpan<object?>`.

> [!NOTE]
Expand Down
45 changes: 27 additions & 18 deletions src/WinRT.Projection.Writer/Factories/ClassFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -494,8 +494,8 @@ public static event {{eventType}} {{evtName}}
}

/// <summary>
/// Emits the static lazy objref property for a static factory interface (mirrors truth's
/// pattern: lazy <c>WindowsRuntimeObjectReference.GetActivationFactory(...)</c>).
/// Emits the static objref property for an activation factory interface (ie. a <c>[Static]</c>, <c>[Activatable]</c>,
/// or <c>[Composable]</c> factory interface), see <see cref="WriteActivationFactoryObjRef"/>.
/// </summary>
internal static void WriteStaticFactoryObjRef(IndentedTextWriter writer, ProjectionEmitContext context, TypeDefinition staticIface, string runtimeClassFullName, string objRefName)
{
Expand All @@ -507,24 +507,33 @@ internal static void WriteStaticFactoryObjRef(IndentedTextWriter writer, Project
return;
}

writer.WriteLine();
WriteActivationFactoryObjRef(writer, runtimeClassFullName, objRefName, ObjRefNameGenerator.WriteIidExpression(context, staticIface));
}

IndentedTextWriterCallback iid = ObjRefNameGenerator.WriteIidExpression(context, staticIface);
/// <summary>
/// Emits the static objref property for an activation factory of a given runtime class (using the property backing field to cache it).
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write to.</param>
/// <param name="runtimeClassFullName">The full name of the runtime class to get the activation factory for.</param>
/// <param name="objRefName">The name of the objref property to emit (ie. <c>_objRef_*</c>).</param>
/// <param name="iid">The IID expression for the activation factory interface, or <see langword="null"/> for the default <c>IActivationFactory</c> interface.</param>
/// <remarks>
/// This method should not be called for reference projections (where the objref is omitted).
/// </remarks>
internal static void WriteActivationFactoryObjRef(IndentedTextWriter writer, string runtimeClassFullName, string objRefName, IndentedTextWriterCallback? iid)
{
writer.WriteLine();

writer.WriteLine(isMultiline: true, $$"""
private static WindowsRuntimeObjectReference {{objRefName}}
{
get
{
var __{{objRefName}} = field;
if (__{{objRefName}} != null && __{{objRefName}}.IsInCurrentContext)
{
return __{{objRefName}};
}
return field = WindowsRuntimeObjectReference.GetActivationFactory("{{runtimeClassFullName}}", {{iid}});
}
}
""");
// The cached activation factory (the property backing field) is managed by 'WindowsRuntimeObjectReference', which also takes
// care of resolving a new activation factory when the cached one can't be used (ie. when it is accessed from a different context).
if (iid is null)
{
writer.WriteLine($"""private static WindowsRuntimeObjectReference {objRefName} => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "{runtimeClassFullName}");""");
}
else
{
writer.WriteLine($"""private static WindowsRuntimeObjectReference {objRefName} => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "{runtimeClassFullName}", {iid});""");
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,22 +42,7 @@ public static void WriteAttributedTypes(IndentedTextWriter writer, ProjectionEmi
{
string fullName = classType.FullName ?? string.Empty;
string objRefName = "_objRef_" + IidExpressionGenerator.EscapeTypeNameForIdentifier(GlobalPrefix + fullName, stripGlobal: true);
writer.WriteLine();
writer.Write($"private static WindowsRuntimeObjectReference {objRefName}");
writer.WriteLine();
writer.WriteLine(isMultiline: true, $$"""
{
get
{
var __{{objRefName}} = field;
if (__{{objRefName}} != null && __{{objRefName}}.IsInCurrentContext)
{
return __{{objRefName}};
}
return field = WindowsRuntimeObjectReference.GetActivationFactory("{{fullName}}");
}
}
""");
ClassFactory.WriteActivationFactoryObjRef(writer, fullName, objRefName, iid: null);
}

// A class can be activated through several composable factories (e.g. one per contract version), but the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;

#pragma warning disable CS1573

Expand Down Expand Up @@ -30,6 +32,49 @@ public static WindowsRuntimeObjectReference GetActivationFactory(string runtimeC
return AttachUnsafe(ref activationFactory, in iid)!;
}

/// <summary>
/// Gets a cached activation factory for the specified Windows Runtime type, resolving a new one if needed.
/// </summary>
/// <param name="location">The location of the cached activation factory (initially <see langword="null"/>), which is updated whenever a new activation factory is resolved.</param>
/// <param name="iid">The IID of the interface pointer (from the resolved activation factory) to wrap in the returned object reference.</param>
/// <returns>A <see cref="WindowsRuntimeObjectReference"/> instance wrapping an instance of the activation factory for the specified Windows Runtime type.</returns>
/// <remarks>
/// <para>
/// The cached activation factory is reused as long as it can be used from the current context. In all other cases, a new activation
/// factory is resolved and stored in <paramref name="location"/>.
/// </para>
/// <para>
/// If multiple threads resolve a new activation factory concurrently, the last one to be stored wins (all resolved instances are valid).
/// </para>
/// </remarks>
/// <inheritdoc cref="WindowsRuntimeActivationFactory.GetActivationFactoryUnsafe(string)"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static WindowsRuntimeObjectReference GetActivationFactory(
ref WindowsRuntimeObjectReference? location,
string runtimeClassName,
in Guid iid)
{
// Fast path for free-threaded activation factories (ie. almost always). Context-aware activation factories always go through the
// slow path, which also checks whether they're in the current context. We intentionally don't check 'IsInCurrentContext' here: it
// calls into a virtual method, and the guarded devirtualization for it would inline a copy of that check for each context-aware
// type (plus the 'CoGetContextToken' call) into every getter, bloating binary size. The slot is read with a volatile operation,
// as it can be updated concurrently by other threads.
return Volatile.Read(ref location) is { IsFreeThreaded: true } activationFactory
? activationFactory
: GetOrResolveActivationFactory(ref location, runtimeClassName, in iid);
}

/// <inheritdoc cref="GetActivationFactory(ref WindowsRuntimeObjectReference?, string, in Guid)"/>
/// <remarks>
/// This overload resolves the default <c>IActivationFactory</c> interface (see <see cref="GetActivationFactory(string)"/>).
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static WindowsRuntimeObjectReference GetActivationFactory(ref WindowsRuntimeObjectReference? location, string runtimeClassName)
{
// A 'null' IID means that the default 'IActivationFactory' interface should be resolved (same as for 'WindowsRuntimeActivationFactory')
return GetActivationFactory(ref location, runtimeClassName, in Unsafe.NullRef<Guid>());
}

/// <param name="activationFactory">A <see cref="WindowsRuntimeObjectReference"/> instance wrapping an instance of the activation factory for the specified Windows Runtime type, if successfully retrieved.</param>
/// <inheritdoc cref="WindowsRuntimeActivationFactory.TryGetActivationFactoryUnsafe(string, out void*)"/>
public static bool TryGetActivationFactory(string runtimeClassName, [NotNullWhen(true)] out WindowsRuntimeObjectReference? activationFactory)
Expand Down Expand Up @@ -61,4 +106,31 @@ public static bool TryGetActivationFactory(string runtimeClassName, in Guid iid,

return true;
}

/// <summary>
/// Gets the cached activation factory if it can be reused, or resolves (and caches) a new one otherwise.
/// </summary>
/// <param name="iid">The IID of the interface pointer to resolve, or a <see langword="null"/> reference for the default <c>IActivationFactory</c> interface.</param>
/// <inheritdoc cref="GetActivationFactory(ref WindowsRuntimeObjectReference?, string, in Guid)"/>
[MethodImpl(MethodImplOptions.NoInlining)]
private static WindowsRuntimeObjectReference GetOrResolveActivationFactory(
ref WindowsRuntimeObjectReference? location,
string runtimeClassName,
in Guid iid)
{
// The fast path only accepts free-threaded activation factories, so this is where cached context-aware ones are validated.
// They can be reused if they're in the current context. Without this check, they'd be resolved on every access.
if (Volatile.Read(ref location) is { IsInCurrentContext: true } cachedActivationFactory)
{
return cachedActivationFactory;
}

WindowsRuntimeObjectReference activationFactory = Unsafe.IsNullRef(in iid)
? GetActivationFactory(runtimeClassName)
: GetActivationFactory(runtimeClassName, in iid);

Volatile.Write(ref location, activationFactory);

return activationFactory;
}
}
Loading