本文整理汇总了C#中System.Reflection.PortableExecutable.PEReader类的典型用法代码示例。如果您正苦于以下问题:C# PEReader类的具体用法?C# PEReader怎么用?C# PEReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PEReader类属于System.Reflection.PortableExecutable命名空间,在下文中一共展示了PEReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
}
示例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;
}
示例3: InspectableAssembly
public InspectableAssembly(string filename, ParseContext context)
{
Stream = File.OpenRead(filename);
Pe = new PEReader(Stream);
Reader = Pe.GetMetadataReader();
Context = context;
}
示例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;
}
示例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();
}
}
}
示例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);
}
}
}
示例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;
}
示例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);
}
示例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());
}
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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;
}
示例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;
}
}
}
示例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;
}
}