Ejemplo n.º 1
0
        public override MethodIL EmitIL()
        {
            // Target has the same signature as the Invoke method, except it's static.
            MethodSignatureBuilder builder = new MethodSignatureBuilder(Signature);

            builder.Flags = Signature.Flags | MethodSignatureFlags.Static;

            var          emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            // Load all arguments except 'this'
            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);
            }

            // Indirectly call the delegate target static method.
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));

            codeStream.Emit(ILOpcode.calli, emitter.NewToken(builder.ToSignature()));

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 2
0
        public override MethodIL EmitIL()
        {
            var          emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            // Load the stored 'this'
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));

            // Load all arguments except 'this'
            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);
            }

            // Indirectly call the delegate target
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));

            codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature));

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 3
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "Interlocked");

            if (method.HasInstantiation && method.Name == "CompareExchange")
            {
                TypeDesc   objectType            = method.Context.GetWellKnownType(WellKnownType.Object);
                MethodDesc compareExchangeObject = method.OwningType.GetKnownMethod("CompareExchange",
                                                                                    new MethodSignature(
                                                                                        MethodSignatureFlags.Static,
                                                                                        genericParameterCount: 0,
                                                                                        returnType: objectType,
                                                                                        parameters: new TypeDesc[] { objectType.MakeByRefType(), objectType, objectType }));

                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                codeStream.EmitLdArg(0);
                codeStream.EmitLdArg(1);
                codeStream.EmitLdArg(2);
                codeStream.Emit(ILOpcode.call, emit.NewToken(compareExchangeObject));
                codeStream.Emit(ILOpcode.ret);
                return(emit.Link(method));
            }

            return(null);
        }
Ejemplo n.º 4
0
        public override MethodIL EmitIL()
        {
            TypeDesc[] targetMethodParameters = new TypeDesc[Signature.Length + 1];
            targetMethodParameters[0] = Context.GetWellKnownType(WellKnownType.Object);

            for (int i = 0; i < Signature.Length; i++)
            {
                targetMethodParameters[i + 1] = Signature[i];
            }

            var targetMethodSignature = new MethodSignature(
                Signature.Flags | MethodSignatureFlags.Static, 0, Signature.ReturnType, targetMethodParameters);

            var          emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            // Load the stored 'this'
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));

            // Load all arguments except 'this'
            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);
            }

            // Indirectly call the delegate target static method.
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
            codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSignature));
            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 5
0
        public override MethodIL EmitIL()
        {
            Debug.Assert(Signature.Length > 0);

            var          emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            // Load all arguments except delegate's 'this'
            TypeDesc boxThisType = null;

            TypeDesc[] parameters = new TypeDesc[Signature.Length - 1];
            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);

                if (i == 0)
                {
                    // Ensure that we're working with an object type by boxing it here.
                    // This is to allow delegates which are generic over thier first parameter
                    // to have valid code in their thunk.
                    if (Signature[i].IsSignatureVariable)
                    {
                        boxThisType = Signature[i];
                        codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType));
                    }
                }
                else
                {
                    parameters[i - 1] = Signature[i];
                }
            }

            // Call a helper to get the actual method target
            codeStream.EmitLdArg(0);

            if (Signature[0].IsByRef)
            {
                codeStream.Emit(ILOpcode.ldnull);
            }
            else
            {
                codeStream.EmitLdArg(1);
                if (boxThisType != null)
                {
                    codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType));
                }
            }

            codeStream.Emit(ILOpcode.call, emitter.NewToken(SystemDelegateType.GetKnownMethod("GetActualTargetFunctionPointer", null)));

            MethodSignature targetSignature = new MethodSignature(0, 0, Signature.ReturnType, parameters);

            codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetSignature));
            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This thunk creates a delegate from a native function pointer
        /// by first creating a PInvokeDelegateWrapper from the function pointer
        /// and then creating the delegate from the Invoke method of the wrapper
        ///
        /// Generated IL:
        ///     ldarg   0
        ///     newobj PInvokeDelegateWrapper.ctor
        ///     dup
        ///     ldvirtftn PInvokeDelegateWrapper.Invoke
        ///     newobj DelegateType.ctor
        ///     ret
        ///
        /// Equivalent C#
        ///     return new DelegateType(new PInvokeDelegateWrapper(functionPointer).Invoke)
        /// </summary>
        public override MethodIL EmitIL()
        {
            var          emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            codeStream.EmitLdArg(0);

            codeStream.Emit(ILOpcode.newobj, emitter.NewToken(
                                _interopStateManager.GetPInvokeDelegateWrapper(DelegateType)
                                .GetPInvokeDelegateWrapperMethod(PInvokeDelegateWrapperMethodKind.Constructor)));

            codeStream.Emit(ILOpcode.dup);

            codeStream.Emit(ILOpcode.ldvirtftn, emitter.NewToken(
                                _interopStateManager.GetPInvokeDelegateWrapper(DelegateType)
                                .GetPInvokeDelegateWrapperMethod(PInvokeDelegateWrapperMethodKind.Invoke)));

            codeStream.Emit(ILOpcode.newobj, emitter.NewToken(
                                _delegateType.GetMethod(".ctor",
                                                        new MethodSignature(MethodSignatureFlags.None,
                                                                            genericParameterCount: 0,
                                                                            returnType: Context.GetWellKnownType(WellKnownType.Void),
                                                                            parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Object),
                                                                                                         Context.GetWellKnownType(WellKnownType.IntPtr) }
                                                                            ))));

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 7
0
 private void EmitLoadInteriorAddress(ILCodeStream codeStream, int offset)
 {
     codeStream.EmitLdArg(0); // this
     codeStream.Emit(ILOpcode.ldflda, _helperFieldToken);
     codeStream.EmitLdc(offset);
     codeStream.Emit(ILOpcode.add);
 }
Ejemplo n.º 8
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "MemoryMarshal");
            string methodName = method.Name;

            if (method.Instantiation.Length != 1)
            {
                return(null); // we only handle the generic method GetArrayDataReference<T>(T[])
            }

            if (methodName == "GetArrayDataReference")
            {
                var rawArrayData = method.Context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "RawArrayData");
#if READYTORUN
                if (!rawArrayData.IsNonVersionable())
                {
                    return(null); // This is only an intrinsic if we can prove that RawArrayData is known to be of fixed offset
                }
#endif
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.ldflda, emit.NewToken(rawArrayData.GetField("Data")));
                codeStream.Emit(ILOpcode.ret);
                return(emit.Link(method));
            }

            // unknown method
            return(null);
        }
Ejemplo n.º 9
0
 private void EmitLoadInteriorAddress(ILCodeStream codeStream, int offset)
 {
     codeStream.EmitLdArg(0); // this
     codeStream.Emit(ILOpcode.ldflda, _helperFieldToken);
     codeStream.EmitLdc(offset);
     codeStream.Emit(ILOpcode.add);
 }
Ejemplo n.º 10
0
        private static MethodIL EmitInitBlock(MethodDesc method, bool unaligned)
        {
            ILEmitter    emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            codeStream.EmitLdArg(0);
            codeStream.EmitLdArg(1);
            codeStream.EmitLdArg(2);
            if (unaligned)
            {
                codeStream.EmitUnaligned();
            }
            codeStream.Emit(ILOpcode.initblk);
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(method));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Loads the value of field of a struct at argument index argIndex to stack
        /// </summary>
        private void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILCodeStream stream  = pInvokeILCodeStreams.MarshallingCodeStream;
            ILEmitter    emitter = pInvokeILCodeStreams.Emitter;

            stream.EmitLdArg(argIndex);
            stream.Emit(ILOpcode.ldfld, emitter.NewToken(field));
        }
Ejemplo n.º 12
0
        private static MethodIL EmitCopy(MethodDesc method)
        {
            Debug.Assert(method.Signature.IsStatic && method.Signature.Length == 2);

            TypeSystemContext context = method.Context;

            ILEmitter    emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();
            ILToken      token      = emit.NewToken(context.GetSignatureVariable(0, method: true));

            codeStream.EmitLdArg(0);
            codeStream.EmitLdArg(1);
            codeStream.Emit(ILOpcode.ldobj, token);
            codeStream.Emit(ILOpcode.stobj, token);
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(method));
        }
Ejemplo n.º 13
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "Stream");

            bool isRead = method.Name == "HasOverriddenBeginEndRead";

            if (!isRead && method.Name != "HasOverriddenBeginEndWrite")
            {
                return(null);
            }

            TypeDesc   streamClass = method.OwningType;
            MethodDesc beginMethod = streamClass.GetMethod(isRead ? "BeginRead" : "BeginWrite", null);
            MethodDesc endMethod   = streamClass.GetMethod(isRead ? "EndRead" : "EndWrite", null);

            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codestream = emitter.NewCodeStream();

            ILCodeLabel lOverriden = emitter.NewCodeLabel();

            ILToken beginMethodToken = emitter.NewToken(beginMethod);

            codestream.EmitLdArg(0);
            codestream.Emit(ILOpcode.ldvirtftn, beginMethodToken);
            codestream.Emit(ILOpcode.ldftn, beginMethodToken);
            codestream.Emit(ILOpcode.bne_un, lOverriden);

            ILToken endMethodToken = emitter.NewToken(endMethod);

            codestream.EmitLdArg(0);
            codestream.Emit(ILOpcode.ldvirtftn, endMethodToken);
            codestream.Emit(ILOpcode.ldftn, endMethodToken);
            codestream.Emit(ILOpcode.bne_un, lOverriden);

            codestream.EmitLdc(0);
            codestream.Emit(ILOpcode.ret);

            codestream.EmitLabel(lOverriden);
            codestream.EmitLdc(1);
            codestream.Emit(ILOpcode.ret);

            return(emitter.Link(method));
        }
Ejemplo n.º 14
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(method.OwningType.IsDelegate);
            Debug.Assert(method.IsRuntimeImplemented);

            if (method.Name == "BeginInvoke" || method.Name == "EndInvoke")
            {
                // BeginInvoke and EndInvoke are not supported on .NET Core
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                MethodDesc   notSupportedExceptionHelper = method.Context.GetHelperEntryPoint("ThrowHelpers", "ThrowPlatformNotSupportedException");
                codeStream.EmitCallThrowHelper(emit, notSupportedExceptionHelper);
                return(emit.Link(method));
            }

            if (method.Name == ".ctor")
            {
                TypeSystemContext context = method.Context;

                ILEmitter emit = new ILEmitter();

                TypeDesc   delegateType         = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
                MethodDesc objectCtorMethod     = context.GetWellKnownType(WellKnownType.Object).GetDefaultConstructor();
                FieldDesc  functionPointerField = delegateType.GetKnownField("m_functionPointer");
                FieldDesc  firstParameterField  = delegateType.GetKnownField("m_firstParameter");

                ILCodeStream codeStream = emit.NewCodeStream();
                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.call, emit.NewToken(objectCtorMethod));
                codeStream.EmitLdArg(0);
                codeStream.EmitLdArg(1);
                codeStream.Emit(ILOpcode.stfld, emit.NewToken(firstParameterField));
                codeStream.EmitLdArg(0);
                codeStream.EmitLdArg(2);
                codeStream.Emit(ILOpcode.stfld, emit.NewToken(functionPointerField));
                codeStream.Emit(ILOpcode.ret);

                return(emit.Link(method));
            }

            return(null);
        }
Ejemplo n.º 15
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(method.OwningType.IsDelegate);
            Debug.Assert(method.IsRuntimeImplemented);

            if (method.Name == "BeginInvoke" || method.Name == "EndInvoke")
            {
                // BeginInvoke and EndInvoke are not supported on .NET Core
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                MethodDesc   notSupportedExceptionHelper = method.Context.GetHelperEntryPoint("ThrowHelpers", "ThrowPlatformNotSupportedException");
                codeStream.EmitCallThrowHelper(emit, notSupportedExceptionHelper);
                return(emit.Link(method));
            }

            if (method.Name == ".ctor")
            {
                // TODO: this should be an assert that codegen never asks for this.
                // This is just a workaround for https://github.com/dotnet/corert/issues/2102
                // The code below is making a wild guess that we're creating a closed
                // instance delegate. Without shared generics, this should only happen
                // for virtual method (so we're fine there). With shared generics, this can
                // happen for anything and might be pretty wrong.
                TypeSystemContext context = method.Context;

                ILEmitter    emit             = new ILEmitter();
                TypeDesc     delegateType     = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
                MethodDesc   initializeMethod = delegateType.GetKnownMethod("InitializeClosedInstanceSlow", null);
                ILCodeStream codeStream       = emit.NewCodeStream();

                codeStream.EmitLdArg(0);
                codeStream.EmitLdArg(1);
                codeStream.EmitLdArg(2);
                codeStream.Emit(ILOpcode.call, emit.NewToken(initializeMethod));
                codeStream.Emit(ILOpcode.ret);

                return(emit.Link(method));
            }

            return(null);
        }
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.constrained, emitter.NewToken(_owningType.UnderlyingType));
            codeStream.Emit(ILOpcode.callvirt, emitter.NewToken(ObjectGetHashCodeMethod));
            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 17
0
        void EmitLoadInteriorAddress(ILCodeStream codeStream, int offset)
        {
            // This helper field is needed to generate proper GC tracking. There is no direct way
            // to create interior pointer. 
            if (_helperFieldToken == 0)
                _helperFieldToken = NewToken(_method.Context.GetWellKnownType(WellKnownType.Object).GetField("m_pEEType"));

            codeStream.EmitLdArg(0); // this
            codeStream.Emit(ILOpcode.ldflda, _helperFieldToken);
            codeStream.EmitLdc(offset);
            codeStream.Emit(ILOpcode.add);
        }
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            // InstantiateAsOpen covers the weird case of generic enums
            TypeDesc owningTypeAsOpen = _owningType.InstantiateAsOpen();

            ILCodeLabel lNotEqual = emitter.NewCodeLabel();

            // if (!(obj is {enumtype}))
            //     return false;

            codeStream.EmitLdArg(1);
            codeStream.Emit(ILOpcode.isinst, emitter.NewToken(owningTypeAsOpen));
            codeStream.Emit(ILOpcode.dup);
            codeStream.Emit(ILOpcode.brfalse, lNotEqual);

            // return ({underlyingtype})this == ({underlyingtype})obj;

            // PREFER: ILOpcode.unbox, but the codegen for that is pretty bad
            codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(Context.GetWellKnownType(WellKnownType.Object).GetKnownField("m_pEEType")));
            codeStream.EmitLdc(Context.Target.PointerSize);
            codeStream.Emit(ILOpcode.add);
            codeStream.EmitLdInd(owningTypeAsOpen);

            codeStream.EmitLdArg(0);
            codeStream.EmitLdInd(owningTypeAsOpen);

            codeStream.Emit(ILOpcode.ceq);

            codeStream.Emit(ILOpcode.ret);

            codeStream.EmitLabel(lNotEqual);
            codeStream.Emit(ILOpcode.pop);
            codeStream.EmitLdc(0);
            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 19
0
        public static MethodIL EmitIL(
#if READYTORUN
            ILCompiler.CompilationModuleGroup compilationModuleGroup,
#endif // READYTORUN
            MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "Interlocked");

            if (method.HasInstantiation && method.Name == "CompareExchange")
            {
#if READYTORUN
                // Check to see if the tokens needed to describe the CompareExchange are naturally present within
                // the compilation. The current implementation of stable tokens used by cross module inlining is not
                // compatible with rewriting the IL of a compiler generated intrinsic. Fortunately, it turns out
                // that the managed implementation of this intrinsic is correct, just a few more IL instructions.
                if (compilationModuleGroup.ContainsType(method.OwningType))
#endif // READYTORUN
                {
                    TypeDesc   objectType            = method.Context.GetWellKnownType(WellKnownType.Object);
                    MethodDesc compareExchangeObject = method.OwningType.GetKnownMethod("CompareExchange",
                                                                                        new MethodSignature(
                                                                                            MethodSignatureFlags.Static,
                                                                                            genericParameterCount: 0,
                                                                                            returnType: objectType,
                                                                                            parameters: new TypeDesc[] { objectType.MakeByRefType(), objectType, objectType }));

                    ILEmitter    emit       = new ILEmitter();
                    ILCodeStream codeStream = emit.NewCodeStream();
                    codeStream.EmitLdArg(0);
                    codeStream.EmitLdArg(1);
                    codeStream.EmitLdArg(2);
                    codeStream.Emit(ILOpcode.call, emit.NewToken(compareExchangeObject));
                    codeStream.Emit(ILOpcode.ret);
                    return(emit.Link(method));
                }
            }

            return(null);
        }
Ejemplo n.º 20
0
        private void StoreFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILCodeStream stream  = pInvokeILCodeStreams.MarshallingCodeStream;
            ILEmitter    emitter = pInvokeILCodeStreams.Emitter;

            Internal.IL.Stubs.ILLocalVariable var = emitter.NewLocal(field.FieldType);

            stream.EmitStLoc(var);

            stream.EmitLdArg(argIndex);
            stream.EmitLdLoc(var);
            stream.Emit(ILOpcode.stfld, emitter.NewToken(field));
        }
Ejemplo n.º 21
0
        public override MethodIL EmitIL()
        {
            ILEmitter    emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            Debug.Assert(Signature[0] == _helperMethod.Signature[0]);
            codeStream.EmitLdArg(0);

            Debug.Assert(_helperMethod.Signature[1].IsString);
            codeStream.Emit(ILOpcode.ldstr, emit.NewToken(DefaultAssemblyName));

            for (int i = 2; i < _helperMethod.Signature.Length; i++)
            {
                // The helper method could be expecting more arguments than what we have - check for that
                // The thunk represents one of the 6 possible overloads:
                // (String), (String, bool), (String, bool, bool)
                // (String, Func<...>, Func<...>), (String, Func<...>, Func<...>, bool), (String, Func<...>, Func<...>, bool, bool)
                // We only need 2 helpers to support all 6 overloads. The default value for the bools is false.

                if (i - 1 < Signature.Length)
                {
                    // Pass user's parameter
                    Debug.Assert(_helperMethod.Signature[i] == Signature[i - 1]);
                    codeStream.EmitLdArg(i - 1);
                }
                else
                {
                    // Pass a default value
                    Debug.Assert(_helperMethod.Signature[i].IsWellKnownType(WellKnownType.Boolean));
                    codeStream.EmitLdc(0);
                }
            }

            codeStream.Emit(ILOpcode.call, emit.NewToken(_helperMethod));
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(this));
        }
Ejemplo n.º 22
0
        private static MethodIL EmitReadWrite(MethodDesc method, bool write, bool unaligned = false)
        {
            Debug.Assert(method.Signature.IsStatic && method.Signature.Length == (write ? 2 : 1));

            TypeSystemContext context = method.Context;

            ILEmitter    emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            codeStream.EmitLdArg(0);
            if (write)
            {
                codeStream.EmitLdArg(1);
            }
            if (unaligned)
            {
                codeStream.EmitUnaligned();
            }
            codeStream.Emit(write ? ILOpcode.stobj : ILOpcode.ldobj,
                            emit.NewToken(context.GetSignatureVariable(0, method: true)));
            codeStream.Emit(ILOpcode.ret);
            return(emit.Link(method));
        }
Ejemplo n.º 23
0
        void EmitLoadInteriorAddress(ILCodeStream codeStream, int offset)
        {
            // This helper field is needed to generate proper GC tracking. There is no direct way
            // to create interior pointer.
            if (_helperFieldToken == 0)
            {
                _helperFieldToken = NewToken(_method.Context.GetWellKnownType(WellKnownType.Object).GetField("m_pEEType"));
            }

            codeStream.EmitLdArg(0); // this
            codeStream.Emit(ILOpcode.ldflda, _helperFieldToken);
            codeStream.EmitLdc(offset);
            codeStream.Emit(ILOpcode.add);
        }
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "MemoryMarshal");
            string methodName = method.Name;

            if (methodName == "GetArrayDataReference")
            {
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.ldflda, emit.NewToken(method.Context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "RawArrayData").GetField("Data")));
                codeStream.Emit(ILOpcode.ret);
                return(emit.Link(method));
            }

            // unknown method
            return(null);
        }
Ejemplo n.º 25
0
        private void EmitCalli(PInvokeILCodeStreams ilCodeStreams, CalliMarshallingMethodThunk calliThunk)
        {
            ILEmitter    emitter = ilCodeStreams.Emitter;
            ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;

            TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;

            TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

            for (int i = 1; i < _marshallers.Length; i++)
            {
                nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
            }

            MethodSignature nativeSig = new MethodSignature(
                calliThunk.TargetSignature.Flags, 0, nativeReturnType,
                nativeParameterTypes, calliThunk.TargetSignature.GetEmbeddedSignatureData());

            callsiteSetupCodeStream.EmitLdArg(calliThunk.TargetSignature.Length);
            callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
        }
Ejemplo n.º 26
0
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter             = new ILEmitter();
            ILCodeStream argSetupStream      = emitter.NewCodeStream();
            ILCodeStream callSiteSetupStream = emitter.NewCodeStream();

            // This function will look like
            //
            // !For each parameter to the delegate
            //    !if (parameter is In Parameter)
            //       localX is TypeOfParameterX&
            //       ldtoken TypeOfParameterX
            //       call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
            //       stloc localX
            //    !else
            //       localX is TypeOfParameter
            //       ldtoken TypeOfParameterX
            //       call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
            //       stloc localX

            // ldarg.3
            // call DynamicInvokeArgSetupComplete(ref ArgSetupState)

            // *** Second instruction stream starts here ***

            // ldarg.1 // Load this pointer
            // !For each parameter
            //    !if (parameter is In Parameter)
            //       ldloc localX
            //       ldobj TypeOfParameterX
            //    !else
            //       ldloc localX
            // ldarg.1
            // calli ReturnType thiscall(TypeOfParameter1, ...)
            // !if ((ReturnType == void)
            //    ldnull
            // !else if (ReturnType is a byref)
            //    ldobj StripByRef(ReturnType)
            //    box StripByRef(ReturnType)
            // !else
            //    box ReturnType
            // ret

            callSiteSetupStream.EmitLdArg(1);

            MethodSignature delegateSignature = _delegateInfo.Signature;

            TypeDesc[] targetMethodParameters = new TypeDesc[delegateSignature.Length];

            for (int paramIndex = 0; paramIndex < delegateSignature.Length; paramIndex++)
            {
                TypeDesc paramType = delegateSignature[paramIndex];
                TypeDesc localType = paramType;

                targetMethodParameters[paramIndex] = paramType;

                if (localType.IsByRef)
                {
                    // Strip ByRef
                    localType = ((ByRefType)localType).ParameterType;
                }
                else
                {
                    // Only if this is not a ByRef, convert the parameter type to something boxable.
                    // Everything but pointer types are boxable.
                    localType = ConvertToBoxableType(localType);
                }

                ILLocalVariable local = emitter.NewLocal(localType.MakeByRefType());

                callSiteSetupStream.EmitLdLoc(local);

                argSetupStream.Emit(ILOpcode.ldtoken, emitter.NewToken(localType));

                if (paramType.IsByRef)
                {
                    argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null)));
                }
                else
                {
                    argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null)));

                    callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(paramType));
                }
                argSetupStream.EmitStLoc(local);
            }

            argSetupStream.EmitLdArg(3);
            argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null)));

            callSiteSetupStream.EmitLdArg(2);

            MethodSignature targetMethodSig = new MethodSignature(0, 0, delegateSignature.ReturnType, targetMethodParameters);

            callSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSig));

            if (delegateSignature.ReturnType.IsVoid)
            {
                callSiteSetupStream.Emit(ILOpcode.ldnull);
            }
            else if (delegateSignature.ReturnType.IsByRef)
            {
                TypeDesc targetType = ((ByRefType)delegateSignature.ReturnType).ParameterType;
                callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(targetType));
                callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(targetType));
            }
            else
            {
                callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(delegateSignature.ReturnType));
            }

            callSiteSetupStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 27
0
        public override MethodIL EmitIL()
        {
            // We will generate the following code:
            //
            // object ret;
            // object[] args = new object[parameterCount];
            // args[0] = param0;
            // args[1] = param1;
            //  ...
            // try {
            //      ret = ((Func<object[], object>)dlg.m_helperObject)(args);
            // } finally {
            //      param0 = (T0)args[0];   // only generated for each byref argument
            // }
            // return (TRet)ret;

            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            TypeDesc objectType      = Context.GetWellKnownType(WellKnownType.Object);
            TypeDesc objectArrayType = objectType.MakeArrayType();

            ILLocalVariable argsLocal = emitter.NewLocal(objectArrayType);

            bool hasReturnValue = !Signature.ReturnType.IsVoid;

            bool hasRefArgs = false;

            if (Signature.Length > 0)
            {
                codeStream.EmitLdc(Signature.Length);
                codeStream.Emit(ILOpcode.newarr, emitter.NewToken(objectType));
                codeStream.EmitStLoc(argsLocal);

                for (int i = 0; i < Signature.Length; i++)
                {
                    TypeDesc paramType    = Signature[i];
                    bool     paramIsByRef = false;

                    if (paramType.IsByRef)
                    {
                        hasRefArgs  |= paramType.IsByRef;
                        paramIsByRef = true;
                        paramType    = ((ByRefType)paramType).ParameterType;
                    }

                    hasRefArgs |= paramType.IsByRef;

                    codeStream.EmitLdLoc(argsLocal);
                    codeStream.EmitLdc(i);
                    codeStream.EmitLdArg(i + 1);

                    TypeDesc boxableParamType  = DelegateDynamicInvokeThunk.ConvertToBoxableType(paramType);
                    ILToken  boxableParamToken = emitter.NewToken(boxableParamType);

                    if (paramIsByRef)
                    {
                        codeStream.Emit(ILOpcode.ldobj, boxableParamToken);
                    }
                    codeStream.Emit(ILOpcode.box, boxableParamToken);
                    codeStream.Emit(ILOpcode.stelem_ref);
                }
            }
            else
            {
                MethodDesc emptyObjectArrayMethod = Context.GetHelperEntryPoint("DelegateHelpers", "GetEmptyObjectArray");
                codeStream.Emit(ILOpcode.call, emitter.NewToken(emptyObjectArrayMethod));
                codeStream.EmitStLoc(argsLocal);
            }

            if (hasRefArgs)
            {
                // we emit a try/finally to update the args array even if an exception is thrown
                // ilgen.BeginTryBody();
            }

            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));

            MetadataType funcType         = Context.SystemModule.GetKnownType("System", "Func`2");
            TypeDesc     instantiatedFunc = funcType.MakeInstantiatedType(objectArrayType, objectType);

            codeStream.Emit(ILOpcode.castclass, emitter.NewToken(instantiatedFunc));

            codeStream.EmitLdLoc(argsLocal);

            MethodDesc invokeMethod = instantiatedFunc.GetKnownMethod("Invoke", null);

            codeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod));

            ILLocalVariable retLocal = (ILLocalVariable)(-1);

            if (hasReturnValue)
            {
                retLocal = emitter.NewLocal(objectType);
                codeStream.EmitStLoc(retLocal);
            }
            else
            {
                codeStream.Emit(ILOpcode.pop);
            }

            if (hasRefArgs)
            {
                // ILGeneratorLabel returnLabel = new ILGeneratorLabel();
                // ilgen.Emit(OperationCode.Leave, returnLabel);
                // copy back ref/out args
                //ilgen.BeginFinallyBlock();

                for (int i = 0; i < Signature.Length; i++)
                {
                    TypeDesc paramType = Signature[i];
                    if (paramType.IsByRef)
                    {
                        paramType = ((ByRefType)paramType).ParameterType;
                        TypeDesc boxableParamType  = DelegateDynamicInvokeThunk.ConvertToBoxableType(paramType);
                        ILToken  boxableParamToken = emitter.NewToken(boxableParamType);

                        // Update parameter
                        codeStream.EmitLdArg(i + 1);
                        codeStream.EmitLdLoc(argsLocal);
                        codeStream.EmitLdc(i);
                        codeStream.Emit(ILOpcode.ldelem_ref);
                        codeStream.Emit(ILOpcode.unbox_any, boxableParamToken);
                        codeStream.Emit(ILOpcode.stobj, boxableParamToken);
                    }
                }
                // ilgen.Emit(OperationCode.Endfinally);
                // ilgen.EndTryBody();
                // ilgen.MarkLabel(returnLabel);
            }

            if (hasReturnValue)
            {
                TypeDesc boxableReturnType = DelegateDynamicInvokeThunk.ConvertToBoxableType(Signature.ReturnType);
                codeStream.EmitLdLoc(retLocal);
                codeStream.Emit(ILOpcode.unbox_any, emitter.NewToken(boxableReturnType));
            }

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 28
0
        public MethodIL EmitIL()
        {
            MethodSignature targetMethodSignature = _targetMethod.Signature;

            // We have 4 code streams:
            // - _marshallingCodeStream is used to convert each argument into a native type and 
            // store that into the local
            // - callsiteSetupCodeStream is used to used to load each previously generated local
            // and call the actual target native method.
            // - _returnValueMarshallingCodeStream is used to convert the native return value 
            // to managed one.
            // - _unmarshallingCodestream is used to propagate [out] native arguments values to 
            // managed ones.
            _emitter = new ILEmitter();
            ILCodeStream fnptrLoadStream = _emitter.NewCodeStream();
            _marshallingCodeStream = _emitter.NewCodeStream();
            ILCodeStream callsiteSetupCodeStream = _emitter.NewCodeStream();
            _returnValueMarshallingCodeStream = _emitter.NewCodeStream();
            _unmarshallingCodestream = _emitter.NewCodeStream();

            TypeDesc[] nativeParameterTypes = new TypeDesc[targetMethodSignature.Length];

            //
            // Parameter marshalling
            //

            //
            // Convert each argument to something we can pass to native and store it in a local.
            // Then load the local in the second code stream.
            //
            for (int i = 0; i < targetMethodSignature.Length; i++)
            {
                // TODO: throw if there's custom marshalling

                _marshallingCodeStream.EmitLdArg(i);

                TypeDesc nativeType = MarshalArgument(targetMethodSignature[i]);

                nativeParameterTypes[i] = nativeType;

                ILLocalVariable vMarshalledTypeTemp = _emitter.NewLocal(nativeType);
                _marshallingCodeStream.EmitStLoc(vMarshalledTypeTemp);

                callsiteSetupCodeStream.EmitLdLoc(vMarshalledTypeTemp);
            }

            //
            // Return value marshalling
            //

            // TODO: throw if SetLastError is true
            // TODO: throw if there's custom marshalling

            TypeDesc nativeReturnType = MarshalReturnValue(targetMethodSignature.ReturnType);

            if (UseLazyResolution(_targetMethod, _importMetadata.Module))
            {
                MetadataType lazyHelperType = _targetMethod.Context.GetHelperType("InteropHelpers");
                FieldDesc lazyDispatchCell = new PInvokeLazyFixupField((DefType)_targetMethod.OwningType, _importMetadata);
                fnptrLoadStream.Emit(ILOpcode.ldsflda, _emitter.NewToken(lazyDispatchCell));
                fnptrLoadStream.Emit(ILOpcode.call, _emitter.NewToken(lazyHelperType.GetKnownMethod("ResolvePInvoke", null)));

                MethodSignatureFlags unmanagedCallConv = PInvokeMetadata.GetUnmanagedCallingConvention(_importMetadata.Attributes);

                MethodSignature nativeCalliSig = new MethodSignature(
                    targetMethodSignature.Flags | unmanagedCallConv, 0, nativeReturnType, nativeParameterTypes);

                ILLocalVariable vNativeFunctionPointer = _emitter.NewLocal(_targetMethod.Context.GetWellKnownType(WellKnownType.IntPtr));
                fnptrLoadStream.EmitStLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.Emit(ILOpcode.calli, _emitter.NewToken(nativeCalliSig));
            }
            else
            {
                // Eager call
                PInvokeMetadata nativeImportMetadata =
                    new PInvokeMetadata(_importMetadata.Module, _importMetadata.Name ?? _targetMethod.Name, _importMetadata.Attributes);

                MethodSignature nativeSig = new MethodSignature(
                    targetMethodSignature.Flags, 0, nativeReturnType, nativeParameterTypes);

                MethodDesc nativeMethod =
                    new PInvokeTargetNativeMethod(_targetMethod.OwningType, nativeSig, nativeImportMetadata);

                callsiteSetupCodeStream.Emit(ILOpcode.call, _emitter.NewToken(nativeMethod));
            }
            
            _unmarshallingCodestream.Emit(ILOpcode.ret);

            return _emitter.Link(_targetMethod);
        }
Ejemplo n.º 29
0
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType();

            ILLocalVariable delegateArrayLocal   = emitter.NewLocal(invocationListArrayType);
            ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
            ILLocalVariable iteratorLocal        = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
            ILLocalVariable delegateToCallLocal  = emitter.NewLocal(SystemDelegateType);

            ILLocalVariable returnValueLocal = 0;

            if (!Signature.ReturnType.IsVoid)
            {
                returnValueLocal = emitter.NewLocal(Signature.ReturnType);
            }

            // Fill in delegateArrayLocal
            // Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject

            // ldarg.0 (this pointer)
            // ldfld Delegate.HelperObjectField
            // castclass Delegate[]
            // stloc delegateArrayLocal
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
            codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType));
            codeStream.EmitStLoc(delegateArrayLocal);

            // Fill in invocationCountLocal
            // int invocationCountLocal = this.m_extraFunctionPointerOrData
            // ldarg.0 (this pointer)
            // ldfld Delegate.m_extraFunctionPointerOrData
            // stloc invocationCountLocal
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
            codeStream.EmitStLoc(invocationCountLocal);

            // Fill in iteratorLocal
            // int iteratorLocal = 0;

            // ldc.0
            // stloc iteratorLocal
            codeStream.EmitLdc(0);
            codeStream.EmitStLoc(iteratorLocal);

            // Loop across every element of the array.
            ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel();

            codeStream.EmitLabel(startOfLoopLabel);

            // Implement as do/while loop. We only have this stub in play if we're in the multicast situation
            // Find the delegate to call
            // Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal];

            // ldloc delegateArrayLocal
            // ldloc iteratorLocal
            // ldelem System.Delegate
            // stloc delegateToCallLocal
            codeStream.EmitLdLoc(delegateArrayLocal);
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType));
            codeStream.EmitStLoc(delegateToCallLocal);

            // Call the delegate
            // returnValueLocal = delegateToCallLocal(...);

            // ldloc delegateToCallLocal
            // ldfld System.Delegate.m_firstParameter
            // ldarg 1, n
            // ldloc delegateToCallLocal
            // ldfld System.Delegate.m_functionPointer
            // calli returnValueType thiscall (all the params)
            // IF there is a return value
            // stloc returnValueLocal

            codeStream.EmitLdLoc(delegateToCallLocal);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField));

            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);
            }

            codeStream.EmitLdLoc(delegateToCallLocal);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField));

            codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature));

            if (returnValueLocal != 0)
            {
                codeStream.EmitStLoc(returnValueLocal);
            }

            // Increment iteratorLocal
            // ++iteratorLocal;

            // ldloc iteratorLocal
            // ldc.i4.1
            // add
            // stloc iteratorLocal
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.EmitLdc(1);
            codeStream.Emit(ILOpcode.add);
            codeStream.EmitStLoc(iteratorLocal);

            // Check to see if the loop is done
            codeStream.EmitLdLoc(invocationCountLocal);
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel);

            // Return to caller. If the delegate has a return value, be certain to return that.
            // return returnValueLocal;

            // ldloc returnValueLocal
            // ret
            if (returnValueLocal != 0)
            {
                codeStream.EmitLdLoc(returnValueLocal);
            }

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Ejemplo n.º 30
0
        public MethodIL EmitIL()
        {
            MethodSignature targetMethodSignature = _targetMethod.Signature;

            // We have two code streams - one is used to convert each argument into a native type
            // and store that into the local. The other is used to load each previously generated local
            // and call the actual target native method.
            _emitter = new ILEmitter();
            _marshallingCodeStream = _emitter.NewCodeStream();
            ILCodeStream callsiteSetupCodeStream = _emitter.NewCodeStream();
            _returnValueMarshallingCodeStream = _emitter.NewCodeStream();

            TypeDesc[] nativeParameterTypes = new TypeDesc[targetMethodSignature.Length];

            //
            // Parameter marshalling
            //

            //
            // Convert each argument to something we can pass to native and store it in a local.
            // Then load the local in the second code stream.
            //
            for (int i = 0; i < targetMethodSignature.Length; i++)
            {
                // TODO: throw if there's custom marshalling
                TypeDesc parameterType = targetMethodSignature[i];

                _marshallingCodeStream.EmitLdArg(i);

                TypeDesc nativeType;
                if (parameterType.IsSzArray)
                {
                    nativeType = EmitArrayMarshalling((ArrayType)parameterType);
                }
                else if (parameterType.IsByRef)
                {
                    nativeType = EmitByRefMarshalling((ByRefType)parameterType);
                }
                else if (parameterType.IsString)
                {
                    nativeType = EmitStringMarshalling();
                }
                else if (parameterType.Category == TypeFlags.Boolean)
                {
                    nativeType = EmitBooleanMarshalling();
                }
                else
                {
                    if (!IsBlittableType(parameterType))
                        throw new NotSupportedException();

                    nativeType = parameterType.UnderlyingType;
                }

                nativeParameterTypes[i] = nativeType;

                ILLocalVariable vMarshalledTypeTemp = _emitter.NewLocal(nativeType);
                _marshallingCodeStream.EmitStLoc(vMarshalledTypeTemp);

                callsiteSetupCodeStream.EmitLdLoc(vMarshalledTypeTemp);
            }

            //
            // Return value marshalling
            //

            // TODO: throw if SetLastError is true
            // TODO: throw if there's custom marshalling
            TypeDesc returnType = targetMethodSignature.ReturnType;

            TypeDesc nativeReturnType;
            if (returnType.IsVoid)
            {
                nativeReturnType = returnType;
            }
            else if (returnType.Category == TypeFlags.Boolean)
            {
                nativeReturnType = EmitBooleanReturnValueMarshalling();
            }
            else
            {
                if (!IsBlittableType(returnType))
                    throw new NotSupportedException();

                nativeReturnType = returnType;
            }

            MethodSignature nativeSig = new MethodSignature(
                targetMethodSignature.Flags, 0, nativeReturnType, nativeParameterTypes);
            MethodDesc nativeMethod =
                new PInvokeTargetNativeMethod(_targetMethod.OwningType, nativeSig, _importMetadata);

            // Call the native method
            callsiteSetupCodeStream.Emit(ILOpcode.call, _emitter.NewToken(nativeMethod));
            callsiteSetupCodeStream.Emit(ILOpcode.ret);

            return _emitter.Link();
        }
Ejemplo n.º 31
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "RuntimeHelpers");
            string methodName = method.Name;

            if (methodName == "GetRawSzArrayData")
            {
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.ldflda, emit.NewToken(method.Context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "RawArrayData").GetField("Data")));
                codeStream.Emit(ILOpcode.ret);
                return(emit.Link(method));
            }

            // All the methods handled below are per-instantiation generic methods
            if (method.Instantiation.Length != 1 || method.IsTypicalMethodDefinition)
            {
                return(null);
            }

            TypeDesc elementType = method.Instantiation[0];

            // Fallback to non-intrinsic implementation for universal generics
            if (elementType.IsCanonicalSubtype(CanonicalFormKind.Universal))
            {
                return(null);
            }

            bool result;

            if (methodName == "IsReferenceOrContainsReferences")
            {
                result = elementType.IsGCPointer || (elementType is DefType defType && defType.ContainsGCPointers);
            }
            else if (methodName == "IsReference")
            {
                result = elementType.IsGCPointer;
            }
            else if (methodName == "IsBitwiseEquatable")
            {
                // Ideally we could detect automatically whether a type is trivially equatable
                // (i.e., its operator == could be implemented via memcmp). But for now we'll
                // do the simple thing and hardcode the list of types we know fulfill this contract.
                // n.b. This doesn't imply that the type's CompareTo method can be memcmp-implemented,
                // as a method like CompareTo may need to take a type's signedness into account.
                switch (elementType.UnderlyingType.Category)
                {
                case TypeFlags.Boolean:
                case TypeFlags.Byte:
                case TypeFlags.SByte:
                case TypeFlags.Char:
                case TypeFlags.UInt16:
                case TypeFlags.Int16:
                case TypeFlags.UInt32:
                case TypeFlags.Int32:
                case TypeFlags.UInt64:
                case TypeFlags.Int64:
                case TypeFlags.IntPtr:
                case TypeFlags.UIntPtr:
                    result = true;
                    break;

                default:
                    var mdType = elementType as MetadataType;
                    if (mdType != null && mdType.Name == "Rune" && mdType.Namespace == "System.Text")
                    {
                        result = true;
                    }
                    else if (mdType != null && mdType.Name == "Char8" && mdType.Namespace == "System")
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                    break;
                }
            }
            else
            {
                return(null);
            }

            ILOpcode opcode = result ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0;

            return(new ILStubMethodIL(method, new byte[] { (byte)opcode, (byte)ILOpcode.ret }, Array.Empty <LocalVariableDefinition>(), Array.Empty <object>()));
        }
Ejemplo n.º 32
0
        private void EmitDelegateCall(DelegateMarshallingMethodThunk delegateMethod, PInvokeILCodeStreams ilCodeStreams)
        {
            ILEmitter         emitter                 = ilCodeStreams.Emitter;
            ILCodeStream      fnptrLoadStream         = ilCodeStreams.FunctionPointerLoadStream;
            ILCodeStream      callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
            TypeSystemContext context                 = _targetMethod.Context;

            Debug.Assert(delegateMethod != null);

            if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseOpenStatic)
            {
                //
                // For Open static delegates call
                //     InteropHelpers.GetCurrentCalleeOpenStaticDelegateFunctionPointer()
                // which returns a function pointer. Just call the function pointer and we are done.
                //
                TypeDesc[] parameters = new TypeDesc[_marshallers.Length - 1];
                for (int i = 1; i < _marshallers.Length; i++)
                {
                    parameters[i - 1] = _marshallers[i].ManagedParameterType;
                }

                MethodSignature managedSignature = new MethodSignature(
                    MethodSignatureFlags.Static, 0, _marshallers[0].ManagedParameterType, parameters);

                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(
                                         delegateMethod.Context.GetHelperType("InteropHelpers").GetKnownMethod(
                                             "GetCurrentCalleeOpenStaticDelegateFunctionPointer", null)));

                ILLocalVariable vDelegateStub = emitter.NewLocal(
                    delegateMethod.Context.GetWellKnownType(WellKnownType.IntPtr));

                fnptrLoadStream.EmitStLoc(vDelegateStub);
                callsiteSetupCodeStream.EmitLdLoc(vDelegateStub);
                callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(managedSignature));
            }
            else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseClosed)
            {
                //
                // For closed delegates call
                //     InteropHelpers.GetCurrentCalleeDelegate<Delegate>
                // which returns the delegate. Do a CallVirt on the invoke method.
                //
                MethodDesc instantiatedHelper = delegateMethod.Context.GetInstantiatedMethod(
                    delegateMethod.Context.GetHelperType("InteropHelpers")
                    .GetKnownMethod("GetCurrentCalleeDelegate", null),
                    new Instantiation((delegateMethod.DelegateType)));

                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(instantiatedHelper));

                ILLocalVariable vDelegateStub = emitter.NewLocal(delegateMethod.DelegateType);
                fnptrLoadStream.EmitStLoc(vDelegateStub);
                fnptrLoadStream.EmitLdLoc(vDelegateStub);
                MethodDesc invokeMethod = delegateMethod.DelegateType.GetKnownMethod("Invoke", null);
                callsiteSetupCodeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod));
            }
            else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind
                     .ForwardNativeFunctionWrapper)
            {
                // if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, clear the error code before doing P/Invoke
                if (_flags.SetLastError)
                {
                    callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                     InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
                }

                //
                // For NativeFunctionWrapper we need to load the native function and call it
                //
                fnptrLoadStream.EmitLdArg(0);
                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(InteropTypes
                                                                     .GetNativeFunctionPointerWrapper(context)
                                                                     .GetMethod("get_NativeFunctionPointer", null)));

                var fnPtr = emitter.NewLocal(
                    context.GetWellKnownType(WellKnownType.IntPtr));

                fnptrLoadStream.EmitStLoc(fnPtr);
                callsiteSetupCodeStream.EmitLdLoc(fnPtr);

                TypeDesc   nativeReturnType     = _marshallers[0].NativeParameterType;
                TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

                for (int i = 1; i < _marshallers.Length; i++)
                {
                    nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
                }

                MethodSignature nativeSig = new MethodSignature(
                    MethodSignatureFlags.Static | _flags.UnmanagedCallingConvention, 0, nativeReturnType, nativeParameterTypes);

                callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));

                // if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, call the PInvokeMarshal.
                // SaveLastWin32Error so that last error can be used later by calling
                // PInvokeMarshal.GetLastWin32Error
                if (_flags.SetLastError)
                {
                    callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                     InteropTypes.GetPInvokeMarshal(context)
                                                     .GetKnownMethod("SaveLastWin32Error", null)));
                }
            }
            else
            {
                Debug.Fail("Unexpected DelegateMarshallingMethodThunkKind");
            }
        }
Ejemplo n.º 33
0
        public MethodIL EmitIL()
        {
            MethodSignature targetMethodSignature = _targetMethod.Signature;

            // We have 4 code streams:
            // - _marshallingCodeStream is used to convert each argument into a native type and
            // store that into the local
            // - callsiteSetupCodeStream is used to used to load each previously generated local
            // and call the actual target native method.
            // - _returnValueMarshallingCodeStream is used to convert the native return value
            // to managed one.
            // - _unmarshallingCodestream is used to propagate [out] native arguments values to
            // managed ones.
            _emitter = new ILEmitter();
            _marshallingCodeStream = _emitter.NewCodeStream();
            ILCodeStream callsiteSetupCodeStream = _emitter.NewCodeStream();

            _returnValueMarshallingCodeStream = _emitter.NewCodeStream();
            _unmarshallingCodestream          = _emitter.NewCodeStream();

            TypeDesc[] nativeParameterTypes = new TypeDesc[targetMethodSignature.Length];

            //
            // Parameter marshalling
            //

            //
            // Convert each argument to something we can pass to native and store it in a local.
            // Then load the local in the second code stream.
            //
            for (int i = 0; i < targetMethodSignature.Length; i++)
            {
                // TODO: throw if there's custom marshalling

                _marshallingCodeStream.EmitLdArg(i);

                TypeDesc nativeType = MarshalArgument(targetMethodSignature[i]);

                nativeParameterTypes[i] = nativeType;

                ILLocalVariable vMarshalledTypeTemp = _emitter.NewLocal(nativeType);
                _marshallingCodeStream.EmitStLoc(vMarshalledTypeTemp);

                callsiteSetupCodeStream.EmitLdLoc(vMarshalledTypeTemp);
            }

            //
            // Return value marshalling
            //

            // TODO: throw if SetLastError is true
            // TODO: throw if there's custom marshalling

            TypeDesc nativeReturnType = MarshalReturnValue(targetMethodSignature.ReturnType);

            MethodSignature nativeSig = new MethodSignature(
                targetMethodSignature.Flags, 0, nativeReturnType, nativeParameterTypes);
            MethodDesc nativeMethod =
                new PInvokeTargetNativeMethod(_targetMethod.OwningType, nativeSig, _importMetadata);

            // Call the native method
            callsiteSetupCodeStream.Emit(ILOpcode.call, _emitter.NewToken(nativeMethod));

            _unmarshallingCodestream.Emit(ILOpcode.ret);

            return(_emitter.Link());
        }
Ejemplo n.º 34
0
        public MethodIL EmitIL()
        {
            MethodSignature targetMethodSignature = _targetMethod.Signature;

            // We have 4 code streams:
            // - _marshallingCodeStream is used to convert each argument into a native type and 
            // store that into the local
            // - callsiteSetupCodeStream is used to used to load each previously generated local
            // and call the actual target native method.
            // - _returnValueMarshallingCodeStream is used to convert the native return value 
            // to managed one.
            // - _unmarshallingCodestream is used to propagate [out] native arguments values to 
            // managed ones.
            _emitter = new ILEmitter();
            _marshallingCodeStream = _emitter.NewCodeStream();
            ILCodeStream callsiteSetupCodeStream = _emitter.NewCodeStream();
            _returnValueMarshallingCodeStream = _emitter.NewCodeStream();
            _unmarshallingCodestream = _emitter.NewCodeStream();

            TypeDesc[] nativeParameterTypes = new TypeDesc[targetMethodSignature.Length];

            //
            // Parameter marshalling
            //

            //
            // Convert each argument to something we can pass to native and store it in a local.
            // Then load the local in the second code stream.
            //
            for (int i = 0; i < targetMethodSignature.Length; i++)
            {
                // TODO: throw if there's custom marshalling

                _marshallingCodeStream.EmitLdArg(i);

                TypeDesc nativeType = MarshalArgument(targetMethodSignature[i]);

                nativeParameterTypes[i] = nativeType;

                ILLocalVariable vMarshalledTypeTemp = _emitter.NewLocal(nativeType);
                _marshallingCodeStream.EmitStLoc(vMarshalledTypeTemp);

                callsiteSetupCodeStream.EmitLdLoc(vMarshalledTypeTemp);
            }

            //
            // Return value marshalling
            //

            // TODO: throw if SetLastError is true
            // TODO: throw if there's custom marshalling

            TypeDesc nativeReturnType = MarshalReturnValue(targetMethodSignature.ReturnType);

            MethodSignature nativeSig = new MethodSignature(
                targetMethodSignature.Flags, 0, nativeReturnType, nativeParameterTypes);
            MethodDesc nativeMethod =
                new PInvokeTargetNativeMethod(_targetMethod.OwningType, nativeSig, _importMetadata);

            // Call the native method
            callsiteSetupCodeStream.Emit(ILOpcode.call, _emitter.NewToken(nativeMethod));

            _unmarshallingCodestream.Emit(ILOpcode.ret);

            return _emitter.Link();
        }
Ejemplo n.º 35
0
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter                   = new ILEmitter();
            ILCodeStream argSetupStream            = emitter.NewCodeStream();
            ILCodeStream thisCallSiteSetupStream   = emitter.NewCodeStream();
            ILCodeStream staticCallSiteSetupStream = emitter.NewCodeStream();

            // This function will look like
            //
            // !For each parameter to the method
            //    !if (parameter is In Parameter)
            //       localX is TypeOfParameterX&
            //       ldtoken TypeOfParameterX
            //       call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
            //       stloc localX
            //    !else
            //       localX is TypeOfParameter
            //       ldtoken TypeOfParameterX
            //       call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
            //       stloc localX

            // ldarg.2
            // call DynamicInvokeArgSetupComplete(ref ArgSetupState)

            // *** Thiscall instruction stream starts here ***

            // ldarg.3 // Load targetIsThisCall
            // brfalse Not_this_call

            // ldarg.0 // Load this pointer
            // !For each parameter
            //    !if (parameter is In Parameter)
            //       ldloc localX
            //       ldobj TypeOfParameterX
            //    !else
            //       ldloc localX
            // ldarg.1
            // calli ReturnType thiscall(TypeOfParameter1, ...)
            // !if ((ReturnType == void)
            //    ldnull
            // !elif (ReturnType is pointer)
            //    System.Reflection.Pointer.Box(ReturnType)
            // !else
            //    box ReturnType
            // ret

            // *** Static call instruction stream starts here ***

            // Not_this_call:
            // !For each parameter
            //    !if (parameter is In Parameter)
            //       ldloc localX
            //       ldobj TypeOfParameterX
            //    !else
            //       ldloc localX
            // ldarg.1
            // calli ReturnType (TypeOfParameter1, ...)
            // !if ((ReturnType == void)
            //    ldnull
            // !elif (ReturnType is pointer)
            //    System.Reflection.Pointer.Box(ReturnType)
            // !else
            //    box ReturnType
            // ret

            ILCodeLabel lStaticCall = emitter.NewCodeLabel();

            thisCallSiteSetupStream.EmitLdArg(3); // targetIsThisCall
            thisCallSiteSetupStream.Emit(ILOpcode.brfalse, lStaticCall);
            staticCallSiteSetupStream.EmitLabel(lStaticCall);

            thisCallSiteSetupStream.EmitLdArg(0); // thisPtr

            ILToken tokDynamicInvokeParamHelperRef =
                emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null));
            ILToken tokDynamicInvokeParamHelperIn =
                emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null));

            TypeDesc[] targetMethodSignature = new TypeDesc[_targetSignature.Length];

            for (int paramIndex = 0; paramIndex < _targetSignature.Length; paramIndex++)
            {
                TypeDesc paramType = Context.GetSignatureVariable(paramIndex, true);
                DynamicInvokeMethodParameterKind paramKind = _targetSignature[paramIndex];

                if (paramKind == DynamicInvokeMethodParameterKind.Pointer)
                {
                    for (int i = 0; i < _targetSignature.GetNumberOfParameterPointerIndirections(paramIndex); i++)
                    {
                        paramType = paramType.MakePointerType();
                    }
                }

                ILToken         tokParamType = emitter.NewToken(paramType);
                ILLocalVariable local        = emitter.NewLocal(paramType.MakeByRefType());

                thisCallSiteSetupStream.EmitLdLoc(local);
                staticCallSiteSetupStream.EmitLdLoc(local);

                argSetupStream.Emit(ILOpcode.ldtoken, tokParamType);

                if (paramKind == DynamicInvokeMethodParameterKind.Reference)
                {
                    argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperRef);

                    targetMethodSignature[paramIndex] = paramType.MakeByRefType();
                }
                else
                {
                    argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperIn);

                    thisCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType);
                    staticCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType);

                    targetMethodSignature[paramIndex] = paramType;
                }
                argSetupStream.EmitStLoc(local);
            }

            argSetupStream.EmitLdArg(2); // argSetupState
            argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null)));

            thisCallSiteSetupStream.EmitLdArg(1);   // methodToCall
            staticCallSiteSetupStream.EmitLdArg(1); // methodToCall

            DynamicInvokeMethodParameterKind returnKind = _targetSignature.ReturnType;
            TypeDesc returnType = returnKind != DynamicInvokeMethodParameterKind.None ?
                                  Context.GetSignatureVariable(_targetSignature.Length, true) :
                                  Context.GetWellKnownType(WellKnownType.Void);

            if (returnKind == DynamicInvokeMethodParameterKind.Pointer)
            {
                for (int i = 0; i < _targetSignature.GetNumerOfReturnTypePointerIndirections(); i++)
                {
                    returnType = returnType.MakePointerType();
                }
            }

            MethodSignature thisCallMethodSig = new MethodSignature(0, 0, returnType, targetMethodSignature);

            thisCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(thisCallMethodSig));

            MethodSignature staticCallMethodSig = new MethodSignature(MethodSignatureFlags.Static, 0, returnType, targetMethodSignature);

            staticCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(staticCallMethodSig));

            if (returnKind == DynamicInvokeMethodParameterKind.None)
            {
                thisCallSiteSetupStream.Emit(ILOpcode.ldnull);
                staticCallSiteSetupStream.Emit(ILOpcode.ldnull);
            }
            else if (returnKind == DynamicInvokeMethodParameterKind.Pointer)
            {
                thisCallSiteSetupStream.Emit(ILOpcode.ldtoken, emitter.NewToken(returnType));
                staticCallSiteSetupStream.Emit(ILOpcode.ldtoken, emitter.NewToken(returnType));
                MethodDesc getTypeFromHandleMethod =
                    Context.SystemModule.GetKnownType("System", "Type").GetKnownMethod("GetTypeFromHandle", null);
                thisCallSiteSetupStream.Emit(ILOpcode.call, emitter.NewToken(getTypeFromHandleMethod));
                staticCallSiteSetupStream.Emit(ILOpcode.call, emitter.NewToken(getTypeFromHandleMethod));

                MethodDesc pointerBoxMethod =
                    Context.SystemModule.GetKnownType("System.Reflection", "Pointer").GetKnownMethod("Box", null);
                thisCallSiteSetupStream.Emit(ILOpcode.call, emitter.NewToken(pointerBoxMethod));
                staticCallSiteSetupStream.Emit(ILOpcode.call, emitter.NewToken(pointerBoxMethod));
            }
            else
            {
                Debug.Assert(returnKind == DynamicInvokeMethodParameterKind.Value);
                ILToken tokReturnType = emitter.NewToken(returnType);
                thisCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType);
                staticCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType);
            }

            thisCallSiteSetupStream.Emit(ILOpcode.ret);
            staticCallSiteSetupStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }