-
Notifications
You must be signed in to change notification settings - Fork 12
/
gztool.c
6401 lines (5838 loc) · 308 KB
/
gztool.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
//
// gztool
//
// Create small indexes for gzipped files and use them
// for quick and random data extraction.
// No more waiting when the end of a 10 GiB gzip is needed!
//
// based on parts from
// zlib/examples/zran.c & zlib/examples/zpipe.c by Mark Adler
// //github.com/madler/zlib
//
//.................................................
//
// LICENSE:
//
// v0.1 to v1.8* by Roberto S. Galende, 2019, 2020, 2021, 2022, 2023, 2024
// //github.com/circulosmeos/gztool
// A work by Roberto S. Galende
// distributed under the same License terms covering
// zlib from Mark Adler (aka Zlib license):
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors 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.
//
// License contained in zlib.h by Mark Adler is copied here:
//
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.11, January 15th, 2017
Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors 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.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
(zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
*/
//.................................................
//
// Original zran.c notice is copied here:
//
/* zran.c -- example of zlib/gzip stream indexing and random access
* Copyright (C) 2005, 2012 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
Version 1.1 29 Sep 2012 Mark Adler */
/* Version History:
1.0 29 May 2005 First version
1.1 29 Sep 2012 Fix memory reallocation error
*/
/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary()
for random access of a compressed file. A file containing a zlib or gzip
stream is provided on the command line. The compressed stream is decoded in
its entirety, and an index built with access points about every SPAN bytes
in the uncompressed output. The compressed file is left open, and can then
be read randomly, having to decompress on the average SPAN/2 uncompressed
bytes before getting to the desired block of data.
An access point can be created at the start of any deflate block, by saving
the starting file offset and bit of that block, and the 32K bytes of
uncompressed data that precede that block. Also the uncompressed offset of
that block is saved to provide a reference for locating a desired starting
point in the uncompressed stream. build_index() works by decompressing the
input zlib or gzip stream a block at a time, and at the end of each block
deciding if enough uncompressed data has gone by to justify the creation of
a new access point. If so, that point is saved in a data structure that
grows as needed to accommodate the points.
To use the index, an offset in the uncompressed data is provided, for which
the latest access point at or preceding that offset is located in the index.
The input file is positioned to the specified location in the index, and if
necessary the first few bits of the compressed data is read from the file.
inflate is initialized with those bits and the 32K of uncompressed data, and
the decompression then proceeds until the desired offset in the file is
reached. Then the decompression continues to read the desired uncompressed
data from the file.
Another approach would be to generate the index on demand. In that case,
requests for random access reads from the compressed data would try to use
the index, but if a read far enough past the end of the index is required,
then further index entries would be generated and added.
There is some fair bit of overhead to starting inflation for the random
access, mainly copying the 32K byte dictionary. So if small pieces of the
file are being accessed, it would make sense to implement a cache to hold
some lookahead and avoid many calls to extract() for small lengths.
Another way to build an index would be to use inflateCopy(). That would
not be constrained to have access points at block boundaries, but requires
more memory per access point, and also cannot be saved to file due to the
use of pointers in the state. The approach here allows for storage of the
index in a file.
*/
//
// .................................................
// large file support (LFS) (files with size >2^31 (2 GiB) in linux, and >4 GiB in Windows)
#define _FILE_OFFSET_BITS 64 // defining _FILE_OFFSET_BITS with the value 64 (before including
// any header files) will turn off_t into a 64-bit type
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE // off64_t for fseek64
// .................................................
//#define COMPILING_DEBIAN_PACKAGE
#ifdef COMPILING_DEBIAN_PACKAGE
#include <config.h>
#else
#define PACKAGE_NAME "gztool"
#define PACKAGE_VERSION "1.8.0"
#endif
#define _XOPEN_SOURCE 500 // expose <unistd.h>'s pread()
// and <stdio.h>'s fileno()
#include <stdint.h> // uint32_t, uint64_t, UINT32_MAX
#include <stdio.h>
#include <stdarg.h> // va_start, va_list, va_end
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <zlib.h>
#include <unistd.h> // getopt(), access(), sleep(), pread()
#include <getopt.h> // getopt(): optarg, optopt, optind
#include <ctype.h> // isprint()
#include <sys/stat.h> // stat()
#include <math.h> // pow()
#include <stdbool.h>// bool, false, true
// sets binary mode for stdin in Windows
#define STDIN 0
#define STDOUT 1
#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# define SET_BINARY_MODE(handle) setmode(handle, O_BINARY)
#else
# define SET_BINARY_MODE(handle) ((void)0)
#endif
#define local static
#define SPAN 10485760L /* desired distance between access points */
#define WINSIZE 32768U /* sliding window size */
#define CHUNK 16384 /* file input buffer size */
#define UNCOMPRESSED_WINDOW UINT32_MAX // window is an uncompressed WINSIZE size window
#define GZIP_INDEX_IDENTIFIER_STRING "gzipindx" // default index version (v0)
#define GZIP_INDEX_IDENTIFIER_STRING_V1 "gzipindX" // index version with line number info
#define GZIP_INDEX_HEADER_SIZE 16 // header size in bytes of gztool's .gzi files
#define GZIP_HEADER_SIZE_BY_ZLIB 10 // header size in bytes of gzip files created by zlib:
//github.com/madler/zlib/blob/master/zlib.h
// If deflateSetHeader is not used, the default gzip header has text false,
// the time set to zero, and os set to 255, with no extra, name, or comment
// fields.
// default waiting time in seconds when supervising a growing gzip file:
#define WAITING_TIME 4
// how many CHUNKs will be decompressed in advance if it is needed (parameter gzip_stream_may_be_damaged, `-p`)
#define CHUNKS_TO_DECOMPRESS_IN_ADVANCE 3
// how many CHUNKs will be look to backwards for a new good gzip reentry point after an error is found (with `-p`)
#define CHUNKS_TO_LOOK_BACKWARDS 3
/* access point entry */
struct point {
uint64_t out; /* corresponding offset in uncompressed data */
uint64_t in; /* offset in input file of first full byte */
uint32_t bits; /* number of bits (1-7) from byte at in - 1, or 0 */
uint64_t window_beginning;/* offset at index file where this compressed window is stored */
uint32_t window_size; /* size of (compressed) window */
unsigned char *window; /* preceding 32K of uncompressed data, compressed */
// index v1:
uint64_t line_number; /* if index_version == 1 stores line number at this index point */
};
// NOTE: window_beginning is not stored on disk, it's an on-memory-only value
/* access point list */
struct access {
uint64_t have; /* number of list entries filled in */
uint64_t size; /* number of list entries allocated */
uint64_t file_size; /* size of uncompressed file (useful for bgzip files) */
struct point *list; /* allocated list */
char *file_name; /* path to index file */
int index_complete; /* 1: index is complete; 0: index is (still) incomplete */
// index v1:
int index_version; /* 0: default; 1: index with line numbers */
uint32_t line_number_format; /* 0: linux \r | windows \n\r; 1: mac \n */
uint64_t number_of_lines; /* number of lines (only used with v1 index format) */
};
// NOTE: file_name, index_complete and index_version are not stored on disk (on-memory-only values)
/* generic struct to return a function error code and a value */
struct returned_output {
uint64_t value;
int error;
};
enum EXIT_RETURNED_VALUES {
// used for app exit values:
EXIT_OK = 0,
EXIT_GENERIC_ERROR = 1,
EXIT_INVALID_OPTION = 2,
// used with returned_output.error, not in app exit values:
// +100 not to crush with Z_* values (zlib): //www.zlib.net/manual.html
// (and also not to crush with GZIP_MARK_FOUND_TYPE values... though
// they are used only for decompress_in_advance()'s ret.error value)
EXIT_FILE_OVERWRITTEN = 100,
};
enum INDEX_AND_EXTRACTION_OPTIONS {
JUST_CREATE_INDEX = 1, SUPERVISE_DO,
SUPERVISE_DO_AND_EXTRACT_FROM_TAIL, EXTRACT_FROM_BYTE,
EXTRACT_TAIL, COMPRESS_AND_CREATE_INDEX, DECOMPRESS,
EXTRACT_FROM_LINE };
enum ACTION
{ ACT_NOT_SET, ACT_EXTRACT_FROM_BYTE, ACT_COMPRESS_CHUNK, ACT_DECOMPRESS_CHUNK,
ACT_CREATE_INDEX, ACT_LIST_INFO, ACT_HELP, ACT_SUPERVISE, ACT_EXTRACT_TAIL,
ACT_EXTRACT_TAIL_AND_CONTINUE, ACT_COMPRESS_AND_CREATE_INDEX, ACT_DECOMPRESS,
ACT_EXTRACT_FROM_LINE };
enum VERBOSITY_LEVEL { VERBOSITY_NONE = 0, VERBOSITY_NORMAL = 1, VERBOSITY_EXCESSIVE = 2,
VERBOSITY_MANIAC = 3, VERBOSITY_CRAZY = 4, VERBOSITY_NUTS = 5 };
enum VERBOSITY_LEVEL verbosity_level = VERBOSITY_NORMAL;
// values returned by decompress_in_advance() in ret.error value:
enum GZIP_MARK_FOUND_TYPE {
GZIP_MARK_ERROR // GZIP_MARK_ERROR informs that recovery is not possible, but
// also that process will try to continue without recovery.
= 8, // All values greater than Z_* zlib's return codes, because
// a ret.error is used at decompress_in_advance() for both
// zlib's outputs and the function output (GZIP_MARK_FOUND_TYPE).
GZIP_MARK_FATAL_ERROR, // This value aborts process, 'cause a compulsory fseeko() failed.
GZIP_MARK_NONE, // Decompress_in_advance() didn't find an error in gzip stream (all ok!).
GZIP_MARK_BEGINNING, // An error was found, and a new complete gzip stream was found
// to reinitiate process at ret.value byte.
GZIP_MARK_FULL_FLUSH // An error was found, and a new gzip-Z_FULL_FLUSH was found
// to reinitiate process at ret.value byte.
};
// values used to initialize or continue processing with decompress_in_advance() function:
enum DECOMPRESS_IN_ADVANCE_INITIALIZERS {
DECOMPRESS_IN_ADVANCE_RESET, // initial total reset
DECOMPRESS_IN_ADVANCE_CONTINUE, // no reset, just continue processing
DECOMPRESS_IN_ADVANCE_SOFT_RESET // reset all but last_correct_reentry_point_returned
// in order to continue processing the same gzip stream.
};
// shared string for printing unit conversions without dealing with pointers:
// Always %.2f : "1234.67 Bytes\0" = 14 chars maximum
#define MAX_giveMeSIUnits_RETURNED_LENGTH 14
char number_output[MAX_giveMeSIUnits_RETURNED_LENGTH];
// `fprintf` substitute for printing with VERBOSITY_LEVEL
void printToStderr ( enum VERBOSITY_LEVEL verbosity, const char * format, ... ) {
// if verbosity of message is above general verbosity_level, ignore message
if ( verbosity <= verbosity_level ) {
va_list args;
va_start (args, format);
vfprintf ( stderr, format, args );
va_end (args);
}
}
// Convert an integer to a short string (2 decimal places) using SI units.
// Please, note that this function uses always "number_output" global variable as output.
// INPUT:
// uint64_t input_number : number to convert to binary SI units
// int binary : 0: decimal suffixes, 1: binary suffixes
// OUTPUT:
// pointer to buffer where string will be written:
// It is ALWAYS the "number_output" global variable.
char *giveMeSIUnits ( uint64_t input_number, int binary ) {
int i;
double number = (double)input_number;
double BASE = ( (binary==1)? 1024.0: 1000.0 );
char *SI_UNITS[7] =
{ "", "k", "M", "G", "T", "P", "E" };
char *SI_BINARY_UNITS[7] =
{ "Bytes", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
// totally empty string so that
// end-of-string char is always correctly set no matter the number
for ( i = 0; i < MAX_giveMeSIUnits_RETURNED_LENGTH; i++ )
number_output[i] = '\0';
for ( i = 0; number >= BASE; i++ )
number /= BASE;
snprintf( number_output, MAX_giveMeSIUnits_RETURNED_LENGTH,
"%.2f %s", number, ( (binary==1)? SI_BINARY_UNITS[i]: SI_UNITS[i] ) );
return number_output;
}
/**************
* Endianness *
**************/
static inline int endiannes_is_big(void)
{
long one= 1;
return !(*((char *)(&one)));
}
static inline uint32_t endiannes_swap_4(uint32_t v)
{
v = ((v & 0x0000FFFFU) << 16) | (v >> 16);
return ((v & 0x00FF00FFU) << 8) | ((v & 0xFF00FF00U) >> 8);
}
static inline void *endiannes_swap_4p(void *x)
{
*(uint32_t*)x = endiannes_swap_4(*(uint32_t*)x);
return x;
}
static inline uint64_t endiannes_swap_8(uint64_t v)
{
v = ((v & 0x00000000FFFFFFFFLLU) << 32) | (v >> 32);
v = ((v & 0x0000FFFF0000FFFFLLU) << 16) | ((v & 0xFFFF0000FFFF0000LLU) >> 16);
return ((v & 0x00FF00FF00FF00FFLLU) << 8) | ((v & 0xFF00FF00FF00FF00LLU) >> 8);
}
static inline void *endiannes_swap_8p(void *x)
{
*(uint64_t*)x = endiannes_swap_8(*(uint64_t*)x);
return x;
}
// fread() substitute for endianness management of 4 and 8 bytes words
// Data in *ptr will be received as this target system waits them
// independently of how they were stored (always as big endian).
// INPUT:
// void * ptr : pointer to buffer where data will be received
// size_t size : size of data in bytes
// FILE * stream: stream to read
// OUTPUT:
// number of bytes read
local size_t fread_endian( void * ptr, size_t size, FILE * stream ) {
size_t output = fread(ptr, size, 1, stream);
if (endiannes_is_big()) {
;
} else {
// machine is little endian: flip bytes
switch (size) {
case 4:
endiannes_swap_4p(ptr);
break;
case 8:
endiannes_swap_8p(ptr);
break;
default:
assert(0);
}
}
return output;
}
// fwrite() substitute for endianness management of 4 and 8 bytes words
// Data in *ptr will be stored as big endian
// independently of how they were stored in this system.
// INPUT:
// void * ptr : pointer to buffer where data is stored
// size_t size : size of data in bytes
// FILE * stream: stream to write
// OUTPUT:
// number of bytes written
local size_t fwrite_endian( void * ptr, size_t size, FILE * stream ) {
size_t output;
void *endian_ptr;
endian_ptr = malloc(size);
if (endiannes_is_big()) {
memcpy(endian_ptr, ptr, size);
} else {
// machine is little endian: flip bytes
switch (size) {
case 4:
*(uint32_t *)endian_ptr = *(uint32_t *)ptr;
endiannes_swap_4p(endian_ptr);
break;
case 8:
*(uint64_t *)endian_ptr = *(uint64_t *)ptr;
endiannes_swap_8p(endian_ptr);
break;
default:
assert(0);
}
}
output = fwrite(endian_ptr, size, 1, stream);
free(endian_ptr);
return output;
}
/*******************
* end: Endianness *
*******************/
// Compress source stream using zlib format.
// Used internally to compress the index' windows.
// based on def() from zlib/examples/zpipe.c by Mark Adler :
/* Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files. */
// INPUT:
// unsigned char *source: pointer to data
// uint64_t *size : size of data in bytes
// int level : level of compression
// OUTPUT:
// pointer to compressed data (NULL on error)
local unsigned char *compress_chunk(unsigned char *source, uint64_t *size, int level)
{
int ret, flush;
unsigned have;
z_stream strm;
uint64_t i = 0;
uint64_t output_size = 0;
uint64_t input_size = *size;
unsigned char *in, *out, *out_complete;
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return NULL;
in = malloc(CHUNK);
out = malloc(CHUNK);
out_complete = malloc(CHUNK);
/* compress until end of input */
do {
strm.avail_in = ((i + CHUNK) < input_size) ? CHUNK : (input_size - i);
if ( memcpy(in, source + i, strm.avail_in) == NULL ) {
(void)deflateEnd(&strm);
goto compress_chunk_error;
}
flush = ((i + CHUNK) >= input_size) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
i += strm.avail_in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = CHUNK - strm.avail_out;
if ( have != 0 && (
NULL == (out_complete = realloc(out_complete, output_size + have)) ||
NULL == memcpy(out_complete + output_size, out, have)
) ) {
(void)deflateEnd(&strm);
goto compress_chunk_error;
}
output_size += have;
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
/* done when last data in source processed */
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /* stream will be complete */
/* clean up and return */
(void)deflateEnd(&strm);
free(in);
free(out);
// return size of returned char array in size pointer parameter
*size = output_size;
return out_complete;
compress_chunk_error:
free(in);
free(out);
free(out_complete);
return NULL;
}
// Decompress a source stream with zlib format.
// Used internally to decompress the index' windows.
// based on inf() from zlib/examples/zpipe.c by Mark Adler
/* Decompress from file source to file dest until stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_DATA_ERROR if the deflate data is
invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
the version of the library linked do not match, or Z_ERRNO if there
is an error reading or writing the files. */
// INPUT:
// unsigned char *source: pointer to data
// uint64_t *size : size of data in bytes
// OUTPUT:
// pointer to decompressed data (NULL on error)
local unsigned char *decompress_chunk(unsigned char *source, uint64_t *size)
{
int ret;
unsigned have;
z_stream strm;
uint64_t i = 0;
uint64_t output_size = 0;
uint64_t input_size = *size;
unsigned char *in, *out, *out_complete;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK)
return NULL;
in = malloc(CHUNK);
out = malloc(CHUNK);
out_complete = malloc(CHUNK);
/* decompress until deflate stream ends or end of file */
do {
strm.avail_in = (i + CHUNK < input_size) ? CHUNK : (input_size - i);
if ( memcpy(in, source + i, strm.avail_in) == NULL ) {
(void)inflateEnd(&strm);
goto decompress_chunk_error;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
i += strm.avail_in;
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR;
(void)inflateEnd(&strm);
goto decompress_chunk_error;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
goto decompress_chunk_error;
}
have = CHUNK - strm.avail_out;
if ( have != 0 && (
NULL == (out_complete = realloc(out_complete, output_size + have)) ||
NULL == memcpy(out_complete + output_size, out, have)
) ) {
(void)inflateEnd(&strm);
goto decompress_chunk_error;
}
output_size += have;
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/* clean up and return */
(void)inflateEnd(&strm);
free(in);
free(out);
if (ret != Z_OK && ret != Z_STREAM_END) {
printToStderr( VERBOSITY_NORMAL, "Decompression of index' chunk terminated with error (%d).\n", ret);
}
// return size of returned char array in size pointer parameter
*size = output_size;
return out_complete;
decompress_chunk_error:
free(in);
free(out);
free(out_complete);
return NULL;
}
// Deallocate from memory
// an index built by decompress_and_build_index()
// INPUT:
// struct access *index: pointer to index
local void free_index(struct access *index)
{
uint64_t i;
if (index != NULL) {
for(i=0; i < index->have; i++) {
free(index->list[i].window);
}
free(index->list);
free(index->file_name);
free(index);
}
}
// fill pointers of and index->list with NULL windows
// so that free_index() can proceed on any contingency
// INPUT:
// struct access *index : pointer to index
// uint64_t from : initial point to fill
// uint64_t to : last point to fill
local void empty_index_list(struct access *index, uint64_t from, uint64_t to)
{
uint64_t i;
for (i=from; i<to; i++) {
index->list[i].window = NULL;
index->list[i].window_size = 0;
}
return;
}
// Allocate an index structure
// and fill it with empty values
// OUTPUT:
// pointer to index
local struct access *create_empty_index()
{
struct access *index;
if ( NULL == ( index = malloc(sizeof(struct access)) ) ) {
return NULL;
}
index->index_version = 0;
index->line_number_format = 0;
index->file_size = 0;
index->number_of_lines = 0;
index->list = NULL;
index->file_name = NULL;
index->list = malloc(sizeof(struct point) << 3);
empty_index_list( index, 0, 8 );
if (index->list == NULL) {
free(index);
return NULL;
}
index->size = 8;
index->have = 0;
index->index_complete = 0;
return index;
}
/* Add an entry to the access point list. If out of memory, deallocate the
existing list and return NULL. */
// INPUT:
// struct access *index : pointer to original index
// uint32_t bits : (new entry data)
// uint64_t in : (new entry data)
// uint64_t out : (new entry data)
// unsigned left : (new entry data)
// unsigned char *window: window data, already compressed with size window_size,
// or uncompressed with size WINSIZE,
// or store an empty window (NULL) because it resides on file.
// uint32_t window_size : size of passed *window (may be already compressed o not)
// uint64_t line_number : actual line number if index v1, 0 otherwise
// int compress_window : 0: store window of size window_size, as it is, in point structure
// 1: compress passed window of size window_size
// OUTPUT:
// pointer to (new) index (NULL on error)
local struct access *addpoint( struct access *index, uint32_t bits,
uint64_t in, uint64_t out, unsigned left, unsigned char *window, uint32_t window_size,
uint64_t line_number, int compress_window )
{
struct point *next;
uint64_t size = window_size;
unsigned char *compressed_chunk;
/* if list is empty, create it (starts with eight points) */
if (index == NULL) {
index = create_empty_index();
if (index == NULL) return NULL;
}
/* if list is full, make it bigger */
else if (index->have == index->size) {
index->size <<= 1;
next = realloc(index->list, sizeof(struct point) * index->size);
if (next == NULL) {
free_index(index);
return NULL;
}
index->list = next;
empty_index_list( index, index->have, index->size );
}
/* fill in entry and increment how many we have */
next = index->list + index->have;
next->bits = bits;
next->in = in;
next->out = out;
next->line_number = line_number;
if ( compress_window == 1 ) {
next->window_size = window_size;
next->window = NULL;
if ( window_size > 0 ) {
// compress window if window_size > 0: if not, a zero-length window is stored.
next->window = malloc( window_size );
// check left value with windows of size != WINSIZE
if ( left > window_size ||
window_size != WINSIZE )
left = 0;
if (left)
memcpy(next->window, window + window_size - left, left);
if (left < window_size)
memcpy(next->window + left, window, window_size - left);
// compress window
compressed_chunk = compress_chunk(next->window, &size, Z_DEFAULT_COMPRESSION);
if (compressed_chunk == NULL) {
printToStderr( VERBOSITY_NORMAL, "Error whilst compressing index chunk\nProcess aborted\n." );
return NULL;
}
free(next->window);
next->window = compressed_chunk;
/* uint64_t size and uint32_t window_size, but windows are small, so this will always fit */
next->window_size = size;
}
printToStderr( VERBOSITY_EXCESSIVE, "\t[%llu/%llu] window_size = %d\n", index->have+1, index->size, next->window_size);
} else {
// if NULL == window, this creates a NULL window: it resides on file,
// and can/will later loaded on memory with its correct ->window_size;
// if passed window is already compressed it will be stored as it is with size "window_size"
next->window_size = window_size;
next->window = window;
}
index->have++;
/* return list, possibly reallocated */
return index;
}
// serialize index into a file
// Note that the function writes and empty header when called with index_last_written_point = 0
// and also writes next points from index_last_written_point to index->have.
// To create a valid index, this function must be called a last time (at least, a 2nd time)
// to write the correct header values (and the (optional) tail (size of uncompressed file)).
// INPUT:
// FILE *output_file : output stream
// struct access *index : pointer to index
// uint64_t index_last_written_point : last index point already written to file: its values
// go from 1 to index->have, so that 0 has special value "None".
// OUTPUT:
// 0 on error, 1 on success
int serialize_index_to_file( FILE *output_file, struct access *index, uint64_t index_last_written_point ) {
struct point *here = NULL;
uint64_t temp;
uint64_t offset;
uint64_t i;
/* proceed only if there's something reasonable to do */
if (NULL == output_file || NULL == index) {
return 0;
}
/*if (index->have <= 0)
return 0;*/
/* writing and empty index is allowed: writes the header (of size 4*8 = 32 bytes) */
if ( index_last_written_point == 0 ) {
/* write header */
fseeko( output_file, 0, SEEK_SET);
/* 0x0 8 bytes (to be compatible with .gzi for bgzip format: */
/* the initial uint32_t is the number of bgzip-idx registers) */
temp = 0;
fwrite_endian(&temp, sizeof(temp), output_file);
/* a 64 bits readable identifier */
if ( index->index_version == 0 )
fprintf(output_file, GZIP_INDEX_IDENTIFIER_STRING);
else {
fprintf(output_file, GZIP_INDEX_IDENTIFIER_STRING_V1);
// there's an additional register on v1: line_number_format
fwrite_endian(&(index->line_number_format), sizeof(index->line_number_format), output_file);
}
/* and now the raw data: the access struct "index" */
// as this may be a growing index
// values will be filled with special, not actual, values:
// 0x0..0 , 0xf..f
// Last write operation will overwrite these with correct values, that is, when
// serialize_index_to_file() be called with index_last_written_point = index->have
temp = 0;
fwrite_endian(&temp, sizeof(temp), output_file); // have
temp = UINT64_MAX;
fwrite_endian(&temp, sizeof(temp), output_file); // size
}
offset = GZIP_INDEX_HEADER_SIZE + sizeof(temp) +
( (index->index_version == 1)? sizeof(index->line_number_format): 0 );
// update index->size on disk with index->have data
// ( if index->have == 0, no index points still, maintain UINT64_MAX )
if ( index->have > 0 ) {
// seek to index->have position
fseeko( output_file, offset, SEEK_SET );
// write index->have value; (when the index be closed, index->size on disk will be >0)
fwrite_endian( &(index->have), sizeof(index->have), output_file );
}
// fseek to index position of index_last_written_point
offset += sizeof(temp);
for (i = 0; i < index_last_written_point; i++) {
here = &(index->list[i]);
offset += sizeof(here->out) + sizeof(here->in) +
sizeof(here->bits) + sizeof(here->window_size) +
((here->window_size==UNCOMPRESSED_WINDOW)? WINSIZE: (here->window_size)) +
( (index->index_version == 1)? sizeof(here->line_number): 0 );
}
fseeko( output_file, offset, SEEK_SET);
printToStderr( VERBOSITY_MANIAC, "index_last_written_point = %llu\n", index_last_written_point );
if (NULL!=here) {
printToStderr( VERBOSITY_MANIAC, "%llu->window_size = %d\n", i, here->window_size );
}
printToStderr( VERBOSITY_MANIAC, "have = %llu, offset = %llu\n", index->have, offset );
if ( index_last_written_point != index->have ) {
for (i = index_last_written_point; i < index->have; i++) {
here = &(index->list[i]);
printToStderr( VERBOSITY_EXCESSIVE, "writing new point #%llu (%llu, %llu)\n", i+1, here->in, here->out );
fwrite_endian(&(here->out), sizeof(here->out), output_file);
fwrite_endian(&(here->in), sizeof(here->in), output_file);
fwrite_endian(&(here->bits), sizeof(here->bits), output_file);
if ( here->window_size==UNCOMPRESSED_WINDOW ) {
temp = WINSIZE;
fwrite_endian(&(temp), sizeof(here->window_size), output_file);
} else {
fwrite_endian(&(here->window_size), sizeof(here->window_size), output_file);
}
here->window_beginning = ftello(output_file);
if ( NULL == here->window &&
here->window_size != 0 ) {
printToStderr( VERBOSITY_NORMAL, "Index incomplete! - index writing aborted.\n" );
return 0;
} else {
if ( here->window_size > 0 )
fwrite(here->window, here->window_size, 1, output_file);
}
// once written, point's window CAN (and will now) BE DELETED from memory
free(here->window);
here->window = NULL;
if ( index->index_version == 1 ) {
// there's an additional register on v1: line_number
fwrite_endian(&(here->line_number), sizeof(here->line_number), output_file);
}
}
} else {
// Last write operation:
// tail must be written:
/* write size of uncompressed file (useful for bgzip files) */
fwrite_endian(&(index->file_size), sizeof(index->file_size), output_file);
if ( index->index_version == 1 ) {
// there's an additional register on v1: number_of_lines
fwrite_endian(&(index->number_of_lines), sizeof(index->number_of_lines), output_file);
}
// and header must be updated:
// for this, move position to header:
fseeko( output_file,
GZIP_INDEX_HEADER_SIZE + ( (1 == index->index_version)? sizeof(index->line_number_format): 0 ),
SEEK_SET );
fwrite_endian(&index->have, sizeof(index->have), output_file);
/* index->size is not written as only filled entries are usable */
fwrite_endian(&index->have, sizeof(index->have), output_file);
index->index_complete = 1; /* index is now complete */
}
// flush written content to disk
fflush( output_file );
return 1;
}
/* Basic checks of existing index file:
- Checks that last index point ->in isn't greater than gzip file size
*/
// INPUT:
// struct access *index : pointer to index. Can be NULL => no check.
// char *file_name : gzip file name. Can be NULL or "" => no check.
// char *index_filename: index file name. Must be != NULL, but can be "". Only used to print warning.
// OUTPUT:
// 0 on error, 1 on success
int check_index_file( struct access *index, char *file_name, char *index_filename ) {
if ( NULL != file_name &&
strlen( file_name ) > 0 ) {
if ( NULL != index &&
index->have > 0 ) {
// size of input file
struct stat st;
stat( file_name, &st );
printToStderr( VERBOSITY_EXCESSIVE, "(%llu >= %llu)\n", st.st_size, ( index->list[index->have - 1].in ) );
if ( index->have > 1 &&
(uint64_t) st.st_size < ( index->list[index->have - 1].in )
) {
printToStderr( VERBOSITY_NORMAL, "WARNING: Index file '%s' corresponds to a file bigger than '%s'\n",
index_filename, file_name );
return 0;
}
}
}
return 1;
}
// pread() does not exist in Windows, so in this platform
// pread() is substitued by a fseeko() + fread() operations.
// ReadFile() in Windows would also be feasible in decompress_in_advance()
// context as it will explicitly restore file pointer at the end,
// but it doesn't seem to worth the effort of using non-POSIX functions.
ssize_t PREAD(
FILE *fildes, void *buf, size_t nbyte, off_t offset
) {
#ifdef _WIN32
fseeko( fildes, offset, SEEK_SET );
return fread( buf, 1, nbyte, fildes );
#else
return pread( fileno( fildes ), buf, nbyte, offset );
#endif
}
// decompress at least CHUNKS_TO_DECOMPRESS_IN_ADVANCE chunks
// in front of actual decompression stream (decompress_and_build_index()),
// to assure that no errors will be found, and if an error is found in advance,
// try to find a reason in these CHUNKS_TO_DECOMPRESS_IN_ADVANCE chunks
// that explain it as an incorrectly terminated gzip stream and the
// beginning of a new one immediately attached after it:
// and so either a GZIP header or a full flush point are found there.
// If an error is found and a feasible restart is found, its gzip stream
// byte position is returned for decompress_and_build_index() to decompress
// ONLY until that point, and RESTART decompression just in it later.
// If errors aren't detected with decompression in advance, incorrect but
// technically viable (will not launch zlib errors) data can/will be extracted,
// and the point of error will be already inserted in another gzip stream
// than the original.
// INPUT:
// z_stream strm_original: shallow copy of strm from caller decompress_and_build_index()
// only used if local static strm structure hasn't been initialized
// FILE *file_in : file to be used for reading. Its position pointer will be restored
// to actual position when this function returns.
// (stdin is not valid as it doesn't allow fseeko())
// char *file_name: name of the input file associated with FILE *in, to check the size
// of the input file (if not stdin) to check shrinking.
// Can be "" (no file name: stdin used; though decompress_in_advance() MUST NOT be called then,
// because this function MUST be able to seek backwards in gzip stream),
// or NULL if initialize_function == DECOMPRESS_IN_ADVANCE_RESET.
// uint64_t totin0: total number of input gzip stream bytes already "correctly" processed:
// it is set on first call, with initialize_function == DECOMPRESS_IN_ADVANCE_RESET, AND ALSO in all later calls.
// int chunks_in_advance0 : indicates if a decompression in advance will be used and how many CHUNKs
// will be decompressed in advance then (CHUNKS_TO_DECOMPRESS_IN_ADVANCE).
// If decompress_in_advance is called, this value MUST be GREATER than 0
// AND it MUST be set ONLY on first call with initialize_function == DECOMPRESS_IN_ADVANCE_RESET.
// int chunks_to_look_backwards0 : indicates how many CHUNKs can look the function backwards in order
// to find a new good gzip entry point to patch an error found in the stream.
// If decompress_in_advance is called, this value MUST be GREATER than 0
// AND it MUST be set ONLY on first call with initialize_function == DECOMPRESS_IN_ADVANCE_RESET.
// enum INDEX_AND_EXTRACTION_OPTIONS indx_n_extraction_opts0: value of indx_n_extraction_opts on caller.