Coverage Report

Created: 2026-11-12 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/xz/src/liblzma/common/stream_decoder_mt.c
Line
Count
Source
1
// SPDX-License-Identifier: 0BSD
2
3
///////////////////////////////////////////////////////////////////////////////
4
//
5
/// \file       stream_decoder_mt.c
6
/// \brief      Multithreaded .xz Stream decoder
7
//
8
//  Authors:    Sebastian Andrzej Siewior
9
//              Lasse Collin
10
//
11
///////////////////////////////////////////////////////////////////////////////
12
13
#include "common.h"
14
#include "block_decoder.h"
15
#include "stream_decoder.h"
16
#include "index.h"
17
#include "outqueue.h"
18
19
20
typedef enum {
21
  /// Waiting for work.
22
  /// Main thread may change this to THR_RUN or THR_EXIT.
23
  THR_IDLE,
24
25
  /// Decoding is in progress.
26
  /// Main thread may change this to THR_IDLE or THR_EXIT.
27
  /// The worker thread may change this to THR_IDLE.
28
  THR_RUN,
29
30
  /// The main thread wants the thread to exit.
31
  THR_EXIT,
32
33
} worker_state;
34
35
36
struct worker_thread {
37
  /// Worker state is protected with our mutex.
38
  worker_state state;
39
40
  /// Input buffer that will contain the whole Block except Block Header.
41
  uint8_t *in;
42
43
  /// Amount of memory allocated for "in"
44
  size_t in_size;
45
46
  /// Number of bytes written to "in" by the main thread
47
  size_t in_filled;
48
49
  /// Number of bytes consumed from "in" by the worker thread.
50
  size_t in_pos;
51
52
  /// Amount of uncompressed data that has been decoded. This local
53
  /// copy is needed because updating outbuf->pos requires locking
54
  /// the main mutex (coder->mutex).
55
  size_t out_pos;
56
57
  /// Pointer to the main structure is needed to (1) lock the main
58
  /// mutex (coder->mutex) when updating outbuf->pos and (2) when
59
  /// putting this thread back to the stack of free threads.
60
  struct lzma_stream_coder *coder;
61
62
  /// The allocator is set by the main thread. Since a copy of the
63
  /// pointer is kept here, the application must not change the
64
  /// allocator before calling lzma_end().
65
  const lzma_allocator *allocator;
66
67
  /// Output queue buffer to which the uncompressed data is written.
68
  lzma_outbuf *outbuf;
69
70
  /// Amount of compressed data that has already been decompressed.
71
  /// This is updated from in_pos when our mutex is locked.
72
  /// This is size_t, not uint64_t, because per-thread progress
73
  /// is limited to sizes of allocated buffers.
74
  size_t progress_in;
75
76
  /// Like progress_in but for uncompressed data.
77
  size_t progress_out;
78
79
  /// Updating outbuf->pos requires locking the main mutex
80
  /// (coder->mutex). Since the main thread will only read output
81
  /// from the oldest outbuf in the queue, only the worker thread
82
  /// that is associated with the oldest outbuf needs to update its
83
  /// outbuf->pos. This avoids useless mutex contention that would
84
  /// happen if all worker threads were frequently locking the main
85
  /// mutex to update their outbuf->pos.
86
  ///
87
  /// When partial_update_enabled is true, this worker thread will
88
  /// update outbuf->pos and outbuf->decoder_in_pos after each call
89
  /// to the Block decoder. This is initially false. Main thread may
90
  /// set this to true.
91
  bool partial_update_enabled;
92
93
  /// Once the main thread has set partial_updated_enabled = true,
94
  /// we will do the first partial update as soon as we can and
95
  /// set partial_update_started = true. After the first update,
96
  /// we only update if we have made progress. This avoids useless
97
  /// locking of thr->coder->mutex.
98
  bool partial_update_started;
99
100
  /// Block decoder
101
  lzma_next_coder block_decoder;
102
103
  /// Thread-specific Block options are needed because the Block
104
  /// decoder modifies the struct given to it at initialization.
105
  lzma_block block_options;
106
107
  /// Filter chain memory usage
108
  uint64_t mem_filters;
109
110
  /// Next structure in the stack of free worker threads.
111
  struct worker_thread *next;
112
113
  mythread_mutex mutex;
114
  mythread_cond cond;
115
116
  /// The ID of this thread is used to join the thread
117
  /// when it's not needed anymore.
118
  mythread thread_id;
119
};
120
121
122
struct lzma_stream_coder {
123
  enum {
124
    SEQ_STREAM_HEADER,
125
    SEQ_BLOCK_HEADER,
126
    SEQ_BLOCK_INIT,
127
    SEQ_BLOCK_THR_INIT,
128
    SEQ_BLOCK_THR_RUN,
129
    SEQ_BLOCK_DIRECT_INIT,
130
    SEQ_BLOCK_DIRECT_RUN,
131
    SEQ_INDEX_WAIT_OUTPUT,
132
    SEQ_INDEX_DECODE,
133
    SEQ_STREAM_FOOTER,
134
    SEQ_STREAM_PADDING,
135
    SEQ_ERROR,
136
  } sequence;
137
138
  /// Block decoder
139
  lzma_next_coder block_decoder;
140
141
  /// Every Block Header will be decoded into this structure.
142
  /// This is also used to initialize a Block decoder when in
143
  /// direct mode. In threaded mode, a thread-specific copy will
144
  /// be made for decoder initialization because the Block decoder
145
  /// will modify the structure given to it.
146
  lzma_block block_options;
147
148
  /// Buffer to hold a filter chain for Block Header decoding and
149
  /// initialization. These are freed after successful Block decoder
150
  /// initialization or at stream_decoder_mt_end(). The thread-specific
151
  /// copy of block_options won't hold a pointer to filters[] after
152
  /// initialization.
153
  lzma_filter filters[LZMA_FILTERS_MAX + 1];
154
155
  /// Stream Flags from Stream Header
156
  lzma_stream_flags stream_flags;
157
158
  /// Index is hashed so that it can be compared to the sizes of Blocks
159
  /// with O(1) memory usage.
160
  lzma_index_hash *index_hash;
161
162
163
  /// Maximum wait time if cannot use all the input and cannot
164
  /// fill the output buffer. This is in milliseconds.
165
  uint32_t timeout;
166
167
168
  /// Error code from a worker thread.
169
  ///
170
  /// \note       Use mutex.
171
  lzma_ret thread_error;
172
173
  /// Error code to return after pending output has been copied out. If
174
  /// set in read_output_and_wait(), this is a mirror of thread_error.
175
  /// If set in stream_decode_mt() then it's, for example, error that
176
  /// occurred when decoding Block Header.
177
  lzma_ret pending_error;
178
179
  /// Number of threads that will be created at maximum.
180
  uint32_t threads_max;
181
182
  /// Number of thread structures that have been initialized from
183
  /// "threads", and thus the number of worker threads actually
184
  /// created so far.
185
  uint32_t threads_initialized;
186
187
  /// Array of allocated thread-specific structures. When no threads
188
  /// are in use (direct mode) this is NULL. In threaded mode this
189
  /// points to an array of threads_max number of worker_thread structs.
190
  struct worker_thread *threads;
191
192
  /// Stack of free threads. When a thread finishes, it puts itself
193
  /// back into this stack. This starts as empty because threads
194
  /// are created only when actually needed.
195
  ///
196
  /// \note       Use mutex.
197
  struct worker_thread *threads_free;
198
199
  /// The most recent worker thread to which the main thread writes
200
  /// the new input from the application.
201
  struct worker_thread *thr;
202
203
  /// Output buffer queue for decompressed data from the worker threads
204
  ///
205
  /// \note       Use mutex with operations that need it.
206
  lzma_outq outq;
207
208
  mythread_mutex mutex;
209
  mythread_cond cond;
210
211
212
  /// Memory usage that will not be exceeded in multi-threaded mode.
213
  /// Single-threaded mode can exceed this even by a large amount.
214
  uint64_t memlimit_threading;
215
216
  /// Memory usage limit that should never be exceeded.
217
  /// LZMA_MEMLIMIT_ERROR will be returned if decoding isn't possible
218
  /// even in single-threaded mode without exceeding this limit.
219
  uint64_t memlimit_stop;
220
221
  /// Amount of memory in use by the direct mode decoder
222
  /// (coder->block_decoder). In threaded mode this is 0.
223
  uint64_t mem_direct_mode;
224
225
  /// Amount of memory needed by the running worker threads.
226
  /// This doesn't include the memory needed by the output buffer.
227
  ///
228
  /// \note       Use mutex.
229
  uint64_t mem_in_use;
230
231
  /// Amount of memory used by the idle (cached) threads.
232
  ///
233
  /// \note       Use mutex.
234
  uint64_t mem_cached;
235
236
237
  /// Amount of memory needed for the filter chain of the next Block.
238
  uint64_t mem_next_filters;
239
240
  /// Amount of memory needed for the thread-specific input buffer
241
  /// for the next Block.
242
  uint64_t mem_next_in;
243
244
  /// Amount of memory actually needed to decode the next Block
245
  /// in threaded mode. This is
246
  /// mem_next_filters + mem_next_in + memory needed for lzma_outbuf.
247
  uint64_t mem_next_block;
248
249
250
  /// Amount of compressed data in Stream Header + Blocks that have
251
  /// already been finished.
252
  ///
253
  /// \note       Use mutex when worker threads might be active.
254
  uint64_t progress_in;
255
256
  /// Amount of uncompressed data in Blocks that have already
257
  /// been finished.
258
  ///
259
  /// \note       Use mutex when worker threads might be active.
260
  uint64_t progress_out;
261
262
263
  /// If true, LZMA_NO_CHECK is returned if the Stream has
264
  /// no integrity check.
265
  bool tell_no_check;
266
267
  /// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
268
  /// an integrity check that isn't supported by this liblzma build.
269
  bool tell_unsupported_check;
270
271
  /// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
272
  bool tell_any_check;
273
274
  /// If true, we will tell the Block decoder to skip calculating
275
  /// and verifying the integrity check.
276
  bool ignore_check;
277
278
  /// If true, we will decode concatenated Streams that possibly have
279
  /// Stream Padding between or after them. LZMA_STREAM_END is returned
280
  /// once the application isn't giving us any new input (LZMA_FINISH),
281
  /// and we aren't in the middle of a Stream, and possible
282
  /// Stream Padding is a multiple of four bytes.
283
  bool concatenated;
284
285
  /// If true, we will return any errors immediately instead of first
286
  /// producing all output before the location of the error.
287
  bool fail_fast;
288
289
290
  /// When decoding concatenated Streams, this is true as long as we
291
  /// are decoding the first Stream. This is needed to avoid misleading
292
  /// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
293
  /// bytes.
294
  bool first_stream;
295
296
  /// This is used to track if the previous call to stream_decode_mt()
297
  /// had output space (*out_pos < out_size) and managed to fill the
298
  /// output buffer (*out_pos == out_size). This may be set to true
299
  /// in read_output_and_wait(). This is read and then reset to false
300
  /// at the beginning of stream_decode_mt().
301
  ///
302
  /// This is needed to support applications that call lzma_code() in
303
  /// such a way that more input is provided only when lzma_code()
304
  /// didn't fill the output buffer completely. Basically, this makes
305
  /// it easier to convert such applications from single-threaded
306
  /// decoder to multi-threaded decoder.
307
  bool out_was_filled;
308
309
  /// Write position in buffer[] and position in Stream Padding
310
  size_t pos;
311
312
  /// Buffer to hold Stream Header, Block Header, and Stream Footer.
313
  /// Block Header has biggest maximum size.
314
  uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
315
};
316
317
318
/// Enables updating of outbuf->pos. This is a callback function that is
319
/// used with lzma_outq_enable_partial_output().
320
static void
321
worker_enable_partial_update(void *thr_ptr)
322
419k
{
323
419k
  struct worker_thread *thr = thr_ptr;
324
325
419k
  mythread_sync(thr->mutex) {
326
419k
    thr->partial_update_enabled = true;
327
419k
    mythread_cond_signal(&thr->cond);
328
419k
  }
329
419k
}
330
331
332
static MYTHREAD_RET_TYPE
333
worker_decoder(void *thr_ptr)
334
78.1k
{
335
78.1k
  struct worker_thread *thr = thr_ptr;
336
78.1k
  size_t in_filled;
337
78.1k
  bool partial_update_enabled;
338
78.1k
  lzma_ret ret;
339
340
512k
next_loop_lock:
341
342
512k
  mythread_mutex_lock(&thr->mutex);
343
950k
next_loop_unlocked:
344
345
950k
  if (thr->state == THR_IDLE) {
346
436k
    mythread_cond_wait(&thr->cond, &thr->mutex);
347
436k
    goto next_loop_unlocked;
348
436k
  }
349
350
514k
  if (thr->state == THR_EXIT) {
351
78.1k
    mythread_mutex_unlock(&thr->mutex);
352
353
78.1k
    lzma_free(thr->in, thr->allocator);
354
78.1k
    lzma_next_end(&thr->block_decoder, thr->allocator);
355
356
78.1k
    mythread_mutex_destroy(&thr->mutex);
357
78.1k
    mythread_cond_destroy(&thr->cond);
358
359
78.1k
    return MYTHREAD_RET_VALUE;
360
78.1k
  }
361
362
514k
  assert(thr->state == THR_RUN);
363
364
  // Update progress info for get_progress().
365
436k
  thr->progress_in = thr->in_pos;
366
436k
  thr->progress_out = thr->out_pos;
367
368
  // If we don't have any new input, wait for a signal from the main
369
  // thread except if partial output has just been enabled
370
  // (partial_update_enabled is true but _started is false). In that
371
  // case we will do one normal run so that the partial output info
372
  // gets passed to the main thread. The call to block_decoder.code()
373
  // is useless but harmless as it can occur only once per Block.
374
436k
  in_filled = thr->in_filled;
375
436k
  partial_update_enabled = thr->partial_update_enabled;
376
377
436k
  if (in_filled == thr->in_pos && !(partial_update_enabled
378
1.85k
      && !thr->partial_update_started)) {
379
1.85k
    mythread_cond_wait(&thr->cond, &thr->mutex);
380
1.85k
    goto next_loop_unlocked;
381
1.85k
  }
382
383
434k
  mythread_mutex_unlock(&thr->mutex);
384
385
  // Pass the input in small chunks to the Block decoder.
386
  // This way we react reasonably fast if we are told to stop/exit,
387
  // and (when partial update is enabled) we tell about our progress
388
  // to the main thread frequently enough.
389
434k
  const size_t chunk_size = 16384;
390
434k
  if ((in_filled - thr->in_pos) > chunk_size)
391
891
    in_filled = thr->in_pos + chunk_size;
392
393
434k
  ret = thr->block_decoder.code(
394
434k
      thr->block_decoder.coder, thr->allocator,
395
434k
      thr->in, &thr->in_pos, in_filled,
396
434k
      thr->outbuf->buf, &thr->out_pos,
397
434k
      thr->outbuf->allocated, LZMA_RUN);
398
399
434k
  if (ret == LZMA_OK) {
400
2.14k
    if (partial_update_enabled) {
401
      // Remember that we have done at least one partial
402
      // update. After the first update we won't do updates
403
      // unless we have made progress.
404
2.05k
      thr->partial_update_started = true;
405
406
      // The main thread is reading decompressed data
407
      // from thr->outbuf. Tell the main thread about
408
      // our progress.
409
      //
410
      // NOTE: It's possible that we consumed input without
411
      // producing any new output so it's possible that only
412
      // in_pos has changed. If thr->partial_update_started
413
      // was false, it is possible that neither in_pos nor
414
      // out_pos has changed.
415
2.05k
      mythread_sync(thr->coder->mutex) {
416
2.05k
        thr->outbuf->pos = thr->out_pos;
417
2.05k
        thr->outbuf->decoder_in_pos = thr->in_pos;
418
2.05k
        mythread_cond_signal(&thr->coder->cond);
419
2.05k
      }
420
2.05k
    }
421
422
2.14k
    goto next_loop_lock;
423
2.14k
  }
424
425
  // Either we finished successfully (LZMA_STREAM_END) or an error
426
  // occurred.
427
  //
428
  // The sizes are in the Block Header and the Block decoder
429
  // checks that they match, thus we know these:
430
434k
  assert(ret != LZMA_STREAM_END || thr->in_pos == thr->in_size);
431
432k
  assert(ret != LZMA_STREAM_END
432
432k
    || thr->out_pos == thr->block_options.uncompressed_size);
433
434
432k
  mythread_sync(thr->mutex) {
435
    // Block decoder ensures this, but do a sanity check anyway
436
    // because thr->in_filled < thr->in_size means that the main
437
    // thread is still writing to thr->in.
438
432k
    if (ret == LZMA_STREAM_END && thr->in_filled != thr->in_size) {
439
0
      assert(0);
440
0
      ret = LZMA_PROG_ERROR;
441
0
    }
442
443
432k
    if (thr->state != THR_EXIT)
444
432k
      thr->state = THR_IDLE;
445
432k
  }
446
447
  // Free the input buffer. Don't update in_size as we need
448
  // it later to update thr->coder->mem_in_use.
449
  //
450
  // This step is skipped if an error occurred because the main thread
451
  // might still be writing to thr->in. The memory will be freed after
452
  // threads_end() sets thr->state = THR_EXIT.
453
432k
  if (ret == LZMA_STREAM_END) {
454
430k
    lzma_free(thr->in, thr->allocator);
455
430k
    thr->in = NULL;
456
430k
  }
457
458
432k
  mythread_sync(thr->coder->mutex) {
459
    // Move our progress info to the main thread.
460
432k
    thr->coder->progress_in += thr->in_pos;
461
432k
    thr->coder->progress_out += thr->out_pos;
462
432k
    thr->progress_in = 0;
463
432k
    thr->progress_out = 0;
464
465
    // Mark the outbuf as finished.
466
432k
    thr->outbuf->pos = thr->out_pos;
467
432k
    thr->outbuf->decoder_in_pos = thr->in_pos;
468
432k
    thr->outbuf->finished = true;
469
432k
    thr->outbuf->finish_ret = ret;
470
432k
    thr->outbuf = NULL;
471
472
    // If an error occurred, tell it to the main thread.
473
432k
    if (ret != LZMA_STREAM_END
474
1.79k
        && thr->coder->thread_error == LZMA_OK)
475
1.68k
      thr->coder->thread_error = ret;
476
477
    // Return the worker thread to the stack of available
478
    // threads only if no errors occurred.
479
432k
    if (ret == LZMA_STREAM_END) {
480
      // Update memory usage counters.
481
430k
      thr->coder->mem_in_use -= thr->in_size;
482
430k
      thr->coder->mem_in_use -= thr->mem_filters;
483
430k
      thr->coder->mem_cached += thr->mem_filters;
484
485
      // Put this thread to the stack of free threads.
486
430k
      thr->next = thr->coder->threads_free;
487
430k
      thr->coder->threads_free = thr;
488
430k
    }
489
490
432k
    mythread_cond_signal(&thr->coder->cond);
491
432k
  }
492
493
432k
  goto next_loop_lock;
494
432k
}
495
496
497
/// Tells the worker threads to exit and waits for them to terminate.
498
static void
499
threads_end(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
500
71.0k
{
501
149k
  for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
502
78.1k
    mythread_sync(coder->threads[i].mutex) {
503
78.1k
      coder->threads[i].state = THR_EXIT;
504
78.1k
      mythread_cond_signal(&coder->threads[i].cond);
505
78.1k
    }
506
78.1k
  }
507
508
149k
  for (uint32_t i = 0; i < coder->threads_initialized; ++i)
509
78.1k
    mythread_join(coder->threads[i].thread_id);
510
511
71.0k
  lzma_free(coder->threads, allocator);
512
71.0k
  coder->threads_initialized = 0;
513
71.0k
  coder->threads = NULL;
514
71.0k
  coder->threads_free = NULL;
515
516
  // The threads don't update these when they exit. Do it here.
517
71.0k
  coder->mem_in_use = 0;
518
71.0k
  coder->mem_cached = 0;
519
520
71.0k
  return;
521
71.0k
}
522
523
524
/// Tell worker threads to stop without doing any cleaning up.
525
/// The clean up will be done when threads_exit() is called;
526
/// it's not possible to reuse the threads after threads_stop().
527
///
528
/// This is called before returning an unrecoverable error code
529
/// to the application. It would be waste of processor time
530
/// to keep the threads running in such a situation.
531
static void
532
threads_stop(struct lzma_stream_coder *coder)
533
1.69k
{
534
3.83k
  for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
535
    // The threads that are in the THR_RUN state will stop
536
    // when they check the state the next time. There's no
537
    // need to signal coder->threads[i].cond.
538
2.14k
    mythread_sync(coder->threads[i].mutex) {
539
2.14k
      coder->threads[i].state = THR_IDLE;
540
2.14k
    }
541
2.14k
  }
542
543
1.69k
  return;
544
1.69k
}
545
546
547
/// Initialize a new worker_thread structure and create a new thread.
548
static lzma_ret
549
initialize_new_thread(struct lzma_stream_coder *coder,
550
    const lzma_allocator *allocator)
551
78.1k
{
552
  // Allocate the coder->threads array if needed. It's done here instead
553
  // of when initializing the decoder because we don't need this if we
554
  // use the direct mode (we may even free coder->threads in the middle
555
  // of the file if we switch from threaded to direct mode).
556
78.1k
  if (coder->threads == NULL) {
557
40.3k
    coder->threads = lzma_alloc(
558
40.3k
      coder->threads_max * sizeof(struct worker_thread),
559
40.3k
      allocator);
560
561
40.3k
    if (coder->threads == NULL)
562
3
      return LZMA_MEM_ERROR;
563
40.3k
  }
564
565
  // Pick a free structure.
566
78.1k
  assert(coder->threads_initialized < coder->threads_max);
567
78.1k
  struct worker_thread *thr
568
78.1k
      = &coder->threads[coder->threads_initialized];
569
570
78.1k
  if (mythread_mutex_init(&thr->mutex))
571
0
    goto error_mutex;
572
573
78.1k
  if (mythread_cond_init(&thr->cond))
574
0
    goto error_cond;
575
576
78.1k
  thr->state = THR_IDLE;
577
78.1k
  thr->in = NULL;
578
78.1k
  thr->in_size = 0;
579
78.1k
  thr->allocator = allocator;
580
78.1k
  thr->coder = coder;
581
78.1k
  thr->outbuf = NULL;
582
78.1k
  thr->block_decoder = LZMA_NEXT_CODER_INIT;
583
78.1k
  thr->mem_filters = 0;
584
585
78.1k
  if (mythread_create(&thr->thread_id, worker_decoder, thr))
586
0
    goto error_thread;
587
588
78.1k
  ++coder->threads_initialized;
589
78.1k
  coder->thr = thr;
590
591
78.1k
  return LZMA_OK;
592
593
0
error_thread:
594
0
  mythread_cond_destroy(&thr->cond);
595
596
0
error_cond:
597
0
  mythread_mutex_destroy(&thr->mutex);
598
599
0
error_mutex:
600
0
  return LZMA_MEM_ERROR;
601
0
}
602
603
604
static lzma_ret
605
get_thread(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
606
432k
{
607
  // If there is a free structure on the stack, use it.
608
432k
  mythread_sync(coder->mutex) {
609
432k
    if (coder->threads_free != NULL) {
610
354k
      coder->thr = coder->threads_free;
611
354k
      coder->threads_free = coder->threads_free->next;
612
613
      // The thread is no longer in the cache so subtract
614
      // it from the cached memory usage. Don't add it
615
      // to mem_in_use though; the caller will handle it
616
      // since it knows how much memory it will actually
617
      // use (the filter chain might change).
618
354k
      coder->mem_cached -= coder->thr->mem_filters;
619
354k
    }
620
432k
  }
621
622
432k
  if (coder->thr == NULL) {
623
78.1k
    assert(coder->threads_initialized < coder->threads_max);
624
625
    // Initialize a new thread.
626
78.1k
    return_if_error(initialize_new_thread(coder, allocator));
627
78.1k
  }
628
629
432k
  coder->thr->in_filled = 0;
630
432k
  coder->thr->in_pos = 0;
631
432k
  coder->thr->out_pos = 0;
632
633
432k
  coder->thr->progress_in = 0;
634
432k
  coder->thr->progress_out = 0;
635
636
432k
  coder->thr->partial_update_enabled = false;
637
432k
  coder->thr->partial_update_started = false;
638
639
432k
  return LZMA_OK;
640
432k
}
641
642
643
static lzma_ret
644
read_output_and_wait(struct lzma_stream_coder *coder,
645
    const lzma_allocator *allocator,
646
    uint8_t *restrict out, size_t *restrict out_pos,
647
    size_t out_size,
648
    bool *input_is_possible,
649
    bool waiting_allowed,
650
    mythread_condtime *wait_abs, bool *has_blocked)
651
964k
{
652
964k
  lzma_ret ret = LZMA_OK;
653
654
964k
  mythread_sync(coder->mutex) {
655
1.34M
    do {
656
      // Get as much output from the queue as is possible
657
      // without blocking.
658
1.34M
      const size_t out_start = *out_pos;
659
1.77M
      do {
660
1.77M
        ret = lzma_outq_read(&coder->outq, allocator,
661
1.77M
            out, out_pos, out_size,
662
1.77M
            NULL, NULL);
663
664
        // If a Block was finished, tell the worker
665
        // thread of the next Block (if it is still
666
        // running) to start telling the main thread
667
        // when new output is available.
668
1.77M
        if (ret == LZMA_STREAM_END)
669
430k
          lzma_outq_enable_partial_output(
670
430k
            &coder->outq,
671
430k
            &worker_enable_partial_update);
672
673
        // Loop until a Block wasn't finished.
674
        // It's important to loop around even if
675
        // *out_pos == out_size because there could
676
        // be an empty Block that will return
677
        // LZMA_STREAM_END without needing any
678
        // output space.
679
1.77M
      } while (ret == LZMA_STREAM_END);
680
681
      // Check if lzma_outq_read reported an error from
682
      // the Block decoder.
683
1.34M
      if (ret != LZMA_OK)
684
1.67k
        break;
685
686
      // If the output buffer is now full but it wasn't full
687
      // when this function was called, set out_was_filled.
688
      // This way the next call to stream_decode_mt() knows
689
      // that some output was produced and no output space
690
      // remained in the previous call to stream_decode_mt().
691
1.34M
      if (*out_pos == out_size && *out_pos != out_start)
692
17.1k
        coder->out_was_filled = true;
693
694
      // Check if any thread has indicated an error.
695
1.34M
      if (coder->thread_error != LZMA_OK) {
696
        // If LZMA_FAIL_FAST was used, report errors
697
        // from worker threads immediately.
698
10.5k
        if (coder->fail_fast) {
699
0
          ret = coder->thread_error;
700
0
          break;
701
0
        }
702
703
        // Otherwise set pending_error. The value we
704
        // set here will not actually get used other
705
        // than working as a flag that an error has
706
        // occurred. This is because in SEQ_ERROR
707
        // all output before the error will be read
708
        // first by calling this function, and once we
709
        // reach the location of the (first) error the
710
        // error code from the above lzma_outq_read()
711
        // will be returned to the application.
712
        //
713
        // Use LZMA_PROG_ERROR since the value should
714
        // never leak to the application. It's
715
        // possible that pending_error has already
716
        // been set but that doesn't matter: if we get
717
        // here, pending_error only works as a flag.
718
10.5k
        coder->pending_error = LZMA_PROG_ERROR;
719
10.5k
      }
720
721
      // Check if decoding of the next Block can be started.
722
      // The memusage of the active threads must be low
723
      // enough, there must be a free buffer slot in the
724
      // output queue, and there must be a free thread
725
      // (that can be either created or an existing one
726
      // reused).
727
      //
728
      // NOTE: This is checked after reading the output
729
      // above because reading the output can free a slot in
730
      // the output queue and also reduce active memusage.
731
      //
732
      // NOTE: If output queue is empty, then input will
733
      // always be possible.
734
1.34M
      if (input_is_possible != NULL
735
774k
          && coder->memlimit_threading
736
774k
            - coder->mem_in_use
737
774k
            - coder->outq.mem_in_use
738
774k
            >= coder->mem_next_block
739
445k
          && lzma_outq_has_buf(&coder->outq)
740
444k
          && (coder->threads_initialized
741
444k
              < coder->threads_max
742
358k
            || coder->threads_free
743
432k
              != NULL)) {
744
432k
        *input_is_possible = true;
745
432k
        break;
746
432k
      }
747
748
      // If the caller doesn't want us to block, return now.
749
912k
      if (!waiting_allowed)
750
444k
        break;
751
752
      // This check is needed only when input_is_possible
753
      // is NULL. We must return if we aren't waiting for
754
      // input to become possible and there is no more
755
      // output coming from the queue.
756
468k
      if (lzma_outq_is_empty(&coder->outq)) {
757
68.2k
        assert(input_is_possible == NULL);
758
68.2k
        break;
759
68.2k
      }
760
761
      // If there is more data available from the queue,
762
      // our out buffer must be full and we need to return
763
      // so that the application can provide more output
764
      // space.
765
      //
766
      // NOTE: In general lzma_outq_is_readable() can return
767
      // true also when there are no more bytes available.
768
      // This can happen when a Block has finished without
769
      // providing any new output. We know that this is not
770
      // the case because in the beginning of this loop we
771
      // tried to read as much as possible even when we had
772
      // no output space left and the mutex has been locked
773
      // all the time (so worker threads cannot have changed
774
      // anything). Thus there must be actual pending output
775
      // in the queue.
776
400k
      if (lzma_outq_is_readable(&coder->outq)) {
777
16.9k
        assert(*out_pos == out_size);
778
16.9k
        break;
779
16.9k
      }
780
781
      // If the application stops providing more input
782
      // in the middle of a Block, there will eventually
783
      // be one worker thread left that is stuck waiting for
784
      // more input (that might never arrive) and a matching
785
      // outbuf which the worker thread cannot finish due
786
      // to lack of input. We must detect this situation,
787
      // otherwise we would end up waiting indefinitely
788
      // (if no timeout is in use) or keep returning
789
      // LZMA_TIMED_OUT while making no progress. Thus, the
790
      // application would never get LZMA_BUF_ERROR from
791
      // lzma_code() which would tell the application that
792
      // no more progress is possible. No LZMA_BUF_ERROR
793
      // means that, for example, truncated .xz files could
794
      // cause an infinite loop.
795
      //
796
      // A worker thread doing partial updates will
797
      // store not only the output position in outbuf->pos
798
      // but also the matching input position in
799
      // outbuf->decoder_in_pos. Here we check if that
800
      // input position matches the amount of input that
801
      // the worker thread has been given (in_filled).
802
      // If so, we must return and not wait as no more
803
      // output will be coming without first getting more
804
      // input to the worker thread. If the application
805
      // keeps calling lzma_code() without providing more
806
      // input, it will eventually get LZMA_BUF_ERROR.
807
      //
808
      // NOTE: We can read partial_update_enabled and
809
      // in_filled without thr->mutex as only the main thread
810
      // modifies these variables. decoder_in_pos requires
811
      // coder->mutex which we are already holding.
812
383k
      if (coder->thr != NULL &&
813
1.71k
          coder->thr->partial_update_enabled) {
814
        // There is exactly one outbuf in the queue.
815
1.57k
        assert(coder->thr->outbuf == coder->outq.head);
816
1.57k
        assert(coder->thr->outbuf == coder->outq.tail);
817
818
1.57k
        if (coder->thr->outbuf->decoder_in_pos
819
1.57k
            == coder->thr->in_filled)
820
621
          break;
821
1.57k
      }
822
823
      // Wait for input or output to become possible.
824
382k
      if (coder->timeout != 0) {
825
        // See the comment in stream_encoder_mt.c
826
        // about why mythread_condtime_set() is used
827
        // like this.
828
        //
829
        // FIXME?
830
        // In contrast to the encoder, this calls
831
        // _condtime_set while the mutex is locked.
832
0
        if (!*has_blocked) {
833
0
          *has_blocked = true;
834
0
          mythread_condtime_set(wait_abs,
835
0
              &coder->cond,
836
0
              coder->timeout);
837
0
        }
838
839
0
        if (mythread_cond_timedwait(&coder->cond,
840
0
            &coder->mutex,
841
0
            wait_abs) != 0) {
842
0
          ret = LZMA_TIMED_OUT;
843
0
          break;
844
0
        }
845
382k
      } else {
846
382k
        mythread_cond_wait(&coder->cond,
847
382k
            &coder->mutex);
848
382k
      }
849
382k
    } while (ret == LZMA_OK);
850
964k
  }
851
852
  // If we are returning an error, then the application cannot get
853
  // more output from us and thus keeping the threads running is
854
  // useless and waste of CPU time.
855
964k
  if (ret != LZMA_OK && ret != LZMA_TIMED_OUT)
856
1.67k
    threads_stop(coder);
857
858
964k
  return ret;
859
964k
}
860
861
862
static lzma_ret
863
decode_block_header(struct lzma_stream_coder *coder,
864
    const lzma_allocator *allocator, const uint8_t *restrict in,
865
    size_t *restrict in_pos, size_t in_size)
866
505k
{
867
505k
  if (*in_pos >= in_size)
868
510
    return LZMA_OK;
869
870
505k
  if (coder->pos == 0) {
871
    // Detect if it's Index.
872
502k
    if (in[*in_pos] == INDEX_INDICATOR)
873
19.9k
      return LZMA_INDEX_DETECTED;
874
875
    // Calculate the size of the Block Header. Note that
876
    // Block Header decoder wants to see this byte too
877
    // so don't advance *in_pos.
878
482k
    coder->block_options.header_size
879
482k
        = lzma_block_header_size_decode(
880
482k
          in[*in_pos]);
881
482k
  }
882
883
  // Copy the Block Header to the internal buffer.
884
485k
  lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
885
485k
      coder->block_options.header_size);
886
887
  // Return if we didn't get the whole Block Header yet.
888
485k
  if (coder->pos < coder->block_options.header_size)
889
3.37k
    return LZMA_OK;
890
891
481k
  coder->pos = 0;
892
893
  // Version 1 is needed to support the .ignore_check option.
894
481k
  coder->block_options.version = 1;
895
896
  // Block Header decoder will initialize all members of this array
897
  // so we don't need to do it here.
898
481k
  coder->block_options.filters = coder->filters;
899
900
  // Decode the Block Header.
901
481k
  return_if_error(lzma_block_header_decode(&coder->block_options,
902
481k
      allocator, coder->buffer));
903
904
  // If LZMA_IGNORE_CHECK was used, this flag needs to be set.
905
  // It has to be set after lzma_block_header_decode() because
906
  // it always resets this to false.
907
481k
  coder->block_options.ignore_check = coder->ignore_check;
908
909
  // coder->block_options is ready now.
910
481k
  return LZMA_STREAM_END;
911
481k
}
912
913
914
/// Get the size of the Compressed Data + Block Padding + Check.
915
static size_t
916
comp_blk_size(const struct lzma_stream_coder *coder)
917
440k
{
918
440k
  return vli_ceil4(coder->block_options.compressed_size)
919
440k
      + lzma_check_size(coder->stream_flags.check);
920
440k
}
921
922
923
/// Returns true if the size (compressed or uncompressed) is such that
924
/// threaded decompression cannot be used. Sizes that are too big compared
925
/// to SIZE_MAX must be rejected to avoid integer overflows and truncations
926
/// when lzma_vli is assigned to a size_t.
927
static bool
928
is_direct_mode_needed(lzma_vli size)
929
921k
{
930
921k
  return size == LZMA_VLI_UNKNOWN || size > SIZE_MAX / 3;
931
921k
}
932
933
934
static lzma_ret
935
stream_decoder_reset(struct lzma_stream_coder *coder,
936
    const lzma_allocator *allocator)
937
36.4k
{
938
  // Initialize the Index hash used to verify the Index.
939
36.4k
  coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
940
36.4k
  if (coder->index_hash == NULL)
941
32
    return LZMA_MEM_ERROR;
942
943
  // Reset the rest of the variables.
944
36.4k
  coder->sequence = SEQ_STREAM_HEADER;
945
36.4k
  coder->pos = 0;
946
947
36.4k
  return LZMA_OK;
948
36.4k
}
949
950
951
static lzma_ret
952
stream_decode_mt(void *coder_ptr, const lzma_allocator *allocator,
953
     const uint8_t *restrict in, size_t *restrict in_pos,
954
     size_t in_size,
955
     uint8_t *restrict out, size_t *restrict out_pos,
956
     size_t out_size, lzma_action action)
957
98.8k
{
958
98.8k
  struct lzma_stream_coder *coder = coder_ptr;
959
960
98.8k
  mythread_condtime wait_abs;
961
98.8k
  bool has_blocked = false;
962
963
  // Determine if in SEQ_BLOCK_HEADER and SEQ_BLOCK_THR_RUN we should
964
  // tell read_output_and_wait() to wait until it can fill the output
965
  // buffer (or a timeout occurs). Two conditions must be met:
966
  //
967
  // (1) If the caller provided no new input. The reason for this
968
  //     can be, for example, the end of the file or that there is
969
  //     a pause in the input stream and more input is available
970
  //     a little later. In this situation we should wait for output
971
  //     because otherwise we would end up in a busy-waiting loop where
972
  //     we make no progress and the application just calls us again
973
  //     without providing any new input. This would then result in
974
  //     LZMA_BUF_ERROR even though more output would be available
975
  //     once the worker threads decode more data.
976
  //
977
  // (2) Even if (1) is true, we will not wait if the previous call to
978
  //     this function managed to produce some output and the output
979
  //     buffer became full. This is for compatibility with applications
980
  //     that call lzma_code() in such a way that new input is provided
981
  //     only when the output buffer didn't become full. Without this
982
  //     trick such applications would have bad performance (bad
983
  //     parallelization due to decoder not getting input fast enough).
984
  //
985
  //     NOTE: Such loops might require that timeout is disabled (0)
986
  //     if they assume that output-not-full implies that all input has
987
  //     been consumed. If and only if timeout is enabled, we may return
988
  //     when output isn't full *and* not all input has been consumed.
989
  //
990
  // However, if LZMA_FINISH is used, the above is ignored and we always
991
  // wait (timeout can still cause us to return) because we know that
992
  // we won't get any more input. This matters if the input file is
993
  // truncated and we are doing single-shot decoding, that is,
994
  // timeout = 0 and LZMA_FINISH is used on the first call to
995
  // lzma_code() and the output buffer is known to be big enough
996
  // to hold all uncompressed data:
997
  //
998
  //   - If LZMA_FINISH wasn't handled specially, we could return
999
  //     LZMA_OK before providing all output that is possible with the
1000
  //     truncated input. The rest would be available if lzma_code() was
1001
  //     called again but then it's not single-shot decoding anymore.
1002
  //
1003
  //   - By handling LZMA_FINISH specially here, the first call will
1004
  //     produce all the output, matching the behavior of the
1005
  //     single-threaded decoder.
1006
  //
1007
  // So it's a very specific corner case but also easy to avoid. Note
1008
  // that this special handling of LZMA_FINISH has no effect for
1009
  // single-shot decoding when the input file is valid (not truncated);
1010
  // premature LZMA_OK wouldn't be possible as long as timeout = 0.
1011
98.8k
  const bool waiting_allowed = action == LZMA_FINISH
1012
52.7k
      || (*in_pos == in_size && !coder->out_was_filled);
1013
98.8k
  coder->out_was_filled = false;
1014
1015
98.8k
  while (true)
1016
663k
  switch (coder->sequence) {
1017
47.8k
  case SEQ_STREAM_HEADER: {
1018
    // Copy the Stream Header to the internal buffer.
1019
47.8k
    const size_t in_old = *in_pos;
1020
47.8k
    lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
1021
47.8k
        LZMA_STREAM_HEADER_SIZE);
1022
47.8k
    coder->progress_in += *in_pos - in_old;
1023
1024
    // Return if we didn't get the whole Stream Header yet.
1025
47.8k
    if (coder->pos < LZMA_STREAM_HEADER_SIZE)
1026
19.0k
      return LZMA_OK;
1027
1028
28.8k
    coder->pos = 0;
1029
1030
    // Decode the Stream Header.
1031
28.8k
    const lzma_ret ret = lzma_stream_header_decode(
1032
28.8k
        &coder->stream_flags, coder->buffer);
1033
28.8k
    if (ret != LZMA_OK)
1034
3.04k
      return ret == LZMA_FORMAT_ERROR && !coder->first_stream
1035
3.04k
          ? LZMA_DATA_ERROR : ret;
1036
1037
    // If we are decoding concatenated Streams, and the later
1038
    // Streams have invalid Header Magic Bytes, we give
1039
    // LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
1040
25.7k
    coder->first_stream = false;
1041
1042
    // Copy the type of the Check so that Block Header and Block
1043
    // decoders see it.
1044
25.7k
    coder->block_options.check = coder->stream_flags.check;
1045
1046
    // Even if we return LZMA_*_CHECK below, we want
1047
    // to continue from Block Header decoding.
1048
25.7k
    coder->sequence = SEQ_BLOCK_HEADER;
1049
1050
    // Detect if there's no integrity check or if it is
1051
    // unsupported if those were requested by the application.
1052
25.7k
    if (coder->tell_no_check && coder->stream_flags.check
1053
0
        == LZMA_CHECK_NONE)
1054
0
      return LZMA_NO_CHECK;
1055
1056
25.7k
    if (coder->tell_unsupported_check
1057
0
        && !lzma_check_is_supported(
1058
0
          coder->stream_flags.check))
1059
0
      return LZMA_UNSUPPORTED_CHECK;
1060
1061
25.7k
    if (coder->tell_any_check)
1062
0
      return LZMA_GET_CHECK;
1063
1064
25.7k
    FALLTHROUGH;
1065
25.7k
  }
1066
1067
505k
  case SEQ_BLOCK_HEADER: {
1068
505k
    const size_t in_old = *in_pos;
1069
505k
    const lzma_ret ret = decode_block_header(coder, allocator,
1070
505k
        in, in_pos, in_size);
1071
1072
    // Worker threads may finish earlier Blocks and need to update
1073
    // coder->progress_in at the same time with us.
1074
505k
    mythread_sync(coder->mutex) {
1075
505k
      coder->progress_in += *in_pos - in_old;
1076
505k
    }
1077
1078
505k
    if (ret == LZMA_OK) {
1079
      // We didn't decode the whole Block Header yet.
1080
      //
1081
      // Read output from the queue before returning. This
1082
      // is important because it is possible that the
1083
      // application doesn't have any new input available
1084
      // immediately. If we didn't try to copy output from
1085
      // the output queue here, lzma_code() could end up
1086
      // returning LZMA_BUF_ERROR even though queued output
1087
      // is available.
1088
      //
1089
      // If the lzma_code() call provided at least one input
1090
      // byte, only copy as much data from the output queue
1091
      // as is available immediately. This way the
1092
      // application will be able to provide more input
1093
      // without a delay.
1094
      //
1095
      // On the other hand, if lzma_code() was called with
1096
      // an empty input buffer(*), treat it specially: try
1097
      // to fill the output buffer even if it requires
1098
      // waiting for the worker threads to provide output
1099
      // (timeout, if specified, can still cause us to
1100
      // return).
1101
      //
1102
      //   - This way the application will be able to get all
1103
      //     data that can be decoded from the input provided
1104
      //     so far.
1105
      //
1106
      //   - We avoid both premature LZMA_BUF_ERROR and
1107
      //     busy-waiting where the application repeatedly
1108
      //     calls lzma_code() which immediately returns
1109
      //     LZMA_OK without providing new data.
1110
      //
1111
      //   - If the queue becomes empty, we won't wait
1112
      //     anything and will return LZMA_OK immediately
1113
      //     (coder->timeout is completely ignored).
1114
      //
1115
      // (*) See the comment at the beginning of this
1116
      //     function how waiting_allowed is determined
1117
      //     and why there is an exception to the rule
1118
      //     of "called with an empty input buffer".
1119
3.88k
      assert(*in_pos == in_size);
1120
1121
      // If LZMA_FINISH was used we know that we won't get
1122
      // more input, so the file must be truncated if we
1123
      // get here. If worker threads don't detect any
1124
      // errors, eventually there will be no more output
1125
      // while we keep returning LZMA_OK which gets
1126
      // converted to LZMA_BUF_ERROR in lzma_code().
1127
      //
1128
      // If fail-fast is enabled then we will return
1129
      // immediately using LZMA_DATA_ERROR instead of
1130
      // LZMA_OK or LZMA_BUF_ERROR. Rationale for the
1131
      // error code:
1132
      //
1133
      //   - Worker threads may have a large amount of
1134
      //     not-yet-decoded input data and we don't
1135
      //     know for sure if all data is valid. Bad
1136
      //     data there would result in LZMA_DATA_ERROR
1137
      //     when fail-fast isn't used.
1138
      //
1139
      //   - Immediate LZMA_BUF_ERROR would be a bit weird
1140
      //     considering the older liblzma code. lzma_code()
1141
      //     even has an assertion to prevent coders from
1142
      //     returning LZMA_BUF_ERROR directly.
1143
      //
1144
      // The downside of this is that with fail-fast apps
1145
      // cannot always distinguish between corrupt and
1146
      // truncated files.
1147
3.88k
      if (action == LZMA_FINISH && coder->fail_fast) {
1148
        // We won't produce any more output. Stop
1149
        // the unfinished worker threads so they
1150
        // won't waste CPU time.
1151
0
        threads_stop(coder);
1152
0
        return LZMA_DATA_ERROR;
1153
0
      }
1154
1155
      // read_output_and_wait() will call threads_stop()
1156
      // if needed so with that we can use return_if_error.
1157
3.88k
      return_if_error(read_output_and_wait(coder, allocator,
1158
3.88k
        out, out_pos, out_size,
1159
3.88k
        NULL, waiting_allowed,
1160
3.88k
        &wait_abs, &has_blocked));
1161
1162
3.75k
      if (coder->pending_error != LZMA_OK) {
1163
24
        coder->sequence = SEQ_ERROR;
1164
24
        break;
1165
24
      }
1166
1167
3.73k
      return LZMA_OK;
1168
3.75k
    }
1169
1170
501k
    if (ret == LZMA_INDEX_DETECTED) {
1171
19.9k
      coder->sequence = SEQ_INDEX_WAIT_OUTPUT;
1172
19.9k
      break;
1173
19.9k
    }
1174
1175
    // See if an error occurred.
1176
481k
    if (ret != LZMA_STREAM_END) {
1177
      // NOTE: Here and in all other places where
1178
      // pending_error is set, it may overwrite the value
1179
      // (LZMA_PROG_ERROR) set by read_output_and_wait().
1180
      // That function might overwrite value set here too.
1181
      // These are fine because when read_output_and_wait()
1182
      // sets pending_error, it actually works as a flag
1183
      // variable only ("some error has occurred") and the
1184
      // actual value of pending_error is not used in
1185
      // SEQ_ERROR. In such cases SEQ_ERROR will eventually
1186
      // get the correct error code from the return value of
1187
      // a later read_output_and_wait() call.
1188
901
      coder->pending_error = ret;
1189
901
      coder->sequence = SEQ_ERROR;
1190
901
      break;
1191
901
    }
1192
1193
    // Calculate the memory usage of the filters / Block decoder.
1194
481k
    coder->mem_next_filters = lzma_raw_decoder_memusage(
1195
481k
        coder->filters);
1196
1197
481k
    if (coder->mem_next_filters == UINT64_MAX) {
1198
      // One or more unknown Filter IDs.
1199
39
      coder->pending_error = LZMA_OPTIONS_ERROR;
1200
39
      coder->sequence = SEQ_ERROR;
1201
39
      break;
1202
39
    }
1203
1204
481k
    coder->sequence = SEQ_BLOCK_INIT;
1205
481k
    FALLTHROUGH;
1206
481k
  }
1207
1208
481k
  case SEQ_BLOCK_INIT: {
1209
    // Check if decoding is possible at all with the current
1210
    // memlimit_stop which we must never exceed.
1211
    //
1212
    // This needs to be the first thing in SEQ_BLOCK_INIT
1213
    // to make it possible to restart decoding after increasing
1214
    // memlimit_stop with lzma_memlimit_set().
1215
481k
    if (coder->mem_next_filters > coder->memlimit_stop) {
1216
      // Flush pending output before returning
1217
      // LZMA_MEMLIMIT_ERROR. If the application doesn't
1218
      // want to increase the limit, at least it will get
1219
      // all the output possible so far.
1220
336
      return_if_error(read_output_and_wait(coder, allocator,
1221
336
          out, out_pos, out_size,
1222
336
          NULL, true, &wait_abs, &has_blocked));
1223
1224
319
      if (!lzma_outq_is_empty(&coder->outq))
1225
307
        return LZMA_OK;
1226
1227
12
      return LZMA_MEMLIMIT_ERROR;
1228
319
    }
1229
1230
    // Check if the size information is available in Block Header.
1231
    // If it is, check if the sizes are small enough that we don't
1232
    // need to worry *too* much about integer overflows later in
1233
    // the code. If these conditions are not met, we must use the
1234
    // single-threaded direct mode.
1235
480k
    if (is_direct_mode_needed(coder->block_options.compressed_size)
1236
440k
        || is_direct_mode_needed(
1237
440k
        coder->block_options.uncompressed_size)) {
1238
40.6k
      coder->sequence = SEQ_BLOCK_DIRECT_INIT;
1239
40.6k
      break;
1240
40.6k
    }
1241
1242
    // Calculate the amount of memory needed for the input and
1243
    // output buffers in threaded mode.
1244
    //
1245
    // These cannot overflow because we already checked that
1246
    // the sizes are small enough using is_direct_mode_needed().
1247
440k
    coder->mem_next_in = comp_blk_size(coder);
1248
440k
    const uint64_t mem_buffers = coder->mem_next_in
1249
440k
        + lzma_outq_outbuf_memusage(
1250
440k
        coder->block_options.uncompressed_size);
1251
1252
    // Add the amount needed by the filters.
1253
    // Avoid integer overflows.
1254
440k
    if (UINT64_MAX - mem_buffers < coder->mem_next_filters) {
1255
      // Use direct mode if the memusage would overflow.
1256
      // This is a theoretical case that shouldn't happen
1257
      // in practice unless the input file is weird (broken
1258
      // or malicious).
1259
0
      coder->sequence = SEQ_BLOCK_DIRECT_INIT;
1260
0
      break;
1261
0
    }
1262
1263
    // Amount of memory needed to decode this Block in
1264
    // threaded mode:
1265
440k
    coder->mem_next_block = coder->mem_next_filters + mem_buffers;
1266
1267
    // If this alone would exceed memlimit_threading, then we must
1268
    // use the single-threaded direct mode.
1269
440k
    if (coder->mem_next_block > coder->memlimit_threading) {
1270
7.35k
      coder->sequence = SEQ_BLOCK_DIRECT_INIT;
1271
7.35k
      break;
1272
7.35k
    }
1273
1274
    // Use the threaded mode. Free the direct mode decoder in
1275
    // case it has been initialized.
1276
432k
    lzma_next_end(&coder->block_decoder, allocator);
1277
432k
    coder->mem_direct_mode = 0;
1278
1279
    // Since we already know what the sizes are supposed to be,
1280
    // we can already add them to the Index hash. The Block
1281
    // decoder will verify the values while decoding.
1282
432k
    const lzma_ret ret = lzma_index_hash_append(coder->index_hash,
1283
432k
        lzma_block_unpadded_size(
1284
432k
          &coder->block_options),
1285
432k
        coder->block_options.uncompressed_size);
1286
432k
    if (ret != LZMA_OK) {
1287
0
      coder->pending_error = ret;
1288
0
      coder->sequence = SEQ_ERROR;
1289
0
      break;
1290
0
    }
1291
1292
432k
    coder->sequence = SEQ_BLOCK_THR_INIT;
1293
432k
    FALLTHROUGH;
1294
432k
  }
1295
1296
433k
  case SEQ_BLOCK_THR_INIT: {
1297
    // We need to wait for a multiple conditions to become true
1298
    // until we can initialize the Block decoder and let a worker
1299
    // thread decode it:
1300
    //
1301
    //   - Wait for the memory usage of the active threads to drop
1302
    //     so that starting the decoding of this Block won't make
1303
    //     us go over memlimit_threading.
1304
    //
1305
    //   - Wait for at least one free output queue slot.
1306
    //
1307
    //   - Wait for a free worker thread.
1308
    //
1309
    // While we wait, we must copy decompressed data to the out
1310
    // buffer and catch possible decoder errors.
1311
    //
1312
    // read_output_and_wait() does all the above.
1313
433k
    bool block_can_start = false;
1314
1315
433k
    return_if_error(read_output_and_wait(coder, allocator,
1316
433k
        out, out_pos, out_size,
1317
433k
        &block_can_start, true,
1318
433k
        &wait_abs, &has_blocked));
1319
1320
433k
    if (coder->pending_error != LZMA_OK) {
1321
41
      coder->sequence = SEQ_ERROR;
1322
41
      break;
1323
41
    }
1324
1325
433k
    if (!block_can_start) {
1326
      // It's not a timeout because return_if_error handles
1327
      // it already. Output queue cannot be empty either
1328
      // because in that case block_can_start would have
1329
      // been true. Thus the output buffer must be full and
1330
      // the queue isn't empty.
1331
312
      assert(*out_pos == out_size);
1332
312
      assert(!lzma_outq_is_empty(&coder->outq));
1333
312
      return LZMA_OK;
1334
312
    }
1335
1336
    // We know that we can start decoding this Block without
1337
    // exceeding memlimit_threading. However, to stay below
1338
    // memlimit_threading may require freeing some of the
1339
    // cached memory.
1340
    //
1341
    // Get a local copy of variables that require locking the
1342
    // mutex. It is fine if the worker threads modify the real
1343
    // values after we read these as those changes can only be
1344
    // towards more favorable conditions (less memory in use,
1345
    // more in cache).
1346
    //
1347
    // These are initialized to silence warnings.
1348
432k
    uint64_t mem_in_use = 0;
1349
432k
    uint64_t mem_cached = 0;
1350
432k
    struct worker_thread *thr = NULL;
1351
1352
432k
    mythread_sync(coder->mutex) {
1353
432k
      mem_in_use = coder->mem_in_use;
1354
432k
      mem_cached = coder->mem_cached;
1355
432k
      thr = coder->threads_free;
1356
432k
    }
1357
1358
    // The maximum amount of memory that can be held by other
1359
    // threads and cached buffers while allowing us to start
1360
    // decoding the next Block.
1361
432k
    const uint64_t mem_max = coder->memlimit_threading
1362
432k
        - coder->mem_next_block;
1363
1364
    // If the existing allocations are so large that starting
1365
    // to decode this Block might exceed memlimit_threads,
1366
    // try to free memory from the output queue cache first.
1367
    //
1368
    // NOTE: This math assumes the worst case. It's possible
1369
    // that the limit wouldn't be exceeded if the existing cached
1370
    // allocations are reused.
1371
432k
    if (mem_in_use + mem_cached + coder->outq.mem_allocated
1372
432k
        > mem_max) {
1373
      // Clear the outq cache except leave one buffer in
1374
      // the cache if its size is correct. That way we
1375
      // don't free and almost immediately reallocate
1376
      // an identical buffer.
1377
322k
      lzma_outq_clear_cache2(&coder->outq, allocator,
1378
322k
        coder->block_options.uncompressed_size);
1379
322k
    }
1380
1381
    // If there is at least one worker_thread in the cache and
1382
    // the existing allocations are so large that starting to
1383
    // decode this Block might exceed memlimit_threads, free
1384
    // memory by freeing cached Block decoders.
1385
    //
1386
    // NOTE: The comparison is different here than above.
1387
    // Here we don't care about cached buffers in outq anymore
1388
    // and only look at memory actually in use. This is because
1389
    // if there is something in outq cache, it's a single buffer
1390
    // that can be used as is. We ensured this in the above
1391
    // if-block.
1392
432k
    uint64_t mem_freed = 0;
1393
432k
    if (thr != NULL && mem_in_use + mem_cached
1394
354k
        + coder->outq.mem_in_use > mem_max) {
1395
      // Don't free the first Block decoder if its memory
1396
      // usage isn't greater than what this Block will need.
1397
      // Typically the same filter chain is used for all
1398
      // Blocks so this way the allocations can be reused
1399
      // when get_thread() picks the first worker_thread
1400
      // from the cache.
1401
322k
      if (thr->mem_filters <= coder->mem_next_filters)
1402
193k
        thr = thr->next;
1403
1404
765k
      while (thr != NULL) {
1405
442k
        lzma_next_end(&thr->block_decoder, allocator);
1406
442k
        mem_freed += thr->mem_filters;
1407
442k
        thr->mem_filters = 0;
1408
442k
        thr = thr->next;
1409
442k
      }
1410
322k
    }
1411
1412
    // Update the memory usage counters. Note that coder->mem_*
1413
    // may have changed since we read them so we must subtract
1414
    // or add the changes.
1415
432k
    mythread_sync(coder->mutex) {
1416
432k
      coder->mem_cached -= mem_freed;
1417
1418
      // Memory needed for the filters and the input buffer.
1419
      // The output queue takes care of its own counter so
1420
      // we don't touch it here.
1421
      //
1422
      // NOTE: After this, coder->mem_in_use +
1423
      // coder->mem_cached might count the same thing twice.
1424
      // If so, this will get corrected in get_thread() when
1425
      // a worker_thread is picked from coder->free_threads
1426
      // and its memory usage is subtracted from mem_cached.
1427
432k
      coder->mem_in_use += coder->mem_next_in
1428
432k
          + coder->mem_next_filters;
1429
432k
    }
1430
1431
    // Allocate memory for the output buffer in the output queue.
1432
432k
    lzma_ret ret = lzma_outq_prealloc_buf(
1433
432k
        &coder->outq, allocator,
1434
432k
        coder->block_options.uncompressed_size);
1435
432k
    if (ret != LZMA_OK) {
1436
3
      threads_stop(coder);
1437
3
      return ret;
1438
3
    }
1439
1440
    // Set up coder->thr.
1441
432k
    ret = get_thread(coder, allocator);
1442
432k
    if (ret != LZMA_OK) {
1443
3
      threads_stop(coder);
1444
3
      return ret;
1445
3
    }
1446
1447
    // The new Block decoder memory usage is already counted in
1448
    // coder->mem_in_use. Store it in the thread too.
1449
432k
    coder->thr->mem_filters = coder->mem_next_filters;
1450
1451
    // Initialize the Block decoder.
1452
432k
    coder->thr->block_options = coder->block_options;
1453
432k
    ret = lzma_block_decoder_init(
1454
432k
          &coder->thr->block_decoder, allocator,
1455
432k
          &coder->thr->block_options);
1456
1457
    // Free the allocated filter options since they are needed
1458
    // only to initialize the Block decoder.
1459
432k
    lzma_filters_free(coder->filters, allocator);
1460
432k
    coder->thr->block_options.filters = NULL;
1461
1462
    // Check if memory usage calculation and Block encoder
1463
    // initialization succeeded.
1464
432k
    if (ret != LZMA_OK) {
1465
74
      coder->pending_error = ret;
1466
74
      coder->sequence = SEQ_ERROR;
1467
74
      break;
1468
74
    }
1469
1470
    // Allocate the input buffer.
1471
432k
    coder->thr->in_size = coder->mem_next_in;
1472
432k
    coder->thr->in = lzma_alloc(coder->thr->in_size, allocator);
1473
432k
    if (coder->thr->in == NULL) {
1474
7
      threads_stop(coder);
1475
7
      return LZMA_MEM_ERROR;
1476
7
    }
1477
1478
    // Get the preallocated output buffer.
1479
432k
    coder->thr->outbuf = lzma_outq_get_buf(
1480
432k
        &coder->outq, coder->thr);
1481
1482
    // Start the decoder.
1483
432k
    mythread_sync(coder->thr->mutex) {
1484
432k
      assert(coder->thr->state == THR_IDLE);
1485
432k
      coder->thr->state = THR_RUN;
1486
432k
      mythread_cond_signal(&coder->thr->cond);
1487
432k
    }
1488
1489
    // Enable output from the thread that holds the oldest output
1490
    // buffer in the output queue (if such a thread exists).
1491
432k
    mythread_sync(coder->mutex) {
1492
432k
      lzma_outq_enable_partial_output(&coder->outq,
1493
432k
          &worker_enable_partial_update);
1494
432k
    }
1495
1496
432k
    coder->sequence = SEQ_BLOCK_THR_RUN;
1497
432k
    FALLTHROUGH;
1498
432k
  }
1499
1500
447k
  case SEQ_BLOCK_THR_RUN: {
1501
447k
    if (action == LZMA_FINISH && coder->fail_fast) {
1502
      // We know that we won't get more input and that
1503
      // the caller wants fail-fast behavior. If we see
1504
      // that we don't have enough input to finish this
1505
      // Block, return LZMA_DATA_ERROR immediately.
1506
      // See SEQ_BLOCK_HEADER for the error code rationale.
1507
0
      const size_t in_avail = in_size - *in_pos;
1508
0
      const size_t in_needed = coder->thr->in_size
1509
0
          - coder->thr->in_filled;
1510
0
      if (in_avail < in_needed) {
1511
0
        threads_stop(coder);
1512
0
        return LZMA_DATA_ERROR;
1513
0
      }
1514
0
    }
1515
1516
    // Copy input to the worker thread.
1517
447k
    size_t cur_in_filled = coder->thr->in_filled;
1518
447k
    lzma_bufcpy(in, in_pos, in_size, coder->thr->in,
1519
447k
        &cur_in_filled, coder->thr->in_size);
1520
1521
    // Tell the thread how much we copied.
1522
447k
    mythread_sync(coder->thr->mutex) {
1523
447k
      coder->thr->in_filled = cur_in_filled;
1524
1525
      // NOTE: Most of the time we are copying input faster
1526
      // than the thread can decode so most of the time
1527
      // calling mythread_cond_signal() is useless but
1528
      // we cannot make it conditional because thr->in_pos
1529
      // is updated without a mutex. And the overhead should
1530
      // be very much negligible anyway.
1531
447k
      mythread_cond_signal(&coder->thr->cond);
1532
447k
    }
1533
1534
    // Read output from the output queue. Just like in
1535
    // SEQ_BLOCK_HEADER, we wait to fill the output buffer
1536
    // only if waiting_allowed was set to true in the beginning
1537
    // of this function (see the comment there) and there is
1538
    // no input available. In SEQ_BLOCK_HEADER, there is never
1539
    // input available when read_output_and_wait() is called,
1540
    // but here there can be when LZMA_FINISH is used, thus we
1541
    // need to check if *in_pos == in_size. Otherwise we would
1542
    // wait here instead of using the available input to start
1543
    // a new thread.
1544
447k
    return_if_error(read_output_and_wait(coder, allocator,
1545
447k
        out, out_pos, out_size,
1546
447k
        NULL,
1547
447k
        waiting_allowed && *in_pos == in_size,
1548
447k
        &wait_abs, &has_blocked));
1549
1550
447k
    if (coder->pending_error != LZMA_OK) {
1551
89
      coder->sequence = SEQ_ERROR;
1552
89
      break;
1553
89
    }
1554
1555
    // Return if the input didn't contain the whole Block.
1556
    //
1557
    // NOTE: When we updated coder->thr->in_filled a few lines
1558
    // above, the worker thread might by now have finished its
1559
    // work and returned itself back to the stack of free threads.
1560
447k
    if (coder->thr->in_filled < coder->thr->in_size) {
1561
15.1k
      assert(*in_pos == in_size);
1562
15.1k
      return LZMA_OK;
1563
15.1k
    }
1564
1565
    // The whole Block has been copied to the thread-specific
1566
    // buffer. Continue from the next Block Header or Index.
1567
432k
    coder->thr = NULL;
1568
432k
    coder->sequence = SEQ_BLOCK_HEADER;
1569
432k
    break;
1570
447k
  }
1571
1572
48.3k
  case SEQ_BLOCK_DIRECT_INIT: {
1573
    // Wait for the threads to finish and that all decoded data
1574
    // has been copied to the output. That is, wait until the
1575
    // output queue becomes empty.
1576
    //
1577
    // NOTE: No need to check for coder->pending_error as
1578
    // we aren't consuming any input until the queue is empty
1579
    // and if there is a pending error, read_output_and_wait()
1580
    // will eventually return it before the queue is empty.
1581
48.3k
    return_if_error(read_output_and_wait(coder, allocator,
1582
48.3k
        out, out_pos, out_size,
1583
48.3k
        NULL, true, &wait_abs, &has_blocked));
1584
48.0k
    if (!lzma_outq_is_empty(&coder->outq))
1585
333
      return LZMA_OK;
1586
1587
    // Free the cached output buffers.
1588
47.7k
    lzma_outq_clear_cache(&coder->outq, allocator);
1589
1590
    // Get rid of the worker threads, including the coder->threads
1591
    // array.
1592
47.7k
    threads_end(coder, allocator);
1593
1594
    // Initialize the Block decoder.
1595
47.7k
    const lzma_ret ret = lzma_block_decoder_init(
1596
47.7k
        &coder->block_decoder, allocator,
1597
47.7k
        &coder->block_options);
1598
1599
    // Free the allocated filter options since they are needed
1600
    // only to initialize the Block decoder.
1601
47.7k
    lzma_filters_free(coder->filters, allocator);
1602
47.7k
    coder->block_options.filters = NULL;
1603
1604
    // Check if Block decoder initialization succeeded.
1605
47.7k
    if (ret != LZMA_OK)
1606
19
      return ret;
1607
1608
    // Make the memory usage visible to _memconfig().
1609
47.6k
    coder->mem_direct_mode = coder->mem_next_filters;
1610
1611
47.6k
    coder->sequence = SEQ_BLOCK_DIRECT_RUN;
1612
47.6k
    FALLTHROUGH;
1613
47.6k
  }
1614
1615
86.9k
  case SEQ_BLOCK_DIRECT_RUN: {
1616
86.9k
    const size_t in_old = *in_pos;
1617
86.9k
    const size_t out_old = *out_pos;
1618
86.9k
    const lzma_ret ret = coder->block_decoder.code(
1619
86.9k
        coder->block_decoder.coder, allocator,
1620
86.9k
        in, in_pos, in_size, out, out_pos, out_size,
1621
86.9k
        action);
1622
86.9k
    coder->progress_in += *in_pos - in_old;
1623
86.9k
    coder->progress_out += *out_pos - out_old;
1624
1625
86.9k
    if (ret != LZMA_STREAM_END)
1626
42.6k
      return ret;
1627
1628
    // Block decoded successfully. Add the new size pair to
1629
    // the Index hash.
1630
44.2k
    return_if_error(lzma_index_hash_append(coder->index_hash,
1631
44.2k
        lzma_block_unpadded_size(
1632
44.2k
          &coder->block_options),
1633
44.2k
        coder->block_options.uncompressed_size));
1634
1635
44.2k
    coder->sequence = SEQ_BLOCK_HEADER;
1636
44.2k
    break;
1637
44.2k
  }
1638
1639
20.6k
  case SEQ_INDEX_WAIT_OUTPUT:
1640
    // Flush the output from all worker threads so that we can
1641
    // decode the Index without thinking about threading.
1642
20.6k
    return_if_error(read_output_and_wait(coder, allocator,
1643
20.6k
        out, out_pos, out_size,
1644
20.6k
        NULL, true, &wait_abs, &has_blocked));
1645
1646
20.5k
    if (!lzma_outq_is_empty(&coder->outq))
1647
695
      return LZMA_OK;
1648
1649
19.8k
    coder->sequence = SEQ_INDEX_DECODE;
1650
19.8k
    FALLTHROUGH;
1651
1652
20.4k
  case SEQ_INDEX_DECODE: {
1653
    // If we don't have any input, don't call
1654
    // lzma_index_hash_decode() since it would return
1655
    // LZMA_BUF_ERROR, which we must not do here.
1656
20.4k
    if (*in_pos >= in_size)
1657
40
      return LZMA_OK;
1658
1659
    // Decode the Index and compare it to the hash calculated
1660
    // from the sizes of the Blocks (if any).
1661
20.3k
    const size_t in_old = *in_pos;
1662
20.3k
    const lzma_ret ret = lzma_index_hash_decode(coder->index_hash,
1663
20.3k
        in, in_pos, in_size);
1664
20.3k
    coder->progress_in += *in_pos - in_old;
1665
20.3k
    if (ret != LZMA_STREAM_END)
1666
1.12k
      return ret;
1667
1668
19.2k
    coder->sequence = SEQ_STREAM_FOOTER;
1669
19.2k
    FALLTHROUGH;
1670
19.2k
  }
1671
1672
19.5k
  case SEQ_STREAM_FOOTER: {
1673
    // Copy the Stream Footer to the internal buffer.
1674
19.5k
    const size_t in_old = *in_pos;
1675
19.5k
    lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
1676
19.5k
        LZMA_STREAM_HEADER_SIZE);
1677
19.5k
    coder->progress_in += *in_pos - in_old;
1678
1679
    // Return if we didn't get the whole Stream Footer yet.
1680
19.5k
    if (coder->pos < LZMA_STREAM_HEADER_SIZE)
1681
323
      return LZMA_OK;
1682
1683
19.2k
    coder->pos = 0;
1684
1685
    // Decode the Stream Footer. The decoder gives
1686
    // LZMA_FORMAT_ERROR if the magic bytes don't match,
1687
    // so convert that return code to LZMA_DATA_ERROR.
1688
19.2k
    lzma_stream_flags footer_flags;
1689
19.2k
    const lzma_ret ret = lzma_stream_footer_decode(
1690
19.2k
        &footer_flags, coder->buffer);
1691
19.2k
    if (ret != LZMA_OK)
1692
97
      return ret == LZMA_FORMAT_ERROR
1693
97
          ? LZMA_DATA_ERROR : ret;
1694
1695
    // Check that Index Size stored in the Stream Footer matches
1696
    // the real size of the Index field.
1697
19.1k
    if (lzma_index_hash_size(coder->index_hash)
1698
19.1k
        != footer_flags.backward_size)
1699
27
      return LZMA_DATA_ERROR;
1700
1701
    // Compare that the Stream Flags fields are identical in
1702
    // both Stream Header and Stream Footer.
1703
19.1k
    return_if_error(lzma_stream_flags_compare(
1704
19.1k
        &coder->stream_flags, &footer_flags));
1705
1706
19.0k
    if (!coder->concatenated)
1707
36
      return LZMA_STREAM_END;
1708
1709
19.0k
    coder->sequence = SEQ_STREAM_PADDING;
1710
19.0k
    FALLTHROUGH;
1711
19.0k
  }
1712
1713
19.6k
  case SEQ_STREAM_PADDING:
1714
19.6k
    assert(coder->concatenated);
1715
1716
    // Skip over possible Stream Padding.
1717
3.19M
    while (true) {
1718
3.19M
      if (*in_pos >= in_size) {
1719
        // Unless LZMA_FINISH was used, we cannot
1720
        // know if there's more input coming later.
1721
587
        if (action != LZMA_FINISH)
1722
546
          return LZMA_OK;
1723
1724
        // Stream Padding must be a multiple of
1725
        // four bytes.
1726
41
        return coder->pos == 0
1727
41
            ? LZMA_STREAM_END
1728
41
            : LZMA_DATA_ERROR;
1729
587
      }
1730
1731
      // If the byte is not zero, it probably indicates
1732
      // beginning of a new Stream (or the file is corrupt).
1733
3.19M
      if (in[*in_pos] != 0x00)
1734
19.0k
        break;
1735
1736
3.17M
      ++*in_pos;
1737
3.17M
      ++coder->progress_in;
1738
3.17M
      coder->pos = (coder->pos + 1) & 3;
1739
3.17M
    }
1740
1741
    // Stream Padding must be a multiple of four bytes (empty
1742
    // Stream Padding is OK).
1743
19.0k
    if (coder->pos != 0) {
1744
5
      ++*in_pos;
1745
5
      ++coder->progress_in;
1746
5
      return LZMA_DATA_ERROR;
1747
5
    }
1748
1749
    // Prepare to decode the next Stream.
1750
19.0k
    return_if_error(stream_decoder_reset(coder, allocator));
1751
19.0k
    break;
1752
1753
19.0k
  case SEQ_ERROR:
1754
10.2k
    if (!coder->fail_fast) {
1755
      // Let the application get all data before the point
1756
      // where the error was detected. This matches the
1757
      // behavior of single-threaded use.
1758
      //
1759
      // FIXME? Some errors (LZMA_MEM_ERROR) don't get here,
1760
      // they are returned immediately. Thus in rare cases
1761
      // the output will be less than in the single-threaded
1762
      // mode. Maybe this doesn't matter much in practice.
1763
10.2k
      return_if_error(read_output_and_wait(coder, allocator,
1764
10.2k
          out, out_pos, out_size,
1765
10.2k
          NULL, true, &wait_abs, &has_blocked));
1766
1767
      // We get here only if the error happened in the main
1768
      // thread, for example, unsupported Block Header.
1769
9.57k
      if (!lzma_outq_is_empty(&coder->outq))
1770
9.03k
        return LZMA_OK;
1771
9.57k
    }
1772
1773
    // We only get here if no errors were detected by the worker
1774
    // threads. Errors from worker threads would have already been
1775
    // returned by the call to read_output_and_wait() above.
1776
537
    return coder->pending_error;
1777
1778
0
  default:
1779
0
    assert(0);
1780
0
    return LZMA_PROG_ERROR;
1781
663k
  }
1782
1783
  // Never reached
1784
98.8k
}
1785
1786
1787
static void
1788
stream_decoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)
1789
5.87k
{
1790
5.87k
  struct lzma_stream_coder *coder = coder_ptr;
1791
1792
5.87k
  threads_end(coder, allocator);
1793
5.87k
  lzma_outq_end(&coder->outq, allocator);
1794
1795
5.87k
  lzma_next_end(&coder->block_decoder, allocator);
1796
5.87k
  lzma_filters_free(coder->filters, allocator);
1797
5.87k
  lzma_index_hash_end(coder->index_hash, allocator);
1798
1799
5.87k
  lzma_free(coder, allocator);
1800
5.87k
  return;
1801
5.87k
}
1802
1803
1804
static lzma_check
1805
stream_decoder_mt_get_check(const void *coder_ptr)
1806
0
{
1807
0
  const struct lzma_stream_coder *coder = coder_ptr;
1808
0
  return coder->stream_flags.check;
1809
0
}
1810
1811
1812
static lzma_ret
1813
stream_decoder_mt_memconfig(void *coder_ptr, uint64_t *memusage,
1814
    uint64_t *old_memlimit, uint64_t new_memlimit)
1815
0
{
1816
  // NOTE: This function gets/sets memlimit_stop. For now,
1817
  // memlimit_threading cannot be modified after initialization.
1818
  //
1819
  // *memusage will include cached memory too. Excluding cached memory
1820
  // would be misleading and it wouldn't help the applications to
1821
  // know how much memory is actually needed to decompress the file
1822
  // because the higher the number of threads and the memlimits are
1823
  // the more memory the decoder may use.
1824
  //
1825
  // Setting a new limit includes the cached memory too and too low
1826
  // limits will be rejected. Alternative could be to free the cached
1827
  // memory immediately if that helps to bring the limit down but
1828
  // the current way is the simplest. It's unlikely that limit needs
1829
  // to be lowered in the middle of a file anyway; the typical reason
1830
  // to want a new limit is to increase after LZMA_MEMLIMIT_ERROR
1831
  // and even such use isn't common.
1832
0
  struct lzma_stream_coder *coder = coder_ptr;
1833
1834
0
  mythread_sync(coder->mutex) {
1835
0
    *memusage = coder->mem_direct_mode
1836
0
        + coder->mem_in_use
1837
0
        + coder->mem_cached
1838
0
        + coder->outq.mem_allocated;
1839
0
  }
1840
1841
  // If no filter chains are allocated, *memusage may be zero.
1842
  // Always return at least LZMA_MEMUSAGE_BASE.
1843
0
  if (*memusage < LZMA_MEMUSAGE_BASE)
1844
0
    *memusage = LZMA_MEMUSAGE_BASE;
1845
1846
0
  *old_memlimit = coder->memlimit_stop;
1847
1848
0
  if (new_memlimit != 0) {
1849
0
    if (new_memlimit < *memusage)
1850
0
      return LZMA_MEMLIMIT_ERROR;
1851
1852
0
    coder->memlimit_stop = new_memlimit;
1853
0
  }
1854
1855
0
  return LZMA_OK;
1856
0
}
1857
1858
1859
static void
1860
stream_decoder_mt_get_progress(void *coder_ptr,
1861
    uint64_t *progress_in, uint64_t *progress_out)
1862
0
{
1863
0
  struct lzma_stream_coder *coder = coder_ptr;
1864
1865
  // Lock coder->mutex to prevent finishing threads from moving their
1866
  // progress info from the worker_thread structure to lzma_stream_coder.
1867
0
  mythread_sync(coder->mutex) {
1868
0
    *progress_in = coder->progress_in;
1869
0
    *progress_out = coder->progress_out;
1870
1871
0
    for (size_t i = 0; i < coder->threads_initialized; ++i) {
1872
0
      mythread_sync(coder->threads[i].mutex) {
1873
0
        *progress_in += coder->threads[i].progress_in;
1874
0
        *progress_out += coder->threads[i]
1875
0
            .progress_out;
1876
0
      }
1877
0
    }
1878
0
  }
1879
1880
0
  return;
1881
0
}
1882
1883
1884
static lzma_ret
1885
stream_decoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
1886
           const lzma_mt *options)
1887
17.4k
{
1888
17.4k
  struct lzma_stream_coder *coder;
1889
1890
17.4k
  if (options->threads == 0 || options->threads > LZMA_THREADS_MAX)
1891
0
    return LZMA_OPTIONS_ERROR;
1892
1893
17.4k
  if (options->flags & ~LZMA_SUPPORTED_FLAGS)
1894
0
    return LZMA_OPTIONS_ERROR;
1895
1896
17.4k
  lzma_next_coder_init(&stream_decoder_mt_init, next, allocator);
1897
1898
17.4k
  coder = next->coder;
1899
17.4k
  if (!coder) {
1900
5.90k
    coder = lzma_alloc(sizeof(struct lzma_stream_coder), allocator);
1901
5.90k
    if (coder == NULL)
1902
27
      return LZMA_MEM_ERROR;
1903
1904
5.87k
    next->coder = coder;
1905
1906
5.87k
    if (mythread_mutex_init(&coder->mutex)) {
1907
0
      lzma_free(coder, allocator);
1908
0
      return LZMA_MEM_ERROR;
1909
0
    }
1910
1911
5.87k
    if (mythread_cond_init(&coder->cond)) {
1912
0
      mythread_mutex_destroy(&coder->mutex);
1913
0
      lzma_free(coder, allocator);
1914
0
      return LZMA_MEM_ERROR;
1915
0
    }
1916
1917
5.87k
    next->code = &stream_decode_mt;
1918
5.87k
    next->end = &stream_decoder_mt_end;
1919
5.87k
    next->get_check = &stream_decoder_mt_get_check;
1920
5.87k
    next->memconfig = &stream_decoder_mt_memconfig;
1921
5.87k
    next->get_progress = &stream_decoder_mt_get_progress;
1922
1923
5.87k
    coder->filters[0].id = LZMA_VLI_UNKNOWN;
1924
5.87k
    memzero(&coder->outq, sizeof(coder->outq));
1925
1926
5.87k
    coder->block_decoder = LZMA_NEXT_CODER_INIT;
1927
5.87k
    coder->mem_direct_mode = 0;
1928
1929
5.87k
    coder->index_hash = NULL;
1930
5.87k
    coder->threads = NULL;
1931
5.87k
    coder->threads_free = NULL;
1932
5.87k
    coder->threads_initialized = 0;
1933
5.87k
  }
1934
1935
  // Cleanup old filter chain if one remains after unfinished decoding
1936
  // of a previous Stream.
1937
17.4k
  lzma_filters_free(coder->filters, allocator);
1938
1939
  // By allocating threads from scratch we can start memory-usage
1940
  // accounting from scratch, too. Changes in filter and block sizes may
1941
  // affect number of threads.
1942
  //
1943
  // Reusing threads doesn't seem worth it. Unlike the single-threaded
1944
  // decoder, with some types of input file combinations reusing
1945
  // could leave quite a lot of memory allocated but unused (first
1946
  // file could allocate a lot, the next files could use fewer
1947
  // threads and some of the allocations from the first file would not
1948
  // get freed unless memlimit_threading forces us to clear caches).
1949
  //
1950
  // NOTE: The direct mode decoder isn't freed here if one exists.
1951
  // It will be reused or freed as needed in the main loop.
1952
17.4k
  threads_end(coder, allocator);
1953
1954
  // All memusage counters start at 0 (including mem_direct_mode).
1955
  // The little extra that is needed for the structs in this file
1956
  // get accounted well enough by the filter chain memory usage
1957
  // which adds LZMA_MEMUSAGE_BASE for each chain. However,
1958
  // stream_decoder_mt_memconfig() has to handle this specially so that
1959
  // it will never return less than LZMA_MEMUSAGE_BASE as memory usage.
1960
17.4k
  coder->mem_in_use = 0;
1961
17.4k
  coder->mem_cached = 0;
1962
17.4k
  coder->mem_next_block = 0;
1963
1964
17.4k
  coder->progress_in = 0;
1965
17.4k
  coder->progress_out = 0;
1966
1967
17.4k
  coder->sequence = SEQ_STREAM_HEADER;
1968
17.4k
  coder->thread_error = LZMA_OK;
1969
17.4k
  coder->pending_error = LZMA_OK;
1970
17.4k
  coder->thr = NULL;
1971
1972
17.4k
  coder->timeout = options->timeout;
1973
1974
17.4k
  coder->memlimit_threading = my_max(1, options->memlimit_threading);
1975
17.4k
  coder->memlimit_stop = my_max(1, options->memlimit_stop);
1976
17.4k
  if (coder->memlimit_threading > coder->memlimit_stop)
1977
0
    coder->memlimit_threading = coder->memlimit_stop;
1978
1979
17.4k
  coder->tell_no_check = (options->flags & LZMA_TELL_NO_CHECK) != 0;
1980
17.4k
  coder->tell_unsupported_check
1981
17.4k
      = (options->flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
1982
17.4k
  coder->tell_any_check = (options->flags & LZMA_TELL_ANY_CHECK) != 0;
1983
17.4k
  coder->ignore_check = (options->flags & LZMA_IGNORE_CHECK) != 0;
1984
17.4k
  coder->concatenated = (options->flags & LZMA_CONCATENATED) != 0;
1985
17.4k
  coder->fail_fast = (options->flags & LZMA_FAIL_FAST) != 0;
1986
1987
17.4k
  coder->first_stream = true;
1988
17.4k
  coder->out_was_filled = false;
1989
17.4k
  coder->pos = 0;
1990
1991
17.4k
  coder->threads_max = options->threads;
1992
1993
17.4k
  return_if_error(lzma_outq_init(&coder->outq, allocator,
1994
17.4k
               coder->threads_max));
1995
1996
17.4k
  return stream_decoder_reset(coder, allocator);
1997
17.4k
}
1998
1999
2000
extern LZMA_API(lzma_ret)
2001
lzma_stream_decoder_mt(lzma_stream *strm, const lzma_mt *options)
2002
17.5k
{
2003
17.5k
  lzma_next_strm_init(stream_decoder_mt_init, strm, options);
2004
2005
17.4k
  strm->internal->supported_actions[LZMA_RUN] = true;
2006
17.4k
  strm->internal->supported_actions[LZMA_FINISH] = true;
2007
2008
17.4k
  return LZMA_OK;
2009
17.5k
}