stuffr_cli/compat/zstd/mod.rs
1//! The zstd family (`zstd`, `unzstd`, `zstdcat`, `zstdmt`): stuffr
2//! behaving as zstd 1.5.7's command line tool.
3//!
4//! Ported from zstd 1.5.7 `programs/` by Yann Collet and the zstd
5//! contributors (Meta Platforms, Inc.; BSD-3-Clause, the licence ships as
6//! `LICENSE-zstd`), one module per C file: `cli.rs` (zstdcli.c's argument
7//! parsing, help texts and parameter printers), `dibio.rs` (dibio.c,
8//! `--train*`), `util.rs` (util.c),
9//! `display.rs` (fileio_common.h's display macros) and this module
10//! (zstdcli.c's `main` after the arguments). Every string is in
11//! `messages.rs`. libzstd itself is reached through
12//! `stuffr::zstd_opts`.
13//!
14//! **Names** (spec section 1): the four map to this family, and the
15//! presets come from the invoked name by zstdcli.c's `exeNameMatch` (the
16//! name, then the end or a `.`): `unzstd` decompresses, `zstdcat`
17//! decompresses to standard output with pass-through at display level 1,
18//! `zstdmt` compresses with `-T0`. zstdcli.c's gzip, xz, lzma and lz4
19//! presets are ported too, though dispatch never reaches them (those names
20//! belong to other families).
21//!
22//! **The machine** (R3): the real process counts its cores as util.c does
23//! (`host::cores`, shared with the lz4 family since 0.15.0); a sandboxed run ([`run_in_counted`]) sees 8
24//! logical and 4 physical cores.
25//!
26//! Known deviations (the source of truth; the README and the spec mirror
27//! this list):
28//!
29//! 1. The banner names stuffr wherever zstd prints `WELCOME_MESSAGE`
30//! (`-V`, `-vV`, `-vvV`, the first line of `-H`, and `-v`'s welcome
31//! line on standard error): `*** Zstandard CLI (stuffr X.Y.Z; zstd
32//! 1.5.7 compatible) (64-bit) v1.5.7, by Yann Collet ***`. `-qV` prints
33//! exactly `1.5.7`, and `-vV`'s "supports:" line is zstd's. `-vvV`
34//! prints zstd's POSIX lines for the platform, but not its three
35//! library-version lines (the zlib, lz4 and lzma zstd links), which
36//! describe zstd's own build.
37//! 2. The `-v` summary's timing fields vary from run to run, as they do
38//! between two runs of zstd.
39//! 3. An input that is also the output is never lost.
40//! 4. Closed standard streams and a parent that ignores SIGPIPE: the Rust
41//! runtime reopens a closed standard descriptor on `/dev/null` and
42//! resets SIGPIPE before `main`, so neither is seen.
43//! 5. Out of scope, refused as a zstd built with `ZSTD_NOBENCH` and
44//! `ZSTD_NOTRACE` refuses them: `-b`, `-e#`, `-i#` ("Incorrect
45//! parameter: -b", exit 1) and `--trace` ("Incorrect parameter:
46//! --trace"); `-H` omits their lines. `-B#`, `-S` and `-p#` keep the
47//! reference's meaning. `--[no-]asyncio` is accepted and has no visible
48//! effect. `--trace-file-stat` is accepted and prints no trace.
49//! - `-l` on two malformed skippable frames (ruling T7-a): a size field
50//! of `0xFFFFFFF8` makes zstd loop forever, and stuffr answers exit 1
51//! with `could not find end of skippable frame`; a skippable frame cut
52//! after 5 to 7 bytes makes zstd read uninitialised stack, and stuffr
53//! reads a deterministic header. Neither upstream defect is
54//! reproduced.
55//! - At display level 5 and above, `EXM_THROW`'s `Error defined at
56//! <file>, line <n>` line is not printed (ruling T4-b): it names the C
57//! implementation's source lines.
58//! 6. `--train-cover` (ruling T1-a): libzstd 1.5.7's cover sort breaks ties
59//! by comparing addresses (`cover.c:300`, `:316`), so a cover dictionary
60//! depends on heap layout, in zstd itself too. It is promised valid and
61//! usable by zstd, not byte for byte. `--train`, `--train-fastcover` and
62//! `--train-legacy` write zstd's bytes. `--adapt` changes the level by
63//! timing, so its frames are compatible, not identical.
64//!
65//! Spec deviation 7, the pure tier (`zstd-pure` without `zstd-c`), as far
66//! as compressing and decompressing go (`fileio.rs`):
67//!
68//! - Every level compresses with `ruzstd`'s `Fastest`, so the sizes and
69//! ratios in the summaries and in `-vvvvvv`'s trace are the tier's own;
70//! the reference decodes every frame. The compression parameters are
71//! range-checked as libzstd checks them, then ignored: `-T`,
72//! `--auto-threads` and `zstdmt` run single-threaded, and the LDM,
73//! `--rsyncable`, block-size and overlap options have no effect.
74//! - Content size and window: our frames never record a content size, so
75//! `--content-size` has no effect and `-l` on our own output says the
76//! decompressed size is unknown. The window is 128 KiB whatever `--long`
77//! asks.
78//! - Each input is compressed as one frame built in memory: memory use
79//! grows with the input's size (a piped standard input is unbounded),
80//! and a run that exhausts memory ends outside zstd's exit codes.
81//! - Compressing with `-D` or `--patch-from` is refused, after everything
82//! zstd prints first: `zstd: error 1 : dictionary compression is not
83//! available in this build (stuffr pure tier)`. Decompressing with either
84//! works (a `--patch-from` prefix through a hand-built raw-content
85//! dictionary, Task 1's spike S1).
86//! - `--train*` answers as a zstd built with `ZSTD_NODICT`: `--train`
87//! prints `training mode not available`, exit 1, and `--train-cover`,
88//! `--train-fastcover` and `--train-legacy` are no options there
89//! (`Incorrect parameter`). `-H` still lists the dictionary builder.
90//! - `--adapt` is accepted and the level never moves (the encoder has no
91//! jobs to measure).
92//! - A legacy frame (v0.5 to v0.7) is `unsupported format`, what a zstd
93//! built without legacy support says.
94//! - A corrupt frame whose blocks overflow the output libzstd sized from
95//! its header can be named `Data corruption detected` where libzstd says
96//! `Destination buffer is too small`.
97//! - `--format=gzip|xz|lzma` write flate2's and `xz_opts`' pure encoders'
98//! bytes, which the reference decodes (compatible, not identical; the
99//! summaries' sizes are the tier's own).
100//! - A gzip member's deflate data goes through flate2 (miniz_oxide), which
101//! accepts some streams zlib refuses (a distance reaching before the
102//! output, a code with no end of block): where the reference says
103//! `inflate error -3` and writes nothing, the pure tier may write bytes
104//! and then fail (`premature gz end`), or, when the trailer's CRC and
105//! size match what miniz_oxide decoded, succeed with exit 0 and that
106//! output. With `zlib-c` it is zlib's own `inflate`.
107//! - An xz or lzma frame that fails to decode (the xz family's P6 and P9):
108//! what is written before the error can be a strict prefix of what
109//! liblzma writes, and corruption in the last bytes of a `.lzma` reads as
110//! the input ending there (`premature lzma end`, the jobs before it
111//! written) where liblzma says `lzma_code decoding error 9`.
112//!
113//! The foreign formats on both tiers (`formats.rs`; spec "Promises"):
114//! `--format=gzip` is zlib's bytes with `zlib-c`, `--format=xz|lzma`
115//! liblzma's with `xz-c`, `--format=lz4` liblz4 1.10.0's with `lz4-c`
116//! (`stuffr::lz4_opts`, plain `LZ4F` streaming: 64 KiB linked blocks, content
117//! size when known, content checksum, as fileio.c sets them; byte-identical
118//! from files, to standard output and from standard input). Without `lz4-c`
119//! the pure tier's `--format=lz4` is compatible: `lz4_flex`'s block
120//! compressor at every level, inside the same frame descriptor.
121
122use std::collections::BTreeMap;
123use std::ffi::{OsStr, OsString};
124use std::io::{self, Read, Write};
125use std::path::Path;
126use std::process::ExitCode;
127use std::sync::atomic::AtomicU64;
128use std::sync::{Arc, Mutex};
129
130use stuffr::zstd_opts::{self, CParamKey};
131
132use super::CountedRun;
133use super::host::{self, Cores, Host, SANDBOX_OUTPUT_CAP, Sandbox, reset_sigpipe};
134
135pub(crate) mod cli;
136mod dibio;
137pub(crate) mod display;
138pub(crate) mod fileio;
139mod formats;
140mod list;
141mod messages;
142pub(crate) mod util;
143
144use cli::{Command, Limits, Operation, Progress, STDINMARK, STDOUTMARK, Stop};
145use display::{Display, exm_throw};
146use messages::{self as m, printf};
147
148/// Entry point for the four names; `name` is the canonical invoked name,
149/// `argv0` the program as invoked (its last component is zstd's
150/// `programName`) and `args` the arguments after it.
151pub fn run(name: &'static str, argv0: &OsStr, args: Vec<OsString>) -> ExitCode {
152 // zstd dies of SIGPIPE writing to a closed pipe.
153 reset_sigpipe();
154 let argv0 = if argv0.is_empty() {
155 name.as_bytes()
156 } else {
157 argv0.as_encoded_bytes()
158 };
159 let env = |k: &str| std::env::var_os(k);
160 let mut err = io::stderr();
161 let code = main(
162 argv0,
163 &args,
164 &env,
165 &mut Host::Real,
166 host::cores(&Host::Real),
167 None,
168 &mut err,
169 );
170 // The process's exit status is the code's low byte, as `exit()` makes
171 // it.
172 ExitCode::from(code as u8)
173}
174
175/// [`run`] without the process: operands resolve against `dir`, standard
176/// input is `stdin` (a pipe), standard output and error are captured and
177/// returned with the exit code, neither is a terminal, `env` stands in for
178/// the environment (`ZSTD_CLEVEL`, `ZSTD_NBTHREADS`) and `SIGPIPE` is left
179/// alone. The machine is R3's fixed 8 logical and 4 physical cores.
180///
181/// R9's input-independent bounds hold whatever the arguments say: the
182/// decoder's window log is at most 24 (16 MiB; a lower `--memory` or
183/// `--long` stands), `--train*` loads at most 256 KiB of samples with at
184/// most 4 optimiser steps, and compression runs at most 2 workers; xz and
185/// lzma frames decode under a 256 MiB memory limit and compress at preset
186/// 6 at most (`formats.rs`). Standard output and output files share the [`SANDBOX_OUTPUT_CAP`]
187/// budget. No signal handler is installed. For the fuzz target; not a
188/// stable interface.
189#[doc(hidden)]
190pub fn run_in_counted(
191 dir: &Path,
192 name: &'static str,
193 args: &[OsString],
194 stdin: &[u8],
195 env: &dyn Fn(&str) -> Option<OsString>,
196) -> CountedRun {
197 let stdout = Arc::new(Mutex::new(Vec::new()));
198 let reads = Arc::new(Mutex::new(BTreeMap::new()));
199 let mut host = Host::Sandbox(Sandbox {
200 dir: dir.to_path_buf(),
201 stdin: Some(stdin.to_vec()),
202 stdout: stdout.clone(),
203 budget: Arc::new(AtomicU64::new(SANDBOX_OUTPUT_CAP)),
204 reads: reads.clone(),
205 });
206 let mut err = Vec::new();
207 let code = main(
208 name.as_bytes(),
209 args,
210 env,
211 &mut host,
212 Cores::SANDBOX,
213 Some(Limits::SANDBOX),
214 &mut err,
215 );
216 drop(host);
217 let out = std::mem::take(&mut *stdout.lock().unwrap_or_else(|p| p.into_inner()));
218 let reads = std::mem::take(&mut *reads.lock().unwrap_or_else(|p| p.into_inner()));
219 (code, out, err, reads)
220}
221
222/// zstdcli.c: main, below the process boundary. Returns the exit code.
223fn main(
224 argv0: &[u8],
225 args: &[OsString],
226 env: &dyn Fn(&str) -> Option<OsString>,
227 host: &mut Host,
228 cores: Cores,
229 limits: Option<Limits>,
230 err: &mut dyn Write,
231) -> i32 {
232 let program = String::from_utf8_lossy(cli::last_name_from_path(argv0)).into_owned();
233 let mut out = host.out_writer(None);
234 let stop = match cli::parse(&program, env, args, cores, &mut out, err) {
235 Ok(mut cmd) => {
236 cmd.limits = limits;
237 execute(&mut cmd, host, &mut out, err)
238 }
239 Err(stop) => stop,
240 };
241 let _ = out.flush();
242 if stop.clean && stop.pause {
243 wait_enter(host, err);
244 }
245 stop.code
246}
247
248/// zstdcli.c: waitEnter, for `-p`.
249fn wait_enter(host: &mut Host, err: &mut dyn Write) {
250 printf(err, m::PRESS_ENTER, &[]);
251 let mut byte = [0u8; 1];
252 let _ = host.stdin().read(&mut byte);
253}
254
255/// UTIL_isLink and UTIL_isFIFO: whether `name` is a symbolic link (lstat)
256/// that does not lead to a FIFO (stat). Never on Windows, as util.c.
257fn is_link_not_fifo(host: &Host, name: &[u8]) -> bool {
258 util::is_link(host, name) && !util::is_fifo(host, name)
259}
260
261/// UTIL_getFileSize: a regular file's size (following links), else
262/// unknown.
263fn file_size(host: &Host, name: &[u8]) -> Option<u64> {
264 Some(util::file_size(host, name)).filter(|&s| s != util::FILESIZE_UNKNOWN)
265}
266
267/// An operation's result as `main` ends it: `CLEAN_RETURN` with the
268/// result, or the `EXM_THROW` exit.
269fn finish(r: fileio::Fio<i32>, pause: bool) -> Stop {
270 match r {
271 Ok(code) => Stop {
272 code,
273 clean: true,
274 pause,
275 },
276 Err(fileio::Thrown(code)) => Stop {
277 code,
278 clean: false,
279 pause,
280 },
281 }
282}
283
284/// zstdcli.c: main, from the symbolic-link filter to the operation.
285fn execute(cmd: &mut Command, host: &mut Host, out: &mut dyn Write, err: &mut dyn Write) -> Stop {
286 let pause = cmd.main_pause;
287 let clean = |code| Stop {
288 code,
289 clean: true,
290 pause,
291 };
292 let exit = |code| Stop {
293 code,
294 clean: false,
295 pause,
296 };
297 let mut d = Display::new(cmd.display_level);
298 // g_utilDisplayLevel.
299 cmd.prefs.util_level = cmd.display_level;
300 let util_level = cmd.display_level;
301
302 if !cmd.follow_links {
303 let total = cmd.files.len();
304 let mut kept = Vec::with_capacity(total);
305 for name in std::mem::take(&mut cmd.files) {
306 if is_link_not_fifo(host, &name) {
307 d.at(2, err, m::SYMLINK_IGNORED, &[&name]);
308 } else {
309 kept.push(name);
310 }
311 }
312 cmd.files = kept;
313 if cmd.files.is_empty() && total > 0 {
314 return clean(1);
315 }
316 }
317 for list in std::mem::take(&mut cmd.filelists) {
318 match util::names_from_file(host, &list, util_level, err) {
319 Some(names) => cmd.files.extend(names),
320 None => {
321 d.at(1, err, m::ERROR_READING, &[&list]);
322 return clean(1);
323 }
324 }
325 }
326 cmd.nb_input_files = cmd.files.len();
327 if cmd.recursive {
328 let names = std::mem::take(&mut cmd.files);
329 cmd.files = util::expand_names(host, names, cmd.follow_links, util_level, err);
330 }
331
332 match cmd.op {
333 Operation::List => return clean(list::list_files(cmd, host, out, err)),
334 Operation::Train => return finish(dibio::train_files(cmd, host, err), pause),
335 Operation::Test => {
336 cmd.prefs.test_mode = true;
337 cmd.out_file = Some(cli::NULMARK.to_vec());
338 cmd.prefs.remove_src = false;
339 }
340 Operation::Compress | Operation::Decompress => {}
341 }
342
343 if cmd.files.is_empty() {
344 if cmd.nb_input_files > 0 {
345 d.at(1, err, m::NO_INPUT_LEFT, &[]);
346 return clean(0);
347 }
348 cmd.files.push(STDINMARK.to_vec());
349 }
350 if cmd.files.len() == 1 && cmd.files[0] == STDINMARK && cmd.out_file.is_none() {
351 cmd.out_file = Some(STDOUTMARK.to_vec());
352 }
353
354 let has_stdin = cmd.files.iter().any(|f| f == STDINMARK);
355 if !cmd.force_stdin && has_stdin && (cmd.prefs.fake_stdin_console || host.stdin_is_tty()) {
356 d.at(1, err, m::STDIN_CONSOLE, &[]);
357 return clean(1);
358 }
359 if cmd.out_file.as_deref().is_none_or(|o| o == STDOUTMARK)
360 && (cmd.prefs.fake_stdout_console || host.stdout_is_tty())
361 && has_stdin
362 && !cmd.force_stdout
363 && cmd.op != Operation::Decompress
364 {
365 d.at(1, err, m::STDOUT_CONSOLE, &[]);
366 return clean(1);
367 }
368
369 let max_level = if cmd.ultra {
370 zstd_opts::MAX_CLEVEL
371 } else {
372 cli::CLEVEL_MAX
373 };
374 if cmd.level > max_level {
375 d.at(
376 2,
377 err,
378 m::LEVEL_REDUCED,
379 &[max_level.to_string().as_bytes()],
380 );
381 cmd.level = max_level;
382 }
383
384 if cmd.show_default_cparams && cmd.op == Operation::Decompress {
385 d.at(1, err, m::CPARAMS_DECOMPRESS, &[]);
386 return clean(1);
387 }
388 if cmd.dict_file.is_some() && cmd.patch_from.is_some() {
389 d.at(1, err, m::DICT_AND_PATCH, &[]);
390 return clean(1);
391 }
392 if cmd.patch_from.is_some() && cmd.files.len() > 1 {
393 d.at(1, err, m::PATCH_MULTIPLE, &[]);
394 return clean(1);
395 }
396
397 let has_stdout = cmd.out_file.as_deref() == Some(STDOUTMARK);
398 if has_stdout && d.level == 2 {
399 d.level = 1;
400 }
401 cmd.display_level = d.level;
402 let stderr_console = cmd.prefs.fake_stderr_console || host.stderr_is_tty();
403 if !stderr_console && cmd.prefs.progress != Progress::Always {
404 cmd.prefs.progress = Progress::Never;
405 }
406 if has_stdout && cmd.prefs.remove_src {
407 d.at(3, err, m::SRC_KEPT_STDOUT, &[]);
408 cmd.prefs.remove_src = false;
409 }
410 cmd.prefs.has_stdout_output = has_stdout;
411 cmd.prefs.nb_files_total = cmd.files.len();
412 cmd.prefs.has_stdin_input = has_stdin;
413 cmd.prefs.patch_from_mode = cmd.patch_from.is_some();
414 if cmd.prefs.memory_limit == 0 {
415 let wlog = cmd.cparam(CParamKey::WindowLog);
416 cmd.prefs.memory_limit = if wlog == 0 {
417 1 << cli::DEFAULT_MAX_WINDOW_LOG
418 } else {
419 1u32 << (wlog & 31)
420 };
421 }
422 if cmd.patch_from.is_some() {
423 cmd.dict_file = cmd.patch_from.clone();
424 }
425
426 if cmd.op != Operation::Compress {
427 if let Some(l) = cmd.limits {
428 // R9: the decoder's window log at most 24.
429 cmd.prefs.memory_limit = cmd.prefs.memory_limit.min(1 << l.window_log_max);
430 }
431 return finish(fileio::decompress_files(cmd, host, out, err), pause);
432 }
433
434 // FIO_setCompressionType .. FIO_setSparseWrite, with their messages.
435 if let Some(l) = cmd.limits
436 && cmd.prefs.workers > l.workers
437 {
438 // R9: at most 2 workers in the sandbox.
439 cmd.prefs.workers = l.workers;
440 }
441 let workers = cmd.prefs.workers;
442 // FIO_setBlockSize takes `(int)blockSize`.
443 if cmd.prefs.job_size as i32 != 0 && workers == 0 {
444 d.at(2, err, m::BLOCK_SIZE_USELESS, &[]);
445 }
446 if let Some(ovlog) = cmd.prefs.overlap_log
447 && ovlog != 0
448 && workers == 0
449 {
450 d.at(2, err, m::OVERLAP_LOG_USELESS, &[]);
451 }
452 if cmd.prefs.adapt && workers == 0 {
453 return exit(exm_throw(&d, err, 1, m::ADAPT_SINGLE_THREAD.as_bytes()));
454 }
455 if cmd.prefs.rsyncable && workers == 0 {
456 return exit(exm_throw(&d, err, 1, m::RSYNCABLE_SINGLE_THREAD.as_bytes()));
457 }
458 cmd.prefs.sparse = 0;
459 if cmd.prefs.adapt_min > cmd.level {
460 cmd.level = cmd.prefs.adapt_min;
461 }
462 if cmd.prefs.adapt_max < cmd.level {
463 cmd.level = cmd.prefs.adapt_max;
464 }
465
466 if cmd.show_default_cparams || d.level >= 4 {
467 let dict_size = cmd
468 .dict_file
469 .as_deref()
470 .map_or(0, |f| file_size(host, f).unwrap_or(u64::MAX));
471 for name in &cmd.files {
472 let size = file_size(host, name);
473 if cmd.show_default_cparams {
474 cli::print_default_cparams(err, name, size, dict_size, cmd.level);
475 }
476 if d.level >= 4 {
477 cli::print_actual_cparams(err, size, dict_size, cmd.level, cmd);
478 }
479 }
480 }
481 if d.level >= 4 {
482 display_compression_parameters(cmd, err);
483 }
484 finish(fileio::compress_files(cmd, host, out, err), pause)
485}
486
487/// fileio.c: FIO_displayCompressionParameters (display level 4).
488fn display_compression_parameters(cmd: &Command, err: &mut dyn Write) {
489 let p = &cmd.prefs;
490 let n = |v: i64| v.to_string();
491 printf(
492 err,
493 m::DCP_FORMAT,
494 &[m::FORMAT_OPTIONS[p.ctype.index()].as_bytes()],
495 );
496 printf(err, m::DCP_SPARSE[p.sparse.clamp(0, 2) as usize], &[]);
497 if !p.dict_id {
498 printf(err, m::DCP_NO_DICT_ID, &[]);
499 }
500 printf(err, m::DCP_CHECKSUM[p.checksum.clamp(0, 2) as usize], &[]);
501 printf(
502 err,
503 m::DCP_BLOCK_SIZE,
504 &[n(i64::from(p.job_size as i32)).as_bytes()],
505 );
506 if p.adapt {
507 printf(
508 err,
509 m::DCP_ADAPT,
510 &[
511 n(p.adapt_min.into()).as_bytes(),
512 n(p.adapt_max.into()).as_bytes(),
513 ],
514 );
515 }
516 printf(
517 err,
518 m::DCP_ROW_MATCH_FINDER[p.row_match_finder.value() as usize],
519 &[],
520 );
521 if p.rsyncable {
522 printf(err, m::DCP_RSYNCABLE, &[]);
523 }
524 if p.stream_size != 0 {
525 printf(
526 err,
527 m::DCP_STREAM_SIZE,
528 &[n((p.stream_size as u32).into()).as_bytes()],
529 );
530 }
531 if p.size_hint != 0 {
532 printf(err, m::DCP_SIZE_HINT, &[n(p.size_hint.into()).as_bytes()]);
533 }
534 if p.target_cblock_size != 0 {
535 printf(
536 err,
537 m::DCP_TARGET_CBLOCK,
538 &[n((p.target_cblock_size as u32).into()).as_bytes()],
539 );
540 }
541 printf(
542 err,
543 m::DCP_LITERALS[p.literal_compression.value() as usize],
544 &[],
545 );
546 let memory = if p.memory_limit != 0 {
547 p.memory_limit
548 } else {
549 128 << 20
550 };
551 printf(err, m::DCP_MEMORY, &[n(memory.into()).as_bytes()]);
552 printf(err, m::DCP_THREADS, &[n(p.workers.into()).as_bytes()]);
553 if p.exclude_compressed {
554 printf(err, m::DCP_EXCLUDE, &[]);
555 }
556 printf(
557 err,
558 m::DCP_CONTENT_SIZE,
559 &[if p.content_size { "" } else { m::DCP_NO }.as_bytes()],
560 );
561}
562
563#[cfg(test)]
564mod tests;