Debian Codegraph @

Lib/test/pythoninfo.py

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