From 4bb41d065bb0474582042462cf9c34bdbc1e50e3 Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Wed, 23 Nov 2016 16:57:01 +0100 Subject: [PATCH] :bug: parsing erroneous files yields an exception (#366) --- src/json.hpp | 6 ++++++ src/json.hpp.re2c | 6 ++++++ test/src/unit-regression.cpp | 6 ++++++ 3 files changed, 18 insertions(+) diff --git a/src/json.hpp b/src/json.hpp index e71ffc4a..dbe49c2a 100644 --- a/src/json.hpp +++ b/src/json.hpp @@ -7597,6 +7597,12 @@ class basic_json explicit lexer(std::istream& s) : m_stream(&s), m_line_buffer() { + // immediately abort if stream is erroneous + if (s.fail()) + { + throw std::invalid_argument("stream error: " + std::string(strerror(errno))); + } + // fill buffer fill_line_buffer(); diff --git a/src/json.hpp.re2c b/src/json.hpp.re2c index 9eccc144..ef9910ce 100644 --- a/src/json.hpp.re2c +++ b/src/json.hpp.re2c @@ -7597,6 +7597,12 @@ class basic_json explicit lexer(std::istream& s) : m_stream(&s), m_line_buffer() { + // immediately abort if stream is erroneous + if (s.fail()) + { + throw std::invalid_argument("stream error: " + std::string(strerror(errno))); + } + // fill buffer fill_line_buffer(); diff --git a/test/src/unit-regression.cpp b/test/src/unit-regression.cpp index 661edc25..ac6d25df 100644 --- a/test/src/unit-regression.cpp +++ b/test/src/unit-regression.cpp @@ -495,4 +495,10 @@ TEST_CASE("regression tests") json j = json::parse("22e2222"); CHECK(j == json()); } + + SECTION("issue #366 - json::parse on failed stream gets stuck") + { + std::ifstream f("file_not_found.json"); + CHECK_THROWS_AS(json::parse(f), std::invalid_argument); + } }