Debian Codegraph @

zstd/blockdec.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2019+ Klaus Post. All rights reserved.
2 // License information can be found in the LICENSE file.
3 // Based on work by Yann Collet, released under BSD License.
4
5 package zstd
6
7 import (
8 "errors"
9 "fmt"
10 "hash/crc32"
11 "io"
12 "sync"
13
14 "github.com/klauspost/compress/huff0"
•15 "github.com/cespare/xxhash/v2"
16 )
17
18 type blockType uint8
19
20 //go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex
21
22 const (
23 blockTypeRaw blockType = iota
24 blockTypeRLE
25 blockTypeCompressed
26 blockTypeReserved
27 )
28
29 type literalsBlockType uint8
30
31 const (
32 literalsBlockRaw literalsBlockType = iota
33 literalsBlockRLE
34 literalsBlockCompressed
35 literalsBlockTreeless
36 )
37
38 const (
39 // maxCompressedBlockSize is the biggest allowed compressed block size (128KB)
40 maxCompressedBlockSize = 128 << 10
41
42 compressedBlockOverAlloc = 16
43 maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc
44
45 // Maximum possible block size (all Raw+Uncompressed).
46 maxBlockSize = (1 << 21) - 1
47
48 maxMatchLen = 131074
49 maxSequences = 0x7f00 + 0xffff
50
51 // We support slightly less than the reference decoder to be able to
52 // use ints on 32 bit archs.
53 maxOffsetBits = 30
54 )
55
56 var (
57 huffDecoderPool = sync.Pool{New: func() any {
58 return &huff0.Scratch{}
59 }}
60
61 fseDecoderPool = sync.Pool{New: func() any {
62 return &fseDecoder{}
63 }}
64 )
65
66 type blockDec struct {
67 // Raw source data of the block.
68 data []byte
69 dataStorage []byte
70
71 // Destination of the decoded data.
72 dst []byte
73
74 // Buffer for literals data.
75 literalBuf []byte
76
77 // Window size of the block.
78 WindowSize uint64
79
80 err error
81
82 // Check against this crc, if hasCRC is true.
83 checkCRC uint32
84 hasCRC bool
85
86 // Frame to use for singlethreaded decoding.
87 // Should not be used by the decoder itself since parent may be another frame.
88 localFrame *frameDec
89
90 sequence []seqVals
91
92 async struct {
93 newHist *history
94 literals []byte
95 seqData []byte
96 seqSize int // Size of uncompressed sequences
97 fcs uint64
98 }
99
100 // Block is RLE, this is the size.
101 RLESize uint32
102
103 Type blockType
104
105 // Is this the last block of a frame?
106 Last bool
107
108 // Use less memory
109 lowMem bool
110 }
111
112 func (b *blockDec) String() string {
113 if b == nil {
114 return "<nil>"
115 }
116 return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(b.data), b.Type, b.Last, b.WindowSize)
117 }
118
119 func newBlockDec(lowMem bool) *blockDec {
120 b := blockDec{
121 lowMem: lowMem,
122 }
123 return &b
124 }
125
126 // reset will reset the block.
127 // Input must be a start of a block and will be at the end of the block when returned.
128 func (b *blockDec) reset(br byteBuffer, windowSize uint64) error {
129 b.WindowSize = windowSize
130 tmp, err := br.readSmall(3)
131 if err != nil {
132 println("Reading block header:", err)
133 return err
134 }
135 bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16)
136 b.Last = bh&1 != 0
137 b.Type = blockType((bh >> 1) & 3)
138 // find size.
139 cSize := int(bh >> 3)
140 maxSize := maxCompressedBlockSizeAlloc
141 switch b.Type {
142 case blockTypeReserved:
143 return ErrReservedBlockType
144 case blockTypeRLE:
145 if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) {
146 if debugDecoder {
147 printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b)
148 }
149 return ErrWindowSizeExceeded
150 }
151 b.RLESize = uint32(cSize)
152 if b.lowMem {
153 maxSize = cSize
154 }
155 cSize = 1
156 case blockTypeCompressed:
157 if debugDecoder {
158 println("Data size on stream:", cSize)
159 }
160 b.RLESize = 0
161 maxSize = maxCompressedBlockSizeAlloc
162 if windowSize < maxCompressedBlockSize && b.lowMem {
163 maxSize = int(windowSize) + compressedBlockOverAlloc
164 }
165 if cSize > maxCompressedBlockSize || uint64(cSize) > b.WindowSize {
166 if debugDecoder {
167 printf("compressed block too big: csize:%d block: %+v\n", uint64(cSize), b)
168 }
169 return ErrCompressedSizeTooBig
170 }
171 // Empty compressed blocks must at least be 2 bytes
172 // for Literals_Block_Type and one for Sequences_Section_Header.
173 if cSize < 2 {
174 return ErrBlockTooSmall
175 }
176 case blockTypeRaw:
177 if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) {
178 if debugDecoder {
179 printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b)
180 }
181 return ErrWindowSizeExceeded
182 }
183
184 b.RLESize = 0
185 // We do not need a destination for raw blocks.
186 maxSize = -1
187 default:
188 panic("Invalid block type")
189 }
190
191 // Read block data.
192 if _, ok := br.(*byteBuf); !ok && cap(b.dataStorage) < cSize {
193 // byteBuf doesn't need a destination buffer.
194 if b.lowMem || cSize > maxCompressedBlockSize {
195 b.dataStorage = make([]byte, 0, cSize+compressedBlockOverAlloc)
196 } else {
197 b.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc)
198 }
199 }
200 b.data, err = br.readBig(cSize, b.dataStorage)
201 if err != nil {
202 if debugDecoder {
203 println("Reading block:", err, "(", cSize, ")", len(b.data))
204 printf("%T", br)
205 }
206 return err
207 }
208 if cap(b.dst) <= maxSize {
209 b.dst = make([]byte, 0, maxSize+1)
210 }
211 return nil
212 }
213
214 // sendEOF will make the decoder send EOF on this frame.
215 func (b *blockDec) sendErr(err error) {
216 b.Last = true
217 b.Type = blockTypeReserved
218 b.err = err
219 }
220
221 // Close will release resources.
222 // Closed blockDec cannot be reset.
223 func (b *blockDec) Close() {
224 }
225
226 // decodeBuf
227 func (b *blockDec) decodeBuf(hist *history) error {
228 switch b.Type {
229 case blockTypeRLE:
230 if cap(b.dst) < int(b.RLESize) {
231 if b.lowMem {
232 b.dst = make([]byte, b.RLESize)
233 } else {
234 b.dst = make([]byte, maxCompressedBlockSize)
235 }
236 }
237 b.dst = b.dst[:b.RLESize]
238 v := b.data[0]
239 for i := range b.dst {
240 b.dst[i] = v
241 }
242 hist.appendKeep(b.dst)
243 return nil
244 case blockTypeRaw:
245 hist.appendKeep(b.data)
246 return nil
247 case blockTypeCompressed:
248 saved := b.dst
249 // Append directly to history
250 if hist.ignoreBuffer == 0 {
251 b.dst = hist.b
252 hist.b = nil
253 } else {
254 b.dst = b.dst[:0]
255 }
256 err := b.decodeCompressed(hist)
257 if debugDecoder {
258 println("Decompressed to total", len(b.dst), "bytes, hash:", xxhash.Sum64(b.dst), "error:", err)
259 }
260 if hist.ignoreBuffer == 0 {
261 hist.b = b.dst
262 b.dst = saved
263 } else {
264 hist.appendKeep(b.dst)
265 }
266 return err
267 case blockTypeReserved:
268 // Used for returning errors.
269 return b.err
270 default:
271 panic("Invalid block type")
272 }
273 }
274
275 func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err error) {
276 // There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header
277 if len(in) < 2 {
278 return in, ErrBlockTooSmall
279 }
280
281 litType := literalsBlockType(in[0] & 3)
282 var litRegenSize int
283 var litCompSize int
284 sizeFormat := (in[0] >> 2) & 3
285 var fourStreams bool
286 var literals []byte
287 switch litType {
288 case literalsBlockRaw, literalsBlockRLE:
289 switch sizeFormat {
290 case 0, 2:
291 // Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte.
292 litRegenSize = int(in[0] >> 3)
293 in = in[1:]
294 case 1:
295 // Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes.
296 litRegenSize = int(in[0]>>4) + (int(in[1]) << 4)
297 in = in[2:]
298 case 3:
299 // Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes.
300 if len(in) < 3 {
301 println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
302 return in, ErrBlockTooSmall
303 }
304 litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + (int(in[2]) << 12)
305 in = in[3:]
306 }
307 case literalsBlockCompressed, literalsBlockTreeless:
308 switch sizeFormat {
309 case 0, 1:
310 // Both Regenerated_Size and Compressed_Size use 10 bits (0-1023).
311 if len(in) < 3 {
312 println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
313 return in, ErrBlockTooSmall
314 }
315 n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12)
316 litRegenSize = int(n & 1023)
317 litCompSize = int(n >> 10)
318 fourStreams = sizeFormat == 1
319 in = in[3:]
320 case 2:
321 fourStreams = true
322 if len(in) < 4 {
323 println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
324 return in, ErrBlockTooSmall
325 }
326 n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20)
327 litRegenSize = int(n & 16383)
328 litCompSize = int(n >> 14)
329 in = in[4:]
330 case 3:
331 fourStreams = true
332 if len(in) < 5 {
333 println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
334 return in, ErrBlockTooSmall
335 }
336 n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + (uint64(in[4]) << 28)
337 litRegenSize = int(n & 262143)
338 litCompSize = int(n >> 18)
339 in = in[5:]
340 }
341 }
342 if debugDecoder {
343 println("literals type:", litType, "litRegenSize:", litRegenSize, "litCompSize:", litCompSize, "sizeFormat:", sizeFormat, "4X:", fourStreams)
344 }
345 if litRegenSize > int(b.WindowSize) || litRegenSize > maxCompressedBlockSize {
346 return in, ErrWindowSizeExceeded
347 }
348
349 switch litType {
350 case literalsBlockRaw:
351 if len(in) < litRegenSize {
352 println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litRegenSize)
353 return in, ErrBlockTooSmall
354 }
355 literals = in[:litRegenSize]
356 in = in[litRegenSize:]
357 //printf("Found %d uncompressed literals\n", litRegenSize)
358 case literalsBlockRLE:
359 if len(in) < 1 {
360 println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", 1)
361 return in, ErrBlockTooSmall
362 }
363 if cap(b.literalBuf) < litRegenSize {
364 if b.lowMem {
365 b.literalBuf = make([]byte, litRegenSize, litRegenSize+compressedBlockOverAlloc)
366 } else {
367 b.literalBuf = make([]byte, litRegenSize, maxCompressedBlockSize+compressedBlockOverAlloc)
368 }
369 }
370 literals = b.literalBuf[:litRegenSize]
371 v := in[0]
372 for i := range literals {
373 literals[i] = v
374 }
375 in = in[1:]
376 if debugDecoder {
377 printf("Found %d RLE compressed literals\n", litRegenSize)
378 }
379 case literalsBlockTreeless:
380 if len(in) < litCompSize {
381 println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize)
382 return in, ErrBlockTooSmall
383 }
384 // Store compressed literals, so we defer decoding until we get history.
385 literals = in[:litCompSize]
386 in = in[litCompSize:]
387 if debugDecoder {
388 printf("Found %d compressed literals\n", litCompSize)
389 }
390 huff := hist.huffTree
391 if huff == nil {
392 return in, errors.New("literal block was treeless, but no history was defined")
393 }
394 // Ensure we have space to store it.
395 if cap(b.literalBuf) < litRegenSize {
396 if b.lowMem {
397 b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc)
398 } else {
399 b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
400 }
401 }
402 var err error
403 // Decoder.Decompress* uses cap(dst) for the size limit. Do not write
404 // MaxDecodedSize on hist.huffTree: with a trained dictionary that
405 // pointer aliases the shared dict.litEnc and concurrent DecodeAll races.
406 if fourStreams {
407 literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals)
408 } else {
409 literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals)
410 }
411 // Make sure we don't leak our literals buffer
412 if err != nil {
413 println("decompressing literals:", err)
414 return in, err
415 }
416 if len(literals) != litRegenSize {
417 return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals))
418 }
419
420 case literalsBlockCompressed:
421 if len(in) < litCompSize {
422 println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize)
423 return in, ErrBlockTooSmall
424 }
425 literals = in[:litCompSize]
426 in = in[litCompSize:]
427 // Ensure we have space to store it.
428 if cap(b.literalBuf) < litRegenSize {
429 if b.lowMem {
430 b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc)
431 } else {
432 b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
433 }
434 }
435 huff := hist.huffTree
436 if huff == nil || (hist.dict != nil && huff == hist.dict.litEnc) {
437 huff = huffDecoderPool.Get().(*huff0.Scratch)
438 if huff == nil {
439 huff = &huff0.Scratch{}
440 }
441 }
442 var err error
443 if debugDecoder {
444 println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals))
445 }
446 huff, literals, err = huff0.ReadTable(literals, huff)
447 if err != nil {
448 println("reading huffman table:", err)
449 return in, err
450 }
451 hist.huffTree = huff
452 huff.MaxDecodedSize = litRegenSize
453 // Use our out buffer.
454 if fourStreams {
455 literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals)
456 } else {
457 literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals)
458 }
459 if err != nil {
460 println("decoding compressed literals:", err)
461 return in, err
462 }
463 // Make sure we don't leak our literals buffer
464 if len(literals) != litRegenSize {
465 return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals))
466 }
467 // Re-cap to get extra size.
468 literals = b.literalBuf[:len(literals)]
469 if debugDecoder {
470 printf("Decompressed %d literals into %d bytes\n", litCompSize, litRegenSize)
471 }
472 }
473 hist.decoders.literals = literals
474 return in, nil
475 }
476
477 // decodeCompressed will start decompressing a block.
478 func (b *blockDec) decodeCompressed(hist *history) error {
479 in := b.data
480 in, err := b.decodeLiterals(in, hist)
481 if err != nil {
482 return err
483 }
484 err = b.prepareSequences(in, hist)
485 if err != nil {
486 return err
487 }
488 if hist.decoders.nSeqs == 0 {
489 b.dst = append(b.dst, hist.decoders.literals...)
490 return nil
491 }
492 before := len(hist.decoders.out)
493 err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:])
494 if err != nil {
495 return err
496 }
497 if hist.decoders.maxSyncLen > 0 {
498 hist.decoders.maxSyncLen += uint64(before)
499 hist.decoders.maxSyncLen -= uint64(len(hist.decoders.out))
500 }
501 b.dst = hist.decoders.out
502 hist.recentOffsets = hist.decoders.prevOffset
503 return nil
504 }
505
506 func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) {
507 if debugDecoder {
508 printf("prepareSequences: %d byte(s) input\n", len(in))
509 }
510 // Decode Sequences
511 // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section
512 if len(in) < 1 {
513 return ErrBlockTooSmall
514 }
515 var nSeqs int
516 seqHeader := in[0]
517 switch {
518 case seqHeader < 128:
519 nSeqs = int(seqHeader)
520 in = in[1:]
521 case seqHeader < 255:
522 if len(in) < 2 {
523 return ErrBlockTooSmall
524 }
525 nSeqs = int(seqHeader-128)<<8 | int(in[1])
526 in = in[2:]
527 case seqHeader == 255:
528 if len(in) < 3 {
529 return ErrBlockTooSmall
530 }
531 nSeqs = 0x7f00 + int(in[1]) + (int(in[2]) << 8)
532 in = in[3:]
533 }
534 if nSeqs == 0 && len(in) != 0 {
535 // When no sequences, there should not be any more data...
536 if debugDecoder {
537 printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len(in))
538 }
539 return ErrUnexpectedBlockSize
540 }
541
542 var seqs = &hist.decoders
543 seqs.nSeqs = nSeqs
544 if nSeqs > 0 {
545 if len(in) < 1 {
546 return ErrBlockTooSmall
547 }
548 br := byteReader{b: in, off: 0}
549 compMode := br.Uint8()
550 br.advance(1)
551 if debugDecoder {
552 printf("Compression modes: 0b%b", compMode)
553 }
554 if compMode&3 != 0 {
555 return errors.New("corrupt block: reserved bits not zero")
556 }
557 for i := range uint(3) {
558 mode := seqCompMode((compMode >> (6 - i*2)) & 3)
559 if debugDecoder {
560 println("Table", tableIndex(i), "is", mode)
561 }
562 var seq *sequenceDec
563 switch tableIndex(i) {
564 case tableLiteralLengths:
565 seq = &seqs.litLengths
566 case tableOffsets:
567 seq = &seqs.offsets
568 case tableMatchLengths:
569 seq = &seqs.matchLengths
570 default:
571 panic("unknown table")
572 }
573 switch mode {
574 case compModePredefined:
575 if seq.fse != nil && !seq.fse.preDefined {
576 fseDecoderPool.Put(seq.fse)
577 }
578 seq.fse = &fsePredef[i]
579 case compModeRLE:
580 if br.remain() < 1 {
581 return ErrBlockTooSmall
582 }
583 v := br.Uint8()
584 br.advance(1)
585 if seq.fse == nil || seq.fse.preDefined {
586 seq.fse = fseDecoderPool.Get().(*fseDecoder)
587 }
588 symb, err := decSymbolValue(v, symbolTableX[i])
589 if err != nil {
590 printf("RLE Transform table (%v) error: %v", tableIndex(i), err)
591 return err
592 }
593 seq.fse.setRLE(symb)
594 if debugDecoder {
595 printf("RLE set to 0x%x, code: %v", symb, v)
596 }
597 case compModeFSE:
598 if debugDecoder {
599 println("Reading table for", tableIndex(i))
600 }
601 if seq.fse == nil || seq.fse.preDefined {
602 seq.fse = fseDecoderPool.Get().(*fseDecoder)
603 }
604 err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i]))
605 if err != nil {
606 println("Read table error:", err)
607 return err
608 }
609 err = seq.fse.transform(symbolTableX[i])
610 if err != nil {
611 println("Transform table error:", err)
612 return err
613 }
614 if debugDecoder {
615 println("Read table ok", "symbolLen:", seq.fse.symbolLen)
616 }
617 case compModeRepeat:
618 seq.repeat = true
619 }
620 if br.overread() {
621 return io.ErrUnexpectedEOF
622 }
623 }
624 in = br.unread()
625 }
626 if debugDecoder {
627 println("Literals:", len(seqs.literals), "hash:", xxhash.Sum64(seqs.literals), "and", seqs.nSeqs, "sequences.")
628 }
629
630 if nSeqs == 0 {
631 if len(b.sequence) > 0 {
632 b.sequence = b.sequence[:0]
633 }
634 return nil
635 }
636 br := seqs.br
637 if br == nil {
638 br = &bitReader{}
639 }
640 if err := br.init(in); err != nil {
641 return err
642 }
643
644 if err := seqs.initialize(br, hist, b.dst); err != nil {
645 println("initializing sequences:", err)
646 return err
647 }
648
649 return nil
650 }
651
652 func (b *blockDec) decodeSequences(hist *history) error {
653 if cap(b.sequence) < hist.decoders.nSeqs {
654 if b.lowMem {
655 b.sequence = make([]seqVals, 0, hist.decoders.nSeqs)
656 } else {
657 b.sequence = make([]seqVals, 0, 0x7F00+0xffff)
658 }
659 }
660 b.sequence = b.sequence[:hist.decoders.nSeqs]
661 if hist.decoders.nSeqs == 0 {
662 hist.decoders.seqSize = len(hist.decoders.literals)
663 return nil
664 }
665 hist.decoders.windowSize = hist.windowSize
666 hist.decoders.prevOffset = hist.recentOffsets
667
668 err := hist.decoders.decode(b.sequence)
669 hist.recentOffsets = hist.decoders.prevOffset
670 return err
671 }
672
673 func (b *blockDec) executeSequences(hist *history) error {
674 hbytes := hist.b
675 if len(hbytes) > hist.windowSize {
676 hbytes = hbytes[len(hbytes)-hist.windowSize:]
677 }
678 hist.decoders.windowSize = hist.windowSize
679 hist.decoders.out = b.dst[:0]
680 err := hist.decoders.execute(b.sequence, hbytes)
681 if err != nil {
682 return err
683 }
684 return b.updateHistory(hist)
685 }
686
687 func (b *blockDec) updateHistory(hist *history) error {
688 if len(b.data) > maxCompressedBlockSize {
689 return fmt.Errorf("compressed block size too large (%d)", len(b.data))
690 }
691 // Set output and release references.
692 b.dst = hist.decoders.out
693 hist.recentOffsets = hist.decoders.prevOffset
694
695 if b.Last {
696 // if last block we don't care about history.
697 println("Last block, no history returned")
698 hist.b = hist.b[:0]
699 return nil
700 } else {
701 hist.append(b.dst)
702 if debugDecoder {
703 println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b))
704 }
705 }
706 hist.decoders.out, hist.decoders.literals = nil, nil
707
708 return nil
709 }