From 3cbb529d16e3b06216414fa0c55e773715a3a358 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:32 +0100 Subject: [PATCH] fix(scene): write the region cache through a temporary file, reject a damaged one (#351) * fix(scene): write the region cache through a temporary file, reject a damaged one The static geometry cache of a scenery (.sbt) was written in place, and only its 8-byte header was checked before it was used. A write cut short (a crash, the process killed, the test mode's real time watchdog) left a truncated file which every later start loaded as it was: the sections up to the cut, then whatever the reads past the end produced, with the section index used unchecked and the section size read and ignored. - basic_region::serialize() writes .sbt.tmp and renames it over the final name only when complete; a failed write is logged and the temporary file removed, the previous file stays. - basic_region::is_scene() checks the whole layout: header, section count, every section index within the region and present once, and the section sizes adding up to the length of the file. A cut-short file is turned down there ("Bad file: ... ignored"), so the scenery loads from the text and the cache is written anew at the end of the load. - basic_region::deserialize() checks the layout again, reads each section out of its own data (sectionsize bytes) and requires the section to use exactly that; sections are restored apart from the region and taken over only when the whole file was read, so a damaged file leaves nothing of itself behind. If the content is damaged although the layout holds, the default .sbt (the game's own copy of the text) is removed so the next start rebuilds it. - A vertex count the rest of the data can't hold, a shape count running past the data, and a string cut short by the end of the data (sn_utils::d_str() looped forever there) now stop the read instead of allocating or looping on. - The layout check and the write through a temporary file are in scene/regionfile.{h,cpp}, in the core library with sn_utils, and have unit tests (test_region_file.cpp). - run.py also removes a .sbt.tmp left by a run cut short. The file format is unchanged. * refactor(scene): the region file code without Sonar issues write_through_temporary takes the writer as a template parameter, the messages are built with std::format, the reading of one section moves into a helper (one break per loop), and the test drops chained assignments and implicit lambda captures. No change in behaviour. --- CMakeLists.txt | 3 +- scene/regionfile.cpp | 130 ++++++++++++ scene/regionfile.h | 77 ++++++++ scene/scene.cpp | 240 ++++++++++++++++------- scene/scene.h | 9 + scene/scenenode.cpp | 16 +- scene/sn_utils.cpp | 16 +- scene/sn_utils.h | 2 + simulation/simulationstateserializer.cpp | 8 +- tests/scenarios/run.py | 9 +- tests/unit/test_region_file.cpp | 207 +++++++++++++++++++ 11 files changed, 634 insertions(+), 83 deletions(-) create mode 100644 scene/regionfile.cpp create mode 100644 scene/regionfile.h create mode 100644 tests/unit/test_region_file.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bb63e935..2f4f8227d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,7 +146,6 @@ set(SOURCES "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" -"scene/sn_utils.cpp" "world/Segment.cpp" "environment/sky.cpp" "environment/sun.cpp" @@ -552,6 +551,8 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"scene/sn_utils.cpp" +"scene/regionfile.cpp" "utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" diff --git a/scene/regionfile.cpp b/scene/regionfile.cpp new file mode 100644 index 000000000..593e07e82 --- /dev/null +++ b/scene/regionfile.cpp @@ -0,0 +1,130 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +namespace scene::region_file { + +std::string +check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ) { + + Input.clear(); + Input.seekg( 0, std::ios::end ); + auto const end { Input.tellg() }; + Input.seekg( 0, std::ios::beg ); + if( ( end < 0 ) || ( false == Input.good() ) ) { + return "can't be read"; + } + auto const filesize { static_cast( end ) }; + + auto const headermain { sn_utils::ld_uint32( Input ) }; + if( auto const headertype { sn_utils::ld_uint32( Input ) }; ( false == Input.good() ) || ( headermain != Header ) || ( headertype != Version ) ) { + return "is of either unrecognized type or version"; + } + auto sectioncount { sn_utils::ld_uint32( Input ) }; + if( false == Input.good() ) { + return "ends before the section count"; + } + if( sectioncount > Sectionlimit ) { + return std::format( "holds {} sections, more than the {} a region has", sectioncount, Sectionlimit ); + } + std::vector present( Sectionlimit, false ); + std::uint64_t position { 3 * sizeof( std::uint32_t ) }; + std::uint32_t sectionnumber { 0 }; + while( sectionnumber < sectioncount ) { + if( filesize - position < section_header_size ) { + return std::format( "ends after {} of its {} sections", sectionnumber, sectioncount ); + } + std::uint32_t index; + std::uint32_t size; + if( auto const error { read_section_header( Input, Sectionlimit, index, size ) }; false == error.empty() ) { + return error; + } + if( true == present[ index ] ) { + return std::format( "holds section {} more than once", index ); + } + present[ index ] = true; + if( filesize - position < size ) { + return std::format( + "ends inside section {} ({} of {}), {} of its {} bytes are there", index, sectionnumber + 1, sectioncount, filesize - position, size ); + } + position += size; + Input.seekg( static_cast( position ), std::ios::beg ); + if( false == Input.good() ) { + return std::format( "can't be read past section {}", index ); + } + ++sectionnumber; + } + if( position != filesize ) { + return std::format( "has {} bytes past its last section", filesize - position ); + } + return {}; +} + +std::string +read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ) { + + Index = sn_utils::ld_uint32( Input ); + Size = sn_utils::ld_uint32( Input ); + if( false == Input.good() ) { + return "ends inside a section header"; + } + if( Index >= Sectionlimit ) { + return std::format( "holds section {}, out of the {} a region has", Index, Sectionlimit ); + } + if( Size < section_header_size ) { + return std::format( "gives section {} the size of {} bytes, less than its header takes", Index, Size ); + } + return {}; +} + +std::string +open_temporary( std::string const &Filename, std::ofstream &Output ) { + + Output.open( Filename + ".tmp", std::ios::binary | std::ios::trunc ); + if( Output.fail() ) { + return "can't write to file \"" + Filename + ".tmp\""; + } + return {}; +} + +std::string +finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ) { + + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + Output.close(); + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + std::filesystem::path const temporaryfile { Filename + ".tmp" }; + std::error_code result; + if( false == Error.empty() ) { + std::filesystem::remove( temporaryfile, result ); + return Error; + } + // the finished file replaces the previous version in one go, so an interrupted write doesn't leave a broken one behind + std::filesystem::rename( temporaryfile, Filename, result ); + if( result ) { + Error = "can't replace file \"" + Filename + "\": " + result.message(); + std::filesystem::remove( temporaryfile, result ); + return Error; + } + return {}; +} + +} // scene::region_file diff --git a/scene/regionfile.h b/scene/regionfile.h new file mode 100644 index 000000000..dd497a487 --- /dev/null +++ b/scene/regionfile.h @@ -0,0 +1,77 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// the parts of the region file (.sbt, the static geometry of a scenery cached by basic_region) which need +// nothing of the scene: checking how a file is laid out, and writing it so that an interrupted write leaves no +// cut-short file behind. kept apart so the unit tests can check them +namespace scene::region_file { + +// layout of the file: the header (two uint32: the file type and its version), the section count (uint32), then for +// each section its index (uint32), its size (uint32, counted from the start of the index, so it covers the index, +// the size itself and the section data) and the section data. all numbers little endian + +// size of the index and the size of a section, the least a section can take +std::uint32_t constexpr section_header_size { 2 * sizeof( std::uint32_t ) }; + +// checks the layout of the file held by the stream, read from its start: the header has to match the provided type +// and version, the sections have to have indices below Sectionlimit, each one no more than once, and their sizes have +// to add up to the length of the file. the section data itself isn't read. returns: the empty string if the layout +// holds, the reason why not otherwise +std::string + check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ); + +// reads the index and the size of the next section, and checks them: the index has to be below Sectionlimit, and the +// section no smaller than its own index and size. returns: the empty string if both were read and are sound, the +// reason why not otherwise +std::string + read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ); + +// opens the temporary file write_through_temporary() writes into. returns: the empty string on success, the reason of +// the failure otherwise +std::string + open_temporary( std::string const &Filename, std::ofstream &Output ); + +// closes the temporary file write_through_temporary() wrote into, and puts it in place of the file, unless Error holds +// the reason why the writing failed. the temporary file is removed on a failure. returns: the empty string on success, +// the reason of the failure otherwise +std::string + finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ); + +// writes a file with the provided function (taking the std::ostream to write into) into a temporary file next to it +// (the name with .tmp added), which then replaces the file in one go. if the writing fails or is cut short, the +// previous file (or none) stays in place, rather than a partial one; the temporary file is removed when the failure is +// noticed. returns: the empty string on success, the reason of the failure otherwise +template +std::string + write_through_temporary( std::string const &Filename, Writer_ const &Write ) { + + std::ofstream output; + if( auto const openerror { open_temporary( Filename, output ) }; false == openerror.empty() ) { + return openerror; + } + std::string error; + try { + Write( output ); + output.flush(); + } + catch( std::exception const &Exception ) { + error = "can't write to file \"" + Filename + ".tmp\": " + Exception.what(); + } + return finish_temporary( Filename, output, std::move( error ) ); +} + +} // scene::region_file diff --git a/scene/scene.cpp b/scene/scene.cpp index eed3f6438..666cd43c0 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -19,17 +19,71 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "scene/sn_utils.h" +#include "scene/regionfile.h" #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" +#include + namespace scene { std::string const EU07_FILEEXTENSION_REGION { ".sbt" }; std::uint32_t const EU07_FILEHEADER { MAKE_ID4( 'E','U','0','7' ) }; std::uint32_t const EU07_FILEVERSION_REGION { MAKE_ID4( 'S', 'B', 'T', '2' ) }; std::map Hierarchy; + +namespace { + +// name of the region file kept for specified scenario file +std::string +region_file_name( std::string const &Scenariofile ) { + + auto filename { Scenariofile }; + while( filename[ 0 ] == '$' ) { + // trim leading $ char rainsted utility may add to the base name for modified .scn files + filename.erase( 0, 1 ); + } + erase_extension( filename ); + filename = Global.asCurrentSceneryPath + filename; + filename += EU07_FILEEXTENSION_REGION; + + return filename; +} + +// reads the next section of a region file into the provided list. returns: the empty string on success, the reason +// of the failure otherwise +std::string +read_region_section( std::istream &Input, std::uint32_t const Sectionlimit, std::vector>> &Sections ) { + + // section index, followed by section data size (counted from the start of the index), followed by section data + std::uint32_t sectionindex; + std::uint32_t sectionsize; + if( auto const error { region_file::read_section_header( Input, Sectionlimit, sectionindex, sectionsize ) }; false == error.empty() ) { + return error; + } + // the section is read out of its own data, it can't reach into the next one + std::string data( sectionsize - region_file::section_header_size, '\0' ); + Input.read( data.data(), static_cast( data.size() ) ); + if( false == Input.good() ) { + return std::format( "ends inside section {}", sectionindex ); + } + std::istringstream sectioninput { std::move( data ) }; + auto section { std::make_unique() }; + section->deserialize( sectioninput ); + std::string error; + if( true == sectioninput.fail() ) { + error = std::format( "has section {} shorter than its content", sectionindex ); + } + else if( sectioninput.peek() != std::char_traits::eof() ) { + error = std::format( "has section {} longer than its content", sectionindex ); + } + Sections.emplace_back( sectionindex, std::move( section ) ); + return error; +} + +} // namespace // potentially activates event handler with the same name as provided node, and within handler activation range void @@ -241,22 +295,38 @@ basic_cell::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // cell shapes // shape count followed by opaque shape data + // NOTE: a damaged count is cut short by the end of the data rather than followed auto itemcount { sn_utils::ld_uint32( Input ) }; - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapesopaque.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapestranslucent.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_lines.emplace_back( lines_node().deserialize( Input ) ); } // cell activation flag m_active = true == m_active || false == m_shapesopaque.empty() || false == m_shapestranslucent.empty() || false == m_lines.empty(); } +// takes over the content restored from a file into another cell, as deserialize() would have added it to this one +void +basic_cell::merge( basic_cell &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapesopaque.insert( m_shapesopaque.end(), std::make_move_iterator( Other.m_shapesopaque.begin() ), std::make_move_iterator( Other.m_shapesopaque.end() ) ); + m_shapestranslucent.insert( m_shapestranslucent.end(), std::make_move_iterator( Other.m_shapestranslucent.begin() ), std::make_move_iterator( Other.m_shapestranslucent.end() ) ); + m_lines.insert( m_lines.end(), std::make_move_iterator( Other.m_lines.begin() ), std::make_move_iterator( Other.m_lines.end() ) ); + m_active = true == m_active || true == Other.m_active; + Other.m_shapesopaque.clear(); + Other.m_shapestranslucent.clear(); + Other.m_lines.clear(); +} + // sends content of the class in legacy (text) format to provided stream void basic_cell::export_as_text( std::ostream &Output ) const { @@ -885,7 +955,7 @@ basic_section::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // section shapes: shape count followed by shape data auto shapecount { sn_utils::ld_uint32( Input ) }; - while( shapecount-- ) { + while( ( shapecount-- ) && ( true == Input.good() ) ) { m_shapes.emplace_back( shape_node().deserialize( Input ) ); } // partitioned data @@ -894,6 +964,19 @@ basic_section::deserialize( std::istream &Input ) { } } +// takes over the content restored from a file into another section, as deserialize() would have added it to this one +void +basic_section::merge( basic_section &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapes.insert( m_shapes.end(), std::make_move_iterator( Other.m_shapes.begin() ), std::make_move_iterator( Other.m_shapes.end() ) ); + Other.m_shapes.clear(); + for( std::size_t index { 0 }; index < m_cells.size(); ++index ) { + m_cells[ index ].merge( std::move( Other.m_cells[ index ] ) ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_section::export_as_text( std::ostream &Output ) const { @@ -1220,26 +1303,17 @@ basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, doubl bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { return false; } - // file type and version check + // file type and version check, and whether the sections add up to the whole file. a file cut short (by a write + // interrupted with an older version, or a copy) is caught here, while the scenery can still be loaded from the text std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type + if( auto const layout { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, static_cast( m_sections.size() ) ) }; + false == layout.empty() ) { + WriteLog( "Bad file: \"" + filename + "\" " + layout + ", ignored" ); return false; } @@ -1250,38 +1324,35 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; - std::ofstream output { filename, std::ios::binary }; - - // region file version 1 - // header: EU07SBT + version (0-255) - sn_utils::ls_uint32( output, EU07_FILEHEADER ); - sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); - // sections - // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { - if( section != nullptr ) { - ++sectioncount; + // the file is written under a temporary name and takes the final one only when complete, so a write cut short + // (a crash, the process killed) leaves no partial file to be read on the next start + auto const error { region_file::write_through_temporary( filename, [ this ]( std::ostream &output ) { + // region file version 1 + // header: EU07SBT + version (0-255) + sn_utils::ls_uint32( output, EU07_FILEHEADER ); + sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); + // sections + // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range + std::uint32_t sectioncount { 0 }; + for( auto *section : m_sections ) { + if( section != nullptr ) { + ++sectioncount; + } } - } - // section count, followed by section data - sn_utils::ls_uint32( output, sectioncount ); - std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { - // section data: section index, followed by length of section data, followed by section data - if( section != nullptr ) { - sn_utils::ls_uint32( output, sectionindex ); - section->serialize( output ); } - ++sectionindex; + // section count, followed by section data + sn_utils::ls_uint32( output, sectioncount ); + std::uint32_t sectionindex { 0 }; + for( auto *section : m_sections ) { + // section data: section index, followed by length of section data, followed by section data + if( section != nullptr ) { + sn_utils::ls_uint32( output, sectionindex ); + section->serialize( output ); } + ++sectionindex; + } } ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: binary version of the scenery wasn't written, " + error ); } } @@ -1289,48 +1360,69 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; return false; } // region file version 1 - // file type and version check + // file type and version check, and whether the sections add up to the whole file std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type - WriteLog( "Bad file: \"" + filename + "\" is of either unrecognized type or version" ); + auto const sectionlimit { static_cast( m_sections.size() ) }; + auto error { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, sectionlimit ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); return false; } // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - // section count - auto sectioncount { sn_utils::ld_uint32( input ) }; - while( sectioncount-- ) { - // section index, followed by section data size, followed by section data - auto const sectionindex { sn_utils::ld_uint32( input ) }; - auto const sectionsize { sn_utils::ld_uint32( input ) }; - if( m_sections[ sectionindex ] == nullptr ) { - m_sections[ sectionindex ] = new basic_section(); + // the sections are restored apart from the region, which takes them over only once the whole file was read + // without a fault: a damaged file leaves nothing of itself behind + std::vector>> sections; + try { + input.clear(); + input.seekg( 2 * sizeof( std::uint32_t ), std::ios::beg ); + // section count + auto sectioncount { sn_utils::ld_uint32( input ) }; + sections.reserve( sectioncount ); + while( ( sectioncount-- ) && ( true == error.empty() ) ) { + error = read_region_section( input, sectionlimit, sections ); + } + } + catch( std::exception const &Exception ) { + error = std::string( "can't be read, " ) + Exception.what(); + } + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); + return false; + } + for( auto &[ sectionindex, section ] : sections ) { + if( m_sections[ sectionindex ] == nullptr ) { + m_sections[ sectionindex ] = section.release(); + } + else { + m_sections[ sectionindex ]->merge( std::move( *section ) ); } - m_sections[ sectionindex ]->deserialize( input ); } return true; } +// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew +void +basic_region::discard_scene( std::string const &Scenariofile ) const { + + auto const filename { region_file_name( Scenariofile ) }; + std::error_code error; + if( true == std::filesystem::remove( filename, error ) ) { + WriteLog( "Bad file: \"" + filename + "\" removed, it will be made anew from the scenery on the next start" ); + } + else if( error ) { + ErrorLog( "Bad file: \"" + filename + "\" can't be removed, " + error.message() + ". Remove it to have it made anew from the scenery" ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_region::export_as_text( std::ostream &Output ) const { diff --git a/scene/scene.h b/scene/scene.h index b8256e257..bde88bc87 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -134,6 +134,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another cell, as deserialize() would have added it to this one + void + merge( basic_cell &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -343,6 +346,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another section, as deserialize() would have added it to this one + void + merge( basic_section &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -474,6 +480,9 @@ public: // restores content of the class from file with specified name. returns: true on success, false otherwise bool deserialize( std::string const &Scenariofile ); + // removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew + void + discard_scene( std::string const &Scenariofile ) const; // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 18b1905a4..afe87cf83 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -108,7 +108,13 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); if(has_userdata) userdata.resize(vertices.size()); gfx::basic_vertex localvertex; @@ -527,7 +533,13 @@ lines_node::linesnode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); gfx::basic_vertex localvertex; for( auto &vertex : vertices ) { localvertex.deserialize( Input ); diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index b6a3f7c32..fbdbcb7f0 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -93,14 +93,26 @@ std::string sn_utils::d_str(std::istream &s) char c{}; while (true) { - s.read(&c, 1); - if (c == 0) + // a string cut short by the end of the data ends there too + if (!s.read(&c, 1) || c == 0) break; r.push_back(c); } return r; } +// number of bytes left to read in the stream, 0 if it failed or can't tell +std::uint64_t sn_utils::remaining(std::istream &s) +{ + auto const position{s.tellg()}; + if (position < 0) + return 0; + s.seekg(0, std::ios::end); + auto const end{s.tellg()}; + s.seekg(position); + return end > position ? static_cast(end - position) : 0; +} + bool sn_utils::d_bool(std::istream& s) { return ld_uint16(s) == 1; diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 4212ac29a..87da22d93 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -20,6 +20,8 @@ public: static glm::dvec3 d_dvec3(std::istream&); static glm::vec3 d_vec3(std::istream&); static glm::vec4 d_vec4(std::istream&); + // number of bytes left to read in the stream, 0 if it failed or can't tell + static std::uint64_t remaining(std::istream&); static void ls_uint16(std::ostream&, uint16_t); static void ls_uint32(std::ostream&, uint32_t); diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index da3e075ef..0b114f837 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -426,7 +426,13 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc // TBD: postpone loading furter and only load required blocks during the simulation? if (false == Scratchpad.binary.terrain_included) { - Region->deserialize(Scratchpad.name); + if (false == Region->deserialize(Scratchpad.name)) + { + // the file looked whole to is_scene() but its content is damaged. the geometry it holds is missing from this + // session, as the text definitions were skipped already. the file is the game's own copy of the text, so it + // goes, and the next start loads the text and writes it anew + Region->discard_scene(Scratchpad.name); + } } else { diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 52ff6cf2a..438b68aa4 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -883,10 +883,13 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}") ok &= passed # a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing - # the scenery's geometry cache; the simulator checks only the header of it, so the next runs would read - # a truncated one. it is written again on the next run + # the scenery's geometry cache. the simulator writes it through .sbt.tmp and turns down a cut-short + # one, but older builds wrote it in place and checked only its header, so the next runs would read a + # truncated one. either is written again on the next run if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)): - scenery_cache(game_dir, name).unlink(missing_ok=True) + cache = scenery_cache(game_dir, name) + cache.unlink(missing_ok=True) + cache.with_name(cache.name + ".tmp").unlink(missing_ok=True) if result.failure: say(f" FAIL {result.failure}") ok = False diff --git a/tests/unit/test_region_file.cpp b/tests/unit/test_region_file.cpp new file mode 100644 index 000000000..346823ae3 --- /dev/null +++ b/tests/unit/test_region_file.cpp @@ -0,0 +1,207 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +// the region file (.sbt), the static geometry of a scenery the game caches beside it: a file cut short or +// damaged is turned down before any of it is used, and the game writes it so that it is never left cut short + +namespace { + +std::uint32_t constexpr header{0x37305545}; // EU07 +std::uint32_t constexpr version{0x32544253}; // SBT2 +std::uint32_t constexpr sectionlimit{500 * 500}; + +struct section { + std::uint32_t index; + std::string data; +}; + +// the file as basic_region::serialize() lays it out: the section size covers the index, the size and the data +std::string region(std::vector
const &Sections, std::uint32_t const Header = header, std::uint32_t const Version = version) { + std::ostringstream output; + sn_utils::ls_uint32(output, Header); + sn_utils::ls_uint32(output, Version); + sn_utils::ls_uint32(output, static_cast(Sections.size())); + for (auto const §ion : Sections) { + sn_utils::ls_uint32(output, section.index); + sn_utils::ls_uint32(output, static_cast(scene::region_file::section_header_size + section.data.size())); + output << section.data; + } + return output.str(); +} + +std::string check(std::string const &File) { + std::istringstream input{File}; + return scene::region_file::check_layout(input, header, version, sectionlimit); +} + +// what a writer throws when it gives up +class writer_failure : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +std::string read(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + return {std::istreambuf_iterator{input}, std::istreambuf_iterator{}}; +} + +} // namespace + +TEST_CASE("region file: a file laid out whole is accepted, with no sections or with many") { + CHECK(check(region({})) == ""); + CHECK(check(region({{0, ""}, {7, std::string(100, 'x')}, {sectionlimit - 1, std::string(3, '\0')}})) == ""); +} + +TEST_CASE("region file: a file cut short anywhere is turned down") { + auto const file{region({{12, std::string(40, 'a')}, {13, std::string(7, 'b')}, {250, std::string(64, 'c')}})}; + REQUIRE(check(file) == ""); + for (std::size_t length{0}; length < file.size(); ++length) { + CAPTURE(length); + CHECK(check(file.substr(0, length)) != ""); + } + // the count of the sections is checked against those present, and the length against where the last one ends + CHECK(check(file.substr(0, file.size() - 64 - 8)).find("ends after 2 of its 3 sections") != std::string::npos); + CHECK(check(file.substr(0, file.size() / 2)).find("ends inside section") != std::string::npos); +} + +TEST_CASE("region file: a file of another type or version is turned down") { + CHECK(check(region({{1, "x"}}, header, version + 1)).find("unrecognized type or version") != std::string::npos); + CHECK(check(region({{1, "x"}}, header + 1, version)).find("unrecognized type or version") != std::string::npos); + CHECK(check("EU0").find("unrecognized type or version") != std::string::npos); +} + +TEST_CASE("region file: sections the region can't hold, held twice, or of impossible sizes are turned down") { + CHECK(check(region({{sectionlimit, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{0xffffffffu, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{5, "x"}, {5, "y"}})).find("more than once") != std::string::npos); + + // a size smaller than the header of the section + auto file{region({{5, "abcd"}})}; + file[16] = 7; + file[17] = 0; + file[18] = 0; + file[19] = 0; + CHECK(check(file).find("less than its header takes") != std::string::npos); + // a size reaching past the end of the file + file[16] = 13; + CHECK(check(file).find("ends inside section 5") != std::string::npos); + // a size falling short of it + file[16] = 11; + CHECK(check(file).find("bytes past its last section") != std::string::npos); + // more sections than a region has + auto many{region({})}; + for (std::size_t byte{8}; byte < 12; ++byte) { + many[byte] = static_cast(0xff); + } + CHECK(check(many).find("more than the 250000") != std::string::npos); +} + +TEST_CASE("region file: the header of a section is read and checked") { + std::uint32_t index{0}; + std::uint32_t size{0}; + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size) == ""); + CHECK(index == 42); + CHECK(size == 11); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12, 6)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size).find("ends inside a section header") != std::string::npos); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, 42, index, size).find("out of the 42") != std::string::npos); + } +} + +TEST_CASE("region file: a string cut short by the end of the data ends there, rather than being read on forever") { + std::istringstream input{std::string{"abc"}}; + CHECK(sn_utils::d_str(input) == "abc"); + CHECK(input.fail()); + CHECK(sn_utils::d_str(input) == ""); + + std::istringstream whole{std::string{"abc\0def", 7}}; + CHECK(sn_utils::d_str(whole) == "abc"); + CHECK(whole.good()); +} + +TEST_CASE("region file: the bytes left in the data are known, so a count it can't hold is turned down before anything is made for it") { + std::istringstream input{std::string(100, 'x')}; + CHECK(sn_utils::remaining(input) == 100); + sn_utils::ld_uint32(input); + CHECK(sn_utils::remaining(input) == 96); + // asking doesn't move the reading on + CHECK(sn_utils::ld_uint32(input) == 0x78787878); + input.seekg(0, std::ios::end); + CHECK(sn_utils::remaining(input) == 0); + sn_utils::ld_uint32(input); + CHECK(input.fail()); + CHECK(sn_utils::remaining(input) == 0); +} + +TEST_CASE("region file: the file is written through a temporary one, which replaces the previous file when complete") { + test::scratch_folder folder{"region_file"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + auto const write = [&file](std::string const &Content) { + return scene::region_file::write_through_temporary(file.string(), [&Content](std::ostream &Output) { Output << Content; }); + }; + + SUBCASE("a new file") { + CHECK(write("first") == ""); + CHECK(read(file) == "first"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a previous file is replaced, a longer one entirely") { + REQUIRE(write("a much longer first version") == ""); + CHECK(write("second") == ""); + CHECK(read(file) == "second"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a temporary file left by a write cut short earlier is written over") { + folder.write("scenery.sbt.tmp", "left over from a crash, longer than what follows"); + CHECK(write("third") == ""); + CHECK(read(file) == "third"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } +} + +TEST_CASE("region file: a write which fails leaves the previous file, or none, and no temporary file") { + test::scratch_folder folder{"region_file_failed"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + folder.write("scenery.sbt", "previous"); + + SUBCASE("the writer gives up half way") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + throw writer_failure("out of memory"); + })}; + CHECK(error.find("out of memory") != std::string::npos); + } + SUBCASE("the stream fails") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + Output.setstate(std::ios::badbit); + })}; + CHECK(error.find("can't write to file") != std::string::npos); + } + CHECK(read(file) == "previous"); + CHECK_FALSE(std::filesystem::exists(temporary)); + + SUBCASE("the temporary file can't be made") { + auto const missing{folder.root() / "no such folder" / "scenery.sbt"}; + auto const error{scene::region_file::write_through_temporary(missing.string(), [](std::ostream &Output) { Output << "x"; })}; + CHECK(error.find("can't write to file") != std::string::npos); + CHECK_FALSE(std::filesystem::exists(missing)); + } +}