Ejemplo n.º 1
0
        internal DeclarationUnifier(SourceMethodBody sourceMethodBody)
        {
            Contract.Requires(sourceMethodBody != null);

              this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(this.numberOfReferencesToLocal != null);
              this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(this.numberOfAssignmentsToLocal != null);
        }
Ejemplo n.º 2
0
    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;
          }
        }
      }
    }
Ejemplo n.º 3
0
 public static IBlockStatement RemoveCachedDelegates(IMetadataHost host, IBlockStatement blockStatement, SourceMethodBody sourceMethodBody)
 {
     var finder = new FindAssignmentToCachedDelegateStaticFieldOrLocal(sourceMethodBody);
       finder.Traverse(blockStatement);
       if (finder.cachedDelegateFieldsOrLocals.Count == 0) return blockStatement;
       var mutator = new CachedDelegateRemover(host, finder.cachedDelegateFieldsOrLocals);
       return mutator.Visit(blockStatement);
 }
Ejemplo n.º 4
0
		internal ResourceUseReplacer(SourceMethodBody sourceMethodBody)
		{
			Contract.Requires(sourceMethodBody != null);
			this.host = sourceMethodBody.host;
            Contract.Assume(sourceMethodBody.host != null);
            this.IDisposable = CreateTypeReference(
                host,
                new Microsoft.Cci.MutableCodeModel.AssemblyReference() { AssemblyIdentity = this.host.CoreAssemblySymbolicIdentity, }, "System.IDisposable");
        }
Ejemplo n.º 5
0
 internal PatternReplacer(SourceMethodBody sourceMethodBody, BlockStatement block) {
   Contract.Requires(sourceMethodBody != null);
   Contract.Requires(block != null);
   this.host = sourceMethodBody.host; Contract.Assume(this.host != null);
   this.nameTable = this.host.NameTable;
   this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
   this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(this.numberOfAssignmentsToLocal != null);
   this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(this.numberOfReferencesToLocal != null);
   this.bindingsThatMakeALastUseOfALocalVersion = sourceMethodBody.bindingsThatMakeALastUseOfALocalVersion; Contract.Assume(this.bindingsThatMakeALastUseOfALocalVersion != null);
   this.singleAssignmentReferenceFinder = new SingleAssignmentSingleReferenceFinder(this.bindingsThatMakeALastUseOfALocalVersion, this.numberOfReferencesToLocal);
   this.singleAssignmentLocalReplacer = new SingleAssignmentLocalReplacer(this.host, this.bindingsThatMakeALastUseOfALocalVersion, this.numberOfAssignmentsToLocal);
   this.sourceLocationProvider = sourceMethodBody.sourceLocationProvider;
   this.singleUseExpressionChecker = new SingleUseExpressionChecker();
   Contract.Assume(sourceMethodBody.ilMethodBody != null);
   this.isVoidMethod = sourceMethodBody.ilMethodBody.MethodDefinition.Type.TypeCode == PrimitiveTypeCode.Void;
   while (block != null) {
     var n = block.Statements.Count;
     if (n > 0) {
       var nestedBlock = block.Statements[n-1] as BlockStatement;
       if (nestedBlock != null) { block = nestedBlock; continue; }
     }
     if (n >= 2) { // && sourceMethodBody.ilMethodBody.MethodDefinition.Type.TypeCode != PrimitiveTypeCode.Void) {
       var labeledStatement = block.Statements[n-2] as LabeledStatement;
       if (labeledStatement == null && n >= 3 && block.Statements[n-2] is EmptyStatement) {
         labeledStatement = block.Statements[n-3] as LabeledStatement;
       }
       var returnStatement = block.Statements[n-1] as ReturnStatement;
       if (labeledStatement != null && returnStatement != null) {
         if (sourceMethodBody.ilMethodBody.MethodDefinition.Type.TypeCode != PrimitiveTypeCode.Void) {
           var boundExpression = returnStatement.Expression as BoundExpression;
           if (boundExpression != null) {
             this.returnValueTemp = boundExpression.Definition as ILocalDefinition;
             if (this.returnValueTemp != null) {
               bool isCompilerGenerated = false;
               if (this.sourceLocationProvider != null)
                 this.sourceLocationProvider.GetSourceNameFor(this.returnValueTemp, out isCompilerGenerated);
               if (isCompilerGenerated) {
                 this.labelOfFinalReturn = labeledStatement.Label;
                 this.finalBlock = block;
               } else {
                 this.returnValueTemp = null;
               }
             }
           }
         } else {
           this.labelOfFinalReturn = labeledStatement.Label;
         }
       }
     }
     block = null; //TODO: putting a return here causes Clousot to conclude that the object invariant is never reached.
   }
 }
Ejemplo n.º 6
0
        private Unstacker(SourceMethodBody sourceMethodBody)
            : base(sourceMethodBody.host)
        {
            Contract.Requires(sourceMethodBody != null);
            Contract.Assume(sourceMethodBody.host != null);
            this.sourceLocationProvider = sourceMethodBody.sourceLocationProvider;

            this.locals = new Stack<ILocalDefinition>();
            this.methodDefinition = sourceMethodBody.MethodDefinition;
            this.createdLocals = new Dictionary<Tuple<int, uint>, ILocalDefinition>();

            this.systemBool = this.host.PlatformType.SystemBoolean;
            this.systemInt32 = this.host.PlatformType.SystemInt32;
        }
Ejemplo n.º 7
0
 internal void Traverse(SourceMethodBody body, BasicBlock rootBlock)
 {
     this.Traverse(rootBlock);
       //Now add declarations for any locals declared only on the body (for example temporary variables introduced by Unstacker).
       List<IStatement> prelude = new List<IStatement>();
       var localsAndTemps = body.localVariablesAndTemporaries;
       this.AddDeclarationsWithInitialValues(localsAndTemps, rootBlock);
       foreach (var localDef in localsAndTemps) {
     if (this.declaredLocals.ContainsKey(localDef)) continue;
     LocalDeclarationStatement localDecl = new LocalDeclarationStatement();
     localDecl.LocalVariable = localDef;
     prelude.Add(localDecl);
       }
       if (prelude.Count > 0)
     rootBlock.Statements.InsertRange(0, prelude); //TODO: use pdb info to insert them in the same order they appear in the source
 }
 internal RemoveBranchConditionLocals(SourceMethodBody sourceMethodBody)
 {
     this.sourceMethodBody = sourceMethodBody;
       var ops = new List<IOperation>(sourceMethodBody.ilMethodBody.Operations);
       foreach (var local in sourceMethodBody.localVariablesAndTemporaries) {
     if (local.Type.TypeCode != PrimitiveTypeCode.Boolean) continue;
     int i = 0;
     int n = ops.Count;
     while (i < n) {
       if (IsLoadLocalOp(ops[i].OperationCode) && 0 < i && ops[i].Value == local) {
     if (!IsStoreLocalOp(ops[i - 1].OperationCode)) break;
       }
       i++;
     }
     if (i == n) this.branchConditionLocals.Add(local, true);
       }
 }
Ejemplo n.º 9
0
            public override void Traverse(IMethodBody methodBody)
            {
                PrintToken(CSharpToken.LeftCurly);

                ISourceMethodBody/*?*/ sourceMethodBody = methodBody as ISourceMethodBody;
                if (sourceMethodBody == null)
                {
                    var options = DecompilerOptions.Loops;
                    if (!printCompilerGeneratedMembers)
                        options |= (DecompilerOptions.AnonymousDelegates | DecompilerOptions.Iterators);
                    sourceMethodBody = new SourceMethodBody(methodBody, host, pdbReader, pdbReader, options);
                }
                if (noIL)
                    Traverse(sourceMethodBody.Block.Statements);
                else
                {
                   // this.Traverse(sourceMethodBody.Block);
                  //  PrintToken(CSharpToken.NewLine);

                    if (pdbReader != null)
                        PrintScopes(methodBody);
                    else
                        PrintLocals(methodBody.LocalVariables);

                    int currentIndex = -1; // a number no index matches
                    foreach (IOperation operation in methodBody.Operations)
                    {
                        if (pdbReader != null)
                        {
                            foreach (IPrimarySourceLocation psloc in pdbReader.GetPrimarySourceLocationsFor(operation.Location))
                            {
                                if (psloc.StartIndex != currentIndex)
                                {
                                    PrintSourceLocation(psloc);
                                    currentIndex = psloc.StartIndex;
                                }
                            }
                        }
                        PrintOperation(operation);
                    }
                }

                PrintToken(CSharpToken.RightCurly);
            }
Ejemplo n.º 10
0
    internal LockReplacer(SourceMethodBody sourceMethodBody) {
      Contract.Requires(sourceMethodBody != null);
      this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
      this.sourceLocationProvider = sourceMethodBody.sourceLocationProvider;
      this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(sourceMethodBody.numberOfReferencesToLocal != null);
      this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(sourceMethodBody.numberOfAssignmentsToLocal != null);
      this.bindingsThatMakeALastUseOfALocalVersion = sourceMethodBody.bindingsThatMakeALastUseOfALocalVersion; Contract.Assume(sourceMethodBody.bindingsThatMakeALastUseOfALocalVersion != null);
      var systemThreading = new Immutable.NestedUnitNamespaceReference(this.host.PlatformType.SystemObject.ContainingUnitNamespace,
        this.host.NameTable.GetNameFor("Threading"));
      var systemThreadingMonitor = new Immutable.NamespaceTypeReference(this.host, systemThreading, this.host.NameTable.GetNameFor("Monitor"), 0,
        isEnum: false, isValueType: false, typeCode: PrimitiveTypeCode.NotPrimitive);
      var parameters = new IParameterTypeInformation[2];
      this.monitorEnter = new MethodReference(this.host, systemThreadingMonitor, CallingConvention.Default, this.host.PlatformType.SystemVoid,
        this.host.NameTable.GetNameFor("Enter"), 0, parameters);
      parameters[0] = new SimpleParameterTypeInformation(monitorEnter, 0, this.host.PlatformType.SystemObject);
      parameters[1] = new SimpleParameterTypeInformation(monitorEnter, 1, this.host.PlatformType.SystemBoolean, isByReference: true);
      this.monitorExit = new MethodReference(this.host, systemThreadingMonitor, CallingConvention.Default, this.host.PlatformType.SystemVoid,
        this.host.NameTable.GetNameFor("Exit"), 0, this.host.PlatformType.SystemObject);

    }
Ejemplo n.º 11
0
    internal TryCatchReplacer(SourceMethodBody sourceMethodBody, DecompiledBlock block) {
      Contract.Requires(sourceMethodBody != null);
      Contract.Requires(block != null);
      this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
      this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
      this.unconditionalBranchRemover.gotosThatTarget = sourceMethodBody.gotosThatTarget;

      Contract.Assume(sourceMethodBody.ilMethodBody != null);
      foreach (var exInfo in sourceMethodBody.ilMethodBody.OperationExceptionInformation) {
        var tryCatchF = this.tryCatchFinallyMap.Find(exInfo.TryStartOffset, exInfo.TryEndOffset);
        if (tryCatchF == null) {
          tryCatchF = new TryCatchFinallyStatement();
          this.tryCatchFinallyMap.Add(exInfo.TryStartOffset, exInfo.TryEndOffset, tryCatchF);
        }        
        if (exInfo.HandlerKind == HandlerKind.Filter) {
          this.tryCatchFinallyMap.Add(exInfo.FilterDecisionStartOffset, exInfo.HandlerEndOffset, tryCatchF); 
          this.handlerMap.Add(exInfo.FilterDecisionStartOffset, exInfo.HandlerEndOffset, exInfo); 
        }
        this.tryCatchFinallyMap.Add(exInfo.HandlerStartOffset, exInfo.HandlerEndOffset, tryCatchF);
        this.handlerMap.Add(exInfo.HandlerStartOffset, exInfo.HandlerEndOffset, exInfo); 
      }
    }
Ejemplo n.º 12
0
 public static IBlockStatement GetRidOfStack(SourceMethodBody methodBody, IBlockStatement block)
 {
     var me = new Unstacker(methodBody);
     var result = me.Rewrite(block);
     var stmts = new List<IStatement>();
     foreach (var loc in me.createdLocals.Values)
     {
         var decl = new LocalDeclarationStatement()
         {
             InitialValue = null,
             LocalVariable = loc,
         };
         stmts.Add(decl);
     }
     stmts.AddRange(result.Statements);
     var newBlock = new BlockStatement()
     {
         Statements = stmts,
         Locations = new List<ILocation>(result.Locations),
     };
     return newBlock;
 }
Ejemplo n.º 13
0
 internal WhileLoopReplacer(SourceMethodBody sourceMethodBody) {
   Contract.Requires(sourceMethodBody != null);
   this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
   this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Returns a method whose body is empty, but which can be replaced with the real body when it is
        /// available.
        /// </summary>
        /// <remarks>
        /// Public because it needs to get called when an anonymous delegate is encountered
        /// while translating a method body. Just mapping the anonymous delegate doesn't
        /// provide the information needed. The parameters of a method reference are not
        /// IParameterDefinitions.
        /// </remarks>
        public MethodDefinition TranslateMetadata(R.IMethodSymbol methodSymbol)
        {
            Contract.Requires(methodSymbol != null);
            Contract.Ensures(Contract.Result <MethodDefinition>() != null);

            var containingType = (ITypeDefinition)this.typeSymbolCache[methodSymbol.ContainingType];
            var isConstructor  = methodSymbol.MethodKind == R.CommonMethodKind.Constructor;
            List <IParameterDefinition> parameters = new List <IParameterDefinition>();

            var m = new MethodDefinition()
            {
                CallingConvention        = methodSymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis,
                ContainingTypeDefinition = containingType,
                InternFactory            = this.host.InternFactory,
                IsHiddenBySignature      = true,               // REVIEW
                IsNewSlot        = containingType.IsInterface, // REVIEW
                IsRuntimeSpecial = isConstructor,
                IsSpecialName    = isConstructor,
                IsStatic         = methodSymbol.IsStatic,
                IsVirtual        = containingType.IsInterface, // REVIEW: Why doesn't using methodSymbol.Virtual work for interface methods?
                Locations        = Helper.WrapLocations(methodSymbol.Locations),
                Name             = this.nameTable.GetNameFor(methodSymbol.Name),
                Parameters       = parameters,
                Type             = this.Map(methodSymbol.ReturnType),
                Visibility       = this.Map(methodSymbol.DeclaredAccessibility),
            };

            // IMPORTANT: Have to add it to the cache before doing anything else because it may
            // get looked up if it is generic and a parameter's type involves the generic
            // method parameter.
            this.methodSymbolCache.Add(methodSymbol, m);

            #region Define the generic parameters
            if (methodSymbol.IsGenericMethod)
            {
                var genericParameters = new List <IGenericMethodParameter>();
                foreach (var gp in methodSymbol.TypeParameters)
                {
                    var gp2 = this.CreateTypeDefinition(gp);
                    genericParameters.Add((IGenericMethodParameter)gp2);
                }
                m.GenericParameters = genericParameters;
            }
            #endregion

            #region Define the parameters
            ushort i = 0;
            foreach (var p in methodSymbol.Parameters)
            {
                var p_prime = new ParameterDefinition()
                {
                    ContainingSignature = m,
                    IsByReference       = p.RefKind == RefKind.Ref,
                    IsIn  = p.RefKind == RefKind.None,
                    IsOut = p.RefKind == RefKind.Out,
                    Name  = nameTable.GetNameFor(p.Name),
                    Type  = this.Map(p.Type),
                    Index = i++,
                };
                parameters.Add(p_prime);
            }
            #endregion Define the parameters

            #region Define default ctor, if needed
            if (/*methodSymbol.IsSynthesized &&*/ isConstructor) // BUGBUG!!
            {
                m.IsHiddenBySignature = true;
                m.IsRuntimeSpecial    = true;
                m.IsSpecialName       = true;
                var statements = new List <IStatement>();
                var body       = new SourceMethodBody(this.host, null, null)
                {
                    LocalsAreZeroed = true,
                    Block           = new BlockStatement()
                    {
                        Statements = statements
                    },
                };
                var thisRef = new ThisReference()
                {
                    Type = containingType,
                };
                // base();
                foreach (var baseClass in containingType.BaseClasses)
                {
                    var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference()
                    {
                        CallingConvention     = CallingConvention.HasThis,
                        ContainingType        = baseClass,
                        GenericParameterCount = 0,
                        InternFactory         = this.host.InternFactory,
                        Name = nameTable.Ctor,
                        Type = this.host.PlatformType.SystemVoid,
                    };
                    statements.Add(
                        new ExpressionStatement()
                    {
                        Expression = new MethodCall()
                        {
                            MethodToCall = baseCtor,
                            IsStaticCall = false,                             // REVIEW: Is this needed in addition to setting the ThisArgument?
                            ThisArgument = thisRef,
                            Type         = this.host.PlatformType.SystemVoid, // REVIEW: Is this the right way to do this?
                            Arguments    = new List <IExpression>(),
                        }
                    }
                        );
                    break;
                }
                // return;
                statements.Add(new ReturnStatement());
                body.MethodDefinition = m;
                m.Body = body;
            }
            #endregion

            return(m);
        }
Ejemplo n.º 15
0
		internal ForEachLoopReplacer(SourceMethodBody sourceMethodBody)
		{
			Contract.Requires(sourceMethodBody != null);
			this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
		}
Ejemplo n.º 16
0
 internal UnreferencedLabelRemover(SourceMethodBody sourceMethodBody) {
   Contract.Requires(sourceMethodBody != null);
   this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
   this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(this.numberOfAssignmentsToLocal != null);
   this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(this.numberOfReferencesToLocal != null);
 }
Ejemplo n.º 17
0
 internal UnreferencedLabelRemover(SourceMethodBody methodBody)
 {
     this.methodBody = methodBody;
 }
Ejemplo n.º 18
0
        private IExpression ConvertToAnonymousDelegate(CreateDelegateInstance createDelegateInstance, bool iteratorsHaveNotBeenDecompiled)
        {
            IMethodDefinition closureMethod = createDelegateInstance.MethodToCallViaDelegate.ResolvedMethod;
              if (this.sourceMethodBody.privateHelperMethodsToRemove == null) this.sourceMethodBody.privateHelperMethodsToRemove = new Dictionary<uint, IMethodDefinition>();
              IMethodBody closureMethodBody = UnspecializedMethods.GetMethodBodyFromUnspecializedVersion(closureMethod);
              AnonymousDelegate anonDel = new AnonymousDelegate();
              anonDel.CallingConvention = closureMethod.CallingConvention;
              var unspecializedClosureMethod = UnspecializedMethods.UnspecializedMethodDefinition(closureMethod);
              this.sourceMethodBody.privateHelperMethodsToRemove[unspecializedClosureMethod.InternedKey] = unspecializedClosureMethod;
              anonDel.Parameters = new List<IParameterDefinition>(unspecializedClosureMethod.Parameters);
              for (int i = 0, n = anonDel.Parameters.Count; i < n; i++) {
            IParameterDefinition closureMethodPar = UnspecializedParameterDefinition(anonDel.Parameters[i]);
            ParameterDefinition par = new ParameterDefinition();
            this.parameterMap.Add(closureMethodPar, par);
            par.Copy(closureMethodPar, this.host.InternFactory);
            par.ContainingSignature = anonDel;
            anonDel.Parameters[i] = par;
              }
              var alreadyDecompiledBody = closureMethodBody as SourceMethodBody;
              ISourceMethodBody anonDelSourceMethodBody = alreadyDecompiledBody;
              if (alreadyDecompiledBody == null) {
            var alreadyDecompiledBody2 = closureMethodBody as Microsoft.Cci.MutableCodeModel.SourceMethodBody;
            if (alreadyDecompiledBody2 == null) {
              var smb = new SourceMethodBody(closureMethodBody, this.sourceMethodBody.host,
            this.sourceMethodBody.sourceLocationProvider, this.sourceMethodBody.localScopeProvider, this.sourceMethodBody.options);
              anonDelSourceMethodBody = smb;
              anonDel.Body = smb.Block;
            } else {
              anonDel.Body = alreadyDecompiledBody2.Block;
              anonDelSourceMethodBody = alreadyDecompiledBody2;
            }
              } else {
            anonDel.Body = alreadyDecompiledBody.Block;
              }

              anonDel.ReturnValueIsByRef = closureMethod.ReturnValueIsByRef;
              if (closureMethod.ReturnValueIsModified)
            anonDel.ReturnValueCustomModifiers = new List<ICustomModifier>(closureMethod.ReturnValueCustomModifiers);
              anonDel.ReturnType = closureMethod.Type;
              anonDel.Type = createDelegateInstance.Type;

              if (iteratorsHaveNotBeenDecompiled && unspecializedClosureMethod.ContainingTypeDefinition.IsGeneric &&
            unspecializedClosureMethod.ContainingTypeDefinition.GenericParameterCount ==
            this.sourceMethodBody.MethodDefinition.ContainingTypeDefinition.GenericParameterCount) {
            var mapper = new GenericTypeParameterMapper(this.host, this.sourceMethodBody.MethodDefinition.ContainingTypeDefinition,
              unspecializedClosureMethod.ContainingTypeDefinition);
            mapper.Rewrite(anonDel);
              }

              BlockStatement bs = anonDel.Body as BlockStatement;
              if (bs != null) {
            var savedReferencedLabels = this.referencedLabels;
            this.referencedLabels = null;
            anonDel.Body = this.RemoveCompilationArtifacts(bs);
            this.referencedLabels = savedReferencedLabels;
              }
              IExpression result = anonDel;

              if (this.sourceMethodBody.MethodDefinition.IsGeneric) {
            if (unspecializedClosureMethod.IsGeneric)
              this.genericParameterMapper = new GenericMethodParameterMapper(this.host, this.sourceMethodBody.MethodDefinition, unspecializedClosureMethod);
            // If the closure method was not generic, then its containing type is generic
            // and the generic parameter mapper was created when the closure instance creation
            // was discovered at the beginning of this visitor.
            if (this.genericParameterMapper != null) {
              result = this.genericParameterMapper.Visit(result);
              foreach (var v in this.capturedBinding.Values) {
            // Do NOT visit any of the parameters in the table because that
            // will cause them to (possibly) have their types changed. But
            // they already have the correct type because they are parameters
            // of the enclosing method.
            // But the locals are ones that were created by this visitor so
            // they need their types updated.
            LocalDefinition ld = v.Definition as LocalDefinition;
            if (ld != null) {
              ld.Type = this.genericParameterMapper.Visit(ld.Type);
              ld.MethodDefinition = this.sourceMethodBody.MethodDefinition;
            }
              }
            }
              }

              return result;
        }
Ejemplo n.º 19
0
        private NamespaceTypeDefinition CreateContractReferenceAssemblyAttribute(IRootUnitNamespace rootNs)
        {
            var internFactory = this.host.InternFactory;
            var nameTable     = this.host.NameTable;

            var contractReferenceAssemblyAttributeName = nameTable.GetNameFor("ContractReferenceAssemblyAttribute");
            var contractNamespaceName = nameTable.GetNameFor("System.Diagnostics.Contracts");

            #region Define type
            CustomAttribute compilerGeneratedAttribute = new CustomAttribute()
            {
                Constructor = new Microsoft.Cci.MethodReference(
                    this.host,
                    this.compilerGeneratedAttributeType,
                    CallingConvention.HasThis,
                    this.systemVoidType,
                    this.host.NameTable.Ctor,
                    0)
            };

            var contractsNs = new NestedUnitNamespace()
            {
                ContainingUnitNamespace = rootNs,
                Name = contractNamespaceName,
            };
            NamespaceTypeDefinition result = new NamespaceTypeDefinition()
            {
                Name       = contractReferenceAssemblyAttributeName,
                Attributes = new List <ICustomAttribute> {
                    compilerGeneratedAttribute
                },
                BaseClasses = new List <ITypeReference> {
                    this.systemAttributeType
                },
                ContainingUnitNamespace = contractsNs, //unitNamespace,
                InternFactory           = internFactory,
                IsBeforeFieldInit       = true,
                IsClass      = true,
                IsSealed     = true,
                Methods      = new List <IMethodDefinition>(),
                Layout       = LayoutKind.Auto,
                StringFormat = StringFormatKind.Ansi,
            };
            contractsNs.Members.Add(result);
            this.allTypes.Add(result);
            #endregion Define type
            #region Define the ctor
            List <IStatement> statements = new List <IStatement>();
            SourceMethodBody  body       = new SourceMethodBody(this.host)
            {
                LocalsAreZeroed = true,
                Block           = new BlockStatement()
                {
                    Statements = statements
                },
            };
            MethodDefinition ctor = new MethodDefinition()
            {
                Body = body,
                CallingConvention        = CallingConvention.HasThis,
                ContainingTypeDefinition = result,
                InternFactory            = internFactory,
                IsRuntimeSpecial         = true,
                IsStatic      = false,
                IsSpecialName = true,
                Name          = nameTable.Ctor,
                Type          = this.systemVoidType,
                Visibility    = TypeMemberVisibility.Public,
            };
            body.MethodDefinition = ctor;
            var thisRef = new ThisReference()
            {
                Type = result,
            };
            // base();
            foreach (var baseClass in result.BaseClasses)
            {
                var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference()
                {
                    CallingConvention     = CallingConvention.HasThis,
                    ContainingType        = baseClass,
                    GenericParameterCount = 0,
                    InternFactory         = this.host.InternFactory,
                    Name = nameTable.Ctor,
                    Type = this.systemVoidType,
                };
                statements.Add(
                    new ExpressionStatement()
                {
                    Expression = new MethodCall()
                    {
                        MethodToCall = baseCtor,
                        IsStaticCall = false, // REVIEW: Is this needed in addition to setting the ThisArgument?
                        ThisArgument = new ThisReference()
                        {
                            Type = result,
                        },
                        Type      = this.systemVoidType, // REVIEW: Is this the right way to do this?
                        Arguments = new List <IExpression>(),
                    }
                }
                    );
                break;
            }

            // return;
            statements.Add(new ReturnStatement());
            result.Methods.Add(ctor);
            #endregion Define the ctor
            return(result);
        }
Ejemplo n.º 20
0
 internal CompilationArtifactRemover(SourceMethodBody sourceMethodBody, bool restoreAnonymousDelegates)
     : base(sourceMethodBody.host, true)
 {
     this.containingType = sourceMethodBody.ilMethodBody.MethodDefinition.ContainingTypeDefinition;
       this.sourceMethodBody = sourceMethodBody;
       this.restoreAnonymousDelegates = restoreAnonymousDelegates;
 }
Ejemplo n.º 21
0
 internal FindAssignmentToCachedDelegateStaticFieldOrLocal(SourceMethodBody sourceMethodBody)
 {
     this.sourceMethodBody = sourceMethodBody;
 }
 internal CompilationArtifactRemover(SourceMethodBody sourceMethodBody)
   : base(sourceMethodBody.host) {
   Contract.Requires(sourceMethodBody != null);
   this.numberOfAssignmentsToLocal = sourceMethodBody.numberOfAssignmentsToLocal; Contract.Assume(this.numberOfAssignmentsToLocal != null);
   this.numberOfReferencesToLocal = sourceMethodBody.numberOfReferencesToLocal; Contract.Assume(this.numberOfReferencesToLocal != null);
 }
Ejemplo n.º 23
0
 public static IEnumerable <IStatement> Statements(this SourceMethodBody methodBody)
 {
     return(methodBody.Block.Statements);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Visits the specified method body.
 /// </summary>
 /// <param name="methodBody">The method body.</param>
 /// <returns></returns>
 public override IMethodBody Visit(IMethodBody methodBody)
 {
     ISourceMethodBody sourceMethodBody = methodBody as ISourceMethodBody;
       if (sourceMethodBody != null) {
     SourceMethodBody mutableSourceMethodBody = new SourceMethodBody(this.host, this.sourceLocationProvider);
     mutableSourceMethodBody.Block = this.Visit(sourceMethodBody.Block);
     var currentMethod = this.GetCurrentMethod();
     // Visiting the block extracts the contract, but it gets associated with the immutable method
     if (this.contractProvider != null) {
       var methodDef = methodBody.MethodDefinition;
       IMethodContract/*?*/ methodContract = this.contractProvider.GetMethodContractFor(methodDef);
       if (methodContract != null)
     this.contractProvider.AssociateMethodWithContract(currentMethod, this.Visit(methodContract));
     }
     mutableSourceMethodBody.MethodDefinition = currentMethod;
     mutableSourceMethodBody.LocalsAreZeroed = methodBody.LocalsAreZeroed;
     return mutableSourceMethodBody;
       }
       return base.Visit(methodBody);
 }
Ejemplo n.º 25
0
 internal PatternDecompiler(SourceMethodBody sourceMethodBody, Dictionary<ILabeledStatement, List<IGotoStatement>> predecessors)
 {
     this.nameTable = sourceMethodBody.nameTable;
       this.sourceMethodBody = sourceMethodBody;
       this.predecessors = predecessors;
 }