From 4d59d97f567c1bcd41ca0cc8ff9f9547f0f8293d Mon Sep 17 00:00:00 2001 From: Chris Hennes Date: Sat, 7 Nov 2026 13:44:54 -0600 Subject: [PATCH] No really MSVC, use the version I tell you to --- Readme.md | 2 +- compile_all.py | 47 ++++++++++++++++++++++++++++--- create_libpack.py | 63 ++++++++++++++++++++++++++++++++++++++++++ path_cleaner.py | 61 +++++++++++++++++++++++++++++++++++++++- test_compile_all.py | 55 ++++++++++++++++++++++++++++++++++++ test_create_libpack.py | 42 ++++++++++++++++++++++++++++ test_path_cleaner.py | 52 ++++++++++++++++++++++++++++++++++ 7 files changed, 316 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 677d3ca..841e2ea 100644 --- a/Readme.md +++ b/Readme.md @@ -62,7 +62,7 @@ Arguments: * `--7zip` -- Path to 7-zip executable if not in PATH * `--bison` -- Path to Bison executable if not in PATH * `--vs-version` -- Visual Studio toolchain to build with. Accepts `latest` (default), `2022`, `2026`, or a raw `vswhere` `-version` range such as `[17.0,18.0)`. -* `--vcvars-ver` -- Optional MSVC toolset version to select inside the chosen Visual Studio installation, passed through to `vcvars64.bat` as `-vcvars_ver=VALUE`. Use this to build with the v143 (VS 2022) toolset from a VS 2026 installation, for example `--vcvars-ver=14.4`. +* `--vcvars-ver` -- Optional MSVC toolset version to select inside the chosen Visual Studio installation, passed through to `vcvars64.bat` as `-vcvars_ver=VALUE`. Use this to build with the v143 (VS 2022) toolset from a VS 2026 installation, for example `--vcvars-ver=14.4`. The selection also applies to CMake's Visual Studio generators, the ICU build, and pip source builds, and the build stops before archiving if a binary it compiled was linked with newer tools. * `--fallback-build-dir` -- Override the fallback build directory used by Qt to avoid Windows path-length limits during its build. Replaces the value declared in `config.json` for the `qt` entry. Supply a short path on a drive that exists on this machine, for example `C:\temp`. ## License diff --git a/compile_all.py b/compile_all.py index be5f399..1fdddb2 100644 --- a/compile_all.py +++ b/compile_all.py @@ -299,6 +299,12 @@ def __init__( # MSBuild falls back to the newest installed compiler regardless of what the # environment or -vcvars_ver requested. self.msvc_tools_version = None + # PlatformToolset matching msvc_tools_version, for example "v143". + self.msvc_platform_toolset = None + # Value for CMake's -T option. The Visual Studio generators resolve the compiler through + # MSBuild and ignore the environment that vcvars sets up, so -vcvars_ver alone does not + # reach them. + self.cmake_toolset = None # CMake's default Visual Studio generator is the newest installed version, regardless # of the environment that vcvars sets up, so the choice must be passed explicitly. self.cmake_generator = None @@ -1091,6 +1097,13 @@ def _run_pip_install( existing_cl = env.get("CL", "").strip() env["CL"] = ("/Gy " + existing_cl).strip() if existing_cl else "/Gy" call_args = [*self.init_script, "&", *pip_args] + elif sys.platform.startswith("win32"): + # Packages without a matching wheel compile from sdist in Release too, and setuptools + # would otherwise auto-detect the newest installed compiler. + env = os.environ.copy() + env["DISTUTILS_USE_SDK"] = "1" + env["MSSdk"] = "1" + call_args = [*self.init_script, "&", *pip_args] else: env = None call_args = pip_args @@ -1355,14 +1368,21 @@ def _arm64_platform_flag(self, generator_args: List[str]) -> List[str]: selector.""" if not (sys.platform.startswith("win32") and platform.machine() == "ARM64"): return [] + generator = self._explicit_generator(generator_args) + if generator is None or "Visual Studio" in generator: + return ["-A ARM64"] + return [] + + @staticmethod + def _explicit_generator(generator_args: List[str]) -> Optional[str]: + """Return the generator named in generator_args, or None if it names none.""" args = generator_args or [] for index, arg in enumerate(args): if arg == "-G" and index + 1 < len(args): - return ["-A ARM64"] if "Visual Studio" in args[index + 1] else [] + return args[index + 1] if arg.startswith("-G") and arg != "-G": - generator = arg[2:].lstrip("=").strip() - return ["-A ARM64"] if "Visual Studio" in generator else [] - return ["-A ARM64"] + return arg[2:].lstrip("=").strip() + return None def _default_generator_args(self, generator_args: List[str]) -> List[str]: """Return the arguments selecting the configured CMake generator, or an empty list @@ -1373,11 +1393,29 @@ def _default_generator_args(self, generator_args: List[str]) -> List[str]: return [] return ["-G", self.cmake_generator] + def _toolset_args(self, generator_args: List[str]) -> List[str]: + """Return the arguments selecting the configured MSVC toolset. Only the Visual Studio + generators accept them; generators such as Ninja use the compiler vcvars put on PATH.""" + generator = self._explicit_generator(generator_args) or self.cmake_generator + if not self.cmake_toolset or not generator or "Visual Studio" not in generator: + return [] + return ["-T", self.cmake_toolset] + + def _msbuild_toolset_args(self) -> List[str]: + """Return the properties that pin a direct msbuild invocation to the requested tools.""" + if not self.msvc_tools_version: + return [] + return [ + f"/p:PlatformToolset={self.msvc_platform_toolset}", + f"/p:VCToolsVersion={self.msvc_tools_version}", + ] + def _cmake_configure(self, extra_args: List[str] = None): options = self.get_cmake_options() if extra_args: options.extend(extra_args) options.extend(self._default_generator_args(extra_args)) + options.extend(self._toolset_args(extra_args)) options.extend(self._arm64_platform_flag(extra_args)) options.append( ".." @@ -2011,6 +2049,7 @@ def build_icu(self, _: None): f"/p:Platform={arch}", f"/p:WindowsTargetPlatformVersion={target}", "/p:SkipUWP=true", + *self._msbuild_toolset_args(), "allinone.sln", ] try: diff --git a/create_libpack.py b/create_libpack.py index 393a590..ce42fc3 100644 --- a/create_libpack.py +++ b/create_libpack.py @@ -413,6 +413,12 @@ def write_manifest(outer_config: dict, mode_used: compile_all.BuildMode): "2026": "[18.0,19.0)", } +PLATFORM_TOOLSETS_BY_MSVC_MINOR_VERSION = ( + (range(20, 30), "v142"), + (range(30, 50), "v143"), + (range(50, 60), "v145"), +) + CMAKE_GENERATORS_BY_VS_MAJOR_VERSION = { "17": "Visual Studio 17 2022", "18": "Visual Studio 18 2026", @@ -474,6 +480,48 @@ def resolve_msvc_tools_version(vs_install_path: str, requested: str) -> str: return matches[0] +def platform_toolset_for_tools_version(tools_version: str) -> str: + """Return the MSBuild PlatformToolset for an MSVC tools version such as '14.44.35207', or + None if this script does not know that version.""" + minor_version = int(tools_version.split(".")[1]) + for minor_versions, toolset in PLATFORM_TOOLSETS_BY_MSVC_MINOR_VERSION: + if minor_version in minor_versions: + return toolset + return None + + +def find_side_by_side_toolset_version(vs_install_path: str, tools_version: str) -> str: + """Return the name of the VC\\Auxiliary\\Build side-by-side directory that describes + tools_version, for example '14.44.17.14' for '14.44.35207'. CMake's -T version field takes + this name rather than the tools version. Returns None if no such directory exists.""" + build_root = Path(vs_install_path) / "VC" / "Auxiliary" / "Build" + for version_file in build_root.glob("14.*/Microsoft.VCToolsVersion.*.txt"): + if version_file.read_text(encoding="utf-8").strip() == tools_version: + return version_file.parent.name + return None + + +def cmake_toolset_argument(platform_toolset: str, side_by_side_version: str = None) -> str: + """Return the value for CMake's -T option.""" + if side_by_side_version: + return f"{platform_toolset},version={side_by_side_version}" + return platform_toolset + + +def enforce_msvc_tools_version(libpack_path: str, tools_version: str) -> None: + """Abort before archiving if a binary compiled by this build used newer tools than were + requested. Binaries that may be upstream wheels are reported but do not abort the build.""" + print(f"Checking that compiled binaries do not exceed MSVC {tools_version}") + violations, unverified = path_cleaner.find_binaries_newer_than(libpack_path, tools_version) + for path in unverified: + print(f" WARNING: newer linker version, possibly an upstream wheel: {path}") + if violations: + print(f"ERROR: {len(violations)} binaries were built with tools newer than requested:") + for path in violations: + print(f" {path}") + exit(1) + + def cmake_generator_for_vs_version(installation_version: str) -> str: """Return the CMake generator matching a Visual Studio installation version such as '17.14.36408.4', or None if this script does not know that major version.""" @@ -745,6 +793,19 @@ def prevent_sleep_mode(): f"{list_msvc_tools_versions(vs_install_path)}" ) exit(1) + compiler.msvc_platform_toolset = platform_toolset_for_tools_version( + compiler.msvc_tools_version + ) + if not compiler.msvc_platform_toolset: + print( + f"ERROR: No PlatformToolset is known for MSVC {compiler.msvc_tools_version}. " + "Add it to PLATFORM_TOOLSETS_BY_MSVC_MINOR_VERSION." + ) + exit(1) + compiler.cmake_toolset = cmake_toolset_argument( + compiler.msvc_platform_toolset, + find_side_by_side_toolset_version(vs_install_path, compiler.msvc_tools_version), + ) else: compiler.init_script = [init_bat] # Ignore the per-user site-packages, which the LibPack's Python shares with any @@ -782,6 +843,8 @@ def prevent_sleep_mode(): path_cleaner.move_pdbs_to_sidecar(base_path, pdb_sidecar_path) write_manifest(config_dict, mode) + if compiler.msvc_tools_version: + enforce_msvc_tools_version(base_path, compiler.msvc_tools_version) if args["archive"]: create_archive(base_path) diff --git a/path_cleaner.py b/path_cleaner.py index a41188b..6a07e13 100644 --- a/path_cleaner.py +++ b/path_cleaner.py @@ -9,7 +9,8 @@ import os import re import shutil -from typing import Dict, List +import struct +from typing import Dict, List, Optional, Tuple paths_to_delete = [ "custom_vc14_64.bat", @@ -23,6 +24,12 @@ ] +_REDISTRIBUTABLE_RUNTIME_RE = re.compile( + r"(concrt|msvcp|ucrtbase|vccorlib|vcomp|vcruntime)", re.IGNORECASE +) +_LOCALLY_COMPILED_SITE_PACKAGES = {"opencamlib", "PySide6", "shiboken6", "vtkmodules"} + + def delete_extraneous_files(base_path: str) -> None: """Delete each of the files or directories listed above from the path specified in base_path. Failure to delete an entry does not constitute a fatal error.""" @@ -519,6 +526,58 @@ def move_pdbs_to_sidecar(base_path: str, sidecar_path: str) -> int: return moved +def read_linker_version(path: str) -> Optional[Tuple[int, int]]: + """Return the (major, minor) linker version recorded in a PE file's optional header, or + None if the file is not a PE image.""" + with open(path, "rb") as f: + dos_header = f.read(64) + if len(dos_header) < 64 or dos_header[:2] != b"MZ": + return None + f.seek(struct.unpack_from(" bool: + parts = relative_path.replace("\\", "/").split("/") + if parts[:2] == ["bin", "Scripts"]: + return True + if "site-packages" not in parts: + return False + top_level = parts[parts.index("site-packages") + 1] + return top_level not in _LOCALLY_COMPILED_SITE_PACKAGES + + +def find_binaries_newer_than(base_path: str, tools_version: str) -> Tuple[List[str], List[str]]: + """Find PE binaries linked with tools newer than tools_version, such as '14.44.35207'. + + Returns (violations, unverified) as paths relative to base_path. Violations are binaries + this build compiled. Unverified binaries sit where pip installs upstream wheels, whose + toolchain the LibPack does not control. Microsoft's redistributable runtime DLLs are + skipped because they are copied in rather than compiled.""" + limit = tuple(int(part) for part in tools_version.split(".")[:2]) + violations: List[str] = [] + unverified: List[str] = [] + for root, _dirs, files in os.walk(base_path): + for name in files: + if not name.lower().endswith((".dll", ".exe", ".pyd")): + continue + if _REDISTRIBUTABLE_RUNTIME_RE.match(name): + continue + path = os.path.join(root, name) + version = read_linker_version(path) + if version is None or version <= limit: + continue + relative_path = os.path.relpath(path, base_path) + if _may_be_upstream_binary(relative_path): + unverified.append(relative_path) + else: + violations.append(relative_path) + return sorted(violations), sorted(unverified) + + def delete_pdb_files(base_path: str) -> int: """Remove every Microsoft debug-symbol (.pdb) file from the LibPack. diff --git a/test_compile_all.py b/test_compile_all.py index 301de54..db2f860 100644 --- a/test_compile_all.py +++ b/test_compile_all.py @@ -57,6 +57,61 @@ def test_cmake_configure_passes_configured_generator(self, _, run_cmake_mock: Ma options = run_cmake_mock.call_args[0][0] self.assertEqual(options[options.index("-G") + 1], "Visual Studio 17 2022") + def test_toolset_args_apply_to_the_configured_visual_studio_generator(self): + """Without an explicit generator, the configured toolset accompanies the VS generator.""" + self.compiler.cmake_generator = "Visual Studio 18 2026" + self.compiler.cmake_toolset = "v143,version=14.44.17.14" + self.assertEqual( + self.compiler._toolset_args(["-D FOO=BAR"]), ["-T", "v143,version=14.44.17.14"] + ) + + def test_toolset_args_are_omitted_for_ninja(self): + """Ninja rejects -T, and already uses the compiler selected by vcvars.""" + self.compiler.cmake_generator = "Visual Studio 18 2026" + self.compiler.cmake_toolset = "v143,version=14.44.17.14" + self.assertEqual(self.compiler._toolset_args(["-G", "Ninja"]), []) + self.assertEqual(self.compiler._toolset_args(["-GNinja"]), []) + + def test_toolset_args_without_configured_toolset(self): + """With no configured toolset the choice is left to CMake.""" + self.compiler.cmake_generator = "Visual Studio 18 2026" + self.assertEqual(self.compiler._toolset_args(None), []) + + @patch("compile_all.Compiler._run_cmake") + @patch("compile_all.Compiler.get_cmake_options", return_value=[]) + def test_cmake_configure_passes_configured_toolset(self, _, run_cmake_mock: MagicMock): + """Configuring a package passes the configured toolset through to CMake.""" + self.compiler.cmake_generator = "Visual Studio 18 2026" + self.compiler.cmake_toolset = "v143,version=14.44.17.14" + self.compiler._cmake_configure(["-D FOO=BAR"]) + options = run_cmake_mock.call_args[0][0] + self.assertEqual(options[options.index("-T") + 1], "v143,version=14.44.17.14") + + def test_msbuild_toolset_args(self): + """A direct msbuild invocation is pinned to the requested tools.""" + self.compiler.msvc_platform_toolset = "v143" + self.compiler.msvc_tools_version = "14.44.35207" + self.assertEqual( + self.compiler._msbuild_toolset_args(), + ["/p:PlatformToolset=v143", "/p:VCToolsVersion=14.44.35207"], + ) + + def test_msbuild_toolset_args_without_requested_tools(self): + """Without a requested version msbuild keeps its default.""" + self.assertEqual(self.compiler._msbuild_toolset_args(), []) + + @patch("sys.platform", "win32") + @patch("compile_all.Compiler._run_streaming") + @patch("compile_all.Compiler.python_exe", return_value="python") + def test_release_pip_install_uses_the_requested_compiler(self, _, run_mock: MagicMock): + """Release sdist builds run under vcvars and trust that environment.""" + self.compiler.mode = compile_all.BuildMode.RELEASE + self.compiler.init_script = ["vcvars.bat", "-vcvars_ver=14.4"] + self.compiler._run_pip_install(["pkg==1.0"], False, ()) + args = run_mock.call_args[0][0] + self.assertEqual(args[:3], ["vcvars.bat", "-vcvars_ver=14.4", "&"]) + self.assertEqual(run_mock.call_args[1]["env"]["DISTUTILS_USE_SDK"], "1") + @patch("os.chdir") @patch("compile_all.Compiler.build_nonexistent") def test_compile_all_calls_build_function(self, nonexistent_mock: MagicMock, _): diff --git a/test_create_libpack.py b/test_create_libpack.py index 240c637..6fb746f 100644 --- a/test_create_libpack.py +++ b/test_create_libpack.py @@ -4,6 +4,7 @@ import contextlib import os +from pathlib import Path import shutil from subprocess import CalledProcessError import tempfile @@ -295,6 +296,47 @@ def test_cmake_generator_for_vs_version(self): "Visual Studio 18 2026", ) + def test_platform_toolset_for_tools_version(self): + """The PlatformToolset follows the minor version of the MSVC tools.""" + self.assertEqual(create_libpack.platform_toolset_for_tools_version("14.29.30133"), "v142") + self.assertEqual(create_libpack.platform_toolset_for_tools_version("14.44.35207"), "v143") + self.assertEqual(create_libpack.platform_toolset_for_tools_version("14.51.36231"), "v145") + self.assertIsNone(create_libpack.platform_toolset_for_tools_version("14.60.0")) + + def test_find_side_by_side_toolset_version(self): + """The side-by-side directory is identified by the tools version recorded inside it.""" + with tempfile.TemporaryDirectory() as vs_path: + for name, contents in (("14.44.17.14", "14.44.35207\r\n"), ("14.51", "14.51.36231")): + directory = Path(vs_path) / "VC" / "Auxiliary" / "Build" / name + directory.mkdir(parents=True) + (directory / f"Microsoft.VCToolsVersion.{name}.txt").write_text(contents) + self.assertEqual( + create_libpack.find_side_by_side_toolset_version(vs_path, "14.44.35207"), + "14.44.17.14", + ) + self.assertIsNone( + create_libpack.find_side_by_side_toolset_version(vs_path, "14.38.33130") + ) + + def test_cmake_toolset_argument(self): + """The version field is present only when a side-by-side toolset was found.""" + self.assertEqual( + create_libpack.cmake_toolset_argument("v143", "14.44.17.14"), + "v143,version=14.44.17.14", + ) + self.assertEqual(create_libpack.cmake_toolset_argument("v143"), "v143") + + @patch("path_cleaner.find_binaries_newer_than", return_value=(["bin/a.dll"], [])) + def test_enforce_msvc_tools_version_stops_on_violation(self, _): + """A locally compiled binary with newer tools stops the build before archiving.""" + with self.assertRaises(SystemExit): + create_libpack.enforce_msvc_tools_version("libpack", "14.44.35207") + + @patch("path_cleaner.find_binaries_newer_than", return_value=([], ["wheel/a.pyd"])) + def test_enforce_msvc_tools_version_tolerates_upstream_wheels(self, _): + """A binary that may come from an upstream wheel is only reported.""" + create_libpack.enforce_msvc_tools_version("libpack", "14.44.35207") + def test_cmake_generator_for_unknown_vs_version(self): """An unrecognized major version yields None so that the caller can refuse to build.""" self.assertIsNone(create_libpack.cmake_generator_for_vs_version("16.11.0.0")) diff --git a/test_path_cleaner.py b/test_path_cleaner.py index abfb596..34a2b0f 100644 --- a/test_path_cleaner.py +++ b/test_path_cleaner.py @@ -725,5 +725,57 @@ def test_missing_layout_is_not_an_error(self): self.assertEqual(path_cleaner.delete_python_test_suites(self.base_dir), 0) +class TestFindBinariesNewerThan(unittest.TestCase): + def setUp(self) -> None: + self.base_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.base_dir) + + def _write_pe(self, relative_path: str, minor_version: int) -> None: + path = os.path.join(self.base_dir, *relative_path.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + dos_header = b"MZ" + bytes(58) + (64).to_bytes(4, "little") + pe_header = b"PE\0\0" + bytes(22) + bytes([14, minor_version]) + with open(path, "wb") as f: + f.write(dos_header + pe_header) + + def test_reads_linker_version(self): + self._write_pe("bin/a.dll", 44) + version = path_cleaner.read_linker_version(os.path.join(self.base_dir, "bin", "a.dll")) + self.assertEqual(version, (14, 44)) + + def test_non_pe_file_has_no_linker_version(self): + path = os.path.join(self.base_dir, "fake.dll") + with open(path, "wb") as f: + f.write(b"not a binary") + self.assertIsNone(path_cleaner.read_linker_version(path)) + + def test_locally_compiled_binary_is_a_violation(self): + self._write_pe("bin/TKernel.dll", 51) + self._write_pe("bin/Lib/site-packages/vtkmodules/vtkCommon.pyd", 51) + violations, unverified = path_cleaner.find_binaries_newer_than(self.base_dir, "14.44.35207") + self.assertEqual(len(violations), 2) + self.assertEqual(unverified, []) + + def test_matching_and_older_binaries_pass(self): + self._write_pe("bin/Qt6Core.dll", 44) + self._write_pe("bin/libffi-8.dll", 34) + self.assertEqual( + path_cleaner.find_binaries_newer_than(self.base_dir, "14.44.35207"), ([], []) + ) + + def test_possible_upstream_wheels_are_only_unverified(self): + self._write_pe("bin/Lib/site-packages/regex/_regex.pyd", 51) + self._write_pe("bin/Scripts/maturin.exe", 51) + violations, unverified = path_cleaner.find_binaries_newer_than(self.base_dir, "14.44.35207") + self.assertEqual(violations, []) + self.assertEqual(len(unverified), 2) + + def test_redistributable_runtime_is_skipped(self): + self._write_pe("bin/vcruntime140.dll", 50) + self.assertEqual( + path_cleaner.find_binaries_newer_than(self.base_dir, "14.44.35207"), ([], []) + ) + + if __name__ == "__main__": unittest.main()