From e7b118dfba5c6c117a3de08d51f135048cadd652 Mon Sep 17 00:00:00 2001 From: Amorilia <amorilia@users.sourceforge.net> Date: Sat, 17 Sep 2011 09:47:56 +0100 Subject: [PATCH] Provide defaults for the read values, and check for premature read failures (contributed by gentle_sal, see niftools issue #3403926). --- src/NIF_IO.cpp | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/NIF_IO.cpp b/src/NIF_IO.cpp index b70dff24..f39cb744 100644 --- a/src/NIF_IO.cpp +++ b/src/NIF_IO.cpp @@ -111,42 +111,54 @@ float SwapEndian( float in ) { int ReadInt( istream& in ){ - int tmp; + int tmp = 0; in.read( (char*)&tmp, 4 ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } unsigned int ReadUInt( istream& in ){ - unsigned int tmp; + unsigned int tmp = 0; in.read( (char*)&tmp, 4 ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } unsigned short ReadUShort( istream& in ){ - unsigned short tmp; + unsigned short tmp = 0; in.read( (char*)&tmp, 2 ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } short ReadShort( istream& in ){ - short tmp; + short tmp = 0; in.read( (char*)&tmp, 2 ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } byte ReadByte( istream& in ){ - byte tmp; + byte tmp = 0; in.read( (char*)&tmp, 1 ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } float ReadFloat( istream &in ){ - float tmp; + float tmp = 0; in.read( reinterpret_cast<char*>(&tmp), sizeof(tmp) ); + if (in.fail()) + throw runtime_error("premature end of stream"); return tmp; } @@ -157,7 +169,9 @@ string ReadString( istream &in ) { throw runtime_error("String too long. Not a NIF file or unsupported format?"); if ( len > 0 ) { out.resize(len); - in.read( (char*)&out[0], len ); + in.read( (char*)&out[0], len ); + if (in.fail()) + throw runtime_error("premature end of stream"); } return out; } @@ -435,6 +449,8 @@ void NifStream( ShortString & val, istream& in, const NifInfo & info ) { byte len = ReadByte( in ); char * buffer = new char[len]; in.read( buffer, len ); + if (in.fail()) + throw runtime_error("premature end of stream"); val.str = buffer; delete [] buffer; }; -- GitLab