From 65b4031e7ac457da626a3d7581c835130280a656 Mon Sep 17 00:00:00 2001 From: Ivan Solovev Date: Thu, 9 Feb 2023 16:12:15 +0100 Subject: QFuture: fix continuation cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Not clearing the continuationData could lead to use-after-free when there is an attempt to cancel an already finished future, which belongs to an already-destroyed promise. This patch fixes it be explicitly resetting continuationData to nullptr in the clearContinuation() method, which is called from the QPromise destructor. Task-number: QTBUG-103514 Change-Id: I6418b3f5ad04f2fdc13a196ae208009eaa5de367 Reviewed-by: Qt CI Bot Reviewed-by: MÃ¥rten Nordheim (cherry picked from commit b34bea5e96370986ea5dfc499fc2ec6366fda627) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/thread/qfutureinterface.cpp | 1 + tests/auto/corelib/thread/qfuture/tst_qfuture.cpp | 26 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/corelib/thread/qfutureinterface.cpp b/src/corelib/thread/qfutureinterface.cpp index eedfd7ceeb..ed46052fa7 100644 --- a/src/corelib/thread/qfutureinterface.cpp +++ b/src/corelib/thread/qfutureinterface.cpp @@ -847,6 +847,7 @@ void QFutureInterfaceBase::cleanContinuation() QMutexLocker lock(&d->continuationMutex); d->continuation = nullptr; d->continuationState = QFutureInterfaceBasePrivate::Cleaned; + d->continuationData = nullptr; } void QFutureInterfaceBase::runContinuation() const diff --git a/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp b/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp index d6c214f534..21408095de 100644 --- a/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp +++ b/tests/auto/corelib/thread/qfuture/tst_qfuture.cpp @@ -221,6 +221,7 @@ private slots: void whenAnyDifferentTypesWithFailed(); void continuationsDontLeak(); + void cancelAfterFinishWithContinuations(); void unwrap(); @@ -4721,6 +4722,31 @@ void tst_QFuture::continuationsDontLeak() QCOMPARE(InstanceCounter::count, 0); } +// This test checks that we do not get use-after-free +void tst_QFuture::cancelAfterFinishWithContinuations() +{ + QFuture future; + bool continuationIsRun = false; + bool cancelCalled = false; + { + QPromise promise; + future = promise.future(); + + future.then([&continuationIsRun]() { + continuationIsRun = true; + }).onCanceled([&cancelCalled]() { + cancelCalled = true; + }); + + promise.start(); + promise.finish(); + } + + QVERIFY(continuationIsRun); + future.cancel(); + QVERIFY(!cancelCalled); +} + void tst_QFuture::unwrap() { // The nested future succeeds -- cgit v1.2.1