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//! (`util::Cores::detect`); 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` is compatible only on every tier:
116//! `lz4_flex`'s fast compressor at every level, inside liblz4's frame
117//! descriptor (64 KiB linked blocks, content size, content checksum as
118//! fileio.c sets them).
119
120use std::collections::BTreeMap;
121use std::ffi::{OsStr, OsString};
122use std::io::{self, Read, Write};
123use std::path::Path;
124use std::process::ExitCode;
125use std::sync::atomic::AtomicU64;
126use std::sync::{Arc, Mutex};
127
128use stuffr::zstd_opts::{self, CParamKey};
129
130use super::CountedRun;
131use super::host::{Host, SANDBOX_OUTPUT_CAP, Sandbox, reset_sigpipe};
132
133pub(crate) mod cli;
134mod dibio;
135pub(crate) mod display;
136pub(crate) mod fileio;
137mod formats;
138mod list;
139mod messages;
140pub(crate) mod util;
141
142use cli::{Command, Limits, Operation, Progress, STDINMARK, STDOUTMARK, Stop};
143use display::{Display, exm_throw};
144use messages::{self as m, printf};
145use util::Cores;
146
147/// Entry point for the four names; `name` is the canonical invoked name,
148/// `argv0` the program as invoked (its last component is zstd's
149/// `programName`) and `args` the arguments after it.
150pub fn run(name: &'static str, argv0: &OsStr, args: Vec<OsString>) -> ExitCode {
151 // zstd dies of SIGPIPE writing to a closed pipe.
152 reset_sigpipe();
153 let argv0 = if argv0.is_empty() {
154 name.as_bytes()
155 } else {
156 argv0.as_encoded_bytes()
157 };
158 let env = |k: &str| std::env::var_os(k);
159 let mut err = io::stderr();
160 let code = main(
161 argv0,
162 &args,
163 &env,
164 &mut Host::Real,
165 Cores::detect(),
166 None,
167 &mut err,
168 );
169 // The process's exit status is the code's low byte, as `exit()` makes
170 // it.
171 ExitCode::from(code as u8)
172}
173
174/// [`run`] without the process: operands resolve against `dir`, standard
175/// input is `stdin` (a pipe), standard output and error are captured and
176/// returned with the exit code, neither is a terminal, `env` stands in for
177/// the environment (`ZSTD_CLEVEL`, `ZSTD_NBTHREADS`) and `SIGPIPE` is left
178/// alone. The machine is R3's fixed 8 logical and 4 physical cores.
179///
180/// R9's input-independent bounds hold whatever the arguments say: the
181/// decoder's window log is at most 24 (16 MiB; a lower `--memory` or
182/// `--long` stands), `--train*` loads at most 256 KiB of samples with at
183/// most 4 optimiser steps, and compression runs at most 2 workers; xz and
184/// lzma frames decode under a 256 MiB memory limit and compress at preset
185/// 6 at most (`formats.rs`). Standard output and output files share the [`SANDBOX_OUTPUT_CAP`]
186/// budget. No signal handler is installed. For the fuzz target; not a
187/// stable interface.
188#[doc(hidden)]
189pub fn run_in_counted(
190 dir: &Path,
191 name: &'static str,
192 args: &[OsString],
193 stdin: &[u8],
194 env: &dyn Fn(&str) -> Option<OsString>,
195) -> CountedRun {
196 let stdout = Arc::new(Mutex::new(Vec::new()));
197 let reads = Arc::new(Mutex::new(BTreeMap::new()));
198 let mut host = Host::Sandbox(Sandbox {
199 dir: dir.to_path_buf(),
200 stdin: Some(stdin.to_vec()),
201 stdout: stdout.clone(),
202 budget: Arc::new(AtomicU64::new(SANDBOX_OUTPUT_CAP)),
203 reads: reads.clone(),
204 });
205 let mut err = Vec::new();
206 let code = main(
207 name.as_bytes(),
208 args,
209 env,
210 &mut host,
211 Cores::SANDBOX,
212 Some(Limits::SANDBOX),
213 &mut err,
214 );
215 drop(host);
216 let out = std::mem::take(&mut *stdout.lock().unwrap_or_else(|p| p.into_inner()));
217 let reads = std::mem::take(&mut *reads.lock().unwrap_or_else(|p| p.into_inner()));
218 (code, out, err, reads)
219}
220
221/// zstdcli.c: main, below the process boundary. Returns the exit code.
222fn main(
223 argv0: &[u8],
224 args: &[OsString],
225 env: &dyn Fn(&str) -> Option<OsString>,
226 host: &mut Host,
227 cores: Cores,
228 limits: Option<Limits>,
229 err: &mut dyn Write,
230) -> i32 {
231 let program = String::from_utf8_lossy(cli::last_name_from_path(argv0)).into_owned();
232 let mut out = host.out_writer(None);
233 let stop = match cli::parse(&program, env, args, cores, &mut out, err) {
234 Ok(mut cmd) => {
235 cmd.limits = limits;
236 execute(&mut cmd, host, &mut out, err)
237 }
238 Err(stop) => stop,
239 };
240 let _ = out.flush();
241 if stop.clean && stop.pause {
242 wait_enter(host, err);
243 }
244 stop.code
245}
246
247/// zstdcli.c: waitEnter, for `-p`.
248fn wait_enter(host: &mut Host, err: &mut dyn Write) {
249 printf(err, m::PRESS_ENTER, &[]);
250 let mut byte = [0u8; 1];
251 let _ = host.stdin().read(&mut byte);
252}
253
254/// UTIL_isLink and UTIL_isFIFO: whether `name` is a symbolic link (lstat)
255/// that does not lead to a FIFO (stat). Never on Windows, as util.c.
256fn is_link_not_fifo(host: &Host, name: &[u8]) -> bool {
257 util::is_link(host, name) && !util::is_fifo(host, name)
258}
259
260/// UTIL_getFileSize: a regular file's size (following links), else
261/// unknown.
262fn file_size(host: &Host, name: &[u8]) -> Option<u64> {
263 Some(util::file_size(host, name)).filter(|&s| s != util::FILESIZE_UNKNOWN)
264}
265
266/// An operation's result as `main` ends it: `CLEAN_RETURN` with the
267/// result, or the `EXM_THROW` exit.
268fn finish(r: fileio::Fio<i32>, pause: bool) -> Stop {
269 match r {
270 Ok(code) => Stop {
271 code,
272 clean: true,
273 pause,
274 },
275 Err(fileio::Thrown(code)) => Stop {
276 code,
277 clean: false,
278 pause,
279 },
280 }
281}
282
283/// zstdcli.c: main, from the symbolic-link filter to the operation.
284fn execute(cmd: &mut Command, host: &mut Host, out: &mut dyn Write, err: &mut dyn Write) -> Stop {
285 let pause = cmd.main_pause;
286 let clean = |code| Stop {
287 code,
288 clean: true,
289 pause,
290 };
291 let exit = |code| Stop {
292 code,
293 clean: false,
294 pause,
295 };
296 let mut d = Display::new(cmd.display_level);
297 // g_utilDisplayLevel.
298 cmd.prefs.util_level = cmd.display_level;
299 let util_level = cmd.display_level;
300
301 if !cmd.follow_links {
302 let total = cmd.files.len();
303 let mut kept = Vec::with_capacity(total);
304 for name in std::mem::take(&mut cmd.files) {
305 if is_link_not_fifo(host, &name) {
306 d.at(2, err, m::SYMLINK_IGNORED, &[&name]);
307 } else {
308 kept.push(name);
309 }
310 }
311 cmd.files = kept;
312 if cmd.files.is_empty() && total > 0 {
313 return clean(1);
314 }
315 }
316 for list in std::mem::take(&mut cmd.filelists) {
317 match util::names_from_file(host, &list, util_level, err) {
318 Some(names) => cmd.files.extend(names),
319 None => {
320 d.at(1, err, m::ERROR_READING, &[&list]);
321 return clean(1);
322 }
323 }
324 }
325 cmd.nb_input_files = cmd.files.len();
326 if cmd.recursive {
327 let names = std::mem::take(&mut cmd.files);
328 cmd.files = util::expand_names(host, names, cmd.follow_links, util_level, err);
329 }
330
331 match cmd.op {
332 Operation::List => return clean(list::list_files(cmd, host, out, err)),
333 Operation::Train => return finish(dibio::train_files(cmd, host, err), pause),
334 Operation::Test => {
335 cmd.prefs.test_mode = true;
336 cmd.out_file = Some(cli::NULMARK.to_vec());
337 cmd.prefs.remove_src = false;
338 }
339 Operation::Compress | Operation::Decompress => {}
340 }
341
342 if cmd.files.is_empty() {
343 if cmd.nb_input_files > 0 {
344 d.at(1, err, m::NO_INPUT_LEFT, &[]);
345 return clean(0);
346 }
347 cmd.files.push(STDINMARK.to_vec());
348 }
349 if cmd.files.len() == 1 && cmd.files[0] == STDINMARK && cmd.out_file.is_none() {
350 cmd.out_file = Some(STDOUTMARK.to_vec());
351 }
352
353 let has_stdin = cmd.files.iter().any(|f| f == STDINMARK);
354 if !cmd.force_stdin && has_stdin && (cmd.prefs.fake_stdin_console || host.stdin_is_tty()) {
355 d.at(1, err, m::STDIN_CONSOLE, &[]);
356 return clean(1);
357 }
358 if cmd.out_file.as_deref().is_none_or(|o| o == STDOUTMARK)
359 && (cmd.prefs.fake_stdout_console || host.stdout_is_tty())
360 && has_stdin
361 && !cmd.force_stdout
362 && cmd.op != Operation::Decompress
363 {
364 d.at(1, err, m::STDOUT_CONSOLE, &[]);
365 return clean(1);
366 }
367
368 let max_level = if cmd.ultra {
369 zstd_opts::MAX_CLEVEL
370 } else {
371 cli::CLEVEL_MAX
372 };
373 if cmd.level > max_level {
374 d.at(
375 2,
376 err,
377 m::LEVEL_REDUCED,
378 &[max_level.to_string().as_bytes()],
379 );
380 cmd.level = max_level;
381 }
382
383 if cmd.show_default_cparams && cmd.op == Operation::Decompress {
384 d.at(1, err, m::CPARAMS_DECOMPRESS, &[]);
385 return clean(1);
386 }
387 if cmd.dict_file.is_some() && cmd.patch_from.is_some() {
388 d.at(1, err, m::DICT_AND_PATCH, &[]);
389 return clean(1);
390 }
391 if cmd.patch_from.is_some() && cmd.files.len() > 1 {
392 d.at(1, err, m::PATCH_MULTIPLE, &[]);
393 return clean(1);
394 }
395
396 let has_stdout = cmd.out_file.as_deref() == Some(STDOUTMARK);
397 if has_stdout && d.level == 2 {
398 d.level = 1;
399 }
400 cmd.display_level = d.level;
401 let stderr_console = cmd.prefs.fake_stderr_console || host.stderr_is_tty();
402 if !stderr_console && cmd.prefs.progress != Progress::Always {
403 cmd.prefs.progress = Progress::Never;
404 }
405 if has_stdout && cmd.prefs.remove_src {
406 d.at(3, err, m::SRC_KEPT_STDOUT, &[]);
407 cmd.prefs.remove_src = false;
408 }
409 cmd.prefs.has_stdout_output = has_stdout;
410 cmd.prefs.nb_files_total = cmd.files.len();
411 cmd.prefs.has_stdin_input = has_stdin;
412 cmd.prefs.patch_from_mode = cmd.patch_from.is_some();
413 if cmd.prefs.memory_limit == 0 {
414 let wlog = cmd.cparam(CParamKey::WindowLog);
415 cmd.prefs.memory_limit = if wlog == 0 {
416 1 << cli::DEFAULT_MAX_WINDOW_LOG
417 } else {
418 1u32 << (wlog & 31)
419 };
420 }
421 if cmd.patch_from.is_some() {
422 cmd.dict_file = cmd.patch_from.clone();
423 }
424
425 if cmd.op != Operation::Compress {
426 if let Some(l) = cmd.limits {
427 // R9: the decoder's window log at most 24.
428 cmd.prefs.memory_limit = cmd.prefs.memory_limit.min(1 << l.window_log_max);
429 }
430 return finish(fileio::decompress_files(cmd, host, out, err), pause);
431 }
432
433 // FIO_setCompressionType .. FIO_setSparseWrite, with their messages.
434 if let Some(l) = cmd.limits
435 && cmd.prefs.workers > l.workers
436 {
437 // R9: at most 2 workers in the sandbox.
438 cmd.prefs.workers = l.workers;
439 }
440 let workers = cmd.prefs.workers;
441 // FIO_setBlockSize takes `(int)blockSize`.
442 if cmd.prefs.job_size as i32 != 0 && workers == 0 {
443 d.at(2, err, m::BLOCK_SIZE_USELESS, &[]);
444 }
445 if let Some(ovlog) = cmd.prefs.overlap_log
446 && ovlog != 0
447 && workers == 0
448 {
449 d.at(2, err, m::OVERLAP_LOG_USELESS, &[]);
450 }
451 if cmd.prefs.adapt && workers == 0 {
452 return exit(exm_throw(&d, err, 1, m::ADAPT_SINGLE_THREAD.as_bytes()));
453 }
454 if cmd.prefs.rsyncable && workers == 0 {
455 return exit(exm_throw(&d, err, 1, m::RSYNCABLE_SINGLE_THREAD.as_bytes()));
456 }
457 cmd.prefs.sparse = 0;
458 if cmd.prefs.adapt_min > cmd.level {
459 cmd.level = cmd.prefs.adapt_min;
460 }
461 if cmd.prefs.adapt_max < cmd.level {
462 cmd.level = cmd.prefs.adapt_max;
463 }
464
465 if cmd.show_default_cparams || d.level >= 4 {
466 let dict_size = cmd
467 .dict_file
468 .as_deref()
469 .map_or(0, |f| file_size(host, f).unwrap_or(u64::MAX));
470 for name in &cmd.files {
471 let size = file_size(host, name);
472 if cmd.show_default_cparams {
473 cli::print_default_cparams(err, name, size, dict_size, cmd.level);
474 }
475 if d.level >= 4 {
476 cli::print_actual_cparams(err, size, dict_size, cmd.level, cmd);
477 }
478 }
479 }
480 if d.level >= 4 {
481 display_compression_parameters(cmd, err);
482 }
483 finish(fileio::compress_files(cmd, host, out, err), pause)
484}
485
486/// fileio.c: FIO_displayCompressionParameters (display level 4).
487fn display_compression_parameters(cmd: &Command, err: &mut dyn Write) {
488 let p = &cmd.prefs;
489 let n = |v: i64| v.to_string();
490 printf(
491 err,
492 m::DCP_FORMAT,
493 &[m::FORMAT_OPTIONS[p.ctype.index()].as_bytes()],
494 );
495 printf(err, m::DCP_SPARSE[p.sparse.clamp(0, 2) as usize], &[]);
496 if !p.dict_id {
497 printf(err, m::DCP_NO_DICT_ID, &[]);
498 }
499 printf(err, m::DCP_CHECKSUM[p.checksum.clamp(0, 2) as usize], &[]);
500 printf(
501 err,
502 m::DCP_BLOCK_SIZE,
503 &[n(i64::from(p.job_size as i32)).as_bytes()],
504 );
505 if p.adapt {
506 printf(
507 err,
508 m::DCP_ADAPT,
509 &[
510 n(p.adapt_min.into()).as_bytes(),
511 n(p.adapt_max.into()).as_bytes(),
512 ],
513 );
514 }
515 printf(
516 err,
517 m::DCP_ROW_MATCH_FINDER[p.row_match_finder.value() as usize],
518 &[],
519 );
520 if p.rsyncable {
521 printf(err, m::DCP_RSYNCABLE, &[]);
522 }
523 if p.stream_size != 0 {
524 printf(
525 err,
526 m::DCP_STREAM_SIZE,
527 &[n((p.stream_size as u32).into()).as_bytes()],
528 );
529 }
530 if p.size_hint != 0 {
531 printf(err, m::DCP_SIZE_HINT, &[n(p.size_hint.into()).as_bytes()]);
532 }
533 if p.target_cblock_size != 0 {
534 printf(
535 err,
536 m::DCP_TARGET_CBLOCK,
537 &[n((p.target_cblock_size as u32).into()).as_bytes()],
538 );
539 }
540 printf(
541 err,
542 m::DCP_LITERALS[p.literal_compression.value() as usize],
543 &[],
544 );
545 let memory = if p.memory_limit != 0 {
546 p.memory_limit
547 } else {
548 128 << 20
549 };
550 printf(err, m::DCP_MEMORY, &[n(memory.into()).as_bytes()]);
551 printf(err, m::DCP_THREADS, &[n(p.workers.into()).as_bytes()]);
552 if p.exclude_compressed {
553 printf(err, m::DCP_EXCLUDE, &[]);
554 }
555 printf(
556 err,
557 m::DCP_CONTENT_SIZE,
558 &[if p.content_size { "" } else { m::DCP_NO }.as_bytes()],
559 );
560}
561
562#[cfg(test)]
563mod tests;