Hardware/Ring0.cs
author moel.mich
Tue, 17 Jul 2012 16:10:59 +0000
changeset 364 25ef2c489ce8
parent 361 0a386ef7d5bb
child 367 45215572a774
permissions -rw-r--r--
Attempt at fixing Issue 253 without breaking Issue 159 once more.
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@364
   126
        // driver is not loaded, try to install and open
moel@255
   127
moel@283
   128
        fileName = GetTempFileName();
moel@283
   129
        if (fileName != null && ExtractDriver(fileName)) {
moel@254
   130
          if (driver.Install(fileName)) {
moel@254
   131
            driver.Open();
moel@236
   132
moel@254
   133
            if (!driver.IsOpen) {
moel@254
   134
              driver.Delete();
moel@364
   135
              report.AppendLine("Status: Opening driver failed after install");
moel@254
   136
            }
moel@254
   137
          } else {
moel@364
   138
            // install failed, try to delete and reinstall
moel@364
   139
            driver.Delete();
moel@364
   140
moel@364
   141
            if (driver.Install(fileName)) {
moel@364
   142
              driver.Open();
moel@364
   143
moel@364
   144
              if (!driver.IsOpen) {
moel@364
   145
                driver.Delete();
moel@364
   146
                report.AppendLine(
moel@364
   147
                  "Status: Opening driver failed after reinstall");
moel@364
   148
              }
moel@364
   149
            } else {
moel@364
   150
              report.AppendLine("Status: Installing driver \"" +
moel@364
   151
                fileName + "\" failed" +
moel@364
   152
                (File.Exists(fileName) ? " and file exists" : ""));
moel@364
   153
              report.AppendLine();
moel@364
   154
              report.Append("Exception: " + Marshal.GetExceptionForHR(
moel@364
   155
                Marshal.GetHRForLastWin32Error()).Message);
moel@364
   156
            }
moel@254
   157
          }
moel@254
   158
        } else {
moel@283
   159
          report.AppendLine("Status: Extracting driver failed");
moel@236
   160
        }
moel@281
   161
moel@281
   162
        try {
moel@281
   163
          // try to delte the driver file
moel@281
   164
          if (File.Exists(fileName))
moel@281
   165
            File.Delete(fileName);
moel@281
   166
          fileName = null;
moel@281
   167
        } catch (IOException) { } 
moel@281
   168
          catch (UnauthorizedAccessException) { }
moel@236
   169
      }
moel@236
   170
moel@236
   171
      if (!driver.IsOpen) 
moel@236
   172
        driver = null;
moel@236
   173
moel@285
   174
      string mutexName = "Global\\Access_ISABUS.HTP.Method";
moel@285
   175
      try {
moel@285
   176
        isaBusMutex = new Mutex(false, mutexName);
moel@285
   177
      } catch (UnauthorizedAccessException) {
moel@285
   178
        try {
moel@285
   179
          isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
moel@285
   180
        } catch { }
moel@285
   181
      }
moel@236
   182
    }
moel@236
   183
moel@236
   184
    public static bool IsOpen {
moel@236
   185
      get { return driver != null; }
moel@236
   186
    }
moel@236
   187
moel@236
   188
    public static void Close() {
moel@236
   189
      if (driver == null)
moel@236
   190
        return;
moel@236
   191
moel@236
   192
      uint refCount = 0;
moel@236
   193
      driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
moel@236
   194
moel@236
   195
      driver.Close();
moel@236
   196
moel@236
   197
      if (refCount <= 1)
moel@236
   198
        driver.Delete();
moel@236
   199
moel@236
   200
      driver = null;
moel@236
   201
moel@285
   202
      if (isaBusMutex != null) {
moel@285
   203
        isaBusMutex.Close();
moel@285
   204
        isaBusMutex = null;
moel@285
   205
      }
moel@281
   206
moel@281
   207
      // try to delete temporary driver file again if failed during open
moel@281
   208
      if (fileName != null && File.Exists(fileName)) {
moel@281
   209
        try {
moel@281
   210
          File.Delete(fileName);
moel@281
   211
          fileName = null;
moel@281
   212
        } catch (IOException) { } 
moel@281
   213
          catch (UnauthorizedAccessException) { }
moel@281
   214
      }
moel@236
   215
    }
moel@236
   216
moel@254
   217
    public static string GetReport() {
moel@254
   218
      if (report.Length > 0) {
moel@256
   219
        StringBuilder r = new StringBuilder();
moel@256
   220
        r.AppendLine("Ring0");
moel@256
   221
        r.AppendLine();
moel@256
   222
        r.Append(report);
moel@256
   223
        r.AppendLine();
moel@256
   224
        return r.ToString();
moel@254
   225
      } else
moel@254
   226
        return null;
moel@254
   227
    }
moel@254
   228
moel@236
   229
    public static bool WaitIsaBusMutex(int millisecondsTimeout) {
moel@285
   230
      if (isaBusMutex == null)
moel@285
   231
        return true;
moel@236
   232
      try {
moel@236
   233
        return isaBusMutex.WaitOne(millisecondsTimeout, false);
moel@236
   234
      } catch (AbandonedMutexException) { return false; } 
moel@236
   235
        catch (InvalidOperationException) { return false; }
moel@236
   236
    }
moel@236
   237
moel@236
   238
    public static void ReleaseIsaBusMutex() {
moel@285
   239
      if (isaBusMutex == null)
moel@285
   240
        return;
moel@236
   241
      isaBusMutex.ReleaseMutex();
moel@236
   242
    }
moel@236
   243
moel@236
   244
    public static bool Rdmsr(uint index, out uint eax, out uint edx) {
moel@236
   245
      if (driver == null) {
moel@236
   246
        eax = 0;
moel@236
   247
        edx = 0;
moel@236
   248
        return false;
moel@236
   249
      }
moel@236
   250
moel@236
   251
      ulong buffer = 0;
moel@236
   252
      bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
moel@236
   253
        ref buffer);
moel@236
   254
moel@236
   255
      edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
moel@236
   256
      eax = (uint)(buffer & 0xFFFFFFFF);
moel@236
   257
      return result;
moel@236
   258
    }
moel@236
   259
moel@236
   260
    public static bool RdmsrTx(uint index, out uint eax, out uint edx,
moel@238
   261
      ulong threadAffinityMask) 
moel@236
   262
    {
moel@238
   263
      ulong mask = ThreadAffinity.Set(threadAffinityMask);
moel@236
   264
moel@236
   265
      bool result = Rdmsr(index, out eax, out edx);
moel@236
   266
moel@238
   267
      ThreadAffinity.Set(mask);
moel@236
   268
      return result;
moel@236
   269
    }
moel@236
   270
moel@236
   271
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   272
    private struct WrmsrInput {
moel@236
   273
      public uint Register;
moel@236
   274
      public ulong Value;
moel@236
   275
    }
moel@236
   276
moel@236
   277
    public static bool Wrmsr(uint index, uint eax, uint edx) {
moel@236
   278
      if (driver == null)
moel@236
   279
        return false;
moel@236
   280
moel@236
   281
      WrmsrInput input = new WrmsrInput();
moel@236
   282
      input.Register = index;
moel@236
   283
      input.Value = ((ulong)edx << 32) | eax;
moel@236
   284
moel@236
   285
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
moel@236
   286
    }
moel@236
   287
moel@236
   288
    public static byte ReadIoPort(uint port) {
moel@236
   289
      if (driver == null)
moel@236
   290
        return 0;
moel@236
   291
moel@236
   292
      uint value = 0;
moel@236
   293
      driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
moel@236
   294
moel@236
   295
      return (byte)(value & 0xFF);
moel@236
   296
    }
moel@236
   297
moel@236
   298
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   299
    private struct WriteIoPortInput {
moel@236
   300
      public uint PortNumber;
moel@236
   301
      public byte Value;
moel@236
   302
    }
moel@236
   303
moel@236
   304
    public static void WriteIoPort(uint port, byte value) {
moel@236
   305
      if (driver == null)
moel@236
   306
        return;
moel@236
   307
moel@236
   308
      WriteIoPortInput input = new WriteIoPortInput();
moel@236
   309
      input.PortNumber = port;
moel@236
   310
      input.Value = value;
moel@236
   311
moel@236
   312
      driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
moel@236
   313
    }
moel@236
   314
moel@236
   315
    public const uint InvalidPciAddress = 0xFFFFFFFF;
moel@236
   316
moel@236
   317
    public static uint GetPciAddress(byte bus, byte device, byte function) {
moel@236
   318
      return
moel@236
   319
        (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
moel@236
   320
    }
moel@236
   321
moel@236
   322
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   323
    private struct ReadPciConfigInput {
moel@236
   324
      public uint PciAddress;
moel@236
   325
      public uint RegAddress;
moel@236
   326
    }
moel@236
   327
moel@236
   328
    public static bool ReadPciConfig(uint pciAddress, uint regAddress, 
moel@236
   329
      out uint value) 
moel@236
   330
    {
moel@236
   331
      if (driver == null || (regAddress & 3) != 0) {
moel@236
   332
        value = 0;
moel@236
   333
        return false;
moel@236
   334
      }
moel@236
   335
moel@236
   336
      ReadPciConfigInput input = new ReadPciConfigInput();
moel@236
   337
      input.PciAddress = pciAddress;
moel@236
   338
      input.RegAddress = regAddress;
moel@236
   339
moel@236
   340
      value = 0;
moel@236
   341
      return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, 
moel@236
   342
        ref value);
moel@236
   343
    }
moel@236
   344
moel@236
   345
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   346
    private struct WritePciConfigInput {
moel@236
   347
      public uint PciAddress;
moel@236
   348
      public uint RegAddress;
moel@236
   349
      public uint Value;
moel@236
   350
    }
moel@236
   351
moel@236
   352
    public static bool WritePciConfig(uint pciAddress, uint regAddress, 
moel@236
   353
      uint value) 
moel@236
   354
    {
moel@236
   355
      if (driver == null || (regAddress & 3) != 0)
moel@236
   356
        return false;
moel@236
   357
moel@236
   358
      WritePciConfigInput input = new WritePciConfigInput();
moel@236
   359
      input.PciAddress = pciAddress;
moel@236
   360
      input.RegAddress = regAddress;
moel@236
   361
      input.Value = value;
moel@236
   362
moel@236
   363
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
moel@236
   364
    }
moel@279
   365
moel@279
   366
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@279
   367
    private struct ReadMemoryInput {
moel@279
   368
      public ulong address;
moel@279
   369
      public uint unitSize;
moel@279
   370
      public uint count;
moel@279
   371
    }
moel@279
   372
moel@279
   373
    public static bool ReadMemory<T>(ulong address, ref T buffer) {
moel@279
   374
      if (driver == null) {
moel@279
   375
        return false;
moel@279
   376
      }
moel@279
   377
moel@279
   378
      ReadMemoryInput input = new ReadMemoryInput();
moel@279
   379
      input.address = address;
moel@279
   380
      input.unitSize = 1;
moel@279
   381
      input.count = (uint)Marshal.SizeOf(buffer);
moel@279
   382
moel@279
   383
      return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
moel@279
   384
        ref buffer);
moel@279
   385
    }
moel@236
   386
  }
moel@236
   387
}