public static int Of(IMethodDefinition method, PdbReader pdb, IMetadataHost host) { if (method.HasOperations()) return method.CalculateCyclomaticComplexity(pdb, host); else return 0; }
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; }
static void Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: peToText [path]fileName.ext"); return; } using (var host = new PeReader.DefaultHost()) { IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly."); return; } PdbReader/*?*/ pdbReader = null; string pdbFile = Path.ChangeExtension(module.Location, "pdb"); if (File.Exists(pdbFile)) { Stream pdbStream = File.OpenRead(pdbFile); pdbReader = new PdbReader(pdbStream, host); } using (pdbReader) { string txtFile = Path.ChangeExtension(pdbFile, "txt"); using (var writer = new StreamWriter(txtFile)) { SourceEmitter csSourceEmitter = new SourceEmitter(writer, host, pdbReader); csSourceEmitter.Traverse((INamespaceDefinition)module.UnitNamespaceRoot); writer.Close(); } } } }
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 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 bool TrimBinaries(string sourceDir, string outputDir) { bool fSuccess = true; foreach (TrimAssembly trimAssembly in _includeSet.GetAllAssemblies()) { _currentTrimAssembly = trimAssembly; try { string sourceFile = Path.Combine(sourceDir, trimAssembly.Name + ".dll"); string outputFile = Path.Combine(outputDir, trimAssembly.Name + ".dll"); Console.WriteLine("loading assembly '" + sourceFile + "'"); IModule module = host.LoadUnitFrom(sourceFile) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { throw new Exception(sourceFile + " is not a PE file containing a CLR module or assembly, or an error occurred when loading it."); } // Working around bug DummyTraverser dummyTraverser = new DummyTraverser(); PdbReader pdbReader = null; PdbWriter pdbWriter = null; string pdbSourceFile = Path.ChangeExtension(sourceFile, "pdb"); string pdbOutputFile = Path.ChangeExtension(outputFile, "pdb"); if (File.Exists(pdbSourceFile)) { Stream pdbStream = File.OpenRead(pdbSourceFile); pdbReader = new PdbReader(pdbStream, host); pdbWriter = new PdbWriter(Path.GetFullPath(pdbOutputFile), pdbReader); } IAssembly/*?*/ assembly = module as IAssembly; if (assembly != null) { dummyTraverser.Visit(assembly); module = this.Rewrite(assembly); } else { dummyTraverser.Visit(module); module = this.Rewrite(module); } PeWriter.WritePeToStream(module, host, File.Create(outputFile), pdbReader, pdbReader, pdbWriter); } catch (Exception e) { Console.WriteLine(trimAssembly.Key + ": " + e.Message); throw; } } if (!fSuccess) Console.Error.WriteLine(String.Format("At least one of the assemblies could not be processed!")); return fSuccess; }
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 StatementTraverser(Sink sink, PdbReader/*?*/ pdbReader, bool contractContext, TraverserFactory factory) { this.sink = sink; this.factory = factory; PdbReader = pdbReader; this.contractContext = contractContext; this.captureState = sink.Options.captureState; this.PreorderVisitor = new SourceContextEmitter(this); }
private static void AnalyzeFileWithPdb(string toAnalyse, IMetadataHost host, Action<PdbReader> pdbReader) { string pdbFile = Path.ChangeExtension(toAnalyse, "pdb"); if (File.Exists(pdbFile)) using (var pdb = new PdbReader(File.OpenRead(pdbFile), host)) pdbReader(pdb); else pdbReader(null); }
static int Main(string[] args) { /* if (args == null || args.Length < 1) { Console.WriteLine("Usage: ILMutator <assembly> [<outputPath>]"); return 1; } */ String inputFile = @"c:\Users\typ\Documents\Visual Studio 2013\Projects\vererbung\vererbung\bin\Debug\vererbung.exe"; using (var host = new PeReader.DefaultHost()) { //IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule; IModule/*?*/ module = host.LoadUnitFrom(inputFile) as IModule; if (module == null || module is Dummy) { Console.WriteLine(args[0] + " is not a PE file containing a CLR assembly, or an error occurred when loading it."); return 1; } module = new MetadataDeepCopier(host).Copy(module); 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); } } else { Console.WriteLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway."); } using (pdbReader) { var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader); module = RewriteStoreLocal.RewriteModule(host, localScopeProvider, pdbReader, module); string newName; if (args.Length == 2) { //newName = args[1]; newName = @"e:\mutated.exe"; } else { var loc = module.Location; var path = Path.GetDirectoryName(loc)??""; var fileName = Path.GetFileNameWithoutExtension(loc); var ext = Path.GetExtension(loc); newName = Path.Combine(path, fileName + "1" + ext); newName = @"e:\mutated.exe"; } using (var peStream = File.Create(newName)) { using (var pdbWriter = new PdbWriter(Path.ChangeExtension(newName, ".pdb"), pdbReader)) { PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter); } } } return 0; // success } }
public MemoryVisitor(CodeContractAwareHostEnvironment host, PdbReader pdbReader, ContractProvider contractProvider, MemoryContractsInformation memoryContractsInformation, PointsToInformation pointsToInformation) { _host = host; _pdbReader = pdbReader; _contractProvider = contractProvider; _memoryContractsInformation = memoryContractsInformation; _errorReportItems = new List<ErrorReportItem>(); _pointsToInformation = pointsToInformation; }
private static void AnalyzeMethod(IMethodDefinition method, PdbReader pdb) { Console.WriteLine("\t" + method.Name); AnalyzeLocalVariables(method); AnalyzeCallOperations(method); Console.WriteLine("\t\tcc: " + CyclomaticComplexity.Of(method)); Console.WriteLine("\t\tml: " + MethodLength.Of(method)); Console.WriteLine("\t\tms: " + MethodLength.WithSymbols(method, pdb)); }
public Assembly LoadAssemblyFrom(string location, out PdbReader pdbReader) { var assembly = (IAssembly)this.LoadUnitFrom(location); if (!this.TryGetPdbReader(assembly, out pdbReader)) pdbReader = null; var decompiled = Decompiler.GetCodeModelFromMetadataModel(this, assembly, pdbReader); return new CodeDeepCopier(this, pdbReader).Copy(decompiled); }
public static int Of(IMethodDefinition method, PdbReader pdb) { if (pdb != null) { if (pdb.IsIterator(method.Body)) return -1; var locations = method.LocatedOperations(pdb); return locations.GetAllStartLinesOfInterestingOpCodes().Distinct().Count(); } return -1; }
public static int Of(IMethodDefinition method, PdbReader pdb) { if (pdb != null) { if (pdb.IsIterator(method.Body)) return -1; var locations = method.LocatedOperations(pdb); return locations.DifferenceBetweenStartAndEndlines(); } return -1; }
public static IAssembly RewriteModule(IMetadataHost host, PdbReader pdbReader, IAssembly assembly, ITypeReference contractClassType, ITypeReference compilerGeneratedAttributeType, ITypeReference systemAttributeType, ITypeReference systemBooleanType, ITypeReference systemObjectType, ITypeReference systemStringType, ITypeReference systemVoidType) { var me = new AsmMetaRewriter(host, pdbReader, contractClassType, compilerGeneratedAttributeType, systemAttributeType, systemBooleanType, systemObjectType, systemStringType, systemVoidType); return me.Rewrite(assembly); }
internal static IModule GetInstrumented(IMetadataHost host, IModule module, PdbReader/*?*/ pdbReader, INamespaceTypeDefinition logger) { var copier = new MetadataDeepCopier(host); var copy = copier.Copy(module); var loggerCopy = copier.Copy(logger); loggerCopy.ContainingUnitNamespace = copy.UnitNamespaceRoot; var logEdgeCount = TypeHelper.GetMethod(loggerCopy, host.NameTable.GetNameFor("LogEdgeCount"), host.PlatformType.SystemUInt32); new Instrumenter(host, pdbReader, logEdgeCount).Rewrite(copy); copy.AllTypes.Add(loggerCopy); return copy; }
internal Translator(IMetadataHost host, IModule module, IAssembly mscorlib, SourceEmitter source, SourceEmitter header, string location, PdbReader/*?*/ pdbReader) { Contract.Requires(host != null); Contract.Requires(module != null); Contract.Requires(mscorlib != null); Contract.Requires(source != null); Contract.Requires(header != null); Contract.Requires(location != null); this.host = host; this.module = module; this.pdbReader = pdbReader; this.currentBody = Dummy.MethodBody; this.source = source; this.header = header; this.location = location; this.sourceEmitter = header; this.arithmeticExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.ArithmeticException"); this.contextBoundObject = UnitHelper.FindType(host.NameTable, mscorlib, "System.ContextBoundObject"); this.cRuntimeAttribute = UnitHelper.FindType(host.NameTable, mscorlib, "System.CRuntimeAttribute"); this.divideByZeroExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.DivideByZeroException"); this.doNotMangleAttribute = UnitHelper.FindType(host.NameTable, mscorlib, "System.Runtime.CompilerServices.DoNotMangleAttribute"); this.invalidCastExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.InvalidCastException"); this.marshalByRefObject = UnitHelper.FindType(host.NameTable, mscorlib, "System.MarshalByRefObject"); this.overflowExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.OverflowException"); this.outOfMemoryExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.OutOfMemoryException"); this.runtimeHelpers = UnitHelper.FindType(host.NameTable, mscorlib, "System.Runtime.CompilerServices.RuntimeHelpers"); this.runtimeType = UnitHelper.FindType(host.NameTable, mscorlib, "System.RuntimeType"); this.stackOverflowExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.StackOverflowException"); this.nullReferenceExceptionType = UnitHelper.FindType(host.NameTable, mscorlib, "System.NullReferenceException"); this.threadStaticAttribute = UnitHelper.FindType(host.NameTable, mscorlib, "System.ThreadStaticAttribute"); this.vaListType = UnitHelper.FindType(host.NameTable, mscorlib, "System.CRuntime.va_list"); this.callFunctionPointer = host.NameTable.GetNameFor("CallFunctionPointer"); this.callFunctionPointer2 = host.NameTable.GetNameFor("CallFunctionPointer2"); this.getAs = host.NameTable.GetNameFor("GetAs"); this.getAsPointer = host.NameTable.GetNameFor("GetAsPointer"); this.getOffsetToStringData = host.NameTable.GetNameFor("get_OffsetToStringData"); this.baseClass0 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass0")); this.baseClass1 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass1")); this.baseClass2 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass2")); this.baseClass3 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass3")); this.baseClass4 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass4")); this.baseClass5 = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClass5")); this.baseClasses6andBeyond = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("baseClasses6andBeyond")); this.directInterfacesField = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("directlyImplementedInterfaces")); this.implementedInterfaceMapField = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("implementedInterfaceMap")); this.genericArgumentsField = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("genericArguments")); this.defaultConstructorField = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("defaultConstructor")); this.interfaceIndexField = TypeHelper.GetField(host.PlatformType.SystemType.ResolvedType, host.NameTable.GetNameFor("interfaceIndex")); this.stringEmptyField = TypeHelper.GetField(host.PlatformType.SystemString.ResolvedType, host.NameTable.GetNameFor("Empty")); this.typeField = TypeHelper.GetField(host.PlatformType.SystemObject.ResolvedType, host.NameTable.GetNameFor("type")); this.delegateTargetField = TypeHelper.GetField(host.PlatformType.SystemDelegate.ResolvedType, host.NameTable.GetNameFor("_target")); this.delegateIsStaticField = TypeHelper.GetField(host.PlatformType.SystemDelegate.ResolvedType, host.NameTable.GetNameFor("_isStatic")); this.delegateMethodPtrField = TypeHelper.GetField(host.PlatformType.SystemDelegate.ResolvedType, host.NameTable.GetNameFor("_methodPtr")); }
protected override TypeMetricsReport AnalyzeType(INamedTypeDefinition type, PdbReader pdb, IEnumerable<MethodMetricsReport> methods) { return new TypeMetricsReport { Name = type.Name(), FullName = type.FullName(), Namespaces = type.Namespaces(), CompilerGenerated = type.IsGeneratedCode(), NumberOfNonStaticPublicFields = NumberOfNonStaticPublicFields.Of(type), NumberOfMethods = NumberOfMethods.Of(type), DirectDependencies = DirectDependencies.Of(type, methods) }; }
static void Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: PeToPe [path]fileName.ext"); return; } using (var host = new PeReader.DefaultHost()) { 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; } PdbReader/*?*/ pdbReader = null; string pdbFile = module.DebugInformationLocation; if (string.IsNullOrEmpty(pdbFile)) pdbFile = Path.ChangeExtension(module.Location, "pdb"); if (File.Exists(pdbFile)) { Stream pdbStream = File.OpenRead(pdbFile); pdbReader = new PdbReader(pdbStream, host); } using (pdbReader) { //Make a mutable copy of the module. var copier = new MetadataDeepCopier(host); var mutableModule = copier.Copy(module); //Traverse the module. In a real application the MetadataVisitor and/or the MetadataTravers will be subclasses //and the traversal will gather information to use during rewriting. var traverser = new MetadataTraverser() { PreorderVisitor = new MetadataVisitor(), TraverseIntoMethodBodies = true }; traverser.Traverse(mutableModule); //Rewrite the mutable copy. In a real application the rewriter would be a subclass of MetadataRewriter that actually does something. var rewriter = new MetadataRewriter(host); var rewrittenModule = rewriter.Rewrite(mutableModule); //Write out rewritten module. using (var peStream = File.Create(rewrittenModule.Location + ".pe")) { if (pdbReader == null) { PeWriter.WritePeToStream(rewrittenModule, host, peStream); } else { //Note that the default copier and rewriter preserves the locations collections, so the original pdbReader is still a valid ISourceLocationProvider. //However, if IL instructions were rewritten, the pdbReader will no longer be an accurate ILocalScopeProvider using (var pdbWriter = new PdbWriter(pdbFile + ".pdb", pdbReader)) { PeWriter.WritePeToStream(rewrittenModule, host, peStream, pdbReader, pdbReader, pdbWriter); } } } } } }
public bool TryGetPdbReader(IAssembly assembly, out PdbReader reader) { lock (this.syncLock) { string pdbFile = Path.ChangeExtension(assembly.Location, ".pdb"); if (!this.pdbReaders.TryGetValue(pdbFile, out reader)) this.pdbReaders[pdbFile] = reader = File.Exists(pdbFile) ? new PdbReader(File.OpenRead(pdbFile), this) : null; return reader != null; } }
static void Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: ILtoC [path]fileName.ext"); return; } using (var host = new Host()) { var mscorlib = host.LoadUnitFrom("mscorlib.dll") as IAssembly; if (mscorlib == null || mscorlib is Dummy) { Console.WriteLine("mscorlib.dll must be in the same directory as "+args[0]); return; } var coreIdentity = host.CoreAssemblySymbolicIdentity; //Force the host to select the local mscorlib as the core assembly. if (coreIdentity != mscorlib.AssemblyIdentity) { Console.WriteLine("bug in host"); return; } 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; } var moduleLocation = args[0]; Contract.Assume(moduleLocation.Length > 0); PdbReader/*?*/ pdbReader = null; string pdbFileName = Path.ChangeExtension(moduleLocation, "pdb"); if (File.Exists(pdbFileName)) { using (var pdbStream = File.OpenRead(pdbFileName)) { pdbReader = new PdbReader(pdbStream, host); } } var cfile = Path.ChangeExtension(moduleLocation, ".c"); var hfile = Path.ChangeExtension(moduleLocation, ".h"); var moduleFileName = Path.GetFileName(moduleLocation); Contract.Assume(moduleFileName != null && moduleFileName.Length > 0); string location = Path.GetFullPath(moduleLocation).Replace(moduleFileName, ""); ; using (var cStreamWriter = File.CreateText(cfile)) { using (var hStreamWriter = File.CreateText(hfile)) { var cEmitter = new SourceEmitter(cStreamWriter); cEmitter.EmitString("#include \""); cEmitter.EmitString(hfile); cEmitter.EmitString("\""); cEmitter.EmitNewLine(); var hEmitter = new SourceEmitter(hStreamWriter); new Translator(host, module, mscorlib, cEmitter, hEmitter, location, pdbReader).TranslateToC(); } } } }
public CciMetadataTraverser(ReportingResult analysis, PdbReader pdbReader) { _analysis = analysis; _pdbReader = pdbReader; var missingMembers = from type in analysis.GetMissingTypes() from member in type.MissingMembers select member; _interestingMethods = missingMembers .ToDictionary(m => m.MemberName, m => m); _interestingTypes = analysis.GetMissingTypes() .Where(type => type.IsMissing) .ToDictionary(t => t.DocId, t => t); }
protected override MethodMetricsReport AnalyzeMethod(IMethodDefinition method, PdbReader pdb, IMetadataHost host) { return new MethodMetricsReport { Name = method.Name(), Signature = method.Signature(), CompilerGenerated = method.IsGeneratedCode(), OnlyDeclaration = method.IsOnlyDeclaration(), DefaultConstructor = method.IsDefaultCtor(), SourceLocation = SourceCodeLocating.Of(method, pdb), CyclomaticComplexity = CyclomaticComplexityOfAst.Of(method, pdb, host), NumberOfStatements = NumberOfStatements.Of(method, pdb, host), NumberOfRealLines = NumberOfRealLines.Of(method, pdb), NumberOfLogicalLines = NumberOfLogicalLines.Of(method, pdb), TypeDependencies = TypeDependencies.Of(method) }; }
public override IEnumerable<ISourceMappedItem> GetSourceInfo(string assemblyPath, string pdbPath, ReportingResult report) { using (var host = new HostEnvironment()) using (var pdbFs = File.OpenRead(pdbPath)) using (var pdbReader = new PdbReader(pdbFs, host)) { var metadataVisitor = new CciMetadataTraverser(report, pdbReader); var traverser = new MetadataTraverser { PreorderVisitor = metadataVisitor, TraverseIntoMethodBodies = true }; var cciAssembly = host.LoadAssembly(assemblyPath); traverser.Traverse(cciAssembly); return metadataVisitor.FoundItems; } }
static void Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: EdgeProfiler [path]fileName.ext"); return; } using (var host = new PeReader.DefaultHost()) { IModule/*?*/ 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; } var coreIdentity = host.CoreAssemblySymbolicIdentity; //force host to let args[0] determine the target platform var profiler = (IAssembly)host.LoadUnitFrom(typeof(Program).Assembly.Location); var logger = (INamespaceTypeDefinition)UnitHelper.FindType(host.NameTable, profiler, "Logger"); 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) { var instrumentedModule = Instrumenter.GetInstrumented(host, module, pdbReader, logger); var newRoot = Path.GetFileNameWithoutExtension(module.Location)+".instrumented"; var newName = newRoot+Path.GetExtension(module.Location); using (var peStream = File.Create(newName)) { if (pdbReader == null) { PeWriter.WritePeToStream(instrumentedModule, host, peStream); } else { var localScopeProvider = new ILGenerator.LocalScopeProvider(pdbReader); using (var pdbWriter = new PdbWriter(newRoot + ".pdb", pdbReader)) { PeWriter.WritePeToStream(instrumentedModule, host, peStream, pdbReader, localScopeProvider, pdbWriter); } } } } } }
static void Main(string[] args) { if (args == null || args.Length != 2) { Console.WriteLine("usage: asmmeta <input> <output>"); return; } HostEnvironment host = new HostEnvironment(); IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { Console.WriteLine(args[0]+" is not a PE file containing a CLR module or assembly."); return; } string outputFile = args[1]; string outputPDBFile = Path.ChangeExtension(args[1], "pdb"); PdbReader/*?*/ pdbReader = null; PdbWriter/*?*/ pdbWriter = null; string pdbFile = Path.ChangeExtension(module.Location, "pdb"); if (File.Exists(pdbFile)) { Stream pdbStream = File.OpenRead(pdbFile); pdbReader = new PdbReader(pdbStream, host); pdbWriter = new PdbWriter(Path.GetFullPath(outputPDBFile), pdbReader); } MetadataMutator mutator = new MetadataMutator(host); IAssembly/*?*/ assembly = module as IAssembly; if (assembly != null) { var mutable = mutator.GetMutableCopy(assembly); mutable.Name = host.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(args[1])); module = mutator.Visit(mutable); } else { var mutable = mutator.GetMutableCopy(module); mutable.Name = host.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(args[1])); module = mutator.Visit(mutable); } PeWriter.WritePeToStream(module, host, File.Create(Path.GetFullPath(outputFile)), pdbReader, pdbReader, pdbWriter); }
private AsmMetaRewriter( IMetadataHost host, PdbReader pdbReader, ITypeReference contractClassType, ITypeReference compilerGeneratedAttributeType, ITypeReference systemAttributeType, ITypeReference systemBooleanType, ITypeReference systemObjectType, ITypeReference systemStringType, ITypeReference systemVoidType ) : base(host) { this.pdbReader = pdbReader; this.MoveNextName = host.NameTable.GetNameFor("MoveNext"); this.contractClassType = contractClassType; this.compilerGeneratedAttributeType = compilerGeneratedAttributeType; this.systemAttributeType = systemAttributeType; this.systemBooleanType = systemBooleanType; this.systemObjectType = systemObjectType; this.systemStringType = systemStringType; this.systemVoidType = systemVoidType; }
public ILMutator(IMetadataHost host, PdbReader/*?*/ pdbReader) : base(host) { this.pdbReader = pdbReader; #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, PrimitiveTypeCode.NotPrimitive); this.consoleDotWriteLine = new Microsoft.Cci.MethodReference( this.host, SystemDotConsoleType, CallingConvention.Default, systemVoid, nameTable.GetNameFor("WriteLine"), 0, systemString); #endregion Get reference to Console.WriteLine }
private IEnumerable <data.Variable> ParseLocalVariables(cci.IMethodDefinition method, cci.PdbReader symbol) { IEnumerable <cci.ILocalDefinition> locals; if (symbol != null) { locals = from cci.ILocalDefinition localVar in symbol.GetLocalScopes(method.Body).SelectMany <cci.ILocalScope, cci.ILocalDefinition>(symbol.GetVariablesInScope) select localVar; } else { locals = method.Body.LocalVariables; } foreach (cci.ILocalDefinition local in locals) { data.Variable variable = new data.Variable(); variable.Name = local.Name.Value; variable.Type = ParseTypeName(local.Type); yield return(variable); } }
public void Inspect(cci.IAssembly assembly, cci.INamedTypeDefinition type, cci.IMethodDefinition method, cci.PdbReader symbol) { data.MethodInfo info = new data.MethodInfo(); info.MethodCalls = ParseMethodCalls(method); }
public void Inspect(cci.IAssembly assembly, cci.INamedTypeDefinition type, cci.PdbReader symbol) { }
public void Inspect(cci.IAssembly assembly, cci.PdbReader symbol) { }
static int RealMain(string[] args) { int errorReturnValue = -1; #region Check options ILMerge.options = new ILMergeOptions(); options.Parse(args); if (options.HelpRequested) { options.PrintOptions(""); return(errorReturnValue); } if (options.HasErrors) { options.PrintErrorsAndExit(Console.Out); } if (options.breakIntoDebugger) { System.Diagnostics.Debugger.Break(); } #endregion Version version = null; if (options.version != null) { TryGetVersionNumber(options.version, out version); } using (var host = new ILMergeHost(options.libpaths)) { if (options.libpaths != null) { foreach (var libpath in options.libpaths) { host.AddLibPath(libpath); } } Assembly /*?*/ primaryAssembly = null; var modules = new List <Module>(); var unit2SourceLocationProviderMap = new Dictionary <IUnit, ISourceLocationProvider>(); var unit2LocalScopeProviderMap = new Dictionary <IUnit, ILocalScopeProvider>(); try { for (int i = 0; i < options.GeneralArguments.Count; i++) { var unitName = options.GeneralArguments[i]; var u = host.LoadUnitFrom(unitName) as IModule; if (i == 0) { IAssembly /*?*/ assembly = u as IAssembly; if (assembly == null || assembly is Dummy) { Console.WriteLine(unitName + " is not a PE file containing a CLR assembly, or an error occurred when loading it."); return(errorReturnValue); } // Use (the copy of) the first input assembly as the merged assembly! primaryAssembly = new MetadataDeepCopier(host).Copy(assembly); } else { var copier = new MetadataDeepCopier(host, primaryAssembly); var mutableModule = copier.Copy(u); modules.Add(mutableModule); } PdbReader /*?*/ pdbReader = null; string pdbFile = Path.ChangeExtension(u.Location, "pdb"); if (File.Exists(pdbFile)) { using (var pdbStream = File.OpenRead(pdbFile)) { pdbReader = new PdbReader(pdbStream, host); } unit2SourceLocationProviderMap.Add(u, pdbReader); unit2LocalScopeProviderMap.Add(u, pdbReader); } else { Console.WriteLine("Could not load the PDB file for the unit '" + u.Name.Value + "' . Proceeding anyway."); unit2SourceLocationProviderMap.Add(u, null); } } //PdbWriter/*?*/ pdbWriter = null; RewriteUnitReferences renamer = new RewriteUnitReferences(host, modules, options); renamer.targetAssembly = primaryAssembly; renamer.originalAssemblyIdentity = primaryAssembly.AssemblyIdentity; int totalNumberOfTypes = primaryAssembly.AllTypes.Count; #region Pass 1: Mutate each input module (including the primary assembly) so everything is re-parented to the merged assembly renamer.RewriteChildren(primaryAssembly); for (int i = 0, n = modules.Count; i < n; i++) { var mutableModule = modules[i]; // call Rewrite and not RewriteChildren so dynamic dispatch can call the right rewriter method // otherwise, it just rewrites it as a module, not whatever subtype it is. renamer.Rewrite(mutableModule); // However, the rewriter does *not* rewrite parents. So need to re-parent the root unit namespace // of the mutable assembly so it points to the merged assembly. Otherwise, interning (among other // things) will not work correctly. var rootUnitNs = (RootUnitNamespace)mutableModule.UnitNamespaceRoot; rootUnitNs.Unit = primaryAssembly; totalNumberOfTypes += mutableModule.AllTypes.Count; } #endregion #region Pass 2: Collect all of the types into the merged assembly var mergedTypes = new List <INamedTypeDefinition>(totalNumberOfTypes); #region Merge together all of the <Module> classes from the input assemblies // TODO: Merge all of the <Module> classes, i.e., type 0 from each of the input assemblies mergedTypes.Add(primaryAssembly.AllTypes[0]); #endregion var internedKeys = new HashSet <string>(); // keep track of all namespace type definitions #region Types from the primary assembly for (int i = 1, n = primaryAssembly.AllTypes.Count; i < n; i++) { var t = primaryAssembly.AllTypes[i]; mergedTypes.Add(t); if (t is INamespaceTypeDefinition) // don't care about nested types { var key = TypeHelper.GetTypeName(t, NameFormattingOptions.None); internedKeys.Add(key); } } #endregion #region Types from the other input assemblies, taking care of duplicates for (int i = 0, n = modules.Count; i < n; i++) { var module = modules[i]; var unitName = module.Name.Value; for (int j = 1, m = module.AllTypes.Count; j < m; j++) { var t = module.AllTypes[j]; var namespaceTypeDefinition = t as NamespaceTypeDefinition; // duplicates can be only at the top-level: namespace type definitions // if a namespace type definition is unique, then so are all of its nested types if (namespaceTypeDefinition != null) { var typeName = TypeHelper.GetTypeName(namespaceTypeDefinition, NameFormattingOptions.UseGenericTypeNameSuffix); if (internedKeys.Contains(typeName)) // error: duplicate! { if (!namespaceTypeDefinition.IsPublic || options.allowDup) { var newName = String.Format("{0}_from_{1}", namespaceTypeDefinition.Name.Value, unitName); namespaceTypeDefinition.Name = host.NameTable.GetNameFor(newName); var newTypeName = TypeHelper.GetTypeName(namespaceTypeDefinition, NameFormattingOptions.UseGenericTypeNameSuffix); Console.WriteLine("Adding '{0}' as '{1}'", typeName, newTypeName); internedKeys.Add(typeName); t = namespaceTypeDefinition; } else { Console.WriteLine("Error: Duplicate type '{0}'", typeName); continue; //TODO: set a flag somewhere to force a failure. } } else { //Console.WriteLine("Adding '{0}'", typeName); internedKeys.Add(typeName); } } mergedTypes.Add(t); } } #endregion primaryAssembly.AllTypes = mergedTypes; #endregion CopyResourcesToPrimaryAssembly(primaryAssembly, modules); if (version != null) { primaryAssembly.Version = version; } string outputPath; if (options.output != null) { outputPath = options.output; } else { outputPath = primaryAssembly.Name.Value + Path.GetExtension(options.GeneralArguments[0]) + ".meta"; } using (var aggregateSourceLocationProvider = new AggregatingSourceLocationProvider(unit2SourceLocationProviderMap)) { using (var aggregateLocalScopeProvider = new AggregatingLocalScopeProvider(unit2LocalScopeProviderMap)) { using (var peStream = File.Create(outputPath)) { using (var pdbWriter = new PdbWriter(Path.ChangeExtension(outputPath, "pdb"), aggregateSourceLocationProvider)) { PeWriter.WritePeToStream(primaryAssembly, host, peStream, aggregateSourceLocationProvider, aggregateLocalScopeProvider, pdbWriter); } } } } } finally { } return(0); // success } }