2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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.
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 */
18 # if !defined(_LARGEFILE_SOURCE) /* obsolete macro, replaced with _FILE_OFFSET_BITS */
19 # define _LARGEFILE_SOURCE 1 /* Large File Support extension (LFS) - fseeko, ftello */
21 # if defined(_AIX) || defined(__hpux)
22 # define _LARGE_FILES /* Large file support on 32-bits AIX and HP-UX */
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
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
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>
48 # elif !defined(_WIN32) \
49 && ( defined(__unix__) || defined(__unix) \
50 || defined(__midipix__) || defined(__VMS) || defined(__HAIKU__) )
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 */
57 # include <unistd.h> /* declares _POSIX_VERSION */
58 # if defined(_POSIX_VERSION) /* POSIX compliant */
59 # define PLATFORM_POSIX_VERSION _POSIX_VERSION
61 # define PLATFORM_POSIX_VERSION 1
66 # define __USE_MISC /* enable st_mtim on uclibc */
70 # else /* non-unix target platform (like Windows) */
71 # define PLATFORM_POSIX_VERSION 0
74 #endif /* PLATFORM_POSIX_VERSION */
77 /* ************************************************************
78 * Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
79 ***************************************************************/
80 #if defined(_MSC_VER) && _MSC_VER >= 1400
81 # define LONG_SEEK _fseeki64
82 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
83 # define LONG_SEEK fseeko
84 #elif defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)
85 # define LONG_SEEK fseeko64
86 #elif defined(_WIN32) && !defined(__DJGPP__)
88 static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
91 off.QuadPart = offset;
92 if (origin == SEEK_END)
94 else if (origin == SEEK_CUR)
95 method = FILE_CURRENT;
99 if (SetFilePointerEx((HANDLE) _get_osfhandle(_fileno(file)), off, NULL, method))
105 # define LONG_SEEK fseek
108 #include <stdlib.h> /* malloc, free */
109 #include <stdio.h> /* FILE* */
110 #include <limits.h> /* UNIT_MAX */
113 #define XXH_STATIC_LINKING_ONLY
116 #define ZSTD_STATIC_LINKING_ONLY
118 #include "zstd_errors.h"
120 #include "zstd_seekable.h"
123 #define ERROR(name) ((size_t)-ZSTD_error_##name)
125 #define CHECK_IO(f) { int const errcod = (f); if (errcod < 0) return ERROR(seekableIO); }
129 #define MIN(a, b) ((a) < (b) ? (a) : (b))
130 #define MAX(a, b) ((a) > (b) ? (a) : (b))
132 #define ZSTD_SEEKABLE_NO_OUTPUT_PROGRESS_MAX 16
134 /* Special-case callbacks for FILE* and in-memory modes, so that we can treat
135 * them the same way as the advanced API */
136 static int ZSTD_seekable_read_FILE(void* opaque, void* buffer, size_t n)
138 size_t const result = fread(buffer, 1, n, (FILE*)opaque);
145 static int ZSTD_seekable_seek_FILE(void* opaque, long long offset, int origin)
147 int const ret = LONG_SEEK((FILE*)opaque, offset, origin);
149 return fflush((FILE*)opaque);
158 static int ZSTD_seekable_read_buff(void* opaque, void* buffer, size_t n)
160 buffWrapper_t* const buff = (buffWrapper_t*)opaque;
161 assert(buff != NULL);
162 if (buff->pos + n > buff->size) return -1;
163 memcpy(buffer, (const BYTE*)buff->ptr + buff->pos, n);
168 static int ZSTD_seekable_seek_buff(void* opaque, long long offset, int origin)
170 buffWrapper_t* const buff = (buffWrapper_t*) opaque;
171 unsigned long long newOffset;
172 assert(buff != NULL);
176 newOffset = (unsigned long long)offset;
179 newOffset = (unsigned long long)((long long)buff->pos + offset);
182 newOffset = (unsigned long long)((long long)buff->size + offset);
185 assert(0); /* not possible */
187 if (newOffset > buff->size) {
190 buff->pos = newOffset;
200 struct ZSTD_seekTable_s {
201 seekEntry_t* entries;
207 #define SEEKABLE_BUFF_SIZE ZSTD_BLOCKSIZE_MAX
209 struct ZSTD_seekable_s {
210 ZSTD_DStream* dstream;
211 ZSTD_seekTable seekTable;
212 ZSTD_seekable_customFile src;
214 U64 decompressedOffset;
217 BYTE inBuff[SEEKABLE_BUFF_SIZE]; /* need to do our own input buffering */
218 BYTE outBuff[SEEKABLE_BUFF_SIZE]; /* so we can efficiently decompress the
219 starts of chunks before we get to the
221 ZSTD_inBuffer in; /* maintain continuity across ZSTD_seekable_decompress operations */
222 buffWrapper_t buffWrapper; /* for `src.opaque` in in-memory mode */
224 XXH64_state_t xxhState;
227 ZSTD_seekable* ZSTD_seekable_create(void)
229 ZSTD_seekable* const zs = (ZSTD_seekable*)malloc(sizeof(ZSTD_seekable));
230 if (zs == NULL) return NULL;
232 /* also initializes stage to zsds_init */
233 memset(zs, 0, sizeof(*zs));
235 zs->dstream = ZSTD_createDStream();
236 if (zs->dstream == NULL) {
244 size_t ZSTD_seekable_free(ZSTD_seekable* zs)
246 if (zs == NULL) return 0; /* support free on null */
247 ZSTD_freeDStream(zs->dstream);
248 free(zs->seekTable.entries);
253 ZSTD_seekTable* ZSTD_seekTable_create_fromSeekable(const ZSTD_seekable* zs)
255 ZSTD_seekTable* const st = (ZSTD_seekTable*)malloc(sizeof(ZSTD_seekTable));
256 if (st==NULL) return NULL;
258 st->checksumFlag = zs->seekTable.checksumFlag;
259 st->tableLen = zs->seekTable.tableLen;
261 /* Allocate an extra entry at the end to match logic of initial allocation */
262 size_t const entriesSize = sizeof(seekEntry_t) * (zs->seekTable.tableLen + 1);
263 seekEntry_t* const entries = (seekEntry_t*)malloc(entriesSize);
269 memcpy(entries, zs->seekTable.entries, entriesSize);
270 st->entries = entries;
274 size_t ZSTD_seekTable_free(ZSTD_seekTable* st)
276 if (st == NULL) return 0; /* support free on null */
282 /** ZSTD_seekable_offsetToFrameIndex() :
283 * Performs a binary search to find the last frame with a decompressed offset
285 * @return : the frame's index */
286 unsigned ZSTD_seekable_offsetToFrameIndex(const ZSTD_seekable* zs, unsigned long long pos)
288 return ZSTD_seekTable_offsetToFrameIndex(&zs->seekTable, pos);
291 unsigned ZSTD_seekTable_offsetToFrameIndex(const ZSTD_seekTable* st, unsigned long long pos)
294 U32 hi = (U32)st->tableLen;
295 assert(st->tableLen <= UINT_MAX);
297 if (pos >= st->entries[st->tableLen].dOffset) {
298 return (unsigned)st->tableLen;
301 while (lo + 1 < hi) {
302 U32 const mid = lo + ((hi - lo) >> 1);
303 if (st->entries[mid].dOffset <= pos) {
312 unsigned ZSTD_seekable_getNumFrames(const ZSTD_seekable* zs)
314 return ZSTD_seekTable_getNumFrames(&zs->seekTable);
317 unsigned ZSTD_seekTable_getNumFrames(const ZSTD_seekTable* st)
319 assert(st->tableLen <= UINT_MAX);
320 return (unsigned)st->tableLen;
323 unsigned long long ZSTD_seekable_getFrameCompressedOffset(const ZSTD_seekable* zs, unsigned frameIndex)
325 return ZSTD_seekTable_getFrameCompressedOffset(&zs->seekTable, frameIndex);
328 unsigned long long ZSTD_seekTable_getFrameCompressedOffset(const ZSTD_seekTable* st, unsigned frameIndex)
330 if (frameIndex >= st->tableLen) return ZSTD_SEEKABLE_FRAMEINDEX_TOOLARGE;
331 return st->entries[frameIndex].cOffset;
334 unsigned long long ZSTD_seekable_getFrameDecompressedOffset(const ZSTD_seekable* zs, unsigned frameIndex)
336 return ZSTD_seekTable_getFrameDecompressedOffset(&zs->seekTable, frameIndex);
339 unsigned long long ZSTD_seekTable_getFrameDecompressedOffset(const ZSTD_seekTable* st, unsigned frameIndex)
341 if (frameIndex >= st->tableLen) return ZSTD_SEEKABLE_FRAMEINDEX_TOOLARGE;
342 return st->entries[frameIndex].dOffset;
345 size_t ZSTD_seekable_getFrameCompressedSize(const ZSTD_seekable* zs, unsigned frameIndex)
347 return ZSTD_seekTable_getFrameCompressedSize(&zs->seekTable, frameIndex);
350 size_t ZSTD_seekTable_getFrameCompressedSize(const ZSTD_seekTable* st, unsigned frameIndex)
352 if (frameIndex >= st->tableLen) return ERROR(frameIndex_tooLarge);
353 return st->entries[frameIndex + 1].cOffset -
354 st->entries[frameIndex].cOffset;
357 size_t ZSTD_seekable_getFrameDecompressedSize(const ZSTD_seekable* zs, unsigned frameIndex)
359 return ZSTD_seekTable_getFrameDecompressedSize(&zs->seekTable, frameIndex);
362 size_t ZSTD_seekTable_getFrameDecompressedSize(const ZSTD_seekTable* st, unsigned frameIndex)
364 if (frameIndex > st->tableLen) return ERROR(frameIndex_tooLarge);
365 return st->entries[frameIndex + 1].dOffset -
366 st->entries[frameIndex].dOffset;
369 static size_t ZSTD_seekable_loadSeekTable(ZSTD_seekable* zs)
372 ZSTD_seekable_customFile src = zs->src;
373 /* read the footer, fixed size */
374 CHECK_IO(src.seek(src.opaque, -(int)ZSTD_seekTableFooterSize, SEEK_END));
375 CHECK_IO(src.read(src.opaque, zs->inBuff, ZSTD_seekTableFooterSize));
377 if (MEM_readLE32(zs->inBuff + 5) != ZSTD_SEEKABLE_MAGICNUMBER) {
378 return ERROR(prefix_unknown);
381 { BYTE const sfd = zs->inBuff[4];
382 checksumFlag = sfd >> 7;
384 /* check reserved bits */
385 if ((sfd >> 2) & 0x1f) {
386 return ERROR(corruption_detected);
389 { U32 const numFrames = MEM_readLE32(zs->inBuff);
390 U32 const sizePerEntry = 8 + (checksumFlag?4:0);
391 U32 const tableSize = sizePerEntry * numFrames;
392 U32 const frameSize = tableSize + ZSTD_seekTableFooterSize + ZSTD_SKIPPABLEHEADERSIZE;
394 U32 remaining = frameSize - ZSTD_seekTableFooterSize; /* don't need to re-read footer */
395 { U32 const toRead = MIN(remaining, SEEKABLE_BUFF_SIZE);
396 CHECK_IO(src.seek(src.opaque, -(S64)frameSize, SEEK_END));
397 CHECK_IO(src.read(src.opaque, zs->inBuff, toRead));
401 if (MEM_readLE32(zs->inBuff) != (ZSTD_MAGIC_SKIPPABLE_START | 0xE)) {
402 return ERROR(prefix_unknown);
404 if (MEM_readLE32(zs->inBuff+4) + ZSTD_SKIPPABLEHEADERSIZE != frameSize) {
405 return ERROR(prefix_unknown);
408 { /* Allocate an extra entry at the end so that we can do size
409 * computations on the last element without special case */
410 seekEntry_t* const entries = (seekEntry_t*)malloc(sizeof(seekEntry_t) * (numFrames + 1));
418 if (entries == NULL) return ERROR(memory_allocation);
420 /* compute cumulative positions */
421 for (; idx < numFrames; idx++) {
422 if (pos + sizePerEntry > SEEKABLE_BUFF_SIZE) {
423 U32 const offset = SEEKABLE_BUFF_SIZE - pos;
424 U32 const toRead = MIN(remaining, SEEKABLE_BUFF_SIZE - offset);
425 memmove(zs->inBuff, zs->inBuff + pos, offset); /* move any data we haven't read yet */
426 CHECK_IO(src.read(src.opaque, zs->inBuff+offset, toRead));
430 entries[idx].cOffset = cOffset;
431 entries[idx].dOffset = dOffset;
433 cOffset += MEM_readLE32(zs->inBuff + pos);
435 dOffset += MEM_readLE32(zs->inBuff + pos);
438 entries[idx].checksum = MEM_readLE32(zs->inBuff + pos);
442 entries[numFrames].cOffset = cOffset;
443 entries[numFrames].dOffset = dOffset;
445 zs->seekTable.entries = entries;
446 zs->seekTable.tableLen = numFrames;
447 zs->seekTable.checksumFlag = checksumFlag;
453 size_t ZSTD_seekable_initBuff(ZSTD_seekable* zs, const void* src, size_t srcSize)
455 zs->buffWrapper = (buffWrapper_t){src, srcSize, 0};
456 { ZSTD_seekable_customFile srcFile = {&zs->buffWrapper,
457 &ZSTD_seekable_read_buff,
458 &ZSTD_seekable_seek_buff};
459 return ZSTD_seekable_initAdvanced(zs, srcFile); }
462 size_t ZSTD_seekable_initFile(ZSTD_seekable* zs, FILE* src)
464 ZSTD_seekable_customFile srcFile = {src, &ZSTD_seekable_read_FILE,
465 &ZSTD_seekable_seek_FILE};
466 return ZSTD_seekable_initAdvanced(zs, srcFile);
469 size_t ZSTD_seekable_initAdvanced(ZSTD_seekable* zs, ZSTD_seekable_customFile src)
473 { const size_t seekTableInit = ZSTD_seekable_loadSeekTable(zs);
474 if (ZSTD_isError(seekTableInit)) return seekTableInit; }
476 zs->decompressedOffset = (U64)-1;
477 zs->curFrame = (U32)-1;
479 { const size_t dstreamInit = ZSTD_initDStream(zs->dstream);
480 if (ZSTD_isError(dstreamInit)) return dstreamInit; }
484 size_t ZSTD_seekable_decompress(ZSTD_seekable* zs, void* dst, size_t len, unsigned long long offset)
486 unsigned long long const eos = zs->seekTable.entries[zs->seekTable.tableLen].dOffset;
487 if (offset + len > eos) {
491 U32 targetFrame = ZSTD_seekable_offsetToFrameIndex(zs, offset);
492 U32 noOutputProgressCount = 0;
493 size_t srcBytesRead = 0;
495 /* check if we can continue from a previous decompress job */
496 if (targetFrame != zs->curFrame || offset < zs->decompressedOffset) {
497 zs->decompressedOffset = zs->seekTable.entries[targetFrame].dOffset;
498 zs->curFrame = targetFrame;
500 assert(zs->seekTable.entries[targetFrame].cOffset < LLONG_MAX);
501 CHECK_IO(zs->src.seek(zs->src.opaque,
502 (long long)zs->seekTable.entries[targetFrame].cOffset,
504 zs->in = (ZSTD_inBuffer){zs->inBuff, 0, 0};
505 XXH64_reset(&zs->xxhState, 0);
506 ZSTD_DCtx_reset(zs->dstream, ZSTD_reset_session_only);
507 if (zs->buffWrapper.size && srcBytesRead > zs->buffWrapper.size) {
508 return ERROR(seekableIO);
512 while (zs->decompressedOffset < offset + len) {
514 ZSTD_outBuffer outTmp;
517 size_t forwardProgress;
518 if (zs->decompressedOffset < offset) {
519 /* dummy decompressions until we get to the target offset */
520 outTmp = (ZSTD_outBuffer){zs->outBuff, (size_t) (MIN(SEEKABLE_BUFF_SIZE, offset - zs->decompressedOffset)), 0};
522 outTmp = (ZSTD_outBuffer){dst, len, (size_t) (zs->decompressedOffset - offset)};
525 prevOutPos = outTmp.pos;
526 prevInPos = zs->in.pos;
527 toRead = ZSTD_decompressStream(zs->dstream, &outTmp, &zs->in);
528 if (ZSTD_isError(toRead)) {
532 if (zs->seekTable.checksumFlag) {
533 XXH64_update(&zs->xxhState, (BYTE*)outTmp.dst + prevOutPos,
534 outTmp.pos - prevOutPos);
536 forwardProgress = outTmp.pos - prevOutPos;
537 if (forwardProgress == 0) {
538 if (noOutputProgressCount++ > ZSTD_SEEKABLE_NO_OUTPUT_PROGRESS_MAX) {
539 return ERROR(seekableIO);
542 noOutputProgressCount = 0;
544 zs->decompressedOffset += forwardProgress;
545 srcBytesRead += zs->in.pos - prevInPos;
550 /* verify checksum */
551 if (zs->seekTable.checksumFlag &&
552 (XXH64_digest(&zs->xxhState) & 0xFFFFFFFFU) !=
553 zs->seekTable.entries[targetFrame].checksum) {
554 return ERROR(corruption_detected);
557 if (zs->decompressedOffset < offset + len) {
558 /* go back to the start and force a reset of the stream */
559 targetFrame = ZSTD_seekable_offsetToFrameIndex(zs, zs->decompressedOffset);
560 /* in this case it will fail later with corruption_detected, since last block does not have checksum */
561 assert(targetFrame != zs->seekTable.tableLen);
566 /* read in more data if we're done with this buffer */
567 if (zs->in.pos == zs->in.size) {
568 toRead = MIN(toRead, SEEKABLE_BUFF_SIZE);
569 CHECK_IO(zs->src.read(zs->src.opaque, zs->inBuff, toRead));
570 zs->in.size = toRead;
573 } /* while (zs->decompressedOffset < offset + len) */
574 } while (zs->decompressedOffset != offset + len);
579 size_t ZSTD_seekable_decompressFrame(ZSTD_seekable* zs, void* dst, size_t dstSize, unsigned frameIndex)
581 if (frameIndex >= zs->seekTable.tableLen) {
582 return ERROR(frameIndex_tooLarge);
585 { size_t const decompressedSize =
586 zs->seekTable.entries[frameIndex + 1].dOffset -
587 zs->seekTable.entries[frameIndex].dOffset;
588 if (dstSize < decompressedSize) {
589 return ERROR(dstSize_tooSmall);
591 return ZSTD_seekable_decompress(
592 zs, dst, decompressedSize,
593 zs->seekTable.entries[frameIndex].dOffset);