Truly independent web browser
#!/usr/bin/env python3
# Copyright (c) 2026, Ali Mohammad Pur <[email protected]>
#
# SPDX-License-Identifier: BSD-2-Clause
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Optional
META_SOURCE_DIR = Path(__file__).resolve().parent.parent
LADYBIRD_SOURCE_DIR = META_SOURCE_DIR.parent
sys.path.append(str(META_SOURCE_DIR))
from Utils.host_platform import HostArchitecture # noqa: E402
from Utils.host_platform import HostSystem # noqa: E402
from Utils.host_platform import Platform # noqa: E402
# The features of vcpkg.json, with the CMake options and their defaults. All options for a feature must be on
# to select it. Keep in sync with Meta/CMake/environment.cmake.
MANIFEST_FEATURE_OPTIONS = {
"qt": {"LADYBIRD_BUILD_QT": False, "ENABLE_GUI_TARGETS": True},
"sparkle": {"LADYBIRD_ENABLE_UPDATE_CHECK": True, "LADYBIRD_ENABLE_SPARKLE": True},
}
# The lists in Meta/CMake of the ports that distribution builds link dynamically. Keep in sync with
# Meta/CMake/vcpkg/distribution-triplets/distribution.cmake.
DYNAMIC_LIBRARY_LISTS = ("lgpl-libraries.txt", "dynamic-libraries.txt")
DEPEND_INFO_REGEX = re.compile(r"^([a-zA-Z0-9-]+)(?:\[([^]]*)\])?(:host)?:\s*(.*)$")
def vcpkg_type(preset: str) -> str:
# environment.cmake derives the overlay triplets from LADYBIRD_VCPKG_TYPE, which each preset sets in its _base.
presets_path = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "presets" / "CMakeBasePresets.json"
with open(presets_path, "r") as presets_file:
presets = json.load(presets_file)["configurePresets"]
for entry in presets:
if entry["name"] == f"{preset}_base":
return entry["cacheVariables"]["LADYBIRD_VCPKG_TYPE"]
raise RuntimeError(f"No LADYBIRD_VCPKG_TYPE for preset {preset} in {presets_path}")
def vcpkg_root() -> Path:
if root := os.environ.get("VCPKG_ROOT"):
return Path(root)
return LADYBIRD_SOURCE_DIR / "Build" / "vcpkg"
def vcpkg_executable(platform: Platform) -> Path:
exe = "vcpkg.exe" if platform.host_system == HostSystem.Windows else "vcpkg"
return vcpkg_root() / exe
def determine_triplet(platform: Platform, preset: str) -> str:
# Keep in sync with the triplet munging in Meta/CMake/vcpkg/generate_vcpkg_toolchain_variables.cmake.
if platform.host_architecture == HostArchitecture.x86_64:
arch = "x64"
elif platform.host_architecture == HostArchitecture.AArch64:
arch = "arm64"
elif platform.host_architecture == HostArchitecture.riscv64:
arch = "riscv64"
else:
raise RuntimeError(f"Unable to determine vcpkg triplet for architecture {platform.architecture}")
if platform.host_system == HostSystem.Linux:
os_name = "linux"
elif platform.host_system == HostSystem.macOS:
os_name = "osx"
elif platform.host_system == HostSystem.Windows:
os_name = "windows"
elif platform.system == "FreeBSD":
os_name = "freebsd"
else:
raise RuntimeError(f"Unable to determine vcpkg triplet for host system {platform.system}")
triplet = f"{arch}-{os_name}"
if vcpkg_type(preset) != "distribution":
if platform.host_system != HostSystem.Windows:
triplet += "-dynamic"
elif platform.host_system == HostSystem.Windows:
triplet += "-static"
return triplet
def overlay_triplets_dir(preset: str) -> Path:
return LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "vcpkg" / f"{vcpkg_type(preset)}-triplets"
def deps_dir_for(build_dir: Path) -> Path:
return build_dir / "vcpkg-deps"
def overlay_ports_dir() -> Path:
return LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "vcpkg" / "overlay-ports"
def binary_cache_dir() -> Path:
# Keep in sync with LADYBIRD_CACHE_DIR in Meta/CMake/environment.cmake.
main_source_dir = os.environ.get("LADYBIRD_MAIN_SOURCE_DIR") or LADYBIRD_SOURCE_DIR
return Path(main_source_dir) / "Build" / "caches" / "vcpkg-binary-cache"
def write_if_changed(path: Path, content: str) -> bool:
if path.exists() and path.read_text() == content:
return False
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
return True
def extra_vcpkg_variables(platform: Platform, cc: str, cxx: str) -> str:
# The data generated by this must be exactly identical to the one generated by Meta/CMake/vcpkg/generate_vcpkg_toolchain_variables.cmake;
# as vcpkg will use the identity of that as part of the ABI hash.
variables = ""
if platform.host_system != HostSystem.Windows:
variables += f"set(ENV{{CC}} {cc})\n"
variables += f"set(ENV{{CXX}} {cxx})\n"
if platform.host_system == HostSystem.Linux and not os.environ.get("LAGOM_USE_LINKER"):
variables += "set(ENV{LDFLAGS} -Wl,-z,noseparate-code)\n"
if platform.host_system == HostSystem.macOS:
# Keep the fallback in sync with CMAKE_OSX_DEPLOYMENT_TARGET in the top-level CMakeLists.txt.
deployment_target = os.environ.get("CMAKE_OSX_DEPLOYMENT_TARGET") or "14.4"
variables += f"set(VCPKG_OSX_DEPLOYMENT_TARGET {deployment_target})\n"
return variables
def vcpkg_environment() -> dict[str, str]:
env = os.environ.copy()
env["VCPKG_ROOT"] = str(vcpkg_root())
# Keep in sync with the environment blocks in Meta/CMake/presets/CMakeBasePresets.json.
binary_sources = f"clear;files,{binary_cache_dir()},readwrite"
if env.get("VCPKG_BINARY_SOURCES"):
binary_sources += f";{env['VCPKG_BINARY_SOURCES']}"
env["VCPKG_BINARY_SOURCES"] = binary_sources
sas = env.get("VCPKG_CACHE_SAS", "")
mode = env.get("VCPKG_CACHE_MODE", "")
env["X_VCPKG_ASSET_SOURCES"] = (
f"clear;x-azurl,https://vcpkg-cache.app.ladybird.org/ladybird/source-assets/,{sas},read{mode}"
)
return env
def common_vcpkg_arguments(triplet: str, preset: str) -> list[str]:
return [
f"--triplet={triplet}",
f"--host-triplet={triplet}",
f"--overlay-triplets={overlay_triplets_dir(preset)}",
]
def cmake_option_is_on(cache: str, option: str, default: bool) -> bool:
# The values that count as off are the constants that CMake's if() takes as false.
match = re.search(rf"^{option}:[A-Z]+=(.*)$", cache, re.MULTILINE)
if not match:
return default
value = match.group(1).strip().upper()
return value not in ("", "0", "OFF", "NO", "FALSE", "N", "IGNORE", "NOTFOUND") and not value.endswith("-NOTFOUND")
def manifest_feature_arguments(build_dir: Path) -> list[str]:
# Only a build directory that CMake configured before has options to go by.
cache_path = build_dir / "CMakeCache.txt"
cache = cache_path.read_text() if cache_path.exists() else ""
return [
f"--x-feature={feature}"
for feature, options in MANIFEST_FEATURE_OPTIONS.items()
if all(cmake_option_is_on(cache, option, default) for option, default in options.items())
]
def vcpkg_install_arguments(vcpkg: Path, triplet: str, preset: str) -> list[str]:
return [str(vcpkg), "install", *common_vcpkg_arguments(triplet, preset), "--no-print-usage"]
class PortNode:
def __init__(self, name: str):
self.name = name
self.features: set[str] = set()
self.dependencies: set[str] = set()
def query_dependency_graph(
vcpkg: Path, triplet: str, preset: str, install_root: Path, feature_arguments: list[str]
) -> dict[str, PortNode]:
# NOTE: depend-info still takes the install root's lock, so keep it out of the source tree.
result = subprocess.run(
[
str(vcpkg),
"depend-info",
*common_vcpkg_arguments(triplet, preset),
*feature_arguments,
f"--x-install-root={install_root}",
"--format=list",
],
cwd=LADYBIRD_SOURCE_DIR,
env=vcpkg_environment(),
capture_output=True,
text=True,
)
if result.returncode != 0:
print(result.stdout, file=sys.stderr)
print(result.stderr, file=sys.stderr)
raise RuntimeError("vcpkg depend-info failed")
# NOTE: This folds host and target entries, same as what vcpkg does.
# FIXME: Investigate when cross-compilation becomes a problem this has to touch.
graph: dict[str, PortNode] = {}
for line in (result.stdout + result.stderr).splitlines():
match = DEPEND_INFO_REGEX.match(line.strip())
if not match:
continue
name, features, _, dependencies = match.groups()
node = graph.setdefault(name, PortNode(name))
if features:
node.features.update(f for f in (feature.strip() for feature in features.split(",")) if f and f != "core")
for dependency in dependencies.split(","):
dependency = dependency.strip()
if not dependency:
continue
dependency = dependency.split("[")[0].removesuffix(":host")
if dependency != name:
node.dependencies.add(dependency)
return graph
def dependency_closure(graph: dict[str, PortNode], port: str) -> set[str]:
closure: set[str] = set()
queue = [port]
while queue:
current = queue.pop()
if current in closure:
continue
closure.add(current)
queue.extend(graph[current].dependencies)
return closure
def solo_manifest(graph: dict[str, PortNode], port: str, baseline: str, overrides: list) -> str:
# Resolve the largest set of features requested by any dependency, for any dependency; we will build every dep exactly once, so we must know the closure in advance.
dependencies = []
for name in sorted(dependency_closure(graph, port)):
dependency: dict = {"name": name, "default-features": False}
if graph[name].features:
dependency["features"] = sorted(graph[name].features)
dependencies.append(dependency)
manifest = {
"builtin-baseline": baseline,
"dependencies": dependencies,
"overrides": overrides,
}
return json.dumps(manifest, indent=2) + "\n"
def ninja_escape(value: str) -> str:
return value.replace("$", "$$").replace(" ", "$ ").replace(":", "$:")
def generate_build_files(
platform: Platform,
preset: str,
build_dir: Path,
vcpkg: Path,
triplet: str,
graph: dict[str, PortNode],
) -> Path:
deps_dir = deps_dir_for(build_dir)
deps_dir.mkdir(parents=True, exist_ok=True)
with open(LADYBIRD_SOURCE_DIR / "vcpkg.json", "r") as vcpkg_json_file:
vcpkg_json = json.load(vcpkg_json_file)
baseline = vcpkg_json["builtin-baseline"]
overrides = vcpkg_json.get("overrides", [])
variables = extra_vcpkg_variables_path(build_dir).read_text()
triplet_inputs = []
for triplet_dir in (
overlay_triplets_dir(preset),
overlay_triplets_dir(preset).parent / "base-triplets",
):
triplet_inputs.extend(sorted(str(f) for f in triplet_dir.glob("*.cmake")))
triplet_inputs.extend(str(LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / name) for name in DYNAMIC_LIBRARY_LISTS)
lines = [
"ninja_required_version = 1.5",
"",
"rule vcpkg_port",
f' command = "{sys.executable}" "{Path(__file__).resolve()}" run-node'
f' --vcpkg "{vcpkg}" --triplet {triplet} --preset {preset} --node-dir "$node_dir" --stamp "$out"',
" description = vcpkg $port",
"",
]
for name in sorted(graph):
node_dir = deps_dir / name
write_if_changed(node_dir / "vcpkg.json", solo_manifest(graph, name, baseline, overrides))
write_if_changed(node_dir / "build-vcpkg-variables.cmake", variables)
inputs = [
str(node_dir / "vcpkg.json"),
str(node_dir / "build-vcpkg-variables.cmake"),
]
inputs.extend(triplet_inputs)
overlay_port = overlay_ports_dir() / name
if overlay_port.is_dir():
inputs.extend(sorted(str(f) for f in overlay_port.rglob("*") if f.is_file()))
order_only = [str(deps_dir / dependency / ".stamp") for dependency in sorted(graph[name].dependencies)]
build_line = f"build {ninja_escape(str(node_dir / '.stamp'))}: vcpkg_port"
build_line += " " + " ".join(ninja_escape(i) for i in inputs)
if order_only:
build_line += " || " + " ".join(ninja_escape(o) for o in order_only)
lines.append(build_line)
lines.append(f" node_dir = {ninja_escape(str(node_dir))}")
lines.append(f" port = {name}")
lines.append("")
write_if_changed(deps_dir / "build.ninja", "\n".join(lines))
return deps_dir
def extra_vcpkg_variables_path(build_dir: Path) -> Path:
return build_dir / "build-vcpkg-variables.cmake"
# Without ladybird.py's shared pool, each port gets a private pool this large.
PRIVATE_POOL_SIZE = 2
# Builds that pass VCPKG_CONCURRENCY as their own -j run outside the pool.
UNPOOLED_JOBS = 2
# GNU Make takes a jobserver FIFO from 4.4 on, and Ninja from 1.13.
FIFO_JOBSERVER_MAKE_VERSION = (4, 4)
FIFO_JOBSERVER_NINJA_VERSION = (1, 13)
def tool_version(executable: str, version_pattern: str) -> Optional[tuple[int, int]]:
try:
output = subprocess.run([executable, "--version"], capture_output=True, text=True).stdout
except OSError:
return None
match = re.match(version_pattern, output)
if not match:
return None
return (int(match[1]), int(match[2]))
def make_takes_jobserver_fifo(make: str) -> bool:
version = tool_version(make, r"GNU Make (\d+)\.(\d+)")
return version is not None and version >= FIFO_JOBSERVER_MAKE_VERSION
def jobserver_make_directory(deps_dir: Path) -> Optional[Path]:
make = shutil.which("make")
if make and make_takes_jobserver_fifo(make):
return None
# vcpkg's make helpers look for plain `make` in PATH, so offer a newer gmake (e.g. Homebrew's) under that name.
gmake = shutil.which("gmake")
if gmake and make_takes_jobserver_fifo(gmake):
directory = deps_dir / "gnu-make"
directory.mkdir(exist_ok=True)
link = directory / "make"
link.unlink(missing_ok=True)
link.symlink_to(gmake)
return directory
print(
f"warning: GNU Make 4.4 or newer wasn't found, so ports built with make are limited to {UNPOOLED_JOBS} jobs."
" On macOS, install it with `brew install make`."
)
return None
def warn_if_ninja_lacks_jobserver(vcpkg: Path, environment: dict[str, str]):
# This is the ninja that vcpkg will build ports with, which is the system's if VCPKG_FORCE_SYSTEM_BINARIES is set.
fetch = subprocess.run([str(vcpkg), "fetch", "ninja"], capture_output=True, text=True, env=environment)
output_lines = fetch.stdout.strip().splitlines()
if fetch.returncode != 0 or not output_lines:
return
version = tool_version(output_lines[-1], r"(\d+)\.(\d+)")
if version is not None and version < FIFO_JOBSERVER_NINJA_VERSION:
print(
f"warning: vcpkg's Ninja is older than 1.13, so ports built with Ninja are limited to {UNPOOLED_JOBS} jobs."
" Install Ninja 1.13 or newer."
)
def warn_once_about_private_pools(deps_dir: Path):
# Every node of one ninja run shares a parent, so warn once per ninja run.
marker = deps_dir / ".private-pool-warning"
ninja_pid = str(os.getppid())
try:
if marker.read_text() == ninja_pid:
return
except FileNotFoundError:
pass
marker.write_text(ninja_pid)
print(
f"warning: vcpkg dependencies are being built without Meta/ladybird.py, so each port is limited to"
f" {PRIVATE_POOL_SIZE} jobs. Run `Meta/ladybird.py deps` instead.",
file=sys.stderr,
)
def run_node(arguments: argparse.Namespace):
node_dir = Path(arguments.node_dir)
install_arguments = vcpkg_install_arguments(Path(arguments.vcpkg), arguments.triplet, arguments.preset)
install_arguments.extend(
[
f"--overlay-ports={overlay_ports_dir()}",
f"--x-manifest-root={node_dir}",
f"--x-install-root={node_dir / 'vcpkg_installed'}",
f"--x-packages-root={node_dir / 'packages'}",
# vcpkg really likes locks, so we give it a new build tree to lock to its heart's content.
f"--x-buildtrees-root={node_dir / 'buildtrees'}",
"--clean-buildtrees-after-build",
"--clean-packages-after-build",
]
)
environment = vcpkg_environment()
private_fifo = None
token_fifo = environment.get("LADYBIRD_VCPKG_TOKEN_FIFO")
if token_fifo and Path(token_fifo).exists():
pool = int(environment["LADYBIRD_VCPKG_TOKEN_POOL"])
fifo_fd = os.open(token_fifo, os.O_RDWR)
else:
warn_once_about_private_pools(node_dir.parent)
pool = PRIVATE_POOL_SIZE
private_fifo = node_dir / ".tokens"
private_fifo.unlink(missing_ok=True)
os.mkfifo(private_fifo)
token_fifo = str(private_fifo)
fifo_fd = os.open(token_fifo, os.O_RDWR)
os.write(fifo_fd, b"x" * pool)
# This token is the node's own job; the make and ninja under vcpkg take any more from the pool as jobserver clients.
own_token = os.read(fifo_fd, 1)
environment["MAKEFLAGS"] = f" --jobserver-auth=fifo:{token_fifo}"
environment["VCPKG_MAX_CONCURRENCY"] = str(UNPOOLED_JOBS)
log_path = node_dir / "build.log"
try:
with open(log_path, "w") as log:
log.write(f"[vcpkg-deps] Taking build jobs from a pool of {pool} at {token_fifo}\n")
log.flush()
result = subprocess.run(install_arguments, env=environment, stdout=log, stderr=subprocess.STDOUT)
finally:
os.write(fifo_fd, own_token)
os.close(fifo_fd)
if private_fifo:
private_fifo.unlink(missing_ok=True)
if result.returncode != 0:
log_lines = log_path.read_text().splitlines()
print("\n".join(log_lines[-60:]), file=sys.stderr)
print(f"\nFull build log: {log_path}", file=sys.stderr)
sys.exit(result.returncode)
Path(arguments.stamp).touch()
def run_quietly(arguments: list[str], log_path: Path, environment: dict[str, str]):
with open(log_path, "w") as log:
result = subprocess.run(
arguments,
cwd=LADYBIRD_SOURCE_DIR,
env=environment,
stdout=log,
stderr=subprocess.STDOUT,
)
if result.returncode != 0:
log_lines = log_path.read_text().splitlines()
print("\n".join(log_lines[-60:]), file=sys.stderr)
print(f"\nFull log: {log_path}", file=sys.stderr)
raise subprocess.CalledProcessError(result.returncode, arguments)
def restore_stamp_content(features: list[str]) -> str:
return "features: " + " ".join(features) + "\n"
def install_is_stale(deps_dir: Path, graph: dict[str, PortNode], install_root: Path, features: list[str]) -> bool:
restore_stamp = deps_dir / ".restore-stamp"
if not restore_stamp.exists() or not (install_root / "vcpkg").is_dir():
return True
# The stamp names the features that were installed, which change with the options of the build.
if restore_stamp.read_text() != restore_stamp_content(features):
return True
restore_time = restore_stamp.stat().st_mtime
for name in graph:
stamp = deps_dir / name / ".stamp"
if not stamp.exists() or stamp.stat().st_mtime > restore_time:
return True
return False
def build_dependencies(
platform: Platform,
preset: str,
build_dir: Path,
cc: str,
cxx: str,
jobs: Optional[str] = None,
fetch_only: bool = False,
rebuild: bool = False,
) -> str:
vcpkg = vcpkg_executable(platform)
triplet = determine_triplet(platform, preset)
environment = vcpkg_environment()
import fcntl
# Hold the lock while generating inputs too, so a concurrent invocation can't rewrite them under our build.
deps_dir = deps_dir_for(build_dir)
deps_dir.mkdir(parents=True, exist_ok=True)
lock_fd = os.open(deps_dir / ".lock", os.O_RDWR | os.O_CREAT, 0o644)
try:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("Another dependency build is running against this build directory; waiting for it to finish...")
fcntl.flock(lock_fd, fcntl.LOCK_EX)
write_if_changed(extra_vcpkg_variables_path(build_dir), extra_vcpkg_variables(platform, cc, cxx))
# CMake can rewrite its cache while this runs, so everything below goes by one reading of the features.
feature_arguments = manifest_feature_arguments(build_dir)
manifest_arguments = vcpkg_install_arguments(vcpkg, triplet, preset)
manifest_arguments.extend(feature_arguments)
manifest_arguments.append(f"--x-install-root={build_dir / 'vcpkg_installed'}")
if fetch_only:
subprocess.check_call(
manifest_arguments + ["--only-downloads"],
cwd=LADYBIRD_SOURCE_DIR,
env=environment,
)
return triplet
graph = query_dependency_graph(vcpkg, triplet, preset, build_dir / "vcpkg_installed", feature_arguments)
generate_build_files(platform, preset, build_dir, vcpkg, triplet, graph)
# Wipe the stamps if the binary cache is gone.
have_stamps = any((deps_dir / name / ".stamp").exists() for name in graph)
cache_is_empty = not any(binary_cache_dir().glob("*/*.zip"))
if rebuild or (have_stamps and cache_is_empty):
if not rebuild:
print("Binary cache is empty but dependency stamps exist; rebuilding dependencies from scratch.")
for name in graph:
(deps_dir / name / ".stamp").unlink(missing_ok=True)
shutil.rmtree(deps_dir / name / "vcpkg_installed", ignore_errors=True)
check = subprocess.run(["ninja", "-C", str(deps_dir), "-n"], capture_output=True, text=True)
have_work = "no work to do" not in check.stdout
if have_work:
run_quietly(manifest_arguments + ["--dry-run"], deps_dir / "plan.log", environment)
tokens = int(jobs) if jobs else (os.cpu_count() or 2) + 2
token_fifo = deps_dir / ".tokens"
token_fifo.unlink(missing_ok=True)
os.mkfifo(token_fifo)
fifo_fd = os.open(token_fifo, os.O_RDWR)
os.write(fifo_fd, b"x" * tokens)
ninja_environment = os.environ.copy()
# Only the nodes take jobs from the pool; ninja joining it as well would count each node twice.
ninja_environment.pop("MAKEFLAGS", None)
if make_directory := jobserver_make_directory(deps_dir):
ninja_environment["PATH"] = os.pathsep.join([str(make_directory), ninja_environment.get("PATH", "")])
warn_if_ninja_lacks_jobserver(vcpkg, environment)
ninja_environment["LADYBIRD_VCPKG_TOKEN_FIFO"] = str(token_fifo)
ninja_environment["LADYBIRD_VCPKG_TOKEN_POOL"] = str(tokens)
try:
ninja_arguments = ["ninja", "-C", str(deps_dir)]
if jobs:
ninja_arguments.extend(["-j", jobs])
subprocess.check_call(ninja_arguments, env=ninja_environment)
finally:
os.close(fifo_fd)
token_fifo.unlink(missing_ok=True)
if install_is_stale(deps_dir, graph, build_dir / "vcpkg_installed", feature_arguments):
print("Installing dependencies from the binary cache...")
# A restore that stops halfway must not leave a stamp that vouches for what it removed.
(deps_dir / ".restore-stamp").unlink(missing_ok=True)
run_quietly(manifest_arguments, deps_dir / "restore.log", environment)
(deps_dir / ".restore-stamp").write_text(restore_stamp_content(feature_arguments))
finally:
os.close(lock_fd)
return triplet
def main():
parser = argparse.ArgumentParser(description="vcpkg dependency build node")
subparsers = parser.add_subparsers(dest="command", required=True)
node_parser = subparsers.add_parser("run-node")
node_parser.add_argument("--vcpkg", required=True)
node_parser.add_argument("--triplet", required=True)
node_parser.add_argument("--preset", required=True)
node_parser.add_argument("--node-dir", required=True)
node_parser.add_argument("--stamp", required=True)
arguments = parser.parse_args()
if arguments.command == "run-node":
run_node(arguments)
if __name__ == "__main__":
main()