Filter:   InfoImg
download comdelegate.h
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 121
Project Info
Shared Source Common Language Infrastructure(sscli20)
Server: Shared Source Common Language Infrastructure
Type: filesystem
...sscli20\sscli20\clr\src\vm\
   appdomain.cpp
   appdomain.hpp
   appdomain.inl
   appdomainhelper.cpp
   appdomainhelper.h
   appdomainnative.cpp
   appdomainnative.hpp
   appdomainstack.cpp
   appdomainstack.h
   appdomainstack.inl
   argslot.h
   array.cpp
   array.h
   assembly.cpp
   assembly.hpp
   assemblyname.cpp
   assemblyname.hpp
   assemblynative.cpp
   assemblynative.hpp
   assemblysink.cpp
   assemblysink.h
   assemblyspec.cpp
   assemblyspec.hpp
   binder.cpp
   binder.h
   cachelinealloc.cpp
   cachelinealloc.h
   ceeload.cpp
   ceeload.h
   ceeload.inl
   ceemain.cpp
   ceemain.h
   certificatecache.cpp
   certificatecache.h
   cgensys.h
   class.cpp
   class.h
   class.inl
   classloadlevel.h
   classnames.h
   clrex.cpp
   clrex.h
   clsload.cpp
   clsload.hpp
   clsload.inl
   codeman.cpp
   codeman.h
   codeman.inl
   comarrayhelpers.cpp
   comarrayhelpers.h
   comarrayinfo.cpp
   comarrayinfo.h
   comcallablewrapper.cpp
   comcallablewrapper.h
   comcurrency.cpp
   comcurrency.h
   comdatetime.cpp
   comdatetime.h
   comdecimal.cpp
   comdecimal.h
   comdelegate.cpp
   comdelegate.h
   comdynamic.cpp
   comdynamic.h
   comisolatedstorage.cpp
   comisolatedstorage.h
   commemoryfailpoint.cpp
   commemoryfailpoint.h
   commethodrental.cpp
   commethodrental.h
   commodule.cpp
   commodule.h
   common.cpp
   common.h
   comnumber.cpp
   comnumber.h
   comobject.cpp
   comobject.h
   comreflectioncache.hpp
   comreflectioncommon.cpp
   comreflectioncommon.h
   comstreams.cpp
   comstreams.h
   comstring.cpp
   comstring.h
   comstringbuffer.cpp
   comstringbuffer.h
   comstringcommon.h
   comsynchronizable.cpp
   comsynchronizable.h
   comsystem.cpp
   comsystem.h
   comthreadpool.cpp
   comthreadpool.h
   comutilnative.cpp
   comutilnative.h
   comvarargs.cpp
   comvarargs.h
   comvariant.cpp
   comvariant.h
   comwaithandle.cpp
   comwaithandle.h
   confighelper.cpp
   confighelper.h
   ...inedexecutionregion.cpp
   ...rainedexecutionregion.h
   context.h
   contexts.cpp
   contractimpl.cpp
   contractimpl.h
   corhost.cpp
   crossdomaincalls.cpp
   crossdomaincalls.h
   crst.cpp
   crst.h
   cryptapis.h
   ctxtcall.h
   customattribute.cpp
   customattribute.h
   custommarshalerinfo.cpp
   custommarshalerinfo.h
   dbginterface.h
   debugdebugger.cpp
   debugdebugger.h
   debughelp.cpp
   debuginfostore.cpp
   debuginfostore.h
   decodemd.cpp
   decodemd.h
   delegateinfo.h
   dllimport.cpp
   dllimport.h
   dllimportcallback.cpp
   dllimportcallback.h
   domainfile.cpp
   domainfile.h
   domainfile.inl
   dynamicmethod.cpp
   dynamicmethod.h
   ecall.cpp
   ecall.h
   ecmakey.h
   eecallconv.h
   eeconfig.cpp
   eeconfig.h
   eeconfigfactory.cpp
   eeconfigfactory.h
   eecontract.cpp
   eecontract.h
   eecontract.inl
   eedbginterface.h
   eedbginterfaceimpl.cpp
   eedbginterfaceimpl.h
   eedbginterfaceimpl.inl
   eehash.cpp
   eehash.h
   eemessagebox.cpp
   eemessagebox.h
   eepolicy.cpp
   eepolicy.h
   eeprofinterfaces.h
   eeprofinterfaces.inl
   ...rofinterfacewrapper.inl
   eetwain.cpp
   encee.h
   eventstore.cpp
   eventstore.hpp
   excep.cpp
   excep.h
   exceptmacros.h
   exinfo.cpp
   exinfo.h
   exstate.cpp
   exstate.h
   exstatecommon.h
   fcall.cpp
   fcall.h
   field.cpp
   field.h
   fieldmarshaler.cpp
   fieldmarshaler.h
   fjit_eetwain.cpp
   fjit_eetwain.h
   fptrstubs.cpp
   fptrstubs.h
   frames.cpp
   frames.h
   fusionbind.cpp
   fusioninit.cpp
   fusionsink.cpp
   fusionwrap.cpp
   fusionwrap.h
   gc.h
   gccommon.cpp
   gcdecode.cpp
   gcdesc.h
   gcee.cpp
   gceesvr.cpp
   gceewks.cpp
   gchost.cpp
   gcimpl.h
   gcscan.cpp
   gcscan.h
   gcsmp.cpp
   gcsmppriv.h
   gcsvr.cpp
   gcwks.cpp
   genericdict.cpp
   genericdict.h
   generics.cpp
   generics.h
   genmeth.cpp
   gmheap.cpp
   gmheap.hpp
   gms.h
   h2inc.pl
   handletable.cpp
   handletable.h
   handletable.inl
   handletablecache.cpp
   handletablecore.cpp
   handletablepriv.h
   handletablescan.cpp
   hash.cpp
   hash.h
   hostexecutioncontext.cpp
   hostexecutioncontext.h
   hosting.cpp
   hosting.h
   ibclogger.h
   ildump.h
   ilmarshalers.cpp
   ilmarshalers.h
   ilstubcache.cpp
   ilstubcache.h
   ilstubresolver.cpp
   ilstubresolver.h
   instmethhash.cpp
   instmethhash.h
   interopconverter.cpp
   interopconverter.h
   interoputil.cpp
   interoputil.h
   ...lidoverlappedwrappers.h
   invokeutil.cpp
   invokeutil.h
   jithelpers.cpp
   jitinterface.cpp
   jitinterface.h
   jitinterfacegen.cpp
   list.cpp
   list.h
   listlock.cpp
   listlock.h
   listlock.inl
   makefile.inc
   managedmdimport.cpp
   managedmdimport.hpp
   marshaler.h
   marshalnative.cpp
   marshalnative.h
   mdaassistants.h
   mdaassistantsptr.h
   memberload.cpp
   memberload.h
   message.cpp
   message.h
   metasig.h
   method.cpp
   method.hpp
   method.inl
   methodimpl.cpp
   methodimpl.h
   methoditer.cpp
   methoditer.h
   methodtable.cpp
   methodtable.h
   methodtable.inl
   ml.cpp
   ml.h
   mlcache.cpp
   mlcache.h
   mlgen.cpp
   mlgen.h
   mlinfo.cpp
   mlinfo.h
   mlopdef.h
   mscorlib.h
   mtypes.h
   namespace.h
   nativeoverlapped.cpp
   nativeoverlapped.h
   newcompressedstack.cpp
   newcompressedstack.h
   nsenums.h
   object.cpp
   object.h
   object.inl
   objectclone.cpp
   objectclone.h
   objecthandle.cpp
   objecthandle.h
   objectlist.cpp
   objectlist.h
   olevariant.cpp
   olevariant.h
   pefile.cpp
   pefile.h
   pefile.inl
   peimage.cpp
   peimage.h
   peimage.inl
   peimagelayout.cpp
   peimagelayout.h
   peimagelayout.inl
   pendingload.cpp
   pendingload.h
   precode.cpp
   precode.h
   prestub.cpp
   proftoeeinterfaceimpl.cpp
   proftoeeinterfaceimpl.h
   reflectclasswriter.cpp
   reflectclasswriter.h
   reflectioninvocation.cpp
   reflectioninvocation.h
   remoting.cpp
   remoting.h
   rexcep.h
   runtimeexceptionkind.h
   runtimehandles.cpp
   runtimehandles.h
   rwlock.cpp
   rwlock.h
   safehandle.cpp
   security.h
   security.inl
   securityattributes.cpp
   securityattributes.h
   securityconfig.cpp
   securityconfig.h
   securitydeclarative.cpp
   securitydeclarative.h
   securitydescriptor.cpp
   securitydescriptor.h
   ...descriptorappdomain.cpp
   ...tydescriptorappdomain.h
   ...ydescriptorassembly.cpp
   ...itydescriptorassembly.h
   securityhostprotection.cpp
   securityhostprotection.h
   securityimperative.cpp
   securityimperative.h
   securitymeta.cpp
   securitymeta.h
   securitypolicy.cpp
   securitypolicy.h
   securitystackwalk.cpp
   securitystackwalk.h
   ...transparentassembly.cpp
   ...tytransparentassembly.h
   sigformat.cpp
   sigformat.h
   siginfo.cpp
   siginfo.hpp
   simplerwlock.cpp
   simplerwlock.hpp
   sourceline.cpp
   sourceline.h
   sources.dac
   sources.inc
   specialstatics.h
   spinlock.cpp
   spinlock.h
   stackbuildersink.cpp
   stackbuildersink.h
   stackcompressor.cpp
   stackcompressor.h
   stackingallocator.cpp
   stackingallocator.h
   stackprobe.h
   stackprobe.inl
   stackwalk.cpp
   stackwalk.h
   stackwalktypes.h
   stringliteralmap.cpp
   stringliteralmap.h
   strongname.cpp
   stubgen.h
   stublink.cpp
   stublink.h
   stublink.inl
   stubmgr.cpp
   stubmgr.h
   syncblk.cpp
   syncblk.h
   syncblk.inl
   syncclean.cpp
   syncclean.hpp
   synch.cpp
   synch.h
   ...zationcontextnative.cpp
   ...nizationcontextnative.h
   testhookmgr.cpp
   testhookmgr.h
   thekey.h
   threads.cpp
   threads.h
   threads.inl
   tokeniter.cpp
   tokeniter.hpp
   typectxt.cpp
   typectxt.h
   typedesc.cpp
   typedesc.h
   typedesc.inl
   typehandle.cpp
   typehandle.h
   typehandle.inl
   typehash.cpp
   typehash.h
   typekey.h
   typeparse.cpp
   typeparse.h
   typestring.cpp
   typestring.h
   umthunkhash.cpp
   umthunkhash.h
   util.cpp
   util.hpp
   validator.cpp
   vars.cpp
   vars.hpp
   verifier.cpp
   verifier.hpp
   veropcodes.hpp
   vertable.h
   virtualcallstub.cpp
   virtualcallstub.h
   vmholder.h
   win32threadpool.cpp
   win32threadpool.h
   wrappers.h

// ==++==
// 
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
// 
// ==--==
// This module contains the native methods for the delegate class
//
// Date: June 1998
////////////////////////////////////////////////////////////////////////////////

#ifndef _COMDELEGATE_H_
#define _COMDELEGATE_H_

class Stub;
class ShuffleThunkCache;

#include "cgensys.h"
#include "dllimportcallback.h"
#include "comvariant.h"
#include "mlcache.h"

typedef ArgBasedStubCache MulticastStubCache;


VOID GenerateShuffleArray(MethodDesc* pInvoke, MethodDesc *pTargetMeth, struct ShuffleEntry * pShuffleEntryArray, size_t nEntries);


// This class represents the native methods for the Delegate class
class COMDelegate
{
private:
    // friend VOID CPUSTUBLINKER::EmitMulticastInvoke(...);
    // friend VOID CPUSTUBLINKER::EmitShuffleThunk(...);
    friend class CPUSTUBLINKER;
    friend class DelegateInvokeStubManager;
    friend class SecureDelegateFrame;
    friend BOOL MulticastFrame::TraceFrame(Thread *thread, BOOL fromPatch, 
                                TraceDestination *trace, REGDISPLAY *regs);

    static MulticastStubCache* m_pSecureDelegateStubCache;
    static MulticastStubCache* m_pMulticastStubCache;
    static Stub* s_pInvokeStub;
    static Stub* s_pHasRetBuffInvokeStub;

    static MethodTable* s_pIAsyncResult;    // points to System.IAsyncResult's method table
    static MethodTable* s_pAsyncCallback;   // points to System.AsyncCallBack's method table

    static CrstStatic   s_DelegateToFPtrHashCrst;   // Lock for the following hash.
    static PtrHashMap*  s_pDelegateToFPtrHash;      // Hash table containing the Delegate->FPtr pairs
                                                    // passed out to unmanaged code.
public:
    static ShuffleThunkCache *m_pShuffleThunkCache;

    static void Init();

    static FCDECL3(void, DelegateConstruct, Object* refThis, Object* target, SLOT method);

    static FCDECL1(Object*, InternalAlloc, void* target);
    static FCDECL1(Object*, InternalAllocLike, Object* pThis);
    static FCDECL2(FC_BOOL_RET, InternalEqualTypes, Object* pThis, Object *pThat);
    
    static FCDECL3(void*, AdjustTarget, Object* refThis, Object* target, SLOT method);
    static FCDECL2(void*, GetCallStub, Object* refThis, SLOT method);

    static FCDECL5(FC_BOOL_RET, BindToMethodName, Object* refThisUNSAFE, Object* targetUNSAFE, void *methodType, StringObject* methodNameUNSAFE, int flags);

    static FCDECL5(FC_BOOL_RET, BindToMethodInfo, Object* refThisUNSAFE, Object* targetUNSAFE, MethodDesc *method, void *methodType, int flags);

    // This gets the MethodInfo for a delegate, creating it if necessary
    static FCDECL1(MethodDesc*, FindMethodHandle, Object* refThis);

    // Get the invoke method for the delegate. Used to transition delegates to multicast delegates.
    static FCDECL1(SLOT, GetMulticastInvoke, Object* refThis);
    static FCDECL1(MethodDesc*, GetInvokeMethod, Object* refThis);
    static SLOT GetSecureInvoke(MethodDesc* pMD);
    // determines whether the delegate needs to be wrapped
    static BOOL NeedsSecureDelegate(Assembly* pCreatorAssembly, AppDomain *pCreatorDomain, MethodDesc* pTargetMD);
    // on entry delegate points to the delegate to wrap
    static DELEGATEREF CreateSecureDelegate(DELEGATEREF delegate, Assembly* pCreatorAssembly, MethodDesc* pTargetMD);

    // Marshals a delegate to a unmanaged callback.
    static LPVOID ConvertToCallback(OBJECTREF pDelegate);

    // Marshals an unmanaged callback to Delegate
    static OBJECTREF ConvertToDelegate(LPVOID pCallback, MethodTable* pMT);

    // Returns the unmanaged callsite for a function pointer wrapped in a delegate
    static FCDECL1(void*, GetUnmanagedCallSite, Object* refThisUNSAFE);


    // Creates the ML marshaling stub for a delegate -> unmanaged call
    static Stub* ComputeDllImportStub(MethodDesc *pMD);

    static void ValidateDelegatePInvoke(MethodDesc* pMD);

    // Creates the runtime "DllImport" stub for a delegate -> unmanaged call
    static Stub* CreateGenericDllImportStubForDelegate(StubLinker *pstublinker, UINT numStackBytes, DelegateEEClass* pClass);

    static void RemoveEntryFromFPtrHash(UPTR key);
    
    // Decides if pcls derives from Delegate.
    static BOOL IsDelegate(MethodTable *pMT);

    // Decides if this is a secure delegate
    static BOOL IsSecureDelegate(DELEGATEREF dRef);
   
    // Get the cpu stub for a delegate invoke.
    static Stub *GetInvokeMethodStub(EEImplMethodDesc* pMD);

    // get the one single delegate invoke stub
    static Stub *TheDelegateInvokeStub(BOOL bHasReturnBuffer = FALSE);

    static void DoUnmanagedCodeAccessCheck(MethodDesc* pMeth);

    static MethodDesc * __fastcall GetMethodDesc(OBJECTREF obj);
    static OBJECTREF GetTargetObject(OBJECTREF obj);

    static BOOL IsTrueMulticastDelegate(OBJECTREF delegate);

private:

    static Stub* SetupShuffleThunk(DelegateEEClass *pDelCls, MethodDesc *pTargetMeth);
    static size_t GetShuffleArrayEntryCount(MethodDesc* pMD);

public:
    static MethodDesc* FindDelegateInvokeMethod(MethodTable *pMT);

    static BOOL IsMethodDescCompatible(TypeHandle   thFirstArg,
                                       TypeHandle   thExactMethodType,
                                       MethodDesc  *pTargetMethod,
                                       TypeHandle   thDelegate,
                                       MethodDesc  *pInvokeMethod,
                                       int          flags,
                                       BOOL        *pfIsOpenDelegate);
    static MethodDesc* GetDelegateCtor(TypeHandle delegateType, MethodDesc *pTargetMethod, DelegateCtorArgs *pCtorData);
    //@GENERICSVER: new (suitable for generics)
    // Method to do static validation of delegate .ctor
    static BOOL ValidateCtor(TypeHandle objHnd, TypeHandle ftnParentHnd, MethodDesc *pFtn, TypeHandle dlgtHnd);

private:
    static BOOL ValidateBeginInvoke(DelegateEEClass* pClass);   // make certain the BeginInvoke method is consistant with the Invoke Method
    static BOOL ValidateEndInvoke(DelegateEEClass* pClass);     // make certain the EndInvoke method is consistant with the Invoke Method

    static void BindToMethod(DELEGATEREF   *pRefThis,
                             OBJECTREF     *pRefFirstArg,
                             MethodDesc    *pTargetMethod,
                             MethodTable   *pExactMethodType,
                             BOOL           fIsOpenDelegate,
                             BOOL           fCheckSecurity);
};

// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in bcl\system\delegate.cs.
enum DelegateBindingFlags
{
    DBF_StaticMethodOnly    =   0x00000001, // Can only bind to static target methods
    DBF_InstanceMethodOnly  =   0x00000002, // Can only bind to instance (including virtual) methods
    DBF_OpenDelegateOnly    =   0x00000004, // Only allow the creation of delegates open over the 1st argument
    DBF_ClosedDelegateOnly  =   0x00000008, // Only allow the creation of delegates closed over the 1st argument
    DBF_NeverCloseOverNull  =   0x00000010, // A null target will never been considered as a possible null 1st argument
    DBF_CaselessMatching    =   0x00000020, // Use case insensitive lookup for methods matched by name
    DBF_SkipSecurityChecks  =   0x00000040, // Skip security checks (visibility, link demand etc.)
    DBF_RelaxedSignature    =   0x00000080, // Allow relaxed signature matching (co/contra variance)
};

void DistributeEventReliably(OBJECTREF *pDelegate,
                             OBJECTREF *pDomain);

void DistributeUnhandledExceptionReliably(OBJECTREF *pDelegate,
                                          OBJECTREF *pDomain,
                                          OBJECTREF *pThrowable,
                                          BOOL       isTerminating);

// Want no unused bits in ShuffleEntry since unused bits can make
// equivalent ShuffleEntry arrays look unequivalent and deoptimize our
// hashing.
#include <pshpack1.h>

// To handle a call to a static delegate, we create an array of ShuffleEntry
// structures. Each entry instructs the shuffler to move a chunk of bytes.
// The size of the chunk is StackElemSize (typically a DWORD): long arguments
// have to be expressed as multiple ShuffleEntry's.
//
// The ShuffleEntry array serves two purposes:
//
//  1. A platform-indepedent blueprint for creating the platform-specific
//     shuffle thunk.
//  2. A hash key for finding the shared shuffle thunk for a particular
//     signature.
struct ShuffleEntry
{
    enum {
        REGMASK  = 0x8000,
        OFSMASK  = 0x7fff,
        SENTINEL = 0xffff,
    };

    // Special values:
    //  -1       - indicates end of shuffle array: stacksizedelta
    //             == difference in stack size between virtual and static sigs.
    //  high bit - indicates a register argument: mask it off and
    //             the result is an offset into ArgumentRegisters.

    union {
        UINT16    srcofs;
        CorElementType  argtype;    // AMD64: shuffle array is just types
    };
    union {
        UINT16    nStackAlignmentUnits; // IA64: shuffle array just has one element that contains 
                                        //       the number stack bytes used by the method
        UINT16    dstofs;           //if srcofs != SENTINEL
        UINT16    stacksizedelta;   //if dstofs == SENTINEL
        BOOL      isretbuffarg;     // AMD64: ret buff? (first arg only)
    };
};


#include <poppack.h>

void __stdcall DoDelegateInvokeForHostCheck(Object* pDelegate);

#endif  // _COMDELEGATE_H_