Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Share `ObjectiveCMarshal` reference-tracking logic between CoreCLR and NativeAOT by Copilot · Pull Request #128961 · dotnet/runtime · GitHub
Skip to content
Merged
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,9 @@ internal unsafe struct MethodTable
#if FEATURE_TYPEEQUIVALENCE
private const uint enum_flag_HasTypeEquivalence = 0x02000000;
#endif // FEATURE_TYPEEQUIVALENCE
#if FEATURE_OBJCMARSHAL
private const uint enum_flag_IsTrackedReferenceWithFinalizer = 0x04000000;
#endif // FEATURE_OBJCMARSHAL
private const uint enum_flag_HasFinalizer = 0x00100000;
private const uint enum_flag_Collectible = 0x00200000;
private const uint enum_flag_Category_Mask = 0x000F0000;
Expand DownExpand Up@@ -904,6 +907,10 @@ internal unsafe struct MethodTable
public bool HasTypeEquivalence => (Flags & enum_flag_HasTypeEquivalence) != 0;
#endif // FEATURE_TYPEEQUIVALENCE

#if FEATURE_OBJCMARSHAL
public bool IsTrackedReferenceWithFinalizer => (Flags & enum_flag_IsTrackedReferenceWithFinalizer) != 0;
#endif // FEATURE_OBJCMARSHAL

public bool HasFinalizer => (Flags & enum_flag_HasFinalizer) != 0;

public bool IsCollectible => (Flags & enum_flag_Collectible) != 0;
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

Expand DownExpand Up@@ -31,19 +32,35 @@ private static partial bool TrySetGlobalMessageSendCallback(
private static unsafe partial bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization,
ObjectHandleOnStack objectTrackingInfoTable);

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_CreateReferenceTrackingHandle")]
private static partial IntPtr CreateReferenceTrackingHandleInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static bool TryInitializeReferenceTracker(
delegate* unmanaged<void> beginEndCallback,
delegate* unmanaged<IntPtr, int> isReferencedCallback,
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization)
{
// Make a local of the readonly field because it needs to be passed by ref to a QCall
// and it is marked as readonly to prevent accidental reassignment.
ConditionalWeakTable<object, ObjcTrackingInformation> objects = s_objects;
bool result = TryInitializeReferenceTracker(
beginEndCallback,
isReferencedCallback,
trackedObjectEnteredFinalization,
ObjectHandleOnStack.Create(ref objects));
Debug.Assert(object.ReferenceEquals(objects, s_objects));

return result;
}

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_AllocateReferenceTrackingHandle")]
private static partial IntPtr AllocateReferenceTrackingHandle(ObjectHandleOnStack obj);

private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> AllocateReferenceTrackingHandle(ObjectHandleOnStack.Create(ref obj));

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ObjCMarshal_GetOrCreateReferenceTrackingMemory")]
private static partial void GetOrCreateReferenceTrackingMemoryInternal(
ObjectHandleOnStack obj,
out int memInSizeT,
out IntPtr mem);
private static unsafe bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;

[UnmanagedCallersOnly]
internal static unsafe void* InvokeUnhandledExceptionPropagation(Exception* pExceptionArg, IntPtr methodDesc, IntPtr* pContext, Exception* pException)
Expand Down
33 changes: 21 additions & 12 deletions src/coreclr/debug/daccess/request.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,10 @@
#include <interoplibabi.h>
#endif // FEATURE_COMWRAPPERS

#if defined(FEATURE_OBJCMARSHAL)
#include <interoplibinterface.h>
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
// It is unfortunate having to include this header just to get the definition of GenericModeBlock
#include <msodw.h>
Expand DownExpand Up@@ -2351,7 +2355,7 @@ ClrDataAccess::GetObjectData(CLRDATA_ADDRESS addr, struct DacpObjectData *object
objectData->ElementTypeHandle = (CLRDATA_ADDRESS)(thElem.AsTAddr());
objectData->dwRank = mt->GetRank();
objectData->dwNumComponents = pArrayObj->GetNumComponents ();
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetDataPtr (TRUE));
objectData->ArrayDataPtr = PTR_CDADDR(pArrayObj->GetGCSafeDataPtr());
objectData->ArrayBoundsPtr = HOST_CDADDR(pArrayObj->GetBoundsPtr());
objectData->ArrayLowerBoundsPtr = HOST_CDADDR(pArrayObj->GetLowerBoundsPtr());
}
Expand DownExpand Up@@ -5393,21 +5397,26 @@ namespace
#ifdef FEATURE_OBJCMARSHAL
EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY
{
PTR_SyncBlock pSyncBlk = DACGetSyncBlockFromObjectPointer(CLRDATA_ADDRESS_TO_TADDR(objAddr), target);
if (pSyncBlk != NULL)
if (g_ObjectiveCTrackingInfoTable != NULL)
{
PTR_InteropSyncBlockInfo pInfo = pSyncBlk->GetInteropInfoNoCreate();
if (pInfo != NULL)
CONDITIONAL_WEAK_TABLE_REF trackingTable = (CONDITIONAL_WEAK_TABLE_REF)ObjectFromHandle(g_ObjectiveCTrackingInfoTable);
if (trackingTable != NULL)
{
CLRDATA_ADDRESS taggedMemoryLocal = PTR_CDADDR(pInfo->GetTaggedMemory());
if (taggedMemoryLocal != NULL)
OBJECTREF object = OBJECTREF(CLRDATA_ADDRESS_TO_TADDR(objAddr));
OBJC_TRACKING_INFO_REF trackingInfo = NULL;
if (trackingTable->TryGetValue(object, &trackingInfo) && trackingInfo != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = taggedMemoryLocal;
TADDR memory = (TADDR)trackingInfo->_memory;
if (memory != NULL)
{
hasTaggedMemory = TRUE;
if (taggedMemory)
*taggedMemory = (CLRDATA_ADDRESS)memory;

if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = pInfo->GetTaggedMemorySizeInBytes();
constexpr int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
if (taggedMemorySizeInBytes)
*taggedMemorySizeInBytes = TAGGED_MEMORY_SIZE_IN_POINTERS * sizeof(TADDR);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/coreclr/inc/dacvars.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -214,6 +214,10 @@ DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList)
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_knownQueryInterfaceImplementations, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS

#ifdef FEATURE_OBJCMARSHAL
DEFINE_DACVAR(UNKNOWN_POINTER_TYPE, dac__g_ObjectiveCTrackingInfoTable, ::g_ObjectiveCTrackingInfoTable)
#endif // FEATURE_OBJCMARSHAL

#ifndef TARGET_UNIX
DEFINE_DACVAR(SIZE_T, dac__g_runtimeLoadedBaseAddress, ::g_runtimeLoadedBaseAddress)
DEFINE_DACVAR(SIZE_T, dac__g_runtimeVirtualSize, ::g_runtimeVirtualSize)
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,6 @@ namespace System.Runtime.InteropServices.ObjectiveC
public static unsafe partial class ObjectiveCMarshal
{
private static readonly IntPtr[] s_ObjcMessageSendFunctions = new IntPtr[(int)MessageSendFunction.MsgSendSuperStret + 1];
private static bool s_initialized;
private static readonly ConditionalWeakTable<object, ObjcTrackingInformation> s_objects = new();
private static delegate* unmanaged[SuppressGCTransition]<void*, int> s_IsTrackedReferenceCallback;
private static delegate* unmanaged[SuppressGCTransition]<void*, void> s_OnEnteredFinalizerQueueCallback;

Expand DownExpand Up@@ -116,94 +114,13 @@ private static bool TryInitializeReferenceTracker(

s_IsTrackedReferenceCallback = (delegate* unmanaged[SuppressGCTransition]<void*, int>)isReferencedCallback;
s_OnEnteredFinalizerQueueCallback = (delegate* unmanaged[SuppressGCTransition]<void*, void>)trackedObjectEnteredFinalization;
s_initialized = true;

return true;
}

private static IntPtr CreateReferenceTrackingHandleInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
// Rely on GetOrCreateReferenceTrackingMemoryInternal for state checking.
GetOrCreateReferenceTrackingMemoryInternal(obj, out memInSizeT, out mem);
return RuntimeImports.RhHandleAllocRefCounted(obj);
}

private static void GetOrCreateReferenceTrackingMemoryInternal(
object obj,
out int memInSizeT,
out IntPtr mem)
{
if (!s_initialized)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCMarshalNotInitialized);
}

if (!obj.GetMethodTable()->IsTrackedReferenceWithFinalizer)
{
throw new InvalidOperationException(SR.InvalidOperation_ObjectiveCTypeNoFinalizer);
}

var trackerInfo = s_objects.GetOrAdd(obj, static o => new ObjcTrackingInformation());
trackerInfo.EnsureInitialized(obj);
trackerInfo.GetTaggedMemory(out memInSizeT, out mem);
}

internal class ObjcTrackingInformation
{
// This matches the CoreCLR implementation. See
// InteropSyncBlockInfo::m_taggedAlloc in syncblk.h .
private const int TAGGED_MEMORY_SIZE_IN_POINTERS = 2;
private static IntPtr AllocateReferenceTrackingHandle(object obj)
=> RuntimeImports.RhHandleAllocRefCounted(obj);

internal IntPtr _memory;
private IntPtr _longWeakHandle;

public ObjcTrackingInformation()
{
_memory = (IntPtr)NativeMemory.AllocZeroed(TAGGED_MEMORY_SIZE_IN_POINTERS * (nuint)IntPtr.Size);
}

public void GetTaggedMemory(out int memInSizeT, out IntPtr mem)
{
memInSizeT = TAGGED_MEMORY_SIZE_IN_POINTERS;
mem = _memory;
}

public void EnsureInitialized(object o)
{
if (_longWeakHandle != IntPtr.Zero)
{
return;
}

IntPtr newHandle = RuntimeImports.RhHandleAlloc(o, GCHandleType.WeakTrackResurrection);
if (Interlocked.CompareExchange(ref _longWeakHandle, newHandle, IntPtr.Zero) != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(newHandle);
}
}

~ObjcTrackingInformation()
{
if (_longWeakHandle != IntPtr.Zero && RuntimeImports.RhHandleGet(_longWeakHandle) != null)
{
GC.ReRegisterForFinalize(this);
return;
}

if (_memory != IntPtr.Zero)
{
NativeMemory.Free((void*)_memory);
_memory = IntPtr.Zero;
}
if (_longWeakHandle != IntPtr.Zero)
{
RuntimeImports.RhHandleFree(_longWeakHandle);
_longWeakHandle = IntPtr.Zero;
}
}
}
private static bool IsTrackedReferenceWithFinalizer(object obj)
=> RuntimeHelpers.GetMethodTable(obj)->IsTrackedReferenceWithFinalizer;
}
}
2 changes: 1 addition & 1 deletion src/coreclr/vm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ set(VM_SOURCES_DAC_AND_WKS_COMMON
clsload.cpp
codeman.cpp
codeversion.cpp
conditionalweaktable.cpp
contractimpl.cpp
corhost.cpp
crst.cpp
Expand DownExpand Up@@ -277,7 +278,6 @@ list(APPEND VM_HEADERS_DAC_AND_WKS_COMMON

set(VM_SOURCES_DAC
${VM_SOURCES_DAC_AND_WKS_COMMON}
conditionalweaktable.cpp # The usage of conditionalweaktable is only in the DAC, but we put the headers in the VM to enable validation.
)

set(VM_HEADERS_DAC
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/vm/binder.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@
#include "sigbuilder.h"
#include "configuration.h"
#include "conditionalweaktable.h"
#include "interoplibinterface_comwrappers.h"
#include "interoplibinterface.h"
#include "assemblynative.hpp"

//
Expand Down
23 changes: 20 additions & 3 deletions src/coreclr/vm/conditionalweaktable.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,20 @@

#include "conditionalweaktable.h"
#include "gchandleutilities.h"

#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE

bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF* value)
{
STANDARD_VM_CONTRACT;
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
SUPPORTS_DAC;
_ASSERTE(key != nullptr && value != nullptr);

Expand All@@ -24,11 +33,19 @@ bool ConditionalWeakTableContainerObject::TryGetValue(OBJECTREF key, OBJECTREF*
int bucket = hashCode & (_buckets->GetNumComponents() - 1);
PTR_int32_t buckets = _buckets->GetDirectPointerToNonObjectElements();
DPTR(Entry) entries = _entries->GetDirectPointerToNonObjectElements();

for (int entriesIndex = buckets[bucket]; entriesIndex != -1; entriesIndex = entries[entriesIndex].Next)
{
if (entries[entriesIndex].HashCode == hashCode && ObjectFromHandle(entries[entriesIndex].depHnd) == key)
const Entry& entry = entries[entriesIndex];
if (entry.HashCode == hashCode && ObjectFromHandle(entry.depHnd) == key)
{
*value = HndGetHandleExtraInfo(entries[entriesIndex].depHnd);
#ifdef DACCESS_COMPILE
// In the DACCESS_COMPILE, the handle helper is directly accessible.
*value = GetDependentHandleSecondary(entry.depHnd);
#else
IGCHandleManager* mgr = GCHandleUtilities::GetGCHandleManager();
*value = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(entry.depHnd));
#endif // !DACCESS_COMPILE
return true;
}
}
Expand Down
16 changes: 6 additions & 10 deletions src/coreclr/vm/conditionalweaktable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,20 @@ class ConditionalWeakTableContainerObject final : public Object
ENTRYARRAYREF _entries;

public:
#ifdef DACCESS_COMPILE
bool TryGetValue(OBJECTREF key, OBJECTREF* value);
#endif
};

class ConditionalWeakTableObject final : public Object
{
friend class CoreLibBinder;
OBJECTREF _lock;
VolatilePtr<ConditionalWeakTableContainerObject, CONDITIONAL_WEAK_TABLE_CONTAINER_REF> _container;
VolatilePtr<ConditionalWeakTableContainerObject> _container;
public:
#ifdef DACCESS_COMPILE
// Currently, we only use this for access from the DAC, so we don't need to worry about
// locking or tracking the active enumerator count.
// If we need to use this in a context where the runtime isn't suspended, we need to add
// the locking and tracking support.
// This helper can be used when the runtime is suspended (for example, DAC access
// or Objective-C interop callbacks that run under GC suspension). During suspension
// the table shape is stable since no mutations can run, so lock-free lookup is safe.
// If we need to use this in a context where the runtime isn't suspended, we need to
// add locking and active enumerator tracking support.
template<typename TKey, typename TValue>
bool TryGetValue(TKey key, TValue* value)
{
Expand All@@ -67,10 +65,8 @@ class ConditionalWeakTableObject final : public Object
{
*value = (TValue)valueObj;
}

return found;
}
#endif
};

#endif // CONDITIONAL_WEAK_TABLE_H
3 changes: 3 additions & 0 deletions src/coreclr/vm/corelib.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -460,6 +460,9 @@ DEFINE_FIELD_U(_buckets, GCHandleSetObject, _buckets)
#ifdef FEATURE_OBJCMARSHAL
DEFINE_CLASS(OBJCMARSHAL, ObjectiveC, ObjectiveCMarshal)
DEFINE_METHOD(OBJCMARSHAL, INVOKEUNHANDLEDEXCEPTIONPROPAGATION, InvokeUnhandledExceptionPropagation, SM_PtrException_IntPtr_PtrIntPtr_PtrException_RetVoidPtr)
DEFINE_FIELD(OBJCMARSHAL, OBJECTS, s_objects)
DEFINE_CLASS_U(ObjectiveC, ObjectiveCMarshal+ObjcTrackingInformation, ObjcTrackingInformationObject)
DEFINE_FIELD_U(_memory, ObjcTrackingInformationObject, _memory)
#endif // FEATURE_OBJCMARSHAL

DEFINE_CLASS_U(Interop, TypeMapLazyDictionary+CallbackContext, CallbackContext)
Expand Down
3 changes: 0 additions & 3 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,9 +220,6 @@ CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCW, cdac_data<InteropSyncBlock
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, RCW, cdac_data<InteropSyncBlockInfo>::RCW)
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, CCF, cdac_data<InteropSyncBlockInfo>::CCF)
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_OBJCMARSHAL
CDAC_TYPE_FIELD(InteropSyncBlockInfo, T_POINTER, TaggedMemory, cdac_data<InteropSyncBlockInfo>::TaggedMemory)
#endif // FEATURE_OBJCMARSHAL
CDAC_TYPE_END(InteropSyncBlockInfo)

CDAC_TYPE_BEGIN(SyncBlock)
Expand Down
Loading
Loading