From 1f4e6022ac318e7c348da4b5f74739937fc2aa75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Tue, 15 May 2012 12:49:38 +0200 Subject: [PATCH] TgaImporter: check if the file is long enough. Prevents undefined behavior when opening e.g. empty files. --- src/Plugins/TgaImporter/Test/TgaImporterTest.cpp | 12 ++++++++++++ src/Plugins/TgaImporter/Test/TgaImporterTest.h | 1 + src/Plugins/TgaImporter/TgaImporter.cpp | 9 +++++++++ 3 files changed, 22 insertions(+) diff --git a/src/Plugins/TgaImporter/Test/TgaImporterTest.cpp b/src/Plugins/TgaImporter/Test/TgaImporterTest.cpp index a237555d0..29db4bc52 100644 --- a/src/Plugins/TgaImporter/Test/TgaImporterTest.cpp +++ b/src/Plugins/TgaImporter/Test/TgaImporterTest.cpp @@ -36,6 +36,18 @@ void TgaImporterTest::openInexistent() { QCOMPARE(debug.str().c_str(), "TgaImporter: cannot open file inexistent.file\n"); } +void TgaImporterTest::openShort() { + const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + istringstream in(string(data, sizeof(data))); + + ostringstream debug; + Error::setOutput(&debug); + + TgaImporter importer; + QVERIFY(!importer.open(in)); + QCOMPARE(debug.str().c_str(), "TgaImporter: the file is too short: 17 bytes\n"); +} + void TgaImporterTest::paletted() { const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; istringstream in(string(data, sizeof(data))); diff --git a/src/Plugins/TgaImporter/Test/TgaImporterTest.h b/src/Plugins/TgaImporter/Test/TgaImporterTest.h index f4647c681..e4d0f1fac 100644 --- a/src/Plugins/TgaImporter/Test/TgaImporterTest.h +++ b/src/Plugins/TgaImporter/Test/TgaImporterTest.h @@ -24,6 +24,7 @@ class TgaImporterTest: public QObject { private slots: void openInexistent(); + void openShort(); void paletted(); void nonRgb(); void bits16(); diff --git a/src/Plugins/TgaImporter/TgaImporter.cpp b/src/Plugins/TgaImporter/TgaImporter.cpp index 359f6158f..a8c49a176 100644 --- a/src/Plugins/TgaImporter/TgaImporter.cpp +++ b/src/Plugins/TgaImporter/TgaImporter.cpp @@ -47,6 +47,15 @@ bool TgaImporter::open(std::istream& in) { return false; } + /* Check if the file is long enough */ + in.seekg(0, istream::end); + streampos filesize = in.tellg(); + in.seekg(0, istream::beg); + if(filesize < streampos(sizeof(Header))) { + Error() << "TgaImporter: the file is too short:" << filesize << "bytes"; + return false; + } + Header header; in.read(reinterpret_cast(&header), sizeof(Header));