public override int GetNumberOfStackPops(MethodBase aMethod) { switch (OpCode) { case Code.Initobj: return 1; case Code.Ldelema: return 2; case Code.Newarr: return 1; case Code.Box: return 1; case Code.Stelem: return 3; case Code.Ldelem: return 2; case Code.Isinst: return 1; case Code.Castclass: return 1; case Code.Constrained: return 0; case Code.Unbox_Any: return 1; case Code.Unbox: return 1; case Code.Stobj: return 2; case Code.Ldobj: return 1; default: throw new NotImplementedException("OpCode '" + OpCode + "' not implemented! Encountered in method " + aMethod.ToString()); } }
protected static void stackInfo(ref string _filename, ref string _objectName, ref string _methodName, ref int _lineNumber) { string filename = string.Empty; string objectName = "Unknown"; string methodName = "Unknown"; int lineNumber = 0; StackFrame sf = new StackFrame(3, true); try { if (sf != null) { System.Reflection.MethodBase method = sf.GetMethod(); if (method != null) { if (method.ReflectedType != null) { objectName = method.ReflectedType.ToString(); } else { objectName = "Global"; } methodName = method.ToString(); } int space = methodName.IndexOf(" "); space++; methodName = methodName.Substring(space, methodName.Length - space); filename = sf.GetFileName(); if (filename != null) { int lastSlash = filename.LastIndexOf(@"\"); lastSlash++; filename = filename.Substring(lastSlash, filename.Length - lastSlash); } lineNumber = sf.GetFileLineNumber(); } } catch { } _filename = filename; _objectName = objectName; _methodName = methodName; _lineNumber = lineNumber; }
private static string GetMethodName(System.Reflection.MethodBase method) { var type = method.ReflectedType; if (type != null) { return(type.Name); } else { return(method.ToString()); } }
public static LateBoundMethod CreateMethod(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); ParameterInfo[] args = method.GetParameters(); Label argsOk = generator.DefineLabel(); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldlen); generator.Emit(OpCodes.Ldc_I4, args.Length); generator.Emit(OpCodes.Beq, argsOk); generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Throw); generator.MarkLabel(argsOk); if (!method.IsConstructor && !method.IsStatic) generator.PushInstance(method.DeclaringType); for (int i = 0; i < args.Length; i++) { generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Ldelem_Ref); generator.UnboxIfNeeded(args[i].ParameterType); } if (method.IsConstructor) generator.Emit(OpCodes.Newobj, (ConstructorInfo)method); else if (method.IsFinal || !method.IsVirtual) generator.CallMethod((MethodInfo)method); Type returnType = method.IsConstructor ? method.DeclaringType : ((MethodInfo)method).ReturnType; if (returnType != typeof(void)) generator.BoxIfNeeded(returnType); else generator.Emit(OpCodes.Ldnull); generator.Return(); return (LateBoundMethod)dynamicMethod.CreateDelegate(typeof(LateBoundMethod)); }
private static string GetLogSourceInfo(int skipFrames) { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(skipFrames, true); if (stackFrame == null) { return(""); } string fileName = stackFrame.GetFileName(); fileName = (fileName == null) ? "UnknownFile" : fileName.Substring(fileName.LastIndexOf('/') + 1); int lineNumber = stackFrame.GetFileLineNumber(); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); string methodName = (methodBase == null) ? "UnknownMethod" : methodBase.ToString(); return(fileName + "(" + lineNumber + "): " + methodName); }
// calculate signature so that is is compatible with CORE public static String fixDotNetSignature(MethodBase mbMethodBase, String sReturnParameter) { try { // internal dotnet method that already has all paramters calculated // String sMethodSignature = (String)reflection.invokeMethod_InstanceStaticPublicNonPublic(mbMethodBase, "ConstructName", new object[] { mbMethodBase }); var sMethodSignature = (String) DI.reflection.invokeMethod_Static("System.Reflection.RuntimeMethodInfo", "ConstructName", new object[] { mbMethodBase }); if (sMethodSignature == null) { DI.log.error("in fixDotNetSignature could not resolve method signature for :{0}", mbMethodBase.ToString()); sMethodSignature = "(COULD NOT RESOLVE SIGNATURE): " + mbMethodBase; } sMethodSignature = sMethodSignature.Replace(", ", ";"); String sClass = mbMethodBase.ReflectedType.FullName; String sFullSignature = String.Format("{0}.{1}:{2}", sClass, sMethodSignature, sReturnParameter); // specific method fixes: sFullSignature = sFullSignature.Replace("System.String", "string"); sFullSignature = sFullSignature.Replace("System.Object", "object"); sFullSignature = sFullSignature.Replace("Int16", "short"); sFullSignature = sFullSignature.Replace("Int32", "int"); sFullSignature = sFullSignature.Replace("Int64", "long"); sFullSignature = sFullSignature.Replace("Boolean", "bool"); sFullSignature = sFullSignature.Replace("Double", "double"); sFullSignature = sFullSignature.Replace("Void", "void"); sFullSignature = sFullSignature.Replace(" ByRef", ""); // this doesn't seem to be included in the CIR signature return sFullSignature; } catch (Exception ex) { DI.log.error("In fixDotNetSignature:{0}", ex.Message); return ""; } }
public bool Matches(MethodBase member) { var interfacetypes = member.DeclaringType.GetInterfaces(); foreach (var interfacetype in interfacetypes) { var method = interfacetype.GetMethod(member.Name); if (method.ToString() == member.ToString()) { foreach (CachingAttribute attribute in ReflectionHelper.GetAllAttributes<CachingAttribute>(method, true)) { if (attribute.CachingEnable) return true; } } } foreach (CachingAttribute attribute in ReflectionHelper.GetAllAttributes<CachingAttribute>(member, true)) { if (attribute.CachingEnable) return true; } return false; }
public DisassembledMethod Disassemble(MethodBase method) { Contract.Requires(method != null); Contract.Requires(CanDisassemble(method)); var methodBody = method.GetMethodBody(); if (methodBody == null) { throw new NotSupportedException(method.DeclaringType +" {" + method.ToString() + "} "+ method.GetMethodImplementationFlags() ); } Contract.Assert(methodBody!=null); // ReSharper disable PossibleNullReferenceException var ilBytes = methodBody.GetILAsByteArray(); // ReSharper restore PossibleNullReferenceException Type returnType = method is MethodInfo ? (method as MethodInfo).ReturnType : typeof (void); var handlingClauses = methodBody.ExceptionHandlingClauses; Type[] genericParameters = null; if (method.IsGenericMethod) { genericParameters = method.GetGenericArguments(); } return new DisassembledMethod( ilBytes, Scan(ilBytes, handlingClauses), new ModuleMetadataResolver(method.Module), handlingClauses, methodBody.LocalVariables, returnType, method.GetParameters(), method.IsGenericMethodDefinition , genericParameters ); }
/// <summary> /// TODO: Resolve IsPublic, IsNotPublic semantics of reflection /// </summary> /// <param name="ci"></param> /// <returns></returns> private bool OkToUseBase(MethodBase ci, out string message) { if (ci.IsAbstract) { message = "Will not use: method or constructor is abstract: " + ci.ToString(); return false; } foreach (ParameterInfo pi in ci.GetParameters()) { if (pi.ParameterType.Name.EndsWith("&")) { message = "Will not use: method or constructor has a parameter containing \"&\": " + ci.ToString(); return false; } if (pi.IsOut) { message = "Will not use: method or constructor has an out parameter: " + ci.ToString(); return false; } if (pi.ParameterType.IsGenericParameter) { message = "Will not use: method or constructor has a generic parameter: " + ci.ToString(); return false; } } if (!this.useInternal && !ci.IsPublic) { message = "Will not use: method or constructor is not public: " + ci.ToString(); return false; } if (ci.IsPrivate) { message = "Will not use: method or constructor is private: " + ci.ToString(); return false; } if (ci.IsStatic) { if (!useStaticMethods) { message = "Will not use: method or constructor is static: " + ci.ToString(); return false; } } if (ci.DeclaringType.Equals(typeof(object))) { message = "Will not use: method is System.Object's: " + ci.ToString(); return false; } foreach (Attribute attr in ci.GetCustomAttributes(true)) { if (attr is ObsoleteAttribute) { //WriteLine("Obsolete Method " + ci.DeclaringType + "::" + ci.Name + "()" + "detected\n"); message = "Will not use: has attribute System.ObsoleteAttribute: " + ci.ToString(); return false; } //TODO: there are still cases where an obsolete method is not caught. e.g. System.Xml.XmlSchema::ElementType } message = "@@@OK8" + ci.ToString(); return true; }
/// <summary> /// Returns a string that can be used for representing a method or constructor in log entries. /// </summary> /// <param name="info"></param> /// <param name="includeDeclaringType">If true, the methods or constructors declaring type is included in the returned name.</param> /// <returns></returns> public static string MethodInfo(MethodBase info, bool includeDeclaringType = true) { if (info is MethodInfo) return MethodInfo(info as MethodInfo); else if (info is ConstructorInfo) return ConstructorInfo(info as ConstructorInfo); else if (info != null) return info.ToString(); else return "null"; }
public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder) { throw new ArgumentException("Method " + callee.ToString() + " was assumed not to be called at runtime. " + "However, a call to this method was found in " + decompilee.Method.ToString()); }
/// <summary> /// Method called at compile-time by the weaver just before the instance is serialized. /// </summary> /// <param name="method">Method on which this instance is applied.</param> /// <remarks> /// <para>Derived classes should implement this method if they want to compute some information /// at compile time. This information to be stored in member variables. It shall be /// serialized at compile time and deserialized at runtime. /// </para> /// <para> /// You cannot store and serialize the <paramref name="method"/> parameter because it is basically /// a runtime object. You shall receive the <see cref="MethodBase"/> at runtime by the /// <see cref="RuntimeInitialize"/> function. /// </para> /// </remarks> public override bool CompileTimeValidate( MethodBase method ) { bool hasError = false; // Cannot be a constructor. MethodInfo methodInfo = method as MethodInfo; if ( methodInfo == null ) { DbInvokeMessageSource.Instance.Write( SeverityType.Error, "DBI0001", new object[] {method.DeclaringType.FullName} ); return false; } // Should have void return type. if ( methodInfo.ReturnType != typeof(void) ) { DbInvokeMessageSource.Instance.Write( SeverityType.Error, "DBI0002", new object[] {method.ToString()} ); hasError = true; } // All parameters should be mappable. foreach ( ParameterInfo parameter in methodInfo.GetParameters() ) { Type parameterType = parameter.ParameterType; if ( parameterType.IsByRef ) parameterType = parameterType.GetElementType(); if ( DbTypeMapping.GetPreferredMapping( parameterType ) == null ) { DbInvokeMessageSource.Instance.Write( SeverityType.Error, "DBI0003", new object[] { method.ToString(), parameter.ParameterType.FullName, parameter.Name } ); hasError = true; } } return !hasError; }
private static string GetCacheKeyByMethodAndParams(MethodBase persistedMethod, params object[] methodParams) { return GetCacheKey(new object[] { persistedMethod.DeclaringType.ToString(), persistedMethod.ToString(), GetCacheKey(methodParams) }); }
/// <summary> /// Returns the method reference which refers specified method. /// </summary> /// <param name="method">The method to refer.</param> /// <returns>The method reference which refers specified method.</returns> public static MethodRef Serialize(MethodBase method) { return _reverseCache.GetValue(method) ?? new MethodRef( TypeRef.Serialize(method.ReflectedType), method.Name != ".ctor" ? method.Name : null, method.ToString(), method.IsGenericMethod && !method.IsGenericMethodDefinition ? method.GetGenericArguments().SelectAll(TypeRef.Serialize) : null ).Apply(m => _reverseCache.Add(method, m)); }
public void Debug(string sText, MethodBase method = null) { Flush(LogLevel.DEBUG, method == null ? sText : method.ToString() + ":" + sText); }
internal static string Describe(MethodBase methodBase) { return "{0} {1}{2} {3}".FormatInvariant( Describe(methodBase.ReflectedType), DescribeVisibility(methodBase), methodBase.IsStatic ? " static" : String.Empty, methodBase.ToString() ); }
public static MethodBodyInfo Create(MethodBase method) { MethodBodyInfo mbi = new MethodBodyInfo(); mbi.Identity = method.GetHashCode(); mbi.TypeName = method.GetType().Name; mbi.MethodToString = method.ToString(); ReadableILStringVisitor readableIlStringVisitor = new ReadableILStringVisitor((IILStringCollector) new MethodBodyInfo.MethodBodyInfoBuilder(mbi), (IFormatProvider) DefaultFormatProvider.Instance); new ILReader(method).Accept((ILInstructionVisitor) readableIlStringVisitor); return mbi; }
public static string GenerateFullName(MethodBase aMethod) { if (aMethod == null) { throw new ArgumentNullException("aMethod"); } var xBuilder = new StringBuilder(256); var xParts = aMethod.ToString().Split(' '); var xParts2 = xParts.Skip(1).ToArray(); var xMethodInfo = aMethod as System.Reflection.MethodInfo; if (xMethodInfo != null) { xBuilder.Append(GetFullName(xMethodInfo.ReturnType)); } else { var xCtor = aMethod as ConstructorInfo; if (xCtor != null) { xBuilder.Append(typeof(void).FullName); } else { xBuilder.Append(xParts[0]); } } xBuilder.Append(" "); if (aMethod.DeclaringType != null) { xBuilder.Append(GetFullName(aMethod.DeclaringType)); } else { xBuilder.Append("dynamic_method"); } xBuilder.Append("."); xBuilder.Append(aMethod.Name); if (aMethod.IsGenericMethod || aMethod.IsGenericMethodDefinition) { var xGenArgs = aMethod.GetGenericArguments(); if (xGenArgs.Length > 0) { xBuilder.Append("<"); for (int i = 0; i < xGenArgs.Length - 1; i++) { xBuilder.Append(GetFullName(xGenArgs[i])); xBuilder.Append(", "); } xBuilder.Append(GetFullName(xGenArgs.Last())); xBuilder.Append(">"); } } xBuilder.Append("("); var xParams = aMethod.GetParameters(); for (var i = 0; i < xParams.Length; i++) { if (i == 0 && xParams[i].Name == "aThis") { continue; } xBuilder.Append(GetFullName(xParams[i].ParameterType)); if (i < (xParams.Length - 1)) { xBuilder.Append(", "); } } xBuilder.Append(")"); return String.Intern(xBuilder.ToString()); }
public MethodData (MethodBase mi, int il_size) { this.Type = mi.DeclaringType.ToString (); this.MethodName = mi.ToString (); this.MethodAttributes = (int) mi.Attributes; this.ILSize = il_size; }
private int DeobfString(MethodDefinition searchInMethod, MethodDefinition searchForMethod, MethodBase calledMethod, int fromIndex) { if (_options.IgnoredMethodFile.IsMatch(searchForMethod)) return 0; if (searchInMethod == null || !searchInMethod.HasBody) return 0; if (searchInMethod.MetadataToken == searchForMethod.MetadataToken) return 0; if (searchForMethod.ReturnType.FullName != "System.String" && searchForMethod.ReturnType.FullName != "System.Object") return 0; Mono.Cecil.Cil.MethodBody body = searchInMethod.Body; Collection<Instruction> instructions = body.Instructions; int deobfCount = 0; int errorCount = 0; for (int i = fromIndex; i < instructions.Count; i++) { Instruction ins = instructions[i]; if (ins.OpCode != OpCodes.Call) continue; MethodDefinition operand = Resolve(ins.Operand as MethodReference); if (operand == null) continue; if (operand.MetadataToken != searchForMethod.MetadataToken) continue; int startIndex; object[] p = SearchParameters(searchForMethod, i, searchInMethod, out startIndex); if (p == null) continue; #region invoke method object o; try { o = calledMethod.Invoke(null, p); } catch(Exception ex) { o = null; errorCount++; while (ex.InnerException != null) ex = ex.InnerException; string errMsg = String.Format("Error when calling 0x{0:x08} ({1}): {2}", calledMethod.MetadataToken, calledMethod.ToString(), ex.Message ); _options.AppendTextInfoLine(errMsg, true); } if (o != null) { if (searchForMethod.ReturnType.FullName != "System.String" && o.GetType().FullName != "System.String") continue; string oStr = (string)o; if (_options.IgnoredMethodFile.IgnoreMethodsReturnPath && (Directory.Exists(oStr) || File.Exists(oStr))) continue; ILProcessor ilp = searchInMethod.Body.GetILProcessor(); //int size = 0; for (int j = startIndex; j <= i; j++) { //size += instructions[i_1].GetSize(); //there is problem for remove operation, not consider br reference //ilp.Remove(instructions[i_1]);//the instruction move up, so always is startIndex //here we don't want to insert nop, otherwise index will be wrong InsUtils.ToNop(ilp, instructions, j, false); } //insert may break br reference //Instruction insertIns = ilp.Create(OpCodes.Ldstr, (string)o); //int insertSize = insertIns.GetSize(); //ilp.InsertBefore(instructions[i_1], insertIns); //set the last instruction so br reference is ok instructions[i].OpCode = OpCodes.Ldstr; instructions[i].Operand = oStr; deobfCount++; } if (errorCount > this.Options.IgnoredMethodFile.MaxCallError) { this.Options.IgnoredMethodFile.Ignore(searchForMethod.ToString()); break; } #endregion invoke method } if (deobfCount > 0) { InsUtils.ComputeOffsets(instructions); } return deobfCount; }
public int DeobfBoolFunction(MethodDefinition searchInMethod, MethodDefinition searchForMethod, MethodBase mb) { int count = 0; if (_options.IgnoredMethodFile.IsMatch(searchForMethod)) return count; if (searchInMethod == null || !searchInMethod.HasBody) return count; if (searchInMethod.MetadataToken == searchForMethod.MetadataToken) return count; if (searchForMethod.ReturnType.FullName != "System.Boolean") return count; if (searchForMethod.Parameters.Count != 0) return count; Mono.Cecil.Cil.MethodBody body = searchInMethod.Body; Collection<Instruction> instructions = body.Instructions; //bool hasDeobf = false; for (int i = 0; i < instructions.Count; i++) { Instruction ins = instructions[i]; if (ins.OpCode != OpCodes.Call) continue; MethodDefinition operand = ins.Operand as MethodDefinition; if (operand == null) continue; if (operand.MetadataToken != searchForMethod.MetadataToken) continue; #region invoke method object o; try { o = mb.Invoke(null, null); } catch(Exception ex) { o = null; _options.IgnoredMethodFile.Ignore(searchForMethod.ToString()); while (ex.InnerException != null) ex = ex.InnerException; string errMsg = String.Format("Error when calling 0x{0:x08} ({1}): {2}", mb.MetadataToken, mb.ToString(), ex.Message ); _options.AppendTextInfoLine(errMsg, true); } if (o != null) { if (Convert.ToBoolean(o)) { instructions[i].OpCode = OpCodes.Ldc_I4_1; } else { instructions[i].OpCode = OpCodes.Ldc_I4_0; } instructions[i].Operand = null; count++; //hasDeobf = true; } else { break; } #endregion invoke method } if (count > 0) { InsUtils.ComputeOffsets(instructions); } return count; }
public static string Format(DateTime t, Object o, MethodBase m, String msg) { return "[" + t.ToString("HH:mm:ss") + "](" + o.GetHashCode() + "){ " + m.ToString() + " } >> " + msg; }
public void Warn(string sText, MethodBase method = null) { Flush(LogLevel.WARN, method == null ? sText : method.ToString() + ":" + sText); }
/// <summary>Gets the id for a method.</summary> /// <param name="methodBase">The method base.</param> /// <returns>A string unique to this method</returns> public static string GetId(MethodBase methodBase) { //return methodBase.GetHashCode().ToString(); return methodBase.Module.Name + ">" + methodBase.DeclaringType.FullName + ">" + methodBase.ToString(); }
/// <summary> /// Returns the signature for a method,property or ctor. /// </summary> /// <param name="method">a method,property or ctor</param> /// <returns>string based representation of the method signature</returns> public static string GetMethodSignature(MethodBase method) { return method.ToString(); }
bool CompareIL (MethodBase mi, PositiveTestCase test, PositiveChecker checker) { string m_name = mi.ToString (); string decl_type = mi.DeclaringType.ToString (); PositiveTestCase.VerificationData data_provider = test.VerificationProvider; PositiveTestCase.VerificationData.MethodData md = data_provider.FindMethodData (m_name, decl_type); if (md == null) { data_provider.AddNewMethod (mi, GetILSize (mi)); if (!data_provider.IsNewSet) { checker.HandleFailure (test.FileName, PositiveChecker.TestResult.ILError, decl_type + ": " + m_name + " (new method?)"); return false; } return true; } if (md.Checked) { checker.HandleFailure (test.FileName, PositiveChecker.TestResult.ILError, decl_type + ": " + m_name + " has a duplicate"); return false; } md.Checked = true; if (md.MethodAttributes != (int) mi.Attributes) { checker.HandleFailure (test.FileName, PositiveChecker.TestResult.MethodAttributesError, string.Format ("{0} ({1} -> {2})", decl_type + ": " + m_name, md.MethodAttributes, mi.Attributes)); } md.MethodAttributes = (int) mi.Attributes; int il_size = GetILSize (mi); if (md.ILSize == il_size) return true; if (md.ILSize > il_size) { checker.LogFileLine (test.FileName, "{0} (code size reduction {1} -> {2})", decl_type + ": " + m_name, md.ILSize, il_size); md.ILSize = il_size; return true; } checker.HandleFailure (test.FileName, PositiveChecker.TestResult.ILError, string.Format ("{0} (code size {1} -> {2})", decl_type + ": " + m_name, md.ILSize, il_size)); md.ILSize = il_size; return false; }
private static bool IsValidMethodBase(MethodBase method, string[] skipExpressions) { foreach (string expression in skipExpressions) { if (method.ReflectedType.ToString().IndexOf(expression) > -1 || method.ToString().IndexOf(expression) > -1) return false; } return true; }