-
Notifications
You must be signed in to change notification settings - Fork 176
/
pigz.c
4743 lines (4309 loc) · 176 KB
/
pigz.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* pigz.c -- parallel implementation of gzip
* Copyright (C) 2007-2023 Mark Adler
* Version 2.8 19 Aug 2023 Mark Adler
*/
/*
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler
madler@alumni.caltech.edu
*/
/* Version history:
1.0 17 Jan 2007 First version, pipe only
1.1 28 Jan 2007 Avoid void * arithmetic (some compilers don't get that)
Add note about requiring zlib 1.2.3
Allow compression level 0 (no compression)
Completely rewrite parallelism -- add a write thread
Use deflateSetDictionary() to make use of history
Tune argument defaults to best performance on four cores
1.2.1 1 Feb 2007 Add long command line options, add all gzip options
Add debugging options
1.2.2 19 Feb 2007 Add list (--list) function
Process file names on command line, write .gz output
Write name and time in gzip header, set output file time
Implement all command line options except --recursive
Add --keep option to prevent deleting input files
Add thread tracing information with -vv used
Copy crc32_combine() from zlib (shared libraries issue)
1.3 25 Feb 2007 Implement --recursive
Expand help to show all options
Show help if no arguments or output piping are provided
Process options in GZIP environment variable
Add progress indicator to write thread if --verbose
1.4 4 Mar 2007 Add --independent to facilitate damaged file recovery
Reallocate jobs for new --blocksize or --processes
Do not delete original if writing to stdout
Allow --processes 1, which does no threading
Add NOTHREAD define to compile without threads
Incorporate license text from zlib in source code
1.5 25 Mar 2007 Reinitialize jobs for new compression level
Copy attributes and owner from input file to output file
Add decompression and testing
Add -lt (or -ltv) to show all entries and proper lengths
Add decompression, testing, listing of LZW (.Z) files
Only generate and show trace log if DEBUG defined
Take "-" argument to mean read file from stdin
1.6 30 Mar 2007 Add zlib stream compression (--zlib), and decompression
1.7 29 Apr 2007 Decompress first entry of a zip file (if deflated)
Avoid empty deflate blocks at end of deflate stream
Show zlib check value (Adler-32) when listing
Don't complain when decompressing empty file
Warn about trailing junk for gzip and zlib streams
Make listings consistent, ignore gzip extra flags
Add zip stream compression (--zip)
1.8 13 May 2007 Document --zip option in help output
2.0 19 Oct 2008 Complete rewrite of thread usage and synchronization
Use polling threads and a pool of memory buffers
Remove direct pthread library use, hide in yarn.c
2.0.1 20 Oct 2008 Check version of zlib at compile time, need >= 1.2.3
2.1 24 Oct 2008 Decompress with read, write, inflate, and check threads
Remove spurious use of ctime_r(), ctime() more portable
Change application of job->calc lock to be a semaphore
Detect size of off_t at run time to select %lu vs. %llu
#define large file support macro even if not __linux__
Remove _LARGEFILE64_SOURCE, _FILE_OFFSET_BITS is enough
Detect file-too-large error and report, blame build
Replace check combination routines with those from zlib
2.1.1 28 Oct 2008 Fix a leak for files with an integer number of blocks
Update for yarn 1.1 (yarn_prefix and yarn_abort)
2.1.2 30 Oct 2008 Work around use of beta zlib in production systems
2.1.3 8 Nov 2008 Don't use zlib combination routines, put back in pigz
2.1.4 9 Nov 2008 Fix bug when decompressing very short files
2.1.5 20 Jul 2009 Added 2008, 2009 to --license statement
Allow numeric parameter immediately after -p or -b
Enforce parameter after -p, -b, -s, before other options
Enforce numeric parameters to have only numeric digits
Try to determine the number of processors for -p default
Fix --suffix short option to be -S to match gzip [Bloch]
Decompress if executable named "unpigz" [Amundsen]
Add a little bit of testing to Makefile
2.1.6 17 Jan 2010 Added pigz.spec to distribution for RPM systems [Brown]
Avoid some compiler warnings
Process symbolic links if piping to stdout [Hoffstätte]
Decompress if executable named "gunzip" [Hoffstätte]
Allow ".tgz" suffix [Chernookiy]
Fix adler32 comparison on .zz files
2.1.7 17 Dec 2011 Avoid unused parameter warning in reenter()
Don't assume 2's complement ints in compress_thread()
Replicate gzip -cdf cat-like behavior
Replicate gzip -- option to suppress option decoding
Test output from make test instead of showing it
Updated pigz.spec to install unpigz, pigz.1 [Obermaier]
Add PIGZ environment variable [Mueller]
Replicate gzip suffix search when decoding or listing
Fix bug in load() to set in_left to zero on end of file
Do not check suffix when input file won't be modified
Decompress to stdout if name is "*cat" [Hayasaka]
Write data descriptor signature to be like Info-ZIP
Update and sort options list in help
Use CC variable for compiler in Makefile
Exit with code 2 if a warning has been issued
Fix thread synchronization problem when tracing
Change macro name MAX to MAX2 to avoid library conflicts
Determine number of processors on HP-UX [Lloyd]
2.2 31 Dec 2011 Check for expansion bound busting (e.g. modified zlib)
Make the "threads" list head global variable volatile
Fix construction and printing of 32-bit check values
Add --rsyncable functionality
2.2.1 1 Jan 2012 Fix bug in --rsyncable buffer management
2.2.2 1 Jan 2012 Fix another bug in --rsyncable buffer management
2.2.3 15 Jan 2012 Remove volatile in yarn.c
Reduce the number of input buffers
Change initial rsyncable hash to comparison value
Improve the efficiency of arriving at a byte boundary
Add thread portability #defines from yarn.c
Have rsyncable compression be independent of threading
Fix bug where constructed dictionaries not being used
2.2.4 11 Mar 2012 Avoid some return value warnings
Improve the portability of printing the off_t type
Check for existence of compress binary before using
Update zlib version checking to 1.2.6 for new functions
Fix bug in zip (-K) output
Fix license in pigz.spec
Remove thread portability #defines in pigz.c
2.2.5 28 Jul 2012 Avoid race condition in free_pool()
Change suffix to .tar when decompressing or listing .tgz
Print name of executable in error messages
Show help properly when the name is unpigz or gunzip
Fix permissions security problem before output is closed
2.3 3 Mar 2013 Don't complain about missing suffix on stdout
Put all global variables in a structure for readability
Do not decompress concatenated zlib streams (just gzip)
Add option for compression level 11 to use zopfli
Fix handling of junk after compressed data
2.3.1 9 Oct 2013 Fix builds of pigzt and pigzn to include zopfli
Add -lm, needed to link log function on some systems
Respect LDFLAGS in Makefile, use CFLAGS consistently
Add memory allocation tracking
Fix casting error in uncompressed length calculation
Update zopfli to Mar 10, 2013 Google state
Support zopfli in single thread case
Add -F, -I, -M, and -O options for zopfli tuning
2.3.2 24 Jan 2015 Change whereis to which in Makefile for portability
Return zero exit code when only warnings are issued
Increase speed of unlzw (Unix compress decompression)
Update zopfli to current google state
Allow larger maximum blocksize (-b), now 512 MiB
Do not require that -d precede -N, -n, -T options
Strip any path from header name for -dN or -dNT
Remove use of PATH_MAX (PATH_MAX is not reliable)
Do not abort on inflate data error, do remaining files
Check gzip header CRC if present
Improve decompression error detection and reporting
2.3.3 24 Jan 2015 Portability improvements
Update copyright years in documentation
2.3.4 1 Oct 2016 Fix an out of bounds access due to invalid LZW input
Add an extra sync marker between independent blocks
Add zlib version for verbose version option (-vV)
Permit named pipes as input (e.g. made by mkfifo())
Fix a bug in -r directory traversal
Add warning for a zip file entry 4 GiB or larger
2.4 26 Dec 2017 Portability improvements
Produce Zip64 format when needed for --zip (>= 4 GiB)
Make -no-name compatible with gzip, add --time option
Add -m as a short option for --no-time
Check run-time zlib version to handle weak linking
Fix a concurrent read bug in --list operation
Process options first, for gzip compatibility
Add --synchronous (-Y) option to force device write
Disallow an empty suffix (e.g. --suffix '')
Return an exit code of 1 if any issues are encountered
Fix sign error in compression reduction percentage
2.5 23 Jan 2021 Add --alias/-A option to set .zip name for stdin input
Add --comment/-C option to add comment in .gz or .zip
Fix a bug that misidentified a multi-entry .zip
Fix a bug that did not emit double syncs for -i -p 1
Fix a bug in yarn that could try to access freed data
Do not delete multi-entry .zip files when extracting
Do not reject .zip entries with bit 11 set
Avoid a possible threads lock-order inversion
Ignore trailing junk after a gzip stream by default
2.6 6 Feb 2021 Add --huffman/-H and --rle/U strategy options
Fix issue when compiling for no threads
Fail silently on a broken pipe
2.7 15 Jan 2022 Show time stamp only for the first gzip member
Show totals when listing more than one gzip member
Don't unlink input file if it has other links
Add documentation for environment variables
Fix bug when combining -l with -d
Exit with status of zero if skipping non .gz files
Permit Huffman only (-H) when not compiling with zopfli
2.8 19 Aug 2023 Fix version bug when compiling with zlib 1.3
Save a modification time only for regular files
Write all available uncompressed data on an error
*/
#define VERSION "pigz 2.8"
/* To-do:
- make source portable for Windows, VMS, etc. (see gzip source code)
- make build portable (currently good for Unixish)
*/
/*
pigz compresses using threads to make use of multiple processors and cores.
The input is broken up into 128 KB chunks with each compressed in parallel.
The individual check value for each chunk is also calculated in parallel.
The compressed data is written in order to the output, and a combined check
value is calculated from the individual check values.
The compressed data format generated is in the gzip, zlib, or single-entry
zip format using the deflate compression method. The compression produces
partial raw deflate streams which are concatenated by a single write thread
and wrapped with the appropriate header and trailer, where the trailer
contains the combined check value.
Each partial raw deflate stream is terminated by an empty stored block
(using the Z_SYNC_FLUSH option of zlib), in order to end that partial bit
stream at a byte boundary, unless that partial stream happens to already end
at a byte boundary (the latter requires zlib 1.2.6 or later). Ending on a
byte boundary allows the partial streams to be concatenated simply as
sequences of bytes. This adds a very small four to five byte overhead
(average 3.75 bytes) to the output for each input chunk.
The default input block size is 128K, but can be changed with the -b option.
The number of compress threads is set by default to 8, which can be changed
using the -p option. Specifying -p 1 avoids the use of threads entirely.
pigz will try to determine the number of processors in the machine, in which
case if that number is two or greater, pigz will use that as the default for
-p instead of 8.
The input blocks, while compressed independently, have the last 32K of the
previous block loaded as a preset dictionary to preserve the compression
effectiveness of deflating in a single thread. This can be turned off using
the --independent or -i option, so that the blocks can be decompressed
independently for partial error recovery or for random access.
Decompression can't be parallelized over an arbitrary number of processors
like compression can be, at least not without specially prepared deflate
streams for that purpose. As a result, pigz uses a single thread (the main
thread) for decompression, but will create three other threads for reading,
writing, and check calculation, which can speed up decompression under some
circumstances. Parallel decompression can be turned off by specifying one
process (-dp 1 or -tp 1).
pigz requires zlib 1.2.1 or later to allow setting the dictionary when doing
raw deflate. Since zlib 1.2.3 corrects security vulnerabilities in zlib
version 1.2.1 and 1.2.2, conditionals check for zlib 1.2.3 or later during
the compilation of pigz.c. zlib 1.2.4 includes some improvements to
Z_FULL_FLUSH and deflateSetDictionary() that permit identical output for
pigz with and without threads, which is not possible with zlib 1.2.3. This
may be important for uses of pigz -R where small changes in the contents
should result in small changes in the archive for rsync. Note that due to
the details of how the lower levels of compression result in greater speed,
compression level 3 and below does not permit identical pigz output with and
without threads.
pigz uses the POSIX pthread library for thread control and communication,
through the yarn.h interface to yarn.c. yarn.c can be replaced with
equivalent implementations using other thread libraries. pigz can be
compiled with NOTHREAD #defined to not use threads at all (in which case
pigz will not be able to live up to the "parallel" in its name).
*/
/*
Details of parallel compression implementation:
When doing parallel compression, pigz uses the main thread to read the input
in 'size' sized chunks (see -b), and puts those in a compression job list,
each with a sequence number to keep track of the ordering. If it is not the
first chunk, then that job also points to the previous input buffer, from
which the last 32K will be used as a dictionary (unless -i is specified).
This sets a lower limit of 32K on 'size'.
pigz launches up to 'procs' compression threads (see -p). Each compression
thread continues to look for jobs in the compression list and perform those
jobs until instructed to return. When a job is pulled, the dictionary, if
provided, will be loaded into the deflate engine and then that input buffer
is dropped for reuse. Then the input data is compressed into an output
buffer that grows in size if necessary to hold the compressed data. The job
is then put into the write job list, sorted by the sequence number. The
compress thread however continues to calculate the check value on the input
data, either a CRC-32 or Adler-32, possibly in parallel with the write
thread writing the output data. Once that's done, the compress thread drops
the input buffer and also releases the lock on the check value so that the
write thread can combine it with the previous check values. The compress
thread has then completed that job, and goes to look for another.
All of the compress threads are left running and waiting even after the last
chunk is processed, so that they can support the next input to be compressed
(more than one input file on the command line). Once pigz is done, it will
call all the compress threads home (that'll do pig, that'll do).
Before starting to read the input, the main thread launches the write thread
so that it is ready pick up jobs immediately. The compress thread puts the
write jobs in the list in sequence sorted order, so that the first job in
the list is always has the lowest sequence number. The write thread waits
for the next write job in sequence, and then gets that job. The job still
holds its input buffer, from which the write thread gets the input buffer
length for use in check value combination. Then the write thread drops that
input buffer to allow its reuse. Holding on to the input buffer until the
write thread starts also has the benefit that the read and compress threads
can't get way ahead of the write thread and build up a large backlog of
unwritten compressed data. The write thread will write the compressed data,
drop the output buffer, and then wait for the check value to be unlocked by
the compress thread. Then the write thread combines the check value for this
chunk with the total check value for eventual use in the trailer. If this is
not the last chunk, the write thread then goes back to look for the next
output chunk in sequence. After the last chunk, the write thread returns and
joins the main thread. Unlike the compress threads, a new write thread is
launched for each input stream. The write thread writes the appropriate
header and trailer around the compressed data.
The input and output buffers are reused through their collection in pools.
Each buffer has a use count, which when decremented to zero returns the
buffer to the respective pool. Each input buffer has up to three parallel
uses: as the input for compression, as the data for the check value
calculation, and as a dictionary for compression. Each output buffer has
only one use, which is as the output of compression followed serially as
data to be written. The input pool is limited in the number of buffers, so
that reading does not get way ahead of compression and eat up memory with
more input than can be used. The limit is approximately two times the number
of compression threads. In the case that reading is fast as compared to
compression, that number allows a second set of buffers to be read while the
first set of compressions are being performed. The number of output buffers
is not directly limited, but is indirectly limited by the release of input
buffers to about the same number.
*/
// Portability defines.
#define _FILE_OFFSET_BITS 64 // Use large file functions
#define _LARGE_FILES // Same thing for AIX
#define _XOPEN_SOURCE 700 // For POSIX 2008
// Included headers and what is expected from each.
#include <stdio.h> // fflush(), fprintf(), fputs(), getchar(), putc(),
// puts(), printf(), vasprintf(), stderr, EOF, NULL,
// SEEK_END, size_t, off_t
#include <stdlib.h> // exit(), malloc(), free(), realloc(), atol(), atoi(),
// getenv()
#include <stdarg.h> // va_start(), va_arg(), va_end(), va_list
#include <string.h> // memset(), memchr(), memcpy(), strcmp(), strcpy(),
// strncpy(), strlen(), strcat(), strrchr(),
// strerror()
#include <errno.h> // errno, EEXIST
#include <assert.h> // assert()
#include <time.h> // ctime(), time(), time_t, mktime()
#include <signal.h> // signal(), SIGINT
#include <sys/types.h> // ssize_t
#include <sys/stat.h> // chmod(), stat(), fstat(), lstat(), struct stat,
// S_IFDIR, S_IFLNK, S_IFMT, S_IFREG
#include <sys/time.h> // utimes(), gettimeofday(), struct timeval
#include <unistd.h> // unlink(), _exit(), read(), write(), close(),
// lseek(), isatty(), chown(), fsync()
#include <fcntl.h> // open(), O_CREAT, O_EXCL, O_RDONLY, O_TRUNC,
// O_WRONLY, fcntl(), F_FULLFSYNC
#include <dirent.h> // opendir(), readdir(), closedir(), DIR,
// struct dirent
#include <limits.h> // UINT_MAX, INT_MAX
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
# include <inttypes.h> // intmax_t, uintmax_t
typedef uintmax_t length_t;
typedef uint32_t crc_t;
typedef uint_least16_t prefix_t;
#else
typedef unsigned long length_t;
typedef unsigned long crc_t;
typedef unsigned prefix_t;
#endif
#ifdef PIGZ_DEBUG
# if defined(__APPLE__)
# include <malloc/malloc.h>
# define MALLOC_SIZE(p) malloc_size(p)
# elif defined (__linux)
# include <malloc.h>
# define MALLOC_SIZE(p) malloc_usable_size(p)
# elif defined (_WIN32) || defined(_WIN64)
# include <malloc.h>
# define MALLOC_SIZE(p) _msize(p)
# else
# define MALLOC_SIZE(p) (0)
# endif
#endif
#ifdef __hpux
# include <sys/param.h>
# include <sys/pstat.h>
#endif
#ifndef S_IFLNK
# define S_IFLNK 0
#endif
#ifdef __MINGW32__
# define chown(p,o,g) 0
# define utimes(p,t) 0
# define lstat(p,s) stat(p,s)
# define _exit(s) exit(s)
#endif
#include "zlib.h" // deflateInit2(), deflateReset(), deflate(),
// deflateEnd(), deflateSetDictionary(), crc32(),
// adler32(), inflateBackInit(), inflateBack(),
// inflateBackEnd(), Z_DEFAULT_COMPRESSION,
// Z_DEFAULT_STRATEGY, Z_DEFLATED, Z_NO_FLUSH, Z_NULL,
// Z_OK, Z_SYNC_FLUSH, z_stream
#if !defined(ZLIB_VERNUM) || ZLIB_VERNUM < 0x1230
# error "Need zlib version 1.2.3 or later"
#endif
#ifndef NOTHREAD
# include "yarn.h" // thread, launch(), join(), join_all(), lock,
// new_lock(), possess(), twist(), wait_for(),
// release(), peek_lock(), free_lock(), yarn_name
#endif
#ifndef NOZOPFLI
# include "zopfli/src/zopfli/deflate.h" // ZopfliDeflatePart(),
// ZopfliInitOptions(),
// ZopfliOptions
#endif
#include "try.h" // try, catch, always, throw, drop, punt, ball_t
// For local functions and globals.
#define local static
// Prevent end-of-line conversions on MSDOSish operating systems.
#if defined(MSDOS) || defined(OS2) || defined(_WIN32) || defined(__CYGWIN__)
# include <io.h> // setmode(), O_BINARY, _commit() for _WIN32
# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
#else
# define SET_BINARY_MODE(fd)
#endif
// Release an allocated pointer, if allocated, and mark as unallocated.
#define RELEASE(ptr) \
do { \
if ((ptr) != NULL) { \
FREE(ptr); \
ptr = NULL; \
} \
} while (0)
// Sliding dictionary size for deflate.
#define DICT 32768U
// Largest power of 2 that fits in an unsigned int. Used to limit requests to
// zlib functions that use unsigned int lengths.
#define MAXP2 (UINT_MAX - (UINT_MAX >> 1))
/* rsyncable constants -- RSYNCBITS is the number of bits in the mask for
comparison. For random input data, there will be a hit on average every
1<<RSYNCBITS bytes. So for an RSYNCBITS of 12, there will be an average of
one hit every 4096 bytes, resulting in a mean block size of 4096. RSYNCMASK
is the resulting bit mask. RSYNCHIT is what the hash value is compared to
after applying the mask.
The choice of 12 for RSYNCBITS is consistent with the original rsyncable
patch for gzip which also uses a 12-bit mask. This results in a relatively
small hit to compression, on the order of 1.5% to 3%. A mask of 13 bits can
be used instead if a hit of less than 1% to the compression is desired, at
the expense of more blocks transmitted for rsync updates. (Your mileage may
vary.)
This implementation of rsyncable uses a different hash algorithm than what
the gzip rsyncable patch uses in order to provide better performance in
several regards. The algorithm is simply to shift the hash value left one
bit and exclusive-or that with the next byte. This is masked to the number
of hash bits (RSYNCMASK) and compared to all ones except for a zero in the
top bit (RSYNCHIT). This rolling hash has a very small window of 19 bytes
(RSYNCBITS+7). The small window provides the benefit of much more rapid
resynchronization after a change, than does the 4096-byte window of the gzip
rsyncable patch.
The comparison value is chosen to avoid matching any repeated bytes or short
sequences. The gzip rsyncable patch on the other hand uses a sum and zero
for comparison, which results in certain bad behaviors, such as always
matching everywhere in a long sequence of zeros. Such sequences occur
frequently in tar files.
This hash efficiently discards history older than 19 bytes simply by
shifting that data past the top of the mask -- no history needs to be
retained to undo its impact on the hash value, as is needed for a sum.
The choice of the comparison value (RSYNCHIT) has the virtue of avoiding
extremely short blocks. The shortest block is five bytes (RSYNCBITS-7) from
hit to hit, and is unlikely. Whereas with the gzip rsyncable algorithm,
blocks of one byte are not only possible, but in fact are the most likely
block size.
Thanks and acknowledgement to Kevin Day for his experimentation and insights
on rsyncable hash characteristics that led to some of the choices here.
*/
#define RSYNCBITS 12
#define RSYNCMASK ((1U << RSYNCBITS) - 1)
#define RSYNCHIT (RSYNCMASK >> 1)
// Initial pool counts and sizes -- INBUFS is the limit on the number of input
// spaces as a function of the number of processors (used to throttle the
// creation of compression jobs), OUTPOOL is the initial size of the output
// data buffer, chosen to make resizing of the buffer very unlikely and to
// allow prepending with a dictionary for use as an input buffer for zopfli.
#define INBUFS(p) (((p)<<1)+3)
#define OUTPOOL(s) ((s)+((s)>>4)+DICT)
// Input buffer size, and augmentation for re-inserting a central header.
#define BUF 32768
#define CEN 42
#define EXT (BUF + CEN) // provide enough room to unget a header
// Globals (modified by main thread only when it's the only thread).
local struct {
int ret; // pigz return code
char *prog; // name by which pigz was invoked
int ind; // input file descriptor
int outd; // output file descriptor
char *inf; // input file name (allocated)
size_t inz; // input file name allocated size
char *outf; // output file name (allocated)
int verbosity; // 0 = quiet, 1 = normal, 2 = verbose, 3 = trace
int headis; // 1 to store name, 2 to store date, 3 both
int pipeout; // write output to stdout even if file
int keep; // true to prevent deletion of input file
int force; // true to overwrite, compress links, cat
int sync; // true to flush output file
int form; // gzip = 0, zlib = 1, zip = 2 or 3
int magic1; // first byte of possible header when decoding
int recurse; // true to dive down into directory structure
char *sufx; // suffix to use (".gz" or user supplied)
char *name; // name for gzip or zip header
char *alias; // name for zip header when input is stdin
char *comment; // comment for gzip or zip header.
time_t mtime; // time stamp from input file for gzip header
int list; // true to list files instead of compress
int first; // true if we need to print listing header
int decode; // 0 to compress, 1 to decompress, 2 to test
int level; // compression level
int strategy; // compression strategy
#ifndef NOZOPFLI
ZopfliOptions zopts; // zopfli compression options
#endif
int rsync; // true for rsync blocking
int procs; // maximum number of compression threads (>= 1)
int setdict; // true to initialize dictionary in each thread
size_t block; // uncompressed input size per thread (>= 32K)
crc_t shift; // pre-calculated CRC-32 shift for length block
// saved gzip/zip header data for decompression, testing, and listing
time_t stamp; // time stamp from gzip header
char *hname; // name from header (allocated)
char *hcomm; // comment from header (allocated)
unsigned long zip_crc; // local header crc
length_t zip_clen; // local header compressed length
length_t zip_ulen; // local header uncompressed length
int zip64; // true if has zip64 extended information
// globals for decompression and listing buffered reading
unsigned char in_buf[EXT]; // input buffer
unsigned char *in_next; // next unused byte in buffer
size_t in_left; // number of unused bytes in buffer
int in_eof; // true if reached end of file on input
int in_short; // true if last read didn't fill buffer
length_t in_tot; // total bytes read from input
length_t out_tot; // total bytes written to output
unsigned long out_check; // check value of output
#ifndef NOTHREAD
// globals for decompression parallel reading
unsigned char in_buf2[EXT]; // second buffer for parallel reads
size_t in_len; // data waiting in next buffer
int in_which; // -1: start, 0: in_buf2, 1: in_buf
lock *load_state; // value = 0 to wait, 1 to read a buffer
thread *load_thread; // load_read() thread for joining
#endif
} g;
local void message(char *fmt, va_list ap) {
if (g.verbosity > 0) {
fprintf(stderr, "%s: ", g.prog);
vfprintf(stderr, fmt, ap);
putc('\n', stderr);
fflush(stderr);
}
}
// Display a complaint with the program name on stderr.
local int complain(char *fmt, ...) {
g.ret = 1;
va_list ap;
va_start(ap, fmt);
message(fmt, ap);
va_end(ap);
return 0;
}
// Same as complain(), but don't force a bad return code.
local int grumble(char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
message(fmt, ap);
va_end(ap);
return 0;
}
#ifdef PIGZ_DEBUG
// Memory tracking.
#define MAXMEM 131072 // maximum number of tracked pointers
local struct mem_track_s {
size_t num; // current number of allocations
size_t size; // total size of current allocations
size_t tot; // maximum number of allocations
size_t max; // maximum size of allocations
#ifndef NOTHREAD
lock *lock; // lock for access across threads
#endif
size_t have; // number in array (possibly != num)
void *mem[MAXMEM]; // sorted array of allocated pointers
} mem_track;
#ifndef NOTHREAD
# define mem_track_grab(m) possess((m)->lock)
# define mem_track_drop(m) release((m)->lock)
#else
# define mem_track_grab(m)
# define mem_track_drop(m)
#endif
// Return the leftmost insert location of ptr in the sorted list mem->mem[],
// which currently has mem->have elements. If ptr is already in the list, the
// returned value will point to its first occurrence. The return location will
// be one after the last element if ptr is greater than all of the elements.
local size_t search_track(struct mem_track_s *mem, void *ptr) {
ptrdiff_t left = 0;
ptrdiff_t right = mem->have - 1;
while (left <= right) {
ptrdiff_t mid = (left + right) >> 1;
if (mem->mem[mid] < ptr)
left = mid + 1;
else
right = mid - 1;
}
return left;
}
// Insert ptr in the sorted list mem->mem[] and update the memory allocation
// statistics.
local void insert_track(struct mem_track_s *mem, void *ptr) {
mem_track_grab(mem);
assert(mem->have < MAXMEM && "increase MAXMEM in source and try again");
size_t i = search_track(mem, ptr);
if (i < mem->have && mem->mem[i] == ptr)
complain("mem_track: duplicate pointer %p\n", ptr);
memmove(&mem->mem[i + 1], &mem->mem[i],
(mem->have - i) * sizeof(void *));
mem->mem[i] = ptr;
mem->have++;
mem->num++;
mem->size += MALLOC_SIZE(ptr);
if (mem->num > mem->tot)
mem->tot = mem->num;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
// Find and delete ptr from the sorted list mem->mem[] and update the memory
// allocation statistics.
local void delete_track(struct mem_track_s *mem, void *ptr) {
mem_track_grab(mem);
size_t i = search_track(mem, ptr);
if (i < mem->num && mem->mem[i] == ptr) {
memmove(&mem->mem[i], &mem->mem[i + 1],
(mem->have - (i + 1)) * sizeof(void *));
mem->have--;
}
else
complain("mem_track: missing pointer %p\n", ptr);
mem->num--;
mem->size -= MALLOC_SIZE(ptr);
mem_track_drop(mem);
}
local void *malloc_track(struct mem_track_s *mem, size_t size) {
void *ptr = malloc(size);
if (ptr != NULL)
insert_track(mem, ptr);
return ptr;
}
local void *realloc_track(struct mem_track_s *mem, void *ptr, size_t size) {
if (ptr == NULL)
return malloc_track(mem, size);
delete_track(mem, ptr);
void *got = realloc(ptr, size);
insert_track(mem, got == NULL ? ptr : got);
return got;
}
local void free_track(struct mem_track_s *mem, void *ptr) {
if (ptr != NULL) {
delete_track(mem, ptr);
free(ptr);
}
}
#ifndef NOTHREAD
local void *yarn_malloc(size_t size) {
return malloc_track(&mem_track, size);
}
local void yarn_free(void *ptr) {
free_track(&mem_track, ptr);
}
#endif
local voidpf zlib_alloc(voidpf opaque, uInt items, uInt size) {
return malloc_track(opaque, items * (size_t)size);
}
local void zlib_free(voidpf opaque, voidpf address) {
free_track(opaque, address);
}
#define REALLOC(p, s) realloc_track(&mem_track, p, s)
#define FREE(p) free_track(&mem_track, p)
#define OPAQUE (&mem_track)
#define ZALLOC zlib_alloc
#define ZFREE zlib_free
#else // !PIGZ_DEBUG
#define REALLOC realloc
#define FREE free
#define OPAQUE Z_NULL
#define ZALLOC Z_NULL
#define ZFREE Z_NULL
#endif
// Assured memory allocation.
local void *alloc(void *ptr, size_t size) {
ptr = REALLOC(ptr, size);
if (ptr == NULL)
throw(ENOMEM, "not enough memory");
return ptr;
}
#ifdef PIGZ_DEBUG
// Logging.
// Starting time of day for tracing.
local struct timeval start;
// Trace log.
local struct log {
struct timeval when; // time of entry
char *msg; // message
struct log *next; // next entry
} *log_head, **log_tail = NULL;
#ifndef NOTHREAD
local lock *log_lock = NULL;
#endif
// Maximum log entry length.
#define MAXMSG 256
// Set up log (call from main thread before other threads launched).
local void log_init(void) {
if (log_tail == NULL) {
mem_track.num = 0;
mem_track.size = 0;
mem_track.num = 0;
mem_track.max = 0;
mem_track.have = 0;
#ifndef NOTHREAD
mem_track.lock = new_lock(0);
yarn_mem(yarn_malloc, yarn_free);
log_lock = new_lock(0);
#endif
log_head = NULL;
log_tail = &log_head;
}
}
// Add entry to trace log.
local void log_add(char *fmt, ...) {
struct timeval now;
struct log *me;
va_list ap;
char msg[MAXMSG];
gettimeofday(&now, NULL);
me = alloc(NULL, sizeof(struct log));
me->when = now;
va_start(ap, fmt);
vsnprintf(msg, MAXMSG, fmt, ap);
va_end(ap);
me->msg = alloc(NULL, strlen(msg) + 1);
strcpy(me->msg, msg);
me->next = NULL;
#ifndef NOTHREAD
assert(log_lock != NULL);
possess(log_lock);
#endif
*log_tail = me;
log_tail = &(me->next);
#ifndef NOTHREAD
twist(log_lock, BY, +1);
#endif
}
// Pull entry from trace log and print it, return false if empty.
local int log_show(void) {
struct log *me;
struct timeval diff;
if (log_tail == NULL)
return 0;
#ifndef NOTHREAD
possess(log_lock);
#endif
me = log_head;
if (me == NULL) {
#ifndef NOTHREAD
release(log_lock);
#endif
return 0;
}
log_head = me->next;
if (me->next == NULL)
log_tail = &log_head;
#ifndef NOTHREAD
twist(log_lock, BY, -1);
#endif
diff.tv_usec = me->when.tv_usec - start.tv_usec;
diff.tv_sec = me->when.tv_sec - start.tv_sec;
if (diff.tv_usec < 0) {
diff.tv_usec += 1000000L;
diff.tv_sec--;
}
fprintf(stderr, "trace %ld.%06ld %s\n",
(long)diff.tv_sec, (long)diff.tv_usec, me->msg);
fflush(stderr);
FREE(me->msg);
FREE(me);
return 1;
}
// Release log resources (need to do log_init() to use again).
local void log_free(void) {
struct log *me;
if (log_tail != NULL) {
#ifndef NOTHREAD
possess(log_lock);
#endif
while ((me = log_head) != NULL) {
log_head = me->next;
FREE(me->msg);
FREE(me);
}
#ifndef NOTHREAD
twist(log_lock, TO, 0);
free_lock(log_lock);
log_lock = NULL;
yarn_mem(malloc, free);
free_lock(mem_track.lock);
#endif
log_tail = NULL;
}
}
// Show entries until no more, free log.
local void log_dump(void) {
if (log_tail == NULL)
return;
while (log_show())
;
log_free();
if (mem_track.num || mem_track.size)
complain("memory leak: %zu allocs of %zu bytes total",
mem_track.num, mem_track.size);
if (mem_track.max)
fprintf(stderr, "%zu bytes of memory used in %zu allocs\n",
mem_track.max, mem_track.tot);
}
// Debugging macro.
#define Trace(x) \
do { \
if (g.verbosity > 2) { \
log_add x; \
} \
} while (0)
#else // !PIGZ_DEBUG
#define log_dump()
#define Trace(x)
#endif
// Abort or catch termination signal.
local void cut_short(int sig) {
if (sig == SIGINT) {
Trace(("termination by user"));
}
if (g.outd != -1 && g.outd != 1) {
unlink(g.outf);
RELEASE(g.outf);
g.outd = -1;
}
log_dump();
_exit(sig < 0 ? -sig : EINTR);
}
// Common code for catch block of top routine in the thread.
#define THREADABORT(ball) \
do { \
if ((ball).code != EPIPE) \
complain("abort: %s", (ball).why); \
drop(ball); \
cut_short(-(ball).code); \
} while (0)
// Compute next size up by multiplying by about 2**(1/3) and rounding to the
// next power of 2 if close (three applications results in doubling). If small,
// go up to at least 16, if overflow, go to max size_t value.
local inline size_t grow(size_t size) {
size_t was, top;
int shift;
was = size;
size += size >> 2;
top = size;
for (shift = 0; top > 7; shift++)
top >>= 1;
if (top == 7)
size = (size_t)1 << (shift + 3);
if (size < 16)
size = 16;
if (size <= was)
size = (size_t)0 - 1;
return size;
}
// Copy cpy[0..len-1] to *mem + off, growing *mem if necessary, where *size is
// the allocated size of *mem. Return the number of bytes in the result.
local inline size_t vmemcpy(char **mem, size_t *size, size_t off,
void *cpy, size_t len) {
size_t need;
need = off + len;
if (need < off)
throw(ERANGE, "overflow");
if (need > *size) {
need = grow(need);
if (off == 0) {
RELEASE(*mem);
*size = 0;
}
*mem = alloc(*mem, need);
*size = need;
}
memcpy(*mem + off, cpy, len);
return off + len;
}
// Copy the zero-terminated string cpy to *str + off, growing *str if
// necessary, where *size is the allocated size of *str. Return the length of
// the string plus one.
local inline size_t vstrcpy(char **str, size_t *size, size_t off, void *cpy) {
return vmemcpy(str, size, off, cpy, strlen(cpy) + 1);
}
// Read up to len bytes into buf, repeating read() calls as needed.
local size_t readn(int desc, unsigned char *buf, size_t len) {
ssize_t ret;