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[..., object] | 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 else:
470 tmp_dir = tempfile.gettempdir()
471
472 return os.path.abspath(tmp_dir)
473
474
475 def fix_umask() -> None:
476 if support.is_emscripten:
477 # Emscripten has default umask 0o777, which breaks some tests.
478 # see https://github.com/emscripten-core/emscripten/issues/17269
479 old_mask = os.umask(0)
480 if old_mask == 0o777:
481 os.umask(0o027)
482 else:
483 os.umask(old_mask)
484
485
486 def get_work_dir(parent_dir: StrPath, worker: bool = False) -> StrPath:
487 # Define a writable temp dir that will be used as cwd while running
488 # the tests. The name of the dir includes the pid to allow parallel
489 # testing (see the -j option).
490 # Emscripten and WASI have stubbed getpid(), Emscripten has only
491 # millisecond clock resolution. Use randint() instead.
492 if support.is_emscripten or support.is_wasi:
493 nounce = random.randint(0, 1_000_000)
494 else:
495 nounce = os.getpid()
496
497 if worker:
498 work_dir = WORK_DIR_PREFIX + str(nounce)
499 else:
500 work_dir = WORKER_WORK_DIR_PREFIX + str(nounce)
501 work_dir += os_helper.FS_NONASCII
502 work_dir = os.path.join(parent_dir, work_dir)
503 return work_dir
504
505
506 @contextlib.contextmanager
507 def exit_timeout():
508 try:
509 yield
510 except SystemExit as exc:
511 # bpo-38203: Python can hang at exit in Py_Finalize(), especially
512 # on threading._shutdown() call: put a timeout
513 if threading_helper.can_start_thread:
514 faulthandler.dump_traceback_later(EXIT_TIMEOUT, exit=True)
515 sys.exit(exc.code)
516
517
518 def remove_testfn(test_name: TestName, verbose: int) -> None:
519 # Try to clean up os_helper.TESTFN if left behind.
520 #
521 # While tests shouldn't leave any files or directories behind, when a test
522 # fails that can be tedious for it to arrange. The consequences can be
523 # especially nasty on Windows, since if a test leaves a file open, it
524 # cannot be deleted by name (while there's nothing we can do about that
525 # here either, we can display the name of the offending test, which is a
526 # real help).
527 name = os_helper.TESTFN
528 if not os.path.exists(name):
529 return
530
531 nuker: Callable[[str], None]
532 if os.path.isdir(name):
533 import shutil
534 kind, nuker = "directory", shutil.rmtree
535 elif os.path.isfile(name):
536 kind, nuker = "file", os.unlink
537 else:
538 raise RuntimeError(f"os.path says {name!r} exists but is neither "
539 f"directory nor file")
540
541 if verbose:
542 print_warning(f"{test_name} left behind {kind} {name!r}")
543 support.environment_altered = True
544
545 try:
546 import stat
547 # fix possible permissions problems that might prevent cleanup
548 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
549 nuker(name)
550 except Exception as exc:
551 print_warning(f"{test_name} left behind {kind} {name!r} "
552 f"and it couldn't be removed: {exc}")
553
554
555 def abs_module_name(test_name: TestName, test_dir: StrPath | None) -> TestName:
556 if test_name.startswith('test.') or test_dir:
557 return test_name
558 else:
559 # Import it from the test package
560 return 'test.' + test_name
561
562
563 # gh-90681: When rerunning tests, we might need to rerun the whole
564 # class or module suite if some its life-cycle hooks fail.
565 # Test level hooks are not affected.
566 _TEST_LIFECYCLE_HOOKS = frozenset((
567 'setUpClass', 'tearDownClass',
568 'setUpModule', 'tearDownModule',
569 ))
570
571 def normalize_test_name(test_full_name: str, *,
572 is_error: bool = False) -> str | None:
573 short_name = test_full_name.split(" ")[0]
574 if is_error and short_name in _TEST_LIFECYCLE_HOOKS:
575 if test_full_name.startswith(('setUpModule (', 'tearDownModule (')):
576 # if setUpModule() or tearDownModule() failed, don't filter
577 # tests with the test file name, don't use filters.
578 return None
579
580 # This means that we have a failure in a life-cycle hook,
581 # we need to rerun the whole module or class suite.
582 # Basically the error looks like this:
583 # ERROR: setUpClass (test.test_reg_ex.RegTest)
584 # or
585 # ERROR: setUpModule (test.test_reg_ex)
586 # So, we need to parse the class / module name.
587 lpar = test_full_name.index('(')
588 rpar = test_full_name.index(')')
589 return test_full_name[lpar + 1: rpar].split('.')[-1]
590 return short_name
591
592
593 def adjust_rlimit_nofile() -> None:
594 """
595 On macOS the default fd limit (RLIMIT_NOFILE) is sometimes too low (256)
596 for our test suite to succeed. Raise it to something more reasonable. 1024
597 is a common Linux default.
598 """
599 try:
600 import resource
601 except ImportError:
602 return
603
604 fd_limit, max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)
605
606 desired_fds = 1024
607
608 if fd_limit < desired_fds and fd_limit < max_fds:
609 new_fd_limit = min(desired_fds, max_fds)
610 try:
611 resource.setrlimit(resource.RLIMIT_NOFILE,
612 (new_fd_limit, max_fds))
613 print(f"Raised RLIMIT_NOFILE: {fd_limit} -> {new_fd_limit}")
614 except (ValueError, OSError) as err:
615 print_warning(f"Unable to raise RLIMIT_NOFILE from {fd_limit} to "
616 f"{new_fd_limit}: {err}.")
617
618
619 def get_host_runner() -> str:
620 if (hostrunner := os.environ.get("_PYTHON_HOSTRUNNER")) is None:
621 hostrunner = sysconfig.get_config_var("HOSTRUNNER")
622 return hostrunner
623
624
625 def is_cross_compiled() -> bool:
626 return ('_PYTHON_HOST_PLATFORM' in os.environ)
627
628
629 def format_resources(use_resources: dict[str, str | None]) -> str:
630 all_resources = set(ALL_RESOURCES)
631
632 values = []
633 for name in sorted(use_resources):
634 if use_resources[name] is not None:
635 values.append(f'{name}={use_resources[name]}')
636
637 # Express resources relative to "all"
638 relative_all = ['all']
639 for name in sorted(all_resources - set(use_resources)):
640 relative_all.append(f'-{name}')
641 for name in sorted(set(use_resources) - all_resources):
642 if use_resources[name] is None:
643 relative_all.append(name)
644 all_text = ','.join(relative_all + values)
645 all_text = f"resources: {all_text}"
646
647 # List of enabled resources
648 resources = []
649 for name in sorted(use_resources):
650 if use_resources[name] is None:
651 resources.append(name)
652 text = ','.join(resources + values)
653 text = f"resources ({len(use_resources)}): {text}"
654
655 # Pick the shortest string (prefer relative to all if lengths are equal)
656 if len(all_text) <= len(text):
657 return all_text
658 else:
659 return text
660
661
662 def display_header(use_resources: dict[str, str | None],
663 python_cmd: tuple[str, ...] | None) -> None:
664 # Print basic platform information
665 print("==", platform.python_implementation(), *sys.version.split())
666 print("==", platform.platform(aliased=True),
667 "%s-endian" % sys.byteorder)
668 print("== Python build:", ' '.join(get_build_info()))
669 print("== cwd:", os.getcwd())
670
671 cpu_count: object = os.cpu_count()
672 if cpu_count:
673 # The function is new in Python 3.13; mypy doesn't know about it yet:
674 process_cpu_count = os.process_cpu_count() # type: ignore[attr-defined]
675 if process_cpu_count and process_cpu_count != cpu_count:
676 cpu_count = f"{process_cpu_count} (process) / {cpu_count} (system)"
677 print("== CPU count:", cpu_count)
678 print("== encodings: locale=%s FS=%s"
679 % (locale.getencoding(), sys.getfilesystemencoding()))
680
681 if use_resources:
682 text = format_resources(use_resources)
683 print(f"== {text}")
684 else:
685 print("== resources: all test resources are disabled, "
686 "use -u option to unskip tests")
687
688 cross_compile = is_cross_compiled()
689 if cross_compile:
690 print("== cross compiled: Yes")
691 if python_cmd:
692 cmd = shlex.join(python_cmd)
693 print(f"== host python: {cmd}")
694
695 get_cmd = [*python_cmd, '-m', 'platform']
696 proc = subprocess.run(
697 get_cmd,
698 stdout=subprocess.PIPE,
699 text=True,
700 cwd=os_helper.SAVEDCWD)
701 stdout = proc.stdout.replace('\n', ' ').strip()
702 if stdout:
703 print(f"== host platform: {stdout}")
704 elif proc.returncode:
705 print(f"== host platform: <command failed with exit code {proc.returncode}>")
706 else:
707 hostrunner = get_host_runner()
708 if hostrunner:
709 print(f"== host runner: {hostrunner}")
710
711 # This makes it easier to remember what to set in your local
712 # environment when trying to reproduce a sanitizer failure.
713 asan = support.check_sanitizer(address=True)
714 msan = support.check_sanitizer(memory=True)
715 ubsan = support.check_sanitizer(ub=True)
716 tsan = support.check_sanitizer(thread=True)
717 sanitizers = []
718 if asan:
719 sanitizers.append("address")
720 if msan:
721 sanitizers.append("memory")
722 if ubsan:
723 sanitizers.append("undefined behavior")
724 if tsan:
725 sanitizers.append("thread")
726 if sanitizers:
727 print(f"== sanitizers: {', '.join(sanitizers)}")
728 for sanitizer, env_var in (
729 (asan, "ASAN_OPTIONS"),
730 (msan, "MSAN_OPTIONS"),
731 (ubsan, "UBSAN_OPTIONS"),
732 (tsan, "TSAN_OPTIONS"),
733 ):
734 options= os.environ.get(env_var)
735 if sanitizer and options is not None:
736 print(f"== {env_var}={options!r}")
737
738 print(flush=True)
739
740
741 def cleanup_temp_dir(tmp_dir: StrPath) -> None:
742 import glob
743
744 path = os.path.join(glob.escape(tmp_dir), TMP_PREFIX + '*')
745 print("Cleanup %s directory" % tmp_dir)
746 for name in glob.glob(path):
747 if os.path.isdir(name):
748 print("Remove directory: %s" % name)
749 os_helper.rmtree(name)
750 else:
751 print("Remove file: %s" % name)
752 os_helper.unlink(name)
753
754 WINDOWS_STATUS = {
755 0xC0000005: "STATUS_ACCESS_VIOLATION",
756 0xC00000FD: "STATUS_STACK_OVERFLOW",
757 0xC000013A: "STATUS_CONTROL_C_EXIT",
758 }
759
760 def get_signal_name(exitcode):
761 if exitcode < 0:
762 signum = -exitcode
763 try:
764 return signal.Signals(signum).name
765 except ValueError:
766 pass
767
768 # Shell exit code (ex: WASI build)
769 if 128 < exitcode < 256:
770 signum = exitcode - 128
771 try:
772 return signal.Signals(signum).name
773 except ValueError:
774 pass
775
776 try:
777 return WINDOWS_STATUS[exitcode]
778 except KeyError:
779 pass
780
781 return None
782
783
784 ILLEGAL_XML_CHARS_RE = re.compile(
785 '['
786 # Control characters; newline (\x0A and \x0D) and TAB (\x09) are legal
787 '\x00-\x08\x0B\x0C\x0E-\x1F'
788 # Surrogate characters
789 '\uD800-\uDFFF'
790 # Special Unicode characters
791 '\uFFFE'
792 '\uFFFF'
793 # Match multiple sequential invalid characters for better efficiency
794 ']+')
795
796 def _sanitize_xml_replace(regs):
797 text = regs[0]
798 return ''.join(f'\\x{ord(ch):02x}' if ch <= '\xff' else ascii(ch)[1:-1]
799 for ch in text)
800
801 def sanitize_xml(text: str) -> str:
802 return ILLEGAL_XML_CHARS_RE.sub(_sanitize_xml_replace, text)