public GetParameters ( ) : System.Reflection.ParameterInfo[] | ||
return | System.Reflection.ParameterInfo[] |
/// <summary> /// The criteria to restrict an attribute to a specific type at compile time /// </summary> /// <param name="methodBase"></param> /// <param name="type"></param> /// <returns></returns> public static bool RestrictPropertySetterToSpecificType(MethodBase methodBase, Type type) { if (methodBase.GetParameters() == null) { return false; } if (methodBase.GetParameters().Length != 1) { return false; } return methodBase.GetParameters()[0].ParameterType == type; }
/// <summary> /// The criteria to restrict an attribute to a specific interfaceType at compile time /// </summary> /// <param name="methodBase"></param> /// <param name="interfaceType"></param> /// <returns></returns> public static bool RestrictPropertySetterToSpecificImplementation(MethodBase methodBase, Type interfaceType) { if (methodBase.GetParameters() == null) { return false; } if (methodBase.GetParameters().Length != 1) { return false; } Type type = methodBase.GetParameters()[0].ParameterType; string interfaceFullName = interfaceType.FullName; return type.GetInterface(interfaceFullName) != null; }
public FunctionBase(MethodBase method, XmlComments comments) { Comments = comments; Method = method; Type = method.DeclaringType; Parameters = method.GetParameters(); string parameterString = String.Empty; if (Parameters.Length > 0) { for (int i = 0; i < Parameters.Length; i++) { ParameterInfo parameter = Parameters[i]; ParameterDic.Add(parameter.Name.ToLowerInvariant(), parameter); if ((DefaultVarPos < 0) && parameter.GetCustomAttributes(typeof(DefaultVar), false).Length > 0) { DefaultVarPos = i; parameterString += "[DefaultVar] "; } parameterString += parameter.ParameterType.GenericName() + " " + parameter.Name + ", "; } parameterString = parameterString.Substring(0, parameterString.Length - 2); } ParameterString = parameterString; }
private static bool HasParameters(MethodBase method) { if (method == null) return false; return method.GetParameters().Length == 0; }
// Validate the attribute usage. public override bool CompileTimeValidate( MethodBase method ) { // Don't apply to constructors. if ( method is ConstructorInfo ) { Message.Write( SeverityType.Error, "CX0001", "Cannot cache constructors." ); return false; } MethodInfo methodInfo = (MethodInfo) method; // Don't apply to void methods. if ( methodInfo.ReturnType.Name == "Void" ) { Message.Write( SeverityType.Error, "CX0002", "Cannot cache void methods." ); return false; } // Does not support out parameters. ParameterInfo[] parameters = method.GetParameters(); for ( int i = 0; i < parameters.Length; i++ ) { if ( parameters[i].IsOut ) { Message.Write( SeverityType.Error, "CX0003", "Cannot cache methods with return values." ); return false; } } return true; }
/// <summary> /// パラメータのリストを文字列にして取得します。 /// </summary> /// <param name="m">メソッドを表す System.Reflection.MethodBase を指定して下さい。</param> /// <returns>パラメータのリストを表す文字列を返します。</returns> public static string GetParameterList(System.Reflection.MethodBase m) { System.Reflection.ParameterInfo[] ps = m.GetParameters(); System.Text.StringBuilder build = new System.Text.StringBuilder(); for (int i = 0, iM = ps.Length; i < iM; i++) { if (i != 0) { build.Append(','); } System.Type t = ps[i].ParameterType; if (t.IsByRef) { build.AppendFormat("{0} {1}", ps[i].IsOut?"out":"ref", CSharpName(t.GetElementType())); } else { if (ps[i].GetCustomAttributes(typeof(System.ParamArrayAttribute), false).Length > 0) { build.Append("params "); } build.Append(CSharpName(t)); } build.Append(' '); build.Append(ps[i].Name); } return(build.ToString()); }
//=========================================================================================== private bool IsStatic(MethodBase method) { if (method == null) return false; return method.GetParameters().Length == 0; }
internal static Expression[] CreateRefParameterExpressions(MethodBase method, Expression argumentsParameter) { // http://stackoverflow.com/questions/3146317/create-expression-to-invoke-method-with-out-parameter // for reference parameters need to call MakeByRefType() somehow??? //return method.GetParameters().Select((parameter, index) => // ).ToArray(); ParameterInfo[] parameters = method.GetParameters(); Expression[] toReturn = new Expression[parameters.Count()]; for (int i=0;i<parameters.Length; i++) { ParameterInfo pi = parameters[i]; if (pi.ParameterType.IsByRef) { // doesn't work somehow I need to affect the argumentsParemter expression else I get a not in scope exception! toReturn[i] = Expression.Convert(Expression.ArrayIndex(argumentsParameter, Expression.Constant(i)), pi.ParameterType.GetElementType()); } else { toReturn[i] = Expression.Convert(Expression.ArrayIndex(argumentsParameter, Expression.Constant(i)), pi.ParameterType); } } return toReturn; }
public static uint GetStackSizeToReservate(MethodBase aMethod) { var xMethodInfo = aMethod as SysReflection.MethodInfo; uint xReturnSize = 0; if (xMethodInfo != null) { xReturnSize = SizeOfType(xMethodInfo.ReturnType); } if (xReturnSize == 0) { return 0; } // todo: implement exception support int xExtraStackSize = (int)Align(xReturnSize, 4); var xParameters = aMethod.GetParameters(); foreach (var xItem in xParameters) { xExtraStackSize -= (int)Align(SizeOfType(xItem.ParameterType), 4); } if (!xMethodInfo.IsStatic) { xExtraStackSize -= GetNativePointerSize(xMethodInfo); } if (xExtraStackSize > 0) { return (uint)xExtraStackSize; } return 0; }
public bool MethodSigEquals(MethodBaseSig sig, MethodBase method) { if (sig == null || method == null) return false; if (sig.HasThis != !method.IsStatic) return false; if (sig.Generic != method.IsGenericMethod) return false; if (sig.Generic) { if (sig.GenParamCount != method.GetGenericArguments().Length) return false; } if (method.IsMethodSpec()) method = method.Module.ResolveMethod(method.MetadataToken) ?? method; var mps = method.GetParameters(); if (sig.Params.Count != mps.Length) return false; var minfo = method as MethodInfo; if (minfo != null) { if (!Equals(sig.RetType, minfo.ReturnType)) return false; } else { if (sig.RetType.RemovePinnedAndModifiers().GetElementType() != ElementType.Void) return false; } for (int i = 0; i < mps.Length; i++) { if (!Equals(sig.Params[i], mps[i].ParameterType)) return false; } return true; }
private static ParameterInfo[] GetParameters(MethodBase method) { var parameters = method.GetParameters(); if (method.IsExtensionMethod()) parameters = parameters.Skip(1).ToArray(); return parameters; }
protected object[] UnwrapArgs(MethodBase m, object[] args) { ParameterInfo[] paramInfos = m.GetParameters(); if (args != null && args.Length > paramInfos.Length) throw new ArgumentException(String.Format("Too many js arguments passed to plugin method {0}; expected {1} got {2}", m.Name, paramInfos.Length, args.Length)); object[] newArgs = new object[paramInfos.Length]; int k = 0; for (int i = 0; i < paramInfos.Length; i++) { ParameterInfo paramInfo = paramInfos[i]; object argValue; if (k < args.Length && TryConvertArg(paramInfo, args[k], out argValue)) // If args[k] matches { newArgs[i] = argValue; k++; continue; } if (TryGetOptionalArg(paramInfo, out argValue)) { newArgs[i] = argValue; } else { throw new MissingMemberException(); } } return newArgs; }
internal MethodInformation(MethodBase method, int parametersToIgnore) { this.method = method; this.isGeneric = method.IsGenericMethod; ParameterInfo[] parameters = method.GetParameters(); int num = parameters.Length - parametersToIgnore; this.parameters = new ParameterInformation[num]; for (int i = 0; i < num; i++) { this.parameters[i] = new ParameterInformation(parameters[i]); if (parameters[i].IsOptional) { this.hasOptional = true; } } this.hasVarArgs = false; if (num > 0) { ParameterInfo info = parameters[num - 1]; if ((!this.hasOptional && info.ParameterType.IsArray) && (info.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length != 0)) { this.hasVarArgs = true; this.parameters[num - 1].isParamArray = true; } } }
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { this.methodPath = method.DeclaringType.FullName .Replace('.', '/').Replace('+', '/') + "/" + method.Name; this.parameterNames = method.GetParameters().Select(p => p.Name).ToArray(); }
/// <summary> /// Scores the given constructor based on the number of dependencies we can fill. /// </summary> static int Rate(MethodBase constructor, TypeTracker typeTracker) { // Preserve the default behaviour of preferring explicitly marked constructors. if (constructor.IsDefined(typeof(InjectionConstructorAttribute), false)) return int.MaxValue; var score = 0; foreach (var parameter in constructor.GetParameters()) { if(parameter.IsOut || parameter.IsRetval) return -1; if (typeTracker.HasDependency(parameter.ParameterType)) { score++; } else { // We don't know how to fill this parameter so try a different constructor return -1; } } return score; }
/// <summary> /// <para>Gets the selector for the given method.</para> /// <para>The selector for a method is build with the following rules: /// <list type = "bullet"> /// <item>Selector begins with the method name</item> /// <item>The first parameter if present is appended by its name with the "With" prefix</item> /// <item>The other parameters if present are appended by their names</item> /// </list> /// </para> /// <para>Here are some examples of result: /// <list type = "table"> /// <listheader> /// <term>Method</term> /// <description>Corresponding selector</description> /// </listheader> /// <item> /// <term>public void DoThis()</term> /// <description>DoThis</description> /// </item> /// <item> /// <term>public void DoThis(int value)</term> /// <description>DoThisWithValue:</description> /// </item> /// <item> /// <term>public void DoThis(NSString str, int val)</term> /// <description>DoThisWithStr:val:</description> /// </item> /// </list> /// </para> /// </summary> /// <param name = "methodBase">The method.</param> /// <returns> /// A selector compliant with Objective-C messaging. /// </returns> public static String GetSelector (MethodBase methodBase) { if (methodBase == null) { throw new ArgumentNullException ("methodBase"); } StringBuilder builder = new StringBuilder (); ParameterInfo[] parameters = methodBase.GetParameters (); // Add name builder.Append (methodBase.Name); for (int i = 0; i < parameters.Length; i++) { String name = parameters [i].Name; // If first parameter, use "With" prefix if (i == 0) { builder.Append (WITH); builder.Append (name.Substring (0, 1).ToUpperInvariant ()); if (name.Length > 1) { builder.Append (name.Substring (1)); } } else { builder.Append (name); } builder.Append (COLON); } return builder.ToString (); }
public MethodInvocation (object target, MethodBase method, params object[] arguments) { Target = target; MethodBase = method; Arguments = new ParameterCollection (arguments, method.GetParameters ()); Context = new Dictionary<string, object> (); }
private void AppendMethod(StringBuilder builder, MethodBase method) { if (method.DeclaringType != null) { AppendType(builder, method.DeclaringType); builder.Append("."); } AppendName(builder, method.Name); if (method.IsGenericMethod) { builder.Append("["); method.GetGenericArguments().ForEach((type, index) => { if (index > 0) builder.Append(","); AppendType(builder, type); }); builder.Append("]"); } builder.Append("("); method.GetParameters().ForEach((parameter, index) => { if (index > 0) builder.Append(", "); builder.Append(parameter.ParameterType.Name) .Append(" ") .Append(parameter.Name); }); builder.Append(")"); }
private void CheckOptionalParametersAltNamesAreNotDuplicated(MethodBase method) { var parameterNames = new List<string>(); foreach (ParameterInfo parameter in method.GetParameters()) { if (_metadata.IsRequired(parameter)) { parameterNames.Add(parameter.Name.ToLower()); } else { if (parameterNames.Contains(parameter.Name.ToLower())) { throw new NConsolerException( "Found duplicated parameter name \"{0}\" in method \"{1}\". Please check alt names for optional parameters", parameter.Name, method.Name); } parameterNames.Add(parameter.Name.ToLower()); var optional = _metadata.GetOptional(parameter); foreach (string altName in optional.AltNames) { if (parameterNames.Contains(altName.ToLower())) { throw new NConsolerException( "Found duplicated parameter name \"{0}\" in method \"{1}\". Please check alt names for optional parameters", altName, method.Name); } parameterNames.Add(altName.ToLower()); } } } }
private static object[] GetMethodArguments(MethodBase method) { return ( from parameter in method.GetParameters() let parameterType = parameter.ParameterType select GetInstance(parameterType)).ToArray(); }
public sealed override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { var type = method.DeclaringType; if (this.cacheName == null) { this.cacheName = type.FullName; } this.isClassGeneric = type.IsGenericType; this.isMethodGeneric = method.IsGenericMethod; this.className = type.FullName; this.methodName = method.Name; var parameters = method.GetParameters(); this.parameterTypeNames = parameters.Select(p => p.ParameterType.FullName).ToArray(); var indexes = new List <int>(); for (int cnt = 0; cnt < parameters.Length; cnt++) { var doNotIncludeInCacheKey = parameters[cnt].CustomAttributes .Any(a => a.AttributeType == typeof(DoNotIncludeInCacheKeyAttribute)); if (doNotIncludeInCacheKey) { indexes.Add(cnt); } } this.indexesNotToCache = indexes.ToArray(); }
private EcmaCil.MethodMeta EnqueueMethod(MethodBase aMethod, object aSource, string aSourceType) { if (mLogEnabled) { LogMapPoint(aSource, aSourceType, aMethod); } if (aMethod.IsGenericMethodDefinition) { throw new Exception("Cannot queue generic method definitions"); } Type xReturnType = null; var xMethodInfo = aMethod as MethodInfo; if (xMethodInfo != null) { xReturnType = xMethodInfo.ReturnType; } else { xReturnType = typeof(void); } var xQueuedMethod = new QueuedMethod(aMethod.DeclaringType, aMethod, (from item in aMethod.GetParameters() select item.ParameterType).ToArray(), xReturnType); EcmaCil.MethodMeta xMethodMeta; if(mMethods.TryGetValue(xQueuedMethod, out xMethodMeta)){ return xMethodMeta; } var xDeclaringType = EnqueueType(aMethod.DeclaringType, aMethod, "Declaring type"); xMethodMeta = new EcmaCil.MethodMeta(); mMethodMetaToMethod.Add(xMethodMeta, aMethod); xMethodMeta.DeclaringType = xDeclaringType; xDeclaringType.Methods.Add(xMethodMeta); mMethods.Add(xQueuedMethod, xMethodMeta); mQueue.Enqueue(xQueuedMethod); return xMethodMeta; }
private static string GenerateMethod(MethodBase method, AjaxMethodAttribute attribute, string url) { // FORMAT: // 1. Async: // <MethodName>:function(<Parameters: pi>,sc,ec) {var p={<Parameters: pi:pi>};MkAJAX.callAsync(<URL>,<RequestType>,p,sc,ec);} // 2. Blocking: // <MethodName>:function(<Parameters: pi>) {var p={<Parameters: pi:pi>};return MkAJAX.callBlock(<URL>,<RequestType>,p);} ParameterInfo[] methodParams = method.GetParameters(); string name = attribute.Name ?? method.Name; bool isAsync = attribute.ExecutionType == ExecutionType.Async; return string.Format("{0}{1}:function({2}{3}){{var p={{{4}}};{5}(\"{6}/{7}\",{8},p{9}{3});}}", /*0*/Environment.NewLine, /*1*/attribute.UseJavaScriptNamingConvention ? FirstCharacterToLower(name) : name, /*2*/string.Format("{0}{1}", string.Join(",", Array.ConvertAll(methodParams, p => p.Name)), methodParams.Length > 0 && isAsync ? "," : string.Empty), /*3*/isAsync ? "cb" : string.Empty, /*4*/methodParams.Length > 0 ? string.Join(",", Array.ConvertAll(methodParams, p => string.Format("{0}:{0}", p.Name))) : string.Empty, /*5*/isAsync ? "MkAjax.callAsync" : "return MkAjax.callBlock", /*6*/url, /*7*/method.Name, /*8*/attribute.RequestType == RequestType.Post ? "true" : "false", // false for now mean GET /*9*/isAsync ? "," : string.Empty); }
private static object[] DataBindParameters(Controller controller, MethodBase action) { ParameterInfo[] param = action.GetParameters(); object[] args = new object[param.Length]; foreach (ParameterInfo info in param) { string name = info.Name; Type type = info.ParameterType; if (controller.PropertyBag[name] != null) { // Console.WriteLine("type:"+type); // Console.WriteLine("Base:" + controller.PropertyBag[name].GetType().BaseType + " :" + controller.PropertyBag[name].GetType().BaseType.Equals(type)); // Console.WriteLine("getType:" + controller.PropertyBag[name].GetType() + " :" + controller.PropertyBag[name].GetType().Equals(type)); // Console.WriteLine("issubclass:"+controller.PropertyBag[name].GetType().IsSubclassOf(type)); if (controller.PropertyBag[name].GetType().BaseType.Equals(type) || controller.PropertyBag[name].GetType().Equals(type) || controller.PropertyBag[name].GetType().IsSubclassOf(type)) { //info.RawDefaultValue = args[info.Position] = controller.PropertyBag[name]; } } } return args; }
protected static bool CanProcess(MethodBase method, EntityDomain domain, object domainId) { ParameterInfo[] parameters = method.GetParameters(); if (method.IsStatic) return parameters.Length == 0 || domain != null; return (parameters.Length == 0 && domainId != null) || (domain != null && domainId != null); }
protected byte CreateLocalsForByRefParams(byte paramArrayIndex, MethodBase invocationInfo) { byte numberOfByRefParams = 0; ParameterInfo[] parameters = invocationInfo.GetParameters(); for (int i = 0; i < ParameterTypes.Length; i++) { Type paramType = ParameterTypes[i]; if (paramType.IsByRef) { Type type = paramType.GetElementType(); Emit.DeclareLocal(type); if (!parameters[i].IsOut) // no initialization necessary is 'out' parameter { Emit.ldarg(paramArrayIndex) .ldc_i4(i) .ldelem_ref .CastFromObject(type) .stloc(numberOfByRefParams) .end(); } numberOfByRefParams++; } } return numberOfByRefParams; }
public static MethodBuilder OverrideMethod(this TypeBuilder source, MethodBase parentMethod, Func<ILGenerator, ILGenerator> body, IDictionary<MethodBase, MethodBuilder> map) { // don't defer this check since default error message doesn't say // what exact method is the reason of the failure to compile the class parentMethod.IsVirtual.AssertTrue(); parentMethod.IsFinal.AssertFalse(); var attrs = parentMethod.Attributes; attrs &= ~MethodAttributes.NewSlot; attrs &= ~MethodAttributes.Abstract; var derived = source.DefineMethod( // that's an awesome idea but it hurts reflector and debuggability // String.Format("{0}_{1}", parentMethod.Name, parentMethod.DeclaringType.ToShortString()), parentMethod.Name, attrs, parentMethod.Ret(), parentMethod.Params()); parentMethod.GetParameters().ForEach((pi, i) => derived.DefineParameter(i + 1, ParmA.None, pi.Name)); // the stuff below ain't necessary at all since we don't change the name // // note. the checks are very important since otherwise we get an exception: // // System.TypeLoadException: Signature of the body and declaration in a method implementation do not match. // if (!parentMethod.IsAbstract && !parentMethod.IsGenericMethod) // { // source.DefineMethodOverride(derived, parentMethod); // } if (body != null) body(derived.il()); if (map != null) map[parentMethod] = derived; return derived; }
private string GenerateMethodCaption(MethodBase mb) { StringBuilder builder = new StringBuilder(0x100); if (!this.IsConstructor) { builder.Append(mb.Name); } else { builder.Append(mb.DeclaringType.Name); } builder.Append('('); ParameterInfo[] parameters = mb.GetParameters(); if (parameters != null) { int length = parameters.Length; for (int i = 0; i < length; i++) { if (i != 0) { builder.Append(", "); } builder.Append(parameters[i].ParameterType.Name); } } builder.Append(')'); return builder.ToString(); }
public static string GetId(MethodBase methodOrConstructor) { var genericPart = string.Empty; if (methodOrConstructor.IsGenericMethod) { genericPart = string.Format(CultureInfo.InvariantCulture, "``{0}", methodOrConstructor.GetGenericArguments().Length); } var parametersPart = string.Join( ",", methodOrConstructor.GetParameters() .Select(x => GetTypeName(x.ParameterType))); if (!string.IsNullOrEmpty(parametersPart)) { parametersPart = "(" + parametersPart + ")"; } var conversionReturnTypePart = string.Empty; if (methodOrConstructor.IsSpecialName && (methodOrConstructor.Name.Equals("op_Explicit") || methodOrConstructor.Name.Equals("op_Implicit"))) { conversionReturnTypePart = "~" + GetTypeName(((MethodInfo)methodOrConstructor).ReturnType); } return string.Format( CultureInfo.InvariantCulture, "M:{0}.{1}{2}{3}{4}", GetTypeName(methodOrConstructor.ReflectedType), HashEncode(methodOrConstructor.Name), genericPart, parametersPart, conversionReturnTypePart); }
private object[] ResolveParameters(MethodBase methodBase, IIocContainer context) { //Gets a list of parameters to attempt to resolve those parameters //before calling the constructor with the resolved objects ParameterInfo[] methodParams = methodBase.GetParameters(); object[] dependentObjects = new object[methodParams.Length]; int paramIndexer = 0; for (paramIndexer = 0; paramIndexer <= methodParams.Length - 1; paramIndexer++) { ParameterInfo param = (ParameterInfo) methodParams.GetValue(paramIndexer); try { string identString = string.Empty; Attribute[] attrs = (Attribute[])param.GetCustomAttributes(typeof(IocDependencyAttribute), false); //Parameters can be specified with an IocDependencyAttribute if a specific string must be used if (attrs.Length > 0) { IocDependencyAttribute dependentAttr = (IocDependencyAttribute) attrs.GetValue(0); identString = dependentAttr.Identifier; } object paramValue = context.Resolve(param.ParameterType, identString); dependentObjects.SetValue(paramValue, paramIndexer); } catch (IocException) { throw new IocException("Could not resolve parameter type: " + param.ParameterType.UnderlyingSystemType.ToString()); } } return dependentObjects; }
private void ResolveOverloadedMethod(RuntimeType t) { if (this.args != null) { MemberInfo[] infoArray = t.GetMember(this.methodName, MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); int length = infoArray.Length; switch (length) { case 1: this.MI = infoArray[0] as System.Reflection.MethodBase; return; case 0: return; } int num2 = this.args.Length; System.Reflection.MethodBase base2 = null; for (int i = 0; i < length; i++) { System.Reflection.MethodBase base3 = infoArray[i] as System.Reflection.MethodBase; if (base3.GetParameters().Length == num2) { if (base2 != null) { throw new RemotingException(Environment.GetResourceString("Remoting_AmbiguousMethod")); } base2 = base3; } } if (base2 != null) { this.MI = base2; } } }
/* * Matches a method against its arguments in the Lua stack. Returns * if the match was succesful. It it was also returns the information * necessary to invoke the method. */ internal bool matchParameters(IntPtr luaState,MethodBase method,ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod=true; ParameterInfo[] paramInfo=method.GetParameters(); int currentLuaParam=1; int nLuaParams=LuaDLL.lua_gettop(luaState); ArrayList paramList=new ArrayList(); ArrayList outList=new ArrayList(); ArrayList argTypes=new ArrayList(); foreach(ParameterInfo currentNetParam in paramInfo) { if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params { outList.Add(paramList.Add(null)); } else if(currentLuaParam>nLuaParams) // Adds optional parameters { if(currentNetParam.IsOptional) { paramList.Add(currentNetParam.DefaultValue); } else { isMethod=false; break; } } else if((extractValue=translator.typeChecker.checkType(luaState,currentLuaParam,currentNetParam.ParameterType))!=null) // Type checking { int index=paramList.Add(extractValue(luaState,currentLuaParam)); MethodArgs methodArg=new MethodArgs(); methodArg.index=index; methodArg.extractValue=extractValue; argTypes.Add(methodArg); if(currentNetParam.ParameterType.IsByRef) outList.Add(index); currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if(currentNetParam.IsOptional) { paramList.Add(currentNetParam.DefaultValue); } else // No match { isMethod=false; break; } } if(currentLuaParam!=nLuaParams+1) // Number of parameters does not match isMethod=false; if(isMethod) { methodCache.args=paramList.ToArray(); methodCache.cachedMethod=method; methodCache.outList=(int[])outList.ToArray(typeof(int)); methodCache.argTypes=(MethodArgs[])argTypes.ToArray(typeof(MethodArgs)); } return isMethod; }
private ServiceEntry Create(string serviceId, MethodBase implementationMethod) { var type = implementationMethod.DeclaringType; return new ServiceEntry { Descriptor = new ServiceDescriptor { Id = serviceId }, Func = parameters => { var instance = _serviceFactory.Create(type); var list = new List<object>(); foreach (var parameterInfo in implementationMethod.GetParameters()) { var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = implementationMethod.Invoke(instance, list.ToArray()); return result; } }; }
// Use this for initialization public static void log() { // StackTrace st = new StackTrace(true); // StackFrame sf = st.GetFrame(1); // string info = "所调用的类名为:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " 所调用的方法:" + System.Reflection.MethodBase.GetCurrentMethod().Name; // MethodBase parenMethod = null; // if(sf.GetMethod()!=null) { // parenMethod = sf.GetMethod(); // info = info + " 被 " + parenMethod.ReflectedType + "类的 " + parenMethod.Name + " 方法调用"; // } // UnityEngine.Debug.Log(info); StackTrace st = new StackTrace(true); StackFrame stackFrame = st.GetFrame(1); MethodBase paren = null; string parentClass = ""; string parentMethod = ""; string parainfo = "( "; int numLine = stackFrame.GetFileLineNumber(); if (stackFrame.GetMethod() != null) { paren = stackFrame.GetMethod(); ParameterInfo[] parameters = paren.GetParameters(); foreach (ParameterInfo p in parameters) { parainfo += "" + p.ParameterType.Name + " " + p.Name + " ,"; } parainfo = parainfo.TrimEnd(','); parainfo += " )"; parentClass = paren.ReflectedType.FullName; parentMethod = paren.Name; } UnityEngine.Debug.Log("+++++++++++++++调用方法开始++++++++++类:" + parentClass + " 方法:" + parentMethod + parainfo + " +++++++++++行数:" + numLine + "++++++++++++"); System.Diagnostics.StackTrace stt = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame[] sfs = stt.GetFrames(); string subparainfo = "( "; for (int u = 0; u < sfs.Length; ++u) { System.Reflection.MethodBase mb = sfs[u].GetMethod(); //过滤不输出包含某些字符串的字段 if (mb.DeclaringType.FullName.Contains("UIElements")) { return; } ParameterInfo[] subparameters = mb.GetParameters(); foreach (ParameterInfo p in subparameters) { subparainfo += "" + p.ParameterType.Name + " " + p.Name + " ,"; } subparainfo = subparainfo.TrimEnd(','); subparainfo += " )"; UnityEngine.Debug.Log("[调用顺序(" + u + ")] " + "类:" + mb.DeclaringType.FullName + " 方法: " + mb.Name + subparainfo + " 行数:" + sfs[u].GetFileLineNumber()); subparainfo = "( "; } UnityEngine.Debug.Log("------------------------------调用方法结束---------------------------------------"); }
public CompositionException(System.Reflection.MethodBase Method, string message, System.Exception innerException) : this(String.Format("{0}\r\nAssembly:{1}\r\n{2}:{3}\r\nArgs:\r\n", message, Method.ReflectedType.AssemblyQualifiedName, Method.MemberType.ToString(), Method.Name), innerException) { System.Reflection.ParameterInfo[] parameters = Method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { _message = String.Format("{0}\t{1}({2})\r\n", _message, parameters[i].Name, parameters[i].ParameterType.ToString()); } }
public MethodReference ImportMethod(SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification(method) || ImportOpenGenericMethod(method, import_kind)) { return(ImportMethodSpecification(method, context)); } var declaring_type = ImportType(method.DeclaringType, context); if (IsGenericInstance(method.DeclaringType)) { method = method.Module.ResolveMethod(method.MetadataToken); } var reference = new MethodReference(method.Name, module.Import(typeof(void))) { Name = method.Name, HasThis = HasCallingConvention(method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention(method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType(method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention(method, SR.CallingConventions.VarArgs)) { reference.CallingConvention &= MethodCallingConvention.VarArg; } if (method.IsGenericMethod) { ImportGenericParameters(reference, method.GetGenericArguments()); } context.Push(reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType(method_info.ReturnType, context) : ImportType(typeof(void), default(ImportGenericContext)); var parameters = method.GetParameters(); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) { reference_parameters.Add( new ParameterDefinition(ImportType(parameters[i].ParameterType, context))); } reference.DeclaringType = declaring_type; return(reference); } finally { context.Pop(); } }
/// <summary>This method returns the full name of a method and its return type and its parameters. /// A full name is including namespaces and classes. /// </summary> /// <param name="method"></param> /// <returns></returns> public static string MethodFullNameReturnParametertypes(System.Reflection.MethodBase method) { return(string.Format("{0} {1}.{2} ({3})", ((System.Reflection.MethodInfo)method).ReturnType, method.DeclaringType.FullName, method.Name, string.Join(",", method.GetParameters().Select(p => p.ParameterType.ToString() + " " + p.Name).ToArray()) // () or (int) or (int,string) etc. )); }
List <TypeSig> GetParameters(SR.MethodBase delMethod) { var pms = new List <TypeSig>(); foreach (var param in delMethod.GetParameters()) { pms.Add(importer.ImportAsTypeSig(param.ParameterType)); } return(pms); }
public override bool CompileTimeValidate(System.Reflection.MethodBase method) { if (string.IsNullOrEmpty(this._parameterName) && this._parameterIndex == -1) { Message.Write(method, SeverityType.Error, ValidationHelper.ParameterNullCheckParameterNotDefined, ValidationMessages.ResourceManager.GetString(ValidationHelper.ParameterNullCheckParameterNotDefined)); return(false); } var param = method.GetParameters(); if (param.Length == 0) { Message.Write(method, SeverityType.Error, ValidationHelper.ParameterNullCheckParameterNotFound, ValidationMessages.ResourceManager.GetString(ValidationHelper.ParameterNullCheckParameterNotFound), method.DeclaringType.Name, method.Name); return(false); } //validate if match ParameterInfo info = null; if (this._parameterIndex >= 0) { if (!(_parameterIndex < param.Length)) { Message.Write(method, SeverityType.Error, ValidationHelper.ParameterNullCheckParameterNotFoundIndex, ValidationMessages.ResourceManager.GetString(ValidationHelper.ParameterNullCheckParameterNotFoundIndex), method.DeclaringType.Name, method.Name, _parameterIndex); return(false); } info = param[_parameterIndex]; _parameterName = info.Name; } else { var findParam = param.FirstOrDefault(p => string.Compare(p.Name, _parameterName, StringComparison.OrdinalIgnoreCase) == 0); if (findParam == null) { Message.Write(method, SeverityType.Error, ValidationHelper.ParameterNullCheckParameterNotFoundName, ValidationHelper.ParameterNullCheckParameterNotFoundName, method.DeclaringType.Name, method.Name, _parameterName); return(false); } for (int index = 0; index < param.Length; index++) { info = param[index]; if (info == findParam) { _parameterIndex = index; break; } info = null; } } if (info.ParameterType.IsValueType) { Message.Write(method, SeverityType.Error, ValidationHelper.ParameterNullCheckParameterValueType, ValidationMessages.ResourceManager.GetString(ValidationHelper.ParameterNullCheckParameterValueType), method.DeclaringType.Name, method.Name, _parameterName); return(false); } return(true); }
string GetArguments(bcl.MethodBase method) { var arguments = new List <string>(); foreach (var arg in method.GetParameters()) { arguments.Add(GetArgument(arg)); } return(string.Join(", ", arguments)); }
private void ResolveOverloadedMethod(RuntimeType t, string methodName, ArrayList argNames, ArrayList argValues) { System.Reflection.MethodBase base2; MemberInfo[] infoArray = t.GetMember(methodName, MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); int length = infoArray.Length; switch (length) { case 1: this.MI = infoArray[0] as System.Reflection.MethodBase; return; case 0: return; default: base2 = null; for (int i = 0; i < length; i++) { System.Reflection.MethodBase base3 = infoArray[i] as System.Reflection.MethodBase; ParameterInfo[] parameters = base3.GetParameters(); if (parameters.Length == argValues.Count) { bool flag = true; for (int j = 0; j < parameters.Length; j++) { Type parameterType = parameters[j].ParameterType; if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); } if (parameterType != argValues[j].GetType()) { flag = false; break; } } if (flag) { base2 = base3; break; } } } break; } if (base2 == null) { throw new RemotingException(Environment.GetResourceString("Remoting_AmbiguousMethod")); } this.MI = base2; }
private static void PushAlignedParameterSize(System.Reflection.MethodBase aMethod) { System.Reflection.ParameterInfo[] xParams = aMethod.GetParameters(); int xSize = 0; for (int i = 0; i < xParams.Length; i++) { xSize += xParams[i].ParameterType.SizeOf().Align(); } Core.AssemblerCode.Add(new Add { DestinationReg = Registers.ESP, SourceRef = "0x" + xSize.ToString("X") }); }
static StackObject *GetParameters_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.MethodBase instance_of_this_method = (System.Reflection.MethodBase) typeof(System.Reflection.MethodBase).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetParameters(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
internal static string MethodInfoFromStackFrame(StackFrame frame) { System.Reflection.MethodBase method = frame.GetMethod(); if (method == null) { return(string.Empty); } StringBuilder builder = new StringBuilder(); builder.Append(method.DeclaringType.FullName); builder.Append("."); builder.Append(method.Name); // Write paramter types and names builder.Append("("); bool isFirstParam = true; foreach (ParameterInfo info in method.GetParameters()) { if (!isFirstParam) { builder.Append(", "); } else { isFirstParam = false; } string name = "<UnknownType>"; if (info.ParameterType != null) { name = info.ParameterType.Name; } builder.Append(name + " " + info.Name); } builder.Append(")"); // Write private symbol information if available if (!String.IsNullOrEmpty(frame.GetFileName())) { builder.Append(' '); builder.AppendFormat(CultureInfo.CurrentCulture, "in {0}:line {1}", frame.GetFileName(), frame.GetFileLineNumber()); } return(builder.ToString()); }
private static void PushAlignedParameterSize(SysReflection.MethodBase aMethod) { SysReflection.ParameterInfo[] xParams = aMethod.GetParameters(); uint xSize; new Comment("[ Newobj.PushAlignedParameterSize start count = " + xParams.Length.ToString() + " ]"); for (int i = 0; i < xParams.Length; i++) { xSize = SizeOfType(xParams[i].ParameterType); new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, SourceValue = Align(xSize, 4) }; } new Comment("[ Newobj.PushAlignedParameterSize end ]"); }
public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { if (this.cacheName == null) { this.cacheName = method.DeclaringType.FullName; } this.className = method.DeclaringType.FullName; this.methodName = method.Name; var parameters = method.GetParameters(); this.parameterTypeNames = parameters.Select(p => p.ParameterType.FullName).ToArray(); var indexes = new List <int>(); for (int cnt = 0; cnt < parameters.Length; cnt++) { var doNotIncludeInCacheKey = parameters[cnt].CustomAttributes .Any(a => a.GetType() == typeof(DoNotIncludeInCacheKeyAttribute)); if (doNotIncludeInCacheKey) { indexes.Add(cnt); } } this.indexesNotToCache = indexes.ToArray(); TryGetKeyDataTypes(this.dataKeyConverterType, out this.keyType, out this.dataType); this.createDataKeyConverter = this.dataKeyConverterType.GetConstructor(new Type[0]); this.convertDataToKey = this.dataKeyConverterType.GetMethod("GetKey", new Type[] { this.dataType }); var keyListType = typeof(List <>).MakeGenericType(this.keyType); var dataListType = typeof(List <>).MakeGenericType(this.dataType); var dataEnumerableType = typeof(IEnumerable <>).MakeGenericType(this.dataType); this.createKeyList = keyListType.GetConstructor(new Type[0]); this.createDataList = dataListType.GetConstructor(new Type[0]); this.addKey = keyListType.GetMethod("Add", new[] { this.keyType }); this.addData = dataListType.GetMethod("Add", new[] { this.dataType }); this.addDataRange = dataListType.GetMethod("AddRange", new[] { dataEnumerableType }); }
public static void ProcessStackTrace() { // пока не используется System.Diagnostics.StackTrace callStack = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame frame = null; System.Reflection.MethodBase calledMethod = null; System.Reflection.ParameterInfo[] passedParams = null; for (int x = 0; x < callStack.FrameCount; x++) { frame = callStack.GetFrame(x); calledMethod = frame.GetMethod(); passedParams = calledMethod.GetParameters(); foreach (System.Reflection.ParameterInfo param in passedParams) { HttpContext.Current.Response.Write(param.ToString() + " " + param.DefaultValue + " " + param.RawDefaultValue + "<br />"); } } }
public static MethodSignature FromReflection(R.MethodBase method) { method = SanitizeDeclaringTypeGenerics(method.IsGenericMethod ? ((R.MethodInfo)method).GetGenericMethodDefinition() : method); var declaringType = TypeSignature.FromType(method.DeclaringType); var accessibility = method.IsPublic ? Accessibility.APublic : method.IsAssembly ? Accessibility.AInternal : method.IsPrivate ? Accessibility.APrivate : method.IsFamily ? Accessibility.AProtected : method.IsFamilyOrAssembly ? Accessibility.AProtectedInternal : method.IsFamilyAndAssembly ? Accessibility.APrivateProtected : throw new NotSupportedException("Unsupported accessibility of " + method); var parameters = method.GetParameters().EagerSelect(p => { var t = TypeReference.FromType(p.ParameterType); return(new MethodParameter(t, p.Name ?? "", p.HasDefaultValue, p.HasDefaultValue ? CanonicalizeDefaultValue(p.DefaultValue, t) : null, p.IsDefined(typeof(ParamArrayAttribute), true))); }); var genericParameters = method.IsGenericMethodDefinition ? method.GetGenericArguments() : method.IsGenericMethod ? ((R.MethodInfo)method).GetGenericMethodDefinition().GetGenericArguments() : Type.EmptyTypes; var returnType = method is R.MethodInfo mi ? TypeReference.FromType(mi.ReturnType) : TypeSignature.Void; var isDestructor = method.Name == "Finalize" && !method.IsStatic && method is R.MethodInfo min && min.ReturnType == typeof(void) && min.GetParameters().Length == 0; return(new MethodSignature(declaringType, parameters, method.Name, returnType, method.IsStatic, accessibility, method.IsVirtual && !method.IsFinal && declaringType.CanOverride, isOverride: (method as R.MethodInfo)?.GetBaseDefinition() != method, method.IsAbstract, method.IsSpecialName || isDestructor, genericParameters.EagerSelect(GenericParameter.FromType) )); }
private IList <IParameter> GetArguments(System.Reflection.MethodBase method) { ParameterInfo[] parameters = method.GetParameters(); IParameter[] parameter = new IParameter[(int)parameters.Length]; for (int i = 0; i < (int)parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; Type valueType = PlatformTypeHelper.GetValueType(parameterInfo); IType type = null; if (valueType != null) { type = this.typeResolver.GetType(valueType); } if (type == null) { type = this.typeResolver.ResolveType(PlatformTypes.Object); } parameter[i] = new BaseMethod.Parameter(type, parameterInfo.Name); } return(new ReadOnlyCollection <IParameter>(parameter)); }
/// <summary> /// Construct the method name for later use /// </summary> /// <param name="method"></param> /// <param name="aspectInfo"></param> public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { base.CompileTimeInitialize(method, aspectInfo); MethodName = string.Format("{0}.{1}", method.DeclaringType.Name, method.Name); if (ArgumentName != null) { string name = ArgumentName; if (name.Contains(".")) { name = name.Substring(0, name.IndexOf('.')); } ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (parameter.Name == name) { ArgumentIndex = parameter.Position; } } } }
private static string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) { ArrayList methodParameterNames = new ArrayList(); try { System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); for (int i = 0; i <= methodBaseGetParametersCount; i++) { methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); } } catch (Exception ex) { LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); } return((string[])methodParameterNames.ToArray(typeof(string))); }
public override void RuntimeInitialize(System.Reflection.MethodBase method) { if (_mode.HasFlag(AuthorizationMode.AccountRequest) || _mode.HasFlag(AuthorizationMode.AccountEntityCommand)) { _accountAuthorizer = IocContainer.AccountRequestAuthorizer; var methodParams = method.GetParameters(); for (int i = 0; i < methodParams.Length; i++) { var param = methodParams[i]; if (param.ParameterType.IsAssignableTo <IAuthoriziedAccountRequest>()) { _authoriziedAccountRequestParams.Add(i); } if (param.ParameterType.IsAssignableTo <IAuthoriziedEntityCommand>() && IocContainer.EntityCommandAuthorizers.TryGetValue(param.ParameterType, out IAuthorizer authorizer)) { _authorizersCache.Add(i, authorizer); } } } if (_mode.HasFlag(AuthorizationMode.ReturnValue) && method is MethodInfo info) { if (info.ReturnType.IsAssignableTo <IHasAccountNumber>()) { _returnValueHasAccountNumber = true; } else if (info.ReturnType.IsAssignableTo <IEnumerable <IHasAccountNumber> >()) { _returnValueHasAccountNumberEnumerable = true; } } base.RuntimeInitialize(method); }
static string GetMethodBaseSignature(SR.MethodBase meth, Type declaringType, Type retType) { StringBuilder sb = new StringBuilder(); sb.Append(GetTypeSignature(retType)); sb.Append(' '); sb.Append(GetTypeSignature(declaringType)); sb.Append("::"); sb.Append(meth.Name); if (IsGenericMethodSpec(meth)) { sb.Append("<"); Type [] genArgs = GetGenericArguments(meth as SR.MethodInfo); for (int i = 0; i < genArgs.Length; i++) { if (i > 0) { sb.Append(","); } sb.Append(GetTypeSignature(genArgs [i])); } sb.Append(">"); } sb.Append("("); SR.ParameterInfo [] parameters = meth.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (i > 0) { sb.Append(","); } sb.Append(GetTypeSignature(parameters [i].ParameterType)); } sb.Append(")"); return(sb.ToString()); }
public override bool CompileTimeValidate(System.Reflection.MethodBase method) { Type keyType, dataType; if (!TryGetKeyDataTypes(this.dataKeyConverterType, out keyType, out dataType)) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", "The type provided does not implement IDataKeyConverter<TKey, TData>."); return(false); } if (this.dataKeyConverterType.IsAbstract || this.dataKeyConverterType.GetConstructor(new Type[0]) == null) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", string.Format("{0} is abstract or does not have a public parameter-less constructor", this.dataKeyConverterType.FullName)); return(false); } var keyIListType = typeof(IList <>).MakeGenericType(keyType); var dataIListType = typeof(IList <>).MakeGenericType(dataType); if (method.GetParameters().Length <= this.keyParameterNumber) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", string.Format("The method {0} does not have a parameter {1}.", method.Name, this.keyParameterNumber)); return(false); } var keysParameterType = method.GetParameters()[this.keyParameterNumber].ParameterType; if (keysParameterType != keyIListType) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", string.Format("The parameter {1} of method {0} != IList<TKey>.", method.Name, this.keyParameterNumber)); return(false); } var methodInfo = method as System.Reflection.MethodInfo; if (methodInfo == null || methodInfo.ReturnType == null) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", string.Format("The method {0} has no return type.", method.Name)); return(false); } var returnType = methodInfo.ReturnType; if (returnType != dataIListType) { PostSharp.Extensibility.Message.Write( PostSharp.MessageLocation.Of(method), PostSharp.Extensibility.SeverityType.Error, "Custom01", string.Format("The return type of method {0} != IList<TData>.", method.Name)); return(false); } return(true); }
public static uint CompareNameAndMethodInfo(/*STRING*/ byte *name, System.Reflection.MethodBase methodBase, tMetaData *pSigMetaData, tMD_TypeDef **ppSigClassTypeArgs, tMD_TypeDef **ppSigMethodTypeArgs, tMD_MethodDef *pMethod, tMD_TypeDef **ppMethodClassTypeArgs, tMD_TypeDef **ppMethodMethodTypeArgs) { if (S.strcmp(name, pMethod->name) == 0) { uint i; if (METHOD_ISSTATIC(pMethod) != methodBase.IsStatic || METHOD_ISVIRTUAL(pMethod) != methodBase.IsVirtual) { return(0); } System.Reflection.ParameterInfo[] paramInfos = methodBase.GetParameters(); uint numberOfParameters = (uint)(paramInfos.Length + (methodBase.IsStatic ? 0 : 1)); if ((uint)pMethod->numberOfParameters != numberOfParameters) { return(0); } if (methodBase.IsGenericMethod != (pMethod->isGenericDefinition != 0)) { return(0); } if (methodBase is MethodInfo) { if (pMethod->pReturnType == null) { if (((MethodInfo)methodBase).ReturnType != typeof(void)) { return(0); } } else if (pMethod->pReturnType != MonoType.GetTypeForMonoType(((MethodInfo)methodBase).ReturnType, ppMethodClassTypeArgs, ppMethodMethodTypeArgs)) { return(0); } } uint start = 0; if (!methodBase.IsStatic) { // if (pMethod->pParams[0].pStackTypeDef != MonoType.GetTypeForMonoType(methodInfo.DeclaringType)) // return 0; start = 1; } for (i = start; i < numberOfParameters; i++) { tParameter *pParam = &pMethod->pParams[i]; System.Reflection.ParameterInfo paramInfo = paramInfos[i - start]; // NOTE: We are not checking to see if params are REF params here. Potentially a problem. if (pParam->pStackTypeDef != MonoType.GetTypeForMonoType(paramInfo.ParameterType, ppMethodClassTypeArgs, ppMethodMethodTypeArgs)) { return(0); } } return(1); } return(0); }
MethodReference ImportMethodBase(SR.MethodBase mb, Type retType, ImportContext context) { if (IsGenericMethod(mb) && !IsGenericMethodDefinition(mb)) { return(ImportGenericInstanceMethod((SR.MethodInfo)mb, context)); } Type originalDecType = mb.DeclaringType; Type declaringTypeDef = originalDecType; while (IsGenericTypeSpec(declaringTypeDef)) { declaringTypeDef = GetGenericTypeDefinition(declaringTypeDef); } if (mb.DeclaringType != declaringTypeDef && mb is SR.MethodInfo) { int mt = GetMetadataToken(mb as SR.MethodInfo); // hack to get the generic method definition from the constructed method foreach (SR.MethodInfo mi in declaringTypeDef.GetMethods()) { if (GetMetadataToken(mi) == mt) { mb = mi; retType = mi.ReturnType; break; } } } string sig = GetMethodBaseSignature(mb, originalDecType, retType); MethodReference meth = (MethodReference)GetMemberReference(sig); if (meth != null) { return(meth); } meth = new MethodReference( mb.Name, (mb.CallingConvention & SR.CallingConventions.HasThis) > 0, (mb.CallingConvention & SR.CallingConventions.ExplicitThis) > 0, MethodCallingConvention.Default); // TODO: get the real callconv meth.DeclaringType = ImportSystemType(originalDecType, context); if (IsGenericMethod(mb)) { foreach (Type genParam in GetGenericArguments(mb as SR.MethodInfo)) { meth.GenericParameters.Add(new GenericParameter(genParam.Name, meth)); } } TypeReference contextType = context.GenericContext.Type; MethodReference contextMethod = context.GenericContext.Method; context.GenericContext.Method = meth; context.GenericContext.Type = ImportSystemType(declaringTypeDef, context); meth.ReturnType.ReturnType = ImportSystemType(retType, context); SR.ParameterInfo [] parameters = mb.GetParameters(); for (int i = 0; i < parameters.Length; i++) { meth.Parameters.Add(new ParameterDefinition( ImportSystemType(parameters [i].ParameterType, context))); } context.GenericContext.Type = contextType; context.GenericContext.Method = contextMethod; m_module.MemberReferences.Add(meth); return(meth); }
//Execution using strongly typed enumerations. Working implementation will be converted native integer values // to allow native MSIL instruction public object ExecuteTyped(List <ILInstruction> stream, IILInstructionResolver resolver = null, object[] args = null, ILVariable[] locals = null, ILOperandStack frameStack = null) { //getArglistHandle(__arglist(1, 2, "s", 8)); <-- can't support dynamic/reflection based invocation // probably best we can do is detect varargs, convert them to object[] and reinterprit msil. // for now will just have to throw excpetion. if (resolver is null) { resolver = ILInstructionResolver.ExecutingAssemblyResolver; } var resolveField = resolver.ResolveFieldToken; var resolveMember = resolver.ResolveMemberToken; var resolveMethod = resolver.ResolveMethodToken; var resolveSignature = resolver.ResolveSignatureToken; var resolveString = resolver.ResolveStringToken; var resolveType = resolver.ResolveTypeToken; var stack = frameStack ?? new ILOperandStack(); ILInstruction current; OpCode code; int pos = -1; Dictionary <int, int> jmptable = stream.ToDictionary(x => (int)x.ByteIndex, x => ++ pos); pos = -1; goto Inc; ReadNext: current = stream[pos]; code = current.OpCode; short opCodeValue = code.Value; switch (opCodeValue) { case (short)ILOpCodeValues.Nop: break; case (short)ILOpCodeValues.Ret: goto Ret; case (short)ILOpCodeValues.Stloc_0: locals[0].Value = stack.Pop(); break; case (short)ILOpCodeValues.Stloc_1: locals[1].Value = stack.Pop(); break; case (short)ILOpCodeValues.Stloc_2: locals[2].Value = stack.Pop(); break; case (short)ILOpCodeValues.Stloc_3: locals[3].Value = stack.Pop(); break; case unchecked ((short)ILOpCodeValues.Stloc): locals[(int)current.Arg].Value = stack.Pop(); break; case (short)ILOpCodeValues.Stloc_S: locals[(byte)current.Arg].Value = stack.Pop(); break; case (short)ILOpCodeValues.Stobj: throw new NotImplementedException(); case (short)ILOpCodeValues.Ldloc_0: stack.Push(locals[0].Value); break; case (short)ILOpCodeValues.Ldloc_1: stack.Push(locals[1].Value); break; case (short)ILOpCodeValues.Ldloc_2: stack.Push(locals[2].Value); break; case (short)ILOpCodeValues.Ldloc_3: stack.Push(locals[3].Value); break; case unchecked ((short)ILOpCodeValues.Ldloc): stack.Push(locals[(int)current.Arg].Value); break; case (short)ILOpCodeValues.Ldloc_S: stack.Push(locals[(byte)current.Arg].Value); break; case unchecked ((short)ILOpCodeValues.Ldloca): stack.Push(locals[(int)current.Arg]); break; case (short)ILOpCodeValues.Ldloca_S: stack.Push(locals[(byte)current.Arg]); break; case (short)ILOpCodeValues.Ldarg_0: stack.Push(args[0]); break; case (short)ILOpCodeValues.Ldarg_1: stack.Push(args[1]); break; case (short)ILOpCodeValues.Ldarg_2: stack.Push(args[2]); break; case (short)ILOpCodeValues.Ldarg_3: stack.Push(args[3]); break; case unchecked ((short)ILOpCodeValues.Ldarg): stack.Push(args[(int)current.Arg]); break; case unchecked ((short)ILOpCodeValues.Ldarg_S): stack.Push(args[(byte)current.Arg]); break; case (short)ILOpCodeValues.Ldarga_S: stack.Push(args[(byte)current.Arg]); break; case unchecked ((short)ILOpCodeValues.Ldarga): stack.Push(args[(int)current.Arg]); break; case (short)ILOpCodeValues.Ldc_I4: stack.Push((int)current.Arg); break; case (short)ILOpCodeValues.Ldc_I4_0: stack.Push(0); break; case (short)ILOpCodeValues.Ldc_I4_1: stack.Push(1); break; case (short)ILOpCodeValues.Ldc_I4_2: stack.Push(2); break; case (short)ILOpCodeValues.Ldc_I4_3: stack.Push(3); break; case (short)ILOpCodeValues.Ldc_I4_4: stack.Push(4); break; case (short)ILOpCodeValues.Ldc_I4_5: stack.Push(5); break; case (short)ILOpCodeValues.Ldc_I4_6: stack.Push(6); break; case (short)ILOpCodeValues.Ldc_I4_7: stack.Push(7); break; case (short)ILOpCodeValues.Ldc_I4_8: stack.Push(8); break; case (short)ILOpCodeValues.Ldc_I4_S: stack.Push(Convert.ToInt32(current.Arg)); break; case (short)ILOpCodeValues.Ldc_I4_M1: stack.Push(-1); break; case (short)ILOpCodeValues.Ldc_I8: stack.Push(Convert.ToInt64(current.Arg)); break; case (short)ILOpCodeValues.Ldc_R4: stack.Push(Convert.ToSingle(current.Arg)); break; case (short)ILOpCodeValues.Ldc_R8: stack.Push(Convert.ToDouble(current.Arg)); break; case (short)ILOpCodeValues.Box: // 140: //box stack.Push(((object)stack.Pop())); break; case (short)ILOpCodeValues.Ckfinite: // 195: //ckfinite var ckval = stack.Pop(); stack.Push((ckval is float?float.IsInfinity((float)ckval) : double.IsInfinity((double)ckval))); break; case (short)ILOpCodeValues.Conv_I1: // 103: //conv.i1 stack.Push(unchecked ((sbyte)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I2: //104: //conv.i2 stack.Push(unchecked ((short)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I4: //105: //conv.i4 stack.Push(unchecked ((int)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I8: //106: //conv.i8 { var arg = stack.Pop(); try { stack.Push(unchecked (Convert.ToInt64(arg))); } catch { stack.Push(unchecked ((long)Convert.ToUInt64(arg))); } } break; case (short)ILOpCodeValues.Conv_Ovf_I1: //179: //conv.ovf.i1 stack.Push(checked ((sbyte)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I1_Un: //130: //conv.ovf.i1.un stack.Push(checked ((sbyte)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I2: //181: //conv.ovf.i2 stack.Push(checked ((short)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I2_Un: //131: //conv.ovf.i2.un stack.Push(checked ((short)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I4: //183: //conv.ovf.i4 stack.Push(checked ((int)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I4_Un: //132: //conv.ovf.i4.un stack.Push(checked ((int)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I8: //185: //conv.ovf.i8 stack.Push(checked ((long)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I8_Un: //133: //conv.ovf.i8.un stack.Push(checked ((long)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U1: //180: //conv.ovf.u1 stack.Push(checked ((byte)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U1_Un: //134: //conv.ovf.u1.un stack.Push(checked ((byte)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U2: //182: //conv.ovf.u2 stack.Push(checked ((ushort)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U2_Un: //135: //conv.ovf.u2.un stack.Push(checked ((ushort)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U4: //184: //conv.ovf.u4 stack.Push(checked ((uint)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U4_Un: //136: //conv.ovf.u4.un stack.Push(checked ((uint)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U8: //186: //conv.ovf.u8 stack.Push(checked ((ulong)Convert.ToInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_U8_Un: //137: //conv.ovf.u8.un stack.Push(checked ((ulong)Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_R4: //107: //conv.r4 stack.Push(Convert.ToSingle(stack.Pop())); break; case (short)ILOpCodeValues.Conv_R8: //108: //conv.r8 stack.Push(Convert.ToDouble(stack.Pop())); break; case (short)ILOpCodeValues.Conv_R_Un: //118: //conv.r.un stack.Push(Convert.ToSingle(stack.Pop())); break; case (short)ILOpCodeValues.Conv_U1: //210: //conv.u1 stack.Push(unchecked (Convert.ToByte(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U2: //209: //conv.u2 stack.Push(unchecked (Convert.ToUInt16(stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U4: //109: //conv.u4 stack.Push(unchecked ((uint)(Convert.ToInt64(stack.Pop())))); break; case (short)ILOpCodeValues.Conv_U8: //110: //conv.u8 stack.Push(unchecked (Convert.ToUInt64(stack.Pop()))); break; case (short)ILOpCodeValues.Neg: //101: //neg stack.Push(-((dynamic)stack.Pop())); break; case (short)ILOpCodeValues.Newarr: //141: //newarr stack.Push(Array.CreateInstance(((current.Arg is int) ? resolveType((int)current.Arg) : (Type)current.Arg), (int)stack.Pop())); break; case (short)ILOpCodeValues.Not: //102: //not stack.Push(!((dynamic)stack.Pop())); break; case (short)ILOpCodeValues.Pop: //38: //pop stack.Pop(); // no push break; case (short)ILOpCodeValues.Shl: //98: //shl stack.Push(((dynamic)stack.Pop()) << ((int)current.Arg)); break; case (short)ILOpCodeValues.Shr: //99: //shr stack.Push(((dynamic)stack.Pop()) >> ((int)current.Arg)); break; case (short)ILOpCodeValues.Shr_Un: //100: //shr.un stack.Push(((dynamic)stack.Pop()) >> ((int)current.Arg)); break; case (short)ILOpCodeValues.Unbox: //121: //unbox stack.Push(Convert.ChangeType(stack.Pop(), resolveType((int)current.Arg))); break; case (short)ILOpCodeValues.Unbox_Any: //165: //unbox.any stack.Push(Convert.ChangeType(stack.Pop(), resolveType((int)current.Arg))); break; case (short)ILOpCodeValues.Add: //: //add stack.Push(unchecked ((dynamic)stack.Pop() + (dynamic)stack.Pop())); break; case (short)ILOpCodeValues.Add_Ovf: // 214: //add.ovf stack.Push(checked ((dynamic)stack.Pop() + (dynamic)stack.Pop())); break; case (short)ILOpCodeValues.Add_Ovf_Un: // 215: //add.ovf.un stack.Push(checked ((dynamic)stack.Pop() + (dynamic)stack.Pop())); break; case (short)ILOpCodeValues.And: //95: //and stack.Push(((dynamic)stack.Pop()) & ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Ceq): //: //ceq { var opa = stack.Pop(); var opb = stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); stack.Push(compc == 0 ? 1 : 0); } else { stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } } break; case unchecked ((short)ILOpCodeValues.Cgt): // -510: //cgt stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) < ((dynamic)stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Cgt_Un): //- 509: //cgt.un stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) < ((dynamic)stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Clt): // -508: //clt stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) > ((dynamic)stack.Pop()))); //either swap pop order or sign break; case unchecked ((short)ILOpCodeValues.Clt_Un): // -507: //clt.un stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) > ((dynamic)stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Div): // 91: //div stack.Push(((dynamic)stack.Pop()) / ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Div_Un): // 92: //div.un stack.Push(((dynamic)stack.Pop()) / ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Mul): // 90: //mul stack.Push(unchecked (((dynamic)stack.Pop()) * ((dynamic)stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Mul_Ovf): // 216: //mul.ovf stack.Push(((dynamic)stack.Pop()) * ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Mul_Ovf_Un): // 217: //mul.ovf.un stack.Push(((dynamic)stack.Pop()) * ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Or): // 96: //or stack.Push(((dynamic)stack.Pop()) | ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Rem): // 93: //rem stack.Push(((dynamic)stack.Pop()) % ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Rem_Un): // 94: //rem.un stack.Push(((dynamic)stack.Pop()) % ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Sub): // 89: //sub stack.Push(unchecked (((dynamic)stack.Pop()) - ((dynamic)stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Sub_Ovf): // 218: //sub.ovf stack.Push(((dynamic)stack.Pop()) - ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Sub_Ovf_Un): // 219: //sub.ovf.un stack.Push(((dynamic)stack.Pop()) - ((dynamic)stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Xor): // 97: //xor stack.Push(((dynamic)stack.Pop()) ^ ((dynamic)stack.Pop())); break; case (short)ILOpCodeValues.Ldstr: { if (current.Arg is string) { stack.Push((string)current.Arg); } else { stack.Push(resolveString((int)current.Arg)); } break; } case (short)ILOpCodeValues.Newobj: { var ctor = (System.Reflection.ConstructorInfo)resolveMethod((int)current.Arg); var ctorArgs = new object[ctor.GetParameters().Length]; for (var i = ctorArgs.Length - 1; i > -1; i--) { ctorArgs[i] = stack.Pop(); } //var reversed = ctorArgs.Reverse().ToArray(); var ctorResult = ctor.Invoke(ctorArgs); stack.Push(ctorResult); break; } case (short)ILOpCodeValues.Ldfld: { var field = resolveField((int)current.Arg); var target = stack.Pop(); var value = field.GetValue(target); stack.Push(value); break; } case (short)ILOpCodeValues.Ldsfld: { var field = resolveField((int)current.Arg); var value = field.GetValue(null); stack.Push(value); break; } case (short)ILOpCodeValues.Stfld: { var field = resolveField((int)current.Arg); var fo = stack.Pop(); var target = stack.Pop(); field.SetValue(target, fo); //stack.Push(value); break; } case (short)ILOpCodeValues.Stsfld: { var field = resolveField((int)current.Arg); var fo = stack.Pop(); //var target = stack.Pop(); field.SetValue(null, fo); break; } case (short)ILOpCodeValues.Ldlen: { var array = stack.Pop(); var arr = (Array)array; stack.Push(arr.Length); break; } case (short)ILOpCodeValues.Stelem: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = (Array)stack.Pop(); array.GetType() .GetMethod("SetValue", new[] { typeof(object), typeof(int) }) .Invoke(array, new object[] { el, index }); break; } case (short)ILOpCodeValues.Stelem_I1: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(sbyte)) { ((sbyte[])array)[index] = (sbyte)(int)el; } else { ((byte[])array)[index] = (byte)(int)el; } break; } case (short)ILOpCodeValues.Stelem_I2: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(short)) { ((Array)array).SetValue((short)(int)el, index); } else if (arrElType == typeof(short)) { ((Array)array).SetValue((ushort)(int)el, index); } else { ((Array)array).SetValue(Convert.ChangeType(el, arrElType), index); } break; } case (short)ILOpCodeValues.Stelem_I4: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(int)) { ((int[])array)[index] = (int)el; } else { ((uint[])array)[index] = (uint)el; } break; } case (short)ILOpCodeValues.Stelem_I8: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(long)) { ((long[])array)[index] = (long)el; } else { ((ulong[])array)[index] = (ulong)el; } break; } case (short)ILOpCodeValues.Stelem_R4: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(float)) { ((float[])array)[index] = (float)el; } //else ((ulong[])array)[index] = (ulong)el; break; } case (short)ILOpCodeValues.Stelem_R8: { object el = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(double)) { ((double[])array)[index] = (double)el; } //else ((ulong[])array)[index] = (ulong)el; break; } case (short)ILOpCodeValues.Stelem_Ref: { object val = stack.Pop(); int index = (int)stack.Pop(); var array = stack.Pop(); ((Array)array).SetValue(val, index); break; } case (short)ILOpCodeValues.Ldelem: case (short)ILOpCodeValues.Ldelema: case (short)ILOpCodeValues.Ldelem_I: case (short)ILOpCodeValues.Ldelem_Ref: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); stack.Push(val); break; } case (short)ILOpCodeValues.Ldelem_I1: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = (sbyte)Convert.ToInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I2: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = (short)Convert.ToInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I4: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I8: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToInt64(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U1: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = (byte)Convert.ToUInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U2: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = (ushort)Convert.ToUInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U4: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToUInt32(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_R4: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToSingle(val); stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_R8: { var idx = (int)stack.Pop(); var array = (Array)stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToDouble(val); stack.Push(target); break; } case (short)ILOpCodeValues.Conv_I: case (short)ILOpCodeValues.Conv_Ovf_I_Un: case (short)ILOpCodeValues.Conv_Ovf_I: //Todo: native int operations throw new OpCodeNotImplementedException(code); case (short)ILOpCodeValues.Dup: stack.Push(stack.Peek()); break; //TODO: Implemented scopre validation for branch: (EG, inside try, catch, finally,etc) case (short)ILOpCodeValues.Leave_S: case (short)ILOpCodeValues.Br_S: //0x2b: { var delta = (int)(sbyte)Convert.ToByte(current.Arg); var directpos = (int)stream[pos + 1].ByteIndex + delta; pos = jmptable[directpos]; goto MoveNext; } case (short)ILOpCodeValues.Leave: case (short)ILOpCodeValues.Br: // 0x38: { var delta = Convert.ToInt32(current.Arg); var directpos = (int)stream[pos + 1].ByteIndex + delta; pos = jmptable[directpos]; goto MoveNext; } case (short)ILOpCodeValues.Beq: { var opa = stack.Pop(); var opb = stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); stack.Push(compc == 0 ? 1 : 0); } else { stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } goto case (short)ILOpCodeValues.Brtrue; } case (short)ILOpCodeValues.Beq_S: { var opa = stack.Pop(); var opb = stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); stack.Push(compc == 0 ? 1 : 0); } else { stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } goto case (short)ILOpCodeValues.Brtrue_S; } case (short)ILOpCodeValues.Brfalse: //00111001 { var chk = stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 0) { condtarget = (int)stream[pos + 1].ByteIndex + Convert.ToInt32(current.Arg); pos = jmptable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brfalse_S: { var chk = stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 0) { condtarget = (int)stream[pos + 1].ByteIndex + (int)(sbyte)Convert.ToByte(current.Arg); pos = jmptable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brtrue: { var chk = stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 1) { condtarget = (int)stream[pos + 1].ByteIndex + Convert.ToInt32(current.Arg); pos = jmptable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brtrue_S: { var chk = stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 1) { condtarget = (int)stream[pos + 1].ByteIndex + (int)(sbyte)Convert.ToByte(current.Arg); pos = jmptable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Call: case (short)ILOpCodeValues.Calli: case (short)ILOpCodeValues.Callvirt: System.Reflection.MethodBase method = null; object resolved = null; if (current.Arg is System.Reflection.MethodInfo) { method = (System.Reflection.MethodInfo)current.Arg; } else { resolved = resolveMethod((int)current.Arg); } if (resolved is ConstructorInfo) { method = (ConstructorInfo)resolved; } else { method = (System.Reflection.MethodInfo)resolved; } var parameters = method.GetParameters(); var methodArgs = new object[parameters.Length]; for (var i = methodArgs.Length - 1; i >= 0; i--) { var val = stack.Pop(); if (val is ILVariable) { methodArgs[i] = ((ILVariable)(val)).Value; } else { methodArgs[i] = val; } } object methodTarget = null; if (!method.IsStatic && !method.IsConstructor) { methodTarget = stack.Pop(); } if (methodTarget is ILVariable) { methodTarget = ((ILVariable)methodTarget).Value; } //var t = default(RuntimeTypeHandle); //var t1 = default(ArgIterator); //var tobject = new object[] { t, t }; //var del = Delegate.CreateDelegate() //((ConstructorInfo)method).Invoke( new object[]{ t}); for (var i = methodArgs.Length - 1; i >= 0; i--) { if (methodArgs[i] is IConvertible) { methodArgs[i] = Convert.ChangeType(methodArgs[i], parameters[i].ParameterType); } } //if the current method is invoking another method then convert the arguments for the inner method. if (methodTarget is MethodBase && methodArgs.Length == 2 && methodArgs[1] is Array) { var invokeArgs = (Array)methodArgs[1]; var invokeParameters = ((MethodInfo)methodTarget).GetParameters(); for (var i = invokeArgs.Length - 1; i >= 0; i--) { var arg = invokeArgs.GetValue(i); if (arg is IConvertible) { invokeArgs.SetValue(Convert.ChangeType(arg, invokeParameters[i].ParameterType), i); } } //if (invokeArgs.GetValue(i) is IConvertible) // invokeArgs.SetValue(Convert.ChangeType(invokeArgs[i], invokeParameters[i].ParameterType)); } // Roadblock here: Int.CompareTo(object value) -> argument value must be of type int but there is no way to programatically determine the expected destination type. var methodresult = (method is MethodInfo) ? method.Invoke(methodTarget, methodArgs) : ((ConstructorInfo)method).Invoke(methodArgs); if (code.StackBehaviourPush == StackBehaviour.Varpush) { if ((method as MethodInfo)?.ReturnType != typeof(void) || method.IsConstructor) { stack.Push(methodresult); } } break; case unchecked ((short)ILOpCodeValues.Ldobj): stack.Push(current.Arg); break; case (short)ILOpCodeValues.Ldnull: stack.Push(null); break; case unchecked ((short)ILOpCodeValues.Ldftn): var ftnToken = (int)current.Arg; var ftnMethod = resolver.ResolveMethodToken(ftnToken); stack.Push(ftnMethod.MethodHandle.GetFunctionPointer()); break; case unchecked ((short)ILOpCodeValues.Initobj): var newObj = Activator.CreateInstance(resolver.ResolveTypeToken((int)current.Arg)); var inst = stack.Pop(); if (inst is ILVariable ilvar) { ilvar.Value = newObj; locals[ilvar.Index] = ilvar; } else { inst = newObj; } break; case (short)ILOpCodeValues.Ldtoken: var metaToken = (int)current.Arg; var memToken = resolver.ResolveMemberToken(metaToken); var tokenType = memToken.GetType(); switch (tokenType.Name) { case "RtFieldInfo": { var fieldInfo = resolver.ResolveFieldToken(metaToken); var handle = (FieldInfo)fieldInfo; stack.Push(handle.FieldHandle); } break; case "RuntimeType": { var type = resolver.ResolveTypeToken(metaToken); var handle = (Type)type; stack.Push(handle.TypeHandle); } break; default: throw new OpCodeNotImplementedException(code); } break; case (short)ILOpCodeValues.Castclass: var targetClassToken = (int)current.Arg; var targetType = resolver.ResolveTypeToken(targetClassToken); var listType = typeof(List <>).MakeGenericType(new[] { targetType }); var instance = Activator.CreateInstance(listType); var prop = listType.GetProperty("Item"); var src = stack.Pop(); var add = listType.GetMethod("Add"); add.Invoke(instance, new[] { src }); var get = listType.GetMethod("get_Item"); var listresult = get.Invoke(instance, new object[] { 0 }); stack.Push(listresult); break; case (short)ILOpCodeValues.Break: if (TriggerBreak) { System.Diagnostics.Debugger.Break(); } break; default: throw new OpCodeNotImplementedException(code); } Inc: pos++; MoveNext: if (pos < stream.Count) { goto ReadNext; } Ret: var result = (stack.Count > 0) ? stack.Pop() : null; if (TriggerBreak) { System.Diagnostics.Debug.Assert(stack.Count == 0); } else { //if (stack.Count > 0) throw new InvalidProgramException("Stack is not empty {stack.Count}"); } return(result); }
public static IList <Attribute> GetParameterAttributes(System.Reflection.MethodBase method, int index) { return(new ReadOnlyCollection <Attribute>(System.Reflection.CustomAttributeExtensions.GetCustomAttributes(method.GetParameters()[index], true).ToList())); }
public void ExecuteFrame(ILStackFrameWithDiagnostics frame) { frame.Reset(); goto Inc; ReadNext: frame.ReadNext(); short opCodeValue = frame.Code.Value; switch (opCodeValue) { case (short)ILOpCodeValues.Nop: break; case (short)ILOpCodeValues.Ret: goto Ret; case (short)ILOpCodeValues.Stloc_0: frame.Locals[0].Value = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Stloc_1: frame.Locals[1].Value = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Stloc_2: frame.Locals[2].Value = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Stloc_3: frame.Locals[3].Value = frame.Stack.Pop(); break; case unchecked ((short)ILOpCodeValues.Stloc): frame.Locals[(int)frame.Current.Arg].Value = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Stloc_S: frame.Locals[(byte)(int)frame.Current.Arg].Value = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Stobj: throw new NotImplementedException(); case (short)ILOpCodeValues.Ldloc_0: frame.Stack.Push(frame.Locals[0].Value); break; case (short)ILOpCodeValues.Ldloc_1: frame.Stack.Push(frame.Locals[1].Value); break; case (short)ILOpCodeValues.Ldloc_2: frame.Stack.Push(frame.Locals[2].Value); break; case (short)ILOpCodeValues.Ldloc_3: frame.Stack.Push(frame.Locals[3].Value); break; case unchecked ((short)ILOpCodeValues.Ldloc): frame.Stack.Push(frame.Locals[(int)frame.Current.Arg].Value); break; case (short)ILOpCodeValues.Ldloc_S: frame.Stack.Push(frame.Locals[(byte)(int)frame.Current.Arg].Value); break; case unchecked ((short)ILOpCodeValues.Ldloca): frame.Stack.Push(frame.Locals[(int)frame.Current.Arg].Value); break; case (short)ILOpCodeValues.Ldloca_S: frame.Stack.Push(frame.Locals[(byte)(int)frame.Current.Arg].Value); break; case (short)ILOpCodeValues.Ldarg_0: frame.Stack.Push(frame.Args[0]); break; case (short)ILOpCodeValues.Ldarg_1: frame.Stack.Push(frame.Args[1]); break; case (short)ILOpCodeValues.Ldarg_2: frame.Stack.Push(frame.Args[2]); break; case (short)ILOpCodeValues.Ldarg_3: frame.Stack.Push(frame.Args[3]); break; case unchecked ((short)ILOpCodeValues.Ldarg): frame.Stack.Push(frame.Args[(int)frame.Current.Arg]); break; case unchecked ((short)ILOpCodeValues.Ldarg_S): frame.Stack.Push(frame.Args[(byte)(int)frame.Current.Arg]); break; case (short)ILOpCodeValues.Ldarga_S: frame.Stack.Push(frame.Args[(byte)(int)frame.Current.Arg]); break; case unchecked ((short)ILOpCodeValues.Ldarga): frame.Stack.Push(frame.Args[(int)frame.Current.Arg]); break; case unchecked ((short)ILOpCodeValues.Starg): frame.Args[(int)frame.Current.Arg] = frame.Stack.Pop(); break; case unchecked ((short)ILOpCodeValues.Starg_S): frame.Args[(byte)(int)frame.Current.Arg] = frame.Stack.Pop(); break; case (short)ILOpCodeValues.Ldc_I4: frame.Stack.Push((int)frame.Current.Arg); break; case (short)ILOpCodeValues.Ldc_I4_0: frame.Stack.Push(0); break; case (short)ILOpCodeValues.Ldc_I4_1: frame.Stack.Push(1); break; case (short)ILOpCodeValues.Ldc_I4_2: frame.Stack.Push(2); break; case (short)ILOpCodeValues.Ldc_I4_3: frame.Stack.Push(3); break; case (short)ILOpCodeValues.Ldc_I4_4: frame.Stack.Push(4); break; case (short)ILOpCodeValues.Ldc_I4_5: frame.Stack.Push(5); break; case (short)ILOpCodeValues.Ldc_I4_6: frame.Stack.Push(6); break; case (short)ILOpCodeValues.Ldc_I4_7: frame.Stack.Push(7); break; case (short)ILOpCodeValues.Ldc_I4_8: frame.Stack.Push(8); break; case (short)ILOpCodeValues.Ldc_I4_S: frame.Stack.Push(Convert.ToInt32(frame.Current.Arg)); break; case (short)ILOpCodeValues.Ldc_I4_M1: frame.Stack.Push(-1); break; case (short)ILOpCodeValues.Ldc_I8: frame.Stack.Push(Convert.ToInt64(frame.Current.Arg)); break; case (short)ILOpCodeValues.Ldc_R4: frame.Stack.Push(Convert.ToSingle(frame.Current.Arg)); break; case (short)ILOpCodeValues.Ldc_R8: frame.Stack.Push(Convert.ToDouble(frame.Current.Arg)); break; case (short)ILOpCodeValues.Box: // 140: //box frame.Stack.Push(((object)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Ckfinite: // 195: //ckfinite var ckval = frame.Stack.Pop(); frame.Stack.Push((ckval is float?float.IsInfinity((float)ckval) : double.IsInfinity((double)ckval))); break; case (short)ILOpCodeValues.Conv_I: // 103: //conv.i1 frame.Stack.Push(unchecked ((int)Convert.ToInt64(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U: // 103: //conv.i1 frame.Stack.Push(unchecked ((uint)Convert.ToUInt64(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I1: // 103: //conv.i1 frame.Stack.Push(unchecked (Convert.ToSByte(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I2: //104: //conv.i2 frame.Stack.Push(unchecked (Convert.ToInt16(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I4: //105: //conv.i4 frame.Stack.Push(unchecked (Convert.ToInt32(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_I8: //106: //conv.i8 frame.Stack.Push(unchecked (Convert.ToInt64(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_Ovf_I1: //179: //conv.ovf.i1 frame.Stack.Push(Convert.ToSByte(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I1_Un: //130: //conv.ovf.i1.un frame.Stack.Push(Convert.ToSByte(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I2: //181: //conv.ovf.i2 frame.Stack.Push(Convert.ToInt16(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I2_Un: //131: //conv.ovf.i2.un frame.Stack.Push(Convert.ToInt16(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I4: //183: //conv.ovf.i4 frame.Stack.Push(Convert.ToInt32(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I4_Un: //132: //conv.ovf.i4.un frame.Stack.Push(Convert.ToInt32(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I8: //185: //conv.ovf.i8 frame.Stack.Push(Convert.ToInt64(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_I8_Un: //133: //conv.ovf.i8.un frame.Stack.Push(Convert.ToInt64(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U1: //180: //conv.ovf.u1 frame.Stack.Push(Convert.ToByte(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U1_Un: //134: //conv.ovf.u1.un frame.Stack.Push(Convert.ToByte(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U2: //182: //conv.ovf.u2 frame.Stack.Push(Convert.ToUInt16(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U2_Un: //135: //conv.ovf.u2.un frame.Stack.Push(Convert.ToUInt16(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U4: //184: //conv.ovf.u4 frame.Stack.Push(Convert.ToUInt32(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U4_Un: //136: //conv.ovf.u4.un frame.Stack.Push(Convert.ToUInt32(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U8: //186: //conv.ovf.u8 frame.Stack.Push(Convert.ToUInt64(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_Ovf_U8_Un: //137: //conv.ovf.u8.un frame.Stack.Push(Convert.ToUInt64(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_R4: //107: //conv.r4 frame.Stack.Push(Convert.ToSingle(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_R8: //108: //conv.r8 frame.Stack.Push(Convert.ToDouble(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_R_Un: //118: //conv.r.un frame.Stack.Push(Convert.ToSingle(frame.Stack.Pop())); break; case (short)ILOpCodeValues.Conv_U1: //210: //conv.u1 frame.Stack.Push(unchecked (Convert.ToByte(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U2: //209: //conv.u2 frame.Stack.Push(unchecked (Convert.ToUInt16(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U4: //109: //conv.u4 frame.Stack.Push(unchecked (Convert.ToUInt32(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Conv_U8: //110: //conv.u8 frame.Stack.Push(unchecked (Convert.ToUInt64(frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Neg: //101: //neg frame.Stack.Push(-((dynamic)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Newarr: //141: //newarr frame.Stack.Push(Array.CreateInstance(((frame.Current.Arg is int) ? frame.ResolveTypeToken((int)frame.Current.Arg) : (Type)frame.Current.Arg), (int)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Not: //102: //not frame.Stack.Push(!((dynamic)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Pop: //38: //pop frame.Stack.Pop(); // no push break; case (short)ILOpCodeValues.Shl: //98: //shl frame.Stack.Push(((dynamic)frame.Stack.Pop()) << ((int)frame.Current.Arg)); break; case (short)ILOpCodeValues.Shr: //99: //shr frame.Stack.Push(((dynamic)frame.Stack.Pop()) >> ((int)frame.Current.Arg)); break; case (short)ILOpCodeValues.Shr_Un: //100: //shr.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) >> ((int)frame.Current.Arg)); break; case (short)ILOpCodeValues.Unbox: //121: //unbox frame.Stack.Push(Convert.ChangeType(frame.Stack.Pop(), frame.ResolveTypeToken((int)frame.Current.Arg))); break; case (short)ILOpCodeValues.Unbox_Any: //165: //unbox.any frame.Stack.Push(Convert.ChangeType(frame.Stack.Pop(), frame.ResolveTypeToken((int)frame.Current.Arg))); break; case (short)ILOpCodeValues.Add: //: //add frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop()))); break; case (short)ILOpCodeValues.Add_Ovf: // 214: //add.ovf frame.Stack.Push(((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Add_Ovf_Un: // 215: //add.ovf.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop())); break; case (short)ILOpCodeValues.And: //95: //and frame.Stack.Push(((dynamic)frame.Stack.Pop()) & ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Ceq): //: //ceq { var opa = frame.Stack.Pop(); var opb = frame.Stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); frame.Stack.Push(compc == 0 ? 1 : 0); } else { frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } } break; case unchecked ((short)ILOpCodeValues.Cgt): // -510: //cgt frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) < ((dynamic)frame.Stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Cgt_Un) - 509: //cgt.un frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) < ((dynamic)frame.Stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Clt): // -508: //clt frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) > ((dynamic)frame.Stack.Pop()))); //either swap pop order or sign break; case unchecked ((short)ILOpCodeValues.Clt_Un): // -507: //clt.un frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) > ((dynamic)frame.Stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Div): // 91: //div frame.Stack.Push(((dynamic)frame.Stack.Pop()) / ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Div_Un): // 92: //div.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) / ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Mul): // 90: //mul frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Mul_Ovf): // 216: //mul.ovf frame.Stack.Push(((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Mul_Ovf_Un): // 217: //mul.ovf.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Or): // 96: //or frame.Stack.Push(((dynamic)frame.Stack.Pop()) | ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Rem): // 93: //rem frame.Stack.Push(((dynamic)frame.Stack.Pop()) % ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Rem_Un): // 94: //rem.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) % ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Sub): // 89: //sub frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop()))); break; case unchecked ((short)ILOpCodeValues.Sub_Ovf): // 218: //sub.ovf frame.Stack.Push(((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Sub_Ovf_Un): // 219: //sub.ovf.un frame.Stack.Push(((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop())); break; case unchecked ((short)ILOpCodeValues.Xor): // 97: //xor frame.Stack.Push(((dynamic)frame.Stack.Pop()) ^ ((dynamic)frame.Stack.Pop())); break; case (short)ILOpCodeValues.Ldstr: { if (frame.Current.Arg is string) { frame.Stack.Push((string)frame.Current.Arg); } else { frame.Stack.Push(frame.ResolveStringToken((int)frame.Current.Arg)); } break; } case (short)ILOpCodeValues.Newobj: { var ctor = (System.Reflection.ConstructorInfo)frame.ResolveMethodToken((int)frame.Current.Arg); var ctorArgs = new object[ctor.GetParameters().Length]; for (var i = ctorArgs.Length - 1; i > -1; i--) { ctorArgs[i] = frame.Stack.Pop(); } //var reversed = ctorArgs.Reverse().ToArray(); var ctorResult = ctor.Invoke(ctorArgs); frame.Stack.Push(ctorResult); break; } case (short)ILOpCodeValues.Ldfld: { var field = frame.ResolveFieldToken((int)frame.Current.Arg); var target = frame.Stack.Pop(); var value = field.GetValue(target); frame.Stack.Push(value); break; } case (short)ILOpCodeValues.Ldsfld: { var field = frame.ResolveFieldToken((int)frame.Current.Arg); var value = field.GetValue(null); frame.Stack.Push(value); break; } case (short)ILOpCodeValues.Stfld: { var field = frame.ResolveFieldToken((int)frame.Current.Arg); var fo = frame.Stack.Pop(); var target = frame.Stack.Pop(); field.SetValue(target, fo); //frame.Stack.Push(value); break; } case (short)ILOpCodeValues.Stsfld: { var field = frame.ResolveFieldToken((int)frame.Current.Arg); var fo = frame.Stack.Pop(); //var target = frame.Stack.Pop(); field.SetValue(null, fo); break; } case (short)ILOpCodeValues.Ldlen: { var array = frame.Stack.Pop(); var arr = (Array)array; frame.Stack.Push(arr.Length); break; } case (short)ILOpCodeValues.Stelem: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); array.GetType() .GetMethod("SetValue", new[] { typeof(object), typeof(int) }) .Invoke(array, new object[] { el, index }); break; } case (short)ILOpCodeValues.Stelem_I1: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(sbyte)) { ((sbyte[])array)[index] = (sbyte)(int)el; } else { ((byte[])array)[index] = (byte)(int)el; } break; } case (short)ILOpCodeValues.Stelem_I2: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(short)) { ((Array)array).SetValue((short)(int)el, index); } else if (arrElType == typeof(short)) { ((Array)array).SetValue((ushort)(int)el, index); } else { ((Array)array).SetValue(Convert.ChangeType(el, arrElType), index); } break; } case (short)ILOpCodeValues.Stelem_I4: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(int)) { ((int[])array)[index] = (int)el; } else { ((uint[])array)[index] = (uint)el; } break; } case (short)ILOpCodeValues.Stelem_I8: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(long)) { ((long[])array)[index] = (long)el; } else { ((ulong[])array)[index] = (ulong)el; } break; } case (short)ILOpCodeValues.Stelem_R4: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(float)) { ((float[])array)[index] = (float)el; } //else ((ulong[])array)[index] = (ulong)el; break; } case (short)ILOpCodeValues.Stelem_R8: { object el = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); var arrType = array.GetType(); var arrElType = arrType.GetElementType(); var elType = el.GetType(); if (elType == arrElType) { ((Array)array).SetValue(el, index); } else if (arrElType == typeof(double)) { ((double[])array)[index] = (double)el; } //else ((ulong[])array)[index] = (ulong)el; break; } case (short)ILOpCodeValues.Stelem_Ref: { object val = frame.Stack.Pop(); int index = (int)frame.Stack.Pop(); var array = frame.Stack.Pop(); ((Array)array).SetValue(val, index); break; } case (short)ILOpCodeValues.Ldelem: case (short)ILOpCodeValues.Ldelema: case (short)ILOpCodeValues.Ldelem_I: case (short)ILOpCodeValues.Ldelem_Ref: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); frame.Stack.Push(val); break; } case (short)ILOpCodeValues.Ldelem_I1: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = (sbyte)Convert.ToInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I2: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = (short)Convert.ToInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I4: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_I8: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToInt64(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U1: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = (byte)Convert.ToUInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U2: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = (ushort)Convert.ToUInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_U4: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToUInt32(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_R4: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToSingle(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Ldelem_R8: { var idx = (int)frame.Stack.Pop(); var array = (Array)frame.Stack.Pop(); var val = array.GetValue(idx); var target = Convert.ToDouble(val); frame.Stack.Push(target); break; } case (short)ILOpCodeValues.Conv_Ovf_I_Un: case (short)ILOpCodeValues.Conv_Ovf_I: //Todo: native int operations throw new NotImplementedException(); case (short)ILOpCodeValues.Dup: frame.Stack.Push(frame.Stack.Peek()); break; //TODO: Implemented scopre validation for branch: (EG, inside try, catch, finally,etc) case (short)ILOpCodeValues.Leave_S: case (short)ILOpCodeValues.Br_S: //0x2b: { var delta = (int)(sbyte)Convert.ToByte(frame.Current.Arg); var directpos = (int)frame.Stream[frame.Position + 1].ByteIndex + delta; frame.Position = frame.JumpTable[directpos]; goto MoveNext; } case (short)ILOpCodeValues.Leave: case (short)ILOpCodeValues.Br: // 0x38: { var delta = Convert.ToInt32(frame.Current.Arg); var directpos = (int)frame.Stream[frame.Position + 1].ByteIndex + delta; frame.Position = frame.JumpTable[directpos]; goto MoveNext; } case (short)ILOpCodeValues.Beq: { var opa = frame.Stack.Pop(); var opb = frame.Stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); frame.Stack.Push(compc == 0 ? 1 : 0); } else { frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } goto case (short)ILOpCodeValues.Brtrue; } case (short)ILOpCodeValues.Beq_S: { var opa = frame.Stack.Pop(); var opb = frame.Stack.Pop(); if (opa is IConvertible && opb is IConvertible) { var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa))); frame.Stack.Push(compc == 0 ? 1 : 0); } else { frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb))); } goto case (short)ILOpCodeValues.Brtrue_S; } case (short)ILOpCodeValues.Brfalse: //00111001 { var chk = frame.Stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 0) { condtarget = (int)frame.Stream[frame.Position + 1].ByteIndex + Convert.ToInt32(frame.Current.Arg); frame.Position = frame.JumpTable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brfalse_S: { var chk = frame.Stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 0) { condtarget = (int)frame.Stream[frame.Position + 1].ByteIndex + (int)(sbyte)Convert.ToByte(frame.Current.Arg); frame.Position = frame.JumpTable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brtrue: { var chk = frame.Stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 1) { condtarget = (int)frame.Stream[frame.Position + 1].ByteIndex + Convert.ToInt32(frame.Current.Arg); frame.Position = frame.JumpTable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Brtrue_S: { var chk = frame.Stack.Pop(); int cond = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null))); var condtarget = -1; if (cond == 1) { condtarget = (int)frame.Stream[frame.Position + 1].ByteIndex + (int)(sbyte)Convert.ToByte(frame.Current.Arg); frame.Position = frame.JumpTable[condtarget]; goto MoveNext; } break; } case (short)ILOpCodeValues.Call: case (short)ILOpCodeValues.Callvirt: System.Reflection.MethodBase method = null; object resolved = null; if (frame.Current.Arg is System.Reflection.MethodInfo) { method = (System.Reflection.MethodInfo)frame.Current.Arg; } else { resolved = frame.ResolveMethodToken((int)frame.Current.Arg); } if (resolved is ConstructorInfo) { method = (ConstructorInfo)resolved; } else { method = (System.Reflection.MethodInfo)resolved; } var parameters = method.GetParameters(); var methodArgs = new object[parameters.Length]; for (var i = methodArgs.Length - 1; i >= 0; i--) { var val = frame.Stack.Pop(); if (val is ILVariable) { methodArgs[i] = ((ILVariable)(val)).Value; } else { methodArgs[i] = val; } } object methodTarget = null; if (!method.IsStatic) { methodTarget = frame.Stack.Pop(); } if (methodTarget is ILVariable) { methodTarget = ((ILVariable)methodTarget).Value; } //var t = default(RuntimeTypeHandle); //var t1 = default(ArgIterator); //var tobject = new object[] { t, t }; //var del = Delegate.CreateDelegate() //((ConstructorInfo)method).Invoke( new object[]{ t}); for (var i = methodArgs.Length - 1; i >= 0; i--) { if (methodArgs[i] is IConvertible) { methodArgs[i] = Convert.ChangeType(methodArgs[i], parameters[i].ParameterType); } } //if the current method is invoking another method then convert the arguments for the inner method. if (methodTarget is MethodBase && methodArgs.Length == 2 && methodArgs[1] is Array) { var invokeArgs = (Array)methodArgs[1]; var invokeParameters = ((MethodInfo)methodTarget).GetParameters(); for (var i = invokeArgs.Length - 1; i >= 0; i--) { var arg = invokeArgs.GetValue(i); if (arg is IConvertible) { invokeArgs.SetValue(Convert.ChangeType(arg, invokeParameters[i].ParameterType), i); } } //if (invokeArgs.GetValue(i) is IConvertible) // invokeArgs.SetValue(Convert.ChangeType(invokeArgs[i], invokeParameters[i].ParameterType)); } // Roadblock here: Int.CompareTo(object value) -> argument value must be of type int but there is no way to programatically determine the expected destination type. var methodresult = (method is MethodInfo) ? method.Invoke(methodTarget, methodArgs) : ((ConstructorInfo)method).Invoke(methodArgs); if (frame.Code.StackBehaviourPush == StackBehaviour.Varpush) { if ((method as MethodInfo)?.ReturnType != typeof(void) || method.IsConstructor) { frame.Stack.Push(methodresult); } } break; case (short)ILOpCodeValues.Ldnull: frame.Stack.Push(null); break; case unchecked ((short)ILOpCodeValues.Ldftn): var ftnToken = (int)frame.Current.Arg; var ftnMethod = frame.ResolveMethodToken(ftnToken); frame.Stack.Push(ftnMethod.MethodHandle.GetFunctionPointer()); break; case unchecked ((short)ILOpCodeValues.Initobj): var newObj = Activator.CreateInstance(frame.ResolveTypeToken((int)frame.Current.Arg)); var inst = frame.Stack.Pop(); if (inst is ILVariable ilvar) { ilvar.Value = newObj; frame.Locals[ilvar.Index] = ilvar; } else { inst = newObj; } break; case (short)ILOpCodeValues.Ldtoken: var metaToken = (int)frame.Current.Arg; var memToken = frame.ResolveMemberToken(metaToken); var tokenType = memToken.GetType(); switch (tokenType.Name) { case "RtFieldInfo": { var fieldInfo = frame.ResolveFieldToken(metaToken); var handle = (FieldInfo)fieldInfo; frame.Stack.Push(handle.FieldHandle); } break; case "RuntimeType": { var type = frame.ResolveTypeToken(metaToken); var handle = (Type)type; frame.Stack.Push(handle.TypeHandle); } break; default: frame.Exception = new NotImplementedException($"{nameof(OpCode)} {frame.Code} token {tokenType.Name}"); goto Ret; //throw new NotImplementedException(); } break; case (short)ILOpCodeValues.Castclass: var targetClassToken = (int)frame.Current.Arg; var targetType = frame.ResolveTypeToken(targetClassToken); var listType = typeof(List <>).MakeGenericType(new[] { targetType }); var instance = Activator.CreateInstance(listType); var prop = listType.GetProperty("Item"); var src = frame.Stack.Pop(); var add = listType.GetMethod("Add"); add.Invoke(instance, new[] { src }); var get = listType.GetMethod("get_Item"); var listresult = get.Invoke(instance, new object[] { 0 }); frame.Stack.Push(listresult); break; case (short)ILOpCodeValues.Break: if (frame.TriggerBreak) { System.Diagnostics.Debugger.Break(); } break; default: frame.Exception = new NotImplementedException($"{nameof(OpCode)} {frame.Code} is not implemented"); goto Ret; } Inc: frame.Inc(); MoveNext: if (frame.MoveNext()) { goto ReadNext; } Ret: frame.ReturnResult = (frame.Stack.Count > 0 && frame.Exception == null) ? frame.Stack.Pop() : null; }
/* END Added for PS 3.0 */ /// <summary> /// Method invoked at build time to initialize the instance fields of the current aspect. This method is invoked before any other build-time method. /// </summary> /// <param name="method">Method to which the current aspect is applied</param> /// <param name="aspectInfo">Reserved for future usage.</param> public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { this.methodName = method.Name; this.parameters = method.GetParameters(); }