private void AnalyzeAssemblyInHost(IMetadataHost host, IAssembly assembly, string pdbPath) { if (pdbPath != null) AnalyzeAssemblyInHostWithProgramDatabase(assembly, host, pdbPath); else AnalyzeTypes(assembly, null, host, Report); }
/// <summary> /// Allocates a reference to a .NET assembly. /// </summary> /// <param name="host">Provides a standard abstraction over the applications that host components that provide or consume objects from the metadata model.</param> /// <param name="assemblyIdentity">The identity of the referenced assembly.</param> /// <param name="isRetargetable">True if the implementation of the referenced assembly used at runtime is not expected to match the version seen at compile time.</param> /// <param name="containsForeignTypes"> /// True if the referenced assembly contains types that describe objects that are neither COM objects nor objects that are managed by the CLR. /// Instances of such types are created and managed by another runtime and are accessed by CLR objects via some form of interoperation mechanism. /// </param> public AssemblyReference(IMetadataHost host, AssemblyIdentity assemblyIdentity, bool isRetargetable = false, bool containsForeignTypes = false) { this.host = host; this.assemblyIdentity = assemblyIdentity; this.isRetargetable = isRetargetable; this.containsForeignTypes = containsForeignTypes; }
internal static void Reachable( IMetadataHost host, ISlice<MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, IAssemblyReference> slice, HashSet<object> thingsToKeep, HashSet<uint> methodsWhoseBodiesShouldBeKept, out Dictionary<IMethodDefinition, uint> contractOffsets ) { Contract.Requires(host != null); Contract.Requires(slice != null); Contract.Requires(thingsToKeep != null); Contract.Requires(methodsWhoseBodiesShouldBeKept != null); var traverser = new MetadataTraverser(); var me = new FindReachable(host, traverser, slice, thingsToKeep, methodsWhoseBodiesShouldBeKept); traverser.TraverseIntoMethodBodies = true; traverser.PreorderVisitor = me; var methodsToTraverse = slice.Methods; foreach (var m in methodsToTraverse) { var methodDefinition = m.reference.ResolvedMethod; traverser.Traverse(methodDefinition); } foreach (var c in slice.Chains) { VisitChain(c, traverser); } contractOffsets = me.contractOffsets; return; }
private static IMethodBody/*?*/ FirstStatementIsIteratorCreation(IMetadataHost host, ISourceMethodBody possibleIterator, INameTable nameTable, IStatement statement) { ICreateObjectInstance createObjectInstance = GetICreateObjectInstance(statement); if (createObjectInstance == null) { // If the first statement in the method body is not the creation of iterator closure, return a dummy. // Possible corner case not handled: a local is used to hold the constant value for the initial state of the closure. return null; } ITypeReference closureType/*?*/ = createObjectInstance.MethodToCall.ContainingType; ITypeReference unspecializedClosureType = ContractHelper.Unspecialized(closureType); if (!AttributeHelper.Contains(unspecializedClosureType.Attributes, host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute)) return null; INestedTypeReference closureTypeAsNestedTypeReference = unspecializedClosureType as INestedTypeReference; if (closureTypeAsNestedTypeReference == null) return null; ITypeReference unspecializedClosureContainingType = ContractHelper.Unspecialized(closureTypeAsNestedTypeReference.ContainingType); if (closureType != null && TypeHelper.TypesAreEquivalent(possibleIterator.MethodDefinition.ContainingTypeDefinition, unspecializedClosureContainingType)) { IName MoveNextName = nameTable.GetNameFor("MoveNext"); foreach (ITypeDefinitionMember member in closureType.ResolvedType.GetMembersNamed(MoveNextName, false)) { IMethodDefinition moveNext = member as IMethodDefinition; if (moveNext != null) { ISpecializedMethodDefinition moveNextGeneric = moveNext as ISpecializedMethodDefinition; if (moveNextGeneric != null) moveNext = moveNextGeneric.UnspecializedVersion.ResolvedMethod; return moveNext.Body; } } } return null; }
private static int CalculateCyclomaticComplexity(this IMethodDefinition method, PdbReader pdb, IMetadataHost host) { var methodBody = method.Decompile(pdb, host); var cyclomaticComplexityCalculator = new CyclomaticComplexityCalculator(); cyclomaticComplexityCalculator.Traverse(methodBody.Statements()); return cyclomaticComplexityCalculator.Result; }
public FieldAssignmentReplacementBuilder(FieldReference field, IMetadataHost host, ExpressionStatement assignment, ReplacementRegistry registry) { this.field = field; this.host = host; this.assignment = assignment; this.registry = registry; }
/// <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, }; }
private static int CalculateStatements(this IMethodDefinition method, PdbReader pdb, IMetadataHost host) { var methodBody = method.Decompile(pdb, host); var statementCollector = new StatementCollector(pdb); statementCollector.Traverse(methodBody.Statements()); return statementCollector.ResultCount; }
private static void AnalyzeFileInHost(string toAnalyse, IMetadataHost host) { AnalyzeFileWithPdb(toAnalyse, host, (pdb) => { AnalyzeAssembly(host.LoadUnitFrom(toAnalyse) as IAssembly, pdb); }); }
public DotNetDesktopStubMethodBodyEmitter(IMetadataHost host) : base(host) { this.consoleWriteLine = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Console"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("WriteLine"), 0, host.PlatformType.SystemString); this.environmentGetStackTrace = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemString, host.NameTable.GetNameFor("get_StackTrace"), 0); this.environmentExit = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("Exit"), 0, host.PlatformType.SystemInt32); }
internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host) { Contract.Requires(containingType != null); Contract.Requires(host != null); this.containingType = containingType; this.host = host; this.platformType = containingType.PlatformType; }
internal AnonymousDelegateCachingRemover(IMetadataHost host, Hashtable<IAnonymousDelegate>/*?*/ delegatesCachedInFields, Hashtable<LocalDefinition, AnonymousDelegate>/*?*/ delegatesCachedInLocals) : base(host) { Contract.Requires(host != null); this.delegatesCachedInFields = delegatesCachedInFields; this.delegatesCachedInLocals = delegatesCachedInLocals; }
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; } } } }
public SpecifiedMethodCallRegistrar(IMetadataHost host, ILogger log, ReplacementRegistry registry) { this.host = host; this.log = log; this.registry = registry; reflector = new UnitReflector(host); }
/// <summary> /// For an iterator method, find the closure class' MoveNext method and return its body. /// </summary> /// <param name="host"></param> /// <param name="possibleIterator">The (potential) iterator method.</param> /// <returns>Dummy.MethodBody if <paramref name="possibleIterator"/> does not fit into the code pattern of an iterator method, /// or the body of the MoveNext method of the corresponding closure class if it does. /// </returns> public static IMethodBody/*?*/ FindClosureMoveNext(IMetadataHost host, ISourceMethodBody/*!*/ possibleIterator) { if (possibleIterator is Dummy) return null; var nameTable = host.NameTable; var possibleIteratorBody = possibleIterator.Block; foreach (var statement in possibleIteratorBody.Statements) { var expressionStatement = statement as IExpressionStatement; if (expressionStatement != null) return FirstStatementIsIteratorCreation(host, possibleIterator, nameTable, statement); break; } foreach (var statement in possibleIteratorBody.Statements){ //var lds = statement as ILocalDeclarationStatement; //if (lds != null) { // if (lds.InitialValue != null) // return null; // else // continue; //} var returnStatement = statement as IReturnStatement; if (returnStatement == null) return null; var blockExpression = returnStatement.Expression as IBlockExpression; if (blockExpression == null) return null; foreach (var s in blockExpression.BlockStatement.Statements) { return FirstStatementIsIteratorCreation(host, possibleIterator, nameTable, s); } } return null; }
public static int Of(IMethodDefinition method, PdbReader pdb, IMetadataHost host) { if (method.HasOperations()) return method.CalculateCyclomaticComplexity(pdb, host); else return 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); }
private TypeMetricsWithMethodMetrics TypeAndMethods(PdbReader pdb, IMetadataHost host, INamedTypeDefinition type) { var typeAndMethods = new TypeMetricsWithMethodMetrics(); typeAndMethods.AddMethodReports(AnalyzeMethods(type, pdb, host)); typeAndMethods.Type = AnalyzeType(type, pdb, typeAndMethods.Methods); return typeAndMethods; }
public static SourceMethodBody Decompile(this IMethodDefinition method, PdbReader pdb, IMetadataHost host) { return new SourceMethodBody(method.Body, host, pdb, pdb, DecompilerOptions.Loops | DecompilerOptions.AnonymousDelegates | DecompilerOptions.Iterators); }
public static int Of(IMethodDefinition method, PdbReader pdb, IMetadataHost host) { if (method.HasOperations()) return method.CalculateStatements(pdb, host); else return 0; }
public SharpMockTypes(IMetadataHost host) { var funcs = new Dictionary<int, INamedTypeReference>(); var acts = new Dictionary<int, INamedTypeReference>(); var sharpMockTypes = host.LoadUnitFrom( System.Reflection.Assembly.GetExecutingAssembly().Location); var sharpMockDelegateTypes = sharpMockTypes as IAssembly; Unit = sharpMockTypes; foreach (var type in sharpMockDelegateTypes.GetAllTypes()) { if (type.Name.Value == "VoidAction") { acts.Add(type.GenericParameterCount, type); } if (type.Name.Value == "Function") { funcs.Add(type.GenericParameterCount - 1, type); } } functions = new GenericMethodTypeDictionary(funcs, "Unable to find type Function<> with {0} input parameter arguments."); actions = new GenericMethodTypeDictionary(acts, "Unable to find type VoidAction<> with {0} parameter arguments."); }
public static Module GetCodeModelFromMetadataModel(IMetadataHost host, IModule module, PdbReader/*?*/ pdbReader, DecompilerOptions options = DecompilerOptions.None) { Contract.Requires(host != null); Contract.Requires(module != null); Contract.Requires(!(module is Dummy)); Contract.Ensures(Contract.Result<Module>() != null); return GetCodeModelFromMetadataModelHelper(host, module, pdbReader, pdbReader, options); }
/// <summary> /// /// </summary> /// <param name="method"></param> /// <param name="host"></param> internal ClosureFinder(IMethodDefinition method, IMetadataHost host) { this.method = method; this.fieldForCapturedLocalOrParameter = new Dictionary<object, BoundField>(); this.host = host; this.nameTable = host.NameTable; this.counter = 0; this.classList.Add((INamedTypeDefinition)method.ContainingTypeDefinition); }
/// <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); }
public static IBlockStatement RemoveCachedDelegates(IMetadataHost host, IBlockStatement blockStatement, SourceMethodBody sourceMethodBody) { var finder = new FindAssignmentToCachedDelegateStaticFieldOrLocal(sourceMethodBody); finder.Traverse(blockStatement); if (finder.cachedDelegateFieldsOrLocals.Count == 0) return blockStatement; var mutator = new CachedDelegateRemover(host, finder.cachedDelegateFieldsOrLocals); return mutator.Visit(blockStatement); }
/// <summary> /// Creates a type reference anchored in the given assembly reference and whose names are relative to the given host. /// When the type name has periods in it, a structured reference with nested namespaces is created. /// </summary> private static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName) { IUnitNamespaceReference ns = new Immutable.RootUnitNamespaceReference(assemblyReference); string[] names = typeName.Split('.'); for (int i = 0, n = names.Length - 1; i < n; i++) ns = new Immutable.NestedUnitNamespaceReference(ns, host.NameTable.GetNameFor(names[i])); return new Immutable.NamespaceTypeReference(host, ns, host.NameTable.GetNameFor(names[names.Length - 1]), 0, false, false, true, PrimitiveTypeCode.NotPrimitive); }
/// <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> /// A rewriter that takes a copy of the body of an iterator method and turns it into the body of a MoveNext method /// by replacing parameters and locals with iterator state fields and replacing occurrences of the generic /// method parameters of the iterator with generic type parameter of the iterator state class. /// </summary> /// <param name="fieldForCapturedLocalOrParameter">A map from captured locals and parameters to the closure class fields that hold their state for the method /// corresponding to the anonymous delegate.</param> /// <param name="genericParameterMapping">The mapping between generic type parameter(s) of the closure class, if any, to the generic method parameter(s).</param> /// <param name="closure">Information regarding the closure created for the iterator.</param> /// <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="iteratorLocalCount">A map that indicates how many iterator locals are present in a given block. Only useful for generated MoveNext methods.</param> internal RewriteAsMoveNext(Dictionary<object, BoundField> fieldForCapturedLocalOrParameter, Dictionary<IBlockStatement, uint> iteratorLocalCount, Dictionary<uint, IGenericTypeParameter> genericParameterMapping, IteratorClosureInformation closure, IMetadataHost host) : base(host) { this.fieldForCapturedLocalOrParameter = fieldForCapturedLocalOrParameter; this.iteratorClosure = closure; this.genericParameterMapping = genericParameterMapping; this.iteratorLocalCount = iteratorLocalCount; }
public VisualSourceEmitter(ISourceEmitterOutput sourceEmitterOutput, IMetadataHost host, PdbReader/*?*/ pdbReader, bool noIL, bool printCompilerGeneratedMembers) : base(sourceEmitterOutput) { this.host = host; this.pdbReader = pdbReader; this.noIL = noIL; this.printCompilerGeneratedMembers = printCompilerGeneratedMembers; }
/// <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; }
internal CopyMarkedNodes(IMetadataHost host) : base(host) { this.deepCopier = new MetadataDeepCopier(host); }
public Viss(IMetadataHost host, IMethodDefinition sourceMethod) : base(host, false) { _sourceMethod = sourceMethod; }
public BaseWeaver(IMetadataHost host) : base(host, true) { }
public ConstantPropagationSetAnalysis(ControlFlowGraph cfg, IMethodDefinition m, IMetadataHost h, IEnumerable <ITypeDefinition> schemas) : base(cfg) { method = m; host = h; schemaTypes = schemas; Initialize(); }
internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host) { this.containingType = containingType; this.host = host; this.platformType = containingType.PlatformType; }
// This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table // for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition // so we make an ITypeReference copy as a workaround. private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host) { var nestedTypeDef = typeDef as INestedTypeDefinition; if (nestedTypeDef == null) { return(typeDef); } var typeRef = new NestedTypeReference(); typeRef.Copy(nestedTypeDef, host.InternFactory); return(typeRef); }
/// <summary> /// Information needed for and during the creation of the closure class for an iterator method. Such information includes: /// 1) the closure class, /// 2) its members, and /// 3) references to the generic instances of the class and its members /// </summary> internal IteratorClosureInformation(IMetadataHost host) { this.host = host; }
internal static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName) { return(CreateTypeReference(host, assemblyReference, typeName, 0)); }
internal SwitchReplacer(SourceMethodBody sourceMethodBody) { Contract.Requires(sourceMethodBody != null); this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null); this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null); }
/// <summary> /// Create a new XPure object. /// </summary> public XPure(IMetadataHost host, bool isPure, DocTracker docTracker) : base(host, null, null, docTracker) { Contract.Requires(docTracker != null); this.isPure = isPure; }
/// <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); }
private static IMethodDefinition CreateIsLibraryInitialized(IMetadataHost host, ITypeDefinition typeDef, IFieldReference intPtrZero) { MethodDefinition methodDefinition = new MethodDefinition { ContainingTypeDefinition = typeDef, IsStatic = true, IsNeverInlined = true, IsHiddenBySignature = true, Visibility = TypeMemberVisibility.Assembly, Type = host.PlatformType.SystemVoid, Parameters = new List <IParameterDefinition> { new ParameterDefinition { Index = 0, Type = host.PlatformType.SystemIntPtr }, new ParameterDefinition { Index = 1, Type = host.PlatformType.SystemString } }, Name = host.NameTable.GetNameFor("IsLibraryInitialized") }; var ilGenerator = new ILGenerator(host, methodDefinition); var retLabel = new ILGeneratorLabel(); var exceptionCtor = new Microsoft.Cci.MutableCodeModel.MethodReference { Name = host.NameTable.GetNameFor(".ctor"), ContainingType = host.PlatformType.SystemException, Type = host.PlatformType.SystemVoid, CallingConvention = CallingConvention.HasThis, Parameters = new List <IParameterTypeInformation> { new ParameterDefinition { Index = 0, Type = host.PlatformType.SystemString } } }; var stringConcat = new Microsoft.Cci.MutableCodeModel.MethodReference { Name = host.NameTable.GetNameFor("Concat"), ContainingType = host.PlatformType.SystemString, Type = host.PlatformType.SystemString, Parameters = new List <IParameterTypeInformation> { new ParameterDefinition { Index = 0, Type = host.PlatformType.SystemString }, new ParameterDefinition { Index = 1, Type = host.PlatformType.SystemString }, new ParameterDefinition { Index = 2, Type = host.PlatformType.SystemString }, new ParameterDefinition { Index = 3, Type = host.PlatformType.SystemString } } }; var intPtrOpEquality = new Microsoft.Cci.MutableCodeModel.MethodReference { Name = host.NameTable.OpEquality, ContainingType = host.PlatformType.SystemIntPtr, Type = host.PlatformType.SystemBoolean, Parameters = new List <IParameterTypeInformation> { new ParameterDefinition { Index = 0, Type = host.PlatformType.SystemIntPtr }, new ParameterDefinition { Index = 1, Type = host.PlatformType.SystemIntPtr } } }; ilGenerator.Emit(OperationCode.Ldarg_0); ilGenerator.Emit(OperationCode.Ldsfld, intPtrZero); ilGenerator.Emit(OperationCode.Call, intPtrOpEquality); ilGenerator.Emit(OperationCode.Brfalse_S, retLabel); ilGenerator.Emit(OperationCode.Ldstr, "Library '"); ilGenerator.Emit(OperationCode.Ldarg_1); ilGenerator.Emit(OperationCode.Ldstr, "' is not initialized. Load the native library (from its file path) by calling LoadLibrary"); ilGenerator.Emit(OperationCode.Ldarg_1); ilGenerator.Emit(OperationCode.Call, stringConcat); ilGenerator.Emit(OperationCode.Newobj, exceptionCtor); ilGenerator.Emit(OperationCode.Throw); ilGenerator.MarkLabel(retLabel); ilGenerator.Emit(OperationCode.Ret); methodDefinition.Body = new ILGeneratorMethodBody(ilGenerator, true, 8, methodDefinition, new List <ILocalDefinition>(), new List <ITypeDefinition>()); return(methodDefinition); }
public VccGlobalDeclarationContainerClass(IMetadataHost compilationHost) : base(compilationHost) { }
public XRewriter(IMetadataHost host, bool copyAndRewriteImmutableReferences = false) : base(host, copyAndRewriteImmutableReferences) { }
internal ReplaceReturns(IMetadataHost host, LocalDefinition r, LabeledStatement b) : base(host) { this.result = r; this.newExit = b; }
public static ControlFlowGraph CFG; // ugly - the thing is that if labels were erased we can't create cfg public Traverser(IMetadataHost host, ISourceLocationProvider sourceLocationProvider, ClassHierarchyAnalysis CHAnalysis) { this.host = host; this.sourceLocationProvider = sourceLocationProvider; CHA = CHAnalysis; }
/// <summary> /// Returns a unit namespace definition, nested in the given unitNamespace if possible, /// otherwise nested in the given unit if possible, otherwise nested in the given host if possible, otherwise it returns Dummy.UnitNamespace. /// If unitNamespaceReference is a root namespace, the result is equal to the given unitNamespace if not null, /// otherwise the result is the root namespace of the given unit if not null, /// otherwise the result is root namespace of unitNamespaceReference.Unit, if that can be resolved via the given host, /// otherwise the result is Dummy.UnitNamespace. /// </summary> public static IUnitNamespace Resolve(IUnitNamespaceReference unitNamespaceReference, IMetadataHost host, IUnit unit = null, IUnitNamespace unitNamespace = null) { Contract.Requires(unitNamespaceReference != null); Contract.Requires(host != null); Contract.Requires(unit != null || unitNamespace == null); Contract.Ensures(Contract.Result <IUnitNamespace>() != null); var rootNsRef = unitNamespaceReference as IRootUnitNamespaceReference; if (rootNsRef != null) { if (unitNamespace != null) { return(unitNamespace); } if (unit != null) { return(unit.UnitNamespaceRoot); } unit = UnitHelper.Resolve(unitNamespaceReference.Unit, host); if (unit is Dummy) { return(Dummy.UnitNamespace); } return(unit.UnitNamespaceRoot); } var nestedNsRef = unitNamespaceReference as INestedUnitNamespaceReference; if (nestedNsRef == null) { return(Dummy.UnitNamespace); } var containingNsDef = UnitHelper.Resolve(nestedNsRef.ContainingUnitNamespace, host, unit, unitNamespace); if (containingNsDef is Dummy) { return(Dummy.UnitNamespace); } foreach (var nsMem in containingNsDef.GetMembersNamed(nestedNsRef.Name, ignoreCase: false)) { var neNsDef = nsMem as INestedUnitNamespace; if (neNsDef != null) { return(neNsDef); } } return(Dummy.UnitNamespace); }
internal AddGenericMethodParameters(IMetadataHost host) : base(host) { }
public ILAmender(IMetadataHost host, MethodBody methodBody) : base(host, methodBody.MethodDefinition) { this.methodBody = methodBody; this.operations = methodBody.Operations ?? new List <IOperation>(); // Track existing offsets used by exception handlers if (methodBody.OperationExceptionInformation != null) { foreach (var exceptionInfo in methodBody.OperationExceptionInformation) { uint x = exceptionInfo.TryStartOffset; if (!offsetsUsedInExceptionInformation.ContainsKey(x)) { offsetsUsedInExceptionInformation.Add(x, true); } x = exceptionInfo.TryEndOffset; if (!offsetsUsedInExceptionInformation.ContainsKey(x)) { offsetsUsedInExceptionInformation.Add(x, true); } x = exceptionInfo.HandlerStartOffset; if (!offsetsUsedInExceptionInformation.ContainsKey(x)) { offsetsUsedInExceptionInformation.Add(x, true); } x = exceptionInfo.HandlerEndOffset; if (!offsetsUsedInExceptionInformation.ContainsKey(x)) { offsetsUsedInExceptionInformation.Add(x, true); } if (exceptionInfo.HandlerKind == HandlerKind.Filter) { x = exceptionInfo.FilterDecisionStartOffset; if (!offsetsUsedInExceptionInformation.ContainsKey(x)) { offsetsUsedInExceptionInformation.Add(x, true); } } } } // Create and cache labels for each branch statement foreach (var op in operations) { switch (op.OperationCode) { case OperationCode.Beq: case OperationCode.Bge: case OperationCode.Bge_Un: case OperationCode.Bgt: case OperationCode.Bgt_Un: case OperationCode.Ble: case OperationCode.Ble_Un: case OperationCode.Blt: case OperationCode.Blt_Un: case OperationCode.Bne_Un: case OperationCode.Br: case OperationCode.Brfalse: case OperationCode.Brtrue: case OperationCode.Leave: case OperationCode.Beq_S: case OperationCode.Bge_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_S: case OperationCode.Blt_Un_S: case OperationCode.Bne_Un_S: case OperationCode.Br_S: case OperationCode.Brfalse_S: case OperationCode.Brtrue_S: case OperationCode.Leave_S: uint x = (uint)op.Value; if (!offset2Label.ContainsKey(x)) { offset2Label.Add(x, new ILGeneratorLabel()); } break; case OperationCode.Switch: uint[] offsets = op.Value as uint[]; foreach (var offset in offsets) { if (!offset2Label.ContainsKey(offset)) { offset2Label.Add(offset, new ILGeneratorLabel()); } } break; default: break; } } // Automatically emit the first operation if it is a NOP (debug statement) if (operations.Count > 0 && operations[0].OperationCode == OperationCode.Nop) { EmitOperations(1); } }
/// <summary> /// Returns the Assembly identity for the assembly name. /// </summary> /// <param name="assemblyName"></param> /// <param name="metadataHost"></param> /// <returns></returns> public static AssemblyIdentity GetAssemblyIdentity(System.Reflection.AssemblyName assemblyName, IMetadataHost metadataHost) { Contract.Requires(assemblyName != null); Contract.Requires(metadataHost != null); Contract.Ensures(Contract.Result <AssemblyIdentity>() != null); string culture = assemblyName.CultureInfo == null || assemblyName.CultureInfo == System.Globalization.CultureInfo.InvariantCulture ? "neutral" : assemblyName.CultureInfo.ToString(); string name = assemblyName.Name; if (name == null) { name = string.Empty; } Version version = assemblyName.Version; if (version == null) { version = Dummy.Version; } byte[] token = assemblyName.GetPublicKeyToken(); if (token == null) { token = new byte[0]; } #if COREFX_SUBSET string codeBase = null; #else string codeBase = assemblyName.CodeBase; #endif if (codeBase == null) { codeBase = string.Empty; } return(new AssemblyIdentity(metadataHost.NameTable.GetNameFor(name), culture, version, token, codeBase)); }
private Visibility(IMetadataHost host) { this.host = host; }
internal ReferenceFixer(IMetadataHost host, INamedTypeDefinition newRoot) : base(host) { this.newRoot = newRoot; }
internal PdbLocalConstant(PdbConstant pdbConstant, IMetadataHost host, IMethodDefinition methodDefinition) { this.pdbConstant = pdbConstant; this.host = host; this.methodDefinition = methodDefinition; }
internal AddGenericParameters(IMetadataHost host, List <INamedTypeDefinition> alltypes, int number) : base(host) { this.allTypes = alltypes; this.number = number; }
public NameChanger(IMetadataHost host, Regex pattern, MatchEvaluator matchEvaluator) : base(host) { this.evaluator = matchEvaluator; this.pattern = pattern; }
public ReparentModule(IMetadataHost host, IUnit targetUnit, IUnit sourceUnit) : base(host) { this.targetUnit = targetUnit; this.sourceUnit = sourceUnit; }
public RuntimeLoader(IMetadataHost host) { this.host = host; }
/// <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 static Bpl.Program /*?*/ TranslateAssembly(List <string> assemblyNames, HeapFactory heapFactory, Options options, List <Regex> exemptionList, bool whiteList) { Contract.Requires(assemblyNames != null); Contract.Requires(heapFactory != null); var libPaths = options.libpaths; var wholeProgram = options.wholeProgram; var /*?*/ stubAssemblies = options.stub; var host = new CodeContractAwareHostEnvironment(libPaths != null ? libPaths : Enumerable <string> .Empty, true, true); Host = host; Bpl.CommandLineOptions.Install(new Bpl.CommandLineOptions()); #region Assemlies to translate (via cmd line) modules = new List <IModule>(); var contractExtractors = new Dictionary <IUnit, IContractProvider>(); var pdbReaders = new Dictionary <IUnit, PdbReader>(); #region Load *all* of the assemblies before doing anything else so that they can all vote on unification matters foreach (var a in assemblyNames) { var module = host.LoadUnitFrom(a) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { Console.WriteLine(a + " is not a PE file containing a CLR module or assembly, or an error occurred when loading it."); Console.WriteLine("Skipping it, continuing with other input assemblies"); continue; } modules.Add(module); } #endregion #region Decompile all of the assemblies var decompiledModules = new List <IModule>(); foreach (var m in modules) { PdbReader /*?*/ pdbReader = null; string pdbFile = Path.ChangeExtension(m.Location, "pdb"); if (File.Exists(pdbFile)) { Stream pdbStream = File.OpenRead(pdbFile); pdbReader = new PdbReader(pdbStream, host); } var m2 = Decompiler.GetCodeModelFromMetadataModel(host, m, pdbReader, DecompilerOptions.Unstack) as IModule; // The decompiler does not turn calls to Assert/Assume into Code Model nodes m2 = new Microsoft.Cci.MutableContracts.ContractExtractor.AssertAssumeExtractor(host, pdbReader).Rewrite(m2); decompiledModules.Add(m2); host.RegisterAsLatest(m2); contractExtractors.Add(m2, host.GetContractExtractor(m2.UnitIdentity)); pdbReaders.Add(m2, pdbReader); } modules = decompiledModules; #endregion #endregion #region Assemblies to translate (stubs) if (stubAssemblies != null) { foreach (var s in stubAssemblies) { var module = host.LoadUnitFrom(s) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { Console.WriteLine(s + " is not a PE file containing a CLR module or assembly, or an error occurred when loading it."); Console.WriteLine("Skipping it, continuing with other input assemblies"); } PdbReader /*?*/ pdbReader = null; string pdbFile = Path.ChangeExtension(module.Location, "pdb"); if (File.Exists(pdbFile)) { Stream pdbStream = File.OpenRead(pdbFile); pdbReader = new PdbReader(pdbStream, host); } module = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, DecompilerOptions.Unstack) as IModule; var copier = new CodeDeepCopier(host); var mutableModule = copier.Copy(module); var mscorlib = TypeHelper.GetDefiningUnit(host.PlatformType.SystemObject.ResolvedType); //var mutator = new ReparentModule(host, mscorlib, mutableModule); //module = mutator.Rewrite(mutableModule); //modules.Add(Tuple.Create(module, pdbReader)); RewriteUnitReferences renamer = new RewriteUnitReferences(host, mutableModule); var mscorlibAssembly = (IAssembly)mscorlib; renamer.targetAssembly = mscorlibAssembly; renamer.originalAssemblyIdentity = mscorlibAssembly.AssemblyIdentity; renamer.RewriteChildren(mutableModule); modules.Add((IModule)mutableModule); contractExtractors.Add(module, host.GetContractExtractor(module.UnitIdentity)); pdbReaders.Add(module, pdbReader); } } #endregion if (modules.Count == 0) { throw new TranslationException("No input assemblies to translate."); } //var primaryModule = modules[0]; Sink sink = new Sink(host, heapFactory, options, exemptionList, whiteList); TranslationHelper.tmpVarCounter = 0; // TODO move away, get all plugin and translators from a config file or alike #region Plugged translators List <Translator> translatorsPlugged = new List <Translator>(); ITranslationPlugin bctPlugin = new BytecodeTranslatorPlugin(wholeProgram); Translator bcTranslator = bctPlugin.getTranslator(sink, contractExtractors, pdbReaders); translatorsPlugged.Add(bcTranslator); #endregion sink.TranslationPlugins = translatorsPlugged; // TODO replace the whole translation by a translator initialization and an orchestrator calling back for each element // TODO for the current BC translator it will possibly just implement onMetadataElement(IModule) // TODO refactor this away, handle priorities between plugged translators IOrderedEnumerable <Translator> prioritizedTranslators = translatorsPlugged.OrderBy(t => t.getPriority()); foreach (Translator t in prioritizedTranslators) { t.initialize(); if (t.isOneShot()) { t.TranslateAssemblies(modules); } } foreach (var pair in sink.delegateTypeToDelegates.Values) { CreateDispatchMethod(sink, pair.Item1, pair.Item2); CreateDelegateCreateMethod(sink, pair.Item1, pair.Item2); CreateDelegateAddMethod(sink, pair.Item1, pair.Item2); CreateDelegateRemoveMethod(sink, pair.Item1, pair.Item2); } // Subtyping for extern types if (sink.Options.typeInfo > 0) { sink.DeclareExternTypeSubtyping(); } //sink.CreateIdentifierCorrespondenceTable(primaryModule.Name.Value); //var rc = new Bpl.ResolutionContext((Bpl.IErrorSink)null); //foreach (var decl in sink.TranslatedProgram.TopLevelDeclarations) { // decl.Register(rc); //} //sink.TranslatedProgram.Resolve(rc); //var goodDecls = new List<Bpl.Declaration>(); //var tc = new Bpl.TypecheckingContext(null); //foreach (var decl in sink.TranslatedProgram.TopLevelDeclarations) { // var impl = decl as Bpl.Implementation; // if (impl == null) { // goodDecls.Add(decl); // continue; // } // try { // //var tc = new Bpl.TypecheckingContext(null); // impl.Typecheck(tc); // goodDecls.Add(impl); // } catch { // Console.WriteLine("Deleting implementation for: " + impl.Name); // // nothing to do, just continue // } //} //sink.TranslatedProgram.TopLevelDeclarations = goodDecls; return(sink.TranslatedProgram); }
public RewriteUnitReferences(IMetadataHost host, Module sourceUnit) : base(host) { this.sourceUnitIdentity = sourceUnit.UnitIdentity; }