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