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;
          }
        }
      }
    }
示例#2
0
        public static IModule RewriteModule(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider, IModule module)
        {
            var rew = new MyILRewriter(host, localScopeProvider, sourceLocationProvider);
            var me  = new RewriteStoreLocal(host, rew);

            return(me.Rewrite(module));
        }
示例#3
0
        public static IModule RewriteModule(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider, IModule module)
        {
            var m = new PropertyChangedWeaver(host);
            m._rewriter = new ReferenceReplacementRewriter(host, localScopeProvider, sourceLocationProvider);

            return m.Rewrite(module);
        }
示例#4
0
        /// <summary>
        /// Allocates a metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
        /// </summary>
        /// <param name="ilMethodBody">A method body whose IL operations should be decompiled into a block of statements that will be the
        /// result of the Block property of the resulting source method body.</param>
        /// <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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
        /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method.</param>
        /// <param name="options">Set of options that control decompilation.</param>
        public SourceMethodBody(IMethodBody ilMethodBody, IMetadataHost host, ISourceLocationProvider /*?*/ sourceLocationProvider,
                                ILocalScopeProvider /*?*/ localScopeProvider, DecompilerOptions options = DecompilerOptions.None)
            : base(host, sourceLocationProvider, localScopeProvider)
        {
            Contract.Requires(ilMethodBody != null);
            Contract.Requires(host != null);

            this.ilMethodBody           = ilMethodBody;
            this.host                   = host;
            this.nameTable              = host.NameTable;
            this.sourceLocationProvider = sourceLocationProvider;
            this.pdbReader              = sourceLocationProvider as PdbReader;
            this.localScopeProvider     = localScopeProvider;
            this.options                = options;
            this.platformType           = ilMethodBody.MethodDefinition.ContainingTypeDefinition.PlatformType;
            if (IteratorHelper.EnumerableIsNotEmpty(ilMethodBody.LocalVariables))
            {
                this.LocalsAreZeroed = ilMethodBody.LocalsAreZeroed;
            }
            else
            {
                this.LocalsAreZeroed = true;
            }
            this.MethodDefinition             = ilMethodBody.MethodDefinition;
            this.privateHelperFieldsToRemove  = null;
            this.privateHelperMethodsToRemove = null;
            this.privateHelperTypesToRemove   = null;
            this.cdfg = ControlAndDataFlowGraph <BasicBlock <Instruction>, Instruction> .GetControlAndDataFlowGraphFor(host, ilMethodBody, localScopeProvider);
        }
        private ControlFlowInferencer(IMetadataHost host, IMethodBody methodBody, ILocalScopeProvider /*?*/ localScopeProvider = null)
        {
            Contract.Requires(host != null);
            Contract.Requires(methodBody != null);

            this.platformType       = host.PlatformType;
            this.internFactory      = host.InternFactory;
            this.methodBody         = methodBody;
            this.localScopeProvider = localScopeProvider;

            int size = 1024;
            var ops  = methodBody.Operations as ICollection <IOperation>;

            if (ops != null)
            {
                size = ops.Count;
            }
            Hashtable <BasicBlock> blockFor   = new Hashtable <BasicBlock>((uint)size);
            List <BasicBlock>      allBlocks  = new List <BasicBlock>(size);
            List <BasicBlock>      rootBlocks = new List <BasicBlock>(1 + (int)IteratorHelper.EnumerableCount(methodBody.OperationExceptionInformation));

            this.successorEdges   = new List <BasicBlock>(size);
            this.cdfg             = new ControlAndDataFlowGraph <BasicBlock, Instruction>(methodBody, this.successorEdges, allBlocks, rootBlocks, blockFor);
            this.instructions     = new List <Instruction>(size);
            this.blocksThatTarget = new MultiHashtable <BasicBlock>((uint)size);
        }
示例#6
0
        private ILocalScopeProvider /*?*/ GetProvider(IMethodDefinition methodDefinition)
        {
            Contract.Requires(methodDefinition != null);

            if (methodDefinition == lastUsedMethod)
            {
                return(lastUsedProvider);
            }
            ILocalScopeProvider provider = null;
            var definingUnit             = TypeHelper.GetDefiningUnit(methodDefinition.ContainingTypeDefinition);

            this.unit2Provider.TryGetValue(definingUnit, out provider);
            if (provider != null)
            {
                this.lastUsedMethod   = methodDefinition;
                this.lastUsedProvider = provider;
                return(provider);
            }
            foreach (var location in methodDefinition.Locations)
            {
                var ilLocation = location as IILLocation;
                if (ilLocation == null || ilLocation.MethodDefinition == methodDefinition)
                {
                    continue;
                }
                return(this.GetProvider(ilLocation.MethodDefinition));
            }
            return(null);
        }
示例#7
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="host"></param>
    /// <param name="localScopeProvider"></param>
    /// <param name="sourceLocationProvider"></param>
    public ILRewriter(IMetadataHost host, ILocalScopeProvider/*?*/ localScopeProvider, ISourceLocationProvider/*?*/ sourceLocationProvider) {
      Contract.Requires(host != null);

      this.host = host;
      this.generator = new ILGenerator(host, Dummy.MethodDefinition);
      this.localScopeProvider = localScopeProvider;
      this.sourceLocationProvider = sourceLocationProvider;
    }
示例#8
0
    /// <summary>
    /// A rewriter for method bodies that inlines calls to methods identified by the rewriter client via a call back.
    /// </summary>
    /// <param name="host">An object representing the application that is hosting this mutator. 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="inlineSelector">
    /// Returns zero or more method definitions that should be inlined at a given call site. Zero methods means no inlining. For non virtual calls, one method means that the call
    /// should be inlined. For virtual calls, one or methods means that the call site should do call site type tests to avoid virtual calls for the returned methods.
    /// A subsequent call to ShouldInline, using one of the method definitions as the methodBeingCalled parameter can be used to determine if the call following the type test
    /// should be inline or not.
    /// </param>
    /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
    /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
    public Inliner(IMetadataHost host, ShouldInline inlineSelector, ILocalScopeProvider/*?*/ localScopeProvider, ISourceLocationProvider/*?*/ sourceLocationProvider) 
      : base(host, localScopeProvider, sourceLocationProvider) {
      Contract.Requires(host != null);
      Contract.Requires(inlineSelector != null);

      this.inlineSelector = inlineSelector;
      this.method = Dummy.MethodDefinition;
    }
示例#9
0
 /// <summary>
 /// Allocates a mutator that copies metadata models into mutable code models by using the base MetadataMutator class to make a mutable copy
 /// of a given metadata model and also replaces any method bodies with instances of SourceMethodBody, which implements the ISourceMethodBody.Block property
 /// by decompiling the metadata model information provided by the properties of IMethodBody.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting this mutator. 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="unit">The unit of metadata that will be mutated.</param>
 /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
 /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
 /// <param name="options">Set of options that control decompilation.</param>
 internal ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(IMetadataHost host, IUnit unit,
                                                                ISourceLocationProvider /*?*/ sourceLocationProvider, ILocalScopeProvider /*?*/ localScopeProvider, DecompilerOptions options)
 {
     this.localScopeProvider     = localScopeProvider;
     this.sourceLocationProvider = sourceLocationProvider;
     this.host    = host;
     this.options = options;
 }
示例#10
0
        public static IModule RewriteModule(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider, IModule module)
        {
            var m = new PropertyChangedWeaver(host);

            m._rewriter = new ReferenceReplacementRewriter(host, localScopeProvider, sourceLocationProvider);

            return(m.Rewrite(module));
        }
示例#11
0
文件: ILRewriter.cs 项目: xornand/cci
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        /// <param name="localScopeProvider"></param>
        /// <param name="sourceLocationProvider"></param>
        public ILRewriter(IMetadataHost host, ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
        {
            Contract.Requires(host != null);

            this.host                   = host;
            this.generator              = new ILGenerator(host, Dummy.MethodDefinition);
            this.localScopeProvider     = localScopeProvider;
            this.sourceLocationProvider = sourceLocationProvider;
        }
示例#12
0
        /// <summary>
        /// A rewriter for method bodies that inlines calls to methods identified by the rewriter client via a call back.
        /// </summary>
        /// <param name="host">An object representing the application that is hosting this mutator. 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="inlineSelector">
        /// Returns zero or more method definitions that should be inlined at a given call site. Zero methods means no inlining. For non virtual calls, one method means that the call
        /// should be inlined. For virtual calls, one or methods means that the call site should do call site type tests to avoid virtual calls for the returned methods.
        /// A subsequent call to ShouldInline, using one of the method definitions as the methodBeingCalled parameter can be used to determine if the call following the type test
        /// should be inline or not.
        /// </param>
        /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
        /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
        public Inliner(IMetadataHost host, ShouldInline inlineSelector, ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
            : base(host, localScopeProvider, sourceLocationProvider)
        {
            Contract.Requires(host != null);
            Contract.Requires(inlineSelector != null);

            this.inlineSelector = inlineSelector;
            this.method         = Dummy.MethodDefinition;
        }
示例#13
0
        /// <summary>
        /// Allocates a mutator that copies metadata models into mutable code models by using the base MetadataMutator class to make a mutable copy
        /// of a given metadata model and also replaces any method bodies with instances of SourceMethodBody, which implements the ISourceMethodBody.Block property
        /// by decompiling the metadata model information provided by the properties of IMethodBody.
        /// </summary>
        /// <param name="host">An object representing the application that is hosting this mutator. 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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
        /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
        /// <param name="options">Set of options that control decompilation.</param>
        internal ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(IMetadataHost host,
                                                                       ISourceLocationProvider /*?*/ sourceLocationProvider, ILocalScopeProvider /*?*/ localScopeProvider, DecompilerOptions options)
        {
            Contract.Requires(host != null);

            this.localScopeProvider     = localScopeProvider;
            this.sourceLocationProvider = sourceLocationProvider;
            this.host    = host;
            this.options = options;
        }
 public DynamicLoader(ISourceLocationProvider/*?*/ sourceLocationProvider, ILocalScopeProvider/*?*/ localScopeProvider) {
   this.sourceLocationProvider = sourceLocationProvider;
   this.localScopeProvider = localScopeProvider;
   this.emitter = new Emitter(this, sourceLocationProvider, localScopeProvider);
   this.initializingTraverser = new MetadataTraverser() { PostorderVisitor = this.emitter, TraverseIntoMethodBodies = true };
   this.typeBuilderAllocator = new TypeBuilderAllocater(this);
   this.typeCreator = new TypeCreator(this);
   this.memberBuilderAllocator = new MemberBuilderAllocator(this);
   this.mapper = new ReflectionMapper();
   this.builderMap = new Dictionary<object, object>();
 }
示例#15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cdfg"></param>
        /// <param name="ilGenerator"></param>
        /// <param name="localScopeProvider"></param>
        /// <param name="sourceLocationProvider"></param>
        public ControlFlowToMethodBodyConverter(ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ILGenerator ilGenerator,
                                                ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
        {
            Contract.Requires(cdfg != null);
            Contract.Requires(ilGenerator != null);

            this.cdfg                   = cdfg;
            this.ilGenerator            = ilGenerator;
            this.localScopeProvider     = localScopeProvider;
            this.sourceLocationProvider = sourceLocationProvider;
        }
示例#16
0
            internal ILConverter(ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ILGenerator ilGenerator,
                                 ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
                : base(cdfg, ilGenerator, localScopeProvider, sourceLocationProvider)
            {
                Contract.Requires(cdfg != null);
                Contract.Requires(ilGenerator != null);

                this.localFor                   = new Hashtable <object, GeneratorLocal>();
                this.redundantLocals            = new SetOfObjects();
                this.storesThatShouldBecomePops = new SetOfObjects();
                this.useCount                   = new Dictionary <ILocalDefinition, int>();
            }
示例#17
0
        public TestUtilMethodInjector(
            IMetadataHost host,
            ILocalScopeProvider localScopeProvider,
            ISourceLocationProvider sourceLocationProvider,
            IAssembly winbertCore)
            : base(host, localScopeProvider, sourceLocationProvider)
        {
            if (winbertCore == null)
            {
                throw new ArgumentNullException("winbertCore");
            }

            var testUtilDefinition = (INamespaceTypeDefinition)UnitHelper.FindType(host.NameTable, winbertCore, typeof(TestUtil).FullName);

            // AddMethodToDynamicCallGraph(string)
            this.AddMethodToDynamicCallGraphDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(AddMethodToDynamicCallGraphName),
                host.PlatformType.SystemString);

            // StartTest(string)
            this.StartTestWithNameDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(StartTestName),
                host.PlatformType.SystemString);

            // RecordVoidInstanceMethod(object, string)
             this.RecordVoidInstanceMethodDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(RecordVoidInstanceMethodCallName),
                host.PlatformType.SystemObject,
                host.PlatformType.SystemString);

            // RecordInstanceMethod(object, object, string)
            this.RecordInstanceMethodDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(RecordInstanceMethodCallName),
                host.PlatformType.SystemObject,
                host.PlatformType.SystemObject,
                host.PlatformType.SystemString);

            // EndTest()
            this.EndTestDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(EndTestName));

            // SaveResults(string)
            this.SaveResultsDefinition = TypeHelper.GetMethod(
                testUtilDefinition,
                host.NameTable.GetNameFor(SaveResultsName),
                host.PlatformType.SystemString);
        }
示例#18
0
        /// <summary>
        /// Returns zero or more local variable definitions that are local to the given scope.
        /// </summary>
        public IEnumerable <ILocalDefinition> GetVariablesInScope(ILocalScope scope)
        {
            ILocalScopeProvider /*?*/ provider = this.GetProvider(scope.MethodDefinition);

            if (provider == null)
            {
                return(Enumerable <ILocalDefinition> .Empty);
            }
            else
            {
                return(provider.GetVariablesInScope(scope));
            }
        }
示例#19
0
        /// <summary>
        /// Returns zero or more namespace scopes into which the namespace type containing the given method body has been nested.
        /// These scopes determine how simple names are looked up inside the method body. There is a separate scope for each dotted
        /// component in the namespace type name. For istance namespace type x.y.z will have two namespace scopes, the first is for the x and the second
        /// is for the y.
        /// </summary>
        public IEnumerable <INamespaceScope> GetNamespaceScopes(IMethodBody methodBody)
        {
            ILocalScopeProvider /*?*/ provider = this.GetProvider(methodBody.MethodDefinition);

            if (provider == null)
            {
                return(Enumerable <INamespaceScope> .Empty);
            }
            else
            {
                return(provider.GetNamespaceScopes(methodBody));
            }
        }
示例#20
0
        /// <summary>
        /// Returns zero or more local (block) scopes into which the CLR IL operations in the given method body is organized.
        /// </summary>
        public IEnumerable <ILocalScope> GetLocalScopes(IMethodBody methodBody)
        {
            ILocalScopeProvider /*?*/ provider = this.GetProvider(methodBody.MethodDefinition);

            if (provider == null)
            {
                return(IteratorHelper.GetEmptyEnumerable <ILocalScope>());
            }
            else
            {
                return(provider.GetLocalScopes(methodBody));
            }
        }
示例#21
0
        /// <summary>
        /// Returns zero or more local constant definitions that are local to the given scope.
        /// </summary>
        public IEnumerable <ILocalDefinition> GetConstantsInScope(ILocalScope scope)
        {
            ILocalScopeProvider /*?*/ provider = this.GetProvider(scope.MethodDefinition);

            if (provider == null)
            {
                return(IteratorHelper.GetEmptyEnumerable <ILocalDefinition>());
            }
            else
            {
                return(provider.GetConstantsInScope(scope));
            }
        }
示例#22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        /// <param name="cdfg"></param>
        /// <param name="cfgQueries"></param>
        /// <param name="localScopeProvider"></param>
        /// <param name="sourceLocationProvider"></param>
        public LocalMinimizer(IMetadataHost host,
                              ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ControlGraphQueries <BasicBlock, Instruction> cfgQueries,
                              ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
        {
            Contract.Requires(host != null);
            Contract.Requires(cdfg != null);
            Contract.Requires(cfgQueries != null);

            this.host = host;
            this.localScopeProvider     = localScopeProvider;
            this.sourceLocationProvider = sourceLocationProvider;
            this.cdfg       = cdfg;
            this.cfgQueries = cfgQueries;
        }
示例#23
0
        private ILocalScopeProvider /*?*/ GetProvider(IMethodDefinition methodDefinition)
        {
            if (methodDefinition == lastUsedMethod)
            {
                return(lastUsedProvider);
            }
            ILocalScopeProvider provider = null;
            var definingUnit             = TypeHelper.GetDefiningUnit(methodDefinition.ResolvedMethod.ContainingTypeDefinition);

            this.unit2Provider.TryGetValue(definingUnit, out provider);
            if (provider != null)
            {
                this.lastUsedMethod   = methodDefinition;
                this.lastUsedProvider = provider;
            }
            return(provider);
        }
示例#24
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: CDFG [path]fileName.ext");
                return;
            }

            using (var host = new DefaultWindowsRuntimeHost())
            {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(args[0]) as IModule;
                if (module == null || module is Dummy)
                {
                    Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Get a PDB reader if there is a PDB file.
                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = module.DebugInformationLocation;
                if (string.IsNullOrEmpty(pdbFile) || !File.Exists(pdbFile))
                {
                    pdbFile = Path.ChangeExtension(module.Location, "pdb");
                }
                if (File.Exists(pdbFile))
                {
                    using (var pdbStream = File.OpenRead(pdbFile))
                    {
                        pdbReader = new PdbReader(pdbStream, host);
                    }
                }
                using (pdbReader)
                {
                    ISourceLocationProvider sourceLocationProvider = pdbReader;
                    ILocalScopeProvider     localScopeProvider     = pdbReader;

                    var cdfgVisitor = new LoopFinderVisitor(host, pdbReader);
                    var traverser   = new MetadataTraverser();
                    traverser.TraverseIntoMethodBodies = true;
                    traverser.PreorderVisitor          = cdfgVisitor;
                    traverser.Traverse(module);
                }
            }
        }
示例#25
0
 public MyILRewriter(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider)
     : base(host, localScopeProvider, sourceLocationProvider)
 {
     #region Get reference to Console.WriteLine
     var nameTable            = host.NameTable;
     var platformType         = host.PlatformType;
     var systemString         = platformType.SystemString;
     var systemVoid           = platformType.SystemVoid;
     var SystemDotConsoleType =
         new Microsoft.Cci.Immutable.NamespaceTypeReference(
             host,
             systemString.ContainingUnitNamespace,
             nameTable.GetNameFor("Console"),
             0, false, false, true, PrimitiveTypeCode.NotPrimitive);
     this.consoleDotWriteLine = new Microsoft.Cci.MethodReference(
         host, SystemDotConsoleType,
         CallingConvention.Default,
         systemVoid,
         nameTable.GetNameFor("WriteLine"),
         0, systemString);
     #endregion Get reference to Console.WriteLine
 }
示例#26
0
    /// <summary>
    /// Allocates a metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
    /// </summary>
    /// <param name="ilMethodBody">A method body whose IL operations should be decompiled into a block of statements that will be the
    /// result of the Block property of the resulting source method body.</param>
    /// <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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
    /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method.</param>
    /// <param name="options">Set of options that control decompilation.</param>
    public SourceMethodBody(IMethodBody ilMethodBody, IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider,
      ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options = DecompilerOptions.None)
      : base(host, sourceLocationProvider, localScopeProvider) {
      Contract.Requires(ilMethodBody != null);
      Contract.Requires(host != null);

      this.ilMethodBody = ilMethodBody;
      this.host = host;
      this.nameTable = host.NameTable;
      this.sourceLocationProvider = sourceLocationProvider;
      this.pdbReader = sourceLocationProvider as PdbReader;
      this.localScopeProvider = localScopeProvider;
      this.options = options;
      this.platformType = ilMethodBody.MethodDefinition.ContainingTypeDefinition.PlatformType;
      if (IteratorHelper.EnumerableIsNotEmpty(ilMethodBody.LocalVariables))
        this.LocalsAreZeroed = ilMethodBody.LocalsAreZeroed;
      else
        this.LocalsAreZeroed = true;
      this.MethodDefinition = ilMethodBody.MethodDefinition;
      this.privateHelperFieldsToRemove = null;
      this.privateHelperMethodsToRemove = null;
      this.privateHelperTypesToRemove = null;
      this.cdfg = ControlAndDataFlowGraph<BasicBlock<Instruction>, Instruction>.GetControlAndDataFlowGraphFor(host, ilMethodBody, localScopeProvider);
    }
示例#27
0
 /// <summary>
 /// Allocates an object that provides a metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting this source method body. 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="sourceLocationProvider">An object that can map the ILocation objects found in the block of statements to IPrimarySourceLocation objects.  May be null.</param>
 /// <param name="localScopeProvider"></param>
 /// <param name="iteratorLocalCount">A map that indicates how many iterator locals are present in a given block. Only useful for generated MoveNext methods. May be null.</param>
 public SourceMethodBody(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider = null, ILocalScopeProvider/*?*/ localScopeProvider = null, IDictionary<IBlockStatement, uint>/*?*/ iteratorLocalCount = null) {
   this.host = host;
   this.sourceLocationProvider = sourceLocationProvider;
   this.localScopeProvider = localScopeProvider;
   this.iteratorLocalCount = iteratorLocalCount;
 }
    /// <summary>
    /// A local scope provider that can be used together with an object model that is a deep copy made by MetadataDeepCopier. It ensures that all
    /// metadata definitions obtained from the original ILocalScopeProvider have been mapped to their copies and does the reverse map before
    /// passing queries along to the original ILocalScopeProvider.
    /// </summary>
    /// <param name="mapFromCopyToOriginal">A map from copied definition objects to the original definitions from which the copies were constructed.</param>
    /// <param name="mapFromOriginalToCopy">A map from original definition objects to the copied definitions.</param>
    /// <param name="providerForOriginal">An ILocalScopeProvider associated with the original object model.</param>
    public CopiedLocalScopeProvider(Hashtable<object, object> mapFromCopyToOriginal, Hashtable<object, object> mapFromOriginalToCopy, ILocalScopeProvider providerForOriginal) {
      Contract.Requires(mapFromCopyToOriginal != null);
      Contract.Requires(mapFromOriginalToCopy != null);
      Contract.Requires(providerForOriginal != null);

      this.mapFromCopyToOriginal = mapFromCopyToOriginal;
      this.mapFromOriginalToCopy = mapFromOriginalToCopy;
      this.providerForOriginal = providerForOriginal;
    }
示例#29
0
        /// <summary>
        /// Constructs a control and data flow graph for the given method body.
        /// </summary>
        public static ControlAndDataFlowGraph <BasicBlock, Instruction> GetControlAndDataFlowGraphFor(IMetadataHost host, IMethodBody methodBody, ILocalScopeProvider /*?*/ localScopeProvider = null)
        {
            Contract.Requires(host != null);
            Contract.Requires(methodBody != null);
            Contract.Ensures(Contract.Result <ControlAndDataFlowGraph <BasicBlock, Instruction> >() != null);

            var cdfg = ControlFlowInferencer <BasicBlock, Instruction> .SetupControlFlow(host, methodBody, localScopeProvider);

            DataFlowInferencer <BasicBlock, Instruction> .SetupDataFlow(host, methodBody, cdfg);

            TypeInferencer <BasicBlock, Instruction> .FillInTypes(host, cdfg);

            return(cdfg);
        }
示例#30
0
        /// <summary>
        /// Called on dispose of this object.
        /// </summary>
        /// <param name="disposing">
        /// Was this method called from Dispose() or a finualizer?
        /// </param>
        private void OnDispose(bool disposing)
        {
            if (!this.IsDisposed)
            {
                if (disposing)
                {
                    // The host we're using is *likely* to be disposable, but check here anyhow.
                    var disposableHost = this.Host as System.IDisposable;
                    if (disposableHost != null)
                    {
                        disposableHost.Dispose();
                    }

                    if (this.PdbReader != null)
                    {
                        this.PdbReader.Dispose();
                    }

                    this.Host = null;
                    this.PdbReader = null;
                    this.MutableAssembly = null;
                    this.SourceLocationProvider = null;
                    this.localScopeProvider = null;
                }

                this.IsDisposed = true;
            }
        }
 public DCGMethodInjector(
     IMetadataHost host,
     ILocalScopeProvider localScopeProvider,
     ISourceLocationProvider sourceLocationProvider,
     IAssembly winbertCore)
     : base(host, localScopeProvider, sourceLocationProvider, winbertCore)
 {
 }
示例#32
0
 /// <summary>
 /// Allocates a mutator that copies metadata models into mutable code models by using the base MetadataMutator class to make a mutable copy
 /// of a given metadata model and also replaces any method bodies with instances of SourceMethodBody, which implements the ISourceMethodBody.Block property
 /// by decompiling the metadata model information provided by the properties of IMethodBody.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting this mutator. 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="unit">The unit of metadata that will be mutated.</param>
 /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
 /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
 /// <param name="options">Set of options that control decompilation.</param>
 internal ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(IMetadataHost host, IUnit unit,
     ISourceLocationProvider/*?*/ sourceLocationProvider, ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options)
 {
     this.localScopeProvider = localScopeProvider;
       this.sourceLocationProvider = sourceLocationProvider;
       this.host = host;
       this.options = options;
 }
示例#33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="targetHost">An object representing the application that will host the copies made by this copier.</param>
 /// <param name="sourceLocationProvider"></param>
 /// <param name="localScopeProvider"></param>
 public CodeDeepCopier(IMetadataHost targetHost, ISourceLocationProvider sourceLocationProvider = null, ILocalScopeProvider localScopeProvider = null)
   : this(targetHost, new CodeShallowCopier(targetHost, sourceLocationProvider, localScopeProvider)) {
   Contract.Requires(targetHost != null);
 }
示例#34
0
        /// <summary>
        /// A local scope provider that can be used together with an object model that is a deep copy made by MetadataDeepCopier. It ensures that all
        /// metadata definitions obtained from the original ILocalScopeProvider have been mapped to their copies and does the reverse map before
        /// passing queries along to the original ILocalScopeProvider.
        /// </summary>
        /// <param name="mapFromCopyToOriginal">A map from copied definition objects to the original definitions from which the copies were constructed.</param>
        /// <param name="mapFromOriginalToCopy">A map from original definition objects to the copied definitions.</param>
        /// <param name="providerForOriginal">An ILocalScopeProvider associated with the original object model.</param>
        public CopiedLocalScopeProvider(Hashtable <object, object> mapFromCopyToOriginal, Hashtable <object, object> mapFromOriginalToCopy, ILocalScopeProvider providerForOriginal)
        {
            Contract.Requires(mapFromCopyToOriginal != null);
            Contract.Requires(mapFromOriginalToCopy != null);
            Contract.Requires(providerForOriginal != null);

            this.mapFromCopyToOriginal = mapFromCopyToOriginal;
            this.mapFromOriginalToCopy = mapFromOriginalToCopy;
            this.providerForOriginal   = providerForOriginal;
        }
示例#35
0
 internal SeparateContractsFromCode(IContractAwareHost host, PdbReader/*?*/ pdbReader, ILocalScopeProvider/*?*/ localScopeProvider, ContractProvider contractProvider) {
   this.contractAwareHost = host;
   this.pdbReader = pdbReader;
   this.localScopeProvider = localScopeProvider;
   this.contractProvider = contractProvider;
   this.TraverseIntoMethodBodies = true;
 }
示例#36
0
 /// <summary>
 /// Allocates an object that provides a metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting this source method body. 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="sourceLocationProvider">An object that can map the ILocation objects found in the block of statements to IPrimarySourceLocation objects.  May be null.</param>
 /// <param name="localScopeProvider"></param>
 /// <param name="iteratorLocalCount">A map that indicates how many iterator locals are present in a given block. Only useful for generated MoveNext methods. May be null.</param>
 public SourceMethodBody(IMetadataHost host, ISourceLocationProvider /*?*/ sourceLocationProvider = null, ILocalScopeProvider /*?*/ localScopeProvider = null, IDictionary <IBlockStatement, uint> /*?*/ iteratorLocalCount = null)
 {
     this.host = host;
     this.sourceLocationProvider = sourceLocationProvider;
     this.localScopeProvider     = localScopeProvider;
     this.iteratorLocalCount     = iteratorLocalCount;
 }
示例#37
0
 /// <summary>
 /// Allocates a metadata (IL) representation along with a source level representation of the body of an iterator method/property/event accessor.
 /// </summary>
 /// <param name="iteratorMethodBody"> The method body of the iterator method, to which this MoveNextSourceMethodBody corresponds.</param>
 /// <param name="ilMethodBody">The method body of MoveNext whose IL operations should be decompiled into a block of statements that will be the
 /// result of the Block property of the resulting source method body. More importantly, the decompiled body for the original iterator method 
 /// is accessed by the TransformedBlock property.</param>
 /// <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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
 /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method.</param>
 /// <param name="options">Set of options that control decompilation.</param>
 public MoveNextSourceMethodBody(IMethodBody iteratorMethodBody, IMethodBody ilMethodBody, IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider, ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options = DecompilerOptions.None)
     : base(ilMethodBody, host, sourceLocationProvider, localScopeProvider, options)
 {
     this.iteratorMethodBody = iteratorMethodBody;
 }
示例#38
0
        public bool WriteSliceToFile(ISlice <MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, IAssemblyReference> slice, string directory, out string dll)
        {
#if TRACE_PERFORMANCE
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif

            var newAssembly = Prune.PruneAssembly(host, slice);

#if TRACE_PERFORMANCE
            Console.WriteLine("Time to prune the assembly: {0}", stopWatch.Elapsed);
#endif

            var errors = ValidateAssembly(host, newAssembly);
            if (/*errors != null && */ 0 < errors.Count)
            {
#if !DEBUG_SLICE
                dll = null;
                return(false);
#endif
            }

            //Get a PDB reader if there is a PDB file.
            PdbReader /*?*/ pdbReader = null;
            string          pdbFile   = slice.ContainingAssembly.ResolvedAssembly.DebugInformationLocation;
            if (string.IsNullOrEmpty(pdbFile) || !File.Exists(pdbFile))
            {
                pdbFile = Path.ChangeExtension(slice.ContainingAssembly.ResolvedAssembly.Location, "pdb");
            }
            if (File.Exists(pdbFile))
            {
                using (var pdbStream = File.OpenRead(pdbFile)) {
                    pdbReader = new PdbReader(pdbStream, host);
                }
            }
            using (pdbReader) {
                ISourceLocationProvider sourceLocationProvider = pdbReader;
                ILocalScopeProvider     localScopeProvider     = pdbReader;

                Contract.Assume(sourceLocationProvider != null, "why??");
                if (!MakeSureSliceHasAtLeastMethodSourceLocation(slice, sourceLocationProvider))
                {
                    dll = null;
                    return(false);
                }

                dll = Path.Combine(directory, slice.Name + ".dll");

#if TRACE_PERFORMANCE
                stopWatch.Reset();
#endif

                using (var peStream = File.Create(dll)) {
                    if (pdbReader == null)
                    {
                        PeWriter.WritePeToStream(newAssembly, host, peStream);
                    }
                    else
                    {
                        using (var pdbWriter = new PdbWriter(dll.Replace(".dll", ".pdb"), pdbReader, emitTokenSourceInfo: true)) {
                            PeWriter.WritePeToStream(newAssembly, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                        }
                    }
                }

#if TRACE_PERFORMANCE
                Console.WriteLine("Time spent to write on the disk: {0}", stopWatch.Elapsed);
#endif
            }

#if !DEBUG_SLICE
            if (errors != null && 0 < errors.Count)
            {
                using (var tw = new StreamWriter(File.Create(Path.Combine(directory, slice.Name + ".errors.txt"))))
                {
                    // something is performed asynchronously and may not be terminated here, that is wrong!
                    lock (errors)
                    {
                        foreach (var err in errors)
                        {
                            tw.WriteLine(err.Location);
                            foreach (var e in err.Errors)
                            {
                                tw.WriteLine("{0} {1} {2}", e.IsWarning ? "WARNING" : "ERROR ", e.Code, e.Message);
                            }
                            tw.WriteLine();
                        }
                    }
                }

                return(false);
            }
#endif

            // Can this be checked before writing it out?
            if (newAssembly.AssemblyReferences.Any(ar => ar.AssemblyIdentity.Equals(slice.ContainingAssembly.AssemblyIdentity)))
            {
            }

            return(true);
        }
示例#39
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="targetHost">An object representing the application that will host the copies made by this copier.</param>
 /// <param name="sourceLocationProvider"></param>
 /// <param name="localScopeProvider"></param>
 public CodeShallowCopier(IMetadataHost targetHost, ISourceLocationProvider sourceLocationProvider = null, ILocalScopeProvider localScopeProvider = null)
   : base(targetHost) {
   this.sourceLocationProvider = sourceLocationProvider;
   this.localScopeProvider = localScopeProvider;
 }
示例#40
0
 /// <summary>
 /// An object that can provide information about the local scopes of a method.
 /// </summary>
 /// <param name="originalLocalScopeProvider">The local scope provider to use for methods that have not been decompiled.</param>
 public LocalScopeProvider(ILocalScopeProvider originalLocalScopeProvider)
 {
     this.originalLocalScopeProvider = originalLocalScopeProvider;
 }
示例#41
0
 public ReferenceReplacementRewriter(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider)
     : base(host, localScopeProvider, sourceLocationProvider)
 {
 }
 public ReferenceReplacementRewriter(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider)
     : base(host, localScopeProvider, sourceLocationProvider)
 {
 }
示例#43
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        /// <param name="cdfg"></param>
        /// <param name="localScopeProvider"></param>
        /// <param name="sourceLocationProvider"></param>
        public StackEliminator(IMetadataHost host,
                               ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ILocalScopeProvider /*?*/ localScopeProvider, ISourceLocationProvider /*?*/ sourceLocationProvider)
        {
            Contract.Requires(host != null);
            Contract.Requires(cdfg != null);

            this.host = host;
            this.localScopeProvider     = localScopeProvider;
            this.sourceLocationProvider = sourceLocationProvider;
            this.cdfg = cdfg;
        }
        /// <summary>
        ///
        /// </summary>
        internal static ControlAndDataFlowGraph <BasicBlock, Instruction> SetupControlFlow(IMetadataHost host, IMethodBody methodBody, ILocalScopeProvider /*?*/ localScopeProvider = null)
        {
            Contract.Requires(host != null);
            Contract.Requires(methodBody != null);
            Contract.Ensures(Contract.Result <ControlAndDataFlowGraph <BasicBlock, Instruction> >() != null);

            var inferencer = new ControlFlowInferencer <BasicBlock, Instruction>(host, methodBody, localScopeProvider);

            return(inferencer.CreateBlocksAndEdges());
        }
 public DynamicMethod Load(IMethodDefinition method, bool skipVisibility) {
   var savedLocalScopeProvider = this.localScopeProvider;
   var savedSourceLocationProvider = this.sourceLocationProvider;
   this.localScopeProvider = null; //dynamic methods do not support debug info.
   this.sourceLocationProvider = null;
   var attributes = MemberBuilderAllocator.GetMethodAttributes(method);
   var callingConvention = MemberBuilderAllocator.GetCallingConvention(method.CallingConvention);
   var returnType = this.mapper.GetType(method.Type);
   var parameterTypes = new Type[method.ParameterCount];
   int i = 0;
   foreach (var parameter in method.Parameters)
     parameterTypes[i++] = this.mapper.GetType(parameter.Type);
   DynamicMethod dm = new DynamicMethod(method.Name.Value, attributes, callingConvention, returnType, parameterTypes, this.ModuleBuilder, skipVisibility);
   dm.InitLocals = method.Body.LocalsAreZeroed;
   this.emitter.EmitIL(dm.GetILGenerator(), method.Body);
   this.localScopeProvider = savedLocalScopeProvider;
   this.sourceLocationProvider = savedSourceLocationProvider;
   return dm;
 }
示例#46
0
        private static Module GetCodeModelFromMetadataModelHelper(IMetadataHost host, IModule module,
                                                                  ISourceLocationProvider /*?*/ sourceLocationProvider, ILocalScopeProvider /*?*/ localScopeProvider, DecompilerOptions options)
        {
            Contract.Requires(host != null);
            Contract.Requires(module != null);
            Contract.Requires(!(module is Dummy));
            Contract.Ensures(Contract.Result <Module>() != null);

            var result   = new MetadataDeepCopier(host).Copy(module);
            var replacer = new ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(host, sourceLocationProvider, localScopeProvider, options);

            replacer.Traverse(result);
            var finder = new HelperTypeFinder(host, sourceLocationProvider);

            finder.Traverse(result);
            Contract.Assume(finder.helperTypes != null);
            Contract.Assume(finder.helperMethods != null);
            Contract.Assume(finder.helperFields != null);
            var remover = new RemoveUnnecessaryTypes(finder.helperTypes, finder.helperMethods, finder.helperFields);

            remover.Traverse(result);
            result.AllTypes.RemoveAll(td => finder.helperTypes.ContainsKey(td.InternedKey)); // depends on RemoveAll preserving order
            return(result);
        }
示例#47
0
 /// <summary>
 /// An object that can provide information about the local scopes of a method.
 /// </summary>
 /// <param name="originalLocalScopeProvider">The local scope provider to use for methods that have not been decompiled.</param>
 public LocalScopeProvider(ILocalScopeProvider originalLocalScopeProvider)
 {
     Contract.Requires(originalLocalScopeProvider != null);
     this.originalLocalScopeProvider = originalLocalScopeProvider;
 }
示例#48
0
文件: Decompiler.cs 项目: xornand/cci
    /// <summary>
    /// Allocates a mutator that copies metadata models into mutable code models by using the base MetadataMutator class to make a mutable copy
    /// of a given metadata model and also replaces any method bodies with instances of SourceMethodBody, which implements the ISourceMethodBody.Block property
    /// by decompiling the metadata model information provided by the properties of IMethodBody.
    /// </summary>
    /// <param name="host">An object representing the application that is hosting this mutator. 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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
    /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
    /// <param name="options">Set of options that control decompilation.</param>
    internal ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(IMetadataHost host,
      ISourceLocationProvider/*?*/ sourceLocationProvider, ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options) {
      Contract.Requires(host != null);

      this.localScopeProvider = localScopeProvider;
      this.sourceLocationProvider = sourceLocationProvider;
      this.host = host;
      this.options = options;
    }
 internal Emitter(DynamicLoader loader, ISourceLocationProvider sourceLocationProvider, ILocalScopeProvider localScopeProvider) {
   this.loader = loader;
   this.sourceLocationProvider = sourceLocationProvider;
   this.localScopeProvider = localScopeProvider;
 }
    private ILocalScopeProvider/*?*/ GetProvider(IMethodDefinition methodDefinition) {
      Contract.Requires(methodDefinition != null);

      if (methodDefinition == lastUsedMethod) return lastUsedProvider;
      ILocalScopeProvider provider = null;
      var definingUnit = TypeHelper.GetDefiningUnit(methodDefinition.ContainingTypeDefinition);
      this.unit2Provider.TryGetValue(definingUnit, out provider);
      if (provider != null) {
        this.lastUsedMethod = methodDefinition;
        this.lastUsedProvider = provider;
        return provider;
      }
      foreach (var location in methodDefinition.Locations) {
        var ilLocation = location as IILLocation;
        if (ilLocation == null || ilLocation.MethodDefinition == methodDefinition) continue;
        return this.GetProvider(ilLocation.MethodDefinition);
      }
      return null;
    }
示例#51
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: PeToPe [path]fileName.ext [decompile] [noStack]");
                return;
            }
            bool decompile = args.Length >= 2;
            bool noStack   = args.Length >= 3;

            using (var host = new HostEnvironment()) {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(args[0]) as IModule;
                if (module == null || module is Dummy)
                {
                    Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Get a PDB reader if there is a PDB file.
                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = module.DebugInformationLocation;
                if (string.IsNullOrEmpty(pdbFile) || !File.Exists(pdbFile))
                {
                    pdbFile = Path.ChangeExtension(module.Location, "pdb");
                }
                if (File.Exists(pdbFile))
                {
                    using (var pdbStream = File.OpenRead(pdbFile)) {
                        pdbReader = new PdbReader(pdbStream, host);
                    }
                }
                using (pdbReader) {
                    ISourceLocationProvider sourceLocationProvider = pdbReader;
                    ILocalScopeProvider     localScopeProvider     = pdbReader;
                    if (decompile)
                    {
                        //Construct a Code Model from the Metadata model via decompilation
                        var options = DecompilerOptions.AnonymousDelegates | DecompilerOptions.Iterators | DecompilerOptions.Loops;
                        if (noStack)
                        {
                            options |= DecompilerOptions.Unstack;
                        }
                        module = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, options);
                        if (pdbReader != null)
                        {
                            localScopeProvider = new Decompiler.LocalScopeProvider(pdbReader);
                        }
                    }

                    MetadataRewriter   rewriter;
                    MetadataDeepCopier copier;
                    if (decompile)
                    {
                        copier   = new CodeDeepCopier(host, pdbReader, pdbReader);
                        rewriter = new CodeRewriter(host);
                    }
                    else
                    {
                        copier   = new MetadataDeepCopier(host);
                        rewriter = new MetadataRewriter(host);
                    }

                    var mutableModule = copier.Copy(module);
                    module = rewriter.Rewrite(mutableModule);

                    //var validator = new MetadataValidator(host);
                    //List<Microsoft.Cci.ErrorEventArgs> errorEvents = new List<Microsoft.Cci.ErrorEventArgs>();
                    //host.Errors += (object sender, Microsoft.Cci.ErrorEventArgs e) => errorEvents.Add(e);
                    //var assem = module as IAssembly;
                    //validator.Validate(assem);
                    //if (errorEvents.Count != 0)
                    //{
                    //    foreach (var e in errorEvents)
                    //    {
                    //        foreach (var err in e.Errors)
                    //        {
                    //            Console.WriteLine(err.Message);
                    //        }
                    //    }
                    //}

#if DEBUG
                    var newRoot = Path.GetFileNameWithoutExtension(module.Location) + "1";
                    var newName = newRoot + Path.GetExtension(module.Location);
                    using (Stream peStream = File.Create(newName)) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(module, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(newRoot + ".pdb", pdbReader, emitTokenSourceInfo: true)) {
                                PeWriter.WritePeToStream(module, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                            }
                        }
                    }
#else
                    using (Stream peStream = File.Create(module.Location)) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(module, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(pdbFile, pdbReader, emitTokenSourceInfo: true)) {
                                PeWriter.WritePeToStream(module, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                            }
                        }
                    }
#endif
                }
            }
        }
示例#52
0
文件: Decompiler.cs 项目: xornand/cci
 /// <summary>
 /// An object that can provide information about the local scopes of a method.
 /// </summary>
 /// <param name="originalLocalScopeProvider">The local scope provider to use for methods that have not been decompiled.</param>
 public LocalScopeProvider(ILocalScopeProvider originalLocalScopeProvider) {
   Contract.Requires(originalLocalScopeProvider != null);
   this.originalLocalScopeProvider = originalLocalScopeProvider;
 }
示例#53
0
 /// <summary>
 /// Returns a mutable Code Model module that is equivalent to the given Metadata Model module,
 /// except that in the new module method bodies also implement ISourceMethodBody.
 /// </summary>
 /// <param name="host">An object representing the application that is hosting this decompiler. 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="module">The root of the Metadata Model to be converted to a Code Model.</param>
 /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
 /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
 /// <param name="options">Set of options that control decompilation.</param>
 private static Module GetCodeModelFromMetadataModelHelper(IMetadataHost host, IModule module,
     ISourceLocationProvider/*?*/ sourceLocationProvider, ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options)
 {
     var result = new MetadataDeepCopier(host).Copy(module);
       var replacer = new ReplaceMetadataMethodBodiesWithDecompiledMethodBodies(host, module, sourceLocationProvider, localScopeProvider, options);
       replacer.Traverse(result);
       var finder = new HelperTypeFinder(host, sourceLocationProvider);
       finder.Traverse(result);
       var remover = new RemoveUnnecessaryTypes(finder.helperTypes, finder.helperMethods, finder.helperFields);
       remover.Traverse(result);
       result.AllTypes.RemoveAll(td => finder.helperTypes.ContainsKey(td.InternedKey)); // depends on RemoveAll preserving order
       return result;
 }
示例#54
0
 public MyILRewriter(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider)
   : base(host, localScopeProvider, sourceLocationProvider) {
   #region Get reference to Console.WriteLine
   var nameTable = host.NameTable;
   var platformType = host.PlatformType;
   var systemString = platformType.SystemString;
   var systemVoid = platformType.SystemVoid;
   var SystemDotConsoleType =
     new Microsoft.Cci.Immutable.NamespaceTypeReference(
       host,
       systemString.ContainingUnitNamespace,
       nameTable.GetNameFor("Console"),
       0, false, false, true, PrimitiveTypeCode.NotPrimitive);
   this.consoleDotWriteLine = new Microsoft.Cci.MethodReference(
     host, SystemDotConsoleType,
     CallingConvention.Default,
     systemVoid,
     nameTable.GetNameFor("WriteLine"),
     0, systemString);
   #endregion Get reference to Console.WriteLine
 }
示例#55
0
 /// <summary>
 /// An object that can provide information about the local scopes of a method.
 /// </summary>
 /// <param name="originalLocalScopeProvider">The local scope provider to use for methods that have not been decompiled.</param>
 public LocalScopeProvider(ILocalScopeProvider originalLocalScopeProvider)
 {
     this.originalLocalScopeProvider = originalLocalScopeProvider;
 }
示例#56
0
 /// <summary>
 /// Allocates a metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
 /// </summary>
 /// <param name="ilMethodBody">A method body whose IL operations should be decompiled into a block of statements that will be the
 /// result of the Block property of the resulting source method body.</param>
 /// <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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
 /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method.</param>
 /// <param name="options">Set of options that control decompilation.</param>
 public SourceMethodBody(IMethodBody ilMethodBody, IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider,
     ILocalScopeProvider/*?*/ localScopeProvider, DecompilerOptions options = DecompilerOptions.None)
     : base(host, sourceLocationProvider)
 {
     this.ilMethodBody = ilMethodBody;
       this.host = host;
       this.nameTable = host.NameTable;
       this.sourceLocationProvider = sourceLocationProvider;
       this.pdbReader = sourceLocationProvider as PdbReader;
       this.localScopeProvider = localScopeProvider;
       this.options = options;
       this.platformType = ilMethodBody.MethodDefinition.ContainingTypeDefinition.PlatformType;
       this.operationEnumerator = ilMethodBody.Operations.GetEnumerator();
       if (IteratorHelper.EnumerableIsNotEmpty(ilMethodBody.LocalVariables))
     this.LocalsAreZeroed = ilMethodBody.LocalsAreZeroed;
       else
     this.LocalsAreZeroed = true;
       this.MethodDefinition = ilMethodBody.MethodDefinition;
 }
示例#57
0
 public static IModule RewriteModule(IMetadataHost host, ILocalScopeProvider localScopeProvider, ISourceLocationProvider sourceLocationProvider, IModule module) {
   var rew = new MyILRewriter(host, localScopeProvider, sourceLocationProvider);
   var me = new RewriteStoreLocal(host, rew);
   return me.Rewrite(module);
 }
示例#58
0
 /*?*/
 private ILocalScopeProvider GetProvider(IMethodDefinition methodDefinition)
 {
     if (methodDefinition == lastUsedMethod) return lastUsedProvider;
       ILocalScopeProvider provider = null;
       var definingUnit = TypeHelper.GetDefiningUnit(methodDefinition.ResolvedMethod.ContainingTypeDefinition);
       this.unit2Provider.TryGetValue(definingUnit, out provider);
       if (provider != null) {
     this.lastUsedMethod = methodDefinition;
     this.lastUsedProvider = provider;
       }
       return provider;
 }
示例#59
0
 /// <summary>
 /// Given a mutable module that is a "declarative" module, i.e., it has contracts expressed as contract calls
 /// at the beginning of method bodies, this method will extract them, leaving the method bodies without those
 /// calls and return a contract provider for the module containing any extracted contracts.
 /// </summary>
 public static ContractProvider ExtractContracts(IContractAwareHost host, Module module, PdbReader/*?*/ pdbReader, ILocalScopeProvider/*?*/ localScopeProvider) {
   var contractMethods = new ContractMethods(host);
   var cp = new Microsoft.Cci.MutableContracts.ContractProvider(contractMethods, module);
   var extractor = new SeparateContractsFromCode(host, pdbReader, localScopeProvider, cp);
   extractor.Traverse(module);
   return cp;
 }