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