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