forked from madler/pigz
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pigz.c
4805 lines (4298 loc) · 169 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.1 9 Oct 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 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
*/
#define VERSION "pigz 2.3.1\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.
The --index or -X option causes the generation of a block index which can be
used for parallel decompression. The block index can be appended onto the
compressed output or it may be stored in a separate file. The uncompressed
size, compressed size, checksum of each block are stored in the index,
allowing future applications to perform random reads of the compressed file.
Streams generated with -X are readable by legacy versions of pigz and gzip.
Decompression can be parallelized, but only if a block index is available.
If a block index is not present, 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).
If the block index is present, the main thread reads the input file and
dispatches each block to an uncompress thread. The uncompress thread
uncompresses the block, verifies the block checksum, and passes the block
off to a writer thread. The writer thread writes the blocks in order,
and combines the individual block checksums into a per-file checksum. The
per-file checksum is compared to the checksum in the stream's trailer.
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 writes an index entry (if -X)
and 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, INT_MAX */
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
# include <inttypes.h> /* intmax_t */
#endif
#include <stddef.h> /* offsetof() */
#include <sys/mman.h> /* mmap() */
#include <netinet/in.h> /* htonl() */
#ifdef 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
#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" /* ZopfliDeflatePart(), ZopfliInitOptions(),
ZopfliOptions */
/* 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 */
int idxd; /* index file descriptor */
char inf[PATH_MAX+1]; /* input file name (accommodate recursion) */
char *outf; /* output file name (allocated if not NULL) */
char *indexf; /* index file name template (may have %f, %z) */
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 */
ZopfliOptions zopts; /* zopfli compression options */
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;
}
local void idx_abort(void);
/* exit with error, delete output file if in the middle of writing it */
local int bail(char *why, char *what)
{
idx_abort();
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
complain("abort: %s%s", why, what);
exit(1);
return 0;
}
#ifdef DEBUG
/* memory tracking */
local struct mem_track_s {
size_t num; /* current number of allocations */
size_t size; /* total size of current allocations */
size_t max; /* maximum size of allocations */
#ifndef NOTHREAD
lock *lock; /* lock for access across threads */
#endif
} 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
local void *malloc_track(struct mem_track_s *mem, size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num++;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void *realloc_track(struct mem_track_s *mem, void *ptr, size_t size)
{
size_t was;
if (ptr == NULL)
return malloc_track(mem, size);
was = MALLOC_SIZE(ptr);
ptr = realloc(ptr, size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->size -= was;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void free_track(struct mem_track_s *mem, void *ptr)
{
size_t size;
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num--;
mem->size -= size;
mem_track_drop(mem);
free(ptr);
}
}
#ifndef NOTHREAD
local void *yarn_malloc(size_t size)
{
return malloc_track(&mem_track, size);
}
local void yarn_free(void *ptr)
{
return 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 MALLOC(s) malloc_track(&mem_track, s)
#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
/* 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.max = 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 = 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;
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: %lu allocs of %lu bytes total",
mem_track.num, mem_track.size);
if (mem_track.max)
fprintf(stderr, "%lu bytes of memory used\n", mem_track.max);
}
/* debugging macro */
#define Trace(x) \
do { \
if (g.verbosity > 2) { \
log_add x; \
} \
} while (0)
#else /* !DEBUG */
#define MALLOC malloc
#define REALLOC realloc
#define FREE free
#define OPAQUE Z_NULL
#define ZALLOC Z_NULL
#define ZFREE Z_NULL
#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 PUT8L(a,b) (PUT4L(a,(b)&0xffffffff),PUT4L((a)+4,(b)>>32))
#define PUT4M(a,b) (*(a)=(b)>>24,(a)[1]=(b)>>16,(a)[2]=(b)>>8,(a)[3]=(b))
/* pull LSB order or MSB order integers from an unsigned char buffer */
#define PULL2L(p) ((p)[0] + ((unsigned)((p)[1]) << 8))
#define PULL4L(p) (PULL2L(p) + ((unsigned long)(PULL2L((p) + 2)) << 16))
#define PULL8L(p) ((uint64_t)((p)[0]) | ((uint64_t)((p)[1]) << 8) | \
((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \
((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \
((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))
#define PULL2M(p) (((unsigned)((p)[0]) << 8) + (p)[1])
#define PULL4M(p) (((unsigned long)(PULL2M(p)) << 16) + PULL2M((p) + 2))
/* 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 */