Commit 2895f1cd for xz

commit 2895f1cdbe50020e6ba1ae87b7d2185d5c508430
Author: Lasse Collin <lasse.collin@tukaani.org>
Date:   Sat Oct 17 18:37:39 2026 +0300

    liblzma: mt enc: Always return workers to coder->threads_free on THR_STOP

    If the main thread started a worker thread by changing the state from
    THR_IDLE to THR_RUN, and very soon the main thread told the same worker
    to stop by setting the state to THR_STOP, and the worker hadn't yet
    woken up and reacted to THR_RUN, the worker would simply set the state
    back to THR_IDLE. This was wrong because on THR_STOP the worker needs
    to return itself to the stack of free threads (thr->coder->threads_free).

    This bug could result in a deadlock if threaded encoder was reinitialized
    when lzma_code() hadn't returned LZMA_STREAM_END.

    Reported-by: Mar <mardgez13@gmail.com>
    Fixes: de678e0c924a ("liblzma: Add lzma_stream_encoder_mt() for threaded compression.")

diff --git a/src/liblzma/common/stream_encoder_mt.c b/src/liblzma/common/stream_encoder_mt.c
index 2d2508cc..67a93bd3 100644
--- a/src/liblzma/common/stream_encoder_mt.c
+++ b/src/liblzma/common/stream_encoder_mt.c
@@ -368,27 +368,16 @@ worker_start(void *thr_ptr)
 	while (true) {
 		// Wait for work.
 		mythread_sync(thr->mutex) {
-			while (true) {
-				// The thread is already idle so if we are
-				// requested to stop, just set the state.
-				if (thr->state == THR_STOP) {
-					thr->state = THR_IDLE;
-					mythread_cond_signal(&thr->cond);
-				}
-
-				state = thr->state;
-				if (state != THR_IDLE)
-					break;
-
+			// NOTE: On THR_STOP, we need to return this
+			// worker to the stack of free threads; we
+			// cannot just set state = THR_IDLE here.
+			while (thr->state == THR_IDLE)
 				mythread_cond_wait(&thr->cond, &thr->mutex);
-			}
+
+			state = thr->state;
 		}

 		size_t out_pos = 0;
-
-		assert(state != THR_IDLE);
-		assert(state != THR_STOP);
-
 		if (state <= THR_FINISH)
 			state = worker_encode(thr, &out_pos, state);

@@ -447,8 +436,13 @@ threads_stop(lzma_stream_coder *coder, bool wait_for_threads)
 	// Tell the threads to stop.
 	for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
 		mythread_sync(coder->threads[i].mutex) {
-			coder->threads[i].state = THR_STOP;
-			mythread_cond_signal(&coder->threads[i].cond);
+			// Only set THR_STOP if the thread isn't idle because
+			// only non-idle threads need to be returned to the
+			// stack of free threads (coder->threads_free).
+			if (coder->threads[i].state != THR_IDLE) {
+				coder->threads[i].state = THR_STOP;
+				mythread_cond_signal(&coder->threads[i].cond);
+			}
 		}
 	}