Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
vendor/
/vendor/
composer.lock
.phpunit.result.cache
/native/build/
Expand Down
14 changes: 14 additions & 0 deletions native/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion native/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ license = "MIT"
publish = false
build = "build.rs"

# no dependencies: the decoder is the vendored zstd/ (see build.rs), everything else is std
[dependencies]
# the zstd decoder, without unsafe code (its simd feature would bring in a crate with some, for no measurable gain
# here). Pinned exactly and vendored, as the Linux build runs offline: review the changes when updating with
# `RUSTC_BOOTSTRAP=1 cargo vendor vendor`
zrip-decode = { version = "=0.8.22", default-features = false, features = ["std"] }

[patch.crates-io]
zrip-core = { path = "vendor/zrip-core" }
zrip-decode = { path = "vendor/zrip-decode" }

[profile.release]
opt-level = 3
Expand Down
2 changes: 1 addition & 1 deletion native/build-linux.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ docker run --rm --network none -v "$PWD:/src:ro" -v "$PWD/build:/out" -e OWNER="
version() { apk --no-network info -v 2>/dev/null | sed -n "s/^$1-\([0-9].*\)/\1/p"; }
arch=$(uname -m)
mkdir /tmp/native
cp -r /src/.cargo /src/static-pie-cc /src/Cargo.toml /src/Cargo.lock /src/rust-toolchain.toml /src/build.rs /src/src /src/zstd /tmp/native/
cp -r /src/.cargo /src/static-pie-cc /src/Cargo.toml /src/Cargo.lock /src/rust-toolchain.toml /src/build.rs /src/src /src/vendor /tmp/native/
cd /tmp/native
EXTRACT_LIBC="musl $(version musl)" RUSTC_BOOTSTRAP=1 cargo build -q --release --locked --offline --target "$arch-unknown-linux-musl"
echo "#include <string.h>" | gcc -O2 -D_FORTIFY_SOURCE=2 -E - | grep -q /fortify/string.h # fortify is really on
Expand Down
129 changes: 10 additions & 119 deletions native/build.rs
Original file line number Diff line number Diff line change
@@ -1,129 +1,20 @@
//! Compiles the vendored zstd decoder (zstd/, see update-zstd.sh) and links its objects into the binary.
//! No build dependencies: the compiler is called directly, with the same flags as the C build had.
//! Records the rustc and zrip-decode versions for --version.

use std::env;
use std::path::PathBuf;
use std::process::Command;

const DEFINES: &[&str] = &[
"ZSTD_LEGACY_SUPPORT=0",
"ZSTD_MULTITHREAD=0",
"XXH_NAMESPACE=ZSTD_",
"ZSTD_NO_TRACE",
"DEBUGLEVEL=0",
];

fn sources() -> Vec<PathBuf> {
let mut srcs = Vec::new();
for dir in ["zstd/common", "zstd/decompress"] {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.extension().is_some_and(|x| x == "c" || x == "S") {
srcs.push(p);
}
}
}
srcs.sort(); // link order is part of the output
srcs
}

fn run(cmd: &mut Command) {
let status = cmd
.status()
.unwrap_or_else(|e| panic!("cannot run {cmd:?}: {e}"));
assert!(status.success(), "{cmd:?} failed");
}

fn main() {
println!("cargo:rerun-if-changed=zstd");
println!("cargo:rerun-if-env-changed=CC");
println!("cargo:rerun-if-changed=Cargo.lock");
println!("cargo:rerun-if-env-changed=EXTRACT_LIBC");
let target = env::var("TARGET").unwrap();
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let msvc = target.ends_with("-msvc");

let mut objs = Vec::new();
for src in sources() {
let asm = src.extension().unwrap() == "S";
if asm && msvc {
continue; // MSVC builds use ZSTD_DISABLE_ASM
}
let obj = out
.join(src.file_name().unwrap())
.with_extension(if msvc { "obj" } else { "o" });
let mut cc = if msvc {
Command::new("cl")
} else {
Command::new(env::var("CC").unwrap_or_else(|_| "cc".into()))
};
if msvc {
cc.args([
"/nologo",
"/c",
"/O2",
"/MT",
"/W3",
"/GS",
"/guard:cf",
"/utf-8",
"/Brepro",
"/Izstd",
"/DZSTD_DISABLE_ASM",
]);
cc.args(DEFINES.iter().map(|d| format!("/D{d}")));
cc.arg(format!("/Fo{}", obj.display()));
} else {
cc.args([
"-c",
"-O2",
"-std=c99",
"-Wall",
"-Wextra",
"-Izstd",
"-ffunction-sections",
"-fdata-sections",
]);
cc.args([
"-fstack-protector-strong",
"-U_FORTIFY_SOURCE",
"-D_FORTIFY_SOURCE=2",
"-fPIE",
]);
cc.args(DEFINES.iter().map(|d| format!("-D{d}")));
if target.contains("apple") {
let arch = if target.starts_with("aarch64") {
"arm64"
} else {
"x86_64"
};
cc.args(["-arch", arch, "-mmacosx-version-min=11.0"]);
}
cc.arg("-o").arg(&obj);
}
cc.arg(&src);
run(&mut cc);
objs.push(obj);
}
// a static library, so it is linked before the system libraries it needs
let lib = out.join(if msvc { "zstd.lib" } else { "libzstd.a" });
let _ = std::fs::remove_file(&lib);
let mut ar = if msvc {
let mut c = Command::new("lib");
c.args(["/nologo", "/Brepro"])
.arg(format!("/OUT:{}", lib.display()));
c
} else if target.contains("apple") {
let mut c = Command::new("libtool");
c.args(["-static", "-D", "-o"]).arg(&lib); // -D: no timestamps or uids
c
} else {
let mut c = Command::new(env::var("AR").unwrap_or_else(|_| "ar".into()));
c.arg("crsD").arg(&lib); // D: no timestamps or uids
c
};
run(ar.args(&objs));
println!("cargo:rustc-link-search=native={}", out.display());
println!("cargo:rustc-link-lib=static=zstd");
let lock = std::fs::read_to_string("Cargo.lock").unwrap();
let zrip = lock
.split("[[package]]")
.find(|p| p.contains("name = \"zrip-decode\""))
.and_then(|p| p.lines().find_map(|l| l.strip_prefix("version = \"")))
.and_then(|v| v.strip_suffix('"'))
.expect("zrip-decode in Cargo.lock");
println!("cargo:rustc-env=EXTRACT_ZRIP={zrip}");

let rustc = env::var("RUSTC").unwrap();
let v = Command::new(rustc)
Expand Down
24 changes: 9 additions & 15 deletions native/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ mod sys;
mod zstd;

const EXTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
const WINDOW_LOG_MAX: i32 = 27;
const WINDOW_LOG_MAX: u32 = 27;
const MAX_REL: usize = 4096;
/* every component costs a lookup in each filesystem call on the path */
const MAX_DEPTH: usize = 128;
Expand Down Expand Up @@ -120,7 +120,6 @@ struct Reader {
input: Vec<u8>,
in_pos: usize,
in_len: usize,
last_ret: usize,
out: Vec<u8>,
out_len: usize,
pos: usize,
Expand All @@ -130,17 +129,13 @@ struct Reader {

impl Reader {
fn new(f: File, max_size: u64) -> Reader {
let ds =
zstd::Stream::new(WINDOW_LOG_MAX).unwrap_or_else(|| fail(EXIT_IO, "out of memory"));
let (in_size, out_size) = (zstd::in_size(), zstd::out_size());
Reader {
f,
ds,
input: vec![0; in_size],
ds: zstd::Stream::new(WINDOW_LOG_MAX),
input: vec![0; zstd::IN_SIZE],
in_pos: 0,
in_len: 0,
last_ret: 0,
out: vec![0; out_size],
out: vec![0; zstd::OUT_SIZE],
out_len: 0,
pos: 0,
total: 0,
Expand All @@ -153,22 +148,21 @@ impl Reader {
self.pos = 0;
self.out_len = 0;
while self.out_len == 0 {
if self.in_pos == self.in_len {
if self.in_pos == self.in_len && !self.ds.has_pending_output() {
let n = read_some(&mut self.f, &mut self.input);
if n == 0 {
if self.last_ret != 0 {
if self.ds.finish().is_err() {
fail(EXIT_INVALID, "truncated zstd stream");
}
return false;
}
self.in_pos = 0;
self.in_len = n;
}
let (n, ret) = self
let n = self
.ds
.decompress(&self.input[..self.in_len], &mut self.in_pos, &mut self.out)
.unwrap_or_else(|e| fail(EXIT_INVALID, format!("zstd: {e}")));
self.last_ret = ret;
self.out_len = n;
self.total += n as u64;
if self.total > self.max_size {
Expand Down Expand Up @@ -855,9 +849,9 @@ fn main() {
.map(|l| format!(", {l}"))
.unwrap_or_default();
println!(
"zstd-extract {} (zstd {}, rustc {}{})",
"zstd-extract {} (zrip-decode {}, rustc {}{})",
EXTRACT_VERSION,
zstd::version(),
zstd::VERSION,
env!("EXTRACT_RUSTC"),
libc
);
Expand Down
Loading
Loading