void CheckParametersAndValues (IMetadataTokenProvider provider, IMethodSignature constructor, IList<CustomAttributeArgument> arguments) { for (int index = 0; index < arguments.Count; index++) { ParameterDefinition parameter = constructor.Parameters[index]; if (parameter.ParameterType.IsNamed ("System", "String")) { string value = (string) arguments [index].Value; if (Contains (parameter.Name, "version")) { Version v = null; if (!Version.TryParse (value, out v)) { string msg = String.Format (CultureInfo.InvariantCulture, "The value passed: {0} can't be parsed to a valid Version.", value); Runner.Report (provider, Severity.High, Confidence.High, msg); } continue; } if (Contains (parameter.Name, "url") || Contains (parameter.Name, "uri") || Contains (parameter.Name, "urn")) { Uri parsed = null; if (!Uri.TryCreate (value, UriKind.Absolute, out parsed)) { string msg = String.Format (CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Uri.", value); Runner.Report (provider, Severity.High, Confidence.High, msg); } continue; } if (Contains (parameter.Name, "guid")) { Guid g; if (!Guid.TryParse (value, out g)) { string msg = String.Format (CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Guid.", value); Runner.Report (provider, Severity.High, Confidence.High, msg); } continue; } } } }
/// <summary> /// Compare the IMethodSignature members with the one being specified. /// </summary> /// <param name="self">>The IMethodSignature on which the extension method can be called.</param> /// <param name="signature">The IMethodSignature which is being compared.</param> /// <returns>True if the IMethodSignature members are identical, false otherwise</returns> public static bool CompareSignature(this IMethodSignature self, IMethodSignature signature) { if (self == null) return (signature == null); if (self.HasThis != signature.HasThis) return false; if (self.ExplicitThis != signature.ExplicitThis) return false; if (self.CallingConvention != signature.CallingConvention) return false; if (!AreSameElementTypes(self.ReturnType, signature.ReturnType)) return false; bool h1 = self.HasParameters; bool h2 = signature.HasParameters; if (h1 != h2) return false; if (!h1 && !h2) return true; IList<ParameterDefinition> pdc1 = self.Parameters; IList<ParameterDefinition> pdc2 = signature.Parameters; int count = pdc1.Count; if (count != pdc2.Count) return false; for (int i = 0; i < count; ++i) { if (!AreSameElementTypes(pdc1[i].ParameterType, pdc2[i].ParameterType)) return false; } return true; }
private bool CheckReturnVoid (IMetadataTokenProvider eventType, IMethodSignature invoke) { string full_name = invoke.ReturnType.FullName; if (String.Compare (full_name, "System.Void") == 0) return true; string msg = String.Format ("The delegate should return void, not {0}", full_name); Runner.Report (eventType, Severity.Medium, Confidence.High, msg); return false; }
//TODO: Consider creating a class that will represent member signature private static void AppendMethodSignature(StringBuilder scope, IMethodSignature method) { scope.Append(method.HasThis ? 's' : 'i'); scope.Append(' '); scope.Append(method.CallingConvention.ToString()); scope.Append(' '); AppendTypeSignature(scope, method.ReturnType); scope.Append(' '); AppendParametersString(scope, method.Parameters); }
private void CheckParameters(IMethodSignature concat, MethodDefinition caller, Instruction ins) { // check for boxed (likely char, but could be other types too) on any parameter for (int i = 0; i < concat.Parameters.Count; i++) { Instruction source = ins.TraceBack(caller, -i); if ((source == null) || (source.OpCode.Code != Code.Box)) { continue; } ReportBoxing(caller, source, Confidence.High); } }
static bool ParametersMatch(IMethodSignature meth, string [] parameters) { for (int i = 0; i < parameters.Length; i++) { ParameterDefinition param = meth.Parameters [i]; if (param.ParameterType.FullName != parameters [i]) { return(false); } } return(true); }
private void EmitGetMethodReplacement(CilWorker IL, IMethodSignature hostMethod, VariableDefinition provider) { // var replacement = MethodReplacementProvider.GetReplacement(info); IL.Emit(OpCodes.Ldloc, provider); // Push the host instance var pushInstance = hostMethod.HasThis ? IL.Create(OpCodes.Ldarg_0) : IL.Create(OpCodes.Ldnull); IL.Append(pushInstance); IL.Emit(OpCodes.Ldloc, _invocationInfo); IL.Emit(OpCodes.Callvirt, _getReplacement); IL.Emit(OpCodes.Stloc, _replacement); }
private void CheckConstructor(IMethodSignature constructor) { //Skip enums, interfaces, <Module>, static classes ... //All stuff that doesn't contain a constructor if (constructor == null) { return; } if (HasMoreParametersThanAllowed(constructor)) { Runner.Report(constructor, Severity.Medium, Confidence.High, "This constructor contains a long parameter list."); } }
/// <summary> /// Joins the specified item. Want to take the Type from the item, but keep the Value /// from this object. Enables the correct data type for the signature, so replaces /// string for whatever type the actual values are. /// </summary> /// <param name="item">The item.</param> /// <returns>An object that supports the <see cref="IMethodSignature"/> interface.</returns> public IMethodSignature Join(IMethodSignature item) { var args = new List <IMethodArgument>(); for (var i = 0; i < item.Arguments.Count(); i++) { args.Add(new GenericParameter( MethodArgType.Parameter, item.Arguments.ElementAt(i).Type, this.Arguments.ElementAt(i).Value)); } return(new TestCaseSignature(args)); }
private ImportContext(Type targetType, Type importType, MemberInfo targetMemberInfo, IMethodSignature signature) { TargetMemberInfo = targetMemberInfo; ImportType = importType; TargetType = targetType; Signature = signature; _hash = HashCode.Start .Add(targetMemberInfo) .Add(importType) .Add(targetType) .Add(Signature) .Value; }
private bool CompareMethodParams(IMethodSignature targetMethod, IMethodSignature newMethod, IMetadataTokenProvider callbackInfoType) { // TODO ugly hack atm string targetMethodParams = string.Join(",", targetMethod.Parameters.Select(t => t.ParameterType.FullName).ToArray()); string patchMethodParams = string.Join(",", newMethod.Parameters .Where(t => t.CustomAttributes.All(a => a.AttributeType.FullName != typeof(CaptureLocal).FullName) && t.CustomAttributes.All(a => a.AttributeType.FullName != typeof(StoreLocal).FullName) && t.ParameterType != callbackInfoType) .Select(t => t.ParameterType.FullName) .ToArray()); return(patchMethodParams == targetMethodParams); }
/// <summary> /// Determine if two method signatures are equal /// </summary> /// <param name="imsRef">Reference method signature</param> /// <param name="imsDecl">Method declaration signature</param> /// <returns></returns> internal static bool MethodSignaturesAreEqual2(IMethodSignature imsRef, IMethodSignature imsDecl) { MethodBase refMI = imsRef.MethodInfo; MethodBase decMI = imsDecl.MethodInfo; if (refMI != null && refMI.Equals(decMI)) { return(true); } else { return(false); } }
/// <summary> /// Gets a <see cref="ParameterDefinition"/> by name and optionally either returns null or throws /// an <see cref="InvalidOperationException"/> if no method definition with the specified name is found. /// </summary> /// <param name="signature">The <see cref="IMethodSignature"/> to get the parameter definition from.</param> /// <param name="name">The name of the parameter. This is case-sensitive.</param> /// <param name="throwIfNoneFound"> /// Whether to throw an <see cref="InvalidOperationException"/> /// if no parameter definition with the specified name is found. /// </param> /// <returns> /// If <paramref name="throwIfNoneFound"/> is true: The first parameter definition with the provided name. /// <para/> /// Otherwise: Either the first parameter definition with the given name, or null if none is found. /// </returns> public static ParameterDefinition GetParameter ( this IMethodSignature signature, string name, bool throwIfNoneFound ) { if (throwIfNoneFound) { return(signature.Parameters.First(p => p.Name == name)); } return(signature.Parameters.FirstOrDefault(p => p.Name == name)); }
public void ReadMethodSignature(IMethodSignature method) { byte num = base.ReadByte(); if ((num & 0x20) != 0) { method.HasThis = true; num = (byte)(num & -33); } if ((num & 0x40) != 0) { method.ExplicitThis = true; num = (byte)(num & -65); } method.CallingConvention = (MethodCallingConvention)num; MethodReference owner = method as MethodReference; if ((owner != null) && !owner.DeclaringType.IsArray) { this.reader.context = owner; } if ((num & 0x10) != 0) { uint num2 = base.ReadCompressedUInt32(); if ((owner != null) && !owner.IsDefinition) { CheckGenericContext(owner, ((int)num2) - 1); } } uint num3 = base.ReadCompressedUInt32(); method.MethodReturnType.ReturnType = this.ReadTypeSignature(); if (num3 != 0) { Collection <ParameterDefinition> parameters; MethodReference reference2 = method as MethodReference; if (reference2 == null) { parameters = method.Parameters; } else { parameters = reference2.parameters = new ParameterDefinitionCollection(method, (int)num3); } for (int i = 0; i < num3; i++) { parameters.Add(new ParameterDefinition(this.ReadTypeSignature())); } } }
public static int GetPopDelta(this Instruction instruction, MethodDefinition current, int currentStackSize) { OpCode code = instruction.OpCode; switch (code.StackBehaviourPop) { case StackBehaviour.Pop0: return 0; case StackBehaviour.Popi: case StackBehaviour.Popref: case StackBehaviour.Pop1: return 1; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: return 2; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: return 3; case StackBehaviour.PopAll: return currentStackSize; case StackBehaviour.Varpop: if (code == OpCodes.Ret) return IsVoid (current.ReturnType) ? 0 : 1; if (code.FlowControl != FlowControl.Call) break; IMethodSignature method = (IMethodSignature) instruction.Operand; int count = method.HasParameters ? method.Parameters.Count : 0; if (method.HasThis && code != OpCodes.Newobj) ++count; return count; } throw new NotSupportedException (); }
/// <summary> /// Get fingerprint of MemberReference. If fingerprints are equal, members can be implementations of each other /// </summary> /// <param name="memberReference">Type member which fingerprint is returned</param> /// <param name="genericInterface">GenericInstanceType instance to resolve generic types if they are explicitly specified in the interface implementation code</param> /// <remarks>Any existing MemberFormatter can't be used for generation of fingerprint because none of them generate equal signatures /// for an interface member and its implementation in the following cases: /// 1. Explicitly implemented members /// 2. Different names of generic arguments in interface and in implementing type /// 3. Implementation of interface with generic type parameters /// The last point is especially interesting because it makes GetFingerprint method context-sensitive: /// it returns signatures of interface members depending on generic parameters of the implementing type (GenericInstanceType parameter).</remarks> public static string GetFingerprint(MemberReference memberReference, GenericInstanceType genericInterface = null) { // An interface contains only the signatures of methods, properties, events or indexers. StringBuilder buf = new StringBuilder(); var unifiedTypeNames = new Dictionary <string, string>(); FillUnifiedMemberTypeNames(unifiedTypeNames, memberReference as IGenericParameterProvider); // Fill the member generic parameters unified names as M0, M1.... FillUnifiedTypeNames(unifiedTypeNames, memberReference.DeclaringType, genericInterface); // Fill the type generic parameters unified names as T0, T1.... if (memberReference is IMethodSignature) { IMethodSignature methodSignature = (IMethodSignature)memberReference; buf.Append(GetUnifiedTypeName(methodSignature.ReturnType, unifiedTypeNames)).Append(" "); buf.Append(SimplifyName(memberReference.Name)).Append(" "); AppendParameters(buf, methodSignature.Parameters, unifiedTypeNames); } if (memberReference is PropertyDefinition) { PropertyDefinition propertyReference = (PropertyDefinition)memberReference; buf.Append(GetUnifiedTypeName(propertyReference.PropertyType, unifiedTypeNames)).Append(" "); if (propertyReference.GetMethod != null) { buf.Append("get").Append(" "); } if (propertyReference.SetMethod != null) { buf.Append("set").Append(" "); } buf.Append(SimplifyName(memberReference.Name)).Append(" "); AppendParameters(buf, propertyReference.Parameters, unifiedTypeNames); } if (memberReference is EventDefinition) { EventDefinition eventReference = (EventDefinition)memberReference; buf.Append(GetUnifiedTypeName(eventReference.EventType, unifiedTypeNames)).Append(" "); buf.Append(SimplifyName(memberReference.Name)).Append(" "); } var memberUnifiedTypeNames = new Dictionary <string, string>(); FillUnifiedMemberTypeNames(memberUnifiedTypeNames, memberReference as IGenericParameterProvider); if (memberUnifiedTypeNames.Any())// Add generic arguments to the fingerprint. SomeMethod<T>() != SomeMethod() { buf.Append(" ").Append(string.Join(" ", memberUnifiedTypeNames.Values)); } return(buf.ToString()); }
private void WriteMethodArguments(StringBuilder formatBuilder, int[] argumentsIndex, int startParameter, bool includeParameterName, bool includeParameterType, bool includeParameterValue, bool includeOutParams) { IMethodSignature methodSignature = this.context.MethodMapping.MethodSignature; int parameterCount = methodSignature.ParameterCount; for (int i = 0; i < parameterCount; i++) { int index = i + startParameter; if (index > 0) { formatBuilder.Append(", "); } bool isOut = this.targetMethod.Parameters[i].Attributes.HasFlag(ParameterAttributes.Out); bool isRef = this.targetMethod.Parameters[i].ParameterType is PointerTypeSignature; ITypeSignature parameterType = methodSignature.GetParameterType(i); if (includeParameterType) { string typeName = parameterType.GetReflectionName(ReflectionNameOptions.MethodParameterContext, NameShortener.Instance); if (isRef) { typeName = string.Format("{0} {1}", (isOut ? "out" : "ref"), typeName.Remove(typeName.Length - 6)); //Remove 'ByRef' suffix } formatBuilder.Append(typeName); } if (includeParameterName) { formatBuilder.AppendFormat(" {0}", this.context.MethodMapping.MethodMappingInformation.GetParameterName(i)); } if ((includeOutParams || !isOut) && includeParameterValue) { if (includeParameterName || includeParameterType) { formatBuilder.AppendFormat(" = "); } AppendFormatPlaceholder(index, formatBuilder, parameterType); argumentsIndex[index] = i; } } }
private bool CheckReturnVoid(IMetadataTokenProvider eventType, IMethodSignature invoke) { TypeReference rtype = invoke.ReturnType; if (rtype.IsNamed("System", "Void")) { return(true); } string msg = String.Format(CultureInfo.InvariantCulture, "The delegate should return void, not {0}", rtype.GetFullName()); Runner.Report(eventType, Severity.Medium, Confidence.High, msg); return(false); }
public static int GetSentinelPosition(this IMethodSignature self) { if (self.HasParameters) { Collection <ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { if (parameters[i].ParameterType.IsSentinel) { return(i); } } } return(-1); }
private static int GetArgCount(OpCode opCode, IMethodSignature method) { var argCount = method.Parameters.Count; if (method.HasThis && !method.ExplicitThis && opCode.Code != Code.Newobj) { ++argCount; } if (opCode.Code == Code.Calli) { ++argCount; } return(argCount); }
public IMethod Resolve(IMethodSignature methodSig, ICodeNode context, bool polymorphic = false, bool throwOnFailure = false) { var method = ResolveMethod(methodSig, context.Module, context, polymorphic); if (method == null) { if (throwOnFailure) { throw new ResolveReferenceException(string.Format(SR.MethodResolveError, methodSig.ToString())); } return(null); } return(method); }
private List <ICustomAttribute> GetSortedReturnValueAttributes(IMemberDefinition member) { IMethodSignature method = null; TypeDefinition type = member as TypeDefinition; if (type != null && type.IsDelegate()) { method = type.Methods.FirstOrDefault(m => m.Name == "Invoke"); } else { method = member as IMethodSignature; } return(base.GetSortedReturnValueAttributes(method)); }
private void ProcessCall([NonNull] Instruction insn, bool warn, bool indirect, [NonNull] NullDerefFrame frame) { IMethodSignature csig = (IMethodSignature)insn.Operand; if (indirect) { frame.PopStack(); /* Function pointer */ } foreach (ParameterDefinition param in csig.Parameters) { Nullity n = frame.PopStack(); if (warn && nnaCollector.HasNonNullAttribute(method, param)) { if (Verbose) { Trace.WriteLine(string.Format("FAILURE6: null deref at {0:X2}", insn.Offset)); } if (n == Nullity.Null) { runner.Report(method, insn, Severity.High, Confidence.Low, "passing null value as argument declared non-null"); } else if (n == Nullity.Unknown) { runner.Report(method, insn, Severity.High, Confidence.Low, "passing possibly null value as argument declared non-null"); } } } if (csig.HasThis && !Ignoring(csig)) /* Add 'this' parameter. */ { Check(insn, warn, frame.PopStack(), "method"); } if (!IsVoid(csig.ReturnType)) { if (csig.ReturnType.IsValueType) { frame.PushStack(Nullity.NonNull); } else if (nnaCollector.HasNonNullAttribute(csig)) { frame.PushStack(Nullity.NonNull); } else { frame.PushStack(Nullity.Unknown); } } }
/// <summary> /// Checks if a method's parameters match an array of types, throwing an exception if they don't. /// </summary> /// <param name="method">The method to check against</param> /// <param name="args">The parameters to check for</param> /// <exception cref="Exception">If both parameter sets don't match</exception> private static void AssertParams(IMethodSignature method, params TypeReference[] args) { var c = method.Parameters.Count; if (args.Length != c) { throw new Exception( $"Method [{method}] does not match [{string.Join(",", args.Select(e => e.ToString()))}]"); } for (var i = 0; i < c; i++) { if (method.Parameters[i].ParameterType.FullName != args[i].FullName) { throw new Exception($"Expected {args[i]} but got {method.Parameters[i].ParameterType}"); } } }
public MethodDeclaration Find(IMethodSignature methodSig, SignatureComparer comparer, bool throwIfMissing = false) { foreach (var method in this) { if (comparer.Equals(method, methodSig)) { return(method); } } if (throwIfMissing) { throw new CodeModelException(string.Format(SR.MethodNotFound2, methodSig.ToString())); } return(null); }
/// <summary> /// Checks if a method's parameters match an array of types. /// </summary> /// <param name="method">The method to check against</param> /// <param name="args">The parameters to check for</param> /// <returns>True if both parameter sets match, false otherwise</returns> private static bool EqualParams(IMethodSignature method, params TypeReference[] args) { var c = method.Parameters.Count; if (args.Length != c) { return(false); } for (var i = 0; i < c; i++) { if (method.Parameters[i].ParameterType.FullName != args[i].FullName) { return(false); } } return(true); }
public void Setup() { var sig = new TestCaseSignature(new List <ITestCaseCell> { new TestCaseCell("first"), new TestCaseCell("second"), new TestCaseCell("result") }, MethodArgType.Parameter); arguments = new TestCaseSignature(new List <ITestCaseCell> { new TestCaseCell("0x?"), new TestCaseCell("0x01"), new TestCaseCell("0x0102") }, MethodArgType.Argument); signature = sig.Join(arguments); }
public override PexResultTracking GetResultTreatment(PexTrackingThread thread, int callId, IMethodSignature methodSignature, TypeEx[] varArgTypes, bool hasDerivedResult) { Dump("in GetResultTreatment============================="); // track uninstrumented method calls if (!hasDerivedResult) { var method = methodSignature as Method; if (method.FullName.Equals(_trackMethod.FullName)) { if (track) { Dump("start to track " + method.FullName); TrackingMethods.Add(method); Dump("end GetResultTreatment============================="); return(PexResultTracking.Track); } Dump("method " + method.FullName + " is not tracked!"); } // IssueTrackDatabase db; // if (host.TryGetService<IssueTrackDatabase>(out db)) // { //// host.Log.Dump("size", "size", "uninstrumented methods: " + db.UnInstrumentedMethods.Count); // foreach (var uninstrumentedMethod in db.UnInstrumentedMethods) // { //// host.Log.Dump("Method", "Method", "uninstrumented methods: " + uninstrumentedMethod.Method.FullName); //// host.Log.Dump("Method", "Method2", "methods: " + method.Definition.FullName); // if (uninstrumentedMethod.Method.FullName.Equals(method.FullName)) // { //// host.Log.Dump("Method", "track", "track: " + method.Definition.FullName); // if (TrackingMethods.Add(method)) // { // return PexResultTracking.Track; // } // } // } // } } Dump("end GetResultTreatment============================="); return(PexResultTracking.ConcreteOrDerived); }
void MakeByRefCallSimple(SsaBlock block, ref int instructionIndexInBlock, IMethodSignature targetMethod) { SsaInstruction inst = block.Instructions[instructionIndexInBlock]; for (int i = 0; i < inst.Operands.Length; i++) { SsaVariable operand = inst.Operands[i]; if (operand.IsSingleAssignment && operand.Usage.Count == 1 && IsLoadAddress(operand.Definition)) { // address is used for this method call only Instruction loadAddressInstruction = operand.Definition.Instruction; // find target parameter type: bool isOut; if (i == 0 && targetMethod.HasThis) { isOut = false; } else { ParameterDefinition parameter = targetMethod.Parameters[i - (targetMethod.HasThis ? 1 : 0)]; isOut = parameter.IsOut; } SsaVariable addressTakenOf = GetVariableFromLoadAddressInstruction(loadAddressInstruction); // insert "Prepare" instruction on front SpecialOpCode loadOpCode = isOut ? SpecialOpCode.PrepareByOutCall : SpecialOpCode.PrepareByRefCall; block.Instructions.Insert(instructionIndexInBlock++, new SsaInstruction( block, null, operand, new SsaVariable[] { addressTakenOf }, specialOpCode: loadOpCode)); // insert "WriteAfterByRefOrOutCall" instruction after call block.Instructions.Insert(instructionIndexInBlock + 1, new SsaInstruction( block, null, addressTakenOf, new SsaVariable[] { operand }, specialOpCode: SpecialOpCode.WriteAfterByRefOrOutCall)); couldSimplifySomething = true; // remove the loadAddressInstruction later // (later because it might be defined in the current block and we don't want instructionIndex to become invalid) redundantLoadAddressInstructions.Add(operand.Definition); } } }
void CheckParametersAndValues(IMetadataTokenProvider provider, IMethodSignature constructor, IList <CustomAttributeArgument> arguments) { for (int index = 0; index < arguments.Count; index++) { ParameterDefinition parameter = constructor.Parameters[index]; if (parameter.ParameterType.IsNamed("System", "String")) { string value = (string)arguments [index].Value; if (Contains(parameter.Name, "version")) { Version v = null; if (!Version.TryParse(value, out v)) { string msg = String.Format(CultureInfo.InvariantCulture, "The value passed: {0} can't be parsed to a valid Version.", value); Runner.Report(provider, Severity.High, Confidence.High, msg); } continue; } if (Contains(parameter.Name, "url") || Contains(parameter.Name, "uri") || Contains(parameter.Name, "urn")) { Uri parsed = null; if (!Uri.TryCreate(value, UriKind.Absolute, out parsed)) { string msg = String.Format(CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Uri.", value); Runner.Report(provider, Severity.High, Confidence.High, msg); } continue; } if (Contains(parameter.Name, "guid")) { Guid g; if (!Guid.TryParse(value, out g)) { string msg = String.Format(CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Guid.", value); Runner.Report(provider, Severity.High, Confidence.High, msg); } continue; } } } }
public static int GetSentinelPosition(IMethodSignature self) { if (!self.HasParameters) { return(-1); } var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { if (parameters[i].ParameterType.IsSentinel) { return(i); } } return(-1); }
private void EmitCanReplace(CilWorker IL, IMethodSignature hostMethod, VariableDefinition provider) { var skipGetProvider = IL.Create(OpCodes.Nop); IL.Emit(OpCodes.Ldloc, provider); IL.Emit(OpCodes.Brfalse, skipGetProvider); IL.Emit(OpCodes.Ldloc, provider); // Push the host instance var pushInstance = hostMethod.HasThis ? IL.Create(OpCodes.Ldarg_0) : IL.Create(OpCodes.Ldnull); IL.Append(pushInstance); IL.Emit(OpCodes.Ldloc, _invocationInfo); IL.Emit(OpCodes.Callvirt, _canReplace); IL.Emit(OpCodes.Stloc, _canReplaceFlag); IL.Append(skipGetProvider); }
/// <summary> /// /// </summary> /// <param name="signature"></param> /// <param name="method"></param> /// <param name="flags"></param> /// <returns></returns> protected virtual bool NameMatch(IMethodSignature signature, MethodInfo method, CutPointFlags flags) { String sign = signature.Method; String name = method.Name; if (sign.IndexOf('*') != -1) { return(Regex.IsMatch(name, sign)); } if ((method.IsSpecialName && (((int)(flags & CutPointFlags.Property)) != 0)) || (name.StartsWith("get_") && (((int)(flags & CutPointFlags.PropertyRead)) != 0)) || (name.StartsWith("set_") && (((int)(flags & CutPointFlags.PropertyWrite)) != 0))) { name = name.Substring(4); } return(name.Equals(sign)); }
internal bool Equals(IMethodSignature x, IMethodSignature y, ICodeNode xGenericContext = null) { if (x.Name != y.Name) { return(false); } if (x.HasThis != y.HasThis) { return(false); } if (x.CallConv != y.CallConv) { return(false); } if (x.GenericParameterCount != y.GenericParameterCount) { return(false); } int xArgumentCount = x.GetArgumentCountNoVarArgs(); int yArgumentCount = y.GetArgumentCountNoVarArgs(); if (xArgumentCount != yArgumentCount) { return(false); } if (!EqualsTypes(x.Arguments, y.Arguments, xArgumentCount, xGenericContext)) { return(false); } if (!EqualsType(x.ReturnType, y.ReturnType, xGenericContext)) { return(false); } return(true); }
public static void MethodSignatureFullName (IMethodSignature self, StringBuilder builder) { builder.Append ("("); if (self.HasParameters) { var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { var parameter = parameters [i]; if (i > 0) builder.Append (","); if (parameter.ParameterType.IsSentinel) builder.Append ("...,"); builder.Append (parameter.ParameterType.FullName); } } builder.Append (")"); }
internal ParameterDefinition (TypeReference parameterType, IMethodSignature method) : this (string.Empty, ParameterAttributes.None, parameterType) { this.method = method; }
/// <summary> /// Return the instruction that match the current instruction. This is computed by /// substracting push and adding pop counts until the total becomes zero. /// </summary> /// <param name="self">The Instruction on which the extension method can be called.</param> /// <param name="method">The method from which the instruction was extracted.</param> /// <param name="offset">Offset to add the the Pop count. Useful to track several parameters to a method.</param> /// <returns>The instruction that match the current instruction.</returns> public static Instruction TraceBack (this Instruction self, IMethodSignature method, int offset) { int n = offset + self.GetPopCount (method); while (n > 0 && self.Previous != null) { self = self.Previous; // we cannot "simply" trace backward over a unconditional branch if (self.OpCode.FlowControl == FlowControl.Branch) return null; n -= self.GetPushCount (); if (n == 0) return self; int pop = self.GetPopCount (method); if (pop == -1) return null; // PopAll n += pop; } return null; }
/// <summary> /// Return the instruction that match the current instruction. This is computed by /// substracting push and adding pop counts until the total becomes zero. /// </summary> /// <param name="self">The Instruction on which the extension method can be called.</param> /// <param name="method">The method from which the instruction was extracted.</param> /// <returns>The instruction that match the current instruction.</returns> public static Instruction TraceBack (this Instruction self, IMethodSignature method) { return TraceBack (self, method, 0); }
/// <summary> /// Get the number of values removed on the stack for this instruction. /// </summary> /// <param name="self">The Instruction on which the extension method can be called.</param> /// <param name="method">The method inside which the instruction comes from /// (needed for StackBehaviour.Varpop).</param> /// <returns>The number of value removed (pop) from the stack for this instruction.</returns> public static int GetPopCount (this Instruction self, IMethodSignature method) { if (self == null) throw new ArgumentException ("self"); if (method == null) throw new ArgumentException ("method"); switch (self.OpCode.StackBehaviourPop) { case StackBehaviour.Pop0: return 0; case StackBehaviour.Pop1: case StackBehaviour.Popi: case StackBehaviour.Popref: return 1; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: case StackBehaviour.Popi_popi: return 2; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: return 3; case StackBehaviour.Varpop: switch (self.OpCode.FlowControl) { case FlowControl.Return: return method.ReturnType.FullName == "System.Void" ? 0 : 1; case FlowControl.Call: IMethodSignature calledMethod = (IMethodSignature) self.Operand; // avoid allocating empty ParameterDefinitionCollection int n = calledMethod.HasParameters ? calledMethod.Parameters.Count : 0; if (self.OpCode.Code != Code.Newobj) { if (calledMethod.HasThis) n++; } return n; default: throw new NotImplementedException ("Varpop not supported for this Instruction."); } case StackBehaviour.PopAll: return -1; default: string unknown = String.Format ("'{0}' is not a valid value for instruction '{1}'.", self.OpCode.StackBehaviourPush, self.OpCode); throw new InvalidOperationException (unknown); } }
public static int GetSentinelPosition(IMethodSignature ms) { if (!ms.HasParameters) return -1; var parameters = ms.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters[i].ParameterType.IsSentinel) return i; return -1; }
public override PexResultTracking GetResultTreatment(PexTrackingThread thread, int callId, IMethodSignature methodSignature, TypeEx[] varArgTypes, bool hasDerivedResult) { // track uninstrumented method calls if (!hasDerivedResult) { var method = methodSignature as Method; if (method.FullName.Equals(_trackMethod.FullName)) { if (track) { Dump("start to track " + method.FullName); TrackingMethods.Add(method); return PexResultTracking.Track; } Dump("method " + method.FullName + " is not tracked!"); } // IssueTrackDatabase db; // if (host.TryGetService<IssueTrackDatabase>(out db)) // { //// host.Log.Dump("size", "size", "uninstrumented methods: " + db.UnInstrumentedMethods.Count); // foreach (var uninstrumentedMethod in db.UnInstrumentedMethods) // { //// host.Log.Dump("Method", "Method", "uninstrumented methods: " + uninstrumentedMethod.Method.FullName); //// host.Log.Dump("Method", "Method2", "methods: " + method.Definition.FullName); // if (uninstrumentedMethod.Method.FullName.Equals(method.FullName)) // { //// host.Log.Dump("Method", "track", "track: " + method.Definition.FullName); // if (TrackingMethods.Add(method)) // { // return PexResultTracking.Track; // } // } // } // } } return PexResultTracking.ConcreteOrDerived; }
public MethodReturnType(IMethodSignature method) { this.method = method; }
private MethodReference FindImpurity (IMethodSignature method, Instruction end) { MethodReference impure = null; Instruction ins = FullTraceBack (method, end); if (ins != null) { Log.WriteLine (this, "checking args for call at {0:X4} starting at {1:X4}", end.Offset, ins.Offset); while (ins.Offset < end.Offset && impure == null) { if (ins.OpCode.Code == Code.Call || ins.OpCode.Code == Code.Callvirt) { MethodReference candidate = ins.Operand as MethodReference; if (!IsPure (candidate)) return candidate; } ins = ins.Next; } } return impure; }
// This is like the TraceBack rock except that it continues traversing backwards // until it finds an instruction which does not pop any values off the stack. This // allows us to check all of the instructions used to compute the method's // arguments. internal static Instruction FullTraceBack (IMethodSignature method, Instruction end) { Instruction first = end.TraceBack (method); while (first != null && first.GetPopCount (method) > 0) { first = first.TraceBack (method); } return first; }
private bool CheckParameterTypes (IMetadataTokenProvider eventType, IMethodSignature invoke) { bool ok = true; if (!invoke.HasParameters) return ok; IList<ParameterDefinition> pdc = invoke.Parameters; if (pdc.Count >= 1) { string type_name = pdc [0].ParameterType.FullName; if (String.Compare (type_name, "System.Object") != 0) { Runner.Report (eventType, Severity.Medium, Confidence.High, String.Format ("The first parameter should have an object, not {0}", type_name)); ok = false; } } if (pdc.Count >= 2) { if (!pdc [1].ParameterType.Inherits ("System.EventArgs")) { Runner.Report (eventType, Severity.Medium, Confidence.High, "The second parameter should be a subclass of System.EventArgs"); ok = false; } } return ok; }
private static IEnumerable<TypeReference> ParameterTypes(IMethodSignature method) { return method.Parameters.Select(x => x.ParameterType); }
private bool CheckAmountOfParameters (IMetadataTokenProvider eventType, IMethodSignature invoke) { if (invoke.HasParameters && (invoke.Parameters.Count == 2)) return true; Runner.Report (eventType, Severity.Medium, Confidence.High, "The delegate should have 2 parameters"); return false; }
private static string GetSuggestionMemberKind (IMethodSignature method) { if (method.Parameters.Count == 1 && method.ReturnType.FullName != "System.Void") return "property"; return "method"; }
private IEnumerable<TypeReference> ParameterCustomAttributeTypes(IMethodSignature method) { return method.Parameters.SelectMany(x => CustomAttributesOf(x)); }
private void CheckParameters (IMethodSignature concat, MethodDefinition caller, Instruction ins) { // check for boxed (likely char, but could be other types too) on any parameter for (int i = 0; i < concat.Parameters.Count; i++) { Instruction source = ins.TraceBack (caller, -i); if ((source == null) || (source.OpCode.Code != Code.Box)) continue; ReportBoxing (caller, source, Confidence.High); } }
private IEnumerable<TypeReference> ReturnTypeCustomAttributesTypes(IMethodSignature method) { return CustomAttributesOf(method.MethodReturnType); }
private static void PopulateMethodParameters(IMethodSignature member, CodeParameterDeclarationExpressionCollection parameters, bool isExtension = false) { foreach (var parameter in member.Parameters) { FieldDirection direction = 0; if (parameter.IsOut) direction |= FieldDirection.Out; else if (parameter.ParameterType.IsByReference) direction |= FieldDirection.Ref; var parameterType = parameter.ParameterType.IsByReference ? parameter.ParameterType.GetElementType() : parameter.ParameterType; var type = CreateCodeTypeReference(parameterType); if (isExtension) { type = ModifyCodeTypeReference(type, "this"); isExtension = false; } var name = parameter.HasConstant ? string.Format("{0} = {1}", parameter.Name, FormatParameterConstant(parameter)) : parameter.Name; var expression = new CodeParameterDeclarationExpression(type, name) { Direction = direction, CustomAttributes = CreateCustomAttributes(parameter) }; parameters.Add(expression); } }
public override int GetNextCallId(int threadId, int offset, IMethodSignature methodSignature, TypeEx[] varArgTypes, Term[] arguments) { DumpInfo(methodSignature, threadId, offset, varArgTypes); var termManager = host.ExplorationServices.TermManager; var method = methodSignature as Method; if (method != null) { Dump("method name: " + method.FullName + " offset: " + offset); if (!method.FullName.Equals(_trackMethod.FullName)) { Dump("method: " + method.FullName + " is not tracking method " + _trackMethod); Dump("end GetNextCallId============================="); Dump(""); return 0; } } if (method != null) { Dump("method name: " + method.FullName); if (method.FullName.Equals(_trackMethod.FullName)) { bool foundSymbol = false; if (arguments == null) { Dump("args is null"); } else { string arg = ""; foreach (Term term in arguments) { arg += "arg: " + term + " is symbolic: " + termManager.IsSymbol(term); var extractor = new ResultTrackConditionExtractor(termManager); extractor.VisitTerm(default(TVoid), term); arg += " symbol: " + extractor.Log; } Dump("args: " + arg); foreach (Term argument in arguments) { if (termManager.IsSymbol(argument)) { foundSymbol = true; break; } } } track = foundSymbol; if (track) { Dump("track " + method.FullName); trackArg = true; methodForTrackingArg = method; Dump("track parameter of " + method.FullName); } } } else { Dump(methodSignature + " signature is null."); } Dump("end GetNextCallId============================="); Dump(""); return 0; }
public static List<CompParameter> GetParameters(IMethodSignature provider) { var l = new List<CompParameter> (); foreach (ParameterDefinition pd in provider.Parameters) { l.Add (new CecilParameter (pd)); } return l; }
private void DumpInfo(IMethodSignature methodSignature, int threadId, int offset, TypeEx[] varArgTypes) { Dump("in GetNextCallId============================="); Dump("method of the stack: " + methodStack.Peek().FullName); try { Dump("threadId: " + threadId + " offset: " + offset + " method: " + methodSignature); if (varArgTypes == null) { Dump("types is null"); } else { string types = ""; foreach (TypeEx ex in varArgTypes) { types += "varArgType: " + ex + ", "; } Dump("types: " + types); } } catch (Exception e) { Dump(e.Message + " trace: " +e.StackTrace); } }
private static bool CompareParameters (IMethodSignature m1, IMethodSignature m2) { bool h1 = m1.HasParameters; bool h2 = m2.HasParameters; if (h1 != h2) return false; if (!h1 && !h2) return true; IList<ParameterDefinition> pdc1 = m1.Parameters; IList<ParameterDefinition> pdc2 = m2.Parameters; if (pdc1.Count != pdc2.Count) return false; for (int i = 0; i < pdc1.Count; ++i) { if (!AreSameElementTypes (pdc1 [i].ParameterType, pdc2 [i].ParameterType)) return false; } return true; }
private static IEnumerable<TypeReference> MethodReturnType(IMethodSignature method) { yield return method.ReturnType; }