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