Files
client/xtask/src/deps.rs
T
omar eb24965076
ci / linux-arm64-cross (push) Successful in 4m7s
ci / linux-x64 (push) Successful in 4m42s
Implement Rust and Slint native client migration and fix desktop startup
2026-11-10 15:45:24 +03:00

766 lines
46 KiB
Rust

//! Pinned source provisioning. This never invokes a package manager or accepts a
//! downloaded WebRTC archive. The source checkout and all generated files belong
//! to target/native-deps/<triple>; the committed lock records completed builds.
use std::{
collections::BTreeMap,
ffi::OsStr,
fs::{self, File},
io::{Read, Write},
path::{Path, PathBuf},
process::Command,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use crate::{Options, build_native::Environment};
const SDK_REV: &str = "88705b15086ecbe2c26ee91ede6203f974a0fc62";
const WEBRTC_REV: &str = "9c3a1386f07e4348c28cd85c066821cebc3b56e4";
const DEPOT_REV: &str = "2f9bc10799af5aeb4a0ed903742ad69bb1d0ef75";
const LOCK: &str = "native/native-deps.lock.json";
#[derive(Clone, Copy)]
pub(crate) struct Target<'a> {
pub triple: &'a str,
pub os: &'static str,
pub cpu: &'static str,
pub simulator: bool,
}
impl<'a> Target<'a> {
pub fn parse(triple: &'a str) -> Result<Self, String> {
let (os, cpu, simulator) = match triple {
"x86_64-pc-windows-msvc" => ("win", "x64", false),
"aarch64-pc-windows-msvc" => ("win", "arm64", false),
"x86_64-unknown-linux-gnu" => ("linux", "x64", false),
"aarch64-unknown-linux-gnu" => ("linux", "arm64", false),
"x86_64-apple-darwin" => ("mac", "x64", false),
"aarch64-apple-darwin" => ("mac", "arm64", false),
"aarch64-linux-android" => ("android", "arm64", false),
"x86_64-linux-android" => ("android", "x64", false),
"aarch64-apple-ios" => ("ios", "arm64", false),
"aarch64-apple-ios-sim" => ("ios", "arm64", true),
_ => return Err(format!("unsupported native target: {triple}")),
};
Ok(Self { triple, os, cpu, simulator })
}
pub fn check_host(self) -> Result<(), String> {
let expected = match self.os { "win" => "windows", "mac" | "ios" => "macos", _ => "linux" };
if std::env::consts::OS != expected {
return Err(format!("{} requires a {expected} source-build host, not {}; no SDK is downloaded or installed on an incompatible host", self.triple, std::env::consts::OS));
}
Ok(())
}
}
pub(crate) fn cache(root: &Path, target: Target<'_>) -> PathBuf {
root.join("target/native-deps").join(target.triple)
}
fn command_label(command: &Command) -> String {
format!("{:?} {:?}", command.get_program(), command.get_args().collect::<Vec<_>>())
}
pub(crate) fn run(command: &mut Command) -> Result<(), String> {
let label = command_label(command);
eprintln!("+ {label}");
let status = command.status().map_err(|e| format!("starting {label}: {e}"))?;
if !status.success() { return Err(format!("command failed ({status}): {label}")); }
Ok(())
}
pub(crate) fn capture(command: &mut Command) -> Result<String, String> {
let label = command_label(command);
let result = command.output().map_err(|e| format!("starting {label}: {e}"))?;
if !result.status.success() {
return Err(format!("command failed ({}): {label}\n{}", result.status, String::from_utf8_lossy(&result.stderr)));
}
String::from_utf8(result.stdout).map_err(|e| format!("non-UTF8 output from {label}: {e}"))
}
pub(crate) fn read_text(path: &Path) -> Result<String, String> {
fs::read_to_string(path).map_err(|e| format!("reading {}: {e}", path.display()))
}
fn read_json(path: &Path) -> Result<Value, String> {
serde_json::from_str(&read_text(path)?).map_err(|e| format!("parsing {}: {e}", path.display()))
}
pub(crate) fn require_file(path: &Path) -> Result<(), String> {
if !path.is_file() { return Err(format!("required file is missing: {}", path.display())); }
Ok(())
}
fn mkdir(path: &Path) -> Result<(), String> {
fs::create_dir_all(path).map_err(|e| format!("creating {}: {e}", path.display()))
}
fn save(path: &Path, bytes: impl AsRef<[u8]>) -> Result<(), String> {
if let Some(parent) = path.parent() { mkdir(parent)?; }
fs::write(path, bytes).map_err(|e| format!("writing {}: {e}", path.display()))
}
fn copy(source: &Path, destination: &Path) -> Result<(), String> {
require_file(source)?;
if let Some(parent) = destination.parent() { mkdir(parent)?; }
if destination.is_file() {
if sha256(source)? == sha256(destination)? { return Ok(()); }
#[cfg(windows)] {
let mut permissions = fs::metadata(destination).map_err(|e| e.to_string())?.permissions();
if permissions.readonly() {
permissions.set_readonly(false);
fs::set_permissions(destination, permissions).map_err(|e| e.to_string())?;
}
}
}
fs::copy(source, destination).map_err(|e| format!("copying {} to {}: {e}", source.display(), destination.display()))?;
Ok(())
}
pub(crate) fn sha256(path: &Path) -> Result<String, String> {
let mut file = File::open(path).map_err(|e| format!("opening {}: {e}", path.display()))?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
loop {
let size = file.read(&mut buffer).map_err(|e| format!("hashing {}: {e}", path.display()))?;
if size == 0 { break; }
hash.update(&buffer[..size]);
}
Ok(format!("{:x}", hash.finalize()))
}
fn bytes_hash(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) }
fn text<'a>(value: &'a Value, name: &str) -> Result<&'a str, String> {
value.get(name).and_then(Value::as_str).ok_or_else(|| format!("dependency lock is missing string {name}"))
}
fn lock_policy(root: &Path) -> Result<Value, String> {
let lock = read_json(&root.join(LOCK))?;
if lock["schema"] != 1 || lock["sdk"]["revision"] != SDK_REV || lock["webrtc"]["revision"] != WEBRTC_REV || lock["depot_tools"]["revision"] != DEPOT_REV {
return Err("unsupported native dependency lock or source revision; update the provisioning implementation deliberately, never float to a branch".into());
}
Ok(lock)
}
fn policy_hash(lock: &Value) -> Result<String, String> {
let mut policy = lock.clone();
policy.as_object_mut().ok_or("dependency lock must be an object")?.remove("builds");
Ok(bytes_hash(&serde_json::to_vec(&policy).map_err(|e| e.to_string())?))
}
fn driver_hashes(root: &Path) -> Result<Value, String> {
let mut files = BTreeMap::new();
for relative in ["xtask/src/main.rs", "xtask/src/deps.rs", "xtask/src/build_native.rs"] {
files.insert(relative, sha256(&root.join(relative))?);
}
Ok(json!(files))
}
/// Serializes provisioning across targets as they update one committed lock.
/// An interrupted process leaves an explicit lock to inspect, not a fabricated
/// completed record or an automatically stolen lock from another build.
struct ProvisionLease(PathBuf);
impl ProvisionLease {
fn acquire(root: &Path) -> Result<Self, String> {
let path = root.join("target/native-deps/.provision-lock");
mkdir(path.parent().ok_or("missing cache parent")?)?;
let mut file = File::options().write(true).create_new(true).open(&path)
.map_err(|e| format!("cannot acquire {}: {e}; another provisioner may be running; after an interrupted build inspect and remove this file explicitly", path.display()))?;
writeln!(file, "pid={}", std::process::id()).map_err(|e| e.to_string())?;
Ok(Self(path))
}
}
impl Drop for ProvisionLease { fn drop(&mut self) { let _ = fs::remove_file(&self.0); } }
fn checkout(env: &Environment, directory: &Path, source: &Value) -> Result<(), String> {
let revision = text(source, "revision")?;
let url = text(source, "url")?;
if directory.join(".git").exists() {
let actual = capture(env.command("git").arg("-C").arg(directory).args(["rev-parse", "HEAD"]))?;
let origin = capture(env.command("git").arg("-C").arg(directory).args(["remote", "get-url", "origin"]))?;
if actual.trim() != revision || origin.trim() != url {
return Err(format!("{} is not the pinned checkout ({url}@{revision}); refusing to reset an existing tree", directory.display()));
}
return Ok(());
}
if directory.exists() && fs::read_dir(directory).map_err(|e| e.to_string())?.next().is_some() {
return Err(format!("{} is nonempty but not a Git checkout", directory.display()));
}
mkdir(directory)?;
run(env.command("git").arg("init").arg(directory))?;
run(env.command("git").arg("-C").arg(directory).args(["config", "core.autocrlf", "false"]))?;
run(env.command("git").arg("-C").arg(directory).args(["config", "core.longpaths", "true"]))?;
run(env.command("git").arg("-C").arg(directory).args(["remote", "add", "origin", url]))?;
run(env.command("git").arg("-C").arg(directory).args(["fetch", "--depth=1", "origin", revision]))?;
run(env.command("git").arg("-C").arg(directory).args(["checkout", "--detach", "FETCH_HEAD"]))?;
let actual = capture(env.command("git").arg("-C").arg(directory).args(["rev-parse", "HEAD"]))?;
if actual.trim() != revision { return Err(format!("unexpected revision after fetching {url}: {actual}")); }
Ok(())
}
fn apply_patch(env: &Environment, source: &Path, patch: &Path, expected: &str) -> Result<(), String> {
if sha256(patch)? != expected { return Err(format!("patch SHA256 mismatch: {}", patch.display())); }
let reverse = env.command("git").arg("-C").arg(source)
.args(["apply", "--reverse", "--check"]).arg(patch).output().map_err(|e| e.to_string())?;
if reverse.status.success() { return Ok(()); }
// No whitespace/fuzz tolerance: a revision incompatibility must stop here.
run(env.command("git").arg("-C").arg(source).args(["apply", "--check"]).arg(patch))
.map_err(|e| format!("pinned patch is incompatible, not skipping {}:\n{e}", patch.display()))?;
run(env.command("git").arg("-C").arg(source).args(["apply", "--whitespace=error"]).arg(patch))
}
fn gn_args(target: Target<'_>) -> String {
let mut args = vec![
"is_debug=false".to_owned(), format!("target_os=\"{}\"", target.os), format!("target_cpu=\"{}\"", target.cpu),
"is_clang=true".into(), "is_component_build=false".into(), "rtc_include_tests=false".into(),
"rtc_build_examples=false".into(), "rtc_build_tools=false".into(), "rtc_enable_protobuf=false".into(),
"rtc_use_h264=true".into(), "ffmpeg_branding=\"Chrome\"".into(), "rtc_libvpx_build_vp9=true".into(),
"enable_libaom=true".into(), "rtc_include_dav1d_in_internal_decoder_factory=true".into(),
"symbol_level=0".into(), "enable_iterator_debugging=false".into(), "use_clang_modules=false".into(),
"use_rtti=true".into(), "treat_warnings_as_errors=false".into(),
];
if target.os == "linux" {
args.extend(["use_custom_libcxx=true", "use_custom_libcxx_for_host=true", "use_llvm_libatomic=false", "rtc_use_pipewire=true", "rtc_use_x11=true"].map(str::to_owned));
} else {
args.push("use_custom_libcxx=false".into());
}
match target.os {
"android" => args.extend(["android_package_prefix=\"livekit\"", "is_java_debug=false", "default_min_sdk_version=26", "android_ndk_api_level=26", "rtc_use_pipewire=false", "android_static_analysis=\"off\""].map(str::to_owned)),
"mac" | "ios" => {
args.extend(["enable_dsyms=false", "rtc_enable_symbol_export=true", "rtc_enable_objc_symbol_export=false", "clang_use_chrome_plugins=false", "use_lld=false"].map(str::to_owned));
if target.os == "ios" {
args.extend(["ios_enable_code_signing=false".into(), "ios_deployment_target=\"16.0\"".into(), format!("target_environment=\"{}\"", if target.simulator { "simulator" } else { "device" })]);
} else {
args.extend(["mac_deployment_target=\"14.2\"", "mac_min_system_version=\"14.2\"", "rtc_include_internal_audio_device=true"].map(str::to_owned));
}
}
_ => {}
}
args.join("\n") + "\n"
}
fn selected_patches<'a>(lock: &'a Value, target: Target<'_>) -> Result<Vec<&'a Value>, String> {
Ok(lock["sdk_patches"].as_array().ok_or("lock has no SDK patch list")?.iter()
.filter(|p| p["platforms"].as_array().is_some_and(|oses| oses.iter().any(|os| os == target.os))).collect())
}
fn gclient(env: &Environment, depot: &Path, checkout: &Path) -> Command {
let launcher = depot.join(if cfg!(windows) { "gclient.bat" } else { "gclient" });
let mut command = env.command(launcher);
command.current_dir(checkout);
command
}
pub(crate) fn provision(root: &Path, options: &Options) -> Result<(), String> {
let target = Target::parse(&options.target)?;
target.check_host()?;
let mut environment = Environment::discover(root, options, target, false)?;
environment.check_source_prerequisites(target)?;
let _lease = ProvisionLease::acquire(root)?;
let mut lock = lock_policy(root)?;
let base = cache(root, target);
let sdk = base.join("sdk");
let depot = base.join("depot_tools");
let checkout_root = base.join("checkout");
let source = checkout_root.join("src");
let out = source.join("out/teamspeach-release");
let artifact = base.join("webrtc");
checkout(&environment, &sdk, &lock["sdk"])?;
checkout(&environment, &depot, &lock["depot_tools"])?;
environment.prepend_path(&depot)?;
environment.set("DEPOT_TOOLS_UPDATE", "0");
environment.set("DEPOT_TOOLS_WIN_TOOLCHAIN", "0");
environment.set("DEPOT_TOOLS_METRICS", "0");
environment.set("GCLIENT_SUPPRESS_GC", "1");
environment.set("CIPD_CACHE_DIR", base.join("cipd-cache"));
environment.set("VPYTHON_VIRTUALENV_ROOT", base.join("vpython-cache"));
environment.set("GIT_CONFIG_COUNT", "2");
environment.set("GIT_CONFIG_KEY_0", "core.autocrlf");
environment.set("GIT_CONFIG_VALUE_0", "false");
environment.set("GIT_CONFIG_KEY_1", "core.longpaths");
environment.set("GIT_CONFIG_VALUE_1", "true");
if cfg!(windows) {
run(&mut environment.command(depot.join("bootstrap/win_tools.bat")))?;
}
checkout(&environment, &source, &lock["webrtc"])?;
let config = format!("solutions = [{{'name': 'src', 'url': '{}@{}', 'deps_file': 'DEPS', 'managed': False, 'custom_deps': {{}}}}]\ntarget_os = ['{}']\ntarget_cpu = ['{}']\n", text(&lock["webrtc"], "url")?, WEBRTC_REV, target.os, target.cpu);
let config_path = checkout_root.join(".gclient");
if config_path.exists() && read_text(&config_path)? != config { return Err("existing .gclient differs from the pinned target configuration".into()); }
save(&config_path, &config)?;
let mut sync = gclient(&environment, &depot, &checkout_root);
// The root is already checked out and verified at WEBRTC_REV. A revision
// override changes gclient's unmanaged root into a managed checkout and
// rejects the exact SDK patches on the next invocation.
sync.args(["sync", "--no-history", "--nohooks"]);
if let Some(jobs) = options.jobs { sync.arg(format!("--jobs={jobs}")); }
run(&mut sync)?;
checkout(&environment, &source, &lock["webrtc"])?;
for entry in selected_patches(&lock, target)? {
apply_patch(&environment, &source.join(text(entry, "directory")?), &sdk.join(text(entry, "path")?), text(entry, "sha256")?)?;
}
for entry in lock["patches"].as_array().ok_or("lock has no application patch list")? {
if entry["platforms"].as_array().is_some_and(|oses| !oses.iter().any(|os| os == target.os)) { continue; }
let repository = if entry["repository"] == "sdk" { &sdk } else { &source };
apply_patch(&environment, &repository.join(text(entry, "directory")?), &root.join(text(entry, "path")?), text(entry, "sha256")?)?;
}
// Hooks fetch only pinned checkout-local compiler/sysroot assets. The SDK's
// install-build-deps scripts and unpinned build scripts are never invoked.
run(gclient(&environment, &depot, &checkout_root).arg("runhooks"))?;
// The WebRTC SDK commit need not carry Chromium's Change-Id footer. In a
// shallow checkout that filter yields epoch zero and an invalid PE timestamp.
// Record the verified WebRTC HEAD itself, never a dummy version or wall clock.
run(environment.command(depot.join(if cfg!(windows) { "vpython3.bat" } else { "vpython3" }))
.arg(source.join("build/util/lastchange.py"))
.args(["--filter", "", "--source-dir"]).arg(&source)
.arg("--output").arg(source.join("build/util/LASTCHANGE")))?;
copy(&source.join(".vpython3"), &checkout_root.join(".vpython3"))?;
let dependencies_path = base.join("resolved-dependencies.json");
run(gclient(&environment, &depot, &checkout_root).args(["revinfo", "--actual", "--output-json"]).arg(&dependencies_path))?;
let dependencies = read_json(&dependencies_path)?;
let deps_files = dependency_files(&checkout_root, &dependencies)?;
let args = gn_args(target);
mkdir(&out)?;
// C++ object compatibility depends on the pinned source/patch policy, GN
// arguments and resolved DEPS, not edits to receipt/reporting Rust code.
// The full driver hashes remain part of the completed provenance receipt.
let fingerprint = json!({"policy":policy_hash(&lock)?, "gn_args":args, "dependencies":dependencies});
let marker = out.join("teamspeach-inputs.json");
if marker.exists() {
let previous = read_json(&marker)?;
if ["policy", "gn_args", "dependencies"].iter().any(|field| previous[*field] != fingerprint[*field]) {
return Err(format!("build inputs changed; refusing to reuse potentially stale object files in {}. Move that generated output directory aside explicitly and rerun deps", out.display()));
}
}
save(&marker, serde_json::to_vec_pretty(&fingerprint).map_err(|e| e.to_string())?)?;
save(&out.join("args.gn"), &args)?;
let gn = source.join(format!("buildtools/{}/{}", match std::env::consts::OS { "windows" => "win", "macos" => "mac", _ => "linux64" }, executable("gn")));
let ninja = source.join("third_party/ninja").join(executable("ninja"));
require_file(&gn)?;
require_file(&ninja)?;
run(environment.command(&gn).current_dir(&source).arg("gen").arg(&out).arg("--fail-on-unused-args"))?;
verify_codec_graph(&environment, &gn, &source, &out, target)?;
let effective_args = capture(environment.command(&gn).current_dir(&source).arg("args").arg(&out).args(["--list", "--short"]))?;
if target.os == "win" {
let flags = capture(environment.command(&gn).current_dir(&source).arg("desc").arg(&out).args(["//:webrtc", "cflags"]))?;
if !flags.split_whitespace().any(|flag| flag == "/MT") || flags.split_whitespace().any(|flag| matches!(flag, "/MD" | "/MDd" | "/MTd")) {
return Err("WebRTC GN target does not select the required static release /MT CRT".into());
}
}
let mut targets = vec![":default"];
if target.os == "android" { targets.extend(["sdk/android:native_api", "sdk/android:libwebrtc", "sdk/android:libjingle_peerconnection_so"]); }
if matches!(target.os, "mac" | "ios") {
targets.extend(["api/audio_codecs:builtin_audio_decoder_factory", "api/task_queue:default_task_queue_factory", "sdk:native_api", "sdk:default_codec_factory_objc", "pc:peer_connection", "sdk:videocapture_objc"]);
targets.push(if target.os == "mac" { "sdk:mac_framework_objc" } else { "sdk:framework_objc" });
if target.os == "mac" { targets.extend(["desktop_capture_objc", "modules/audio_device:audio_device"]); }
}
ninja_build(&environment, &ninja, &out, options.jobs, &targets)?;
if target.os == "linux" {
let graph = capture(environment.command(&ninja).arg("-C").arg(&out).args(["-t", "targets", "all"]))?;
let libraries: Vec<&str> = graph.lines().filter_map(|line| line.split_once(':').map(|(name, _)| name))
.filter(|name| name.starts_with("obj/") && (name.ends_with("/libc++.a") || name.ends_with("/libc++abi.a"))).collect();
if libraries.len() < 2 { return Err("GN graph does not contain target hermetic libc++ AND libc++abi archives".into()); }
ninja_build(&environment, &ninja, &out, options.jobs, &libraries)?;
}
mkdir(&artifact.join("lib"))?;
let archive = artifact.join("lib").join(if target.os == "win" { "webrtc.lib" } else { "libwebrtc.a" });
let llvm_bin = source.join("third_party/llvm-build/Release+Asserts/bin");
if target.os == "win" {
copy(&out.join("obj/webrtc.lib"), &archive)?;
} else {
assemble_archive(&environment, &llvm_bin, &out, &archive)?;
}
let opus_namespace = namespace_opus(&environment, &llvm_bin, &out, &archive, &artifact, target)?;
if target.os == "linux" { prefix_linux_symbols(&environment, &llvm_bin, &sdk, &out, &archive)?; }
if target.os == "android" { android_artifacts(&environment, &sdk, &source, &out, &artifact)?; }
// License failure is fatal, unlike upstream's optional generation.
run(environment.command(&environment.python).current_dir(&source).arg(source.join("tools_webrtc/libs/generate_licenses.py")).args(["--target", ":default"]).arg(&out).arg(&out))?;
for file in ["args.gn", "LICENSE.md", "obj/webrtc.ninja"] {
copy(&out.join(file), &artifact.join(Path::new(file).file_name().ok_or("invalid metadata path")?))?;
}
let desktop = out.join("obj/modules/desktop_capture/desktop_capture.ninja");
if desktop.exists() { copy(&desktop, &artifact.join("desktop_capture.ninja"))?; }
copy_headers(&source, &source, &artifact.join("include"), false)?;
// Generated public buildflag/JNI headers must accompany the source headers.
copy_headers(&out.join("gen"), &out.join("gen"), &artifact.join("include"), false)?;
if target.os == "linux" {
for include in ["third_party/libc++/src/include", "third_party/libc++abi/src/include", "buildtools/third_party/libc++"] {
copy_headers(&source.join(include), &source.join(include), &artifact.join("include").join(include), true)?;
}
}
let gates = verify_archive(&environment, &llvm_bin, &archive, target)?;
if target.os == "android" { verify_android(&environment, &llvm_bin, &artifact, target)?; }
let files = artifact_hashes(&artifact)?;
let source_changes = source_patch_diffs(&environment, &checkout_root, &dependencies)?;
let sdk_changes = capture(environment.command("git").arg("-C").arg(&sdk).args(["diff", "--binary", "HEAD", "--"]))?;
let mut inspection_tools = BTreeMap::new();
let mut used_tools = vec!["llvm-nm", "llvm-objcopy", "llvm-ar"];
if target.os == "win" { used_tools.extend(["llvm-readobj", "llvm-lib"]); }
for name in used_tools {
let tool = environment.llvm_tool(&llvm_bin, name)?;
inspection_tools.insert(name, json!({"sha256":sha256(&tool)?, "version":capture(environment.command(&tool).arg("--version"))?}));
}
let build = json!({
"policy_sha256":policy_hash(&lock)?, "driver_sha256":driver_hashes(root)?,
"target":target.triple, "host":std::env::consts::OS, "host_arch":std::env::consts::ARCH,
"sdk_revision":SDK_REV, "webrtc_revision":WEBRTC_REV, "depot_tools_revision":DEPOT_REV,
"gn_args":args, "gclient_config":config, "resolved_dependencies":dependencies,
"effective_gn_args":effective_args,
"deps_files":deps_files, "applied_source_diffs":source_changes,
"applied_sdk_diff":sdk_changes, "inspection_tools":inspection_tools,
"artifact_root":format!("target/native-deps/{}/webrtc", target.triple),
"files":files, "archive_gates":gates,
"opus_namespace":opus_namespace,
"compiler_version":capture(environment.command(llvm_bin.join(executable(if target.os == "win" { "clang-cl" } else { "clang" }))).arg("--version"))?,
"runtime_decode_gate":"not exercised by deps; fixture decode is required separately"
});
// Write the durable receipt before publishing it in the committed lock.
save(&base.join("provenance.json"), serde_json::to_vec_pretty(&build).map_err(|e| e.to_string())?)?;
lock["builds"][target.triple] = build;
replace_lock(&root.join(LOCK), &lock)?;
println!("LK_CUSTOM_WEBRTC={}", artifact.display());
println!("Verified source dependency provenance: {}", base.join("provenance.json").display());
Ok(())
}
pub(crate) fn executable(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.into() }
}
fn ninja_build(env: &Environment, ninja: &Path, out: &Path, jobs: Option<usize>, targets: &[&str]) -> Result<(), String> {
let mut command = env.command(ninja);
command.arg("-C").arg(out);
if let Some(jobs) = jobs { command.arg("-j").arg(jobs.to_string()); }
run(command.args(targets))
}
fn verify_codec_graph(env: &Environment, gn: &Path, source: &Path, out: &Path, target: Target<'_>) -> Result<(), String> {
let graph = capture(env.command(gn).current_dir(source).arg("desc").arg(out).args(["//:webrtc", "deps", "--all"]))?;
for dependency in ["//third_party/ffmpeg", "//third_party/openh264:encoder", "//modules/video_coding:webrtc_h264", "//modules/video_coding:webrtc_vp8", "//modules/video_coding:webrtc_vp9", "//modules/video_coding/codecs/av1:dav1d_decoder"] {
if !graph.contains(dependency) { return Err(format!("GN archive dependency graph omits {dependency}")); }
}
let config_os = target.os;
let config_cpu = if target.cpu == "x64" { "x64" } else { "arm64" };
let config = source.join(format!("third_party/ffmpeg/chromium/config/Chrome/{config_os}/{config_cpu}/config_components.h"));
let text = read_text(&config)?;
if !text.lines().any(|line| line.trim() == "#define CONFIG_H264_DECODER 1") {
return Err(format!("{} does not compile the actual FFmpeg H264 decoder", config.display()));
}
Ok(())
}
fn files_below(directory: &Path, result: &mut Vec<PathBuf>) -> Result<(), String> {
for entry in fs::read_dir(directory).map_err(|e| format!("listing {}: {e}", directory.display()))? {
let entry = entry.map_err(|e| e.to_string())?;
let file_type = entry.file_type().map_err(|e| e.to_string())?;
if file_type.is_symlink() { return Err(format!("unexpected symlink in generated artifact tree: {}", entry.path().display())); }
if file_type.is_dir() { files_below(&entry.path(), result)?; }
else if file_type.is_file() { result.push(entry.path()); }
}
Ok(())
}
fn assemble_archive(env: &Environment, llvm_bin: &Path, out: &Path, archive: &Path) -> Result<(), String> {
let mut objects = Vec::new();
files_below(&out.join("obj"), &mut objects)?;
objects.retain(|p| p.extension() == Some(OsStr::new("o")) && !p.to_string_lossy().replace('\\', "/").contains("/third_party/nasm/"));
objects.sort();
if objects.is_empty() { return Err("WebRTC build produced no target object files".into()); }
// llvm-ar supports response files, avoiding command-line limits and keeping
// object ordering deterministic. A fresh archive cannot retain stale members.
let response = out.join("teamspeach-objects.rsp");
let contents = objects.iter().map(|p| format!("\"{}\"\n", p.to_string_lossy().replace('\\', "/"))).collect::<String>();
save(&response, contents)?;
let temporary = archive.with_extension("a.new");
if temporary.exists() { fs::remove_file(&temporary).map_err(|e| e.to_string())?; }
run(env.command(env.llvm_tool(llvm_bin, "llvm-ar")?).arg("rcsD").arg(&temporary).arg(format!("@{}", response.display())))?;
if archive.exists() { fs::remove_file(archive).map_err(|e| e.to_string())?; }
fs::rename(&temporary, archive).map_err(|e| format!("publishing archive: {e}"))
}
// The voice core keeps its existing audiopus build. Isolate every external C
// symbol owned by WebRTC's Opus objects (including SIMD/internal helpers), and
// rewrite all references in the assembled WebRTC archive to that namespace.
// /FORCE:MULTIPLE or selecting whichever Opus happens to link first is unsafe.
fn namespace_opus(env: &Environment, llvm: &Path, out: &Path, archive: &Path, artifact: &Path, target: Target<'_>) -> Result<Value, String> {
let mut objects = Vec::new();
files_below(&out.join("obj/third_party/opus"), &mut objects)?;
objects.retain(|path| matches!(path.extension().and_then(OsStr::to_str), Some("obj" | "o")));
objects.sort();
if objects.is_empty() { return Err("WebRTC Opus object set is empty; cannot isolate codecs".into()); }
let response = out.join("teamspeach-opus-objects.rsp");
let paths = objects.iter().map(|path| {
let relative = path.strip_prefix(out).map_err(|e| e.to_string())?.to_string_lossy().replace('\\', "/");
serde_json::to_string(&relative).map_err(|e| e.to_string())
}).collect::<Result<Vec<_>,_>>()?.join("\n");
save(&response, paths)?;
let nm = env.llvm_tool(llvm, "llvm-nm")?;
let symbols = capture(env.command(&nm).current_dir(out).args(["--defined-only", "--extern-only", "-j"]).arg(format!("@{}", response.display())))?;
let apple = matches!(target.os, "mac" | "ios");
let mut names = std::collections::BTreeSet::new();
for line in symbols.lines() {
let name = line.trim();
if !name.is_empty() && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') && !name.as_bytes()[0].is_ascii_digit() {
names.insert(name.to_owned());
}
}
let original = |name: &str| if apple { format!("_{name}") } else { name.to_owned() };
let renamed = |name: &str| if apple { format!("_TP_RTC_{}", name.strip_prefix('_').unwrap_or(name)) } else { format!("TP_RTC_{name}") };
for required in ["opus_encoder_create", "opus_encode", "opus_decoder_create", "opus_decode"] {
if !names.contains(&original(required)) { return Err(format!("WebRTC Opus objects do not define {required}")); }
}
let map = names.iter().map(|name| format!("{name} {}\n", renamed(name))).collect::<String>();
let map_path = artifact.join("opus-symbol-map.txt");
save(&map_path, map)?;
// llvm-objcopy 21 corrupts NASM COFF .file auxiliary records even when no
// symbol in that object is renamed. Rewrite only objects owning/referencing
// Opus symbols; preserve every unrelated object byte-for-byte.
let mut inputs = Vec::new();
if target.os == "win" {
let members = capture(env.command(env.llvm_tool(llvm, "llvm-ar")?).arg("t").arg(out.join("obj/webrtc.lib")))?;
for member in members.lines().filter(|line| !line.trim().is_empty()) {
let path = out.join(member.trim());
require_file(&path)?;
inputs.push(path);
}
} else {
files_below(&out.join("obj"), &mut inputs)?;
inputs.retain(|p| p.extension() == Some(OsStr::new("o")) && !p.to_string_lossy().replace('\\', "/").contains("/third_party/nasm/"));
inputs.sort();
}
let scan_response = out.join("teamspeach-opus-reference-scan.rsp");
let arguments = inputs.iter().map(|p| serde_json::to_string(&p.to_string_lossy().replace('\\', "/")).map_err(|e| e.to_string())).collect::<Result<Vec<_>,_>>()?.join("\n");
save(&scan_response, arguments)?;
let scan = capture(env.command(&nm).args(["--extern-only", "-A"]).arg(format!("@{}", scan_response.display())))?;
let mut rewrite = std::collections::BTreeSet::new();
let mut expected_symbols = std::collections::BTreeSet::new();
let mut expected_definitions = std::collections::BTreeSet::new();
for line in scan.lines() {
let Some((file, record)) = line.rsplit_once(": ") else { continue; };
let mut fields = record.split_whitespace().rev();
let (Some(symbol), Some(kind)) = (fields.next(), fields.next()) else { continue; };
if !matches!(kind, "U" | "w" | "v") {
expected_definitions.insert(if names.contains(symbol) { renamed(symbol) } else { symbol.to_owned() });
}
if names.contains(symbol) {
rewrite.insert(PathBuf::from(file));
expected_symbols.insert(renamed(symbol));
} else if !symbol.is_empty() {
expected_symbols.insert(symbol.to_owned());
}
}
if rewrite.is_empty() { return Err("No Opus-bearing objects found during reference scan".into()); }
let objcopy = env.llvm_tool(llvm, "llvm-objcopy")?;
for input in &mut inputs {
if !rewrite.contains(input) { continue; }
let output = out.join("teamspeach-opus-isolated").join(input.strip_prefix(out).map_err(|e| e.to_string())?);
mkdir(output.parent().ok_or("isolated object has no parent")?)?;
run(env.command(&objcopy).arg(format!("--redefine-syms={}", map_path.display())).arg(&*input).arg(&output))?;
*input = output;
}
let linked_response = out.join("teamspeach-opus-isolated.rsp");
save(&linked_response, inputs.iter().map(|p| serde_json::to_string(&p.to_string_lossy().replace('\\', "/")).map_err(|e| e.to_string())).collect::<Result<Vec<_>,_>>()?.join("\n"))?;
let temporary = archive.with_extension("isolated.new");
if temporary.exists() { fs::remove_file(&temporary).map_err(|e| e.to_string())?; }
if target.os == "win" {
run(env.command(env.llvm_tool(llvm, "llvm-lib")?).arg(format!("/OUT:{}", temporary.display())).arg(format!("@{}", linked_response.display())))?;
} else {
run(env.command(env.llvm_tool(llvm, "llvm-ar")?).arg("rcsD").arg(&temporary).arg(format!("@{}", linked_response.display())))?;
}
let final_symbols = capture(env.command(&nm).args(["--extern-only", "-j"]).arg(&temporary))?;
let final_names: std::collections::BTreeSet<&str> = final_symbols.lines().map(str::trim).collect();
if let Some(missing) = expected_symbols.iter().find(|name| !final_names.contains(name.as_str())) {
return Err(format!("Codec isolation lost an unrelated definition/reference: {missing}"));
}
let defined_symbols = capture(env.command(&nm).args(["--defined-only", "--extern-only", "-j"]).arg(&temporary))?;
let defined_names: std::collections::BTreeSet<&str> = defined_symbols.lines().map(str::trim).collect();
if let Some(missing) = expected_definitions.iter().find(|name| !defined_names.contains(name.as_str())) {
return Err(format!("Codec isolation lost a symbol definition: {missing}"));
}
for name in &names {
if final_names.contains(name.as_str()) { return Err(format!("Unisolated Opus definition/reference remains: {name}")); }
}
for required in ["opus_encoder_create", "opus_encode", "opus_decoder_create", "opus_decode"] {
if !final_names.contains(renamed(&original(required)).as_str()) { return Err(format!("Isolated Opus entry is absent: {required}")); }
}
if archive.exists() { fs::remove_file(archive).map_err(|e| e.to_string())?; }
fs::rename(&temporary, archive).map_err(|e| e.to_string())?;
Ok(json!({"prefix":"TP_RTC_", "object_count":objects.len(), "rewritten_objects":rewrite.len(), "symbol_count":names.len(), "map_sha256":sha256(&map_path)?}))
}
fn prefix_linux_symbols(env: &Environment, llvm: &Path, sdk: &Path, out: &Path, archive: &Path) -> Result<(), String> {
run(env.command(env.llvm_tool(llvm, "llvm-objcopy")?).arg(format!("--redefine-syms={}", sdk.join("webrtc-sys/libwebrtc/boringssl_prefix_symbols.txt").display())).arg(archive))?;
let symbols = capture(env.command(env.llvm_tool(llvm, "llvm-nm")?).args(["-j", "--extern-only"]).arg(archive))?;
let mut names = std::collections::BTreeSet::new();
for line in symbols.lines() {
let name = line.trim();
if ["av_", "avcodec_", "avdevice_", "avfilter_", "avformat_", "avio_", "avpriv_", "avsubtitle_", "avutil_", "swr_", "swresample_", "sws_", "swscale_", "ff_", "ffio_", "ffurl_"].iter().any(|prefix| name.starts_with(prefix)) {
names.insert(name);
}
}
if names.is_empty() { return Err("FFmpeg prefix map is empty; archive has no FFmpeg implementation".into()); }
let map = names.into_iter().map(|name| format!("{name} LK_{name}\n")).collect::<String>();
let path = out.join("ffmpeg_prefix_symbols.txt");
save(&path, map)?;
run(env.command(env.llvm_tool(llvm, "llvm-objcopy")?).arg(format!("--redefine-syms={}", path.display())).arg(archive))
}
fn copy_headers(current: &Path, base: &Path, destination: &Path, all: bool) -> Result<(), String> {
for entry in fs::read_dir(current).map_err(|e| format!("listing {}: {e}", current.display()))? {
let entry = entry.map_err(|e| e.to_string())?;
let name = entry.file_name();
let kind = entry.file_type().map_err(|e| e.to_string())?;
if kind.is_dir() {
if name.to_string_lossy().starts_with('.') || name == "out" || name == "depot_tools" { continue; }
copy_headers(&entry.path(), base, destination, all)?;
} else if kind.is_file() && (all || matches!(entry.path().extension().and_then(OsStr::to_str), Some("h" | "inc"))) {
let path = entry.path();
copy(&path, &destination.join(path.strip_prefix(base).map_err(|e| e.to_string())?))?;
}
}
Ok(())
}
fn android_artifacts(env: &Environment, sdk: &Path, source: &Path, out: &Path, artifact: &Path) -> Result<(), String> {
copy(&out.join("libjingle_peerconnection_so.so"), &artifact.join("lib/libjingle_peerconnection_so.so"))?;
let project = sdk.join("webrtc-sys/libwebrtc/prefixed-jni");
let jar = project.join("libs/classes.jar");
copy(&out.join("lib.java/sdk/android/libwebrtc.jar"), &jar)?;
run(env.command(&env.python).arg(sdk.join("webrtc-sys/libwebrtc/tools/downgrade_android_class_version.py")).arg(&jar))?;
// The checked-in Gradle wrapper and its checksum determine the downloaded
// Gradle distribution. Cache stays below this target, not in the home dir.
run(env.command("sh").current_dir(&project).arg("./gradlew").args(["--no-daemon", "shadowJar"]).env("GRADLE_USER_HOME", artifact.parent().ok_or("artifact has no parent")?.join("gradle-cache")))?;
copy(&project.join("build/libs/prefixed-jni-all.jar"), &artifact.join("libwebrtc.jar"))?;
copy(&source.join("sdk/android/AndroidManifest.xml"), &artifact.join("AndroidManifest.xml"))
}
fn verify_archive(env: &Environment, llvm: &Path, archive: &Path, target: Target<'_>) -> Result<Value, String> {
let symbols = capture(env.command(env.llvm_tool(llvm, "llvm-nm")?).args(["--defined-only", "--extern-only", "-j"]).arg(archive))?;
let required = ["dav1d_open", if target.os == "linux" { "LK_ff_h264_decoder" } else { "ff_h264_decoder" }, "vpx_codec_vp8_dx", "vpx_codec_vp9_dx"];
for symbol in required {
if !symbols.lines().any(|line| line.trim().trim_start_matches('_') == symbol) { return Err(format!("{} has no defined {symbol}; advertising a codec is not a compiled decoder", archive.display())); }
}
if target.os == "linux" {
for symbol in ["__libcpp_verbose_abort", "__cxa_throw"] {
if !symbols.contains(symbol) { return Err(format!("hermetic libc++ archive is missing {symbol}")); }
}
}
if target.os == "win" { verify_windows_crt(env, llvm, archive)?; }
Ok(json!({"defined_decoder_symbols":required, "hermetic_libcxx":target.os == "linux", "static_release_crt":target.os == "win"}))
}
pub(crate) fn verify_windows_crt(env: &Environment, llvm: &Path, archive: &Path) -> Result<(), String> {
let output = capture(env.command(env.llvm_tool(llvm, "llvm-readobj")?).arg("--coff-directives").arg(archive))?.to_ascii_lowercase();
for line in output.lines().filter(|line| line.contains("directive(s):")) {
for forbidden in ["msvcrt", "libcmtd", "runtimelibrary=md", "runtimelibrary=mtd"] {
if line.contains(forbidden) { return Err(format!("{} violates the static release CRT contract ({forbidden})", archive.display())); }
}
}
// Some assembly-only archives have no CRT directives; they are compatible.
Ok(())
}
fn verify_android(env: &Environment, llvm: &Path, artifact: &Path, target: Target<'_>) -> Result<(), String> {
let jar = artifact.join("libwebrtc.jar");
require_file(&jar)?;
let entries = capture(env.command("jar").arg("tf").arg(&jar))?;
if !entries.lines().any(|entry| entry == "livekit/org/webrtc/PeerConnection.class") || entries.lines().any(|entry| entry.starts_with("org/webrtc/")) {
return Err("libwebrtc.jar is missing the matching livekit.org.webrtc relocation or contains unprefixed classes".into());
}
let shared = artifact.join("lib/libjingle_peerconnection_so.so");
let symbols = capture(env.command(env.llvm_tool(llvm, "llvm-nm")?).args(["--defined-only", "-D"]).arg(&shared))?;
if !symbols.contains("Java_livekit_org_webrtc") { return Err("Android WebRTC library has no matching Java_livekit_org_webrtc JNI symbols".into()); }
if target.cpu == "arm64" { verify_elf_alignment(&shared)?; }
Ok(())
}
pub(crate) fn verify_elf_alignment(path: &Path) -> Result<(), String> {
let bytes = fs::read(path).map_err(|e| e.to_string())?;
if bytes.get(..6) != Some(&[0x7f, b'E', b'L', b'F', 2, 1]) { return Err(format!("{} is not little-endian ELF64", path.display())); }
fn number(bytes: &[u8], at: usize, length: usize) -> Result<u64, String> {
let slice = bytes.get(at..at.checked_add(length).ok_or("ELF offset overflow")?).ok_or("truncated ELF header")?;
let mut output = [0u8; 8]; output[..length].copy_from_slice(slice); Ok(u64::from_le_bytes(output))
}
let offset = usize::try_from(number(&bytes, 32, 8)?).map_err(|e| e.to_string())?;
let size = number(&bytes, 54, 2)? as usize;
let count = number(&bytes, 56, 2)? as usize;
if size < 56 || count == 0 { return Err(format!("{} has no valid ELF program headers", path.display())); }
let mut loads = 0;
for index in 0..count {
let at = offset.checked_add(index.checked_mul(size).ok_or("ELF offset overflow")?).ok_or("ELF offset overflow")?;
if number(&bytes, at, 4)? != 1 { continue; }
loads += 1;
let alignment = number(&bytes, at + 48, 8)?;
let file_offset = number(&bytes, at + 8, 8)?;
let address = number(&bytes, at + 16, 8)?;
if alignment < 16384 || !alignment.is_power_of_two() || file_offset % 16384 != address % 16384 {
return Err(format!("{} has a PT_LOAD incompatible with 16-KiB pages", path.display()));
}
}
if loads == 0 { return Err(format!("{} has no loadable ELF segments", path.display())); }
Ok(())
}
fn artifact_hashes(artifact: &Path) -> Result<Value, String> {
let mut files = Vec::new(); files_below(artifact, &mut files)?;
let mut entries = BTreeMap::new();
for path in files {
let relative = path.strip_prefix(artifact).map_err(|e| e.to_string())?.to_string_lossy().replace('\\', "/");
entries.insert(relative, json!({"sha256":sha256(&path)?, "size":fs::metadata(&path).map_err(|e| e.to_string())?.len()}));
}
Ok(json!(entries))
}
fn dependency_files(checkout: &Path, dependencies: &Value) -> Result<Value, String> {
let mut files = BTreeMap::new();
for path in dependencies.as_object().ok_or("gclient revision output is not an object")?.keys() {
if path.contains(':') { continue; }
let deps = checkout.join(path).join("DEPS");
if deps.is_file() {
files.insert(format!("{path}/DEPS"), json!({"sha256":sha256(&deps)?, "content":read_text(&deps)?}));
}
}
if !files.contains_key("src/DEPS") { return Err("gclient provenance omits root DEPS".into()); }
Ok(json!(files))
}
fn source_patch_diffs(env: &Environment, checkout: &Path, dependencies: &Value) -> Result<Value, String> {
let mut changes = BTreeMap::new();
for (path, entry) in dependencies.as_object().ok_or("invalid dependency map")? {
if path.contains(':') || entry["rev"].as_str().is_none_or(|revision| revision.len() != 40) { continue; }
let directory = checkout.join(path);
if !directory.join(".git").exists() { continue; }
let diff = capture(env.command("git").arg("-C").arg(&directory).args(["diff", "--binary", "HEAD", "--"]))?;
if !diff.is_empty() { changes.insert(path, diff); }
}
Ok(json!(changes))
}
fn replace_lock(path: &Path, lock: &Value) -> Result<(), String> {
let temporary = path.with_extension("json.new");
let mut file = File::create(&temporary).map_err(|e| e.to_string())?;
serde_json::to_writer_pretty(&mut file, lock).map_err(|e| e.to_string())?;
file.write_all(b"\n").and_then(|_| file.sync_all()).map_err(|e| e.to_string())?;
// Windows rename does not replace an existing destination. Keep the previous
// complete lock until the new one is ready, and restore it if rename fails.
let backup = path.with_extension("json.previous");
if backup.exists() { return Err(format!("interrupted lock replacement requires inspection: {}", backup.display())); }
fs::rename(path, &backup).map_err(|e| e.to_string())?;
if let Err(error) = fs::rename(&temporary, path) {
fs::rename(&backup, path).map_err(|rollback| format!("lock write failed: {error}; restoration failed: {rollback}"))?;
return Err(format!("lock write failed: {error}"));
}
fs::remove_file(&backup).map_err(|e| e.to_string())
}
/// Offline verification is deliberately separate from provisioning: build never
/// falls back to the SDK's mutable prebuilt download on missing/stale inputs.
pub(crate) fn verify(root: &Path, target: Target<'_>) -> Result<PathBuf, String> {
let lock = lock_policy(root)?;
let build = &lock["builds"][target.triple];
if build.is_null() { return Err(format!("no completed dependency build for {}; run xtask deps --target {}", target.triple, target.triple)); }
if build["policy_sha256"] != policy_hash(&lock)? || build["driver_sha256"] != driver_hashes(root)? || build["gn_args"] != gn_args(target) {
return Err("dependency recipe changed; rerun xtask deps before building".into());
}
for entry in lock["patches"].as_array().ok_or("missing patch list")? {
if sha256(&root.join(text(entry, "path")?))? != text(entry, "sha256")? { return Err("application patch SHA256 differs from dependency lock".into()); }
}
let base = cache(root, target);
if read_json(&base.join("provenance.json"))? != *build { return Err("local dependency provenance differs from committed lock".into()); }
let artifact = base.join("webrtc");
if artifact_hashes(&artifact)? != build["files"] { return Err(format!("dependency artifact missing, altered or unexpectedly added beneath {}", artifact.display())); }
require_file(&artifact.join("lib").join(if target.os == "win" { "webrtc.lib" } else { "libwebrtc.a" }))?;
if target.os == "android" { require_file(&artifact.join("libwebrtc.jar"))?; }
Ok(artifact)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_receipts_do_not_change_source_policy_hash() {
let mut policy = json!({"schema":1, "webrtc":{"revision":WEBRTC_REV}, "builds":{}});
let before = policy_hash(&policy).unwrap();
policy["builds"]["example"] = json!({"files":{"archive":{"sha256":"example"}}});
assert_eq!(before, policy_hash(&policy).unwrap());
policy["webrtc"]["revision"] = json!("different");
assert_ne!(before, policy_hash(&policy).unwrap());
}
}