Repository: dotnet/runtime
File: src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs (C#)

Code before:
                throw new ArgumentException();

            Contracts.IBuiltInCOM contract = _target.Contracts.BuiltInCOM;
            TargetPointer listPtr = cleanupListPtr.ToTargetPointer(_target);

            cleanupInfos = contract.GetRCWCleanupList(listPtr);
            foreach (Contracts.RCWCleanupInfo info in cleanupInfos)
            {
                pCallback(
                    info.RCW.ToClrDataAddress(_target).Value,
                    info.Context.ToClrDataAddress(_target).Value,
                    info.STAThread.ToClrDataAddress(_target).Value,
                    info.IsFreeThreaded ? Interop.BOOL.TRUE : Interop.BOOL.FALSE,
                    token);
            }
        }
        catch (System.Exception ex)
        {
            hr = ex.HResult;
        }
#if DEBUG
        if (_legacyImpl is not null)
        {
            Dictionary<ulong, ulong> expectedElements = cleanupInfos.ToDictionary(info => info.RCW.ToClrDataAddress(_target).Value, info => info.Context.ToClrDataAddress(_target).Value);
            expectedElements.Add(default, 0);
            void* tokenDebug = GCHandle.ToIntPtr(GCHandle.Alloc(expectedElements)).ToPointer();
            delegate* unmanaged[Stdcall]<ulong, ulong, ulong, Interop.BOOL, void*, Interop.BOOL> callbackDebugPtr = &TraverseRCWCleanupListCallback;

            int hrLocal = _legacyImpl.TraverseRCWCleanupList(cleanupListPtr, callbackDebugPtr, tokenDebug);
            Debug.Assert(hrLocal == hr, $"cDAC: {hr:x}, DAC: {hrLocal:x}");
            Debug.Assert(expectedElements[default] == (ulong)cleanupInfos.Count(), $"cDAC: {cleanupInfos.Count()} elements, DAC: {expectedElements[default]} elements");
            GCHandle.FromIntPtr((nint)tokenDebug).Free();
        }
#endif
        return hr;
    }
    int ISOSDacInterface.TraverseVirtCallStubHeap(ClrDataAddress pAppDomain, int heaptype, void* pCallback)
        => _legacyImpl is not null ? _legacyImpl.TraverseVirtCallStubHeap(pAppDomain, heaptype, pCallback) : HResults.E_NOTIMPL;
    #endregion ISOSDacInterface

    #region ISOSDacInterface2
    int ISOSDacInterface2.GetObjectExceptionData(ClrDataAddress objectAddress, DacpExceptionObjectData* data)
    {
        try
        {
            Contracts.IException contract = _target.Contracts.Exception;
            Contracts.ExceptionData exceptionData = contract.GetExceptionData(objectAddress.ToTargetPointer(_target));
            data->Message = exceptionData.Message.ToClrDataAddress(_target);
            data->InnerException = exceptionData.InnerException.ToClrDataAddress(_target);
            data->StackTrace = exceptionData.StackTrace.ToClrDataAddress(_target);
            data->WatsonBuckets = exceptionData.WatsonBuckets.ToClrDataAddress(_target);

Review comment (suggestion):
nit: We can hold the reference to the GCHandle directly to call the free below instead of casting it from the IntPtr.

Code after:
        var expectedElementsDict = (Dictionary<ulong, uint>)GCHandle.FromIntPtr((nint)expectedElements).Target!;
        if (expectedElementsDict.TryGetValue(moduleAddr, out uint expectedIndex) && expectedIndex == index)
        {
            expectedElementsDict[default]++; // Increment the count for verification
        }
        else
        {
            Debug.Assert(false, $"Unexpected module address {moduleAddr:x} at index {index}");
        }
    }
#endif
    int ISOSDacInterface.TraverseModuleMap(ModuleMapType mmt, ClrDataAddress moduleAddr, delegate* unmanaged[Stdcall]<uint, ulong, void*, void> pCallback, void* token)
    {
        int hr = HResults.S_OK;
        IEnumerable<(TargetPointer Address, uint Index)> elements = Enumerable.Empty<(TargetPointer, uint)>();
        try
        {
            if (moduleAddr == 0)
                throw new ArgumentException();

            Contracts.ILoader loader = _target.Contracts.Loader;
            TargetPointer moduleAddrPtr = moduleAddr.ToTargetPointer(_target);
            Contracts.ModuleHandle moduleHandle = loader.GetModuleHandleFromModulePtr(moduleAddrPtr);
            Contracts.ModuleLookupTables lookupTables = loader.GetLookupTables(moduleHandle);
            switch (mmt)
            {
                case ModuleMapType.TYPEDEFTOMETHODTABLE:
                    elements = loader.EnumerateModuleLookupMap(lookupTables.TypeDefToMethodTable);
                    break;
                case ModuleMapType.TYPEREFTOMETHODTABLE:
                    elements = loader.EnumerateModuleLookupMap(lookupTables.TypeRefToMethodTable);
                    break;
                default:
                    throw new ArgumentException();
            }
            foreach ((TargetPointer element, uint index) in elements)
            {
                // Call the callback with each element
                pCallback(index, element.ToClrDataAddress(_target).Value, token);
            }
        }
        catch (System.Exception ex)
        {
            hr = ex.HResult;
        }
#if DEBUG
        if (_legacyImpl is not null)
        {
            Dictionary<ulong, uint> expectedElements = elements.ToDictionary(tuple => tuple.Address.ToClrDataAddress(_target).Value, tuple => tuple.Index);
            expectedElements.Add(default, 0);
            void* tokenDebug = GCHandle.ToIntPtr(GCHandle.Alloc(expectedElements)).ToPointer();