Debian Codegraph @

lib-python/3/test/pythoninfo.py

raw symbols SCIP
1 """
2 Collect various information about Python to help debugging test failures.
3 """
4 import errno
5 import re
6 import sys
7 import traceback
8 import warnings
9
10
11 def normalize_text(text):
12 if text is None:
13 return None
14 text = str(text)
15 text = re.sub(r'\s+', ' ', text)
16 return text.strip()
17
18
19 class PythonInfo:
20 def __init__(self):
21 self.info = {}
22
23 def add(self, key, value):
24 if key in self.info:
25 raise ValueError("duplicate key: %r" % key)
26
27 if value is None:
28 return
29
30 if not isinstance(value, int):
31 if not isinstance(value, str):
32 # convert other objects like sys.flags to string
33 value = str(value)
34
35 value = value.strip()
36 if not value:
37 return
38
39 self.info[key] = value
40
41 def get_infos(self):
42 """
43 Get information as a key:value dictionary where values are strings.
44 """
45 return {key: str(value) for key, value in self.info.items()}
46
47
48 def copy_attributes(info_add, obj, name_fmt, attributes, *, formatter=None):
49 for attr in attributes:
50 value = getattr(obj, attr, None)
51 if value is None:
52 continue
53 name = name_fmt % attr
54 if formatter is not None:
55 value = formatter(attr, value)
56 info_add(name, value)
57
58
59 def copy_attr(info_add, name, mod, attr_name):
60 try:
61 value = getattr(mod, attr_name)
62 except AttributeError:
63 return
64 info_add(name, value)
65
66
67 def call_func(info_add, name, mod, func_name, *, formatter=None):
68 try:
69 func = getattr(mod, func_name)
70 except AttributeError:
71 return
72 value = func()
73 if formatter is not None:
74 value = formatter(value)
75 info_add(name, value)
76
77
78 def collect_sys(info_add):
79 attributes = (
80 '_emscripten_info',
81 '_framework',
82 'abiflags',
83 'api_version',
84 'builtin_module_names',
85 'byteorder',
86 'dont_write_bytecode',
87 'executable',
88 'flags',
89 'float_info',
90 'float_repr_style',
91 'hash_info',
92 'hexversion',
93 'implementation',
94 'int_info',
95 'maxsize',
96 'maxunicode',
97 'path',
98 'platform',
99 'platlibdir',
100 'prefix',
101 'thread_info',
102 'version',
103 'version_info',
104 'winver',
105 )
106 copy_attributes(info_add, sys, 'sys.%s', attributes)
107
108 call_func(info_add, 'sys.androidapilevel', sys, 'getandroidapilevel')
109 call_func(info_add, 'sys.windowsversion', sys, 'getwindowsversion')
110 call_func(info_add, 'sys.getrecursionlimit', sys, 'getrecursionlimit')
111
112 encoding = sys.getfilesystemencoding()
113 if hasattr(sys, 'getfilesystemencodeerrors'):
114 encoding = '%s/%s' % (encoding, sys.getfilesystemencodeerrors())
115 info_add('sys.filesystem_encoding', encoding)
116
117 for name in ('stdin', 'stdout', 'stderr'):
118 stream = getattr(sys, name)
119 if stream is None:
120 continue
121 encoding = getattr(stream, 'encoding', None)
122 if not encoding:
123 continue
124 errors = getattr(stream, 'errors', None)
125 if errors:
126 encoding = '%s/%s' % (encoding, errors)
127 info_add('sys.%s.encoding' % name, encoding)
128
129 # Were we compiled --with-pydebug?
130 Py_DEBUG = hasattr(sys, 'gettotalrefcount')
131 if Py_DEBUG:
132 text = 'Yes (sys.gettotalrefcount() present)'
133 else:
134 text = 'No (sys.gettotalrefcount() missing)'
135 info_add('build.Py_DEBUG', text)
136
137 # Were we compiled --with-trace-refs?
138 Py_TRACE_REFS = hasattr(sys, 'getobjects')
139 if Py_TRACE_REFS:
140 text = 'Yes (sys.getobjects() present)'
141 else:
142 text = 'No (sys.getobjects() missing)'
143 info_add('build.Py_TRACE_REFS', text)
144
145
146 def collect_platform(info_add):
147 import platform
148
149 arch = platform.architecture()
150 arch = ' '.join(filter(bool, arch))
151 info_add('platform.architecture', arch)
152
153 info_add('platform.python_implementation',
154 platform.python_implementation())
155 info_add('platform.platform',
156 platform.platform(aliased=True))
157
158 libc_ver = ('%s %s' % platform.libc_ver()).strip()
159 if libc_ver:
160 info_add('platform.libc_ver', libc_ver)
161
162 try:
163 os_release = platform.freedesktop_os_release()
164 except OSError:
165 pass
166 else:
167 for key in (
168 'ID',
169 'NAME',
170 'PRETTY_NAME'
171 'VARIANT',
172 'VARIANT_ID',
173 'VERSION',
174 'VERSION_CODENAME',
175 'VERSION_ID',
176 ):
177 if key not in os_release:
178 continue
179 info_add(f'platform.freedesktop_os_release[{key}]',
180 os_release[key])
181
182
183 def collect_locale(info_add):
184 import locale
185
186 info_add('locale.getencoding', locale.getencoding())
187
188
189 def collect_builtins(info_add):
190 info_add('builtins.float.float_format', float.__getformat__("float"))
191 info_add('builtins.float.double_format', float.__getformat__("double"))
192
193
194 def collect_urandom(info_add):
195 import os
196
197 if hasattr(os, 'getrandom'):
198 # PEP 524: Check if system urandom is initialized
199 try:
200 try:
201 os.getrandom(1, os.GRND_NONBLOCK)
202 state = 'ready (initialized)'
203 except BlockingIOError as exc:
204 state = 'not seeded yet (%s)' % exc
205 info_add('os.getrandom', state)
206 except OSError as exc:
207 # Python was compiled on a more recent Linux version
208 # than the current Linux kernel: ignore OSError(ENOSYS)
209 if exc.errno != errno.ENOSYS:
210 raise
211
212
213 def collect_os(info_add):
214 import os
215
216 def format_attr(attr, value):
217 if attr in ('supports_follow_symlinks', 'supports_fd',
218 'supports_effective_ids'):
219 return str(sorted(func.__name__ for func in value))
220 else:
221 return value
222
223 attributes = (
224 'name',
225 'supports_bytes_environ',
226 'supports_effective_ids',
227 'supports_fd',
228 'supports_follow_symlinks',
229 )
230 copy_attributes(info_add, os, 'os.%s', attributes, formatter=format_attr)
231
232 for func in (
233 'cpu_count',
234 'getcwd',
235 'getegid',
236 'geteuid',
237 'getgid',
238 'getloadavg',
239 'getresgid',
240 'getresuid',
241 'getuid',
242 'process_cpu_count',
243 'uname',
244 ):
245 call_func(info_add, 'os.%s' % func, os, func)
246
247 def format_groups(groups):
248 return ', '.join(map(str, groups))
249
250 call_func(info_add, 'os.getgroups', os, 'getgroups', formatter=format_groups)
251
252 if hasattr(os, 'getlogin'):
253 try:
254 login = os.getlogin()
255 except OSError:
256 # getlogin() fails with "OSError: [Errno 25] Inappropriate ioctl
257 # for device" on Travis CI
258 pass
259 else:
260 info_add("os.login", login)
261
262 # Environment variables used by the stdlib and tests. Don't log the full
263 # environment: filter to list to not leak sensitive information.
264 #
265 # HTTP_PROXY is not logged because it can contain a password.
266 ENV_VARS = frozenset((
267 "APPDATA",
268 "AR",
269 "ARCHFLAGS",
270 "ARFLAGS",
271 "AUDIODEV",
272 "BUILDPYTHON",
273 "CC",
274 "CFLAGS",
275 "COLUMNS",
276 "COMPUTERNAME",
277 "COMSPEC",
278 "CPP",
279 "CPPFLAGS",
280 "DISPLAY",
281 "DISTUTILS_DEBUG",
282 "DISTUTILS_USE_SDK",
283 "DYLD_LIBRARY_PATH",
284 "ENSUREPIP_OPTIONS",
285 "HISTORY_FILE",
286 "HOME",
287 "HOMEDRIVE",
288 "HOMEPATH",
289 "IDLESTARTUP",
290 "LANG",
291 "LDFLAGS",
292 "LDSHARED",
293 "LD_LIBRARY_PATH",
294 "LINES",
295 "MACOSX_DEPLOYMENT_TARGET",
296 "MAILCAPS",
297 "MAKEFLAGS",
298 "MIXERDEV",
299 "MSSDK",
300 "PATH",
301 "PATHEXT",
302 "PIP_CONFIG_FILE",
303 "PLAT",
304 "POSIXLY_CORRECT",
305 "PY_SAX_PARSER",
306 "ProgramFiles",
307 "ProgramFiles(x86)",
308 "RUNNING_ON_VALGRIND",
309 "SDK_TOOLS_BIN",
310 "SERVER_SOFTWARE",
311 "SHELL",
312 "SOURCE_DATE_EPOCH",
313 "SYSTEMROOT",
314 "TEMP",
315 "TERM",
316 "TILE_LIBRARY",
317 "TMP",
318 "TMPDIR",
319 "TRAVIS",
320 "TZ",
321 "USERPROFILE",
322 "VIRTUAL_ENV",
323 "WAYLAND_DISPLAY",
324 "WINDIR",
325 "_PYTHON_HOSTRUNNER",
326 "_PYTHON_HOST_PLATFORM",
327 "_PYTHON_PROJECT_BASE",
328 "_PYTHON_SYSCONFIGDATA_NAME",
329 "__PYVENV_LAUNCHER__",
330
331 # Sanitizer options
332 "ASAN_OPTIONS",
333 "LSAN_OPTIONS",
334 "MSAN_OPTIONS",
335 "TSAN_OPTIONS",
336 "UBSAN_OPTIONS",
337 ))
338 for name, value in os.environ.items():
339 uname = name.upper()
340 if (uname in ENV_VARS
341 # Copy PYTHON* variables like PYTHONPATH
342 # Copy LC_* variables like LC_ALL
343 or uname.startswith(("PYTHON", "LC_"))
344 # Visual Studio: VS140COMNTOOLS
345 or (uname.startswith("VS") and uname.endswith("COMNTOOLS"))):
346 info_add('os.environ[%s]' % name, value)
347
348 if hasattr(os, 'umask'):
349 mask = os.umask(0)
350 os.umask(mask)
351 info_add("os.umask", '0o%03o' % mask)
352
353
354 def collect_pwd(info_add):
355 try:
356 import pwd
357 except ImportError:
358 return
359 import os
360
361 uid = os.getuid()
362 try:
363 entry = pwd.getpwuid(uid)
364 except KeyError:
365 entry = None
366
367 info_add('pwd.getpwuid(%s)'% uid,
368 entry if entry is not None else '<KeyError>')
369
370 if entry is None:
371 # there is nothing interesting to read if the current user identifier
372 # is not the password database
373 return
374
375 if hasattr(os, 'getgrouplist'):
376 groups = os.getgrouplist(entry.pw_name, entry.pw_gid)
377 groups = ', '.join(map(str, groups))
378 info_add('os.getgrouplist', groups)
379
380
381 def collect_readline(info_add):
382 try:
383 import readline
384 except ImportError:
385 return
386
387 def format_attr(attr, value):
388 if isinstance(value, int):
389 return "%#x" % value
390 else:
391 return value
392
393 attributes = (
394 "_READLINE_VERSION",
395 "_READLINE_RUNTIME_VERSION",
396 "_READLINE_LIBRARY_VERSION",
397 )
398 copy_attributes(info_add, readline, 'readline.%s', attributes,
399 formatter=format_attr)
400
401 if not hasattr(readline, "_READLINE_LIBRARY_VERSION"):
402 # _READLINE_LIBRARY_VERSION has been added to CPython 3.7
403 doc = getattr(readline, '__doc__', '')
404 if 'libedit readline' in doc:
405 info_add('readline.library', 'libedit readline')
406 elif 'GNU readline' in doc:
407 info_add('readline.library', 'GNU readline')
408
409
410 def collect_gdb(info_add):
411 import subprocess
412
413 try:
414 proc = subprocess.Popen(["gdb", "-nx", "--version"],
415 stdout=subprocess.PIPE,
416 stderr=subprocess.PIPE,
417 universal_newlines=True)
418 version = proc.communicate()[0]
419 if proc.returncode:
420 # ignore gdb failure: test_gdb will log the error
421 return
422 except OSError:
423 return
424
425 # Only keep the first line
426 version = version.splitlines()[0]
427 info_add('gdb_version', version)
428
429
430 def collect_tkinter(info_add):
431 try:
432 import _tkinter
433 except ImportError:
434 pass
435 else:
436 attributes = ('TK_VERSION', 'TCL_VERSION')
437 copy_attributes(info_add, _tkinter, 'tkinter.%s', attributes)
438
439 try:
440 import tkinter
441 except ImportError:
442 pass
443 else:
444 tcl = tkinter.Tcl()
445 patchlevel = tcl.call('info', 'patchlevel')
446 info_add('tkinter.info_patchlevel', patchlevel)
447
448
449 def collect_time(info_add):
450 import time
451
452 info_add('time.time', time.time())
453
454 attributes = (
455 'altzone',
456 'daylight',
457 'timezone',
458 'tzname',
459 )
460 copy_attributes(info_add, time, 'time.%s', attributes)
461
462 if hasattr(time, 'get_clock_info'):
463 for clock in ('clock', 'monotonic', 'perf_counter',
464 'process_time', 'thread_time', 'time'):
465 try:
466 # prevent DeprecatingWarning on get_clock_info('clock')
467 with warnings.catch_warnings(record=True):
468 clock_info = time.get_clock_info(clock)
469 except ValueError:
470 # missing clock like time.thread_time()
471 pass
472 else:
473 info_add('time.get_clock_info(%s)' % clock, clock_info)
474
475
476 def collect_curses(info_add):
477 try:
478 import curses
479 except ImportError:
480 return
481
482 copy_attr(info_add, 'curses.ncurses_version', curses, 'ncurses_version')
483
484
485 def collect_datetime(info_add):
486 try:
487 import datetime
488 except ImportError:
489 return
490
491 info_add('datetime.datetime.now', datetime.datetime.now())
492
493
494 def collect_sysconfig(info_add):
495 import sysconfig
496
497 info_add('sysconfig.is_python_build', sysconfig.is_python_build())
498
499 for name in (
500 'ABIFLAGS',
501 'ANDROID_API_LEVEL',
502 'CC',
503 'CCSHARED',
504 'CFLAGS',
505 'CFLAGSFORSHARED',
506 'CONFIG_ARGS',
507 'HOSTRUNNER',
508 'HOST_GNU_TYPE',
509 'MACHDEP',
510 'MULTIARCH',
511 'OPT',
512 'PY_CFLAGS',
513 'PY_CFLAGS_NODIST',
514 'PY_CORE_LDFLAGS',
515 'PY_LDFLAGS',
516 'PY_LDFLAGS_NODIST',
517 'PY_STDMODULE_CFLAGS',
518 'Py_DEBUG',
519 'Py_ENABLE_SHARED',
520 'Py_NOGIL',
521 'SHELL',
522 'SOABI',
523 'abs_builddir',
524 'abs_srcdir',
525 'prefix',
526 'srcdir',
527 ):
528 value = sysconfig.get_config_var(name)
529 if name == 'ANDROID_API_LEVEL' and not value:
530 # skip ANDROID_API_LEVEL=0
531 continue
532 value = normalize_text(value)
533 info_add('sysconfig[%s]' % name, value)
534
535 PY_CFLAGS = sysconfig.get_config_var('PY_CFLAGS')
536 NDEBUG = (PY_CFLAGS and '-DNDEBUG' in PY_CFLAGS)
537 if NDEBUG:
538 text = 'ignore assertions (macro defined)'
539 else:
540 text= 'build assertions (macro not defined)'
541 info_add('build.NDEBUG',text)
542
543 for name in (
544 'WITH_DOC_STRINGS',
545 'WITH_DTRACE',
546 'WITH_FREELISTS',
547 'WITH_PYMALLOC',
548 'WITH_VALGRIND',
549 ):
550 value = sysconfig.get_config_var(name)
551 if value:
552 text = 'Yes'
553 else:
554 text = 'No'
555 info_add(f'build.{name}', text)
556
557
558 def collect_ssl(info_add):
559 import os
560 try:
561 import ssl
562 except ImportError:
563 return
564 try:
565 import _ssl
566 except ImportError:
567 _ssl = None
568
569 def format_attr(attr, value):
570 if attr.startswith('OP_'):
571 return '%#8x' % value
572 else:
573 return value
574
575 attributes = (
576 'OPENSSL_VERSION',
577 'OPENSSL_VERSION_INFO',
578 'HAS_SNI',
579 'OP_ALL',
580 'OP_NO_TLSv1_1',
581 )
582 copy_attributes(info_add, ssl, 'ssl.%s', attributes, formatter=format_attr)
583
584 for name, ctx in (
585 ('SSLContext', ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)),
586 ('default_https_context', ssl._create_default_https_context()),
587 ('stdlib_context', ssl._create_stdlib_context()),
588 ):
589 attributes = (
590 'minimum_version',
591 'maximum_version',
592 'protocol',
593 'options',
594 'verify_mode',
595 )
596 copy_attributes(info_add, ctx, f'ssl.{name}.%s', attributes)
597
598 env_names = ["OPENSSL_CONF", "SSLKEYLOGFILE"]
599 if _ssl is not None and hasattr(_ssl, 'get_default_verify_paths'):
600 parts = _ssl.get_default_verify_paths()
601 env_names.extend((parts[0], parts[2]))
602
603 for name in env_names:
604 try:
605 value = os.environ[name]
606 except KeyError:
607 continue
608 info_add('ssl.environ[%s]' % name, value)
609
610
611 def collect_socket(info_add):
612 try:
613 import socket
614 except ImportError:
615 return
616
617 try:
618 hostname = socket.gethostname()
619 except (OSError, AttributeError):
620 # WASI SDK 16.0 does not have gethostname(2).
621 if sys.platform != "wasi":
622 raise
623 else:
624 info_add('socket.hostname', hostname)
625
626
627 def collect_sqlite(info_add):
628 try:
629 import sqlite3
630 except ImportError:
631 return
632
633 attributes = ('sqlite_version',)
634 copy_attributes(info_add, sqlite3, 'sqlite3.%s', attributes)
635
636
637 def collect_zlib(info_add):
638 try:
639 import zlib
640 except ImportError:
641 return
642
643 attributes = ('ZLIB_VERSION', 'ZLIB_RUNTIME_VERSION')
644 copy_attributes(info_add, zlib, 'zlib.%s', attributes)
645
646
647 def collect_expat(info_add):
648 try:
649 from xml.parsers import expat
650 except ImportError:
651 return
652
653 attributes = ('EXPAT_VERSION',)
654 copy_attributes(info_add, expat, 'expat.%s', attributes)
655
656
657 def collect_decimal(info_add):
658 try:
659 import _decimal
660 except ImportError:
661 return
662
663 attributes = ('__libmpdec_version__',)
664 copy_attributes(info_add, _decimal, '_decimal.%s', attributes)
665
666
667 def collect_testcapi(info_add):
668 try:
669 import _testcapi
670 except ImportError:
671 return
672
673 for name in (
674 'LONG_MAX', # always 32-bit on Windows, 64-bit on 64-bit Unix
675 'PY_SSIZE_T_MAX',
676 'Py_C_RECURSION_LIMIT',
677 'SIZEOF_TIME_T', # 32-bit or 64-bit depending on the platform
678 'SIZEOF_WCHAR_T', # 16-bit or 32-bit depending on the platform
679 ):
680 copy_attr(info_add, f'_testcapi.{name}', _testcapi, name)
681
682
683 def collect_testinternalcapi(info_add):
684 try:
685 import _testinternalcapi
686 except ImportError:
687 return
688
689 call_func(info_add, 'pymem.allocator', _testinternalcapi, 'pymem_getallocatorsname')
690
691 for name in (
692 'SIZEOF_PYGC_HEAD',
693 'SIZEOF_PYOBJECT',
694 ):
695 copy_attr(info_add, f'_testinternalcapi.{name}', _testinternalcapi, name)
696
697
698 def collect_resource(info_add):
699 try:
700 import resource
701 except ImportError:
702 return
703
704 limits = [attr for attr in dir(resource) if attr.startswith('RLIMIT_')]
705 for name in limits:
706 key = getattr(resource, name)
707 value = resource.getrlimit(key)
708 info_add('resource.%s' % name, value)
709
710 call_func(info_add, 'resource.pagesize', resource, 'getpagesize')
711
712
713 def collect_test_socket(info_add):
714 import unittest
715 try:
716 from test import test_socket
717 except (ImportError, unittest.SkipTest):
718 return
719
720 # all check attributes like HAVE_SOCKET_CAN
721 attributes = [name for name in dir(test_socket)
722 if name.startswith('HAVE_')]
723 copy_attributes(info_add, test_socket, 'test_socket.%s', attributes)
724
725
726 def collect_support(info_add):
727 try:
728 from test import support
729 except ImportError:
730 return
731
732 attributes = (
733 'MS_WINDOWS',
734 'has_fork_support',
735 'has_socket_support',
736 'has_strftime_extensions',
737 'has_subprocess_support',
738 'is_android',
739 'is_emscripten',
740 'is_jython',
741 'is_wasi',
742 )
743 copy_attributes(info_add, support, 'support.%s', attributes)
744
745 call_func(info_add, 'support._is_gui_available', support, '_is_gui_available')
746 call_func(info_add, 'support.python_is_optimized', support, 'python_is_optimized')
747
748 info_add('support.check_sanitizer(address=True)',
749 support.check_sanitizer(address=True))
750 info_add('support.check_sanitizer(memory=True)',
751 support.check_sanitizer(memory=True))
752 info_add('support.check_sanitizer(ub=True)',
753 support.check_sanitizer(ub=True))
754
755
756 def collect_support_os_helper(info_add):
757 try:
758 from test.support import os_helper
759 except ImportError:
760 return
761
762 for name in (
763 'can_symlink',
764 'can_xattr',
765 'can_chmod',
766 'can_dac_override',
767 ):
768 func = getattr(os_helper, name)
769 info_add(f'support_os_helper.{name}', func())
770
771
772 def collect_support_socket_helper(info_add):
773 try:
774 from test.support import socket_helper
775 except ImportError:
776 return
777
778 attributes = (
779 'IPV6_ENABLED',
780 'has_gethostname',
781 )
782 copy_attributes(info_add, socket_helper, 'support_socket_helper.%s', attributes)
783
784 for name in (
785 'tcp_blackhole',
786 ):
787 func = getattr(socket_helper, name)
788 info_add(f'support_socket_helper.{name}', func())
789
790
791 def collect_support_threading_helper(info_add):
792 try:
793 from test.support import threading_helper
794 except ImportError:
795 return
796
797 attributes = (
798 'can_start_thread',
799 )
800 copy_attributes(info_add, threading_helper, 'support_threading_helper.%s', attributes)
801
802
803 def collect_cc(info_add):
804 import subprocess
805 import sysconfig
806
807 CC = sysconfig.get_config_var('CC')
808 if not CC:
809 return
810
811 try:
812 import shlex
813 args = shlex.split(CC)
814 except ImportError:
815 args = CC.split()
816 args.append('--version')
817 try:
818 proc = subprocess.Popen(args,
819 stdout=subprocess.PIPE,
820 stderr=subprocess.STDOUT,
821 universal_newlines=True)
822 except OSError:
823 # Cannot run the compiler, for example when Python has been
824 # cross-compiled and installed on the target platform where the
825 # compiler is missing.
826 return
827
828 stdout = proc.communicate()[0]
829 if proc.returncode:
830 # CC --version failed: ignore error
831 return
832
833 text = stdout.splitlines()[0]
834 text = normalize_text(text)
835 info_add('CC.version', text)
836
837
838 def collect_gdbm(info_add):
839 try:
840 from _gdbm import _GDBM_VERSION
841 except ImportError:
842 return
843
844 info_add('gdbm.GDBM_VERSION', '.'.join(map(str, _GDBM_VERSION)))
845
846
847 def collect_get_config(info_add):
848 # Get global configuration variables, _PyPreConfig and _PyCoreConfig
849 try:
850 from _testinternalcapi import get_configs
851 except ImportError:
852 return
853
854 all_configs = get_configs()
855 for config_type in sorted(all_configs):
856 config = all_configs[config_type]
857 for key in sorted(config):
858 info_add('%s[%s]' % (config_type, key), repr(config[key]))
859
860
861 def collect_subprocess(info_add):
862 import subprocess
863 copy_attributes(info_add, subprocess, 'subprocess.%s', ('_USE_POSIX_SPAWN',))
864
865
866 def collect_windows(info_add):
867 if sys.platform != "win32":
868 # Code specific to Windows
869 return
870
871 # windows.RtlAreLongPathsEnabled: RtlAreLongPathsEnabled()
872 # windows.is_admin: IsUserAnAdmin()
873 try:
874 import ctypes
875 if not hasattr(ctypes, 'WinDLL'):
876 raise ImportError
877 except ImportError:
878 pass
879 else:
880 ntdll = ctypes.WinDLL('ntdll')
881 BOOLEAN = ctypes.c_ubyte
882 try:
883 RtlAreLongPathsEnabled = ntdll.RtlAreLongPathsEnabled
884 except AttributeError:
885 res = '<function not available>'
886 else:
887 RtlAreLongPathsEnabled.restype = BOOLEAN
888 RtlAreLongPathsEnabled.argtypes = ()
889 res = bool(RtlAreLongPathsEnabled())
890 info_add('windows.RtlAreLongPathsEnabled', res)
891
892 shell32 = ctypes.windll.shell32
893 IsUserAnAdmin = shell32.IsUserAnAdmin
894 IsUserAnAdmin.restype = BOOLEAN
895 IsUserAnAdmin.argtypes = ()
896 info_add('windows.is_admin', IsUserAnAdmin())
897
898 try:
899 import _winapi
900 dll_path = _winapi.GetModuleFileName(sys.dllhandle)
901 info_add('windows.dll_path', dll_path)
902 except (ImportError, AttributeError):
903 pass
904
905 # windows.version_caption: "wmic os get Caption,Version /value" command
906 import subprocess
907 try:
908 # When wmic.exe output is redirected to a pipe,
909 # it uses the OEM code page
910 proc = subprocess.Popen(["wmic", "os", "get", "Caption,Version", "/value"],
911 stdout=subprocess.PIPE,
912 stderr=subprocess.PIPE,
913 encoding="oem",
914 text=True)
915 output, stderr = proc.communicate()
916 if proc.returncode:
917 output = ""
918 except OSError:
919 pass
920 else:
921 for line in output.splitlines():
922 line = line.strip()
923 if line.startswith('Caption='):
924 line = line.removeprefix('Caption=').strip()
925 if line:
926 info_add('windows.version_caption', line)
927 elif line.startswith('Version='):
928 line = line.removeprefix('Version=').strip()
929 if line:
930 info_add('windows.version', line)
931
932 # windows.ver: "ver" command
933 try:
934 proc = subprocess.Popen(["ver"], shell=True,
935 stdout=subprocess.PIPE,
936 stderr=subprocess.PIPE,
937 text=True)
938 output = proc.communicate()[0]
939 if proc.returncode == 0xc0000142:
940 return
941 if proc.returncode:
942 output = ""
943 except OSError:
944 return
945 else:
946 output = output.strip()
947 line = output.splitlines()[0]
948 if line:
949 info_add('windows.ver', line)
950
951 # windows.developer_mode: get AllowDevelopmentWithoutDevLicense registry
952 import winreg
953 try:
954 key = winreg.OpenKey(
955 winreg.HKEY_LOCAL_MACHINE,
956 r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock")
957 subkey = "AllowDevelopmentWithoutDevLicense"
958 try:
959 value, value_type = winreg.QueryValueEx(key, subkey)
960 finally:
961 winreg.CloseKey(key)
962 except OSError:
963 pass
964 else:
965 info_add('windows.developer_mode', "enabled" if value else "disabled")
966
967
968 def collect_fips(info_add):
969 try:
970 import _hashlib
971 except ImportError:
972 _hashlib = None
973
974 if _hashlib is not None:
975 call_func(info_add, 'fips.openssl_fips_mode', _hashlib, 'get_fips_mode')
976
977 try:
978 with open("/proc/sys/crypto/fips_enabled", encoding="utf-8") as fp:
979 line = fp.readline().rstrip()
980
981 if line:
982 info_add('fips.linux_crypto_fips_enabled', line)
983 except OSError:
984 pass
985
986
987 def collect_tempfile(info_add):
988 import tempfile
989
990 info_add('tempfile.gettempdir', tempfile.gettempdir())
991
992
993 def collect_libregrtest_utils(info_add):
994 try:
995 from test.libregrtest import utils
996 except ImportError:
997 return
998
999 info_add('libregrtests.build_info', ' '.join(utils.get_build_info()))
1000
1001
1002 def collect_info(info):
1003 error = False
1004 info_add = info.add
1005
1006 for collect_func in (
1007 # collect_urandom() must be the first, to check the getrandom() status.
1008 # Other functions may block on os.urandom() indirectly and so change
1009 # its state.
1010 collect_urandom,
1011
1012 collect_builtins,
1013 collect_cc,
1014 collect_curses,
1015 collect_datetime,
1016 collect_decimal,
1017 collect_expat,
1018 collect_fips,
1019 collect_gdb,
1020 collect_gdbm,
1021 collect_get_config,
1022 collect_locale,
1023 collect_os,
1024 collect_platform,
1025 collect_pwd,
1026 collect_readline,
1027 collect_resource,
1028 collect_socket,
1029 collect_sqlite,
1030 collect_ssl,
1031 collect_subprocess,
1032 collect_sys,
1033 collect_sysconfig,
1034 collect_testcapi,
1035 collect_testinternalcapi,
1036 collect_tempfile,
1037 collect_time,
1038 collect_tkinter,
1039 collect_windows,
1040 collect_zlib,
1041 collect_libregrtest_utils,
1042
1043 # Collecting from tests should be last as they have side effects.
1044 collect_test_socket,
1045 collect_support,
1046 collect_support_os_helper,
1047 collect_support_socket_helper,
1048 collect_support_threading_helper,
1049 ):
1050 try:
1051 collect_func(info_add)
1052 except Exception:
1053 error = True
1054 print("ERROR: %s() failed" % (collect_func.__name__),
1055 file=sys.stderr)
1056 traceback.print_exc(file=sys.stderr)
1057 print(file=sys.stderr)
1058 sys.stderr.flush()
1059
1060 return error
1061
1062
1063 def dump_info(info, file=None):
1064 title = "Python debug information"
1065 print(title)
1066 print("=" * len(title))
1067 print()
1068
1069 infos = info.get_infos()
1070 infos = sorted(infos.items())
1071 for key, value in infos:
1072 value = value.replace("\n", " ")
1073 print("%s: %s" % (key, value))
1074
1075
1076 def main():
1077 info = PythonInfo()
1078 error = collect_info(info)
1079 dump_info(info)
1080
1081 if error:
1082 print()
1083 print("Collection failed: exit with error", file=sys.stderr)
1084 sys.exit(1)
1085
1086
1087 if __name__ == "__main__":
1088 main()