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; } } } }
/// <summary> /// A rewriter for CodeModel method bodies, which changes any foreach loops found in the body into lower level structures. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in a block of statements to IPrimarySourceLocation objects. May be null.</param> public ForEachRemover(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) : base(host) { this.sourceLocationProvider = sourceLocationProvider; this.moveNext = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = host.PlatformType.SystemCollectionsIEnumerator, InternFactory = host.InternFactory, Name = host.NameTable.GetNameFor("MoveNext"), Parameters = new List<IParameterTypeInformation>(), Type = host.PlatformType.SystemBoolean, }; var assemblyReference = new Immutable.AssemblyReference(this.host, this.host.CoreAssemblySymbolicIdentity); IUnitNamespaceReference ns = new Immutable.RootUnitNamespaceReference(assemblyReference); ns = new Immutable.NestedUnitNamespaceReference(ns, this.host.NameTable.GetNameFor("System")); var iDisposable = new Immutable.NamespaceTypeReference(this.host, ns, this.host.NameTable.GetNameFor("IDisposable"), 0, false, false, true, PrimitiveTypeCode.Reference); this.disposeMethod = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = iDisposable, InternFactory = host.InternFactory, Name = this.host.NameTable.GetNameFor("Dispose"), Parameters = new List<IParameterTypeInformation>(), Type = this.host.PlatformType.SystemVoid, }; }
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); }
/// <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; }
/// <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; }
/// <summary> /// A rewriter for CodeModel method bodies, which changes any anynomous delegate expressions found in the body into delegates over /// methods of either the containing type of the method, or of a nested type of that type. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in a block of statements to IPrimarySourceLocation objects. May be null.</param> public AnonymousDelegateRemover(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) : base(host) { this.copier = new MetadataDeepCopier(host); this.sourceLocationProvider = sourceLocationProvider; var compilerGeneratedCtor = this.GetReferenceToDefaultConstructor(host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute); this.compilerGenerated = new CustomAttribute() { Constructor = compilerGeneratedCtor }; this.objectCtor = this.GetReferenceToDefaultConstructor(this.host.PlatformType.SystemObject); }
/// <summary> /// Note that it leaves any calls to contract methods in their original locations, /// i.e., it does *not* extract contracts. That is up to the caller of this method. /// </summary> public static bool FileToUnitAndSourceLocationProvider(IMetadataHost host, string filename, List<string> libPaths, List<string> referencedAssemblies, out IModule module, out ISourceLocationProvider/*?*/ sourceLocationProvider) { var text = File.ReadAllText(filename); CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, filename); // This ctor isn't implemented yet. //var mscorlib = new Roslyn.Compilers.AssemblyObjectReference(typeof(object).Assembly); //var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib"); // Roslyn takes care of resolving where it lives. var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); var refs = new List<MetadataReference>(); refs.Add(mscorlib); foreach (var r in referencedAssemblies) { refs.Add(new MetadataFileReference(Path.GetFileNameWithoutExtension((r)))); } var baseFileName = Path.GetFileNameWithoutExtension(filename); var defaultResolver = FileResolver.Default; var ar = new FileResolver(libPaths.Select(lp => Path.GetFullPath(lp)), defaultResolver.KeyFileSearchPaths, defaultResolver.BaseDirectory); var c = CSharpCompilation.Create( baseFileName , syntaxTrees: new SyntaxTree[] { tree } , references: refs , fileResolver: ar , options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); var diags = c.GetDiagnostics(); if (diags.Count() > 0) { foreach (var diag in diags) { Console.WriteLine(diag.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } //c = c.AddSyntaxTrees(tree); // Use this form to add another syntax tree to the same compilation (getting a new compilation since they're immutable) var binding = c.GetSemanticModel(tree); diags = binding.GetDiagnostics(); if (diags.Count() > 0) { foreach (var d in diags) { Console.WriteLine(d.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } ConvertRoslynToCCI(host, tree, binding, out module, out sourceLocationProvider); return true; }
/// <summary> /// Initializes an object with a method that converts a given block of statements to a list of IL operations, exception information and possibly some private helper types. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="method">The method that contains the block of statements that will be converted.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in the block of statements to IPrimarySourceLocation objects. May be null.</param> public CodeModelToILConverter(IMetadataHost host, IMethodDefinition method, ISourceLocationProvider/*?*/ sourceLocationProvider) { Contract.Requires(host != null); Contract.Requires(method != null); this.generator = new ILGenerator(host, method); this.host = host; this.method = method; this.sourceLocationProvider = sourceLocationProvider; this.minizeCodeSize = true; }
public 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>(); }
/// <summary> /// Initializes an object with a method that converts a given block of statements to a list of IL operations, exception information and possibly some private helper types. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="method">The method that contains the block of statements that will be converted.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in the block of statements to IPrimarySourceLocation objects. May be null.</param> /// <param name="asyncMethod">May be null.</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 CodeModelToILConverter(IMetadataHost host, IMethodDefinition method, ISourceLocationProvider/*?*/ sourceLocationProvider, IMethodDefinition/*?*/ asyncMethod, IDictionary<IBlockStatement, uint>/*?*/ iteratorLocalCount) { Contract.Requires(host != null); Contract.Requires(method != null); this.generator = new ILGenerator(host, method, asyncMethod); this.host = host; this.method = method; this.sourceLocationProvider = sourceLocationProvider; this.minizeCodeSize = true; this.iteratorLocalCount = iteratorLocalCount; }
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); }
private IEnumerable <IPrimarySourceLocation /*?*/> MapLocationToSourceLocations(ILocation location) { IILLocation /*?*/ mbLocation = location as IILLocation; ISourceLocationProvider provider = this.GetProvider(mbLocation); if (provider != null) { foreach (var psloc in provider.GetPrimarySourceLocationsFor(location)) { yield return(psloc); } } }
public NodeVisitor(IMetadataHost host, CommonSemanticModel semanticModel, ISourceLocationProvider /*?*/ sourceLocationProvider) { this.host = host; this.nameTable = host.NameTable; this.semanticModel = semanticModel; this.sourceLocationProvider = sourceLocationProvider; this.contractMethods = new ContractMethods(host); // translate the entire metadata model for the assembly // the actual visit is just to get method bodies for any methods // defined in the cone that is visited. this.mapper = ReferenceMapper.TranslateAssembly(host, semanticModel.Compilation.Assembly); }
/// <summary> /// Return zero or more locations in primary source documents that correspond to the definition of the given local. /// </summary> public IEnumerable <IPrimarySourceLocation> GetPrimarySourceLocationsForDefinitionOf(ILocalDefinition localDefinition) { ISourceLocationProvider /*?*/ provider = this.GetProvider(localDefinition); if (provider == null) { return(IteratorHelper.GetEmptyEnumerable <IPrimarySourceLocation>()); } else { return(provider.GetPrimarySourceLocationsForDefinitionOf(localDefinition)); } }
/// <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; }
public static void ConvertRoslynToCCI( IMetadataHost host, SyntaxTree tree, SemanticModel semanticModel, out IModule module, out ISourceLocationProvider sourceLocationProvider) { sourceLocationProvider = new SourceLocationProvider(); var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider); var assembly = (IModule)transformer.Visit(tree.GetRoot()); module = assembly; }
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; }
public static void ConvertRoslynToCCI( IMetadataHost host, Microsoft.CodeAnalysis.CSharp.SyntaxTree tree, Microsoft.CodeAnalysis.CSharp.Semantics.SemanticModel semanticModel, out IModule module, out ISourceLocationProvider sourceLocationProvider) { sourceLocationProvider = new SourceLocationProvider(); var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider); var assembly = (Module)transformer.Visit(tree.GetRoot()); assembly.Location = Path.GetFullPath(tree.FilePath); module = assembly; }
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; }
/// <summary> /// Returns the source name of the given local definition, if this is available. /// Otherwise returns the value of the Name property and sets isCompilerGenerated to true. /// </summary> public string GetSourceNameFor(ILocalDefinition localDefinition, out bool isCompilerGenerated) { ISourceLocationProvider /*?*/ provider = this.GetProvider(localDefinition); if (provider == null) { isCompilerGenerated = false; return(""); } else { return(provider.GetSourceNameFor(localDefinition, out isCompilerGenerated)); } }
public ScopeAnalysis(IMetadataHost host, Assembly assembly, IEnumerable <Assembly> refAssemblies, IEnumerable <string> ips) { this.mhost = host; this.assembly = assembly; this.refAssemblies = refAssemblies; sourceLocationProvider = assembly.PdbReader; interestingProcessors = ips; if (interestingProcessors == null) { Utils.WriteLine("Interesting processors list not provided, continuing without it."); } LoadTypes(); }
/// <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); }
private ISourceLocationProvider /*?*/ GetProvider(IMethodDefinition methodDefinition) { if (methodDefinition == lastUsedMethod) { return(lastUsedProvider); } ISourceLocationProvider 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); }
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); } } }
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); }
/// <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); }
/// <summary> /// Initializes an instance of SingleAssigner. /// </summary> /// <param name="cdfg"> /// A set of basic blocks, each of which has a list of successor blocks and some other information. /// Each block consists of a list of instructions, each of which can point to previous instructions that compute the operands it consumes. /// </param> /// <param name="nameTable"> /// An extensible collection of IName instances that represent names that are commonly used during compilation. /// </param> /// <param name="cfgQueries"></param> /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param> private SingleAssigner(INameTable nameTable, ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ControlGraphQueries <BasicBlock, Instruction> cfgQueries, ISourceLocationProvider sourceLocationProvider) { Contract.Requires(nameTable != null); Contract.Requires(cdfg != null); Contract.Requires(cfgQueries != null); this.nameTable = nameTable; this.cdfg = cdfg; this.cfgQueries = cfgQueries; this.sourceLocationProvider = sourceLocationProvider; }
/// <summary> /// Rewrites the blocks in the given cdfg so that every assignment to a local or parameter is to a new local (and thus each local is just /// assigned to in exactly one place in the graph). The new names introduced by the writes are connected to the reads in successor blocks /// by means of join points (a.k.a. Phi nodes) that are found in the Reads property of an SSABasicBlock. /// </summary> /// <param name="cdfg"> /// A set of basic blocks, each of which has a list of successor blocks and some other information. /// Each block consists of a list of instructions, each of which can point to previous instructions that compute the operands it consumes. /// </param> /// <param name="cfgQueries"> /// Presents information derived from a simple control flow graph. For example, traversal orders, predecessors, dominators and dominance frontiers. /// </param> /// <param name="nameTable"> /// An extensible collection of IName instances that represent names that are commonly used during compilation. /// </param> /// <param name="sourceLocationProvider"></param> public static void GetInSingleAssignmentForm(INameTable nameTable, ControlAndDataFlowGraph <BasicBlock, Instruction> cdfg, ControlGraphQueries <BasicBlock, Instruction> cfgQueries, ISourceLocationProvider sourceLocationProvider) { Contract.Requires(nameTable != null); Contract.Requires(cdfg != null); Contract.Requires(cfgQueries != null); var singleAssigner = new SingleAssigner <BasicBlock, Instruction>(nameTable, cdfg, cfgQueries, sourceLocationProvider); singleAssigner.GetInSingleAssignmentForm(); }
public MethodCfgAndTac AnalyzeIntraProcedural(IMethodDefinition methodDefinition) { // System.Console.WriteLine("Traversing: {0}", methodDefinition.GetName()); if (Stubber.SuppressM(methodDefinition)) { return(null); } if (methodDefinition.IsExternal) { return(null); } if (methodDefinition.IsAbstract) { return(null); } ITypeDefinition containingDefn = methodDefinition.ContainingTypeDefinition; ISourceLocationProvider sourceLocationProvider = null; if (containingDefn != null) { IModule mod = TypeHelper.GetDefiningUnit(containingDefn) as IModule; if (moduleToPdbMap.ContainsKey(mod)) { sourceLocationProvider = moduleToPdbMap[mod]; } else { if (!(mod == null || mod == Dummy.Module || mod == Dummy.Assembly)) { sourceLocationProvider = GetPdbReader(mod.Location); moduleToPdbMap[mod] = sourceLocationProvider; } } } var disassembler = new Disassembler(host, methodDefinition, sourceLocationProvider); var methodBody = disassembler.Execute(); var cfAnalysis = new ControlFlowAnalysis(methodBody); // var cfg = cfAnalysis.GenerateNormalControlFlow(); var cfg = cfAnalysis.GenerateExceptionalControlFlow(); var domAnalysis = new DominanceAnalysis(cfg); domAnalysis.Analyze(); domAnalysis.GenerateDominanceTree(); var loopAnalysis = new NaturalLoopAnalysis(cfg); loopAnalysis.Analyze(); var domFrontierAnalysis = new DominanceFrontierAnalysis(cfg); domFrontierAnalysis.Analyze(); var splitter = new WebAnalysis(cfg, methodDefinition); splitter.Analyze(); splitter.Transform(); methodBody.UpdateVariables(); var typeAnalysis = new TypeInferenceAnalysis(cfg, methodDefinition.Type); typeAnalysis.Analyze(); var forwardCopyAnalysis = new ForwardCopyPropagationAnalysis(cfg); forwardCopyAnalysis.Analyze(); forwardCopyAnalysis.Transform(methodBody); // backwardCopyAnalysis is buggy - it says so in the source file - see notes in src/test // var backwardCopyAnalysis = new BackwardCopyPropagationAnalysis(cfg); // backwardCopyAnalysis.Analyze(); // backwardCopyAnalysis.Transform(methodBody); var liveVariables = new LiveVariablesAnalysis(cfg); liveVariables.Analyze(); var ssa = new StaticSingleAssignment(methodBody, cfg); ssa.Transform(); ssa.Prune(liveVariables); methodBody.UpdateVariables(); MethodCfgAndTac mct = new MethodCfgAndTac(cfg, methodBody); foreach (IExceptionHandlerBlock ehInfo in disassembler.GetExceptionHandlers()) { if (ehInfo is CatchExceptionHandler) { mct.ehInfoList.Add(ehInfo as CatchExceptionHandler); } } return(mct); }
/// <summary> /// Provides copy of a method body, a statement, or an expression, in which the references to the nodes /// inside a cone is replaced. The cone is defined using the parent class. /// </summary> public CodeCopier(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) : base(host) { this.sourceLocationProvider = sourceLocationProvider; this.createMutableType = new CreateMutableType(this); }
/// <summary> /// Note that it leaves any calls to contract methods in their original locations, /// i.e., it does *not* extract contracts. That is up to the caller of this method. /// </summary> public static bool FileToUnitAndSourceLocationProvider(IMetadataHost host, string filename, List <string> libPaths, List <string> referencedAssemblies, out IModule module, out ISourceLocationProvider /*?*/ sourceLocationProvider) { var text = File.ReadAllText(filename); CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, filename); // This ctor isn't implemented yet. //var mscorlib = new Roslyn.Compilers.AssemblyObjectReference(typeof(object).Assembly); //var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib"); // Roslyn takes care of resolving where it lives. var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); var refs = new List <MetadataReference>(); refs.Add(mscorlib); foreach (var r in referencedAssemblies) { refs.Add(new MetadataFileReference(Path.GetFileNameWithoutExtension((r)))); } var baseFileName = Path.GetFileNameWithoutExtension(filename); var defaultResolver = FileResolver.Default; var ar = new FileResolver(libPaths.Select(lp => Path.GetFullPath(lp)), defaultResolver.KeyFileSearchPaths, defaultResolver.BaseDirectory); var c = CSharpCompilation.Create( baseFileName , syntaxTrees: new SyntaxTree[] { tree } , references: refs , fileResolver: ar , options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); var diags = c.GetDiagnostics(); if (diags.Count() > 0) { foreach (var diag in diags) { Console.WriteLine(diag.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return(false); } } //c = c.AddSyntaxTrees(tree); // Use this form to add another syntax tree to the same compilation (getting a new compilation since they're immutable) var binding = c.GetSemanticModel(tree); diags = binding.GetDiagnostics(); if (diags.Count() > 0) { foreach (var d in diags) { Console.WriteLine(d.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return(false); } } ConvertRoslynToCCI(host, tree, binding, out module, out sourceLocationProvider); return(true); }
public static ControlFlowGraph DoAnalysisPhases(this IMethodDefinition method, IMetadataHost host, ISourceLocationProvider locationProvider, IEnumerable <IMethodReference> methodsToTryToInline = null) { AnalysisStats.extraAnalysisOverHead.Start(); var disassembler = new Disassembler(host, method, locationProvider); var methodBody = disassembler.Execute(); MethodBodyProvider.Instance.AddBody(method, methodBody); if (methodsToTryToInline != null) { DoInlining(method, host, methodBody, locationProvider, methodsToTryToInline); } var cfAnalysis = new ControlFlowAnalysis(methodBody); //var cfg = cfAnalysis.GenerateExceptionalControlFlow(); var cfg = cfAnalysis.GenerateNormalControlFlow(); var domAnalysis = new DominanceAnalysis(cfg); domAnalysis.Analyze(); domAnalysis.GenerateDominanceTree(); var loopAnalysis = new NaturalLoopAnalysis(cfg); loopAnalysis.Analyze(); var domFrontierAnalysis = new DominanceFrontierAnalysis(cfg); domFrontierAnalysis.Analyze(); var splitter = new WebAnalysis(cfg, method); splitter.Analyze(); splitter.Transform(); methodBody.UpdateVariables(); var analysis = new TypeInferenceAnalysis(cfg, methodBody.MethodDefinition.Type); analysis.Analyze(); var copyProgapagtion = new ForwardCopyPropagationAnalysis(cfg); copyProgapagtion.Analyze(); copyProgapagtion.Transform(methodBody); //var backwardCopyProgapagtion = new BackwardCopyPropagationAnalysis(cfg); //backwardCopyProgapagtion.Analyze(); //backwardCopyProgapagtion.Transform(methodBody); var liveVariables = new LiveVariablesAnalysis(cfg); var resultLiveVar = liveVariables.Analyze(); var ssa = new StaticSingleAssignment(methodBody, cfg); ssa.Transform(); ssa.Prune(liveVariables); methodBody.UpdateVariables(); AnalysisStats.extraAnalysisOverHead.Stop(); return(cfg); }
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 }
public PdbWriter(string fileName, ISourceLocationProvider sourceLocationProvider, bool emitTokenSourceInfo = false) { this.fileName = fileName; this.sourceLocationProvider = sourceLocationProvider; this.emitTokenSourceInfo = emitTokenSourceInfo; }
/// <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; }
/// <summary> /// Provides copy of a method body, a statement, or an expression, in which the references to the nodes /// inside a cone is replaced. The cone is defined using the parent class. /// </summary> public CodeCopier(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider, IDefinition rootOfCone, out List<INamedTypeDefinition> newTypes) : base(host, rootOfCone, out newTypes) { this.sourceLocationProvider = sourceLocationProvider; this.createMutableType = new CreateMutableType(this); }
private static void DoInlining(IMethodDefinition method, IMetadataHost host, MethodBody methodBody, ISourceLocationProvider sourceLocationProvider, IEnumerable <IMethodReference> methodsToTryToInline = null) { if (methodsToTryToInline == null) { methodsToTryToInline = new HashSet <IMethodReference>(); } var methodCalls = methodBody.Instructions.OfType <MethodCallInstruction>().Where(ins => methodsToTryToInline.Contains(ins.Method)).ToList(); foreach (var methodCall in methodCalls) { var callee = methodCall.Method.ResolvedMethod; if (callee != null) { // var calleeCFG = DoAnalysisPhases(callee, host); var disassemblerCallee = new Disassembler(host, callee, sourceLocationProvider); var methodBodyCallee = disassemblerCallee.Execute(); methodBody.Inline(methodCall, methodBodyCallee); } } methodBody.UpdateVariables(); }
/// <summary> /// /// </summary> /// <param name="targetHost">An object representing the application that will host the copies made by this copier.</param> /// <param name="targetUnit">The unit of metadata into which copies made by this copier will be inserted.</param> /// <param name="sourceLocationProvider"></param> public CodeDeepCopier(IMetadataHost targetHost, IUnit targetUnit, ISourceLocationProvider sourceLocationProvider = null) : this(targetHost, new CodeShallowCopier(targetHost, targetUnit, sourceLocationProvider)) { }
/// <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; }
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)); }
public ContractRewriter(IMetadataHost host, ContractProvider contractProvider, ISourceLocationProvider sourceLocationProvider) : base(host, contractProvider) { systemVoid = host.PlatformType.SystemVoid; this.sourceLocationProvider = sourceLocationProvider; }
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)); }
private bool MakeSureSliceHasAtLeastMethodSourceLocation(ISlice <MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, IAssemblyReference> slice, ISourceLocationProvider sourceLocationProvider) { Contract.Requires(slice != null); Contract.Requires(sourceLocationProvider != null); foreach (var m in slice.Methods) { var methodDefinition = m.reference.ResolvedMethod; if (sourceLocationProvider.GetPrimarySourceLocationsFor(methodDefinition.Locations).Any()) { return(true); } } return(false); }
static int Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: HelloContracts [path]fileName.Contracts.dll [-libpaths ...]* [-p [-i] | -inject]"); return(1); } #region Parse options var options = new Options(); options.Parse(args); if (options.HelpRequested) { options.PrintOptions(""); return(1); } if (options.HasErrors) { options.PrintErrorsAndExit(Console.Out); } #endregion var fileName = String.IsNullOrEmpty(options.assembly) ? options.GeneralArguments[0] : options.assembly; if (options.printContracts) { #region Collect and write contracts using (var host = new CodeContractAwareHostEnvironment(options.libpaths)) { IModule module = host.LoadUnitFrom(fileName) as IModule; if (module == null || module is Dummy) { Console.WriteLine("'{0}' is not a PE file containing a CLR module or assembly.", fileName); Environment.Exit(1); } var t = new Traverser(host, options.inherited); t.Traverse(module); } #endregion return(0); } else { using (var host = new CodeContractAwareHostEnvironment(options.libpaths, true, true)) { // Read the Metadata Model from the PE file var module = host.LoadUnitFrom(fileName) as IModule; if (module == null || module is Dummy) { Console.WriteLine(fileName + " is not a PE file containing a CLR module or assembly."); return(1); } // Get a PDB reader if there is a PDB file. PdbReader /*?*/ pdbReader = null; string 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; // Construct a Code Model from the Metadata model via decompilation var mutableModule = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, DecompilerOptions.AnonymousDelegates | DecompilerOptions.Loops); ILocalScopeProvider localScopeProvider = new Decompiler.LocalScopeProvider(pdbReader); // Extract contracts (side effect: removes them from the method bodies) var contractProvider = Microsoft.Cci.MutableContracts.ContractHelper.ExtractContracts(host, mutableModule, pdbReader, localScopeProvider); // Inject non-null postconditions if (options.inject) { new NonNullInjector(host, contractProvider).Traverse(mutableModule); } // Put the contracts back in as method calls at the beginning of each method Microsoft.Cci.MutableContracts.ContractHelper.InjectContractCalls(host, mutableModule, contractProvider, sourceLocationProvider); // Write out the resulting module. Each method's corresponding IL is produced // lazily using CodeModelToILConverter via the delegate that the mutator stored in the method bodies. using (var peStream = File.Create(mutableModule.Location + ".pe")) { if (pdbReader == null) { PeWriter.WritePeToStream(mutableModule, host, peStream); } else { using (var pdbWriter = new PdbWriter(mutableModule.Location + ".pdb", sourceLocationProvider)) { PeWriter.WritePeToStream(mutableModule, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter); } } } } } return(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); }
public PdbWriter(string fileName, ISourceLocationProvider sourceLocationProvider) { this.fileName = fileName; this.sourceLocationProvider = sourceLocationProvider; }
/// <summary> /// /// </summary> /// <param name="targetHost">An object representing the application that will host the copies made by this copier.</param> /// <param name="targetUnit">The unit of metadata into which copies made by this copier will be inserted.</param> /// <param name="sourceLocationProvider"></param> public CodeShallowCopier(IMetadataHost targetHost, IUnit targetUnit, ISourceLocationProvider sourceLocationProvider = null) : base(targetHost, targetUnit) { this.sourceLocationProvider = sourceLocationProvider; }
private ISourceLocationProvider/*?*/ GetProvider(IMethodDefinition methodDefinition) { Contract.Requires(methodDefinition != null); if (methodDefinition == lastUsedMethod) return lastUsedProvider; ISourceLocationProvider 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; }
/// <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; }
/// <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; }
/// <summary> /// A traverser that visits every method body and collects together all of the private helper types of these bodies. /// </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="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param> internal HelperTypeFinder(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) { this.host = host; this.sourceLocationProvider = sourceLocationProvider; this.TraverseIntoMethodBodies = true; }
/// <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; }
/// <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; }
/// <summary> /// Provides copy of a method contract, method body, a statement, or an expression, in which the references to the nodes /// inside a cone is replaced. The cone is defined using the parent class. /// </summary> public CodeAndContractCopier(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) : base(host, sourceLocationProvider) { }
public static void IMethodDefinitionTraverse(IMethodDefinition mD, IMetadataHost host, ISourceLocationProvider sourceLocationProvider) { if (mD.IsStaticConstructor) { staticConstructors.Add(mD); } else if (Helpers.IsMain(mD)) { mainMethods.Add(mD); } }
/*?*/ private ISourceLocationProvider GetProvider(IMethodDefinition methodDefinition) { if (methodDefinition == lastUsedMethod) return lastUsedProvider; ISourceLocationProvider 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; }
/// <summary> /// Provides copy of a method contract, method body, a statement, or an expression, in which the references to the nodes /// inside a cone is replaced. The cone is defined using the parent class. /// </summary> public CodeAndContractCopier(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider, IDefinition rootOfCone, out List<INamedTypeDefinition> newTypes) : base(host, sourceLocationProvider, rootOfCone, out newTypes) { }