From 94751cbfb54f98cf1b1be14c6e22a8b93547a177 Mon Sep 17 00:00:00 2001
From: Jarek Kobus <jaroslaw.kobus@qt.io>
Date: Thu, 31 Mar 2022 11:34:29 +0200
Subject: Ensure that readAllStandardError() doesn't crash on assert

Ensure that it's safe to call readAllStandardError()
when process channel mode is set to MergedChannels.

Task-number: QTBUG-102177
Task-number: QTCREATORBUG-27196
Change-Id: I01073255d9347dee4654d602802a12d341372b73
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
(cherry picked from commit b49f7e064c648f7de9782f1a5bbd652429db8e5b)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
---
 src/corelib/io/qprocess.cpp                     | 14 ++++++++++----
 tests/auto/corelib/io/qprocess/tst_qprocess.cpp | 10 ++++++++++
 2 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/src/corelib/io/qprocess.cpp b/src/corelib/io/qprocess.cpp
index 3378412502..6d85d1e87e 100644
--- a/src/corelib/io/qprocess.cpp
+++ b/src/corelib/io/qprocess.cpp
@@ -1942,10 +1942,16 @@ QByteArray QProcess::readAllStandardOutput()
 */
 QByteArray QProcess::readAllStandardError()
 {
-    ProcessChannel tmp = readChannel();
-    setReadChannel(StandardError);
-    QByteArray data = readAll();
-    setReadChannel(tmp);
+    Q_D(QProcess);
+    QByteArray data;
+    if (d->processChannelMode == MergedChannels) {
+        qWarning("QProcess::readAllStandardError: Called with MergedChannels");
+    } else {
+        ProcessChannel tmp = readChannel();
+        setReadChannel(StandardError);
+        data = readAll();
+        setReadChannel(tmp);
+    }
     return data;
 }
 
diff --git a/tests/auto/corelib/io/qprocess/tst_qprocess.cpp b/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
index 80005a7284..16b7dc666f 100644
--- a/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
+++ b/tests/auto/corelib/io/qprocess/tst_qprocess.cpp
@@ -1082,6 +1082,16 @@ void tst_QProcess::mergedChannels()
 
     QVERIFY(process.waitForStarted(5000));
 
+    {
+        QCOMPARE(process.write("abc"), qlonglong(3));
+        while (process.bytesAvailable() < 6)
+            QVERIFY(process.waitForReadyRead(5000));
+        QCOMPARE(process.readAllStandardOutput(), QByteArray("aabbcc"));
+        QTest::ignoreMessage(QtWarningMsg,
+            "QProcess::readAllStandardError: Called with MergedChannels");
+        QCOMPARE(process.readAllStandardError(), QByteArray());
+    }
+
     for (int i = 0; i < 100; ++i) {
         QCOMPARE(process.write("abc"), qlonglong(3));
         while (process.bytesAvailable() < 6)
-- 
cgit v1.2.1

