Attempt at fixing Issue 253 without breaking Issue 159 once more.
3 This Source Code Form is subject to the terms of the Mozilla Public
4 License, v. 2.0. If a copy of the MPL was not distributed with this
5 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 Copyright (C) 2010-2012 Michael Möller <mmoeller@openhardwaremonitor.org>
13 using System.Reflection;
14 using System.Runtime.InteropServices;
15 using System.Security.AccessControl;
16 using System.Threading;
19 namespace OpenHardwareMonitor.Hardware {
20 internal static class Ring0 {
22 private static KernelDriver driver;
23 private static string fileName;
24 private static Mutex isaBusMutex;
25 private static readonly StringBuilder report = new StringBuilder();
27 private const uint OLS_TYPE = 40000;
28 private static IOControlCode
29 IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
30 IOControlCode.Access.Any),
31 IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
32 IOControlCode.Access.Any),
33 IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
34 IOControlCode.Access.Any),
35 IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822,
36 IOControlCode.Access.Any),
37 IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
38 IOControlCode.Access.Read),
39 IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836,
40 IOControlCode.Access.Write),
41 IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851,
42 IOControlCode.Access.Read),
43 IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
44 IOControlCode.Access.Write),
45 IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
46 IOControlCode.Access.Read);
48 private static string GetTempFileName() {
50 // try to get a file in the temporary folder
52 return Path.GetTempFileName();
53 } catch (IOException) {
56 catch (UnauthorizedAccessException) {
57 // we do not have the right to create a file in the temp folder
59 catch (NotSupportedException) {
60 // invalid path format of the TMP system environment variable
63 // if this failed, we try to create one in the application folder
64 string fileName = Path.ChangeExtension(
65 Assembly.GetExecutingAssembly().Location, ".sys");
67 using (FileStream stream = File.Create(fileName)) {
70 } catch (IOException) { }
71 catch (UnauthorizedAccessException) { }
76 private static bool ExtractDriver(string fileName) {
77 string resourceName = "OpenHardwareMonitor.Hardware." +
78 (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :
82 Assembly.GetExecutingAssembly().GetManifestResourceNames();
84 for (int i = 0; i < names.Length; i++) {
85 if (names[i].Replace('\\', '.') == resourceName) {
86 using (Stream stream = Assembly.GetExecutingAssembly().
87 GetManifestResourceStream(names[i]))
89 buffer = new byte[stream.Length];
90 stream.Read(buffer, 0, buffer.Length);
99 using (FileStream target = new FileStream(fileName, FileMode.Create)) {
100 target.Write(buffer, 0, buffer.Length);
102 } catch (IOException) {
103 // for example there is not enough space on the disk
110 public static void Open() {
111 // no implementation for unix systems
112 int p = (int)Environment.OSVersion.Platform;
113 if ((p == 4) || (p == 128))
119 // clear the current report
122 driver = new KernelDriver("WinRing0_1_2_0");
125 if (!driver.IsOpen) {
126 // driver is not loaded, try to install and open
128 fileName = GetTempFileName();
129 if (fileName != null && ExtractDriver(fileName)) {
130 if (driver.Install(fileName)) {
133 if (!driver.IsOpen) {
135 report.AppendLine("Status: Opening driver failed after install");
138 // install failed, try to delete and reinstall
141 if (driver.Install(fileName)) {
144 if (!driver.IsOpen) {
147 "Status: Opening driver failed after reinstall");
150 report.AppendLine("Status: Installing driver \"" +
151 fileName + "\" failed" +
152 (File.Exists(fileName) ? " and file exists" : ""));
154 report.Append("Exception: " + Marshal.GetExceptionForHR(
155 Marshal.GetHRForLastWin32Error()).Message);
159 report.AppendLine("Status: Extracting driver failed");
163 // try to delte the driver file
164 if (File.Exists(fileName))
165 File.Delete(fileName);
167 } catch (IOException) { }
168 catch (UnauthorizedAccessException) { }
174 string mutexName = "Global\\Access_ISABUS.HTP.Method";
176 isaBusMutex = new Mutex(false, mutexName);
177 } catch (UnauthorizedAccessException) {
179 isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
184 public static bool IsOpen {
185 get { return driver != null; }
188 public static void Close() {
193 driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
202 if (isaBusMutex != null) {
207 // try to delete temporary driver file again if failed during open
208 if (fileName != null && File.Exists(fileName)) {
210 File.Delete(fileName);
212 } catch (IOException) { }
213 catch (UnauthorizedAccessException) { }
217 public static string GetReport() {
218 if (report.Length > 0) {
219 StringBuilder r = new StringBuilder();
220 r.AppendLine("Ring0");
229 public static bool WaitIsaBusMutex(int millisecondsTimeout) {
230 if (isaBusMutex == null)
233 return isaBusMutex.WaitOne(millisecondsTimeout, false);
234 } catch (AbandonedMutexException) { return false; }
235 catch (InvalidOperationException) { return false; }
238 public static void ReleaseIsaBusMutex() {
239 if (isaBusMutex == null)
241 isaBusMutex.ReleaseMutex();
244 public static bool Rdmsr(uint index, out uint eax, out uint edx) {
245 if (driver == null) {
252 bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
255 edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
256 eax = (uint)(buffer & 0xFFFFFFFF);
260 public static bool RdmsrTx(uint index, out uint eax, out uint edx,
261 ulong threadAffinityMask)
263 ulong mask = ThreadAffinity.Set(threadAffinityMask);
265 bool result = Rdmsr(index, out eax, out edx);
267 ThreadAffinity.Set(mask);
271 [StructLayout(LayoutKind.Sequential, Pack = 1)]
272 private struct WrmsrInput {
273 public uint Register;
277 public static bool Wrmsr(uint index, uint eax, uint edx) {
281 WrmsrInput input = new WrmsrInput();
282 input.Register = index;
283 input.Value = ((ulong)edx << 32) | eax;
285 return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
288 public static byte ReadIoPort(uint port) {
293 driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
295 return (byte)(value & 0xFF);
298 [StructLayout(LayoutKind.Sequential, Pack = 1)]
299 private struct WriteIoPortInput {
300 public uint PortNumber;
304 public static void WriteIoPort(uint port, byte value) {
308 WriteIoPortInput input = new WriteIoPortInput();
309 input.PortNumber = port;
312 driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
315 public const uint InvalidPciAddress = 0xFFFFFFFF;
317 public static uint GetPciAddress(byte bus, byte device, byte function) {
319 (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
322 [StructLayout(LayoutKind.Sequential, Pack = 1)]
323 private struct ReadPciConfigInput {
324 public uint PciAddress;
325 public uint RegAddress;
328 public static bool ReadPciConfig(uint pciAddress, uint regAddress,
331 if (driver == null || (regAddress & 3) != 0) {
336 ReadPciConfigInput input = new ReadPciConfigInput();
337 input.PciAddress = pciAddress;
338 input.RegAddress = regAddress;
341 return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input,
345 [StructLayout(LayoutKind.Sequential, Pack = 1)]
346 private struct WritePciConfigInput {
347 public uint PciAddress;
348 public uint RegAddress;
352 public static bool WritePciConfig(uint pciAddress, uint regAddress,
355 if (driver == null || (regAddress & 3) != 0)
358 WritePciConfigInput input = new WritePciConfigInput();
359 input.PciAddress = pciAddress;
360 input.RegAddress = regAddress;
363 return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
366 [StructLayout(LayoutKind.Sequential, Pack = 1)]
367 private struct ReadMemoryInput {
368 public ulong address;
369 public uint unitSize;
373 public static bool ReadMemory<T>(ulong address, ref T buffer) {
374 if (driver == null) {
378 ReadMemoryInput input = new ReadMemoryInput();
379 input.address = address;
381 input.count = (uint)Marshal.SizeOf(buffer);
383 return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,