diff options
-rw-r--r-- | AUTHORS | 8 | ||||
-rw-r--r-- | ChangeLog | 167 | ||||
-rw-r--r-- | INSTALL | 30 | ||||
-rw-r--r-- | Makefile.in | 9 | ||||
-rw-r--r-- | NEWS | 44 | ||||
-rw-r--r-- | README | 123 | ||||
-rw-r--r-- | arg_parser.cc | 30 | ||||
-rw-r--r-- | arg_parser.h | 69 | ||||
-rwxr-xr-x | configure | 58 | ||||
-rw-r--r-- | decoder.cc | 31 | ||||
-rw-r--r-- | decoder.h | 60 | ||||
-rw-r--r-- | doc/lzip.1 | 37 | ||||
-rw-r--r-- | doc/lzip.info | 1326 | ||||
-rw-r--r-- | doc/lzip.texi | 819 | ||||
-rw-r--r-- | encoder.cc | 42 | ||||
-rw-r--r-- | encoder.h | 24 | ||||
-rw-r--r-- | encoder_base.cc | 31 | ||||
-rw-r--r-- | encoder_base.h | 52 | ||||
-rw-r--r-- | fast_encoder.cc | 24 | ||||
-rw-r--r-- | fast_encoder.h | 24 | ||||
-rw-r--r-- | list.cc | 57 | ||||
-rw-r--r-- | lzip.h | 36 | ||||
-rw-r--r-- | lzip_index.cc | 106 | ||||
-rw-r--r-- | lzip_index.h | 30 | ||||
-rw-r--r-- | main.cc | 512 | ||||
-rwxr-xr-x | testsuite/check.sh | 155 | ||||
-rw-r--r-- | testsuite/fox.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_bcrc.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_crc0.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_das46.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_de20.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_mes81.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_s11.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/fox_v2.lz | bin | 0 -> 80 bytes | |||
-rw-r--r-- | testsuite/test_em.txt.lz | bin | 0 -> 14024 bytes |
35 files changed, 2128 insertions, 1776 deletions
@@ -1,7 +1,7 @@ Lzip was written by Antonio Diaz Diaz. The ideas embodied in lzip are due to (at least) the following people: -Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for -the definition of Markov chains), G.N.N. Martin (for the definition of -range encoding), Igor Pavlov (for putting all the above together in -LZMA), and Julian Seward (for bzip2's CLI). +Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the +definition of Markov chains), G.N.N. Martin (for the definition of range +encoding), Igor Pavlov (for putting all the above together in LZMA), and +Julian Seward (for bzip2's CLI). @@ -1,31 +1,48 @@ +2021-01-04 Antonio Diaz Diaz <antonio@gnu.org> + + * Version 1.22 released. + * main.cc (main): Report an error if a file name is empty. + Make '-o' behave like '-c', but writing to file instead of stdout. + Make '-c' and '-o' check whether the output is a terminal only once. + Do not open output if input is a terminal. + * configure: Build, check, and install without 'make'. + * Replace 'decompressed', 'compressed' with 'out', 'in' in output. + * lzip_index.cc: Improve messages for corruption in last header. + * main.cc: Set a valid invocation_name even if argc == 0. + * Document extraction from tar.lz in manual, '--help', and man page. + * lzip.texi (Introduction): Mention plzip and tarlz as alternatives. + * lzip.texi: Several fixes and improvements. + * testsuite: Add 9 new test files. + 2019-01-03 Antonio Diaz Diaz <antonio@gnu.org> * Version 1.21 released. - * File_* renamed to Lzip_*. + * Rename File_* to Lzip_*. * lzip.h (Lzip_trailer): New function 'verify_consistency'. * lzip_index.cc: Detect some kinds of corrupt trailers. * main.cc (main): Check return value of close( infd ). * main.cc: Compile on DOS with DJGPP. - * lzip.texi: Improved description of '-0..-9', '-m' and '-s'. + * Fix a GCC warning about catching std::bad_alloc by value. + * lzip.texi: Improve description of '-0..-9', '-m', and '-s'. * configure: Accept appending to CXXFLAGS, 'CXXFLAGS+=OPTIONS'. * INSTALL: Document use of CXXFLAGS+='-D __USE_MINGW_ANSI_STDIO'. 2018-02-11 Antonio Diaz Diaz <antonio@gnu.org> * Version 1.20 released. - * Added new option '--loose-trailing'. - * Improved corrupt header detection to HD=3. + * New option '--loose-trailing'. + * Improve corrupt header detection to HD=3. * main.cc: Show corrupt or truncated header in multimember file. * main.cc (main): Option '-S, --volume-size' now keeps input files. * encoder_base.*: Adjust dictionary size for each member. - * Replaced 'bits/byte' with inverse compression ratio in output. + * Replace 'bits/byte' with inverse compression ratio in output. * Show progress of decompression at verbosity level 2 (-vv). * Show progress of (de)compression only if stderr is a terminal. * main.cc: Show final diagnostic when testing multiple files. - * main.cc: Do not add a second .lz extension to the arg of -o. + * main.cc: Do not add a second extension '.lz' to the arg of '-o'. * decoder.cc (verify_trailer): Show stored sizes also in hex. Show dictionary size at verbosity level 4 (-vvvv). - * lzip.texi: Added chapter 'Output'. + * lzip.texi: New chapter 'Meaning of lzip's output'. 2017-04-13 Antonio Diaz Diaz <antonio@gnu.org> @@ -36,20 +53,20 @@ * Decompression time has been reduced by 2%. * main.cc: Continue testing if any input file is a terminal. * main.cc: Show trailing data in both hexadecimal and ASCII. - * encoder.cc (Matchfinder_base): Verify size passed to new. + * encoder.cc (Matchfinder_base): Verify the size passed to new. * lzip_index.cc: Improve detection of bad dict and trailing data. - * lzip.h: Unified messages for bad magic, trailing data, etc. + * lzip.h: Unify messages for bad magic, trailing data, etc. 2016-05-14 Antonio Diaz Diaz <antonio@gnu.org> * Version 1.18 released. - * Added new option '-a, --trailing-error'. + * New option '-a, --trailing-error'. * Decompression time has been reduced by 2%. - * decoder.cc (verify_trailer): Removed test of final code. + * decoder.cc (verify_trailer): Remove test of final code. * main.cc (main): Delete '--output' file if infd is a terminal. * main.cc (main): Don't use stdin more than once. - * Removed decompression support for version 0 files. - * lzip.texi: Added chapter 'Trailing data'. + * Remove decompression support for version 0 files. + * lzip.texi: New chapter 'Trailing data'. * configure: Avoid warning on some shells when testing for g++. * Makefile.in: Detect the existence of install-info. * check.sh: A POSIX shell is required to run the tests. @@ -59,8 +76,8 @@ * Version 1.17 released. * Reorganization of the compression code. - * lzip.texi: Added chapter 'Quality assurance'. - * Makefile.in: Added new targets 'install*-compress'. + * lzip.texi: New chapter 'Quality assurance'. + * Makefile.in: New targets 'install*-compress'. 2014-08-26 Antonio Diaz Diaz <antonio@gnu.org> @@ -70,8 +87,8 @@ * Compression time of option '-0' has been reduced by 2%. * main.cc (close_and_set_permissions): Behave like 'cp -p'. * Minor improvements. - * lzip.texinfo: Renamed to lzip.texi. - * License changed to GPL version 2 or later. + * lzip.texinfo: Rename to lzip.texi. + * Change license to GPL version 2 or later. 2013-09-20 Antonio Diaz Diaz <antonio@gnu.org> @@ -80,7 +97,7 @@ * main.cc (show_header): Don't show header version. * Ignore option '-n, --threads' for compatibility with plzip. * configure: Options now accept a separate argument. - * lzip.texinfo: Added chapter 'Stream format' and appendix + * lzip.texinfo: New chapter 'Stream format' and appendix 'Reference source code'. 2013-02-17 Antonio Diaz Diaz <ant_diaz@teleline.es> @@ -90,7 +107,7 @@ * Compression ratio has been slightly increased. * Compression time has been reduced by 5%. * Decompression time has been reduced by 12%. - * Makefile.in: Added new target 'install-bin'. + * Makefile.in: New target 'install-bin'. * main.cc: Use 'setmode' instead of '_setmode' on Windows and OS/2. * main.cc: Define 'strtoull' to 'std::strtoul' on Windows. @@ -103,21 +120,20 @@ * Compression time of option '-0' has been reduced by 2%. * Reorganization of the compression code. * Small change in '--help' output and man page. - * Changed quote characters in messages as advised by GNU Standards. - * configure: 'datadir' renamed to 'datarootdir'. + * Change quote characters in messages as advised by GNU Standards. + * configure: Rename 'datadir' to 'datarootdir'. * 'unzcrash.cc' has been moved to package 'lziprecover'. 2011-04-30 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.12 released. - * Added new option '-F, --recompress'. + * New option '-F, --recompress'. * encoder.h (update_prices): Update high length symbol prices independently of the value of 'pos_state'. This gives better compression for large values of '--match-length' without being slower. - * encoder.h encoder.cc: Optimize pair price calculations. This - reduces compression time for large values of '--match-length' - by up to 6%. + * encoder.h, encoder.cc: Optimize pair price calculations, reducing + compression time for large values of '--match-length' by up to 6%. * Compression time of option '-0' has been reduced by 2%. * main.cc (decompress): Print only one status line for each multimember file when only one '-v' is specified. @@ -127,41 +143,39 @@ " and '--stdout' was not specified" for directories, etc. * lziprecover.cc: If '-v' is not specified show errors only. * unzcrash.cc: Use Arg_parser. - * unzcrash.cc: Added new option '-b, --bits'. - * unzcrash.cc: Added new option '-p, --position'. - * unzcrash.cc: Added new option '-s, --size'. + * unzcrash.cc: New options '-b, --bits', '-p, --position', and + '-s, --size'. 2010-09-16 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.11 released. - * Added new option '-0' which produces a compression speed and ratio + * New option '-0', which produces a compression speed and ratio comparable to those of 'gzip -9'. - * fast_encoder.h fast_encoder.cc: New files. + * fast_encoder.h, fast_encoder.cc: New files. * main.cc: Match length limit set by options -1 to -8 has been reduced to extend range of use towards gzip. Lower numbers now compress less but faster. (-1 now takes 43% less time for only 20% larger compressed size). + Exit with status 1 if any output file exists and is skipped. * Compression ratio of option '-9' has been slightly increased. - * lziprecover.cc: Added new option '-m, --merge' which tries to - produce a correct file merging the good parts of two or more - damaged copies. - * lziprecover.cc: Added new option '-R, --repair' for repairing a + * lziprecover.cc: New option '-m, --merge', which tries to produce a + correct file by merging the good parts of two or more damaged copies. + * lziprecover.cc: New option '-R, --repair' for repairing a 1-byte error in single-member files. * decoder.cc (decode_member): Detect file errors earlier to improve efficiency of lziprecover's new repair capability. This change also prevents (harmless) access to uninitialized memory when decompressing a corrupt file. - * lziprecover.cc: Added new option '-f, --force'. - * lziprecover.cc: Added new option '-o, --output'. - * lziprecover.cc: Added new option '-s, --split' to select the until + * lziprecover.cc: New options '-f, --force' and '-o, --output'. + * lziprecover.cc: New option '-s, --split' to select the until now only operation of splitting multimember files. * lziprecover.cc: If no operation is specified, warn the user and do nothing. - * main.cc: Fixed warning about fchown's return value being ignored. + * main.cc: Fix warning about fchown's return value being ignored. * decoder.cc: '-tvvvv' now also shows compression ratio. * main.cc: Set stdin/stdout in binary mode on MSVC and OS2. - * lzip.texinfo: Added new examples. - * testsuite: 'test1' renamed to 'test.txt'. Added new tests. + * lzip.texinfo: New examples. + * testsuite: Rename 'test1' to 'test.txt'. New tests. * Matchfinder types HC4 (4 bytes hash-chain) and HT4 (4 bytes hash-table) have been tested and found no better than the current BT4. @@ -175,14 +189,14 @@ * main.cc: New constant 'o_binary'. * main.cc: Dictionary size for options -2, -3, -4 and -8 has been changed to improve linearity of compressed sizes. - * lzip.h: Fixed warnings produced by over-optimization (-O3). - * Makefile.in: Added quotes to directory names. + * lzip.h: Fix warnings produced by over-optimization (-O3). + * Makefile.in: Add quotes to directory names. 2010-01-17 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.9 released. * main.cc (main): Return at least 1 if closing stdout fails. - * Makefile.in: Added '--name' option to help2man invocation. + * Makefile.in: Add option '--name' to help2man invocation. * check.sh: Use 'test1' instead of 'COPYING' for testing. 2009-09-02 Antonio Diaz Diaz <ant_diaz@teleline.es> @@ -190,41 +204,41 @@ * Version 1.8 released. * Compression time has been reduced by 4%. * Lzdiff and lzgrep have been moved to the new package zutils. - * Fixed warnings on systems where uint32_t != unsigned int. + * Fix warnings on systems where uint32_t != unsigned int. 2009-06-25 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.7 released. - * decoder.h (copy_block): Fixed memcpy overlap introduced in 1.6. + * decoder.h (copy_block): Fix memcpy overlap introduced in 1.6. 2009-06-22 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.6 released. * Decompression time has been reduced by 17%. - * Added decompression support for Sync Flush marker. - * Added support for .tbz extension to lzdiff and lzgrep. - * Added man pages for lzdiff, lzgrep and lziprecover. + * Add decompression support for Sync Flush marker. + * Add support for the extension '.tbz' to lzdiff and lzgrep. + * Add man pages for lzdiff, lzgrep and lziprecover. * encoder.cc (Matchfinder): Reduce memory use to 9x if input file is smaller than dictionary size limit. - * decoder.cc: Added extra flush calls to improve partial - decompression of corrupt files. + * decoder.cc: Add extra flush calls to improve partial decompression + of corrupt files. * '--test' no longer needs '/dev/null'. - * Removed some 'bashisms' from lzdiff and lzgrep. + * Remove some 'bashisms' from lzdiff and lzgrep. * Dictionary size for options '-1' to '-4' has been changed. - * main.cc (signal_handler): Declared as 'extern "C"'. + * main.cc (signal_handler): Declare as 'extern "C"'. * Makefile.in: Extra files are now installed by default. * check.sh: Test lziprecover. - * Added 'export LC_ALL=C' to all scripts. + * Add 'export LC_ALL=C' to all scripts. 2009-04-12 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.5 released. - * lzip.h: Coded dictionary size implemented in Lzip_header. - * Fixed some includes that prevented compilation with GCC 4.4. + * lzip.h: Implement coded dictionary size in Lzip_header. + * Fix some includes that prevented compilation with GCC 4.4. * 'member_size' and 'volume_size' are now accurate limits. * Compression speed has been improved. - * Implemented bt4 type matchfinder. - * lzip.texinfo: Added chapter 'Algorithm'. + * Implement bt4 type matchfinder. + * lzip.texinfo: New chapter 'Algorithm'. * Lzdiff and lzgrep now accept '-h' for '--help' and '-V' for '--version'. * Makefile.in: Man page is now installed by default. @@ -233,12 +247,11 @@ 2009-01-24 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.4 released. - * Implemented compression of version 1 files. - * Added new option '-b, --member-size'. - * Added new option '-S, --volume-size'. - * Added new option '-o, --output'. - * main.cc: Read from non regular files if '--stdout' is specified. - * Added 'lziprecover', a member recoverer program. + * Implement compression of version 1 files. + * New options '-b, --member-size', '-S, --volume-size', and + '-o, --output'. + * main.cc: Read from non-regular files if '--stdout' is specified. + * Add 'lziprecover', a member recoverer program. * unzcrash.cc: Test all 1-byte errors. 2008-12-21 Antonio Diaz Diaz <ant_diaz@teleline.es> @@ -247,8 +260,8 @@ * This version automatically chooses the smallest possible dictionary size for each file during compression, saving memory during decompression. - * Implemented decompression of version 1 files. - * check.sh: Replaced 'diff -q' with 'cmp'. + * Implement decompression of version 1 files. + * check.sh: Replace 'diff -q' with 'cmp'. 2008-12-10 Antonio Diaz Diaz <ant_diaz@teleline.es> @@ -256,18 +269,18 @@ * encoder.cc: A 1-byte read outside allocated memory has been fixed. * lzip.h: Dictionary size limit has been reduced to 512MiB because setting it to 1GiB causes overflow of a 32 bit integer. - * Added 'lzdiff', a diff/cmp wrapper for gzip, bzip2, lzip and + * Add 'lzdiff', a diff/cmp wrapper for gzip, bzip2, lzip and non-compressed files. - * Added 'lzgrep', a grep wrapper for gzip, bzip2, lzip and + * Add 'lzgrep', a grep wrapper for gzip, bzip2, lzip and non-compressed files. * 'make install-info' should now work on Debian and OS X. 2008-11-17 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 1.1 released. - * Changed short name of option '--dictionary-size' to '-s'. - * Changed short name of option '--match-length' to '-m'. - * Changed LONG_LONG_MAX to LLONG_MAX. + * Change short name of option '--dictionary-size' to '-s'. + * Change short name of option '--match-length' to '-m'. + * Change LONG_LONG_MAX to LLONG_MAX. 2008-10-14 Antonio Diaz Diaz <ant_diaz@teleline.es> @@ -283,14 +296,14 @@ * Version 0.4 released. * Code cleanup for global variable 'verbosity'. - * Regained the compression ratio of 0.2 with 5% faster speed. - * Fixed compilation on systems where size_t != unsigned int. + * Regain the compression ratio of 0.2 with 5% faster speed. + * lzip.h: Fix compilation on systems where size_t != unsigned int. 2008-09-15 Antonio Diaz Diaz <ant_diaz@teleline.es> * Version 0.3 released. * encoder.cc: Compression is now 15% faster, 1% worse. - * main.cc (main): Make '-t' option override '-c'. + * main.cc (main): Make option '-t' override '-c'. * main.cc (decompress): Show 'done' instead of 'ok' when not testing. * encoder.h: Use trials[] to return the list of pairs. @@ -305,8 +318,8 @@ * Version 0.1 released. -Copyright (C) 2008-2019 Antonio Diaz Diaz. +Copyright (C) 2008-2021 Antonio Diaz Diaz. -This file is a collection of facts, and thus it is not copyrightable, but -just in case, you have unlimited permission to copy, distribute and modify -it. +This file is a collection of facts, and thus it is not copyrightable, +but just in case, you have unlimited permission to copy, distribute, and +modify it. @@ -1,7 +1,7 @@ Requirements ------------ -You will need a C++ compiler. -I use gcc 5.3.0 and 4.1.2, but the code should compile with any standards +You will need a C++11 compiler. (gcc 3.3.6 or newer is recommended). +I use gcc 6.1.0 and 4.1.2, but the code should compile with any standards compliant compiler. Gcc is available at http://gcc.gnu.org. @@ -41,21 +41,21 @@ the main archive. documentation. Or type 'make install-compress', which additionally compresses the - info manual and the man page after installation. (Installing - compressed docs may become the default in the future). + info manual and the man page after installation. + (Installing compressed docs may become the default in the future). - You can install only the program, the info manual or the man page by - typing 'make install-bin', 'make install-info' or 'make install-man' + You can install only the program, the info manual, or the man page by + typing 'make install-bin', 'make install-info', or 'make install-man' respectively. Another way ----------- You can also compile lzip into a separate directory. -To do this, you must use a version of 'make' that supports the 'VPATH' -variable, such as GNU 'make'. 'cd' to the directory where you want the +To do this, you must use a version of 'make' that supports the variable +'VPATH', such as GNU 'make'. 'cd' to the directory where you want the object files and executables to go and run the 'configure' script. -'configure' automatically checks for the source code in '.', in '..' and +'configure' automatically checks for the source code in '.', in '..', and in the directory that 'configure' is in. 'configure' recognizes the option '--srcdir=DIR' to control where to @@ -66,7 +66,15 @@ After running 'configure', you can run 'make' and 'make install' as explained above. -Copyright (C) 2008-2019 Antonio Diaz Diaz. +Building without 'make' +----------------------- +If you need to build lzip on a system lacking a 'make' program, you can use +'configure' to build, check, and install the lzip executable like this: + + ./configure --build --check --installdir=/usr/local/bin + + +Copyright (C) 2008-2021 Antonio Diaz Diaz. This file is free documentation: you have unlimited permission to copy, -distribute and modify it. +distribute, and modify it. diff --git a/Makefile.in b/Makefile.in index 20e9f16..7df577a 100644 --- a/Makefile.in +++ b/Makefile.in @@ -74,7 +74,7 @@ install-info : -rm -f "$(DESTDIR)$(infodir)/$(pkgname).info"* $(INSTALL_DATA) $(VPATH)/doc/$(pkgname).info "$(DESTDIR)$(infodir)/$(pkgname).info" -if $(CAN_RUN_INSTALLINFO) ; then \ - install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$(pkgname).info" ; \ + install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$(pkgname).info" ; \ fi install-info-compress : install-info @@ -95,7 +95,7 @@ uninstall-bin : uninstall-info : -if $(CAN_RUN_INSTALLINFO) ; then \ - install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$(pkgname).info" ; \ + install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$(pkgname).info" ; \ fi -rm -f "$(DESTDIR)$(infodir)/$(pkgname).info"* @@ -120,7 +120,10 @@ dist : doc $(DISTNAME)/*.cc \ $(DISTNAME)/testsuite/check.sh \ $(DISTNAME)/testsuite/test.txt \ - $(DISTNAME)/testsuite/test.txt.lz + $(DISTNAME)/testsuite/fox.lz \ + $(DISTNAME)/testsuite/fox_*.lz \ + $(DISTNAME)/testsuite/test.txt.lz \ + $(DISTNAME)/testsuite/test_em.txt.lz rm -f $(DISTNAME) lzip -v -9 $(DISTNAME).tar @@ -1,17 +1,39 @@ -Changes in version 1.21: +Changes in version 1.22: -Detection of forbidden combinations of characters in trailing data has been -improved. +Lzip now reports an error if a file name is empty (lzip -t ""). -Errors are now also checked when closing the input file. +Option '-o, --output' now behaves like '-c, --stdout', but sending the +output unconditionally to a file instead of to standard output. See the new +description of '-o' in the manual. This change is backwards compatible only +when (de)compressing from standard input alone. Therefore commands like: + lzip -o foo.lz - bar < foo +must now be split into: + lzip -o foo.lz - < foo + lzip bar +or rewritten as: + lzip - bar < foo > foo.lz -Lzip now compiles on DOS with DJGPP. (Patch from Robert Riebisch). +When using '-c' or '-o', lzip now checks whether the output is a terminal +only once. -The descriptions of '-0..-9', '-m' and '-s' in the manual have been -improved. +Lzip now does not even open the output file if the input file is a terminal. -The configure script now accepts appending options to CXXFLAGS using the -syntax 'CXXFLAGS+=OPTIONS'. +Lzip can now be built, tested, and installed on systems lacking a 'make' +program. (Feature suggested by Mohammad Akhlaghi). -It has been documented in INSTALL the use of -CXXFLAGS+='-D __USE_MINGW_ANSI_STDIO' when compiling on MinGW. +The words 'decompressed' and 'compressed' have been replaced with the +shorter 'out' and 'in' in the verbose output when decompressing or testing. + +Option '--list' now reports corruption or truncation of the last header in a +multimenber file specifically instead of showing the generic message "Last +member in input file is truncated or corrupt." + +The commands needed to extract files from a tar.lz archive have been +documented in the manual, in the output of '--help', and in the man page. + +Plzip and tarlz are mentioned in the manual as alternatives for +multiprocessors. + +Several fixes and improvements have been made to the manual. + +9 new test files have been added to the testsuite. @@ -1,52 +1,62 @@ Description -Lzip is a lossless data compressor with a user interface similar to the -one of gzip or bzip2. Lzip can compress about as fast as gzip (lzip -0) -or compress most files more than bzip2 (lzip -9). Decompression speed is -intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 -from a data recovery perspective. Lzip has been designed, written and -tested with great care to replace gzip and bzip2 as the standard -general-purpose compressed format for unix-like systems. +Lzip is a lossless data compressor with a user interface similar to the one +of gzip or bzip2. Lzip uses a simplified form of the 'Lempel-Ziv-Markov +chain-Algorithm' (LZMA) stream format, chosen to maximize safety and +interoperability. Lzip can compress about as fast as gzip (lzip -0) or +compress most files more than bzip2 (lzip -9). Decompression speed is +intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 from +a data recovery perspective. Lzip has been designed, written, and tested +with great care to replace gzip and bzip2 as the standard general-purpose +compressed format for unix-like systems. + +For compressing/decompressing large files on multiprocessor machines plzip +can be much faster than lzip at the cost of a slightly reduced compression +ratio. + +For creation and manipulation of compressed tar archives tarlz can be more +efficient than using tar and plzip because tarlz is able to keep the +alignment between tar members and lzip members. The lzip file format is designed for data sharing and long-term archiving, taking into account both data integrity and decoder availability: * The lzip format provides very safe integrity checking and some data - recovery means. The lziprecover program can repair bit flip errors - (one of the most common forms of data corruption) in lzip files, - and provides data recovery capabilities, including error-checked - merging of damaged copies of a file. - - * The lzip format is as simple as possible (but not simpler). The - lzip manual provides the source code of a simple decompressor - along with a detailed explanation of how it works, so that with - the only help of the lzip manual it would be possible for a - digital archaeologist to extract the data from a lzip file long - after quantum computers eventually render LZMA obsolete. + recovery means. The program lziprecover can repair bit flip errors + (one of the most common forms of data corruption) in lzip files, and + provides data recovery capabilities, including error-checked merging + of damaged copies of a file. + + * The lzip format is as simple as possible (but not simpler). The lzip + manual provides the source code of a simple decompressor along with a + detailed explanation of how it works, so that with the only help of the + lzip manual it would be possible for a digital archaeologist to extract + the data from a lzip file long after quantum computers eventually + render LZMA obsolete. * Additionally the lzip reference implementation is copylefted, which guarantees that it will remain free forever. -A nice feature of the lzip format is that a corrupt byte is easier to -repair the nearer it is from the beginning of the file. Therefore, with -the help of lziprecover, losing an entire archive just because of a -corrupt byte near the beginning is a thing of the past. +A nice feature of the lzip format is that a corrupt byte is easier to repair +the nearer it is from the beginning of the file. Therefore, with the help of +lziprecover, losing an entire archive just because of a corrupt byte near +the beginning is a thing of the past. Lzip uses the same well-defined exit status values used by bzip2, which makes it safer than compressors returning ambiguous warning values (like gzip) when it is used as a back end for other programs like tar or zutils. -Lzip will automatically use for each file the largest dictionary size -that does not exceed neither the file size nor the limit given. Keep in -mind that the decompression memory requirement is affected at -compression time by the choice of dictionary size limit. +Lzip will automatically use for each file the largest dictionary size that +does not exceed neither the file size nor the limit given. Keep in mind that +the decompression memory requirement is affected at compression time by the +choice of dictionary size limit. The amount of memory required for compression is about 1 or 2 times the dictionary size limit (1 if input file size is less than dictionary size -limit, else 2) plus 9 times the dictionary size really used. The option -'-0' is special and only requires about 1.5 MiB at most. The amount of -memory required for decompression is about 46 kB larger than the -dictionary size really used. +limit, else 2) plus 9 times the dictionary size really used. The option '-0' +is special and only requires about 1.5 MiB at most. The amount of memory +required for decompression is about 46 kB larger than the dictionary size +really used. When compressing, lzip replaces every file given in the command line with a compressed version of itself, with the name "original_name.lz". @@ -63,37 +73,36 @@ possible, ownership of the file just as 'cp -p' does. (If the user ID or the group ID can't be duplicated, the file permission bits S_ISUID and S_ISGID are cleared). -Lzip is able to read from some types of non regular files if the -'--stdout' option is specified. +Lzip is able to read from some types of non-regular files if either the +option '-c' or the option '-o' is specified. If no file names are specified, lzip compresses (or decompresses) from -standard input to standard output. In this case, lzip will decline to -write compressed output to a terminal, as this would be entirely -incomprehensible and therefore pointless. +standard input to standard output. Lzip will refuse to read compressed data +from a terminal or write compressed data to a terminal, as this would be +entirely incomprehensible and might leave the terminal in an abnormal state. Lzip will correctly decompress a file which is the concatenation of two or more compressed files. The result is the concatenation of the corresponding decompressed files. Integrity testing of concatenated compressed files is also supported. -Lzip can produce multimember files, and lziprecover can safely recover -the undamaged members in case of file damage. Lzip can also split the -compressed output in volumes of a given size, even when reading from -standard input. This allows the direct creation of multivolume -compressed tar archives. +Lzip can produce multimember files, and lziprecover can safely recover the +undamaged members in case of file damage. Lzip can also split the compressed +output in volumes of a given size, even when reading from standard input. +This allows the direct creation of multivolume compressed tar archives. Lzip is able to compress and decompress streams of unlimited size by -automatically creating multimember output. The members so created are -large, about 2 PiB each. +automatically creating multimember output. The members so created are large, +about 2 PiB each. In spite of its name (Lempel-Ziv-Markov chain-Algorithm), LZMA is not a concrete algorithm; it is more like "any algorithm using the LZMA coding -scheme". For example, the option '-0' of lzip uses the scheme in almost -the simplest way possible; issuing the longest match it can find, or a -literal byte if it can't find a match. Inversely, a much more elaborated -way of finding coding sequences of minimum size than the one currently -used by lzip could be developed, and the resulting sequence could also -be coded using the LZMA coding scheme. +scheme". For example, the option '-0' of lzip uses the scheme in almost the +simplest way possible; issuing the longest match it can find, or a literal +byte if it can't find a match. Inversely, a much more elaborated way of +finding coding sequences of minimum size than the one currently used by lzip +could be developed, and the resulting sequence could also be coded using the +LZMA coding scheme. Lzip currently implements two variants of the LZMA algorithm; fast (used by option '-0') and normal (used by all other compression levels). @@ -105,20 +114,20 @@ similar order-0 entropy coder as its last stage) with segregation of contexts according to what the bits are used for. The ideas embodied in lzip are due to (at least) the following people: -Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for -the definition of Markov chains), G.N.N. Martin (for the definition of -range encoding), Igor Pavlov (for putting all the above together in -LZMA), and Julian Seward (for bzip2's CLI). +Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the +definition of Markov chains), G.N.N. Martin (for the definition of range +encoding), Igor Pavlov (for putting all the above together in LZMA), and +Julian Seward (for bzip2's CLI). -LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may never -have been compressed. Decompressed is used to refer to data which have -undergone the process of decompression. +LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may never have +been compressed. Decompressed is used to refer to data which have undergone +the process of decompression. -Copyright (C) 2008-2019 Antonio Diaz Diaz. +Copyright (C) 2008-2021 Antonio Diaz Diaz. This file is free documentation: you have unlimited permission to copy, -distribute and modify it. +distribute, and modify it. The file Makefile.in is a data file used by configure to produce the Makefile. It has the same copyright owner and permissions that configure diff --git a/arg_parser.cc b/arg_parser.cc index ea32fde..2e40a13 100644 --- a/arg_parser.cc +++ b/arg_parser.cc @@ -1,20 +1,20 @@ -/* Arg_parser - POSIX/GNU command line argument parser. (C++ version) - Copyright (C) 2006-2019 Antonio Diaz Diaz. +/* Arg_parser - POSIX/GNU command line argument parser. (C++ version) + Copyright (C) 2006-2021 Antonio Diaz Diaz. - This library is free software. Redistribution and use in source and - binary forms, with or without modification, are permitted provided - that the following conditions are met: + This library is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #include <cstring> @@ -167,7 +167,7 @@ Arg_parser::Arg_parser( const int argc, const char * const argv[], else non_options.push_back( argv[argind++] ); } } - if( error_.size() ) data.clear(); + if( !error_.empty() ) data.clear(); else { for( unsigned i = 0; i < non_options.size(); ++i ) @@ -190,7 +190,7 @@ Arg_parser::Arg_parser( const char * const opt, const char * const arg, { if( opt[2] ) parse_long_option( opt, arg, options, argind ); } else parse_short_option( opt, arg, options, argind ); - if( error_.size() ) data.clear(); + if( !error_.empty() ) data.clear(); } else data.push_back( Record( opt ) ); } diff --git a/arg_parser.h b/arg_parser.h index ceb9933..5629b90 100644 --- a/arg_parser.h +++ b/arg_parser.h @@ -1,43 +1,43 @@ -/* Arg_parser - POSIX/GNU command line argument parser. (C++ version) - Copyright (C) 2006-2019 Antonio Diaz Diaz. +/* Arg_parser - POSIX/GNU command line argument parser. (C++ version) + Copyright (C) 2006-2021 Antonio Diaz Diaz. - This library is free software. Redistribution and use in source and - binary forms, with or without modification, are permitted provided - that the following conditions are met: + This library is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ -/* Arg_parser reads the arguments in 'argv' and creates a number of - option codes, option arguments and non-option arguments. +/* Arg_parser reads the arguments in 'argv' and creates a number of + option codes, option arguments, and non-option arguments. - In case of error, 'error' returns a non-empty error message. + In case of error, 'error' returns a non-empty error message. - 'options' is an array of 'struct Option' terminated by an element - containing a code which is zero. A null name means a short-only - option. A code value outside the unsigned char range means a - long-only option. + 'options' is an array of 'struct Option' terminated by an element + containing a code which is zero. A null name means a short-only + option. A code value outside the unsigned char range means a + long-only option. - Arg_parser normally makes it appear as if all the option arguments - were specified before all the non-option arguments for the purposes - of parsing, even if the user of your program intermixed option and - non-option arguments. If you want the arguments in the exact order - the user typed them, call 'Arg_parser' with 'in_order' = true. + Arg_parser normally makes it appear as if all the option arguments + were specified before all the non-option arguments for the purposes + of parsing, even if the user of your program intermixed option and + non-option arguments. If you want the arguments in the exact order + the user typed them, call 'Arg_parser' with 'in_order' = true. - The argument '--' terminates all options; any following arguments are - treated as non-option arguments, even if they begin with a hyphen. + The argument '--' terminates all options; any following arguments are + treated as non-option arguments, even if they begin with a hyphen. - The syntax for optional option arguments is '-<short_option><argument>' - (without whitespace), or '--<long_option>=<argument>'. + The syntax for optional option arguments is '-<short_option><argument>' + (without whitespace), or '--<long_option>=<argument>'. */ class Arg_parser @@ -61,6 +61,7 @@ private: explicit Record( const char * const arg ) : code( 0 ), argument( arg ) {} }; + const std::string empty_arg; std::string error_; std::vector< Record > data; @@ -73,17 +74,17 @@ public: Arg_parser( const int argc, const char * const argv[], const Option options[], const bool in_order = false ); - // Restricted constructor. Parses a single token and argument (if any) + // Restricted constructor. Parses a single token and argument (if any). Arg_parser( const char * const opt, const char * const arg, const Option options[] ); const std::string & error() const { return error_; } - // The number of arguments parsed (may be different from argc) + // The number of arguments parsed. May be different from argc. int arguments() const { return data.size(); } - // If code( i ) is 0, argument( i ) is a non-option. - // Else argument( i ) is the option's argument (or empty). + /* If code( i ) is 0, argument( i ) is a non-option. + Else argument( i ) is the option's argument (or empty). */ int code( const int i ) const { if( i >= 0 && i < arguments() ) return data[i].code; @@ -93,6 +94,6 @@ public: const std::string & argument( const int i ) const { if( i >= 0 && i < arguments() ) return data[i].argument; - else return error_; + else return empty_arg; } }; @@ -1,12 +1,12 @@ #! /bin/sh # configure script for Lzip - LZMA lossless data compressor -# Copyright (C) 2008-2019 Antonio Diaz Diaz. +# Copyright (C) 2008-2021 Antonio Diaz Diaz. # # This configure script is free software: you have unlimited permission -# to copy, distribute and modify it. +# to copy, distribute, and modify it. pkgname=lzip -pkgversion=1.21 +pkgversion=1.22 progname=lzip srctrigger=doc/${pkgname}.texi @@ -20,17 +20,16 @@ bindir='$(exec_prefix)/bin' datarootdir='$(prefix)/share' infodir='$(datarootdir)/info' mandir='$(datarootdir)/man' +build=no +check=no +installdir= CXX=g++ CPPFLAGS= CXXFLAGS='-Wall -W -O2' LDFLAGS= # checking whether we are using GNU C++. -/bin/sh -c "${CXX} --version" > /dev/null 2>&1 || - { - CXX=c++ - CXXFLAGS=-O2 - } +/bin/sh -c "${CXX} --version" > /dev/null 2>&1 || { CXX=c++ ; CXXFLAGS=-O2 ; } # Loop over all args args= @@ -42,11 +41,12 @@ while [ $# != 0 ] ; do shift # Add the argument quoted to args - args="${args} \"${option}\"" + if [ -z "${args}" ] ; then args="\"${option}\"" + else args="${args} \"${option}\"" ; fi # Split out the argument for options that take them case ${option} in - *=*) optarg=`echo ${option} | sed -e 's,^[^=]*=,,;s,/$,,'` ;; + *=*) optarg=`echo "${option}" | sed -e 's,^[^=]*=,,;s,/$,,'` ;; esac # Process the options @@ -67,6 +67,9 @@ while [ $# != 0 ] ; do echo " --datarootdir=DIR base directory for doc and data [${datarootdir}]" echo " --infodir=DIR info files directory [${infodir}]" echo " --mandir=DIR man pages directory [${mandir}]" + echo " --build build in one step without using 'make'" + echo " --check check without using 'make', implies --build" + echo " --installdir=BINDIR install without using 'make', implies --build" echo " CXX=COMPILER C++ compiler to use [${CXX}]" echo " CPPFLAGS=OPTIONS command line options for the preprocessor [${CPPFLAGS}]" echo " CXXFLAGS=OPTIONS command line options for the C++ compiler [${CXXFLAGS}]" @@ -84,6 +87,7 @@ while [ $# != 0 ] ; do --datarootdir) datarootdir=$1 ; arg2=yes ;; --infodir) infodir=$1 ; arg2=yes ;; --mandir) mandir=$1 ; arg2=yes ;; + --installdir) installdir=$1 ; arg2=yes ;; --srcdir=*) srcdir=${optarg} ;; --prefix=*) prefix=${optarg} ;; @@ -92,6 +96,9 @@ while [ $# != 0 ] ; do --datarootdir=*) datarootdir=${optarg} ;; --infodir=*) infodir=${optarg} ;; --mandir=*) mandir=${optarg} ;; + --build) build=yes ;; + --check) check=yes ; build=yes ;; + --installdir=*) installdir=${optarg} ; build=yes ;; --no-create) no_create=yes ;; CXX=*) CXX=${optarg} ;; @@ -125,7 +132,7 @@ if [ -z "${srcdir}" ] ; then if [ ! -r "${srcdir}/${srctrigger}" ] ; then srcdir=.. ; fi if [ ! -r "${srcdir}/${srctrigger}" ] ; then ## the sed command below emulates the dirname command - srcdir=`echo $0 | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + srcdir=`echo "$0" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` fi fi @@ -138,6 +145,29 @@ fi # Set srcdir to . if that's what it is. if [ "`pwd`" = "`cd "${srcdir}" ; pwd`" ] ; then srcdir=. ; fi +if [ "${build}" = yes ] ; then + objs=$(sed -e :a -e '/\\$/N; s/\\\n//; ta' "${srcdir}/Makefile.in" | \ + sed -n -e 's/^ *objs *= *//p' | sed -e 's/ \{2,\}/ /g') + for ofile in ${objs} ; do + file="${ofile%.o}.cc" ; pver= + [ "${ofile}" = main.o ] && pver=" -DPROGVERSION=\"${pkgversion}\"" + compile_command="${CXX} ${CPPFLAGS} ${CXXFLAGS}${pver} -c -o ${ofile}" + echo "${compile_command} ${srcdir}/${file}" + ${compile_command} "${srcdir}/${file}" || exit 1 + done + link_command="${CXX} ${LDFLAGS} ${CXXFLAGS} -o ${progname} ${objs}" + echo "${link_command}" ; ${link_command} || exit 1 + if [ "${check}" = yes ] ; then + "${srcdir}/testsuite/check.sh" "${srcdir}/testsuite" ${pkgversion} || exit 1 + fi + if [ -n "${installdir}" ] ; then + echo "installing ${progname} in ${installdir}" + [ -d "${installdir}" ] || mkdir -p "${installdir}" || exit 1 + cp -fp ${progname} "${installdir}/${progname}" || exit 1 + fi + exit 0 +fi + echo if [ -z "${no_create}" ] ; then echo "creating config.status" @@ -148,7 +178,7 @@ if [ -z "${no_create}" ] ; then # Run this file to recreate the current configuration. # # This script is free software: you have unlimited permission -# to copy, distribute and modify it. +# to copy, distribute, and modify it. exec /bin/sh $0 ${args} --no-create EOF @@ -170,11 +200,11 @@ echo "LDFLAGS = ${LDFLAGS}" rm -f Makefile cat > Makefile << EOF # Makefile for Lzip - LZMA lossless data compressor -# Copyright (C) 2008-2019 Antonio Diaz Diaz. +# Copyright (C) 2008-2021 Antonio Diaz Diaz. # This file was generated automatically by configure. Don't edit. # # This Makefile is free software: you have unlimited permission -# to copy, distribute and modify it. +# to copy, distribute, and modify it. pkgname = ${pkgname} pkgversion = ${pkgversion} @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 @@ -156,16 +156,15 @@ bool LZ_decoder::verify_trailer( const Pretty_print & pp ) const { if( verbosity >= 4 ) show_header( dictionary_size ); if( data_size == 0 || member_size == 0 ) - std::fputs( "no data compressed. ", stderr ); + std::fputs( "no data compressed. ", stderr ); else - std::fprintf( stderr, "%6.3f:1, %5.2f%% ratio, %5.2f%% saved. ", + std::fprintf( stderr, "%6.3f:1, %5.2f%% ratio, %5.2f%% saved. ", (double)data_size / member_size, ( 100.0 * member_size ) / data_size, 100.0 - ( ( 100.0 * member_size ) / data_size ) ); if( verbosity >= 4 ) std::fprintf( stderr, "CRC %08X, ", td_crc ); if( verbosity >= 3 ) - std::fprintf( stderr, "decompressed %9llu, compressed %8llu. ", - data_size, member_size ); + std::fprintf( stderr, "%9llu out, %8llu in. ", data_size, member_size ); } return true; } @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ class Range_decoder @@ -48,7 +48,9 @@ public: ~Range_decoder() { delete[] buffer; } bool finished() { return pos >= stream_pos && !read_block(); } - unsigned long long member_position() const { return partial_member_pos + pos; } + + unsigned long long member_position() const + { return partial_member_pos + pos; } void reset_member_position() { partial_member_pos = 0; partial_member_pos -= pos; } @@ -76,7 +78,7 @@ public: void load() { code = 0; - for( int i = 0; i < 5; ++i ) code = (code << 8) | get_byte(); + for( int i = 0; i < 5; ++i ) code = ( code << 8 ) | get_byte(); range = 0xFFFFFFFFU; code &= range; // make sure that first byte is discarded } @@ -84,7 +86,7 @@ public: void normalize() { if( range <= 0x00FFFFFFU ) - { range <<= 8; code = (code << 8) | get_byte(); } + { range <<= 8; code = ( code << 8 ) | get_byte(); } } unsigned decode( const int num_bits ) @@ -97,7 +99,7 @@ public: // symbol <<= 1; // if( code >= range ) { code -= range; symbol |= 1; } const bool bit = ( code >= range ); - symbol = ( symbol << 1 ) + bit; + symbol <<= 1; symbol += bit; code -= range & ( 0U - bit ); } return symbol; @@ -110,7 +112,8 @@ public: if( code < bound ) { range = bound; - bm.probability += (bit_model_total - bm.probability) >> bit_model_move_bits; + bm.probability += + ( bit_model_total - bm.probability ) >> bit_model_move_bits; return 0; } else @@ -124,8 +127,7 @@ public: unsigned decode_tree3( Bit_model bm[] ) { - unsigned symbol = 1; - symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); + unsigned symbol = 2 | decode_bit( bm[1] ); symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); return symbol & 7; @@ -133,8 +135,7 @@ public: unsigned decode_tree6( Bit_model bm[] ) { - unsigned symbol = 1; - symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); + unsigned symbol = 2 | decode_bit( bm[1] ); symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); @@ -158,7 +159,7 @@ public: for( int i = 0; i < num_bits; ++i ) { const unsigned bit = decode_bit( bm[model] ); - model = ( model << 1 ) + bit; + model <<= 1; model += bit; symbol |= ( bit << i ); } return symbol; @@ -167,12 +168,9 @@ public: unsigned decode_tree_reversed4( Bit_model bm[] ) { unsigned symbol = decode_bit( bm[1] ); - unsigned model = 2 + symbol; - unsigned bit = decode_bit( bm[model] ); - model = ( model << 1 ) + bit; symbol |= ( bit << 1 ); - bit = decode_bit( bm[model] ); - model = ( model << 1 ) + bit; symbol |= ( bit << 2 ); - symbol |= ( decode_bit( bm[model] ) << 3 ); + symbol += decode_bit( bm[2+symbol] ) << 1; + symbol += decode_bit( bm[4+symbol] ) << 2; + symbol += decode_bit( bm[8+symbol] ) << 3; return symbol; } @@ -183,9 +181,9 @@ public: while( symbol < 0x100 ) { const unsigned match_bit = ( match_byte <<= 1 ) & 0x100; - const unsigned bit = decode_bit( bm1[match_bit+symbol] ); - symbol = ( symbol << 1 ) | bit; - if( match_bit != bit << 8 ) + const bool bit = decode_bit( bm1[symbol+match_bit] ); + symbol <<= 1; symbol |= bit; + if( match_bit >> 8 != bit ) { while( symbol < 0x100 ) symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); @@ -1,18 +1,20 @@ -.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.46.1. -.TH LZIP "1" "January 2019" "lzip 1.21" "User Commands" +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.16. +.TH LZIP "1" "January 2021" "lzip 1.22" "User Commands" .SH NAME lzip \- reduces the size of files .SH SYNOPSIS .B lzip [\fI\,options\/\fR] [\fI\,files\/\fR] .SH DESCRIPTION -Lzip is a lossless data compressor with a user interface similar to the -one of gzip or bzip2. Lzip can compress about as fast as gzip (lzip \fB\-0\fR) -or compress most files more than bzip2 (lzip \fB\-9\fR). Decompression speed is -intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 -from a data recovery perspective. Lzip has been designed, written and -tested with great care to replace gzip and bzip2 as the standard -general\-purpose compressed format for unix\-like systems. +Lzip is a lossless data compressor with a user interface similar to the one +of gzip or bzip2. Lzip uses a simplified form of the 'Lempel\-Ziv\-Markov +chain\-Algorithm' (LZMA) stream format, chosen to maximize safety and +interoperability. Lzip can compress about as fast as gzip (lzip \fB\-0\fR) or +compress most files more than bzip2 (lzip \fB\-9\fR). Decompression speed is +intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 from +a data recovery perspective. Lzip has been designed, written, and tested +with great care to replace gzip and bzip2 as the standard general\-purpose +compressed format for unix\-like systems. .SH OPTIONS .TP \fB\-h\fR, \fB\-\-help\fR @@ -49,7 +51,7 @@ print (un)compressed file sizes set match length limit in bytes [36] .TP \fB\-o\fR, \fB\-\-output=\fR<file> -if reading standard input, write to <file> +write to <file>, keep input files .TP \fB\-q\fR, \fB\-\-quiet\fR suppress all messages @@ -87,19 +89,28 @@ to 2^29 bytes. .PP The bidimensional parameter space of LZMA can't be mapped to a linear scale optimal for all files. If your files are large, very repetitive, -etc, you may need to use the \fB\-\-dictionary\-size\fR and \fB\-\-match\-length\fR -options directly to achieve optimal performance. +etc, you may need to use the options \fB\-\-dictionary\-size\fR and \fB\-\-match\-length\fR +directly to achieve optimal performance. +.PP +To extract all the files from archive 'foo.tar.lz', use the commands +\&'tar \fB\-xf\fR foo.tar.lz' or 'lzip \fB\-cd\fR foo.tar.lz | tar \fB\-xf\fR \-'. .PP Exit status: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or invalid input file, 3 for an internal consistency error (eg, bug) which caused lzip to panic. +.PP +The ideas embodied in lzip are due to (at least) the following people: +Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the +definition of Markov chains), G.N.N. Martin (for the definition of range +encoding), Igor Pavlov (for putting all the above together in LZMA), and +Julian Seward (for bzip2's CLI). .SH "REPORTING BUGS" Report bugs to lzip\-bug@nongnu.org .br Lzip home page: http://www.nongnu.org/lzip/lzip.html .SH COPYRIGHT -Copyright \(co 2019 Antonio Diaz Diaz. +Copyright \(co 2021 Antonio Diaz Diaz. License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html> .br This is free software: you are free to change and redistribute it. diff --git a/doc/lzip.info b/doc/lzip.info index 36368c4..883ab08 100644 --- a/doc/lzip.info +++ b/doc/lzip.info @@ -11,14 +11,14 @@ File: lzip.info, Node: Top, Next: Introduction, Up: (dir) Lzip Manual *********** -This manual is for Lzip (version 1.21, 3 January 2019). +This manual is for Lzip (version 1.22, 4 January 2021). * Menu: * Introduction:: Purpose and features of lzip * Output:: Meaning of lzip's output * Invoking lzip:: Command line interface -* Quality assurance:: Design, development and testing of lzip +* Quality assurance:: Design, development, and testing of lzip * File format:: Detailed format of the compressed file * Algorithm:: How lzip compresses the data * Stream format:: Format of the LZMA stream in lzip files @@ -29,10 +29,10 @@ This manual is for Lzip (version 1.21, 3 January 2019). * Concept index:: Index of concepts - Copyright (C) 2008-2019 Antonio Diaz Diaz. + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This manual is free documentation: you have unlimited permission to -copy, distribute and modify it. + This manual is free documentation: you have unlimited permission to copy, +distribute, and modify it. File: lzip.info, Node: Introduction, Next: Output, Prev: Top, Up: Top @@ -40,103 +40,112 @@ File: lzip.info, Node: Introduction, Next: Output, Prev: Top, Up: Top 1 Introduction ************** -Lzip is a lossless data compressor with a user interface similar to the -one of gzip or bzip2. Lzip can compress about as fast as gzip (lzip -0) -or compress most files more than bzip2 (lzip -9). Decompression speed -is intermediate between gzip and bzip2. Lzip is better than gzip and -bzip2 from a data recovery perspective. +Lzip is a lossless data compressor with a user interface similar to the one +of gzip or bzip2. Lzip uses a simplified form of the 'Lempel-Ziv-Markov +chain-Algorithm' (LZMA) stream format, chosen to maximize safety and +interoperability. Lzip can compress about as fast as gzip (lzip -0) or +compress most files more than bzip2 (lzip -9). Decompression speed is +intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 from +a data recovery perspective. Lzip has been designed, written, and tested +with great care to replace gzip and bzip2 as the standard general-purpose +compressed format for unix-like systems. + + For compressing/decompressing large files on multiprocessor machines +plzip can be much faster than lzip at the cost of a slightly reduced +compression ratio. *Note plzip manual: (plzip)Top. + + For creation and manipulation of compressed tar archives tarlz can be +more efficient than using tar and plzip because tarlz is able to keep the +alignment between tar members and lzip members. *Note tarlz manual: +(tarlz)Top. The lzip file format is designed for data sharing and long-term -archiving, taking into account both data integrity and decoder -availability: +archiving, taking into account both data integrity and decoder availability: * The lzip format provides very safe integrity checking and some data - recovery means. The lziprecover program can repair bit flip errors - (one of the most common forms of data corruption) in lzip files, - and provides data recovery capabilities, including error-checked - merging of damaged copies of a file. *Note Data safety: - (lziprecover)Data safety. - - * The lzip format is as simple as possible (but not simpler). The - lzip manual provides the source code of a simple decompressor - along with a detailed explanation of how it works, so that with - the only help of the lzip manual it would be possible for a - digital archaeologist to extract the data from a lzip file long - after quantum computers eventually render LZMA obsolete. + recovery means. The program lziprecover can repair bit flip errors + (one of the most common forms of data corruption) in lzip files, and + provides data recovery capabilities, including error-checked merging + of damaged copies of a file. *Note Data safety: (lziprecover)Data + safety. + + * The lzip format is as simple as possible (but not simpler). The lzip + manual provides the source code of a simple decompressor along with a + detailed explanation of how it works, so that with the only help of the + lzip manual it would be possible for a digital archaeologist to extract + the data from a lzip file long after quantum computers eventually + render LZMA obsolete. * Additionally the lzip reference implementation is copylefted, which guarantees that it will remain free forever. A nice feature of the lzip format is that a corrupt byte is easier to -repair the nearer it is from the beginning of the file. Therefore, with -the help of lziprecover, losing an entire archive just because of a -corrupt byte near the beginning is a thing of the past. - - The member trailer stores the 32-bit CRC of the original data, the -size of the original data and the size of the member. These values, -together with the end-of-stream marker, provide a 3 factor integrity -checking which guarantees that the decompressed version of the data is -identical to the original. This guards against corruption of the -compressed data, and against undetected bugs in lzip (hopefully very -unlikely). The chances of data corruption going undetected are -microscopic. Be aware, though, that the check occurs upon -decompression, so it can only tell you that something is wrong. It -can't help you recover the original uncompressed data. - - Lzip uses the same well-defined exit status values used by bzip2, -which makes it safer than compressors returning ambiguous warning -values (like gzip) when it is used as a back end for other programs -like tar or zutils. +repair the nearer it is from the beginning of the file. Therefore, with the +help of lziprecover, losing an entire archive just because of a corrupt +byte near the beginning is a thing of the past. + + The member trailer stores the 32-bit CRC of the original data, the size +of the original data, and the size of the member. These values, together +with the end-of-stream marker, provide a 3 factor integrity checking which +guarantees that the decompressed version of the data is identical to the +original. This guards against corruption of the compressed data, and +against undetected bugs in lzip (hopefully very unlikely). The chances of +data corruption going undetected are microscopic. Be aware, though, that +the check occurs upon decompression, so it can only tell you that something +is wrong. It can't help you recover the original uncompressed data. + + Lzip uses the same well-defined exit status values used by bzip2, which +makes it safer than compressors returning ambiguous warning values (like +gzip) when it is used as a back end for other programs like tar or zutils. Lzip will automatically use for each file the largest dictionary size that does not exceed neither the file size nor the limit given. Keep in -mind that the decompression memory requirement is affected at -compression time by the choice of dictionary size limit. +mind that the decompression memory requirement is affected at compression +time by the choice of dictionary size limit. - The amount of memory required for compression is about 1 or 2 times -the dictionary size limit (1 if input file size is less than dictionary -size limit, else 2) plus 9 times the dictionary size really used. The -option '-0' is special and only requires about 1.5 MiB at most. The -amount of memory required for decompression is about 46 kB larger than -the dictionary size really used. + The amount of memory required for compression is about 1 or 2 times the +dictionary size limit (1 if input file size is less than dictionary size +limit, else 2) plus 9 times the dictionary size really used. The option +'-0' is special and only requires about 1.5 MiB at most. The amount of +memory required for decompression is about 46 kB larger than the dictionary +size really used. When compressing, lzip replaces every file given in the command line -with a compressed version of itself, with the name "original_name.lz". -When decompressing, lzip attempts to guess the name for the decompressed -file from that of the compressed file as follows: +with a compressed version of itself, with the name "original_name.lz". When +decompressing, lzip attempts to guess the name for the decompressed file +from that of the compressed file as follows: filename.lz becomes filename filename.tlz becomes filename.tar anyothername becomes anyothername.out - (De)compressing a file is much like copying or moving it; therefore -lzip preserves the access and modification dates, permissions, and, when + (De)compressing a file is much like copying or moving it; therefore lzip +preserves the access and modification dates, permissions, and, when possible, ownership of the file just as 'cp -p' does. (If the user ID or the group ID can't be duplicated, the file permission bits S_ISUID and S_ISGID are cleared). - Lzip is able to read from some types of non regular files if the -'--stdout' option is specified. + Lzip is able to read from some types of non-regular files if either the +option '-c' or the option '-o' is specified. - If no file names are specified, lzip compresses (or decompresses) -from standard input to standard output. In this case, lzip will decline -to write compressed output to a terminal, as this would be entirely -incomprehensible and therefore pointless. + Lzip will refuse to read compressed data from a terminal or write +compressed data to a terminal, as this would be entirely incomprehensible +and might leave the terminal in an abnormal state. - Lzip will correctly decompress a file which is the concatenation of -two or more compressed files. The result is the concatenation of the + Lzip will correctly decompress a file which is the concatenation of two +or more compressed files. The result is the concatenation of the corresponding decompressed files. Integrity testing of concatenated compressed files is also supported. - Lzip can produce multimember files, and lziprecover can safely -recover the undamaged members in case of file damage. Lzip can also -split the compressed output in volumes of a given size, even when -reading from standard input. This allows the direct creation of -multivolume compressed tar archives. + Lzip can produce multimember files, and lziprecover can safely recover +the undamaged members in case of file damage. Lzip can also split the +compressed output in volumes of a given size, even when reading from +standard input. This allows the direct creation of multivolume compressed +tar archives. Lzip is able to compress and decompress streams of unlimited size by -automatically creating multimember output. The members so created are -large, about 2 PiB each. +automatically creating multimember output. The members so created are large, +about 2 PiB each. File: lzip.info, Node: Output, Next: Invoking lzip, Prev: Introduction, Up: Top @@ -149,42 +158,41 @@ The output of lzip looks like this: lzip -v foo foo: 6.676:1, 14.98% ratio, 85.02% saved, 450560 in, 67493 out. - lzip -tvv foo.lz - foo.lz: 6.676:1, 14.98% ratio, 85.02% saved. ok + lzip -tvvv foo.lz + foo.lz: 6.676:1, 14.98% ratio, 85.02% saved. 450560 out, 67493 in. ok The meaning of each field is as follows: 'N:1' - The compression ratio (uncompressed_size / compressed_size), shown - as N to 1. + The compression ratio (uncompressed_size / compressed_size), shown as + N to 1. 'ratio' - The inverse compression ratio - (compressed_size / uncompressed_size), shown as a percentage. A - decimal ratio is easily obtained by moving the decimal point two - places to the left; 14.98% = 0.1498. + The inverse compression ratio (compressed_size / uncompressed_size), + shown as a percentage. A decimal ratio is easily obtained by moving the + decimal point two places to the left; 14.98% = 0.1498. 'saved' The space saved by compression (1 - ratio), shown as a percentage. 'in' - The size of the uncompressed data. When decompressing or testing, - it is shown as 'decompressed'. Note that lzip always prints the - uncompressed size before the compressed size when compressing, - decompressing, testing or listing. + Size of the input data. This is the uncompressed size when + compressing, or the compressed size when decompressing or testing. + Note that lzip always prints the uncompressed size before the + compressed size when compressing, decompressing, testing, or listing. 'out' - The size of the compressed data. When decompressing or testing, it - is shown as 'compressed'. + Size of the output data. This is the compressed size when compressing, + or the decompressed size when decompressing or testing. When decompressing or testing at verbosity level 4 (-vvvv), the -dictionary size used to compress the file and the CRC32 of the -uncompressed data are also shown. +dictionary size used to compress the file and the CRC32 of the uncompressed +data are also shown. - LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may -never have been compressed. Decompressed is used to refer to data which -have undergone the process of decompression. + LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may never +have been compressed. Decompressed is used to refer to data which have +undergone the process of decompression. File: lzip.info, Node: Invoking lzip, Next: Quality assurance, Prev: Output, Up: Top @@ -196,11 +204,13 @@ The format for running lzip is: lzip [OPTIONS] [FILES] -'-' used as a FILE argument means standard input. It can be mixed with -other FILES and is read just once, the first time it appears in the -command line. +If no file names are specified, lzip compresses (or decompresses) from +standard input to standard output. A hyphen '-' used as a FILE argument +means standard input. It can be mixed with other FILES and is read just +once, the first time it appears in the command line. - lzip supports the following options: + lzip supports the following options: *Note Argument syntax: +(arg_parser)Argument syntax. '-h' '--help' @@ -208,38 +218,39 @@ command line. '-V' '--version' - Print the version number of lzip on the standard output and exit. - This version number should be included in all bug reports. + Print the version number of lzip on the standard output and exit. This + version number should be included in all bug reports. '-a' '--trailing-error' Exit with error status 2 if any remaining input is detected after - decompressing the last member. Such remaining input is usually - trailing garbage that can be safely ignored. *Note - concat-example::. + decompressing the last member. Such remaining input is usually trailing + garbage that can be safely ignored. *Note concat-example::. '-b BYTES' '--member-size=BYTES' - When compressing, set the member size limit to BYTES. A small - member size may degrade compression ratio, so use it only when - needed. Valid values range from 100 kB to 2 PiB. Defaults to - 2 PiB. + When compressing, set the member size limit to BYTES. It is advisable + to keep members smaller than RAM size so that they can be repaired with + lziprecover in case of corruption. A small member size may degrade + compression ratio, so use it only when needed. Valid values range from + 100 kB to 2 PiB. Defaults to 2 PiB. '-c' '--stdout' - Compress or decompress to standard output; keep input files - unchanged. If compressing several files, each file is compressed - independently. This option is needed when reading from a named - pipe (fifo) or from a device. Use it also to recover as much of - the decompressed data as possible when decompressing a corrupt - file. + Compress or decompress to standard output; keep input files unchanged. + If compressing several files, each file is compressed independently. + (The output consists of a sequence of independently compressed + members). This option (or '-o') is needed when reading from a named + pipe (fifo) or from a device. Use it also to recover as much of the + decompressed data as possible when decompressing a corrupt file. '-c' + overrides '-o' and '-S'. '-c' has no effect when testing or listing. '-d' '--decompress' - Decompress the specified files. If a file does not exist or can't - be opened, lzip continues decompressing the rest of the files. If - a file fails to decompress, or is a terminal, lzip exits - immediately without decompressing the rest of the files. + Decompress the files specified. If a file does not exist or can't be + opened, lzip continues decompressing the rest of the files. If a file + fails to decompress, or is a terminal, lzip exits immediately without + decompressing the rest of the files. '-f' '--force' @@ -247,45 +258,56 @@ command line. '-F' '--recompress' - When compressing, force re-compression of files whose name already - has the '.lz' or '.tlz' suffix. + When compressing, force re-compression of files whose name already has + the '.lz' or '.tlz' suffix. '-k' '--keep' - Keep (don't delete) input files during compression or - decompression. + Keep (don't delete) input files during compression or decompression. '-l' '--list' - Print the uncompressed size, compressed size and percentage saved - of the specified files. Trailing data are ignored. The values - produced are correct even for multimember files. If more than one - file is given, a final line containing the cumulative sizes is - printed. With '-v', the dictionary size, the number of members in - the file, and the amount of trailing data (if any) are also - printed. With '-vv', the positions and sizes of each member in - multimember files are also printed. '-lq' can be used to verify - quickly (without decompressing) the structural integrity of the - specified files. (Use '--test' to verify the data integrity). - '-alq' additionally verifies that none of the specified files - contain trailing data. + Print the uncompressed size, compressed size, and percentage saved of + the files specified. Trailing data are ignored. The values produced + are correct even for multimember files. If more than one file is + given, a final line containing the cumulative sizes is printed. With + '-v', the dictionary size, the number of members in the file, and the + amount of trailing data (if any) are also printed. With '-vv', the + positions and sizes of each member in multimember files are also + printed. + + '-lq' can be used to verify quickly (without decompressing) the + structural integrity of the files specified. (Use '--test' to verify + the data integrity). '-alq' additionally verifies that none of the + files specified contain trailing data. '-m BYTES' '--match-length=BYTES' - When compressing, set the match length limit in bytes. After a - match this long is found, the search is finished. Valid values - range from 5 to 273. Larger values usually give better compression - ratios but longer compression times. + When compressing, set the match length limit in bytes. After a match + this long is found, the search is finished. Valid values range from 5 + to 273. Larger values usually give better compression ratios but longer + compression times. '-o FILE' '--output=FILE' - When reading from standard input and '--stdout' has not been - specified, use 'FILE' as the virtual name of the uncompressed - file. This produces a file named 'FILE' when decompressing, or a - file named 'FILE.lz' when compressing. A second '.lz' extension is - not added if 'FILE' already ends in '.lz' or '.tlz'. When - compressing and splitting the output in volumes, several files - named 'FILE00001.lz', 'FILE00002.lz', etc, are created. + If '-c' has not been also specified, write the (de)compressed output to + FILE; keep input files unchanged. If compressing several files, each + file is compressed independently. (The output consists of a sequence of + independently compressed members). This option (or '-c') is needed when + reading from a named pipe (fifo) or from a device. '-o -' is + equivalent to '-c'. '-o' has no effect when testing or listing. + + In order to keep backward compatibility with lzip versions prior to + 1.22, when compressing from standard input and no other file names are + given, the extension '.lz' is appended to FILE unless it already ends + in '.lz' or '.tlz'. This feature will be removed in a future version + of lzip. Meanwhile, redirection may be used instead of '-o' to write + the compressed output to a file without the extension '.lz' in its + name: 'lzip < file > foo'. + + When compressing and splitting the output in volumes, FILE is used as + a prefix, and several files named 'FILE00001.lz', 'FILE00002.lz', etc, + are created. In this case, only one input file is allowed. '-q' '--quiet' @@ -293,39 +315,38 @@ command line. '-s BYTES' '--dictionary-size=BYTES' - When compressing, set the dictionary size limit in bytes. Lzip - will use for each file the largest dictionary size that does not - exceed neither the file size nor this limit. Valid values range - from 4 KiB to 512 MiB. Values 12 to 29 are interpreted as powers - of two, meaning 2^12 to 2^29 bytes. Dictionary sizes are quantized - so that they can be coded in just one byte (*note - coded-dict-size::). If the specified size does not match one of - the valid sizes, it will be rounded upwards by adding up to - (BYTES / 8) to it. - - For maximum compression you should use a dictionary size limit as - large as possible, but keep in mind that the decompression memory - requirement is affected at compression time by the choice of - dictionary size limit. + When compressing, set the dictionary size limit in bytes. Lzip will use + for each file the largest dictionary size that does not exceed neither + the file size nor this limit. Valid values range from 4 KiB to + 512 MiB. Values 12 to 29 are interpreted as powers of two, meaning + 2^12 to 2^29 bytes. Dictionary sizes are quantized so that they can be + coded in just one byte (*note coded-dict-size::). If the size specified + does not match one of the valid sizes, it will be rounded upwards by + adding up to (BYTES / 8) to it. + + For maximum compression you should use a dictionary size limit as large + as possible, but keep in mind that the decompression memory requirement + is affected at compression time by the choice of dictionary size limit. '-S BYTES' '--volume-size=BYTES' - When compressing, split the compressed output into several volume - files with names 'original_name00001.lz', 'original_name00002.lz', - etc, and set the volume size limit to BYTES. Input files are kept - unchanged. Each volume is a complete, maybe multimember, lzip - file. A small volume size may degrade compression ratio, so use it - only when needed. Valid values range from 100 kB to 4 EiB. + When compressing, and '-c' has not been also specified, split the + compressed output into several volume files with names + 'original_name00001.lz', 'original_name00002.lz', etc, and set the + volume size limit to BYTES. Input files are kept unchanged. Each + volume is a complete, maybe multimember, lzip file. A small volume + size may degrade compression ratio, so use it only when needed. Valid + values range from 100 kB to 4 EiB. '-t' '--test' - Check integrity of the specified files, but don't decompress them. - This really performs a trial decompression and throws away the - result. Use it together with '-v' to see information about the - files. If a file fails the test, does not exist, can't be opened, - or is a terminal, lzip continues checking the rest of the files. A - final diagnostic is shown at verbosity level 1 or higher if any - file fails the test when testing multiple files. + Check integrity of the files specified, but don't decompress them. This + really performs a trial decompression and throws away the result. Use + it together with '-v' to see information about the files. If a file + fails the test, does not exist, can't be opened, or is a terminal, lzip + continues checking the rest of the files. A final diagnostic is shown + at verbosity level 1 or higher if any file fails the test when testing + multiple files. '-v' '--verbose' @@ -333,27 +354,27 @@ command line. When compressing, show the compression ratio and size for each file processed. When decompressing or testing, further -v's (up to 4) increase the - verbosity level, showing status, compression ratio, dictionary - size, trailer contents (CRC, data size, member size), and up to 6 - bytes of trailing data (if any) both in hexadecimal and as a - string of printable ASCII characters. + verbosity level, showing status, compression ratio, dictionary size, + trailer contents (CRC, data size, member size), and up to 6 bytes of + trailing data (if any) both in hexadecimal and as a string of printable + ASCII characters. Two or more '-v' options show the progress of (de)compression. '-0 .. -9' - Compression level. Set the compression parameters (dictionary size - and match length limit) as shown in the table below. The default - compression level is '-6', equivalent to '-s8MiB -m36'. Note that - '-9' can be much slower than '-0'. These options have no effect - when decompressing, testing or listing. + Compression level. Set the compression parameters (dictionary size and + match length limit) as shown in the table below. The default + compression level is '-6', equivalent to '-s8MiB -m36'. Note that '-9' + can be much slower than '-0'. These options have no effect when + decompressing, testing, or listing. - The bidimensional parameter space of LZMA can't be mapped to a - linear scale optimal for all files. If your files are large, very - repetitive, etc, you may need to use the '--dictionary-size' and - '--match-length' options directly to achieve optimal performance. + The bidimensional parameter space of LZMA can't be mapped to a linear + scale optimal for all files. If your files are large, very repetitive, + etc, you may need to use the options '--dictionary-size' and + '--match-length' directly to achieve optimal performance. - If several compression levels or '-s' or '-m' options are given, - the last setting is used. For example '-9 -s64MiB' is equivalent - to '-s64MiB -m273' + If several compression levels or '-s' or '-m' options are given, the + last setting is used. For example '-9 -s64MiB' is equivalent to + '-s64MiB -m273' Level Dictionary size (-s) Match length limit (-m) -0 64 KiB 16 bytes @@ -372,11 +393,11 @@ command line. Aliases for GNU gzip compatibility. '--loose-trailing' - When decompressing, testing or listing, allow trailing data whose - first bytes are so similar to the magic bytes of a lzip header - that they can be confused with a corrupt header. Use this option - if a file triggers a "corrupt header" error and the cause is not - indeed a corrupt header. + When decompressing, testing, or listing, allow trailing data whose + first bytes are so similar to the magic bytes of a lzip header that + they can be confused with a corrupt header. Use this option if a file + triggers a "corrupt header" error and the cause is not indeed a + corrupt header. Numbers given as arguments to options may be followed by a multiplier @@ -395,83 +416,87 @@ Z zettabyte (10^21) | Zi zebibyte (2^70) Y yottabyte (10^24) | Yi yobibyte (2^80) - Exit status: 0 for a normal exit, 1 for environmental problems (file -not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or -invalid input file, 3 for an internal consistency error (eg, bug) which -caused lzip to panic. + Exit status: 0 for a normal exit, 1 for environmental problems (file not +found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or invalid +input file, 3 for an internal consistency error (eg, bug) which caused lzip +to panic. File: lzip.info, Node: Quality assurance, Next: File format, Prev: Invoking lzip, Up: Top -4 Design, development and testing of lzip -***************************************** +4 Design, development, and testing of lzip +****************************************** -There are two ways of constructing a software design: One way is to make -it so simple that there are obviously no deficiencies and the other way -is to make it so complicated that there are no obvious deficiencies. The -first method is far more difficult. +There are two ways of constructing a software design: One way is to make it +so simple that there are obviously no deficiencies and the other way is to +make it so complicated that there are no obvious deficiencies. The first +method is far more difficult. -- C.A.R. Hoare - Lzip has been designed, written and tested with great care to replace + Lzip is developed by volunteers who lack the resources required for +extensive testing in all circumstances. It is up to you to test lzip before +using it in mission-critical applications. However, a compressor like lzip +is not a toy, and maintaining it is not a hobby. Many people's data depend +on it. Therefore the lzip file format has been reviewed carefully and is +believed to be free from negligent design errors. + + Lzip has been designed, written, and tested with great care to replace gzip and bzip2 as the standard general-purpose compressed format for -unix-like systems. This chapter describes the lessons learned from -these previous formats, and their application to the design of lzip. +unix-like systems. This chapter describes the lessons learned from these +previous formats, and their application to the design of lzip. 4.1 Format design ================= -When gzip was designed in 1992, computers and operating systems were -much less capable than they are today. Gzip tried to work around some of -those limitations, like 8.3 file names, with additional fields in its -file format. +When gzip was designed in 1992, computers and operating systems were much +less capable than they are today. The designers of gzip tried to work around +some of those limitations, like 8.3 file names, with additional fields in +the file format. - Today those limitations have mostly disappeared, and the format of -gzip has proved to be unnecessarily complicated. It includes fields -that were never used, others that have lost their usefulness, and -finally others that have become too limited. + Today those limitations have mostly disappeared, and the format of gzip +has proved to be unnecessarily complicated. It includes fields that were +never used, others that have lost their usefulness, and finally others that +have become too limited. - Bzip2 was designed 5 years later, and its format is simpler than the -one of gzip. + Bzip2 was designed 5 years later, and its format is simpler than the one +of gzip. - Probably the worst defect of the gzip format from the point of view -of data safety is the variable size of its header. If the byte at -offset 3 (flags) of a gzip member gets corrupted, it may become -difficult to recover the data, even if the compressed blocks are -intact, because it can't be known with certainty where the compressed -blocks begin. + Probably the worst defect of the gzip format from the point of view of +data safety is the variable size of its header. If the byte at offset 3 +(flags) of a gzip member gets corrupted, it may become difficult to recover +the data, even if the compressed blocks are intact, because it can't be +known with certainty where the compressed blocks begin. By contrast, the header of a lzip member has a fixed length of 6. The -LZMA stream in a lzip member always starts at offset 6, making it -trivial to recover the data even if the whole header becomes corrupt. - - Bzip2 also provides a header of fixed length and marks the begin and -end of each compressed block with six magic bytes, making it possible to -find the compressed blocks even in case of file damage. But bzip2 does -not store the size of each compressed block, as lzip does. - - Lzip provides better data recovery capabilities than any other -gzip-like compressor because its format has been designed from the -beginning to be simple and safe. It also helps that the LZMA data -stream as used by lzip is extraordinarily safe. It provides embedded -error detection. Any distance larger than the dictionary size acts as a +LZMA stream in a lzip member always starts at offset 6, making it trivial to +recover the data even if the whole header becomes corrupt. + + Bzip2 also provides a header of fixed length and marks the begin and end +of each compressed block with six magic bytes, making it possible to find +the compressed blocks even in case of file damage. But bzip2 does not store +the size of each compressed block, as lzip does. + + Lziprecover is able to provide unique data recovery capabilities because +the lzip format is extraordinarily safe. The simple and safe design of the +file format complements the embedded error detection provided by the LZMA +data stream. Any distance larger than the dictionary size acts as a forbidden symbol, allowing the decompressor to detect the approximate position of errors, and leaving very little work for the check sequence -(CRC and data sizes) in the detection of errors. Lzip is usually able -to detect all possible bit flips in the compressed data without -resorting to the check sequence. It would be difficult to write an -automatic recovery tool like lziprecover for the gzip format. And, as -far as I know, it has never been written. +(CRC and data sizes) in the detection of errors. Lzip is usually able to +detect all possible bit flips in the compressed data without resorting to +the check sequence. It would be difficult to write an automatic recovery +tool like lziprecover for the gzip format. And, as far as I know, it has +never been written. Lzip, like gzip and bzip2, uses a CRC32 to check the integrity of the -decompressed data because it provides optimal accuracy in the detection -of errors up to a compressed size of about 16 GiB, a size larger than -that of most files. In the case of lzip, the additional detection -capability of the decompressor reduces the probability of undetected -errors about four million times more, resulting in a combined integrity -checking optimally accurate for any member size produced by lzip. -Preliminary results suggest that the lzip format is safe enough to be -used in critical safety avionics systems. +decompressed data because it provides optimal accuracy in the detection of +errors up to a compressed size of about 16 GiB, a size larger than that of +most files. In the case of lzip, the additional detection capability of the +decompressor reduces the probability of undetected errors several million +times more, resulting in a combined integrity checking optimally accurate +for any member size produced by lzip. Preliminary results suggest that the +lzip format is safe enough to be used in critical safety avionics systems. The lzip format is designed for long-term archiving. Therefore it excludes any unneeded features that may interfere with the future @@ -482,64 +507,63 @@ extraction of the decompressed data. --------------------------------------------------- 'Multiple algorithms' - Gzip provides a CM (Compression Method) field that has never been - used because it is a bad idea to begin with. New compression - methods may require additional fields, making it impossible to - implement new methods and, at the same time, keep the same format. - This field does not solve the problem of format proliferation; it - just makes the problem less obvious. + Gzip provides a CM (Compression Method) field that has never been used + because it is a bad idea to begin with. New compression methods may + require additional fields, making it impossible to implement new + methods and, at the same time, keep the same format. This field does + not solve the problem of format proliferation; it just makes the + problem less obvious. 'Optional fields in header' - Unless special precautions are taken, optional fields are - generally a bad idea because they produce a header of variable - size. The gzip header has 2 fields that, in addition to being - optional, are zero-terminated. This means that if any byte inside - the field gets zeroed, or if the terminating zero gets altered, - gzip won't be able to find neither the header CRC nor the - compressed blocks. + Unless special precautions are taken, optional fields are generally a + bad idea because they produce a header of variable size. The gzip + header has 2 fields that, in addition to being optional, are + zero-terminated. This means that if any byte inside the field gets + zeroed, or if the terminating zero gets altered, gzip won't be able to + find neither the header CRC nor the compressed blocks. 'Optional CRC for the header' - Using an optional CRC for the header is not only a bad idea, it is - an error; it circumvents the HD of the CRC and may prevent the - extraction of perfectly good data. For example, if the CRC is used - and the bit enabling it is reset by a bit flip, the header will - appear to be intact (in spite of being corrupt) while the - compressed blocks will appear to be totally unrecoverable (in - spite of being intact). Very misleading indeed. + Using an optional CRC for the header is not only a bad idea, it is an + error; it circumvents the Hamming distance (HD) of the CRC and may + prevent the extraction of perfectly good data. For example, if the CRC + is used and the bit enabling it is reset by a bit flip, the header + will appear to be intact (in spite of being corrupt) while the + compressed blocks will appear to be totally unrecoverable (in spite of + being intact). Very misleading indeed. 'Metadata' - The gzip format stores some metadata, like the modification time - of the original file or the operating system on which compression - took place. This complicates reproducible compression (obtaining - identical compressed output from identical input). + The gzip format stores some metadata, like the modification time of the + original file or the operating system on which compression took place. + This complicates reproducible compression (obtaining identical + compressed output from identical input). 4.1.2 Lzip format improvements over gzip and bzip2 -------------------------------------------------- '64-bit size field' - Probably the most frequently reported shortcoming of the gzip - format is that it only stores the least significant 32 bits of the + Probably the most frequently reported shortcoming of the gzip format + is that it only stores the least significant 32 bits of the uncompressed size. The size of any file larger than 4 GiB gets truncated. Bzip2 does not store the uncompressed size of the file. The lzip format provides a 64-bit field for the uncompressed size. - Additionally, lzip produces multimember output automatically when - the size is too large for a single member, allowing for an - unlimited uncompressed size. + Additionally, lzip produces multimember output automatically when the + size is too large for a single member, allowing for an unlimited + uncompressed size. 'Distributed index' - The lzip format provides a distributed index that, among other - things, helps plzip to decompress several times faster than pigz - and helps lziprecover do its job. Neither the gzip format nor the - bzip2 format do provide an index. + The lzip format provides a distributed index that, among other things, + helps plzip to decompress several times faster than pigz and helps + lziprecover do its job. Neither the gzip format nor the bzip2 format + do provide an index. A distributed index is safer and more scalable than a monolithic - index. The monolithic index introduces a single point of failure - in the compressed file and may limit the number of members or the - total uncompressed size. + index. The monolithic index introduces a single point of failure in + the compressed file and may limit the number of members or the total + uncompressed size. 4.2 Quality of implementation @@ -547,42 +571,41 @@ extraction of the decompressed data. 'Accurate and robust error detection' The lzip format provides 3 factor integrity checking and the - decompressors report mismatches in each factor separately. This - way if just one byte in one factor fails but the other two factors - match the data, it probably means that the data are intact and the - corruption just affects the mismatching factor (CRC or data size) - in the check sequence. + decompressors report mismatches in each factor separately. This way if + just one byte in one factor fails but the other two factors match the + data, it probably means that the data are intact and the corruption + just affects the mismatching factor (CRC or data size) in the check + sequence. 'Multiple implementations' Just like the lzip format provides 3 factor protection against undetected data corruption, the development methodology of the lzip - family of compressors provides 3 factor protection against - undetected programming errors. - - Three related but independent compressor implementations, lzip, - clzip and minilzip/lzlib, are developed concurrently. Every stable - release of any of them is subjected to a hundred hours of - intensive testing to verify that it produces identical output to - the other two. This guarantees that all three implement the same - algorithm, and makes it unlikely that any of them may contain - serious undiscovered errors. In fact, no errors have been - discovered in lzip since 2009. - - Additionally, the three implementations have been extensively - tested with unzcrash, valgrind and 'american fuzzy lop' without - finding a single vulnerability or false negative. *Note Unzcrash: + family of compressors provides 3 factor protection against undetected + programming errors. + + Three related but independent compressor implementations, lzip, clzip, + and minilzip/lzlib, are developed concurrently. Every stable release + of any of them is tested to verify that it produces identical output + to the other two. This guarantees that all three implement the same + algorithm, and makes it unlikely that any of them may contain serious + undiscovered errors. In fact, no errors have been discovered in lzip + since 2009. + + Additionally, the three implementations have been extensively tested + with unzcrash, valgrind, and 'american fuzzy lop' without finding a + single vulnerability or false negative. *Note Unzcrash: (lziprecover)Unzcrash. 'Dictionary size' - Lzip automatically adapts the dictionary size to the size of each - file. In addition to reducing the amount of memory required for - decompression, this feature also minimizes the probability of - being affected by RAM errors during compression. + Lzip automatically adapts the dictionary size to the size of each file. + In addition to reducing the amount of memory required for + decompression, this feature also minimizes the probability of being + affected by RAM errors during compression. 'Exit status' Returning a warning status of 2 is a design flaw of compress that - leaked into the design of gzip. Both bzip2 and lzip are free from - this flaw. + leaked into the design of gzip. Both bzip2 and lzip are free from this + flaw. @@ -597,11 +620,13 @@ when there is no longer anything to take away. In the diagram below, a box like this: + +---+ | | <-- the vertical bars might be missing +---+ represents one byte; a box like this: + +==============+ | | +==============+ @@ -610,10 +635,11 @@ when there is no longer anything to take away. A lzip file consists of a series of "members" (compressed data sets). -The members simply appear one after another in the file, with no -additional information before, between, or after them. +The members simply appear one after another in the file, with no additional +information before, between, or after them. Each member has the following structure: + +--+--+--+--+----+----+=============+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ID string | VN | DS | LZMA stream | CRC32 | Data size | Member size | +--+--+--+--+----+----+=============+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -621,17 +647,16 @@ additional information before, between, or after them. All multibyte values are stored in little endian order. 'ID string (the "magic" bytes)' - A four byte string, identifying the lzip format, with the value - "LZIP" (0x4C, 0x5A, 0x49, 0x50). + A four byte string, identifying the lzip format, with the value "LZIP" + (0x4C, 0x5A, 0x49, 0x50). 'VN (version number, 1 byte)' - Just in case something needs to be modified in the future. 1 for - now. + Just in case something needs to be modified in the future. 1 for now. 'DS (coded dictionary size, 1 byte)' The dictionary size is calculated by taking a power of 2 (the base - size) and subtracting from it a fraction between 0/16 and 7/16 of - the base size. + size) and subtracting from it a fraction between 0/16 and 7/16 of the + base size. Bits 4-0 contain the base 2 logarithm of the base size (12 to 29). Bits 7-5 contain the numerator of the fraction (0 to 7) to subtract from the base size to obtain the dictionary size. @@ -640,20 +665,20 @@ additional information before, between, or after them. 'LZMA stream' The LZMA stream, finished by an end of stream marker. Uses default - values for encoder properties. *Note Stream format::, for a - complete description. + values for encoder properties. *Note Stream format::, for a complete + description. 'CRC32 (4 bytes)' - CRC of the uncompressed original data. + Cyclic Redundancy Check (CRC) of the uncompressed original data. 'Data size (8 bytes)' Size of the uncompressed original data. 'Member size (8 bytes)' - Total size of the member, including header and trailer. This field - acts as a distributed index, allows the verification of stream - integrity, and facilitates safe recovery of undamaged members from - multimember files. + Total size of the member, including header and trailer. This field acts + as a distributed index, allows the verification of stream integrity, + and facilitates safe recovery of undamaged members from multimember + files. @@ -664,27 +689,30 @@ File: lzip.info, Node: Algorithm, Next: Stream format, Prev: File format, Up In spite of its name (Lempel-Ziv-Markov chain-Algorithm), LZMA is not a concrete algorithm; it is more like "any algorithm using the LZMA coding -scheme". For example, the option '-0' of lzip uses the scheme in almost -the simplest way possible; issuing the longest match it can find, or a -literal byte if it can't find a match. Inversely, a much more elaborated -way of finding coding sequences of minimum size than the one currently -used by lzip could be developed, and the resulting sequence could also -be coded using the LZMA coding scheme. - - Lzip currently implements two variants of the LZMA algorithm; fast -(used by option '-0') and normal (used by all other compression levels). - - The high compression of LZMA comes from combining two basic, -well-proven compression ideas: sliding dictionaries (LZ77/78) and -markov models (the thing used by every compression algorithm that uses -a range encoder or similar order-0 entropy coder as its last stage) -with segregation of contexts according to what the bits are used for. - - Lzip is a two stage compressor. The first stage is a Lempel-Ziv -coder, which reduces redundancy by translating chunks of data to their +scheme". LZMA compression consists in describing the uncompressed data as a +succession of coding sequences from the set shown in Section 'What is +coded' (*note what-is-coded::), and then encoding them using a range +encoder. For example, the option '-0' of lzip uses the scheme in almost the +simplest way possible; issuing the longest match it can find, or a literal +byte if it can't find a match. Inversely, a much more elaborated way of +finding coding sequences of minimum size than the one currently used by +lzip could be developed, and the resulting sequence could also be coded +using the LZMA coding scheme. + + Lzip currently implements two variants of the LZMA algorithm; fast (used +by option '-0') and normal (used by all other compression levels). + + The high compression of LZMA comes from combining two basic, well-proven +compression ideas: sliding dictionaries (LZ77/78) and markov models (the +thing used by every compression algorithm that uses a range encoder or +similar order-0 entropy coder as its last stage) with segregation of +contexts according to what the bits are used for. + + Lzip is a two stage compressor. The first stage is a Lempel-Ziv coder, +which reduces redundancy by translating chunks of data to their corresponding distance-length pairs. The second stage is a range encoder -that uses a different probability model for each type of data; -distances, lengths, literal bytes, etc. +that uses a different probability model for each type of data; distances, +lengths, literal bytes, etc. Here is how it works, step by step: @@ -696,15 +724,15 @@ bytes to which the match finder can refer to. 3) The main encoder advances to the next byte in the input data and calls the match finder. - 4) The match finder fills an array with the minimum distances before -the current byte where a match of a given length can be found. + 4) The match finder fills an array with the minimum distances before the +current byte where a match of a given length can be found. 5) Go back to step 3 until a sequence (formed of pairs, repeated -distances and literal bytes) of minimum price has been formed. Where the +distances, and literal bytes) of minimum price has been formed. Where the price represents the number of output bits produced. - 6) The range encoder encodes the sequence produced by the main -encoder and sends the produced bytes to the output stream. + 6) The range encoder encodes the sequence produced by the main encoder +and sends the bytes produced to the output stream. 7) Go back to step 3 until the input data are finished or until the member or volume size limits are reached. @@ -716,11 +744,17 @@ member or volume size limits are reached. 10) If there are more data to compress, go back to step 1. + During compression, lzip reads data in large blocks (one dictionary size +at a time). Therefore it may block for up to tens of seconds any process +feeding data to it through a pipe. This is normal. The blocking intervals +get longer with higher compression levels because dictionary size increases +(and compression speed decreases) with compression level. + The ideas embodied in lzip are due to (at least) the following people: -Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for -the definition of Markov chains), G.N.N. Martin (for the definition of -range encoding), Igor Pavlov (for putting all the above together in -LZMA), and Julian Seward (for bzip2's CLI). +Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the +definition of Markov chains), G.N.N. Martin (for the definition of range +encoding), Igor Pavlov (for putting all the above together in LZMA), and +Julian Seward (for bzip2's CLI). File: lzip.info, Node: Stream format, Next: Trailing data, Prev: Algorithm, Up: Top @@ -728,116 +762,118 @@ File: lzip.info, Node: Stream format, Next: Trailing data, Prev: Algorithm, 7 Format of the LZMA stream in lzip files ***************************************** -The LZMA algorithm has three parameters, called "special LZMA -properties", to adjust it for some kinds of binary data. These -parameters are; 'literal_context_bits' (with a default value of 3), -'literal_pos_state_bits' (with a default value of 0), and -'pos_state_bits' (with a default value of 2). As a general purpose -compressor, lzip only uses the default values for these parameters. In -particular 'literal_pos_state_bits' has been optimized away and does -not even appear in the code. - - Lzip also finishes the LZMA stream with an "End Of Stream" marker -(the distance-length pair 0xFFFFFFFFU, 2), which in conjunction with the -"member size" field in the member trailer allows the verification of -stream integrity. The LZMA stream in lzip files always has these two -features (default properties and EOS marker) and is referred to in this -document as LZMA-302eos or LZMA-lzip. +Lzip uses a simplified form of the LZMA stream format chosen to maximize +safety and interoperability. + + The LZMA algorithm has three parameters, called "special LZMA +properties", to adjust it for some kinds of binary data. These parameters +are; 'literal_context_bits' (with a default value of 3), +'literal_pos_state_bits' (with a default value of 0), and 'pos_state_bits' +(with a default value of 2). As a general purpose compressor, lzip only +uses the default values for these parameters. In particular +'literal_pos_state_bits' has been optimized away and does not even appear +in the code. + + Lzip finishes the LZMA stream with an "End Of Stream" (EOS) marker (the +distance-length pair 0xFFFFFFFFU, 2), which in conjunction with the 'member +size' field in the member trailer allows the verification of stream +integrity. The LZMA stream in lzip files always has these two features +(default properties and EOS marker) and is referred to in this document as +LZMA-302eos. The EOS marker is the only marker allowed in lzip files. The second stage of LZMA is a range encoder that uses a different probability model for each type of symbol; distances, lengths, literal bytes, etc. Range encoding conceptually encodes all the symbols of the message into one number. Unlike Huffman coding, which assigns to each -symbol a bit-pattern and concatenates all the bit-patterns together, -range encoding can compress one symbol to less than one bit. Therefore -the compressed data produced by a range encoder can't be split in pieces -that could be individually described. +symbol a bit-pattern and concatenates all the bit-patterns together, range +encoding can compress one symbol to less than one bit. Therefore the +compressed data produced by a range encoder can't be split in pieces that +could be described individually. It seems that the only way of describing the LZMA-302eos stream is -describing the algorithm that decodes it. And given the many details -about the range decoder that need to be described accurately, the source -code of a real decoder seems the only appropriate reference to use. +describing the algorithm that decodes it. And given the many details about +the range decoder that need to be described accurately, the source code of +a real decoder seems the only appropriate reference to use. - What follows is a description of the decoding algorithm for -LZMA-302eos streams using as reference the source code of "lzd", an -educational decompressor for lzip files which can be downloaded from -the lzip download directory. The source code of lzd is included in -appendix A. *Note Reference source code::. + What follows is a description of the decoding algorithm for LZMA-302eos +streams using as reference the source code of "lzd", an educational +decompressor for lzip files which can be downloaded from the lzip download +directory. The source code of lzd is included in appendix A. *Note +Reference source code::. 7.1 What is coded ================= -The LZMA stream includes literals, matches and repeated matches (matches -reusing a recently used distance). There are 7 different coding -sequences: +The LZMA stream includes literals, matches, and repeated matches (matches +reusing a recently used distance). There are 7 different coding sequences: -Bit sequence Name Description ------------------------------------------------------------------------- -0 + byte literal literal byte -1 + 0 + len + dis match distance-length pair -1 + 1 + 0 + 0 shortrep 1 byte match at latest used distance -1 + 1 + 0 + 1 + len rep0 len bytes match at latest used - distance -1 + 1 + 1 + 0 + len rep1 len bytes match at second latest - used distance -1 + 1 + 1 + 1 + 0 + len rep2 len bytes match at third latest used - distance -1 + 1 + 1 + 1 + 1 + len rep3 len bytes match at fourth latest - used distance +Bit sequence Name Description +----------------------------------------------------------------------------- +0 + byte literal literal byte +1 + 0 + len + dis match distance-length pair +1 + 1 + 0 + 0 shortrep 1 byte match at latest used distance +1 + 1 + 0 + 1 + len rep0 len bytes match at latest used distance +1 + 1 + 1 + 0 + len rep1 len bytes match at second latest used + distance +1 + 1 + 1 + 1 + 0 + len rep2 len bytes match at third latest used + distance +1 + 1 + 1 + 1 + 1 + len rep3 len bytes match at fourth latest used + distance - In the following tables, multibit sequences are coded in normal -order, from MSB to LSB, except where noted otherwise. + In the following tables, multibit sequences are coded in normal order, +from most significant bit (MSB) to least significant bit (LSB), except +where noted otherwise. Lengths (the 'len' in the table above) are coded as follows: -Bit sequence Description ------------------------------------------------------------------------- -0 + 3 bits lengths from 2 to 9 -1 + 0 + 3 bits lengths from 10 to 17 -1 + 1 + 8 bits lengths from 18 to 273 +Bit sequence Description +---------------------------------------------------------------------------- +0 + 3 bits lengths from 2 to 9 +1 + 0 + 3 bits lengths from 10 to 17 +1 + 1 + 8 bits lengths from 18 to 273 The coding of distances is a little more complicated, so I'll begin explaining a simpler version of the encoding. - Imagine you need to code a number from 0 to 2^32 - 1, and you want -to do it in a way that produces shorter codes for the smaller numbers. -You may first send the position of the most significant bit that is set -to 1, which you may find by making a bit scan from the left (from the -MSB). A position of 0 means that the number is 0 (no bit is set), 1 -means the LSB is the first bit set (the number is 1), and 32 means the -MSB is set (i.e., the number is >= 0x80000000). Let's call this bit -position a "slot". Then, if slot is > 1, you send the remaining -slot - 1 bits. Let's call these bits "direct_bits" because they are -coded directly by value instead of indirectly by position. - - The inconvenient of this simple method is that it needs 6 bits to -code the slot, but it just uses 33 of the 64 possible values, wasting -almost half of the codes. - - The intelligent trick of LZMA is that it encodes the position of the -most significant bit set, along with the value of the next bit, in the -same 6 bits that would take to encode the position alone. This seems to -need 66 slots (2 * position + next_bit), but for slots 0 and 1 there is -no next bit, so the number of needed slots is 64 (0 to 63). + Imagine you need to encode a number from 0 to 2^32 - 1, and you want to +do it in a way that produces shorter codes for the smaller numbers. You may +first encode the position of the most significant bit that is set to 1, +which you may find by making a bit scan from the left (from the MSB). A +position of 0 means that the number is 0 (no bit is set), 1 means the LSB is +the first bit set (the number is 1), and 32 means the MSB is set (i.e., the +number is >= 0x80000000). Then, if the position is >= 2, you encode the +remaining position - 1 bits. Let's call these bits "direct_bits" because +they are coded directly by value instead of indirectly by position. + + The inconvenient of this simple method is that it needs 6 bits to encode +the position, but it just uses 33 of the 64 possible values, wasting almost +half of the codes. + + The intelligent trick of LZMA is that it encodes in what it calls a +"slot" the position of the most significant bit set, along with the value +of the next bit, using the same 6 bits that would take to encode the +position alone. This seems to need 66 slots (twice the number of +positions), but for positions 0 and 1 there is no next bit, so the number +of slots needed is 64 (0 to 63). The 6 bits representing this "slot number" are then context-coded. If -the distance is >= 4, the remaining bits are coded as follows. -'direct_bits' is the amount of remaining bits (from 0 to 30) needed to -form a complete distance, and is calculated as (slot >> 1) - 1. If a -distance needs 6 or more direct_bits, the last 4 bits are coded -separately. The last piece (all the direct_bits for distances 4 to 127 -or the last 4 bits for distances >= 128) is context-coded in reverse -order (from LSB to MSB). For distances >= 128, the 'direct_bits - 4' -part is coded with fixed 0.5 probability. - -Bit sequence Description ------------------------------------------------------------------------- -slot distances from 0 to 3 -slot + direct_bits distances from 4 to 127 -slot + (direct_bits - 4) + 4 bits distances from 128 to 2^32 - 1 +the distance is >= 4, the remaining bits are encoded as follows. +'direct_bits' is the amount of remaining bits (from 1 to 30) needed to form +a complete distance, and is calculated as (slot >> 1) - 1. If a distance +needs 6 or more direct_bits, the last 4 bits are encoded separately. The +last piece (all the direct_bits for distances 4 to 127, or the last 4 bits +for distances >= 128) is context-coded in reverse order (from LSB to MSB). +For distances >= 128, the 'direct_bits - 4' part is encoded with fixed 0.5 +probability. + +Bit sequence Description +---------------------------------------------------------------------------- +slot distances from 0 to 3 +slot + direct_bits distances from 4 to 127 +slot + (direct_bits - 4) + 4 bits distances from 128 to 2^32 - 1 7.2 The coding contexts @@ -854,20 +890,20 @@ integers representing the probability of the corresponding bit being 0. state is 0. 'pos_state' - Value of the 2 least significant bits of the current position in - the decoded data. + Value of the 2 least significant bits of the current position in the + decoded data. 'literal_state' Value of the 3 most significant bits of the latest byte decoded. 'len_state' - Coded value of length (length - 2), with a maximum of 3. The - resulting value is in the range 0 to 3. + Coded value of the current match length (length - 2), with a maximum + of 3. The resulting value is in the range 0 to 3. In the following table, '!literal' is any sequence except a literal -byte. 'rep' is any one of 'rep0', 'rep1', 'rep2' or 'rep3'. The types -of previous sequences corresponding to each state are: +byte. 'rep' is any one of 'rep0', 'rep1', 'rep2', or 'rep3'. The types of +previous sequences corresponding to each state are: State Types of previous sequences ------------------------------------------------------ @@ -887,78 +923,81 @@ State Types of previous sequences The contexts for decoding the type of coding sequence are: -Name Indices Used when ------------------------------------------------------------------------ -bm_match state, pos_state sequence start -bm_rep state after sequence 1 -bm_rep0 state after sequence 11 -bm_rep1 state after sequence 111 -bm_rep2 state after sequence 1111 -bm_len state, pos_state after sequence 110 +Name Indices Used when +---------------------------------------------------------------------------- +bm_match state, pos_state sequence start +bm_rep state after sequence 1 +bm_rep0 state after sequence 11 +bm_rep1 state after sequence 111 +bm_rep2 state after sequence 1111 +bm_len state, pos_state after sequence 110 The contexts for decoding distances are: -Name Indices Used when ------------------------------------------------------------------------- -bm_dis_slot len_state, bit tree distance start -bm_dis reverse bit tree after slots 4 to 13 -bm_align reverse bit tree for distances >= 128, after fixed - probability bits +Name Indices Used when +---------------------------------------------------------------------------- +bm_dis_slot len_state, bit tree distance start +bm_dis reverse bit tree after slots 4 to 13 +bm_align reverse bit tree for distances >= 128, after fixed + probability bits - There are two separate sets of contexts for lengths ('Len_model' in -the source). One for normal matches, the other for repeated matches. The + There are two separate sets of contexts for lengths ('Len_model' in the +source). One for normal matches, the other for repeated matches. The contexts in each Len_model are (see 'decode_len' in the source): -Name Indices Used when ------------------------------------------------------------------------- -choice1 none length start -choice2 none after sequence 1 -bm_low pos_state, bit tree after sequence 0 -bm_mid pos_state, bit tree after sequence 10 -bm_high bit tree after sequence 11 +Name Indices Used when +--------------------------------------------------------------------------- +choice1 none length start +choice2 none after sequence 1 +bm_low pos_state, bit tree after sequence 0 +bm_mid pos_state, bit tree after sequence 10 +bm_high bit tree after sequence 11 The context array 'bm_literal' is special. In principle it acts as a -normal bit tree context, the one selected by 'literal_state'. But if -the previous decoded byte was not a literal, two other bit tree -contexts are used depending on the value of each bit in 'match_byte' -(the byte at the latest used distance), until a bit is decoded that is -different from its corresponding bit in 'match_byte'. After the first -difference is found, the rest of the byte is decoded using the normal -bit tree context. (See 'decode_matched' in the source). +normal bit tree context, the one selected by 'literal_state'. But if the +previous decoded byte was not a literal, two other bit tree contexts are +used depending on the value of each bit in 'match_byte' (the byte at the +latest used distance), until a bit is decoded that is different from its +corresponding bit in 'match_byte'. After the first difference is found, the +rest of the byte is decoded using the normal bit tree context. (See +'decode_matched' in the source). 7.3 The range decoder ===================== -The LZMA stream is consumed one byte at a time by the range decoder. -(See 'normalize' in the source). Every byte consumed produces a -variable number of decoded bits, depending on how well these bits agree -with their context. (See 'decode_bit' in the source). +The LZMA stream is consumed one byte at a time by the range decoder. (See +'normalize' in the source). Every byte consumed produces a variable number +of decoded bits, depending on how well these bits agree with their context. +(See 'decode_bit' in the source). The range decoder state consists of two unsigned 32-bit variables; -'range' (representing the most significant part of the range size not -yet decoded), and 'code' (representing the current point within -'range'). 'range' is initialized to (2^32 - 1), and 'code' is -initialized to 0. +'range' (representing the most significant part of the range size not yet +decoded), and 'code' (representing the current point within 'range'). +'range' is initialized to 2^32 - 1, and 'code' is initialized to 0. The range encoder produces a first 0 byte that must be ignored by the range decoder. This is done by shifting 5 bytes in the initialization of -'code' instead of 4. (See the 'Range_decoder' constructor in the -source). +'code' instead of 4. (See the 'Range_decoder' constructor in the source). -7.4 Decoding the LZMA stream -============================ +7.4 Decoding and verifying the LZMA stream +========================================== After decoding the member header and obtaining the dictionary size, the -range decoder is initialized and then the LZMA decoder enters a loop -(See 'decode_member' in the source) where it invokes the range decoder -with the appropriate contexts to decode the different coding sequences -(matches, repeated matches, and literal bytes), until the "End Of -Stream" marker is decoded. +range decoder is initialized and then the LZMA decoder enters a loop (See +'decode_member' in the source) where it invokes the range decoder with the +appropriate contexts to decode the different coding sequences (matches, +repeated matches, and literal bytes), until the "End Of Stream" marker is +decoded. + + Once the "End Of Stream" marker has been decoded, the decompressor reads +and decodes the member trailer, and verifies that the three integrity +factors (CRC, data size, and member size) match those calculated by the +LZMA decoder. File: lzip.info, Node: Trailing data, Next: Examples, Prev: Stream format, Up: Top @@ -969,43 +1008,40 @@ File: lzip.info, Node: Trailing data, Next: Examples, Prev: Stream format, U Sometimes extra data are found appended to a lzip file after the last member. Such trailing data may be: - * Padding added to make the file size a multiple of some block size, - for example when writing to a tape. It is safe to append any - amount of padding zero bytes to a lzip file. + * Padding added to make the file size a multiple of some block size, for + example when writing to a tape. It is safe to append any amount of + padding zero bytes to a lzip file. * Useful data added by the user; a cryptographically secure hash, a - description of file contents, etc. It is safe to append any amount - of text to a lzip file as long as none of the first four bytes of - the text match the corresponding byte in the string "LZIP", and - the text does not contain any zero bytes (null characters). - Nonzero bytes and zero bytes can't be safely mixed in trailing - data. + description of file contents, etc. It is safe to append any amount of + text to a lzip file as long as none of the first four bytes of the text + match the corresponding byte in the string "LZIP", and the text does + not contain any zero bytes (null characters). Nonzero bytes and zero + bytes can't be safely mixed in trailing data. * Garbage added by some not totally successful copy operation. - * Malicious data added to the file in order to make its total size - and hash value (for a chosen hash) coincide with those of another - file. + * Malicious data added to the file in order to make its total size and + hash value (for a chosen hash) coincide with those of another file. * In rare cases, trailing data could be the corrupt header of another member. In multimember or concatenated files the probability of corruption happening in the magic bytes is 5 times smaller than the - probability of getting a false positive caused by the corruption - of the integrity information itself. Therefore it can be - considered to be below the noise level. Additionally, the test - used by lzip to discriminate trailing data from a corrupt header - has a Hamming distance (HD) of 3, and the 3 bit flips must happen - in different magic bytes for the test to fail. In any case, the - option '--trailing-error' guarantees that any corrupt header will - be detected. + probability of getting a false positive caused by the corruption of the + integrity information itself. Therefore it can be considered to be + below the noise level. Additionally, the test used by lzip to + discriminate trailing data from a corrupt header has a Hamming + distance (HD) of 3, and the 3 bit flips must happen in different magic + bytes for the test to fail. In any case, the option '--trailing-error' + guarantees that any corrupt header will be detected. Trailing data are in no way part of the lzip file format, but tools reading lzip files are expected to behave as correctly and usefully as possible in the presence of trailing data. - Trailing data can be safely ignored in most cases. In some cases, -like that of user-added data, they are expected to be ignored. In those -cases where a file containing trailing data must be rejected, the option + Trailing data can be safely ignored in most cases. In some cases, like +that of user-added data, they are expected to be ignored. In those cases +where a file containing trailing data must be rejected, the option '--trailing-error' can be used. *Note --trailing-error::. @@ -1017,80 +1053,88 @@ File: lzip.info, Node: Examples, Next: Problems, Prev: Trailing data, Up: To WARNING! Even if lzip is bug-free, other causes may result in a corrupt compressed file (bugs in the system libraries, memory errors, etc). Therefore, if the data you are going to compress are important, give the -'--keep' option to lzip and don't remove the original file until you -verify the compressed file with a command like -'lzip -cd file.lz | cmp file -'. Most RAM errors happening during -compression can only be detected by comparing the compressed file with -the original because the corruption happens before lzip compresses the -RAM contents, resulting in a valid compressed file containing wrong -data. +option '--keep' to lzip and don't remove the original file until you verify +the compressed file with a command like 'lzip -cd file.lz | cmp file -'. +Most RAM errors happening during compression can only be detected by +comparing the compressed file with the original because the corruption +happens before lzip compresses the RAM contents, resulting in a valid +compressed file containing wrong data. + + +Example 1: Extract all the files from archive 'foo.tar.lz'. + tar -xf foo.tar.lz + or + lzip -cd foo.tar.lz | tar -xf - -Example 1: Replace a regular file with its compressed version 'file.lz' -and show the compression ratio. + +Example 2: Replace a regular file with its compressed version 'file.lz' and +show the compression ratio. lzip -v file -Example 2: Like example 1 but the created 'file.lz' is multimember with -a member size of 1 MiB. The compression ratio is not shown. +Example 3: Like example 1 but the created 'file.lz' is multimember with a +member size of 1 MiB. The compression ratio is not shown. lzip -b 1MiB file -Example 3: Restore a regular file from its compressed version -'file.lz'. If the operation is successful, 'file.lz' is removed. +Example 4: Restore a regular file from its compressed version 'file.lz'. If +the operation is successful, 'file.lz' is removed. lzip -d file.lz -Example 4: Verify the integrity of the compressed file 'file.lz' and -show status. +Example 5: Verify the integrity of the compressed file 'file.lz' and show +status. lzip -tv file.lz -Example 5: Compress a whole device in /dev/sdc and send the output to +Example 6: Compress a whole device in /dev/sdc and send the output to 'file.lz'. - lzip -c /dev/sdc > file.lz + lzip -c /dev/sdc > file.lz + or + lzip /dev/sdc -o file.lz -Example 6: The right way of concatenating the decompressed output of two -or more compressed files. *Note Trailing data::. +Example 7: The right way of concatenating the decompressed output of two or +more compressed files. *Note Trailing data::. Don't do this - cat file1.lz file2.lz file3.lz | lzip -d + cat file1.lz file2.lz file3.lz | lzip -d - Do this instead lzip -cd file1.lz file2.lz file3.lz -Example 7: Decompress 'file.lz' partially until 10 KiB of decompressed -data are produced. +Example 8: Decompress 'file.lz' partially until 10 KiB of decompressed data +are produced. lzip -cd file.lz | dd bs=1024 count=10 -Example 8: Decompress 'file.lz' partially from decompressed byte 10000 -to decompressed byte 15000 (5000 bytes are produced). +Example 9: Decompress 'file.lz' partially from decompressed byte at offset +10000 to decompressed byte at offset 14999 (5000 bytes are produced). lzip -cd file.lz | dd bs=1000 skip=10 count=5 -Example 9: Create a multivolume compressed tar archive with a volume -size of 1440 KiB. +Example 10: Create a multivolume compressed tar archive with a volume size +of 1440 KiB. - tar -c some_directory | lzip -S 1440KiB -o volume_name + tar -c some_directory | lzip -S 1440KiB -o volume_name - -Example 10: Extract a multivolume compressed tar archive. +Example 11: Extract a multivolume compressed tar archive. lzip -cd volume_name*.lz | tar -xf - -Example 11: Create a multivolume compressed backup of a large database -file with a volume size of 650 MB, where each volume is a multimember -file with a member size of 32 MiB. +Example 12: Create a multivolume compressed backup of a large database file +with a volume size of 650 MB, where each volume is a multimember file with +a member size of 32 MiB. lzip -b 32MiB -S 650MB big_db @@ -1100,14 +1144,14 @@ File: lzip.info, Node: Problems, Next: Reference source code, Prev: Examples, 10 Reporting bugs ***************** -There are probably bugs in lzip. There are certainly errors and -omissions in this manual. If you report them, they will get fixed. If -you don't, no one will ever know about them and they will remain unfixed -for all eternity, if not longer. +There are probably bugs in lzip. There are certainly errors and omissions +in this manual. If you report them, they will get fixed. If you don't, no +one will ever know about them and they will remain unfixed for all +eternity, if not longer. If you find a bug in lzip, please send electronic mail to -<lzip-bug@nongnu.org>. Include the version number, which you can find -by running 'lzip --version'. +<lzip-bug@nongnu.org>. Include the version number, which you can find by +running 'lzip --version'. File: lzip.info, Node: Reference source code, Next: Concept index, Prev: Problems, Up: Top @@ -1115,28 +1159,28 @@ File: lzip.info, Node: Reference source code, Next: Concept index, Prev: Prob Appendix A Reference source code ******************************** -/* Lzd - Educational decompressor for the lzip format - Copyright (C) 2013-2019 Antonio Diaz Diaz. +/* Lzd - Educational decompressor for the lzip format + Copyright (C) 2013-2021 Antonio Diaz Diaz. - This program is free software. Redistribution and use in source and - binary forms, with or without modification, are permitted provided - that the following conditions are met: + This program is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* - Exit status: 0 for a normal exit, 1 for environmental problems - (file not found, invalid flags, I/O errors, etc), 2 to indicate a - corrupt or invalid input file. + Exit status: 0 for a normal exit, 1 for environmental problems + (file not found, invalid flags, I/O errors, etc), 2 to indicate a + corrupt or invalid input file. */ #include <algorithm> @@ -1164,7 +1208,7 @@ public: void set_char() { - static const int next[states] = { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5 }; + const int next[states] = { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5 }; st = next[st]; } void set_match() { st = ( st < 7 ) ? 7 : 10; } @@ -1186,7 +1230,7 @@ enum { dis_slot_bits = 6, start_dis_model = 4, end_dis_model = 14, - modeled_distances = 1 << (end_dis_model / 2), // 128 + modeled_distances = 1 << ( end_dis_model / 2 ), // 128 dis_align_bits = 4, dis_align_size = 1 << dis_align_bits, @@ -1247,8 +1291,9 @@ public: const CRC32 crc32; -typedef uint8_t Lzip_header[6]; // 0-3 magic, 4 version, 5 coded_dict_size - +typedef uint8_t Lzip_header[6]; // 0-3 magic bytes + // 4 version + // 5 coded dictionary size typedef uint8_t Lzip_trailer[20]; // 0-3 CRC32 of the uncompressed data // 4-11 size of the uncompressed data @@ -1256,16 +1301,18 @@ typedef uint8_t Lzip_trailer[20]; class Range_decoder { + unsigned long long member_pos; uint32_t code; uint32_t range; public: - Range_decoder() : code( 0 ), range( 0xFFFFFFFFU ) + Range_decoder() : member_pos( 6 ), code( 0 ), range( 0xFFFFFFFFU ) { - for( int i = 0; i < 5; ++i ) code = (code << 8) | get_byte(); + for( int i = 0; i < 5; ++i ) code = ( code << 8 ) | get_byte(); } - uint8_t get_byte() { return std::getc( stdin ); } + uint8_t get_byte() { ++member_pos; return std::getc( stdin ); } + unsigned long long member_position() const { return member_pos; } unsigned decode( const int num_bits ) { @@ -1276,7 +1323,7 @@ public: symbol <<= 1; if( code >= range ) { code -= range; symbol |= 1; } if( range <= 0x00FFFFFFU ) // normalize - { range <<= 8; code = (code << 8) | get_byte(); } + { range <<= 8; code = ( code << 8 ) | get_byte(); } } return symbol; } @@ -1288,7 +1335,8 @@ public: if( code < bound ) { range = bound; - bm.probability += (bit_model_total - bm.probability) >> bit_model_move_bits; + bm.probability += + ( bit_model_total - bm.probability ) >> bit_model_move_bits; symbol = 0; } else @@ -1299,7 +1347,7 @@ public: symbol = 1; } if( range <= 0x00FFFFFFU ) // normalize - { range <<= 8; code = (code << 8) | get_byte(); } + { range <<= 8; code = ( code << 8 ) | get_byte(); } return symbol; } @@ -1308,7 +1356,7 @@ public: unsigned symbol = 1; for( int i = 0; i < num_bits; ++i ) symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); - return symbol - (1 << num_bits); + return symbol - ( 1 << num_bits ); } unsigned decode_tree_reversed( Bit_model bm[], const int num_bits ) @@ -1395,7 +1443,11 @@ public: ~LZ_decoder() { delete[] buffer; } unsigned crc() const { return crc_ ^ 0xFFFFFFFFU; } - unsigned long long data_position() const { return partial_data_pos + pos; } + unsigned long long data_position() const + { return partial_data_pos + pos; } + uint8_t get_byte() { return rdec.get_byte(); } + unsigned long long member_position() const + { return rdec.member_position(); } bool decode_member(); }; @@ -1407,7 +1459,6 @@ void LZ_decoder::flush_data() { const unsigned size = pos - stream_pos; crc32.update_buf( crc_, buffer + stream_pos, size ); - errno = 0; if( std::fwrite( buffer + stream_pos, 1, size, stdout ) != size ) { std::fprintf( stderr, "Write error: %s\n", std::strerror( errno ) ); std::exit( 1 ); } @@ -1418,7 +1469,7 @@ void LZ_decoder::flush_data() } -bool LZ_decoder::decode_member() // Returns false if error +bool LZ_decoder::decode_member() // Returns false if error { Bit_model bm_literal[1<<literal_context_bits][0x300]; Bit_model bm_match[State::states][pos_states]; @@ -1498,7 +1549,8 @@ bool LZ_decoder::decode_member() // Returns false if error direct_bits ); else { - rep0 += rdec.decode( direct_bits - dis_align_bits ) << dis_align_bits; + rep0 += + rdec.decode( direct_bits - dis_align_bits ) << dis_align_bits; rep0 += rdec.decode_tree_reversed( bm_align, dis_align_bits ); if( rep0 == 0xFFFFFFFFU ) // marker found { @@ -1520,20 +1572,21 @@ bool LZ_decoder::decode_member() // Returns false if error int main( const int argc, const char * const argv[] ) { - if( argc > 1 ) + if( argc > 2 || ( argc == 2 && std::strcmp( argv[1], "-d" ) != 0 ) ) { - std::printf( "Lzd %s - Educational decompressor for the lzip format.\n", - PROGVERSION ); - std::printf( "Study the source to learn how a lzip decompressor works.\n" - "See the lzip manual for an explanation of the code.\n" - "It is not safe to use lzd for any real work.\n" - "\nUsage: %s < file.lz > file\n", argv[0] ); - std::printf( "Lzd decompresses from standard input to standard output.\n" - "\nCopyright (C) 2019 Antonio Diaz Diaz.\n" - "This is free software: you are free to change and redistribute it.\n" - "There is NO WARRANTY, to the extent permitted by law.\n" - "Report bugs to lzip-bug@nongnu.org\n" - "Lzd home page: http://www.nongnu.org/lzip/lzd.html\n" ); + std::printf( + "Lzd %s - Educational decompressor for the lzip format.\n" + "Study the source to learn how a lzip decompressor works.\n" + "See the lzip manual for an explanation of the code.\n" + "\nUsage: %s [-d] < file.lz > file\n" + "Lzd decompresses from standard input to standard output.\n" + "\nCopyright (C) 2021 Antonio Diaz Diaz.\n" + "License 2-clause BSD.\n" + "This is free software: you are free to change and redistribute it.\n" + "There is NO WARRANTY, to the extent permitted by law.\n" + "Report bugs to lzip-bug@nongnu.org\n" + "Lzd home page: http://www.nongnu.org/lzip/lzd.html\n", + PROGVERSION, argv[0] ); return 0; } @@ -1549,9 +1602,9 @@ int main( const int argc, const char * const argv[] ) if( std::feof( stdin ) || std::memcmp( header, "LZIP\x01", 5 ) != 0 ) { if( first_member ) - { std::fputs( "Bad magic number (file not in lzip format).\n", stderr ); - return 2; } - break; + { std::fputs( "Bad magic number (file not in lzip format).\n", + stderr ); return 2; } + break; // ignore trailing data } unsigned dict_size = 1 << ( header[5] & 0x1F ); dict_size -= ( dict_size / 16 ) * ( ( header[5] >> 5 ) & 7 ); @@ -1564,18 +1617,30 @@ int main( const int argc, const char * const argv[] ) { std::fputs( "Data error\n", stderr ); return 2; } Lzip_trailer trailer; // verify trailer - for( int i = 0; i < 20; ++i ) trailer[i] = std::getc( stdin ); + for( int i = 0; i < 20; ++i ) trailer[i] = decoder.get_byte(); + int retval = 0; unsigned crc = 0; - for( int i = 3; i >= 0; --i ) { crc <<= 8; crc += trailer[i]; } + for( int i = 3; i >= 0; --i ) crc = ( crc << 8 ) + trailer[i]; + if( crc != decoder.crc() ) + { std::fputs( "CRC mismatch\n", stderr ); retval = 2; } + unsigned long long data_size = 0; - for( int i = 11; i >= 4; --i ) { data_size <<= 8; data_size += trailer[i]; } - if( crc != decoder.crc() || data_size != decoder.data_position() ) - { std::fputs( "CRC error\n", stderr ); return 2; } + for( int i = 11; i >= 4; --i ) + data_size = ( data_size << 8 ) + trailer[i]; + if( data_size != decoder.data_position() ) + { std::fputs( "Data size mismatch\n", stderr ); retval = 2; } + + unsigned long long member_size = 0; + for( int i = 19; i >= 12; --i ) + member_size = ( member_size << 8 ) + trailer[i]; + if( member_size != decoder.member_position() ) + { std::fputs( "Member size mismatch\n", stderr ); retval = 2; } + if( retval ) return retval; } if( std::fclose( stdout ) != 0 ) - { std::fprintf( stderr, "Error closing stdout: %s\n", std::strerror( errno ) ); - return 1; } + { std::fprintf( stderr, "Error closing stdout: %s\n", + std::strerror( errno ) ); return 1; } return 0; } @@ -1588,41 +1653,42 @@ Concept index * Menu: -* algorithm: Algorithm. (line 6) -* bugs: Problems. (line 6) -* examples: Examples. (line 6) -* file format: File format. (line 6) -* format of the LZMA stream: Stream format. (line 6) -* getting help: Problems. (line 6) -* introduction: Introduction. (line 6) -* invoking: Invoking lzip. (line 6) -* options: Invoking lzip. (line 6) -* output: Output. (line 6) -* quality assurance: Quality assurance. (line 6) -* reference source code: Reference source code. (line 6) -* trailing data: Trailing data. (line 6) -* usage: Invoking lzip. (line 6) -* version: Invoking lzip. (line 6) +* algorithm: Algorithm. (line 6) +* bugs: Problems. (line 6) +* examples: Examples. (line 6) +* file format: File format. (line 6) +* format of the LZMA stream: Stream format. (line 6) +* getting help: Problems. (line 6) +* introduction: Introduction. (line 6) +* invoking: Invoking lzip. (line 6) +* options: Invoking lzip. (line 6) +* output: Output. (line 6) +* quality assurance: Quality assurance. (line 6) +* reference source code: Reference source code. (line 6) +* trailing data: Trailing data. (line 6) +* usage: Invoking lzip. (line 6) +* version: Invoking lzip. (line 6) Tag Table: Node: Top208 -Node: Introduction1200 -Node: Output6244 -Node: Invoking lzip7756 -Ref: --trailing-error8378 -Node: Quality assurance16391 -Node: File format24994 -Ref: coded-dict-size26286 -Node: Algorithm27396 -Node: Stream format30222 -Node: Trailing data40873 -Node: Examples43149 -Ref: concat-example44571 -Node: Problems45609 -Node: Reference source code46141 -Node: Concept index60353 +Node: Introduction1202 +Node: Output6930 +Node: Invoking lzip8525 +Ref: --trailing-error9314 +Node: Quality assurance18307 +Node: File format27264 +Ref: coded-dict-size28554 +Node: Algorithm29690 +Node: Stream format33090 +Ref: what-is-coded35459 +Node: Trailing data44328 +Node: Examples46589 +Ref: concat-example48189 +Node: Problems49252 +Node: Reference source code49784 +Node: Concept index64648 End Tag Table diff --git a/doc/lzip.texi b/doc/lzip.texi index 142e5a0..b22337e 100644 --- a/doc/lzip.texi +++ b/doc/lzip.texi @@ -6,8 +6,8 @@ @finalout @c %**end of header -@set UPDATED 3 January 2019 -@set VERSION 1.21 +@set UPDATED 4 January 2021 +@set VERSION 1.22 @dircategory Data Compression @direntry @@ -29,6 +29,7 @@ @contents @end ifnothtml +@ifnottex @node Top @top @@ -38,7 +39,7 @@ This manual is for Lzip (version @value{VERSION}, @value{UPDATED}). * Introduction:: Purpose and features of lzip * Output:: Meaning of lzip's output * Invoking lzip:: Command line interface -* Quality assurance:: Design, development and testing of lzip +* Quality assurance:: Design, development, and testing of lzip * File format:: Detailed format of the compressed file * Algorithm:: How lzip compresses the data * Stream format:: Format of the LZMA stream in lzip files @@ -50,22 +51,42 @@ This manual is for Lzip (version @value{VERSION}, @value{UPDATED}). @end menu @sp 1 -Copyright @copyright{} 2008-2019 Antonio Diaz Diaz. +Copyright @copyright{} 2008-2021 Antonio Diaz Diaz. -This manual is free documentation: you have unlimited permission -to copy, distribute and modify it. +This manual is free documentation: you have unlimited permission to copy, +distribute, and modify it. +@end ifnottex @node Introduction @chapter Introduction @cindex introduction -@uref{http://www.nongnu.org/lzip/lzip.html,,Lzip} is a lossless data -compressor with a user interface similar to the one of gzip or bzip2. Lzip -can compress about as fast as gzip @w{(lzip -0)} or compress most files more -than bzip2 @w{(lzip -9)}. Decompression speed is intermediate between gzip -and bzip2. Lzip is better than gzip and bzip2 from a data recovery -perspective. +@uref{http://www.nongnu.org/lzip/lzip.html,,Lzip} +is a lossless data compressor with a user interface similar to the one +of gzip or bzip2. Lzip uses a simplified form of the 'Lempel-Ziv-Markov +chain-Algorithm' (LZMA) stream format, chosen to maximize safety and +interoperability. Lzip can compress about as fast as gzip @w{(lzip -0)} or +compress most files more than bzip2 @w{(lzip -9)}. Decompression speed is +intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 from +a data recovery perspective. Lzip has been designed, written, and tested +with great care to replace gzip and bzip2 as the standard general-purpose +compressed format for unix-like systems. + +For compressing/decompressing large files on multiprocessor machines +@uref{http://www.nongnu.org/lzip/manual/plzip_manual.html,,plzip} can be +much faster than lzip at the cost of a slightly reduced compression ratio. +@ifnothtml +@xref{Top,plzip manual,,plzip}. +@end ifnothtml + +For creation and manipulation of compressed tar archives +@uref{http://www.nongnu.org/lzip/manual/tarlz_manual.html,,tarlz} can be +more efficient than using tar and plzip because tarlz is able to keep the +alignment between tar members and lzip members. +@ifnothtml +@xref{Top,tarlz manual,,tarlz}. +@end ifnothtml The lzip file format is designed for data sharing and long-term archiving, taking into account both data integrity and decoder availability: @@ -73,11 +94,11 @@ taking into account both data integrity and decoder availability: @itemize @bullet @item The lzip format provides very safe integrity checking and some data -recovery means. The +recovery means. The program @uref{http://www.nongnu.org/lzip/manual/lziprecover_manual.html#Data-safety,,lziprecover} -program can repair bit flip errors (one of the most common forms of data -corruption) in lzip files, and provides data recovery capabilities, -including error-checked merging of damaged copies of a file. +can repair bit flip errors (one of the most common forms of data corruption) +in lzip files, and provides data recovery capabilities, including +error-checked merging of damaged copies of a file. @ifnothtml @xref{Data safety,,,lziprecover}. @end ifnothtml @@ -87,21 +108,21 @@ The lzip format is as simple as possible (but not simpler). The lzip manual provides the source code of a simple decompressor along with a detailed explanation of how it works, so that with the only help of the lzip manual it would be possible for a digital archaeologist to extract -the data from a lzip file long after quantum computers eventually render -LZMA obsolete. +the data from a lzip file long after quantum computers eventually +render LZMA obsolete. @item Additionally the lzip reference implementation is copylefted, which guarantees that it will remain free forever. @end itemize -A nice feature of the lzip format is that a corrupt byte is easier to -repair the nearer it is from the beginning of the file. Therefore, with -the help of lziprecover, losing an entire archive just because of a -corrupt byte near the beginning is a thing of the past. +A nice feature of the lzip format is that a corrupt byte is easier to repair +the nearer it is from the beginning of the file. Therefore, with the help of +lziprecover, losing an entire archive just because of a corrupt byte near +the beginning is a thing of the past. The member trailer stores the 32-bit CRC of the original data, the size -of the original data and the size of the member. These values, together +of the original data, and the size of the member. These values, together with the end-of-stream marker, provide a 3 factor integrity checking which guarantees that the decompressed version of the data is identical to the original. This guards against corruption of the compressed data, @@ -115,10 +136,10 @@ Lzip uses the same well-defined exit status values used by bzip2, which makes it safer than compressors returning ambiguous warning values (like gzip) when it is used as a back end for other programs like tar or zutils. -Lzip will automatically use for each file the largest dictionary size -that does not exceed neither the file size nor the limit given. Keep in -mind that the decompression memory requirement is affected at -compression time by the choice of dictionary size limit. +Lzip will automatically use for each file the largest dictionary size that +does not exceed neither the file size nor the limit given. Keep in mind that +the decompression memory requirement is affected at compression time by the +choice of dictionary size limit. The amount of memory required for compression is about 1 or 2 times the dictionary size limit (1 if input file size is less than dictionary size @@ -144,28 +165,26 @@ possible, ownership of the file just as @samp{cp -p} does. (If the user ID or the group ID can't be duplicated, the file permission bits S_ISUID and S_ISGID are cleared). -Lzip is able to read from some types of non regular files if the -@samp{--stdout} option is specified. +Lzip is able to read from some types of non-regular files if either the +option @samp{-c} or the option @samp{-o} is specified. -If no file names are specified, lzip compresses (or decompresses) from -standard input to standard output. In this case, lzip will decline to -write compressed output to a terminal, as this would be entirely -incomprehensible and therefore pointless. +Lzip will refuse to read compressed data from a terminal or write compressed +data to a terminal, as this would be entirely incomprehensible and might +leave the terminal in an abnormal state. -Lzip will correctly decompress a file which is the concatenation of two -or more compressed files. The result is the concatenation of the -corresponding decompressed files. Integrity testing of concatenated -compressed files is also supported. +Lzip will correctly decompress a file which is the concatenation of two or +more compressed files. The result is the concatenation of the corresponding +decompressed files. Integrity testing of concatenated compressed files is +also supported. -Lzip can produce multimember files, and lziprecover can safely recover -the undamaged members in case of file damage. Lzip can also split the -compressed output in volumes of a given size, even when reading from -standard input. This allows the direct creation of multivolume -compressed tar archives. +Lzip can produce multimember files, and lziprecover can safely recover the +undamaged members in case of file damage. Lzip can also split the compressed +output in volumes of a given size, even when reading from standard input. +This allows the direct creation of multivolume compressed tar archives. Lzip is able to compress and decompress streams of unlimited size by -automatically creating multimember output. The members so created are -large, about @w{2 PiB} each. +automatically creating multimember output. The members so created are large, +about @w{2 PiB} each. @node Output @@ -178,16 +197,16 @@ The output of lzip looks like this: lzip -v foo foo: 6.676:1, 14.98% ratio, 85.02% saved, 450560 in, 67493 out. -lzip -tvv foo.lz - foo.lz: 6.676:1, 14.98% ratio, 85.02% saved. ok +lzip -tvvv foo.lz + foo.lz: 6.676:1, 14.98% ratio, 85.02% saved. 450560 out, 67493 in. ok @end example The meaning of each field is as follows: @table @code @item N:1 -The compression ratio @w{(uncompressed_size / compressed_size)}, shown -as N to 1. +The compression ratio @w{(uncompressed_size / compressed_size)}, shown as +@w{N to 1}. @item ratio The inverse compression ratio @w{(compressed_size / uncompressed_size)}, @@ -198,24 +217,24 @@ decimal point two places to the left; @w{14.98% = 0.1498}. The space saved by compression @w{(1 - ratio)}, shown as a percentage. @item in -The size of the uncompressed data. When decompressing or testing, it is -shown as @code{decompressed}. Note that lzip always prints the -uncompressed size before the compressed size when compressing, -decompressing, testing or listing. +Size of the input data. This is the uncompressed size when compressing, or +the compressed size when decompressing or testing. Note that lzip always +prints the uncompressed size before the compressed size when compressing, +decompressing, testing, or listing. @item out -The size of the compressed data. When decompressing or testing, it is -shown as @code{compressed}. +Size of the output data. This is the compressed size when compressing, or +the decompressed size when decompressing or testing. @end table -When decompressing or testing at verbosity level 4 (-vvvv), the -dictionary size used to compress the file and the CRC32 of the -uncompressed data are also shown. +When decompressing or testing at verbosity level 4 (-vvvv), the dictionary +size used to compress the file and the CRC32 of the uncompressed data are +also shown. -LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may never -have been compressed. Decompressed is used to refer to data which have -undergone the process of decompression. +LANGUAGE NOTE: Uncompressed = not compressed = plain data; it may never have +been compressed. Decompressed is used to refer to data which have undergone +the process of decompression. @node Invoking lzip @@ -232,11 +251,16 @@ lzip [@var{options}] [@var{files}] @end example @noindent -@samp{-} used as a @var{file} argument means standard input. It can be -mixed with other @var{files} and is read just once, the first time it -appears in the command line. +If no file names are specified, lzip compresses (or decompresses) from +standard input to standard output. A hyphen @samp{-} used as a @var{file} +argument means standard input. It can be mixed with other @var{files} and is +read just once, the first time it appears in the command line. -lzip supports the following options: +lzip supports the following +@uref{http://www.nongnu.org/arg-parser/manual/arg_parser_manual.html#Argument-syntax,,options}: +@ifnothtml +@xref{Argument syntax,,,arg_parser}. +@end ifnothtml @table @code @item -h @@ -257,21 +281,25 @@ garbage that can be safely ignored. @xref{concat-example}. @item -b @var{bytes} @itemx --member-size=@var{bytes} -When compressing, set the member size limit to @var{bytes}. A small -member size may degrade compression ratio, so use it only when needed. -Valid values range from @w{100 kB} to @w{2 PiB}. Defaults to @w{2 PiB}. +When compressing, set the member size limit to @var{bytes}. It is advisable +to keep members smaller than RAM size so that they can be repaired with +lziprecover in case of corruption. A small member size may degrade +compression ratio, so use it only when needed. Valid values range from +@w{100 kB} to @w{2 PiB}. Defaults to @w{2 PiB}. @item -c @itemx --stdout -Compress or decompress to standard output; keep input files unchanged. -If compressing several files, each file is compressed independently. -This option is needed when reading from a named pipe (fifo) or from a -device. Use it also to recover as much of the decompressed data as -possible when decompressing a corrupt file. +Compress or decompress to standard output; keep input files unchanged. If +compressing several files, each file is compressed independently. (The +output consists of a sequence of independently compressed members). This +option (or @samp{-o}) is needed when reading from a named pipe (fifo) or +from a device. Use it also to recover as much of the decompressed data as +possible when decompressing a corrupt file. @samp{-c} overrides @samp{-o} +and @samp{-S}. @samp{-c} has no effect when testing or listing. @item -d @itemx --decompress -Decompress the specified files. If a file does not exist or can't be +Decompress the files specified. If a file does not exist or can't be opened, lzip continues decompressing the rest of the files. If a file fails to decompress, or is a terminal, lzip exits immediately without decompressing the rest of the files. @@ -291,17 +319,18 @@ Keep (don't delete) input files during compression or decompression. @item -l @itemx --list -Print the uncompressed size, compressed size and percentage saved of the -specified files. Trailing data are ignored. The values produced are -correct even for multimember files. If more than one file is given, a -final line containing the cumulative sizes is printed. With @samp{-v}, -the dictionary size, the number of members in the file, and the amount -of trailing data (if any) are also printed. With @samp{-vv}, the -positions and sizes of each member in multimember files are also -printed. @samp{-lq} can be used to verify quickly (without -decompressing) the structural integrity of the specified files. (Use -@samp{--test} to verify the data integrity). @samp{-alq} additionally -verifies that none of the specified files contain trailing data. +Print the uncompressed size, compressed size, and percentage saved of the +files specified. Trailing data are ignored. The values produced are correct +even for multimember files. If more than one file is given, a final line +containing the cumulative sizes is printed. With @samp{-v}, the dictionary +size, the number of members in the file, and the amount of trailing data (if +any) are also printed. With @samp{-vv}, the positions and sizes of each +member in multimember files are also printed. + +@samp{-lq} can be used to verify quickly (without decompressing) the +structural integrity of the files specified. (Use @samp{--test} to verify +the data integrity). @samp{-alq} additionally verifies that none of the +files specified contain trailing data. @item -m @var{bytes} @itemx --match-length=@var{bytes} @@ -312,14 +341,25 @@ compression times. @item -o @var{file} @itemx --output=@var{file} -When reading from standard input and @samp{--stdout} has not been -specified, use @samp{@var{file}} as the virtual name of the uncompressed -file. This produces a file named @samp{@var{file}} when decompressing, -or a file named @samp{@var{file}.lz} when compressing. A second -@samp{.lz} extension is not added if @samp{@var{file}} already ends in -@samp{.lz} or @samp{.tlz}. When compressing and splitting the output in -volumes, several files named @samp{@var{file}00001.lz}, -@samp{@var{file}00002.lz}, etc, are created. +If @samp{-c} has not been also specified, write the (de)compressed output to +@var{file}; keep input files unchanged. If compressing several files, each +file is compressed independently. (The output consists of a sequence of +independently compressed members). This option (or @samp{-c}) is needed when +reading from a named pipe (fifo) or from a device. @w{@samp{-o -}} is +equivalent to @samp{-c}. @samp{-o} has no effect when testing or listing. + +In order to keep backward compatibility with lzip versions prior to 1.22, +when compressing from standard input and no other file names are given, the +extension @samp{.lz} is appended to @var{file} unless it already ends in +@samp{.lz} or @samp{.tlz}. This feature will be removed in a future version +of lzip. Meanwhile, redirection may be used instead of @samp{-o} to write +the compressed output to a file without the extension @samp{.lz} in its +name: @w{@samp{lzip < file > foo}}. + +When compressing and splitting the output in volumes, @var{file} is used as +a prefix, and several files named @samp{@var{file}00001.lz}, +@samp{@var{file}00002.lz}, etc, are created. In this case, only one input +file is allowed. @item -q @itemx --quiet @@ -332,7 +372,7 @@ for each file the largest dictionary size that does not exceed neither the file size nor this limit. Valid values range from @w{4 KiB} to @w{512 MiB}. Values 12 to 29 are interpreted as powers of two, meaning 2^12 to 2^29 bytes. Dictionary sizes are quantized so that they can be -coded in just one byte (@pxref{coded-dict-size}). If the specified size +coded in just one byte (@pxref{coded-dict-size}). If the size specified does not match one of the valid sizes, it will be rounded upwards by adding up to @w{(@var{bytes} / 8)} to it. @@ -342,16 +382,17 @@ is affected at compression time by the choice of dictionary size limit. @item -S @var{bytes} @itemx --volume-size=@var{bytes} -When compressing, split the compressed output into several volume files -with names @samp{original_name00001.lz}, @samp{original_name00002.lz}, -etc, and set the volume size limit to @var{bytes}. Input files are kept -unchanged. Each volume is a complete, maybe multimember, lzip file. A -small volume size may degrade compression ratio, so use it only when -needed. Valid values range from @w{100 kB} to @w{4 EiB}. +When compressing, and @samp{-c} has not been also specified, split the +compressed output into several volume files with names +@samp{original_name00001.lz}, @samp{original_name00002.lz}, etc, and set the +volume size limit to @var{bytes}. Input files are kept unchanged. Each +volume is a complete, maybe multimember, lzip file. A small volume size may +degrade compression ratio, so use it only when needed. Valid values range +from @w{100 kB} to @w{4 EiB}. @item -t @itemx --test -Check integrity of the specified files, but don't decompress them. This +Check integrity of the files specified, but don't decompress them. This really performs a trial decompression and throws away the result. Use it together with @samp{-v} to see information about the files. If a file fails the test, does not exist, can't be opened, or is a terminal, lzip @@ -376,12 +417,12 @@ Compression level. Set the compression parameters (dictionary size and match length limit) as shown in the table below. The default compression level is @samp{-6}, equivalent to @w{@samp{-s8MiB -m36}}. Note that @samp{-9} can be much slower than @samp{-0}. These options have no -effect when decompressing, testing or listing. +effect when decompressing, testing, or listing. The bidimensional parameter space of LZMA can't be mapped to a linear scale optimal for all files. If your files are large, very repetitive, -etc, you may need to use the @samp{--dictionary-size} and -@samp{--match-length} options directly to achieve optimal performance. +etc, you may need to use the options @samp{--dictionary-size} and +@samp{--match-length} directly to achieve optimal performance. If several compression levels or @samp{-s} or @samp{-m} options are given, the last setting is used. For example @w{@samp{-9 -s64MiB}} is @@ -406,7 +447,7 @@ equivalent to @w{@samp{-s64MiB -m273}} Aliases for GNU gzip compatibility. @item --loose-trailing -When decompressing, testing or listing, allow trailing data whose first +When decompressing, testing, or listing, allow trailing data whose first bytes are so similar to the magic bytes of a lzip header that they can be confused with a corrupt header. Use this option if a file triggers a "corrupt header" error and the cause is not indeed a corrupt header. @@ -438,77 +479,83 @@ caused lzip to panic. @node Quality assurance -@chapter Design, development and testing of lzip +@chapter Design, development, and testing of lzip @cindex quality assurance -There are two ways of constructing a software design: One way is to make -it so simple that there are obviously no deficiencies and the other way -is to make it so complicated that there are no obvious deficiencies. The -first method is far more difficult.@* +There are two ways of constructing a software design: One way is to make it +so simple that there are obviously no deficiencies and the other way is to +make it so complicated that there are no obvious deficiencies. The first +method is far more difficult.@* --- C.A.R. Hoare -Lzip has been designed, written and tested with great care to replace -gzip and bzip2 as the standard general-purpose compressed format for -unix-like systems. This chapter describes the lessons learned from -these previous formats, and their application to the design of lzip. +Lzip is developed by volunteers who lack the resources required for +extensive testing in all circumstances. It is up to you to test lzip before +using it in mission-critical applications. However, a compressor like lzip +is not a toy, and maintaining it is not a hobby. Many people's data depend +on it. Therefore the lzip file format has been reviewed carefully and is +believed to be free from negligent design errors. + +Lzip has been designed, written, and tested with great care to replace gzip +and bzip2 as the standard general-purpose compressed format for unix-like +systems. This chapter describes the lessons learned from these previous +formats, and their application to the design of lzip. @sp 1 @section Format design -When gzip was designed in 1992, computers and operating systems were -much less capable than they are today. Gzip tried to work around some of -those limitations, like 8.3 file names, with additional fields in its -file format. - -Today those limitations have mostly disappeared, and the format of gzip -has proved to be unnecessarily complicated. It includes fields that were -never used, others that have lost their usefulness, and finally others -that have become too limited. - -Bzip2 was designed 5 years later, and its format is simpler than the one -of gzip. - -Probably the worst defect of the gzip format from the point of view of -data safety is the variable size of its header. If the byte at offset 3 -(flags) of a gzip member gets corrupted, it may become difficult to -recover the data, even if the compressed blocks are intact, because it -can't be known with certainty where the compressed blocks begin. - -By contrast, the header of a lzip member has a fixed length of 6. The -LZMA stream in a lzip member always starts at offset 6, making it -trivial to recover the data even if the whole header becomes corrupt. - -Bzip2 also provides a header of fixed length and marks the begin and end -of each compressed block with six magic bytes, making it possible to -find the compressed blocks even in case of file damage. But bzip2 does -not store the size of each compressed block, as lzip does. - -Lzip provides better data recovery capabilities than any other gzip-like -compressor because its format has been designed from the beginning to be -simple and safe. It also helps that the LZMA data stream as used by lzip -is extraordinarily safe. It provides embedded error detection. Any -distance larger than the dictionary size acts as a forbidden symbol, -allowing the decompressor to detect the approximate position of errors, -and leaving very little work for the check sequence (CRC and data sizes) -in the detection of errors. Lzip is usually able to detect all possible -bit flips in the compressed data without resorting to the check +When gzip was designed in 1992, computers and operating systems were much +less capable than they are today. The designers of gzip tried to work around +some of those limitations, like 8.3 file names, with additional fields in +the file format. + +Today those limitations have mostly disappeared, and the format of gzip has +proved to be unnecessarily complicated. It includes fields that were never +used, others that have lost their usefulness, and finally others that have +become too limited. + +Bzip2 was designed 5 years later, and its format is simpler than the one of +gzip. + +Probably the worst defect of the gzip format from the point of view of data +safety is the variable size of its header. If the byte at offset 3 (flags) +of a gzip member gets corrupted, it may become difficult to recover the +data, even if the compressed blocks are intact, because it can't be known +with certainty where the compressed blocks begin. + +By contrast, the header of a lzip member has a fixed length of 6. The LZMA +stream in a lzip member always starts at offset 6, making it trivial to +recover the data even if the whole header becomes corrupt. + +Bzip2 also provides a header of fixed length and marks the begin and end of +each compressed block with six magic bytes, making it possible to find the +compressed blocks even in case of file damage. But bzip2 does not store the +size of each compressed block, as lzip does. + +Lziprecover is able to provide unique data recovery capabilities because the +lzip format is extraordinarily safe. The simple and safe design of the file +format complements the embedded error detection provided by the LZMA data +stream. Any distance larger than the dictionary size acts as a forbidden +symbol, allowing the decompressor to detect the approximate position of +errors, and leaving very little work for the check sequence (CRC and data +sizes) in the detection of errors. Lzip is usually able to detect all +possible bit flips in the compressed data without resorting to the check sequence. It would be difficult to write an automatic recovery tool like -lziprecover for the gzip format. And, as far as I know, it has never -been written. +lziprecover for the gzip format. And, as far as I know, it has never been +written. Lzip, like gzip and bzip2, uses a CRC32 to check the integrity of the -decompressed data because it provides optimal accuracy in the detection -of errors up to a compressed size of about @w{16 GiB}, a size larger -than that of most files. In the case of lzip, the additional detection -capability of the decompressor reduces the probability of undetected -errors about four million times more, resulting in a combined integrity -checking optimally accurate for any member size produced by lzip. -Preliminary results suggest that the lzip format is safe enough to be -used in critical safety avionics systems. - -The lzip format is designed for long-term archiving. Therefore it -excludes any unneeded features that may interfere with the future -extraction of the decompressed data. +decompressed data because it provides optimal accuracy in the detection of +errors up to a compressed size of about @w{16 GiB}, a size larger than that +of most files. In the case of lzip, the additional detection capability of +the decompressor reduces the probability of undetected errors several +million times more, resulting in a combined integrity checking optimally +accurate for any member size produced by lzip. Preliminary results suggest +that the lzip format is safe enough to be used in critical safety avionics +systems. + +The lzip format is designed for long-term archiving. Therefore it excludes +any unneeded features that may interfere with the future extraction of the +decompressed data. @sp 1 @subsection Gzip format (mis)features not present in lzip @@ -517,37 +564,35 @@ extraction of the decompressed data. @item Multiple algorithms Gzip provides a CM (Compression Method) field that has never been used -because it is a bad idea to begin with. New compression methods may -require additional fields, making it impossible to implement new methods -and, at the same time, keep the same format. This field does not solve -the problem of format proliferation; it just makes the problem less -obvious. +because it is a bad idea to begin with. New compression methods may require +additional fields, making it impossible to implement new methods and, at the +same time, keep the same format. This field does not solve the problem of +format proliferation; it just makes the problem less obvious. @item Optional fields in header -Unless special precautions are taken, optional fields are generally a -bad idea because they produce a header of variable size. The gzip header -has 2 fields that, in addition to being optional, are zero-terminated. -This means that if any byte inside the field gets zeroed, or if the -terminating zero gets altered, gzip won't be able to find neither the -header CRC nor the compressed blocks. +Unless special precautions are taken, optional fields are generally a bad +idea because they produce a header of variable size. The gzip header has 2 +fields that, in addition to being optional, are zero-terminated. This means +that if any byte inside the field gets zeroed, or if the terminating zero +gets altered, gzip won't be able to find neither the header CRC nor the +compressed blocks. @item Optional CRC for the header -Using an optional CRC for the header is not only a bad idea, it is an -error; it circumvents the HD of the CRC and may prevent the extraction -of perfectly good data. For example, if the CRC is used and the bit -enabling it is reset by a bit flip, the header will appear to be intact -(in spite of being corrupt) while the compressed blocks will appear to -be totally unrecoverable (in spite of being intact). Very misleading -indeed. +Using an optional CRC for the header is not only a bad idea, it is an error; +it circumvents the Hamming distance (HD) of the CRC and may prevent the +extraction of perfectly good data. For example, if the CRC is used and the +bit enabling it is reset by a bit flip, the header will appear to be intact +(in spite of being corrupt) while the compressed blocks will appear to be +totally unrecoverable (in spite of being intact). Very misleading indeed. @item Metadata The gzip format stores some metadata, like the modification time of the -original file or the operating system on which compression took place. -This complicates reproducible compression (obtaining identical -compressed output from identical input). +original file or the operating system on which compression took place. This +complicates reproducible compression (obtaining identical compressed output +from identical input). @end table @@ -556,28 +601,26 @@ compressed output from identical input). @table @samp @item 64-bit size field -Probably the most frequently reported shortcoming of the gzip format is -that it only stores the least significant 32 bits of the uncompressed -size. The size of any file larger than @w{4 GiB} gets truncated. +Probably the most frequently reported shortcoming of the gzip format is that +it only stores the least significant 32 bits of the uncompressed size. The +size of any file larger than @w{4 GiB} gets truncated. Bzip2 does not store the uncompressed size of the file. The lzip format provides a 64-bit field for the uncompressed size. -Additionally, lzip produces multimember output automatically when the -size is too large for a single member, allowing for an unlimited -uncompressed size. +Additionally, lzip produces multimember output automatically when the size +is too large for a single member, allowing for an unlimited uncompressed +size. @item Distributed index -The lzip format provides a distributed index that, among other things, -helps plzip to decompress several times faster than pigz and helps -lziprecover do its job. Neither the gzip format nor the bzip2 format do -provide an index. +The lzip format provides a distributed index that, among other things, helps +plzip to decompress several times faster than pigz and helps lziprecover do +its job. Neither the gzip format nor the bzip2 format do provide an index. -A distributed index is safer and more scalable than a monolithic index. -The monolithic index introduces a single point of failure in the -compressed file and may limit the number of members or the total -uncompressed size. +A distributed index is safer and more scalable than a monolithic index. The +monolithic index introduces a single point of failure in the compressed file +and may limit the number of members or the total uncompressed size. @end table @@ -586,31 +629,29 @@ uncompressed size. @table @samp @item Accurate and robust error detection -The lzip format provides 3 factor integrity checking and the -decompressors report mismatches in each factor separately. This way if -just one byte in one factor fails but the other two factors match the -data, it probably means that the data are intact and the corruption just -affects the mismatching factor (CRC or data size) in the check sequence. +The lzip format provides 3 factor integrity checking and the decompressors +report mismatches in each factor separately. This way if just one byte in +one factor fails but the other two factors match the data, it probably means +that the data are intact and the corruption just affects the mismatching +factor (CRC or data size) in the check sequence. @item Multiple implementations -Just like the lzip format provides 3 factor protection against -undetected data corruption, the development methodology of the lzip -family of compressors provides 3 factor protection against undetected -programming errors. - -Three related but independent compressor implementations, lzip, clzip -and minilzip/lzlib, are developed concurrently. Every stable release of -any of them is subjected to a hundred hours of intensive testing to -verify that it produces identical output to the other two. This -guarantees that all three implement the same algorithm, and makes it -unlikely that any of them may contain serious undiscovered errors. In -fact, no errors have been discovered in lzip since 2009. - -Additionally, the three implementations have been extensively tested -with +Just like the lzip format provides 3 factor protection against undetected +data corruption, the development methodology of the lzip family of +compressors provides 3 factor protection against undetected programming +errors. + +Three related but independent compressor implementations, lzip, clzip, and +minilzip/lzlib, are developed concurrently. Every stable release of any of +them is tested to verify that it produces identical output to the other two. +This guarantees that all three implement the same algorithm, and makes it +unlikely that any of them may contain serious undiscovered errors. In fact, +no errors have been discovered in lzip since 2009. + +Additionally, the three implementations have been extensively tested with @uref{http://www.nongnu.org/lzip/manual/lziprecover_manual.html#Unzcrash,,unzcrash}, -valgrind and @samp{american fuzzy lop} without finding a single +valgrind, and @samp{american fuzzy lop} without finding a single vulnerability or false negative. @ifnothtml @xref{Unzcrash,,,lziprecover}. @@ -620,8 +661,8 @@ vulnerability or false negative. Lzip automatically adapts the dictionary size to the size of each file. In addition to reducing the amount of memory required for decompression, -this feature also minimizes the probability of being affected by RAM -errors during compression. @c key4_mask +this feature also minimizes the probability of being affected by RAM errors +during compression. @c key4_mask @item Exit status @@ -641,6 +682,7 @@ when there is no longer anything to take away.@* @sp 1 In the diagram below, a box like this: + @verbatim +---+ | | <-- the vertical bars might be missing @@ -648,6 +690,7 @@ In the diagram below, a box like this: @end verbatim represents one byte; a box like this: + @verbatim +==============+ | | @@ -662,6 +705,7 @@ The members simply appear one after another in the file, with no additional information before, between, or after them. Each member has the following structure: + @verbatim +--+--+--+--+----+----+=============+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ID string | VN | DS | LZMA stream | CRC32 | Data size | Member size | @@ -681,8 +725,7 @@ Just in case something needs to be modified in the future. 1 for now. @anchor{coded-dict-size} @item DS (coded dictionary size, 1 byte) The dictionary size is calculated by taking a power of 2 (the base size) -and subtracting from it a fraction between 0/16 and 7/16 of the base -size.@* +and subtracting from it a fraction between 0/16 and 7/16 of the base size.@* Bits 4-0 contain the base 2 logarithm of the base size (12 to 29).@* Bits 7-5 contain the numerator of the fraction (0 to 7) to subtract from the base size to obtain the dictionary size.@* @@ -690,12 +733,11 @@ Example: 0xD3 = 2^19 - 6 * 2^15 = 512 KiB - 6 * 32 KiB = 320 KiB@* Valid values for dictionary size range from 4 KiB to 512 MiB. @item LZMA stream -The LZMA stream, finished by an end of stream marker. Uses default -values for encoder properties. @xref{Stream format}, for a complete -description. +The LZMA stream, finished by an end of stream marker. Uses default values +for encoder properties. @xref{Stream format}, for a complete description. @item CRC32 (4 bytes) -CRC of the uncompressed original data. +Cyclic Redundancy Check (CRC) of the uncompressed original data. @item Data size (8 bytes) Size of the uncompressed original data. @@ -714,12 +756,15 @@ facilitates safe recovery of undamaged members from multimember files. In spite of its name (Lempel-Ziv-Markov chain-Algorithm), LZMA is not a concrete algorithm; it is more like "any algorithm using the LZMA coding -scheme". For example, the option @samp{-0} of lzip uses the scheme in almost +scheme". LZMA compression consists in describing the uncompressed data as a +succession of coding sequences from the set shown in Section @samp{What is +coded} (@pxref{what-is-coded}), and then encoding them using a range +encoder. For example, the option @samp{-0} of lzip uses the scheme in almost the simplest way possible; issuing the longest match it can find, or a -literal byte if it can't find a match. Inversely, a much more elaborated -way of finding coding sequences of minimum size than the one currently -used by lzip could be developed, and the resulting sequence could also -be coded using the LZMA coding scheme. +literal byte if it can't find a match. Inversely, a much more elaborated way +of finding coding sequences of minimum size than the one currently used by +lzip could be developed, and the resulting sequence could also be coded +using the LZMA coding scheme. Lzip currently implements two variants of the LZMA algorithm; fast (used by option @samp{-0}) and normal (used by all other compression levels). @@ -750,11 +795,11 @@ calls the match finder. current byte where a match of a given length can be found. 5) Go back to step 3 until a sequence (formed of pairs, repeated -distances and literal bytes) of minimum price has been formed. Where the +distances, and literal bytes) of minimum price has been formed. Where the price represents the number of output bits produced. 6) The range encoder encodes the sequence produced by the main encoder -and sends the produced bytes to the output stream. +and sends the bytes produced to the output stream. 7) Go back to step 3 until the input data are finished or until the member or volume size limits are reached. @@ -766,18 +811,27 @@ member or volume size limits are reached. 10) If there are more data to compress, go back to step 1. @sp 1 +During compression, lzip reads data in large blocks (one dictionary size at +a time). Therefore it may block for up to tens of seconds any process +feeding data to it through a pipe. This is normal. The blocking intervals +get longer with higher compression levels because dictionary size increases +(and compression speed decreases) with compression level. + @noindent The ideas embodied in lzip are due to (at least) the following people: -Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for -the definition of Markov chains), G.N.N. Martin (for the definition of -range encoding), Igor Pavlov (for putting all the above together in -LZMA), and Julian Seward (for bzip2's CLI). +Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the +definition of Markov chains), G.N.N. Martin (for the definition of range +encoding), Igor Pavlov (for putting all the above together in LZMA), and +Julian Seward (for bzip2's CLI). @node Stream format @chapter Format of the LZMA stream in lzip files @cindex format of the LZMA stream +Lzip uses a simplified form of the LZMA stream format chosen to maximize +safety and interoperability. + The LZMA algorithm has three parameters, called "special LZMA properties", to adjust it for some kinds of binary data. These parameters are; @samp{literal_context_bits} (with a default value of 3), @@ -787,12 +841,13 @@ compressor, lzip only uses the default values for these parameters. In particular @samp{literal_pos_state_bits} has been optimized away and does not even appear in the code. -Lzip also finishes the LZMA stream with an "End Of Stream" marker (the -distance-length pair 0xFFFFFFFFU, 2), which in conjunction with the -"member size" field in the member trailer allows the verification of +Lzip finishes the LZMA stream with an "End Of Stream" (EOS) marker +(the distance-length pair 0xFFFFFFFFU, 2), which in conjunction with the +@samp{member size} field in the member trailer allows the verification of stream integrity. The LZMA stream in lzip files always has these two features (default properties and EOS marker) and is referred to in this -document as LZMA-302eos or LZMA-lzip. +document as LZMA-302eos. The EOS marker is the only marker allowed in +lzip files. The second stage of LZMA is a range encoder that uses a different probability model for each type of symbol; distances, lengths, literal @@ -801,7 +856,7 @@ message into one number. Unlike Huffman coding, which assigns to each symbol a bit-pattern and concatenates all the bit-patterns together, range encoding can compress one symbol to less than one bit. Therefore the compressed data produced by a range encoder can't be split in pieces -that could be individually described. +that could be described individually. It seems that the only way of describing the LZMA-302eos stream is describing the algorithm that decodes it. And given the many details @@ -817,17 +872,16 @@ download directory. The source code of lzd is included in appendix A. @sp 1 @section What is coded -The LZMA stream includes literals, matches and repeated matches (matches +@anchor{what-is-coded} +The LZMA stream includes literals, matches, and repeated matches (matches reusing a recently used distance). There are 7 different coding sequences: @multitable @columnfractions .35 .14 .51 @headitem Bit sequence @tab Name @tab Description @item 0 + byte @tab literal @tab literal byte @item 1 + 0 + len + dis @tab match @tab distance-length pair -@item 1 + 1 + 0 + 0 @tab shortrep @tab 1 byte match at latest used -distance -@item 1 + 1 + 0 + 1 + len @tab rep0 @tab len bytes match at latest used -distance +@item 1 + 1 + 0 + 0 @tab shortrep @tab 1 byte match at latest used distance +@item 1 + 1 + 0 + 1 + len @tab rep0 @tab len bytes match at latest used distance @item 1 + 1 + 1 + 0 + len @tab rep1 @tab len bytes match at second latest used distance @item 1 + 1 + 1 + 1 + 0 + len @tab rep2 @tab len bytes match at third @@ -838,7 +892,8 @@ latest used distance @sp 1 In the following tables, multibit sequences are coded in normal order, -from MSB to LSB, except where noted otherwise. +from most significant bit (MSB) to least significant bit (LSB), except +where noted otherwise. Lengths (the @samp{len} in the table above) are coded as follows: @@ -853,36 +908,36 @@ Lengths (the @samp{len} in the table above) are coded as follows: The coding of distances is a little more complicated, so I'll begin explaining a simpler version of the encoding. -Imagine you need to code a number from 0 to @w{2^32 - 1}, and you want -to do it in a way that produces shorter codes for the smaller numbers. -You may first send the position of the most significant bit that is set -to 1, which you may find by making a bit scan from the left (from the -MSB). A position of 0 means that the number is 0 (no bit is set), 1 -means the LSB is the first bit set (the number is 1), and 32 means the -MSB is set (i.e., the number is @w{>= 0x80000000}). Let's call this bit -position a "slot". Then, if slot is @w{> 1}, you send the remaining -@w{slot - 1} bits. Let's call these bits "direct_bits" because they are -coded directly by value instead of indirectly by position. - -The inconvenient of this simple method is that it needs 6 bits to code -the slot, but it just uses 33 of the 64 possible values, wasting almost -half of the codes. - -The intelligent trick of LZMA is that it encodes the position of the -most significant bit set, along with the value of the next bit, in the -same 6 bits that would take to encode the position alone. This seems to -need 66 slots (2 * position + next_bit), but for slots 0 and 1 there is -no next bit, so the number of needed slots is 64 (0 to 63). +Imagine you need to encode a number from 0 to @w{2^32 - 1}, and you want to +do it in a way that produces shorter codes for the smaller numbers. You may +first encode the position of the most significant bit that is set to 1, +which you may find by making a bit scan from the left (from the MSB). A +position of 0 means that the number is 0 (no bit is set), 1 means the LSB is +the first bit set (the number is 1), and 32 means the MSB is set (i.e., the +number is @w{>= 0x80000000}). Then, if the position is @w{>= 2}, you encode +the remaining @w{position - 1} bits. Let's call these bits "direct_bits" +because they are coded directly by value instead of indirectly by position. + +The inconvenient of this simple method is that it needs 6 bits to encode the +position, but it just uses 33 of the 64 possible values, wasting almost half +of the codes. + +The intelligent trick of LZMA is that it encodes in what it calls a "slot" +the position of the most significant bit set, along with the value of the +next bit, using the same 6 bits that would take to encode the position +alone. This seems to need 66 slots (twice the number of positions), but for +positions 0 and 1 there is no next bit, so the number of slots needed is 64 +(0 to 63). The 6 bits representing this "slot number" are then context-coded. If -the distance is @w{>= 4}, the remaining bits are coded as follows. -@samp{direct_bits} is the amount of remaining bits (from 0 to 30) needed +the distance is @w{>= 4}, the remaining bits are encoded as follows. +@samp{direct_bits} is the amount of remaining bits (from 1 to 30) needed to form a complete distance, and is calculated as @w{(slot >> 1) - 1}. -If a distance needs 6 or more direct_bits, the last 4 bits are coded -separately. The last piece (all the direct_bits for distances 4 to 127 +If a distance needs 6 or more direct_bits, the last 4 bits are encoded +separately. The last piece (all the direct_bits for distances 4 to 127, or the last 4 bits for distances @w{>= 128}) is context-coded in reverse order (from LSB to MSB). For distances @w{>= 128}, the -@w{@samp{direct_bits - 4}} part is coded with fixed 0.5 probability. +@w{@samp{direct_bits - 4}} part is encoded with fixed 0.5 probability. @multitable @columnfractions .5 .5 @headitem Bit sequence @tab Description @@ -914,14 +969,14 @@ decoded data. Value of the 3 most significant bits of the latest byte decoded. @item len_state -Coded value of length @w{(length - 2)}, with a maximum of 3. The -resulting value is in the range 0 to 3. +Coded value of the current match length @w{(length - 2)}, with a maximum +of 3. The resulting value is in the range 0 to 3. @end table In the following table, @samp{!literal} is any sequence except a literal -byte. @samp{rep} is any one of @samp{rep0}, @samp{rep1}, @samp{rep2} or +byte. @samp{rep} is any one of @samp{rep0}, @samp{rep1}, @samp{rep2}, or @samp{rep3}. The types of previous sequences corresponding to each state are: @@ -999,18 +1054,18 @@ variable number of decoded bits, depending on how well these bits agree with their context. (See @samp{decode_bit} in the source). The range decoder state consists of two unsigned 32-bit variables; -@code{range} (representing the most significant part of the range size -not yet decoded), and @code{code} (representing the current point within -@code{range}). @code{range} is initialized to @w{(2^32 - 1)}, and -@code{code} is initialized to 0. +@samp{range} (representing the most significant part of the range size +not yet decoded), and @samp{code} (representing the current point within +@samp{range}). @samp{range} is initialized to @w{2^32 - 1}, and +@samp{code} is initialized to 0. The range encoder produces a first 0 byte that must be ignored by the range decoder. This is done by shifting 5 bytes in the initialization of -@code{code} instead of 4. (See the @samp{Range_decoder} constructor in +@samp{code} instead of 4. (See the @samp{Range_decoder} constructor in the source). @sp 1 -@section Decoding the LZMA stream +@section Decoding and verifying the LZMA stream After decoding the member header and obtaining the dictionary size, the range decoder is initialized and then the LZMA decoder enters a loop @@ -1019,6 +1074,10 @@ decoder with the appropriate contexts to decode the different coding sequences (matches, repeated matches, and literal bytes), until the "End Of Stream" marker is decoded. +Once the "End Of Stream" marker has been decoded, the decompressor reads and +decodes the member trailer, and verifies that the three integrity factors +(CRC, data size, and member size) match those calculated by the LZMA decoder. + @node Trailing data @chapter Extra data appended to the file @@ -1078,7 +1137,7 @@ where a file containing trailing data must be rejected, the option WARNING! Even if lzip is bug-free, other causes may result in a corrupt compressed file (bugs in the system libraries, memory errors, etc). Therefore, if the data you are going to compress are important, give the -@samp{--keep} option to lzip and don't remove the original file until you +option @samp{--keep} to lzip and don't remove the original file until you verify the compressed file with a command like @w{@samp{lzip -cd file.lz | cmp file -}}. Most RAM errors happening during compression can only be detected by comparing the compressed file with the @@ -1087,8 +1146,18 @@ contents, resulting in a valid compressed file containing wrong data. @sp 1 @noindent -Example 1: Replace a regular file with its compressed version -@samp{file.lz} and show the compression ratio. +Example 1: Extract all the files from archive @samp{foo.tar.lz}. + +@example + tar -xf foo.tar.lz +or + lzip -cd foo.tar.lz | tar -xf - +@end example + +@sp 1 +@noindent +Example 2: Replace a regular file with its compressed version @samp{file.lz} +and show the compression ratio. @example lzip -v file @@ -1096,8 +1165,8 @@ lzip -v file @sp 1 @noindent -Example 2: Like example 1 but the created @samp{file.lz} is multimember -with a member size of @w{1 MiB}. The compression ratio is not shown. +Example 3: Like example 1 but the created @samp{file.lz} is multimember with +a member size of @w{1 MiB}. The compression ratio is not shown. @example lzip -b 1MiB file @@ -1105,9 +1174,8 @@ lzip -b 1MiB file @sp 1 @noindent -Example 3: Restore a regular file from its compressed version -@samp{file.lz}. If the operation is successful, @samp{file.lz} is -removed. +Example 4: Restore a regular file from its compressed version +@samp{file.lz}. If the operation is successful, @samp{file.lz} is removed. @example lzip -d file.lz @@ -1115,8 +1183,8 @@ lzip -d file.lz @sp 1 @noindent -Example 4: Verify the integrity of the compressed file @samp{file.lz} -and show status. +Example 5: Verify the integrity of the compressed file @samp{file.lz} and +show status. @example lzip -tv file.lz @@ -1124,29 +1192,31 @@ lzip -tv file.lz @sp 1 @noindent -Example 5: Compress a whole device in /dev/sdc and send the output to +Example 6: Compress a whole device in /dev/sdc and send the output to @samp{file.lz}. @example -lzip -c /dev/sdc > file.lz + lzip -c /dev/sdc > file.lz +or + lzip /dev/sdc -o file.lz @end example @sp 1 @anchor{concat-example} @noindent -Example 6: The right way of concatenating the decompressed output of two -or more compressed files. @xref{Trailing data}. +Example 7: The right way of concatenating the decompressed output of two or +more compressed files. @xref{Trailing data}. @example Don't do this - cat file1.lz file2.lz file3.lz | lzip -d + cat file1.lz file2.lz file3.lz | lzip -d - Do this instead lzip -cd file1.lz file2.lz file3.lz @end example @sp 1 @noindent -Example 7: Decompress @samp{file.lz} partially until @w{10 KiB} of +Example 8: Decompress @samp{file.lz} partially until @w{10 KiB} of decompressed data are produced. @example @@ -1155,8 +1225,8 @@ lzip -cd file.lz | dd bs=1024 count=10 @sp 1 @noindent -Example 8: Decompress @samp{file.lz} partially from decompressed byte -10000 to decompressed byte 15000 (5000 bytes are produced). +Example 9: Decompress @samp{file.lz} partially from decompressed byte at +offset 10000 to decompressed byte at offset 14999 (5000 bytes are produced). @example lzip -cd file.lz | dd bs=1000 skip=10 count=5 @@ -1164,16 +1234,16 @@ lzip -cd file.lz | dd bs=1000 skip=10 count=5 @sp 1 @noindent -Example 9: Create a multivolume compressed tar archive with a volume -size of @w{1440 KiB}. +Example 10: Create a multivolume compressed tar archive with a volume size +of @w{1440 KiB}. @example -tar -c some_directory | lzip -S 1440KiB -o volume_name +tar -c some_directory | lzip -S 1440KiB -o volume_name - @end example @sp 1 @noindent -Example 10: Extract a multivolume compressed tar archive. +Example 11: Extract a multivolume compressed tar archive. @example lzip -cd volume_name*.lz | tar -xf - @@ -1181,9 +1251,9 @@ lzip -cd volume_name*.lz | tar -xf - @sp 1 @noindent -Example 11: Create a multivolume compressed backup of a large database -file with a volume size of @w{650 MB}, where each volume is a -multimember file with a member size of @w{32 MiB}. +Example 12: Create a multivolume compressed backup of a large database file +with a volume size of @w{650 MB}, where each volume is a multimember file +with a member size of @w{32 MiB}. @example lzip -b 32MiB -S 650MB big_db @@ -1202,7 +1272,7 @@ for all eternity, if not longer. If you find a bug in lzip, please send electronic mail to @email{lzip-bug@@nongnu.org}. Include the version number, which you can -find by running @w{@code{lzip --version}}. +find by running @w{@samp{lzip --version}}. @node Reference source code @@ -1210,28 +1280,28 @@ find by running @w{@code{lzip --version}}. @cindex reference source code @verbatim -/* Lzd - Educational decompressor for the lzip format - Copyright (C) 2013-2019 Antonio Diaz Diaz. +/* Lzd - Educational decompressor for the lzip format + Copyright (C) 2013-2021 Antonio Diaz Diaz. - This program is free software. Redistribution and use in source and - binary forms, with or without modification, are permitted provided - that the following conditions are met: + This program is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* - Exit status: 0 for a normal exit, 1 for environmental problems - (file not found, invalid flags, I/O errors, etc), 2 to indicate a - corrupt or invalid input file. + Exit status: 0 for a normal exit, 1 for environmental problems + (file not found, invalid flags, I/O errors, etc), 2 to indicate a + corrupt or invalid input file. */ #include <algorithm> @@ -1259,7 +1329,7 @@ public: void set_char() { - static const int next[states] = { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5 }; + const int next[states] = { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5 }; st = next[st]; } void set_match() { st = ( st < 7 ) ? 7 : 10; } @@ -1281,7 +1351,7 @@ enum { dis_slot_bits = 6, start_dis_model = 4, end_dis_model = 14, - modeled_distances = 1 << (end_dis_model / 2), // 128 + modeled_distances = 1 << ( end_dis_model / 2 ), // 128 dis_align_bits = 4, dis_align_size = 1 << dis_align_bits, @@ -1342,8 +1412,9 @@ public: const CRC32 crc32; -typedef uint8_t Lzip_header[6]; // 0-3 magic, 4 version, 5 coded_dict_size - +typedef uint8_t Lzip_header[6]; // 0-3 magic bytes + // 4 version + // 5 coded dictionary size typedef uint8_t Lzip_trailer[20]; // 0-3 CRC32 of the uncompressed data // 4-11 size of the uncompressed data @@ -1351,16 +1422,18 @@ typedef uint8_t Lzip_trailer[20]; class Range_decoder { + unsigned long long member_pos; uint32_t code; uint32_t range; public: - Range_decoder() : code( 0 ), range( 0xFFFFFFFFU ) + Range_decoder() : member_pos( 6 ), code( 0 ), range( 0xFFFFFFFFU ) { - for( int i = 0; i < 5; ++i ) code = (code << 8) | get_byte(); + for( int i = 0; i < 5; ++i ) code = ( code << 8 ) | get_byte(); } - uint8_t get_byte() { return std::getc( stdin ); } + uint8_t get_byte() { ++member_pos; return std::getc( stdin ); } + unsigned long long member_position() const { return member_pos; } unsigned decode( const int num_bits ) { @@ -1371,7 +1444,7 @@ public: symbol <<= 1; if( code >= range ) { code -= range; symbol |= 1; } if( range <= 0x00FFFFFFU ) // normalize - { range <<= 8; code = (code << 8) | get_byte(); } + { range <<= 8; code = ( code << 8 ) | get_byte(); } } return symbol; } @@ -1383,7 +1456,8 @@ public: if( code < bound ) { range = bound; - bm.probability += (bit_model_total - bm.probability) >> bit_model_move_bits; + bm.probability += + ( bit_model_total - bm.probability ) >> bit_model_move_bits; symbol = 0; } else @@ -1394,7 +1468,7 @@ public: symbol = 1; } if( range <= 0x00FFFFFFU ) // normalize - { range <<= 8; code = (code << 8) | get_byte(); } + { range <<= 8; code = ( code << 8 ) | get_byte(); } return symbol; } @@ -1403,7 +1477,7 @@ public: unsigned symbol = 1; for( int i = 0; i < num_bits; ++i ) symbol = ( symbol << 1 ) | decode_bit( bm[symbol] ); - return symbol - (1 << num_bits); + return symbol - ( 1 << num_bits ); } unsigned decode_tree_reversed( Bit_model bm[], const int num_bits ) @@ -1490,7 +1564,11 @@ public: ~LZ_decoder() { delete[] buffer; } unsigned crc() const { return crc_ ^ 0xFFFFFFFFU; } - unsigned long long data_position() const { return partial_data_pos + pos; } + unsigned long long data_position() const + { return partial_data_pos + pos; } + uint8_t get_byte() { return rdec.get_byte(); } + unsigned long long member_position() const + { return rdec.member_position(); } bool decode_member(); }; @@ -1502,7 +1580,6 @@ void LZ_decoder::flush_data() { const unsigned size = pos - stream_pos; crc32.update_buf( crc_, buffer + stream_pos, size ); - errno = 0; if( std::fwrite( buffer + stream_pos, 1, size, stdout ) != size ) { std::fprintf( stderr, "Write error: %s\n", std::strerror( errno ) ); std::exit( 1 ); } @@ -1513,7 +1590,7 @@ void LZ_decoder::flush_data() } -bool LZ_decoder::decode_member() // Returns false if error +bool LZ_decoder::decode_member() // Returns false if error { Bit_model bm_literal[1<<literal_context_bits][0x300]; Bit_model bm_match[State::states][pos_states]; @@ -1593,7 +1670,8 @@ bool LZ_decoder::decode_member() // Returns false if error direct_bits ); else { - rep0 += rdec.decode( direct_bits - dis_align_bits ) << dis_align_bits; + rep0 += + rdec.decode( direct_bits - dis_align_bits ) << dis_align_bits; rep0 += rdec.decode_tree_reversed( bm_align, dis_align_bits ); if( rep0 == 0xFFFFFFFFU ) // marker found { @@ -1615,20 +1693,21 @@ bool LZ_decoder::decode_member() // Returns false if error int main( const int argc, const char * const argv[] ) { - if( argc > 1 ) + if( argc > 2 || ( argc == 2 && std::strcmp( argv[1], "-d" ) != 0 ) ) { - std::printf( "Lzd %s - Educational decompressor for the lzip format.\n", - PROGVERSION ); - std::printf( "Study the source to learn how a lzip decompressor works.\n" - "See the lzip manual for an explanation of the code.\n" - "It is not safe to use lzd for any real work.\n" - "\nUsage: %s < file.lz > file\n", argv[0] ); - std::printf( "Lzd decompresses from standard input to standard output.\n" - "\nCopyright (C) 2019 Antonio Diaz Diaz.\n" - "This is free software: you are free to change and redistribute it.\n" - "There is NO WARRANTY, to the extent permitted by law.\n" - "Report bugs to lzip-bug@nongnu.org\n" - "Lzd home page: http://www.nongnu.org/lzip/lzd.html\n" ); + std::printf( + "Lzd %s - Educational decompressor for the lzip format.\n" + "Study the source to learn how a lzip decompressor works.\n" + "See the lzip manual for an explanation of the code.\n" + "\nUsage: %s [-d] < file.lz > file\n" + "Lzd decompresses from standard input to standard output.\n" + "\nCopyright (C) 2021 Antonio Diaz Diaz.\n" + "License 2-clause BSD.\n" + "This is free software: you are free to change and redistribute it.\n" + "There is NO WARRANTY, to the extent permitted by law.\n" + "Report bugs to lzip-bug@nongnu.org\n" + "Lzd home page: http://www.nongnu.org/lzip/lzd.html\n", + PROGVERSION, argv[0] ); return 0; } @@ -1644,9 +1723,9 @@ int main( const int argc, const char * const argv[] ) if( std::feof( stdin ) || std::memcmp( header, "LZIP\x01", 5 ) != 0 ) { if( first_member ) - { std::fputs( "Bad magic number (file not in lzip format).\n", stderr ); - return 2; } - break; + { std::fputs( "Bad magic number (file not in lzip format).\n", + stderr ); return 2; } + break; // ignore trailing data } unsigned dict_size = 1 << ( header[5] & 0x1F ); dict_size -= ( dict_size / 16 ) * ( ( header[5] >> 5 ) & 7 ); @@ -1659,18 +1738,30 @@ int main( const int argc, const char * const argv[] ) { std::fputs( "Data error\n", stderr ); return 2; } Lzip_trailer trailer; // verify trailer - for( int i = 0; i < 20; ++i ) trailer[i] = std::getc( stdin ); + for( int i = 0; i < 20; ++i ) trailer[i] = decoder.get_byte(); + int retval = 0; unsigned crc = 0; - for( int i = 3; i >= 0; --i ) { crc <<= 8; crc += trailer[i]; } + for( int i = 3; i >= 0; --i ) crc = ( crc << 8 ) + trailer[i]; + if( crc != decoder.crc() ) + { std::fputs( "CRC mismatch\n", stderr ); retval = 2; } + unsigned long long data_size = 0; - for( int i = 11; i >= 4; --i ) { data_size <<= 8; data_size += trailer[i]; } - if( crc != decoder.crc() || data_size != decoder.data_position() ) - { std::fputs( "CRC error\n", stderr ); return 2; } + for( int i = 11; i >= 4; --i ) + data_size = ( data_size << 8 ) + trailer[i]; + if( data_size != decoder.data_position() ) + { std::fputs( "Data size mismatch\n", stderr ); retval = 2; } + + unsigned long long member_size = 0; + for( int i = 19; i >= 12; --i ) + member_size = ( member_size << 8 ) + trailer[i]; + if( member_size != decoder.member_position() ) + { std::fputs( "Member size mismatch\n", stderr ); retval = 2; } + if( retval ) return retval; } if( std::fclose( stdout ) != 0 ) - { std::fprintf( stderr, "Error closing stdout: %s\n", std::strerror( errno ) ); - return 1; } + { std::fprintf( stderr, "Error closing stdout: %s\n", + std::strerror( errno ) ); return 1; } return 0; } @end verbatim @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 @@ -42,9 +42,8 @@ int LZ_encoder::get_match_pairs( Pair * pairs ) if( len_limit < 4 ) return 0; } - int maxlen = 0; + int maxlen = 3; // only used if pairs != 0 int num_pairs = 0; - const int pos1 = pos + 1; const int min_pos = ( pos > dictionary_size ) ? pos - dictionary_size : 0; const uint8_t * const data = ptr_to_current_pos(); @@ -57,32 +56,31 @@ int LZ_encoder::get_match_pairs( Pair * pairs ) if( pairs ) { - int np2 = prev_positions[key2]; - int np3 = prev_positions[key3]; + const int np2 = prev_positions[key2]; + const int np3 = prev_positions[key3]; if( np2 > min_pos && buffer[np2-1] == data[0] ) { pairs[0].dis = pos - np2; - pairs[0].len = maxlen = 2; + pairs[0].len = maxlen = 2 + ( np2 == np3 ); num_pairs = 1; } if( np2 != np3 && np3 > min_pos && buffer[np3-1] == data[0] ) { maxlen = 3; - np2 = np3; - pairs[num_pairs].dis = pos - np2; - ++num_pairs; + pairs[num_pairs++].dis = pos - np3; } if( num_pairs > 0 ) { - const int delta = pos1 - np2; + const int delta = pairs[num_pairs-1].dis + 1; while( maxlen < len_limit && data[maxlen-delta] == data[maxlen] ) ++maxlen; pairs[num_pairs-1].len = maxlen; + if( maxlen < 3 ) maxlen = 3; if( maxlen >= len_limit ) pairs = 0; // done. now just skip } - if( maxlen < 3 ) maxlen = 3; } + const int pos1 = pos + 1; prev_positions[key2] = pos1; prev_positions[key3] = pos1; int newpos1 = prev_positions[key4]; @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ class Len_prices diff --git a/encoder_base.cc b/encoder_base.cc index c2133bd..eb23532 100644 --- a/encoder_base.cc +++ b/encoder_base.cc @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 @@ -21,6 +21,7 @@ #include <cerrno> #include <cstdlib> #include <cstring> +#include <new> #include <string> #include <vector> #include <stdint.h> @@ -90,10 +91,10 @@ Matchfinder_base::Matchfinder_base( const int before_size_, if( !buffer ) throw std::bad_alloc(); if( read_block() && !at_stream_end && buffer_size < buffer_size_limit ) { - buffer_size = buffer_size_limit; - uint8_t * const tmp = (uint8_t *)std::realloc( buffer, buffer_size ); + uint8_t * const tmp = (uint8_t *)std::realloc( buffer, buffer_size_limit ); if( !tmp ) { std::free( buffer ); throw std::bad_alloc(); } buffer = tmp; + buffer_size = buffer_size_limit; read_block(); } if( at_stream_end && stream_pos < dict_size ) @@ -156,7 +157,7 @@ void Range_encoder::flush_data() } - // End Of Stream mark => (dis == 0xFFFFFFFFU, len == min_match_len) +// End Of Stream marker => (dis == 0xFFFFFFFFU, len == min_match_len) void LZ_encoder_base::full_flush( const State state ) { const int pos_state = data_position() & pos_state_mask; diff --git a/encoder_base.h b/encoder_base.h index 4c1962f..9d45565 100644 --- a/encoder_base.h +++ b/encoder_base.h @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ enum { price_shift_bits = 6, @@ -137,7 +137,7 @@ inline int price_symbol_reversed( const Bit_model bm[], int symbol, const bool bit = symbol & 1; symbol >>= 1; price += price_bit( bm[model], bit ); - model = ( model << 1 ) | bit; + model <<= 1; model |= bit; } return price; } @@ -315,27 +315,27 @@ public: void encode_tree3( Bit_model bm[], const int symbol ) { - int model = 1; bool bit = ( symbol >> 2 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[1], bit ); + int model = 2 | bit; bit = ( symbol >> 1 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[model], bit ); model <<= 1; model |= bit; encode_bit( bm[model], symbol & 1 ); } void encode_tree6( Bit_model bm[], const unsigned symbol ) { - int model = 1; bool bit = ( symbol >> 5 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[1], bit ); + int model = 2 | bit; bit = ( symbol >> 4 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[model], bit ); model <<= 1; model |= bit; bit = ( symbol >> 3 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[model], bit ); model <<= 1; model |= bit; bit = ( symbol >> 2 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[model], bit ); model <<= 1; model |= bit; bit = ( symbol >> 1 ) & 1; - encode_bit( bm[model], bit ); model = ( model << 1 ) | bit; + encode_bit( bm[model], bit ); model <<= 1; model |= bit; encode_bit( bm[model], symbol & 1 ); } @@ -346,7 +346,7 @@ public: { const bool bit = ( symbol >> i ) & 1; encode_bit( bm[model], bit ); - model = ( model << 1 ) | bit; + model <<= 1; model |= bit; } } @@ -358,7 +358,7 @@ public: const bool bit = symbol & 1; symbol >>= 1; encode_bit( bm[model], bit ); - model = ( model << 1 ) | bit; + model <<= 1; model |= bit; } } @@ -460,8 +460,8 @@ protected: const unsigned direct_dis = dis - base; if( dis_slot < end_dis_model ) - renc.encode_tree_reversed( bm_dis + ( base - dis_slot ), direct_dis, - direct_bits ); + renc.encode_tree_reversed( bm_dis + ( base - dis_slot ), + direct_dis, direct_bits ); else { renc.encode( direct_dis >> dis_align_bits, direct_bits - dis_align_bits ); diff --git a/fast_encoder.cc b/fast_encoder.cc index 8fc0d3a..f4598b8 100644 --- a/fast_encoder.cc +++ b/fast_encoder.cc @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 diff --git a/fast_encoder.h b/fast_encoder.h index 5570a36..5f8aa38 100644 --- a/fast_encoder.h +++ b/fast_encoder.h @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ class FLZ_encoder : public LZ_encoder_base @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 @@ -36,11 +36,11 @@ void list_line( const unsigned long long uncomp_size, const char * const input_filename ) { if( uncomp_size > 0 ) - std::printf( "%15llu %15llu %6.2f%% %s\n", uncomp_size, comp_size, + std::printf( "%14llu %14llu %6.2f%% %s\n", uncomp_size, comp_size, 100.0 - ( ( 100.0 * comp_size ) / uncomp_size ), input_filename ); else - std::printf( "%15llu %15llu -INF%% %s\n", uncomp_size, comp_size, + std::printf( "%14llu %14llu -INF%% %s\n", uncomp_size, comp_size, input_filename ); } @@ -62,15 +62,15 @@ int list_files( const std::vector< std::string > & filenames, from_stdin ? "(stdin)" : filenames[i].c_str(); struct stat in_stats; // not used const int infd = from_stdin ? STDIN_FILENO : - open_instream( input_filename, &in_stats, true, true ); - if( infd < 0 ) { if( retval < 1 ) retval = 1; continue; } + open_instream( input_filename, &in_stats, false, true ); + if( infd < 0 ) { set_retval( retval, 1 ); continue; } const Lzip_index lzip_index( infd, ignore_trailing, loose_trailing ); close( infd ); if( lzip_index.retval() != 0 ) { show_file_error( input_filename, lzip_index.error().c_str() ); - if( retval < lzip_index.retval() ) retval = lzip_index.retval(); + set_retval( retval, lzip_index.retval() ); continue; } if( verbosity >= 0 ) @@ -78,32 +78,27 @@ int list_files( const std::vector< std::string > & filenames, const unsigned long long udata_size = lzip_index.udata_size(); const unsigned long long cdata_size = lzip_index.cdata_size(); total_comp += cdata_size; total_uncomp += udata_size; ++files; + const long members = lzip_index.members(); if( first_post ) { first_post = false; if( verbosity >= 1 ) std::fputs( " dict memb trail ", stdout ); - std::fputs( " uncompressed compressed saved name\n", stdout ); + std::fputs( " uncompressed compressed saved name\n", stdout ); } if( verbosity >= 1 ) - { - unsigned dictionary_size = 0; - for( long i = 0; i < lzip_index.members(); ++i ) - dictionary_size = - std::max( dictionary_size, lzip_index.dictionary_size( i ) ); - const long long trailing_size = lzip_index.file_size() - cdata_size; - std::printf( "%s %5ld %6lld ", format_ds( dictionary_size ), - lzip_index.members(), trailing_size ); - } + std::printf( "%s %5ld %6lld ", + format_ds( lzip_index.dictionary_size() ), members, + lzip_index.file_size() - cdata_size ); list_line( udata_size, cdata_size, input_filename ); - if( verbosity >= 2 && lzip_index.members() > 1 ) + if( verbosity >= 2 && members > 1 ) { - std::fputs( " member data_pos data_size member_pos member_size\n", stdout ); - for( long i = 0; i < lzip_index.members(); ++i ) + std::fputs( " member data_pos data_size member_pos member_size\n", stdout ); + for( long i = 0; i < members; ++i ) { const Block & db = lzip_index.dblock( i ); const Block & mb = lzip_index.mblock( i ); - std::printf( "%5ld %15llu %15llu %15llu %15llu\n", + std::printf( "%6ld %14llu %14llu %14llu %14llu\n", i + 1, db.pos(), db.size(), mb.pos(), mb.size() ); } first_post = true; // reprint heading after list of members @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ class State @@ -78,7 +78,7 @@ inline int get_len_state( const int len ) { return std::min( len - min_match_len, len_states - 1 ); } inline int get_lit_state( const uint8_t prev_byte ) - { return ( prev_byte >> ( 8 - literal_context_bits ) ); } + { return prev_byte >> ( 8 - literal_context_bits ); } enum { bit_model_move_bits = 5, @@ -208,7 +208,7 @@ struct Lzip_header { uint8_t data[6]; // 0-3 magic bytes // 4 version - // 5 coded_dict_size + // 5 coded dictionary size enum { size = 6 }; void set_magic() { std::memcpy( data, lzip_magic, 4 ); data[4] = 1; } @@ -254,6 +254,10 @@ struct Lzip_header } return true; } + + bool verify() const + { return verify_magic() && verify_version() && + isvalid_ds( dictionary_size() ); } }; @@ -316,6 +320,8 @@ struct Error explicit Error( const char * const s ) : msg( s ) {} }; +inline void set_retval( int & retval, const int new_val ) + { if( retval < new_val ) retval = new_val; } const char * const bad_magic_msg = "Bad magic number (file not in lzip format)."; const char * const bad_dict_msg = "Invalid dictionary size in member header."; @@ -336,7 +342,7 @@ const char * bad_version( const unsigned version ); const char * format_ds( const unsigned dictionary_size ); void show_header( const unsigned dictionary_size ); int open_instream( const char * const name, struct stat * const in_statsp, - const bool no_ofile, const bool reg_only = false ); + const bool one_to_one, const bool reg_only = false ); void show_error( const char * const msg, const int errcode = 0, const bool help = false ); void show_file_error( const char * const filename, const char * const msg, diff --git a/lzip_index.cc b/lzip_index.cc index 4b2aadc..693ef20 100644 --- a/lzip_index.cc +++ b/lzip_index.cc @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 @@ -43,6 +43,17 @@ int seek_read( const int fd, uint8_t * const buf, const int size, } // end namespace +bool Lzip_index::check_header_error( const Lzip_header & header ) + { + if( !header.verify_magic() ) + { error_ = bad_magic_msg; retval_ = 2; return true; } + if( !header.verify_version() ) + { error_ = bad_version( header.version() ); retval_ = 2; return true; } + if( !isvalid_ds( header.dictionary_size() ) ) + { error_ = bad_dict_msg; retval_ = 2; return true; } + return false; + } + void Lzip_index::set_errno_error( const char * const msg ) { error_ = msg; error_ += std::strerror( errno ); @@ -58,14 +69,24 @@ void Lzip_index::set_num_error( const char * const msg, unsigned long long num ) } +bool Lzip_index::read_header( const int fd, Lzip_header & header, + const long long pos ) + { + if( seek_read( fd, header.data, Lzip_header::size, pos ) != Lzip_header::size ) + { set_errno_error( "Error reading member header: " ); return false; } + return true; + } + + // If successful, push last member and set pos to member header. -bool Lzip_index::skip_trailing_data( const int fd, long long & pos, - const bool ignore_trailing, const bool loose_trailing ) +bool Lzip_index::skip_trailing_data( const int fd, unsigned long long & pos, + const bool ignore_trailing, + const bool loose_trailing ) { + if( pos < min_member_size ) return false; enum { block_size = 16384, buffer_size = block_size + Lzip_trailer::size - 1 + Lzip_header::size }; uint8_t buffer[buffer_size]; - if( pos < min_member_size ) return false; int bsize = pos % block_size; // total bytes in buffer if( bsize <= buffer_size - block_size ) bsize += block_size; int search_size = bsize; // bytes to search for trailer @@ -88,26 +109,30 @@ bool Lzip_index::skip_trailing_data( const int fd, long long & pos, if( member_size > ipos + i || !trailer.verify_consistency() ) continue; Lzip_header header; - if( seek_read( fd, header.data, Lzip_header::size, - ipos + i - member_size ) != Lzip_header::size ) - { set_errno_error( "Error reading member header: " ); return false; } - const unsigned dictionary_size = header.dictionary_size(); - if( !header.verify_magic() || !header.verify_version() || - !isvalid_ds( dictionary_size ) ) continue; - if( (*(const Lzip_header *)( buffer + i )).verify_prefix( bsize - i ) ) - { error_ = "Last member in input file is truncated or corrupt."; - retval_ = 2; return false; } - if( !loose_trailing && bsize - i >= Lzip_header::size && - (*(const Lzip_header *)( buffer + i )).verify_corrupt() ) + if( !read_header( fd, header, ipos + i - member_size ) ) return false; + if( !header.verify() ) continue; + const Lzip_header & header2 = *(const Lzip_header *)( buffer + i ); + const bool full_h2 = bsize - i >= Lzip_header::size; + if( header2.verify_prefix( bsize - i ) ) // last member + { + if( !full_h2 ) error_ = "Last member in input file is truncated."; + else if( !check_header_error( header2 ) ) + error_ = "Last member in input file is truncated or corrupt."; + retval_ = 2; return false; + } + if( !loose_trailing && full_h2 && header2.verify_corrupt() ) { error_ = corrupt_mm_msg; retval_ = 2; return false; } if( !ignore_trailing ) { error_ = trailing_msg; retval_ = 2; return false; } pos = ipos + i - member_size; + const unsigned dictionary_size = header.dictionary_size(); member_vector.push_back( Member( 0, trailer.data_size(), pos, member_size, dictionary_size ) ); + if( dictionary_size_ < dictionary_size ) + dictionary_size_ = dictionary_size; return true; } - if( ipos <= 0 ) + if( ipos == 0 ) { set_num_error( "Bad trailer at pos ", pos - Lzip_trailer::size ); return false; } bsize = buffer_size; @@ -121,7 +146,7 @@ bool Lzip_index::skip_trailing_data( const int fd, long long & pos, Lzip_index::Lzip_index( const int infd, const bool ignore_trailing, const bool loose_trailing ) - : insize( lseek( infd, 0, SEEK_END ) ), retval_( 0 ) + : insize( lseek( infd, 0, SEEK_END ) ), retval_( 0 ), dictionary_size_( 0 ) { if( insize < 0 ) { set_errno_error( "Input file is not seekable: " ); return; } @@ -132,16 +157,10 @@ Lzip_index::Lzip_index( const int infd, const bool ignore_trailing, retval_ = 2; return; } Lzip_header header; - if( seek_read( infd, header.data, Lzip_header::size, 0 ) != Lzip_header::size ) - { set_errno_error( "Error reading member header: " ); return; } - if( !header.verify_magic() ) - { error_ = bad_magic_msg; retval_ = 2; return; } - if( !header.verify_version() ) - { error_ = bad_version( header.version() ); retval_ = 2; return; } - if( !isvalid_ds( header.dictionary_size() ) ) - { error_ = bad_dict_msg; retval_ = 2; return; } + if( !read_header( infd, header, 0 ) ) return; + if( check_header_error( header ) ) return; - long long pos = insize; // always points to a header or to EOF + unsigned long long pos = insize; // always points to a header or to EOF while( pos >= min_member_size ) { Lzip_trailer trailer; @@ -149,7 +168,7 @@ Lzip_index::Lzip_index( const int infd, const bool ignore_trailing, pos - Lzip_trailer::size ) != Lzip_trailer::size ) { set_errno_error( "Error reading member trailer: " ); break; } const unsigned long long member_size = trailer.member_size(); - if( member_size > (unsigned long long)pos || !trailer.verify_consistency() ) + if( member_size > pos || !trailer.verify_consistency() ) // bad trailer { if( member_vector.empty() ) { if( skip_trailing_data( infd, pos, ignore_trailing, loose_trailing ) ) @@ -157,12 +176,8 @@ Lzip_index::Lzip_index( const int infd, const bool ignore_trailing, set_num_error( "Bad trailer at pos ", pos - Lzip_trailer::size ); break; } - if( seek_read( infd, header.data, Lzip_header::size, - pos - member_size ) != Lzip_header::size ) - { set_errno_error( "Error reading member header: " ); break; } - const unsigned dictionary_size = header.dictionary_size(); - if( !header.verify_magic() || !header.verify_version() || - !isvalid_ds( dictionary_size ) ) + if( !read_header( infd, header, pos - member_size ) ) break; + if( !header.verify() ) // bad header { if( member_vector.empty() ) { if( skip_trailing_data( infd, pos, ignore_trailing, loose_trailing ) ) @@ -171,8 +186,11 @@ Lzip_index::Lzip_index( const int infd, const bool ignore_trailing, break; } pos -= member_size; + const unsigned dictionary_size = header.dictionary_size(); member_vector.push_back( Member( 0, trailer.data_size(), pos, member_size, dictionary_size ) ); + if( dictionary_size_ < dictionary_size ) + dictionary_size_ = dictionary_size; } if( pos != 0 || member_vector.empty() ) { diff --git a/lzip_index.h b/lzip_index.h index 3be6756..2ee13ad 100644 --- a/lzip_index.h +++ b/lzip_index.h @@ -1,18 +1,18 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef INT64_MAX @@ -52,10 +52,13 @@ class Lzip_index std::string error_; const long long insize; int retval_; + unsigned dictionary_size_; // largest dictionary size in the file + bool check_header_error( const Lzip_header & header ); void set_errno_error( const char * const msg ); void set_num_error( const char * const msg, unsigned long long num ); - bool skip_trailing_data( const int fd, long long & pos, + bool read_header( const int fd, Lzip_header & header, const long long pos ); + bool skip_trailing_data( const int fd, unsigned long long & pos, const bool ignore_trailing, const bool loose_trailing ); public: @@ -65,6 +68,7 @@ public: long members() const { return member_vector.size(); } const std::string & error() const { return error_; } int retval() const { return retval_; } + unsigned dictionary_size() const { return dictionary_size_; } long long udata_size() const { if( member_vector.empty() ) return 0; @@ -1,24 +1,24 @@ -/* Lzip - LZMA lossless data compressor - Copyright (C) 2008-2019 Antonio Diaz Diaz. +/* Lzip - LZMA lossless data compressor + Copyright (C) 2008-2021 Antonio Diaz Diaz. - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* - Exit status: 0 for a normal exit, 1 for environmental problems - (file not found, invalid flags, I/O errors, etc), 2 to indicate a - corrupt or invalid input file, 3 for an internal consistency error - (eg, bug) which caused lzip to panic. + Exit status: 0 for a normal exit, 1 for environmental problems + (file not found, invalid flags, I/O errors, etc), 2 to indicate a + corrupt or invalid input file, 3 for an internal consistency error + (eg, bug) which caused lzip to panic. */ #define _FILE_OFFSET_BITS 64 @@ -31,6 +31,7 @@ #include <cstdio> #include <cstdlib> #include <cstring> +#include <new> #include <string> #include <vector> #include <fcntl.h> @@ -79,8 +80,8 @@ int verbosity = 0; namespace { const char * const program_name = "lzip"; -const char * const program_year = "2019"; -const char * invocation_name = 0; +const char * const program_year = "2021"; +const char * invocation_name = program_name; // default value const struct { const char * from; const char * to; } known_extensions[] = { { ".lz", "" }, @@ -104,13 +105,15 @@ bool delete_output_on_interrupt = false; void show_help() { - std::printf( "Lzip is a lossless data compressor with a user interface similar to the\n" - "one of gzip or bzip2. Lzip can compress about as fast as gzip (lzip -0)\n" - "or compress most files more than bzip2 (lzip -9). Decompression speed is\n" - "intermediate between gzip and bzip2. Lzip is better than gzip and bzip2\n" - "from a data recovery perspective. Lzip has been designed, written and\n" - "tested with great care to replace gzip and bzip2 as the standard\n" - "general-purpose compressed format for unix-like systems.\n" + std::printf( "Lzip is a lossless data compressor with a user interface similar to the one\n" + "of gzip or bzip2. Lzip uses a simplified form of the 'Lempel-Ziv-Markov\n" + "chain-Algorithm' (LZMA) stream format, chosen to maximize safety and\n" + "interoperability. Lzip can compress about as fast as gzip (lzip -0) or\n" + "compress most files more than bzip2 (lzip -9). Decompression speed is\n" + "intermediate between gzip and bzip2. Lzip is better than gzip and bzip2 from\n" + "a data recovery perspective. Lzip has been designed, written, and tested\n" + "with great care to replace gzip and bzip2 as the standard general-purpose\n" + "compressed format for unix-like systems.\n" "\nUsage: %s [options] [files]\n", invocation_name ); std::printf( "\nOptions:\n" " -h, --help display this help and exit\n" @@ -124,7 +127,7 @@ void show_help() " -k, --keep keep (don't delete) input files\n" " -l, --list print (un)compressed file sizes\n" " -m, --match-length=<bytes> set match length limit in bytes [36]\n" - " -o, --output=<file> if reading standard input, write to <file>\n" + " -o, --output=<file> write to <file>, keep input files\n" " -q, --quiet suppress all messages\n" " -s, --dictionary-size=<bytes> set dictionary size limit in bytes [8 MiB]\n" " -S, --volume-size=<bytes> set volume size limit in bytes\n" @@ -134,7 +137,7 @@ void show_help() " --fast alias for -0\n" " --best alias for -9\n" " --loose-trailing allow trailing data seeming corrupt header\n" - "If no file names are given, or if a file is '-', lzip compresses or\n" + "\nIf no file names are given, or if a file is '-', lzip compresses or\n" "decompresses from standard input to standard output.\n" "Numbers may be followed by a multiplier: k = kB = 10^3 = 1000,\n" "Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc...\n" @@ -142,12 +145,19 @@ void show_help() "to 2^29 bytes.\n" "\nThe bidimensional parameter space of LZMA can't be mapped to a linear\n" "scale optimal for all files. If your files are large, very repetitive,\n" - "etc, you may need to use the --dictionary-size and --match-length\n" - "options directly to achieve optimal performance.\n" + "etc, you may need to use the options --dictionary-size and --match-length\n" + "directly to achieve optimal performance.\n" + "\nTo extract all the files from archive 'foo.tar.lz', use the commands\n" + "'tar -xf foo.tar.lz' or 'lzip -cd foo.tar.lz | tar -xf -'.\n" "\nExit status: 0 for a normal exit, 1 for environmental problems (file\n" "not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or\n" "invalid input file, 3 for an internal consistency error (eg, bug) which\n" "caused lzip to panic.\n" + "\nThe ideas embodied in lzip are due to (at least) the following people:\n" + "Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the\n" + "definition of Markov chains), G.N.N. Martin (for the definition of range\n" + "encoding), Igor Pavlov (for putting all the above together in LZMA), and\n" + "Julian Seward (for bzip2's CLI).\n" "\nReport bugs to lzip-bug@nongnu.org\n" "Lzip home page: http://www.nongnu.org/lzip/lzip.html\n" ); } @@ -209,7 +219,7 @@ const char * format_ds( const unsigned dictionary_size ) void show_header( const unsigned dictionary_size ) { - std::fprintf( stderr, "dictionary %s, ", format_ds( dictionary_size ) ); + std::fprintf( stderr, "dict %s, ", format_ds( dictionary_size ) ); } namespace { @@ -299,12 +309,15 @@ int extension_index( const std::string & name ) } -void set_c_outname( const std::string & name, const bool force_ext, - const bool multifile ) +void set_c_outname( const std::string & name, const bool filenames_given, + const bool force_ext, const bool multifile ) { + /* zupdate < 1.9 depends on lzip adding the extension '.lz' to name when + reading from standard input. */ output_filename = name; if( multifile ) output_filename += "00001"; - if( force_ext || multifile || extension_index( output_filename ) < 0 ) + if( force_ext || multifile || + ( !filenames_given && extension_index( output_filename ) < 0 ) ) output_filename += known_extensions[0].from; } @@ -330,7 +343,7 @@ void set_d_outname( const std::string & name, const int eindex ) } // end namespace int open_instream( const char * const name, struct stat * const in_statsp, - const bool no_ofile, const bool reg_only ) + const bool one_to_one, const bool reg_only ) { int infd = open( name, O_RDONLY | O_BINARY ); if( infd < 0 ) @@ -342,13 +355,12 @@ int open_instream( const char * const name, struct stat * const in_statsp, const bool can_read = ( i == 0 && !reg_only && ( S_ISBLK( mode ) || S_ISCHR( mode ) || S_ISFIFO( mode ) || S_ISSOCK( mode ) ) ); - if( i != 0 || ( !S_ISREG( mode ) && ( !can_read || !no_ofile ) ) ) + if( i != 0 || ( !S_ISREG( mode ) && ( !can_read || one_to_one ) ) ) { if( verbosity >= 0 ) std::fprintf( stderr, "%s: Input file '%s' is not a regular file%s.\n", - program_name, name, - ( can_read && !no_ofile ) ? - ",\n and '--stdout' was not specified" : "" ); + program_name, name, ( can_read && one_to_one ) ? + ",\n and neither '-c' nor '-o' were specified" : "" ); close( infd ); infd = -1; } @@ -360,7 +372,7 @@ namespace { int open_instream2( const char * const name, struct stat * const in_statsp, const Mode program_mode, const int eindex, - const bool recompress, const bool to_stdout ) + const bool one_to_one, const bool recompress ) { if( program_mode == m_compress && !recompress && eindex >= 0 ) { @@ -369,16 +381,15 @@ int open_instream2( const char * const name, struct stat * const in_statsp, program_name, name, known_extensions[eindex].from ); return -1; } - const bool no_ofile = ( to_stdout || program_mode == m_test ); - return open_instream( name, in_statsp, no_ofile, false ); + return open_instream( name, in_statsp, one_to_one, false ); } -bool open_outstream( const bool force, const bool from_stdin ) +bool open_outstream( const bool force, const bool protect ) { const mode_t usr_rw = S_IRUSR | S_IWUSR; const mode_t all_rw = usr_rw | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; - const mode_t outfd_mode = from_stdin ? all_rw : usr_rw; + const mode_t outfd_mode = protect ? usr_rw : all_rw; int flags = O_CREAT | O_WRONLY | O_BINARY; if( force ) flags |= O_TRUNC; else flags |= O_EXCL; @@ -397,25 +408,6 @@ bool open_outstream( const bool force, const bool from_stdin ) } -bool check_tty( const char * const input_filename, const int infd, - const Mode program_mode ) - { - if( program_mode == m_compress && isatty( outfd ) ) - { - show_error( "I won't write compressed data to a terminal.", 0, true ); - return false; - } - if( ( program_mode == m_decompress || program_mode == m_test ) && - isatty( infd ) ) - { - show_file_error( input_filename, - "I won't read compressed data from a terminal." ); - return false; - } - return true; - } - - void set_signals( void (*action)(int) ) { std::signal( SIGHUP, action ); @@ -448,7 +440,31 @@ extern "C" void signal_handler( int ) } - // Set permissions, owner and times. +bool check_tty_in( const char * const input_filename, const int infd, + const Mode program_mode, int & retval ) + { + if( ( program_mode == m_decompress || program_mode == m_test ) && + isatty( infd ) ) // for example /dev/tty + { show_file_error( input_filename, + "I won't read compressed data from a terminal." ); + close( infd ); set_retval( retval, 1 ); + if( program_mode != m_test ) cleanup_and_fail( retval ); + return false; } + return true; + } + +bool check_tty_out( const Mode program_mode ) + { + if( program_mode == m_compress && isatty( outfd ) ) + { show_file_error( output_filename.size() ? + output_filename.c_str() : "(stdout)", + "I won't write compressed data to a terminal." ); + return false; } + return true; + } + + +// Set permissions, owner, and times. void close_and_set_permissions( const struct stat * const in_statsp ) { bool warning = false; @@ -506,68 +522,60 @@ int compress( const unsigned long long cfile_size, LZ_encoder_base * encoder = 0; // polymorphic encoder if( verbosity >= 1 ) pp(); - try { - if( zero ) - encoder = new FLZ_encoder( infd, outfd ); - else - { - Lzip_header header; - if( header.dictionary_size( encoder_options.dictionary_size ) && - encoder_options.match_len_limit >= min_match_len_limit && - encoder_options.match_len_limit <= max_match_len ) - encoder = new LZ_encoder( header.dictionary_size(), - encoder_options.match_len_limit, infd, outfd ); - else internal_error( "invalid argument to encoder." ); - } + if( zero ) + encoder = new FLZ_encoder( infd, outfd ); + else + { + Lzip_header header; + if( header.dictionary_size( encoder_options.dictionary_size ) && + encoder_options.match_len_limit >= min_match_len_limit && + encoder_options.match_len_limit <= max_match_len ) + encoder = new LZ_encoder( header.dictionary_size(), + encoder_options.match_len_limit, infd, outfd ); + else internal_error( "invalid argument to encoder." ); + } - unsigned long long in_size = 0, out_size = 0, partial_volume_size = 0; - while( true ) // encode one member per iteration + unsigned long long in_size = 0, out_size = 0, partial_volume_size = 0; + while( true ) // encode one member per iteration + { + const unsigned long long size = ( volume_size > 0 ) ? + std::min( member_size, volume_size - partial_volume_size ) : member_size; + show_cprogress( cfile_size, in_size, encoder, &pp ); // init + if( !encoder->encode_member( size ) ) + { pp( "Encoder error." ); retval = 1; break; } + in_size += encoder->data_position(); + out_size += encoder->member_position(); + if( encoder->data_finished() ) break; + if( volume_size > 0 ) { - const unsigned long long size = ( volume_size > 0 ) ? - std::min( member_size, volume_size - partial_volume_size ) : member_size; - show_cprogress( cfile_size, in_size, encoder, &pp ); // init - if( !encoder->encode_member( size ) ) - { pp( "Encoder error." ); retval = 1; break; } - in_size += encoder->data_position(); - out_size += encoder->member_position(); - if( encoder->data_finished() ) break; - if( volume_size > 0 ) + partial_volume_size += encoder->member_position(); + if( partial_volume_size >= volume_size - min_dictionary_size ) { - partial_volume_size += encoder->member_position(); - if( partial_volume_size >= volume_size - min_dictionary_size ) + partial_volume_size = 0; + if( delete_output_on_interrupt ) { - partial_volume_size = 0; - if( delete_output_on_interrupt ) - { - close_and_set_permissions( in_statsp ); - if( !next_filename() ) - { pp( "Too many volume files." ); retval = 1; break; } - if( !open_outstream( true, !in_statsp ) ) { retval = 1; break; } - } + close_and_set_permissions( in_statsp ); + if( !next_filename() ) + { pp( "Too many volume files." ); retval = 1; break; } + if( !open_outstream( true, in_statsp ) ) { retval = 1; break; } } } - encoder->reset(); - } - - if( retval == 0 && verbosity >= 1 ) - { - if( in_size == 0 || out_size == 0 ) - std::fputs( " no data compressed.\n", stderr ); - else - std::fprintf( stderr, "%6.3f:1, %5.2f%% ratio, %5.2f%% saved, " - "%llu in, %llu out.\n", - (double)in_size / out_size, - ( 100.0 * out_size ) / in_size, - 100.0 - ( ( 100.0 * out_size ) / in_size ), - in_size, out_size ); } + encoder->reset(); } - catch( std::bad_alloc & ) + + if( retval == 0 && verbosity >= 1 ) { - pp( "Not enough memory. Try a smaller dictionary size." ); - retval = 1; + if( in_size == 0 || out_size == 0 ) + std::fputs( " no data compressed.\n", stderr ); + else + std::fprintf( stderr, "%6.3f:1, %5.2f%% ratio, %5.2f%% saved, " + "%llu in, %llu out.\n", + (double)in_size / out_size, + ( 100.0 * out_size ) / in_size, + 100.0 - ( ( 100.0 * out_size ) / in_size ), + in_size, out_size ); } - catch( Error & e ) { pp(); show_error( e.msg, errno ); retval = 1; } delete encoder; return retval; } @@ -612,70 +620,65 @@ int decompress( const unsigned long long cfile_size, const int infd, const bool loose_trailing, const bool testing ) { int retval = 0; - - try { - unsigned long long partial_file_pos = 0; - Range_decoder rdec( infd ); - for( bool first_member = true; ; first_member = false ) + unsigned long long partial_file_pos = 0; + Range_decoder rdec( infd ); + for( bool first_member = true; ; first_member = false ) + { + Lzip_header header; + rdec.reset_member_position(); + const int size = rdec.read_data( header.data, Lzip_header::size ); + if( rdec.finished() ) // End Of File { - Lzip_header header; - rdec.reset_member_position(); - const int size = rdec.read_data( header.data, Lzip_header::size ); - if( rdec.finished() ) // End Of File - { - if( first_member ) - { show_file_error( pp.name(), "File ends unexpectedly at member header." ); - retval = 2; } - else if( header.verify_prefix( size ) ) - { pp( "Truncated header in multimember file." ); - show_trailing_data( header.data, size, pp, true, -1 ); - retval = 2; } - else if( size > 0 && !show_trailing_data( header.data, size, pp, - true, ignore_trailing ) ) - retval = 2; - break; - } - if( !header.verify_magic() ) - { - if( first_member ) - { show_file_error( pp.name(), bad_magic_msg ); retval = 2; } - else if( !loose_trailing && header.verify_corrupt() ) - { pp( corrupt_mm_msg ); - show_trailing_data( header.data, size, pp, false, -1 ); - retval = 2; } - else if( !show_trailing_data( header.data, size, pp, false, ignore_trailing ) ) - retval = 2; - break; - } - if( !header.verify_version() ) - { pp( bad_version( header.version() ) ); retval = 2; break; } - const unsigned dictionary_size = header.dictionary_size(); - if( !isvalid_ds( dictionary_size ) ) - { pp( bad_dict_msg ); retval = 2; break; } - - if( verbosity >= 2 || ( verbosity == 1 && first_member ) ) pp(); - - LZ_decoder decoder( rdec, dictionary_size, outfd ); - show_dprogress( cfile_size, partial_file_pos, &rdec, &pp ); // init - const int result = decoder.decode_member( pp ); - partial_file_pos += rdec.member_position(); - if( result != 0 ) + if( first_member ) + { show_file_error( pp.name(), "File ends unexpectedly at member header." ); + retval = 2; } + else if( header.verify_prefix( size ) ) + { pp( "Truncated header in multimember file." ); + show_trailing_data( header.data, size, pp, true, -1 ); + retval = 2; } + else if( size > 0 && !show_trailing_data( header.data, size, pp, + true, ignore_trailing ) ) + retval = 2; + break; + } + if( !header.verify_magic() ) + { + if( first_member ) + { show_file_error( pp.name(), bad_magic_msg ); retval = 2; } + else if( !loose_trailing && header.verify_corrupt() ) + { pp( corrupt_mm_msg ); + show_trailing_data( header.data, size, pp, false, -1 ); + retval = 2; } + else if( !show_trailing_data( header.data, size, pp, false, ignore_trailing ) ) + retval = 2; + break; + } + if( !header.verify_version() ) + { pp( bad_version( header.version() ) ); retval = 2; break; } + const unsigned dictionary_size = header.dictionary_size(); + if( !isvalid_ds( dictionary_size ) ) + { pp( bad_dict_msg ); retval = 2; break; } + + if( verbosity >= 2 || ( verbosity == 1 && first_member ) ) pp(); + + LZ_decoder decoder( rdec, dictionary_size, outfd ); + show_dprogress( cfile_size, partial_file_pos, &rdec, &pp ); // init + const int result = decoder.decode_member( pp ); + partial_file_pos += rdec.member_position(); + if( result != 0 ) + { + if( verbosity >= 0 && result <= 2 ) { - if( verbosity >= 0 && result <= 2 ) - { - pp(); - std::fprintf( stderr, "%s at pos %llu\n", ( result == 2 ) ? - "File ends unexpectedly" : "Decoder error", - partial_file_pos ); - } - retval = 2; break; + pp(); + std::fprintf( stderr, "%s at pos %llu\n", ( result == 2 ) ? + "File ends unexpectedly" : "Decoder error", + partial_file_pos ); } - if( verbosity >= 2 ) - { std::fputs( testing ? "ok\n" : "done\n", stderr ); pp.reset(); } + retval = 2; break; } + if( verbosity >= 2 ) + { std::fputs( testing ? "ok\n" : "done\n", stderr ); pp.reset(); } } - catch( std::bad_alloc & ) { pp( "Not enough memory." ); retval = 1; } - catch( Error & e ) { pp(); show_error( e.msg, errno ); retval = 1; } if( verbosity == 1 && retval == 0 ) std::fputs( testing ? "ok\n" : "done\n", stderr ); return retval; @@ -792,8 +795,8 @@ int main( const int argc, const char * const argv[] ) { 3 << 23, 132 }, // -8 { 1 << 25, 273 } }; // -9 Lzma_options encoder_options = option_mapping[6]; // default = "-6" - const unsigned long long max_member_size = 0x0008000000000000ULL; - const unsigned long long max_volume_size = 0x4000000000000000ULL; + const unsigned long long max_member_size = 0x0008000000000000ULL; /* 2 PiB */ + const unsigned long long max_volume_size = 0x4000000000000000ULL; /* 4 EiB */ unsigned long long member_size = max_member_size; unsigned long long volume_size = 0; std::string default_output_filename; @@ -806,20 +809,20 @@ int main( const int argc, const char * const argv[] ) bool recompress = false; bool to_stdout = false; bool zero = false; - invocation_name = argv[0]; + if( argc > 0 ) invocation_name = argv[0]; enum { opt_lt = 256 }; const Arg_parser::Option options[] = { { '0', "fast", Arg_parser::no }, - { '1', 0, Arg_parser::no }, - { '2', 0, Arg_parser::no }, - { '3', 0, Arg_parser::no }, - { '4', 0, Arg_parser::no }, - { '5', 0, Arg_parser::no }, - { '6', 0, Arg_parser::no }, - { '7', 0, Arg_parser::no }, - { '8', 0, Arg_parser::no }, + { '1', 0, Arg_parser::no }, + { '2', 0, Arg_parser::no }, + { '3', 0, Arg_parser::no }, + { '4', 0, Arg_parser::no }, + { '5', 0, Arg_parser::no }, + { '6', 0, Arg_parser::no }, + { '7', 0, Arg_parser::no }, + { '8', 0, Arg_parser::no }, { '9', "best", Arg_parser::no }, { 'a', "trailing-error", Arg_parser::no }, { 'b', "member-size", Arg_parser::yes }, @@ -840,7 +843,7 @@ int main( const int argc, const char * const argv[] ) { 'v', "verbose", Arg_parser::no }, { 'V', "version", Arg_parser::no }, { opt_lt, "loose-trailing", Arg_parser::no }, - { 0 , 0, Arg_parser::no } }; + { 0, 0, Arg_parser::no } }; const Arg_parser parser( argc, argv, options ); if( parser.error().size() ) // bad option @@ -872,7 +875,8 @@ int main( const int argc, const char * const argv[] ) getnum( arg, min_match_len_limit, max_match_len ); zero = false; break; case 'n': break; - case 'o': default_output_filename = sarg; break; + case 'o': if( sarg == "-" ) to_stdout = true; + else { default_output_filename = sarg; } break; case 'q': verbosity = -1; break; case 's': encoder_options.dictionary_size = get_dict_size( arg ); zero = false; break; @@ -901,119 +905,115 @@ int main( const int argc, const char * const argv[] ) if( program_mode == m_list ) return list_files( filenames, ignore_trailing, loose_trailing ); - if( program_mode == m_test ) - outfd = -1; - else if( program_mode == m_compress ) + if( program_mode == m_compress ) { + if( volume_size > 0 && !to_stdout && default_output_filename.size() && + filenames.size() > 1 ) + { show_error( "Only can compress one file when using '-o' and '-S'.", + 0, true ); return 1; } dis_slots.init(); prob_prices.init(); } + else volume_size = 0; + if( program_mode == m_test ) to_stdout = false; // apply overrides + if( program_mode == m_test || to_stdout ) default_output_filename.clear(); - if( !to_stdout && program_mode != m_test && - ( filenames_given || default_output_filename.size() ) ) + if( to_stdout && program_mode != m_test ) // check tty only once + { outfd = STDOUT_FILENO; if( !check_tty_out( program_mode ) ) return 1; } + else outfd = -1; + + const bool to_file = !to_stdout && program_mode != m_test && + default_output_filename.size(); + if( !to_stdout && program_mode != m_test && ( filenames_given || to_file ) ) set_signals( signal_handler ); Pretty_print pp( filenames ); int failed_tests = 0; int retval = 0; + const bool one_to_one = !to_stdout && program_mode != m_test && !to_file; bool stdin_used = false; for( unsigned i = 0; i < filenames.size(); ++i ) { std::string input_filename; int infd; struct stat in_stats; - output_filename.clear(); - if( filenames[i].empty() || filenames[i] == "-" ) + pp.set_name( filenames[i] ); + if( filenames[i] == "-" ) { if( stdin_used ) continue; else stdin_used = true; infd = STDIN_FILENO; - if( program_mode != m_test ) - { - if( to_stdout || default_output_filename.empty() ) - outfd = STDOUT_FILENO; - else - { - if( program_mode == m_compress ) - set_c_outname( default_output_filename, false, volume_size > 0 ); - else output_filename = default_output_filename; - if( !open_outstream( force, true ) ) - { - if( retval < 1 ) retval = 1; - close( infd ); - continue; - } - } - } + if( !check_tty_in( pp.name(), infd, program_mode, retval ) ) continue; + if( one_to_one ) { outfd = STDOUT_FILENO; output_filename.clear(); } } else { const int eindex = extension_index( input_filename = filenames[i] ); infd = open_instream2( input_filename.c_str(), &in_stats, program_mode, - eindex, recompress, to_stdout ); - if( infd < 0 ) { if( retval < 1 ) retval = 1; continue; } - if( program_mode != m_test ) + eindex, one_to_one, recompress ); + if( infd < 0 ) { set_retval( retval, 1 ); continue; } + if( !check_tty_in( pp.name(), infd, program_mode, retval ) ) continue; + if( one_to_one ) // open outfd after verifying infd { - if( to_stdout ) outfd = STDOUT_FILENO; - else - { - if( program_mode == m_compress ) - set_c_outname( input_filename, true, volume_size > 0 ); - else set_d_outname( input_filename, eindex ); - if( !open_outstream( force, false ) ) - { - if( retval < 1 ) retval = 1; - close( infd ); - continue; - } - } + if( program_mode == m_compress ) + set_c_outname( input_filename, true, true, volume_size > 0 ); + else set_d_outname( input_filename, eindex ); + if( !open_outstream( force, true ) ) + { close( infd ); set_retval( retval, 1 ); continue; } } } - pp.set_name( input_filename ); - if( !check_tty( pp.name(), infd, program_mode ) ) + if( one_to_one && !check_tty_out( program_mode ) ) + { set_retval( retval, 1 ); return retval; } // don't delete a tty + + if( to_file && outfd < 0 ) // open outfd after verifying infd { - if( retval < 1 ) retval = 1; - if( program_mode == m_test ) { close( infd ); continue; } - cleanup_and_fail( retval ); + if( program_mode == m_compress ) set_c_outname( default_output_filename, + filenames_given, false, volume_size > 0 ); + else output_filename = default_output_filename; + if( !open_outstream( force, false ) || !check_tty_out( program_mode ) ) + return 1; // check tty only once and don't try to delete a tty } - const struct stat * const in_statsp = input_filename.size() ? &in_stats : 0; + const struct stat * const in_statsp = + ( input_filename.size() && one_to_one ) ? &in_stats : 0; const unsigned long long cfile_size = - ( in_statsp && S_ISREG( in_statsp->st_mode ) ) ? - ( in_statsp->st_size + 99 ) / 100 : 0; + ( input_filename.size() && S_ISREG( in_stats.st_mode ) ) ? + ( in_stats.st_size + 99 ) / 100 : 0; int tmp; - if( program_mode == m_compress ) - tmp = compress( cfile_size, member_size, volume_size, infd, - encoder_options, pp, in_statsp, zero ); - else - tmp = decompress( cfile_size, infd, pp, ignore_trailing, - loose_trailing, program_mode == m_test ); - if( close( infd ) != 0 ) - { - show_error( input_filename.size() ? "Error closing input file" : - "Error closing stdin", errno ); - if( tmp < 1 ) tmp = 1; + try { + if( program_mode == m_compress ) + tmp = compress( cfile_size, member_size, volume_size, infd, + encoder_options, pp, in_statsp, zero ); + else + tmp = decompress( cfile_size, infd, pp, ignore_trailing, + loose_trailing, program_mode == m_test ); } - if( tmp > retval ) retval = tmp; + catch( std::bad_alloc & ) + { pp( ( program_mode == m_compress ) ? + "Not enough memory. Try a smaller dictionary size." : + "Not enough memory." ); tmp = 1; } + catch( Error & e ) { pp(); show_error( e.msg, errno ); tmp = 1; } + if( close( infd ) != 0 ) + { show_file_error( pp.name(), "Error closing input file", errno ); + set_retval( tmp, 1 ); } + set_retval( retval, tmp ); if( tmp ) { if( program_mode != m_test ) cleanup_and_fail( retval ); else ++failed_tests; } - if( delete_output_on_interrupt ) + if( delete_output_on_interrupt && one_to_one ) close_and_set_permissions( in_statsp ); - if( input_filename.size() ) - { - if( !keep_input_files && !to_stdout && program_mode != m_test && - ( program_mode != m_compress || volume_size == 0 ) ) - std::remove( input_filename.c_str() ); - } + if( input_filename.size() && !keep_input_files && one_to_one && + ( program_mode != m_compress || volume_size == 0 ) ) + std::remove( input_filename.c_str() ); } - if( outfd >= 0 && close( outfd ) != 0 ) + if( delete_output_on_interrupt ) close_and_set_permissions( 0 ); // -o + else if( outfd >= 0 && close( outfd ) != 0 ) // -c { show_error( "Error closing stdout", errno ); - if( retval < 1 ) retval = 1; + set_retval( retval, 1 ); } if( failed_tests > 0 && verbosity >= 1 && filenames.size() > 1 ) std::fprintf( stderr, "%s: warning: %d %s failed the test.\n", diff --git a/testsuite/check.sh b/testsuite/check.sh index ba85edc..3b887b9 100755 --- a/testsuite/check.sh +++ b/testsuite/check.sh @@ -1,9 +1,9 @@ #! /bin/sh # check script for Lzip - LZMA lossless data compressor -# Copyright (C) 2008-2019 Antonio Diaz Diaz. +# Copyright (C) 2008-2021 Antonio Diaz Diaz. # # This script is free software: you have unlimited permission -# to copy, distribute and modify it. +# to copy, distribute, and modify it. LC_ALL=C export LC_ALL @@ -30,6 +30,8 @@ cd "${objdir}"/tmp || framework_failure cat "${testdir}"/test.txt > in || framework_failure in_lz="${testdir}"/test.txt.lz +in_em="${testdir}"/test_em.txt.lz +fox_lz="${testdir}"/fox.lz fail=0 test_failed() { fail=1 ; printf " $1" ; [ -z "$2" ] || printf "($2)" ; } @@ -58,6 +60,16 @@ done [ $? = 2 ] || test_failed $LINENO "${LZIP}" -dq -o in < "${in_lz}" [ $? = 1 ] || test_failed $LINENO +"${LZIP}" -dq -o in "${in_lz}" +[ $? = 1 ] || test_failed $LINENO +"${LZIP}" -dq -o out nx_file.lz +[ $? = 1 ] || test_failed $LINENO +[ ! -e out ] || test_failed $LINENO +"${LZIP}" -q -o out.lz nx_file +[ $? = 1 ] || test_failed $LINENO +[ ! -e out.lz ] || test_failed $LINENO +"${LZIP}" -qf -S100k -o out in in +[ $? = 1 ] || test_failed $LINENO # these are for code coverage "${LZIP}" -lt "${in_lz}" 2> /dev/null [ $? = 1 ] || test_failed $LINENO @@ -65,7 +77,9 @@ done [ $? = 1 ] || test_failed $LINENO "${LZIP}" -cdt "${in_lz}" > out 2> /dev/null [ $? = 1 ] || test_failed $LINENO -"${LZIP}" -t -- nx_file 2> /dev/null +"${LZIP}" -t -- nx_file.lz 2> /dev/null +[ $? = 1 ] || test_failed $LINENO +"${LZIP}" -t "" < /dev/null 2> /dev/null [ $? = 1 ] || test_failed $LINENO "${LZIP}" --help > /dev/null || test_failed $LINENO "${LZIP}" -n1 -V > /dev/null || test_failed $LINENO @@ -89,12 +103,26 @@ printf "LZIP\001+.............................." | "${LZIP}" -t 2> /dev/null printf "\ntesting decompression..." -"${LZIP}" -lq "${in_lz}" || test_failed $LINENO -"${LZIP}" -t "${in_lz}" || test_failed $LINENO -"${LZIP}" -cd "${in_lz}" > copy || test_failed $LINENO -cmp in copy || test_failed $LINENO +for i in "${in_lz}" "${in_em}" ; do + "${LZIP}" -lq "$i" || test_failed $LINENO "$i" + "${LZIP}" -t "$i" || test_failed $LINENO "$i" + "${LZIP}" -d "$i" -o copy || test_failed $LINENO "$i" + cmp in copy || test_failed $LINENO "$i" + "${LZIP}" -cd "$i" > copy || test_failed $LINENO "$i" + cmp in copy || test_failed $LINENO "$i" + "${LZIP}" -d "$i" -o - > copy || test_failed $LINENO "$i" + cmp in copy || test_failed $LINENO "$i" + "${LZIP}" -d < "$i" > copy || test_failed $LINENO "$i" + cmp in copy || test_failed $LINENO "$i" + rm -f copy || framework_failure +done + +lines=$("${LZIP}" -tvv "${in_em}" 2>&1 | wc -l) || test_failed $LINENO +[ "${lines}" -eq 8 ] || test_failed $LINENO "${lines}" + +lines=$("${LZIP}" -lvv "${in_em}" | wc -l) || test_failed $LINENO +[ "${lines}" -eq 11 ] || test_failed $LINENO "${lines}" -rm -f copy || framework_failure cat "${in_lz}" > copy.lz || framework_failure "${LZIP}" -dk copy.lz || test_failed $LINENO cmp in copy || test_failed $LINENO @@ -114,10 +142,16 @@ cmp in copy || test_failed $LINENO printf "to be overwritten" > copy || framework_failure "${LZIP}" -df -o copy < "${in_lz}" || test_failed $LINENO cmp in copy || test_failed $LINENO +rm -f out copy || framework_failure +"${LZIP}" -d -o ./- "${in_lz}" || test_failed $LINENO +cmp in ./- || test_failed $LINENO +rm -f ./- || framework_failure +"${LZIP}" -d -o ./- < "${in_lz}" || test_failed $LINENO +cmp in ./- || test_failed $LINENO +rm -f ./- || framework_failure -rm -f copy || framework_failure -"${LZIP}" < in > anyothername || test_failed $LINENO -"${LZIP}" -dv --output copy - anyothername - < "${in_lz}" 2> /dev/null || +cat "${in_lz}" > anyothername || framework_failure +"${LZIP}" -dv - anyothername - < "${in_lz}" > copy 2> /dev/null || test_failed $LINENO cmp in copy || test_failed $LINENO cmp in anyothername.out || test_failed $LINENO @@ -158,21 +192,19 @@ done cmp in copy || test_failed $LINENO cat in in > in2 || framework_failure -cat "${in_lz}" "${in_lz}" > in2.lz || framework_failure -"${LZIP}" -lq in2.lz || test_failed $LINENO -"${LZIP}" -t in2.lz || test_failed $LINENO -"${LZIP}" -cd in2.lz > copy2 || test_failed $LINENO +"${LZIP}" -lq "${in_lz}" "${in_lz}" || test_failed $LINENO +"${LZIP}" -t "${in_lz}" "${in_lz}" || test_failed $LINENO +"${LZIP}" -cd "${in_lz}" "${in_lz}" -o out > copy2 || test_failed $LINENO +[ ! -e out ] || test_failed $LINENO # override -o cmp in2 copy2 || test_failed $LINENO - -"${LZIP}" --output=copy2.lz < in2 || test_failed $LINENO -"${LZIP}" -lq copy2.lz || test_failed $LINENO -"${LZIP}" -t copy2.lz || test_failed $LINENO -"${LZIP}" -cd copy2.lz > copy2 || test_failed $LINENO +rm -f copy2 || framework_failure +"${LZIP}" -d "${in_lz}" "${in_lz}" -o copy2 || test_failed $LINENO cmp in2 copy2 || test_failed $LINENO +rm -f copy2 || framework_failure +cat "${in_lz}" "${in_lz}" > copy2.lz || framework_failure printf "\ngarbage" >> copy2.lz || framework_failure "${LZIP}" -tvvvv copy2.lz 2> /dev/null || test_failed $LINENO -rm -f copy2 || framework_failure "${LZIP}" -alq copy2.lz [ $? = 2 ] || test_failed $LINENO "${LZIP}" -atq copy2.lz @@ -188,68 +220,92 @@ rm -f copy2 || framework_failure printf "to be overwritten" > copy2 || framework_failure "${LZIP}" -df copy2.lz || test_failed $LINENO cmp in2 copy2 || test_failed $LINENO -rm -f in2 copy2 || framework_failure +rm -f copy2 || framework_failure printf "\ntesting compression..." +"${LZIP}" -c -0 in in in -S100k -o out3.lz > copy2.lz || test_failed $LINENO +[ ! -e out3.lz ] || test_failed $LINENO # override -o and -S +"${LZIP}" -0f in in --output=copy2.lz || test_failed $LINENO +"${LZIP}" -d copy2.lz -o out2 || test_failed $LINENO +cmp in2 out2 || test_failed $LINENO +rm -f in2 out2 copy2.lz || framework_failure + "${LZIP}" -cf "${in_lz}" > out 2> /dev/null # /dev/null is a tty on OS/2 [ $? = 1 ] || test_failed $LINENO -"${LZIP}" -cFvvm36 "${in_lz}" > out 2> /dev/null || test_failed $LINENO +"${LZIP}" -Fvvm36 -o - "${in_lz}" > out 2> /dev/null || test_failed $LINENO "${LZIP}" -cd out | "${LZIP}" -d > copy || test_failed $LINENO cmp in copy || test_failed $LINENO +"${LZIP}" -0 -o ./- in || test_failed $LINENO +"${LZIP}" -cd ./- | cmp in - || test_failed $LINENO +rm -f ./- || framework_failure +"${LZIP}" -0 -o ./- < in || test_failed $LINENO # add .lz +[ ! -e ./- ] || test_failed $LINENO +"${LZIP}" -cd -- -.lz | cmp in - || test_failed $LINENO +rm -f ./-.lz || framework_failure + for i in s4Ki 0 1 2 3 4 5 6 7 8 9 ; do "${LZIP}" -k -$i in || test_failed $LINENO $i mv -f in.lz copy.lz || test_failed $LINENO $i printf "garbage" >> copy.lz || framework_failure "${LZIP}" -df copy.lz || test_failed $LINENO $i cmp in copy || test_failed $LINENO $i -done -for i in s4Ki 0 1 2 3 4 5 6 7 8 9 ; do - "${LZIP}" -c -$i in > out || test_failed $LINENO $i + "${LZIP}" -$i in -c > out || test_failed $LINENO $i + "${LZIP}" -$i in -o o_out || test_failed $LINENO $i # don't add .lz + [ ! -e o_out.lz ] || test_failed $LINENO + cmp out o_out || test_failed $LINENO $i + rm -f o_out || framework_failure printf "g" >> out || framework_failure "${LZIP}" -cd out > copy || test_failed $LINENO $i cmp in copy || test_failed $LINENO $i -done -for i in s4Ki 0 1 2 3 4 5 6 7 8 9 ; do "${LZIP}" -$i < in > out || test_failed $LINENO $i "${LZIP}" -d < out > copy || test_failed $LINENO $i cmp in copy || test_failed $LINENO $i -done -for i in s4Ki 0 1 2 3 4 5 6 7 8 9 ; do - "${LZIP}" -f -$i -o out < in || test_failed $LINENO $i + rm -f out || framework_failure + printf "to be overwritten" > out.lz || framework_failure + "${LZIP}" -f -$i -o out < in || test_failed $LINENO $i # add .lz + [ ! -e out ] || test_failed $LINENO "${LZIP}" -df -o copy < out.lz || test_failed $LINENO $i cmp in copy || test_failed $LINENO $i done -rm -f out.lz || framework_failure +rm -f out out.lz || framework_failure cat in in in in in in in in > in8 || framework_failure "${LZIP}" -1s12 -S100k in8 || test_failed $LINENO "${LZIP}" -t in800001.lz in800002.lz || test_failed $LINENO "${LZIP}" -cd in800001.lz in800002.lz | cmp in8 - || test_failed $LINENO +[ ! -e in800003.lz ] || test_failed $LINENO rm -f in800001.lz in800002.lz || framework_failure -"${LZIP}" -1s12 -S100k -o out.lz < in8 || test_failed $LINENO +"${LZIP}" -1s12 -S100k -o out.lz in8 || test_failed $LINENO +# ignore -S +"${LZIP}" -d out.lz00001.lz out.lz00002.lz -S100k -o out || test_failed $LINENO +cmp in8 out || test_failed $LINENO "${LZIP}" -t out.lz00001.lz out.lz00002.lz || test_failed $LINENO -"${LZIP}" -cd out.lz00001.lz out.lz00002.lz | cmp in8 - || test_failed $LINENO -rm -f out.lz00001.lz out.lz00002.lz || framework_failure +[ ! -e out.lz00003.lz ] || test_failed $LINENO +rm -f out out.lz00001.lz out.lz00002.lz || framework_failure "${LZIP}" -1ks4Ki -b100000 in8 || test_failed $LINENO "${LZIP}" -t in8.lz || test_failed $LINENO -"${LZIP}" -cd in8.lz | cmp in8 - || test_failed $LINENO +"${LZIP}" -cd in8.lz -o out | cmp in8 - || test_failed $LINENO # override -o +[ ! -e out ] || test_failed $LINENO rm -f in8 || framework_failure "${LZIP}" -0 -S100k -o out < in8.lz || test_failed $LINENO "${LZIP}" -t out00001.lz out00002.lz || test_failed $LINENO "${LZIP}" -cd out00001.lz out00002.lz | cmp in8.lz - || test_failed $LINENO +[ ! -e out00003.lz ] || test_failed $LINENO rm -f out00001.lz || framework_failure "${LZIP}" -1 -S100k -o out < in8.lz || test_failed $LINENO "${LZIP}" -t out00001.lz out00002.lz || test_failed $LINENO "${LZIP}" -cd out00001.lz out00002.lz | cmp in8.lz - || test_failed $LINENO +[ ! -e out00003.lz ] || test_failed $LINENO rm -f out00001.lz out00002.lz || framework_failure "${LZIP}" -0 -F -S100k in8.lz || test_failed $LINENO "${LZIP}" -t in8.lz00001.lz in8.lz00002.lz || test_failed $LINENO "${LZIP}" -cd in8.lz00001.lz in8.lz00002.lz | cmp in8.lz - || test_failed $LINENO +[ ! -e in8.lz00003.lz ] || test_failed $LINENO rm -f in8.lz00001.lz in8.lz00002.lz || framework_failure "${LZIP}" -0kF -b100k in8.lz || test_failed $LINENO "${LZIP}" -t in8.lz.lz || test_failed $LINENO @@ -313,6 +369,21 @@ else fi rm -f int.lz || framework_failure +for i in fox_v2.lz fox_s11.lz fox_de20.lz \ + fox_bcrc.lz fox_crc0.lz fox_das46.lz fox_mes81.lz ; do + "${LZIP}" -tq "${testdir}"/$i + [ $? = 2 ] || test_failed $LINENO $i +done + +"${LZIP}" -cd "${fox_lz}" > fox || test_failed $LINENO +for i in fox_bcrc.lz fox_crc0.lz fox_das46.lz fox_mes81.lz ; do + "${LZIP}" -cdq "${testdir}"/$i > out + [ $? = 2 ] || test_failed $LINENO $i + cmp fox out || test_failed $LINENO $i +done +rm -f fox out || framework_failure + +cat "${in_lz}" "${in_lz}" > in2.lz || framework_failure cat "${in_lz}" "${in_lz}" "${in_lz}" > in3.lz || framework_failure if dd if=in3.lz of=trunc.lz bs=14752 count=1 2> /dev/null && [ -e trunc.lz ] && cmp in2.lz trunc.lz > /dev/null 2>&1 ; then @@ -339,13 +410,21 @@ printf "g" >> ingin.lz || framework_failure cat "${in_lz}" >> ingin.lz || framework_failure "${LZIP}" -lq ingin.lz [ $? = 2 ] || test_failed $LINENO +"${LZIP}" -atq ingin.lz +[ $? = 2 ] || test_failed $LINENO +"${LZIP}" -atq < ingin.lz +[ $? = 2 ] || test_failed $LINENO +"${LZIP}" -acdq ingin.lz > out +[ $? = 2 ] || test_failed $LINENO +"${LZIP}" -adq < ingin.lz > out +[ $? = 2 ] || test_failed $LINENO "${LZIP}" -t ingin.lz || test_failed $LINENO +"${LZIP}" -t < ingin.lz || test_failed $LINENO "${LZIP}" -cd ingin.lz > copy || test_failed $LINENO cmp in copy || test_failed $LINENO -"${LZIP}" -t < ingin.lz || test_failed $LINENO "${LZIP}" -d < ingin.lz > copy || test_failed $LINENO cmp in copy || test_failed $LINENO -rm -f copy ingin.lz || framework_failure +rm -f copy ingin.lz out || framework_failure echo if [ ${fail} = 0 ] ; then diff --git a/testsuite/fox.lz b/testsuite/fox.lz Binary files differnew file mode 100644 index 0000000..509da82 --- /dev/null +++ b/testsuite/fox.lz diff --git a/testsuite/fox_bcrc.lz b/testsuite/fox_bcrc.lz Binary files differnew file mode 100644 index 0000000..8f6a7c4 --- /dev/null +++ b/testsuite/fox_bcrc.lz diff --git a/testsuite/fox_crc0.lz b/testsuite/fox_crc0.lz Binary files differnew file mode 100644 index 0000000..1abe926 --- /dev/null +++ b/testsuite/fox_crc0.lz diff --git a/testsuite/fox_das46.lz b/testsuite/fox_das46.lz Binary files differnew file mode 100644 index 0000000..43ed9f9 --- /dev/null +++ b/testsuite/fox_das46.lz diff --git a/testsuite/fox_de20.lz b/testsuite/fox_de20.lz Binary files differnew file mode 100644 index 0000000..10949d8 --- /dev/null +++ b/testsuite/fox_de20.lz diff --git a/testsuite/fox_mes81.lz b/testsuite/fox_mes81.lz Binary files differnew file mode 100644 index 0000000..d50ef2e --- /dev/null +++ b/testsuite/fox_mes81.lz diff --git a/testsuite/fox_s11.lz b/testsuite/fox_s11.lz Binary files differnew file mode 100644 index 0000000..dca909c --- /dev/null +++ b/testsuite/fox_s11.lz diff --git a/testsuite/fox_v2.lz b/testsuite/fox_v2.lz Binary files differnew file mode 100644 index 0000000..8620981 --- /dev/null +++ b/testsuite/fox_v2.lz diff --git a/testsuite/test_em.txt.lz b/testsuite/test_em.txt.lz Binary files differnew file mode 100644 index 0000000..7e96250 --- /dev/null +++ b/testsuite/test_em.txt.lz |