Exemple #1
0
 private static void AnalyzeCallOperations(IMethodDefinition method)
 {
     foreach (var operation in getCallOperations(method))
     {
         Console.WriteLine("\t\t" + getTypeOfMethod(operation));
     }
 }
        private DifferenceType Diff(IDifferences differences, IMethodDefinition implMethod, IMethodDefinition contractMethod)
        {
            if (implMethod == null || contractMethod == null)
                return DifferenceType.Unknown;

            return DiffConstraints(differences, implMethod, implMethod.GenericParameters, contractMethod.GenericParameters);
        }
Exemple #3
0
 public static int Of(IMethodDefinition method, PdbReader pdb, IMetadataHost host)
 {
     if (method.HasOperations())
         return method.CalculateStatements(pdb, host);
     else
         return 0;
 }
 /// <summary>
 /// Returns the unspecialized version of the given method reference.
 /// </summary>
 public static IMethodReference Unspecialize(IMethodDefinition method) {
   var smd = method as ISpecializedMethodDefinition;
   if (smd != null) return smd.UnspecializedVersion;
   var gmi = method as IGenericMethodInstance;
   if (gmi != null) return gmi.GenericMethod;
   return method;
 }
            private List<IMethodDefinition> FindCandidateMethods(IMethodDefinition method)
            {
                var methodsInThisType = method.ContainingTypeDefinition.Methods
                    .Where(m => m != method && m.Name.Value == method.Name.Value);

                return methodsInThisType.ToList();
            }
 public static int Of(IMethodDefinition method, PdbReader pdb, IMetadataHost host)
 {
     if (method.HasOperations())
         return method.CalculateCyclomaticComplexity(pdb, host);
     else
         return 0;
 }
 public MutationResult(Mutant mutant, ICciModuleSource mutatedModules, List<CciModuleSource> old, IMethodDefinition methodMutated)
 {
     _mutant = mutant;
     MutatedModules = mutatedModules;
     Old = old;
     MethodMutated = methodMutated;
 }
    internal InstructionParser(SourceMethodBody sourceMethodBody) {
      Contract.Requires(sourceMethodBody != null);

      this.sourceMethodBody = sourceMethodBody;
      this.host = sourceMethodBody.host; Contract.Assume(this.host != null);
      this.ilMethodBody = sourceMethodBody.ilMethodBody; Contract.Assume(this.ilMethodBody != null);
      this.MethodDefinition = sourceMethodBody.MethodDefinition;
      this.nameTable = sourceMethodBody.nameTable; Contract.Assume(this.nameTable != null);
      this.sourceLocationProvider = sourceMethodBody.sourceLocationProvider;
      this.localScopeProvider = sourceMethodBody.localScopeProvider;
      this.options = sourceMethodBody.options;
      this.platformType = sourceMethodBody.platformType; Contract.Assume(this.platformType != null);
      this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(this.numberOfAssignmentsToLocal != null);
      this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(this.numberOfReferencesToLocal != null);
      this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
      this.cdfg = sourceMethodBody.cdfg; Contract.Assume(this.cdfg != null);
      this.bindingsThatMakeALastUseOfALocalVersion = sourceMethodBody.bindingsThatMakeALastUseOfALocalVersion; Contract.Assume(this.bindingsThatMakeALastUseOfALocalVersion != null);

      if (this.localScopeProvider != null) {
        var syncInfo = this.localScopeProvider.GetSynchronizationInformation(sourceMethodBody);
        if (syncInfo != null) {
          var syncPointFor = this.synchronizatonPointLocationFor = new Hashtable<SynchronizationPointLocation>();
          IDocument doc = Dummy.Document;
          foreach (var loc in this.MethodDefinition.Locations) { doc = loc.Document; break; }
          foreach (var syncPoint in syncInfo.SynchronizationPoints) {
            Contract.Assume(syncPoint != null);
            var syncLoc = new SynchronizationPointLocation(doc, syncPoint);
            syncPointFor[syncPoint.SynchronizeOffset] = syncLoc;
            if (syncPoint.ContinuationMethod == null)
              syncPointFor[syncPoint.ContinuationOffset] = syncLoc;
          }
        }
      }
    }
        private bool ParamNamesAndTypesMatch(IDifferences differences, IMethodDefinition implMethod, IMethodDefinition contractMethod)
        {
            int paramCount = implMethod.ParameterCount;

            Contract.Assert(paramCount == contractMethod.ParameterCount);

            IParameterDefinition[] implParams = implMethod.Parameters.ToArray();
            IParameterDefinition[] contractParams = contractMethod.Parameters.ToArray();

            bool match = true;
            for (int i = 0; i < paramCount; i++)
            {
                IParameterDefinition implParam = implParams[i];
                IParameterDefinition contractParam = contractParams[i];

                if (!implParam.Name.Value.Equals(contractParam.Name.Value))
                {
                    differences.AddIncompatibleDifference("DelegateParamNameMustMatch",
                        "Parameter name on delegate '{0}' is '{1}' in the implementation but '{2}' in the contract.",
                        implMethod.ContainingType.FullName(), implParam.Name.Value, contractParam.Name.Value);
                    match = false;
                }

                if (!_typeComparer.Equals(implParam.Type, contractParam.Type))
                {
                    differences.AddTypeMismatchDifference("DelegateParamTypeMustMatch", implParam.Type, contractParam.Type,
                        "Type for parameter '{0}' on delegate '{1}' is '{2}' in the implementation but '{3}' in the contract.",
                        implParam.Name.Value, implMethod.ContainingType.FullName(), implParam.Type.FullName(), contractParam.Type.FullName());
                    match = false;
                }
            }
            return match;
        }
Exemple #10
0
    private static IMethodDefinition GetHiddenBaseClassMethod(IMethodDefinition derivedClassMethod, ITypeDefinition baseClass) {
      Contract.Requires(derivedClassMethod != null);
      Contract.Requires(baseClass != null);

      foreach (ITypeDefinitionMember baseMember in baseClass.GetMembersNamed(derivedClassMethod.Name, false)) {
        IMethodDefinition/*?*/ baseMethod = baseMember as IMethodDefinition;
        if (baseMethod == null) continue;
        if (baseMethod.Visibility == TypeMemberVisibility.Private) continue;
        if ((baseMethod.Visibility == TypeMemberVisibility.Assembly || baseMethod.Visibility == TypeMemberVisibility.FamilyAndAssembly) &&
          !UnitHelper.UnitsAreEquivalent(TypeHelper.GetDefiningUnit(derivedClassMethod.ContainingTypeDefinition), TypeHelper.GetDefiningUnit(baseClass)))
          continue;
        if (!derivedClassMethod.IsHiddenBySignature) return baseMethod;
        if (derivedClassMethod.IsGeneric || baseMethod.IsGeneric) {
          if (derivedClassMethod.GenericParameterCount == baseMethod.GenericParameterCount &&
            IteratorHelper.EnumerablesAreEqual(((ISignature)derivedClassMethod).Parameters, ((ISignature)baseMethod).Parameters, MemberHelper.GenericMethodParameterEqualityComparer))
            return baseMethod;
        } else if (IteratorHelper.EnumerablesAreEqual(((ISignature)derivedClassMethod).Parameters, ((ISignature)baseMethod).Parameters, MemberHelper.ParameterInformationComparer))
          return baseMethod;
      }
      var bases = baseClass.IsInterface ? baseClass.Interfaces : baseClass.BaseClasses;
      foreach (ITypeReference baseClassReference in bases) {
        IMethodDefinition overriddenMethod = GetHiddenBaseClassMethod(derivedClassMethod, baseClassReference.ResolvedType);
        if (!(overriddenMethod is Dummy)) return overriddenMethod;
      }
      return Dummy.MethodDefinition;
    }
        private void WriteMethodDefinitionSignature(IMethodDefinition method, string name)
        {
            bool isOperator = method.IsConversionOperator();

            if (!isOperator && !method.IsConstructor)
            {
                WriteAttributes(method.ReturnValueAttributes, true);
                // We are ignoring custom modifiers right now, we might need to add them later.
                WriteTypeName(method.Type, isDynamic: IsDynamic(method.ReturnValueAttributes));
            }

            WriteIdentifier(name);

            if (isOperator)
            {
                WriteSpace();
                WriteTypeName(method.Type);
            }

            Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances");
            if (method.IsGeneric)
                WriteGenericParameters(method.GenericParameters);

            WriteParameters(method.Parameters, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments);
            if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod())
                WriteGenericContraints(method.GenericParameters);
        }
        private void WriteMethodDefinition(IMethodDefinition method)
        {
            if (method.IsPropertyOrEventAccessor())
                return;

            if (method.IsDestructor())
            {
                WriteDestructor(method);
                return;
            }

            string name = method.GetMethodName();

            WriteMethodPseudoCustomAttributes(method);

            WriteAttributes(method.Attributes);
            WriteAttributes(method.SecurityAttributes);

            if (!method.ContainingTypeDefinition.IsInterface)
            {
                if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility);
                WriteMethodModifiers(method);
            }
            WriteInterfaceMethodModifiers(method);
            WriteMethodDefinitionSignature(method, name);
            WriteMethodBody(method);
        }
        public static bool IsPropertyModifier(IMethodDefinition method)
        {
            return method.IsSpecialName && method.ContainingTypeDefinition
                                               .Properties.Any(p => p.Setter != null 
                                                   && p.Setter.Name.UniqueKey == method.Name.UniqueKey);

        }
        private bool ParamNamesMatch(IDifferences differences, IMethodDefinition implMethod, IMethodDefinition contractMethod)
        {
            int paramCount = implMethod.ParameterCount;

            Contract.Assert(paramCount == contractMethod.ParameterCount);

            IParameterDefinition[] implParams = implMethod.Parameters.ToArray();
            IParameterDefinition[] contractParams = contractMethod.Parameters.ToArray();

            bool match = true;
            for (int i = 0; i < paramCount; i++)
            {
                IParameterDefinition implParam = implParams[i];
                IParameterDefinition contractParam = contractParams[i];

                if (!implParam.Name.Value.Equals(contractParam.Name.Value))
                {
                    differences.AddIncompatibleDifference(this,
                        "Parameter name on member '{0}' is '{1}' in the implementation but '{2}' in the contract.",
                        implMethod.FullName(), implParam.Name.Value, contractParam.Name.Value);
                    match = false;
                }
            }
            return match;
        }
        private IMethodDefinition FindBestMatch(IMethodDefinition matchMethod, TypeMapping mapping, int typeIndex, int memberIndex)
        {
            // No matches if we don't have a matching type.
            if (mapping[typeIndex] == null)
                return null;

            foreach (IMethodDefinition method in mapping[typeIndex].Methods)
            {
                if (method.Name.Value != matchMethod.Name.Value) continue;

                if (method.ParameterCount != matchMethod.ParameterCount) continue;

                if (method.IsGeneric && matchMethod.IsGeneric &&
                    method.GenericParameterCount != matchMethod.GenericParameterCount)
                    continue;

                MemberMapping member = mapping.FindMember(method);

                // It is possible to find a match that was filtered at the mapping layer
                if (member == null) continue;

                // If the other member also doesn't have a match then this is our best match
                if (member[memberIndex] == null)
                    return method;
            }

            return null;
        }
Exemple #16
0
        public Helper(IModule module, PeReader.DefaultHost host, Log.Log logger)
        {
            this.host = host;
            this.logger = logger;
            this.module = module;

            // get all needed functions and namespaces
            this.systemString = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.String");
            this.systemIOTextWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.TextWriter");
            this.systemIOStreamWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.StreamWriter");
            this.systemInt32 = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Int32");
            this.systemObject = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Object");
            this.systemConsole = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Console");
            this.systemRandom = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Random");

            ITypeReference[] concatThreeParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] concatTwoParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] streamWriterAppendTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemBoolean };

            this.stringConcatThree = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatThreeParameterTypes);
            this.stringConcatTwo = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatTwoParameterTypes);
            this.textWriterWriteLine = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("WriteLine"), this.host.PlatformType.SystemString);
            this.streamWriterCtor = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), this.host.PlatformType.SystemString);
            this.streamWriterCtorAppend = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), streamWriterAppendTypes);
            this.textWriterWrite = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Write"), this.host.PlatformType.SystemString);
            this.int32ToString = TypeHelper.GetMethod(systemInt32, this.host.NameTable.GetNameFor("ToString"));
            this.textWriterClose = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Close"));
            this.objectGetHashCode = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor("GetHashCode"));
            this.systemConsoleWriteLine = TypeHelper.GetMethod(systemConsole, host.NameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);
            this.objectCtor = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomCtor = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomNext = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor("Next"), host.PlatformType.SystemInt32);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="method"></param>
 /// <param name="host"></param>
 internal ClosureFinder(IMethodDefinition method, IMetadataHost host) {
   this.method = method;
   this.fieldForCapturedLocalOrParameter = new Dictionary<object, BoundField>();
   this.host = host;
   this.nameTable = host.NameTable;
   this.counter = 0;
   this.classList.Add((INamedTypeDefinition)method.ContainingTypeDefinition);
 }
 public MutationResult(Mutant mutant, ICciModuleSource mutatedModules, List<CciModuleSource> old, IMethodDefinition methodMutated, List<IMethodDefinition> additionalMethodsMutated=null)
 {
     _mutant = mutant;
     MutatedModules = mutatedModules;
     Old = old;
     MethodMutated = methodMutated;
     AdditionalMethodsMutated = additionalMethodsMutated;
 }
 private void WriteDestructor(IMethodDefinition method)
 {
     WriteSymbol("~");
     WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name);
     WriteSymbol("(");
     WriteSymbol(")", false);
     WriteEmptyBody();
 }
 public static IEnumerable<string> Of(IMethodDefinition method)
 {
     return Enumerable.Empty<string>()
         .Union(method.ReturnTypes())
         .Union(method.ParameterTypes())
         .Union(method.TypesOfGenericsConstraints())
         .ToList();
 }
        private void AddAlternativeInvocation(BlockStatement block,
            IMethodDefinition fakeMethod, IMethodReference originalCall)
        {
            var context = new ReplacementMethodConstructionContext(host, originalCall, fakeMethod, block, log, null);
            var methodBuilder = context.GetMethodBuilder();

            methodBuilder.BuildMethod();
        }
        public ReachabilitySummary SummarizeMethod(IMethodDefinition method, WholeProgram wholeProgram) {

            if (method.IsExternal == false && method.IsAbstract == false) {
                ReachabilitySummary summary = new ReachabilitySummary();
                IMethodDefinition target;


                // foreach MSIL instruction in the method
                foreach (var op in method.Body.Operations) {
                    switch (op.OperationCode) {
                        // non virtual method calls: just add static type
                        case OperationCode.Newobj:
                        case OperationCode.Call:
                        case OperationCode.Calli:
                            target = (op.Value as IMethodReference).ResolvedMethod;
                            summary.NonvirtuallyCalledMethods.Add(target);
                            break;

                        case OperationCode.Ldvirtftn:
                        case OperationCode.Callvirt:
                            target = (op.Value as IMethodReference).ResolvedMethod;            

                            if (target.IsVirtual == false) {
                                summary.NonvirtuallyCalledMethods.Add(target);
                            } else {
                                ITypeDefinition typeDefiningTarget = target.ContainingTypeDefinition;                                
                                IMethodDefinition targetUnspecialized = GarbageCollectHelper.UnspecializeAndResolveMethodReference(op.Value as IMethodReference);

                                // find all possible implementations of virtual call
                                foreach (ITypeDefinition subType in new ITypeDefinition[] { typeDefiningTarget }.Concat(wholeProgram.ClassHierarchy().AllSubClassesOfClass(typeDefiningTarget))) {
                                    if (GarbageCollectHelper.TypeIsConstructable(subType)) {

                                        // walk class hierarchy from subType up to (including) typeDefiningTarget, looking for targetUnspecialized.
                                        ICollection<IMethodDefinition> implementationsOfMethodDefinitionForSubType = GarbageCollectHelper.Implements(subType, typeDefiningTarget, targetUnspecialized);

                                        // we have to have found at least 1 implementation
                                        Contract.Assert(implementationsOfMethodDefinitionForSubType.Count() > 0);

                                        // add all of them as virtually called methods
                                        foreach (IMethodDefinition implementationOfTarget in implementationsOfMethodDefinitionForSubType) {
                                            summary.VirtuallyCalledMethods.Add(implementationOfTarget);
                                        }
                                    }
                                }

                            }
                            break;

                        default:
                            break;
                    }
                }

                return summary;
            } else {
                return null;
            }
        }
Exemple #23
0
 private static void AnalyzeMethod(IMethodDefinition method, PdbReader pdb)
 {
     Console.WriteLine("\t" + method.Name);
     AnalyzeLocalVariables(method);
     AnalyzeCallOperations(method);
     Console.WriteLine("\t\tcc: " + CyclomaticComplexity.Of(method));
     Console.WriteLine("\t\tml: " + MethodLength.Of(method));
     Console.WriteLine("\t\tms: " + MethodLength.WithSymbols(method, pdb));
 }
 public override void TraverseChildren(IMethodDefinition method)
 {
     if (_filter.Matches(method))
     {
         _visitor.MethodEnter(method);
         base.TraverseChildren(method);
         _visitor.MethodExit(method);
     }
 }
Exemple #25
0
 /// <summary>
 /// Initializes an object with a method that converts a given block of statements to a list of IL operations, exception information and possibly some private helper types.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global
 /// objects and services such as the shared name table and the table for interning references.</param>
 /// <param name="method">The method that contains the block of statements that will be converted.</param>
 /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in the block of statements to IPrimarySourceLocation objects.  May be null.</param>
 public CodeModelToILConverter(IMetadataHost host, IMethodDefinition method, ISourceLocationProvider/*?*/ sourceLocationProvider) {
   Contract.Requires(host != null);
   Contract.Requires(method != null);
   this.generator = new ILGenerator(host, method);
   this.host = host;
   this.method = method;
   this.sourceLocationProvider = sourceLocationProvider;
   this.minizeCodeSize = true;
 }
 public override void TraverseChildren(IMethodDefinition method) {
   this.writer.WriteLine(MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature));
   this.writer.WriteLine();
   if (!method.IsAbstract && !method.IsExternal)
     this.Traverse(method.Body);
   this.writer.WriteLine();
   this.writer.WriteLine("*******************************************************************************");
   this.writer.WriteLine();
 }
Exemple #27
0
 public static int Of(IMethodDefinition method, PdbReader pdb)
 {
     if (pdb != null)
     {
         if (pdb.IsIterator(method.Body)) return -1;
         var locations = method.LocatedOperations(pdb);
         return locations.GetAllStartLinesOfInterestingOpCodes().Distinct().Count();
     }
     return -1;
 }
        public CciMethodDetails(IMethodDefinition method)
            : base(method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            _method = method;
        }
      private static IFieldDefinition TryFindField(IMethodCall call, IMethodDefinition currentMethod)
      {
          var targetType = call.ThisArgument.Type;
 
          var field = currentMethod.ContainingTypeDefinition.Fields
              .Where(f => f.IsStatic == currentMethod.IsStatic)
              .FirstOrDefault(f => isCompatibile(targetType, f.Type.ResolvedType)
                  && FieldIsNotThis(f, call.ThisArgument) && !call.MethodToCall.ResolvedMethod.IsConstructor);
          return field;
      }
Exemple #30
0
 public static int Of(IMethodDefinition method, PdbReader pdb)
 {
     if (pdb != null)
     {
         if (pdb.IsIterator(method.Body)) return -1;
         var locations = method.LocatedOperations(pdb);
         return locations.DifferenceBetweenStartAndEndlines();
     }
     return -1;
 }
        private System.Runtime.CompilerServices.MethodImplOptions CreateMethodImplOptions(IMethodDefinition method)
        {
            // Some options are not exposed in portable contracts. PortingHelpers.cs exposes the missing constants.
            System.Runtime.CompilerServices.MethodImplOptions options = default(System.Runtime.CompilerServices.MethodImplOptions);
            if (method.IsUnmanaged)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Unmanaged;
            }
            if (method.IsForwardReference)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptionsEx.ForwardRef;
            }
            if (method.PreserveSignature)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptions.PreserveSig;
            }
            if (method.IsRuntimeInternal)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptionsEx.InternalCall;
            }
            if (method.IsSynchronized)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Synchronized;
            }
            if (method.IsNeverInlined)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptions.NoInlining;
            }
            if (method.IsAggressivelyInlined)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining;
            }
            if (method.IsNeverOptimized)
            {
                options |= System.Runtime.CompilerServices.MethodImplOptions.NoOptimization;
            }

            return(options);
        }
Exemple #32
0
 public static MethodDefinition FindMatchingMethod(TypeDefinition tdef, IMethodDefinition item)
 {
     return(tdef.Methods.FirstOrDefault(m => m.ToString() == item.ToString()));
 }
Exemple #33
0
        static void copyMethod(MethodDefinition dest, IMethodDefinition source, PeReader.DefaultHost host)
        {
            // only copy body if it is not a dummy (= empty)
            if (!(source.Body is Microsoft.Cci.Dummy))
            {
                // TODO
                // langsames kopieren des Bodies, schnellerer weg möglich?
                var testIlGenerator = new ILGenerator(host, dest);
                foreach (var operation in source.Body.Operations)
                {
                    testIlGenerator.Emit(operation.OperationCode, operation.Value);
                }
                List <ILocalDefinition> variableListCopy           = new List <ILocalDefinition>(source.Body.LocalVariables);
                List <ITypeDefinition>  privateHelperTypesListCopy = new List <ITypeDefinition>(source.Body.PrivateHelperTypes);
                var newBody = new ILGeneratorMethodBody(testIlGenerator, source.Body.LocalsAreZeroed, source.Body.MaxStack, dest, variableListCopy, privateHelperTypesListCopy);
                dest.Body = newBody;
            }

            dest.CallingConvention = source.CallingConvention;
            if (source.IsGeneric)
            {
                dest.GenericParameters = new List <IGenericMethodParameter>(source.GenericParameters);
            }
            else
            {
                dest.GenericParameters = null;
            }
            if (source.ParameterCount > 0)
            {
                dest.Parameters = new List <IParameterDefinition>(source.Parameters);
            }
            else
            {
                dest.Parameters = null;
            }
            if (source.IsPlatformInvoke)
            {
                dest.PlatformInvokeData = source.PlatformInvokeData;
            }
            else
            {
                dest.PlatformInvokeData = Dummy.PlatformInvokeInformation;
            }
            dest.ReturnValueAttributes = new List <ICustomAttribute>(source.ReturnValueAttributes);
            if (source.ReturnValueIsModified)
            {
                dest.ReturnValueCustomModifiers = new List <ICustomModifier>(source.ReturnValueCustomModifiers);
            }
            else
            {
                dest.ReturnValueCustomModifiers = new List <ICustomModifier>(0);
            }
            if (source.ReturnValueIsMarshalledExplicitly)
            {
                dest.ReturnValueMarshallingInformation = source.ReturnValueMarshallingInformation;
            }
            else
            {
                dest.ReturnValueMarshallingInformation = Dummy.MarshallingInformation;
            }
            if (source.HasDeclarativeSecurity && IteratorHelper.EnumerableIsNotEmpty(source.SecurityAttributes))
            {
                dest.SecurityAttributes = new List <ISecurityAttribute>(source.SecurityAttributes);
            }
            else
            {
                dest.SecurityAttributes = null;
            }
            dest.Type = source.Type;
            dest.AcceptsExtraArguments     = source.AcceptsExtraArguments;
            dest.HasDeclarativeSecurity    = source.HasDeclarativeSecurity;
            dest.IsAbstract                = source.IsAbstract;
            dest.IsAccessCheckedOnOverride = source.IsAccessCheckedOnOverride;
            dest.IsCil                 = source.IsCil;
            dest.IsExternal            = source.IsExternal;
            dest.IsForwardReference    = source.IsForwardReference;
            dest.IsHiddenBySignature   = source.IsHiddenBySignature;
            dest.IsNativeCode          = source.IsNativeCode;
            dest.IsNewSlot             = source.IsNewSlot;
            dest.IsNeverInlined        = source.IsNeverInlined;
            dest.IsAggressivelyInlined = source.IsAggressivelyInlined;
            dest.IsNeverOptimized      = source.IsNeverOptimized;
            dest.IsPlatformInvoke      = source.IsPlatformInvoke;
            dest.IsRuntimeImplemented  = source.IsRuntimeImplemented;
            dest.IsRuntimeInternal     = source.IsRuntimeInternal;
            dest.IsRuntimeSpecial      = source.IsRuntimeSpecial;
            dest.IsSealed              = source.IsSealed;
            dest.IsSpecialName         = source.IsSpecialName;
            dest.IsStatic              = source.IsStatic;
            dest.IsSynchronized        = source.IsSynchronized;
            dest.IsUnmanaged           = source.IsUnmanaged;
            if (dest.IsStatic)
            {
                dest.IsVirtual = false;
            }
            else
            {
                dest.IsVirtual = source.IsVirtual;
            }
            dest.PreserveSignature                 = source.PreserveSignature;
            dest.RequiresSecurityObject            = source.RequiresSecurityObject;
            dest.ReturnValueIsByRef                = source.ReturnValueIsByRef;
            dest.ReturnValueIsMarshalledExplicitly = source.ReturnValueIsMarshalledExplicitly;
            dest.ReturnValueName = source.ReturnValueName;
            dest.Name            = source.Name;
            dest.Visibility      = source.Visibility;
        }
Exemple #34
0
        public void ProcessVirtualInvoke(IMethodDefinition mCallee, ITypeDefinition calleeClass, bool isAddrTaken)
        {
            // mCallee is an ordinary method - never a template method.
            // calleeClass and mCallee are either both stubbed or, both unstubbed - i.e. they are consistent.
            bool isInterface = calleeClass.IsInterface;

            IMethodDefinition calleeTemplate = null;

            if (mCallee is IGenericMethodInstance)
            {
                calleeTemplate = (mCallee as IGenericMethodInstance).GenericMethod.ResolvedMethod;
            }

            foreach (ITypeDefinition cl in allocClasses)
            {
                if (cl is IArrayTypeReference)
                {
                    continue;
                }
                if (!Stubber.SuppressM(cl))
                {
                    bool process = false;
                    if (isInterface && Utils.ImplementsInterface(cl, calleeClass))
                    {
                        process = true;
                    }
                    if (Utils.ExtendsClass(cl, calleeClass))
                    {
                        process = true;
                    }
                    if (!process)
                    {
                        continue;
                    }
                    IMethodDefinition calleeArg;
                    if (mCallee is IGenericMethodInstance)
                    {
                        calleeArg = calleeTemplate;
                    }
                    else
                    {
                        calleeArg = mCallee;
                    }
                    IMethodDefinition meth = Utils.GetMethodSignMatchRecursive(cl, calleeArg);
                    if (meth == null)
                    {
                        continue;
                    }
                    if (meth.IsGeneric && calleeTemplate != null)
                    {
                        IMethodDefinition instMeth  = GenericMethods.RecordInfo(meth, mCallee, /* createIfReqd = */ true);
                        IMethodDefinition addedMeth = Stubber.CheckAndAdd(instMeth);
                        if (addedMeth != null && isAddrTaken)
                        {
                            addrTakenMethods.Add(addedMeth);
                        }
                    }
                    else if (meth.IsGeneric && calleeTemplate == null)
                    {
                        continue;
                    }
                    else if (!meth.IsGeneric && calleeTemplate != null)
                    {
                        continue;
                    }
                    else // meth is not generic and calleeTemplate is null
                    {
                        IMethodDefinition addedMeth = Stubber.CheckAndAdd(meth);
                        if (addedMeth != null && isAddrTaken)
                        {
                            addrTakenMethods.Add(addedMeth);
                        }
                    }
                }
            }
        }
Exemple #35
0
        public void SaveScope(IMetadataHost host)
        {
            string                 modulesFN      = "modules.txt";
            StreamWriter           modulesSW      = new StreamWriter(Path.Combine(ConfigParams.SaveScopePath, modulesFN));
            List <IModule>         moduleList     = host.LoadedUnits.OfType <IModule>().ToList();
            TypeDefinitionComparer tdc            = new TypeDefinitionComparer();
            ISet <ITypeDefinition> processedTypes = new HashSet <ITypeDefinition>(tdc);

            foreach (IModule module in moduleList)
            {
                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    System.Console.WriteLine("WARNING: SaveScope - modules: Dummy or null module - skipping.");
                    continue;
                }
                modulesSW.WriteLine("MODULE:" + module.Name.Value + " LOCATION:" + module.Location);
            }
            modulesSW.Close();

            string       classesFN = "classes.txt";
            StreamWriter classesSW = new StreamWriter(Path.Combine(ConfigParams.SaveScopePath, classesFN));

            foreach (ITypeDefinition cl in classes)
            {
                if (processedTypes.Contains(cl))
                {
                    continue;
                }
                IModule mod = TypeHelper.GetDefiningUnit(cl) as IModule;
                if (cl is IGenericTypeInstance)
                {
                    ProcessGenericType(cl, classesSW, mod, processedTypes);
                }
                else
                {
                    classesSW.WriteLine("CLASS:" + cl.FullName() + " ARGS: MODULE:" + mod.Name.Value);
                    processedTypes.Add(cl);
                }
            }
            classesSW.Close();

            string       entClassesFN = "entrypt_classes.txt";
            StreamWriter entClassesSW = new StreamWriter(Path.Combine(ConfigParams.SaveScopePath, entClassesFN));

            foreach (ITypeDefinition cl in entryPtClasses)
            {
                IModule mod = TypeHelper.GetDefiningUnit(cl) as IModule;
                entClassesSW.WriteLine("CLASS:" + cl.FullName() + " ARGS: MODULE:" + mod.Name.Value);
            }
            entClassesSW.Close();

            string       methodsFN = "methods.txt";
            StreamWriter methodsSW = new StreamWriter(Path.Combine(ConfigParams.SaveScopePath, methodsFN));

            foreach (IMethodDefinition meth in methods)
            {
                string            argStr       = "";
                IMethodDefinition methToRecord = meth;
                if (meth is IGenericMethodInstance)
                {
                    IGenericMethodInstance       genericM    = meth as IGenericMethodInstance;
                    IEnumerable <ITypeReference> genericArgs = genericM.GenericArguments;
                    foreach (ITypeReference ty in genericArgs)
                    {
                        ITypeDefinition tyDefn = ty.ResolvedType;
                        argStr += tyDefn.FullName() + ";";
                    }
                    if (!argStr.Equals(""))
                    {
                        argStr = argStr.TrimEnd(';');
                    }
                    methToRecord = genericM.GenericMethod.ResolvedMethod;
                }
                methodsSW.WriteLine("METHOD:" + methToRecord.FullName() + " ARGS:" + argStr + " CLASS:" +
                                    methToRecord.ContainingTypeDefinition.FullName());
            }
            methodsSW.Close();
        }
Exemple #36
0
        public void VisitMethod(MethodBody mBody, ControlFlowGraph cfg)
        {
            VisitLocals(mBody);

            // Going through the instructions via cfg nodes instead of directly iterating over the instructions
            // of the methodBody becuase Phi instructions may not have been inserted in the insts of the methodBody.
            foreach (var node in cfg.Nodes)
            {
                foreach (var instruction in node.Instructions)
                {
                    // System.Console.WriteLine("{0}", instruction.ToString());
                    // System.Console.WriteLine("{0}", instruction.GetType().FullName());
                    // System.Console.WriteLine();

                    if (instruction is LoadInstruction)
                    {
                        LoadInstruction lInst      = instruction as LoadInstruction;
                        IValue          rhsOperand = lInst.Operand;
                        if (rhsOperand is StaticFieldAccess)
                        {
                            StaticFieldAccess rhsAcc  = rhsOperand as StaticFieldAccess;
                            IFieldReference   fld     = rhsAcc.Field;
                            ITypeDefinition   fldType = fld.ContainingType.ResolvedType;
                            Stubber.CheckAndAdd(fldType);
                        }
                        // Note: calls to static methods and instance methods appear as a StaticMethodReference
                        else if (rhsOperand is StaticMethodReference)
                        {
                            StaticMethodReference sMethAddr    = rhsOperand as StaticMethodReference;
                            IMethodDefinition     tgtMeth      = sMethAddr.Method.ResolvedMethod;
                            ITypeDefinition       containingTy = tgtMeth.ContainingTypeDefinition;
                            Stubber.CheckAndAdd(containingTy);
                            IMethodDefinition addedMeth = Stubber.CheckAndAdd(tgtMeth);
                            // addrTakenMethods do not contain templates.
                            if (addedMeth != null)
                            {
                                addrTakenMethods.Add(addedMeth);
                            }
                        }
                        //Note: calls to virtual, abstract or interface methods appear as VirtualMethodReference
                        else if (rhsOperand is VirtualMethodReference)
                        {
                            VirtualMethodReference sMethAddr    = rhsOperand as VirtualMethodReference;
                            IMethodDefinition      tgtMeth      = sMethAddr.Method.ResolvedMethod;
                            ITypeDefinition        containingTy = tgtMeth.ContainingTypeDefinition;
                            ITypeDefinition        addedTy      = Stubber.CheckAndAdd(containingTy);
                            IMethodDefinition      addedMeth    = Stubber.CheckAndAdd(tgtMeth);
                            if (addedTy != null && addedMeth != null)
                            {
                                // addrTakenMethods do not contain templates.
                                addrTakenMethods.Add(addedMeth);
                                ProcessVirtualInvoke(addedMeth, addedTy, true);
                            }
                        }
                        else if (rhsOperand is Reference)
                        {
                            Reference      rhsRef = rhsOperand as Reference;
                            IReferenceable refOf  = rhsRef.Value;
                            if (refOf is StaticFieldAccess)
                            {
                                StaticFieldAccess refAcc  = refOf as StaticFieldAccess;
                                IFieldDefinition  fld     = refAcc.Field.ResolvedField;
                                ITypeDefinition   fldType = fld.ContainingType.ResolvedType;
                                Stubber.CheckAndAdd(fldType);
                                addrTakenStatFlds.Add(fld);
                            }
                            else if (refOf is IVariable)
                            {
                                IVariable refVar = refOf as IVariable;
                                if (!refVar.Type.IsValueType || refVar.Type.ResolvedType.IsStruct)
                                {
                                    addrTakenLocals.Add(refVar);
                                }
                            }
                            else if (refOf is InstanceFieldAccess)
                            {
                                InstanceFieldAccess refAcc = refOf as InstanceFieldAccess;
                                IFieldDefinition    fld    = refAcc.Field.ResolvedField;
                                addrTakenInstFlds.Add(fld);
                            }
                            else if (refOf is ArrayElementAccess)
                            {
                                // All arrays will be added into domX as potential address taken.
                            }
                        }
                    }
                    else if (instruction is StoreInstruction)
                    {
                        StoreInstruction sInst = instruction as StoreInstruction;
                        IAssignableValue lhs   = sInst.Result;
                        if (lhs is StaticFieldAccess)
                        {
                            StaticFieldAccess lhsAcc  = lhs as StaticFieldAccess;
                            IFieldReference   fld     = lhsAcc.Field;
                            ITypeDefinition   fldType = fld.ContainingType.ResolvedType;
                            Stubber.CheckAndAdd(fldType);
                        }
                    }
                    else if (instruction is CreateObjectInstruction)
                    {
                        CreateObjectInstruction newObjInst = instruction as CreateObjectInstruction;
                        ITypeReference          objType    = newObjInst.AllocationType;
                        ITypeDefinition         objTypeDef = objType.ResolvedType;
                        if (objTypeDef is IGenericTypeInstance)
                        {
                            objTypeDef = objTypeDef.ResolvedType;
                        }
                        ITypeDefinition addedTy = Stubber.CheckAndAdd(objTypeDef);
                        if (addedTy != null && !allocClasses.Contains(addedTy))
                        {
                            allocClasses.Add(addedTy);
                        }
                    }
                    else if (instruction is CreateArrayInstruction)
                    {
                        CreateArrayInstruction newArrInst  = instruction as CreateArrayInstruction;
                        ITypeReference         elemType    = newArrInst.ElementType;
                        ITypeDefinition        elemTypeDef = elemType.ResolvedType;
                        ITypeDefinition        addedTy     = Stubber.CheckAndAdd(elemTypeDef);
                        if (addedTy != null && !allocClasses.Contains(addedTy))
                        {
                            allocClasses.Add(addedTy);
                        }
                    }
                    else if (instruction is MethodCallInstruction)
                    {
                        MethodCallInstruction invkInst       = instruction as MethodCallInstruction;
                        IMethodReference      callTgt        = invkInst.Method;
                        ITypeReference        containingType = callTgt.ContainingType;
                        ITypeDefinition       declType       = containingType.ResolvedType;
                        IMethodDefinition     callTgtDef     = callTgt.ResolvedMethod;
                        ITypeDefinition       addedType      = Stubber.CheckAndAdd(declType);
                        IMethodDefinition     addedMeth      = Stubber.CheckAndAdd(callTgtDef);
                        MethodCallOperation   callType       = invkInst.Operation;
                        if (callType == MethodCallOperation.Virtual && addedType != null && addedMeth != null)
                        {
                            ProcessVirtualInvoke(addedMeth, addedType, false);
                        }
                    }
                    else
                    {
                        // System.Console.WriteLine("{0}", instruction.ToString());
                        // System.Console.WriteLine("Not currently handled: {0}", instruction.GetType().ToString());
                        // System.Console.WriteLine();
                    }
                }
            }
        }
Exemple #37
0
 internal ReturnValueParameter(IMethodDefinition containingMethod)
 {
     _containingMethod = containingMethod;
 }
Exemple #38
0
        /// <summary>
        /// Listen to all the IMethodDefinitions
        /// </summary>
        /// <param name="methodDefinition"></param>
        public override void Visit(IMethodDefinition methodDefinition)
        {
            if (methodDefinition == null)
            {
                return;
            }

            if (IsGetter(methodDefinition) || IsSetter(methodDefinition))
            {
                return;
            }

            string methodName = MemberHelper.GetMethodSignature(methodDefinition, NameFormattingOptions.DocID);

            Console.WriteLine(methodName);

            IMethodContract methodContract = this.contractProvider.GetMethodContractFor(methodDefinition);

            //IMethodContract inheritedContract = ContractHelper.InheritMethodContracts(this.host, this.contractProvider, methodDefinition);
            if (methodContract != null)
            {
                XElement member = GetMemberElement(membersElement, methodDefinition);

                //Add contract exceptions
                WriteExceptions(member, methodContract);

                //Add a new element for each contract
                if (options.toSummary == false)
                {
                    foreach (IPrecondition contractElement in methodContract.Preconditions)
                    {
                        Contract.Assume(contractElement != null, "lack of contracts for collections");
                        XAttribute exceptionAttribute = null;
                        if (contractElement.ExceptionToThrow != null)
                        {
                            ITypeOf asTypeOf = contractElement.ExceptionToThrow as ITypeOf;
                            if (asTypeOf != null)
                            {
                                exceptionAttribute = GetTypeAttribute("exception", asTypeOf.TypeToGet);
                            }
                        }
                        WriteContractElement(member, contractElement, "requires", GetDescriptionAttribute(contractElement), exceptionAttribute);
                    }
                    foreach (IPostcondition contractElement in methodContract.Postconditions)
                    {
                        Contract.Assume(contractElement != null, "lack of contracts for collections");
                        WriteContractElement(member, contractElement, "ensures", GetDescriptionAttribute(contractElement));
                    }
                    foreach (IThrownException thrownException in methodContract.ThrownExceptions)
                    {
                        Contract.Assume(thrownException != null, "lack of contracts for collections");
                        Contract.Assume(thrownException.Postcondition != null, "lack of CCI2 contracts");
                        WriteContractElement(member, thrownException.Postcondition, "ensuresOnThrow", GetDescriptionAttribute(thrownException.Postcondition), GetTypeAttribute("exception", thrownException.ExceptionType));
                    }
                }
                //Add contract information into the summary element
                else
                {
                    XElement summaryElement = GetSummaryElement(member);

                    summaryElement.Add(new XElement("para", "Requires: "));
                    foreach (IContractElement contractElement in methodContract.Preconditions)
                    {
                        Contract.Assume(contractElement != null, "lack of contracts for collections");
                        WriteContractElementToSummary(summaryElement, contractElement);
                    }

                    summaryElement.Add(new XElement("para", "Ensures: "));
                    foreach (IContractElement contractElement in methodContract.Postconditions)
                    {
                        Contract.Assume(contractElement != null, "lack of contracts for collections");
                        WriteContractElementToSummary(summaryElement, contractElement);
                    }

                    summaryElement.Add(new XElement("para", "EnsuresOnThrow: "));
                    foreach (ThrownException thrownException in methodContract.ThrownExceptions)
                    {
                        Contract.Assume(thrownException != null, "lack of contracts for collections");
                        Contract.Assume(thrownException.Postcondition != null, "lack of contracts for CCI2");
                        Contract.Assume(thrownException.ExceptionType != null, "lack of contracts for CCI2");
                        WriteContractElementToSummary(summaryElement, thrownException.Postcondition, thrownException.ExceptionType.ToString());
                    }

                    WriteContractElementsToReleventParameters(member, methodDefinition, methodContract);
                }
            }

            base.Visit(methodDefinition);
        }
Exemple #39
0
        bool IsSetter(IMethodDefinition methodDefinition)
        {
            Contract.Requires(methodDefinition != null);

            return(methodDefinition.IsSpecialName && methodDefinition.Name.Value.StartsWith("set_"));
        }
Exemple #40
0
        public bool ShouldForwardNamespaceScopes(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, out IMethodDefinition forwardToMethod)
        {
            if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody))
            {
                // SerializeNamespaceScopeMetadata will do the actual forwarding in case this is a CSharp method.
                // VB on the other hand adds a "@methodtoken" to the scopes instead.
                if (context.Module.GenerateVisualBasicStylePdb)
                {
                    forwardToMethod = _previousMethodBodyWithUsingInfo.MethodDefinition;
                }
                else
                {
                    forwardToMethod = null;
                }

                return(true);
            }

            _previousMethodBodyWithUsingInfo = methodBody;
            _previousMethodWithUsingInfo     = methodHandle;
            forwardToMethod = null;
            return(false);
        }
Exemple #41
0
 internal PdbLocalConstant(PdbConstant pdbConstant, IMetadataHost host, IMethodDefinition methodDefinition)
 {
     this.pdbConstant      = pdbConstant;
     this.host             = host;
     this.methodDefinition = methodDefinition;
 }