From 52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Mon Sep 17 00:00:00 2001
From: Tim Blechmann <tim.blechmann@qt.io>
Date: Fri, 02 Oct 2026 08:31:27 +0800
Subject: [PATCH] Read WAV frames in chunks instead of trusting the header count

The PCM frame count declared by a WAV header is untrusted. Both
QDrWavAudioDecoder and QSampleCache sized their output buffer up
front from that count, so a crafted file with a huge or wrapping
frame count could trigger an enormous allocation or an integer
overflow. Add a QtMultimediaPrivate::readFramesInChunks() helper
that grows the buffer chunk by chunk as frames are actually
produced, and fails unless exactly the declared frame count is
read.

Fixes: QTBUG-151155
Change-Id: I32c9e77cfd29857b8f08f085fe7c77553cb3e3fd
Reviewed-by: Artem Dyomin <artem.dyomin@qt.io>
Reviewed-by: Nils Petter Skålerud <nils.petter.skalerud@qt.io>
(cherry picked from commit ab5d16cdca6d1560bb36b5629352c3e8bc78a408)
Reviewed-by: Tim Blechmann <tim.blechmann@qt.io>
---

diff --git a/src/multimedia/audio/qdrawavaudiodecoder.cpp b/src/multimedia/audio/qdrawavaudiodecoder.cpp
index 6c50bc7..61b48e7 100644
--- a/src/multimedia/audio/qdrawavaudiodecoder.cpp
+++ b/src/multimedia/audio/qdrawavaudiodecoder.cpp
@@ -122,40 +122,41 @@
                              << "totalPCMFrameCount=" << wav.totalPCMFrameCount
                              << "outputFormat=" << outputFormat.sampleFormat();
 
-    // Allocate PCM data for the entire file
-    QByteArray pcmData;
-    pcmData.resizeForOverwrite(wav.totalPCMFrameCount * bytesPerFrame);
-
-    // Read all frames at once using appropriate format
-    uint64_t framesRead = 0;
-
-    switch (outputFormat.sampleFormat()) {
+    const QAudioFormat::SampleFormat readFormat = outputFormat.sampleFormat();
+    switch (readFormat) {
     case QAudioFormat::UInt8:
-        framesRead = drwav_read_pcm_frames(&wav, wav.totalPCMFrameCount,
-                                           reinterpret_cast<uint8_t *>(pcmData.data()));
-        break;
     case QAudioFormat::Int16:
-        framesRead = drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount,
-                                               reinterpret_cast<int16_t *>(pcmData.data()));
-        break;
     case QAudioFormat::Int32:
-        framesRead = drwav_read_pcm_frames_s32(&wav, wav.totalPCMFrameCount,
-                                               reinterpret_cast<int32_t *>(pcmData.data()));
-        break;
     case QAudioFormat::Float:
-        framesRead = drwav_read_pcm_frames_f32(&wav, wav.totalPCMFrameCount,
-                                               reinterpret_cast<float *>(pcmData.data()));
         break;
     default:
         return makeFormatError(QAudioDecoder::tr("Unsupported sample format"));
     }
 
-    if (framesRead != wav.totalPCMFrameCount) {
+    std::optional<QByteArray> decoded = readFramesInChunks(
+            wav.totalPCMFrameCount, bytesPerFrame, [&](uint64_t frameCount, char *out) -> uint64_t {
+        switch (readFormat) {
+        case QAudioFormat::UInt8:
+            return drwav_read_pcm_frames(&wav, frameCount, out);
+        case QAudioFormat::Int16:
+            return drwav_read_pcm_frames_s16(&wav, frameCount, reinterpret_cast<int16_t *>(out));
+        case QAudioFormat::Int32:
+            return drwav_read_pcm_frames_s32(&wav, frameCount, reinterpret_cast<int32_t *>(out));
+        case QAudioFormat::Float:
+            return drwav_read_pcm_frames_f32(&wav, frameCount, reinterpret_cast<float *>(out));
+        default:
+            Q_UNREACHABLE_RETURN(0);
+        }
+    });
+
+    if (!decoded) {
         qCDebug(qLcDrWavDecoder) << "Failed to read all frames:"
-                                 << "expected" << wav.totalPCMFrameCount << "got" << framesRead;
+                                 << "expected" << wav.totalPCMFrameCount;
         return makeFormatError(QAudioDecoder::tr("Unable to read audio data"));
     }
 
+    const QByteArray &pcmData = *decoded;
+
     QAudioBuffer buffer(pcmData, outputFormat);
     if (!buffer.isValid()) {
         return makeFormatError(QAudioDecoder::tr("Failed to create audio buffer"));
diff --git a/src/multimedia/audio/qdrawavaudiodecoder_p.h b/src/multimedia/audio/qdrawavaudiodecoder_p.h
index 674234e..5e52d4c 100644
--- a/src/multimedia/audio/qdrawavaudiodecoder_p.h
+++ b/src/multimedia/audio/qdrawavaudiodecoder_p.h
@@ -16,12 +16,18 @@
 //
 
 #include <QtMultimedia/private/qplatformaudiodecoder_p.h>
+#include <QtCore/qbytearray.h>
 #include <QtCore/qspan.h>
 #include <QtCore/qurl.h>
 #include <QtCore/private/qexpected_p.h>
 
+#include <algorithm>
 #include <atomic>
+#include <cstdint>
 #include <memory>
+#include <new>
+#include <optional>
+#include <type_traits>
 
 QT_BEGIN_NAMESPACE
 
@@ -34,6 +40,57 @@
 QDrWavDecodeResult loadWaveAndDecodeData(QSpan<const std::byte>,
                                          const QAudioFormat &requestedFormat);
 
+#ifdef __cpp_concepts
+template <typename Reader>
+concept FrameReader = std::is_invocable_v<Reader, uint64_t, char *>
+        && std::is_convertible_v<std::invoke_result_t<Reader, uint64_t, char *>, uint64_t>;
+#endif
+
+#ifdef __cpp_concepts
+template <FrameReader Reader>
+#else
+template <typename Reader>
+#endif
+std::optional<QByteArray> readFramesInChunks(uint64_t declaredFrameCount, size_t bytesPerFrame,
+                                             Reader &&readFrames)
+{
+    constexpr size_t chunkBytes = 10 * 1024 * 1024; // 10 MB
+    if (bytesPerFrame == 0)
+        return std::nullopt;
+
+    const uint64_t chunkFrames = std::max<uint64_t>(1, chunkBytes / bytesPerFrame);
+
+    QT_TRY
+    {
+        QByteArray result;
+        uint64_t totalFramesRead = 0;
+        while (totalFramesRead < declaredFrameCount) {
+            const uint64_t framesToRead =
+                    std::min(chunkFrames, declaredFrameCount - totalFramesRead);
+            const uint64_t bytesToRead = framesToRead * bytesPerFrame;
+            const qsizetype oldSize = result.size();
+            if (bytesToRead > uint64_t(QByteArray::maxSize() - oldSize))
+                return std::nullopt;
+
+            result.resizeForOverwrite(oldSize + qsizetype(bytesToRead));
+            const uint64_t framesRead = readFrames(framesToRead, result.data() + oldSize);
+            Q_ASSERT(framesRead <= framesToRead);
+            result.resize(oldSize + qsizetype(framesRead * bytesPerFrame));
+
+            totalFramesRead += framesRead;
+            if (framesRead < framesToRead)
+                break;
+        }
+        if (totalFramesRead != declaredFrameCount)
+            return std::nullopt;
+        return result;
+    }
+    QT_CATCH(const std::bad_alloc &)
+    {
+        return std::nullopt;
+    }
+}
+
 } // namespace QtMultimediaPrivate
 
 class QDrWavAudioDecoder final : public QPlatformAudioDecoder
diff --git a/src/multimedia/audio/qsamplecache_p.cpp b/src/multimedia/audio/qsamplecache_p.cpp
index 4cc5b7f..314d140 100644
--- a/src/multimedia/audio/qsamplecache_p.cpp
+++ b/src/multimedia/audio/qsamplecache_p.cpp
@@ -2,8 +2,13 @@
 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
 
 #include "qsamplecache_p.h"
-#include "qaudiohelpers_p.h"
 
+#include <QtMultimedia/qaudiobuffer.h>
+#include <QtMultimedia/qaudiodecoder.h>
+#include <QtMultimedia/private/qaudiohelpers_p.h>
+#include <QtMultimedia/private/qdrawavaudiodecoder_p.h>
+#include <QtMultimedia/private/qmultimediautils_p.h>
+#include <QtConcurrent/qtconcurrentrun.h>
 #include <QtCore/qapplicationstatic.h>
 #include <QtCore/qbuffer.h>
 #include <QtCore/qcoreapplication.h>
@@ -12,10 +17,7 @@
 #include <QtCore/qfile.h>
 #include <QtCore/qfuturewatcher.h>
 #include <QtCore/qloggingcategory.h>
-#include <QtMultimedia/qaudiobuffer.h>
-#include <QtMultimedia/qaudiodecoder.h>
-#include <QtMultimedia/private/qmultimediautils_p.h>
-#include <QtConcurrent/qtconcurrentrun.h>
+#include <QtCore/qmutex.h>
 
 #if QT_CONFIG(network)
 #  include <QtNetwork/qnetworkaccessmanager.h>
@@ -165,17 +167,16 @@
     audioFormat.setChannelConfig(
             QAudioFormat::defaultChannelConfigForChannelCount(wavParser.channels));
 
-    QByteArray sampleData;
-    sampleData.resizeForOverwrite(qsizetype(sizeof(float) * wavParser.channels
-                                   * wavParser.totalPCMFrameCount));
-    uint64_t framesRead = drwav_read_pcm_frames_f32(&wavParser, wavParser.totalPCMFrameCount,
-                                                    reinterpret_cast<float *>(sampleData.data()));
-
-    if (framesRead != wavParser.totalPCMFrameCount)
+    std::optional<QByteArray> sampleData = QtMultimediaPrivate::readFramesInChunks(
+            wavParser.totalPCMFrameCount, sizeof(float) * wavParser.channels,
+            [&](uint64_t frameCount, char *out) -> uint64_t {
+        return drwav_read_pcm_frames_f32(&wavParser, frameCount, reinterpret_cast<float *>(out));
+    });
+    if (!sampleData)
         return q23::unexpected(QSampleLoadError::FormatError);
 
     return std::pair{
-        std::move(sampleData),
+        std::move(*sampleData),
         audioFormat,
     };
 }
diff --git a/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp b/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp
index 2f92e5e..10c0180 100644
--- a/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp
+++ b/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp
@@ -1,13 +1,15 @@
 // Copyright (C) 2016 The Qt Company Ltd.
 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
 
-#include <QtMultimedia/private/qsamplecache_p.h>
+#include <qmockintegration.h>
 
 #include <QtTest/qtest.h>
+#include <QtMultimedia/private/qsamplecache_p.h>
+#include <QtCore/qendian.h>
 #include <QtCore/qfile.h>
 #include <QtCore/qfuturewatcher.h>
 
-#include <qmockintegration.h>
+#include <cstdint>
 
 Q_ENABLE_MOCK_MULTIMEDIA_PLUGIN
 
@@ -42,6 +44,14 @@
 
     void testLoadSampleFromSpan_valid();
     void testLoadSampleFromSpan_invalid();
+    void testLoadSampleFromSpan_declaredFrameCountMismatch_data();
+    void testLoadSampleFromSpan_declaredFrameCountMismatch();
+    void testLoadSampleFromSpan_multiChannel();
+    void testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch_data()
+    {
+        testLoadSampleFromSpan_declaredFrameCountMismatch_data();
+    }
+    void testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch();
     void testLoadSampleViaDecoder_valid();
     void testLoadSampleViaDecoder_fallbackToDrWav();
     void testLoadSampleViaDecoderBuffer_valid();
@@ -56,6 +66,45 @@
     void testForcedDecoderPathAsync();
 
 private:
+    template <typename T>
+    static void appendLittleEndian(QByteArray &out, T value)
+    {
+        const T le = qToLittleEndian(value);
+        out.append(reinterpret_cast<const char *>(&le), sizeof(le));
+    }
+
+    static QByteArray makeRf64Wav(uint64_t declaredFrameCount, uint16_t channelCount,
+                                  qsizetype dataBytes)
+    {
+        const uint16_t bytesPerFrame = channelCount * sizeof(int16_t);
+
+        QByteArray wav;
+        wav.append("RF64");
+        appendLittleEndian<uint32_t>(wav, 0xFFFFFFFF);
+        wav.append("WAVE");
+
+        wav.append("ds64");
+        appendLittleEndian<uint32_t>(wav, 28);
+        appendLittleEndian<uint64_t>(wav, 0); // RIFF size, ignored
+        appendLittleEndian<uint64_t>(wav, uint64_t(dataBytes));
+        appendLittleEndian<uint64_t>(wav, declaredFrameCount);
+        appendLittleEndian<uint32_t>(wav, 0); // table length
+
+        wav.append("fmt ");
+        appendLittleEndian<uint32_t>(wav, 16);
+        appendLittleEndian<uint16_t>(wav, 1); // PCM
+        appendLittleEndian<uint16_t>(wav, channelCount);
+        appendLittleEndian<uint32_t>(wav, 8000);
+        appendLittleEndian<uint32_t>(wav, 8000 * bytesPerFrame);
+        appendLittleEndian<uint16_t>(wav, bytesPerFrame);
+        appendLittleEndian<uint16_t>(wav, 16);
+
+        wav.append("data");
+        appendLittleEndian<uint32_t>(wav, 0xFFFFFFFF);
+        wav.append(QByteArray(dataBytes, '\x7f'));
+        return wav;
+    }
+
     void generateTestData()
     {
         QTest::addColumn<QSampleCache::SampleSourceType>("sampleSourceType");
@@ -194,6 +243,50 @@
     QCOMPARE(result.error(), QSampleLoadError::FormatError);
 }
 
+void tst_QSampleCache::testLoadSampleFromSpan_declaredFrameCountMismatch_data()
+{
+    QTest::addColumn<uint64_t>("declaredFrameCount");
+
+    // 4 * (2^62 + 256) wraps to 1024 in 64-bit arithmetic
+    QTest::newRow("wrapping") << ((uint64_t(1) << 62) + 256);
+    QTest::newRow("huge") << (uint64_t(1) << 40);
+    QTest::newRow("more-than-data") << uint64_t(1024 * 1024);
+}
+
+void tst_QSampleCache::testLoadSampleFromSpan_declaredFrameCountMismatch()
+{
+    QFETCH(const uint64_t, declaredFrameCount);
+
+    const QByteArray wav = makeRf64Wav(declaredFrameCount, 1, 1024 * 1024);
+    auto result = QSampleCache::loadSample(wav);
+    QVERIFY(!result.has_value());
+    QCOMPARE(result.error(), QSampleLoadError::FormatError);
+}
+
+void tst_QSampleCache::testLoadSampleFromSpan_multiChannel()
+{
+    constexpr uint16_t channelCount = 2;
+    constexpr uint64_t frameCount = 3'000'000; // spans multiple decode chunks
+
+    const QByteArray wav =
+            makeRf64Wav(frameCount, channelCount, qsizetype(frameCount * channelCount * 2));
+    auto result = QSampleCache::loadSample(wav);
+    QVERIFY(result.has_value());
+    QCOMPARE_EQ(result->second.channelCount(), int(channelCount));
+    QCOMPARE_EQ(result->first.size(), qsizetype(frameCount * channelCount * sizeof(float)));
+}
+
+void tst_QSampleCache::testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch()
+{
+    QFETCH(const uint64_t, declaredFrameCount);
+
+    QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface);
+
+    const QByteArray wav = makeRf64Wav(declaredFrameCount, 1, 1024 * 1024);
+    auto result = QSampleCache::loadSampleViaDecoder(wav);
+    QVERIFY(!result.has_value());
+}
+
 void tst_QSampleCache::testLoadSampleViaDecoder_valid()
 {
     const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/test.wav"));
