Skip to content

The agent that grows with you

fix(update): stop WoA integrity gate rejecting ARM64 after IsWow64Process2 HANDLE truncation (#71381)

xxxigmfe3dd9106a1c
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index ff88de141e1..4b453f962a0 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -5556,6 +5556,99 @@ _PE_MACHINE_NAMES = {
_PE_MACHINE_ARM64: "ARM64",
}
+# SYSTEM_INFO.wProcessorArchitecture values (winnt.h). Used by
+# GetNativeSystemInfo as a second OS-native probe when IsWow64Process2 is
+# unavailable or fails under a mistyped ctypes HANDLE.
+_PROCESSOR_ARCHITECTURE_INTEL = 0
+_PROCESSOR_ARCHITECTURE_ARM = 5
+_PROCESSOR_ARCHITECTURE_AMD64 = 9
+_PROCESSOR_ARCHITECTURE_ARM64 = 12
+
+_PE_MACHINE_TO_NAME = {
+ _PE_MACHINE_ARM64: "ARM64",
+ _PE_MACHINE_AMD64: "AMD64",
+ _PE_MACHINE_I386: "X86",
+}
+
+_SYSTEM_INFO_ARCH_TO_NAME = {
+ _PROCESSOR_ARCHITECTURE_ARM64: "ARM64",
+ _PROCESSOR_ARCHITECTURE_AMD64: "AMD64",
+ _PROCESSOR_ARCHITECTURE_INTEL: "X86",
+ _PROCESSOR_ARCHITECTURE_ARM: "ARM",
+}
+
+
+def _windows_native_machine_from_iswow64() -> Optional[str]:
+ """Ask IsWow64Process2 for the OS-native machine (None if unavailable/fail).
+
+ ctypes defaults ``GetCurrentProcess``'s restype to ``c_int``, so the
+ current-process pseudo-handle ``(HANDLE)-1`` is truncated to
+ ``0xFFFFFFFF`` and zero-extended into a 64-bit invalid handle. On Win64
+ that makes ``IsWow64Process2`` fail with ``ERROR_INVALID_HANDLE`` (6),
+ which is exactly the residual Windows-on-ARM failure after #71218: the
+ gate fell through to ``PROCESSOR_ARCHITECTURE=AMD64`` (the emulated
+ process arch) and rejected a correctly-built ARM64 ``Hermes.exe``.
+ Binding ``restype``/``argtypes`` to ``wintypes.HANDLE`` keeps the full
+ ``0xFFFFFFFFFFFFFFFF`` pseudo-handle.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.GetCurrentProcess.argtypes = []
+ kernel32.IsWow64Process2.argtypes = [
+ wintypes.HANDLE,
+ ctypes.POINTER(wintypes.USHORT),
+ ctypes.POINTER(wintypes.USHORT),
+ ]
+ kernel32.IsWow64Process2.restype = wintypes.BOOL
+
+ process_machine = wintypes.USHORT(0)
+ native_machine = wintypes.USHORT(0)
+ if not kernel32.IsWow64Process2(
+ kernel32.GetCurrentProcess(),
+ ctypes.byref(process_machine),
+ ctypes.byref(native_machine),
+ ):
+ return None
+ return _PE_MACHINE_TO_NAME.get(native_machine.value)
+
+
+def _windows_native_machine_from_native_system_info() -> Optional[str]:
+ """GetNativeSystemInfo — truthful under x64-on-ARM64 when IsWow64 fails.
+
+ Unlike ``PROCESSOR_ARCHITECTURE`` (process/emulation view) this reports
+ the OS-native architecture, so it covers the residual #71218 failure mode
+ where ``IsWow64Process2`` returns FALSE and the env-var fallback would
+ otherwise lie as AMD64.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ class _SYSTEM_INFO(ctypes.Structure):
+ _fields_ = [
+ ("wProcessorArchitecture", wintypes.WORD),
+ ("wReserved", wintypes.WORD),
+ ("dwPageSize", wintypes.DWORD),
+ ("lpMinimumApplicationAddress", ctypes.c_void_p),
+ ("lpMaximumApplicationAddress", ctypes.c_void_p),
+ ("dwActiveProcessorMask", ctypes.c_size_t),
+ ("dwNumberOfProcessors", wintypes.DWORD),
+ ("dwProcessorType", wintypes.DWORD),
+ ("dwAllocationGranularity", wintypes.DWORD),
+ ("wProcessorLevel", wintypes.WORD),
+ ("wProcessorRevision", wintypes.WORD),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.GetNativeSystemInfo.argtypes = [ctypes.POINTER(_SYSTEM_INFO)]
+ kernel32.GetNativeSystemInfo.restype = None
+
+ info = _SYSTEM_INFO()
+ kernel32.GetNativeSystemInfo(ctypes.byref(info))
+ return _SYSTEM_INFO_ARCH_TO_NAME.get(info.wProcessorArchitecture)
+
def _windows_native_machine() -> str:
"""The Windows host OS's NATIVE machine architecture, normalized upper.
@@ -5565,35 +5658,29 @@ def _windows_native_machine() -> str:
x64 Python) on Windows-on-ARM devices, where ``platform.machine()``
returns ``AMD64`` even though the OS is ARM64. The #71119 integrity gate
then rejected the CORRECT ARM64 rebuild as an "architecture mismatch"
- (#69179 follow-up report). ``IsWow64Process2`` asks the OS for the true
- native machine and works from emulated processes; the classic
- ``PROCESSOR_ARCHITEW6432`` fallback only covers WOW64 (32-bit processes)
- and is NOT set under x64-on-ARM64 emulation, so it cannot replace the API
- probe — it is kept only for pre-1511 Windows 10 hosts without the API.
+ (#69179 follow-up report). Probe order:
+
+ 1. ``IsWow64Process2`` with a correctly-typed current-process HANDLE
+ (#71218 + HANDLE-truncation fix).
+ 2. ``GetNativeSystemInfo`` — still OS-native when (1) fails under
+ x64-on-ARM64 emulation (env vars alone cannot cover that case).
+ 3. ``PROCESSOR_ARCHITEW6432`` / ``PROCESSOR_ARCHITECTURE`` — WOW64
+ (32-bit) hosts and pre-1511 Windows 10 without the newer APIs.
+ 4. ``platform.machine()``.
"""
if sys.platform == "win32":
- try:
- import ctypes
-
- kernel32 = ctypes.windll.kernel32
- process_machine = ctypes.c_ushort(0)
- native_machine = ctypes.c_ushort(0)
- if kernel32.IsWow64Process2(
- kernel32.GetCurrentProcess(),
- ctypes.byref(process_machine),
- ctypes.byref(native_machine),
- ):
- name = {
- _PE_MACHINE_ARM64: "ARM64",
- _PE_MACHINE_AMD64: "AMD64",
- _PE_MACHINE_I386: "X86",
- }.get(native_machine.value)
- if name:
- return name
- except (OSError, AttributeError):
- # No IsWow64Process2 (pre-1511 Windows 10) — fall through to the
- # documented WOW64 env vars, then the process architecture.
- pass
+ for probe in (
+ _windows_native_machine_from_iswow64,
+ _windows_native_machine_from_native_system_info,
+ ):
+ try:
+ name = probe()
+ except (OSError, AttributeError, TypeError, ValueError):
+ # API missing (pre-1511), DLL load failure in tests, or a
+ # mistyped ctypes binding — try the next probe.
+ name = None
+ if name:
+ return name
env_arch = os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get(
"PROCESSOR_ARCHITECTURE"
)
diff --git a/tests/hermes_cli/test_desktop_exe_integrity.py b/tests/hermes_cli/test_desktop_exe_integrity.py
index 013244da91e..8f6cec6bbbb 100644
--- a/tests/hermes_cli/test_desktop_exe_integrity.py
+++ b/tests/hermes_cli/test_desktop_exe_integrity.py
@@ -122,27 +122,70 @@ def test_expected_machines_unknown_host_is_permissive():
# ─── _windows_native_machine ────────────────────────────────────────────────
+# winnt.h PROCESSOR_ARCHITECTURE_* — mirrors hermes_cli.main constants.
+_SYSINFO_AMD64 = 9
+_SYSINFO_ARM64 = 12
-class _FakeKernel32:
- """Stands in for kernel32 so the IsWow64Process2 path runs on any CI OS."""
- def __init__(self, native_machine: int):
- self._native = native_machine
+class _SettableFunc:
+ """Callable that accepts ctypes ``.restype`` / ``.argtypes`` assignment."""
+
+ def __init__(self, fn):
+ self._fn = fn
+ self.restype = None
+ self.argtypes = None
+
+ def __call__(self, *args, **kwargs):
+ return self._fn(*args, **kwargs)
- def GetCurrentProcess(self):
- return -1
- def IsWow64Process2(self, _handle, process_ref, native_ref):
+class _FakeKernel32:
+ """Stands in for kernel32 so the native-arch probes run on any CI OS."""
+
+ def __init__(
+ self,
+ native_pe_machine: int,
+ *,
+ wow64_ok: bool = True,
+ system_info_arch: int | None = None,
+ ):
+ self._native_pe = native_pe_machine
+ self._wow64_ok = wow64_ok
+ self._system_info_arch = system_info_arch
+ self.GetCurrentProcess = _SettableFunc(lambda: -1)
+ self.IsWow64Process2 = _SettableFunc(self._is_wow64_process2)
+ self.GetNativeSystemInfo = _SettableFunc(self._get_native_system_info)
+
+ def _is_wow64_process2(self, _handle, process_ref, native_ref):
+ if not self._wow64_ok:
+ return 0
process_ref._obj.value = PE_AMD64 # emulated x64 process
- native_ref._obj.value = self._native
+ native_ref._obj.value = self._native_pe
return 1
+ def _get_native_system_info(self, info_ref):
+ if self._system_info_arch is None:
+ raise AttributeError("GetNativeSystemInfo unavailable in this fake")
+ info_ref._obj.wProcessorArchitecture = self._system_info_arch
+
+
+def _fake_windll(
+ native_pe_machine: int,
+ *,
+ wow64_ok: bool = True,
+ system_info_arch: int | None = None,
+):
+ kernel32 = _FakeKernel32(
+ native_pe_machine,
+ wow64_ok=wow64_ok,
+ system_info_arch=system_info_arch,
+ )
-def _fake_windll(native_machine: int):
- class _WinDLL:
- kernel32 = _FakeKernel32(native_machine)
+ def _windll(name, *args, **kwargs):
+ assert "kernel32" in str(name).lower()
+ return kernel32
- return _WinDLL()
+ return _windll
def test_native_machine_reports_os_arch_not_process_arch(monkeypatch):
@@ -152,27 +195,76 @@ def test_native_machine_reports_os_arch_not_process_arch(monkeypatch):
import ctypes
monkeypatch.setattr(cli_main.sys, "platform", "win32")
- with patch.object(ctypes, "windll", _fake_windll(PE_ARM64), create=True), \
+ # WinDLL only exists on Windows; create=True so Linux/macOS CI can stub it.
+ with patch.object(ctypes, "WinDLL", _fake_windll(PE_ARM64), create=True), \
+ patch("platform.machine", return_value="AMD64"):
+ assert cli_main._windows_native_machine() == "ARM64"
+
+
+def test_native_machine_binds_current_process_handle_restype(monkeypatch):
+ """ctypes must type GetCurrentProcess as HANDLE — default c_int truncates
+ the pseudo-handle on Win64 and makes IsWow64Process2 return
+ ERROR_INVALID_HANDLE, re-breaking the #71218 gate on WoA."""
+ import ctypes
+ from ctypes import wintypes
+
+ monkeypatch.setattr(cli_main.sys, "platform", "win32")
+ windll = _fake_windll(PE_ARM64)
+ with patch.object(ctypes, "WinDLL", windll, create=True), \
patch("platform.machine", return_value="AMD64"):
assert cli_main._windows_native_machine() == "ARM64"
+ kernel32 = windll("kernel32")
+ assert kernel32.GetCurrentProcess.restype is wintypes.HANDLE
+ assert kernel32.IsWow64Process2.argtypes is not None
+
+
+def test_native_machine_system_info_fallback_when_iswow64_fails(monkeypatch):
+ """Residual #71218 failure: IsWow64Process2 returns FALSE (e.g. invalid
+ handle) while PROCESSOR_ARCHITECTURE still lies as AMD64. GetNativeSystemInfo
+ must still report the real ARM64 host so the integrity gate accepts the
+ correctly-built ARM64 Hermes.exe."""
+ import ctypes
+
+ monkeypatch.setattr(cli_main.sys, "platform", "win32")
+ monkeypatch.setenv("PROCESSOR_ARCHITECTURE", "AMD64")
+ monkeypatch.delenv("PROCESSOR_ARCHITEW6432", raising=False)
+ with patch.object(
+ ctypes,
+ "WinDLL",
+ _fake_windll(PE_ARM64, wow64_ok=False, system_info_arch=_SYSINFO_ARM64),
+ create=True,
+ ), patch("platform.machine", return_value="AMD64"):
+ assert cli_main._windows_native_machine() == "ARM64"
def test_native_machine_env_fallback_without_api(monkeypatch):
- """Pre-1511 Windows 10: no IsWow64Process2 → the WOW64 env var wins."""
+ """Pre-1511 Windows 10: no IsWow64Process2 / GetNativeSystemInfo → env."""
+ import ctypes
+
monkeypatch.setattr(cli_main.sys, "platform", "win32")
monkeypatch.setenv("PROCESSOR_ARCHITEW6432", "AMD64")
- # On non-Windows interpreters ctypes has no `windll`, which is exactly the
- # AttributeError shape a missing API produces.
- with patch("platform.machine", return_value="x86"):
+
+ def _no_kernel32(name, *args, **kwargs):
+ raise OSError(f"no {name} in this fake pre-1511 host")
+
+ with patch.object(ctypes, "WinDLL", _no_kernel32, create=True), \
+ patch("platform.machine", return_value="x86"):
assert cli_main._windows_native_machine() == "AMD64"
def test_native_machine_platform_fallback(monkeypatch):
"""No API, no env vars → the historical platform.machine() answer."""
+ import ctypes
+
monkeypatch.setattr(cli_main.sys, "platform", "win32")
monkeypatch.delenv("PROCESSOR_ARCHITEW6432", raising=False)
monkeypatch.delenv("PROCESSOR_ARCHITECTURE", raising=False)
- with patch("platform.machine", return_value="AMD64"):
+
+ def _no_kernel32(name, *args, **kwargs):
+ raise OSError(f"no {name} in this fake host")
+
+ with patch.object(ctypes, "WinDLL", _no_kernel32, create=True), \
+ patch("platform.machine", return_value="AMD64"):
assert cli_main._windows_native_machine() == "AMD64"
@@ -189,11 +281,31 @@ def test_integrity_gate_accepts_arm64_exe_from_emulated_x64_process(monkeypatch,
monkeypatch.setattr(cli_main.sys, "platform", "win32")
exe = make_pe(tmp_path / "Hermes.exe", PE_ARM64)
- with patch.object(ctypes, "windll", _fake_windll(PE_ARM64), create=True), \
+ with patch.object(ctypes, "WinDLL", _fake_windll(PE_ARM64), create=True), \
patch("platform.machine", return_value="AMD64"):
assert cli_main._desktop_exe_integrity_error(exe) is None
+def test_integrity_gate_accepts_arm64_when_iswow64_fails_but_system_info_ok(
+ monkeypatch, tmp_path
+):
+ """End-to-end residual WoA shape: IsWow64Process2 fails, env lies as AMD64,
+ GetNativeSystemInfo reports ARM64, ARM64 Hermes.exe must pass the gate."""
+ import ctypes
+
+ monkeypatch.setattr(cli_main.sys, "platform", "win32")
+ monkeypatch.setenv("PROCESSOR_ARCHITECTURE", "AMD64")
+ monkeypatch.delenv("PROCESSOR_ARCHITEW6432", raising=False)
+ exe = make_pe(tmp_path / "Hermes.exe", PE_ARM64)
+ with patch.object(
+ ctypes,
+ "WinDLL",
+ _fake_windll(PE_ARM64, wow64_ok=False, system_info_arch=_SYSINFO_ARM64),
+ create=True,
+ ), patch("platform.machine", return_value="AMD64"):
+ assert cli_main._desktop_exe_integrity_error(exe) is None
+
+
# ─── _desktop_exe_integrity_error ───────────────────────────────────────────