Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions src/coreclr/vm/i386/excepx86.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ AdjustContextForVirtualStub(
PCODE f_IP = GetIP(pContext);

StubCodeBlockKind sk;
VirtualCallStubManager *pMgr = VirtualCallStubManager::FindStubManager(f_IP, &sk);
VirtualCallStubManager::FindStubManager(f_IP, &sk);

if (sk == STUB_CODE_BLOCK_VSD_DISPATCH_STUB)
{
Expand Down Expand Up @@ -119,10 +119,8 @@ AdjustContextForVirtualStub(
ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
Comment thread
VSadov marked this conversation as resolved.
Resolved

DispatchHolder *holder = DispatchHolder::FromDispatchEntry(f_IP);
MethodTable *pMT = (MethodTable*)holder->stub()->expectedMT();
DispatchToken token(VirtualCallStubManager::GetTokenFromStubQuick(pMgr, f_IP, sk));
MethodDesc* pMD = VirtualCallStubManager::GetRepresentativeMethodDescFromToken(token, pMT);
stackArgumentsSize = pMD->SizeOfArgStack();
ResolveHolder *resolveHolder = ResolveHolder::FromFailEntry(holder->stub()->failTarget());
stackArgumentsSize = resolveHolder->stub()->stackArgumentsSize();
}
else
{
Expand Down
49 changes: 40 additions & 9 deletions src/coreclr/vm/virtualcallstub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "CachedInterfaceDispatchPal.h"
#include "CachedInterfaceDispatch.h"
#include "comdelegate.h"
#include "gcrefmap.h"
#include <dn-stdio.h>

#include "perfmap.h"
Expand Down Expand Up @@ -1850,6 +1851,29 @@ ResolveCacheElem* __fastcall VSD_PromoteChainEntry(ResolveCacheElem *pElem)
#endif
#endif

#ifdef TARGET_X86
static size_t GetDispatchStackArgumentsSize(DispatchToken token, MethodTable* objectType)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;

ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();

MethodDesc* pMD = VirtualCallStubManager::GetRepresentativeMethodDescFromToken(token, objectType);
PTR_BYTE pGCRefMap = pMD->FindGCRefMap(objectType, true /* isDispatch */);
if (pGCRefMap != nullptr)
{
GCRefMapDecoder decoder(pGCRefMap);
return decoder.ReadStackPop() * sizeof(TADDR);
}

return pMD->SizeOfArgStack();
}
#endif // TARGET_X86

PCODE VirtualCallStubManager::ResolveWorker(StubCallSite* pCallSite,
OBJECTREF *protectedObj,
DispatchToken token,
Expand Down Expand Up @@ -2061,20 +2085,27 @@ PCODE VirtualCallStubManager::ResolveWorker(StubCallSite* pCallSite,
pResolverFcn = (PCODE) GetEEFuncEntryPoint(ResolveWorkerAsmStub);
#endif

// First see if we've already created a resolve stub for this token
if (resolvers->SetUpProber(token.To_SIZE_T(), 0, &probeR))
size_t resolverKey = 0;
#ifdef TARGET_X86
size_t stackArgumentsSize = 0;
if (!token.IsTypedToken())
{
// Unrelated class methods can share a slot but require different null-fault stack adjustments.
stackArgumentsSize = GetDispatchStackArgumentsSize(token, objectType);
resolverKey = stackArgumentsSize;
}
#endif // TARGET_X86

// First see if we've already created a resolve stub for this token and stack size.
if (resolvers->SetUpProber(token.To_SIZE_T(), resolverKey, &probeR))
{
// Find the right resolver, make it if necessary
PCODE addrOfResolver = (PCODE)(resolvers->Find(&probeR));
if (addrOfResolver == CALL_STUB_EMPTY_ENTRY)
{
#ifdef TARGET_X86
MethodDesc* pMD = VirtualCallStubManager::GetRepresentativeMethodDescFromToken(token, objectType);
size_t stackArgumentsSize;
{
ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
stackArgumentsSize = pMD->SizeOfArgStack();
}
if (token.IsTypedToken())
stackArgumentsSize = GetDispatchStackArgumentsSize(token, objectType);
#endif // TARGET_X86

bool reenteredCooperativeGCMode = PerfMap::IsEnabled();
Expand All @@ -2092,7 +2123,7 @@ PCODE VirtualCallStubManager::ResolveWorker(StubCallSite* pCallSite,
if (reenteredCooperativeGCMode)
{
// The prober may have been invalidated by reentering cooperative GC mode, reset it
BOOL success = resolvers->SetUpProber(token.To_SIZE_T(), 0, &probeR);
BOOL success = resolvers->SetUpProber(token.To_SIZE_T(), resolverKey, &probeR);
_ASSERTE(success);
}
// Add the resolve entrypoint into the cache.
Expand Down
14 changes: 11 additions & 3 deletions src/coreclr/vm/virtualcallstub.h
Original file line number Diff line number Diff line change
Expand Up @@ -1148,8 +1148,8 @@ class ResolveCacheEntry : public Entry
/**********************************************************************************************
ResolveEntry wraps ResolveStubs and provide the concrete implementation of the abstract class Entry.
Polymorphic call sites and monomorphic calls that fail end up in a ResolveStub. Resolve stubs
are stored in hash tables keyed by token, hence the Equals function uses the embedded token in
the stub for comparison purposes. Since we are willing to allow duplicates in the hash table (as
are stored in hash tables keyed by token and, for class tokens on Windows x86, stack argument size.
Since we are willing to allow duplicates in the hash table (as
long as they are relatively rare) we do use direct comparison of the tokens rather than extracting
the fields from within the tokens, for perf reasons. */
class ResolveEntry : public Entry
Expand All @@ -1169,7 +1169,15 @@ class ResolveEntry : public Entry
inline BOOL Equals(size_t keyA, size_t keyB)
{ WRAPPER_NO_CONTRACT; return stub && (keyA == KeyA()) && (keyB == KeyB()); }
inline size_t KeyA() { WRAPPER_NO_CONTRACT; return Token(); }
inline size_t KeyB() { WRAPPER_NO_CONTRACT; return (size_t)0; }
inline size_t KeyB()
{
WRAPPER_NO_CONTRACT;
#ifdef TARGET_X86
if (stub && !DispatchToken(stub->token()).IsTypedToken())
return stub->stackArgumentsSize();
#endif // TARGET_X86
return 0;
}

void SetContents(size_t contents)
{
Expand Down
55 changes: 55 additions & 0 deletions src/tests/CoreMangLib/system/delegate/VSD/OpenDelegate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@ public class ClassA
public virtual int PublicInstanceMethod() { return 17; }
}

public class DerivedClassA : ClassA
{
public override int PublicInstanceMethod() { return 18; }
}

public class ClassB
{
public virtual int PublicInstanceMethod(int a, int b, int c, int d) { return a + b + c + d; }
}

public class DerivedClassB : ClassB
{
public override int PublicInstanceMethod(int a, int b, int c, int d) { return a + b + c + d + 1; }
}

public delegate int Delegate_TC_Int(ClassA tc);
public static MethodInfo GetMethod([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t, string method)
{
Expand All @@ -30,6 +45,46 @@ public static MethodInfo GetMethod([DynamicallyAccessedMembers(DynamicallyAccess
}
return result;
}

// This test is only expected to reproduce the original stack-recovery failure with tiered compilation
// disabled, because Tier-0 frame pointers can conceal the incorrect stack adjustment.
[Theory]
[InlineData(false)]
[InlineData(true)]
[SkipOnMono("https://github.com/dotnet/runtime/issues/137225")]
public static void NullReceiverAfterWarmingUnrelatedVirtualDelegates(bool polymorphic)
{
Func<ClassA, int> first = typeof(ClassA).GetMethod(nameof(ClassA.PublicInstanceMethod))
.CreateDelegate<Func<ClassA, int>>();
Func<ClassB, int, int, int, int, int> second = typeof(ClassB).GetMethod(nameof(ClassB.PublicInstanceMethod))
.CreateDelegate<Func<ClassB, int, int, int, int, int>>();

ClassA firstReceiver = new ClassA();
ClassB secondReceiver = new ClassB();
for (int i = 0; i < 2; i++)
{
Assert.Equal(10, second(secondReceiver, 1, 2, 3, 4));
Assert.Equal(17, first(firstReceiver));
}

if (polymorphic)
{
// Repeated dispatch misses switch the delegate from its dispatch stub to the shared resolver.
ClassA firstDerivedReceiver = new DerivedClassA();
ClassB derivedReceiver = new DerivedClassB();
for (int i = 0; i < 1024; i++)
{
Assert.Equal(18, first(firstDerivedReceiver));
Assert.Equal(17, first(firstReceiver));
Assert.Equal(11, second(derivedReceiver, 1, 2, 3, 4));
Assert.Equal(10, second(secondReceiver, 1, 2, 3, 4));
}
}

Assert.Throws<NullReferenceException>(() => second(null, 1, 2, 3, 4));
Assert.Throws<NullReferenceException>(() => first(null));
}

[OuterLoop]
[Fact]
public static int TestEntryPoint()
Expand Down
19 changes: 17 additions & 2 deletions src/tests/readytorun/tests/coldsignaturedispatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,25 @@ public static void TestEntryPoint()
{
s_isGCStress = TestLibrary.Utilities.IsGCStress;
object reference = new object();
SignatureValue result = new Caller<string>().Invoke(
new GenericTransform<string>(), new SignatureValue { Reference = reference });
Caller<string> caller = new Caller<string>();
GenericTransform<string> target = new GenericTransform<string>();
SignatureValue argument = new SignatureValue { Reference = reference };
SignatureValue result = caller.Invoke(target, argument);
Assert.Same(reference, result.Reference);

// The cold call prepares the target. Further calls install and exercise the dispatch stub.
s_isGCStress = false;
for (int i = 0; i < 2; i++)
{
result = caller.Invoke(target, argument);
Assert.Same(reference, result.Reference);
}

Assert.Throws<NullReferenceException>(() =>
{
caller.Invoke(null, default);
});

// Shared code resolves a generic virtual target at run time. The resolved instantiation
// must load its signature types before GC can scan its prestub frame.
GenericVirtualSignatureValue genericVirtualResult = new Caller<string>().InvokeGenericVirtual(
Expand Down
Loading