Hardware/Ring0.cs
author moel.mich
Sun, 15 May 2011 21:43:40 +0000
changeset 288 a35a89a35532
parent 283 fb88cac4a9aa
child 293 9c1b242b1c63
permissions -rw-r--r--
Improved the selection dragging on the tree view. The selection moves now only when the dragging starts on the tree view. With the old implementation, double-clicking the gadget would change the selection, because the mouse is still pressed when the main window is shown.
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@285
    42
using System.Security.AccessControl;
moel@236
    43
using System.Threading;
moel@254
    44
using System.Text;
moel@236
    45
moel@236
    46
namespace OpenHardwareMonitor.Hardware {
moel@236
    47
  internal static class Ring0 {
moel@236
    48
moel@236
    49
    private static KernelDriver driver;
moel@281
    50
    private static string fileName;
moel@236
    51
    private static Mutex isaBusMutex;
moel@254
    52
    private static readonly StringBuilder report = new StringBuilder();
moel@236
    53
moel@236
    54
    private const uint OLS_TYPE = 40000;
moel@236
    55
    private static IOControlCode
moel@236
    56
      IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
moel@236
    57
        IOControlCode.Access.Any),
moel@236
    58
      IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
moel@236
    59
        IOControlCode.Access.Any),
moel@236
    60
      IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
moel@236
    61
        IOControlCode.Access.Any),
moel@236
    62
      IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822, 
moel@236
    63
        IOControlCode.Access.Any),
moel@236
    64
      IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
moel@236
    65
        IOControlCode.Access.Read),
moel@236
    66
      IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836, 
moel@236
    67
        IOControlCode.Access.Write),
moel@236
    68
      IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851, 
moel@236
    69
        IOControlCode.Access.Read),
moel@236
    70
      IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
moel@279
    71
        IOControlCode.Access.Write),
moel@279
    72
      IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
moel@279
    73
        IOControlCode.Access.Read);
moel@236
    74
moel@283
    75
    private static string GetTempFileName() {
moel@283
    76
moel@283
    77
      // try to get a file in the temporary folder
moel@283
    78
      try {
moel@283
    79
        return Path.GetTempFileName();        
moel@283
    80
      } catch (IOException) { } 
moel@283
    81
        catch (UnauthorizedAccessException) { }
moel@283
    82
moel@283
    83
      // if this failed, we try to create one in the application folder
moel@283
    84
      string fileName = Path.ChangeExtension(
moel@283
    85
        Assembly.GetExecutingAssembly().Location, ".sys");
moel@283
    86
      try {
moel@283
    87
        using (FileStream stream = File.Create(fileName)) {
moel@283
    88
          return fileName;
moel@283
    89
        }        
moel@283
    90
      } catch (IOException) { } 
moel@283
    91
        catch (UnauthorizedAccessException) { }
moel@283
    92
     
moel@283
    93
      return null;
moel@283
    94
    }
moel@283
    95
moel@236
    96
    private static bool ExtractDriver(string fileName) {
moel@236
    97
      string resourceName = "OpenHardwareMonitor.Hardware." +
moel@236
    98
        (IntPtr.Size == 4 ? "WinRing0.sys" : "WinRing0x64.sys");
moel@236
    99
moel@236
   100
      string[] names =
moel@236
   101
        Assembly.GetExecutingAssembly().GetManifestResourceNames();
moel@236
   102
      byte[] buffer = null;
moel@236
   103
      for (int i = 0; i < names.Length; i++) {
moel@236
   104
        if (names[i].Replace('\\', '.') == resourceName) {
moel@236
   105
          using (Stream stream = Assembly.GetExecutingAssembly().
moel@236
   106
            GetManifestResourceStream(names[i])) 
moel@236
   107
          {
moel@236
   108
              buffer = new byte[stream.Length];
moel@236
   109
              stream.Read(buffer, 0, buffer.Length);
moel@236
   110
          }
moel@236
   111
        }
moel@236
   112
      }
moel@236
   113
moel@236
   114
      if (buffer == null)
moel@236
   115
        return false;
moel@236
   116
moel@236
   117
      using (FileStream target = new FileStream(fileName, FileMode.Create)) {
moel@236
   118
        target.Write(buffer, 0, buffer.Length);
moel@236
   119
      }
moel@236
   120
moel@236
   121
      return true;
moel@236
   122
    }
moel@236
   123
moel@236
   124
    public static void Open() {
moel@254
   125
      // no implementation for unix systems
moel@238
   126
      int p = (int)Environment.OSVersion.Platform;
moel@238
   127
      if ((p == 4) || (p == 128))
moel@238
   128
        return;  
moel@238
   129
      
moel@236
   130
      if (driver != null)
moel@236
   131
        return;
moel@254
   132
moel@254
   133
      // clear the current report
moel@254
   134
      report.Length = 0;
moel@236
   135
     
moel@236
   136
      driver = new KernelDriver("WinRing0_1_2_0");
moel@236
   137
      driver.Open();
moel@236
   138
moel@236
   139
      if (!driver.IsOpen) {
moel@255
   140
        // driver is not loaded, try to reinstall and open
moel@255
   141
moel@255
   142
        driver.Delete();
moel@283
   143
        fileName = GetTempFileName();
moel@283
   144
        if (fileName != null && ExtractDriver(fileName)) {
moel@254
   145
          if (driver.Install(fileName)) {
moel@254
   146
            driver.Open();
moel@236
   147
moel@254
   148
            if (!driver.IsOpen) {
moel@254
   149
              driver.Delete();
moel@254
   150
              report.AppendLine("Status: Opening driver failed");
moel@254
   151
            }
moel@254
   152
          } else {
moel@283
   153
            report.AppendLine("Status: Installing driver \"" +
moel@283
   154
              fileName + "\" failed" +
moel@255
   155
              (File.Exists(fileName) ? " and file exists" : ""));
moel@254
   156
            report.AppendLine();
moel@254
   157
            report.Append("Exception: " + Marshal.GetExceptionForHR(
moel@254
   158
              Marshal.GetHRForLastWin32Error()).Message);
moel@254
   159
          }
moel@254
   160
        } else {
moel@283
   161
          report.AppendLine("Status: Extracting driver failed");
moel@236
   162
        }
moel@281
   163
moel@281
   164
        try {
moel@281
   165
          // try to delte the driver file
moel@281
   166
          if (File.Exists(fileName))
moel@281
   167
            File.Delete(fileName);
moel@281
   168
          fileName = null;
moel@281
   169
        } catch (IOException) { } 
moel@281
   170
          catch (UnauthorizedAccessException) { }
moel@236
   171
      }
moel@236
   172
moel@236
   173
      if (!driver.IsOpen) 
moel@236
   174
        driver = null;
moel@236
   175
moel@285
   176
      string mutexName = "Global\\Access_ISABUS.HTP.Method";
moel@285
   177
      try {
moel@285
   178
        isaBusMutex = new Mutex(false, mutexName);
moel@285
   179
      } catch (UnauthorizedAccessException) {
moel@285
   180
        try {
moel@285
   181
          isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
moel@285
   182
        } catch { }
moel@285
   183
      }
moel@236
   184
    }
moel@236
   185
moel@236
   186
    public static bool IsOpen {
moel@236
   187
      get { return driver != null; }
moel@236
   188
    }
moel@236
   189
moel@236
   190
    public static void Close() {
moel@236
   191
      if (driver == null)
moel@236
   192
        return;
moel@236
   193
moel@236
   194
      uint refCount = 0;
moel@236
   195
      driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
moel@236
   196
moel@236
   197
      driver.Close();
moel@236
   198
moel@236
   199
      if (refCount <= 1)
moel@236
   200
        driver.Delete();
moel@236
   201
moel@236
   202
      driver = null;
moel@236
   203
moel@285
   204
      if (isaBusMutex != null) {
moel@285
   205
        isaBusMutex.Close();
moel@285
   206
        isaBusMutex = null;
moel@285
   207
      }
moel@281
   208
moel@281
   209
      // try to delete temporary driver file again if failed during open
moel@281
   210
      if (fileName != null && File.Exists(fileName)) {
moel@281
   211
        try {
moel@281
   212
          File.Delete(fileName);
moel@281
   213
          fileName = null;
moel@281
   214
        } catch (IOException) { } 
moel@281
   215
          catch (UnauthorizedAccessException) { }
moel@281
   216
      }
moel@236
   217
    }
moel@236
   218
moel@254
   219
    public static string GetReport() {
moel@254
   220
      if (report.Length > 0) {
moel@256
   221
        StringBuilder r = new StringBuilder();
moel@256
   222
        r.AppendLine("Ring0");
moel@256
   223
        r.AppendLine();
moel@256
   224
        r.Append(report);
moel@256
   225
        r.AppendLine();
moel@256
   226
        return r.ToString();
moel@254
   227
      } else
moel@254
   228
        return null;
moel@254
   229
    }
moel@254
   230
moel@236
   231
    public static bool WaitIsaBusMutex(int millisecondsTimeout) {
moel@285
   232
      if (isaBusMutex == null)
moel@285
   233
        return true;
moel@236
   234
      try {
moel@236
   235
        return isaBusMutex.WaitOne(millisecondsTimeout, false);
moel@236
   236
      } catch (AbandonedMutexException) { return false; } 
moel@236
   237
        catch (InvalidOperationException) { return false; }
moel@236
   238
    }
moel@236
   239
moel@236
   240
    public static void ReleaseIsaBusMutex() {
moel@285
   241
      if (isaBusMutex == null)
moel@285
   242
        return;
moel@236
   243
      isaBusMutex.ReleaseMutex();
moel@236
   244
    }
moel@236
   245
moel@236
   246
    public static bool Rdmsr(uint index, out uint eax, out uint edx) {
moel@236
   247
      if (driver == null) {
moel@236
   248
        eax = 0;
moel@236
   249
        edx = 0;
moel@236
   250
        return false;
moel@236
   251
      }
moel@236
   252
moel@236
   253
      ulong buffer = 0;
moel@236
   254
      bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
moel@236
   255
        ref buffer);
moel@236
   256
moel@236
   257
      edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
moel@236
   258
      eax = (uint)(buffer & 0xFFFFFFFF);
moel@236
   259
      return result;
moel@236
   260
    }
moel@236
   261
moel@236
   262
    public static bool RdmsrTx(uint index, out uint eax, out uint edx,
moel@238
   263
      ulong threadAffinityMask) 
moel@236
   264
    {
moel@238
   265
      ulong mask = ThreadAffinity.Set(threadAffinityMask);
moel@236
   266
moel@236
   267
      bool result = Rdmsr(index, out eax, out edx);
moel@236
   268
moel@238
   269
      ThreadAffinity.Set(mask);
moel@236
   270
      return result;
moel@236
   271
    }
moel@236
   272
moel@236
   273
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   274
    private struct WrmsrInput {
moel@236
   275
      public uint Register;
moel@236
   276
      public ulong Value;
moel@236
   277
    }
moel@236
   278
moel@236
   279
    public static bool Wrmsr(uint index, uint eax, uint edx) {
moel@236
   280
      if (driver == null)
moel@236
   281
        return false;
moel@236
   282
moel@236
   283
      WrmsrInput input = new WrmsrInput();
moel@236
   284
      input.Register = index;
moel@236
   285
      input.Value = ((ulong)edx << 32) | eax;
moel@236
   286
moel@236
   287
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
moel@236
   288
    }
moel@236
   289
moel@236
   290
    public static byte ReadIoPort(uint port) {
moel@236
   291
      if (driver == null)
moel@236
   292
        return 0;
moel@236
   293
moel@236
   294
      uint value = 0;
moel@236
   295
      driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
moel@236
   296
moel@236
   297
      return (byte)(value & 0xFF);
moel@236
   298
    }
moel@236
   299
moel@236
   300
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   301
    private struct WriteIoPortInput {
moel@236
   302
      public uint PortNumber;
moel@236
   303
      public byte Value;
moel@236
   304
    }
moel@236
   305
moel@236
   306
    public static void WriteIoPort(uint port, byte value) {
moel@236
   307
      if (driver == null)
moel@236
   308
        return;
moel@236
   309
moel@236
   310
      WriteIoPortInput input = new WriteIoPortInput();
moel@236
   311
      input.PortNumber = port;
moel@236
   312
      input.Value = value;
moel@236
   313
moel@236
   314
      driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
moel@236
   315
    }
moel@236
   316
moel@236
   317
    public const uint InvalidPciAddress = 0xFFFFFFFF;
moel@236
   318
moel@236
   319
    public static uint GetPciAddress(byte bus, byte device, byte function) {
moel@236
   320
      return
moel@236
   321
        (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
moel@236
   322
    }
moel@236
   323
moel@236
   324
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   325
    private struct ReadPciConfigInput {
moel@236
   326
      public uint PciAddress;
moel@236
   327
      public uint RegAddress;
moel@236
   328
    }
moel@236
   329
moel@236
   330
    public static bool ReadPciConfig(uint pciAddress, uint regAddress, 
moel@236
   331
      out uint value) 
moel@236
   332
    {
moel@236
   333
      if (driver == null || (regAddress & 3) != 0) {
moel@236
   334
        value = 0;
moel@236
   335
        return false;
moel@236
   336
      }
moel@236
   337
moel@236
   338
      ReadPciConfigInput input = new ReadPciConfigInput();
moel@236
   339
      input.PciAddress = pciAddress;
moel@236
   340
      input.RegAddress = regAddress;
moel@236
   341
moel@236
   342
      value = 0;
moel@236
   343
      return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, 
moel@236
   344
        ref value);
moel@236
   345
    }
moel@236
   346
moel@236
   347
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   348
    private struct WritePciConfigInput {
moel@236
   349
      public uint PciAddress;
moel@236
   350
      public uint RegAddress;
moel@236
   351
      public uint Value;
moel@236
   352
    }
moel@236
   353
moel@236
   354
    public static bool WritePciConfig(uint pciAddress, uint regAddress, 
moel@236
   355
      uint value) 
moel@236
   356
    {
moel@236
   357
      if (driver == null || (regAddress & 3) != 0)
moel@236
   358
        return false;
moel@236
   359
moel@236
   360
      WritePciConfigInput input = new WritePciConfigInput();
moel@236
   361
      input.PciAddress = pciAddress;
moel@236
   362
      input.RegAddress = regAddress;
moel@236
   363
      input.Value = value;
moel@236
   364
moel@236
   365
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
moel@236
   366
    }
moel@279
   367
moel@279
   368
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@279
   369
    private struct ReadMemoryInput {
moel@279
   370
      public ulong address;
moel@279
   371
      public uint unitSize;
moel@279
   372
      public uint count;
moel@279
   373
    }
moel@279
   374
moel@279
   375
    public static bool ReadMemory<T>(ulong address, ref T buffer) {
moel@279
   376
      if (driver == null) {
moel@279
   377
        return false;
moel@279
   378
      }
moel@279
   379
moel@279
   380
      ReadMemoryInput input = new ReadMemoryInput();
moel@279
   381
      input.address = address;
moel@279
   382
      input.unitSize = 1;
moel@279
   383
      input.count = (uint)Marshal.SizeOf(buffer);
moel@279
   384
moel@279
   385
      return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
moel@279
   386
        ref buffer);
moel@279
   387
    }
moel@236
   388
  }
moel@236
   389
}