1# Copyright 2014 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""A server that serves MSR values over TCP. Takes a port as its sole parameter.
6
7The reference client for this server is msr_power_monitor.MsrPowerMonitor.
8
9Must be run as Administrator. We use TCP instead of named pipes or another IPC
10to avoid dealing with the pipe security mechanisms. We take the port as a
11parameter instead of choosing one, because it's hard to communicate the port
12number across integrity levels.
13
14Requires WinRing0 to be installed in the Python directory.
15msr_power_monitor.MsrPowerMonitor does this if needed.
16"""
17
18import argparse
19import ctypes
20import os
21import SocketServer
22import struct
23import sys
24
25
26WINRING0_STATUS_MESSAGES = (
27    'No error',
28    'Unsupported platform',
29    'Driver not loaded. You may need to run as Administrator',
30    'Driver not found',
31    'Driver unloaded by other process',
32    'Driver not loaded because of executing on Network Drive',
33    'Unknown error',
34)
35
36
37# The DLL initialization is global, so put it in a global variable.
38_winring0 = None
39
40
41class WinRing0Error(OSError):
42  pass
43
44
45def _WinRing0Path():
46  python_is_64_bit = sys.maxsize > 2 ** 32
47  dll_file_name = 'WinRing0x64.dll' if python_is_64_bit else 'WinRing0.dll'
48  return os.path.join(os.path.dirname(sys.executable), dll_file_name)
49
50
51def _Initialize():
52  global _winring0
53  if not _winring0:
54    winring0 = ctypes.WinDLL(_WinRing0Path())
55    if not winring0.InitializeOls():
56      winring0_status = winring0.GetDllStatus()
57      raise WinRing0Error(winring0_status,
58                          'Unable to initialize WinRing0: %s' %
59                          WINRING0_STATUS_MESSAGES[winring0_status])
60    _winring0 = winring0
61
62
63def _Deinitialize():
64  global _winring0
65  if _winring0:
66    _winring0.DeinitializeOls()
67    _winring0 = None
68
69
70def _ReadMsr(msr_number):
71  low = ctypes.c_uint()
72  high = ctypes.c_uint()
73  _winring0.Rdmsr(ctypes.c_uint(msr_number),
74                  ctypes.byref(low), ctypes.byref(high))
75  return high.value << 32 | low.value
76
77
78class MsrRequestHandler(SocketServer.StreamRequestHandler):
79  def handle(self):
80    msr_number = struct.unpack('I', self.rfile.read(4))[0]
81    self.wfile.write(struct.pack('Q', _ReadMsr(msr_number)))
82
83
84def main():
85  parser = argparse.ArgumentParser()
86  parser.add_argument('port', type=int)
87  args = parser.parse_args()
88
89  _Initialize()
90  try:
91    SocketServer.TCPServer.allow_reuse_address = True
92    server_address = ('127.0.0.1', args.port)
93    server = SocketServer.TCPServer(server_address, MsrRequestHandler)
94    server.serve_forever()
95  finally:
96    _Deinitialize()
97
98
99if __name__ == '__main__':
100  main()
101