Coverage Report

Created: 2026-12-01 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/contrib/seekable_format/zstdseek_decompress.c
Line
Count
Source
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
/* *********************************************************
12
*  Turn on Large Files support (>4GB) for 32-bit Linux/Unix
13
***********************************************************/
14
#if !defined(__64BIT__) || defined(__MINGW32__)       /* No point defining Large file for 64 bit but MinGW-w64 requires it */
15
#  if !defined(_FILE_OFFSET_BITS)
16
#    define _FILE_OFFSET_BITS 64                      /* turn off_t into a 64-bit type for ftello, fseeko */
17
#  endif
18
#  if !defined(_LARGEFILE_SOURCE)                     /* obsolete macro, replaced with _FILE_OFFSET_BITS */
19
#    define _LARGEFILE_SOURCE 1                       /* Large File Support extension (LFS) - fseeko, ftello */
20
#  endif
21
#  if defined(_AIX) || defined(__hpux)
22
#    define _LARGE_FILES                              /* Large file support on 32-bits AIX and HP-UX */
23
#  endif
24
#endif
25
26
/* ************************************************************
27
*  Detect POSIX version
28
*  PLATFORM_POSIX_VERSION = 0 for non-Unix e.g. Windows
29
*  PLATFORM_POSIX_VERSION = 1 for Unix-like but non-POSIX
30
*  PLATFORM_POSIX_VERSION > 1 is equal to found _POSIX_VERSION
31
*  Value of PLATFORM_POSIX_VERSION can be forced on command line
32
***************************************************************/
33
#ifndef PLATFORM_POSIX_VERSION
34
35
#  if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1-2001 (SUSv3) conformant */ \
36
     || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)  /* BSD distros */
37
     /* exception rule : force posix version to 200112L,
38
      * note: it's better to use unistd.h's _POSIX_VERSION whenever possible */
39
#    define PLATFORM_POSIX_VERSION 200112L
40
41
/* try to determine posix version through official unistd.h's _POSIX_VERSION (https://pubs.opengroup.org/onlinepubs/7908799/xsh/unistd.h.html).
42
 * note : there is no simple way to know in advance if <unistd.h> is present or not on target system,
43
 * Posix specification mandates its presence and its content, but target system must respect this spec.
44
 * It's necessary to _not_ #include <unistd.h> whenever target OS is not unix-like
45
 * otherwise it will block preprocessing stage.
46
 * The following list of build macros tries to "guess" if target OS is likely unix-like, and therefore can #include <unistd.h>
47
 */
48
#  elif !defined(_WIN32) \
49
     && ( defined(__unix__) || defined(__unix) \
50
       || defined(__midipix__) || defined(__VMS) || defined(__HAIKU__) )
51
52
#    if defined(__linux__) || defined(__linux) || defined(__CYGWIN__)
53
#      ifndef _POSIX_C_SOURCE
54
#        define _POSIX_C_SOURCE 200809L  /* feature test macro : https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html */
55
#      endif
56
#    endif
57
#    include <unistd.h>  /* declares _POSIX_VERSION */
58
#    if defined(_POSIX_VERSION)  /* POSIX compliant */
59
#      define PLATFORM_POSIX_VERSION _POSIX_VERSION
60
#    else
61
#      define PLATFORM_POSIX_VERSION 1
62
#    endif
63
64
#    ifdef __UCLIBC__
65
#     ifndef __USE_MISC
66
#      define __USE_MISC /* enable st_mtim on uclibc */
67
#     endif
68
#    endif
69
70
#  else  /* non-unix target platform (like Windows) */
71
#    define PLATFORM_POSIX_VERSION 0
72
#  endif
73
74
#endif   /* PLATFORM_POSIX_VERSION */
75
76
77
/* ************************************************************
78
* Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
79
***************************************************************/
80
#if defined(LIBC_NO_FSEEKO)
81
/* Some older libc implementations don't include these functions (e.g. Bionic < 24) */
82
#   define LONG_SEEK fseek
83
#elif defined(_MSC_VER) && _MSC_VER >= 1400
84
#   define LONG_SEEK _fseeki64
85
#elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
86
0
#   define LONG_SEEK fseeko
87
#elif defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)
88
#   define LONG_SEEK fseeko64
89
#elif defined(_WIN32) && !defined(__DJGPP__)
90
#   include <windows.h>
91
    static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
92
        LARGE_INTEGER off;
93
        DWORD method;
94
        off.QuadPart = offset;
95
        if (origin == SEEK_END)
96
            method = FILE_END;
97
        else if (origin == SEEK_CUR)
98
            method = FILE_CURRENT;
99
        else
100
            method = FILE_BEGIN;
101
102
        if (SetFilePointerEx((HANDLE) _get_osfhandle(_fileno(file)), off, NULL, method))
103
            return 0;
104
        else
105
            return -1;
106
    }
107
#else
108
#   define LONG_SEEK fseek
109
#endif
110
111
#include <stdlib.h>  /* malloc, free */
112
#include <stdio.h>   /* FILE* */
113
#include <limits.h>  /* UNIT_MAX */
114
#include <assert.h>
115
116
#define XXH_STATIC_LINKING_ONLY
117
#include "xxhash.h"
118
119
#define ZSTD_STATIC_LINKING_ONLY
120
#include "zstd.h"
121
#include "zstd_errors.h"
122
#include "mem.h"
123
#include "zstd_seekable.h"
124
125
#undef ERROR
126
0
#define ERROR(name) ((size_t)-ZSTD_error_##name)
127
128
0
#define CHECK_IO(f) { int const errcod = (f); if (errcod < 0) return ERROR(seekableIO); }
129
130
#undef MIN
131
#undef MAX
132
0
#define MIN(a, b) ((a) < (b) ? (a) : (b))
133
#define MAX(a, b) ((a) > (b) ? (a) : (b))
134
135
0
#define ZSTD_SEEKABLE_NO_OUTPUT_PROGRESS_MAX 16
136
137
/* Special-case callbacks for FILE* and in-memory modes, so that we can treat
138
 * them the same way as the advanced API */
139
static int ZSTD_seekable_read_FILE(void* opaque, void* buffer, size_t n)
140
0
{
141
0
    size_t const result = fread(buffer, 1, n, (FILE*)opaque);
142
0
    if (result != n) {
143
0
        return -1;
144
0
    }
145
0
    return 0;
146
0
}
147
148
static int ZSTD_seekable_seek_FILE(void* opaque, long long offset, int origin)
149
0
{
150
0
    int const ret = LONG_SEEK((FILE*)opaque, offset, origin);
151
0
    if (ret) return ret;
152
0
    return fflush((FILE*)opaque);
153
0
}
154
155
typedef struct {
156
    const void *ptr;
157
    size_t size;
158
    size_t pos;
159
} buffWrapper_t;
160
161
static int ZSTD_seekable_read_buff(void* opaque, void* buffer, size_t n)
162
0
{
163
0
    buffWrapper_t* const buff = (buffWrapper_t*)opaque;
164
0
    assert(buff != NULL);
165
0
    if (buff->pos + n > buff->size) return -1;
166
0
    memcpy(buffer, (const BYTE*)buff->ptr + buff->pos, n);
167
0
    buff->pos += n;
168
0
    return 0;
169
0
}
170
171
static int ZSTD_seekable_seek_buff(void* opaque, long long offset, int origin)
172
0
{
173
0
    buffWrapper_t* const buff = (buffWrapper_t*) opaque;
174
0
    unsigned long long newOffset;
175
0
    assert(buff != NULL);
176
0
    switch (origin) {
177
0
    case SEEK_SET:
178
0
        assert(offset >= 0);
179
0
        newOffset = (unsigned long long)offset;
180
0
        break;
181
0
    case SEEK_CUR:
182
0
        newOffset = (unsigned long long)((long long)buff->pos + offset);
183
0
        break;
184
0
    case SEEK_END:
185
0
        newOffset = (unsigned long long)((long long)buff->size + offset);
186
0
        break;
187
0
    default:
188
0
        assert(0);  /* not possible */
189
0
        return -1;
190
0
    }
191
0
    if (newOffset > buff->size) {
192
0
        return -1;
193
0
    }
194
0
    buff->pos = newOffset;
195
0
    return 0;
196
0
}
197
198
typedef struct {
199
    U64 cOffset;
200
    U64 dOffset;
201
    U32 checksum;
202
} seekEntry_t;
203
204
struct ZSTD_seekTable_s {
205
    seekEntry_t* entries;
206
    size_t tableLen;
207
208
    int checksumFlag;
209
};
210
211
0
#define SEEKABLE_BUFF_SIZE ZSTD_BLOCKSIZE_MAX
212
213
struct ZSTD_seekable_s {
214
    ZSTD_DStream* dstream;
215
    ZSTD_seekTable seekTable;
216
    ZSTD_seekable_customFile src;
217
218
    U64 decompressedOffset;
219
    /* (U32)-1 means no frame is ready for decompression. Otherwise this is
220
     * the current frame index. Set to -1 before seeking, so a failed seek
221
     * forces the next call to retry setup. Set to targetFrame only after
222
     * the seek succeeds and the decompression state is initialized. */
223
    U32 curFrame;
224
225
    BYTE inBuff[SEEKABLE_BUFF_SIZE]; /* need to do our own input buffering */
226
    BYTE outBuff[SEEKABLE_BUFF_SIZE]; /* so we can efficiently decompress the
227
                                         starts of chunks before we get to the
228
                                         desired section */
229
    ZSTD_inBuffer in; /* maintain continuity across ZSTD_seekable_decompress operations */
230
    buffWrapper_t buffWrapper; /* for `src.opaque` in in-memory mode */
231
232
    XXH64_state_t xxhState;
233
};
234
235
ZSTD_seekable* ZSTD_seekable_create(void)
236
0
{
237
0
    ZSTD_seekable* const zs = (ZSTD_seekable*)malloc(sizeof(ZSTD_seekable));
238
0
    if (zs == NULL) return NULL;
239
240
    /* also initializes stage to zsds_init */
241
0
    memset(zs, 0, sizeof(*zs));
242
243
0
    zs->dstream = ZSTD_createDStream();
244
0
    if (zs->dstream == NULL) {
245
0
        free(zs);
246
0
        return NULL;
247
0
    }
248
249
0
    return zs;
250
0
}
251
252
size_t ZSTD_seekable_free(ZSTD_seekable* zs)
253
0
{
254
0
    if (zs == NULL) return 0; /* support free on null */
255
0
    ZSTD_freeDStream(zs->dstream);
256
0
    free(zs->seekTable.entries);
257
0
    free(zs);
258
0
    return 0;
259
0
}
260
261
ZSTD_seekTable* ZSTD_seekTable_create_fromSeekable(const ZSTD_seekable* zs)
262
0
{
263
0
    assert(zs != NULL);
264
0
    if (zs->seekTable.entries == NULL) return NULL;
265
0
    ZSTD_seekTable* const st = (ZSTD_seekTable*)malloc(sizeof(ZSTD_seekTable));
266
0
    if (st==NULL) return NULL;
267
268
0
    st->checksumFlag = zs->seekTable.checksumFlag;
269
0
    st->tableLen = zs->seekTable.tableLen;
270
271
    /* Allocate an extra entry at the end to match logic of initial allocation */
272
0
    size_t const entriesSize = sizeof(seekEntry_t) * (zs->seekTable.tableLen + 1);
273
0
    seekEntry_t* const entries = (seekEntry_t*)malloc(entriesSize);
274
0
    if (entries==NULL) {
275
0
        free(st);
276
0
        return NULL;
277
0
    }
278
279
0
    memcpy(entries, zs->seekTable.entries, entriesSize);
280
0
    st->entries = entries;
281
0
    return st;
282
0
}
283
284
size_t ZSTD_seekTable_free(ZSTD_seekTable* st)
285
0
{
286
0
    if (st == NULL) return 0; /* support free on null */
287
0
    free(st->entries);
288
0
    free(st);
289
0
    return 0;
290
0
}
291
292
/** ZSTD_seekable_offsetToFrameIndex() :
293
 *  Performs a binary search to find the last frame with a decompressed offset
294
 *  <= pos
295
 *  @return : the frame's index */
296
unsigned ZSTD_seekable_offsetToFrameIndex(const ZSTD_seekable* zs, unsigned long long pos)
297
0
{
298
0
    return ZSTD_seekTable_offsetToFrameIndex(&zs->seekTable, pos);
299
0
}
300
301
unsigned ZSTD_seekTable_offsetToFrameIndex(const ZSTD_seekTable* st, unsigned long long pos)
302
0
{
303
0
    U32 lo = 0;
304
0
    U32 hi = (U32)st->tableLen;
305
0
    assert(st->tableLen <= UINT_MAX);
306
307
0
    if (hi == 0 || pos >= st->entries[st->tableLen].dOffset) {
308
0
        return (unsigned)st->tableLen;
309
0
    }
310
311
0
    while (lo + 1 < hi) {
312
0
        U32 const mid = lo + ((hi - lo) >> 1);
313
0
        if (st->entries[mid].dOffset <= pos) {
314
0
            lo = mid;
315
0
        } else {
316
0
            hi = mid;
317
0
        }
318
0
    }
319
0
    return lo;
320
0
}
321
322
unsigned ZSTD_seekable_getNumFrames(const ZSTD_seekable* zs)
323
0
{
324
0
    return ZSTD_seekTable_getNumFrames(&zs->seekTable);
325
0
}
326
327
unsigned ZSTD_seekTable_getNumFrames(const ZSTD_seekTable* st)
328
0
{
329
0
    assert(st->tableLen <= UINT_MAX);
330
0
    return (unsigned)st->tableLen;
331
0
}
332
333
unsigned long long ZSTD_seekable_getFrameCompressedOffset(const ZSTD_seekable* zs, unsigned frameIndex)
334
0
{
335
0
    return ZSTD_seekTable_getFrameCompressedOffset(&zs->seekTable, frameIndex);
336
0
}
337
338
unsigned long long ZSTD_seekTable_getFrameCompressedOffset(const ZSTD_seekTable* st, unsigned frameIndex)
339
0
{
340
0
    if (frameIndex >= st->tableLen) return ZSTD_SEEKABLE_FRAMEINDEX_TOOLARGE;
341
0
    return st->entries[frameIndex].cOffset;
342
0
}
343
344
unsigned long long ZSTD_seekable_getFrameDecompressedOffset(const ZSTD_seekable* zs, unsigned frameIndex)
345
0
{
346
0
    return ZSTD_seekTable_getFrameDecompressedOffset(&zs->seekTable, frameIndex);
347
0
}
348
349
unsigned long long ZSTD_seekTable_getFrameDecompressedOffset(const ZSTD_seekTable* st, unsigned frameIndex)
350
0
{
351
0
    if (frameIndex >= st->tableLen) return ZSTD_SEEKABLE_FRAMEINDEX_TOOLARGE;
352
0
    return st->entries[frameIndex].dOffset;
353
0
}
354
355
size_t ZSTD_seekable_getFrameCompressedSize(const ZSTD_seekable* zs, unsigned frameIndex)
356
0
{
357
0
    return ZSTD_seekTable_getFrameCompressedSize(&zs->seekTable, frameIndex);
358
0
}
359
360
size_t ZSTD_seekTable_getFrameCompressedSize(const ZSTD_seekTable* st, unsigned frameIndex)
361
0
{
362
0
    if (frameIndex >= st->tableLen) return ERROR(frameIndex_tooLarge);
363
0
    return st->entries[frameIndex + 1].cOffset -
364
0
           st->entries[frameIndex].cOffset;
365
0
}
366
367
size_t ZSTD_seekable_getFrameDecompressedSize(const ZSTD_seekable* zs, unsigned frameIndex)
368
0
{
369
0
    return ZSTD_seekTable_getFrameDecompressedSize(&zs->seekTable, frameIndex);
370
0
}
371
372
size_t ZSTD_seekTable_getFrameDecompressedSize(const ZSTD_seekTable* st, unsigned frameIndex)
373
0
{
374
0
    if (frameIndex >= st->tableLen) return ERROR(frameIndex_tooLarge);
375
0
    return st->entries[frameIndex + 1].dOffset -
376
0
           st->entries[frameIndex].dOffset;
377
0
}
378
379
static size_t ZSTD_seekable_loadSeekTable(ZSTD_seekable* zs)
380
0
{
381
0
    int checksumFlag;
382
0
    ZSTD_seekable_customFile src = zs->src;
383
    /* read the footer, fixed size */
384
0
    CHECK_IO(src.seek(src.opaque, -(int)ZSTD_seekTableFooterSize, SEEK_END));
385
0
    CHECK_IO(src.read(src.opaque, zs->inBuff, ZSTD_seekTableFooterSize));
386
387
0
    if (MEM_readLE32(zs->inBuff + 5) != ZSTD_SEEKABLE_MAGICNUMBER) {
388
0
        return ERROR(prefix_unknown);
389
0
    }
390
391
0
    {   BYTE const sfd = zs->inBuff[4];
392
0
        checksumFlag = sfd >> 7;
393
394
        /* check reserved bits */
395
0
        if ((sfd >> 2) & 0x1f) {
396
0
            return ERROR(corruption_detected);
397
0
    }   }
398
399
0
    {   U32 const numFrames = MEM_readLE32(zs->inBuff);
400
0
        U32 const sizePerEntry = 8 + (checksumFlag?4:0);
401
0
        U32 const tableSize = sizePerEntry * numFrames;
402
0
        U32 const frameSize = tableSize + ZSTD_seekTableFooterSize + ZSTD_SKIPPABLEHEADERSIZE;
403
404
0
        U32 remaining = frameSize - ZSTD_seekTableFooterSize; /* don't need to re-read footer */
405
406
        /* numFrames is bounded by the format (the compressor never writes more
407
         * than ZSTD_SEEKABLE_MAXFRAMES). A larger value can only come from a
408
         * corrupt footer and overflows the tableSize/frameSize math above, so
409
         * reject it before those values are used to seek or size the table. */
410
0
        if (numFrames > ZSTD_SEEKABLE_MAXFRAMES) return ERROR(corruption_detected);
411
412
0
        {   U32 const toRead = MIN(remaining, SEEKABLE_BUFF_SIZE);
413
0
            CHECK_IO(src.seek(src.opaque, -(S64)frameSize, SEEK_END));
414
0
            CHECK_IO(src.read(src.opaque, zs->inBuff, toRead));
415
0
            remaining -= toRead;
416
0
        }
417
418
0
        if (MEM_readLE32(zs->inBuff) != (ZSTD_MAGIC_SKIPPABLE_START | 0xE)) {
419
0
            return ERROR(prefix_unknown);
420
0
        }
421
0
        if (MEM_readLE32(zs->inBuff+4) + ZSTD_SKIPPABLEHEADERSIZE != frameSize) {
422
0
            return ERROR(prefix_unknown);
423
0
        }
424
425
0
        {   /* Allocate an extra entry at the end so that we can do size
426
             * computations on the last element without special case */
427
0
            seekEntry_t* const entries = (seekEntry_t*)malloc(sizeof(seekEntry_t) * (numFrames + 1));
428
429
0
            U32 idx = 0;
430
0
            U32 pos = 8;
431
432
0
            U64 cOffset = 0;
433
0
            U64 dOffset = 0;
434
435
0
            if (entries == NULL) return ERROR(memory_allocation);
436
437
            /* compute cumulative positions */
438
0
            for (; idx < numFrames; idx++) {
439
0
                if (pos + sizePerEntry > SEEKABLE_BUFF_SIZE) {
440
0
                    U32 const offset = SEEKABLE_BUFF_SIZE - pos;
441
0
                    U32 const toRead = MIN(remaining, SEEKABLE_BUFF_SIZE - offset);
442
0
                    memmove(zs->inBuff, zs->inBuff + pos, offset); /* move any data we haven't read yet */
443
0
                    if (src.read(src.opaque, zs->inBuff+offset, toRead) < 0) {
444
0
                        free(entries);
445
0
                        return ERROR(seekableIO);
446
0
                    }
447
0
                    remaining -= toRead;
448
0
                    pos = 0;
449
0
                }
450
0
                entries[idx].cOffset = cOffset;
451
0
                entries[idx].dOffset = dOffset;
452
453
0
                cOffset += MEM_readLE32(zs->inBuff + pos);
454
0
                pos += 4;
455
0
                dOffset += MEM_readLE32(zs->inBuff + pos);
456
0
                pos += 4;
457
0
                if (checksumFlag) {
458
0
                    entries[idx].checksum = MEM_readLE32(zs->inBuff + pos);
459
0
                    pos += 4;
460
0
                }
461
0
            }
462
0
            entries[numFrames].cOffset = cOffset;
463
0
            entries[numFrames].dOffset = dOffset;
464
465
0
            zs->seekTable.entries = entries;
466
0
            zs->seekTable.tableLen = numFrames;
467
0
            zs->seekTable.checksumFlag = checksumFlag;
468
0
            return 0;
469
0
        }
470
0
    }
471
0
}
472
473
size_t ZSTD_seekable_initBuff(ZSTD_seekable* zs, const void* src, size_t srcSize)
474
0
{
475
0
    zs->buffWrapper = (buffWrapper_t){src, srcSize, 0};
476
0
    {   ZSTD_seekable_customFile srcFile = {&zs->buffWrapper,
477
0
                                            &ZSTD_seekable_read_buff,
478
0
                                            &ZSTD_seekable_seek_buff};
479
0
        return ZSTD_seekable_initAdvanced(zs, srcFile); }
480
0
}
481
482
size_t ZSTD_seekable_initFile(ZSTD_seekable* zs, FILE* src)
483
0
{
484
0
    ZSTD_seekable_customFile srcFile = {src, &ZSTD_seekable_read_FILE,
485
0
                                        &ZSTD_seekable_seek_FILE};
486
0
    return ZSTD_seekable_initAdvanced(zs, srcFile);
487
0
}
488
489
size_t ZSTD_seekable_initAdvanced(ZSTD_seekable* zs, ZSTD_seekable_customFile src)
490
0
{
491
    /* Reinitialization discards the previous archive, even on failure.
492
     * A NULL entries pointer marks a context that is not initialized. */
493
0
    free(zs->seekTable.entries);
494
0
    zs->seekTable = (ZSTD_seekTable){NULL, 0, 0};
495
0
    zs->decompressedOffset = (U64)-1;
496
0
    zs->curFrame = (U32)-1;
497
    /* Discard buffered input from the previous source, even on failure. */
498
0
    zs->in = (ZSTD_inBuffer){zs->inBuff, 0, 0};
499
0
    zs->src = src;
500
    /* When not reading from a buffer via initBuff() clear the buffWrapper
501
     * to avoid inheriting its state. */
502
0
    if (src.opaque != &zs->buffWrapper) {
503
0
        zs->buffWrapper = (buffWrapper_t){NULL, 0, 0};
504
0
    }
505
506
0
    {   const size_t dstreamInit = ZSTD_initDStream(zs->dstream);
507
0
        if (ZSTD_isError(dstreamInit)) return dstreamInit; }
508
    /* Publish the new seek table only after all initialization has succeeded. */
509
0
    return ZSTD_seekable_loadSeekTable(zs);
510
0
}
511
512
static size_t ZSTD_seekable_decompress_internal(ZSTD_seekable* zs, void* dst, size_t len, unsigned long long offset)
513
0
{
514
0
    if (zs->seekTable.entries == NULL) return ERROR(init_missing);
515
0
    unsigned long long const eos = zs->seekTable.entries[zs->seekTable.tableLen].dOffset;
516
0
    if (offset > eos) return ERROR(parameter_outOfBound);
517
0
    if (len > eos - offset) {
518
0
        len = (size_t)(eos - offset);
519
0
    }
520
521
0
    U32 targetFrame = ZSTD_seekable_offsetToFrameIndex(zs, offset);
522
0
    U32 noOutputProgressCount = 0;
523
0
    size_t srcBytesRead = 0;
524
0
    do {
525
        /* check if we can continue from a previous decompress job */
526
0
        if (targetFrame != zs->curFrame || offset < zs->decompressedOffset) {
527
            /* A failed seek must force the next call to reset the stream,
528
             * rather than reuse uninitialized or stale input state. */
529
0
            zs->curFrame = (U32)-1;
530
531
0
            assert(zs->seekTable.entries[targetFrame].cOffset < LLONG_MAX);
532
0
            CHECK_IO(zs->src.seek(zs->src.opaque,
533
0
                                  (long long)zs->seekTable.entries[targetFrame].cOffset,
534
0
                                  SEEK_SET));
535
0
            zs->in = (ZSTD_inBuffer){zs->inBuff, 0, 0};
536
0
            XXH64_reset(&zs->xxhState, 0);
537
0
            ZSTD_DCtx_reset(zs->dstream, ZSTD_reset_session_only);
538
0
            if (zs->buffWrapper.size && srcBytesRead > zs->buffWrapper.size) {
539
0
                return ERROR(seekableIO);
540
0
            }
541
0
            zs->decompressedOffset = zs->seekTable.entries[targetFrame].dOffset;
542
0
            zs->curFrame = targetFrame;
543
0
        }
544
545
0
        while (zs->decompressedOffset < offset + len) {
546
0
            size_t toRead;
547
0
            ZSTD_outBuffer outTmp;
548
0
            size_t prevOutPos;
549
0
            size_t prevInPos;
550
0
            size_t forwardProgress;
551
0
            if (zs->decompressedOffset < offset) {
552
                /* dummy decompressions until we get to the target offset */
553
0
                outTmp = (ZSTD_outBuffer){zs->outBuff, (size_t) (MIN(SEEKABLE_BUFF_SIZE, offset - zs->decompressedOffset)), 0};
554
0
            } else {
555
0
                outTmp = (ZSTD_outBuffer){dst, len, (size_t) (zs->decompressedOffset - offset)};
556
0
            }
557
558
0
            prevOutPos = outTmp.pos;
559
0
            prevInPos = zs->in.pos;
560
0
            toRead = ZSTD_decompressStream(zs->dstream, &outTmp, &zs->in);
561
0
            if (ZSTD_isError(toRead)) {
562
0
                return toRead;
563
0
            }
564
565
0
            if (zs->seekTable.checksumFlag) {
566
0
                XXH64_update(&zs->xxhState, (BYTE*)outTmp.dst + prevOutPos,
567
0
                             outTmp.pos - prevOutPos);
568
0
            }
569
0
            forwardProgress = outTmp.pos - prevOutPos;
570
0
            if (forwardProgress == 0) {
571
0
                if (noOutputProgressCount++ > ZSTD_SEEKABLE_NO_OUTPUT_PROGRESS_MAX) {
572
0
                    return ERROR(seekableIO);
573
0
                }
574
0
            } else {
575
0
                noOutputProgressCount = 0;
576
0
            }
577
0
            zs->decompressedOffset += forwardProgress;
578
0
            srcBytesRead += zs->in.pos - prevInPos;
579
580
0
            if (toRead == 0) {
581
                /* frame complete */
582
583
                /* A completed frame must end at its declared boundary;
584
                 * otherwise the table could re-select this frame and loop. */
585
0
                assert(targetFrame < zs->seekTable.tableLen);
586
0
                if (zs->decompressedOffset != zs->seekTable.entries[targetFrame + 1].dOffset) {
587
0
                    return ERROR(corruption_detected);
588
0
                }
589
590
                /* verify checksum */
591
0
                if (zs->seekTable.checksumFlag &&
592
0
                    (XXH64_digest(&zs->xxhState) & 0xFFFFFFFFU) !=
593
0
                            zs->seekTable.entries[targetFrame].checksum) {
594
0
                    return ERROR(corruption_detected);
595
0
                }
596
597
0
                if (zs->decompressedOffset < offset + len) {
598
                    /* The checked boundary must advance to a later entry. */
599
0
                    U32 const nextFrame = ZSTD_seekable_offsetToFrameIndex(zs, zs->decompressedOffset);
600
0
                    assert(nextFrame > targetFrame);
601
0
                    assert(nextFrame < zs->seekTable.tableLen);
602
0
                    targetFrame = nextFrame;
603
0
                }
604
0
                break;
605
0
            }
606
607
            /* read in more data if we're done with this buffer */
608
0
            if (zs->in.pos == zs->in.size) {
609
0
                toRead = MIN(toRead, SEEKABLE_BUFF_SIZE);
610
0
                CHECK_IO(zs->src.read(zs->src.opaque, zs->inBuff, toRead));
611
0
                zs->in.size = toRead;
612
0
                zs->in.pos = 0;
613
0
            }
614
0
        }  /* while (zs->decompressedOffset < offset + len) */
615
0
    } while (zs->decompressedOffset != offset + len);
616
617
0
    return len;
618
0
}
619
620
size_t ZSTD_seekable_decompress(ZSTD_seekable* zs, void* dst, size_t len, unsigned long long offset)
621
0
{
622
0
    size_t const result = ZSTD_seekable_decompress_internal(zs, dst, len, offset);
623
    /* A failed read may have advanced the source, or the decoder may be in
624
     * an error state. Force the next request to seek and reset its frame. */
625
0
    if (ZSTD_isError(result)) zs->curFrame = (U32)-1;
626
0
    return result;
627
0
}
628
629
size_t ZSTD_seekable_decompressFrame(ZSTD_seekable* zs, void* dst, size_t dstSize, unsigned frameIndex)
630
0
{
631
0
    if (zs->seekTable.entries == NULL) return ERROR(init_missing);
632
0
    if (frameIndex >= zs->seekTable.tableLen) {
633
0
        return ERROR(frameIndex_tooLarge);
634
0
    }
635
636
0
    {   size_t const decompressedSize =
637
0
                zs->seekTable.entries[frameIndex + 1].dOffset -
638
0
                zs->seekTable.entries[frameIndex].dOffset;
639
0
        if (dstSize < decompressedSize) {
640
0
            return ERROR(dstSize_tooSmall);
641
0
        }
642
0
        return ZSTD_seekable_decompress(
643
0
                zs, dst, decompressedSize,
644
0
                zs->seekTable.entries[frameIndex].dOffset);
645
0
    }
646
0
}