Debian Codegraph @

Tools/build/check_extension_modules.py

raw
1 """Check extension modules
2
3 The script checks shared and built-in extension modules. It verifies that the
4 modules have been built and that they can be imported successfully. Missing
5 modules and failed imports are reported to the user. Shared extension
6 files are renamed on failed import.
7
8 Module information is parsed from several sources:
9
10 - core modules hard-coded in Modules/config.c.in
11 - Windows-specific modules that are hard-coded in PC/config.c
12 - MODULE_{name}_STATE entries in Makefile (provided through sysconfig)
13 - Various makesetup files:
14 - $(srcdir)/Modules/Setup
15 - Modules/Setup.[local|bootstrap|stdlib] files, which are generated
16 from $(srcdir)/Modules/Setup.*.in files
17
18 See --help for more information
19 """
20
21 from __future__ import annotations
22
23 import _imp
24 import argparse
25 import enum
26 import logging
27 import os
28 import pathlib
29 import re
30 import sys
31 import sysconfig
32 import warnings
33
34 from collections.abc import Iterable
35 from importlib._bootstrap import _load as bootstrap_load # type: ignore[attr-defined]
36 from importlib.machinery import BuiltinImporter, ExtensionFileLoader, ModuleSpec
37 from importlib.util import spec_from_file_location, spec_from_loader
38 from typing import NamedTuple
39
40 SRC_DIR = pathlib.Path(__file__).parent.parent.parent
41
42 # core modules, hard-coded in Modules/config.h.in
43 CORE_MODULES = {
44 "_ast",
45 "_imp",
46 "_string",
47 "_tokenize",
48 "_warnings",
49 "builtins",
50 "gc",
51 "marshal",
52 "sys",
53 }
54
55 # Windows-only modules
56 WINDOWS_MODULES = {
57 "_overlapped",
58 "_testconsole",
59 "_winapi",
60 "_wmi",
61 "msvcrt",
62 "nt",
63 "winreg",
64 "winsound",
65 }
66
67
68 logger = logging.getLogger(__name__)
69
70 parser = argparse.ArgumentParser(
71 prog="check_extension_modules",
72 description=__doc__,
73 formatter_class=argparse.RawDescriptionHelpFormatter,
74 )
75
76 parser.add_argument(
77 "--verbose",
78 action="store_true",
79 help="Verbose, report builtin, shared, and unavailable modules",
80 )
81
82 parser.add_argument(
83 "--debug",
84 action="store_true",
85 help="Enable debug logging",
86 )
87
88 parser.add_argument(
89 "--strict",
90 action=argparse.BooleanOptionalAction,
91 help=(
92 "Strict check, fail when a module is missing or fails to import"
93 "(default: no, unless env var PYTHONSTRICTEXTENSIONBUILD is set)"
94 ),
95 default=bool(os.environ.get("PYTHONSTRICTEXTENSIONBUILD")),
96 )
97
98 parser.add_argument(
99 "--cross-compiling",
100 action=argparse.BooleanOptionalAction,
101 help=(
102 "Use cross-compiling checks "
103 "(default: no, unless env var _PYTHON_HOST_PLATFORM is set)."
104 ),
105 default="_PYTHON_HOST_PLATFORM" in os.environ,
106 )
107
108 parser.add_argument(
109 "--list-module-names",
110 action="store_true",
111 help="Print a list of module names to stdout and exit",
112 )
113
114
115 @enum.unique
116 class ModuleState(enum.Enum):
117 # Makefile state "yes"
118 BUILTIN = "builtin"
119 SHARED = "shared"
120
121 DISABLED = "disabled"
122 MISSING = "missing"
123 NA = "n/a"
124 # disabled by Setup / makesetup rule
125 DISABLED_SETUP = "disabled_setup"
126
127 def __bool__(self) -> bool:
128 return self.value in {"builtin", "shared"}
129
130
131 class ModuleInfo(NamedTuple):
132 name: str
133 state: ModuleState
134
135
136 class ModuleChecker:
137 pybuilddir_txt = "pybuilddir.txt"
138
139 setup_files = (
140 # see end of configure.ac
141 pathlib.Path("Modules/Setup.local"),
142 pathlib.Path("Modules/Setup.stdlib"),
143 pathlib.Path("Modules/Setup.bootstrap"),
144 SRC_DIR / "Modules/Setup",
145 )
146
147 def __init__(self, cross_compiling: bool = False, strict: bool = False):
148 self.cross_compiling = cross_compiling
149 self.strict_extensions_build = strict
150 self.ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
151 self.platform = sysconfig.get_platform()
152 self.builddir = self.get_builddir()
153 self.modules = self.get_modules()
154
155 self.builtin_ok: list[ModuleInfo] = []
156 self.shared_ok: list[ModuleInfo] = []
157 self.failed_on_import: list[ModuleInfo] = []
158 self.missing: list[ModuleInfo] = []
159 self.disabled_configure: list[ModuleInfo] = []
160 self.disabled_setup: list[ModuleInfo] = []
161 self.notavailable: list[ModuleInfo] = []
162
163 def check(self) -> None:
164 if not hasattr(_imp, 'create_dynamic'):
165 logger.warning(
166 ('Dynamic extensions not supported '
167 '(HAVE_DYNAMIC_LOADING not defined)'),
168 )
169 for modinfo in self.modules:
170 logger.debug("Checking '%s' (%s)", modinfo.name, self.get_location(modinfo))
171 if modinfo.state == ModuleState.DISABLED:
172 self.disabled_configure.append(modinfo)
173 elif modinfo.state == ModuleState.DISABLED_SETUP:
174 self.disabled_setup.append(modinfo)
175 elif modinfo.state == ModuleState.MISSING:
176 self.missing.append(modinfo)
177 elif modinfo.state == ModuleState.NA:
178 self.notavailable.append(modinfo)
179 else:
180 try:
181 if self.cross_compiling:
182 self.check_module_cross(modinfo)
183 else:
184 self.check_module_import(modinfo)
185 except (ImportError, FileNotFoundError):
186 self.rename_module(modinfo)
187 self.failed_on_import.append(modinfo)
188 else:
189 if modinfo.state == ModuleState.BUILTIN:
190 self.builtin_ok.append(modinfo)
191 else:
192 assert modinfo.state == ModuleState.SHARED
193 self.shared_ok.append(modinfo)
194
195 def summary(self, *, verbose: bool = False) -> None:
196 longest = max([len(e.name) for e in self.modules], default=0)
197
198 def print_three_column(modinfos: list[ModuleInfo]) -> None:
199 names = [modinfo.name for modinfo in modinfos]
200 names.sort(key=str.lower)
201 # guarantee zip() doesn't drop anything
202 while len(names) % 3:
203 names.append("")
204 for l, m, r in zip(names[::3], names[1::3], names[2::3]):
205 print("%-*s %-*s %-*s" % (longest, l, longest, m, longest, r))
206
207 if verbose and self.builtin_ok:
208 print("The following *built-in* modules have been successfully built:")
209 print_three_column(self.builtin_ok)
210 print()
211
212 if verbose and self.shared_ok:
213 print("The following *shared* modules have been successfully built:")
214 print_three_column(self.shared_ok)
215 print()
216
217 if self.disabled_configure:
218 print("The following modules are *disabled* in configure script:")
219 print_three_column(self.disabled_configure)
220 print()
221
222 if self.disabled_setup:
223 print("The following modules are *disabled* in Modules/Setup files:")
224 print_three_column(self.disabled_setup)
225 print()
226
227 if verbose and self.notavailable:
228 print(
229 f"The following modules are not available on platform '{self.platform}':"
230 )
231 print_three_column(self.notavailable)
232 print()
233
234 if self.missing:
235 print("The necessary bits to build these optional modules were not found:")
236 print_three_column(self.missing)
237 print("To find the necessary bits, look in configure.ac and config.log.")
238 print()
239
240 if self.failed_on_import:
241 print(
242 "Following modules built successfully "
243 "but were removed because they could not be imported:"
244 )
245 print_three_column(self.failed_on_import)
246 print()
247
248 if any(
249 modinfo.name == "_ssl" for modinfo in self.missing + self.failed_on_import
250 ):
251 print("Could not build the ssl module!")
252 print("Python requires a OpenSSL 1.1.1 or newer")
253 if sysconfig.get_config_var("OPENSSL_LDFLAGS"):
254 print("Custom linker flags may require --with-openssl-rpath=auto")
255 print()
256
257 disabled = len(self.disabled_configure) + len(self.disabled_setup)
258 print(
259 f"Checked {len(self.modules)} modules ("
260 f"{len(self.builtin_ok)} built-in, "
261 f"{len(self.shared_ok)} shared, "
262 f"{len(self.notavailable)} n/a on {self.platform}, "
263 f"{disabled} disabled, "
264 f"{len(self.missing)} missing, "
265 f"{len(self.failed_on_import)} failed on import)"
266 )
267
268 def check_strict_build(self) -> None:
269 """Fail if modules are missing and it's a strict build"""
270 if self.strict_extensions_build and (self.failed_on_import or self.missing):
271 raise RuntimeError("Failed to build some stdlib modules")
272
273 def list_module_names(self, *, all: bool = False) -> set[str]:
274 names = {modinfo.name for modinfo in self.modules}
275 if all:
276 names.update(WINDOWS_MODULES)
277 return names
278
279 def get_builddir(self) -> pathlib.Path:
280 try:
281 with open(self.pybuilddir_txt, encoding="utf-8") as f:
282 builddir = f.read()
283 except FileNotFoundError:
284 logger.error("%s must be run from the top build directory", __file__)
285 raise
286 builddir_path = pathlib.Path(builddir)
287 logger.debug("%s: %s", self.pybuilddir_txt, builddir_path)
288 return builddir_path
289
290 def get_modules(self) -> list[ModuleInfo]:
291 """Get module info from sysconfig and Modules/Setup* files"""
292 seen = set()
293 modules = []
294 # parsing order is important, first entry wins
295 for modinfo in self.get_core_modules():
296 modules.append(modinfo)
297 seen.add(modinfo.name)
298 for setup_file in self.setup_files:
299 for modinfo in self.parse_setup_file(setup_file):
300 if modinfo.name not in seen:
301 modules.append(modinfo)
302 seen.add(modinfo.name)
303 for modinfo in self.get_sysconfig_modules():
304 if modinfo.name not in seen:
305 modules.append(modinfo)
306 seen.add(modinfo.name)
307 logger.debug("Found %i modules in total", len(modules))
308 modules.sort()
309 return modules
310
311 def get_core_modules(self) -> Iterable[ModuleInfo]:
312 """Get hard-coded core modules"""
313 for name in CORE_MODULES:
314 modinfo = ModuleInfo(name, ModuleState.BUILTIN)
315 logger.debug("Found core module %s", modinfo)
316 yield modinfo
317
318 def get_sysconfig_modules(self) -> Iterable[ModuleInfo]:
319 """Get modules defined in Makefile through sysconfig
320
321 MODBUILT_NAMES: modules in *static* block
322 MODSHARED_NAMES: modules in *shared* block
323 MODDISABLED_NAMES: modules in *disabled* block
324 """
325 moddisabled = set(sysconfig.get_config_var("MODDISABLED_NAMES").split())
326 if self.cross_compiling:
327 modbuiltin = set(sysconfig.get_config_var("MODBUILT_NAMES").split())
328 else:
329 modbuiltin = set(sys.builtin_module_names)
330
331 for key, value in sysconfig.get_config_vars().items():
332 if not key.startswith("MODULE_") or not key.endswith("_STATE"):
333 continue
334 if value not in {"yes", "disabled", "missing", "n/a"}:
335 raise ValueError(f"Unsupported value '{value}' for {key}")
336
337 modname = key[7:-6].lower()
338 if modname in moddisabled:
339 # Setup "*disabled*" rule
340 state = ModuleState.DISABLED_SETUP
341 elif value in {"disabled", "missing", "n/a"}:
342 state = ModuleState(value)
343 elif modname in modbuiltin:
344 assert value == "yes"
345 state = ModuleState.BUILTIN
346 else:
347 assert value == "yes"
348 state = ModuleState.SHARED
349
350 modinfo = ModuleInfo(modname, state)
351 logger.debug("Found %s in Makefile", modinfo)
352 yield modinfo
353
354 def parse_setup_file(self, setup_file: pathlib.Path) -> Iterable[ModuleInfo]:
355 """Parse a Modules/Setup file"""
356 assign_var = re.compile(r"^\w+=") # EGG_SPAM=foo
357 # default to static module
358 state = ModuleState.BUILTIN
359 logger.debug("Parsing Setup file %s", setup_file)
360 with open(setup_file, encoding="utf-8") as f:
361 for line in f:
362 line = line.strip()
363 if not line or line.startswith("#") or assign_var.match(line):
364 continue
365 match line.split():
366 case ["*shared*"]:
367 state = ModuleState.SHARED
368 case ["*static*"]:
369 state = ModuleState.BUILTIN
370 case ["*disabled*"]:
371 state = ModuleState.DISABLED
372 case ["*noconfig*"]:
373 continue
374 case [*items]:
375 if state == ModuleState.DISABLED:
376 # *disabled* can disable multiple modules per line
377 for item in items:
378 modinfo = ModuleInfo(item, state)
379 logger.debug("Found %s in %s", modinfo, setup_file)
380 yield modinfo
381 elif state in {ModuleState.SHARED, ModuleState.BUILTIN}:
382 # *shared* and *static*, first item is the name of the module.
383 modinfo = ModuleInfo(items[0], state)
384 logger.debug("Found %s in %s", modinfo, setup_file)
385 yield modinfo
386
387 def get_spec(self, modinfo: ModuleInfo) -> ModuleSpec:
388 """Get ModuleSpec for builtin or extension module"""
389 if modinfo.state == ModuleState.SHARED:
390 mod_location = self.get_location(modinfo)
391 assert mod_location is not None
392 location = os.fspath(mod_location)
393 loader = ExtensionFileLoader(modinfo.name, location)
394 spec = spec_from_file_location(modinfo.name, location, loader=loader)
395 assert spec is not None
396 return spec
397 elif modinfo.state == ModuleState.BUILTIN:
398 spec = spec_from_loader(modinfo.name, loader=BuiltinImporter)
399 assert spec is not None
400 return spec
401 else:
402 raise ValueError(modinfo)
403
404 def get_location(self, modinfo: ModuleInfo) -> pathlib.Path | None:
405 """Get shared library location in build directory"""
406 if modinfo.state == ModuleState.SHARED:
407 return self.builddir / f"{modinfo.name}{self.ext_suffix}"
408 else:
409 return None
410
411 def _check_file(self, modinfo: ModuleInfo, spec: ModuleSpec) -> None:
412 """Check that the module file is present and not empty"""
413 if spec.loader is BuiltinImporter: # type: ignore[comparison-overlap]
414 return
415 try:
416 assert spec.origin is not None
417 st = os.stat(spec.origin)
418 except FileNotFoundError:
419 logger.error("%s (%s) is missing", modinfo.name, spec.origin)
420 raise
421 if not st.st_size:
422 raise ImportError(f"{spec.origin} is an empty file")
423
424 def check_module_import(self, modinfo: ModuleInfo) -> None:
425 """Attempt to import module and report errors"""
426 spec = self.get_spec(modinfo)
427 self._check_file(modinfo, spec)
428 try:
429 with warnings.catch_warnings():
430 # ignore deprecation warning from deprecated modules
431 warnings.simplefilter("ignore", DeprecationWarning)
432 bootstrap_load(spec)
433 except ImportError as e:
434 logger.error("%s failed to import: %s", modinfo.name, e)
435 raise
436 except Exception as e:
437 if not hasattr(_imp, 'create_dynamic'):
438 logger.warning("Dynamic extension '%s' ignored", modinfo.name)
439 return
440 logger.exception("Importing extension '%s' failed!", modinfo.name)
441 raise
442
443 def check_module_cross(self, modinfo: ModuleInfo) -> None:
444 """Sanity check for cross compiling"""
445 spec = self.get_spec(modinfo)
446 self._check_file(modinfo, spec)
447
448 def rename_module(self, modinfo: ModuleInfo) -> None:
449 """Rename module file"""
450 if modinfo.state == ModuleState.BUILTIN:
451 logger.error("Cannot mark builtin module '%s' as failed!", modinfo.name)
452 return
453
454 failed_name = f"{modinfo.name}_failed{self.ext_suffix}"
455 builddir_path = self.get_location(modinfo)
456 assert builddir_path is not None
457 if builddir_path.is_symlink():
458 symlink = builddir_path
459 module_path = builddir_path.resolve().relative_to(os.getcwd())
460 failed_path = module_path.parent / failed_name
461 else:
462 symlink = None
463 module_path = builddir_path
464 failed_path = self.builddir / failed_name
465
466 # remove old failed file
467 failed_path.unlink(missing_ok=True)
468 # remove symlink
469 if symlink is not None:
470 symlink.unlink(missing_ok=True)
471 # rename shared extension file
472 try:
473 module_path.rename(failed_path)
474 except FileNotFoundError:
475 logger.debug("Shared extension file '%s' does not exist.", module_path)
476 else:
477 logger.debug("Rename '%s' -> '%s'", module_path, failed_path)
478
479
480 def main() -> None:
481 args = parser.parse_args()
482 if args.debug:
483 args.verbose = True
484 logging.basicConfig(
485 level=logging.DEBUG if args.debug else logging.INFO,
486 format="[%(levelname)s] %(message)s",
487 )
488
489 checker = ModuleChecker(
490 cross_compiling=args.cross_compiling,
491 strict=args.strict,
492 )
493 if args.list_module_names:
494 names = checker.list_module_names(all=True)
495 for name in sorted(names):
496 print(name)
497 else:
498 checker.check()
499 checker.summary(verbose=args.verbose)
500 try:
501 checker.check_strict_build()
502 except RuntimeError as e:
503 parser.exit(1, f"\nError: {e}\n")
504
505
506 if __name__ == "__main__":
507 main()