Skip to content

Quickly sandbox your AI agent.

Python

Prevent console window flashing for subprocesses on Windows

Jace Medlina5658d879ef0
diff --git a/packages/quicksand-core/quicksand_core/_reaper.py b/packages/quicksand-core/quicksand_core/_reaper.py
index 7fddc72..79134a9 100644
--- a/packages/quicksand-core/quicksand_core/_reaper.py
+++ b/packages/quicksand-core/quicksand_core/_reaper.py
@@ -68,7 +68,10 @@ def main() -> int:
return 2
cmd = sys.argv[2:]
- child = subprocess.Popen(cmd, stdin=subprocess.PIPE)
+ # CREATE_NO_WINDOW: prevent QEMU (a console binary) from flashing its own
+ # console window when launched from a windowed/GUI parent on Windows.
+ _no_window = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
+ child = subprocess.Popen(cmd, stdin=subprocess.PIPE, creationflags=_no_window)
def _forward(signum, _frame):
if child.poll() is None:
diff --git a/packages/quicksand-core/quicksand_core/_types.py b/packages/quicksand-core/quicksand_core/_types.py
index a8ab9a1..a68b2cc 100644
--- a/packages/quicksand-core/quicksand_core/_types.py
+++ b/packages/quicksand-core/quicksand_core/_types.py
@@ -12,6 +12,8 @@ Platform and Architecture enums are in platform.py.
from __future__ import annotations
+import subprocess
+import sys
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
@@ -19,6 +21,11 @@ from typing import Literal, Protocol, TypedDict, runtime_checkable
from pydantic import BaseModel, ConfigDict, field_validator
+# Pass to subprocess.run()/Popen(creationflags=...) so console binaries (QEMU,
+# qemu-img, powershell) don't flash their own console window when launched from a
+# windowed/GUI parent on Windows. No-op (0) on non-Windows platforms.
+NO_WINDOW_CREATIONFLAGS: int = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
+
from .host import Accelerator
# =============================================================================
diff --git a/packages/quicksand-core/quicksand_core/host/os_.py b/packages/quicksand-core/quicksand_core/host/os_.py
index 7bfe3d2..b93f1f8 100644
--- a/packages/quicksand-core/quicksand_core/host/os_.py
+++ b/packages/quicksand-core/quicksand_core/host/os_.py
@@ -286,6 +286,8 @@ class WindowsConfig(BaseOSConfig):
"""Detect Windows Hypervisor Platform."""
try:
# Check both WHPX availability and whether we're inside a hypervisor
+ from .._types import NO_WINDOW_CREATIONFLAGS
+
result = subprocess.run(
[
"powershell",
@@ -296,6 +298,7 @@ class WindowsConfig(BaseOSConfig):
capture_output=True,
text=True,
timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
if result.returncode == 0 and "True" in result.stdout:
# Nested if baseboard is "Microsoft Corporation" (Azure/Hyper-V VM)
diff --git a/packages/quicksand-core/quicksand_core/host/smb.py b/packages/quicksand-core/quicksand_core/host/smb.py
index 5fe05a8..b29c683 100644
--- a/packages/quicksand-core/quicksand_core/host/smb.py
+++ b/packages/quicksand-core/quicksand_core/host/smb.py
@@ -183,10 +183,13 @@ class WindowsSMBServer(SMBServer):
self._port_value = 445 # Windows native SMB always uses 445
def _run_powershell(self, script: str) -> subprocess.CompletedProcess:
+ from .._types import NO_WINDOW_CREATIONFLAGS
+
return subprocess.run(
["powershell", "-NoProfile", "-Command", script],
capture_output=True,
text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
@property
diff --git a/packages/quicksand-core/quicksand_core/qemu/overlay.py b/packages/quicksand-core/quicksand_core/qemu/overlay.py
index 85fdb38..84cf74e 100644
--- a/packages/quicksand-core/quicksand_core/qemu/overlay.py
+++ b/packages/quicksand-core/quicksand_core/qemu/overlay.py
@@ -7,6 +7,8 @@ import logging
import subprocess
from pathlib import Path
+from .._types import NO_WINDOW_CREATIONFLAGS
+
logger = logging.getLogger("quicksand.overlay")
@@ -54,6 +56,7 @@ class OverlayManager:
],
check=True,
capture_output=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
if disk_size:
self.resize_overlay(overlay_path, disk_size)
@@ -73,6 +76,7 @@ class OverlayManager:
],
check=True,
capture_output=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
if disk_size:
@@ -90,6 +94,7 @@ class OverlayManager:
],
check=True,
capture_output=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
# ------------------------------------------------------------------
@@ -106,6 +111,7 @@ class OverlayManager:
check=True,
capture_output=True,
text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
info = json.loads(result.stdout)
return info.get("backing-filename")
@@ -179,4 +185,5 @@ class OverlayManager:
],
check=True,
capture_output=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
diff --git a/packages/quicksand-core/quicksand_core/qemu/platform.py b/packages/quicksand-core/quicksand_core/qemu/platform.py
index d997592..dab7bac 100644
--- a/packages/quicksand-core/quicksand_core/qemu/platform.py
+++ b/packages/quicksand-core/quicksand_core/qemu/platform.py
@@ -223,7 +223,14 @@ class PlatformConfig:
if accelerator:
accel_arg = accelerator.value
- if accelerator == Accelerator.WHPX and nested_virt:
+ if accelerator == Accelerator.WHPX:
+ # kernel-irqchip=off routes interrupts through userspace. WHPX's
+ # in-kernel irqchip combined with the guest's noapic boot param
+ # (our IO-APIC workaround) delivers device interrupts unreliably:
+ # later `mount -t cifs` operations hang in the guest kernel until
+ # they time out. This was previously only applied when nested
+ # (baseboard == "Microsoft Corporation"), but bare-metal Windows
+ # hosts need it too, so apply it for WHPX unconditionally.
accel_arg = "whpx,kernel-irqchip=off"
cmd.extend(["-accel", accel_arg])
diff --git a/packages/quicksand-core/quicksand_core/qemu/process.py b/packages/quicksand-core/quicksand_core/qemu/process.py
index 88699e3..2d8d7f0 100644
--- a/packages/quicksand-core/quicksand_core/qemu/process.py
+++ b/packages/quicksand-core/quicksand_core/qemu/process.py
@@ -86,12 +86,16 @@ class VMProcessManager:
# pipe and the reaper tears QEMU down. write_serial() still reaches
# QEMU because the reaper forwards stdin bytes to QEMU's stdin.
wrapped = [sys.executable, str(_REAPER_SCRIPT), "--", *command]
+ # CREATE_NO_WINDOW: when frozen, sys.executable is a Windows console app;
+ # without this it (and the QEMU it launches) flashes a console window.
+ _no_window = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
self._process = subprocess.Popen(
wrapped,
stdout=self._console_file,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
env=env,
+ creationflags=_no_window,
)
logger.debug(f"Started QEMU via reaper, reaper PID {self._process.pid}")
diff --git a/packages/quicksand-core/quicksand_core/qemu/save.py b/packages/quicksand-core/quicksand_core/qemu/save.py
index 8531c5b..6e22830 100644
--- a/packages/quicksand-core/quicksand_core/qemu/save.py
+++ b/packages/quicksand-core/quicksand_core/qemu/save.py
@@ -8,7 +8,7 @@ import shutil
import subprocess
from pathlib import Path
-from .._types import FilePatterns, SaveManifest
+from .._types import NO_WINDOW_CREATIONFLAGS, FilePatterns, SaveManifest
logger = logging.getLogger("quicksand.save")
@@ -129,6 +129,7 @@ class SaveWriter:
],
capture_output=True,
text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
)
if result.returncode != 0:
raise RuntimeError(f"Failed to compress overlay: {result.stderr}")
diff --git a/packages/quicksand-smb/quicksand_smb/_query.py b/packages/quicksand-smb/quicksand_smb/_query.py
index b782d19..4a7de1a 100644
--- a/packages/quicksand-smb/quicksand_smb/_query.py
+++ b/packages/quicksand-smb/quicksand_smb/_query.py
@@ -458,9 +458,19 @@ def _build_dir_entry(
elif entry is not None:
name = entry.name
try:
- st = entry.stat(follow_symlinks=False)
+ # os.DirEntry.stat() serves a cache tied to the originating
+ # os.scandir() iteration. On Windows that cached stat can raise
+ # OSError when the DirEntry is reused after the scan (as happens on a
+ # second QUERY_DIRECTORY of a reused/leased directory handle), which
+ # silently drops EVERY entry and yields an empty directory listing
+ # (first `ls` works, every subsequent `ls`/`find` returns nothing).
+ # Stat the full path directly so it always succeeds.
+ st = os.stat(entry.path, follow_symlinks=False)
except OSError:
- return None
+ try:
+ st = entry.stat(follow_symlinks=False)
+ except OSError:
+ return None
is_dir = entry.is_dir(follow_symlinks=False)
else:
return None
diff --git a/tests/unit/smb/test_smb_server.py b/tests/unit/smb/test_smb_server.py
index 76fd191..2effdec 100644
--- a/tests/unit/smb/test_smb_server.py
+++ b/tests/unit/smb/test_smb_server.py
@@ -952,3 +952,66 @@ class TestFsInfoSizes:
out = _handle_fs_info(FS_SECTOR_SIZE_INFORMATION, tmp_path)
assert out is not None
assert len(out) == 28
+
+
+class TestBuildDirEntryStat:
+ """Regression: directory listings must survive a raising DirEntry.stat().
+
+ On Windows, os.DirEntry.stat() serves a cache tied to the originating
+ os.scandir() iteration and can raise OSError when the DirEntry is reused
+ for a second QUERY_DIRECTORY (reused/leased directory handle). Previously
+ _build_dir_entry swallowed that OSError and returned None, silently dropping
+ EVERY entry so the guest saw an empty directory (first `ls` works, every
+ subsequent `ls`/`find` returns nothing). The entry must instead be built by
+ stat'ing the full path.
+ """
+
+ def _fake_entry(self, path: Path, *, raise_direntry_stat: bool):
+ import os as _os
+
+ class _FakeDirEntry:
+ def __init__(self, p: Path):
+ self.name = p.name
+ self.path = str(p)
+ self._p = p
+
+ def stat(self, *, follow_symlinks: bool = False):
+ if raise_direntry_stat:
+ raise OSError("simulated stale DirEntry.stat cache (WinError)")
+ return _os.stat(self._p, follow_symlinks=follow_symlinks)
+
+ def is_dir(self, *, follow_symlinks: bool = False):
+ return self._p.is_dir()
+
+ return _FakeDirEntry(path)
+
+ def test_entry_built_when_direntry_stat_raises(self, tmp_path):
+ from quicksand_smb._query import (
+ FILE_BOTH_DIRECTORY_INFORMATION,
+ _build_dir_entry,
+ )
+
+ f = tmp_path / "photo.png"
+ f.write_bytes(b"x" * 42)
+ entry = self._fake_entry(f, raise_direntry_stat=True)
+
+ out = _build_dir_entry(entry, FILE_BOTH_DIRECTORY_INFORMATION)
+
+ # Before the fix this returned None (dropping the entry). It must now
+ # build a valid entry by stat'ing entry.path directly.
+ assert out is not None
+ assert "photo.png".encode("utf-16-le") in out
+
+ def test_entry_still_built_when_direntry_stat_works(self, tmp_path):
+ from quicksand_smb._query import (
+ FILE_BOTH_DIRECTORY_INFORMATION,
+ _build_dir_entry,
+ )
+
+ f = tmp_path / "doc.txt"
+ f.write_text("hello")
+ entry = self._fake_entry(f, raise_direntry_stat=False)
+
+ out = _build_dir_entry(entry, FILE_BOTH_DIRECTORY_INFORMATION)
+ assert out is not None
+ assert "doc.txt".encode("utf-16-le") in out
diff --git a/tests/unit/test_core_sandbox.py b/tests/unit/test_core_sandbox.py
index 3362d76..127024e 100644
--- a/tests/unit/test_core_sandbox.py
+++ b/tests/unit/test_core_sandbox.py
@@ -9,7 +9,7 @@ import httpx
import pytest
from quicksand_core import PortForward, Sandbox, SandboxConfig
from quicksand_core._types import NetworkMode
-from quicksand_core.host import LinuxConfig
+from quicksand_core.host import Accelerator, LinuxConfig
from quicksand_core.host.quicksand_guest_agent_client import _retry_on_transient_error
from quicksand_core.qemu.arch import X86_64Config
from quicksand_core.qemu.platform import PlatformConfig, RuntimeInfo
@@ -199,6 +199,48 @@ class TestSandboxMountConfig:
assert "virtio-9p" not in str(cmd)
+class TestWhpxAccelerator:
+ """Regression: WHPX must always get kernel-irqchip=off.
+
+ WHPX's in-kernel irqchip + the guest's noapic boot param delivers device
+ interrupts unreliably (CIFS mounts hang). kernel-irqchip=off fixes it. This
+ was previously gated on nested_virt (baseboard == Microsoft), but bare-metal
+ Windows hosts need it too, so it must be applied for WHPX regardless.
+ """
+
+ def _build(self, fake_qcow2, *, nested_virt: bool):
+ from quicksand_core.host import WindowsConfig
+ from quicksand_core.qemu.arch import X86_64Config
+
+ platform_config = PlatformConfig(arch=X86_64Config(), os=WindowsConfig())
+ return platform_config.build_qemu_command(
+ config=SandboxConfig(image="ubuntu"),
+ runtime_info=RuntimeInfo(
+ qemu_binary=Path("/usr/bin/qemu-system-x86_64"),
+ qemu_img=Path("/usr/bin/qemu-img"),
+ runtime_dir=Path("/usr"),
+ ),
+ kernel_path=None,
+ initrd_path=None,
+ overlay_path=Path(str(fake_qcow2)),
+ agent_port=12345,
+ agent_token="test_token",
+ accelerator=Accelerator.WHPX,
+ nested_virt=nested_virt,
+ )
+
+ def test_whpx_kernel_irqchip_off_bare_metal(self, fake_qcow2):
+ cmd = self._build(fake_qcow2, nested_virt=False)
+ assert "-accel" in cmd
+ accel_val = cmd[cmd.index("-accel") + 1]
+ assert accel_val == "whpx,kernel-irqchip=off"
+
+ def test_whpx_kernel_irqchip_off_nested(self, fake_qcow2):
+ cmd = self._build(fake_qcow2, nested_virt=True)
+ accel_val = cmd[cmd.index("-accel") + 1]
+ assert accel_val == "whpx,kernel-irqchip=off"
+
+
class TestSandboxContextManager:
"""Tests for async context manager interface."""