-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathzlib_accel.cpp
More file actions
5078 lines (4639 loc) · 212 KB
/
Copy pathzlib_accel.cpp
File metadata and controls
5078 lines (4639 loc) · 212 KB
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
// Copyright (C) 2025 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
// libz exports gzopen64, gzseek64, gztell64 and gzoffset64 alongside their
// plain-named counterparts, and an application built with
// -D_FILE_OFFSET_BITS=64 calls the 64-bit names, so the shim has to define both
// sets or the pair would disagree about where a file is positioned. zlib.h only
// declares them when asked (zconf.h:506), and this is the ask.
//
// zlib offers two large-file mechanisms and they are not interchangeable, which
// zlib.h says in its own words at the top of the block: "provide 64-bit offset
// functions if _LARGEFILE64_SOURCE defined, and/or change the regular functions
// to 64 bits if _FILE_OFFSET_BITS is 64". _LARGEFILE64_SOURCE is *additive*: it
// declares the *64 names next to the plain ones. _FILE_OFFSET_BITS=64 is
// *substitutive*: it renames the plain names into the *64 names and skips the
// branch that would have declared the plain prototypes. This file has to DEFINE
// both sets as separate functions, so only the additive one can be used here.
//
// What is at stake is linkage, not only offset width. There is no extern "C"
// anywhere in this file: every symbol gets C linkage by matching a declaration
// zlib.h already made inside its own extern "C" block. An interceptor that
// zlib.h does not declare is compiled as ordinary C++, comes out as (for
// gzseek64) _Z8gzseek64P8gzFile_sli, and cannot be interposed by LD_PRELOAD --
// with no compile error, no link error and no sign at runtime.
//
// The line below is not what prevents that here, and the note is worth leaving
// rather than implying otherwise: on glibc, features.h defines
// _LARGEFILE64_SOURCE itself whenever _GNU_SOURCE is set, every C++ front end
// predefines _GNU_SOURCE, and features.h is reached before zconf.h tests the
// macro. So Z_LARGE64 is on either way -- checked, including that an explicit
// #undef here does not stick, because features.h re-establishes it afterwards.
// The line stays because the requirement belongs in the file that has it
// instead of resting on a C++ front end's choice of feature macros, and because
// a C translation unit would genuinely need it (gcc -x c leaves
// _LARGEFILE64_SOURCE unset).
#define _LARGEFILE64_SOURCE 1
#include "zlib_accel.h"
// Guarding on Z_WANT64 rather than on _FILE_OFFSET_BITS directly: Z_WANT64 is
// what zconf.h:510 derives, so it is true exactly when the rename is about to
// happen, and it also covers the Z_PREFIX_SET spelling at zlib.h:1870.
#ifdef Z_WANT64
#error \
"zlib_accel.cpp must not be compiled with -D_FILE_OFFSET_BITS=64. zlib.h then renames gzopen to gzopen64 (and gzseek, gztell, gzoffset likewise), and this file has to DEFINE both names, so the rename collapses each pair onto one symbol. Large-file support for the shim comes from _LARGEFILE64_SOURCE above, which declares both sets without renaming either. Applications may use _FILE_OFFSET_BITS freely -- that is what the gzopen64/gzseek64/gztell64/gzoffset64 interceptors are for."
#endif
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/param.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <memory>
#include <new>
#include <string>
#include <utility>
#include <vector>
#include "config/config.h"
#include "logging.h"
#include "sharded_map.h"
#ifdef USE_IAA
#include "iaa.h"
#endif
#ifdef USE_IGZIP
#include "igzip.h"
#endif
#ifdef USE_QAT
#include "qat.h"
#endif
#include "statistics.h"
using namespace config;
// Window bits: 15 = zlib (deflate) format, 31 = gzip format
static constexpr int kWindowBitsZlib = 15;
static constexpr int kWindowBitsGzip = 31;
// Disable cfi-icall as it makes calls to orig* functions fail
#if defined(__clang__)
#pragma clang attribute push(__attribute__((no_sanitize("cfi-icall"))), \
apply_to = function)
#endif
// Original zlib functions
static int (*orig_deflateInit_)(z_streamp strm, int level, const char* version,
int stream_size);
static int (*orig_deflateInit2_)(z_streamp strm, int level, int method,
int window_bits, int mem_level, int strategy,
const char* version, int stream_size);
static int (*orig_deflateSetDictionary)(z_streamp strm, const Bytef* dictionary,
uInt dictLength);
static int (*orig_deflate)(z_streamp strm, int flush);
static int (*orig_deflateEnd)(z_streamp strm);
static int (*orig_deflateReset)(z_streamp strm);
static int (*orig_deflateResetKeep)(z_streamp strm);
static int (*orig_deflateParams)(z_streamp strm, int level, int strategy);
static int (*orig_deflatePrime)(z_streamp strm, int bits, int value);
static int (*orig_deflateCopy)(z_streamp dest, z_streamp source);
static int (*orig_inflateInit_)(z_streamp strm, const char* version,
int stream_size);
static int (*orig_inflateInit2_)(z_streamp strm, int window_bits,
const char* version, int stream_size);
static int (*orig_inflateSetDictionary)(z_streamp strm, const Bytef* dictionary,
uInt dictLength);
static int (*orig_inflate)(z_streamp strm, int flush);
static int (*orig_inflateEnd)(z_streamp strm);
static int (*orig_inflateReset)(z_streamp strm);
static int (*orig_inflateResetKeep)(z_streamp strm);
static int (*orig_inflateReset2)(z_streamp strm, int windowBits);
static int (*orig_inflatePrime)(z_streamp strm, int bits, int value);
static int (*orig_inflateCopy)(z_streamp dest, z_streamp source);
static int (*orig_inflateSync)(z_streamp strm);
static int (*orig_compress)(Bytef* dest, uLongf* destLen, const Bytef* source,
uLong sourceLen);
static int (*orig_compress2)(Bytef* dest, uLongf* destLen, const Bytef* source,
uLong sourceLen, int level);
static int (*orig_uncompress)(Bytef* dest, uLongf* destLen, const Bytef* source,
uLong sourceLen);
static int (*orig_uncompress2)(Bytef* dest, uLongf* destLen,
const Bytef* source, uLong* sourceLen);
static gzFile (*orig_gzopen)(const char* path, const char* mode);
static gzFile (*orig_gzdopen)(int fd, const char* mode);
static int (*orig_gzwrite)(gzFile file, voidpc buf, unsigned len);
static int (*orig_gzread)(gzFile file, voidp buf, unsigned len);
static int (*orig_gzclose)(gzFile file);
static int (*orig_gzclose_r)(gzFile file);
static int (*orig_gzclose_w)(gzFile file);
static int (*orig_gzeof)(gzFile file);
static int (*orig_gzsetparams)(gzFile file, int level, int strategy);
static int (*orig_gzflush)(gzFile file, int flush);
static int (*orig_gzputc)(gzFile file, int c);
static int (*orig_gzputs)(gzFile file, const char* s);
static z_size_t (*orig_gzfwrite)(voidpc buf, z_size_t size, z_size_t nitems,
gzFile file);
static int (*orig_gzvprintf)(gzFile file, const char* format, va_list va);
static int (*orig_gzgetc)(gzFile file);
static int (*orig_gzungetc)(int c, gzFile file);
static char* (*orig_gzgets)(gzFile file, char* buf, int len);
static z_size_t (*orig_gzfread)(voidp buf, z_size_t size, z_size_t nitems,
gzFile file);
// Only ever called on a file zlib owns, where zlib is doing the reading and its
// answer is the true one. Never on a file the shim reads: the call is what
// makes zlib look, and the look allocates and reads ahead. See gzdirect below.
static int (*orig_gzdirect)(gzFile file);
static const char* (*orig_gzerror)(gzFile file, int* errnum);
static void (*orig_gzclearerr)(gzFile file);
static z_off_t (*orig_gztell)(gzFile file);
static z_off64_t (*orig_gztell64)(gzFile file);
static z_off_t (*orig_gzoffset)(gzFile file);
static z_off64_t (*orig_gzoffset64)(gzFile file);
static z_off_t (*orig_gzseek)(gzFile file, z_off_t offset, int whence);
static z_off64_t (*orig_gzseek64)(gzFile file, z_off64_t offset, int whence);
static int (*orig_gzrewind)(gzFile file);
static int (*orig_gzbuffer)(gzFile file, unsigned size);
// Forward declaration — defined after DeflateStreamSettings,
// InflateStreamSettings, and GzipFiles class definitions below
static void InitStreamRegistries();
// Initialize/cleanup functions when library is loaded
static int init_zlib_accel(void) __attribute__((constructor));
static void cleanup_zlib_accel(void) __attribute__((destructor));
// Number of orig_* symbols that failed to resolve. Only used for the summary
// log below: each wrapper checks the specific pointer it needs, so one missing
// symbol degrades only the paths that actually call it.
static int missing_symbol_count = 0;
// Macro that loads symbols. A failure is logged but does not stop the sequence:
// returning early from the constructor would leave every later orig_* pointer
// null (and the return value of a constructor is ignored anyway), so keep going
// and resolve as many as possible.
#define LOAD_SYMBOL(fptr, type, name) \
do { \
dlerror(); \
fptr = reinterpret_cast<type>(dlsym(RTLD_NEXT, name)); \
const char* error = dlerror(); \
if (error != nullptr) { \
Log(LogLevel::LOG_ERROR, "init_zlib_accel Line ", __LINE__, \
"Failed to load symbol '", name, "': ", error, "\n"); \
fptr = nullptr; \
missing_symbol_count++; \
} else if (fptr == nullptr) { \
Log(LogLevel::LOG_ERROR, "init_zlib_accel Line ", __LINE__, " Symbol '", \
name, "' resolved to NULL\n"); \
missing_symbol_count++; \
} \
} while (0)
static int init_zlib_accel(void) {
// Load deflate functions
LOAD_SYMBOL(orig_deflateInit_, int (*)(z_streamp, int, const char*, int),
"deflateInit_");
LOAD_SYMBOL(orig_deflateInit2_,
int (*)(z_streamp, int, int, int, int, int, const char*, int),
"deflateInit2_");
LOAD_SYMBOL(orig_deflateSetDictionary, int (*)(z_streamp, const Bytef*, uInt),
"deflateSetDictionary");
LOAD_SYMBOL(orig_deflate, int (*)(z_streamp, int), "deflate");
LOAD_SYMBOL(orig_deflateEnd, int (*)(z_streamp), "deflateEnd");
LOAD_SYMBOL(orig_deflateReset, int (*)(z_streamp), "deflateReset");
LOAD_SYMBOL(orig_deflateResetKeep, int (*)(z_streamp), "deflateResetKeep");
LOAD_SYMBOL(orig_deflateParams, int (*)(z_streamp, int, int),
"deflateParams");
LOAD_SYMBOL(orig_deflatePrime, int (*)(z_streamp, int, int), "deflatePrime");
LOAD_SYMBOL(orig_deflateCopy, int (*)(z_streamp, z_streamp), "deflateCopy");
// Load inflate functions
LOAD_SYMBOL(orig_inflateInit_, int (*)(z_streamp, const char*, int),
"inflateInit_");
LOAD_SYMBOL(orig_inflateInit2_, int (*)(z_streamp, int, const char*, int),
"inflateInit2_");
LOAD_SYMBOL(orig_inflateSetDictionary, int (*)(z_streamp, const Bytef*, uInt),
"inflateSetDictionary");
LOAD_SYMBOL(orig_inflate, int (*)(z_streamp, int), "inflate");
LOAD_SYMBOL(orig_inflateEnd, int (*)(z_streamp), "inflateEnd");
LOAD_SYMBOL(orig_inflateReset, int (*)(z_streamp), "inflateReset");
LOAD_SYMBOL(orig_inflateResetKeep, int (*)(z_streamp), "inflateResetKeep");
LOAD_SYMBOL(orig_inflateReset2, int (*)(z_streamp, int), "inflateReset2");
LOAD_SYMBOL(orig_inflatePrime, int (*)(z_streamp, int, int), "inflatePrime");
LOAD_SYMBOL(orig_inflateCopy, int (*)(z_streamp, z_streamp), "inflateCopy");
LOAD_SYMBOL(orig_inflateSync, int (*)(z_streamp), "inflateSync");
// Load compress/uncompress functions
LOAD_SYMBOL(orig_compress, int (*)(Bytef*, uLongf*, const Bytef*, uLong),
"compress");
LOAD_SYMBOL(orig_compress2,
int (*)(Bytef*, uLongf*, const Bytef*, uLong, int), "compress2");
LOAD_SYMBOL(orig_uncompress, int (*)(Bytef*, uLongf*, const Bytef*, uLong),
"uncompress");
LOAD_SYMBOL(orig_uncompress2, int (*)(Bytef*, uLongf*, const Bytef*, uLong*),
"uncompress2");
// Load gzip functions
LOAD_SYMBOL(orig_gzopen, gzFile(*)(const char*, const char*), "gzopen");
LOAD_SYMBOL(orig_gzdopen, gzFile(*)(int, const char*), "gzdopen");
LOAD_SYMBOL(orig_gzwrite, int (*)(gzFile, voidpc, unsigned), "gzwrite");
LOAD_SYMBOL(orig_gzread, int (*)(gzFile, voidp, unsigned), "gzread");
LOAD_SYMBOL(orig_gzclose, int (*)(gzFile), "gzclose");
LOAD_SYMBOL(orig_gzclose_r, int (*)(gzFile), "gzclose_r");
LOAD_SYMBOL(orig_gzclose_w, int (*)(gzFile), "gzclose_w");
LOAD_SYMBOL(orig_gzeof, int (*)(gzFile), "gzeof");
LOAD_SYMBOL(orig_gzsetparams, int (*)(gzFile, int, int), "gzsetparams");
LOAD_SYMBOL(orig_gzflush, int (*)(gzFile, int), "gzflush");
LOAD_SYMBOL(orig_gzputc, int (*)(gzFile, int), "gzputc");
LOAD_SYMBOL(orig_gzputs, int (*)(gzFile, const char*), "gzputs");
LOAD_SYMBOL(orig_gzfwrite, z_size_t(*)(voidpc, z_size_t, z_size_t, gzFile),
"gzfwrite");
LOAD_SYMBOL(orig_gzvprintf, int (*)(gzFile, const char*, va_list),
"gzvprintf");
LOAD_SYMBOL(orig_gzgetc, int (*)(gzFile), "gzgetc");
LOAD_SYMBOL(orig_gzungetc, int (*)(int, gzFile), "gzungetc");
LOAD_SYMBOL(orig_gzgets, char* (*)(gzFile, char*, int), "gzgets");
LOAD_SYMBOL(orig_gzfread, z_size_t(*)(voidp, z_size_t, z_size_t, gzFile),
"gzfread");
LOAD_SYMBOL(orig_gzdirect, int (*)(gzFile), "gzdirect");
LOAD_SYMBOL(orig_gzerror, const char* (*)(gzFile, int*), "gzerror");
LOAD_SYMBOL(orig_gzclearerr, void (*)(gzFile), "gzclearerr");
LOAD_SYMBOL(orig_gztell, z_off_t(*)(gzFile), "gztell");
LOAD_SYMBOL(orig_gztell64, z_off64_t(*)(gzFile), "gztell64");
LOAD_SYMBOL(orig_gzoffset, z_off_t(*)(gzFile), "gzoffset");
LOAD_SYMBOL(orig_gzoffset64, z_off64_t(*)(gzFile), "gzoffset64");
LOAD_SYMBOL(orig_gzseek, z_off_t(*)(gzFile, z_off_t, int), "gzseek");
LOAD_SYMBOL(orig_gzseek64, z_off64_t(*)(gzFile, z_off64_t, int), "gzseek64");
LOAD_SYMBOL(orig_gzrewind, int (*)(gzFile), "gzrewind");
LOAD_SYMBOL(orig_gzbuffer, int (*)(gzFile, unsigned), "gzbuffer");
if (missing_symbol_count > 0) {
Log(LogLevel::LOG_ERROR, "init_zlib_accel Line ", __LINE__, " ",
missing_symbol_count,
" zlib symbol(s) could not be resolved; the affected entry points fall "
"back to zlib where possible and return Z_VERSION_ERROR where not\n");
}
// Load configuration file; on failure (file absent or is a symlink) continue
// with compiled-in defaults — a missing config is not fatal. The whole block
// is wrapped: this runs from a constructor, called before the host's own
// main(), so an exception escaping it (std::bad_alloc, or std::system_error
// from a registry's mutex on the non-TBB build) has no handler above it and
// calls std::terminate, aborting the host process outright. Catching here
// keeps that the same non-fatal case as a missing config file.
try {
std::string config_file_content;
std::string log_file;
const bool config_loaded = config::LoadConfigFile(
config_file_content, config::kDefaultConfigPath, &log_file);
if (!config_loaded) {
Log(LogLevel::LOG_ERROR,
"Failed to load configuration file, continuing with defaults\n");
}
InitStreamRegistries();
#if defined(DEBUG_LOG) || defined(ENABLE_STATISTICS)
if (config_loaded && !log_file.empty()) {
CreateLogFile(log_file.c_str());
}
#endif
} catch (...) {
Log(LogLevel::LOG_ERROR, "init_zlib_accel Line ", __LINE__,
" configuration/registry initialization threw; continuing with "
"compiled-in defaults\n");
}
return 0;
}
static void cleanup_zlib_accel(void) {
#if defined(DEBUG_LOG) || defined(ENABLE_STATISTICS)
CloseLogFile();
#endif
}
#undef LOAD_SYMBOL
// Avoid recursive call (e.g., if QATzip falls back to zlib internally)
static thread_local bool in_call = false;
constexpr uint8_t ZLIB_FDICT_MASK = 0x20;
#ifdef DEBUG_LOG
// Readable name for the numeric path in log output. Only referenced from Log(),
// which compiles away entirely when DEBUG_LOG is off.
static const char* ExecutionPathName(ExecutionPath path) {
switch (path) {
case UNDEFINED:
return "UNDEFINED";
case ZLIB:
return "ZLIB";
case QAT:
return "QAT";
case IAA:
return "IAA";
case IGZIP:
return "IGZIP";
}
return "UNKNOWN";
}
#endif // DEBUG_LOG
struct DeflateSettings {
DeflateSettings(int _level, int _method, int _window_bits, int _mem_level,
int _strategy)
: level(_level),
method(_method),
window_bits(_window_bits),
mem_level(_mem_level),
strategy(_strategy) {}
int level;
int method;
int window_bits;
int mem_level;
int strategy;
ExecutionPath path = UNDEFINED;
struct isal_zstream* isal_strm = nullptr;
// Set once the shim has reported Z_STREAM_END for this stream. Only an
// offloaded completion sets it: an accelerator finishes the stream without
// ever feeding zlib's own state, so zlib cannot report the terminal state
// afterwards and every later call would be dispatched from scratch. A
// ZLIB-path stream is left alone, since zlib tracks this itself.
bool stream_end_reached = false;
// The flush value of the last offloaded deflate() call, for the empty-flush
// rule in IsRedundantEmptyFlush(). -2 is what zlib's deflateResetKeep() puts
// in its own last_flush, and it ranks below every real flush value so the
// first call on a stream is never refused.
int last_flush = -2;
};
struct InflateSettings {
InflateSettings(int _window_bits) : window_bits(_window_bits) {}
int window_bits;
ExecutionPath path = UNDEFINED;
struct inflate_state* isal_strm = nullptr;
// See DeflateSettings::stream_end_reached.
bool stream_end_reached = false;
// Set once an offloaded call has consumed input from this stream. From that
// point on next_in addresses the middle of a stream zlib's own inflate state
// has never seen, so the remainder cannot be handed to orig_inflate: it would
// be parsed as the start of a new stream, with no history behind it.
bool bytes_consumed = false;
// Set once a mid-stream decode failure has been reported. zlib latches a data
// error and answers every later call with it until inflateSync() or a reset
// clears the state; ISA-L does not, and keeps parsing whatever follows the
// rejected bytes as a new block header, so the latch has to live here.
bool data_error = false;
// Set once IAA has rejected a block of this stream for referencing a match
// beyond its 4 kB history buffer. Deliberately NOT cleared by inflateReset:
// the window is a property of the compressor that produced the bytes, and a
// reset starts a new stream from the same producer in every caller that
// matters here (Lucene resets its Inflater once per stored-field document).
// Clearing it would make the flag useless, since almost every rejection
// arrives on a stream that is about to be reset.
bool iaa_window_too_large = false;
};
// isal_strm is a raw pointer, so destroying a settings object does not free the
// ISA-L stream it owns. Every path that discards an entry has to come through
// here: *End() when the caller is done with the stream, and Set()/SetFromCopy()
// when a new entry replaces one that is still holding state.
static void ReleaseDeflateIgzipState(
const std::shared_ptr<DeflateSettings>& settings) {
if (settings == nullptr || settings->isal_strm == nullptr) {
return;
}
#ifdef USE_IGZIP
EndCompressIGZIP(settings->isal_strm);
#endif
settings->isal_strm = nullptr;
}
static void ReleaseInflateIgzipState(
const std::shared_ptr<InflateSettings>& settings) {
if (settings == nullptr || settings->isal_strm == nullptr) {
return;
}
#ifdef USE_IGZIP
EndUncompressIGZIP(settings->isal_strm);
#endif
settings->isal_strm = nullptr;
}
class DeflateStreamSettings {
public:
// Reports failure by logging rather than throwing, for the same reason as
// SetFromCopy() below: the caller is deflateInit_/deflateInit2_, an exported
// zlib symbol, and an exception escaping here would cross into a C caller
// that cannot catch it. orig_deflateInit_/orig_deflateInit2_ has already
// succeeded by the time this runs, so a previous entry (if any) belongs to
// a lifecycle that is no longer live -- leaving it in place would hand the
// new zlib stream stale settings, and a stale isal_strm, from the old one.
// On failure the entry is therefore removed outright (Unset() is a no-op if
// there was none), same as a stream that never had an entry, which
// deflate()'s own nullptr-settings check already forwards to zlib. Get() is
// inside the try too: it takes a shared_lock on the non-TBB build and can
// throw std::system_error the same way Set() can.
void Set(z_streamp strm, int level, int method, int window_bits,
int mem_level, int strategy) {
std::shared_ptr<DeflateSettings> previous;
try {
previous = map.Get(strm);
auto settings = std::make_shared<DeflateSettings>(
level, method, window_bits, mem_level, strategy);
map.Set(strm, std::move(settings));
} catch (...) {
Log(LogLevel::LOG_ERROR, "Set() failed to register deflate stream ",
static_cast<void*>(strm), "\n");
map.Unset(strm);
ReleaseDeflateIgzipState(previous);
return;
}
// A second deflateInit*() on a stream that was never ended replaces an
// entry that may still own an ISA-L stream, which nothing can reach once
// the entry is gone. See SetFromCopy() for the ordering.
ReleaseDeflateIgzipState(previous);
}
// Registers dest as a copy of an already-tracked stream, for deflateCopy().
// Deliberately not a copy of the DeflateSettings object: that would carry
// isal_strm over and leave the two streams sharing one ISA-L state.
//
// Reports failure instead of throwing: the caller is an exported zlib symbol,
// so an exception escaping here would cross into a C caller that cannot catch
// it. The catch is deliberately unqualified -- besides bad_alloc from the
// allocations here, ShardedMap::Set() locks a std::shared_mutex on the
// non-TBB build and so can throw std::system_error. Returning false lets the
// caller undo the copy and report Z_MEM_ERROR, which alongside
// Z_STREAM_ERROR is the only failure zlib documents for deflateCopy().
bool SetFromCopy(z_streamp dest, const DeflateSettings& source) {
// dest may already be an initialized, used stream whose entry owns an ISA-L
// stream. Read that entry before replacing it, and release it only after
// the replacement has landed: freeing first would leave a dangling
// isal_strm in the map if the work below throws. The shared_ptr keeps the
// old settings alive past map.Set().
auto previous = map.Get(dest);
try {
auto settings = std::make_shared<DeflateSettings>(
source.level, source.method, source.window_bits, source.mem_level,
source.strategy);
settings->path = source.path;
settings->stream_end_reached = source.stream_end_reached;
settings->last_flush = source.last_flush;
map.Set(dest, std::move(settings));
} catch (...) {
Log(LogLevel::LOG_ERROR,
"SetFromCopy() failed to register deflate stream ",
static_cast<void*>(dest), "\n");
return false;
}
ReleaseDeflateIgzipState(previous);
return true;
}
void Unset(z_streamp strm) { map.Unset(strm); }
std::shared_ptr<DeflateSettings> Get(z_streamp strm) { return map.Get(strm); }
void Init() { map.Init(); }
private:
ShardedMap<z_streamp, std::shared_ptr<DeflateSettings>> map;
};
DeflateStreamSettings deflate_stream_settings;
class InflateStreamSettings {
public:
// See the deflate-side Set() for why failure is logged rather than thrown,
// why a failed Set() removes the entry outright rather than leaving a
// previous one in place, and why Get() is inside the try too.
void Set(z_streamp strm, int window_bits) {
std::shared_ptr<InflateSettings> previous;
try {
previous = map.Get(strm);
auto settings = std::make_shared<InflateSettings>(window_bits);
map.Set(strm, std::move(settings));
} catch (...) {
Log(LogLevel::LOG_ERROR, "Set() failed to register inflate stream ",
static_cast<void*>(strm), "\n");
map.Unset(strm);
ReleaseInflateIgzipState(previous);
return;
}
// See the deflate-side Set().
ReleaseInflateIgzipState(previous);
}
// Registers dest as a copy of an already-tracked stream, for inflateCopy().
// isal_clone is passed in rather than copied from source so that ownership of
// the cloned ISA-L state is explicit: the caller allocates it, this entry
// point hands it to the new settings, and inflateEnd() frees it. Ownership
// therefore transfers only when this returns true; on false the clone is
// still the caller's to free, along with zlib's half of the copy. See the
// deflate-side comment for why failure is reported, not thrown, and for the
// ordering of the release below.
bool SetFromCopy(z_streamp dest, const InflateSettings& source,
struct inflate_state* isal_clone) {
auto previous = map.Get(dest);
try {
auto settings = std::make_shared<InflateSettings>(source.window_bits);
settings->path = source.path;
settings->isal_strm = isal_clone;
settings->stream_end_reached = source.stream_end_reached;
settings->bytes_consumed = source.bytes_consumed;
settings->data_error = source.data_error;
// A copy decodes the rest of the same stream, so it inherits what IAA
// already said about that stream's history window. This has to be copied
// out by hand like every other field: the settings are rebuilt member by
// member here, not assigned, so a new member is silently dropped
// otherwise.
settings->iaa_window_too_large = source.iaa_window_too_large;
map.Set(dest, std::move(settings));
} catch (...) {
Log(LogLevel::LOG_ERROR,
"SetFromCopy() failed to register inflate stream ",
static_cast<void*>(dest), "\n");
return false;
}
ReleaseInflateIgzipState(previous);
return true;
}
void Unset(z_streamp strm) { map.Unset(strm); }
std::shared_ptr<InflateSettings> Get(z_streamp strm) { return map.Get(strm); }
void Init() { map.Init(); }
private:
ShardedMap<z_streamp, std::shared_ptr<InflateSettings>> map;
};
InflateStreamSettings inflate_stream_settings;
static void SetDeflatePath(const std::shared_ptr<DeflateSettings>& settings,
ExecutionPath new_path) {
if (settings == nullptr || settings->path == new_path) {
return;
}
settings->path = new_path;
}
static void SetInflatePath(const std::shared_ptr<InflateSettings>& settings,
ExecutionPath new_path) {
if (settings == nullptr || settings->path == new_path) {
return;
}
settings->path = new_path;
}
// Shim-side state work every deflate reset entry point performs. Only the path
// is cleared. zlib's deflateReset keeps the compression level and strategy,
// including any set later by deflateParams(), so the recorded level must
// survive a reset too or path selection would disagree with the level zlib is
// actually using. The terminal-state flag has to go, though: a reset stream is
// ready to compress again, and leaving it set would wedge every later deflate()
// at Z_STREAM_END.
static void ResetDeflateStreamState(
const std::shared_ptr<DeflateSettings>& settings) {
if (settings == nullptr) {
return;
}
SetDeflatePath(settings, UNDEFINED);
settings->stream_end_reached = false;
// Both of zlib's reset entry points put last_flush back to -2, so the first
// flush on the restarted stream does work whatever the previous one asked
// for.
settings->last_flush = -2;
#ifdef USE_IGZIP
if (settings->isal_strm != nullptr) {
// Keeping the recorded level is not sufficient for the ISA-L stream:
// isal_deflate_reset() deliberately preserves level and level_buf, and
// deflate() only calls InitCompressIGZIP() when isal_strm is null, so a
// level that deflateParams() changed since this stream was built would
// leave the next stream running at the old ISA-L level. Discard the stream
// in that case and let deflate() rebuild it from the current setting; the
// common reset, where the level did not change, keeps the stream and its
// level_buf allocation. The reverse ordering -- reset first, then
// deflateParams() -- is handled in deflateParams().
if (CompressLevelChangedIGZIP(settings->isal_strm, settings->level)) {
EndCompressIGZIP(settings->isal_strm);
settings->isal_strm = nullptr;
} else {
ResetCompressIGZIP(settings->isal_strm);
}
}
#endif
}
// Same for the inflate side. A reset stream is ready to decode again; leaving
// the terminal state set would wedge every later inflate() at Z_STREAM_END.
//
// iaa_window_too_large deliberately does NOT belong here. It records what IAA
// said about the compressor that produced these bytes, and a reset stream is
// almost always the same caller decoding more output from the same producer --
// Lucene resets its Inflater once per stored-field document. Clearing it here
// would make the flag useless: it would be forgotten before it was ever
// consulted, and the shim would go back to submitting jobs it knows will be
// rejected. inflateReset2() is the one exception, and clears the field itself:
// a caller that declares an IAA-sized window has said what the next stream is,
// which beats an inference drawn from the last one.
static void ResetInflateStreamState(
const std::shared_ptr<InflateSettings>& settings) {
if (settings == nullptr) {
return;
}
SetInflatePath(settings, UNDEFINED);
settings->stream_end_reached = false;
settings->bytes_consumed = false;
settings->data_error = false;
if (settings->isal_strm != nullptr) {
#ifdef USE_IGZIP
ResetUncompressIGZIP(settings->isal_strm);
#endif
}
}
// Hand the caller what an offloaded inflate call consumed and produced. Every
// such call goes through here, so this is also where a stream is recorded as
// consumed from -- zlib's inflate state saw none of these bytes.
static void AdvanceInflateStream(
z_streamp strm, const std::shared_ptr<InflateSettings>& settings,
uint32_t input_len, uint32_t output_len) {
strm->next_in += input_len;
strm->avail_in -= input_len;
strm->total_in += input_len;
strm->next_out += output_len;
strm->avail_out -= output_len;
strm->total_out += output_len;
if (input_len > 0 && settings != nullptr) {
settings->bytes_consumed = true;
}
}
#ifdef USE_IGZIP
// An IGZIP decode failure part-way through a stream cannot be handed to zlib.
// zlib's inflate state saw none of the earlier chunks, so the bytes left in
// next_in begin inside a deflate block with no history behind them: zlib parses
// them as a fresh stream, which a zlib or gzip header check rejects but raw
// deflate cannot, and whatever ISA-L had already decoded in the failing call is
// dropped on the way. Deliver that output -- zlib hands back the decodable
// prefix before reporting the error too -- and report the error here.
//
// A stream that has consumed nothing yet is the case the fall-through was
// written for: next_in still addresses the first byte, so zlib can take the
// whole stream from the start, and such a call is left to do exactly that.
// Returns true when the error was answered here.
static bool HandleMidStreamIGZIPInflateError(
z_streamp strm, const std::shared_ptr<InflateSettings>& settings,
uint32_t input_len, uint32_t output_len, int* ret) {
if (settings == nullptr || !settings->bytes_consumed) {
return false;
}
AdvanceInflateStream(strm, settings, input_len, output_len);
settings->data_error = true;
*ret = Z_DATA_ERROR;
return true;
}
// Run ISA-L over one inflate call and apply the path decision it reports.
// inflate() reaches ISA-L two ways -- the IGZIP dispatch and the
// accelerator->IGZIP retry -- and both do exactly this; `source` only names the
// engine in the log line. Returns false when ISA-L has no stream, which is the
// caller's cue to answer Z_DATA_ERROR.
static bool RunIGZIPInflateAndApplyPathAction(
z_streamp strm, const std::shared_ptr<InflateSettings>& settings,
const char* source, uint32_t* input_len, uint32_t* output_len, int* ret,
bool* end_of_stream, bool* midstream_error) {
// Log() compiles away without DEBUG_LOG, taking the only use of `source`.
(void)source;
in_call = true;
const IGZIPInflatePathAction path_action = IGZIPRunInflateAndSelectPathAction(
strm, &settings->isal_strm, settings->window_bits, input_len, output_len,
ret, end_of_stream);
in_call = false;
if (settings->isal_strm == nullptr) {
return false;
}
if (path_action == IGZIP_INFLATE_PATH_FALLBACK_NEED_DICT) {
Log(LogLevel::LOG_ERROR, " strm=", static_cast<void*>(strm),
" source=", source, " total_in=", strm->total_in,
" total_out=", strm->total_out, " adler=", strm->adler, "\n");
*midstream_error = HandleMidStreamIGZIPInflateError(
strm, settings, *input_len, *output_len, ret);
if (!*midstream_error) {
SetInflatePath(settings, ZLIB);
}
} else if (path_action == IGZIP_INFLATE_PATH_FALLBACK_DATA_ERROR) {
*midstream_error = HandleMidStreamIGZIPInflateError(
strm, settings, *input_len, *output_len, ret);
if (!*midstream_error) {
SetInflatePath(settings, ZLIB);
}
} else if (path_action == IGZIP_INFLATE_PATH_SET_IGZIP &&
settings->path != ZLIB) {
SetInflatePath(settings, IGZIP);
}
INCREMENT_STAT(INFLATE_IGZIP_COUNT);
INCREMENT_STAT_COND(*ret != 0, INFLATE_IGZIP_ERROR_COUNT);
return true;
}
#endif // USE_IGZIP
// zlib's Z_NO_COMPRESSION (0) asks for stored, uncompressed deflate blocks. No
// backend can produce those: ISA-L's level 0 is still LZ77+Huffman ("fastest"),
// and QAT and IAA take no level argument at all -- all three would silently
// compress data the caller asked to be stored. Levels outside zlib's -1..9
// range are rejected by zlib itself, so leave those for zlib to report too.
// Everything else maps onto an ISA-L level in InitCompressIGZIP().
static bool IsOffloadableCompressionLevel(int level) {
return level == Z_DEFAULT_COMPRESSION || (level >= 1 && level <= 9);
}
// True when ISA-L holds live state for this stream: it has emitted a header and
// may still hold unflushed data, so the stream can neither be handed to zlib
// nor rebuilt at a different compression level without corrupting the output.
// Both deflate()'s level-0 pin and deflateParams()' discard of a stream built
// for a superseded level exempt such a stream, and deflate() uses it to keep an
// already-started IGZIP stream on IGZIP.
static bool IgzipOwnsDeflateStream(
const std::shared_ptr<DeflateSettings>& settings) {
return settings != nullptr && settings->path == IGZIP &&
settings->isal_strm != nullptr;
}
#ifdef USE_IGZIP
// zlib refuses a deflate() call that carries no input and asks for a flush no
// stronger than the previous one: it has nothing to compress and the flush it
// is being asked for has already been performed, so it reports Z_BUF_ERROR and
// writes nothing. The ranking is zlib's own (the RANK macro in deflate.c), and
// it is not the numeric order of the flush constants -- Z_BLOCK and Z_TREES
// were added later and rank between Z_NO_FLUSH and Z_SYNC_FLUSH:
//
// Z_NO_FLUSH 0, Z_BLOCK 1, Z_PARTIAL_FLUSH 2, Z_TREES 3, Z_SYNC_FLUSH 4,
// Z_FULL_FLUSH 6, Z_FINISH 8
//
// This is zlib policy rather than a property of any backend, so it lives here.
// ISA-L has no such rule: it emits the empty stored block that byte-aligns the
// output for every SYNC_FLUSH and FULL_FLUSH, whether or not one was just
// emitted, so an application that flushes on a timer with no new data would
// grow the stream by those marker bytes on every tick. The output stays valid
// deflate, so nothing downstream reports it.
//
// Z_FINISH is exempt: it must always be able to close the stream, however many
// times it is repeated.
static bool IsRedundantEmptyFlush(uInt avail_in, int flush, int last_flush) {
const auto rank = [](int f) { return f * 2 - (f > 4 ? 9 : 0); };
return avail_in == 0 && flush != Z_FINISH && rank(flush) <= rank(last_flush);
}
// Run ISA-L over one deflate call, creating its stream on first use, after
// applying the rules above for a call zlib would refuse outright. deflate()
// reaches ISA-L two ways -- the IGZIP dispatch and the accelerator->IGZIP retry
// -- and both need this same sequence. Returns whether ISA-L ran: when it has
// no stream there is nothing to report, so `ret` is left as the caller set it
// and the stream falls through to zlib. `call_refused` tells the return-code
// translation that no engine ran, so the call is one of zlib's own
// Z_BUF_ERRORs.
static bool RunIGZIPDeflate(z_streamp strm,
const std::shared_ptr<DeflateSettings>& settings,
int flush, uint32_t* input_len,
uint32_t* output_len, int* ret,
bool* call_refused) {
if (settings->isal_strm == nullptr) {
settings->isal_strm =
InitCompressIGZIP(settings->level, settings->window_bits);
}
if (settings->isal_strm == nullptr) {
return false;
}
if (strm->avail_out == 0) {
// zlib refuses a call with nowhere to write before it looks at the flush
// value at all, so the flush is not recorded: the caller was denied it, and
// a later call asking for the same one still has work to do. Letting ISA-L
// run instead would consume input on a call zlib leaves the caller holding.
*input_len = 0;
*output_len = 0;
*ret = 0;
*call_refused = true;
} else {
// zlib records the flush of every call it does look at, including one it
// goes on to refuse -- a refused Z_PARTIAL_FLUSH lowers last_flush, so a
// following Z_SYNC_FLUSH outranks it and does work. Record it the same way,
// before the decision below reads the previous value.
const int previous_flush = settings->last_flush;
settings->last_flush = flush;
if (IsRedundantEmptyFlush(strm->avail_in, flush, previous_flush)) {
// Answer as zlib does, without letting ISA-L emit another marker. A flush
// ISA-L has not finished writing is not refused here: running out of
// output space is the only reason it stops mid-flush, and that already
// put last_flush at -1, which every flush outranks.
*input_len = 0;
*output_len = 0;
*ret = 0;
*call_refused = true;
} else {
in_call = true;
*ret = CompressIGZIP(settings->isal_strm, flush, strm->next_in, input_len,
strm->next_out, output_len, &strm->total_in,
&strm->total_out);
in_call = false;
}
}
SetDeflatePath(settings, IGZIP);
INCREMENT_STAT(DEFLATE_IGZIP_COUNT);
INCREMENT_STAT_COND(*ret != 0, DEFLATE_IGZIP_ERROR_COUNT);
return true;
}
#endif // USE_IGZIP
// Z_BLOCK and Z_TREES ask inflate() to stop early -- at the next deflate block
// boundary, and additionally at the end of each block header -- and to report
// the bit position reached in z_stream.data_type. No backend can do either.
// QAT and IAA decompress whole streams in one submission with no notion of a
// block boundary, and ISA-L transits ISAL_BLOCK_NEW_HDR/ISAL_BLOCK_HDR inside
// a single isal_inflate() call with no way to stop there. Left offloaded, such
// a call over-delivers -- it returns the whole stream instead of one block and
// leaves data_type untouched -- so the output is a correct prefix but the bit
// accounting the caller asked for is silently missing. Applications pass these
// values to append to, splice, or randomly access deflate streams, i.e. the
// accounting *is* the request. zlib is the only implementation here that can
// honor it, so route the stream there.
static bool IsOffloadableInflateFlush(int flush) {
return flush != Z_BLOCK && flush != Z_TREES;
}
int ZEXPORT deflateInit_(z_streamp strm, int level, const char* version,
int stream_size) {
Log(LogLevel::LOG_INFO, "deflateInit_ Line ", __LINE__, ", strm ",
static_cast<void*>(strm), ", level ", level, "\n");
// The shim has no deflate implementation of its own, so a missing symbol is
// unrecoverable for this entry point. Report it the way zlib reports an
// unusable library and register nothing, which keeps deflate() off this
// stream.
if (orig_deflateInit_ == nullptr) {
return Z_VERSION_ERROR;
}
// Register only once zlib has accepted the stream. On failure the app never
// calls deflateEnd, so an entry made here would outlive the z_streamp; and
// zlib leaves an already-initialized stream untouched when it rejects new
// parameters, so the previous settings must stay in place.
int ret = orig_deflateInit_(strm, level, version, stream_size);
if (ret == Z_OK) {
deflate_stream_settings.Set(strm, level, Z_DEFLATED, kWindowBitsZlib, 8,
Z_DEFAULT_STRATEGY);
}
return ret;
}
int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
int window_bits, int mem_level, int strategy,
const char* version, int stream_size) {
Log(LogLevel::LOG_INFO, "deflateInit2_ Line ", __LINE__, ", strm ",
static_cast<void*>(strm), ", level ", level, ", window_bits ",
window_bits, " \n");
if (orig_deflateInit2_ == nullptr) {
return Z_VERSION_ERROR;
}
int ret = orig_deflateInit2_(strm, level, method, window_bits, mem_level,
strategy, version, stream_size);
if (ret == Z_OK) {
deflate_stream_settings.Set(strm, level, method, window_bits, mem_level,
strategy);
}
return ret;
}
int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef* dictionary,
uInt dictLength) {
if (!configs[IGNORE_ZLIB_DICTIONARY]) {
Log(LogLevel::LOG_INFO, "deflateSetDictionary Line ", __LINE__, ", strm ",
static_cast<void*>(strm), ", dictLength ", dictLength, "\n");
auto deflate_settings = deflate_stream_settings.Get(strm);
// Reject mid-stream: if an accelerator is active, the underlying zlib
// stream has not been advanced, so orig_deflateSetDictionary would
// incorrectly accept the call. Per zlib spec, dictionary must be set before
// compression begins.
if (deflate_settings != nullptr && deflate_settings->path != UNDEFINED &&
deflate_settings->path != ZLIB) {
return Z_STREAM_ERROR;
}
if (orig_deflateSetDictionary == nullptr) {
return Z_VERSION_ERROR;
}
const int ret = orig_deflateSetDictionary(strm, dictionary, dictLength);
if (ret == Z_OK) {
SetDeflatePath(deflate_settings, ZLIB);
}
return ret;
}
Log(LogLevel::LOG_INFO, "deflateSetDictionary Line ", __LINE__,
" ignored because ignore_zlib_dictionary is set to ",
configs[IGNORE_ZLIB_DICTIONARY], "\n");
return Z_OK;
}