Implement Rust and Slint native client migration and fix desktop startup
This commit is contained in:
1 parent
0d11f8f99d
commit
eb24965076
1303 files changed
+732670
-2375
No files matched your search
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "xtask"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json.workspace = true
|
||||
sha2 = "0.10"
|
||||
base64 = "0.22"
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Host toolchain discovery and the native Cargo build. Environment changes are
|
||||
//! child-process scoped; this module never installs tools or changes the OS.
|
||||
use std::{collections::BTreeMap, env, ffi::{OsStr, OsString}, fs, path::{Path, PathBuf}, process::Command};
|
||||
use crate::{Options, deps::{self, Target, capture, run, require_file, read_text}};
|
||||
|
||||
pub(crate) struct Environment {
|
||||
values: BTreeMap<OsString, OsString>,
|
||||
pub python: PathBuf,
|
||||
}
|
||||
impl Environment {
|
||||
pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
command.envs(&self.values);
|
||||
command
|
||||
}
|
||||
pub fn llvm_tool(&self, directory: &Path, name: &str) -> Result<PathBuf, String> {
|
||||
let pinned = directory.join(deps::executable(name));
|
||||
if pinned.is_file() { return Ok(pinned); }
|
||||
if let Some(home) = self.get("LLVM_HOME") {
|
||||
let portable = PathBuf::from(home).join("bin").join(deps::executable(name));
|
||||
if portable.is_file() { return Ok(portable); }
|
||||
}
|
||||
self.require_program(name)
|
||||
}
|
||||
pub fn set(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) {
|
||||
self.values.insert(key.as_ref().to_owned(), value.as_ref().to_owned());
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.values.get(OsStr::new(key)).cloned().or_else(|| env::var_os(key))
|
||||
}
|
||||
pub fn prepend_path(&mut self, directory: &Path) -> Result<(), String> {
|
||||
let previous = self.get("PATH").unwrap_or_default();
|
||||
let paths = std::iter::once(directory.to_owned()).chain(env::split_paths(&previous));
|
||||
self.set("PATH", env::join_paths(paths).map_err(|e| format!("invalid tool path: {e}"))?);
|
||||
Ok(())
|
||||
}
|
||||
fn find(&self, name: &str) -> Option<PathBuf> {
|
||||
let path = self.get("PATH")?;
|
||||
for directory in env::split_paths(&path) {
|
||||
let program = directory.join(deps::executable(name));
|
||||
if program.is_file() { return Some(program); }
|
||||
}
|
||||
None
|
||||
}
|
||||
pub(crate) fn require_program(&self, name: &str) -> Result<PathBuf, String> {
|
||||
self.find(name).ok_or_else(|| format!("required build tool {name} is not on PATH; install/provide it explicitly (xtask never installs system packages)"))
|
||||
}
|
||||
pub fn discover(root: &Path, options: &Options, target: Target<'_>, native_build: bool) -> Result<Self, String> {
|
||||
let mut result = Self { values: BTreeMap::new(), python: PathBuf::new() };
|
||||
if target.os == "win" { result.visual_studio(target)?; }
|
||||
// cargo run exposes its own executable; do not require a globally
|
||||
// installed Rust PATH or a hardcoded user's .cargo directory.
|
||||
if let Some(cargo) = env::var_os("CARGO") {
|
||||
if let Some(bin) = Path::new(&cargo).parent().filter(|path| path.is_dir()) {
|
||||
result.prepend_path(bin)?;
|
||||
}
|
||||
}
|
||||
result.python = if let Some(python) = env::var_os("PYTHON") {
|
||||
let path = PathBuf::from(python);
|
||||
capture(result.command(&path).arg("--version"))?;
|
||||
path
|
||||
} else {
|
||||
let mut selected = None;
|
||||
for name in ["python3", "python"] {
|
||||
if let Some(path) = result.find(name) {
|
||||
if capture(result.command(&path).arg("--version")).is_ok_and(|version| version.starts_with("Python 3.")) {
|
||||
selected = Some(path); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
selected.ok_or("Python 3 is required; set PYTHON to the installed interpreter")?
|
||||
};
|
||||
result.set("PYTHON", &result.python.clone());
|
||||
result.portable_tools(root, options, native_build)?;
|
||||
Ok(result)
|
||||
}
|
||||
fn visual_studio(&mut self, target: Target<'_>) -> Result<(), String> {
|
||||
let install = if let Some(path) = env::var_os("VSINSTALLDIR") { PathBuf::from(path) } else {
|
||||
let program_files = env::var_os("ProgramFiles(x86)").or_else(|| env::var_os("ProgramFiles"))
|
||||
.ok_or("Windows ProgramFiles is not set; use a Visual Studio developer shell")?;
|
||||
let vswhere = PathBuf::from(program_files).join("Microsoft Visual Studio/Installer/vswhere.exe");
|
||||
require_file(&vswhere)?;
|
||||
let selected = capture(self.command(&vswhere).args(["-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]))?;
|
||||
let path = selected.trim();
|
||||
if path.is_empty() { return Err("Visual Studio with C++ build tools was not found; no toolchain is installed automatically".into()); }
|
||||
PathBuf::from(path)
|
||||
};
|
||||
let vcvars = install.join("VC/Auxiliary/Build/vcvarsall.bat");
|
||||
require_file(&vcvars)?;
|
||||
let architecture = match (env::consts::ARCH, target.cpu) {
|
||||
("x86_64", "x64") => "x64", ("x86_64", "arm64") => "x64_arm64",
|
||||
("aarch64", "x64") => "arm64_x64", ("aarch64", "arm64") => "arm64",
|
||||
_ => return Err("Visual Studio provisioning supports only x64/ARM64 hosts and targets".into()),
|
||||
};
|
||||
let path = vcvars.to_string_lossy().replace('/', "\\");
|
||||
if path.contains(['"', '\n', '\r', '%', '!']) { return Err("Visual Studio path contains unsupported command-shell characters".into()); }
|
||||
let mut activation = self.command("cmd.exe");
|
||||
activation.args(["/D", "/S", "/C"]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
activation.raw_arg(format!("\"call \"{path}\" {architecture} >nul && set\""));
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
activation.arg(format!("call \"{path}\" {architecture} >nul && set"));
|
||||
let output = capture(&mut activation)?;
|
||||
for line in output.lines() {
|
||||
let Some((key, value)) = line.split_once('=') else { continue; };
|
||||
// Only import build-tool variables; never copy credentials into the
|
||||
// explicit child environment or diagnostic command output.
|
||||
let upper = key.to_ascii_uppercase();
|
||||
if matches!(upper.as_str(), "PATH" | "INCLUDE" | "LIB" | "LIBPATH" | "VSCMD_ARG_TGT_ARCH" | "VSCMD_ARG_HOST_ARCH")
|
||||
|| upper.starts_with("VS") || upper.starts_with("VC") || upper.starts_with("WINDOWSSDK") || upper.starts_with("UCRT") || upper.starts_with("UNIVERSALCRT") {
|
||||
self.set(if upper == "PATH" { "PATH" } else { key }, value);
|
||||
}
|
||||
}
|
||||
self.set("vs2022_install", &install);
|
||||
self.set("vs2019_install", &install); // Chromium also probes this legacy variable.
|
||||
self.set("DEPOT_TOOLS_WIN_TOOLCHAIN", "0");
|
||||
self.require_program("cl")?;
|
||||
self.require_program("link")?;
|
||||
self.require_program("rc")?;
|
||||
if self.get("WindowsSdkDir").is_none() && self.get("WINDOWSSDKDIR").is_none() {
|
||||
return Err("Visual Studio did not activate a Windows SDK".into());
|
||||
}
|
||||
for directory in ["Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin", "Common7/IDE/CommonExtensions/Microsoft/CMake/Ninja"] {
|
||||
let directory = install.join(directory);
|
||||
if directory.is_dir() { self.prepend_path(&directory)?; }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn portable_tools(&mut self, root: &Path, options: &Options, native_build: bool) -> Result<(), String> {
|
||||
let llvm = choose_directory(options.llvm_dir.as_ref(), self.get("LLVM_HOME"), &root.join("target/tools"), "llvm-", |path| path.join("bin").join(deps::executable("clang")).is_file())?;
|
||||
if let Some(llvm) = llvm {
|
||||
let llvm = absolute(&llvm)?;
|
||||
self.prepend_path(&llvm.join("bin"))?;
|
||||
self.set("LLVM_HOME", &llvm);
|
||||
if self.get("LIBCLANG_PATH").is_none() {
|
||||
let library = if cfg!(windows) { llvm.join("bin") } else { llvm.join("lib") };
|
||||
self.set("LIBCLANG_PATH", library);
|
||||
}
|
||||
if self.get("BINDGEN_EXTRA_CLANG_ARGS").is_none() {
|
||||
let resource = capture(self.command(llvm.join("bin").join(deps::executable("clang"))).arg("-print-resource-dir"))?;
|
||||
self.set("BINDGEN_EXTRA_CLANG_ARGS", format!("-resource-dir \"{}\"", resource.trim()));
|
||||
}
|
||||
}
|
||||
if let Some(libclang) = self.get("LIBCLANG_PATH") {
|
||||
let path = PathBuf::from(libclang);
|
||||
if !path.is_dir() { return Err(format!("LIBCLANG_PATH is not a directory: {}", path.display())); }
|
||||
if cfg!(windows) { require_file(&path.join("libclang.dll"))?; }
|
||||
}
|
||||
if !native_build { return Ok(()); }
|
||||
let skia = choose_directory(options.skia_source.as_ref(), self.get("SKIA_SOURCE_DIR"), &root.join("target/tools"), "skia-", |path| path.join("BUILD.gn").is_file())?;
|
||||
if let Some(skia) = skia {
|
||||
let skia = absolute(&skia)?;
|
||||
require_file(&skia.join("BUILD.gn"))?;
|
||||
self.set("SKIA_SOURCE_DIR", &skia);
|
||||
if self.get("SKIA_GN_COMMAND").is_none() {
|
||||
let gn = skia.join("bin").join(deps::executable("gn"));
|
||||
require_file(&gn)?;
|
||||
self.set("SKIA_GN_COMMAND", gn);
|
||||
}
|
||||
if self.get("SKIA_NINJA_COMMAND").is_none() {
|
||||
self.set("SKIA_NINJA_COMMAND", self.require_program("ninja")?);
|
||||
}
|
||||
}
|
||||
self.require_program("cmake")?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn check_source_prerequisites(&self, target: Target<'_>) -> Result<(), String> {
|
||||
self.require_program("git")?;
|
||||
capture(self.command(&self.python).arg("--version"))?;
|
||||
if matches!(target.os, "linux" | "android") {
|
||||
for program in ["pkg-config", "clang", "clang++", "ar"] { self.require_program(program)?; }
|
||||
if target.os == "linux" {
|
||||
// These are also required by CPAL, the wrapper and desktop
|
||||
// capture; report missing prerequisites instead of apt/sudo.
|
||||
run(self.command("pkg-config").args(["--exists", "alsa", "glib-2.0", "gobject-2.0", "gio-2.0", "x11", "xrandr", "xfixes", "xdamage", "xcomposite", "libpipewire-0.3"]))?;
|
||||
}
|
||||
}
|
||||
if target.os == "android" {
|
||||
for program in ["java", "javac", "jar", "sh"] { self.require_program(program)?; }
|
||||
let sdk = self.get("ANDROID_HOME").or_else(|| self.get("ANDROID_SDK_ROOT")).ok_or("ANDROID_HOME must point to an installed Android SDK 36")?;
|
||||
require_file(&PathBuf::from(sdk).join("platforms/android-36/android.jar"))?;
|
||||
let ndk = self.get("ANDROID_NDK_ROOT").or_else(|| self.get("ANDROID_NDK_HOME")).ok_or("ANDROID_NDK_ROOT must point to installed NDK r28 or newer")?;
|
||||
let properties = read_text(&PathBuf::from(ndk).join("source.properties"))?;
|
||||
let revision = properties.lines().find_map(|line| line.strip_prefix("Pkg.Revision").and_then(|value| value.split_once('=').map(|(_, value)| value.trim()))).ok_or("NDK source.properties has no Pkg.Revision")?;
|
||||
let major: u32 = revision.split('.').next().ok_or("missing NDK major")?.parse().map_err(|_| "invalid NDK revision")?;
|
||||
if major < 28 { return Err(format!("NDK r28+ is required, found {revision}")); }
|
||||
}
|
||||
if matches!(target.os, "mac" | "ios") {
|
||||
self.require_program("xcodebuild")?;
|
||||
self.require_program("xcrun")?;
|
||||
let sdk = apple_sdk(target);
|
||||
let path = capture(self.command("xcrun").args(["--sdk", sdk, "--show-sdk-path"]))?;
|
||||
if !Path::new(path.trim()).is_dir() { return Err(format!("Xcode SDK {sdk} is unavailable")); }
|
||||
capture(self.command("xcodebuild").arg("-version"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rust_flag(&mut self, flag: &str) -> Result<(), String> {
|
||||
if let Some(encoded) = self.get("CARGO_ENCODED_RUSTFLAGS") {
|
||||
let mut encoded = encoded.into_string().map_err(|_| "CARGO_ENCODED_RUSTFLAGS is not UTF-8")?;
|
||||
if !encoded.is_empty() { encoded.push('\x1f'); }
|
||||
encoded.push_str(flag);
|
||||
self.set("CARGO_ENCODED_RUSTFLAGS", encoded);
|
||||
} else {
|
||||
let existing = self.get("RUSTFLAGS").unwrap_or_default().into_string().map_err(|_| "RUSTFLAGS is not UTF-8")?;
|
||||
self.set("RUSTFLAGS", format!("{existing} {flag}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn choose_directory(explicit: Option<&PathBuf>, environment: Option<OsString>, base: &Path, prefix: &str, accepts: impl Fn(&Path) -> bool) -> Result<Option<PathBuf>, String> {
|
||||
if let Some(path) = explicit.cloned().or_else(|| environment.map(PathBuf::from)) {
|
||||
if !accepts(&path) { return Err(format!("invalid {prefix} tool directory: {}", path.display())); }
|
||||
return Ok(Some(path));
|
||||
}
|
||||
if !base.is_dir() { return Ok(None); }
|
||||
let mut candidates = Vec::new();
|
||||
for entry in fs::read_dir(base).map_err(|e| e.to_string())? {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
if entry.file_name().to_string_lossy().starts_with(prefix) && accepts(&entry.path()) { candidates.push(entry.path()); }
|
||||
}
|
||||
match candidates.len() {
|
||||
0 => Ok(None), 1 => Ok(candidates.pop()),
|
||||
_ => Err(format!("multiple {prefix} installations under {}; select --llvm-dir/--skia-source or the corresponding environment variable", base.display())),
|
||||
}
|
||||
}
|
||||
fn absolute(path: &Path) -> Result<PathBuf, String> {
|
||||
if path.is_absolute() { Ok(path.to_owned()) } else { Ok(env::current_dir().map_err(|e| e.to_string())?.join(path)) }
|
||||
}
|
||||
fn apple_sdk(target: Target<'_>) -> &'static str {
|
||||
if target.os == "mac" { "macosx" } else if target.simulator { "iphonesimulator" } else { "iphoneos" }
|
||||
}
|
||||
|
||||
pub(crate) fn build(root: &Path, options: &Options) -> Result<(), String> {
|
||||
let target = Target::parse(&options.target)?;
|
||||
target.check_host()?;
|
||||
let mut environment = Environment::discover(root, options, target, true)?;
|
||||
environment.check_source_prerequisites(target)?;
|
||||
let artifact = deps::verify(root, target)?;
|
||||
let source = deps::cache(root, target).join("checkout/src");
|
||||
let llvm = source.join("third_party/llvm-build/Release+Asserts/bin");
|
||||
environment.set("LK_CUSTOM_WEBRTC", &artifact);
|
||||
let rust_libdir = capture(environment.command("rustc").args(["--print", "target-libdir", "--target", target.triple]))?;
|
||||
if !Path::new(rust_libdir.trim()).is_dir() {
|
||||
return Err(format!("Rust standard library for {} is not installed; explicitly provision it before build", target.triple));
|
||||
}
|
||||
match target.os {
|
||||
"win" => environment.rust_flag("-Ctarget-feature=+crt-static")?,
|
||||
"linux" => {
|
||||
// CXX ABI must match the exact Chromium libc++ headers shipped with
|
||||
// the archive; the vendored wrapper selects those headers itself.
|
||||
environment.set(format!("CXX_{}", target.triple.replace('-', "_")), llvm.join("clang++"));
|
||||
environment.set(format!("CC_{}", target.triple.replace('-', "_")), llvm.join("clang"));
|
||||
if target.cpu == "arm64" { environment.rust_flag("-Clink-arg=-Wl,-z,max-page-size=16384")?; }
|
||||
let native_cpu = if env::consts::ARCH == "aarch64" { "arm64" } else { "x64" };
|
||||
if target.cpu != native_cpu {
|
||||
let sysroots: serde_json::Value = serde_json::from_str(&read_text(&source.join("build/linux/sysroot_scripts/sysroots.json"))?).map_err(|e| e.to_string())?;
|
||||
let arch = if target.cpu == "x64" { "amd64" } else { "arm64" };
|
||||
let directory = sysroots[format!("bullseye_{arch}")]["SysrootDir"].as_str().ok_or("pinned sysroot manifest has no target SysrootDir")?;
|
||||
let sysroot = source.join("build/linux").join(directory);
|
||||
if !sysroot.is_dir() { return Err(format!("target sysroot has not been provisioned: {}", sysroot.display())); }
|
||||
environment.set(format!("CARGO_TARGET_{}_LINKER", target.triple.replace('-', "_").to_ascii_uppercase()), llvm.join("clang"));
|
||||
environment.rust_flag(&format!("-Clink-arg=--target={}", target.triple))?;
|
||||
environment.rust_flag(&format!("-Clink-arg=--sysroot={}", sysroot.display()))?;
|
||||
environment.set("PKG_CONFIG_ALLOW_CROSS", "1");
|
||||
environment.set("PKG_CONFIG_SYSROOT_DIR", &sysroot);
|
||||
environment.set("PKG_CONFIG_LIBDIR", sysroot.join("usr/lib").join(target.triple).join("pkgconfig"));
|
||||
}
|
||||
}
|
||||
"android" => {
|
||||
// Use the very same DEPS-pinned NDK for Rust CXX and the archive.
|
||||
let ndk = source.join("third_party/android_toolchain/ndk");
|
||||
let bin = ndk.join("toolchains/llvm/prebuilt/linux-x86_64/bin");
|
||||
let clang = bin.join(format!("{}26-clang", target.triple));
|
||||
let clangxx = bin.join(format!("{}26-clang++", target.triple));
|
||||
require_file(&clang)?; require_file(&clangxx)?;
|
||||
environment.set("ANDROID_NDK_ROOT", &ndk);
|
||||
environment.set("ANDROID_NDK_HOME", &ndk);
|
||||
environment.set("ANDROID_PLATFORM", "android-26");
|
||||
environment.set("CARGO_NDK_ANDROID_PLATFORM", "26");
|
||||
environment.set(format!("CC_{}", target.triple.replace('-', "_")), &clang);
|
||||
environment.set(format!("CXX_{}", target.triple.replace('-', "_")), &clangxx);
|
||||
environment.set(format!("AR_{}", target.triple.replace('-', "_")), bin.join("llvm-ar"));
|
||||
environment.set(format!("CARGO_TARGET_{}_LINKER", target.triple.replace('-', "_").to_ascii_uppercase()), &clang);
|
||||
if target.cpu == "arm64" { environment.rust_flag("-Clink-arg=-Wl,-z,max-page-size=16384")?; }
|
||||
}
|
||||
"mac" | "ios" => {
|
||||
let sdk = capture(environment.command("xcrun").args(["--sdk", apple_sdk(target), "--show-sdk-path"]))?;
|
||||
environment.set("SDKROOT", sdk.trim());
|
||||
environment.set(if target.os == "mac" { "MACOSX_DEPLOYMENT_TARGET" } else { "IPHONEOS_DEPLOYMENT_TARGET" }, if target.os == "mac" { "14.2" } else { "16.0" });
|
||||
environment.rust_flag("-Clink-arg=-ObjC")?;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
|
||||
let mut command = environment.command(cargo);
|
||||
command.env_remove("LK_DEBUG_WEBRTC");
|
||||
command.current_dir(root).args(["build", "--locked", "--release", "-p", "teamspeach-native", "--target", target.triple]);
|
||||
if target.os == "android" { command.arg("--lib"); } else { command.args(["--bin", "teamspeach"]); }
|
||||
if matches!(target.os,"win"|"linux") { command.args(["--bin", "teamspeach-update-helper"]); }
|
||||
if options.test_harness { command.args(["--features", "test-harness"]); }
|
||||
if let Some(jobs) = options.jobs { command.arg("--jobs").arg(jobs.to_string()); }
|
||||
run(&mut command)?;
|
||||
let target_dir = environment.get("CARGO_TARGET_DIR").map(PathBuf::from).map(|path| if path.is_absolute() { path } else { root.join(path) }).unwrap_or_else(|| root.join("target"));
|
||||
let output = target_dir.join(target.triple).join("release");
|
||||
if target.os == "win" { verify_all_windows_archives(&environment, &llvm, &output)?; }
|
||||
let binary = output.join(if target.os == "android" { "libteamspeach_native.so" } else if target.os == "win" { "teamspeach.exe" } else { "teamspeach" });
|
||||
require_file(&binary)?;
|
||||
if matches!(target.os, "android" | "linux") && target.cpu == "arm64" {
|
||||
deps::verify_elf_alignment(&binary)?;
|
||||
verify_all_shared_elf(&output)?;
|
||||
}
|
||||
if target.os == "android" {
|
||||
// Packaging consumes this exact matching jar, never a warning-only copy
|
||||
// in an unrelated crate target directory.
|
||||
let jar = artifact.join("libwebrtc.jar");
|
||||
require_file(&jar)?;
|
||||
fs::copy(&jar, output.join("libwebrtc.jar")).map_err(|e| format!("copying required Android JNI jar: {e}"))?;
|
||||
}
|
||||
let names:&[&str]=match target.os {
|
||||
"win"=>&["teamspeach.exe","teamspeach-update-helper.exe"],
|
||||
"linux"=>&["teamspeach","teamspeach-update-helper"],
|
||||
"android"=>&["libteamspeach_native.so"],
|
||||
_=>&["teamspeach"],
|
||||
};
|
||||
let binaries=names.iter().map(|name|Ok(serde_json::json!({"name":name,"sha256":deps::sha256(&output.join(name))?}))).collect::<Result<Vec<_>,String>>()?;
|
||||
crate::package::save(&output.join("native-build.json"),&serde_json::json!({"schema":1,"engine":"rust-slint","version":crate::package::version(root)?,"target":target.triple,"testHarness":options.test_harness,"binaries":binaries}))?;
|
||||
println!("Native artifact: {}", binary.display());
|
||||
Ok(())
|
||||
}
|
||||
fn verify_all_windows_archives(environment: &Environment, llvm: &Path, directory: &Path) -> Result<(), String> {
|
||||
for entry in fs::read_dir(directory).map_err(|e| e.to_string())? {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
let kind = entry.file_type().map_err(|e| e.to_string())?;
|
||||
if kind.is_symlink() { continue; }
|
||||
if kind.is_dir() { verify_all_windows_archives(environment, llvm, &entry.path())?; }
|
||||
else if entry.path().extension().and_then(OsStr::to_str).is_some_and(|extension| extension.eq_ignore_ascii_case("lib")) {
|
||||
deps::verify_windows_crt(environment, llvm, &entry.path())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_all_shared_elf(directory: &Path) -> Result<(), String> {
|
||||
for entry in fs::read_dir(directory).map_err(|e| e.to_string())? {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
let kind = entry.file_type().map_err(|e| e.to_string())?;
|
||||
if kind.is_symlink() { continue; }
|
||||
if kind.is_dir() { verify_all_shared_elf(&entry.path())?; }
|
||||
else if entry.path().extension() == Some(OsStr::new("so")) {
|
||||
deps::verify_elf_alignment(&entry.path())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
//! 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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
mod build_native;
|
||||
mod deps;
|
||||
mod package;
|
||||
mod verify_package;
|
||||
mod smoke;
|
||||
|
||||
use std::{env, path::PathBuf, process::ExitCode};
|
||||
|
||||
const USAGE: &str = "usage: cargo run -p xtask -- <deps|build|package|smoke|verify-package> --target <rust-triple> [--llvm-dir <dir>] [--skia-source <dir>] [--jobs <count>] [--out <directory>] [--scenario offline-ui|migration|media-loopback|codec-fixtures] [--codec-probe <executable>] [--device <explicit serial/UDID>] [--app <test APK/simulator app>]\n\ndeps provisions pinned sources; build verifies dependencies and compiles release binaries.\npackage consumes built binaries and host packaging tools; verify-package inspects actual archives.\nsmoke requires a test-harness build and creates a fresh disposable profile/output.\nNo SDK installations, publication, tags, or inferred signing credentials.\nWindows: MSVC/SDK/NSIS/7-Zip; Linux: linuxdeploy/appimagetool/unsquashfs; macOS: Xcode/dylibbundler; Android: cached Gradle/JDK17/SDK36/NDK28+; iOS: Xcode/XcodeGen/provisioning for IPA.\nAll packages remain local-only until acceptance and artwork redistribution authorization.";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Options {
|
||||
target: String,
|
||||
llvm_dir: Option<PathBuf>,
|
||||
skia_source: Option<PathBuf>,
|
||||
jobs: Option<usize>,
|
||||
out: Option<PathBuf>,
|
||||
scenario: Option<String>,
|
||||
codec_probe: Option<PathBuf>,
|
||||
device: Option<String>,
|
||||
app: Option<PathBuf>,
|
||||
test_harness: bool,
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let mut args = env::args().skip(1);
|
||||
let Some(operation) = args.next() else { return Err(USAGE.into()); };
|
||||
if operation == "--help" || operation == "-h" {
|
||||
println!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(operation.as_str(), "deps" | "build" | "package" | "smoke" | "verify-package") {
|
||||
return Err(format!("unsupported operation {operation:?}\n{USAGE}"));
|
||||
}
|
||||
let mut options = Options { target: String::new(), llvm_dir: None, skia_source: None, jobs: None, out: None, scenario: None, codec_probe: None, device: None, app: None, test_harness: false };
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
while let Some(flag) = args.next() {
|
||||
if !seen.insert(flag.clone()) { return Err(format!("duplicate option {flag}")); }
|
||||
let value = args.next().ok_or_else(|| format!("missing value for {flag}\n{USAGE}"))?;
|
||||
match flag.as_str() {
|
||||
"--target" => options.target = value,
|
||||
"--llvm-dir" => options.llvm_dir = Some(PathBuf::from(value)),
|
||||
"--skia-source" => options.skia_source = Some(PathBuf::from(value)),
|
||||
"--out" => options.out = Some(PathBuf::from(value)),
|
||||
"--scenario" => options.scenario = Some(value),
|
||||
"--codec-probe" => options.codec_probe = Some(PathBuf::from(value)),
|
||||
"--device" => options.device = Some(value),
|
||||
"--app" => options.app = Some(PathBuf::from(value)),
|
||||
"--test-harness" => options.test_harness = value.parse().map_err(|_| "--test-harness requires true or false")?,
|
||||
"--jobs" => {
|
||||
let jobs: usize = value.parse().map_err(|_| "--jobs must be a positive integer")?;
|
||||
if jobs == 0 { return Err("--jobs must be greater than zero".into()); }
|
||||
options.jobs = Some(jobs);
|
||||
}
|
||||
_ => return Err(format!("unknown option {flag}\n{USAGE}")),
|
||||
}
|
||||
}
|
||||
deps::Target::parse(&options.target)?;
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent().ok_or("xtask is not inside a workspace")?.to_owned();
|
||||
match operation.as_str() {
|
||||
"deps" => deps::provision(&root, &options),
|
||||
"build" => build_native::build(&root, &options),
|
||||
"package" => package::package(&root, &options),
|
||||
"verify-package" => verify_package::verify(&root, &options),
|
||||
"smoke" => smoke::smoke(&root, &options),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => { eprintln!("xtask: {error}"); ExitCode::FAILURE }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Local-only packaging. No command in this module publishes, downloads SDKs, or
|
||||
//! mutates a runner. Unsigned outputs are recorded explicitly, never release entries.
|
||||
use std::{env, fs, io::Read, path::{Path, PathBuf}, process::Command};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha512};
|
||||
use crate::{Options, deps::{self, Target, run, require_file}};
|
||||
|
||||
pub(crate) fn target_dir(root: &Path) -> PathBuf {
|
||||
env::var_os("CARGO_TARGET_DIR").map(PathBuf::from).map(|p| if p.is_absolute(){p}else{root.join(p)}).unwrap_or_else(||root.join("target"))
|
||||
}
|
||||
pub(crate) fn output_dir(root: &Path, options: &Options) -> PathBuf {
|
||||
options.out.as_ref().map(|p|if p.is_absolute(){p.clone()}else{root.join(p)}).unwrap_or_else(||root.join("dist/native"))
|
||||
}
|
||||
pub(crate) fn mkdir(path: &Path) -> Result<(), String> { fs::create_dir_all(path).map_err(|e|format!("{}: {e}",path.display())) }
|
||||
pub(crate) fn save(path: &Path, value: &Value) -> Result<(), String> {
|
||||
fs::write(path, serde_json::to_vec_pretty(value).map_err(|e|e.to_string())?).map_err(|e|e.to_string())
|
||||
}
|
||||
pub(crate) fn json_file(path: &Path) -> Result<Value, String> {
|
||||
serde_json::from_str(&deps::read_text(path)?).map_err(|e|format!("{}: {e}",path.display()))
|
||||
}
|
||||
pub(crate) fn copy(source: &Path, destination: &Path) -> Result<(), String> {
|
||||
require_file(source)?; if let Some(p)=destination.parent(){mkdir(p)?;}
|
||||
fs::copy(source,destination).map_err(|e|format!("copy {}: {e}",source.display()))?; Ok(())
|
||||
}
|
||||
pub(crate) fn copy_tree(source: &Path, destination: &Path) -> Result<(), String> {
|
||||
mkdir(destination)?;
|
||||
for entry in fs::read_dir(source).map_err(|e|e.to_string())? {
|
||||
let entry=entry.map_err(|e|e.to_string())?; let ty=entry.file_type().map_err(|e|e.to_string())?;
|
||||
if ty.is_symlink(){return Err(format!("package input symlink refused: {}",entry.path().display()));}
|
||||
if ty.is_dir(){copy_tree(&entry.path(),&destination.join(entry.file_name()))?;}else{copy(&entry.path(),&destination.join(entry.file_name()))?;}
|
||||
} Ok(())
|
||||
}
|
||||
pub(crate) fn sha512(path: &Path) -> Result<String,String> {
|
||||
let mut input=fs::File::open(path).map_err(|e|e.to_string())?; let mut hash=Sha512::new(); let mut block=[0u8;65536];
|
||||
loop{let n=input.read(&mut block).map_err(|e|e.to_string())?;if n==0{break;}hash.update(&block[..n]);} Ok(STANDARD.encode(hash.finalize()))
|
||||
}
|
||||
pub(crate) fn version(root: &Path) -> Result<String,String> {
|
||||
let value=json_file(&root.join("package.json"))?;
|
||||
let version=value["version"].as_str().ok_or("package.json version missing")?;
|
||||
if version!=env!("CARGO_PKG_VERSION"){return Err("workspace/package.json version mismatch".into());}
|
||||
Ok(version.to_owned())
|
||||
}
|
||||
pub(crate) fn record(path: &Path, target: Target<'_>, kind: &str) -> Result<Value,String> {
|
||||
require_file(path)?; let size=fs::metadata(path).map_err(|e|e.to_string())?.len(); if size==0{return Err("empty package".into());}
|
||||
Ok(json!({"target":target.triple,"kind":kind,"name":path.file_name().and_then(|s|s.to_str()).ok_or("non-UTF8 package basename")?,"size":size,"sha512":sha512(path)?}))
|
||||
}
|
||||
pub(crate) fn merge_manifest(mut manifest: Value, version: &str, additions: &[Value]) -> Result<Value,String> {
|
||||
if manifest["schema"]!=1||manifest["engine"]!="rust-slint"||manifest["version"]!=version{return Err("native manifest schema/engine/version mismatch".into());}
|
||||
if manifest.as_object().is_none_or(|object|object.len()!=4||object.keys().any(|key|!matches!(key.as_str(),"schema"|"engine"|"version"|"artifacts"))){return Err("native manifest contains unknown fields".into());}
|
||||
let entries=manifest["artifacts"].as_array_mut().ok_or("native artifacts must be an array")?;
|
||||
let mut keys=std::collections::BTreeSet::new(); let mut names=std::collections::BTreeSet::new();
|
||||
for entry in entries.iter().chain(additions.iter()) {
|
||||
if entry.as_object().is_none_or(|object|object.len()!=5||object.keys().any(|key|!matches!(key.as_str(),"target"|"kind"|"name"|"size"|"sha512"))){return Err("native artifact contains unknown fields".into());}
|
||||
let target=entry["target"].as_str().ok_or("artifact target missing")?; let parsed=Target::parse(target)?;
|
||||
if parsed.simulator||(parsed.os=="android"&&parsed.cpu=="x64"){return Err("test-only artifact in release manifest".into());}
|
||||
let kind=entry["kind"].as_str().ok_or("artifact kind missing")?;
|
||||
let allowed:&[&str]=match parsed.os{"win"=>&["nsis","zip"],"linux"=>&["appimage","tar.gz"],"mac"=>&["dmg","zip"],"android"=>&["apk","aab"],"ios"=>&["ipa"],_=>unreachable!()};
|
||||
if !allowed.contains(&kind){return Err("artifact kind does not match target".into());}
|
||||
let name=entry["name"].as_str().ok_or("artifact name missing")?;
|
||||
if name.is_empty()||name.starts_with('.')||!name.bytes().all(|c|c.is_ascii_alphanumeric()||matches!(c,b'-'|b'_'|b'.')){return Err("unsafe asset basename".into());}
|
||||
if entry["size"].as_u64().unwrap_or(0)==0||STANDARD.decode(entry["sha512"].as_str().unwrap_or("")).map_err(|_|"invalid SHA512")?.len()!=64{return Err("invalid artifact size/hash".into());}
|
||||
if !keys.insert((target.to_owned(),kind.to_owned()))||!names.insert(name.to_owned()){return Err(format!("duplicate native artifact {target}/{kind} or asset name"));}
|
||||
}
|
||||
entries.extend_from_slice(additions); Ok(manifest)
|
||||
}
|
||||
fn resources(root: &Path, destination: &Path, native_archive:&Path) -> Result<(),String> {
|
||||
require_file(&root.join("native/resources/licenses/Slint-License-2.0.txt"))?;
|
||||
copy_tree(&root.join("native/resources"),&destination.join("resources"))?;
|
||||
copy_tree(&root.join("LICENSES"),&destination.join("licenses"))?;
|
||||
copy(&root.join("core/THIRD_PARTY_NOTICES.md"),&destination.join("licenses/core-THIRD_PARTY_NOTICES.md"))?;
|
||||
copy(&native_archive.join("LICENSE.md"),&destination.join("licenses/WebRTC-THIRD-PARTY-NOTICES.txt"))?;
|
||||
fs::write(destination.join("LOCAL-ONLY.txt"),"Local functional package. Publication is not authorized: TS6 artwork redistribution rights and platform signing/acceptance must be established separately.\n").map_err(|e|e.to_string())
|
||||
}
|
||||
fn zip(directory: &Path, output: &Path) -> Result<(),String> {
|
||||
if cfg!(windows){run(Command::new("7z").arg("a").arg("-tzip").arg(output).arg(".").current_dir(directory))}
|
||||
else{run(Command::new("zip").args(["-q","-r"]).arg(output).arg(".").current_dir(directory))}
|
||||
}
|
||||
fn signed_windows(path: &Path) -> Result<bool,String> {
|
||||
let Some(cert)=env::var_os("TEAMSPEACH_WINDOWS_CERT_SHA1") else{return Ok(false)};
|
||||
let timestamp=env::var("TEAMSPEACH_WINDOWS_TIMESTAMP_URL").map_err(|_|"signing requires explicit TEAMSPEACH_WINDOWS_TIMESTAMP_URL")?;
|
||||
run(Command::new("signtool").args(["sign","/sha1"]).arg(cert).args(["/fd","SHA256","/tr",×tamp,"/td","SHA256"]).arg(path))?;
|
||||
run(Command::new("signtool").args(["verify","/pa"]).arg(path))?; Ok(true)
|
||||
}
|
||||
fn yaml(out: &Path, version: &str, entry: &Value, target: Target<'_>) -> Result<(),String> {
|
||||
let channel=if version.contains('-'){"preview"}else{"latest"};
|
||||
let suffix=match (target.os,target.cpu){("win","x64")=>"",("linux","x64")=>"-linux",("linux","arm64")=>"-linux-arm64",_=>return Ok(())};
|
||||
// JSON quoted scalars are YAML-compatible; one file per architecture, never ARM Windows in x64 feed.
|
||||
let body=format!("version: {}\nfiles:\n - url: {}\n sha512: {}\n size: {}\npath: {}\nsha512: {}\n",json!(version),entry["name"],entry["sha512"],entry["size"],entry["name"],entry["sha512"]);
|
||||
fs::write(out.join(format!("{channel}{suffix}.yml")),body).map_err(|e|e.to_string())
|
||||
}
|
||||
pub(crate) fn package(root: &Path, options: &Options) -> Result<(),String> {
|
||||
let target=Target::parse(&options.target)?; target.check_host()?; let version=version(root)?;
|
||||
let native_archive=deps::verify(root,target)?;
|
||||
let out=output_dir(root,options); mkdir(&out)?;
|
||||
// A target output is immutable; callers explicitly choose a clean output directory for a rebuild.
|
||||
let work=out.join(target.triple); fs::create_dir(&work).map_err(|e|format!("fresh package directory required {}: {e}",work.display()))?;
|
||||
let release=target_dir(root).join(target.triple).join("release"); let stage=work.join("payload");mkdir(&stage)?;
|
||||
if target.os!="ios"{verify_build_receipt(&release,target,&version,options.test_harness)?;}
|
||||
let stem=format!("TeamsPeach-{version}-{}-{}",target.os,target.cpu);
|
||||
let mut artifacts:Vec<Value>=Vec::new(); let mut release_entries=Vec::new();
|
||||
let mut add=|path:&Path,kind:&str,signing:&str,eligible:bool|->Result<(),String>{
|
||||
let eligible=eligible&&!options.test_harness;
|
||||
let entry=record(path,target,kind)?;let mut local=entry.clone();local["signing"]=json!(signing);local["release_eligible"]=json!(eligible);artifacts.push(local);
|
||||
if eligible{release_entries.push(entry);} Ok(())
|
||||
};
|
||||
match target.os {
|
||||
"win"|"linux"|"mac"=>{
|
||||
let exe=if target.os=="win"{"teamspeach.exe"}else{"teamspeach"};
|
||||
let binary=release.join(exe);crate::verify_package::verify_isa(&binary,target)?;
|
||||
let app=stage.join("TeamsPeach.app");
|
||||
let bin=if target.os=="mac"{app.join("Contents/MacOS")}else{stage.clone()};mkdir(&bin)?;copy(&binary,&bin.join(exe))?;
|
||||
let res=if target.os=="mac"{app.join("Contents/Resources")}else{stage.clone()}; resources(root,&res,&native_archive)?;
|
||||
if target.os!="mac" {let helper=if target.os=="win"{"teamspeach-update-helper.exe"}else{"teamspeach-update-helper"};crate::verify_package::verify_isa(&release.join(helper),target)?;copy(&release.join(helper),&bin.join(helper))?;}
|
||||
match target.os {
|
||||
"win"=>{
|
||||
copy(&root.join("build/icon.ico"),&stage.join("icon.ico"))?;
|
||||
let signed=signed_windows(&stage.join(exe))?;signed_windows(&stage.join("teamspeach-update-helper.exe"))?;
|
||||
stage_build_receipt(&release,&stage,&stage)?;
|
||||
let installer=out.join(format!("{stem}-setup.exe"));
|
||||
run(Command::new("makensis").arg(format!("/DSTAGE={}",stage.display())).arg(format!("/DOUTPUT={}",installer.display())).arg(format!("/DVERSION={version}")).arg(format!("/DTARGET={}",target.triple)).arg(root.join("native/packaging/windows.nsi")))?;
|
||||
signed_windows(&installer)?;
|
||||
add(&installer,"nsis",if signed{"authenticode"}else{"unsigned-local"},true)?;
|
||||
let archive=out.join(format!("{stem}.zip"));zip(&stage,&archive)?;add(&archive,"zip",if signed{"authenticode-payload"}else{"unsigned-local"},true)?;
|
||||
}
|
||||
"linux"=>{
|
||||
let appdir=work.join("TeamsPeach.AppDir");copy_tree(&stage,&appdir.join("usr/bin"))?;
|
||||
copy(&root.join("native/packaging/AppRun"),&appdir.join("AppRun"))?;
|
||||
run(Command::new("chmod").arg("755").arg(appdir.join("AppRun")))?;
|
||||
copy(&root.join("native/packaging/teamspeach.desktop"),&appdir.join("teamspeach.desktop"))?;copy(&root.join("build/icon.png"),&appdir.join("teamspeach.png"))?;
|
||||
// linuxdeploy resolves non-system native libraries; system glibc remains host-provided.
|
||||
run(Command::new("linuxdeploy").arg("--appdir").arg(&appdir).arg("--executable").arg(appdir.join("usr/bin/teamspeach")).arg("--executable").arg(appdir.join("usr/bin/teamspeach-update-helper")))?;
|
||||
stage_build_receipt(&release,&appdir.join("usr/bin"),&appdir.join("usr/bin"))?;
|
||||
let archive=out.join(format!("{stem}.tar.gz"));run(Command::new("tar").arg("-czf").arg(&archive).arg("-C").arg(&appdir).arg("."))?;add(&archive,"tar.gz","not-applicable",true)?;
|
||||
let image=out.join(format!("{stem}.AppImage"));run(Command::new("appimagetool").arg(&appdir).arg(&image).env("ARCH",if target.cpu=="arm64"{"aarch64"}else{"x86_64"}))?;add(&image,"appimage","not-applicable",true)?;
|
||||
}
|
||||
"mac"=>{
|
||||
let plist=deps::read_text(&root.join("native/packaging/macos-info.plist"))?.replace("@VERSION@",&version);
|
||||
fs::write(app.join("Contents/Info.plist"),plist).map_err(|e|e.to_string())?;
|
||||
copy(&root.join("build/icon.png"),&res.join("icon.png"))?;
|
||||
// dylibbundler rewrites and copies actual non-system dependencies; no assumed static linkage.
|
||||
run(Command::new("dylibbundler").args(["-b","-x"]).arg(bin.join(exe)).arg("-d").arg(app.join("Contents/Frameworks")).args(["-p","@executable_path/../Frameworks/"]))?;
|
||||
let identity=env::var("TEAMSPEACH_APPLE_SIGN_IDENTITY").unwrap_or_else(|_|"-".into());
|
||||
run(Command::new("codesign").args(["--force","--deep","--sign",&identity]).arg(&app))?;
|
||||
let signing=if identity=="-"{"ad-hoc-local"}else{"developer-id"};
|
||||
let archive=out.join(format!("{stem}.zip"));run(Command::new("ditto").args(["-c","-k","--keepParent"]).arg(&app).arg(&archive))?;add(&archive,"zip",signing,true)?;
|
||||
let dmg=out.join(format!("{stem}.dmg"));run(Command::new("hdiutil").args(["create","-format","UDZO","-volname","TeamsPeach","-srcfolder"]).arg(&stage).arg(&dmg))?;add(&dmg,"dmg",signing,true)?;
|
||||
}
|
||||
_=>unreachable!()
|
||||
}
|
||||
}
|
||||
"android"=>{
|
||||
let abi=if target.cpu=="arm64"{"arm64-v8a"}else{"x86_64"};let jni=work.join("jni");
|
||||
crate::verify_package::verify_isa(&release.join("libteamspeach_native.so"),target)?;
|
||||
copy(&release.join("libteamspeach_native.so"),&jni.join(abi).join("libteamspeach_native.so"))?;
|
||||
if !options.test_harness{run(Command::new("llvm-strip").arg("--strip-unneeded").arg(jni.join(abi).join("libteamspeach_native.so")))?;}
|
||||
let jar=release.join("libwebrtc.jar");require_file(&jar)?;
|
||||
let pinned=native_archive.join("libwebrtc.jar");if deps::sha256(&jar)?!=deps::sha256(&pinned)?{return Err("Android jar does not match pinned archive".into());}
|
||||
resources(root,&stage,&native_archive)?;
|
||||
stage_build_receipt(&release,&jni.join(abi),&stage)?;
|
||||
let signed=env::var_os("TEAMSPEACH_ANDROID_KEYSTORE").is_some();
|
||||
if signed{for key in ["TEAMSPEACH_ANDROID_STORE_PASSWORD","TEAMSPEACH_ANDROID_KEY_ALIAS","TEAMSPEACH_ANDROID_KEY_PASSWORD"]{if env::var_os(key).is_none(){return Err(format!("missing signing credential {key}"));}}}
|
||||
let mut gradle=Command::new("sh");gradle.current_dir(root.join("platform/android")).arg("gradlew").args(["--offline","--no-daemon"])
|
||||
.arg(format!("-PnativeJniDir={}",jni.display())).arg(format!("-PwebrtcJar={}",jar.display())).arg(format!("-PtargetAbi={abi}"))
|
||||
.arg(format!("-PnativeAssetsDir={}",stage.display())).arg(format!("-PversionName={version}")).arg(format!("-PtestHarness={}",options.test_harness));
|
||||
gradle.arg("nativeArtifacts");run(&mut gradle)?;
|
||||
let outputs=json_file(&root.join("platform/android/build/native-artifacts.json"))?;
|
||||
if outputs["schema"]!=1||outputs["abi"]!=abi||outputs["harness"]!=options.test_harness||outputs["testOnly"]!=(options.test_harness||target.cpu=="x64")||outputs["channel"]!="direct"{return Err("Android artifact report identity/test-harness/channel mismatch".into());}
|
||||
let apks=outputs["apk"].as_array().ok_or("Android artifact report missing APK list")?;
|
||||
if apks.len()!=1{return Err("expected exactly one ABI-specific APK".into());}
|
||||
let mut generated=vec![("apk",PathBuf::from(apks[0].as_str().ok_or("APK path missing")?))];
|
||||
if target.cpu=="arm64"&&!options.test_harness{generated.push(("aab",PathBuf::from(outputs["aab"].as_str().ok_or("ARM64 AAB path missing")?)));}
|
||||
for (kind,mut source) in generated {
|
||||
if kind=="aab"{
|
||||
// Preserve the direct-install APK before rebuilding the store
|
||||
// variant without REQUEST_INSTALL_PACKAGES/self-update routing.
|
||||
gradle.arg("-PbuildChannel=google-play");run(&mut gradle)?;
|
||||
let store=json_file(&root.join("platform/android/build/native-artifacts.json"))?;
|
||||
if store["schema"]!=1||store["abi"]!=abi||store["harness"]!=false||store["testOnly"]!=false||store["channel"]!="google-play"{return Err("Android store artifact report mismatch".into());}
|
||||
source=PathBuf::from(store["aab"].as_str().ok_or("store AAB path missing")?);
|
||||
}
|
||||
let name=format!("{stem}{}.{kind}",if options.test_harness{"-harness-test"}else if target.cpu=="x64"{"-emulator-test"}else if !signed{"-unsigned"}else{""});let dest=out.join(name);copy(&source,&dest)?;
|
||||
add(&dest,kind,if options.test_harness{"android-debug-test"}else if signed{"android-keystore"}else{"unsigned-not-installable"},signed&&target.cpu=="arm64")?;
|
||||
}
|
||||
}
|
||||
"ios"=>{
|
||||
let project=root.join("platform/ios");run(Command::new("xcodegen").arg("--spec").arg(project.join("project.yml")))?;
|
||||
let team=env::var("TEAMSPEACH_APPLE_TEAM").ok().filter(|s|!s.is_empty());let signed=!target.simulator&&team.is_some();
|
||||
let mut command=Command::new("xcodebuild");command.arg("-project").arg(project.join("TeamsPeach.xcodeproj")).args(["-scheme","TeamsPeach","-configuration","Release","-sdk",if target.simulator{"iphonesimulator"}else{"iphoneos"}]);
|
||||
command.env("TEAMSPEACH_TEST_HARNESS",options.test_harness.to_string());
|
||||
if let Some(team)=team{command.arg(format!("DEVELOPMENT_TEAM={team}"));}
|
||||
command.arg(if signed{"CODE_SIGNING_ALLOWED=YES"}else{"CODE_SIGNING_ALLOWED=NO"});
|
||||
if target.simulator{
|
||||
command.arg("-derivedDataPath").arg(work.join("DerivedData")).args(["-destination","generic/platform=iOS Simulator","build"]);run(&mut command)?;
|
||||
copy_tree(&work.join("DerivedData/Build/Products/Release-iphonesimulator/TeamsPeach.app"),&work.join("TeamsPeach.app"))?;
|
||||
artifacts.push(json!({"kind":"simulator.app","path":work.join("TeamsPeach.app"),"signing":"unsigned-simulator","release_eligible":false}));
|
||||
}else{
|
||||
let archive=work.join(if signed{"TeamsPeach.xcarchive"}else{"TeamsPeach-unsigned.xcarchive"});command.arg("-archivePath").arg(&archive).args(["-destination","generic/platform=iOS","archive"]);run(&mut command)?;
|
||||
if signed{
|
||||
let export=env::var_os("TEAMSPEACH_IOS_EXPORT_OPTIONS").map(PathBuf::from).ok_or("signed IPA export requires explicit TEAMSPEACH_IOS_EXPORT_OPTIONS plist and provisioned profiles")?;require_file(&export)?;
|
||||
let export_dir=work.join("export");run(Command::new("xcodebuild").arg("-exportArchive").arg("-archivePath").arg(&archive).arg("-exportPath").arg(&export_dir).arg("-exportOptionsPlist").arg(export))?;
|
||||
let mut ipas=fs::read_dir(&export_dir).map_err(|e|e.to_string())?.filter_map(Result::ok).map(|e|e.path()).filter(|p|p.extension().is_some_and(|s|s=="ipa"));
|
||||
let ipa=ipas.next().ok_or("Xcode export produced no IPA")?;if ipas.next().is_some(){return Err("ambiguous exported IPA".into());}let dest=out.join(format!("{stem}.ipa"));copy(&ipa,&dest)?;add(&dest,"ipa","apple-provisioned",true)?;
|
||||
}
|
||||
artifacts.push(json!({"kind":"xcarchive","path":archive,"signing":if signed{"apple-provisioned"}else{"unsigned-not-installable"},"release_eligible":false}));
|
||||
}
|
||||
}
|
||||
_=>unreachable!()
|
||||
}
|
||||
let source_build=verify_build_receipt(&release,target,&version,options.test_harness)?;
|
||||
let local=json!({"schema":1,"engine":"rust-slint","version":version,"target":target.triple,"testOnly":options.test_harness,"sourceBuild":source_build,"publication":"blocked: acceptance/signing/artwork redistribution authorization required","artifacts":artifacts});
|
||||
save(&work.join("package-report.json"),&local)?;
|
||||
// Verify actual archive contents before exposing update metadata.
|
||||
crate::verify_package::verify(root,options)?;
|
||||
if !release_entries.is_empty(){
|
||||
let manifest_path=out.join("native-manifest.json");
|
||||
// Serialize cross-target merge; never silently overwrite another packaging process.
|
||||
let lock=out.join("native-manifest.lock");let guard=fs::OpenOptions::new().write(true).create_new(true).open(&lock).map_err(|e|format!("manifest merge lock {}: {e}",lock.display()))?;
|
||||
let result:Result<(),String>=(||{
|
||||
let previous=if manifest_path.exists(){json_file(&manifest_path)?}else{json!({"schema":1,"engine":"rust-slint","version":version,"artifacts":[]})};
|
||||
let merged=merge_manifest(previous,&version,&release_entries)?;let temporary=out.join("native-manifest.json.new");save(&temporary,&merged)?;
|
||||
for entry in &release_entries{if matches!(entry["kind"].as_str(),Some("nsis"|"appimage")){yaml(&out,&version,entry,target)?;}}
|
||||
atomic_replace(&temporary,&manifest_path)?;
|
||||
Ok(())
|
||||
})();drop(guard);let cleanup=fs::remove_file(&lock).map_err(|e|e.to_string());result?;cleanup?;
|
||||
}
|
||||
println!("Local package report: {}",work.join("package-report.json").display());
|
||||
println!("PUBLICATION BLOCKED: no release/tag/upload performed; artwork rights and full platform acceptance remain separate gates.");Ok(())
|
||||
}
|
||||
|
||||
fn atomic_replace(source:&Path,destination:&Path)->Result<(),String>{
|
||||
#[cfg(windows)]{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
#[link(name="kernel32")] unsafe extern "system"{fn MoveFileExW(source:*const u16,destination:*const u16,flags:u32)->i32;}
|
||||
let source:Vec<u16>=source.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let destination:Vec<u16>=destination.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
if unsafe{MoveFileExW(source.as_ptr(),destination.as_ptr(),1|8)}==0{return Err(std::io::Error::last_os_error().to_string());}Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]{fs::rename(source,destination).map_err(|e|e.to_string())}
|
||||
}
|
||||
|
||||
fn verify_build_receipt(release:&Path,target:Target<'_>,version:&str,test_harness:bool)->Result<Value,String>{
|
||||
let receipt=json_file(&release.join("native-build.json"))?;
|
||||
if receipt["schema"]!=1||receipt["engine"]!="rust-slint"||receipt["version"]!=version||receipt["target"]!=target.triple||receipt["testHarness"]!=test_harness{return Err("native build receipt version/target/engine/test-harness mismatch; rebuild through xtask build".into());}
|
||||
let binaries=receipt["binaries"].as_array().ok_or("native build receipt lacks binaries")?;
|
||||
let expected:&[&str]=match target.os{"win"=>&["teamspeach.exe","teamspeach-update-helper.exe"],"linux"=>&["teamspeach","teamspeach-update-helper"],"android"=>&["libteamspeach_native.so"],_=>&["teamspeach"]};
|
||||
if binaries.len()!=expected.len(){return Err("native build receipt binary set mismatch".into());}
|
||||
for name in expected{
|
||||
let entries:Vec<_>=binaries.iter().filter(|entry|entry["name"]==*name).collect();
|
||||
if entries.len()!=1||entries[0]["sha256"]!=deps::sha256(&release.join(name))?{return Err(format!("native binary {name} does not match the build/version receipt"));}
|
||||
}Ok(receipt)
|
||||
}
|
||||
fn stage_build_receipt(release:&Path,binaries:&Path,destination:&Path)->Result<(),String>{
|
||||
let mut receipt=json_file(&release.join("native-build.json"))?;
|
||||
for entry in receipt["binaries"].as_array_mut().ok_or("missing build receipt binaries")?{
|
||||
let name=entry["name"].as_str().ok_or("missing build receipt binary name")?;
|
||||
entry["packagedSha256"]=json!(deps::sha256(&binaries.join(name))?);
|
||||
}
|
||||
save(&destination.join("resources/native-build.json"),&receipt)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test] fn manifest_rejects_duplicate_and_mobile_test_assets(){
|
||||
let base=json!({"schema":1,"engine":"rust-slint","version":"0.1.7","artifacts":[]});
|
||||
let entry=json!({"target":"x86_64-pc-windows-msvc","kind":"nsis","name":"client.exe","size":12,"sha512":STANDARD.encode([0u8;64])});
|
||||
let merged=merge_manifest(base.clone(),"0.1.7",&[entry.clone()]).unwrap();
|
||||
assert!(merge_manifest(merged,"0.1.7",&[entry.clone()]).is_err());
|
||||
let mut bad=entry;bad["target"]=json!("x86_64-linux-android");bad["kind"]=json!("apk");assert!(merge_manifest(base,"0.1.7",&[bad]).is_err());
|
||||
}
|
||||
#[test] fn different_windows_isas_share_manifest_not_yaml(){
|
||||
let base=json!({"schema":1,"engine":"rust-slint","version":"0.1.7","artifacts":[]});
|
||||
let x64=json!({"target":"x86_64-pc-windows-msvc","kind":"nsis","name":"client-x64.exe","size":12,"sha512":STANDARD.encode([0u8;64])});
|
||||
let mut arm=x64.clone();arm["target"]=json!("aarch64-pc-windows-msvc");arm["name"]=json!("client-arm64.exe");
|
||||
let merged=merge_manifest(base.clone(),"0.1.7",&[x64.clone(),arm]).unwrap();assert_eq!(merged["artifacts"].as_array().unwrap().len(),2);
|
||||
for name in ["../client.exe","client.exe?other","C:client.exe",".hidden"]{let mut entry=x64.clone();entry["name"]=json!(name);assert!(merge_manifest(base.clone(),"0.1.7",&[entry]).is_err());}
|
||||
let mut invalid=x64;invalid["sha512"]=json!(STANDARD.encode([0u8;32]));assert!(merge_manifest(base,"0.1.7",&[invalid]).is_err());
|
||||
}
|
||||
#[test] fn artifact_digest_changes_when_bytes_change(){
|
||||
let path=env::temp_dir().join(format!("teamspeach-artifact-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
|
||||
fs::write(&path,b"same-size-one").unwrap();let first=record(&path,Target::parse("x86_64-pc-windows-msvc").unwrap(),"zip").unwrap();
|
||||
fs::write(&path,b"same-size-two").unwrap();let second=record(&path,Target::parse("x86_64-pc-windows-msvc").unwrap(),"zip").unwrap();
|
||||
fs::remove_file(path).unwrap();assert_eq!(first["size"],second["size"]);assert_ne!(first["sha512"],second["sha512"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Explicitly invoked offline smoke. Runs real application/decoder binaries in a
|
||||
//! disposable profile, validates their measured reports, and never invents a pass.
|
||||
use std::{fs,path::{Path,PathBuf},process::Command,time::{Duration,Instant}};
|
||||
use serde_json::{Value,json};
|
||||
use crate::{Options,deps::{self,Target,run,capture},package};
|
||||
|
||||
fn execute(command:&mut Command)->Result<(),String>{
|
||||
let mut child=command.spawn().map_err(|e|format!("starting smoke: {e}"))?;let start=Instant::now();
|
||||
loop{if let Some(status)=child.try_wait().map_err(|e|e.to_string())?{return if status.success(){Ok(())}else{Err(format!("smoke process failed: {status}"))};}
|
||||
if start.elapsed()>Duration::from_secs(180){let _=child.kill();let _=child.wait();return Err("smoke exceeded 180-second deadline".into());}
|
||||
std::thread::sleep(Duration::from_millis(50));}
|
||||
}
|
||||
pub(crate) fn smoke(root:&Path,options:&Options)->Result<(),String>{
|
||||
let target=Target::parse(&options.target)?;
|
||||
let scenario=options.scenario.as_deref().ok_or("smoke requires --scenario offline-ui|migration|media-loopback|codec-fixtures")?;
|
||||
if !matches!(scenario,"offline-ui"|"migration"|"media-loopback"|"codec-fixtures"){return Err("unsupported smoke scenario".into());}
|
||||
let out=package::output_dir(root,options);
|
||||
if out.exists(){return Err(format!("smoke requires a fresh --out directory, refusing stale evidence: {}",out.display()));}
|
||||
package::mkdir(&out)?;let out=fs::canonicalize(out).map_err(|e|e.to_string())?;
|
||||
if scenario=="codec-fixtures"{return codecs(root,options,target,&out);}
|
||||
// The importer intentionally rejects every existing unmarked directory, even empty ones.
|
||||
// Supply a fresh destination; the application owns creation/activation of its profile.
|
||||
let profile=out.join("disposable-profile");
|
||||
let binary=package::target_dir(root).join(target.triple).join("release").join(if target.os=="win"{"teamspeach.exe"}else{"teamspeach"});
|
||||
if target.os=="android"{return android(root,options,target,scenario,&out);}
|
||||
if target.os=="ios"{
|
||||
if !target.simulator{return Err("iOS device smoke requires provisioned device accessibility automation; use explicit simulator target for simctl smoke, never infer a device".into());}
|
||||
return ios(root,options,target,scenario,&out);
|
||||
}
|
||||
target.check_host()?;
|
||||
let cpu=if std::env::consts::ARCH=="aarch64"{"arm64"}else{"x64"};if cpu!=target.cpu{return Err("smoke target ISA must match this host; cross-build verification is not runtime acceptance".into());}
|
||||
crate::verify_package::verify_isa(&binary,target)?;
|
||||
execute(Command::new(&binary).args(["--smoke",scenario,"--profile-dir"]).arg(&profile).arg("--output").arg(&out)
|
||||
.env("TEAMSPEACH_PROFILE_DIR",&profile).env("TEAMSPEACH_SMOKE_NO_NETWORK","1").env("TEAMSPEACH_SMOKE_NO_OS_ACTIONS","1").env("TEAMSPEACH_SMOKE_NO_PHYSICAL_CAPTURE","1"))?;
|
||||
validate_report(&out,&profile,target,package::version(root)?.as_str(),scenario)?;
|
||||
println!("Real native smoke report: {}",out.join("result.json").display());Ok(())
|
||||
}
|
||||
fn validate_report(out:&Path,profile:&Path,target:Target<'_>,version:&str,scenario:&str)->Result<(),String>{
|
||||
let report=package::json_file(&out.join("result.json"))?;
|
||||
if report["schema"]!=1||report["engine"]!="rust-slint"||report["version"]!=version||report["target"]!=target.triple||report["scenario"]!=scenario||report["passed"]!=true{return Err("native smoke report identity/result failed".into());}
|
||||
for guard in ["network_enabled","os_actions_enabled","physical_capture_enabled"]{if report[guard]!=false{return Err(format!("unsafe smoke report: {guard}"));}}
|
||||
if report["profile_dir"].as_str()!=profile.to_str(){return Err("smoke report used a non-disposable profile".into());}
|
||||
let checks=report["checks"].as_array().ok_or("smoke lacks measured checks")?;
|
||||
for name in ["profile-restart","capture-denied","stale-session","settings-navigation","chat-draft-retention","responsive-render","local-ptt-text-focus","rich-native-render"]{
|
||||
let found:Vec<_>=checks.iter().filter(|c|c["name"]==name).collect();if found.len()!=1||found[0]["passed"]!=true{return Err(format!("required runtime check failed/missing/duplicated: {name}"));}}
|
||||
for name in match scenario {"migration"=>&["migration-preservation"][..],"media-loopback"=>&["native-peer-loopback"][..],_=>&[][..]} {
|
||||
let found:Vec<_>=checks.iter().filter(|check|check["name"]==*name).collect();
|
||||
if found.len()!=1||found[0]["passed"]!=true{return Err(format!("required scenario check failed/missing/duplicated: {name}"));}
|
||||
}
|
||||
if checks.iter().any(|c|c["passed"]!=true){return Err("native smoke reported a failed check".into());}
|
||||
let screenshots=report["screenshots"].as_array().filter(|s|!s.is_empty()).ok_or("smoke has no rendered screenshots")?;
|
||||
for screenshot in screenshots{
|
||||
let path=PathBuf::from(screenshot["path"].as_str().ok_or("screenshot path missing")?);let path=if path.is_absolute(){path}else{out.join(path)};
|
||||
let path=fs::canonicalize(path).map_err(|e|e.to_string())?;if !path.starts_with(out){return Err("screenshot leaves smoke output directory".into());}
|
||||
let bytes=fs::read(&path).map_err(|e|e.to_string())?;
|
||||
if bytes.len()<33||&bytes[..8]!=b"\x89PNG\r\n\x1a\n"||&bytes[12..16]!=b"IHDR"{return Err("screenshot is not an actual PNG".into());}
|
||||
let width=u32::from_be_bytes(bytes[16..20].try_into().unwrap());let height=u32::from_be_bytes(bytes[20..24].try_into().unwrap());
|
||||
if width==0||height==0||screenshot["width"]!=width||screenshot["height"]!=height{return Err("screenshot dimensions disagree with PNG pixels".into());}
|
||||
}Ok(())
|
||||
}
|
||||
fn android(root:&Path,options:&Options,target:Target<'_>,scenario:&str,out:&Path)->Result<(),String>{
|
||||
let serial=options.device.as_deref().ok_or("Android smoke requires --device <explicit adb serial>; no device is selected automatically")?;
|
||||
let apk=options.app.as_ref().ok_or("Android smoke requires --app <test-harness APK>; installing is limited to the explicitly selected test device")?;deps::require_file(apk)?;
|
||||
run(Command::new("adb").args(["-s",serial,"install","-r"]).arg(apk))?;
|
||||
let package_id="dev.teamspeach.mobile";
|
||||
let home=capture(Command::new("adb").args(["-s",serial,"shell","run-as",package_id,"pwd"]))?;
|
||||
let nonce=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e|e.to_string())?.as_nanos();
|
||||
let base=format!("{}/files/native-smoke/{nonce}",home.trim());let remote=format!("{base}/out");let profile=format!("{base}/profile");
|
||||
run(Command::new("adb").args(["-s",serial,"shell","run-as",package_id,"mkdir","-p",&profile,&remote]))?;
|
||||
run(Command::new("adb").args(["-s",serial,"shell","am","start","-W","-n","dev.teamspeach.mobile/.TeamsPeachActivity","--es","teamspeach.smoke",scenario,"--es","teamspeach.profile",&profile,"--es","teamspeach.out",&remote]))?;
|
||||
// Application writes result last. Poll only this explicit device, bounded by
|
||||
// the smoke deadline; no process kill/physical capture/network actions.
|
||||
let start=Instant::now();let text=loop{
|
||||
let result=Command::new("adb").args(["-s",serial,"exec-out","run-as",package_id,"cat",&format!("{remote}/result.json")]).output().map_err(|e|e.to_string())?;
|
||||
if result.status.success(){break result.stdout;}
|
||||
if start.elapsed()>Duration::from_secs(180){return Err("Android runtime did not produce smoke report (test-harness APK required)".into());}std::thread::sleep(Duration::from_millis(500));
|
||||
};
|
||||
let mut report:Value=serde_json::from_slice(&text).map_err(|e|e.to_string())?;
|
||||
for shot in report["screenshots"].as_array_mut().ok_or("missing Android screenshots")?{
|
||||
let supplied=shot["path"].as_str().ok_or("missing screenshot path")?;
|
||||
let relative=Path::new(supplied).strip_prefix(&remote).unwrap_or(Path::new(supplied));
|
||||
if relative.is_absolute()||relative.components().any(|c|!matches!(c,std::path::Component::Normal(_))){return Err("Android screenshot escapes output".into());}
|
||||
let source=format!("{remote}/{}",relative.to_string_lossy());let local=out.join(relative);if let Some(parent)=local.parent(){package::mkdir(parent)?;}
|
||||
let data=Command::new("adb").args(["-s",serial,"exec-out","run-as",package_id,"cat",&source]).output().map_err(|e|e.to_string())?;if !data.status.success(){return Err("reading Android screenshot failed".into());}fs::write(&local,data.stdout).map_err(|e|e.to_string())?;shot["path"]=json!(local);
|
||||
}
|
||||
// Preserve original device report as evidence; validation uses its real remote
|
||||
// profile and localized screenshot paths, never substitutes a fake result.
|
||||
fs::write(out.join("device-result.json"),text).map_err(|e|e.to_string())?;package::save(&out.join("result.json"),&report)?;
|
||||
validate_report(out,Path::new(&profile),target,&package::version(root)?,scenario)
|
||||
}
|
||||
fn ios(root:&Path,options:&Options,target:Target<'_>,scenario:&str,out:&Path)->Result<(),String>{
|
||||
target.check_host()?;let device=options.device.as_deref().ok_or("iOS simulator smoke requires --device <chosen simulator UDID>")?;
|
||||
let app=options.app.as_ref().ok_or("iOS simulator smoke requires --app <packaged simulator .app>")?;
|
||||
run(Command::new("xcrun").args(["simctl","install",device]).arg(app))?;
|
||||
let home=capture(Command::new("xcrun").args(["simctl","get_app_container",device,"dev.teamspeach.mobile","data"]))?;
|
||||
let nonce=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e|e.to_string())?.as_nanos();let device_out=PathBuf::from(home.trim()).join(format!("Library/Caches/smoke-{nonce}"));let profile=device_out.join("profile");package::mkdir(&device_out)?;
|
||||
run(Command::new("xcrun").args(["simctl","launch",device,"dev.teamspeach.mobile","--smoke",scenario,"--profile-dir"]).arg(&profile).arg("--output").arg(&device_out))?;
|
||||
let start=Instant::now();while !device_out.join("result.json").is_file(){if start.elapsed()>Duration::from_secs(180){return Err("simulator did not produce native smoke report".into());}std::thread::sleep(Duration::from_millis(300));}
|
||||
validate_report(&device_out,&profile,target,&package::version(root)?,scenario)?;
|
||||
package::copy_tree(&device_out,&out.join("simulator-evidence"))?;
|
||||
run(Command::new("xcrun").args(["simctl","io",device,"screenshot"]).arg(out.join("simulator-os.png")))?;
|
||||
println!("Simulator-only evidence: {}",out.join("simulator-evidence/result.json").display());Ok(())
|
||||
}
|
||||
fn codecs(root:&Path,options:&Options,target:Target<'_>,out:&Path)->Result<(),String>{
|
||||
target.check_host()?;
|
||||
if matches!(target.os,"android"|"ios"){return Err("codec executable smoke requires desktop host; mobile fixture decoding must execute within the provisioned device harness".into());}
|
||||
let archive=deps::verify(root,target)?;
|
||||
let generated;
|
||||
let probe=if let Some(probe)=options.codec_probe.as_ref(){probe}else{
|
||||
let environment=crate::build_native::Environment::discover(root,options,target,false)?;
|
||||
let compiler=environment.require_program(if target.os=="win"{"clang-cl"}else{"clang++"})?;
|
||||
run(environment.command(&environment.python).arg(root.join("native/packaging/build_codec_probe.py")).arg(root).arg(&archive).arg(out).arg(target.triple).arg(compiler))?;
|
||||
generated=out.join(if target.os=="win"{"codec_probe.exe"}else{"codec_probe"});&generated
|
||||
};
|
||||
crate::verify_package::verify_isa(probe,target)?;
|
||||
let ffmpeg_version=capture(Command::new("ffmpeg").arg("-version"))?;let mut results=Vec::new();
|
||||
for(codec,encoder,extension)in[("AV1","libaom-av1","ivf"),("H264","libx264","h264"),("VP8","libvpx","ivf"),("VP9","libvpx-vp9","ivf")]{
|
||||
let fixture=out.join(format!("{}.{}",codec.to_lowercase(),extension));let mut generate=Command::new("ffmpeg");
|
||||
generate.args(["-nostdin","-v","error","-f","lavfi","-i","testsrc2=size=160x96:rate=1","-frames:v","1","-pix_fmt","yuv420p","-c:v",encoder]);
|
||||
match codec{"H264"=>{generate.args(["-profile:v","high","-x264-params","cabac=1:8x8dct=1:keyint=1","-crf","10"]);},"AV1"=>{generate.args(["-cpu-used","8","-crf","20"]);},_=>{generate.args(["-b:v","1M"]);}}
|
||||
generate.arg("-f").arg(extension).arg(&fixture);run(&mut generate)?;
|
||||
if codec=="H264"{let data=fs::read(&fixture).map_err(|e|e.to_string())?;if !data.windows(5).any(|w|w[..3]==[0,0,1]&&w[3]&31==7&&w[4]==100){return Err("generated H264 fixture is not actual SPS profile_idc=100 High".into());}}
|
||||
let expected=out.join(format!("{}-reference.i420",codec.to_lowercase()));run(Command::new("ffmpeg").args(["-nostdin","-v","error","-i"]).arg(&fixture).args(["-frames:v","1","-pix_fmt","yuv420p","-f","rawvideo"]).arg(&expected))?;
|
||||
let decoded=out.join(format!("{}-native.i420",codec.to_lowercase()));let decoder=capture(Command::new(probe).arg(codec).arg(&fixture).arg(&decoded))?;
|
||||
let reference=fs::read(&expected).map_err(|e|e.to_string())?;let actual=fs::read(&decoded).map_err(|e|e.to_string())?;
|
||||
if reference.len()!=160*96*3/2||actual.len()!=reference.len(){return Err(format!("{codec} decoded frame size mismatch"));}
|
||||
let error:f64=actual.iter().zip(&reference).map(|(a,b)|(*a as f64-*b as f64).abs()).sum::<f64>()/actual.len() as f64;
|
||||
if actual!=reference{return Err(format!("{codec} production decoded pixels differ from fixture reference: MAE={error}"));}
|
||||
results.push(json!({"codec":codec,"profile":if codec=="H264"{"High profile_idc=100"}else{"fixture default"},"fixture_sha256":deps::sha256(&fixture)?,"pixels_sha256":deps::sha256(&decoded)?,"mae":error,"decoder_output":decoder,"passed":true}));
|
||||
}
|
||||
package::save(&out.join("codec-results.json"),&json!({"schema":1,"engine":"rust-slint","target":target.triple,"passed":true,"physical_capture_enabled":false,"network_enabled":false,"probe_sha256":deps::sha256(probe)?,"probe_source_sha256":deps::sha256(&root.join("native/tools/codec_probe.cpp"))?,"factory_source_sha256":deps::sha256(&root.join("native/vendor/webrtc-sys-0.3.53/src/video_decoder_factory.cpp"))?,"dependency_directory":archive,"ffmpeg":ffmpeg_version,"results":results}))?;Ok(())
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Inspection of real package bytes and extracted payloads, never a manifest-only pass.
|
||||
use std::{collections::BTreeSet, fs, io::Read, path::{Path,PathBuf}, process::Command};
|
||||
use serde_json::{Value,json};
|
||||
use crate::{Options, deps::{self,Target,capture,run}, package};
|
||||
|
||||
fn u16le(bytes:&[u8],at:usize)->Result<u16,String>{Ok(u16::from_le_bytes(bytes.get(at..at+2).ok_or("truncated binary header")?.try_into().unwrap()))}
|
||||
fn u32le(bytes:&[u8],at:usize)->Result<u32,String>{Ok(u32::from_le_bytes(bytes.get(at..at+4).ok_or("truncated binary header")?.try_into().unwrap()))}
|
||||
fn u64le(bytes:&[u8],at:usize)->Result<u64,String>{Ok(u64::from_le_bytes(bytes.get(at..at+8).ok_or("truncated binary header")?.try_into().unwrap()))}
|
||||
fn machine(bytes:&[u8])->Result<(&'static str,&'static str),String>{
|
||||
if bytes.starts_with(b"MZ") {let pe=u32le(bytes,0x3c)? as usize;if bytes.get(pe..pe+4)!=Some(b"PE\0\0"){return Err("invalid PE signature".into());}let cpu=match u16le(bytes,pe+4)?{0x8664=>"x64",0xaa64=>"arm64",_=>return Err("unsupported PE machine".into())};return Ok(("pe",cpu));}
|
||||
if bytes.starts_with(b"\x7fELF"){if bytes.get(4)!=Some(&2)||bytes.get(5)!=Some(&1){return Err("expected little-endian 64-bit ELF".into());}return Ok(("elf",match u16le(bytes,18)?{62=>"x64",183=>"arm64",_=>return Err("unsupported ELF machine".into())}));}
|
||||
if bytes.starts_with(&[0xcf,0xfa,0xed,0xfe]){return Ok(("macho",match u32le(bytes,4)?{0x01000007=>"x64",0x0100000c=>"arm64",_=>return Err("unsupported Mach-O CPU".into())}));}
|
||||
Err("not a supported thin PE/ELF/Mach-O binary (universal payload requires target-specific packaging)".into())
|
||||
}
|
||||
pub(crate) fn verify_isa(path:&Path,target:Target<'_>)->Result<(),String>{
|
||||
let bytes=binary_header(path)?;let(format,cpu)=machine(&bytes)?;
|
||||
let expected=match target.os{"win"=>"pe","linux"|"android"=>"elf",_=>"macho"};
|
||||
if format!=expected||cpu!=target.cpu{return Err(format!("{} is {format}/{cpu}, expected {expected}/{}",path.display(),target.cpu));}
|
||||
if format=="elf"&&target.cpu=="arm64"{verify_elf_pages(&bytes)?;}
|
||||
if format=="macho"{verify_apple_abi(&bytes,target)?;}Ok(())
|
||||
}
|
||||
fn binary_header(path:&Path)->Result<Vec<u8>,String>{
|
||||
let file=fs::File::open(path).map_err(|e|format!("{}: {e}",path.display()))?;
|
||||
let mut bytes=Vec::new();file.take(1024*1024).read_to_end(&mut bytes).map_err(|e|e.to_string())?;Ok(bytes)
|
||||
}
|
||||
fn verify_apple_abi(bytes:&[u8],target:Target<'_>)->Result<(),String>{
|
||||
let mut at=32usize;let mut found=false;
|
||||
for _ in 0..u32le(bytes,16)?{
|
||||
let command=u32le(bytes,at)?;let size=u32le(bytes,at+4)? as usize;if size<8{return Err("invalid Mach-O load command".into());}
|
||||
let(platform,minimum)=match command{
|
||||
0x32=>(u32le(bytes,at+8)?,u32le(bytes,at+12)?),
|
||||
0x24=>(1,u32le(bytes,at+8)?),0x25=>(2,u32le(bytes,at+8)?),_=>{at=at.checked_add(size).ok_or("Mach-O offset overflow")?;continue;}
|
||||
};
|
||||
let expected=if target.os=="mac"{1}else if target.simulator{7}else{2};
|
||||
let maximum=if target.os=="mac"{(14<<16)|(2<<8)}else{16<<16};
|
||||
if platform!=expected||minimum>maximum{return Err("Mach-O platform/device-simulator ABI or minimum OS mismatch".into());}found=true;
|
||||
at=at.checked_add(size).ok_or("Mach-O offset overflow")?;
|
||||
}
|
||||
if !found{return Err("Mach-O missing deployment platform metadata".into());}Ok(())
|
||||
}
|
||||
fn verify_elf_pages(bytes:&[u8])->Result<(),String>{
|
||||
let start=usize::try_from(u64le(bytes,32)?).map_err(|_|"ELF program header overflow")?;let stride=u16le(bytes,54)? as usize;let count=u16le(bytes,56)? as usize;
|
||||
if stride<56{return Err("invalid ELF program-header stride".into());}let mut loads=0;
|
||||
for i in 0..count{let at=start.checked_add(i.checked_mul(stride).ok_or("ELF offset overflow")?).ok_or("ELF offset overflow")?;if u32le(bytes,at)?!=1{continue;}loads+=1;
|
||||
let offset=u64le(bytes,at+8)?;let address=u64le(bytes,at+16)?;let align=u64le(bytes,at+48)?;
|
||||
if align<16384||!align.is_power_of_two()||offset%16384!=address%16384{return Err("ARM64 ELF PT_LOAD is not 16-KiB page compatible".into());}}
|
||||
if loads==0{return Err("ELF has no loadable segments".into());}Ok(())
|
||||
}
|
||||
fn files(root:&Path,result:&mut Vec<PathBuf>)->Result<(),String>{
|
||||
let boundary=fs::canonicalize(root).map_err(|e|e.to_string())?;
|
||||
fn visit(root:&Path,boundary:&Path,result:&mut Vec<PathBuf>)->Result<(),String>{
|
||||
for entry in fs::read_dir(root).map_err(|e|e.to_string())?{
|
||||
let entry=entry.map_err(|e|e.to_string())?;let ty=entry.file_type().map_err(|e|e.to_string())?;
|
||||
if ty.is_symlink(){
|
||||
let resolved=fs::canonicalize(entry.path()).map_err(|e|e.to_string())?;
|
||||
if !resolved.starts_with(boundary){return Err(format!("payload symlink leaves package: {}",entry.path().display()));}
|
||||
continue;
|
||||
}
|
||||
if ty.is_dir(){visit(&entry.path(),boundary,result)?;}else{result.push(entry.path());}
|
||||
}Ok(())
|
||||
}
|
||||
visit(root,&boundary,result)
|
||||
}
|
||||
fn python(root:&Path)->Command{let mut cmd=Command::new(if cfg!(windows){"python"}else{"python3"});cmd.arg(root.join("native/packaging/archive.py"));cmd}
|
||||
fn unpack(root:&Path,path:&Path,kind:&str,destination:&Path)->Result<(),String>{
|
||||
package::mkdir(destination)?;
|
||||
match kind{
|
||||
"zip"|"tar.gz"|"apk"|"aab"|"ipa"=>run(python(root).arg("extract").arg(path).arg(destination)),
|
||||
"nsis"=>{
|
||||
// 7-Zip lists and extracts NSIS without executing the installer. Its own
|
||||
// 32-bit bootstrap is not the application ISA and is checked separately.
|
||||
let listing=capture(Command::new("7z").args(["l","-slt"]).arg(path))?;
|
||||
for line in listing.lines().filter_map(|l|l.strip_prefix("Path = ")).skip(1){safe_member(line)?;}
|
||||
run(Command::new("7z").arg("x").arg("-y").arg(format!("-o{}",destination.display())).arg(path))
|
||||
}
|
||||
"appimage"=>{
|
||||
// Never execute a foreign AppImage to discover its SquashFS offset.
|
||||
let bytes=fs::read(path).map_err(|e|e.to_string())?;
|
||||
let offset=bytes.windows(4).enumerate().filter(|(_,b)|*b==b"hsqs").find_map(|(i,_)|{
|
||||
let major=u16le(&bytes,i+28).ok()?;let used=u64le(&bytes,i+40).ok()?;
|
||||
if major==4&&used>=96&&(i as u64).checked_add(used)?<=bytes.len() as u64{Some(i)}else{None}
|
||||
}).ok_or("AppImage contains no valid SquashFS superblock")?;
|
||||
run(Command::new("unsquashfs").args(["-no-progress","-no-xattrs","-o"]).arg(offset.to_string()).arg("-d").arg(destination).arg(path))
|
||||
}
|
||||
"dmg"=>{
|
||||
let mount=destination.join("mounted");package::mkdir(&mount)?;
|
||||
run(Command::new("hdiutil").args(["attach","-readonly","-nobrowse","-mountpoint"]).arg(&mount).arg(path))?;
|
||||
let copied=package::copy_tree(&mount,&destination.join("payload"));
|
||||
let detached=run(Command::new("hdiutil").arg("detach").arg(&mount));copied?;detached
|
||||
}
|
||||
_=>Err(format!("cannot unpack kind {kind}"))
|
||||
}
|
||||
}
|
||||
fn safe_member(name:&str)->Result<(),String>{
|
||||
if name.starts_with(['/', '\\'])||name.contains(':')||name.replace('\\',"/").split('/').any(|s|s==".."){return Err(format!("archive member escapes payload: {name}"));}Ok(())
|
||||
}
|
||||
fn forbidden(path:&Path)->bool{
|
||||
let name=path.file_name().unwrap_or_default().to_string_lossy().to_ascii_lowercase();
|
||||
matches!(name.as_str(),"electron"|"electron.exe"|"node"|"node.exe"|"node.dll"|"app.asar"|"chrome-sandbox"|"chrome_100_percent.pak"|"chrome_200_percent.pak"|"resources.pak"|"snapshot_blob.bin"|"v8_context_snapshot.bin"|"libcef.dll"|"libcef.so"|"msedgewebview2.exe"|"webview2loader.dll")||[".wasm",".js",".mjs",".cjs",".html"].iter().any(|suffix|name.ends_with(*suffix))||path.components().any(|c|matches!(c.as_os_str().to_string_lossy().to_ascii_lowercase().as_str(),"node_modules"|"electron.framework"|"chromium.framework"|"webview.framework"))
|
||||
}
|
||||
fn dynamic(path:&Path,target:Target<'_>,all:&[PathBuf])->Result<String,String>{
|
||||
let output=match target.os{
|
||||
"win"=>capture(Command::new("llvm-readobj").arg("--coff-imports").arg(path))?,
|
||||
"linux"|"android"=>capture(Command::new("llvm-readelf").args(["-d","--version-info"]).arg(path))?,
|
||||
_=>capture(Command::new("otool").arg("-L").arg(path))?
|
||||
};
|
||||
let bundled:BTreeSet<String>=all.iter().filter_map(|p|p.file_name()).map(|s|s.to_string_lossy().to_ascii_lowercase()).collect();
|
||||
for line in output.lines(){
|
||||
let dependency=if matches!(target.os,"linux"|"android"){
|
||||
if !line.contains("(NEEDED)"){None}else{line.split('[').nth(1).and_then(|s|s.split(']').next())}
|
||||
}else if target.os=="win"{line.trim().strip_prefix("Name: ")}else if line.starts_with('\t'){line.trim().split(" (compatibility").next()}else{None};
|
||||
if let Some(dep)=dependency{
|
||||
let name=Path::new(dep).file_name().unwrap_or_default().to_string_lossy().to_ascii_lowercase();
|
||||
if name.contains("webview")||name.contains("electron")||name=="libnode.so"||name=="webkit"||name=="javascriptcore"{return Err(format!("browser dependency {dep}"));}
|
||||
let system=match target.os{
|
||||
"win"=>name.starts_with("api-ms-win-")||name.starts_with("ext-ms-win-")||WINDOWS_SYSTEM.contains(&name.as_str()),
|
||||
"android"=>["libc.so","libm.so","libdl.so","liblog.so","libandroid.so","libaaudio.so","libmediandk.so","libcamera2ndk.so","libegl.so","libglesv2.so","libglesv3.so","libvulkan.so","libz.so","libjnigraphics.so","libopensles.so"].contains(&name.as_str()),
|
||||
"linux"=>LINUX_SYSTEM.contains(&name.as_str()),
|
||||
_=>dep.starts_with("/System/Library/")||dep.starts_with("/usr/lib/")
|
||||
};
|
||||
if !system&&!bundled.contains(&name){return Err(format!("unbundled non-system dependency {dep} in {}",path.display()));}
|
||||
}
|
||||
if target.os=="linux"{for word in line.split(|c:char|!(c.is_ascii_alphanumeric()||c=='.'||c=='_')){if let Some(v)=word.strip_prefix("GLIBC_"){let mut parts=v.split('.');let major=parts.next().and_then(|s|s.parse::<u32>().ok());let minor=parts.next().and_then(|s|s.parse::<u32>().ok());if major.zip(minor).is_some_and(|v|v>(2,34)){return Err(format!("{} requires {word}, exceeds glibc 2.34 minimum",path.display()));}}}}
|
||||
}Ok(output)
|
||||
}
|
||||
const WINDOWS_SYSTEM:&[&str]=&["kernel32.dll","user32.dll","gdi32.dll","advapi32.dll","shell32.dll","ole32.dll","oleaut32.dll","uuid.dll","ws2_32.dll","bcrypt.dll","bcryptprimitives.dll","uiautomationcore.dll","combase.dll","msdmo.dll","crypt32.dll","ntdll.dll","secur32.dll","shlwapi.dll","comdlg32.dll","comctl32.dll","winmm.dll","version.dll","dwmapi.dll","d3d11.dll","d3d12.dll","dxgi.dll","dxguid.dll","dwrite.dll","d2d1.dll","mf.dll","mfplat.dll","mfreadwrite.dll","mfuuid.dll","propsys.dll","avrt.dll","mmdevapi.dll","setupapi.dll","cfgmgr32.dll","powrprof.dll","iphlpapi.dll","winhttp.dll","wininet.dll","wtsapi32.dll","userenv.dll","uxtheme.dll","hid.dll","imm32.dll","opengl32.dll","msimg32.dll","dcomp.dll","d3dcompiler_47.dll","normaliz.dll","rpcrt4.dll","windowsapp.dll","runtimeobject.dll","urlmon.dll"];
|
||||
const LINUX_SYSTEM:&[&str]=&["libc.so.6","libm.so.6","libdl.so.2","libpthread.so.0","librt.so.1","libresolv.so.2","ld-linux-x86-64.so.2","ld-linux-aarch64.so.1","libgcc_s.so.1","libstdc++.so.6","libgl.so.1","libegl.so.1","libglx.so.0","libglx_mesa.so.0","libopengl.so.0","libvulkan.so.1","libdrm.so.2","libgbm.so.1"];
|
||||
fn payload(root:&Path,directory:&Path,target:Target<'_>,nsis:bool)->Result<Value,String>{
|
||||
let mut all=Vec::new();files(directory,&mut all)?;
|
||||
let mut binaries=Vec::new();let mut application=false;let mut helper=false;
|
||||
for path in &all{
|
||||
if forbidden(path){return Err(format!("browser/Node/WASM payload refused: {}",path.display()));}
|
||||
let mut bytes=[0u8;4];let mut file=fs::File::open(path).map_err(|e|e.to_string())?;let count=file.read(&mut bytes).map_err(|e|e.to_string())?;if count<4{continue;}
|
||||
if bytes.starts_with(b"MZ")||bytes.starts_with(b"\x7fELF")||bytes.starts_with(&[0xcf,0xfa,0xed,0xfe]){
|
||||
// NSIS itself remains x86 even when its installed application is x64/ARM64.
|
||||
// Accept only its exact extracted bootstrap locations, never arbitrary x86 payloads.
|
||||
let bootstrap=nsis&&(path==&directory.join("Uninstall.exe")||path==&directory.join("$PLUGINSDIR/System.dll"));
|
||||
if bootstrap{
|
||||
let header=binary_header(path)?;let pe=u32le(&header,0x3c)? as usize;
|
||||
if header.get(pe..pe+4)!=Some(b"PE\0\0")||u16le(&header,pe+4)?!=0x14c{return Err("invalid NSIS x86 bootstrap".into());}
|
||||
let dependencies=dynamic(path,target,&all)?;
|
||||
binaries.push(json!({"path":path.strip_prefix(directory).unwrap_or(path),"role":"nsis-bootstrap","machine":"x86","dependencies":dependencies,"sha512":package::sha512(path)?}));
|
||||
continue;
|
||||
}
|
||||
verify_isa(path,target)?;let deps=dynamic(path,target,&all)?;
|
||||
let name=path.file_name().unwrap_or_default().to_string_lossy();
|
||||
application|=matches!(name.as_ref(),"teamspeach"|"teamspeach.exe"|"libteamspeach_native.so"|"TeamsPeach");
|
||||
helper|=matches!(name.as_ref(),"teamspeach-update-helper"|"teamspeach-update-helper.exe");
|
||||
if target.os=="android"&&name=="libteamspeach_native.so"{
|
||||
let symbols=capture(Command::new("llvm-nm").args(["-D","--defined-only"]).arg(path))?;
|
||||
if !symbols.contains("Java_livekit_org_webrtc_"){return Err("missing matching prefixed WebRTC JNI symbols".into());}
|
||||
}
|
||||
binaries.push(json!({"path":path.strip_prefix(directory).unwrap_or(path),"dependencies":deps,"sha512":package::sha512(path)?}));
|
||||
}
|
||||
}
|
||||
if !application{return Err("package lacks actual native application binary".into());}
|
||||
if matches!(target.os,"win"|"linux")&&!helper{return Err("package lacks external update helper".into());}
|
||||
if matches!(target.os,"win"|"linux"|"android"){
|
||||
let receipts:Vec<_>=all.iter().filter(|p|p.to_string_lossy().replace('\\',"/").ends_with("resources/native-build.json")).collect();
|
||||
if receipts.len()!=1{return Err("package requires one native build receipt".into());}
|
||||
let receipt=package::json_file(receipts[0])?;
|
||||
if receipt["schema"]!=1||receipt["engine"]!="rust-slint"||receipt["version"]!=package::version(root)?||receipt["target"]!=target.triple{return Err("packaged build receipt identity mismatch".into());}
|
||||
for entry in receipt["binaries"].as_array().ok_or("packaged build receipt lacks binaries")?{
|
||||
let name=entry["name"].as_str().ok_or("packaged binary name missing")?;
|
||||
let matches:Vec<_>=all.iter().filter(|p|p.file_name().and_then(|s|s.to_str())==Some(name)).collect();
|
||||
if matches.len()!=1||entry["packagedSha256"]!=deps::sha256(matches[0])?{return Err(format!("packaged binary/version receipt hash mismatch for {name}"));}
|
||||
}
|
||||
}else{
|
||||
let plists:Vec<_>=all.iter().filter(|p|{
|
||||
p.file_name().is_some_and(|s|s=="Info.plist")
|
||||
&& p.parent().is_some_and(|parent|parent.file_name().is_some_and(|s|s=="Contents"||s=="TeamsPeach.app"))
|
||||
}).collect();
|
||||
if plists.is_empty(){return Err("Apple package lacks application Info.plist".into());}
|
||||
for plist in plists{let actual=capture(Command::new("plutil").args(["-extract","CFBundleShortVersionString","raw","-o","-"]).arg(plist))?;if actual.trim()!=package::version(root)?{return Err("Apple bundle version mismatches native release".into());}}
|
||||
}
|
||||
for suffix in ["resources/fonts/NotoSans-VF.ttf","resources/fonts/NotoSans-Italic-VF.ttf","resources/i18n/en.json","resources/i18n/ru.json","resources/licenses/Slint-License-2.0.txt","licenses/NotoSans-OFL.txt"]{
|
||||
let source=if suffix.starts_with("resources/"){root.join("native").join(suffix)}else{root.join("LICENSES").join(suffix.trim_start_matches("licenses/"))};
|
||||
let matches:Vec<_>=all.iter().filter(|p|{let path=p.to_string_lossy().replace('\\',"/");path.ends_with(suffix)||(target.os=="ios"&&suffix.starts_with("licenses/")&&path.ends_with(&suffix.replacen("licenses/","LICENSES/",1)))}).collect();
|
||||
if matches.is_empty(){return Err(format!("package lacks required asset/license {suffix}"));}
|
||||
for path in matches{if package::sha512(path)?!=package::sha512(&source)?{return Err(format!("packaged asset differs from source: {suffix}"));}}
|
||||
}
|
||||
let notices:Vec<_>=all.iter().filter(|p|p.file_name().is_some_and(|s|s=="WebRTC-THIRD-PARTY-NOTICES.txt")).collect();
|
||||
if notices.len()!=1||package::sha512(notices[0])?!=package::sha512(&deps::cache(root,target).join("webrtc/LICENSE.md"))?{return Err("missing or mismatched pinned native codec notices".into());}
|
||||
if target.os=="android"{
|
||||
let mut classes=String::new();for path in all.iter().filter(|p|p.extension().is_some_and(|s|s=="dex")){classes.push_str(&capture(Command::new("dexdump").arg(path))?);}
|
||||
if !classes.contains("Llivekit/org/webrtc/ContextUtils;"){return Err("APK/AAB lacks matching prefixed WebRTC Java classes".into());}
|
||||
if classes.contains("Landroid/webkit/WebView;"){return Err("Android payload references browser WebView".into());}
|
||||
}
|
||||
Ok(json!({"binaries":binaries,"files":all.len()}))
|
||||
}
|
||||
pub(crate) fn verify(root:&Path,options:&Options)->Result<(),String>{
|
||||
let target=Target::parse(&options.target)?;target.check_host()?;let version=package::version(root)?;let out=package::output_dir(root,options);let work=out.join(target.triple);
|
||||
let report=package::json_file(&work.join("package-report.json"))?;
|
||||
if report["schema"]!=1||report["engine"]!="rust-slint"||report["target"]!=target.triple||report["version"]!=version{return Err("package report identity mismatch".into());}
|
||||
if report["sourceBuild"]["schema"]!=1||report["sourceBuild"]["engine"]!="rust-slint"||report["sourceBuild"]["version"]!=version||report["sourceBuild"]["target"]!=target.triple||report["sourceBuild"]["testHarness"]!=report["testOnly"]{return Err("package source-build provenance mismatch".into());}
|
||||
let mut results=Vec::new();let mut kinds=BTreeSet::new();
|
||||
for (index,entry) in report["artifacts"].as_array().ok_or("missing package artifacts")?.iter().enumerate(){
|
||||
let kind=entry["kind"].as_str().ok_or("missing artifact kind")?;if !kinds.insert(kind.to_owned()){return Err("duplicate package kind".into());}
|
||||
if matches!(kind,"xcarchive"|"simulator.app"){
|
||||
let path=PathBuf::from(entry["path"].as_str().ok_or("missing bundle path")?);
|
||||
if !path.starts_with(&work){return Err("bundle path leaves package output".into());}
|
||||
let bundle=if kind=="xcarchive"{path.join("Products/Applications/TeamsPeach.app")}else{path};
|
||||
if entry["signing"]=="apple-provisioned"{run(Command::new("codesign").args(["--verify","--deep","--strict"]).arg(&bundle))?;}
|
||||
results.push(payload(root,&bundle,target,false)?);continue;
|
||||
}
|
||||
let name=entry["name"].as_str().ok_or("missing asset name")?;safe_member(name)?;if name.contains(['/', '\\']){return Err("asset name is not a basename".into());}
|
||||
let path=out.join(name);let measured=package::record(&path,target,kind)?;
|
||||
for key in ["target","kind","name","size","sha512"]{if entry[key]!=measured[key]{return Err(format!("artifact {name} mismatches {key}"));}}
|
||||
if kind=="appimage"{verify_isa(&path,target)?;}
|
||||
if kind=="apk"{
|
||||
run(Command::new("zipalign").args(["-c","-P","16","-v","4"]).arg(&path))?;
|
||||
let badging=capture(Command::new("aapt2").args(["dump","badging"]).arg(&path))?;
|
||||
if !badging.lines().any(|line|line.starts_with("package:")&&line.contains("name='dev.teamspeach.mobile'")&&line.contains(&format!("versionName='{version}'"))){return Err("APK application identity/version mismatch".into());}
|
||||
}
|
||||
if kind=="aab"{
|
||||
let bundletool=std::env::var_os("TEAMSPEACH_BUNDLETOOL").map(PathBuf::from).ok_or("AAB verification requires explicit TEAMSPEACH_BUNDLETOOL path to installed bundletool.jar (no downloads)")?;
|
||||
deps::require_file(&bundletool)?;
|
||||
let xml=capture(Command::new("java").arg("-jar").arg(bundletool).args(["dump","manifest"]).arg(format!("--bundle={}",path.display())))?;
|
||||
let manifest=work.join(format!("verified-{index}-android-manifest.xml"));fs::write(&manifest,xml).map_err(|e|e.to_string())?;
|
||||
run(python(root).arg("android-manifest").arg(&manifest).arg(&version))?;
|
||||
}
|
||||
match entry["signing"].as_str(){
|
||||
Some("authenticode")=>run(Command::new("signtool").args(["verify","/pa"]).arg(&path))?,
|
||||
Some("android-keystore"|"android-debug-test") if kind=="apk"=>{run(Command::new("apksigner").args(["verify","--verbose","--print-certs"]).arg(&path))?;},
|
||||
Some("android-keystore") if kind=="aab"=>{let text=capture(Command::new("jarsigner").args(["-verify","-verbose","-certs"]).arg(&path))?;if !text.contains("jar verified.")||text.contains("jar is unsigned"){return Err("AAB JAR signing verification failed".into());}},
|
||||
_=>{}
|
||||
}
|
||||
let extracted=work.join(format!("verified-{index}"));if extracted.exists(){fs::remove_dir_all(&extracted).map_err(|e|e.to_string())?;}
|
||||
unpack(root,&path,kind,&extracted)?;
|
||||
if matches!(entry["signing"].as_str(),Some("authenticode"|"authenticode-payload")){
|
||||
let mut paths=Vec::new();files(&extracted,&mut paths)?;
|
||||
for path in paths.iter().filter(|p|matches!(p.file_name().and_then(|s|s.to_str()),Some("teamspeach.exe"|"teamspeach-update-helper.exe"))){run(Command::new("signtool").args(["verify","/pa"]).arg(path))?;}
|
||||
}
|
||||
if matches!(entry["signing"].as_str(),Some("developer-id"|"ad-hoc-local"|"apple-provisioned")){
|
||||
let mut paths=Vec::new();find_apps(&extracted,&mut paths)?;if paths.is_empty(){return Err("Apple package lacks app bundle".into());}
|
||||
for app in paths{run(Command::new("codesign").args(["--verify","--deep","--strict"]).arg(app))?;}
|
||||
}
|
||||
results.push(json!({"artifact":name,"signing":entry["signing"],"payload":payload(root,&extracted,target,kind=="nsis")?}));
|
||||
}
|
||||
let required:&[&str]=match target.os{"win"=>&["nsis","zip"],"linux"=>&["appimage","tar.gz"],"mac"=>&["dmg","zip"],"android" if target.cpu=="arm64"&&report["testOnly"]!=true=>&["apk","aab"],"android"=>&["apk"],"ios" if target.simulator=>&["simulator.app"],"ios"=>&["xcarchive"],_=>unreachable!()};
|
||||
for kind in required{if !kinds.contains(*kind){return Err(format!("missing required package kind {kind}"));}}
|
||||
// When a manifest exists, verify the complete metadata and all committed hashes.
|
||||
let manifest=out.join("native-manifest.json");if manifest.is_file(){
|
||||
let checked=package::merge_manifest(package::json_file(&manifest)?,&version,&[])?;
|
||||
for entry in checked["artifacts"].as_array().unwrap(){let path=out.join(entry["name"].as_str().unwrap());if fs::metadata(&path).map_err(|e|e.to_string())?.len()!=entry["size"].as_u64().unwrap()||package::sha512(&path)?!=entry["sha512"].as_str().unwrap(){return Err("committed manifest artifact hash/size mismatch".into());}}
|
||||
verify_yaml(&out,&version,&checked)?;
|
||||
}
|
||||
package::save(&work.join("verification.json"),&json!({"schema":1,"engine":"rust-slint","target":target.triple,"version":version,"passed":true,"publication_authorized":false,"artifacts":results}))?;
|
||||
println!("Verified local package bytes: {}",work.join("verification.json").display());Ok(())
|
||||
}
|
||||
fn find_apps(root:&Path,apps:&mut Vec<PathBuf>)->Result<(),String>{for entry in fs::read_dir(root).map_err(|e|e.to_string())?{let p=entry.map_err(|e|e.to_string())?.path();if p.is_dir(){if p.extension().is_some_and(|s|s=="app"){apps.push(p);}else{find_apps(&p,apps)?;}}}Ok(())}
|
||||
fn verify_yaml(out:&Path,version:&str,manifest:&Value)->Result<(),String>{
|
||||
let channel=if version.contains('-'){"preview"}else{"latest"};
|
||||
for(target,kind,suffix)in[("x86_64-pc-windows-msvc","nsis",""),("x86_64-unknown-linux-gnu","appimage","-linux"),("aarch64-unknown-linux-gnu","appimage","-linux-arm64")]{
|
||||
if let Some(entry)=manifest["artifacts"].as_array().unwrap().iter().find(|e|e["target"]==target&&e["kind"]==kind){
|
||||
let text=deps::read_text(&out.join(format!("{channel}{suffix}.yml")))?;
|
||||
// Accept only the canonical emitted legacy YAML: disallows added files,
|
||||
// duplicate keys, alternate architectures and semantic parser ambiguity.
|
||||
let expected=format!("version: {}\nfiles:\n - url: {}\n sha512: {}\n size: {}\npath: {}\nsha512: {}\n",json!(version),entry["name"],entry["sha512"],entry["size"],entry["name"],entry["sha512"]);
|
||||
if text!=expected{return Err(format!("manifest/YAML mismatch for {target}"));}
|
||||
}
|
||||
}Ok(())
|
||||
}
|
||||
#[cfg(test)]mod tests{
|
||||
use super::*;
|
||||
#[test]fn isa_checks_bytes_not_filename(){let mut pe=vec![0u8;256];pe[..2].copy_from_slice(b"MZ");pe[0x3c..0x40].copy_from_slice(&128u32.to_le_bytes());pe[128..132].copy_from_slice(b"PE\0\0");pe[132..134].copy_from_slice(&0xaa64u16.to_le_bytes());assert_eq!(machine(&pe).unwrap(),("pe","arm64"));pe.truncate(130);assert!(machine(&pe).is_err());}
|
||||
#[test]fn reject_archive_escape(){for path in ["../key","a/../../key","C:\\key","/etc/passwd","a\\..\\key"]{assert!(safe_member(path).is_err());}assert!(safe_member("resources/fonts/font.ttf").is_ok());}
|
||||
#[test]fn arm64_rejects_small_load_alignment(){let mut elf=vec![0u8;120];elf[32..40].copy_from_slice(&64u64.to_le_bytes());elf[54..56].copy_from_slice(&56u16.to_le_bytes());elf[56..58].copy_from_slice(&1u16.to_le_bytes());elf[64..68].copy_from_slice(&1u32.to_le_bytes());elf[112..120].copy_from_slice(&4096u64.to_le_bytes());assert!(verify_elf_pages(&elf).is_err());elf[112..120].copy_from_slice(&16384u64.to_le_bytes());assert!(verify_elf_pages(&elf).is_ok());}
|
||||
}
|
||||
Reference in new issue
Block a user