internal void Write(PeWriter wtr, ref uint datPtr) { for (int i = 0; i < 8; i++) { if (i < n.Length) { wtr.Write((byte)n[i]); } else { wtr.Write((byte)0); } } wtr.Write((uint)vSize); wtr.Write((uint)vPtr); wtr.Write((uint)dat.Length); wtr.Write((uint)datPtr); wtr.Write((uint)relocPtr); wtr.Write((uint)lnPtr); wtr.Write((ushort)relocNo); wtr.Write((ushort)lnNo); wtr.Write((uint)c); wtr.SaveLocation(); wtr.SetPosition(datPtr); wtr.Write(dat); wtr.LoadLocation(); datPtr += (uint)dat.Length; }
private static void TranslateToExe(SpecSharpOptions commandLineOptions) //^ requires commandLineOptions.FileNames.Count > 0; { HostEnvironment hostEnvironment = new HostEnvironment(); hostEnvironment.Errors += hostEnvironment.HandleErrors; hostEnvironment.displayFileName = true; List <IAssemblyReference> assemblyReferences = GetAssemblyReferences(commandLineOptions, hostEnvironment); List <IModuleReference> moduleReferences = new List <IModuleReference>(); List <SpecSharpSourceDocument> programSources = new List <SpecSharpSourceDocument>(1); IName name = hostEnvironment.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(commandLineOptions.FileNames[0])); SpecSharpAssembly assem = new SpecSharpAssembly(name, Path.GetFullPath(name.Value), hostEnvironment, commandLineOptions, assemblyReferences, moduleReferences, programSources); SpecSharpCompilationHelper helper = new SpecSharpCompilationHelper(assem.Compilation); foreach (string fileName in commandLineOptions.FileNames) { name = hostEnvironment.NameTable.GetNameFor(fileName); StreamReader instream = File.OpenText(fileName); programSources.Add(new SpecSharpSourceDocument(helper, name, Path.GetFullPath(fileName), instream)); } if (assem.Compilation.HasErrors) { return; } var sourceLocationProvider = assem.Compilation.SourceLocationProvider; var localScopeProvider = assem.Compilation.LocalScopeProvider; using (var pdbWriter = new PdbWriter(Path.ChangeExtension(assem.Location, "pdb"), sourceLocationProvider)) { PeWriter.WritePeToStream(assem, hostEnvironment, File.Create(Path.ChangeExtension(assem.Location, "exe")), sourceLocationProvider, localScopeProvider, pdbWriter); } }
public void Write(PeWriter wtr) { wtr.SetPosition(StandardFieldsOffset); sf.Write(wtr); wsf.Write(wtr); dd.Write(wtr); }
void AssertWriteToPeFile(PeVerifyResult expectedResult, IAssembly assembly, string pdbPath) { var validator = new MetadataValidator(this.host); List <Microsoft.Cci.ErrorEventArgs> errorEvents = new List <Microsoft.Cci.ErrorEventArgs>(); this.host.Errors += (object sender, Microsoft.Cci.ErrorEventArgs e) => errorEvents.Add(e); validator.Validate(assembly); Debug.Assert(errorEvents.Count == 0); using (var rewrittenFile = File.Create(assembly.Location)) { if (pdbPath != null) { using (var f = File.OpenRead(pdbPath)) { using (var pdbReader = new PdbReader(f, host)) { using (var pdbWriter = new PdbWriter(Path.GetFullPath(assembly.Location + ".pdb"), pdbReader)) { PeWriter.WritePeToStream(assembly, host, rewrittenFile, pdbReader, pdbReader, pdbWriter); } } } } else { using (var pdbWriter = new PdbWriter(Path.GetFullPath(assembly.Location + ".pdb"), null)) { PeWriter.WritePeToStream(assembly, host, rewrittenFile, null, null, pdbWriter); } } } Assert.True(File.Exists(assembly.Location)); PeVerify.Assert(expectedResult, PeVerify.VerifyAssembly(assembly.Location, true)); }
public void Write(PeWriter wtr) { wtr.SetPosition(SectionHeadersOffset); uint datPtr = SectionHeadersOffset + 40 * (uint)this.Count; if (file.Type == PeFileType.Image) { uint align = file.OptionalHeader.WindowsSpecificFields.FileAlignment; if (datPtr < align) { datPtr = align; } else { uint newPtr = align; while (datPtr > align) { newPtr += align; datPtr -= align; } datPtr = newPtr; } } for (int i = 0; i < file.PEHeader.NumberOfSections; i++) { Items[i].Write(wtr, ref datPtr); } }
private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null) { // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name. string facadeFileName = Path.GetFileName(contract.Location); string facadeOutputPath = Path.Combine(facadePath, facadeFileName); using (Stream peOutStream = File.Create(facadeOutputPath)) { if (pdbLocation != null) { if (File.Exists(pdbLocation)) { string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb"); using (Stream pdbReadStream = File.OpenRead(pdbLocation)) using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost)) using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader)) { PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter); } } else { throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation); } } else { PeWriter.WritePeToStream(facade, seedHost, peOutStream); } } }
static void Main(string[] args) { using (var host = new HelloHost()) { var nameTable = host.NameTable; var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity); var aname = nameTable.GetNameFor("hello"); var mname = nameTable.GetNameFor("hello.exe"); var arefs = IteratorHelper.GetSingletonEnumerable <IAssemblyReference>(coreAssembly); var source = new HelloSourceDocument(aname); var sources = IteratorHelper.GetSingletonEnumerable <HelloSourceDocument>(source); var helloAssembly = new HelloAssembly(aname, host, mname, arefs, sources); var sourceLocationProvider = helloAssembly.Compilation.SourceLocationProvider; var localScopeProvider = helloAssembly.Compilation.LocalScopeProvider; using (var sourceFile = File.CreateText("hello.cs")) { sourceFile.WriteLine("hello"); } using (var peStream = File.Create("hello.exe")) { using (var pdbWriter = new PdbWriter("hello.pdb", sourceLocationProvider)) { PeWriter.WritePeToStream(helloAssembly, host, peStream, helloAssembly.Compilation.SourceLocationProvider, helloAssembly.Compilation.LocalScopeProvider, pdbWriter); } } } }
static void Main(string[] argv) { if (argv == null || argv.Length < 1) { Console.WriteLine("Usage: Main <assemblys> [<outputPath>]"); } using (var host = new PeReader.DefaultHost()) { var module = host.LoadUnitFrom(argv[0]) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { throw new Exception(argv[0] + " is not a PE file containing a CLR assembly, or an error occurred when loading it."); } 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 copy = new MetadataDeepCopier(host).Copy(module); var shadowFieldsAddedAssembly = new ShadowFieldRewriter(host).Rewrite(copy); var shadowFieldsAndMethodsAddedAssembly = new ShadowMethodRewriter(host).Rewrite(shadowFieldsAddedAssembly); var rewrittenAssembly = new FinalizeMethodRewriter(host).Rewrite(shadowFieldsAndMethodsAddedAssembly); var main = rewrittenAssembly.EntryPoint.ResolvedMethod; if (main != Dummy.Method) { var body = main.Body as MethodBody; if (body != null) { new AddGCWaitForFinalization(host, body).Rewrite(); } } var validator = new MetadataValidator(host); validator.Validate(rewrittenAssembly as IAssembly); string outputPath = rewrittenAssembly.Location + ".meta"; var outputFileName = Path.GetFileNameWithoutExtension(outputPath); // Need to not pass in a local scope provider until such time as we have one that will use the mutator // to remap things (like the type of a scope constant) from the original assembly to the mutated one. using (var peStream = File.Create(outputPath)) { using (var pdbWriter = new PdbWriter(outputFileName + ".pdb", pdbReader)) { PeWriter.WritePeToStream(rewrittenAssembly, host, peStream, pdbReader, null, pdbWriter); } } } } }
public override void Write(PeWriter wtr) { wtr.BaseStream.Position = 0; wtr.Write((ushort)m); wtr.Write(hc); wtr.Write((uint)o); wtr.Write(ds); }
private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null) { bool needsConversion = false; string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb"); string finalPdbOutputPath = pdbOutputPath; // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name. string facadeFileName = Path.GetFileName(contract.Location); string facadeOutputPath = Path.Combine(facadePath, facadeFileName); using (Stream peOutStream = File.Create(facadeOutputPath)) { if (pdbLocation != null) { if (File.Exists(pdbLocation)) { // Convert from portable to windows PDBs if necessary. If we convert // set the pdbOutput path to a *.windows.pdb file so we can convert it back // to 'finalPdbOutputPath'. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { needsConversion = ConvertFromPortableIfNecessary(facade.Location, ref pdbLocation); } if (needsConversion) { // We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server string pdbOutputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbOutputPath), "WindowsPdb"); Directory.CreateDirectory(pdbOutputPathPdbDir); pdbOutputPath = Path.Combine(pdbOutputPathPdbDir, Path.GetFileName(pdbOutputPath)); } // do the main GenFacades logic (which today only works with windows PDBs). using (Stream pdbReadStream = File.OpenRead(pdbLocation)) using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost)) using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader)) { PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter); } } else { throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation); } } else { PeWriter.WritePeToStream(facade, seedHost, peOutStream); } } // If we started with Portable PDBs we need to convert the output to portable again. // We have to do this after facadeOutputPath is closed for writing. if (needsConversion) { Trace.TraceInformation("Converting PDB generated by GenFacades " + pdbOutputPath + " to portable format " + finalPdbOutputPath); ConvertFromWindowsPdb(facadeOutputPath, pdbOutputPath, finalPdbOutputPath); } }
public void Write(PeWriter wtr) { wtr.SetPosition(hdr.DataDirectoriesOffset); for (int i = 0; i < 16; i++) { wtr.Write(Items[i].Address); wtr.Write(Items[i].Size); } }
static int Main(string[] args) { if (args == null || args.Length < 1) { Console.WriteLine("Usage: ILMutator <assembly> [<outputPath>]"); return(1); } 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 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); ILMutator mutator = new ILMutator(host, pdbReader); module = mutator.Rewrite(module); string newName; if (args.Length == 2) { newName = args[1]; } 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); } 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 } }
void AssertWriteToPeFile(PeVerifyResult expectedResult, IAssembly assembly, PdbReader pdbReader) { using (var rewrittenFile = File.Create(assembly.Location)) { using (var pdbWriter = new PdbWriter(Path.GetFullPath(assembly.Location + ".pdb"), pdbReader)) { PeWriter.WritePeToStream(assembly, host, rewrittenFile, pdbReader, pdbReader, pdbWriter); } } Assert.True(File.Exists(assembly.Location)); PeVerify.Assert(expectedResult, PeVerify.VerifyAssembly(assembly.Location, true)); }
public override string Run(string tempFolder) { var assembly = Generate(); var fileName = assembly.Kind == ModuleKind.DynamicallyLinkedLibrary ? DllName : ExeName; var resultPath = Path.Combine(tempFolder, fileName); using (var fs = File.Create(resultPath)) PeWriter.WritePeToStream(assembly, Host, fs); return(resultPath); }
public void Save(PeWriter wtr, uint adr) { wtr.SetPosition(adr); foreach (CertificateEntry i in items) { wtr.Write((uint)i.CertificateData.Length + 8); wtr.Write((ushort)i.Revision); wtr.Write((ushort)i.CertificateType); wtr.Write(i.CertificateData); } }
void AssertWriteToPeFile(PeVerifyResult expectedResult, IAssembly assembly) { using (FileStream rewrittenFile = File.Create(assembly.Location)) { using (this.pdbReader) { PeWriter.WritePeToStream(assembly, this.host, rewrittenFile, this.pdbReader, this.pdbReader, this.pdbWriter); } } Assert.True(File.Exists(assembly.Location)); PeVerify.Assert(expectedResult, PeVerify.VerifyAssembly(assembly.Location)); }
public override void Write(PeWriter wtr) { wtr.SetPosition(PEHeaderOffset); wtr.Write((ushort)m); wtr.Write((ushort)noSect); wtr.WriteStamp(stamp); wtr.Write((uint)ptrSym); wtr.Write((uint)noSym); wtr.Write((ushort)sOh); wtr.Write((ushort)c); }
internal static void EmitCorLibWithAssemblyReferences( Compilation comp, string pdbPath, Func <CommonPEModuleBuilder, EmitOptions, CommonPEModuleBuilder> getModuleBuilder, out ImmutableArray <byte> peBytes, out ImmutableArray <byte> pdbBytes) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0").WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var moduleBuilder = comp.CheckOptionsAndCreateModuleBuilder( diagnostics, null, emitOptions, null, null, null, null, default(CancellationToken)); // Wrap the module builder in a module builder that // reports the "System.Object" type as having no base type. moduleBuilder = getModuleBuilder(moduleBuilder, emitOptions); bool result = comp.Compile( moduleBuilder, emittingPdb: pdbPath != null, diagnostics: diagnostics, filterOpt: null, cancellationToken: default(CancellationToken)); using (var peStream = new MemoryStream()) { using (var pdbStream = new MemoryStream()) { PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), comp.MessageProvider, () => peStream, () => pdbStream, null, null, metadataOnly: true, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, cancellationToken: default(CancellationToken)); peBytes = peStream.ToImmutable(); pdbBytes = pdbStream.ToImmutable(); } } diagnostics.Verify(); diagnostics.Free(); }
public override void Write(PeWriter wtr) { wtr.SetPosition(hdr.WindowsSpecificFieldsOffset); if (hdr.Type == ExecutableType.PE32Plus) { wtr.Write((ulong)imgBas); wtr.Write((uint)sectA); wtr.Write((uint)fA); wtr.Write((ushort)maOs); wtr.Write((ushort)miOs); wtr.Write((ushort)maImg); wtr.Write((ushort)miImg); wtr.Write((ushort)maSs); wtr.Write((ushort)miSs); wtr.Write((uint)winVer); wtr.Write((uint)sImg); wtr.Write((uint)sHdr); wtr.Write((uint)cs); wtr.Write((ushort)Ss); wtr.Write((ushort)dll); wtr.Write((ulong)sSr); wtr.Write((ulong)sSc); wtr.Write((ulong)sHr); wtr.Write((ulong)sHc); wtr.Write((uint)ldrF); wtr.Write((uint)noDd); } else { wtr.Write((uint)imgBas); wtr.Write((uint)sectA); wtr.Write((uint)fA); wtr.Write((ushort)maOs); wtr.Write((ushort)miOs); wtr.Write((ushort)maImg); wtr.Write((ushort)miImg); wtr.Write((ushort)maSs); wtr.Write((ushort)miSs); wtr.Write((uint)winVer); wtr.Write((uint)sImg); wtr.Write((uint)sHdr); wtr.Write((uint)cs); wtr.Write((ushort)Ss); wtr.Write((ushort)dll); wtr.Write((uint)sSr); wtr.Write((uint)sSc); wtr.Write((uint)sHr); wtr.Write((uint)sHc); wtr.Write((uint)ldrF); wtr.Write((uint)noDd); } }
private static int RunTest(HostEnvironment hostEnvironment, string suiteName, string test, StringBuilder actualOutput, List <string> compilerParameters, List <string> testCaseParameters) { hostEnvironment.hasError = false; IName name = hostEnvironment.NameTable.GetNameFor(suiteName); SpecSharpOptions options = new SpecSharpOptions(); //TODO: extract from params List <IAssemblyReference> assemblyReferences = new List <IAssemblyReference>(); List <IModuleReference> moduleReferences = new List <IModuleReference>(); assemblyReferences.Add(hostEnvironment.LoadAssembly(hostEnvironment.CoreAssemblySymbolicIdentity)); IUnit unit; SpecSharpAssembly /*?*/ assem = null; SpecSharpCompilationHelper helper; if (hostEnvironment.previousDocument != null && compilerParameters.Contains("/incremental")) { unit = hostEnvironment.GetIncrementalUnit(test); helper = (SpecSharpCompilationHelper)hostEnvironment.previousDocument.SpecSharpCompilationPart.Helper; } else { List <SpecSharpSourceDocument> programSources = new List <SpecSharpSourceDocument>(1); assem = new SpecSharpAssembly(name, "", hostEnvironment, options, assemblyReferences, moduleReferences, programSources); helper = new SpecSharpCompilationHelper(assem.Compilation); programSources.Add(hostEnvironment.previousDocument = new SpecSharpSourceDocument(helper, name, "", test)); unit = assem; } if (assem != null && assem.Compilation.HasErrors) { return(0); } if (assem != null && assem.EntryPoint.ResolvedMethod != Dummy.Method) { var memStream = new MemoryStream(); PeWriter.WritePeToStream(assem, hostEnvironment, memStream); if (hostEnvironment.hasError) { return(0); } var runtimeAssembly = System.Reflection.Assembly.Load(memStream.ToArray()); var result = runtimeAssembly.EntryPoint.Invoke(null, null); if (result is int) { return((int)result); } return(0); } BaseCodeTraverser traverser = new BaseCodeTraverser(); unit.Dispatch(traverser); return(0); }
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); } } } } } }
public void WriteToStream(IModuleInfo moduleInfo, FileStream stream, string filePath) { var module = (ModuleInfo)moduleInfo; if (module.PdbReader == null) { PeWriter.WritePeToStream(module.Module, _host, stream); } else { using (var pdbWriter = new PdbWriter(Path.ChangeExtension(filePath, "pdb"), module.PdbReader)) { PeWriter.WritePeToStream(module.Module, _host, stream, module.PdbReader, module.PdbReader, pdbWriter); } } }
public override void Write(PeWriter wtr) { wtr.SetPosition(hdr.StandardFieldsOffset); wtr.Write((ushort)hdr.t); wtr.Write(maL); wtr.Write(miL); wtr.Write(sC); wtr.Write(sI); wtr.Write(sU); wtr.Write(entry); wtr.Write(bc); if (Magic != ExecutableType.PE32Plus) { wtr.Write(bd); } }
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); }
public void Save(string fileName) { var pdbName = Path.ChangeExtension(fileName, "pdb"); using (var peStream = File.Create(fileName)) { if (this.PdbReader == null) { PeWriter.WritePeToStream(this.Module, this.Host, peStream); } else { using (var pdbWriter = new PdbWriter(pdbName, this.PdbReader)) PeWriter.WritePeToStream(this.Module, this.Host, peStream, this.PdbReader, this.PdbReader, pdbWriter); } } }
private static void RewriteBinary( Assembly copy, AssemblyReport assemblyReport, MetadataReaderHost host, string outputPath, MethodRemoval methodRemoval, StubMethodBodyEmitter stubEmitter) { /* This is an attempt to decouple the MethodRemoval commandline options * from the tree shaker, but it doesn't really seem to be working. * Might be better to just pass the method removal directly to * the rewriter. */ bool removeMethods = (methodRemoval == MethodRemoval.Remove); bool fullDebugStubs = (methodRemoval == MethodRemoval.Debug); bool dryRun = (methodRemoval == MethodRemoval.None); PdbReader /*?*/ pdbReader = null; string pdbFile = Path.ChangeExtension(copy.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 '" + copy.Name.Value + "' . Proceeding anyway."); } using (pdbReader) { var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader); var pdbPath = Path.ChangeExtension(outputPath, ".pdb"); var outputFileName = Path.GetFileNameWithoutExtension(outputPath); using (var peStream = File.Create(outputPath)) { using (var pdbWriter = new PdbWriter(pdbPath, pdbReader)) { var rewriter = new TreeShakingRewriter(host, assemblyReport, dryRun, removeMethods, fullDebugStubs, stubEmitter); IAssembly rewrittenCopy = rewriter.Rewrite(copy); PeWriter.WritePeToStream(rewrittenCopy, host, peStream, pdbReader, localScopeProvider, pdbWriter); } } } }
public void Save(CciAssembly assembly, string path) { Contract.Requires(assembly != null); Contract.Requires(!string.IsNullOrEmpty(path)); var sourceLocationProvider = GetPdbReader(assembly.Module); lock (turnstile) { ContractHelper.InjectContractCalls(host, assembly.Module, assembly.ContractProvider, sourceLocationProvider); } using (var peStream = File.Create(path)) { lock (turnstile) { PeWriter.WritePeToStream(assembly.Module, host, peStream); } } }
public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: PInvokeCompiler Input.dll Output.dll"); return; } var inputFile = args[0]; var outputFile = args[1]; using (var host = new PeReader.DefaultHost()) { var unit = host.LoadUnitFrom(inputFile); var assembly = unit as IAssembly; if (assembly == null) { Console.WriteLine("Error: Input file not loadable as assembly"); return; } Assembly mutable = new MetadataDeepCopier(host).Copy(assembly); var interopHelperReference = new InteropHelperReferences(host, mutable); var pinvokeMethodMetadataTraverser = new PInvokeMethodMetadataTraverser(interopHelperReference.PInvokeHelpers); pinvokeMethodMetadataTraverser.TraverseChildren(mutable); var methodTransformationMetadataRewriter = new MethodTransformationMetadataRewriter(interopHelperReference.LoadLibrary, interopHelperReference.GetProcAddress, interopHelperReference.IsLibraryInitialized, host, pinvokeMethodMetadataTraverser); methodTransformationMetadataRewriter.RewriteChildren(mutable); var pinvokeMethodMetadataRewriter = new PInvokeMethodMetadataRewriter(interopHelperReference, host, methodTransformationMetadataRewriter); pinvokeMethodMetadataRewriter.RewriteChildren(mutable); using (var stream = File.Create(outputFile)) { PeWriter.WritePeToStream(mutable, host, stream); } } }
public MemoryStream WriteToStream(IModuleInfo moduleInfo) { var module = (ModuleInfo)moduleInfo; _log.Info("CommonCompilerInfra.WriteToFile:" + module.Name); MemoryStream stream = new MemoryStream(); if (module.PdbReader == null) { PeWriter.WritePeToStream(module.Module, _host, stream); } else { throw new NotImplementedException(); // using (var pdbWriter = new PdbWriter(Path.ChangeExtension(filePath, "pdb"), module.PdbReader)) // { // PeWriter.WritePeToStream(module.Module, _host, stream, module.SourceLocationProvider, // module.LocalScopeProvider, pdbWriter); // } } stream.Position = 0; return(stream); }
/// <summary> /// Validates that the given stream is marked as signed, the signature matches /// the public key, and the header checksum is correct. /// </summary> public static bool IsStreamFullSigned(Stream moduleContents) { var savedPosition = moduleContents.Position; try { moduleContents.Position = 0; var peHeaders = new PEHeaders(moduleContents); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents, leaveOpen: true)) { var metadataReader = metadata.MetadataReader; var peReader = metadata.Module.PEReaderOpt; var flags = peHeaders.CorHeader.Flags; if (CorFlags.StrongNameSigned != (flags & CorFlags.StrongNameSigned)) { return(false); } var snDirectory = peReader.PEHeaders.CorHeader.StrongNameSignatureDirectory; if (!peHeaders.TryGetDirectoryOffset(snDirectory, out int snOffset)) { return(false); } moduleContents.Position = 0; int peSize; try { peSize = checked ((int)moduleContents.Length); } catch { return(false); } var peImage = new BlobBuilder(peSize); if (peSize != peImage.TryWriteBytes(moduleContents, peSize)) { return(false); } byte[] buffer = GetBlobBuffer(peImage.GetBlobs().Single()); uint expectedChecksum = peHeaders.PEHeader.CheckSum; Blob checksumBlob = MakeBlob(buffer, peHeaders.PEHeaderStartOffset + ChecksumOffset, sizeof(uint)); if (expectedChecksum != PeWriter.CalculateChecksum(peImage, checksumBlob)) { return(false); } int snSize = snDirectory.Size; byte[] hash = ComputeSigningHash(peImage, peHeaders, checksumBlob, snOffset, snSize); ImmutableArray <byte> publicKeyBlob = metadataReader.GetBlobContent(metadataReader.GetAssemblyDefinition().PublicKey); // RSA parameters start after the public key offset byte[] publicKeyParams = new byte[publicKeyBlob.Length - CryptoBlobParser.s_publicKeyHeaderSize]; publicKeyBlob.CopyTo(CryptoBlobParser.s_publicKeyHeaderSize, publicKeyParams, 0, publicKeyParams.Length); var snKey = publicKeyParams.ToRSAParameters(includePrivateParameters: false); using (var rsa = RSA.Create()) { rsa.ImportParameters(snKey); var reversedSignature = peReader.GetSectionData(snDirectory.RelativeVirtualAddress).GetContent(0, snSize).ToArray(); // Unknown why the signature is reversed, but this matches the behavior of the CLR // signing implementation. Array.Reverse(reversedSignature); if (!rsa.VerifyHash(hash, reversedSignature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)) { return(false); } } return(true); } } finally { moduleContents.Position = savedPosition; } }