Esempio n. 1
0
 public JitAction(
     CallingConvention callingConvention = CallingConvention.Default,
     FunctionHints hints = FunctionHints.None,
     CodeGenerator codeGenerator = null)
     : base(callingConvention, hints, codeGenerator)
 {
 }
		internal static string ToString(CallingConvention flags) {
			var sb = new StringBuilder();

			switch (flags & CallingConvention.Mask) {
			case CallingConvention.Default: sb.Append("Default"); break;
			case CallingConvention.C: sb.Append("C"); break;
			case CallingConvention.StdCall: sb.Append("StdCall"); break;
			case CallingConvention.ThisCall: sb.Append("ThisCall"); break;
			case CallingConvention.FastCall: sb.Append("FastCall"); break;
			case CallingConvention.VarArg: sb.Append("VarArg"); break;
			case CallingConvention.Field: sb.Append("Field"); break;
			case CallingConvention.LocalSig: sb.Append("LocalSig"); break;
			case CallingConvention.Property: sb.Append("Property"); break;
			case CallingConvention.Unmanaged: sb.Append("Unmanaged"); break;
			case CallingConvention.GenericInst: sb.Append("GenericInst"); break;
			case CallingConvention.NativeVarArg: sb.Append("NativeVarArg"); break;
			default: sb.Append(string.Format("CC_UNKNOWN_0x{0:X}", (int)(flags & CallingConvention.Mask))); break;
			}

			if ((flags & CallingConvention.Generic) != 0)
				sb.Append(" | Generic");

			if ((flags & CallingConvention.HasThis) != 0)
				sb.Append(" | HasThis");

			if ((flags & CallingConvention.ExplicitThis) != 0)
				sb.Append(" | ExplicitThis");

			if ((flags & CallingConvention.ReservedByCLR) != 0)
				sb.Append(" | ReservedByCLR");

			return sb.ToString();
		}
 internal UnmanagedCalliDescriptor(CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
     : base()
 {
     this.Value = string.Format(CultureInfo.CurrentCulture, "unmanaged {0} {1}({2})",
         unmanagedCallConv.ToString().ToLower(CultureInfo.CurrentCulture),
         new TypeDescriptor(returnType).Value,
         string.Join(", ", CalliDescriptor.GetArguments(parameterTypes).ToArray()));
 }
Esempio n. 4
0
		internal __StandAloneMethodSig(bool unmanaged, CallingConvention unmanagedCallingConvention, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
		{
			this.unmanaged = unmanaged;
			this.unmanagedCallingConvention = unmanagedCallingConvention;
			this.callingConvention = callingConvention;
			this.returnType = returnType;
			this.parameterTypes = parameterTypes;
			this.optionalParameterTypes = optionalParameterTypes;
		}
	private SignatureHelper(Module mod, IntPtr context, IntPtr sig)
			{
				this.mod = mod;
				this.context = context;
				this.sig = sig;
				this.numArgs = 0;
				this.callConv = (CallingConvention)0;
				this.field = false;
				this.bytesOffset = -1;
				((ModuleBuilder)mod).assembly.AddDetach(this);
			}
        public CompilerFunctionCall(Compiler compiler, CompilerFunction caller, Operand target, CallingConvention callingConvention, VariableType[] arguments, VariableType returnValue)
            : base(compiler)
        {
            Contract.Requires(arguments != null);

            _caller = caller;
            _target = target;

            _functionPrototype = new FunctionDeclaration(callingConvention, arguments, returnValue);
            if (arguments != null && arguments.Length > 0)
                _args = new Operand[arguments.Length];
        }
Esempio n. 7
0
        internal FunctionDeclaration(CallingConvention callingConvention, VariableType[] arguments, VariableType returnValue)
        {
            Contract.Requires(arguments != null);

            if (callingConvention == CallingConvention.Default)
                callingConvention = CallingConventionInfo.DefaultCallingConvention;

            _callingConvention = callingConvention;
            if (arguments.Length > 32)
                throw new ArgumentException();

            SetPrototype(arguments, returnValue);
        }
        public CompilerFunctionCall(Compiler compiler, CompilerFunction caller, Operand target, CallingConvention callingConvention, Type delegateType)
            : base(compiler)
        {
            Contract.Requires(compiler != null);
            Contract.Requires(caller != null);

            _caller = caller;
            _target = target;

            _functionPrototype = new FunctionDeclaration(callingConvention, delegateType);
            if (_functionPrototype.Arguments != null && _functionPrototype.Arguments.Length > 0)
                _args = new Operand[_functionPrototype.Arguments.Length];
        }
        public static object DynamicDllFunctionInvoke(
            string dllPath,
            string entryPoint,
            MethodAttributes methodAttr,
            CallingConvention nativeCallConv,
            CharSet nativeCharSet,
            Type returnType,
            Type[] parameterTypes,
            object[] parameterValues
            )
        {
            string dllName = Path.GetFileNameWithoutExtension(dllPath);
            // ����һ����̬����(assembly)��ģ��(module)
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = string.Format("A{0}{1}",
                dllName,
                Guid.NewGuid().ToString( "N" )
                );
            AssemblyBuilder dynamicAssembly =
              AppDomain.CurrentDomain.DefineDynamicAssembly(
              assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder dynamicModule =
              dynamicAssembly.DefineDynamicModule(
              string.Format("M{0}{1}",
              dllName,
              Guid.NewGuid().ToString("N"))
              );

            // ʹ��ָ������Ϣ����ƽ̨����ǩ��
            MethodBuilder dynamicMethod =
                dynamicModule.DefinePInvokeMethod(
                entryPoint,
                dllPath,
                methodAttr,
                CallingConventions.Standard,
                returnType,
                parameterTypes,
                nativeCallConv,
                nativeCharSet
                );

            // ��������
            dynamicModule.CreateGlobalFunctions();

            // ���ƽ̨���õķ���
            MethodInfo methodInfo =
                dynamicModule.GetMethod(entryPoint, parameterTypes);
            // ���÷��йܺ�������÷��صĽ��
            object result = methodInfo.Invoke(null, parameterValues);
            return result;
        }
Esempio n. 10
0
        public unsafe MethodDesc(string name, string dll, string entryPoint, FUNCDESC funcdesc, string[] argumentNames, Func<uint, TypeDesc> typeFactory)
        {
            string tmpl = "___overloaded000";
            if ((name.Length > tmpl.Length) && (name.IndexOf("___overloaded") == (name.Length - tmpl.Length)))
                name = name.Substring(0, name.Length - tmpl.Length);

            Name = EscapMethodName(name);
            Dll = dll;
            EntryPoint = entryPoint;

            Offset = funcdesc.oVft;

            ReturnValue = new ParameterDesc(funcdesc.elemdescFunc, string.Empty, typeFactory, 0, false, null);
            List<ParameterDesc> parameters = new List<ParameterDesc>();
            for (int i = 0; i < funcdesc.cParams; i++)
                parameters.Add(new ParameterDesc(funcdesc.lprgelemdescParam[i], (i < argumentNames.Length) ? argumentNames[i] : "__arg" + i, typeFactory, 0, false, null));
            Parameters = parameters.AsReadOnly();

            //if (funcdesc.cParamsOpt != 0)
            //    throw new Exception("Variable number of optional parameters is not supported");
            //if (funcdesc.invkind != INVOKEKIND.INVOKE_FUNC)
            //    throw new Exception("Only functions are currently supported");
            if (funcdesc.cScodes >= 1)
                throw new Exception("Only one return value is supported");

            switch (funcdesc.callconv)
            {
                case System.Runtime.InteropServices.ComTypes.CALLCONV.CC_CDECL:
                    Convention = CallingConvention.Cdecl;
                    break;
                case System.Runtime.InteropServices.ComTypes.CALLCONV.CC_STDCALL:
                    Convention = CallingConvention.StdCall;
                    break;
                default:
                    throw new Exception("Calling convention " + funcdesc.callconv + " is not supported");
            }

            switch (funcdesc.funckind)
            {
                case FUNCKIND.FUNC_DISPATCH:
                case FUNCKIND.FUNC_VIRTUAL:
                case FUNCKIND.FUNC_PUREVIRTUAL:
                case FUNCKIND.FUNC_NONVIRTUAL:
                case FUNCKIND.FUNC_STATIC:
                    break;
                default:
                    throw new Exception("Function kind " + funcdesc.funckind + " is not supported");
            }
        }
Esempio n. 11
0
 public MethodSignature(
     bool hasThis,
     bool explicitThis,
     CallingConvention callingConvention,
     int genericParamCount,
     IReadOnlyList<Parameter> parameters,
     Type retType
     )
 {
     m_hasThis = hasThis;
     m_explicitThis = explicitThis;
     m_callingConvention = callingConvention.CheckDefined("callingConvention");
     m_genericParamCount = genericParamCount.CheckGTE(0, "genericParamCount");
     m_parameters = parameters.CheckNotNull("parameters");
     m_retType = retType.CheckNotNull("retType");
 }
Esempio n. 12
0
        internal FunctionDeclaration(CallingConvention callingConvention, Type delegateType)
        {
            if (delegateType == null)
                throw new ArgumentNullException("delegateType");

            if (callingConvention == CallingConvention.Default)
                callingConvention = CallingConventionInfo.DefaultCallingConvention;

            _callingConvention = callingConvention;

            if (delegateType == typeof(Action))
            {
                SetPrototype(new VariableType[0], VariableType.Invalid);
            }
            else
            {
                if (!delegateType.IsGenericType)
                    throw new ArgumentException();

                VariableType[] arguments = null;
                VariableType returnValue = VariableType.Invalid;
                Type genericType = delegateType.GetGenericTypeDefinition();
                if (genericType.FullName.StartsWith("System.Action`"))
                {
                    arguments = Array.ConvertAll(delegateType.GetGenericArguments(), Compiler.TypeToId);
                }
                else if (genericType.FullName.StartsWith("System.Func`"))
                {
                    Type[] typeArguments = delegateType.GetGenericArguments();
                    returnValue = Compiler.TypeToId(typeArguments[typeArguments.Length - 1]);
                    Array.Resize(ref typeArguments, typeArguments.Length - 1);
                    arguments = Array.ConvertAll(typeArguments, Compiler.TypeToId);
                }
                else
                {
                    throw new ArgumentException();
                }

                SetPrototype(arguments, returnValue);
            }
        }
        public DLLExportAttribute(string exportName,CallingConvention callingConvention)
        {
            ExportName = exportName;
            switch(callingConvention)
            {
                case CallingConvention.Winapi:
                case CallingConvention.StdCall:
                    Convention	= typeof(CallConvStdcall).FullName;
                    break;
                case CallingConvention.FastCall:
                    Convention	= typeof(CallConvFastcall).FullName;
                    break;
                case CallingConvention.ThisCall:
                    Convention	= typeof(CallConvThiscall).FullName;
                    break;
                case CallingConvention.Cdecl:
                    Convention	= typeof(CallConvCdecl).FullName;
                    break;

                default:
                    throw new NotImplementedException();
            }
        }
Esempio n. 14
0
		public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention,
			Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
			Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
			CallingConvention nativeCallConv, CharSet nativeCharSet)
		{
			MethodBuilder mb = DefineMethod(name, attributes | MethodAttributes.PinvokeImpl, callingConvention,
				returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
				parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
			mb.SetDllImportPseudoCustomAttribute(dllName, entryName, nativeCallConv, nativeCharSet, null, null, null, null, null);
			return mb;
		}
Esempio n. 15
0
 public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention)
 {
     m_callingConvention = callingConvention;
 }
Esempio n. 16
0
 public static void EmitCalli(ILGenerator il, OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
 {
     il.EmitCalli(opcode, unmanagedCallConv, returnType, parameterTypes);
 }
Esempio n. 17
0
        internal static MethodImportAttributes MakeFlags(bool exactSpelling, CharSet charSet, bool setLastError, CallingConvention callingConvention, bool?useBestFit, bool?throwOnUnmappable)
        {
            MethodImportAttributes result = 0;

            if (exactSpelling)
            {
                result |= MethodImportAttributes.ExactSpelling;
            }

            switch (charSet)
            {
            case CharSet.Ansi:
                result |= MethodImportAttributes.CharSetAnsi;
                break;

            case CharSet.Unicode:
                result |= MethodImportAttributes.CharSetUnicode;
                break;

            case Cci.Constants.CharSet_Auto:
                result |= MethodImportAttributes.CharSetAuto;
                break;

                // Dev10: use default without reporting an error
            }

            if (setLastError)
            {
                result |= MethodImportAttributes.SetLastError;
            }

            switch (callingConvention)
            {
            default:     // Dev10: uses default without reporting an error
                result |= MethodImportAttributes.CallingConventionWinApi;
                break;

            case CallingConvention.Cdecl:
                result |= MethodImportAttributes.CallingConventionCDecl;
                break;

            case CallingConvention.StdCall:
                result |= MethodImportAttributes.CallingConventionStdCall;
                break;

            case CallingConvention.ThisCall:
                result |= MethodImportAttributes.CallingConventionThisCall;
                break;

            case Cci.Constants.CallingConvention_FastCall:
                result |= MethodImportAttributes.CallingConventionFastCall;
                break;
            }

            if (throwOnUnmappable.HasValue)
            {
                if (throwOnUnmappable.Value)
                {
                    result |= MethodImportAttributes.ThrowOnUnmappableCharEnable;
                }
                else
                {
                    result |= MethodImportAttributes.ThrowOnUnmappableCharDisable;
                }
            }

            if (useBestFit.HasValue)
            {
                if (useBestFit.Value)
                {
                    result |= MethodImportAttributes.BestFitMappingEnable;
                }
                else
                {
                    result |= MethodImportAttributes.BestFitMappingDisable;
                }
            }

            return(result);
        }
Esempio n. 18
0
 [DllImport(libraryPath, EntryPoint = "JSValueGetType", CallingConvention = CallingConvention.Cdecl)]
Esempio n. 19
0
        public override CallingConvention GetCallingConvention(string ccName)
        {
            switch (Architecture.Name)
            {
            case "mips-be-32":
            case "mips-le-32":
            case "mips-be-64":
            case "mips-le-64":
                return(new MipsCallingConvention(Architecture)); //$ ccName?

            case "ppc-be-32":
            case "ppc-le-32":
                return(new PowerPcCallingConvention(Architecture));

            case "sparc32":
                return(new SparcCallingConvention(Architecture));

            case "x86-protected-32":
                if (this.ccX86 == null)
                {
                    var t = Type.GetType("Reko.Arch.X86.X86CallingConvention,Reko.Arch.X86", true);
                    this.ccX86 = (CallingConvention)Activator.CreateInstance(
                        t,
                        4,      // retAddressOnStack,
                        4,      // stackAlignment,
                        4,      // pointerSize,
                        true,   // callerCleanup,
                        false); // reverseArguments)
                }
                return(this.ccX86);

            case "x86-protected-64":
                return(new X86_64CallingConvention(Architecture));

            case "xtensa":
                return(new XtensaCallingConvention(Architecture));

            case "arm":
                return(new Arm32CallingConvention(Architecture));

            case "arm-64":
                return(new Arm64CallingConvention(Architecture));

            case "m68k":
                return(new M68kCallingConvention(Architecture));

            case "avr8":
                return(new Avr8CallingConvention(Architecture));

            case "msp430":
                return(new Msp430CallingConvention(Architecture));

            case "risc-v":
                if (this.ccRiscV == null)
                {
                    var t = Type.GetType("Reko.Arch.RiscV.RiscVCallingConvention,Reko.Arch.RiscV", true);
                    this.ccRiscV = (CallingConvention)Activator.CreateInstance(t, Architecture);
                }
                return(this.ccRiscV);

            case "superH-le":
            case "superH-be":
                return(new SuperHCallingConvention(Architecture));

            case "alpha":
                return(new AlphaCallingConvention(Architecture));

            case "zSeries":
                return(new zSeriesCallingConvention(Architecture));

            case "blackfin":
                return(new BlackfinCallingConvention(Architecture));

            default:
                throw new NotImplementedException(string.Format("ELF calling convention for {0} not implemented yet.", Architecture.Description));
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">Calling convention</param>
 /// <param name="genParamCount">Number of generic parameters</param>
 public MethodSig(CallingConvention callingConvention, uint genParamCount)
 {
     this.callingConvention = callingConvention;
     this.genParamCount     = genParamCount;
     this.parameters        = ThreadSafeListCreator.Create <TypeSig>();
 }
Esempio n. 21
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">Calling convention (must have Property set)</param>
 internal PropertySig(CallingConvention callingConvention)
 {
     this.callingConvention = callingConvention;
     this.parameters        = ThreadSafeListCreator.Create <TypeSig>();
 }
Esempio n. 22
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Field type</param>
 /// <param name="callingConvention">The calling convention (must have Field set)</param>
 internal FieldSig(CallingConvention callingConvention, TypeSig type)
 {
     this.callingConvention = callingConvention;
     this.type = type;
 }
Esempio n. 23
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">Calling convention</param>
 public MethodSig(CallingConvention callingConvention)
 {
     this.callingConvention = callingConvention;
     this.parameters        = ThreadSafeListCreator.Create <TypeSig>();
 }
Esempio n. 24
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">The calling convention</param>
 protected CallingConventionSig(CallingConvention callingConvention)
 {
     this.callingConvention = callingConvention;
 }
Esempio n. 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">Calling convention (must have GenericInst set)</param>
 /// <param name="size">Number of generic args</param>
 internal GenericInstMethodSig(CallingConvention callingConvention, uint size)
 {
     this.callingConvention = callingConvention;
     this.genericArgs       = ThreadSafeListCreator.Create <TypeSig>((int)size);
 }
Esempio n. 26
0
 internal UnmanagedFunctionPointerAttribute(CallingConvention callingConventionType)
 {
     _callingConvention = callingConventionType.ToString();
 }
Esempio n. 27
0
        [System.Security.SecurityCritical] // auto-generated
#endif
        private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes, 
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
            CharSet nativeCharSet)
        {
            //Global methods must be static.        
            if ((attributes & MethodAttributes.Static) == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
            }
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);
            Contract.EndContractBlock();

            CheckContext(returnType);
            CheckContext(parameterTypes);

            m_moduleData.m_fHasGlobal = true;
            return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
        }
Esempio n. 28
0
        public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if ((attributes & MethodAttributes.Static) == 0)
            {
                throw new ArgumentException("global methods must be static");
            }
            if (global_type_created != null)
            {
                throw new InvalidOperationException("global methods already created");
            }
            CreateGlobalType();
            MethodBuilder mb = global_type.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);

            addGlobalMethod(mb);
            return(mb);
        }
Esempio n. 29
0
        public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
        {
            int             stackchange = 0;
            int             cParams = 0;
            int             i;
            SignatureHelper sig;
            
            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;

            if (parameterTypes != null)
            {
                cParams = parameterTypes.Length;
            }
            
            sig = SignatureHelper.GetMethodSigHelper(
                modBuilder, 
                unmanagedCallConv, 
                returnType);
                            
            if (parameterTypes != null)
            {
                for (i = 0; i < cParams; i++) 
                {
                    sig.AddArgument(parameterTypes[i]);
                }
            }
                                  
            // If there is a non-void return type, push one.
            if (returnType != typeof(void))
                stackchange++;
                
            // Pop off arguments if any.
            if (parameterTypes != null)
                stackchange -= cParams;
                
            // Pop the native function pointer.
            stackchange--;
            UpdateStackSize(OpCodes.Calli, stackchange);

            EnsureCapacity(7);
            Emit(OpCodes.Calli);
            RecordTokenFixup();
            PutInteger4(modBuilder.GetSignatureToken(sig).Token);
        }
Esempio n. 30
0
 public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
 {
     return(GetMethodSigHelper(null, unmanagedCallingConvention, returnType));
 }
Esempio n. 31
0
 public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
 {
     return(DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet));
 }
Esempio n. 32
0
                /// <summary>
                /// Creates a method for calling with the specified signature.  The returned method has a signature
                /// of the form:
                ///
                /// (IntPtr funcAddress, arg0, arg1, ..., object[] constantPool)
                ///
                /// where IntPtr is the address of the function to be called.  The arguments types are based upon
                /// the types that the ArgumentMarshaller requires.
                /// </summary>
                private static MethodInfo /*!*/ CreateInteropInvoker(CallingConvention convention, ArgumentMarshaller /*!*/[] /*!*/ sig, INativeType nativeRetType, bool retVoid, List <object> constantPool)
                {
                    Type[] sigTypes = new Type[sig.Length + 2];
                    sigTypes[0] = typeof(IntPtr);
                    for (int i = 0; i < sig.Length; i++)
                    {
                        sigTypes[i + 1] = sig[i].ArgumentExpression.Type;
                    }
                    sigTypes[sigTypes.Length - 1] = typeof(object[]);

                    Type retType = retVoid ? typeof(void) :
                                   nativeRetType != null?nativeRetType.GetPythonType() : typeof(int);

                    Type calliRetType = retVoid ? typeof(void) :
                                        nativeRetType != null?nativeRetType.GetNativeType() : typeof(int);

#if !CTYPES_USE_SNIPPETS
                    DynamicMethod dm = new DynamicMethod("InteropInvoker", retType, sigTypes, DynamicModule);
#else
                    TypeGen       tg = Snippets.Shared.DefineType("InteropInvoker", typeof(object), false, false);
                    MethodBuilder dm = tg.TypeBuilder.DefineMethod("InteropInvoker", CompilerHelpers.PublicStatic, retType, sigTypes);
#endif

                    ILGenerator  method = dm.GetILGenerator();
                    LocalBuilder calliRetTmp = null, finalRetValue = null;
                    if (dm.ReturnType != typeof(void))
                    {
                        calliRetTmp   = method.DeclareLocal(calliRetType);
                        finalRetValue = method.DeclareLocal(dm.ReturnType);
                    }

                    // try {
                    // emit all of the arguments, save their cleanups

                    method.BeginExceptionBlock();

                    List <MarshalCleanup> cleanups = null;
                    for (int i = 0; i < sig.Length; i++)
                    {
#if DEBUG
                        method.Emit(OpCodes.Ldstr, String.Format("Argument #{0}, Marshaller: {1}, Native Type: {2}", i, sig[i], sig[i].NativeType));
                        method.Emit(OpCodes.Pop);
#endif
                        MarshalCleanup cleanup = sig[i].EmitCallStubArgument(method, i + 1, constantPool, sigTypes.Length - 1);
                        if (cleanup != null)
                        {
                            if (cleanups == null)
                            {
                                cleanups = new List <MarshalCleanup>();
                            }

                            cleanups.Add(cleanup);
                        }
                    }

                    // emit the target function pointer and the calli
#if DEBUG
                    method.Emit(OpCodes.Ldstr, "!!! CALLI !!!");
                    method.Emit(OpCodes.Pop);
#endif

                    method.Emit(OpCodes.Ldarg_0);
                    method.Emit(OpCodes.Calli, GetCalliSignature(convention, sig, calliRetType));

                    // if we have a return value we need to store it and marshal to Python
                    // before we run any cleanup code.
                    if (retType != typeof(void))
                    {
#if DEBUG
                        method.Emit(OpCodes.Ldstr, "!!! Return !!!");
                        method.Emit(OpCodes.Pop);
#endif

                        if (nativeRetType != null)
                        {
                            method.Emit(OpCodes.Stloc, calliRetTmp);
                            nativeRetType.EmitReverseMarshalling(method, new Local(calliRetTmp), constantPool, sig.Length + 1);
                            method.Emit(OpCodes.Stloc, finalRetValue);
                        }
                        else
                        {
                            Debug.Assert(retType == typeof(int));
                            // no marshalling necessary
                            method.Emit(OpCodes.Stloc, finalRetValue);
                        }
                    }

                    // } finally {
                    // emit the cleanup code

                    method.BeginFinallyBlock();

                    if (cleanups != null)
                    {
                        foreach (MarshalCleanup mc in cleanups)
                        {
                            mc.Cleanup(method);
                        }
                    }

                    method.EndExceptionBlock();

                    // }
                    // load the temporary value and return it.
                    if (retType != typeof(void))
                    {
                        method.Emit(OpCodes.Ldloc, finalRetValue);
                    }

                    method.Emit(OpCodes.Ret);

#if CTYPES_USE_SNIPPETS
                    return(tg.TypeBuilder.CreateType().GetMethod("InteropInvoker"));
#else
                    return(dm);
#endif
                }
Esempio n. 33
0
 public NativeSymbolAttribute([NotNull, CallerMemberName] string entrypoint = "")
 {
     CallingConvention = CallingConvention.Cdecl;
     Entrypoint        = entrypoint;
 }
Esempio n. 34
0
 public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
     CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
     CallingConvention nativeCallConv, CharSet nativeCharSet)
 {
     MethodBuilder method = DefinePInvokeMethodHelper(
         name, dllName, name, attributes, callingConvention, returnType, null, null, 
         parameterTypes, null, null, nativeCallConv, nativeCharSet);
     return method;
 }
Esempio n. 35
0
        public void Ctor_CallingConvention(CallingConvention callingConvention)
        {
            var attribute = new UnmanagedFunctionPointerAttribute(callingConvention);

            Assert.Equal(callingConvention, attribute.CallingConvention);
        }
Esempio n. 36
0
        [System.Security.SecurityCritical]  // auto-generated
        private MethodBuilder DefinePInvokeMethodHelper(
            String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            CheckContext(returnType);
            CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
            CheckContext(parameterTypeRequiredCustomModifiers);
            CheckContext(parameterTypeOptionalCustomModifiers);

            AppDomain.CheckDefinePInvokeSupported();

            lock (SyncRoot)
            {
                return DefinePInvokeMethodHelperNoLock(name, dllName, importName, attributes, callingConvention, 
                                                       returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                                                       parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
                                                       nativeCallConv, nativeCharSet);
            }
        }
 public UnmanagedFunctionPointerAttribute()
 {
     _callingConvention = CallingConvention.Winapi;
 }
Esempio n. 38
0
 public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention)
 {
     this.call_conv = callingConvention;
 }
Esempio n. 39
0
 public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention)
 {
     this.call_conv = callingConvention;
 }
Esempio n. 40
0
 /// <summary>
 /// Only constructor.
 /// </summary>
 /// <param name="ChanKind"></param>
 /// <param name="ObjType"></param>
 /// <param name="CallConv"></param>
 /// <param name="InvKind"></param>
 public Client(ChannelKind ChanKind, 
               Type ObjType, 
               CallingConvention CallConv, 
               InvokeKind InvKind,
               string Host)
 {
   m_ChanKind = ChanKind;
   m_ObjType = ObjType;
   m_CallConv = CallConv;
   m_InvKind = InvKind;
   m_Host = Host;
 }//constructor
Esempio n. 41
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="callingConvention">Calling convention (must have LocalSig set)</param>
 /// <param name="count">Number of locals</param>
 internal LocalSig(CallingConvention callingConvention, uint count)
 {
     this.callingConvention = callingConvention;
     this.locals            = ThreadSafeListCreator.Create <TypeSig>((int)count);
 }
Esempio n. 42
0
        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
                throw new ArgumentNullException("customBuilder");
            }

            switch (customBuilder.Ctor.ReflectedType.FullName)
            {
            case "System.Runtime.CompilerServices.MethodImplAttribute":
                byte[] data = customBuilder.Data;
                int    impla;                      // the (stupid) ctor takes a short or an int ...
                impla   = (int)data [2];
                impla  |= ((int)data [3]) << 8;
                iattrs |= (MethodImplAttributes)impla;
                return;

            case "System.Runtime.InteropServices.DllImportAttribute":
                CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr(customBuilder);
                bool preserveSig = true;

                /*
                 * It would be easier to construct a DllImportAttribute from
                 * the custom attribute builder, but the DllImportAttribute
                 * does not contain all the information required here, ie.
                 * - some parameters, like BestFitMapping has three values
                 *   ("on", "off", "missing"), but DllImportAttribute only
                 *   contains two (on/off).
                 * - PreserveSig is true by default, while it is false by
                 *   default in DllImportAttribute.
                 */

                pi_dll = (string)attr.ctorArgs[0];
                if (pi_dll == null || pi_dll.Length == 0)
                {
                    throw new ArgumentException("DllName cannot be empty");
                }

                native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;

                for (int i = 0; i < attr.namedParamNames.Length; ++i)
                {
                    string name  = attr.namedParamNames [i];
                    object value = attr.namedParamValues [i];

                    if (name == "CallingConvention")
                    {
                        native_cc = (CallingConvention)value;
                    }
                    else if (name == "CharSet")
                    {
                        charset = (CharSet)value;
                    }
                    else if (name == "EntryPoint")
                    {
                        pi_entry = (string)value;
                    }
                    else if (name == "ExactSpelling")
                    {
                        ExactSpelling = (bool)value;
                    }
                    else if (name == "SetLastError")
                    {
                        SetLastError = (bool)value;
                    }
                    else if (name == "PreserveSig")
                    {
                        preserveSig = (bool)value;
                    }
#if NET_1_1
                    else if (name == "BestFitMapping")
                    {
                        BestFitMapping = (bool)value;
                    }
                    else if (name == "ThrowOnUnmappableChar")
                    {
                        ThrowOnUnmappableChar = (bool)value;
                    }
#endif
                }

                attrs |= MethodAttributes.PinvokeImpl;
                if (preserveSig)
                {
                    iattrs |= MethodImplAttributes.PreserveSig;
                }
                return;

            case "System.Runtime.InteropServices.PreserveSigAttribute":
                iattrs |= MethodImplAttributes.PreserveSig;
                return;

#if NET_2_0
            case "System.Runtime.CompilerServices.SpecialNameAttribute":
                attrs |= MethodAttributes.SpecialName;
                return;
#endif
            case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
                attrs |= MethodAttributes.HasSecurity;
                break;
            }

            if (cattrs != null)
            {
                CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
                cattrs.CopyTo(new_array, 0);
                new_array [cattrs.Length] = customBuilder;
                cattrs = new_array;
            }
            else
            {
                cattrs     = new CustomAttributeBuilder [1];
                cattrs [0] = customBuilder;
            }
        }
Esempio n. 43
0
 uint IInternFactory.GetFunctionPointerTypeReferenceInternedKey(CallingConvention callingConvention, IEnumerable<IParameterTypeInformation> parameters, IEnumerable<IParameterTypeInformation> extraArgumentTypes, IEnumerable<ICustomModifier> returnValueCustomModifiers, bool returnValueIsByRef, ITypeReference returnType) {
   lock (GlobalLock.LockingObject) {
     return this.GetFunctionPointerTypeReferenceInternId(callingConvention, parameters, extraArgumentTypes, returnValueCustomModifiers, returnValueIsByRef, returnType);
   }
 }
Esempio n. 44
0
 public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
 {
     return(GetMethodSigHelper(mod, CallingConventions.Standard, unmanagedCallConv, returnType, null));
 }
Esempio n. 45
0
 public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
     CallingConventions callingConvention, 
     Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
     Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
     CallingConvention nativeCallConv, CharSet nativeCharSet)
 {
     MethodBuilder method = DefinePInvokeMethodHelper(
     name, dllName, entryName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, 
     parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet);
     return method;
 }
Esempio n. 46
0
        internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, CallingConvention unmanagedCallingConvention, Type returnType,
                                                           Type [] parameters)
        {
            if (mod != null && !(mod is ModuleBuilder))
            {
                throw new ArgumentException("ModuleBuilder is expected");
            }

            if (returnType == null)
            {
                returnType = typeof(void);
            }

            if (returnType.IsUserType)
            {
                throw new NotSupportedException("User defined subclasses of System.Type are not yet supported.");
            }
            if (parameters != null)
            {
                for (int i = 0; i < parameters.Length; ++i)
                {
                    if (parameters [i].IsUserType)
                    {
                        throw new NotSupportedException("User defined subclasses of System.Type are not yet supported.");
                    }
                }
            }

            SignatureHelper helper =
                new SignatureHelper((ModuleBuilder)mod, SignatureHelperType.HELPER_METHOD);

            helper.returnType        = returnType;
            helper.callConv          = callingConvention;
            helper.unmanagedCallConv = unmanagedCallingConvention;

            if (parameters != null)
            {
                helper.arguments = new Type [parameters.Length];
                for (int i = 0; i < parameters.Length; ++i)
                {
                    helper.arguments [i] = parameters [i];
                }
            }

            return(helper);
        }
Esempio n. 47
0
        [System.Security.SecurityCritical]  // auto-generated
        private MethodBuilder DefinePInvokeMethodHelperNoLock(
            String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");

            if (dllName == null)
                throw new ArgumentNullException("dllName");

            if (dllName.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "dllName");

            if (importName == null)
                throw new ArgumentNullException("importName");

            if (importName.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "importName");

            if ((attributes & MethodAttributes.Abstract) != 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod"));
            Contract.EndContractBlock();

            if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeOnInterface"));

            ThrowIfCreated();

            attributes = attributes | MethodAttributes.PinvokeImpl;
            MethodBuilder method = new MethodBuilder(name, attributes, callingConvention, 
                returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
                m_module, this, false);

            //The signature grabbing code has to be up here or the signature won't be finished
            //and our equals check won't work.
            int sigLength;
            byte[] sigBytes = method.GetMethodSignature().InternalGetSignature(out sigLength);

            if (m_listMethods.Contains(method))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_MethodRedefined"));
            }
            m_listMethods.Add(method);

            MethodToken token = method.GetToken();
            
            int linkFlags = 0;
            switch(nativeCallConv)
            {
                case CallingConvention.Winapi:
                    linkFlags =(int)PInvokeMap.CallConvWinapi;
                    break;
                case CallingConvention.Cdecl:
                    linkFlags =(int)PInvokeMap.CallConvCdecl;
                    break;
                case CallingConvention.StdCall:
                    linkFlags =(int)PInvokeMap.CallConvStdcall;
                    break;
                case CallingConvention.ThisCall:
                    linkFlags =(int)PInvokeMap.CallConvThiscall;
                    break;
                case CallingConvention.FastCall:
                    linkFlags =(int)PInvokeMap.CallConvFastcall;
                    break;
            }
            switch(nativeCharSet)
            {
                case CharSet.None:
                    linkFlags |=(int)PInvokeMap.CharSetNotSpec;
                    break;
                case CharSet.Ansi:
                    linkFlags |=(int)PInvokeMap.CharSetAnsi;
                    break;
                case CharSet.Unicode:
                    linkFlags |=(int)PInvokeMap.CharSetUnicode;
                    break;
                case CharSet.Auto:
                    linkFlags |=(int)PInvokeMap.CharSetAuto;
                    break;
            }
            
            SetPInvokeData(m_module.GetNativeHandle(),
                dllName,
                importName,
                token.Token,
                linkFlags);
            method.SetToken(token);

            return method;
        }
Esempio n. 48
0
 /// <summary>
 /// Reads a <see cref="FieldSig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="FieldSig"/> instance</returns>
 FieldSig ReadField(CallingConvention callingConvention) => new FieldSig(callingConvention, ReadType());
 public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention)
 {
     _callingConvention = callingConvention;
 }
Esempio n. 50
0
 /// <summary>
 /// Reads a <see cref="MethodSig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="MethodSig"/> instance</returns>
 MethodSig ReadMethod(CallingConvention callingConvention) => ReadSig(new MethodSig(callingConvention));
Esempio n. 51
0
    }//Usage()
    
    /// <summary>
    /// Gets user options.
    /// </summary>
    private static void GetOptions()
    {
 GetChannel:
      Console.Write("\nHttp (h), TCP (t) or both (b) using threads? ");
      string Reply = Console.ReadLine();
      switch (Reply.ToLower())
      {
        case "b":
          m_ChanKind = ChannelKind.Both;
          break;
        case "h":
          m_ChanKind = ChannelKind.Http;
          break;
        case "t":
          m_ChanKind = ChannelKind.TCP;
          break;
        default:
          Console.WriteLine("Invalid option, please try again.");
          goto GetChannel;
      }//switch

GetConvention:
      Console.Write("\nBy ref (r) or by val (v)? ");
      Reply = Console.ReadLine();
      switch (Reply.ToLower())
      {
        case "r":
          m_CallConv = CallingConvention.ByRef;
          break;
        case "v":
          m_CallConv = CallingConvention.ByVal;
          break;
        default:
          Console.WriteLine("Invalid option, please try again.");
          goto GetConvention;
      }//switch

GetInvoke:
      Console.Write("\nSerial (s) or async (a)? ");
      Reply = Console.ReadLine();
      switch (Reply.ToLower())
      {
        case "a":
          m_InvKind = InvokeKind.Async;
          break;
        case "s":
          m_InvKind = InvokeKind.Sequential;
          break;
        default:
          Console.WriteLine("Invalid option, please try again.");
          goto GetInvoke;
    }//switch

      //Setup the correct Type object to pass to the Client object for object creation.
      switch (m_CallConv)
      {
        case CallingConvention.ByRef:
          m_ObjType = Type.GetType("RemotingSamples.HelloServerByRef,remotingshared");
          break;
        case CallingConvention.ByVal:
          m_ObjType = Type.GetType("RemotingSamples.HelloServerByVal,remotingshared");
          break;
        default:
          throw new System.InvalidOperationException("Invalid Calling Convention in Main()");
      }//switch
      Console.WriteLine();
      return;
    }//GetOptions()
Esempio n. 52
0
 /// <summary>
 /// Reads a <see cref="PropertySig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="PropertySig"/> instance</returns>
 PropertySig ReadProperty(CallingConvention callingConvention) => ReadSig(new PropertySig(callingConvention));
Esempio n. 53
0
		public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
		{
			return DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
		}
Esempio n. 54
0
 /// <summary>
 /// Reads a <see cref="FieldSig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="FieldSig"/> instance</returns>
 FieldSig ReadField(CallingConvention callingConvention)
 {
     return(new FieldSig(callingConvention, ReadType()));
 }
Esempio n. 55
0
        [System.Security.SecurityCritical] // auto-generated
#endif
        public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, 
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
            CharSet nativeCharSet)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            lock(SyncRoot)
            {
                return DefinePInvokeMethodNoLock(name, dllName, entryName, attributes, callingConvention, 
                                                 returnType, parameterTypes, nativeCallConv, nativeCharSet);
            }
        }
Esempio n. 56
0
 /// <summary>
 /// Reads a <see cref="MethodSig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="MethodSig"/> instance</returns>
 MethodSig ReadMethod(CallingConvention callingConvention)
 {
     return(ReadSig(new MethodSig(callingConvention)));
 }
Esempio n. 57
0
 public DllExportAttribute(CallingConvention convention, string name)
 {
     ExportedName = name;
     this.CallingConvention = convention;
 }
Esempio n. 58
0
 /// <summary>
 /// Reads a <see cref="PropertySig"/>
 /// </summary>
 /// <param name="callingConvention">First byte of signature</param>
 /// <returns>A new <see cref="PropertySig"/> instance</returns>
 PropertySig ReadProperty(CallingConvention callingConvention)
 {
     return(ReadSig(new PropertySig(callingConvention)));
 }
Esempio n. 59
0
		/// <summary>
		/// Puts a Calli instruction onto the Microsoft intermediate language (MSIL) stream, specifying an unmanaged
		/// calling convention for the indirect call.
		/// </summary>
		public void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
		{
			if (InterceptEmit(opcode, null)) il.EmitCalli(opcode, unmanagedCallConv, returnType, parameterTypes);
		}
Esempio n. 60
0
 public CallingConventionAttribute(CallingConvention callingConvention)
 {
 }