Hardware/Ring0.cs
author moel.mich
Wed, 11 Jul 2012 22:28:39 +0000
changeset 361 0a386ef7d5bb
parent 344 3145aadca3d2
child 364 25ef2c489ce8
permissions -rw-r--r--
Fixed Issue 274. Fixed Issue 107.
     1 /*
     2  
     3   This Source Code Form is subject to the terms of the Mozilla Public
     4   License, v. 2.0. If a copy of the MPL was not distributed with this
     5   file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  
     7   Copyright (C) 2010-2012 Michael Möller <mmoeller@openhardwaremonitor.org>
     8 	
     9 */
    10 
    11 using System;
    12 using System.IO;
    13 using System.Reflection;
    14 using System.Runtime.InteropServices;
    15 using System.Security.AccessControl;
    16 using System.Threading;
    17 using System.Text;
    18 
    19 namespace OpenHardwareMonitor.Hardware {
    20   internal static class Ring0 {
    21 
    22     private static KernelDriver driver;
    23     private static string fileName;
    24     private static Mutex isaBusMutex;
    25     private static readonly StringBuilder report = new StringBuilder();
    26 
    27     private const uint OLS_TYPE = 40000;
    28     private static IOControlCode
    29       IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
    30         IOControlCode.Access.Any),
    31       IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
    32         IOControlCode.Access.Any),
    33       IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
    34         IOControlCode.Access.Any),
    35       IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822, 
    36         IOControlCode.Access.Any),
    37       IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
    38         IOControlCode.Access.Read),
    39       IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836, 
    40         IOControlCode.Access.Write),
    41       IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851, 
    42         IOControlCode.Access.Read),
    43       IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
    44         IOControlCode.Access.Write),
    45       IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
    46         IOControlCode.Access.Read);
    47 
    48     private static string GetTempFileName() {
    49 
    50       // try to get a file in the temporary folder
    51       try {
    52         return Path.GetTempFileName();        
    53       } catch (IOException) { 
    54           // some I/O exception
    55         } 
    56         catch (UnauthorizedAccessException) { 
    57           // we do not have the right to create a file in the temp folder
    58         }
    59         catch (NotSupportedException) {
    60           // invalid path format of the TMP system environment variable
    61         }
    62 
    63       // if this failed, we try to create one in the application folder
    64       string fileName = Path.ChangeExtension(
    65         Assembly.GetExecutingAssembly().Location, ".sys");
    66       try {
    67         using (FileStream stream = File.Create(fileName)) {
    68           return fileName;
    69         }        
    70       } catch (IOException) { } 
    71         catch (UnauthorizedAccessException) { }
    72      
    73       return null;
    74     }
    75 
    76     private static bool ExtractDriver(string fileName) {
    77       string resourceName = "OpenHardwareMonitor.Hardware." +
    78         (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : 
    79         "WinRing0.sys");
    80 
    81       string[] names =
    82         Assembly.GetExecutingAssembly().GetManifestResourceNames();
    83       byte[] buffer = null;
    84       for (int i = 0; i < names.Length; i++) {
    85         if (names[i].Replace('\\', '.') == resourceName) {
    86           using (Stream stream = Assembly.GetExecutingAssembly().
    87             GetManifestResourceStream(names[i])) 
    88           {
    89               buffer = new byte[stream.Length];
    90               stream.Read(buffer, 0, buffer.Length);
    91           }
    92         }
    93       }
    94 
    95       if (buffer == null)
    96         return false;
    97 
    98       try {
    99         using (FileStream target = new FileStream(fileName, FileMode.Create)) {
   100           target.Write(buffer, 0, buffer.Length);
   101         }
   102       } catch (IOException) { 
   103         // for example there is not enough space on the disk
   104         return false; 
   105       }
   106 
   107       return true;
   108     }
   109 
   110     public static void Open() {
   111       // no implementation for unix systems
   112       int p = (int)Environment.OSVersion.Platform;
   113       if ((p == 4) || (p == 128))
   114         return;  
   115       
   116       if (driver != null)
   117         return;
   118 
   119       // clear the current report
   120       report.Length = 0;
   121      
   122       driver = new KernelDriver("WinRing0_1_2_0");
   123       driver.Open();
   124 
   125       if (!driver.IsOpen) {
   126         // driver is not loaded, try to reinstall and open
   127 
   128         driver.Delete();
   129         fileName = GetTempFileName();
   130         if (fileName != null && ExtractDriver(fileName)) {
   131           if (driver.Install(fileName)) {
   132             driver.Open();
   133 
   134             if (!driver.IsOpen) {
   135               driver.Delete();
   136               report.AppendLine("Status: Opening driver failed");
   137             }
   138           } else {
   139             report.AppendLine("Status: Installing driver \"" +
   140               fileName + "\" failed" +
   141               (File.Exists(fileName) ? " and file exists" : ""));
   142             report.AppendLine();
   143             report.Append("Exception: " + Marshal.GetExceptionForHR(
   144               Marshal.GetHRForLastWin32Error()).Message);
   145           }
   146         } else {
   147           report.AppendLine("Status: Extracting driver failed");
   148         }
   149 
   150         try {
   151           // try to delte the driver file
   152           if (File.Exists(fileName))
   153             File.Delete(fileName);
   154           fileName = null;
   155         } catch (IOException) { } 
   156           catch (UnauthorizedAccessException) { }
   157       }
   158 
   159       if (!driver.IsOpen) 
   160         driver = null;
   161 
   162       string mutexName = "Global\\Access_ISABUS.HTP.Method";
   163       try {
   164         isaBusMutex = new Mutex(false, mutexName);
   165       } catch (UnauthorizedAccessException) {
   166         try {
   167           isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
   168         } catch { }
   169       }
   170     }
   171 
   172     public static bool IsOpen {
   173       get { return driver != null; }
   174     }
   175 
   176     public static void Close() {
   177       if (driver == null)
   178         return;
   179 
   180       uint refCount = 0;
   181       driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
   182 
   183       driver.Close();
   184 
   185       if (refCount <= 1)
   186         driver.Delete();
   187 
   188       driver = null;
   189 
   190       if (isaBusMutex != null) {
   191         isaBusMutex.Close();
   192         isaBusMutex = null;
   193       }
   194 
   195       // try to delete temporary driver file again if failed during open
   196       if (fileName != null && File.Exists(fileName)) {
   197         try {
   198           File.Delete(fileName);
   199           fileName = null;
   200         } catch (IOException) { } 
   201           catch (UnauthorizedAccessException) { }
   202       }
   203     }
   204 
   205     public static string GetReport() {
   206       if (report.Length > 0) {
   207         StringBuilder r = new StringBuilder();
   208         r.AppendLine("Ring0");
   209         r.AppendLine();
   210         r.Append(report);
   211         r.AppendLine();
   212         return r.ToString();
   213       } else
   214         return null;
   215     }
   216 
   217     public static bool WaitIsaBusMutex(int millisecondsTimeout) {
   218       if (isaBusMutex == null)
   219         return true;
   220       try {
   221         return isaBusMutex.WaitOne(millisecondsTimeout, false);
   222       } catch (AbandonedMutexException) { return false; } 
   223         catch (InvalidOperationException) { return false; }
   224     }
   225 
   226     public static void ReleaseIsaBusMutex() {
   227       if (isaBusMutex == null)
   228         return;
   229       isaBusMutex.ReleaseMutex();
   230     }
   231 
   232     public static bool Rdmsr(uint index, out uint eax, out uint edx) {
   233       if (driver == null) {
   234         eax = 0;
   235         edx = 0;
   236         return false;
   237       }
   238 
   239       ulong buffer = 0;
   240       bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
   241         ref buffer);
   242 
   243       edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
   244       eax = (uint)(buffer & 0xFFFFFFFF);
   245       return result;
   246     }
   247 
   248     public static bool RdmsrTx(uint index, out uint eax, out uint edx,
   249       ulong threadAffinityMask) 
   250     {
   251       ulong mask = ThreadAffinity.Set(threadAffinityMask);
   252 
   253       bool result = Rdmsr(index, out eax, out edx);
   254 
   255       ThreadAffinity.Set(mask);
   256       return result;
   257     }
   258 
   259     [StructLayout(LayoutKind.Sequential, Pack = 1)]
   260     private struct WrmsrInput {
   261       public uint Register;
   262       public ulong Value;
   263     }
   264 
   265     public static bool Wrmsr(uint index, uint eax, uint edx) {
   266       if (driver == null)
   267         return false;
   268 
   269       WrmsrInput input = new WrmsrInput();
   270       input.Register = index;
   271       input.Value = ((ulong)edx << 32) | eax;
   272 
   273       return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
   274     }
   275 
   276     public static byte ReadIoPort(uint port) {
   277       if (driver == null)
   278         return 0;
   279 
   280       uint value = 0;
   281       driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
   282 
   283       return (byte)(value & 0xFF);
   284     }
   285 
   286     [StructLayout(LayoutKind.Sequential, Pack = 1)]
   287     private struct WriteIoPortInput {
   288       public uint PortNumber;
   289       public byte Value;
   290     }
   291 
   292     public static void WriteIoPort(uint port, byte value) {
   293       if (driver == null)
   294         return;
   295 
   296       WriteIoPortInput input = new WriteIoPortInput();
   297       input.PortNumber = port;
   298       input.Value = value;
   299 
   300       driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
   301     }
   302 
   303     public const uint InvalidPciAddress = 0xFFFFFFFF;
   304 
   305     public static uint GetPciAddress(byte bus, byte device, byte function) {
   306       return
   307         (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
   308     }
   309 
   310     [StructLayout(LayoutKind.Sequential, Pack = 1)]
   311     private struct ReadPciConfigInput {
   312       public uint PciAddress;
   313       public uint RegAddress;
   314     }
   315 
   316     public static bool ReadPciConfig(uint pciAddress, uint regAddress, 
   317       out uint value) 
   318     {
   319       if (driver == null || (regAddress & 3) != 0) {
   320         value = 0;
   321         return false;
   322       }
   323 
   324       ReadPciConfigInput input = new ReadPciConfigInput();
   325       input.PciAddress = pciAddress;
   326       input.RegAddress = regAddress;
   327 
   328       value = 0;
   329       return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, 
   330         ref value);
   331     }
   332 
   333     [StructLayout(LayoutKind.Sequential, Pack = 1)]
   334     private struct WritePciConfigInput {
   335       public uint PciAddress;
   336       public uint RegAddress;
   337       public uint Value;
   338     }
   339 
   340     public static bool WritePciConfig(uint pciAddress, uint regAddress, 
   341       uint value) 
   342     {
   343       if (driver == null || (regAddress & 3) != 0)
   344         return false;
   345 
   346       WritePciConfigInput input = new WritePciConfigInput();
   347       input.PciAddress = pciAddress;
   348       input.RegAddress = regAddress;
   349       input.Value = value;
   350 
   351       return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
   352     }
   353 
   354     [StructLayout(LayoutKind.Sequential, Pack = 1)]
   355     private struct ReadMemoryInput {
   356       public ulong address;
   357       public uint unitSize;
   358       public uint count;
   359     }
   360 
   361     public static bool ReadMemory<T>(ulong address, ref T buffer) {
   362       if (driver == null) {
   363         return false;
   364       }
   365 
   366       ReadMemoryInput input = new ReadMemoryInput();
   367       input.address = address;
   368       input.unitSize = 1;
   369       input.count = (uint)Marshal.SizeOf(buffer);
   370 
   371       return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
   372         ref buffer);
   373     }
   374   }
   375 }