本文整理汇总了C#中System.Reflection.PortableExecutable.PEReader类的典型用法代码示例。如果您正苦于以下问题:C# PEReader类的具体用法?C# PEReader怎么用?C# PEReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PEReader类属于System.Reflection.PortableExecutable命名空间,在下文中一共展示了PEReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Main
private static void Main(string[] args)
{
bool removeDirectory;
string temporaryDirectory = GetTemporaryDirectory(out removeDirectory);
Console.WriteLine("Working directory: {0}", temporaryDirectory);
try
{
IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2/");
PackageManager packageManager = new PackageManager(sourceRepository, temporaryDirectory);
packageManager.PackageInstalled += HandlePackageInstalled;
packageManager.InstallPackage("Microsoft.Bcl.Immutable", SemanticVersion.Parse("1.0.34"));
packageManager.InstallPackage("System.Collections.Immutable", SemanticVersion.Parse("1.1.33-beta"));
using (PEReader referenceAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "Microsoft.Bcl.Immutable.1.0.34", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll"))))
{
using (PEReader newAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "System.Collections.Immutable.1.1.33-beta", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll"))))
{
Analyzer analyzer = new Analyzer(referenceAssembly, newAssembly, null);
analyzer.Run();
}
}
}
finally
{
if (removeDirectory)
Directory.Delete(temporaryDirectory, true);
}
}
开发者ID:modulexcite,项目名称:dotnet-compatibility,代码行数:29,代码来源:Program.cs
示例2: sizeof
+ sizeof(Int64); // metadata directory
private static bool ExecuteCore(string assemblyPath)
{
if (Directory.Exists(assemblyPath))
{
Console.Error.WriteLine($"Expected file, not a directory: {assemblyPath}");
return false;
}
if (!File.Exists(assemblyPath))
{
Console.Error.WriteLine($"File not found: {assemblyPath}");
return false;
}
using (var stream = OpenFile(assemblyPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var reader = new PEReader(stream))
using (var writer = new BinaryWriter(stream))
{
if (!Validate(reader))
{
Console.Error.WriteLine($"Unable to sign {assemblyPath}");
return false;
}
stream.Position = reader.PEHeaders.CorHeaderStartOffset + OffsetFromStartOfCorHeaderToFlags;
writer.Write((UInt32)(reader.PEHeaders.CorHeader.Flags | CorFlags.StrongNameSigned));
}
return true;
}
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:32,代码来源:Program.cs
示例3: InspectableAssembly
public InspectableAssembly(string filename, ParseContext context)
{
Stream = File.OpenRead(filename);
Pe = new PEReader(Stream);
Reader = Pe.GetMetadataReader();
Context = context;
}
开发者ID:CurlyBrackets,项目名称:FlexCommonCompiler,代码行数:7,代码来源:InspectableAssembly.cs
示例4: TryGetAssemblyIdentity
public static AssemblyIdentity TryGetAssemblyIdentity(string filePath)
{
try
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))
using (var peReader = new PEReader(stream))
{
var metadataReader = peReader.GetMetadataReader();
AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
string name = metadataReader.GetString(assemblyDefinition.Name);
Version version = assemblyDefinition.Version;
StringHandle cultureHandle = assemblyDefinition.Culture;
string cultureName = (!cultureHandle.IsNil) ? metadataReader.GetString(cultureHandle) : null;
AssemblyFlags flags = assemblyDefinition.Flags;
bool hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
BlobHandle publicKeyHandle = assemblyDefinition.PublicKey;
ImmutableArray<byte> publicKeyOrToken = !publicKeyHandle.IsNil
? metadataReader.GetBlobBytes(publicKeyHandle).AsImmutableOrNull()
: default(ImmutableArray<byte>);
return new AssemblyIdentity(name, version, cultureName, publicKeyOrToken, hasPublicKey);
}
}
catch { }
return null;
}
开发者ID:RoryVL,项目名称:roslyn,代码行数:30,代码来源:AssemblyIdentityUtils.cs
示例5: PE
public PE(string fileName)
{
FileName = Path.GetFullPath(fileName);
Uri = new Uri(FileName);
IsPEFile = false;
try
{
_fs = File.OpenRead(FileName);
byte byteRead = (byte)_fs.ReadByte();
if (byteRead != 'M') { return; }
byteRead = (byte)_fs.ReadByte();
if (byteRead != 'Z') { return; }
_fs.Seek(0, SeekOrigin.Begin);
_peReader = new PEReader(_fs);
PEHeaders = _peReader.PEHeaders;
IsPEFile = true;
}
catch (IOException e) { LoadException = e; }
catch (BadImageFormatException e) { LoadException = e; }
catch (UnauthorizedAccessException e) { LoadException = e; }
if (IsPEFile)
{
m_pImage = new SafePointer(_peReader.GetEntireImage().GetContent().ToBuilder().ToArray());
if (IsManaged)
{
_metadataReader = _peReader.GetMetadataReader();
}
}
}
开发者ID:blinds52,项目名称:binskim,代码行数:34,代码来源:PE.cs
示例6: Main
static void Main(string[] args)
{
if (args.Length == 0 || new[] {"/?", "-?", "-h", "--help"}.Any(x => string.Equals(args[0], x, StringComparison.OrdinalIgnoreCase)))
{
PrintUsage();
return;
}
foreach (var fileName in args)
{
Console.WriteLine(fileName);
Console.WriteLine(new string('*', 80));
try
{
using (var stream = File.OpenRead(fileName))
using (var peFile = new PEReader(stream))
{
var metadataReader = peFile.GetMetadataReader();
var visualizer = new MetadataVisualizer(metadataReader, Console.Out);
visualizer.Visualize();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
开发者ID:modulexcite,项目名称:dotnetsamples-1,代码行数:29,代码来源:Program.cs
示例7: Validate
/// <summary>
/// Returns true if the PE file meets all of the pre-conditions to be Open Source Signed.
/// Returns false and logs msbuild errors otherwise.
/// </summary>
private bool Validate(PEReader peReader)
{
if (!peReader.HasMetadata)
{
LogError("PE file is not a managed module.");
return false;
}
var mdReader = peReader.GetMetadataReader();
if (!mdReader.IsAssembly)
{
LogError("PE file is not an assembly.");
return false;
}
CorHeader header = peReader.PEHeaders.CorHeader;
if ((header.Flags & CorFlags.StrongNameSigned) == CorFlags.StrongNameSigned)
{
LogError("PE file is already strong-name signed.");
return false;
}
if ((header.StrongNameSignatureDirectory.Size <= 0) || mdReader.GetAssemblyDefinition().PublicKey.IsNil)
{
LogError("PE file is not a delay-signed assembly.");
return false;
}
return true;
}
开发者ID:TerabyteX,项目名称:buildtools,代码行数:34,代码来源:OpenSourceSign.cs
示例8: Create
public static EcmaModule Create(TypeSystemContext context, PEReader peReader, PdbSymbolReader pdbReader)
{
MetadataReader metadataReader = CreateMetadataReader(context, peReader);
if (metadataReader.IsAssembly)
return new EcmaAssembly(context, peReader, metadataReader, pdbReader);
else
return new EcmaModule(context, peReader, metadataReader, pdbReader);
}
开发者ID:krytarowski,项目名称:corert,代码行数:9,代码来源:EcmaModule.Symbols.cs
示例9: OpenNativeImage
public void OpenNativeImage()
{
using (var reader = new PEReader(File.OpenRead(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernel32.dll"))))
{
Assert.False(reader.HasMetadata);
Assert.True(reader.PEHeaders.IsDll);
Assert.False(reader.PEHeaders.IsExe);
Assert.Throws<InvalidOperationException>(() => reader.GetMetadataReader());
}
}
开发者ID:svcgany1,项目名称:corefx,代码行数:10,代码来源:PEReaderTests.cs
示例10: IL_EagerLoad
public void IL_EagerLoad()
{
var peStream = new MemoryStream(TestResources.Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage))
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
}
}
开发者ID:hitomi333,项目名称:corefx,代码行数:12,代码来源:PEReaderTests.cs
示例11: Execute
public override bool Execute()
{
if (Assemblies == null || Assemblies.Length == 0)
return true;
List<ITaskItem> references = new List<ITaskItem>();
List<ITaskItem> nativeLibs = new List<ITaskItem>();
foreach (var assemblyItem in Assemblies)
{
try
{
if (!File.Exists(assemblyItem.ItemSpec))
{
Log.LogError($"File {assemblyItem.ItemSpec} does not exist, ensure you have built libraries before building the package.");
continue;
}
using (PEReader peReader = new PEReader(new FileStream(assemblyItem.ItemSpec, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)))
{
MetadataReader reader = peReader.GetMetadataReader();
foreach (var handle in reader.AssemblyReferences)
{
AssemblyReference reference = reader.GetAssemblyReference(handle);
TaskItem referenceItem = new TaskItem(reader.GetString(reference.Name));
assemblyItem.CopyMetadataTo(referenceItem);
referenceItem.SetMetadata("Version", reference.Version.ToString());
referenceItem.SetMetadata("AssemblyVersion", reference.Version.ToString());
references.Add(referenceItem);
}
for (int i = 1, count = reader.GetTableRowCount(TableIndex.ModuleRef); i <= count; i++)
{
var moduleRef = reader.GetModuleReference(MetadataTokens.ModuleReferenceHandle(i));
var moduleName = reader.GetString(moduleRef.Name);
TaskItem nativeLib = new TaskItem(moduleName);
assemblyItem.CopyMetadataTo(nativeLib);
nativeLibs.Add(nativeLib);
}
}
}
catch (InvalidOperationException)
{
// Ignore invalid assemblies
}
}
ReferencedAssemblies = references.ToArray();
ReferencedNativeLibraries = nativeLibs.ToArray();
return true;
}
开发者ID:dsgouda,项目名称:buildtools,代码行数:53,代码来源:GetAssemblyReferences.cs
示例12: CreateReader
public static ISymUnmanagedReader CreateReader(Stream pdbStream, Stream peStreamOpt = null)
{
if (peStreamOpt != null)
{
var peReader = new PEReader(peStreamOpt);
return CreateReader(pdbStream, peReader.GetMetadataReader(), peReader);
}
else
{
return CreateReader(pdbStream, null, null);
}
}
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:12,代码来源:SymReaderFactory.cs
示例13: Execute
public override bool Execute()
{
Log.LogMessage(MessageImportance.High, "About to inspect {0} test assemblies.", TestBinaries.Length);
var perfTests = new List<ITaskItem>();
foreach (var testBinary in TestBinaries)
{
Log.LogMessage(MessageImportance.Low, "Inspecting assembly {0}.", testBinary.ItemSpec);
using (var stream = File.OpenRead(testBinary.ItemSpec))
{
using (var peFile = new PEReader(stream))
{
if(!peFile.HasMetadata){
continue;
}
var mdReader = peFile.GetMetadataReader();
foreach (var asmRefHandle in mdReader.AssemblyReferences)
{
var asmRef = mdReader.GetAssemblyReference(asmRefHandle);
var asmRefName = mdReader.GetString(asmRef.Name);
// if an assembly contains a reference to xunit.performance.core
// then it contains at least one performance test.
if (string.Compare(asmRefName, "xunit.performance.core", StringComparison.OrdinalIgnoreCase) == 0)
{
var fileName = (GetFullPaths) ? Path.GetFullPath(testBinary.ItemSpec) : Path.GetFileNameWithoutExtension(testBinary.ItemSpec);
perfTests.Add(new TaskItem(fileName));
Log.LogMessage("+ Assembly {0} contains one or more performance tests.", fileName);
break;
}
}
}
}
}
if (perfTests.Count > 0)
{
PerfTestAssemblies = perfTests.ToArray();
Log.LogMessage(MessageImportance.High, "Found {0} assemblies containing performance tests.", perfTests.Count);
}
else
{
Log.LogWarning("Didn't find any performance tests.");
}
return true;
}
开发者ID:MichalStrehovsky,项目名称:buildtools,代码行数:50,代码来源:GetPerfTestAssemblies.cs
示例14: AnalyzeAssemblies
public static ReadOnlyCollection<Message> AnalyzeAssemblies(string referenceAssemblyFile, string newAssemblyFile)
{
using (PEReader referenceAssembly = new PEReader(File.OpenRead(referenceAssemblyFile)))
{
using (PEReader newAssembly = new PEReader(File.OpenRead(newAssemblyFile)))
{
TestMessageLogger logger = new TestMessageLogger();
Analyzer analyzer = new Analyzer(referenceAssembly, newAssembly, logger);
analyzer.Run();
return logger.RawMessages;
}
}
}
开发者ID:modulexcite,项目名称:dotnet-compatibility,代码行数:14,代码来源:TestUtility.cs
示例15: ReadMvid
/// <summary>
/// Given a path to an assembly, returns its MVID (Module Version ID).
/// May throw.
/// </summary>
/// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception>
/// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception>
public static Guid ReadMvid(string filePath)
{
Debug.Assert(filePath != null);
Debug.Assert(PathUtilities.IsAbsolute(filePath));
using (var reader = new PEReader(FileUtilities.OpenRead(filePath)))
{
var metadataReader = reader.GetMetadataReader();
var mvidHandle = metadataReader.GetModuleDefinition().Mvid;
var fileMvid = metadataReader.GetGuid(mvidHandle);
return fileMvid;
}
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:20,代码来源:AssemblyUtilities.cs
示例16: GetAssemblyInfo
public static AssemblyInfo GetAssemblyInfo(string path)
{
using (var peReader = new PEReader(new FileStream(path, FileMode.Open, FileAccess.Read)))
{
var contractReader = peReader.GetMetadataReader();
var assembly = contractReader.GetAssemblyDefinition();
var name = contractReader.GetString(assembly.Name);
var version = assembly.Version;
var references = GetAssemblyReferences(contractReader);
return new AssemblyInfo(path, name, version, references);
}
}
开发者ID:modulexcite,项目名称:ReferenceGenerator,代码行数:14,代码来源:AssemblyInfo.cs
示例17: TestSpansPresentInResource
public void TestSpansPresentInResource()
{
var c = CreateCompilationWithMscorlib(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' FF-9A-1F-F4-03-A5-A1-F7-8D-CD-00-15-67-0E-BA-F7-23-9D-3F-0F (SHA1)");
Assert.Equal(12, reader.Methods.Length);
string[] sourceLines = ExampleSource.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines, // Main
new SpanResult(5, 4, 9, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 31, "Console.WriteLine(123)"),
new SpanResult(8, 8, 8, 31, "Console.WriteLine(123)"));
VerifySpans(reader, reader.Methods[1], sourceLines, // Fred get
new SpanResult(11, 4, 11, 32, "public static int Fred => 3"),
new SpanResult(11, 30, 11, 31, "3"));
VerifySpans(reader, reader.Methods[2], sourceLines, // Barney
new SpanResult(13, 4, 13, 41, "public static int Barney(int x) => x"),
new SpanResult(13, 39, 13, 40, "x"));
VerifySpans(reader, reader.Methods[3], sourceLines, // Wilma get
new SpanResult(17, 8, 17, 26, "get { return 12; }"),
new SpanResult(17, 14, 17, 24, "return 12"));
VerifySpans(reader, reader.Methods[4], sourceLines, // Wilma set
new SpanResult(18, 8, 18, 15, "set { }"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Betty get
new SpanResult(21, 4, 21, 36, "public static int Betty { get; }"),
new SpanResult(21, 30, 21, 34, "get"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Pebbles get
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 32, 23, 36, "get"));
VerifySpans(reader, reader.Methods[7], sourceLines, // Pebbles set
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 37, 23, 41, "set"));
VerifySpans(reader, reader.Methods[8]);
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:49,代码来源:DynamicAnalysisResourceTests.cs
示例18: EmbeddedPortablePdb
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilationWithMscorlib(Parse(source, "foo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded).WithPdbFilePath(@"a/b/c/d.pdb"));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var embedded = entries[1];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "foo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
}
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:49,代码来源:PortablePdbTests.cs
示例19: BasicValidation
public void BasicValidation()
{
using (var peStream = new MemoryStream())
{
var ilBuilder = new BlobBuilder();
var metadataBuilder = new MetadataBuilder();
var entryPoint = BasicValidationEmit(metadataBuilder, ilBuilder);
WritePEImage(peStream, metadataBuilder, ilBuilder, entryPoint);
peStream.Position = 0;
var r = new PEReader(peStream);
var h = r.PEHeaders;
var mdReader = r.GetMetadataReader();
}
}
开发者ID:RoryVL,项目名称:roslyn,代码行数:15,代码来源:PEBuilderTests.cs
示例20: RemovePublicSign
internal override void RemovePublicSign(string assemblyPath)
{
using (var stream = new FileStream(assemblyPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var peReader = new PEReader(stream))
using (var writer = new BinaryWriter(stream))
{
if (!IsPublicSigned(peReader))
{
return;
}
stream.Position = peReader.PEHeaders.CorHeaderStartOffset + OffsetFromStartOfCorHeaderToFlags;
writer.Write((UInt32)(peReader.PEHeaders.CorHeader.Flags | CorFlags.StrongNameSigned));
}
}
开发者ID:vslsnap,项目名称:roslyn,代码行数:15,代码来源:RealSignTool.cs
注:本文中的System.Reflection.PortableExecutable.PEReader类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论