Debian Codegraph @

Lib/test/libregrtest/utils.py

raw
1 import contextlib
2 import faulthandler
3 import locale
4 import math
5 import os.path
6 import platform
7 import random
8 import re
9 import shlex
10 import signal
11 import subprocess
12 import sys
13 import sysconfig
14 import tempfile
15 import textwrap
16 from collections.abc import Callable
17
18 from test import support
19 from test.support import os_helper
20 from test.support import threading_helper
21
22
23 # All temporary files and temporary directories created by libregrtest should
24 # use TMP_PREFIX so cleanup_temp_dir() can remove them all.
25 TMP_PREFIX = 'test_python_'
26 WORK_DIR_PREFIX = TMP_PREFIX
27 WORKER_WORK_DIR_PREFIX = WORK_DIR_PREFIX + 'worker_'
28
29 # bpo-38203: Maximum delay in seconds to exit Python (call Py_Finalize()).
30 # Used to protect against threading._shutdown() hang.
31 # Must be smaller than buildbot "1200 seconds without output" limit.
32 EXIT_TIMEOUT = 120.0
33
34
35 ALL_RESOURCES = ('audio', 'console', 'curses', 'largefile', 'network',
36 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui', 'walltime')
37
38 # Other resources excluded from --use=all:
39 #
40 # - extralagefile (ex: test_zipfile64): really too slow to be enabled
41 # "by default"
42 # - tzdata: while needed to validate fully test_datetime, it makes
43 # test_datetime too slow (15-20 min on some buildbots) and so is disabled by
44 # default (see bpo-30822).
45 RESOURCE_NAMES = ALL_RESOURCES + ('extralargefile', 'tzdata', 'xpickle', 'wantobjects')
46
47
48 # Types for types hints
49 StrPath = str
50 TestName = str
51 StrJSON = str
52 TestTuple = tuple[TestName, ...]
53 TestList = list[TestName]
54 # --match and --ignore options: list of patterns
55 # ('*' joker character can be used)
56 TestFilter = list[tuple[TestName, bool]]
57 FilterTuple = tuple[TestName, ...]
58 FilterDict = dict[TestName, FilterTuple]
59
60
61 def format_duration(seconds: float) -> str:
62 ms = math.ceil(seconds * 1e3)
63 seconds, ms = divmod(ms, 1000)
64 minutes, seconds = divmod(seconds, 60)
65 hours, minutes = divmod(minutes, 60)
66
67 parts = []
68 if hours:
69 parts.append('%s hour' % hours)
70 if minutes:
71 parts.append('%s min' % minutes)
72 if seconds:
73 if parts:
74 # 2 min 1 sec
75 parts.append('%s sec' % seconds)
76 else:
77 # 1.0 sec
78 parts.append('%.1f sec' % (seconds + ms / 1000))
79 if not parts:
80 return '%s ms' % ms
81
82 parts = parts[:2]
83 return ' '.join(parts)
84
85
86 def strip_py_suffix(names: list[str] | None) -> None:
87 if not names:
88 return
89 for idx, name in enumerate(names):
90 basename, ext = os.path.splitext(name)
91 if ext == '.py':
92 names[idx] = basename
93
94
95 def plural(n: int, singular: str, plural: str | None = None) -> str:
96 if n == 1:
97 return singular
98 elif plural is not None:
99 return plural
100 else:
101 return singular + 's'
102
103
104 def count(n: int, word: str) -> str:
105 if n == 1:
106 return f"{n} {word}"
107 else:
108 return f"{n} {word}s"
109
110
111 def printlist(x, width=70, indent=4, file=None):
112 """Print the elements of iterable x to stdout.
113
114 Optional arg width (default 70) is the maximum line length.
115 Optional arg indent (default 4) is the number of blanks with which to
116 begin each line.
117 """
118
119 blanks = ' ' * indent
120 # Print the sorted list: 'x' may be a '--random' list or a set()
121 print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width,
122 initial_indent=blanks, subsequent_indent=blanks),
123 file=file)
124
125
126 def print_warning(msg: str) -> None:
127 support.print_warning(msg)
128
129
130 orig_unraisablehook: Callable[..., None] | None = None
131
132
133 def regrtest_unraisable_hook(unraisable) -> None:
134 global orig_unraisablehook
135 support.environment_altered = True
136 support.print_warning("Unraisable exception")
137 old_stderr = sys.stderr
138 try:
139 support.flush_std_streams()
140 sys.stderr = support.print_warning.orig_stderr
141 assert orig_unraisablehook is not None, "orig_unraisablehook not set"
142 orig_unraisablehook(unraisable)
143 sys.stderr.flush()
144 finally:
145 sys.stderr = old_stderr
146
147
148 def setup_unraisable_hook() -> None:
149 global orig_unraisablehook
150 orig_unraisablehook = sys.unraisablehook
151 sys.unraisablehook = regrtest_unraisable_hook
152
153
154 orig_threading_excepthook: Callable[..., None] | None = None
155
156
157 def regrtest_threading_excepthook(args) -> None:
158 global orig_threading_excepthook
159 support.environment_altered = True
160 support.print_warning(f"Uncaught thread exception: {args.exc_type.__name__}")
161 old_stderr = sys.stderr
162 try:
163 support.flush_std_streams()
164 sys.stderr = support.print_warning.orig_stderr
165 assert orig_threading_excepthook is not None, "orig_threading_excepthook not set"
166 orig_threading_excepthook(args)
167 sys.stderr.flush()
168 finally:
169 sys.stderr = old_stderr
170
171
172 def setup_threading_excepthook() -> None:
173 global orig_threading_excepthook
174 import threading
175 orig_threading_excepthook = threading.excepthook
176 threading.excepthook = regrtest_threading_excepthook
177
178
179 def clear_caches():
180 # Clear the warnings registry, so they can be displayed again
181 for mod in sys.modules.values():
182 if hasattr(mod, '__warningregistry__'):
183 del mod.__warningregistry__
184
185 # Flush standard output, so that buffered data is sent to the OS and
186 # associated Python objects are reclaimed.
187 for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
188 if stream is not None:
189 stream.flush()
190
191 try:
192 re = sys.modules['re']
193 except KeyError:
194 pass
195 else:
196 re.purge()
197
198 try:
199 _strptime = sys.modules['_strptime']
200 except KeyError:
201 pass
202 else:
203 _strptime._regex_cache.clear()
204
205 try:
206 urllib_parse = sys.modules['urllib.parse']
207 except KeyError:
208 pass
209 else:
210 urllib_parse.clear_cache()
211
212 try:
213 urllib_request = sys.modules['urllib.request']
214 except KeyError:
215 pass
216 else:
217 urllib_request.urlcleanup()
218
219 try:
220 linecache = sys.modules['linecache']
221 except KeyError:
222 pass
223 else:
224 linecache.clearcache()
225
226 try:
227 mimetypes = sys.modules['mimetypes']
228 except KeyError:
229 pass
230 else:
231 mimetypes._default_mime_types()
232
233 try:
234 filecmp = sys.modules['filecmp']
235 except KeyError:
236 pass
237 else:
238 filecmp._cache.clear()
239
240 try:
241 struct = sys.modules['struct']
242 except KeyError:
243 pass
244 else:
245 struct._clearcache()
246
247 try:
248 doctest = sys.modules['doctest']
249 except KeyError:
250 pass
251 else:
252 doctest.master = None
253
254 try:
255 ctypes = sys.modules['ctypes']
256 except KeyError:
257 pass
258 else:
259 ctypes._reset_cache()
260
261 try:
262 typing = sys.modules['typing']
263 except KeyError:
264 pass
265 else:
266 for f in typing._cleanups:
267 f()
268
269 import inspect
270 abs_classes = filter(inspect.isabstract, typing.__dict__.values())
271 for abc in abs_classes:
272 for obj in abc.__subclasses__() + [abc]:
273 obj._abc_caches_clear()
274
275 try:
276 fractions = sys.modules['fractions']
277 except KeyError:
278 pass
279 else:
280 fractions._hash_algorithm.cache_clear()
281
282 try:
283 inspect = sys.modules['inspect']
284 except KeyError:
285 pass
286 else:
287 inspect._shadowed_dict_from_weakref_mro_tuple.cache_clear()
288 inspect._filesbymodname.clear()
289 inspect.modulesbyfile.clear()
290
291 try:
292 importlib_metadata = sys.modules['importlib.metadata']
293 except KeyError:
294 pass
295 else:
296 importlib_metadata.FastPath.__new__.cache_clear()
297
298
299 def get_build_info():
300 # Get most important configure and build options as a list of strings.
301 # Example: ['debug', 'ASAN+MSAN'] or ['release', 'LTO+PGO'].
302
303 config_args = sysconfig.get_config_var('CONFIG_ARGS') or ''
304 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
305 cflags += ' ' + (sysconfig.get_config_var('PY_CFLAGS_NODIST') or '')
306 ldflags_nodist = sysconfig.get_config_var('PY_LDFLAGS_NODIST') or ''
307
308 build = []
309
310 # --disable-gil
311 if sysconfig.get_config_var('Py_GIL_DISABLED'):
312 if not sys.flags.ignore_environment:
313 PYTHON_GIL = os.environ.get('PYTHON_GIL', None)
314 if PYTHON_GIL:
315 PYTHON_GIL = (PYTHON_GIL == '1')
316 else:
317 PYTHON_GIL = None
318
319 free_threading = "free_threading"
320 if PYTHON_GIL is not None:
321 free_threading = f"{free_threading} GIL={int(PYTHON_GIL)}"
322 build.append(free_threading)
323
324 if hasattr(sys, 'gettotalrefcount'):
325 # --with-pydebug
326 build.append('debug')
327
328 if '-DNDEBUG' in cflags:
329 build.append('without_assert')
330 else:
331 build.append('release')
332
333 if '--with-assertions' in config_args:
334 build.append('with_assert')
335 elif '-DNDEBUG' not in cflags:
336 build.append('with_assert')
337
338 # --enable-experimental-jit
339 tier2 = re.search('-D_Py_TIER2=([0-9]+)', cflags)
340 if tier2:
341 tier2 = int(tier2.group(1))
342
343 if not sys.flags.ignore_environment:
344 PYTHON_JIT = os.environ.get('PYTHON_JIT', None)
345 if PYTHON_JIT:
346 PYTHON_JIT = (PYTHON_JIT != '0')
347 else:
348 PYTHON_JIT = None
349
350 if tier2 == 1: # =yes
351 if PYTHON_JIT == False:
352 jit = 'JIT=off'
353 else:
354 jit = 'JIT'
355 elif tier2 == 3: # =yes-off
356 if PYTHON_JIT:
357 jit = 'JIT'
358 else:
359 jit = 'JIT=off'
360 elif tier2 == 4: # =interpreter
361 if PYTHON_JIT == False:
362 jit = 'JIT-interpreter=off'
363 else:
364 jit = 'JIT-interpreter'
365 elif tier2 == 6: # =interpreter-off (Secret option!)
366 if PYTHON_JIT:
367 jit = 'JIT-interpreter'
368 else:
369 jit = 'JIT-interpreter=off'
370 elif '-D_Py_JIT' in cflags:
371 jit = 'JIT'
372 else:
373 jit = None
374 if jit:
375 build.append(jit)
376
377 # --enable-framework=name
378 framework = sysconfig.get_config_var('PYTHONFRAMEWORK')
379 if framework:
380 build.append(f'framework={framework}')
381
382 # --enable-shared
383 shared = int(sysconfig.get_config_var('PY_ENABLE_SHARED') or '0')
384 if shared:
385 build.append('shared')
386
387 # --with-lto
388 optimizations = []
389 if '-flto=thin' in ldflags_nodist:
390 optimizations.append('ThinLTO')
391 elif '-flto' in ldflags_nodist:
392 optimizations.append('LTO')
393
394 if support.check_cflags_pgo():
395 # PGO (--enable-optimizations)
396 optimizations.append('PGO')
397
398 if support.check_bolt_optimized():
399 # BOLT (--enable-bolt)
400 optimizations.append('BOLT')
401
402 if optimizations:
403 build.append('+'.join(optimizations))
404
405 # --with-address-sanitizer
406 sanitizers = []
407 if support.check_sanitizer(address=True):
408 sanitizers.append("ASAN")
409 # --with-memory-sanitizer
410 if support.check_sanitizer(memory=True):
411 sanitizers.append("MSAN")
412 # --with-undefined-behavior-sanitizer
413 if support.check_sanitizer(ub=True):
414 sanitizers.append("UBSAN")
415 # --with-thread-sanitizer
416 if support.check_sanitizer(thread=True):
417 sanitizers.append("TSAN")
418 if sanitizers:
419 build.append('+'.join(sanitizers))
420
421 # --with-trace-refs
422 if hasattr(sys, 'getobjects'):
423 build.append("TraceRefs")
424 # --enable-pystats
425 if hasattr(sys, '_stats_on'):
426 build.append("pystats")
427 # --with-valgrind
428 if sysconfig.get_config_var('WITH_VALGRIND'):
429 build.append("valgrind")
430 # --with-dtrace
431 if sysconfig.get_config_var('WITH_DTRACE'):
432 build.append("dtrace")
433
434 return build
435
436
437 def get_temp_dir(tmp_dir: StrPath | None = None) -> StrPath:
438 if tmp_dir:
439 tmp_dir = os.path.expanduser(tmp_dir)
440 else:
441 # When tests are run from the Python build directory, it is best practice
442 # to keep the test files in a subfolder. This eases the cleanup of leftover
443 # files using the "make distclean" command.
444 if sysconfig.is_python_build():
445 if not support.is_wasi:
446 tmp_dir = sysconfig.get_config_var('abs_builddir')
447 if tmp_dir is None:
448 tmp_dir = sysconfig.get_config_var('abs_srcdir')
449 if not tmp_dir:
450 # gh-74470: On Windows, only srcdir is available. Using
451 # abs_builddir mostly matters on UNIX when building
452 # Python out of the source tree, especially when the
453 # source tree is read only.
454 tmp_dir = sysconfig.get_config_var('srcdir')
455 if not tmp_dir:
456 raise RuntimeError(
457 "Could not determine the correct value for tmp_dir"
458 )
459 tmp_dir = os.path.join(tmp_dir, 'build')
460 else:
461 # WASI platform
462 tmp_dir = sysconfig.get_config_var('projectbase')
463 if not tmp_dir:
464 raise RuntimeError(
465 "sysconfig.get_config_var('projectbase') "
466 f"unexpectedly returned {tmp_dir!r} on WASI"
467 )
468 tmp_dir = os.path.join(tmp_dir, 'build')
469
470 # When get_temp_dir() is called in a worker process,
471 # get_temp_dir() path is different than in the parent process
472 # which is not a WASI process. So the parent does not create
473 # the same "tmp_dir" than the test worker process.
474 os.makedirs(tmp_dir, exist_ok=True)
475 else:
476 tmp_dir = tempfile.gettempdir()
477
478 return os.path.abspath(tmp_dir)
479
480
481 def fix_umask() -> None:
482 if support.is_emscripten:
483 # Emscripten has default umask 0o777, which breaks some tests.
484 # see https://github.com/emscripten-core/emscripten/issues/17269
485 old_mask = os.umask(0)
486 if old_mask == 0o777:
487 os.umask(0o027)
488 else:
489 os.umask(old_mask)
490
491
492 def get_work_dir(parent_dir: StrPath, worker: bool = False) -> StrPath:
493 # Define a writable temp dir that will be used as cwd while running
494 # the tests. The name of the dir includes the pid to allow parallel
495 # testing (see the -j option).
496 # Emscripten and WASI have stubbed getpid(), Emscripten has only
497 # millisecond clock resolution. Use randint() instead.
498 if support.is_emscripten or support.is_wasi:
499 nounce = random.randint(0, 1_000_000)
500 else:
501 nounce = os.getpid()
502
503 if worker:
504 work_dir = WORK_DIR_PREFIX + str(nounce)
505 else:
506 work_dir = WORKER_WORK_DIR_PREFIX + str(nounce)
507 work_dir += os_helper.FS_NONASCII
508 work_dir = os.path.join(parent_dir, work_dir)
509 return work_dir
510
511
512 @contextlib.contextmanager
513 def exit_timeout():
514 try:
515 yield
516 except SystemExit as exc:
517 # bpo-38203: Python can hang at exit in Py_Finalize(), especially
518 # on threading._shutdown() call: put a timeout
519 if threading_helper.can_start_thread:
520 faulthandler.dump_traceback_later(EXIT_TIMEOUT, exit=True)
521 sys.exit(exc.code)
522
523
524 def remove_testfn(test_name: TestName, verbose: int) -> None:
525 # Try to clean up os_helper.TESTFN if left behind.
526 #
527 # While tests shouldn't leave any files or directories behind, when a test
528 # fails that can be tedious for it to arrange. The consequences can be
529 # especially nasty on Windows, since if a test leaves a file open, it
530 # cannot be deleted by name (while there's nothing we can do about that
531 # here either, we can display the name of the offending test, which is a
532 # real help).
533 name = os_helper.TESTFN
534 if not os.path.exists(name):
535 return
536
537 nuker: Callable[[str], None]
538 if os.path.isdir(name):
539 import shutil
540 kind, nuker = "directory", shutil.rmtree
541 elif os.path.isfile(name):
542 kind, nuker = "file", os.unlink
543 else:
544 raise RuntimeError(f"os.path says {name!r} exists but is neither "
545 f"directory nor file")
546
547 if verbose:
548 print_warning(f"{test_name} left behind {kind} {name!r}")
549 support.environment_altered = True
550
551 try:
552 import stat
553 # fix possible permissions problems that might prevent cleanup
554 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
555 nuker(name)
556 except Exception as exc:
557 print_warning(f"{test_name} left behind {kind} {name!r} "
558 f"and it couldn't be removed: {exc}")
559
560
561 def abs_module_name(test_name: TestName, test_dir: StrPath | None) -> TestName:
562 if test_name.startswith('test.') or test_dir:
563 return test_name
564 else:
565 # Import it from the test package
566 return 'test.' + test_name
567
568
569 # gh-90681: When rerunning tests, we might need to rerun the whole
570 # class or module suite if some its life-cycle hooks fail.
571 # Test level hooks are not affected.
572 _TEST_LIFECYCLE_HOOKS = frozenset((
573 'setUpClass', 'tearDownClass',
574 'setUpModule', 'tearDownModule',
575 ))
576
577 def normalize_test_name(test_full_name: str, *,
578 is_error: bool = False) -> str | None:
579 short_name = test_full_name.split(" ")[0]
580 if is_error and short_name in _TEST_LIFECYCLE_HOOKS:
581 if test_full_name.startswith(('setUpModule (', 'tearDownModule (')):
582 # if setUpModule() or tearDownModule() failed, don't filter
583 # tests with the test file name, don't use filters.
584 return None
585
586 # This means that we have a failure in a life-cycle hook,
587 # we need to rerun the whole module or class suite.
588 # Basically the error looks like this:
589 # ERROR: setUpClass (test.test_reg_ex.RegTest)
590 # or
591 # ERROR: setUpModule (test.test_reg_ex)
592 # So, we need to parse the class / module name.
593 lpar = test_full_name.index('(')
594 rpar = test_full_name.index(')')
595 return test_full_name[lpar + 1: rpar].split('.')[-1]
596 return short_name
597
598
599 def adjust_rlimit_nofile() -> None:
600 """
601 On macOS the default fd limit (RLIMIT_NOFILE) is sometimes too low (256)
602 for our test suite to succeed. Raise it to something more reasonable. 1024
603 is a common Linux default.
604 """
605 try:
606 import resource
607 except ImportError:
608 return
609
610 fd_limit, max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)
611
612 desired_fds = 1024
613
614 if fd_limit < desired_fds and fd_limit < max_fds:
615 new_fd_limit = min(desired_fds, max_fds)
616 try:
617 resource.setrlimit(resource.RLIMIT_NOFILE,
618 (new_fd_limit, max_fds))
619 print(f"Raised RLIMIT_NOFILE: {fd_limit} -> {new_fd_limit}")
620 except (ValueError, OSError) as err:
621 print_warning(f"Unable to raise RLIMIT_NOFILE from {fd_limit} to "
622 f"{new_fd_limit}: {err}.")
623
624
625 def get_host_runner() -> str:
626 if (hostrunner := os.environ.get("_PYTHON_HOSTRUNNER")) is None:
627 hostrunner = sysconfig.get_config_var("HOSTRUNNER")
628 return hostrunner
629
630
631 def is_cross_compiled() -> bool:
632 return ('_PYTHON_HOST_PLATFORM' in os.environ)
633
634
635 def format_resources(use_resources: dict[str, str | None]) -> str:
636 all_resources = set(ALL_RESOURCES)
637
638 values = []
639 for name in sorted(use_resources):
640 if use_resources[name] is not None:
641 values.append(f'{name}={use_resources[name]}')
642
643 # Express resources relative to "all"
644 relative_all = ['all']
645 for name in sorted(all_resources - set(use_resources)):
646 relative_all.append(f'-{name}')
647 for name in sorted(set(use_resources) - all_resources):
648 if use_resources[name] is None:
649 relative_all.append(name)
650 all_text = ','.join(relative_all + values)
651 all_text = f"resources: {all_text}"
652
653 # List of enabled resources
654 resources = []
655 for name in sorted(use_resources):
656 if use_resources[name] is None:
657 resources.append(name)
658 text = ','.join(resources + values)
659 text = f"resources ({len(use_resources)}): {text}"
660
661 # Pick the shortest string (prefer relative to all if lengths are equal)
662 if len(all_text) <= len(text):
663 return all_text
664 else:
665 return text
666
667
668 def display_header(use_resources: dict[str, str | None],
669 python_cmd: tuple[str, ...] | None) -> None:
670 # Print basic platform information
671 print("==", platform.python_implementation(), *sys.version.split())
672 print("==", platform.platform(aliased=True),
673 "%s-endian" % sys.byteorder)
674 print("== Python build:", ' '.join(get_build_info()))
675 print("== cwd:", os.getcwd())
676
677 cpu_count: object = os.cpu_count()
678 if cpu_count:
679 # The function is new in Python 3.13; mypy doesn't know about it yet:
680 process_cpu_count = os.process_cpu_count() # type: ignore[attr-defined]
681 if process_cpu_count and process_cpu_count != cpu_count:
682 cpu_count = f"{process_cpu_count} (process) / {cpu_count} (system)"
683 print("== CPU count:", cpu_count)
684 print("== encodings: locale=%s FS=%s"
685 % (locale.getencoding(), sys.getfilesystemencoding()))
686
687 if use_resources:
688 text = format_resources(use_resources)
689 print(f"== {text}")
690 else:
691 print("== resources: all test resources are disabled, "
692 "use -u option to unskip tests")
693
694 cross_compile = is_cross_compiled()
695 if cross_compile:
696 print("== cross compiled: Yes")
697 if python_cmd:
698 cmd = shlex.join(python_cmd)
699 print(f"== host python: {cmd}")
700
701 get_cmd = [*python_cmd, '-m', 'platform']
702 proc = subprocess.run(
703 get_cmd,
704 stdout=subprocess.PIPE,
705 text=True,
706 cwd=os_helper.SAVEDCWD)
707 stdout = proc.stdout.replace('\n', ' ').strip()
708 if stdout:
709 print(f"== host platform: {stdout}")
710 elif proc.returncode:
711 print(f"== host platform: <command failed with exit code {proc.returncode}>")
712 else:
713 hostrunner = get_host_runner()
714 if hostrunner:
715 print(f"== host runner: {hostrunner}")
716
717 # This makes it easier to remember what to set in your local
718 # environment when trying to reproduce a sanitizer failure.
719 asan = support.check_sanitizer(address=True)
720 msan = support.check_sanitizer(memory=True)
721 ubsan = support.check_sanitizer(ub=True)
722 tsan = support.check_sanitizer(thread=True)
723 sanitizers = []
724 if asan:
725 sanitizers.append("address")
726 if msan:
727 sanitizers.append("memory")
728 if ubsan:
729 sanitizers.append("undefined behavior")
730 if tsan:
731 sanitizers.append("thread")
732 if sanitizers:
733 print(f"== sanitizers: {', '.join(sanitizers)}")
734 for sanitizer, env_var in (
735 (asan, "ASAN_OPTIONS"),
736 (msan, "MSAN_OPTIONS"),
737 (ubsan, "UBSAN_OPTIONS"),
738 (tsan, "TSAN_OPTIONS"),
739 ):
740 options= os.environ.get(env_var)
741 if sanitizer and options is not None:
742 print(f"== {env_var}={options!r}")
743
744 print(flush=True)
745
746
747 def cleanup_temp_dir(tmp_dir: StrPath) -> None:
748 import glob
749
750 path = os.path.join(glob.escape(tmp_dir), TMP_PREFIX + '*')
751 print("Cleanup %s directory" % tmp_dir)
752 for name in glob.glob(path):
753 if os.path.isdir(name):
754 print("Remove directory: %s" % name)
755 os_helper.rmtree(name)
756 else:
757 print("Remove file: %s" % name)
758 os_helper.unlink(name)
759
760 WINDOWS_STATUS = {
761 0xC0000005: "STATUS_ACCESS_VIOLATION",
762 0xC00000FD: "STATUS_STACK_OVERFLOW",
763 0xC000013A: "STATUS_CONTROL_C_EXIT",
764 }
765
766 def get_signal_name(exitcode):
767 if exitcode < 0:
768 signum = -exitcode
769 try:
770 return signal.Signals(signum).name
771 except ValueError:
772 pass
773
774 # Shell exit code (ex: WASI build)
775 if 128 < exitcode < 256:
776 signum = exitcode - 128
777 try:
778 return signal.Signals(signum).name
779 except ValueError:
780 pass
781
782 try:
783 return WINDOWS_STATUS[exitcode]
784 except KeyError:
785 pass
786
787 return None
788
789
790 ILLEGAL_XML_CHARS_RE = re.compile(
791 '['
792 # Control characters; newline (\x0A and \x0D) and TAB (\x09) are legal
793 '\x00-\x08\x0B\x0C\x0E-\x1F'
794 # Surrogate characters
795 '\uD800-\uDFFF'
796 # Special Unicode characters
797 '\uFFFE'
798 '\uFFFF'
799 # Match multiple sequential invalid characters for better efficiency
800 ']+')
801
802 def _sanitize_xml_replace(regs):
803 text = regs[0]
804 return ''.join(f'\\x{ord(ch):02x}' if ch <= '\xff' else ascii(ch)[1:-1]
805 for ch in text)
806
807 def sanitize_xml(text: str) -> str:
808 return ILLEGAL_XML_CHARS_RE.sub(_sanitize_xml_replace, text)