Commit 556cc1f7 for xz
commit 556cc1f70f096877e2b61991a482744054c2f8a7
Author: Mar <mardgez13@gmail.com>
Date: Sun Oct 25 14:34:48 2026 +0100
liblzma: mt enc: Initialize the coder only after the old threads stop
stream_encoder_mt_init() set coder->block_size and coder->thread_error
before it stopped or ended the worker threads of the previous use of
the coder. A worker that had just been started could still read
coder->block_size in worker_encode(), and a worker that failed in that
window could still set coder->thread_error, which the new stream would
then return as its own error.
ThreadSanitizer reports the former as a data race in
test_stream_encoder_mt (test_bug2).
Do the basic initializations after threads_stop() or threads_end().
The old block size is then still in coder->block_size when it is
compared to the new one.
diff --git a/src/liblzma/common/stream_encoder_mt.c b/src/liblzma/common/stream_encoder_mt.c
index 3d25f62a..02ab9f84 100644
--- a/src/liblzma/common/stream_encoder_mt.c
+++ b/src/liblzma/common/stream_encoder_mt.c
@@ -1097,16 +1097,6 @@ stream_encoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
coder->threads_initialized = 0;
}
- // Remember the old block size.
- const size_t old_block_size = coder->block_size;
-
- // Basic initializations
- coder->sequence = SEQ_STREAM_HEADER;
- coder->block_size = (size_t)(block_size);
- coder->outbuf_alloc_size = (size_t)(outbuf_size_max);
- coder->thread_error = LZMA_OK;
- coder->thr = NULL;
-
// Allocate the thread-specific base structures.
// If the block size or the number of threads has changed,
// don't reuse the old threads:
@@ -1115,7 +1105,7 @@ stream_encoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
// - coder->threads is allocated below. Its size depends on
// options->threads.
assert(options->threads > 0);
- if (old_block_size != coder->block_size
+ if (coder->block_size != (size_t)(block_size)
|| coder->threads_max != options->threads) {
threads_end(coder, allocator);
@@ -1139,6 +1129,15 @@ stream_encoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
threads_stop(coder, true);
}
+ // Basic initializations. These are done only after the old
+ // worker threads have stopped or exited because the workers
+ // read coder->block_size and write coder->thread_error.
+ coder->sequence = SEQ_STREAM_HEADER;
+ coder->block_size = (size_t)(block_size);
+ coder->outbuf_alloc_size = (size_t)(outbuf_size_max);
+ coder->thread_error = LZMA_OK;
+ coder->thr = NULL;
+
// Output queue
return_if_error(lzma_outq_init(&coder->outq, allocator,
options->threads));