Debian Codegraph @

plyer/platforms/win/cpu.py

raw symbols SCIP
1 '''
2 Module of Windows API for plyer.cpu.
3 '''
4
5 from ctypes import (
6 c_ulonglong, c_ulong, byref,
7 Structure, POINTER, Union, windll, create_string_buffer,
8 sizeof, cast, c_void_p, c_uint32
9 )
10 from ctypes.wintypes import (
11 BYTE, DWORD, WORD
12 )
13
14 from plyer.facades import CPU
15
16
17 KERNEL = windll.kernel32
18 ERROR_INSUFFICIENT_BUFFER = 0x0000007A
19
20
21 class CacheType:
22 '''
23 Win API PROCESSOR_CACHE_TYPE enum.
24 '''
25
26 unified = 0
27 instruction = 1
28 data = 2
29 trace = 3
30
31
32 class RelationshipType:
33 '''
34 Win API LOGICAL_PROCESSOR_RELATIONSHIP enum.
35 '''
36
37 processor_core = 0 # logical proc sharing single core
38 numa_node = 1 # logical proc sharing single NUMA node
39 cache = 2 # logical proc sharing cache
40 processor_package = 3 # logical proc sharing physical package
41 group = 4 # logical proc sharing processor group
42 all = 0xffff # logical proc info for all groups
43
44
45 class CacheDescriptor(Structure):
46 '''
47 Win API CACHE_DESCRIPTOR struct.
48 '''
49
50 _fields_ = [
51 ('Level', BYTE),
52 ('Associativity', BYTE),
53 ('LineSize', WORD),
54 ('Size', DWORD),
55 ('Type', DWORD)
56 ]
57
58
59 class ProcessorCore(Structure):
60 '''
61 Win API ProcessorCore struct.
62 '''
63
64 _fields_ = [('Flags', BYTE)]
65
66
67 class NumaNode(Structure):
68 '''
69 Win API NumaNode struct.
70 '''
71
72 _fields_ = [('NodeNumber', DWORD)]
73
74
75 class SystemLPIUnion(Union):
76 '''
77 Win API SYSTEM_LOGICAL_PROCESSOR_INFORMATION union without name.
78 '''
79
80 _fields_ = [
81 ('ProcessorCore', ProcessorCore),
82 ('NumaNode', NumaNode),
83 ('Cache', CacheDescriptor),
84 ('Reserved', c_ulonglong)
85 ]
86
87
88 class SystemLPI(Structure):
89 '''
90 Win API SYSTEM_LOGICAL_PROCESSOR_INFORMATION struct.
91 '''
92
93 _fields_ = [
94 ('ProcessorMask', c_ulong),
95 ('Relationship', c_ulong),
96 ('LPI', SystemLPIUnion)
97 ]
98
99
100 class WinCPU(CPU):
101 '''
102 Implementation of Windows CPU API.
103 '''
104
105 @staticmethod
106 def _countbits(mask):
107 # make sure the correct ULONG_PTR size is used on 64bit
108 # https://docs.microsoft.com/en-us/windows/
109 # desktop/WinProg/windows-data-types
110 # note: not a pointer per-se, != PULONG_PTR
111 ulong_ptr = c_ulonglong if sizeof(c_void_p) == 8 else c_ulong
112 # note: c_ulonglong only on 64bit, otherwise c_ulong
113
114 # DWORD == c_uint32
115 # https://docs.microsoft.com/en-us/windows/
116 # desktop/WinProg/windows-data-types
117 lshift = c_uint32(sizeof(ulong_ptr) * 8 - 1)
118 assert lshift.value in (31, 63), lshift # 32 or 64 bits - 1
119
120 lshift = lshift.value
121 test = 1 << lshift
122 assert test % 2 == 0, test
123
124 count = 0
125 i = 0
126 while i <= lshift:
127 i += 1
128
129 # do NOT remove!!!
130 # test value has to be %2 == 0,
131 # except the last case where the value is 1,
132 # so that int(test) == int(float(test))
133 # and the mask bit is counted correctly
134 assert test % 2 == 0 or float(test) == 1.0, test
135
136 # https://stackoverflow.com/a/1746642/5994041
137 # note: useful to print(str(bin(int(...)))[2:])
138 count += 1 if (mask & int(test)) else 0
139 test /= 2
140
141 return count
142
143 def _logprocinfo(self, relationship):
144 get_logical_process_info = KERNEL.GetLogicalProcessorInformation
145
146 # first call with no structure to get the real size of the required
147 buff_length = c_ulong(0)
148 result = get_logical_process_info(None, byref(buff_length))
149 assert not result, result
150 error = KERNEL.GetLastError()
151 assert error == ERROR_INSUFFICIENT_BUFFER, error
152 assert buff_length, buff_length
153
154 # create buffer from the real winapi buffer length
155 buff = create_string_buffer(buff_length.value)
156
157 # call again with buffer pointer + the same length as arguments
158 result = get_logical_process_info(buff, byref(buff_length))
159 assert result, (result, KERNEL.GetLastError())
160
161 # memory size of one LPI struct in the array of LPI structs
162 offset = sizeof(SystemLPI) # ok
163 values = {
164 key: 0 for key in (
165 'relationship', 'mask',
166 'L1', 'L2', 'L3'
167 )
168 }
169
170 for i in range(0, buff_length.value, offset):
171 slpi = cast(
172 buff[i: i + offset],
173 POINTER(SystemLPI)
174 ).contents
175
176 if slpi.Relationship != relationship:
177 continue
178
179 values['relationship'] += 1
180 values['mask'] += self._countbits(slpi.ProcessorMask)
181
182 if slpi.LPI.Cache.Level == 1:
183 values['L1'] += 1
184 elif slpi.LPI.Cache.Level == 2:
185 values['L2'] += 1
186 elif slpi.LPI.Cache.Level == 3:
187 values['L3'] += 1
188
189 return values
190
191 def _sockets(self):
192 # physical CPU sockets (or slots) on motherboard
193 return self._logprocinfo(
194 RelationshipType.processor_package
195 )['relationship']
196
197 def _physical(self):
198 # cores
199 return self._logprocinfo(
200 RelationshipType.processor_core
201 )['relationship']
202
203 def _logical(self):
204 # cores * threads
205 # if hyperthreaded core -> more than one logical processor
206 return self._logprocinfo(
207 RelationshipType.processor_core
208 )['mask']
209
210 def _cache(self):
211 # L1, L2, L3 cache count
212 result = self._logprocinfo(
213 RelationshipType.cache
214 )
215 return {
216 key: result[key]
217 for key in result
218 if key in ('L1', 'L2', 'L3')
219 }
220
221 def _numa(self):
222 # numa nodes
223 return self._logprocinfo(
224 RelationshipType.numa_node
225 )['relationship']
226
227
228 def instance():
229 '''
230 Instance for facade proxy.
231 '''
232 return WinCPU()
233
234
235 # Resources:
236 # GetLogicalProcessInformation
237 # https://msdn.microsoft.com/en-us/library/ms683194(v=vs.85).aspx
238
239 # SYSTEM_LOGICAL_PROCESSOR_INFORMATION
240 # https://msdn.microsoft.com/en-us/library/ms686694(v=vs.85).aspx
241
242 # LOGICAL_PROCESSOR_RELATIONSHIP enum (0 - 4, 0xffff)
243 # https://msdn.microsoft.com/2ada52f0-70ec-4146-9ef7-9af3b08996f9
244
245 # CACHE_DESCRIPTOR struct
246 # https://msdn.microsoft.com/38cfa605-831c-45ef-a99f-55f42b2b56e9
247
248 # PROCESSOR_CACHE_TYPE
249 # https://msdn.microsoft.com/23044f67-e944-43c2-8c75-3d2fba87cb3c
250
251 # C example
252 # https://msdn.microsoft.com/en-us/904d2d35-f419-4e8f-a689-f39ed926644c