/src/UnitTests/Tools/PEVerifier.cs
C# | 112 lines | 86 code | 23 blank | 3 comment | 7 complexity | 74c2b9e100d1f9528f14830cc3179a31 MD5 | raw file
1using System; 2using System.Collections.Generic; 3using System.Configuration; 4using System.Diagnostics; 5using System.IO; 6using LinFu.AOP.Cecil.Interfaces; 7using LinFu.Reflection.Emit; 8using Mono.Cecil; 9using Xunit; 10 11namespace LinFu.UnitTests.Tools 12{ 13 internal class PeVerifier : IVerifier 14 { 15 private readonly string _location = string.Empty; 16 private bool _failed; 17 private string _filename = string.Empty; 18 19 internal PeVerifier(string filename) 20 { 21 var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; 22 _location = Path.Combine(baseDirectory, filename); 23 24 _filename = filename; 25 } 26 27 28 public void Verify(AssemblyDefinition assembly) 29 { 30 // Save the assembly to the temporary file and verify it 31 assembly.Save(_location); 32 PeVerify(_location); 33 } 34 35 36 ~PeVerifier() 37 { 38 try 39 { 40 if (File.Exists(_location) && !_failed) 41 File.Delete(_location); 42 } 43 catch 44 { 45 // Do nothing 46 } 47 } 48 49 private void PeVerify(string assemblyLocation) 50 { 51 var pathKeys = new[] 52 { 53 "sdkDir", 54 "x86SdkDir", 55 "sdkDirUnderVista" 56 }; 57 58 var process = new Process(); 59 var peVerifyLocation = string.Empty; 60 61 62 peVerifyLocation = GetPEVerifyLocation(pathKeys, peVerifyLocation); 63 64 // Use PEVerify.exe if it exists 65 if (!File.Exists(peVerifyLocation)) 66 { 67 Console.WriteLine("Warning: PEVerify.exe could not be found. Skipping test."); 68 return; 69 } 70 71 process.StartInfo.FileName = peVerifyLocation; 72 process.StartInfo.RedirectStandardOutput = true; 73 process.StartInfo.UseShellExecute = false; 74 process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory; 75 process.StartInfo.Arguments = "\"" + assemblyLocation + "\" /VERBOSE"; 76 process.StartInfo.CreateNoWindow = true; 77 process.Start(); 78 79 var processOutput = process.StandardOutput.ReadToEnd(); 80 process.WaitForExit(); 81 82 var result = string.Format("PEVerify Exit Code: {0}", process.ExitCode); 83 84 Console.WriteLine(GetType().FullName + ": " + result); 85 86 if (process.ExitCode == 0) 87 return; 88 89 Console.WriteLine(processOutput); 90 _failed = true; 91 Assert.True(false, $"PEVerify output: {Environment.NewLine}{processOutput}{result}"); 92 } 93 94 private static string GetPEVerifyLocation(IEnumerable<string> pathKeys, string peVerifyLocation) 95 { 96 foreach (var key in pathKeys) 97 { 98 var directory = ConfigurationManager.AppSettings[key]; 99 100 if (string.IsNullOrEmpty(directory)) 101 continue; 102 103 peVerifyLocation = Path.Combine(directory, "peverify.exe"); 104 105 if (File.Exists(peVerifyLocation)) 106 break; 107 } 108 109 return peVerifyLocation; 110 } 111 } 112}