Coverage Report

Created: 2026-12-01 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lz4/lib/lz4file.c
Line
Count
Source
1
/*
2
 * LZ4 file library
3
 * Copyright (c) Yann Collet and LZ4 contributors. All rights reserved.
4
 *
5
 * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions are
9
 * met:
10
 *
11
 * - Redistributions of source code must retain the above copyright
12
 *   notice, this list of conditions and the following disclaimer.
13
 * - Redistributions in binary form must reproduce the above
14
 *   copyright notice, this list of conditions and the following disclaimer
15
 *   in the documentation and/or other materials provided with the
16
 *   distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * You can contact the author at :
31
 * - LZ4 homepage : http://www.lz4.org
32
 * - LZ4 source repository : https://github.com/lz4/lz4
33
 */
34
#include <string.h>
35
#include <assert.h>
36
#include "lz4.h"
37
#include "lz4file.h"
38
39
/* =====   Memory routines   ===== */
40
/* custom functions if provided (LZ4F_readOpen_advanced(), LZ4F_writeOpen_advanced()),
41
 * otherwise malloc() and free(), or LZ4_malloc() and LZ4_free()
42
 * when lz4 is compiled with LZ4_USER_MEMORY_FUNCTIONS (see lz4.c),
43
 * and none with LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION */
44
#if defined(LZ4_USER_MEMORY_FUNCTIONS)
45
void* LZ4_malloc(size_t s);
46
void  LZ4_free(void* p);
47
#  define LZ4FILE_MALLOC(s)    LZ4_malloc(s)
48
#  define LZ4FILE_FREE(p)      LZ4_free(p)
49
#elif defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
50
#  define LZ4FILE_MALLOC(s)    NULL   /* no default allocator */
51
#  define LZ4FILE_FREE(p)      ((void)(p))
52
#else
53
#  include <stdlib.h>   /* malloc, free */
54
95.8k
#  define LZ4FILE_MALLOC(s)    malloc(s)
55
95.8k
#  define LZ4FILE_FREE(p)      free(p)
56
#endif
57
58
static void* fileMalloc(size_t s, LZ4F_CustomMem cmem)
59
95.8k
{
60
95.8k
  if (cmem.customAlloc != NULL) return cmem.customAlloc(cmem.opaqueState, s);
61
95.8k
  return LZ4FILE_MALLOC(s);
62
95.8k
}
63
64
static void fileFree(void* p, LZ4F_CustomMem cmem)
65
164k
{
66
164k
  if (p == NULL) return;
67
95.8k
  if (cmem.customFree != NULL) cmem.customFree(cmem.opaqueState, p);
68
95.8k
  else LZ4FILE_FREE(p);
69
95.8k
}
70
71
/* =====   Error Handling   ===== */
72
static LZ4F_errorCode_t returnErrorCode(LZ4F_errorCodes code)
73
3.30k
{
74
3.30k
    return (LZ4F_errorCode_t)-(ptrdiff_t)code;
75
3.30k
}
76
77
#undef RETURN_ERROR
78
3.30k
#define RETURN_ERROR(e) return returnErrorCode(LZ4F_ERROR_ ## e)
79
80
/* =====    Read API Implementation    ===== */
81
82
/* Resume points : positions where decoding can restart, recorded while reading :
83
 * frame starts, and block starts within frames using independent blocks.
84
 * They are spaced by at least LZ4F_RESUME_SPAN bytes of decoded data, to bound memory usage.
85
 * The start of file is an implicit resume point. */
86
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
87
36.1k
#  define LZ4F_RESUME_SPAN 64           /* resume points within small fuzzing inputs */
88
#else
89
#  define LZ4F_RESUME_SPAN (1 << 20)
90
#endif
91
43.5k
#define LZ4F_SKIP_BUFFER_SIZE (64 << 10)
92
31.3k
#define LZ4F_SKIPPABLE_HEADER_SIZE 8   /* magic number, frame size : the shortest complete frame */
93
94
typedef struct {
95
  unsigned long long cPos;       /* position within compressed data : start of a frame, or of a block */
96
  unsigned long long dPos;       /* matching position within decoded data */
97
  unsigned long long frameDPos;  /* block start : position of its frame within decoded data */
98
  LZ4F_frameInfo_t frameInfo;    /* block start : parameters of its frame */
99
  int isBlockStart;
100
} LZ4F_resumePoint;
101
102
struct LZ4_readFile_s {
103
  LZ4F_dctx* dctxPtr;
104
  FILE* fp;
105
  LZ4_byte* srcBuf;
106
  size_t srcBufNext;
107
  size_t srcBufSize;
108
  size_t srcBufMaxSize;
109
  unsigned long long srcBufPos;   /* position of srcBuf within compressed data */
110
  unsigned long long decodedPos;  /* reading position within decoded data */
111
  unsigned long long frameDPos;   /* position of current frame within decoded data */
112
  size_t hint;                    /* input expected by the decoder, up to the end of next block header : 0 between frames */
113
  LZ4F_errorCode_t error;         /* decoding error : the decoder can't continue, until restartFrom() */
114
  int seekable;
115
  LZ4F_resumePoint* points;
116
  size_t nbPoints;
117
  size_t pointsCapacity;
118
  LZ4_byte* skipBuf;              /* receives data skipped by LZ4F_seek() */
119
  LZ4F_CustomMem cmem;
120
};
121
122
static void freeReadFileResources(LZ4_readFile_t* lz4fRead)
123
31.3k
{
124
31.3k
  if (lz4fRead==NULL) return;
125
31.3k
  LZ4F_freeDecompressionContext(lz4fRead->dctxPtr);
126
31.3k
  fileFree(lz4fRead->srcBuf, lz4fRead->cmem);
127
31.3k
  fileFree(lz4fRead->points, lz4fRead->cmem);
128
31.3k
  fileFree(lz4fRead->skipBuf, lz4fRead->cmem);
129
31.3k
  fileFree(lz4fRead, lz4fRead->cmem);
130
31.3k
}
131
132
static LZ4F_errorCode_t readAndParseHeader(LZ4_readFile_t* readFile, FILE* fp)
133
31.3k
{
134
31.3k
    char headerBuf[LZ4F_HEADER_SIZE_MAX];
135
31.3k
    LZ4F_frameInfo_t frameInfo;
136
31.3k
    size_t consumedSize;
137
138
    /* Read the header from file */
139
31.3k
    const size_t bytesRead = fread(headerBuf, 1, sizeof(headerBuf), fp);
140
31.3k
    if (bytesRead < LZ4F_SKIPPABLE_HEADER_SIZE) {
141
255
        RETURN_ERROR(io_read);
142
255
    }
143
144
    /* Parse frame information */
145
31.0k
    consumedSize = bytesRead;
146
31.0k
    { const size_t result = LZ4F_getFrameInfo(readFile->dctxPtr, &frameInfo, headerBuf, &consumedSize);
147
31.0k
      if (LZ4F_isError(result)) {
148
11.7k
          return result;
149
11.7k
      }
150
19.3k
      readFile->hint = result;
151
19.3k
    }
152
    /* A normal frame needs an end mark, while an empty skippable frame is only its header. */
153
19.3k
    if (frameInfo.frameType != LZ4F_skippableFrame
154
19.0k
      && bytesRead < LZ4F_HEADER_SIZE_MIN + LZ4F_ENDMARK_SIZE) {
155
1
        RETURN_ERROR(io_read);
156
1
    }
157
158
    /* Determine buffer size based on block size */
159
19.3k
    { const size_t blockSize = LZ4F_getBlockSize(frameInfo.blockSizeID);
160
19.3k
      if (LZ4F_isError(blockSize)) {
161
0
          RETURN_ERROR(maxBlockSize_invalid);
162
0
      }
163
19.3k
      readFile->srcBufMaxSize = blockSize;
164
19.3k
    }
165
166
    /* Allocate source buffer */
167
19.3k
    assert(readFile->srcBuf == NULL); /* Should be NULL from creation */
168
19.3k
    readFile->srcBuf = (LZ4_byte*)fileMalloc(readFile->srcBufMaxSize, readFile->cmem);
169
19.3k
    if (readFile->srcBuf == NULL) {
170
0
        RETURN_ERROR(allocation_failed);
171
0
    }
172
173
    /* Store remaining header data in buffer */
174
19.3k
    readFile->srcBufPos = consumedSize;
175
19.3k
    readFile->srcBufSize = bytesRead - consumedSize;
176
19.3k
    if (readFile->srcBufSize > 0) {
177
18.6k
        memcpy(readFile->srcBuf, headerBuf + consumedSize, readFile->srcBufSize);
178
18.6k
    }
179
19.3k
    readFile->srcBufNext = 0;
180
181
19.3k
    return LZ4F_OK_NoError;
182
19.3k
}
183
184
LZ4F_errorCode_t LZ4F_readOpen_advanced(LZ4_readFile_t** lz4fRead, FILE* fp, LZ4F_CustomMem customMem)
185
31.3k
{
186
31.3k
    LZ4_readFile_t* readFile;
187
188
    /* Validate parameters */
189
31.3k
    if (lz4fRead == NULL) {
190
0
        RETURN_ERROR(parameter_null);
191
0
    }
192
31.3k
    *lz4fRead = NULL;   /* in case of failure */
193
31.3k
    if (fp == NULL) {
194
0
        RETURN_ERROR(parameter_null);
195
0
    }
196
197
    /* Allocate read file structure */
198
31.3k
    readFile = (LZ4_readFile_t*)fileMalloc(sizeof(LZ4_readFile_t), customMem);
199
31.3k
    if (readFile == NULL) {
200
0
        RETURN_ERROR(allocation_failed);
201
0
    }
202
31.3k
    memset(readFile, 0, sizeof(*readFile));
203
31.3k
    readFile->cmem = customMem;
204
205
31.3k
    readFile->fp = fp;
206
31.3k
    readFile->seekable = (ftell(fp) != -1L);   /* no position on pipes */
207
208
    /* Initialize decompression context */
209
31.3k
    readFile->dctxPtr = LZ4F_createDecompressionContext_advanced(customMem, LZ4F_VERSION);
210
31.3k
    if (readFile->dctxPtr == NULL) {
211
0
        freeReadFileResources(readFile);
212
0
        RETURN_ERROR(allocation_failed);
213
0
    }
214
215
    /* Read and parse the header */
216
31.3k
    { LZ4F_errorCode_t const result = readAndParseHeader(readFile, fp);
217
31.3k
      if (LZ4F_isError(result)) {
218
11.9k
          freeReadFileResources(readFile);
219
11.9k
          return result;
220
11.9k
    } }
221
222
19.3k
    *lz4fRead = readFile;
223
19.3k
    return LZ4F_OK_NoError;
224
31.3k
}
225
226
LZ4F_errorCode_t LZ4F_readOpen(LZ4_readFile_t** lz4fRead, FILE* fp)
227
31.3k
{
228
31.3k
    return LZ4F_readOpen_advanced(lz4fRead, fp, LZ4F_defaultCMem);
229
31.3k
}
230
231
/* records a resume point at current decoded position, if far enough from the previous one.
232
 * Points are appended in increasing order : decoding again a part already indexed records nothing.
233
 * The index is optional : on allocation failure, the point is just not recorded.
234
 * @frameInfo : NULL for a frame start */
235
static void addResumePoint(LZ4_readFile_t* lz4fRead, unsigned long long cPos, const LZ4F_frameInfo_t* frameInfo)
236
36.1k
{
237
36.1k
  unsigned long long const lastDPos = lz4fRead->nbPoints ? lz4fRead->points[lz4fRead->nbPoints-1].dPos : 0;
238
36.1k
  LZ4F_resumePoint* p;
239
36.1k
  if (lz4fRead->decodedPos < lastDPos + LZ4F_RESUME_SPAN) return;
240
9.55k
  if (lz4fRead->nbPoints == lz4fRead->pointsCapacity) {
241
7.50k
    size_t const newCapacity = lz4fRead->pointsCapacity ? 2 * lz4fRead->pointsCapacity : 64;
242
7.50k
    LZ4F_resumePoint* const newPoints = (LZ4F_resumePoint*)fileMalloc(newCapacity * sizeof(*newPoints), lz4fRead->cmem);   /* no realloc() among user functions */
243
7.50k
    if (newPoints == NULL) return;
244
7.50k
    if (lz4fRead->nbPoints) memcpy(newPoints, lz4fRead->points, lz4fRead->nbPoints * sizeof(*newPoints));
245
7.50k
    fileFree(lz4fRead->points, lz4fRead->cmem);
246
7.50k
    lz4fRead->points = newPoints;
247
7.50k
    lz4fRead->pointsCapacity = newCapacity;
248
7.50k
  }
249
9.55k
  p = lz4fRead->points + lz4fRead->nbPoints++;
250
9.55k
  memset(p, 0, sizeof(*p));
251
9.55k
  p->cPos = cPos;
252
9.55k
  p->dPos = lz4fRead->decodedPos;
253
9.55k
  p->frameDPos = lz4fRead->frameDPos;
254
9.55k
  p->isBlockStart = (frameInfo != NULL);
255
9.55k
  if (frameInfo != NULL) p->frameInfo = *frameInfo;
256
9.55k
}
257
258
/* the current frame isn't finished : input can't end here */
259
static int frameInProgress(const LZ4_readFile_t* lz4fRead)
260
412k
{
261
412k
  return lz4fRead->hint != 0;
262
412k
}
263
264
/* input provided at once to the decoder : up to the end of next block header,
265
 * or the minimal header of next frame */
266
static size_t inputLimit(const LZ4_readFile_t* lz4fRead)
267
402k
{
268
402k
  return frameInProgress(lz4fRead) ? lz4fRead->hint : LZ4F_HEADER_SIZE_MIN;
269
402k
}
270
271
/* updates the reading state after LZ4F_decompress() consumed @consumed bytes out of @provided,
272
 * and records resume points */
273
static void trackPosition(LZ4_readFile_t* lz4fRead, size_t decStatus, size_t provided, size_t consumed)
274
159k
{
275
159k
  unsigned long long const cPos = lz4fRead->srcBufPos + lz4fRead->srcBufNext;
276
159k
  if (decStatus == 0) {   /* end of frame : next frame starts here */
277
18.3k
    lz4fRead->hint = 0;
278
18.3k
    lz4fRead->frameDPos = lz4fRead->decodedPos;
279
18.3k
    addResumePoint(lz4fRead, cPos, NULL);
280
18.3k
    return;
281
18.3k
  }
282
  /* exactly the hinted input was consumed, and next hint covers a block :
283
   * decoding stopped right after a block header */
284
141k
  if (consumed == provided && provided == inputLimit(lz4fRead) && decStatus > LZ4F_BLOCK_HEADER_SIZE) {
285
67.8k
    LZ4F_frameInfo_t frameInfo;
286
67.8k
    size_t noInput = 0;
287
    /* fails within a frame header, which isn't followed by a block header yet */
288
67.8k
    if (!LZ4F_isError(LZ4F_getFrameInfo(lz4fRead->dctxPtr, &frameInfo, NULL, &noInput))
289
66.6k
      && frameInfo.frameType == LZ4F_frame
290
66.2k
      && frameInfo.blockMode == LZ4F_blockIndependent)
291
17.8k
      addResumePoint(lz4fRead, cPos - LZ4F_BLOCK_HEADER_SIZE, &frameInfo);
292
67.8k
  }
293
141k
  lz4fRead->hint = decStatus;
294
141k
}
295
296
size_t LZ4F_read(LZ4_readFile_t* lz4fRead, void* buf, size_t size)
297
66.3k
{
298
66.3k
  LZ4_byte* outPtr = (LZ4_byte*)buf;
299
66.3k
  size_t totalBytesRead = 0;
300
301
66.3k
  if (lz4fRead == NULL || buf == NULL)
302
0
    RETURN_ERROR(parameter_null);
303
66.3k
  if (LZ4F_isError(lz4fRead->error))
304
966
    return lz4fRead->error;
305
306
225k
  while (totalBytesRead < size) {
307
173k
    size_t srcBytes = lz4fRead->srcBufSize - lz4fRead->srcBufNext;
308
173k
    size_t dstBytes = size - totalBytesRead;
309
173k
    size_t provided;
310
311
173k
    if (srcBytes == 0) {
312
46.6k
      size_t bytesRead;
313
46.6k
      lz4fRead->srcBufPos += lz4fRead->srcBufSize;
314
46.6k
      lz4fRead->srcBufSize = 0;
315
46.6k
      lz4fRead->srcBufNext = 0;
316
46.6k
      bytesRead = fread(lz4fRead->srcBuf, 1, lz4fRead->srcBufMaxSize, lz4fRead->fp);
317
46.6k
      if (bytesRead == 0) {
318
10.1k
        if (ferror(lz4fRead->fp) || frameInProgress(lz4fRead)) {
319
1.77k
          RETURN_ERROR(io_read);   /* read error, or input ends within a frame */
320
1.77k
        }
321
8.34k
        break; /* end of input reached */
322
10.1k
      }
323
      /* success: ret > 0*/
324
36.5k
      lz4fRead->srcBufSize = bytesRead;
325
36.5k
      srcBytes = lz4fRead->srcBufSize;
326
36.5k
    }
327
328
    /* provide at most the hinted amount : decoding then stops right after each block header */
329
163k
    if (srcBytes > inputLimit(lz4fRead)) srcBytes = inputLimit(lz4fRead);
330
163k
    provided = srcBytes;
331
332
163k
    { size_t const decStatus = LZ4F_decompress(
333
163k
                          lz4fRead->dctxPtr,
334
163k
                          outPtr, &dstBytes,
335
163k
                          lz4fRead->srcBuf + lz4fRead->srcBufNext,
336
163k
                          &srcBytes,
337
163k
                          NULL);
338
163k
      if (LZ4F_isError(decStatus)) {
339
3.72k
          lz4fRead->error = decStatus;   /* the dctx can't be used again before a reset */
340
3.72k
          return decStatus;
341
3.72k
      }
342
159k
      lz4fRead->srcBufNext += srcBytes;
343
159k
      lz4fRead->decodedPos += dstBytes;
344
159k
      totalBytesRead += dstBytes;
345
159k
      outPtr += dstBytes;
346
159k
      trackPosition(lz4fRead, decStatus, provided, srcBytes);
347
159k
    }
348
159k
  }
349
350
59.8k
  return totalBytesRead;
351
65.3k
}
352
353
/* moves @fp by @delta bytes : fseek() offsets are long, which may be 32-bit */
354
static int fseekRelative(FILE* fp, long long delta)
355
15.2k
{
356
15.2k
  long const stepMax = 1L << 30;
357
30.4k
  while (delta != 0) {
358
15.2k
    long const step = (delta > stepMax) ? stepMax : (delta < -stepMax) ? -stepMax : (long)delta;
359
15.2k
    if (fseek(fp, step, SEEK_CUR) != 0) return -1;
360
15.2k
    delta -= step;
361
15.2k
  }
362
15.2k
  return 0;
363
15.2k
}
364
365
/* @return : last resume point at or before @pos within decoded data, or NULL for start of file */
366
static const LZ4F_resumePoint* findResumePoint(const LZ4_readFile_t* lz4fRead, unsigned long long pos)
367
26.6k
{
368
26.6k
  size_t lo = 0, hi = lz4fRead->nbPoints;
369
42.5k
  while (lo < hi) {   /* first point beyond @pos is within [lo, hi] */
370
15.9k
    size_t const mid = lo + (hi - lo) / 2;
371
15.9k
    if (lz4fRead->points[mid].dPos <= pos) lo = mid + 1; else hi = mid;
372
15.9k
  }
373
26.6k
  return lo ? lz4fRead->points + lo - 1 : NULL;
374
26.6k
}
375
376
/* restarts decoding from resume point @p (NULL : start of file) */
377
static LZ4F_errorCode_t restartFrom(LZ4_readFile_t* lz4fRead, const LZ4F_resumePoint* p)
378
15.2k
{
379
15.2k
  unsigned long long const cPos = p ? p->cPos : 0;
380
15.2k
  unsigned long long const filePos = lz4fRead->srcBufPos + lz4fRead->srcBufSize;
381
15.2k
  if (!lz4fRead->seekable || fseekRelative(lz4fRead->fp, (long long)cPos - (long long)filePos))
382
0
    RETURN_ERROR(io_read);
383
15.2k
  lz4fRead->srcBufPos = cPos;
384
15.2k
  lz4fRead->srcBufSize = 0;
385
15.2k
  lz4fRead->srcBufNext = 0;
386
15.2k
  lz4fRead->decodedPos = p ? p->dPos : 0;
387
15.2k
  if (p && p->isBlockStart) {
388
1.20k
    size_t const result = LZ4F_resumeFrame(lz4fRead->dctxPtr, &p->frameInfo, p->dPos - p->frameDPos, NULL, 0);
389
1.20k
    if (LZ4F_isError(result)) return result;
390
1.20k
    lz4fRead->hint = LZ4F_BLOCK_HEADER_SIZE;
391
1.20k
    lz4fRead->frameDPos = p->frameDPos;
392
14.0k
  } else {
393
14.0k
    LZ4F_resetDecompressionContext(lz4fRead->dctxPtr);
394
14.0k
    lz4fRead->hint = 0;
395
14.0k
    lz4fRead->frameDPos = lz4fRead->decodedPos;
396
14.0k
  }
397
15.2k
  lz4fRead->error = LZ4F_OK_NoError;
398
15.2k
  return LZ4F_OK_NoError;
399
15.2k
}
400
401
LZ4F_errorCode_t LZ4F_seek(LZ4_readFile_t* lz4fRead, long long offset, int origin)
402
27.7k
{
403
27.7k
  unsigned long long target;
404
405
27.7k
  if (lz4fRead == NULL)
406
0
    RETURN_ERROR(parameter_null);
407
408
27.7k
  switch (origin) {
409
19.0k
  case SEEK_SET:
410
19.0k
    if (offset < 0) RETURN_ERROR(parameter_invalid);
411
18.2k
    target = (unsigned long long)offset;
412
18.2k
    break;
413
8.75k
  case SEEK_CUR:
414
8.75k
    if (offset < 0 && (unsigned long long)-(offset + 1) >= lz4fRead->decodedPos)
415
412
      RETURN_ERROR(parameter_invalid);   /* before start */
416
8.34k
    target = lz4fRead->decodedPos + (unsigned long long)offset;
417
8.34k
    break;
418
0
  default:   /* SEEK_END is not supported */
419
0
    RETURN_ERROR(parameter_invalid);
420
27.7k
  }
421
422
  /* restart from closest resume point : required backward, and avoids decoding forward */
423
26.6k
  { const LZ4F_resumePoint* const p = findResumePoint(lz4fRead, target);
424
26.6k
    if (target < lz4fRead->decodedPos) {
425
14.4k
      LZ4F_errorCode_t const result = restartFrom(lz4fRead, p);
426
14.4k
      if (LZ4F_isError(result)) return result;
427
14.4k
    } else if (p != NULL && p->dPos > lz4fRead->decodedPos && lz4fRead->seekable) {
428
759
      LZ4F_errorCode_t const result = restartFrom(lz4fRead, p);
429
759
      if (LZ4F_isError(result)) return result;
430
759
  } }
431
432
  /* decode and discard up to target */
433
26.6k
  if (lz4fRead->decodedPos < target && lz4fRead->skipBuf == NULL) {
434
6.29k
    lz4fRead->skipBuf = (LZ4_byte*)fileMalloc(LZ4F_SKIP_BUFFER_SIZE, lz4fRead->cmem);
435
6.29k
    if (lz4fRead->skipBuf == NULL) RETURN_ERROR(allocation_failed);
436
6.29k
  }
437
49.5k
  while (lz4fRead->decodedPos < target) {
438
27.2k
    unsigned long long const remaining = target - lz4fRead->decodedPos;
439
27.2k
    size_t const toRead = (remaining < LZ4F_SKIP_BUFFER_SIZE) ? (size_t)remaining : LZ4F_SKIP_BUFFER_SIZE;
440
27.2k
    size_t const result = LZ4F_read(lz4fRead, lz4fRead->skipBuf, toRead);
441
27.2k
    if (LZ4F_isError(result)) return result;
442
23.0k
    if (result == 0) RETURN_ERROR(parameter_invalid);   /* beyond end of decoded data */
443
23.0k
  }
444
22.3k
  return LZ4F_OK_NoError;
445
26.6k
}
446
447
unsigned long long LZ4F_tell(const LZ4_readFile_t* lz4fRead)
448
72.6k
{
449
72.6k
  return lz4fRead ? lz4fRead->decodedPos : 0;
450
72.6k
}
451
452
LZ4F_errorCode_t LZ4F_readClose(LZ4_readFile_t* lz4fRead)
453
19.3k
{
454
19.3k
  if (lz4fRead == NULL)
455
0
    RETURN_ERROR(parameter_null);
456
19.3k
  freeReadFileResources(lz4fRead);
457
19.3k
  return LZ4F_OK_NoError;
458
19.3k
}
459
460
/* =====   write API   ===== */
461
462
struct LZ4_writeFile_s {
463
  LZ4F_cctx* cctxPtr;
464
  FILE* fp;
465
  LZ4_byte* dstBuf;
466
  size_t maxWriteSize;
467
  size_t dstBufMaxSize;
468
  LZ4F_errorCode_t errCode;
469
  LZ4F_CustomMem cmem;
470
};
471
472
static void freeWriteFileResources(LZ4_writeFile_t* state)
473
15.6k
{
474
15.6k
  if (state == NULL) return;
475
15.6k
  LZ4F_freeCompressionContext(state->cctxPtr);
476
15.6k
  fileFree(state->dstBuf, state->cmem);
477
15.6k
  fileFree(state, state->cmem);
478
15.6k
}
479
480
static LZ4F_errorCode_t writeHeader(LZ4_writeFile_t* writeFile,
481
                  FILE* fp,
482
            const LZ4F_preferences_t* prefsPtr)
483
15.6k
{
484
15.6k
  LZ4_byte headerBuf[LZ4F_HEADER_SIZE_MAX];
485
486
  /* Generate header */
487
15.6k
  LZ4F_errorCode_t const headerSize = LZ4F_compressBegin(writeFile->cctxPtr,
488
15.6k
                                  headerBuf, LZ4F_HEADER_SIZE_MAX, prefsPtr);
489
15.6k
  if (LZ4F_isError(headerSize)) {
490
0
    return headerSize;
491
0
  }
492
493
  /* Write header to file */
494
15.6k
  if (headerSize != fwrite(headerBuf, 1, headerSize, fp)) {
495
0
    RETURN_ERROR(io_write);
496
0
  }
497
498
15.6k
  return LZ4F_OK_NoError;
499
15.6k
}
500
501
LZ4F_errorCode_t LZ4F_writeOpen_advanced(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4F_preferences_t* prefsPtr,
502
                                         LZ4F_CustomMem customMem)
503
15.6k
{
504
15.6k
  LZ4_writeFile_t* writeFile;
505
15.6k
  size_t blockSize;
506
507
15.6k
  if (lz4fWrite == NULL)
508
0
      RETURN_ERROR(parameter_null);
509
15.6k
  *lz4fWrite = NULL;   /* in case of failure */
510
15.6k
  if (fp == NULL)
511
0
      RETURN_ERROR(parameter_null);
512
513
  /* Validate block size */
514
15.6k
  { LZ4F_blockSizeID_t const blockSizeID = prefsPtr ? prefsPtr->frameInfo.blockSizeID : LZ4F_default;
515
15.6k
    blockSize = LZ4F_getBlockSize(blockSizeID);
516
15.6k
    if (LZ4F_isError(blockSize)) {
517
0
        RETURN_ERROR(maxBlockSize_invalid);
518
0
  } }
519
520
  /* Allocate write file structure */
521
15.6k
  writeFile = (LZ4_writeFile_t*)fileMalloc(sizeof(LZ4_writeFile_t), customMem);
522
15.6k
  if (writeFile == NULL) {
523
0
    RETURN_ERROR(allocation_failed);
524
0
  }
525
15.6k
  memset(writeFile, 0, sizeof(*writeFile));
526
15.6k
  writeFile->cmem = customMem;
527
15.6k
  writeFile->fp = fp;
528
15.6k
  writeFile->errCode = LZ4F_OK_NoError;
529
15.6k
  writeFile->maxWriteSize = blockSize;
530
531
  /* Calculate and allocate destination buffer */
532
15.6k
  writeFile->dstBufMaxSize = LZ4F_compressBound(blockSize, prefsPtr);
533
15.6k
  writeFile->dstBuf = (LZ4_byte*)fileMalloc(writeFile->dstBufMaxSize, customMem);
534
15.6k
  if (writeFile->dstBuf == NULL) {
535
0
    freeWriteFileResources(writeFile);
536
0
    RETURN_ERROR(allocation_failed);
537
0
  }
538
539
  /* Initialize compression context */
540
15.6k
  writeFile->cctxPtr = LZ4F_createCompressionContext_advanced(customMem, LZ4F_VERSION);
541
15.6k
  if (writeFile->cctxPtr == NULL) {
542
0
    freeWriteFileResources(writeFile);
543
0
    RETURN_ERROR(allocation_failed);
544
0
  }
545
546
    /* Write header to file */
547
15.6k
  { LZ4F_errorCode_t const writeStatus = writeHeader(writeFile, fp, prefsPtr);
548
15.6k
    if (LZ4F_isError(writeStatus)) {
549
0
        freeWriteFileResources(writeFile);
550
0
        return writeStatus;
551
0
  } }
552
553
15.6k
  *lz4fWrite = writeFile;
554
15.6k
  return LZ4F_OK_NoError;
555
15.6k
}
556
557
LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4F_preferences_t* prefsPtr)
558
15.6k
{
559
15.6k
  return LZ4F_writeOpen_advanced(lz4fWrite, fp, prefsPtr, LZ4F_defaultCMem);
560
15.6k
}
561
562
size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, const void* buf, size_t size)
563
31.3k
{
564
31.3k
  const LZ4_byte* p = (const LZ4_byte*)buf;
565
31.3k
  size_t remainingBytes = size;
566
567
  /* Validate parameters */
568
31.3k
  if (lz4fWrite == NULL || buf == NULL)
569
0
    RETURN_ERROR(parameter_null);
570
571
71.1k
  while (remainingBytes) {
572
39.8k
    size_t const chunkSize = (remainingBytes > lz4fWrite->maxWriteSize) ? lz4fWrite->maxWriteSize : remainingBytes;
573
574
    /* Compress and write chunk */
575
39.8k
    size_t cSize = LZ4F_compressUpdate(lz4fWrite->cctxPtr,
576
39.8k
                              lz4fWrite->dstBuf, lz4fWrite->dstBufMaxSize,
577
39.8k
                              p, chunkSize,
578
39.8k
                              NULL);
579
39.8k
    if (LZ4F_isError(cSize)) {
580
0
      lz4fWrite->errCode = cSize;
581
0
      return cSize;
582
0
    }
583
584
39.8k
    if (cSize != 0 && cSize != fwrite(lz4fWrite->dstBuf, 1, cSize, lz4fWrite->fp)) {
585
0
      lz4fWrite->errCode = returnErrorCode(LZ4F_ERROR_io_write);
586
0
      RETURN_ERROR(io_write);
587
0
    }
588
589
    /* Update positions */
590
39.8k
    p += chunkSize;
591
39.8k
    remainingBytes -= chunkSize;
592
39.8k
  }
593
594
31.3k
  return size;
595
31.3k
}
596
597
LZ4F_errorCode_t LZ4F_writeClose(LZ4_writeFile_t* lz4fWrite)
598
15.6k
{
599
15.6k
  LZ4F_errorCode_t ret;
600
601
15.6k
  if (lz4fWrite == NULL) {
602
0
    RETURN_ERROR(parameter_null);
603
0
  }
604
605
15.6k
  ret = lz4fWrite->errCode;   /* a previous LZ4F_write() failure leaves the frame incomplete */
606
15.6k
  if (ret == LZ4F_OK_NoError) {
607
15.6k
    size_t endSize;
608
15.6k
    do {   /* dstBuf >= LZ4F_compressBound(0) : a single invocation completes the frame */
609
15.6k
      endSize = LZ4F_compressEnd(lz4fWrite->cctxPtr,
610
15.6k
                                 lz4fWrite->dstBuf, lz4fWrite->dstBufMaxSize,
611
15.6k
                                 NULL);
612
15.6k
      if (LZ4F_isError(endSize)) {
613
0
        ret = endSize;
614
0
        break;
615
0
      }
616
15.6k
      if (endSize != fwrite(lz4fWrite->dstBuf, 1, endSize, lz4fWrite->fp)) {
617
0
        ret = returnErrorCode(LZ4F_ERROR_io_write);
618
0
        break;
619
0
      }
620
15.6k
    } while (endSize == lz4fWrite->dstBufMaxSize);
621
15.6k
  }
622
623
15.6k
  freeWriteFileResources(lz4fWrite);
624
15.6k
  return ret;
625
15.6k
}