Debian Codegraph @

cpuinfo/cpuinfo.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) 2014-2022 Matthew Brennan Jones <[email protected]>
4 # Py-cpuinfo gets CPU info with pure Python
5 # It uses the MIT License
6 # It is hosted at: https://github.com/workhorsy/py-cpuinfo
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining
9 # a copy of this software and associated documentation files (the
10 # "Software"), to deal in the Software without restriction, including
11 # without limitation the rights to use, copy, modify, merge, publish,
12 # distribute, sublicense, and/or sell copies of the Software, and to
13 # permit persons to whom the Software is furnished to do so, subject to
14 # the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included
17 # in all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
27 CPUINFO_VERSION = (9, 0, 0)
28 CPUINFO_VERSION_STRING = '.'.join([str(n) for n in CPUINFO_VERSION])
29
30 import os, sys
31 import platform
32 import multiprocessing
33 import ctypes
34
35
36 CAN_CALL_CPUID_IN_SUBPROCESS = True
37
38 g_trace = None
39
40
41 class Trace:
42 def __init__(self, is_active, is_stored_in_string):
43 self._is_active = is_active
44 if not self._is_active:
45 return
46
47 from datetime import datetime
48 from io import StringIO
49
50 if is_stored_in_string:
51 self._output = StringIO()
52 else:
53 date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S-%f")
54 self._output = open('cpuinfo_trace_{0}.trace'.format(date), 'w')
55
56 self._stdout = StringIO()
57 self._stderr = StringIO()
58 self._err = None
59
60 def header(self, msg):
61 if not self._is_active: return
62
63 from inspect import stack
64 frame = stack()[1]
65 file = frame[1]
66 line = frame[2]
67 self._output.write("{0} ({1} {2})\n".format(msg, file, line))
68 self._output.flush()
69
70 def success(self):
71 if not self._is_active: return
72
73 from inspect import stack
74 frame = stack()[1]
75 file = frame[1]
76 line = frame[2]
77
78 self._output.write("Success ... ({0} {1})\n\n".format(file, line))
79 self._output.flush()
80
81 def fail(self, msg):
82 if not self._is_active: return
83
84 from inspect import stack
85 frame = stack()[1]
86 file = frame[1]
87 line = frame[2]
88
89 if isinstance(msg, str):
90 msg = ''.join(['\t' + line for line in msg.split('\n')]) + '\n'
91
92 self._output.write(msg)
93 self._output.write("Failed ... ({0} {1})\n\n".format(file, line))
94 self._output.flush()
95 elif isinstance(msg, Exception):
96 from traceback import format_exc
97 err_string = format_exc()
98 self._output.write("\tFailed ... ({0} {1})\n".format(file, line))
99 self._output.write(''.join(['\t\t{0}\n'.format(n) for n in err_string.split('\n')]) + '\n')
100 self._output.flush()
101
102 def command_header(self, msg):
103 if not self._is_active: return
104
105 from inspect import stack
106 frame = stack()[3]
107 file = frame[1]
108 line = frame[2]
109 self._output.write("\t{0} ({1} {2})\n".format(msg, file, line))
110 self._output.flush()
111
112 def command_output(self, msg, output):
113 if not self._is_active: return
114
115 self._output.write("\t\t{0}\n".format(msg))
116 self._output.write(''.join(['\t\t\t{0}\n'.format(n) for n in output.split('\n')]) + '\n')
117 self._output.flush()
118
119 def keys(self, keys, info, new_info):
120 if not self._is_active: return
121
122 from inspect import stack
123 frame = stack()[2]
124 file = frame[1]
125 line = frame[2]
126
127 # List updated keys
128 self._output.write("\tChanged keys ({0} {1})\n".format(file, line))
129 changed_keys = [key for key in keys if key in info and key in new_info and info[key] != new_info[key]]
130 if changed_keys:
131 for key in changed_keys:
132 self._output.write('\t\t{0}: {1} to {2}\n'.format(key, info[key], new_info[key]))
133 else:
134 self._output.write('\t\tNone\n')
135
136 # List new keys
137 self._output.write("\tNew keys ({0} {1})\n".format(file, line))
138 new_keys = [key for key in keys if key in new_info and key not in info]
139 if new_keys:
140 for key in new_keys:
141 self._output.write('\t\t{0}: {1}\n'.format(key, new_info[key]))
142 else:
143 self._output.write('\t\tNone\n')
144
145 self._output.write('\n')
146 self._output.flush()
147
148 def write(self, msg):
149 if not self._is_active: return
150
151 self._output.write(msg + '\n')
152 self._output.flush()
153
154 def to_dict(self, info, is_fail):
155 return {
156 'output' : self._output.getvalue(),
157 'stdout' : self._stdout.getvalue(),
158 'stderr' : self._stderr.getvalue(),
159 'info' : info,
160 'err' : self._err,
161 'is_fail' : is_fail
162 }
163
164 class DataSource:
165 bits = platform.architecture()[0]
166 cpu_count = multiprocessing.cpu_count()
167 is_windows = platform.system().lower() == 'windows'
168 arch_string_raw = platform.machine()
169 uname_string_raw = platform.uname()[5]
170 can_cpuid = True
171
172 @staticmethod
173 def has_proc_cpuinfo():
174 return os.path.exists('/proc/cpuinfo')
175
176 @staticmethod
177 def has_dmesg():
178 return len(_program_paths('dmesg')) > 0
179
180 @staticmethod
181 def has_var_run_dmesg_boot():
182 uname = platform.system().strip().strip('"').strip("'").strip().lower()
183 return 'linux' in uname and os.path.exists('/var/run/dmesg.boot')
184
185 @staticmethod
186 def has_cpufreq_info():
187 return len(_program_paths('cpufreq-info')) > 0
188
189 @staticmethod
190 def has_sestatus():
191 return len(_program_paths('sestatus')) > 0
192
193 @staticmethod
194 def has_sysctl():
195 return len(_program_paths('sysctl')) > 0
196
197 @staticmethod
198 def has_isainfo():
199 return len(_program_paths('isainfo')) > 0
200
201 @staticmethod
202 def has_kstat():
203 return len(_program_paths('kstat')) > 0
204
205 @staticmethod
206 def has_sysinfo():
207 uname = platform.system().strip().strip('"').strip("'").strip().lower()
208 is_beos = 'beos' in uname or 'haiku' in uname
209 return is_beos and len(_program_paths('sysinfo')) > 0
210
211 @staticmethod
212 def has_lscpu():
213 return len(_program_paths('lscpu')) > 0
214
215 @staticmethod
216 def has_ibm_pa_features():
217 return len(_program_paths('lsprop')) > 0
218
219 @staticmethod
220 def has_wmic():
221 returncode, output = _run_and_get_stdout(['wmic', 'os', 'get', 'Version'])
222 return returncode == 0 and len(output) > 0
223
224 @staticmethod
225 def cat_proc_cpuinfo():
226 return _run_and_get_stdout(['cat', '/proc/cpuinfo'])
227
228 @staticmethod
229 def cpufreq_info():
230 return _run_and_get_stdout(['cpufreq-info'])
231
232 @staticmethod
233 def sestatus_b():
234 return _run_and_get_stdout(['sestatus', '-b'])
235
236 @staticmethod
237 def dmesg_a():
238 return _run_and_get_stdout(['dmesg', '-a'])
239
240 @staticmethod
241 def cat_var_run_dmesg_boot():
242 return _run_and_get_stdout(['cat', '/var/run/dmesg.boot'])
243
244 @staticmethod
245 def sysctl_machdep_cpu_hw_cpufrequency():
246 return _run_and_get_stdout(['sysctl', 'machdep.cpu', 'hw.cpufrequency'])
247
248 @staticmethod
249 def isainfo_vb():
250 return _run_and_get_stdout(['isainfo', '-vb'])
251
252 @staticmethod
253 def kstat_m_cpu_info():
254 return _run_and_get_stdout(['kstat', '-m', 'cpu_info'])
255
256 @staticmethod
257 def sysinfo_cpu():
258 return _run_and_get_stdout(['sysinfo', '-cpu'])
259
260 @staticmethod
261 def lscpu():
262 return _run_and_get_stdout(['lscpu'])
263
264 @staticmethod
265 def ibm_pa_features():
266 import glob
267
268 ibm_features = glob.glob('/proc/device-tree/cpus/*/ibm,pa-features')
269 if ibm_features:
270 return _run_and_get_stdout(['lsprop', ibm_features[0]])
271
272 @staticmethod
273 def wmic_cpu():
274 return _run_and_get_stdout(['wmic', 'cpu', 'get', 'Name,CurrentClockSpeed,L2CacheSize,L3CacheSize,Description,Caption,Manufacturer', '/format:list'])
275
276 @staticmethod
277 def winreg_processor_brand():
278 processor_brand = _read_windows_registry_key(r"Hardware\Description\System\CentralProcessor\0", "ProcessorNameString")
279 return processor_brand.strip()
280
281 @staticmethod
282 def winreg_vendor_id_raw():
283 vendor_id_raw = _read_windows_registry_key(r"Hardware\Description\System\CentralProcessor\0", "VendorIdentifier")
284 return vendor_id_raw
285
286 @staticmethod
287 def winreg_arch_string_raw():
288 arch_string_raw = _read_windows_registry_key(r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", "PROCESSOR_ARCHITECTURE")
289 return arch_string_raw
290
291 @staticmethod
292 def winreg_hz_actual():
293 hz_actual = _read_windows_registry_key(r"Hardware\Description\System\CentralProcessor\0", "~Mhz")
294 hz_actual = _to_decimal_string(hz_actual)
295 return hz_actual
296
297 @staticmethod
298 def winreg_feature_bits():
299 feature_bits = _read_windows_registry_key(r"Hardware\Description\System\CentralProcessor\0", "FeatureSet")
300 return feature_bits
301
302
303 def _program_paths(program_name):
304 paths = []
305 exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
306 for p in os.environ['PATH'].split(os.pathsep):
307 p = os.path.join(p, program_name)
308 if os.access(p, os.X_OK):
309 paths.append(p)
310 for e in exts:
311 pext = p + e
312 if os.access(pext, os.X_OK):
313 paths.append(pext)
314 return paths
315
316 def _run_and_get_stdout(command, pipe_command=None):
317 from subprocess import Popen, PIPE
318
319 g_trace.command_header('Running command "' + ' '.join(command) + '" ...')
320
321 # Run the command normally
322 if not pipe_command:
323 p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
324 # Run the command and pipe it into another command
325 else:
326 p2 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
327 p1 = Popen(pipe_command, stdin=p2.stdout, stdout=PIPE, stderr=PIPE)
328 p2.stdout.close()
329
330 # Get the stdout and stderr
331 stdout_output, stderr_output = p1.communicate()
332 stdout_output = stdout_output.decode(encoding='UTF-8')
333 stderr_output = stderr_output.decode(encoding='UTF-8')
334
335 # Send the result to the logger
336 g_trace.command_output('return code:', str(p1.returncode))
337 g_trace.command_output('stdout:', stdout_output)
338
339 # Return the return code and stdout
340 return p1.returncode, stdout_output
341
342 def _read_windows_registry_key(key_name, field_name):
343 g_trace.command_header('Reading Registry key "{0}" field "{1}" ...'.format(key_name, field_name))
344
345 try:
346 import _winreg as winreg
347 except ImportError as err:
348 try:
349 import winreg
350 except ImportError as err:
351 pass
352
353 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name)
354 value = winreg.QueryValueEx(key, field_name)[0]
355 winreg.CloseKey(key)
356 g_trace.command_output('value:', str(value))
357 return value
358
359 # Make sure we are running on a supported system
360 def _check_arch():
361 arch, bits = _parse_arch(DataSource.arch_string_raw)
362 if not arch in ['ARM_7', 'ARM_8',
363 'HPPA_32', 'HPPA_64',
364 'LOONG_32', 'LOONG_64',
365 'MIPS_32', 'MIPS_64',
366 'PPC_32', 'PPC_64',
367 'RISCV_32', 'RISCV_64',
368 'SPARC_32', 'SPARC_64',
369 'S390X',
370 'X86_32', 'X86_64']:
371 raise Exception("py-cpuinfo currently only works on X86 "
372 "and some ARM/HPPA/LoongArch/MIPS/PPC/RISCV/SPARC/S390X CPUs." )
373
374 def _obj_to_b64(thing):
375 import pickle
376 import base64
377
378 a = thing
379 b = pickle.dumps(a)
380 c = base64.b64encode(b)
381 d = c.decode('utf8')
382 return d
383
384 def _b64_to_obj(thing):
385 import pickle
386 import base64
387
388 try:
389 a = base64.b64decode(thing)
390 b = pickle.loads(a)
391 return b
392 except Exception:
393 return {}
394
395 def _utf_to_str(input):
396 if isinstance(input, list):
397 return [_utf_to_str(element) for element in input]
398 elif isinstance(input, dict):
399 return {_utf_to_str(key): _utf_to_str(value)
400 for key, value in input.items()}
401 else:
402 return input
403
404 def _copy_new_fields(info, new_info):
405 keys = [
406 'vendor_id_raw', 'hardware_raw', 'brand_raw', 'hz_advertised_friendly', 'hz_actual_friendly',
407 'hz_advertised', 'hz_actual', 'arch', 'bits', 'count',
408 'arch_string_raw', 'uname_string_raw',
409 'l2_cache_size', 'l2_cache_line_size', 'l2_cache_associativity',
410 'stepping', 'model', 'family',
411 'processor_type', 'flags',
412 'l3_cache_size', 'l1_data_cache_size', 'l1_instruction_cache_size'
413 ]
414
415 g_trace.keys(keys, info, new_info)
416
417 # Update the keys with new values
418 for key in keys:
419 if new_info.get(key, None) and not info.get(key, None):
420 info[key] = new_info[key]
421 elif key == 'flags' and new_info.get('flags'):
422 for f in new_info['flags']:
423 if f not in info['flags']: info['flags'].append(f)
424 info['flags'].sort()
425
426 def _get_field_actual(cant_be_number, raw_string, field_names):
427 for line in raw_string.splitlines():
428 for field_name in field_names:
429 field_name = field_name.lower()
430 if ':' in line:
431 left, right = line.split(':', 1)
432 left = left.strip().lower()
433 right = right.strip()
434 if left == field_name and len(right) > 0:
435 if cant_be_number:
436 if not right.isdigit():
437 return right
438 else:
439 return right
440
441 return None
442
443 def _get_field(cant_be_number, raw_string, convert_to, default_value, *field_names):
444 retval = _get_field_actual(cant_be_number, raw_string, field_names)
445
446 # Convert the return value
447 if retval and convert_to:
448 try:
449 retval = convert_to(retval)
450 except Exception:
451 retval = default_value
452
453 # Return the default if there is no return value
454 if retval is None:
455 retval = default_value
456
457 return retval
458
459 def _to_decimal_string(ticks):
460 try:
461 # Convert to string
462 ticks = '{0}'.format(ticks)
463 # Sometimes ',' is used as a decimal separator
464 ticks = ticks.replace(',', '.')
465
466 # Strip off non numbers and decimal places
467 ticks = "".join(n for n in ticks if n.isdigit() or n=='.').strip()
468 if ticks == '':
469 ticks = '0'
470
471 # Add decimal if missing
472 if '.' not in ticks:
473 ticks = '{0}.0'.format(ticks)
474
475 # Remove trailing zeros
476 ticks = ticks.rstrip('0')
477
478 # Add one trailing zero for empty right side
479 if ticks.endswith('.'):
480 ticks = '{0}0'.format(ticks)
481
482 # Make sure the number can be converted to a float
483 ticks = float(ticks)
484 ticks = '{0}'.format(ticks)
485 return ticks
486 except Exception:
487 return '0.0'
488
489 def _hz_short_to_full(ticks, scale):
490 try:
491 # Make sure the number can be converted to a float
492 ticks = float(ticks)
493 ticks = '{0}'.format(ticks)
494
495 # Scale the numbers
496 hz = ticks.lstrip('0')
497 old_index = hz.index('.')
498 hz = hz.replace('.', '')
499 hz = hz.ljust(scale + old_index+1, '0')
500 new_index = old_index + scale
501 hz = '{0}.{1}'.format(hz[:new_index], hz[new_index:])
502 left, right = hz.split('.')
503 left, right = int(left), int(right)
504 return (left, right)
505 except Exception:
506 return (0, 0)
507
508 def _hz_friendly_to_full(hz_string):
509 try:
510 hz_string = hz_string.strip().lower()
511 hz, scale = (None, None)
512
513 if hz_string.endswith('ghz'):
514 scale = 9
515 elif hz_string.endswith('mhz'):
516 scale = 6
517 elif hz_string.endswith('hz'):
518 scale = 0
519
520 hz = "".join(n for n in hz_string if n.isdigit() or n=='.').strip()
521 if not '.' in hz:
522 hz += '.0'
523
524 hz, scale = _hz_short_to_full(hz, scale)
525
526 return (hz, scale)
527 except Exception:
528 return (0, 0)
529
530 def _hz_short_to_friendly(ticks, scale):
531 try:
532 # Get the raw Hz as a string
533 left, right = _hz_short_to_full(ticks, scale)
534 result = '{0}.{1}'.format(left, right)
535
536 # Get the location of the dot, and remove said dot
537 dot_index = result.index('.')
538 result = result.replace('.', '')
539
540 # Get the Hz symbol and scale
541 symbol = "Hz"
542 scale = 0
543 if dot_index > 9:
544 symbol = "GHz"
545 scale = 9
546 elif dot_index > 6:
547 symbol = "MHz"
548 scale = 6
549 elif dot_index > 3:
550 symbol = "KHz"
551 scale = 3
552
553 # Get the Hz with the dot at the new scaled point
554 result = '{0}.{1}'.format(result[:-scale-1], result[-scale-1:])
555
556 # Format the ticks to have 4 numbers after the decimal
557 # and remove any superfluous zeroes.
558 result = '{0:.4f} {1}'.format(float(result), symbol)
559 result = result.rstrip('0')
560 return result
561 except Exception:
562 return '0.0000 Hz'
563
564 def _to_friendly_bytes(input):
565 import re
566
567 if not input:
568 return input
569 input = "{0}".format(input)
570
571 formats = {
572 r"^[0-9]+B$" : 'B',
573 r"^[0-9]+K$" : 'KB',
574 r"^[0-9]+M$" : 'MB',
575 r"^[0-9]+G$" : 'GB'
576 }
577
578 for pattern, friendly_size in formats.items():
579 if re.match(pattern, input):
580 return "{0} {1}".format(input[ : -1].strip(), friendly_size)
581
582 return input
583
584 def _friendly_bytes_to_int(friendly_bytes):
585 input = friendly_bytes.lower()
586
587 formats = [
588 {'gib' : 1024 * 1024 * 1024},
589 {'mib' : 1024 * 1024},
590 {'kib' : 1024},
591
592 {'gb' : 1024 * 1024 * 1024},
593 {'mb' : 1024 * 1024},
594 {'kb' : 1024},
595
596 {'g' : 1024 * 1024 * 1024},
597 {'m' : 1024 * 1024},
598 {'k' : 1024},
599 {'b' : 1},
600 ]
601
602 try:
603 for entry in formats:
604 pattern = list(entry.keys())[0]
605 multiplier = list(entry.values())[0]
606 if input.endswith(pattern):
607 return int(input.split(pattern)[0].strip()) * multiplier
608
609 except Exception as err:
610 pass
611
612 return friendly_bytes
613
614 def _parse_cpu_brand_string(cpu_string):
615 # Just return 0 if the processor brand does not have the Hz
616 if not 'hz' in cpu_string.lower():
617 return ('0.0', 0)
618
619 hz = cpu_string.lower()
620 scale = 0
621
622 if hz.endswith('mhz'):
623 scale = 6
624 elif hz.endswith('ghz'):
625 scale = 9
626 if '@' in hz:
627 hz = hz.split('@')[1]
628 else:
629 hz = hz.rsplit(None, 1)[1]
630
631 hz = hz.rstrip('mhz').rstrip('ghz').strip()
632 hz = _to_decimal_string(hz)
633
634 return (hz, scale)
635
636 def _parse_cpu_brand_string_dx(cpu_string):
637 import re
638
639 # Find all the strings inside brackets ()
640 starts = [m.start() for m in re.finditer(r"\(", cpu_string)]
641 ends = [m.start() for m in re.finditer(r"\)", cpu_string)]
642 insides = {k: v for k, v in zip(starts, ends)}
643 insides = [cpu_string[start+1 : end] for start, end in insides.items()]
644
645 # Find all the fields
646 vendor_id, stepping, model, family = (None, None, None, None)
647 for inside in insides:
648 for pair in inside.split(','):
649 pair = [n.strip() for n in pair.split(':')]
650 if len(pair) > 1:
651 name, value = pair[0], pair[1]
652 if name == 'origin':
653 vendor_id = value.strip('"')
654 elif name == 'stepping':
655 stepping = int(value.lstrip('0x'), 16)
656 elif name == 'model':
657 model = int(value.lstrip('0x'), 16)
658 elif name in ['fam', 'family']:
659 family = int(value.lstrip('0x'), 16)
660
661 # Find the Processor Brand
662 # Strip off extra strings in brackets at end
663 brand = cpu_string.strip()
664 is_working = True
665 while is_working:
666 is_working = False
667 for inside in insides:
668 full = "({0})".format(inside)
669 if brand.endswith(full):
670 brand = brand[ :-len(full)].strip()
671 is_working = True
672
673 # Find the Hz in the brand string
674 hz_brand, scale = _parse_cpu_brand_string(brand)
675
676 # Find Hz inside brackets () after the brand string
677 if hz_brand == '0.0':
678 for inside in insides:
679 hz = inside
680 for entry in ['GHz', 'MHz', 'Hz']:
681 if entry in hz:
682 hz = "CPU @ " + hz[ : hz.find(entry) + len(entry)]
683 hz_brand, scale = _parse_cpu_brand_string(hz)
684 break
685
686 return (hz_brand, scale, brand, vendor_id, stepping, model, family)
687
688 def _parse_dmesg_output(output):
689 try:
690 # Get all the dmesg lines that might contain a CPU string
691 lines = output.split(' CPU0:')[1:] + \
692 output.split(' CPU1:')[1:] + \
693 output.split(' CPU:')[1:] + \
694 output.split('\nCPU0:')[1:] + \
695 output.split('\nCPU1:')[1:] + \
696 output.split('\nCPU:')[1:]
697 lines = [l.split('\n')[0].strip() for l in lines]
698
699 # Convert the lines to CPU strings
700 cpu_strings = [_parse_cpu_brand_string_dx(l) for l in lines]
701
702 # Find the CPU string that has the most fields
703 best_string = None
704 highest_count = 0
705 for cpu_string in cpu_strings:
706 count = sum([n is not None for n in cpu_string])
707 if count > highest_count:
708 highest_count = count
709 best_string = cpu_string
710
711 # If no CPU string was found, return {}
712 if not best_string:
713 return {}
714
715 hz_actual, scale, processor_brand, vendor_id, stepping, model, family = best_string
716
717 # Origin
718 if ' Origin=' in output:
719 fields = output[output.find(' Origin=') : ].split('\n')[0]
720 fields = fields.strip().split()
721 fields = [n.strip().split('=') for n in fields]
722 fields = [{n[0].strip().lower() : n[1].strip()} for n in fields]
723
724 for field in fields:
725 name = list(field.keys())[0]
726 value = list(field.values())[0]
727
728 if name == 'origin':
729 vendor_id = value.strip('"')
730 elif name == 'stepping':
731 stepping = int(value.lstrip('0x'), 16)
732 elif name == 'model':
733 model = int(value.lstrip('0x'), 16)
734 elif name in ['fam', 'family']:
735 family = int(value.lstrip('0x'), 16)
736
737 # Features
738 flag_lines = []
739 for category in [' Features=', ' Features2=', ' AMD Features=', ' AMD Features2=']:
740 if category in output:
741 flag_lines.append(output.split(category)[1].split('\n')[0])
742
743 flags = []
744 for line in flag_lines:
745 line = line.split('<')[1].split('>')[0].lower()
746 for flag in line.split(','):
747 flags.append(flag)
748 flags.sort()
749
750 # Convert from GHz/MHz string to Hz
751 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
752
753 # If advertised hz not found, use the actual hz
754 if hz_advertised == '0.0':
755 scale = 6
756 hz_advertised = _to_decimal_string(hz_actual)
757
758 info = {
759 'vendor_id_raw' : vendor_id,
760 'brand_raw' : processor_brand,
761
762 'stepping' : stepping,
763 'model' : model,
764 'family' : family,
765 'flags' : flags
766 }
767
768 if hz_advertised and hz_advertised != '0.0':
769 info['hz_advertised_friendly'] = _hz_short_to_friendly(hz_advertised, scale)
770 info['hz_actual_friendly'] = _hz_short_to_friendly(hz_actual, scale)
771
772 if hz_advertised and hz_advertised != '0.0':
773 info['hz_advertised'] = _hz_short_to_full(hz_advertised, scale)
774 info['hz_actual'] = _hz_short_to_full(hz_actual, scale)
775
776 return {k: v for k, v in info.items() if v}
777 except Exception as err:
778 g_trace.fail(err)
779 #raise
780
781 return {}
782
783 def _parse_arch(arch_string_raw):
784 import re
785
786 arch, bits = None, None
787 arch_string_raw = arch_string_raw.lower()
788
789 # X86
790 if re.match(r'^i\d86$|^x86$|^x86_32$|^i86pc$|^ia32$|^ia-32$|^bepc$', arch_string_raw):
791 arch = 'X86_32'
792 bits = 32
793 elif re.match(r'^x64$|^x86_64$|^x86_64t$|^i686-64$|^amd64$|^ia64$|^ia-64$', arch_string_raw):
794 arch = 'X86_64'
795 bits = 64
796 # ARM
797 elif re.match(r'^armv8-a|aarch64|arm64$', arch_string_raw):
798 arch = 'ARM_8'
799 bits = 64
800 elif re.match(r'^armv7$|^armv7[a-z]$|^armv7-[a-z]$|^armv6[a-z]$', arch_string_raw):
801 arch = 'ARM_7'
802 bits = 32
803 elif re.match(r'^armv8$|^armv8[a-z]$|^armv8-[a-z]$', arch_string_raw):
804 arch = 'ARM_8'
805 bits = 32
806 # PPC
807 elif re.match(r'^ppc32$|^prep$|^pmac$|^powermac$', arch_string_raw):
808 arch = 'PPC_32'
809 bits = 32
810 elif re.match(r'^powerpc$|^ppc64$|^ppc64le$', arch_string_raw):
811 arch = 'PPC_64'
812 bits = 64
813 # SPARC
814 elif re.match(r'^sparc32$|^sparc$', arch_string_raw):
815 arch = 'SPARC_32'
816 bits = 32
817 elif re.match(r'^sparc64$|^sun4u$|^sun4v$', arch_string_raw):
818 arch = 'SPARC_64'
819 bits = 64
820 # S390X
821 elif re.match(r'^s390x$', arch_string_raw):
822 arch = 'S390X'
823 bits = 64
824 # MIPS
825 elif re.match(r'^mips$', arch_string_raw):
826 arch = 'MIPS_32'
827 bits = 32
828 elif re.match(r'^mips64$', arch_string_raw):
829 arch = 'MIPS_64'
830 bits = 64
831 # RISCV
832 elif re.match(r'^riscv$|^riscv32$|^riscv32be$', arch_string_raw):
833 arch = 'RISCV_32'
834 bits = 32
835 elif re.match(r'^riscv64$|^riscv64be$', arch_string_raw):
836 arch = 'RISCV_64'
837 bits = 64
838 # LoongArch
839 elif re.match(r'^loongarch32$', arch_string_raw):
840 arch = 'LOONG_32'
841 bits = 32
842 elif re.match(r'^loongarch64$', arch_string_raw):
843 arch = 'LOONG_64'
844 bits = 64
845 # HPPA
846 elif re.match(r'^parisc$|^parisc64$', arch_string_raw):
847 if platform.architecture()[0].startswith("32"):
848 arch = 'HPPA_32'
849 bits = 32
850 else:
851 arch = 'HPPA_64'
852 bits = 64
853
854 return (arch, bits)
855
856 def _is_bit_set(reg, bit):
857 mask = 1 << bit
858 is_set = reg & mask > 0
859 return is_set
860
861
862 def _is_selinux_enforcing(trace):
863 # Just return if the SE Linux Status Tool is not installed
864 if not DataSource.has_sestatus():
865 trace.fail('Failed to find sestatus.')
866 return False
867
868 # Run the sestatus, and just return if it failed to run
869 returncode, output = DataSource.sestatus_b()
870 if returncode != 0:
871 trace.fail('Failed to run sestatus. Skipping ...')
872 return False
873
874 # Figure out if explicitly in enforcing mode
875 for line in output.splitlines():
876 line = line.strip().lower()
877 if line.startswith("current mode:"):
878 if line.endswith("enforcing"):
879 return True
880 else:
881 return False
882
883 # Figure out if we can execute heap and execute memory
884 can_selinux_exec_heap = False
885 can_selinux_exec_memory = False
886 for line in output.splitlines():
887 line = line.strip().lower()
888 if line.startswith("allow_execheap") and line.endswith("on"):
889 can_selinux_exec_heap = True
890 elif line.startswith("allow_execmem") and line.endswith("on"):
891 can_selinux_exec_memory = True
892
893 trace.command_output('can_selinux_exec_heap:', can_selinux_exec_heap)
894 trace.command_output('can_selinux_exec_memory:', can_selinux_exec_memory)
895
896 return (not can_selinux_exec_heap or not can_selinux_exec_memory)
897
898 def _filter_dict_keys_with_empty_values(info, acceptable_values = {}):
899 filtered_info = {}
900 for key in info:
901 value = info[key]
902
903 # Keep if value is acceptable
904 if key in acceptable_values:
905 if acceptable_values[key] == value:
906 filtered_info[key] = value
907 continue
908
909 # Filter out None, 0, "", (), {}, []
910 if not value:
911 continue
912
913 # Filter out (0, 0)
914 if value == (0, 0):
915 continue
916
917 # Filter out -1
918 if value == -1:
919 continue
920
921 # Filter out strings that start with "0.0"
922 if type(value) == str and value.startswith('0.0'):
923 continue
924
925 filtered_info[key] = value
926
927 return filtered_info
928
929 class ASM:
930 def __init__(self, restype=None, argtypes=(), machine_code=[]):
931 self.restype = restype
932 self.argtypes = argtypes
933 self.machine_code = machine_code
934 self.prochandle = None
935 self.mm = None
936 self.func = None
937 self.address = None
938 self.size = 0
939
940 def compile(self):
941 machine_code = bytes.join(b'', self.machine_code)
942 self.size = ctypes.c_size_t(len(machine_code))
943
944 if DataSource.is_windows:
945 # Allocate a memory segment the size of the machine code, and make it executable
946 size = len(machine_code)
947 # Alloc at least 1 page to ensure we own all pages that we want to change protection on
948 if size < 0x1000: size = 0x1000
949 MEM_COMMIT = ctypes.c_ulong(0x1000)
950 PAGE_READWRITE = ctypes.c_ulong(0x4)
951 pfnVirtualAlloc = ctypes.windll.kernel32.VirtualAlloc
952 pfnVirtualAlloc.restype = ctypes.c_void_p
953 self.address = pfnVirtualAlloc(None, ctypes.c_size_t(size), MEM_COMMIT, PAGE_READWRITE)
954 if not self.address:
955 raise Exception("Failed to VirtualAlloc")
956
957 # Copy the machine code into the memory segment
958 memmove = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t)(ctypes._memmove_addr)
959 if memmove(self.address, machine_code, size) < 0:
960 raise Exception("Failed to memmove")
961
962 # Enable execute permissions
963 PAGE_EXECUTE = ctypes.c_ulong(0x10)
964 old_protect = ctypes.c_ulong(0)
965 pfnVirtualProtect = ctypes.windll.kernel32.VirtualProtect
966 res = pfnVirtualProtect(ctypes.c_void_p(self.address), ctypes.c_size_t(size), PAGE_EXECUTE, ctypes.byref(old_protect))
967 if not res:
968 raise Exception("Failed VirtualProtect")
969
970 # Flush Instruction Cache
971 # First, get process Handle
972 if not self.prochandle:
973 pfnGetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
974 pfnGetCurrentProcess.restype = ctypes.c_void_p
975 self.prochandle = ctypes.c_void_p(pfnGetCurrentProcess())
976 # Actually flush cache
977 res = ctypes.windll.kernel32.FlushInstructionCache(self.prochandle, ctypes.c_void_p(self.address), ctypes.c_size_t(size))
978 if not res:
979 raise Exception("Failed FlushInstructionCache")
980 else:
981 from mmap import mmap, MAP_PRIVATE, MAP_ANONYMOUS, PROT_WRITE, PROT_READ, PROT_EXEC
982
983 # Allocate a private and executable memory segment the size of the machine code
984 machine_code = bytes.join(b'', self.machine_code)
985 self.size = len(machine_code)
986 self.mm = mmap(-1, self.size, flags=MAP_PRIVATE | MAP_ANONYMOUS, prot=PROT_WRITE | PROT_READ | PROT_EXEC)
987
988 # Copy the machine code into the memory segment
989 self.mm.write(machine_code)
990 self.address = ctypes.addressof(ctypes.c_int.from_buffer(self.mm))
991
992 # Cast the memory segment into a function
993 functype = ctypes.CFUNCTYPE(self.restype, *self.argtypes)
994 self.func = functype(self.address)
995
996 def run(self):
997 # Call the machine code like a function
998 retval = self.func()
999
1000 return retval
1001
1002 def free(self):
1003 # Free the function memory segment
1004 if DataSource.is_windows:
1005 MEM_RELEASE = ctypes.c_ulong(0x8000)
1006 ctypes.windll.kernel32.VirtualFree(ctypes.c_void_p(self.address), ctypes.c_size_t(0), MEM_RELEASE)
1007 else:
1008 self.mm.close()
1009
1010 self.prochandle = None
1011 self.mm = None
1012 self.func = None
1013 self.address = None
1014 self.size = 0
1015
1016
1017 class CPUID:
1018 def __init__(self, trace=None):
1019 if trace is None:
1020 trace = Trace(False, False)
1021
1022 # Figure out if SE Linux is on and in enforcing mode
1023 self.is_selinux_enforcing = _is_selinux_enforcing(trace)
1024
1025 def _asm_func(self, restype=None, argtypes=(), machine_code=[]):
1026 asm = ASM(restype, argtypes, machine_code)
1027 asm.compile()
1028 return asm
1029
1030 def _run_asm(self, *machine_code):
1031 asm = ASM(ctypes.c_uint32, (), machine_code)
1032 asm.compile()
1033 retval = asm.run()
1034 asm.free()
1035 return retval
1036
1037 # http://en.wikipedia.org/wiki/CPUID#EAX.3D0:_Get_vendor_ID
1038 def get_vendor_id(self):
1039 # EBX
1040 ebx = self._run_asm(
1041 b"\x31\xC0", # xor eax,eax
1042 b"\x0F\xA2" # cpuid
1043 b"\x89\xD8" # mov ax,bx
1044 b"\xC3" # ret
1045 )
1046
1047 # ECX
1048 ecx = self._run_asm(
1049 b"\x31\xC0", # xor eax,eax
1050 b"\x0f\xa2" # cpuid
1051 b"\x89\xC8" # mov ax,cx
1052 b"\xC3" # ret
1053 )
1054
1055 # EDX
1056 edx = self._run_asm(
1057 b"\x31\xC0", # xor eax,eax
1058 b"\x0f\xa2" # cpuid
1059 b"\x89\xD0" # mov ax,dx
1060 b"\xC3" # ret
1061 )
1062
1063 # Each 4bits is a ascii letter in the name
1064 vendor_id = []
1065 for reg in [ebx, edx, ecx]:
1066 for n in [0, 8, 16, 24]:
1067 vendor_id.append(chr((reg >> n) & 0xFF))
1068 vendor_id = ''.join(vendor_id)
1069
1070 return vendor_id
1071
1072 # http://en.wikipedia.org/wiki/CPUID#EAX.3D1:_Processor_Info_and_Feature_Bits
1073 def get_info(self):
1074 # EAX
1075 eax = self._run_asm(
1076 b"\xB8\x01\x00\x00\x00", # mov eax,0x1"
1077 b"\x0f\xa2" # cpuid
1078 b"\xC3" # ret
1079 )
1080
1081 # Get the CPU info
1082 stepping_id = (eax >> 0) & 0xF # 4 bits
1083 model = (eax >> 4) & 0xF # 4 bits
1084 family_id = (eax >> 8) & 0xF # 4 bits
1085 processor_type = (eax >> 12) & 0x3 # 2 bits
1086 extended_model_id = (eax >> 16) & 0xF # 4 bits
1087 extended_family_id = (eax >> 20) & 0xFF # 8 bits
1088 family = 0
1089
1090 if family_id in [15]:
1091 family = extended_family_id + family_id
1092 else:
1093 family = family_id
1094
1095 if family_id in [6, 15]:
1096 model = (extended_model_id << 4) + model
1097
1098 return {
1099 'stepping' : stepping_id,
1100 'model' : model,
1101 'family' : family,
1102 'processor_type' : processor_type
1103 }
1104
1105 # http://en.wikipedia.org/wiki/CPUID#EAX.3D80000000h:_Get_Highest_Extended_Function_Supported
1106 def get_max_extension_support(self):
1107 # Check for extension support
1108 max_extension_support = self._run_asm(
1109 b"\xB8\x00\x00\x00\x80" # mov ax,0x80000000
1110 b"\x0f\xa2" # cpuid
1111 b"\xC3" # ret
1112 )
1113
1114 return max_extension_support
1115
1116 # http://en.wikipedia.org/wiki/CPUID#EAX.3D1:_Processor_Info_and_Feature_Bits
1117 def get_flags(self, max_extension_support):
1118 # EDX
1119 edx = self._run_asm(
1120 b"\xB8\x01\x00\x00\x00", # mov eax,0x1"
1121 b"\x0f\xa2" # cpuid
1122 b"\x89\xD0" # mov ax,dx
1123 b"\xC3" # ret
1124 )
1125
1126 # ECX
1127 ecx = self._run_asm(
1128 b"\xB8\x01\x00\x00\x00", # mov eax,0x1"
1129 b"\x0f\xa2" # cpuid
1130 b"\x89\xC8" # mov ax,cx
1131 b"\xC3" # ret
1132 )
1133
1134 # Get the CPU flags
1135 flags = {
1136 'fpu' : _is_bit_set(edx, 0),
1137 'vme' : _is_bit_set(edx, 1),
1138 'de' : _is_bit_set(edx, 2),
1139 'pse' : _is_bit_set(edx, 3),
1140 'tsc' : _is_bit_set(edx, 4),
1141 'msr' : _is_bit_set(edx, 5),
1142 'pae' : _is_bit_set(edx, 6),
1143 'mce' : _is_bit_set(edx, 7),
1144 'cx8' : _is_bit_set(edx, 8),
1145 'apic' : _is_bit_set(edx, 9),
1146 #'reserved1' : _is_bit_set(edx, 10),
1147 'sep' : _is_bit_set(edx, 11),
1148 'mtrr' : _is_bit_set(edx, 12),
1149 'pge' : _is_bit_set(edx, 13),
1150 'mca' : _is_bit_set(edx, 14),
1151 'cmov' : _is_bit_set(edx, 15),
1152 'pat' : _is_bit_set(edx, 16),
1153 'pse36' : _is_bit_set(edx, 17),
1154 'pn' : _is_bit_set(edx, 18),
1155 'clflush' : _is_bit_set(edx, 19),
1156 #'reserved2' : _is_bit_set(edx, 20),
1157 'dts' : _is_bit_set(edx, 21),
1158 'acpi' : _is_bit_set(edx, 22),
1159 'mmx' : _is_bit_set(edx, 23),
1160 'fxsr' : _is_bit_set(edx, 24),
1161 'sse' : _is_bit_set(edx, 25),
1162 'sse2' : _is_bit_set(edx, 26),
1163 'ss' : _is_bit_set(edx, 27),
1164 'ht' : _is_bit_set(edx, 28),
1165 'tm' : _is_bit_set(edx, 29),
1166 'ia64' : _is_bit_set(edx, 30),
1167 'pbe' : _is_bit_set(edx, 31),
1168
1169 'pni' : _is_bit_set(ecx, 0),
1170 'pclmulqdq' : _is_bit_set(ecx, 1),
1171 'dtes64' : _is_bit_set(ecx, 2),
1172 'monitor' : _is_bit_set(ecx, 3),
1173 'ds_cpl' : _is_bit_set(ecx, 4),
1174 'vmx' : _is_bit_set(ecx, 5),
1175 'smx' : _is_bit_set(ecx, 6),
1176 'est' : _is_bit_set(ecx, 7),
1177 'tm2' : _is_bit_set(ecx, 8),
1178 'ssse3' : _is_bit_set(ecx, 9),
1179 'cid' : _is_bit_set(ecx, 10),
1180 #'reserved3' : _is_bit_set(ecx, 11),
1181 'fma' : _is_bit_set(ecx, 12),
1182 'cx16' : _is_bit_set(ecx, 13),
1183 'xtpr' : _is_bit_set(ecx, 14),
1184 'pdcm' : _is_bit_set(ecx, 15),
1185 #'reserved4' : _is_bit_set(ecx, 16),
1186 'pcid' : _is_bit_set(ecx, 17),
1187 'dca' : _is_bit_set(ecx, 18),
1188 'sse4_1' : _is_bit_set(ecx, 19),
1189 'sse4_2' : _is_bit_set(ecx, 20),
1190 'x2apic' : _is_bit_set(ecx, 21),
1191 'movbe' : _is_bit_set(ecx, 22),
1192 'popcnt' : _is_bit_set(ecx, 23),
1193 'tscdeadline' : _is_bit_set(ecx, 24),
1194 'aes' : _is_bit_set(ecx, 25),
1195 'xsave' : _is_bit_set(ecx, 26),
1196 'osxsave' : _is_bit_set(ecx, 27),
1197 'avx' : _is_bit_set(ecx, 28),
1198 'f16c' : _is_bit_set(ecx, 29),
1199 'rdrnd' : _is_bit_set(ecx, 30),
1200 'hypervisor' : _is_bit_set(ecx, 31)
1201 }
1202
1203 # Get a list of only the flags that are true
1204 flags = [k for k, v in flags.items() if v]
1205
1206 # http://en.wikipedia.org/wiki/CPUID#EAX.3D7.2C_ECX.3D0:_Extended_Features
1207 if max_extension_support >= 7:
1208 # EBX
1209 ebx = self._run_asm(
1210 b"\x31\xC9", # xor ecx,ecx
1211 b"\xB8\x07\x00\x00\x00" # mov eax,7
1212 b"\x0f\xa2" # cpuid
1213 b"\x89\xD8" # mov ax,bx
1214 b"\xC3" # ret
1215 )
1216
1217 # ECX
1218 ecx = self._run_asm(
1219 b"\x31\xC9", # xor ecx,ecx
1220 b"\xB8\x07\x00\x00\x00" # mov eax,7
1221 b"\x0f\xa2" # cpuid
1222 b"\x89\xC8" # mov ax,cx
1223 b"\xC3" # ret
1224 )
1225
1226 # Get the extended CPU flags
1227 extended_flags = {
1228 #'fsgsbase' : _is_bit_set(ebx, 0),
1229 #'IA32_TSC_ADJUST' : _is_bit_set(ebx, 1),
1230 'sgx' : _is_bit_set(ebx, 2),
1231 'bmi1' : _is_bit_set(ebx, 3),
1232 'hle' : _is_bit_set(ebx, 4),
1233 'avx2' : _is_bit_set(ebx, 5),
1234 #'reserved' : _is_bit_set(ebx, 6),
1235 'smep' : _is_bit_set(ebx, 7),
1236 'bmi2' : _is_bit_set(ebx, 8),
1237 'erms' : _is_bit_set(ebx, 9),
1238 'invpcid' : _is_bit_set(ebx, 10),
1239 'rtm' : _is_bit_set(ebx, 11),
1240 'pqm' : _is_bit_set(ebx, 12),
1241 #'FPU CS and FPU DS deprecated' : _is_bit_set(ebx, 13),
1242 'mpx' : _is_bit_set(ebx, 14),
1243 'pqe' : _is_bit_set(ebx, 15),
1244 'avx512f' : _is_bit_set(ebx, 16),
1245 'avx512dq' : _is_bit_set(ebx, 17),
1246 'rdseed' : _is_bit_set(ebx, 18),
1247 'adx' : _is_bit_set(ebx, 19),
1248 'smap' : _is_bit_set(ebx, 20),
1249 'avx512ifma' : _is_bit_set(ebx, 21),
1250 'pcommit' : _is_bit_set(ebx, 22),
1251 'clflushopt' : _is_bit_set(ebx, 23),
1252 'clwb' : _is_bit_set(ebx, 24),
1253 'intel_pt' : _is_bit_set(ebx, 25),
1254 'avx512pf' : _is_bit_set(ebx, 26),
1255 'avx512er' : _is_bit_set(ebx, 27),
1256 'avx512cd' : _is_bit_set(ebx, 28),
1257 'sha' : _is_bit_set(ebx, 29),
1258 'avx512bw' : _is_bit_set(ebx, 30),
1259 'avx512vl' : _is_bit_set(ebx, 31),
1260
1261 'prefetchwt1' : _is_bit_set(ecx, 0),
1262 'avx512vbmi' : _is_bit_set(ecx, 1),
1263 'umip' : _is_bit_set(ecx, 2),
1264 'pku' : _is_bit_set(ecx, 3),
1265 'ospke' : _is_bit_set(ecx, 4),
1266 #'reserved' : _is_bit_set(ecx, 5),
1267 'avx512vbmi2' : _is_bit_set(ecx, 6),
1268 #'reserved' : _is_bit_set(ecx, 7),
1269 'gfni' : _is_bit_set(ecx, 8),
1270 'vaes' : _is_bit_set(ecx, 9),
1271 'vpclmulqdq' : _is_bit_set(ecx, 10),
1272 'avx512vnni' : _is_bit_set(ecx, 11),
1273 'avx512bitalg' : _is_bit_set(ecx, 12),
1274 #'reserved' : _is_bit_set(ecx, 13),
1275 'avx512vpopcntdq' : _is_bit_set(ecx, 14),
1276 #'reserved' : _is_bit_set(ecx, 15),
1277 #'reserved' : _is_bit_set(ecx, 16),
1278 #'mpx0' : _is_bit_set(ecx, 17),
1279 #'mpx1' : _is_bit_set(ecx, 18),
1280 #'mpx2' : _is_bit_set(ecx, 19),
1281 #'mpx3' : _is_bit_set(ecx, 20),
1282 #'mpx4' : _is_bit_set(ecx, 21),
1283 'rdpid' : _is_bit_set(ecx, 22),
1284 #'reserved' : _is_bit_set(ecx, 23),
1285 #'reserved' : _is_bit_set(ecx, 24),
1286 #'reserved' : _is_bit_set(ecx, 25),
1287 #'reserved' : _is_bit_set(ecx, 26),
1288 #'reserved' : _is_bit_set(ecx, 27),
1289 #'reserved' : _is_bit_set(ecx, 28),
1290 #'reserved' : _is_bit_set(ecx, 29),
1291 'sgx_lc' : _is_bit_set(ecx, 30),
1292 #'reserved' : _is_bit_set(ecx, 31)
1293 }
1294
1295 # Get a list of only the flags that are true
1296 extended_flags = [k for k, v in extended_flags.items() if v]
1297 flags += extended_flags
1298
1299 # http://en.wikipedia.org/wiki/CPUID#EAX.3D80000001h:_Extended_Processor_Info_and_Feature_Bits
1300 if max_extension_support >= 0x80000001:
1301 # EBX
1302 ebx = self._run_asm(
1303 b"\xB8\x01\x00\x00\x80" # mov ax,0x80000001
1304 b"\x0f\xa2" # cpuid
1305 b"\x89\xD8" # mov ax,bx
1306 b"\xC3" # ret
1307 )
1308
1309 # ECX
1310 ecx = self._run_asm(
1311 b"\xB8\x01\x00\x00\x80" # mov ax,0x80000001
1312 b"\x0f\xa2" # cpuid
1313 b"\x89\xC8" # mov ax,cx
1314 b"\xC3" # ret
1315 )
1316
1317 # Get the extended CPU flags
1318 extended_flags = {
1319 'fpu' : _is_bit_set(ebx, 0),
1320 'vme' : _is_bit_set(ebx, 1),
1321 'de' : _is_bit_set(ebx, 2),
1322 'pse' : _is_bit_set(ebx, 3),
1323 'tsc' : _is_bit_set(ebx, 4),
1324 'msr' : _is_bit_set(ebx, 5),
1325 'pae' : _is_bit_set(ebx, 6),
1326 'mce' : _is_bit_set(ebx, 7),
1327 'cx8' : _is_bit_set(ebx, 8),
1328 'apic' : _is_bit_set(ebx, 9),
1329 #'reserved' : _is_bit_set(ebx, 10),
1330 'syscall' : _is_bit_set(ebx, 11),
1331 'mtrr' : _is_bit_set(ebx, 12),
1332 'pge' : _is_bit_set(ebx, 13),
1333 'mca' : _is_bit_set(ebx, 14),
1334 'cmov' : _is_bit_set(ebx, 15),
1335 'pat' : _is_bit_set(ebx, 16),
1336 'pse36' : _is_bit_set(ebx, 17),
1337 #'reserved' : _is_bit_set(ebx, 18),
1338 'mp' : _is_bit_set(ebx, 19),
1339 'nx' : _is_bit_set(ebx, 20),
1340 #'reserved' : _is_bit_set(ebx, 21),
1341 'mmxext' : _is_bit_set(ebx, 22),
1342 'mmx' : _is_bit_set(ebx, 23),
1343 'fxsr' : _is_bit_set(ebx, 24),
1344 'fxsr_opt' : _is_bit_set(ebx, 25),
1345 'pdpe1gp' : _is_bit_set(ebx, 26),
1346 'rdtscp' : _is_bit_set(ebx, 27),
1347 #'reserved' : _is_bit_set(ebx, 28),
1348 'lm' : _is_bit_set(ebx, 29),
1349 '3dnowext' : _is_bit_set(ebx, 30),
1350 '3dnow' : _is_bit_set(ebx, 31),
1351
1352 'lahf_lm' : _is_bit_set(ecx, 0),
1353 'cmp_legacy' : _is_bit_set(ecx, 1),
1354 'svm' : _is_bit_set(ecx, 2),
1355 'extapic' : _is_bit_set(ecx, 3),
1356 'cr8_legacy' : _is_bit_set(ecx, 4),
1357 'abm' : _is_bit_set(ecx, 5),
1358 'sse4a' : _is_bit_set(ecx, 6),
1359 'misalignsse' : _is_bit_set(ecx, 7),
1360 '3dnowprefetch' : _is_bit_set(ecx, 8),
1361 'osvw' : _is_bit_set(ecx, 9),
1362 'ibs' : _is_bit_set(ecx, 10),
1363 'xop' : _is_bit_set(ecx, 11),
1364 'skinit' : _is_bit_set(ecx, 12),
1365 'wdt' : _is_bit_set(ecx, 13),
1366 #'reserved' : _is_bit_set(ecx, 14),
1367 'lwp' : _is_bit_set(ecx, 15),
1368 'fma4' : _is_bit_set(ecx, 16),
1369 'tce' : _is_bit_set(ecx, 17),
1370 #'reserved' : _is_bit_set(ecx, 18),
1371 'nodeid_msr' : _is_bit_set(ecx, 19),
1372 #'reserved' : _is_bit_set(ecx, 20),
1373 'tbm' : _is_bit_set(ecx, 21),
1374 'topoext' : _is_bit_set(ecx, 22),
1375 'perfctr_core' : _is_bit_set(ecx, 23),
1376 'perfctr_nb' : _is_bit_set(ecx, 24),
1377 #'reserved' : _is_bit_set(ecx, 25),
1378 'dbx' : _is_bit_set(ecx, 26),
1379 'perftsc' : _is_bit_set(ecx, 27),
1380 'pci_l2i' : _is_bit_set(ecx, 28),
1381 #'reserved' : _is_bit_set(ecx, 29),
1382 #'reserved' : _is_bit_set(ecx, 30),
1383 #'reserved' : _is_bit_set(ecx, 31)
1384 }
1385
1386 # Get a list of only the flags that are true
1387 extended_flags = [k for k, v in extended_flags.items() if v]
1388 flags += extended_flags
1389
1390 flags.sort()
1391 return flags
1392
1393 # http://en.wikipedia.org/wiki/CPUID#EAX.3D80000002h.2C80000003h.2C80000004h:_Processor_Brand_String
1394 def get_processor_brand(self, max_extension_support):
1395 processor_brand = ""
1396
1397 # Processor brand string
1398 if max_extension_support >= 0x80000004:
1399 instructions = [
1400 b"\xB8\x02\x00\x00\x80", # mov ax,0x80000002
1401 b"\xB8\x03\x00\x00\x80", # mov ax,0x80000003
1402 b"\xB8\x04\x00\x00\x80" # mov ax,0x80000004
1403 ]
1404 for instruction in instructions:
1405 # EAX
1406 eax = self._run_asm(
1407 instruction, # mov ax,0x8000000?
1408 b"\x0f\xa2" # cpuid
1409 b"\x89\xC0" # mov ax,ax
1410 b"\xC3" # ret
1411 )
1412
1413 # EBX
1414 ebx = self._run_asm(
1415 instruction, # mov ax,0x8000000?
1416 b"\x0f\xa2" # cpuid
1417 b"\x89\xD8" # mov ax,bx
1418 b"\xC3" # ret
1419 )
1420
1421 # ECX
1422 ecx = self._run_asm(
1423 instruction, # mov ax,0x8000000?
1424 b"\x0f\xa2" # cpuid
1425 b"\x89\xC8" # mov ax,cx
1426 b"\xC3" # ret
1427 )
1428
1429 # EDX
1430 edx = self._run_asm(
1431 instruction, # mov ax,0x8000000?
1432 b"\x0f\xa2" # cpuid
1433 b"\x89\xD0" # mov ax,dx
1434 b"\xC3" # ret
1435 )
1436
1437 # Combine each of the 4 bytes in each register into the string
1438 for reg in [eax, ebx, ecx, edx]:
1439 for n in [0, 8, 16, 24]:
1440 processor_brand += chr((reg >> n) & 0xFF)
1441
1442 # Strip off any trailing NULL terminators and white space
1443 processor_brand = processor_brand.strip("\0").strip()
1444
1445 return processor_brand
1446
1447 # http://en.wikipedia.org/wiki/CPUID#EAX.3D80000006h:_Extended_L2_Cache_Features
1448 def get_cache(self, max_extension_support):
1449 cache_info = {}
1450
1451 # Just return if the cache feature is not supported
1452 if max_extension_support < 0x80000006:
1453 return cache_info
1454
1455 # ECX
1456 ecx = self._run_asm(
1457 b"\xB8\x06\x00\x00\x80" # mov ax,0x80000006
1458 b"\x0f\xa2" # cpuid
1459 b"\x89\xC8" # mov ax,cx
1460 b"\xC3" # ret
1461 )
1462
1463 cache_info = {
1464 'size_b' : (ecx & 0xFF) * 1024,
1465 'associativity' : (ecx >> 12) & 0xF,
1466 'line_size_b' : (ecx >> 16) & 0xFFFF
1467 }
1468
1469 return cache_info
1470
1471 def get_ticks_func(self):
1472 retval = None
1473
1474 if DataSource.bits == '32bit':
1475 # Works on x86_32
1476 restype = None
1477 argtypes = (ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint))
1478 get_ticks_x86_32 = self._asm_func(restype, argtypes,
1479 [
1480 b"\x55", # push bp
1481 b"\x89\xE5", # mov bp,sp
1482 b"\x31\xC0", # xor ax,ax
1483 b"\x0F\xA2", # cpuid
1484 b"\x0F\x31", # rdtsc
1485 b"\x8B\x5D\x08", # mov bx,[di+0x8]
1486 b"\x8B\x4D\x0C", # mov cx,[di+0xc]
1487 b"\x89\x13", # mov [bp+di],dx
1488 b"\x89\x01", # mov [bx+di],ax
1489 b"\x5D", # pop bp
1490 b"\xC3" # ret
1491 ]
1492 )
1493
1494 # Monkey patch func to combine high and low args into one return
1495 old_func = get_ticks_x86_32.func
1496 def new_func():
1497 # Pass two uint32s into function
1498 high = ctypes.c_uint32(0)
1499 low = ctypes.c_uint32(0)
1500 old_func(ctypes.byref(high), ctypes.byref(low))
1501
1502 # Shift the two uint32s into one uint64
1503 retval = ((high.value << 32) & 0xFFFFFFFF00000000) | low.value
1504 return retval
1505 get_ticks_x86_32.func = new_func
1506
1507 retval = get_ticks_x86_32
1508 elif DataSource.bits == '64bit':
1509 # Works on x86_64
1510 restype = ctypes.c_uint64
1511 argtypes = ()
1512 get_ticks_x86_64 = self._asm_func(restype, argtypes,
1513 [
1514 b"\x48", # dec ax
1515 b"\x31\xC0", # xor ax,ax
1516 b"\x0F\xA2", # cpuid
1517 b"\x0F\x31", # rdtsc
1518 b"\x48", # dec ax
1519 b"\xC1\xE2\x20", # shl dx,byte 0x20
1520 b"\x48", # dec ax
1521 b"\x09\xD0", # or ax,dx
1522 b"\xC3", # ret
1523 ]
1524 )
1525
1526 retval = get_ticks_x86_64
1527 return retval
1528
1529 def get_raw_hz(self):
1530 from time import sleep
1531
1532 ticks_fn = self.get_ticks_func()
1533
1534 start = ticks_fn.func()
1535 sleep(1)
1536 end = ticks_fn.func()
1537
1538 ticks = (end - start)
1539 ticks_fn.free()
1540
1541 return ticks
1542
1543 def _get_cpu_info_from_cpuid_actual():
1544 '''
1545 Warning! This function has the potential to crash the Python runtime.
1546 Do not call it directly. Use the _get_cpu_info_from_cpuid function instead.
1547 It will safely call this function in another process.
1548 '''
1549
1550 from io import StringIO
1551
1552 trace = Trace(True, True)
1553 info = {}
1554
1555 # Pipe stdout and stderr to strings
1556 sys.stdout = trace._stdout
1557 sys.stderr = trace._stderr
1558
1559 try:
1560 # Get the CPU arch and bits
1561 arch, bits = _parse_arch(DataSource.arch_string_raw)
1562
1563 # Return none if this is not an X86 CPU
1564 if not arch in ['X86_32', 'X86_64']:
1565 trace.fail('Not running on X86_32 or X86_64. Skipping ...')
1566 return trace.to_dict(info, True)
1567
1568 # Return none if SE Linux is in enforcing mode
1569 cpuid = CPUID(trace)
1570 if cpuid.is_selinux_enforcing:
1571 trace.fail('SELinux is enforcing. Skipping ...')
1572 return trace.to_dict(info, True)
1573
1574 # Get the cpu info from the CPUID register
1575 max_extension_support = cpuid.get_max_extension_support()
1576 cache_info = cpuid.get_cache(max_extension_support)
1577 info = cpuid.get_info()
1578
1579 processor_brand = cpuid.get_processor_brand(max_extension_support)
1580
1581 # Get the Hz and scale
1582 hz_actual = cpuid.get_raw_hz()
1583 hz_actual = _to_decimal_string(hz_actual)
1584
1585 # Get the Hz and scale
1586 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
1587 info = {
1588 'vendor_id_raw' : cpuid.get_vendor_id(),
1589 'hardware_raw' : '',
1590 'brand_raw' : processor_brand,
1591
1592 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
1593 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
1594 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
1595 'hz_actual' : _hz_short_to_full(hz_actual, 0),
1596
1597 'l2_cache_size' : cache_info['size_b'],
1598 'l2_cache_line_size' : cache_info['line_size_b'],
1599 'l2_cache_associativity' : cache_info['associativity'],
1600
1601 'stepping' : info['stepping'],
1602 'model' : info['model'],
1603 'family' : info['family'],
1604 'processor_type' : info['processor_type'],
1605 'flags' : cpuid.get_flags(max_extension_support)
1606 }
1607
1608 info = _filter_dict_keys_with_empty_values(info)
1609 trace.success()
1610 except Exception as err:
1611 from traceback import format_exc
1612 err_string = format_exc()
1613 trace._err = ''.join(['\t\t{0}\n'.format(n) for n in err_string.split('\n')]) + '\n'
1614 return trace.to_dict(info, True)
1615
1616 return trace.to_dict(info, False)
1617
1618 def _get_cpu_info_from_cpuid_subprocess_wrapper(queue):
1619 orig_stdout = sys.stdout
1620 orig_stderr = sys.stderr
1621
1622 output = _get_cpu_info_from_cpuid_actual()
1623
1624 sys.stdout = orig_stdout
1625 sys.stderr = orig_stderr
1626
1627 queue.put(_obj_to_b64(output))
1628
1629 def _get_cpu_info_from_cpuid():
1630 '''
1631 Returns the CPU info gathered by querying the X86 cpuid register in a new process.
1632 Returns {} on non X86 cpus.
1633 Returns {} if SELinux is in enforcing mode.
1634 '''
1635
1636 g_trace.header('Tying to get info from CPUID ...')
1637
1638 from multiprocessing import Process, Queue
1639
1640 # Return {} if can't cpuid
1641 if not DataSource.can_cpuid:
1642 g_trace.fail('Can\'t CPUID. Skipping ...')
1643 return {}
1644
1645 # Get the CPU arch and bits
1646 arch, bits = _parse_arch(DataSource.arch_string_raw)
1647
1648 # Return {} if this is not an X86 CPU
1649 if not arch in ['X86_32', 'X86_64']:
1650 g_trace.fail('Not running on X86_32 or X86_64. Skipping ...')
1651 return {}
1652
1653 try:
1654 if CAN_CALL_CPUID_IN_SUBPROCESS:
1655 # Start running the function in a subprocess
1656 queue = Queue()
1657 p = Process(target=_get_cpu_info_from_cpuid_subprocess_wrapper, args=(queue,))
1658 p.start()
1659
1660 # Wait for the process to end, while it is still alive
1661 while p.is_alive():
1662 p.join(0)
1663
1664 # Return {} if it failed
1665 if p.exitcode != 0:
1666 g_trace.fail('Failed to run CPUID in process. Skipping ...')
1667 return {}
1668
1669 # Return {} if no results
1670 if queue.empty():
1671 g_trace.fail('Failed to get anything from CPUID process. Skipping ...')
1672 return {}
1673 # Return the result, only if there is something to read
1674 else:
1675 output = _b64_to_obj(queue.get())
1676 import pprint
1677 pp = pprint.PrettyPrinter(indent=4)
1678 #pp.pprint(output)
1679
1680 if 'output' in output and output['output']:
1681 g_trace.write(output['output'])
1682
1683 if 'stdout' in output and output['stdout']:
1684 sys.stdout.write('{0}\n'.format(output['stdout']))
1685 sys.stdout.flush()
1686
1687 if 'stderr' in output and output['stderr']:
1688 sys.stderr.write('{0}\n'.format(output['stderr']))
1689 sys.stderr.flush()
1690
1691 if 'is_fail' not in output:
1692 g_trace.fail('Failed to get is_fail from CPUID process. Skipping ...')
1693 return {}
1694
1695 # Fail if there was an exception
1696 if 'err' in output and output['err']:
1697 g_trace.fail('Failed to run CPUID in process. Skipping ...')
1698 g_trace.write(output['err'])
1699 g_trace.write('Failed ...')
1700 return {}
1701
1702 if 'is_fail' in output and output['is_fail']:
1703 g_trace.write('Failed ...')
1704 return {}
1705
1706 if 'info' not in output or not output['info']:
1707 g_trace.fail('Failed to get return info from CPUID process. Skipping ...')
1708 return {}
1709
1710 return output['info']
1711 else:
1712 # FIXME: This should write the values like in the above call to actual
1713 orig_stdout = sys.stdout
1714 orig_stderr = sys.stderr
1715
1716 output = _get_cpu_info_from_cpuid_actual()
1717
1718 sys.stdout = orig_stdout
1719 sys.stderr = orig_stderr
1720
1721 g_trace.success()
1722 return output['info']
1723 except Exception as err:
1724 g_trace.fail(err)
1725
1726 # Return {} if everything failed
1727 return {}
1728
1729 def _get_cpu_info_from_proc_cpuinfo():
1730 '''
1731 Returns the CPU info gathered from /proc/cpuinfo.
1732 Returns {} if /proc/cpuinfo is not found.
1733 '''
1734
1735 g_trace.header('Tying to get info from /proc/cpuinfo ...')
1736
1737 try:
1738 # Just return {} if there is no cpuinfo
1739 if not DataSource.has_proc_cpuinfo():
1740 g_trace.fail('Failed to find /proc/cpuinfo. Skipping ...')
1741 return {}
1742
1743 returncode, output = DataSource.cat_proc_cpuinfo()
1744 if returncode != 0:
1745 g_trace.fail('Failed to run cat /proc/cpuinfo. Skipping ...')
1746 return {}
1747
1748 # Various fields
1749 vendor_id = _get_field(False, output, None, '', 'vendor_id', 'vendor id', 'vendor')
1750 processor_brand = _get_field(True, output, None, None, 'model name', 'cpu', 'processor', 'uarch')
1751 cache_size = _get_field(False, output, None, '', 'cache size')
1752 stepping = _get_field(False, output, int, -1, 'stepping')
1753 model = _get_field(False, output, int, -1, 'model')
1754 family = _get_field(False, output, int, -1, 'cpu family')
1755 hardware = _get_field(False, output, None, '', 'Hardware')
1756
1757 # Flags
1758 flags = _get_field(False, output, None, None, 'flags', 'Features', 'ASEs implemented')
1759 if flags:
1760 flags = flags.split()
1761 flags.sort()
1762
1763 # Check for other cache format
1764 if not cache_size:
1765 try:
1766 for i in range(0, 10):
1767 name = "cache{0}".format(i)
1768 value = _get_field(False, output, None, None, name)
1769 if value:
1770 value = [entry.split('=') for entry in value.split(' ')]
1771 value = dict(value)
1772 if 'level' in value and value['level'] == '3' and 'size' in value:
1773 cache_size = value['size']
1774 break
1775 except Exception:
1776 pass
1777
1778 # Convert from MHz string to Hz
1779 hz_actual = _get_field(False, output, None, '', 'cpu MHz', 'cpu speed', 'clock', 'cpu MHz dynamic', 'cpu MHz static')
1780 hz_actual = hz_actual.lower().rstrip('mhz').strip()
1781 hz_actual = _to_decimal_string(hz_actual)
1782
1783 # Convert from GHz/MHz string to Hz
1784 hz_advertised, scale = (None, 0)
1785 try:
1786 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
1787 except Exception:
1788 pass
1789
1790 info = {
1791 'hardware_raw' : hardware,
1792 'brand_raw' : processor_brand,
1793
1794 'l3_cache_size' : _friendly_bytes_to_int(cache_size),
1795 'flags' : flags,
1796 'vendor_id_raw' : vendor_id,
1797 'stepping' : stepping,
1798 'model' : model,
1799 'family' : family,
1800 }
1801
1802 # Make the Hz the same for actual and advertised if missing any
1803 if not hz_advertised or hz_advertised == '0.0':
1804 hz_advertised = hz_actual
1805 scale = 6
1806 elif not hz_actual or hz_actual == '0.0':
1807 hz_actual = hz_advertised
1808
1809 # Add the Hz if there is one
1810 if _hz_short_to_full(hz_advertised, scale) > (0, 0):
1811 info['hz_advertised_friendly'] = _hz_short_to_friendly(hz_advertised, scale)
1812 info['hz_advertised'] = _hz_short_to_full(hz_advertised, scale)
1813 if _hz_short_to_full(hz_actual, scale) > (0, 0):
1814 info['hz_actual_friendly'] = _hz_short_to_friendly(hz_actual, 6)
1815 info['hz_actual'] = _hz_short_to_full(hz_actual, 6)
1816
1817 info = _filter_dict_keys_with_empty_values(info, {'stepping':0, 'model':0, 'family':0})
1818 g_trace.success()
1819 return info
1820 except Exception as err:
1821 g_trace.fail(err)
1822 #raise # NOTE: To have this throw on error, uncomment this line
1823 return {}
1824
1825 def _get_cpu_info_from_cpufreq_info():
1826 '''
1827 Returns the CPU info gathered from cpufreq-info.
1828 Returns {} if cpufreq-info is not found.
1829 '''
1830
1831 g_trace.header('Tying to get info from cpufreq-info ...')
1832
1833 try:
1834 hz_brand, scale = '0.0', 0
1835
1836 if not DataSource.has_cpufreq_info():
1837 g_trace.fail('Failed to find cpufreq-info. Skipping ...')
1838 return {}
1839
1840 returncode, output = DataSource.cpufreq_info()
1841 if returncode != 0:
1842 g_trace.fail('Failed to run cpufreq-info. Skipping ...')
1843 return {}
1844
1845 hz_brand = output.split('current CPU frequency is')[1].split('\n')[0]
1846 i = hz_brand.find('Hz')
1847 assert(i != -1)
1848 hz_brand = hz_brand[0 : i+2].strip().lower()
1849
1850 if hz_brand.endswith('mhz'):
1851 scale = 6
1852 elif hz_brand.endswith('ghz'):
1853 scale = 9
1854 hz_brand = hz_brand.rstrip('mhz').rstrip('ghz').strip()
1855 hz_brand = _to_decimal_string(hz_brand)
1856
1857 info = {
1858 'hz_advertised_friendly' : _hz_short_to_friendly(hz_brand, scale),
1859 'hz_actual_friendly' : _hz_short_to_friendly(hz_brand, scale),
1860 'hz_advertised' : _hz_short_to_full(hz_brand, scale),
1861 'hz_actual' : _hz_short_to_full(hz_brand, scale),
1862 }
1863
1864 info = _filter_dict_keys_with_empty_values(info)
1865 g_trace.success()
1866 return info
1867 except Exception as err:
1868 g_trace.fail(err)
1869 #raise # NOTE: To have this throw on error, uncomment this line
1870 return {}
1871
1872 def _get_cpu_info_from_lscpu():
1873 '''
1874 Returns the CPU info gathered from lscpu.
1875 Returns {} if lscpu is not found.
1876 '''
1877
1878 g_trace.header('Tying to get info from lscpu ...')
1879
1880 try:
1881 if not DataSource.has_lscpu():
1882 g_trace.fail('Failed to find lscpu. Skipping ...')
1883 return {}
1884
1885 returncode, output = DataSource.lscpu()
1886 if returncode != 0:
1887 g_trace.fail('Failed to run lscpu. Skipping ...')
1888 return {}
1889
1890 info = {}
1891
1892 new_hz = _get_field(False, output, None, None, 'CPU max MHz', 'CPU MHz')
1893 if new_hz:
1894 new_hz = _to_decimal_string(new_hz)
1895 scale = 6
1896 info['hz_advertised_friendly'] = _hz_short_to_friendly(new_hz, scale)
1897 info['hz_actual_friendly'] = _hz_short_to_friendly(new_hz, scale)
1898 info['hz_advertised'] = _hz_short_to_full(new_hz, scale)
1899 info['hz_actual'] = _hz_short_to_full(new_hz, scale)
1900
1901 new_hz = _get_field(False, output, None, None, 'CPU dynamic MHz', 'CPU static MHz')
1902 if new_hz:
1903 new_hz = _to_decimal_string(new_hz)
1904 scale = 6
1905 info['hz_advertised_friendly'] = _hz_short_to_friendly(new_hz, scale)
1906 info['hz_actual_friendly'] = _hz_short_to_friendly(new_hz, scale)
1907 info['hz_advertised'] = _hz_short_to_full(new_hz, scale)
1908 info['hz_actual'] = _hz_short_to_full(new_hz, scale)
1909
1910 vendor_id = _get_field(False, output, None, None, 'Vendor ID')
1911 if vendor_id:
1912 info['vendor_id_raw'] = vendor_id
1913
1914 brand = _get_field(False, output, None, None, 'Model name')
1915 if brand:
1916 info['brand_raw'] = brand
1917 else:
1918 brand = _get_field(False, output, None, None, 'Model')
1919 if brand and not brand.isdigit():
1920 info['brand_raw'] = brand
1921
1922 family = _get_field(False, output, None, None, 'CPU family')
1923 if family and family.isdigit():
1924 info['family'] = int(family)
1925
1926 stepping = _get_field(False, output, None, None, 'Stepping')
1927 if stepping and stepping.isdigit():
1928 info['stepping'] = int(stepping)
1929
1930 model = _get_field(False, output, None, None, 'Model')
1931 if model and model.isdigit():
1932 info['model'] = int(model)
1933
1934 l1_data_cache_size = _get_field(False, output, None, None, 'L1d cache')
1935 if l1_data_cache_size:
1936 l1_data_cache_size = l1_data_cache_size.split('(')[0].strip()
1937 info['l1_data_cache_size'] = _friendly_bytes_to_int(l1_data_cache_size)
1938
1939 l1_instruction_cache_size = _get_field(False, output, None, None, 'L1i cache')
1940 if l1_instruction_cache_size:
1941 l1_instruction_cache_size = l1_instruction_cache_size.split('(')[0].strip()
1942 info['l1_instruction_cache_size'] = _friendly_bytes_to_int(l1_instruction_cache_size)
1943
1944 l2_cache_size = _get_field(False, output, None, None, 'L2 cache', 'L2d cache')
1945 if l2_cache_size:
1946 l2_cache_size = l2_cache_size.split('(')[0].strip()
1947 info['l2_cache_size'] = _friendly_bytes_to_int(l2_cache_size)
1948
1949 l3_cache_size = _get_field(False, output, None, None, 'L3 cache')
1950 if l3_cache_size:
1951 l3_cache_size = l3_cache_size.split('(')[0].strip()
1952 info['l3_cache_size'] = _friendly_bytes_to_int(l3_cache_size)
1953
1954 # Flags
1955 flags = _get_field(False, output, None, None, 'flags', 'Features', 'ASEs implemented')
1956 if flags:
1957 flags = flags.split()
1958 flags.sort()
1959 info['flags'] = flags
1960
1961 info = _filter_dict_keys_with_empty_values(info, {'stepping':0, 'model':0, 'family':0})
1962 g_trace.success()
1963 return info
1964 except Exception as err:
1965 g_trace.fail(err)
1966 #raise # NOTE: To have this throw on error, uncomment this line
1967 return {}
1968
1969 def _get_cpu_info_from_dmesg():
1970 '''
1971 Returns the CPU info gathered from dmesg.
1972 Returns {} if dmesg is not found or does not have the desired info.
1973 '''
1974
1975 g_trace.header('Tying to get info from the dmesg ...')
1976
1977 # Just return {} if this arch has an unreliable dmesg log
1978 arch, bits = _parse_arch(DataSource.arch_string_raw)
1979 if arch in ['S390X']:
1980 g_trace.fail('Running on S390X. Skipping ...')
1981 return {}
1982
1983 # Just return {} if there is no dmesg
1984 if not DataSource.has_dmesg():
1985 g_trace.fail('Failed to find dmesg. Skipping ...')
1986 return {}
1987
1988 # If dmesg fails return {}
1989 returncode, output = DataSource.dmesg_a()
1990 if output is None or returncode != 0:
1991 g_trace.fail('Failed to run \"dmesg -a\". Skipping ...')
1992 return {}
1993
1994 info = _parse_dmesg_output(output)
1995 g_trace.success()
1996 return info
1997
1998
1999 # https://openpowerfoundation.org/wp-content/uploads/2016/05/LoPAPR_DRAFT_v11_24March2016_cmt1.pdf
2000 # page 767
2001 def _get_cpu_info_from_ibm_pa_features():
2002 '''
2003 Returns the CPU info gathered from lsprop /proc/device-tree/cpus/*/ibm,pa-features
2004 Returns {} if lsprop is not found or ibm,pa-features does not have the desired info.
2005 '''
2006
2007 g_trace.header('Tying to get info from lsprop ...')
2008
2009 try:
2010 # Just return {} if there is no lsprop
2011 if not DataSource.has_ibm_pa_features():
2012 g_trace.fail('Failed to find lsprop. Skipping ...')
2013 return {}
2014
2015 # If ibm,pa-features fails return {}
2016 returncode, output = DataSource.ibm_pa_features()
2017 if output is None or returncode != 0:
2018 g_trace.fail('Failed to glob /proc/device-tree/cpus/*/ibm,pa-features. Skipping ...')
2019 return {}
2020
2021 # Filter out invalid characters from output
2022 value = output.split("ibm,pa-features")[1].lower()
2023 value = [s for s in value if s in list('0123456789abcfed')]
2024 value = ''.join(value)
2025
2026 # Get data converted to Uint32 chunks
2027 left = int(value[0 : 8], 16)
2028 right = int(value[8 : 16], 16)
2029
2030 # Get the CPU flags
2031 flags = {
2032 # Byte 0
2033 'mmu' : _is_bit_set(left, 0),
2034 'fpu' : _is_bit_set(left, 1),
2035 'slb' : _is_bit_set(left, 2),
2036 'run' : _is_bit_set(left, 3),
2037 #'reserved' : _is_bit_set(left, 4),
2038 'dabr' : _is_bit_set(left, 5),
2039 'ne' : _is_bit_set(left, 6),
2040 'wtr' : _is_bit_set(left, 7),
2041
2042 # Byte 1
2043 'mcr' : _is_bit_set(left, 8),
2044 'dsisr' : _is_bit_set(left, 9),
2045 'lp' : _is_bit_set(left, 10),
2046 'ri' : _is_bit_set(left, 11),
2047 'dabrx' : _is_bit_set(left, 12),
2048 'sprg3' : _is_bit_set(left, 13),
2049 'rislb' : _is_bit_set(left, 14),
2050 'pp' : _is_bit_set(left, 15),
2051
2052 # Byte 2
2053 'vpm' : _is_bit_set(left, 16),
2054 'dss_2.05' : _is_bit_set(left, 17),
2055 #'reserved' : _is_bit_set(left, 18),
2056 'dar' : _is_bit_set(left, 19),
2057 #'reserved' : _is_bit_set(left, 20),
2058 'ppr' : _is_bit_set(left, 21),
2059 'dss_2.02' : _is_bit_set(left, 22),
2060 'dss_2.06' : _is_bit_set(left, 23),
2061
2062 # Byte 3
2063 'lsd_in_dscr' : _is_bit_set(left, 24),
2064 'ugr_in_dscr' : _is_bit_set(left, 25),
2065 #'reserved' : _is_bit_set(left, 26),
2066 #'reserved' : _is_bit_set(left, 27),
2067 #'reserved' : _is_bit_set(left, 28),
2068 #'reserved' : _is_bit_set(left, 29),
2069 #'reserved' : _is_bit_set(left, 30),
2070 #'reserved' : _is_bit_set(left, 31),
2071
2072 # Byte 4
2073 'sso_2.06' : _is_bit_set(right, 0),
2074 #'reserved' : _is_bit_set(right, 1),
2075 #'reserved' : _is_bit_set(right, 2),
2076 #'reserved' : _is_bit_set(right, 3),
2077 #'reserved' : _is_bit_set(right, 4),
2078 #'reserved' : _is_bit_set(right, 5),
2079 #'reserved' : _is_bit_set(right, 6),
2080 #'reserved' : _is_bit_set(right, 7),
2081
2082 # Byte 5
2083 'le' : _is_bit_set(right, 8),
2084 'cfar' : _is_bit_set(right, 9),
2085 'eb' : _is_bit_set(right, 10),
2086 'lsq_2.07' : _is_bit_set(right, 11),
2087 #'reserved' : _is_bit_set(right, 12),
2088 #'reserved' : _is_bit_set(right, 13),
2089 #'reserved' : _is_bit_set(right, 14),
2090 #'reserved' : _is_bit_set(right, 15),
2091
2092 # Byte 6
2093 'dss_2.07' : _is_bit_set(right, 16),
2094 #'reserved' : _is_bit_set(right, 17),
2095 #'reserved' : _is_bit_set(right, 18),
2096 #'reserved' : _is_bit_set(right, 19),
2097 #'reserved' : _is_bit_set(right, 20),
2098 #'reserved' : _is_bit_set(right, 21),
2099 #'reserved' : _is_bit_set(right, 22),
2100 #'reserved' : _is_bit_set(right, 23),
2101
2102 # Byte 7
2103 #'reserved' : _is_bit_set(right, 24),
2104 #'reserved' : _is_bit_set(right, 25),
2105 #'reserved' : _is_bit_set(right, 26),
2106 #'reserved' : _is_bit_set(right, 27),
2107 #'reserved' : _is_bit_set(right, 28),
2108 #'reserved' : _is_bit_set(right, 29),
2109 #'reserved' : _is_bit_set(right, 30),
2110 #'reserved' : _is_bit_set(right, 31),
2111 }
2112
2113 # Get a list of only the flags that are true
2114 flags = [k for k, v in flags.items() if v]
2115 flags.sort()
2116
2117 info = {
2118 'flags' : flags
2119 }
2120 info = _filter_dict_keys_with_empty_values(info)
2121 g_trace.success()
2122 return info
2123 except Exception as err:
2124 g_trace.fail(err)
2125 return {}
2126
2127
2128 def _get_cpu_info_from_cat_var_run_dmesg_boot():
2129 '''
2130 Returns the CPU info gathered from /var/run/dmesg.boot.
2131 Returns {} if dmesg is not found or does not have the desired info.
2132 '''
2133
2134 g_trace.header('Tying to get info from the /var/run/dmesg.boot log ...')
2135
2136 # Just return {} if there is no /var/run/dmesg.boot
2137 if not DataSource.has_var_run_dmesg_boot():
2138 g_trace.fail('Failed to find /var/run/dmesg.boot file. Skipping ...')
2139 return {}
2140
2141 # If dmesg.boot fails return {}
2142 returncode, output = DataSource.cat_var_run_dmesg_boot()
2143 if output is None or returncode != 0:
2144 g_trace.fail('Failed to run \"cat /var/run/dmesg.boot\". Skipping ...')
2145 return {}
2146
2147 info = _parse_dmesg_output(output)
2148 g_trace.success()
2149 return info
2150
2151
2152 def _get_cpu_info_from_sysctl():
2153 '''
2154 Returns the CPU info gathered from sysctl.
2155 Returns {} if sysctl is not found.
2156 '''
2157
2158 g_trace.header('Tying to get info from sysctl ...')
2159
2160 try:
2161 # Just return {} if there is no sysctl
2162 if not DataSource.has_sysctl():
2163 g_trace.fail('Failed to find sysctl. Skipping ...')
2164 return {}
2165
2166 # If sysctl fails return {}
2167 returncode, output = DataSource.sysctl_machdep_cpu_hw_cpufrequency()
2168 if output is None or returncode != 0:
2169 g_trace.fail('Failed to run \"sysctl machdep.cpu hw.cpufrequency\". Skipping ...')
2170 return {}
2171
2172 # Various fields
2173 vendor_id = _get_field(False, output, None, None, 'machdep.cpu.vendor')
2174 processor_brand = _get_field(True, output, None, None, 'machdep.cpu.brand_string')
2175 cache_size = _get_field(False, output, int, 0, 'machdep.cpu.cache.size')
2176 stepping = _get_field(False, output, int, 0, 'machdep.cpu.stepping')
2177 model = _get_field(False, output, int, 0, 'machdep.cpu.model')
2178 family = _get_field(False, output, int, 0, 'machdep.cpu.family')
2179
2180 # Flags
2181 flags = _get_field(False, output, None, '', 'machdep.cpu.features').lower().split()
2182 flags.extend(_get_field(False, output, None, '', 'machdep.cpu.leaf7_features').lower().split())
2183 flags.extend(_get_field(False, output, None, '', 'machdep.cpu.extfeatures').lower().split())
2184 flags.sort()
2185
2186 # Convert from GHz/MHz string to Hz
2187 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
2188 hz_actual = _get_field(False, output, None, None, 'hw.cpufrequency')
2189 hz_actual = _to_decimal_string(hz_actual)
2190
2191 info = {
2192 'vendor_id_raw' : vendor_id,
2193 'brand_raw' : processor_brand,
2194
2195 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
2196 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
2197 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
2198 'hz_actual' : _hz_short_to_full(hz_actual, 0),
2199
2200 'l2_cache_size' : int(cache_size) * 1024,
2201
2202 'stepping' : stepping,
2203 'model' : model,
2204 'family' : family,
2205 'flags' : flags
2206 }
2207
2208 info = _filter_dict_keys_with_empty_values(info)
2209 g_trace.success()
2210 return info
2211 except Exception as err:
2212 g_trace.fail(err)
2213 return {}
2214
2215
2216 def _get_cpu_info_from_sysinfo():
2217 '''
2218 Returns the CPU info gathered from sysinfo.
2219 Returns {} if sysinfo is not found.
2220 '''
2221
2222 info = _get_cpu_info_from_sysinfo_v1()
2223 info.update(_get_cpu_info_from_sysinfo_v2())
2224 return info
2225
2226 def _get_cpu_info_from_sysinfo_v1():
2227 '''
2228 Returns the CPU info gathered from sysinfo.
2229 Returns {} if sysinfo is not found.
2230 '''
2231
2232 g_trace.header('Tying to get info from sysinfo version 1 ...')
2233
2234 try:
2235 # Just return {} if there is no sysinfo
2236 if not DataSource.has_sysinfo():
2237 g_trace.fail('Failed to find sysinfo. Skipping ...')
2238 return {}
2239
2240 # If sysinfo fails return {}
2241 returncode, output = DataSource.sysinfo_cpu()
2242 if output is None or returncode != 0:
2243 g_trace.fail('Failed to run \"sysinfo -cpu\". Skipping ...')
2244 return {}
2245
2246 # Various fields
2247 vendor_id = '' #_get_field(False, output, None, None, 'CPU #0: ')
2248 processor_brand = output.split('CPU #0: "')[1].split('"\n')[0].strip()
2249 cache_size = '' #_get_field(False, output, None, None, 'machdep.cpu.cache.size')
2250 stepping = int(output.split(', stepping ')[1].split(',')[0].strip())
2251 model = int(output.split(', model ')[1].split(',')[0].strip())
2252 family = int(output.split(', family ')[1].split(',')[0].strip())
2253
2254 # Flags
2255 flags = []
2256 for line in output.split('\n'):
2257 if line.startswith('\t\t'):
2258 for flag in line.strip().lower().split():
2259 flags.append(flag)
2260 flags.sort()
2261
2262 # Convert from GHz/MHz string to Hz
2263 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
2264 hz_actual = hz_advertised
2265
2266 info = {
2267 'vendor_id_raw' : vendor_id,
2268 'brand_raw' : processor_brand,
2269
2270 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
2271 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale),
2272 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
2273 'hz_actual' : _hz_short_to_full(hz_actual, scale),
2274
2275 'l2_cache_size' : _to_friendly_bytes(cache_size),
2276
2277 'stepping' : stepping,
2278 'model' : model,
2279 'family' : family,
2280 'flags' : flags
2281 }
2282
2283 info = _filter_dict_keys_with_empty_values(info)
2284 g_trace.success()
2285 return info
2286 except Exception as err:
2287 g_trace.fail(err)
2288 #raise # NOTE: To have this throw on error, uncomment this line
2289 return {}
2290
2291 def _get_cpu_info_from_sysinfo_v2():
2292 '''
2293 Returns the CPU info gathered from sysinfo.
2294 Returns {} if sysinfo is not found.
2295 '''
2296
2297 g_trace.header('Tying to get info from sysinfo version 2 ...')
2298
2299 try:
2300 # Just return {} if there is no sysinfo
2301 if not DataSource.has_sysinfo():
2302 g_trace.fail('Failed to find sysinfo. Skipping ...')
2303 return {}
2304
2305 # If sysinfo fails return {}
2306 returncode, output = DataSource.sysinfo_cpu()
2307 if output is None or returncode != 0:
2308 g_trace.fail('Failed to run \"sysinfo -cpu\". Skipping ...')
2309 return {}
2310
2311 # Various fields
2312 vendor_id = '' #_get_field(False, output, None, None, 'CPU #0: ')
2313 processor_brand = output.split('CPU #0: "')[1].split('"\n')[0].strip()
2314 cache_size = '' #_get_field(False, output, None, None, 'machdep.cpu.cache.size')
2315 signature = output.split('Signature:')[1].split('\n')[0].strip()
2316 #
2317 stepping = int(signature.split('stepping ')[1].split(',')[0].strip())
2318 model = int(signature.split('model ')[1].split(',')[0].strip())
2319 family = int(signature.split('family ')[1].split(',')[0].strip())
2320
2321 # Flags
2322 def get_subsection_flags(output):
2323 retval = []
2324 for line in output.split('\n')[1:]:
2325 if not line.startswith(' ') and not line.startswith(' '): break
2326 for entry in line.strip().lower().split(' '):
2327 retval.append(entry)
2328 return retval
2329
2330 flags = get_subsection_flags(output.split('Features: ')[1]) + \
2331 get_subsection_flags(output.split('Extended Features (0x00000001): ')[1]) + \
2332 get_subsection_flags(output.split('Extended Features (0x80000001): ')[1])
2333 flags.sort()
2334
2335 # Convert from GHz/MHz string to Hz
2336 lines = [n for n in output.split('\n') if n]
2337 raw_hz = lines[0].split('running at ')[1].strip().lower()
2338 hz_advertised = raw_hz.rstrip('mhz').rstrip('ghz').strip()
2339 hz_advertised = _to_decimal_string(hz_advertised)
2340 hz_actual = hz_advertised
2341
2342 scale = 0
2343 if raw_hz.endswith('mhz'):
2344 scale = 6
2345 elif raw_hz.endswith('ghz'):
2346 scale = 9
2347
2348 info = {
2349 'vendor_id_raw' : vendor_id,
2350 'brand_raw' : processor_brand,
2351
2352 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
2353 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale),
2354 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
2355 'hz_actual' : _hz_short_to_full(hz_actual, scale),
2356
2357 'l2_cache_size' : _to_friendly_bytes(cache_size),
2358
2359 'stepping' : stepping,
2360 'model' : model,
2361 'family' : family,
2362 'flags' : flags
2363 }
2364
2365 info = _filter_dict_keys_with_empty_values(info)
2366 g_trace.success()
2367 return info
2368 except Exception as err:
2369 g_trace.fail(err)
2370 #raise # NOTE: To have this throw on error, uncomment this line
2371 return {}
2372
2373 def _get_cpu_info_from_wmic():
2374 '''
2375 Returns the CPU info gathered from WMI.
2376 Returns {} if not on Windows, or wmic is not installed.
2377 '''
2378 g_trace.header('Tying to get info from wmic ...')
2379
2380 try:
2381 # Just return {} if not Windows or there is no wmic
2382 if not DataSource.is_windows or not DataSource.has_wmic():
2383 g_trace.fail('Failed to find WMIC, or not on Windows. Skipping ...')
2384 return {}
2385
2386 returncode, output = DataSource.wmic_cpu()
2387 if output is None or returncode != 0:
2388 g_trace.fail('Failed to run wmic. Skipping ...')
2389 return {}
2390
2391 # Break the list into key values pairs
2392 value = output.split("\n")
2393 value = [s.rstrip().split('=') for s in value if '=' in s]
2394 value = {k: v for k, v in value if v}
2395
2396 # Get the advertised MHz
2397 processor_brand = value.get('Name')
2398 hz_advertised, scale_advertised = _parse_cpu_brand_string(processor_brand)
2399
2400 # Get the actual MHz
2401 hz_actual = value.get('CurrentClockSpeed')
2402 scale_actual = 6
2403 if hz_actual:
2404 hz_actual = _to_decimal_string(hz_actual)
2405
2406 # Get cache sizes
2407 l2_cache_size = value.get('L2CacheSize') # NOTE: L2CacheSize is in kilobytes
2408 if l2_cache_size:
2409 l2_cache_size = int(l2_cache_size) * 1024
2410
2411 l3_cache_size = value.get('L3CacheSize') # NOTE: L3CacheSize is in kilobytes
2412 if l3_cache_size:
2413 l3_cache_size = int(l3_cache_size) * 1024
2414
2415 # Get family, model, and stepping
2416 family, model, stepping = '', '', ''
2417 description = value.get('Description') or value.get('Caption')
2418 entries = description.split(' ')
2419
2420 if 'Family' in entries and entries.index('Family') < len(entries)-1:
2421 i = entries.index('Family')
2422 family = int(entries[i + 1])
2423
2424 if 'Model' in entries and entries.index('Model') < len(entries)-1:
2425 i = entries.index('Model')
2426 model = int(entries[i + 1])
2427
2428 if 'Stepping' in entries and entries.index('Stepping') < len(entries)-1:
2429 i = entries.index('Stepping')
2430 stepping = int(entries[i + 1])
2431
2432 info = {
2433 'vendor_id_raw' : value.get('Manufacturer'),
2434 'brand_raw' : processor_brand,
2435
2436 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale_advertised),
2437 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale_actual),
2438 'hz_advertised' : _hz_short_to_full(hz_advertised, scale_advertised),
2439 'hz_actual' : _hz_short_to_full(hz_actual, scale_actual),
2440
2441 'l2_cache_size' : l2_cache_size,
2442 'l3_cache_size' : l3_cache_size,
2443
2444 'stepping' : stepping,
2445 'model' : model,
2446 'family' : family,
2447 }
2448
2449 info = _filter_dict_keys_with_empty_values(info)
2450 g_trace.success()
2451 return info
2452 except Exception as err:
2453 g_trace.fail(err)
2454 #raise # NOTE: To have this throw on error, uncomment this line
2455 return {}
2456
2457 def _get_cpu_info_from_registry():
2458 '''
2459 Returns the CPU info gathered from the Windows Registry.
2460 Returns {} if not on Windows.
2461 '''
2462
2463 g_trace.header('Tying to get info from Windows registry ...')
2464
2465 try:
2466 # Just return {} if not on Windows
2467 if not DataSource.is_windows:
2468 g_trace.fail('Not running on Windows. Skipping ...')
2469 return {}
2470
2471 # Get the CPU name
2472 processor_brand = DataSource.winreg_processor_brand().strip()
2473
2474 # Get the CPU vendor id
2475 vendor_id = DataSource.winreg_vendor_id_raw()
2476
2477 # Get the CPU arch and bits
2478 arch_string_raw = DataSource.winreg_arch_string_raw()
2479 arch, bits = _parse_arch(arch_string_raw)
2480
2481 # Get the actual CPU Hz
2482 hz_actual = DataSource.winreg_hz_actual()
2483 hz_actual = _to_decimal_string(hz_actual)
2484
2485 # Get the advertised CPU Hz
2486 hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
2487
2488 # If advertised hz not found, use the actual hz
2489 if hz_advertised == '0.0':
2490 scale = 6
2491 hz_advertised = _to_decimal_string(hz_actual)
2492
2493 # Get the CPU features
2494 feature_bits = DataSource.winreg_feature_bits()
2495
2496 def is_set(bit):
2497 mask = 0x80000000 >> bit
2498 retval = mask & feature_bits > 0
2499 return retval
2500
2501 # http://en.wikipedia.org/wiki/CPUID
2502 # http://unix.stackexchange.com/questions/43539/what-do-the-flags-in-proc-cpuinfo-mean
2503 # http://www.lohninger.com/helpcsuite/public_constants_cpuid.htm
2504 flags = {
2505 'fpu' : is_set(0), # Floating Point Unit
2506 'vme' : is_set(1), # V86 Mode Extensions
2507 'de' : is_set(2), # Debug Extensions - I/O breakpoints supported
2508 'pse' : is_set(3), # Page Size Extensions (4 MB pages supported)
2509 'tsc' : is_set(4), # Time Stamp Counter and RDTSC instruction are available
2510 'msr' : is_set(5), # Model Specific Registers
2511 'pae' : is_set(6), # Physical Address Extensions (36 bit address, 2MB pages)
2512 'mce' : is_set(7), # Machine Check Exception supported
2513 'cx8' : is_set(8), # Compare Exchange Eight Byte instruction available
2514 'apic' : is_set(9), # Local APIC present (multiprocessor operation support)
2515 'sepamd' : is_set(10), # Fast system calls (AMD only)
2516 'sep' : is_set(11), # Fast system calls
2517 'mtrr' : is_set(12), # Memory Type Range Registers
2518 'pge' : is_set(13), # Page Global Enable
2519 'mca' : is_set(14), # Machine Check Architecture
2520 'cmov' : is_set(15), # Conditional MOVe instructions
2521 'pat' : is_set(16), # Page Attribute Table
2522 'pse36' : is_set(17), # 36 bit Page Size Extensions
2523 'serial' : is_set(18), # Processor Serial Number
2524 'clflush' : is_set(19), # Cache Flush
2525 #'reserved1' : is_set(20), # reserved
2526 'dts' : is_set(21), # Debug Trace Store
2527 'acpi' : is_set(22), # ACPI support
2528 'mmx' : is_set(23), # MultiMedia Extensions
2529 'fxsr' : is_set(24), # FXSAVE and FXRSTOR instructions
2530 'sse' : is_set(25), # SSE instructions
2531 'sse2' : is_set(26), # SSE2 (WNI) instructions
2532 'ss' : is_set(27), # self snoop
2533 #'reserved2' : is_set(28), # reserved
2534 'tm' : is_set(29), # Automatic clock control
2535 'ia64' : is_set(30), # IA64 instructions
2536 '3dnow' : is_set(31) # 3DNow! instructions available
2537 }
2538
2539 # Get a list of only the flags that are true
2540 flags = [k for k, v in flags.items() if v]
2541 flags.sort()
2542
2543 info = {
2544 'vendor_id_raw' : vendor_id,
2545 'brand_raw' : processor_brand,
2546
2547 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
2548 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 6),
2549 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
2550 'hz_actual' : _hz_short_to_full(hz_actual, 6),
2551
2552 'flags' : flags
2553 }
2554
2555 info = _filter_dict_keys_with_empty_values(info)
2556 g_trace.success()
2557 return info
2558 except Exception as err:
2559 g_trace.fail(err)
2560 return {}
2561
2562 def _get_cpu_info_from_kstat():
2563 '''
2564 Returns the CPU info gathered from isainfo and kstat.
2565 Returns {} if isainfo or kstat are not found.
2566 '''
2567
2568 g_trace.header('Tying to get info from kstat ...')
2569
2570 try:
2571 # Just return {} if there is no isainfo or kstat
2572 if not DataSource.has_isainfo() or not DataSource.has_kstat():
2573 g_trace.fail('Failed to find isinfo or kstat. Skipping ...')
2574 return {}
2575
2576 # If isainfo fails return {}
2577 returncode, flag_output = DataSource.isainfo_vb()
2578 if flag_output is None or returncode != 0:
2579 g_trace.fail('Failed to run \"isainfo -vb\". Skipping ...')
2580 return {}
2581
2582 # If kstat fails return {}
2583 returncode, kstat = DataSource.kstat_m_cpu_info()
2584 if kstat is None or returncode != 0:
2585 g_trace.fail('Failed to run \"kstat -m cpu_info\". Skipping ...')
2586 return {}
2587
2588 # Various fields
2589 vendor_id = kstat.split('\tvendor_id ')[1].split('\n')[0].strip()
2590 processor_brand = kstat.split('\tbrand ')[1].split('\n')[0].strip()
2591 stepping = int(kstat.split('\tstepping ')[1].split('\n')[0].strip())
2592 model = int(kstat.split('\tmodel ')[1].split('\n')[0].strip())
2593 family = int(kstat.split('\tfamily ')[1].split('\n')[0].strip())
2594
2595 # Flags
2596 flags = flag_output.strip().split('\n')[-1].strip().lower().split()
2597 flags.sort()
2598
2599 # Convert from GHz/MHz string to Hz
2600 scale = 6
2601 hz_advertised = kstat.split('\tclock_MHz ')[1].split('\n')[0].strip()
2602 hz_advertised = _to_decimal_string(hz_advertised)
2603
2604 # Convert from GHz/MHz string to Hz
2605 hz_actual = kstat.split('\tcurrent_clock_Hz ')[1].split('\n')[0].strip()
2606 hz_actual = _to_decimal_string(hz_actual)
2607
2608 info = {
2609 'vendor_id_raw' : vendor_id,
2610 'brand_raw' : processor_brand,
2611
2612 'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
2613 'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
2614 'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
2615 'hz_actual' : _hz_short_to_full(hz_actual, 0),
2616
2617 'stepping' : stepping,
2618 'model' : model,
2619 'family' : family,
2620 'flags' : flags
2621 }
2622
2623 info = _filter_dict_keys_with_empty_values(info)
2624 g_trace.success()
2625 return info
2626 except Exception as err:
2627 g_trace.fail(err)
2628 return {}
2629
2630 def _get_cpu_info_from_platform_uname():
2631
2632 g_trace.header('Tying to get info from platform.uname ...')
2633
2634 try:
2635 uname = DataSource.uname_string_raw.split(',')[0]
2636
2637 family, model, stepping = (None, None, None)
2638 entries = uname.split(' ')
2639
2640 if 'Family' in entries and entries.index('Family') < len(entries)-1:
2641 i = entries.index('Family')
2642 family = int(entries[i + 1])
2643
2644 if 'Model' in entries and entries.index('Model') < len(entries)-1:
2645 i = entries.index('Model')
2646 model = int(entries[i + 1])
2647
2648 if 'Stepping' in entries and entries.index('Stepping') < len(entries)-1:
2649 i = entries.index('Stepping')
2650 stepping = int(entries[i + 1])
2651
2652 info = {
2653 'family' : family,
2654 'model' : model,
2655 'stepping' : stepping
2656 }
2657 info = _filter_dict_keys_with_empty_values(info)
2658 g_trace.success()
2659 return info
2660 except Exception as err:
2661 g_trace.fail(err)
2662 return {}
2663
2664 def _get_cpu_info_internal():
2665 '''
2666 Returns the CPU info by using the best sources of information for your OS.
2667 Returns {} if nothing is found.
2668 '''
2669
2670 g_trace.write('!' * 80)
2671
2672 # Get the CPU arch and bits
2673 arch, bits = _parse_arch(DataSource.arch_string_raw)
2674
2675 friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unknown bits'
2676 friendly_version = "{0}.{1}.{2}.{3}.{4}".format(*sys.version_info)
2677 PYTHON_VERSION = "{0} ({1})".format(friendly_version, friendly_maxsize)
2678
2679 info = {
2680 'python_version' : PYTHON_VERSION,
2681 'cpuinfo_version' : CPUINFO_VERSION,
2682 'cpuinfo_version_string' : CPUINFO_VERSION_STRING,
2683 'arch' : arch,
2684 'bits' : bits,
2685 'count' : DataSource.cpu_count,
2686 'arch_string_raw' : DataSource.arch_string_raw,
2687 }
2688
2689 g_trace.write("python_version: {0}".format(info['python_version']))
2690 g_trace.write("cpuinfo_version: {0}".format(info['cpuinfo_version']))
2691 g_trace.write("arch: {0}".format(info['arch']))
2692 g_trace.write("bits: {0}".format(info['bits']))
2693 g_trace.write("count: {0}".format(info['count']))
2694 g_trace.write("arch_string_raw: {0}".format(info['arch_string_raw']))
2695
2696 # Try the Windows wmic
2697 _copy_new_fields(info, _get_cpu_info_from_wmic())
2698
2699 # Try the Windows registry
2700 _copy_new_fields(info, _get_cpu_info_from_registry())
2701
2702 # Try /proc/cpuinfo
2703 _copy_new_fields(info, _get_cpu_info_from_proc_cpuinfo())
2704
2705 # Try cpufreq-info
2706 _copy_new_fields(info, _get_cpu_info_from_cpufreq_info())
2707
2708 # Try LSCPU
2709 _copy_new_fields(info, _get_cpu_info_from_lscpu())
2710
2711 # Try sysctl
2712 _copy_new_fields(info, _get_cpu_info_from_sysctl())
2713
2714 # Try kstat
2715 _copy_new_fields(info, _get_cpu_info_from_kstat())
2716
2717 # Try dmesg
2718 _copy_new_fields(info, _get_cpu_info_from_dmesg())
2719
2720 # Try /var/run/dmesg.boot
2721 _copy_new_fields(info, _get_cpu_info_from_cat_var_run_dmesg_boot())
2722
2723 # Try lsprop ibm,pa-features
2724 _copy_new_fields(info, _get_cpu_info_from_ibm_pa_features())
2725
2726 # Try sysinfo
2727 _copy_new_fields(info, _get_cpu_info_from_sysinfo())
2728
2729 # Try querying the CPU cpuid register
2730 # FIXME: This should print stdout and stderr to trace log
2731 _copy_new_fields(info, _get_cpu_info_from_cpuid())
2732
2733 # Try platform.uname
2734 _copy_new_fields(info, _get_cpu_info_from_platform_uname())
2735
2736 g_trace.write('!' * 80)
2737
2738 return info
2739
2740 def get_cpu_info_json():
2741 '''
2742 Returns the CPU info by using the best sources of information for your OS.
2743 Returns the result in a json string
2744 '''
2745
2746 import json
2747
2748 output = None
2749
2750 # If running under pyinstaller, run normally
2751 if getattr(sys, 'frozen', False):
2752 info = _get_cpu_info_internal()
2753 output = json.dumps(info)
2754 output = "{0}".format(output)
2755 # if not running under pyinstaller, run in another process.
2756 # This is done because multiprocesing has a design flaw that
2757 # causes non main programs to run multiple times on Windows.
2758 else:
2759 from subprocess import Popen, PIPE
2760
2761 command = [sys.executable, __file__, '--json']
2762 p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2763 output = p1.communicate()[0]
2764
2765 if p1.returncode != 0:
2766 return "{}"
2767
2768 output = output.decode(encoding='UTF-8')
2769
2770 return output
2771
2772 def get_cpu_info():
2773 '''
2774 Returns the CPU info by using the best sources of information for your OS.
2775 Returns the result in a dict
2776 '''
2777
2778 import json
2779
2780 output = get_cpu_info_json()
2781
2782 # Convert JSON to Python with non unicode strings
2783 output = json.loads(output, object_hook = _utf_to_str)
2784
2785 return output
2786
2787 def main():
2788 from argparse import ArgumentParser
2789 import json
2790
2791 # Parse args
2792 parser = ArgumentParser(description='Gets CPU info with pure Python')
2793 parser.add_argument('--json', action='store_true', help='Return the info in JSON format')
2794 parser.add_argument('--version', action='store_true', help='Return the version of py-cpuinfo')
2795 parser.add_argument('--trace', action='store_true', help='Traces code paths used to find CPU info to file')
2796 args = parser.parse_args()
2797
2798 global g_trace
2799 g_trace = Trace(args.trace, False)
2800
2801 try:
2802 _check_arch()
2803 except Exception as err:
2804 sys.stderr.write(str(err) + "\n")
2805 sys.exit(1)
2806
2807 info = _get_cpu_info_internal()
2808
2809 if not info:
2810 sys.stderr.write("Failed to find cpu info\n")
2811 sys.exit(1)
2812
2813 if args.json:
2814 print(json.dumps(info))
2815 elif args.version:
2816 print(CPUINFO_VERSION_STRING)
2817 else:
2818 print('Python Version: {0}'.format(info.get('python_version', '')))
2819 print('Cpuinfo Version: {0}'.format(info.get('cpuinfo_version_string', '')))
2820 print('Vendor ID Raw: {0}'.format(info.get('vendor_id_raw', '')))
2821 print('Hardware Raw: {0}'.format(info.get('hardware_raw', '')))
2822 print('Brand Raw: {0}'.format(info.get('brand_raw', '')))
2823 print('Hz Advertised Friendly: {0}'.format(info.get('hz_advertised_friendly', '')))
2824 print('Hz Actual Friendly: {0}'.format(info.get('hz_actual_friendly', '')))
2825 print('Hz Advertised: {0}'.format(info.get('hz_advertised', '')))
2826 print('Hz Actual: {0}'.format(info.get('hz_actual', '')))
2827 print('Arch: {0}'.format(info.get('arch', '')))
2828 print('Bits: {0}'.format(info.get('bits', '')))
2829 print('Count: {0}'.format(info.get('count', '')))
2830 print('Arch String Raw: {0}'.format(info.get('arch_string_raw', '')))
2831 print('L1 Data Cache Size: {0}'.format(info.get('l1_data_cache_size', '')))
2832 print('L1 Instruction Cache Size: {0}'.format(info.get('l1_instruction_cache_size', '')))
2833 print('L2 Cache Size: {0}'.format(info.get('l2_cache_size', '')))
2834 print('L2 Cache Line Size: {0}'.format(info.get('l2_cache_line_size', '')))
2835 print('L2 Cache Associativity: {0}'.format(info.get('l2_cache_associativity', '')))
2836 print('L3 Cache Size: {0}'.format(info.get('l3_cache_size', '')))
2837 print('Stepping: {0}'.format(info.get('stepping', '')))
2838 print('Model: {0}'.format(info.get('model', '')))
2839 print('Family: {0}'.format(info.get('family', '')))
2840 print('Processor Type: {0}'.format(info.get('processor_type', '')))
2841 print('Flags: {0}'.format(', '.join(info.get('flags', ''))))
2842
2843
2844 if __name__ == '__main__':
2845 main()
2846 else:
2847 g_trace = Trace(False, False)
2848 _check_arch()