• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 21050823169

15 Jan 2026 12:56PM UTC coverage: 72.522% (-0.2%) from 72.704%
21050823169

push

github

keszybz
tree-wide: lock in all memory pages when mlockall() is utilized, and on demand

When employing MCL_FUTURE we don't actually want it to impose
immediate population of malloc()-ed pages. Hence let's set
MCL_ONFAULT everywhere.

Additionally, specify MCL_CURRENT to ensure future memory allocations
on already mapped pages are covered too. (Addresses
https://github.com/systemd/systemd/pull/40319#discussion_r2693726196)

Note that in shutdown the mlockall() is done to avoid keeping swap space
busy, hence a dedicated call w/ MCL_CURRENT and w/o MCL_ONFAULT is made.

2 of 4 new or added lines in 3 files covered. (50.0%)

1162 existing lines in 49 files now uncovered.

309356 of 426567 relevant lines covered (72.52%)

1129967.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.78
/src/basic/compress.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdio.h>
4
#include <sys/mman.h>
5
#include <sys/stat.h>
6
#include <unistd.h>
7

8
#if HAVE_LZ4
9
#include <lz4.h>
10
#include <lz4hc.h>
11
#include <lz4frame.h>
12
#endif
13

14
#if HAVE_XZ
15
#include <lzma.h>
16
#endif
17

18
#if HAVE_ZSTD
19
#include <zstd.h>
20
#include <zstd_errors.h>
21
#endif
22

23
#include "alloc-util.h"
24
#include "bitfield.h"
25
#include "compress.h"
26
#include "dlfcn-util.h"
27
#include "fileio.h"
28
#include "io-util.h"
29
#include "log.h"
30
#include "string-table.h"
31
#include "string-util.h"
32
#include "unaligned.h"
33

34
#if HAVE_LZ4
35
static void *lz4_dl = NULL;
36

37
static DLSYM_PROTOTYPE(LZ4F_compressBegin) = NULL;
38
static DLSYM_PROTOTYPE(LZ4F_compressBound) = NULL;
39
static DLSYM_PROTOTYPE(LZ4F_compressEnd) = NULL;
40
static DLSYM_PROTOTYPE(LZ4F_compressUpdate) = NULL;
41
static DLSYM_PROTOTYPE(LZ4F_createCompressionContext) = NULL;
42
static DLSYM_PROTOTYPE(LZ4F_createDecompressionContext) = NULL;
43
static DLSYM_PROTOTYPE(LZ4F_decompress) = NULL;
44
static DLSYM_PROTOTYPE(LZ4F_freeCompressionContext) = NULL;
45
static DLSYM_PROTOTYPE(LZ4F_freeDecompressionContext) = NULL;
46
static DLSYM_PROTOTYPE(LZ4F_isError) = NULL;
47
static DLSYM_PROTOTYPE(LZ4_compress_HC) = NULL;
48
/* These are used in test-compress.c so we don't make them static. */
49
DLSYM_PROTOTYPE(LZ4_compress_default) = NULL;
50
DLSYM_PROTOTYPE(LZ4_decompress_safe) = NULL;
51
DLSYM_PROTOTYPE(LZ4_decompress_safe_partial) = NULL;
52
DLSYM_PROTOTYPE(LZ4_versionNumber) = NULL;
53

54
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_compressionContext_t, sym_LZ4F_freeCompressionContext, LZ4F_freeCompressionContextp, NULL);
1✔
55
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_decompressionContext_t, sym_LZ4F_freeDecompressionContext, LZ4F_freeDecompressionContextp, NULL);
3✔
56
#endif
57

58
#if HAVE_ZSTD
59
static void *zstd_dl = NULL;
60

61
static DLSYM_PROTOTYPE(ZSTD_CCtx_setParameter) = NULL;
62
static DLSYM_PROTOTYPE(ZSTD_compress) = NULL;
63
static DLSYM_PROTOTYPE(ZSTD_compressStream2) = NULL;
64
static DLSYM_PROTOTYPE(ZSTD_createCCtx) = NULL;
65
static DLSYM_PROTOTYPE(ZSTD_createDCtx) = NULL;
66
static DLSYM_PROTOTYPE(ZSTD_CStreamInSize) = NULL;
67
static DLSYM_PROTOTYPE(ZSTD_CStreamOutSize) = NULL;
68
static DLSYM_PROTOTYPE(ZSTD_decompressStream) = NULL;
69
static DLSYM_PROTOTYPE(ZSTD_DStreamInSize) = NULL;
70
static DLSYM_PROTOTYPE(ZSTD_DStreamOutSize) = NULL;
71
static DLSYM_PROTOTYPE(ZSTD_freeCCtx) = NULL;
72
static DLSYM_PROTOTYPE(ZSTD_freeDCtx) = NULL;
73
static DLSYM_PROTOTYPE(ZSTD_getErrorCode) = NULL;
74
static DLSYM_PROTOTYPE(ZSTD_getErrorName) = NULL;
75
static DLSYM_PROTOTYPE(ZSTD_getFrameContentSize) = NULL;
76
static DLSYM_PROTOTYPE(ZSTD_isError) = NULL;
77

78
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_CCtx*, sym_ZSTD_freeCCtx, ZSTD_freeCCtxp, NULL);
25✔
79
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_DCtx*, sym_ZSTD_freeDCtx, ZSTD_freeDCtxp, NULL);
4,752,424✔
80

81
static int zstd_ret_to_errno(size_t ret) {
9✔
82
        switch (sym_ZSTD_getErrorCode(ret)) {
9✔
83
        case ZSTD_error_dstSize_tooSmall:
84
                return -ENOBUFS;
85
        case ZSTD_error_memory_allocation:
×
86
                return -ENOMEM;
×
87
        default:
1✔
88
                return -EBADMSG;
1✔
89
        }
90
}
91
#endif
92

93
#if HAVE_XZ
94
static void *lzma_dl = NULL;
95

96
static DLSYM_PROTOTYPE(lzma_code) = NULL;
97
static DLSYM_PROTOTYPE(lzma_easy_encoder) = NULL;
98
static DLSYM_PROTOTYPE(lzma_end) = NULL;
99
static DLSYM_PROTOTYPE(lzma_stream_buffer_encode) = NULL;
100
static DLSYM_PROTOTYPE(lzma_stream_decoder) = NULL;
101
static DLSYM_PROTOTYPE(lzma_lzma_preset) = NULL;
102

103
/* We can't just do _cleanup_(sym_lzma_end) because a compiler bug makes
104
 * this fail with:
105
 * ../src/basic/compress.c: In function ‘decompress_blob_xz’:
106
 * ../src/basic/compress.c:304:9: error: cleanup argument not a function
107
 *   304 |         _cleanup_(sym_lzma_end) lzma_stream s = LZMA_STREAM_INIT;
108
 *       |         ^~~~~~~~~
109
 */
110
static inline void lzma_end_wrapper(lzma_stream *ls) {
2,874✔
111
        sym_lzma_end(ls);
2,874✔
112
}
2,874✔
113
#endif
114

115
#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t))
116

117
static const char* const compression_table[_COMPRESSION_MAX] = {
118
        [COMPRESSION_NONE] = "NONE",
119
        [COMPRESSION_XZ]   = "XZ",
120
        [COMPRESSION_LZ4]  = "LZ4",
121
        [COMPRESSION_ZSTD] = "ZSTD",
122
};
123

124
static const char* const compression_lowercase_table[_COMPRESSION_MAX] = {
125
        [COMPRESSION_NONE] = "none",
126
        [COMPRESSION_XZ]   = "xz",
127
        [COMPRESSION_LZ4]  = "lz4",
128
        [COMPRESSION_ZSTD] = "zstd",
129
};
130

131
DEFINE_STRING_TABLE_LOOKUP(compression, Compression);
492✔
132
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
60✔
133

134
bool compression_supported(Compression c) {
2,667✔
135
        static const unsigned supported =
2,667✔
136
                (1U << COMPRESSION_NONE) |
137
                (1U << COMPRESSION_XZ) * HAVE_XZ |
138
                (1U << COMPRESSION_LZ4) * HAVE_LZ4 |
139
                (1U << COMPRESSION_ZSTD) * HAVE_ZSTD;
140

141
        assert(c >= 0);
2,667✔
142
        assert(c < _COMPRESSION_MAX);
2,667✔
143

144
        return BIT_SET(supported, c);
2,667✔
145
}
146

147
int dlopen_lzma(void) {
2,898✔
148
#if HAVE_XZ
149
        ELF_NOTE_DLOPEN("lzma",
2,898✔
150
                        "Support lzma compression in journal and coredump files",
151
                        COMPRESSION_PRIORITY_XZ,
152
                        "liblzma.so.5");
153

154
        return dlopen_many_sym_or_warn(
2,898✔
155
                        &lzma_dl,
156
                        "liblzma.so.5", LOG_DEBUG,
157
                        DLSYM_ARG(lzma_code),
158
                        DLSYM_ARG(lzma_easy_encoder),
159
                        DLSYM_ARG(lzma_end),
160
                        DLSYM_ARG(lzma_stream_buffer_encode),
161
                        DLSYM_ARG(lzma_lzma_preset),
162
                        DLSYM_ARG(lzma_stream_decoder));
163
#else
164
        return -EOPNOTSUPP;
165
#endif
166
}
167

168
int compress_blob_xz(const void *src, uint64_t src_size,
23✔
169
                     void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
170

171
        assert(src);
23✔
172
        assert(src_size > 0);
23✔
173
        assert(dst);
23✔
174
        assert(dst_alloc_size > 0);
23✔
175
        assert(dst_size);
23✔
176

177
#if HAVE_XZ
178
        lzma_options_lzma opt = {
23✔
179
                1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT,
180
                LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4
181
        };
182
        lzma_filter filters[] = {
23✔
183
                { LZMA_FILTER_LZMA2, &opt },
184
                { LZMA_VLI_UNKNOWN, NULL }
185
        };
186
        lzma_ret ret;
23✔
187
        size_t out_pos = 0;
23✔
188
        int r;
23✔
189

190
        r = dlopen_lzma();
23✔
191
        if (r < 0)
23✔
192
                return r;
23✔
193

194
        if (level >= 0) {
23✔
UNCOV
195
                r = sym_lzma_lzma_preset(&opt, (uint32_t) level);
×
196
                if (r < 0)
197
                        return r;
198
        }
199

200
        /* Returns < 0 if we couldn't compress the data or the
201
         * compressed result is longer than the original */
202

203
        if (src_size < 80)
23✔
204
                return -ENOBUFS;
205

206
        ret = sym_lzma_stream_buffer_encode(filters, LZMA_CHECK_NONE, NULL,
23✔
207
                                        src, src_size, dst, &out_pos, dst_alloc_size);
208
        if (ret != LZMA_OK)
23✔
209
                return -ENOBUFS;
210

211
        *dst_size = out_pos;
18✔
212
        return 0;
18✔
213
#else
214
        return -EPROTONOSUPPORT;
215
#endif
216
}
217

218
int dlopen_lz4(void) {
3,161✔
219
#if HAVE_LZ4
220
        ELF_NOTE_DLOPEN("lz4",
3,161✔
221
                        "Support lz4 compression in journal and coredump files",
222
                        COMPRESSION_PRIORITY_LZ4,
223
                        "liblz4.so.1");
224

225
        return dlopen_many_sym_or_warn(
3,161✔
226
                        &lz4_dl,
227
                        "liblz4.so.1", LOG_DEBUG,
228
                        DLSYM_ARG(LZ4F_compressBegin),
229
                        DLSYM_ARG(LZ4F_compressBound),
230
                        DLSYM_ARG(LZ4F_compressEnd),
231
                        DLSYM_ARG(LZ4F_compressUpdate),
232
                        DLSYM_ARG(LZ4F_createCompressionContext),
233
                        DLSYM_ARG(LZ4F_createDecompressionContext),
234
                        DLSYM_ARG(LZ4F_decompress),
235
                        DLSYM_ARG(LZ4F_freeCompressionContext),
236
                        DLSYM_ARG(LZ4F_freeDecompressionContext),
237
                        DLSYM_ARG(LZ4F_isError),
238
                        DLSYM_ARG(LZ4_compress_default),
239
                        DLSYM_ARG(LZ4_compress_HC),
240
                        DLSYM_ARG(LZ4_decompress_safe),
241
                        DLSYM_ARG(LZ4_decompress_safe_partial),
242
                        DLSYM_ARG(LZ4_versionNumber));
243
#else
244
        return -EOPNOTSUPP;
245
#endif
246
}
247

248
int compress_blob_lz4(const void *src, uint64_t src_size,
142✔
249
                      void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
250

251
        assert(src);
142✔
252
        assert(src_size > 0);
142✔
253
        assert(dst);
142✔
254
        assert(dst_alloc_size > 0);
142✔
255
        assert(dst_size);
142✔
256

257
#if HAVE_LZ4
258
        int r;
142✔
259

260
        r = dlopen_lz4();
142✔
261
        if (r < 0)
142✔
262
                return r;
263
        /* Returns < 0 if we couldn't compress the data or the
264
         * compressed result is longer than the original */
265

266
        if (src_size < 9)
142✔
267
                return -ENOBUFS;
268

269
        if (level <= 0)
142✔
270
                r = sym_LZ4_compress_default(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8);
142✔
271
        else
UNCOV
272
                r = sym_LZ4_compress_HC(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8, level);
×
273
        if (r <= 0)
142✔
274
                return -ENOBUFS;
275

276
        unaligned_write_le64(dst, src_size);
131✔
277
        *dst_size = r + 8;
131✔
278

279
        return 0;
131✔
280
#else
281
        return -EPROTONOSUPPORT;
282
#endif
283
}
284

285
int dlopen_zstd(void) {
4,752,697✔
286
#if HAVE_ZSTD
287
        ELF_NOTE_DLOPEN("zstd",
4,752,697✔
288
                        "Support zstd compression in journal and coredump files",
289
                        COMPRESSION_PRIORITY_ZSTD,
290
                        "libzstd.so.1");
291

292
        return dlopen_many_sym_or_warn(
4,752,697✔
293
                        &zstd_dl,
294
                        "libzstd.so.1", LOG_DEBUG,
295
                        DLSYM_ARG(ZSTD_getErrorCode),
296
                        DLSYM_ARG(ZSTD_compress),
297
                        DLSYM_ARG(ZSTD_getFrameContentSize),
298
                        DLSYM_ARG(ZSTD_decompressStream),
299
                        DLSYM_ARG(ZSTD_getErrorName),
300
                        DLSYM_ARG(ZSTD_DStreamOutSize),
301
                        DLSYM_ARG(ZSTD_CStreamInSize),
302
                        DLSYM_ARG(ZSTD_CStreamOutSize),
303
                        DLSYM_ARG(ZSTD_CCtx_setParameter),
304
                        DLSYM_ARG(ZSTD_compressStream2),
305
                        DLSYM_ARG(ZSTD_DStreamInSize),
306
                        DLSYM_ARG(ZSTD_freeCCtx),
307
                        DLSYM_ARG(ZSTD_freeDCtx),
308
                        DLSYM_ARG(ZSTD_isError),
309
                        DLSYM_ARG(ZSTD_createDCtx),
310
                        DLSYM_ARG(ZSTD_createCCtx));
311
#else
312
        return -EOPNOTSUPP;
313
#endif
314
}
315

316
int compress_blob_zstd(
241✔
317
                const void *src, uint64_t src_size,
318
                void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
319

320
        assert(src);
241✔
321
        assert(src_size > 0);
241✔
322
        assert(dst);
241✔
323
        assert(dst_alloc_size > 0);
241✔
324
        assert(dst_size);
241✔
325

326
#if HAVE_ZSTD
327
        size_t k;
241✔
328
        int r;
241✔
329

330
        r = dlopen_zstd();
241✔
331
        if (r < 0)
241✔
332
                return r;
333

334
        k = sym_ZSTD_compress(dst, dst_alloc_size, src, src_size, level < 0 ? 0 : level);
241✔
335
        if (sym_ZSTD_isError(k))
241✔
336
                return zstd_ret_to_errno(k);
8✔
337

338
        *dst_size = k;
233✔
339
        return 0;
233✔
340
#else
341
        return -EPROTONOSUPPORT;
342
#endif
343
}
344

345
int decompress_blob_xz(
2,600✔
346
                const void *src,
347
                uint64_t src_size,
348
                void **dst,
349
                size_t* dst_size,
350
                size_t dst_max) {
351

352
        assert(src);
2,600✔
353
        assert(src_size > 0);
2,600✔
354
        assert(dst);
2,600✔
355
        assert(dst_size);
2,600✔
356

357
#if HAVE_XZ
358
        int r;
2,600✔
359

360
        r = dlopen_lzma();
2,600✔
361
        if (r < 0)
2,600✔
362
                return r;
2,600✔
363

364
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
2,600✔
365
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
2,600✔
366
        if (ret != LZMA_OK)
2,600✔
367
                return -ENOMEM;
368

369
        size_t space = MIN(src_size * 2, dst_max ?: SIZE_MAX);
2,600✔
370
        if (!greedy_realloc(dst, space, 1))
2,600✔
371
                return -ENOMEM;
372

373
        s.next_in = src;
2,600✔
374
        s.avail_in = src_size;
2,600✔
375

376
        s.next_out = *dst;
2,600✔
377
        s.avail_out = space;
2,600✔
378

379
        for (;;) {
2,820✔
380
                size_t used;
2,710✔
381

382
                ret = sym_lzma_code(&s, LZMA_FINISH);
2,710✔
383
                if (ret == LZMA_STREAM_END)
2,710✔
384
                        break;
385
                if (ret != LZMA_OK)
116✔
386
                        return -ENOMEM;
387

388
                if (dst_max > 0 && (space - s.avail_out) >= dst_max)
110✔
389
                        break;
390
                if (dst_max > 0 && space == dst_max)
110✔
391
                        return -ENOBUFS;
392

393
                used = space - s.avail_out;
110✔
394
                space = MIN(2 * space, dst_max ?: SIZE_MAX);
110✔
395
                if (!greedy_realloc(dst, space, 1))
110✔
396
                        return -ENOMEM;
397

398
                s.avail_out = space - used;
110✔
399
                s.next_out = *(uint8_t**)dst + used;
110✔
400
        }
401

402
        *dst_size = space - s.avail_out;
2,594✔
403
        return 0;
2,594✔
404
#else
405
        return -EPROTONOSUPPORT;
406
#endif
407
}
408

409
int decompress_blob_lz4(
2,743✔
410
                const void *src,
411
                uint64_t src_size,
412
                void **dst,
413
                size_t* dst_size,
414
                size_t dst_max) {
415

416
        assert(src);
2,743✔
417
        assert(src_size > 0);
2,743✔
418
        assert(dst);
2,743✔
419
        assert(dst_size);
2,743✔
420

421
#if HAVE_LZ4
422
        char* out;
2,743✔
423
        int r, size; /* LZ4 uses int for size */
2,743✔
424

425
        r = dlopen_lz4();
2,743✔
426
        if (r < 0)
2,743✔
427
                return r;
428

429
        if (src_size <= 8)
2,743✔
430
                return -EBADMSG;
431

432
        size = unaligned_read_le64(src);
2,741✔
433
        if (size < 0 || (unsigned) size != unaligned_read_le64(src))
2,741✔
434
                return -EFBIG;
435
        out = greedy_realloc(dst, size, 1);
2,737✔
436
        if (!out)
2,737✔
437
                return -ENOMEM;
438

439
        r = sym_LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
2,737✔
440
        if (r < 0 || r != size)
2,737✔
441
                return -EBADMSG;
442

443
        *dst_size = size;
2,737✔
444
        return 0;
2,737✔
445
#else
446
        return -EPROTONOSUPPORT;
447
#endif
448
}
449

450
int decompress_blob_zstd(
237,819✔
451
                const void *src,
452
                uint64_t src_size,
453
                void **dst,
454
                size_t *dst_size,
455
                size_t dst_max) {
456

457
        assert(src);
237,819✔
458
        assert(src_size > 0);
237,819✔
459
        assert(dst);
237,819✔
460
        assert(dst_size);
237,819✔
461

462
#if HAVE_ZSTD
463
        uint64_t size;
237,819✔
464
        int r;
237,819✔
465

466
        r = dlopen_zstd();
237,819✔
467
        if (r < 0)
237,819✔
468
                return r;
237,819✔
469

470
        size = sym_ZSTD_getFrameContentSize(src, src_size);
237,819✔
471
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
237,819✔
472
                return -EBADMSG;
473

474
        if (dst_max > 0 && size > dst_max)
237,813✔
475
                size = dst_max;
×
476
        if (size > SIZE_MAX)
237,813✔
477
                return -E2BIG;
478

479
        if (!(greedy_realloc(dst, MAX(sym_ZSTD_DStreamOutSize(), size), 1)))
237,813✔
480
                return -ENOMEM;
481

482
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
475,626✔
483
        if (!dctx)
237,813✔
484
                return -ENOMEM;
485

486
        ZSTD_inBuffer input = {
237,813✔
487
                .src = src,
488
                .size = src_size,
489
        };
490
        ZSTD_outBuffer output = {
475,626✔
491
                .dst = *dst,
237,813✔
492
                .size = MALLOC_SIZEOF_SAFE(*dst),
237,813✔
493
        };
494

495
        size_t k = sym_ZSTD_decompressStream(dctx, &output, &input);
237,813✔
496
        if (sym_ZSTD_isError(k))
237,813✔
497
                return log_debug_errno(zstd_ret_to_errno(k), "ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
498
        if (output.pos < size)
237,813✔
499
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoded less data than indicated, probably corrupted stream.");
×
500

501
        *dst_size = size;
237,813✔
502
        return 0;
237,813✔
503
#else
504
        return -EPROTONOSUPPORT;
505
#endif
506
}
507

508
int decompress_blob(
242,912✔
509
                Compression compression,
510
                const void *src,
511
                uint64_t src_size,
512
                void **dst,
513
                size_t* dst_size,
514
                size_t dst_max) {
515

516
        switch (compression) {
242,912✔
517
        case COMPRESSION_XZ:
2,586✔
518
                return decompress_blob_xz(
2,586✔
519
                                src, src_size,
520
                                dst, dst_size, dst_max);
521
        case COMPRESSION_LZ4:
2,616✔
522
                return decompress_blob_lz4(
2,616✔
523
                                src, src_size,
524
                                dst, dst_size, dst_max);
525
        case COMPRESSION_ZSTD:
237,710✔
526
                return decompress_blob_zstd(
237,710✔
527
                                src, src_size,
528
                                dst, dst_size, dst_max);
529
        default:
530
                return -EPROTONOSUPPORT;
531
        }
532
}
533

534
int decompress_startswith_xz(
270✔
535
                const void *src,
536
                uint64_t src_size,
537
                void **buffer,
538
                const void *prefix,
539
                size_t prefix_len,
540
                uint8_t extra) {
541

542
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
543
         * follow the prefix */
544

545
        assert(src);
270✔
546
        assert(src_size > 0);
270✔
547
        assert(buffer);
270✔
548
        assert(prefix);
270✔
549

550
#if HAVE_XZ
551
        int r;
270✔
552

553
        r = dlopen_lzma();
270✔
554
        if (r < 0)
270✔
555
                return r;
270✔
556

557
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
270✔
558
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
270✔
559
        if (ret != LZMA_OK)
270✔
560
                return -EBADMSG;
561

562
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
563
                return -ENOMEM;
564

565
        size_t allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
566

567
        s.next_in = src;
270✔
568
        s.avail_in = src_size;
270✔
569

570
        s.next_out = *buffer;
270✔
571
        s.avail_out = allocated;
270✔
572

573
        for (;;) {
270✔
574
                ret = sym_lzma_code(&s, LZMA_FINISH);
270✔
575

576
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
270✔
577
                        return -EBADMSG;
578

579
                if (allocated - s.avail_out >= prefix_len + 1)
270✔
580
                        return memcmp(*buffer, prefix, prefix_len) == 0 &&
540✔
581
                                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
582

583
                if (ret == LZMA_STREAM_END)
×
584
                        return 0;
585

586
                s.avail_out += allocated;
×
587

588
                if (!(greedy_realloc(buffer, allocated * 2, 1)))
×
589
                        return -ENOMEM;
590

591
                allocated = MALLOC_SIZEOF_SAFE(*buffer);
×
592
                s.next_out = *(uint8_t**)buffer + allocated - s.avail_out;
×
593
        }
594

595
#else
596
        return -EPROTONOSUPPORT;
597
#endif
598
}
599

600
int decompress_startswith_lz4(
270✔
601
                const void *src,
602
                uint64_t src_size,
603
                void **buffer,
604
                const void *prefix,
605
                size_t prefix_len,
606
                uint8_t extra) {
607

608
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
609
         * follow the prefix */
610

611
        assert(src);
270✔
612
        assert(src_size > 0);
270✔
613
        assert(buffer);
270✔
614
        assert(prefix);
270✔
615

616
#if HAVE_LZ4
617
        size_t allocated;
270✔
618
        int r;
270✔
619

620
        r = dlopen_lz4();
270✔
621
        if (r < 0)
270✔
622
                return r;
623

624
        if (src_size <= 8)
270✔
625
                return -EBADMSG;
626

627
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
628
                return -ENOMEM;
629
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
630

631
        r = sym_LZ4_decompress_safe_partial(
540✔
632
                        (char*)src + 8,
633
                        *buffer,
634
                        src_size - 8,
270✔
635
                        prefix_len + 1,
270✔
636
                        allocated);
637

638
        /* One lz4 < 1.8.3, we might get "failure" (r < 0), or "success" where just a part of the buffer is
639
         * decompressed. But if we get a smaller amount of bytes than requested, we don't know whether there
640
         * isn't enough data to fill the requested size or whether we just got a partial answer.
641
         */
642
        if (r < 0 || (size_t) r < prefix_len + 1) {
270✔
643
                size_t size;
×
644

645
                if (sym_LZ4_versionNumber() >= 10803)
×
646
                        /* We trust that the newer lz4 decompresses the number of bytes we
647
                         * requested if available in the compressed string. */
648
                        return 0;
×
649

650
                if (r > 0)
×
651
                        /* Compare what we have first, in case of mismatch we can
652
                         * shortcut the full comparison. */
653
                        if (memcmp(*buffer, prefix, r) != 0)
×
654
                                return 0;
655

656
                /* Before version 1.8.3, lz4 always tries to decode full a "sequence",
657
                 * so in pathological cases might need to decompress the full field. */
658
                r = decompress_blob_lz4(src, src_size, buffer, &size, 0);
×
659
                if (r < 0)
×
660
                        return r;
661

662
                if (size < prefix_len + 1)
×
663
                        return 0;
664
        }
665

666
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
270✔
667
                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
668
#else
669
        return -EPROTONOSUPPORT;
670
#endif
671
}
672

673
int decompress_startswith_zstd(
4,514,598✔
674
                const void *src,
675
                uint64_t src_size,
676
                void **buffer,
677
                const void *prefix,
678
                size_t prefix_len,
679
                uint8_t extra) {
680

681
        assert(src);
4,514,598✔
682
        assert(src_size > 0);
4,514,598✔
683
        assert(buffer);
4,514,598✔
684
        assert(prefix);
4,514,598✔
685

686
#if HAVE_ZSTD
687
        int r;
4,514,598✔
688

689
        r = dlopen_zstd();
4,514,598✔
690
        if (r < 0)
4,514,598✔
691
                return r;
4,514,598✔
692

693
        uint64_t size = sym_ZSTD_getFrameContentSize(src, src_size);
4,514,598✔
694
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
4,514,598✔
695
                return -EBADMSG;
696

697
        if (size < prefix_len + 1)
4,514,598✔
698
                return 0; /* Decompressed text too short to match the prefix and extra */
699

700
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
9,029,196✔
701
        if (!dctx)
4,514,598✔
702
                return -ENOMEM;
703

704
        if (!(greedy_realloc(buffer, MAX(sym_ZSTD_DStreamOutSize(), prefix_len + 1), 1)))
4,514,598✔
705
                return -ENOMEM;
706

707
        ZSTD_inBuffer input = {
4,514,598✔
708
                .src = src,
709
                .size = src_size,
710
        };
711
        ZSTD_outBuffer output = {
9,029,196✔
712
                .dst = *buffer,
4,514,598✔
713
                .size = MALLOC_SIZEOF_SAFE(*buffer),
4,514,598✔
714
        };
715
        size_t k;
4,514,598✔
716

717
        k = sym_ZSTD_decompressStream(dctx, &output, &input);
4,514,598✔
718
        if (sym_ZSTD_isError(k)) {
4,514,598✔
719
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
720
                return zstd_ret_to_errno(k);
×
721
        }
722
        assert(output.pos >= prefix_len + 1);
4,514,598✔
723

724
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
4,514,598✔
725
                ((const uint8_t*) *buffer)[prefix_len] == extra;
14,699✔
726
#else
727
        return -EPROTONOSUPPORT;
728
#endif
729
}
730

731
int decompress_startswith(
4,514,340✔
732
                Compression compression,
733
                const void *src,
734
                uint64_t src_size,
735
                void **buffer,
736
                const void *prefix,
737
                size_t prefix_len,
738
                uint8_t extra) {
739

740
        switch (compression) {
4,514,340✔
741

742
        case COMPRESSION_XZ:
4✔
743
                return decompress_startswith_xz(
4✔
744
                                src, src_size,
745
                                buffer,
746
                                prefix, prefix_len,
747
                                extra);
748

749
        case COMPRESSION_LZ4:
4✔
750
                return decompress_startswith_lz4(
4✔
751
                                src, src_size,
752
                                buffer,
753
                                prefix, prefix_len,
754
                                extra);
755
        case COMPRESSION_ZSTD:
4,514,332✔
756
                return decompress_startswith_zstd(
4,514,332✔
757
                                src, src_size,
758
                                buffer,
759
                                prefix, prefix_len,
760
                                extra);
761
        default:
762
                return -EBADMSG;
763
        }
764
}
765

766
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
767
        assert(fdf >= 0);
1✔
768
        assert(fdt >= 0);
1✔
769

770
#if HAVE_XZ
771
        int r;
1✔
772

773
        r = dlopen_lzma();
1✔
774
        if (r < 0)
1✔
775
                return r;
1✔
776

777
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
1✔
778
        lzma_ret ret = sym_lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64);
1✔
779
        if (ret != LZMA_OK)
1✔
780
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
781
                                       "Failed to initialize XZ encoder: code %u",
782
                                       ret);
783

784
        uint8_t buf[BUFSIZ], out[BUFSIZ];
785
        lzma_action action = LZMA_RUN;
786
        for (;;) {
8✔
787
                if (s.avail_in == 0 && action == LZMA_RUN) {
8✔
788
                        size_t m = sizeof(buf);
7✔
789
                        ssize_t n;
7✔
790

791
                        if (max_bytes != UINT64_MAX && (uint64_t) m > max_bytes)
7✔
792
                                m = (size_t) max_bytes;
×
793

794
                        n = read(fdf, buf, m);
7✔
795
                        if (n < 0)
7✔
796
                                return -errno;
×
797
                        if (n == 0)
7✔
798
                                action = LZMA_FINISH;
799
                        else {
800
                                s.next_in = buf;
6✔
801
                                s.avail_in = n;
6✔
802

803
                                if (max_bytes != UINT64_MAX) {
6✔
804
                                        assert(max_bytes >= (uint64_t) n);
×
805
                                        max_bytes -= n;
×
806
                                }
807
                        }
808
                }
809

810
                if (s.avail_out == 0) {
8✔
811
                        s.next_out = out;
2✔
812
                        s.avail_out = sizeof(out);
2✔
813
                }
814

815
                ret = sym_lzma_code(&s, action);
8✔
816
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
8✔
817
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
×
818
                                               "Compression failed: code %u",
819
                                               ret);
820

821
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
8✔
822
                        ssize_t n, k;
2✔
823

824
                        n = sizeof(out) - s.avail_out;
2✔
825

826
                        k = loop_write(fdt, out, n);
2✔
827
                        if (k < 0)
2✔
828
                                return k;
829

830
                        if (ret == LZMA_STREAM_END) {
2✔
831
                                if (ret_uncompressed_size)
1✔
832
                                        *ret_uncompressed_size = s.total_in;
1✔
833

834
                                if (s.total_in == 0)
1✔
835
                                        log_debug("XZ compression finished (no input data)");
×
836
                                else
837
                                        log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
838
                                                  s.total_in, s.total_out,
839
                                                  (double) s.total_out / s.total_in * 100);
840

841
                                return 0;
1✔
842
                        }
843
                }
844
        }
845
#else
846
        return -EPROTONOSUPPORT;
847
#endif
848
}
849

850
#define LZ4_BUFSIZE (512*1024u)
851

852
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
853

854
#if HAVE_LZ4
855
        LZ4F_errorCode_t c;
1✔
856
        _cleanup_(LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL;
×
857
        _cleanup_free_ void *in_buff = NULL;
×
858
        _cleanup_free_ char *out_buff = NULL;
1✔
859
        size_t out_allocsize, n, offset = 0, frame_size;
1✔
860
        uint64_t total_in = 0, total_out;
1✔
861
        int r;
1✔
862
        static const LZ4F_preferences_t preferences = {
1✔
863
                .frameInfo.blockSizeID = 5,
864
        };
865

866
        r = dlopen_lz4();
1✔
867
        if (r < 0)
1✔
868
                return r;
869

870
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1✔
871
        if (sym_LZ4F_isError(c))
1✔
872
                return -ENOMEM;
873

874
        frame_size = sym_LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
1✔
875
        out_allocsize = frame_size + 64*1024; /* add some space for header and trailer */
1✔
876
        out_buff = malloc(out_allocsize);
1✔
877
        if (!out_buff)
1✔
878
                return -ENOMEM;
879

880
        in_buff = malloc(LZ4_BUFSIZE);
1✔
881
        if (!in_buff)
1✔
882
                return -ENOMEM;
883

884
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
1✔
885
        if (sym_LZ4F_isError(n))
1✔
886
                return -EINVAL;
887

888
        log_debug("Buffer size is %zu bytes, header size %zu bytes.", out_allocsize, n);
1✔
889

890
        for (;;) {
2✔
891
                ssize_t k;
2✔
892

893
                k = loop_read(fdf, in_buff, LZ4_BUFSIZE, true);
2✔
894
                if (k < 0)
2✔
895
                        return k;
×
896
                if (k == 0)
2✔
897
                        break;
898
                n = sym_LZ4F_compressUpdate(ctx, out_buff + offset, out_allocsize - offset,
1✔
899
                                        in_buff, k, NULL);
900
                if (sym_LZ4F_isError(n))
1✔
901
                        return -ENOTRECOVERABLE;
902

903
                total_in += k;
1✔
904
                offset += n;
1✔
905
                total_out += n;
1✔
906

907
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes)
1✔
908
                        return log_debug_errno(SYNTHETIC_ERRNO(EFBIG),
×
909
                                               "Compressed stream longer than %" PRIu64 " bytes", max_bytes);
910

911
                if (out_allocsize - offset < frame_size + 4) {
1✔
912
                        k = loop_write(fdt, out_buff, offset);
×
913
                        if (k < 0)
×
914
                                return k;
915
                        offset = 0;
916
                }
917
        }
918

919
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
1✔
920
        if (sym_LZ4F_isError(n))
1✔
921
                return -ENOTRECOVERABLE;
922

923
        offset += n;
1✔
924
        total_out += n;
1✔
925
        r = loop_write(fdt, out_buff, offset);
1✔
926
        if (r < 0)
1✔
927
                return r;
928

929
        if (ret_uncompressed_size)
1✔
930
                *ret_uncompressed_size = total_in;
1✔
931

932
        if (total_in == 0)
1✔
933
                log_debug("LZ4 compression finished (no input data)");
×
934
        else
935
                log_debug("LZ4 compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
1✔
936
                          total_in, total_out,
937
                          (double) total_out / total_in * 100);
938

939
        return 0;
940
#else
941
        return -EPROTONOSUPPORT;
942
#endif
943
}
944

945
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
3✔
946
        assert(fdf >= 0);
3✔
947
        assert(fdt >= 0);
3✔
948

949
#if HAVE_XZ
950
        int r;
3✔
951

952
        r = dlopen_lzma();
3✔
953
        if (r < 0)
3✔
954
                return r;
3✔
955

956
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
3✔
957
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
3✔
958
        if (ret != LZMA_OK)
3✔
959
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEM),
×
960
                                       "Failed to initialize XZ decoder: code %u",
961
                                       ret);
962

963
        uint8_t buf[BUFSIZ], out[BUFSIZ];
964
        lzma_action action = LZMA_RUN;
965
        for (;;) {
15✔
966
                if (s.avail_in == 0 && action == LZMA_RUN) {
15✔
967
                        ssize_t n;
5✔
968

969
                        n = read(fdf, buf, sizeof(buf));
5✔
970
                        if (n < 0)
5✔
971
                                return -errno;
×
972
                        if (n == 0)
5✔
973
                                action = LZMA_FINISH;
974
                        else {
975
                                s.next_in = buf;
5✔
976
                                s.avail_in = n;
5✔
977
                        }
978
                }
979

980
                if (s.avail_out == 0) {
15✔
981
                        s.next_out = out;
13✔
982
                        s.avail_out = sizeof(out);
13✔
983
                }
984

985
                ret = sym_lzma_code(&s, action);
15✔
986
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
15✔
987
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1✔
988
                                               "Decompression failed: code %u",
989
                                               ret);
990

991
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
14✔
992
                        ssize_t n, k;
12✔
993

994
                        n = sizeof(out) - s.avail_out;
12✔
995

996
                        if (max_bytes != UINT64_MAX) {
12✔
997
                                if (max_bytes < (uint64_t) n)
12✔
998
                                        return -EFBIG;
999

1000
                                max_bytes -= n;
11✔
1001
                        }
1002

1003
                        k = loop_write(fdt, out, n);
11✔
1004
                        if (k < 0)
11✔
1005
                                return k;
1006

1007
                        if (ret == LZMA_STREAM_END) {
11✔
1008
                                if (s.total_in == 0)
1✔
1009
                                        log_debug("XZ decompression finished (no input data)");
×
1010
                                else
1011
                                        log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
1012
                                                  s.total_in, s.total_out,
1013
                                                  (double) s.total_out / s.total_in * 100);
1014

1015
                                return 0;
1✔
1016
                        }
1017
                }
1018
        }
1019
#else
1020
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1021
                               "Cannot decompress file. Compiled without XZ support.");
1022
#endif
1023
}
1024

1025
int decompress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) {
3✔
1026
#if HAVE_LZ4
1027
        size_t c;
3✔
1028
        _cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
×
1029
        _cleanup_free_ char *buf = NULL;
3✔
1030
        char *src;
3✔
1031
        struct stat st;
3✔
1032
        int r;
3✔
1033
        size_t total_in = 0, total_out = 0;
3✔
1034

1035
        r = dlopen_lz4();
3✔
1036
        if (r < 0)
3✔
1037
                return r;
1038

1039
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
3✔
1040
        if (sym_LZ4F_isError(c))
3✔
1041
                return -ENOMEM;
1042

1043
        if (fstat(fdf, &st) < 0)
3✔
1044
                return log_debug_errno(errno, "fstat() failed: %m");
×
1045

1046
        if (file_offset_beyond_memory_size(st.st_size))
3✔
1047
                return -EFBIG;
1048

1049
        buf = malloc(LZ4_BUFSIZE);
3✔
1050
        if (!buf)
3✔
1051
                return -ENOMEM;
1052

1053
        src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
3✔
1054
        if (src == MAP_FAILED)
3✔
1055
                return -errno;
×
1056

1057
        while (total_in < (size_t) st.st_size) {
5✔
1058
                size_t produced = LZ4_BUFSIZE;
3✔
1059
                size_t used = st.st_size - total_in;
3✔
1060

1061
                c = sym_LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
3✔
1062
                if (sym_LZ4F_isError(c)) {
3✔
1063
                        r = -EBADMSG;
×
1064
                        goto cleanup;
1✔
1065
                }
1066

1067
                total_in += used;
3✔
1068
                total_out += produced;
3✔
1069

1070
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes) {
3✔
1071
                        log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
1✔
1072
                        r = -EFBIG;
1✔
1073
                        goto cleanup;
1✔
1074
                }
1075

1076
                r = loop_write(fdt, buf, produced);
2✔
1077
                if (r < 0)
2✔
1078
                        goto cleanup;
×
1079
        }
1080

1081
        if (total_in == 0)
2✔
1082
                log_debug("LZ4 decompression finished (no input data)");
×
1083
        else
1084
                log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
2✔
1085
                          total_in, total_out,
1086
                          (double) total_out / total_in * 100);
1087
        r = 0;
1088
 cleanup:
3✔
1089
        munmap(src, st.st_size);
3✔
1090
        return r;
3✔
1091
#else
1092
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1093
                               "Cannot decompress file. Compiled without LZ4 support.");
1094
#endif
1095
}
1096

1097
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
25✔
1098
        assert(fdf >= 0);
25✔
1099
        assert(fdt >= 0);
25✔
1100

1101
#if HAVE_ZSTD
1102
        _cleanup_(ZSTD_freeCCtxp) ZSTD_CCtx *cctx = NULL;
×
1103
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
25✔
1104
        size_t in_allocsize, out_allocsize;
25✔
1105
        size_t z;
25✔
1106
        uint64_t left = max_bytes, in_bytes = 0;
25✔
1107
        int r;
25✔
1108

1109
        r = dlopen_zstd();
25✔
1110
        if (r < 0)
25✔
1111
                return r;
1112

1113
        /* Create the context and buffers */
1114
        in_allocsize = sym_ZSTD_CStreamInSize();
25✔
1115
        out_allocsize = sym_ZSTD_CStreamOutSize();
25✔
1116
        in_buff = malloc(in_allocsize);
25✔
1117
        out_buff = malloc(out_allocsize);
25✔
1118
        cctx = sym_ZSTD_createCCtx();
25✔
1119
        if (!cctx || !out_buff || !in_buff)
25✔
1120
                return -ENOMEM;
1121

1122
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
25✔
1123
        if (sym_ZSTD_isError(z))
25✔
1124
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1125

1126
        /* This loop read from the input file, compresses that entire chunk,
1127
         * and writes all output produced to the output file.
1128
         */
1129
        for (;;) {
565✔
1130
                bool is_last_chunk;
590✔
1131
                ZSTD_inBuffer input = {
590✔
1132
                        .src = in_buff,
1133
                        .size = 0,
1134
                        .pos = 0
1135
                };
1136
                ssize_t red;
590✔
1137

1138
                red = loop_read(fdf, in_buff, in_allocsize, true);
590✔
1139
                if (red < 0)
590✔
1140
                        return red;
×
1141
                is_last_chunk = red == 0;
590✔
1142

1143
                in_bytes += (size_t) red;
590✔
1144
                input.size = (size_t) red;
590✔
1145

1146
                for (bool finished = false; !finished;) {
1,180✔
1147
                        ZSTD_outBuffer output = {
590✔
1148
                                .dst = out_buff,
1149
                                .size = out_allocsize,
1150
                                .pos = 0
1151
                        };
1152
                        size_t remaining;
590✔
1153
                        ssize_t wrote;
590✔
1154

1155
                        /* Compress into the output buffer and write all of the
1156
                         * output to the file so we can reuse the buffer next
1157
                         * iteration.
1158
                         */
1159
                        remaining = sym_ZSTD_compressStream2(
1,155✔
1160
                                cctx, &output, &input,
1161
                                is_last_chunk ? ZSTD_e_end : ZSTD_e_continue);
1162

1163
                        if (sym_ZSTD_isError(remaining)) {
590✔
1164
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1165
                                return zstd_ret_to_errno(remaining);
×
1166
                        }
1167

1168
                        if (left < output.pos)
590✔
1169
                                return -EFBIG;
1170

1171
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
590✔
1172
                        if (wrote < 0)
590✔
1173
                                return wrote;
1174

1175
                        left -= output.pos;
590✔
1176

1177
                        /* If we're on the last chunk we're finished when zstd
1178
                         * returns 0, which means its consumed all the input AND
1179
                         * finished the frame. Otherwise, we're finished when
1180
                         * we've consumed all the input.
1181
                         */
1182
                        finished = is_last_chunk ? (remaining == 0) : (input.pos == input.size);
590✔
1183
                }
1184

1185
                /* zstd only returns 0 when the input is completely consumed */
1186
                assert(input.pos == input.size);
590✔
1187
                if (is_last_chunk)
590✔
1188
                        break;
1189
        }
1190

1191
        if (ret_uncompressed_size)
25✔
1192
                *ret_uncompressed_size = in_bytes;
25✔
1193

1194
        if (in_bytes == 0)
25✔
1195
                log_debug("ZSTD compression finished (no input data)");
×
1196
        else
1197
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
25✔
1198
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1199

1200
        return 0;
1201
#else
1202
        return -EPROTONOSUPPORT;
1203
#endif
1204
}
1205

1206
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
13✔
1207
        assert(fdf >= 0);
13✔
1208
        assert(fdt >= 0);
13✔
1209

1210
#if HAVE_ZSTD
1211
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = NULL;
×
1212
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
13✔
1213
        size_t in_allocsize, out_allocsize;
13✔
1214
        size_t last_result = 0;
13✔
1215
        uint64_t left = max_bytes, in_bytes = 0;
13✔
1216
        int r;
13✔
1217

1218
        r = dlopen_zstd();
13✔
1219
        if (r < 0)
13✔
1220
                return r;
1221
        /* Create the context and buffers */
1222
        in_allocsize = sym_ZSTD_DStreamInSize();
13✔
1223
        out_allocsize = sym_ZSTD_DStreamOutSize();
13✔
1224
        in_buff = malloc(in_allocsize);
13✔
1225
        out_buff = malloc(out_allocsize);
13✔
1226
        dctx = sym_ZSTD_createDCtx();
13✔
1227
        if (!dctx || !out_buff || !in_buff)
13✔
1228
                return -ENOMEM;
1229

1230
        /* This loop assumes that the input file is one or more concatenated
1231
         * zstd streams. This example won't work if there is trailing non-zstd
1232
         * data at the end, but streaming decompression in general handles this
1233
         * case. ZSTD_decompressStream() returns 0 exactly when the frame is
1234
         * completed, and doesn't consume input after the frame.
1235
         */
1236
        for (;;) {
69✔
1237
                bool has_error = false;
41✔
1238
                ZSTD_inBuffer input = {
41✔
1239
                        .src = in_buff,
1240
                        .size = 0,
1241
                        .pos = 0
1242
                };
1243
                ssize_t red;
41✔
1244

1245
                red = loop_read(fdf, in_buff, in_allocsize, true);
41✔
1246
                if (red < 0)
41✔
1247
                        return red;
2✔
1248
                if (red == 0)
41✔
1249
                        break;
1250

1251
                in_bytes += (size_t) red;
31✔
1252
                input.size = (size_t) red;
31✔
1253
                input.pos = 0;
31✔
1254

1255
                /* Given a valid frame, zstd won't consume the last byte of the
1256
                 * frame until it has flushed all of the decompressed data of
1257
                 * the frame. So input.pos < input.size means frame is not done
1258
                 * or there is still output available.
1259
                 */
1260
                while (input.pos < input.size) {
266✔
1261
                        ZSTD_outBuffer output = {
238✔
1262
                                .dst = out_buff,
1263
                                .size = out_allocsize,
1264
                                .pos = 0
1265
                        };
1266
                        ssize_t wrote;
238✔
1267
                        /* The return code is zero if the frame is complete, but
1268
                         * there may be multiple frames concatenated together.
1269
                         * Zstd will automatically reset the context when a
1270
                         * frame is complete. Still, calling ZSTD_DCtx_reset()
1271
                         * can be useful to reset the context to a clean state,
1272
                         * for instance if the last decompression call returned
1273
                         * an error.
1274
                         */
1275
                        last_result = sym_ZSTD_decompressStream(dctx, &output, &input);
238✔
1276
                        if (sym_ZSTD_isError(last_result)) {
238✔
1277
                                has_error = true;
1✔
1278
                                break;
1✔
1279
                        }
1280

1281
                        if (left < output.pos)
237✔
1282
                                return -EFBIG;
2✔
1283

1284
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
236✔
1285
                        if (wrote < 0)
236✔
1286
                                return wrote;
1287

1288
                        left -= output.pos;
235✔
1289
                }
1290
                if (has_error)
29✔
1291
                        break;
1292
        }
1293

1294
        if (in_bytes == 0)
11✔
1295
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1296

1297
        if (last_result != 0) {
11✔
1298
                /* The last return value from ZSTD_decompressStream did not end
1299
                 * on a frame, but we reached the end of the file! We assume
1300
                 * this is an error, and the input was truncated.
1301
                 */
1302
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(last_result));
1✔
1303
                return zstd_ret_to_errno(last_result);
1✔
1304
        }
1305

1306
        if (in_bytes == 0)
10✔
1307
                log_debug("ZSTD decompression finished (no input data)");
1308
        else
1309
                log_debug("ZSTD decompression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
10✔
1310
                          in_bytes,
1311
                          max_bytes - left,
1312
                          (double) (max_bytes - left) / in_bytes * 100);
1313
        return 0;
1314
#else
1315
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1316
                               "Cannot decompress file. Compiled without ZSTD support.");
1317
#endif
1318
}
1319

1320
int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes) {
10✔
1321

1322
        if (endswith(filename, ".lz4"))
10✔
1323
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1324
        if (endswith(filename, ".xz"))
10✔
1325
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1326
        if (endswith(filename, ".zst"))
10✔
1327
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1328

1329
        return -EPROTONOSUPPORT;
1330
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc