Fix UB (reference to local variable leaving scope) in runOnAndroidMainThread()

The QAndroidApplication::runOnAndroidMainThread() function creates a
task on QThreadPool::globalInstance() to wait for a timeout and cancel
the QFuture representing the task.

It does so by passing a lambda to QThreadPool::start(std::function)
that captures the future, a local variable, by reference. This is UB
when the lambda is ever executed, because the local stack variable's
lifetime will have ended.

To fix, simply capture the future by value, not by reference. Since
QFuture::cancel() is not const, we need to make the lambda mutable.

Fixes: QTBUG-109586
Change-Id: Icacfb0dc76bcd3a145f90126f535e7c0f4b5ef6a
Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org>
Reviewed-by: Ville Voutilainen <ville.voutilainen@qt.io>
(cherry picked from commit 3642d5680df8a1b70e4a1a111347005e08555070)
Reviewed-by: Assam Boudjelthia <assam.boudjelthia@qt.io>
This commit is contained in:
Marc Mutz 2022-12-22 15:11:52 +01:00
parent 5ad1d0b83a
commit a6ea94cc3e

View File

@ -166,7 +166,7 @@ QFuture<QVariant> QNativeInterface::QAndroidApplication::runOnAndroidMainThread(
promise->start(); promise->start();
if (!timeout.isForever()) { if (!timeout.isForever()) {
QThreadPool::globalInstance()->start([=, &future]() { QThreadPool::globalInstance()->start([=]() mutable {
QEventLoop loop; QEventLoop loop;
QTimer::singleShot(timeout.remainingTime(), &loop, [&]() { QTimer::singleShot(timeout.remainingTime(), &loop, [&]() {
future.cancel(); future.cancel();