forked from madler/pigz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pigz.c
3792 lines (3417 loc) · 137 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, 2008, 2009, 2010, 2011, 2012, 2013 Mark Adler
* Version 2.3 3 Mar 2013 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
Mark accepts donations for providing this software. Donations are not
required or expected. Any amount that you feel is appropriate would be
appreciated. You can use this link:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=536055
*/
/* 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 when not writing output file
Put all global variables in one global structure for readability
Do not decompress concatenated zlib streams -- only gzip streams
Add option for compression level 11 to use zopfli
Fix handling of junk after compressed data
*/
#define VERSION "pigz 2.3\n"
/* 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, 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.
*/
/* use large file functions if available */
#define _FILE_OFFSET_BITS 64
/* 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_end(), va_list */
#include <string.h> /* memset(), memchr(), memcpy(), strcmp(), strcpy() */
/* strncpy(), strlen(), strcat(), strrchr() */
#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() */
#include <fcntl.h> /* open(), O_CREAT, O_EXCL, O_RDONLY, O_TRUNC, */
/* O_WRONLY */
#include <dirent.h> /* opendir(), readdir(), closedir(), DIR, */
/* struct dirent */
#include <limits.h> /* PATH_MAX, UINT_MAX */
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
# include <inttypes.h> /* intmax_t */
#endif
#ifdef __hpux
# include <sys/param.h>
# include <sys/pstat.h>
#endif
#include "zlib.h" /* deflateInit2(), deflateReset(), deflate(), */
/* deflateEnd(), deflateSetDictionary(), crc32(),
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
#include "zopfli/deflate.h" /* DeflatePart(), Options */
/* 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 */
# 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 */
#define BUF 32768U
/* globals (modified by main thread only when it's the only thread) */
local struct {
char *prog; /* name by which pigz was invoked */
int ind; /* input file descriptor */
int outd; /* output file descriptor */
char inf[PATH_MAX+1]; /* input file name (accommodate recursion) */
char *outf; /* output file name (allocated if not NULL) */
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 form; /* gzip = 0, zlib = 1, zip = 2 or 3 */
unsigned char 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 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 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) */
int warned; /* true if a warning has been given */
/* saved gzip/zip header data for decompression, testing, and listing */
time_t stamp; /* time stamp from gzip header */
char *hname; /* name from header (allocated) */
unsigned long zip_crc; /* local header crc */
unsigned long zip_clen; /* local header compressed length */
unsigned long zip_ulen; /* local header uncompressed length */
/* globals for decompression and listing buffered reading */
unsigned char in_buf[BUF]; /* 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 */
off_t in_tot; /* total bytes read from input */
off_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[BUF]; /* 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;
/* display a complaint with the program name on stderr */
local int complain(char *fmt, ...)
{
va_list ap;
if (g.verbosity > 0) {
fprintf(stderr, "%s: ", g.prog);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
putc('\n', stderr);
fflush(stderr);
g.warned = 1;
}
return 0;
}
/* exit with error, delete output file if in the middle of writing it */
local int bail(char *why, char *what)
{
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
complain("abort: %s%s", why, what);
exit(1);
return 0;
}
#ifdef DEBUG
/* 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) {
#ifndef NOTHREAD
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 = malloc(sizeof(struct log));
if (me == NULL)
bail("not enough memory", "");
me->when = now;
va_start(ap, fmt);
vsnprintf(msg, MAXMSG, fmt, ap);
va_end(ap);
me->msg = malloc(strlen(msg) + 1);
if (me->msg == NULL) {
free(me);
bail("not enough memory", "");
}
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;
#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();
}
/* debugging macro */
#define Trace(x) \
do { \
if (g.verbosity > 2) { \
log_add x; \
} \
} while (0)
#else /* !DEBUG */
#define log_dump()
#define Trace(x)
#endif
/* 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;
size_t got;
got = 0;
while (len) {
ret = read(desc, buf, len);
if (ret < 0)
bail("read error on ", g.inf);
if (ret == 0)
break;
buf += ret;
len -= ret;
got += ret;
}
return got;
}
/* write len bytes, repeating write() calls as needed */
local void writen(int desc, unsigned char *buf, size_t len)
{
ssize_t ret;
while (len) {
ret = write(desc, buf, len);
if (ret < 1) {
complain("write error code %d", errno);
bail("write error on ", g.outf);
}
buf += ret;
len -= ret;
}
}
/* convert Unix time to MS-DOS date and time, assuming current timezone
(you got a better idea?) */
local unsigned long time2dos(time_t t)
{
struct tm *tm;
unsigned long dos;
if (t == 0)
t = time(NULL);
tm = localtime(&t);
if (tm->tm_year < 80 || tm->tm_year > 207)
return 0;
dos = (tm->tm_year - 80) << 25;
dos += (tm->tm_mon + 1) << 21;
dos += tm->tm_mday << 16;
dos += tm->tm_hour << 11;
dos += tm->tm_min << 5;
dos += (tm->tm_sec + 1) >> 1; /* round to double-seconds */
return dos;
}
/* put a 4-byte integer into a byte array in LSB order or MSB order */
#define PUT2L(a,b) (*(a)=(b)&0xff,(a)[1]=(b)>>8)
#define PUT4L(a,b) (PUT2L(a,(b)&0xffff),PUT2L((a)+2,(b)>>16))
#define PUT4M(a,b) (*(a)=(b)>>24,(a)[1]=(b)>>16,(a)[2]=(b)>>8,(a)[3]=(b))
/* write a gzip, zlib, or zip header using the information in the globals */
local unsigned long put_header(void)
{
unsigned long len;
unsigned char head[30];
if (g.form > 1) { /* zip */
/* write local header */
PUT4L(head, 0x04034b50UL); /* local header signature */
PUT2L(head + 4, 20); /* version needed to extract (2.0) */
PUT2L(head + 6, 8); /* flags: data descriptor follows data */
PUT2L(head + 8, 8); /* deflate */
PUT4L(head + 10, time2dos(g.mtime));
PUT4L(head + 14, 0); /* crc (not here) */
PUT4L(head + 18, 0); /* compressed length (not here) */
PUT4L(head + 22, 0); /* uncompressed length (not here) */
PUT2L(head + 26, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(head + 28, 9); /* length of extra field (see below) */
writen(g.outd, head, 30); /* write local header */
len = 30;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
len += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(head, 0x5455); /* extended timestamp signature */
PUT2L(head + 2, 5); /* number of data bytes in this block */
head[4] = 1; /* flag presence of mod time */
PUT4L(head + 5, g.mtime); /* mod time */
writen(g.outd, head, 9); /* write extra field block */
len += 9;
}
else if (g.form) { /* zlib */
head[0] = 0x78; /* deflate, 32K window */
head[1] = (g.level >= 9 ? 3 :
(g.level == 1 ? 0 :
(g.level >= 6 || g.level == Z_DEFAULT_COMPRESSION ?
1 : 2))) << 6;
head[1] += 31 - (((head[0] << 8) + head[1]) % 31);
writen(g.outd, head, 2);
len = 2;
}
else { /* gzip */
head[0] = 31;
head[1] = 139;
head[2] = 8; /* deflate */
head[3] = g.name != NULL ? 8 : 0;
PUT4L(head + 4, g.mtime);
head[8] = g.level >= 9 ? 2 : (g.level == 1 ? 4 : 0);
head[9] = 3; /* unix */
writen(g.outd, head, 10);
len = 10;
if (g.name != NULL)
writen(g.outd, (unsigned char *)g.name, strlen(g.name) + 1);
if (g.name != NULL)
len += strlen(g.name) + 1;
}
return len;
}
/* write a gzip, zlib, or zip trailer */
local void put_trailer(unsigned long ulen, unsigned long clen,
unsigned long check, unsigned long head)
{
unsigned char tail[46];
if (g.form > 1) { /* zip */
unsigned long cent;
/* write data descriptor (as promised in local header) */
PUT4L(tail, 0x08074b50UL);
PUT4L(tail + 4, check);
PUT4L(tail + 8, clen);
PUT4L(tail + 12, ulen);
writen(g.outd, tail, 16);
/* write central file header */
PUT4L(tail, 0x02014b50UL); /* central header signature */
tail[4] = 63; /* obeyed version 6.3 of the zip spec */
tail[5] = 255; /* ignore external attributes */
PUT2L(tail + 6, 20); /* version needed to extract (2.0) */
PUT2L(tail + 8, 8); /* data descriptor is present */
PUT2L(tail + 10, 8); /* deflate */
PUT4L(tail + 12, time2dos(g.mtime));
PUT4L(tail + 16, check); /* crc */
PUT4L(tail + 20, clen); /* compressed length */
PUT4L(tail + 24, ulen); /* uncompressed length */
PUT2L(tail + 28, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(tail + 30, 9); /* length of extra field (see below) */
PUT2L(tail + 32, 0); /* no file comment */
PUT2L(tail + 34, 0); /* disk number 0 */
PUT2L(tail + 36, 0); /* internal file attributes */
PUT4L(tail + 38, 0); /* external file attributes (ignored) */
PUT4L(tail + 42, 0); /* offset of local header */
writen(g.outd, tail, 46); /* write central file header */
cent = 46;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
cent += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(tail, 0x5455); /* extended timestamp signature */
PUT2L(tail + 2, 5); /* number of data bytes in this block */
tail[4] = 1; /* flag presence of mod time */
PUT4L(tail + 5, g.mtime); /* mod time */
writen(g.outd, tail, 9); /* write extra field block */
cent += 9;
/* write end of central directory record */
PUT4L(tail, 0x06054b50UL); /* end of central directory signature */
PUT2L(tail + 4, 0); /* number of this disk */
PUT2L(tail + 6, 0); /* disk with start of central directory */
PUT2L(tail + 8, 1); /* number of entries on this disk */
PUT2L(tail + 10, 1); /* total number of entries */
PUT4L(tail + 12, cent); /* size of central directory */
PUT4L(tail + 16, head + clen + 16); /* offset of central directory */
PUT2L(tail + 20, 0); /* no zip file comment */
writen(g.outd, tail, 22); /* write end of central directory record */
}
else if (g.form) { /* zlib */
PUT4M(tail, check);
writen(g.outd, tail, 4);
}
else { /* gzip */
PUT4L(tail, check);
PUT4L(tail + 4, ulen);
writen(g.outd, tail, 8);
}
}
/* compute check value depending on format */
#define CHECK(a,b,c) (g.form == 1 ? adler32(a,b,c) : crc32(a,b,c))
#ifndef NOTHREAD
/* -- threaded portions of pigz -- */
/* -- check value combination routines for parallel calculation -- */
#define COMB(a,b,c) (g.form == 1 ? adler32_comb(a,b,c) : crc32_comb(a,b,c))
/* combine two crc-32's or two adler-32's (copied from zlib 1.2.3 so that pigz
can be compatible with older versions of zlib) */
/* we copy the combination routines from zlib here, in order to avoid
linkage issues with the zlib 1.2.3 builds on Sun, Ubuntu, and others */
local unsigned long gf2_matrix_times(unsigned long *mat, unsigned long vec)
{
unsigned long sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
local void gf2_matrix_square(unsigned long *square, unsigned long *mat)
{
int n;
for (n = 0; n < 32; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
local unsigned long crc32_comb(unsigned long crc1, unsigned long crc2,
size_t len2)
{
int n;
unsigned long row;
unsigned long even[32]; /* even-power-of-two zeros operator */
unsigned long odd[32]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = 0xedb88320UL; /* CRC-32 polynomial */
row = 1;
for (n = 1; n < 32; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
#define BASE 65521U /* largest prime smaller than 65536 */
#define LOW16 0xffff /* mask lower 16 bits */
local unsigned long adler32_comb(unsigned long adler1, unsigned long adler2,
size_t len2)
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & LOW16;
sum2 = (rem * sum1) % BASE;
sum1 += (adler2 & LOW16) + BASE - 1;
sum2 += ((adler1 >> 16) & LOW16) + ((adler2 >> 16) & LOW16) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* -- pool of spaces for buffer management -- */
/* These routines manage a pool of spaces. Each pool specifies a fixed size
buffer to be contained in each space. Each space has a use count, which
when decremented to zero returns the space to the pool. If a space is
requested from the pool and the pool is empty, a space is immediately
created unless a specified limit on the number of spaces has been reached.
Only if the limit is reached will it wait for a space to be returned to the
pool. Each space knows what pool it belongs to, so that it can be returned.
*/
/* a space (one buffer for each space) */
struct space {
lock *use; /* use count -- return to pool when zero */
unsigned char *buf; /* buffer of size size */
size_t size; /* current size of this buffer */
size_t len; /* for application usage (initially zero) */
struct pool *pool; /* pool to return to */
struct space *next; /* for pool linked list */
};
/* pool of spaces (one pool for each type needed) */
struct pool {
lock *have; /* unused spaces available, lock for list */
struct space *head; /* linked list of available buffers */