diff --git a/code/menuui/readyroom.cpp b/code/menuui/readyroom.cpp index 073759a5940..f78177f089a 100644 --- a/code/menuui/readyroom.cpp +++ b/code/menuui/readyroom.cpp @@ -831,7 +831,8 @@ int readyroom_continue_campaign() { // check for possible mission loop, need to do this before calling mission_campaign_next_mission()! if ( !(Game_mode & GM_MULTIPLAYER) && !Campaign.loop_enabled && (Campaign.current_mission == -1) && - (Campaign.prev_mission != -1) && (Campaign.next_mission != -1) ) + (Campaign.prev_mission >= 0) && (Campaign.prev_mission < Campaign.num_missions) && + (Campaign.next_mission != -1) ) { if (Campaign.missions[Campaign.prev_mission].flags & CMISSION_FLAG_HAS_LOOP) { // NOTE: the order of these calls is *very* important diff --git a/code/pilotfile/BinaryFileHandler.cpp b/code/pilotfile/BinaryFileHandler.cpp index bf8c2426744..f70b8d9c9b6 100644 --- a/code/pilotfile/BinaryFileHandler.cpp +++ b/code/pilotfile/BinaryFileHandler.cpp @@ -151,6 +151,10 @@ Section pilot::BinaryFileHandler::nextSection() { if (size == 0) { return Section::Invalid; } + if (size > static_cast(cfilelength(_cfp)) - static_cast(cftell(_cfp))) { + mprintf(("PLR => WARNING: Section runs past the end of the file.\n")); + return Section::Invalid; + } _section_start_pos = (size_t)cftell(_cfp); _section_end_pos = _section_start_pos + size; @@ -167,11 +171,10 @@ size_t pilot::BinaryFileHandler::startArrayRead(const char*, bool short_index) { Assertion(!_in_array, "Array nesting is not supported!"); _in_array = true; - if (short_index) { - return (size_t) cfread_short(_cfp); - } else { - return (size_t) cfread_int(_cfp); - } + auto count = short_index ? (size_t)cfread_short(_cfp) : (size_t)cfread_int(_cfp); + + // every array element takes at least one byte, so a larger count has no data behind it + return std::min(count, static_cast(cfilelength(_cfp)) - static_cast(cftell(_cfp))); } void pilot::BinaryFileHandler::nextArraySection() { Assertion(_in_array, "nextArraySection() may only be called in an array!"); @@ -182,3 +185,6 @@ void pilot::BinaryFileHandler::endArrayRead() { _in_array = false; } +bool pilot::BinaryFileHandler::atEndOfFile() { + return cfeof(_cfp) != 0; +} diff --git a/code/pilotfile/BinaryFileHandler.h b/code/pilotfile/BinaryFileHandler.h index e878e9732d0..c60bc5c9443 100644 --- a/code/pilotfile/BinaryFileHandler.h +++ b/code/pilotfile/BinaryFileHandler.h @@ -90,6 +90,8 @@ class BinaryFileHandler: public FileHandler { void nextArraySection() override; void endArrayRead() override; + + bool atEndOfFile() override; }; } diff --git a/code/pilotfile/FileHandler.h b/code/pilotfile/FileHandler.h index c75c49fce2a..19b5cabb1e9 100644 --- a/code/pilotfile/FileHandler.h +++ b/code/pilotfile/FileHandler.h @@ -109,6 +109,11 @@ class FileHandler { virtual void nextArraySection() = 0; virtual void endArrayRead() = 0; + + // only the binary format hands back empty values once its data has run out + virtual bool atEndOfFile() { + return false; + } }; } diff --git a/code/pilotfile/csg.cpp b/code/pilotfile/csg.cpp index a03ef84e953..83da068935d 100644 --- a/code/pilotfile/csg.cpp +++ b/code/pilotfile/csg.cpp @@ -81,7 +81,8 @@ void pilotfile::csg_read_info() // ship list (NOTE: may contain more ship classes than this mod defines) list_size = cfread_int(cfp); - for (idx = 0; idx < list_size; idx++) { + // reads at the end of the file return 0 without failing, so loops over a count from the file also stop there + for (idx = 0; idx < list_size && !cfeof(cfp); idx++) { cfread_string_len(t_string, NAME_LENGTH, cfp); ilist.name = t_string; @@ -93,7 +94,7 @@ void pilotfile::csg_read_info() // weapon list (NOTE: may contain more weapon classes than this mod defines) list_size = cfread_int(cfp); - for (idx = 0; idx < list_size; idx++) { + for (idx = 0; idx < list_size && !cfeof(cfp); idx++) { cfread_string_len(t_string, NAME_LENGTH, cfp); ilist.name = t_string; @@ -105,7 +106,7 @@ void pilotfile::csg_read_info() // intel list (NOTE: may contain more than MAX_INTEL_ENTRIES) list_size = cfread_int(cfp); - for (idx = 0; idx < list_size; idx++) { + for (idx = 0; idx < list_size && !cfeof(cfp); idx++) { cfread_string_len(t_string, NAME_LENGTH, cfp); ilist.name = t_string; @@ -117,7 +118,7 @@ void pilotfile::csg_read_info() // medals list (NOTE: may contain more than Num_medals) list_size = cfread_int(cfp); - for (idx = 0; idx < list_size; idx++) { + for (idx = 0; idx < list_size && !cfeof(cfp); idx++) { cfread_string_len(t_string, NAME_LENGTH, cfp); ilist.name = t_string; @@ -130,28 +131,44 @@ void pilotfile::csg_read_info() idx = cfread_int(cfp); // check the idx is within bounds - Assertion ((idx < (int)ship_list.size()), "Campaign file contains an incorrect value for the last flown ship class. No data in ship_list for ship number %d.", idx); - if (idx >= (int)ship_list.size()) - idx = -1; - else if (idx != -1) + if ((idx >= 0) && (idx < (int)ship_list.size())) { p->last_ship_flown_si_index = ship_list[idx].index; - else + } else { + if (idx != -1) { + mprintf(("CSG => Parse Warning: Invalid last flown ship index (%d), clearing it.\n", idx)); + } p->last_ship_flown_si_index = -1; + } // progression state Campaign.prev_mission = cfread_int(cfp); + if (Campaign.num_missions > 0 && (Campaign.prev_mission < -1 || Campaign.prev_mission >= Campaign.num_missions)) { + mprintf(("CSG => Parse Warning: Invalid previous mission (%d), clearing it.\n", Campaign.prev_mission)); + Campaign.prev_mission = -1; + } Campaign.next_mission = cfread_int(cfp); // check that the next mission won't be greater than the total number of missions // though ensure we only flag if campaign exists and has been loaded - if (Campaign.num_missions > 0 && Campaign.next_mission >= Campaign.num_missions) { + if (Campaign.num_missions > 0 && (Campaign.next_mission < -1 || Campaign.next_mission >= Campaign.num_missions)) { Campaign.next_mission = 0; // Prevent trying to load from invalid mission data downstream m_data_invalid = true; // Causes a warning popup to be displayed } // loop state Campaign.loop_reentry = cfread_int(cfp); + bool invalid_loop_reentry = + Campaign.num_missions > 0 && (Campaign.loop_reentry < -1 || Campaign.loop_reentry >= Campaign.num_missions); + if (invalid_loop_reentry) { + mprintf(("CSG => Parse Warning: Invalid loop reentry (%d), leaving the loop.\n", Campaign.loop_reentry)); + Campaign.loop_reentry = -1; + // also cleared before the read, in case the section ends there + Campaign.loop_enabled = 0; + } Campaign.loop_enabled = cfread_int(cfp); + if (invalid_loop_reentry) { + Campaign.loop_enabled = 0; + } // missions completed Campaign.num_missions_completed = cfread_int(cfp); @@ -266,14 +283,22 @@ void pilotfile::csg_read_missions() { int i, j, idx, list_size; cmission *missionp; + cmission discarded_mission; + int num_discarded = 0; if ( !m_have_info ) { throw "Missions before Info!"; } - for (i = 0; i < Campaign.num_missions_completed; i++) { + for (i = 0; i < Campaign.num_missions_completed && !cfeof(cfp); i++) { idx = cfread_int(cfp); - missionp = &Campaign.missions[idx]; + if ((idx < 0) || (idx >= MAX_CAMPAIGN_MISSIONS)) { + mprintf(("CSG => Parse Warning: Invalid mission index (%d), discarding its record.\n", idx)); + missionp = &discarded_mission; + num_discarded++; + } else { + missionp = &Campaign.missions[idx]; + } missionp->completed = 1; @@ -284,7 +309,7 @@ void pilotfile::csg_read_missions() missionp->goals.clear(); int num_goals = cfread_int(cfp); - for (j = 0; j < num_goals; j++) { + for (j = 0; j < num_goals && !cfeof(cfp); j++) { missionp->goals.emplace_back(); auto& stored_goal = missionp->goals.back(); @@ -296,7 +321,7 @@ void pilotfile::csg_read_missions() missionp->events.clear(); int num_events = cfread_int(cfp); - for (j = 0; j < num_events; j++) { + for (j = 0; j < num_events && !cfeof(cfp); j++) { missionp->events.emplace_back(); auto& stored_event = missionp->events.back(); @@ -308,7 +333,7 @@ void pilotfile::csg_read_missions() missionp->variables.clear(); int num_variables = cfread_int(cfp); - for (j = 0; j < num_variables; j++) { + for (j = 0; j < num_variables && !cfeof(cfp); j++) { missionp->variables.emplace_back(); auto& stored_variable = missionp->variables.back(); @@ -353,6 +378,8 @@ void pilotfile::csg_read_missions() } } } + + Campaign.num_missions_completed = i - num_discarded; } void pilotfile::csg_write_missions() @@ -619,7 +646,7 @@ void pilotfile::csg_read_loadout() // primary weapons count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { wep_idx = cfread_int(cfp); if ( (wep_idx >= (int)weapon_list.size()) || (wep_idx < -1) ) { @@ -646,7 +673,7 @@ void pilotfile::csg_read_loadout() // secondary weapons count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { wep_idx = cfread_int(cfp); if ( (wep_idx >= (int)weapon_list.size()) || (wep_idx < -1) ) { @@ -830,7 +857,7 @@ void pilotfile::csg_read_redalert() Red_alert_precursor_mission = t_string; - for (idx = 0; idx < ship_list_size; idx++) { + for (idx = 0; idx < ship_list_size && !cfeof(cfp); idx++) { red_alert_ship_status ras; cfread_string_len(t_string, NAME_LENGTH, cfp); @@ -852,7 +879,7 @@ void pilotfile::csg_read_redalert() // subsystem hits count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { hit = cfread_float(cfp); ras.subsys_current_hits.push_back( hit ); } @@ -860,7 +887,7 @@ void pilotfile::csg_read_redalert() // subsystem aggregate hits count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { hit = cfread_float(cfp); ras.subsys_aggregate_current_hits.push_back( hit ); } @@ -868,11 +895,16 @@ void pilotfile::csg_read_redalert() // primary weapon loadout and status count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { i = cfread_int(cfp); - weapons.index = weapon_list[i].index; weapons.count = cfread_int(cfp); + if ((i < 0) || (i >= (int)weapon_list.size())) { + mprintf(("CSG => Parse Warning: Invalid value for red alert weapon index (%d), skipping.\n", i)); + continue; + } + weapons.index = weapon_list[i].index; + // triggering this means something is really fubar if (weapons.index < 0) { continue; @@ -884,11 +916,16 @@ void pilotfile::csg_read_redalert() // secondary weapon loadout and status count = cfread_int(cfp); - for (j = 0; j < count; j++) { + for (j = 0; j < count && !cfeof(cfp); j++) { i = cfread_int(cfp); - weapons.index = weapon_list[i].index; weapons.count = cfread_int(cfp); + if ((i < 0) || (i >= (int)weapon_list.size())) { + mprintf(("CSG => Parse Warning: Invalid value for red alert weapon index (%d), skipping.\n", i)); + continue; + } + weapons.index = weapon_list[i].index; + // triggering this means something is really fubar if (weapons.index < 0) { continue; @@ -914,7 +951,7 @@ void pilotfile::csg_read_redalert() wing_list_size = cfread_int(cfp); if (wing_list_size > 0) { - for (idx = 0; idx < wing_list_size; idx++) { + for (idx = 0; idx < wing_list_size && !cfeof(cfp); idx++) { red_alert_wing_status rws; cfread_string_len(t_string, NAME_LENGTH, cfp); @@ -1085,7 +1122,7 @@ void pilotfile::csg_read_hud() // gauge-specific colors int num_gauges = cfread_int(cfp); - for (int idx = 0; idx < num_gauges; idx++) { + for (int idx = 0; idx < num_gauges && !cfeof(cfp); idx++) { ubyte red = cfread_ubyte(cfp); ubyte green = cfread_ubyte(cfp); ubyte blue = cfread_ubyte(cfp); @@ -1181,7 +1218,7 @@ void pilotfile::csg_read_variables() if (num_variables > 0) { - for (idx = 0; idx < num_variables; idx++) { + for (idx = 0; idx < num_variables && !cfeof(cfp); idx++) { sexp_variable temp_var; memset(&temp_var, 0, sizeof(sexp_variable)); temp_var.type = cfread_int(cfp); @@ -1206,7 +1243,7 @@ void pilotfile::csg_read_variables() int redalert_num_variables = cfread_int(cfp); if (redalert_num_variables > 0) { - for (idx = 0; idx < redalert_num_variables; idx++) { + for (idx = 0; idx < redalert_num_variables && !cfeof(cfp); idx++) { sexp_variable temp_var; memset(&temp_var, 0, sizeof(sexp_variable)); temp_var.type = cfread_int(cfp); @@ -1426,7 +1463,7 @@ void pilotfile::csg_write_controls() void pilotfile::csg_read_cutscenes() { size_t list_size = cfread_uint(cfp); - for(size_t i = 0; i < list_size; i++) { + for (size_t i = 0; i < list_size && !cfeof(cfp); i++) { char tempFilename[MAX_FILENAME_LEN]; cfread_string_len(tempFilename, MAX_FILENAME_LEN, cfp); @@ -1468,9 +1505,17 @@ void pilotfile::csg_read_lastmissions() int i; // restore list of most recently played missions - Num_recent_missions = cfread_int( cfp ); - Assert(Num_recent_missions <= MAX_RECENT_MISSIONS); - for ( i = 0; i < Num_recent_missions; i++ ) { + // count each entry only once it has been read, so a short section can't leave stale names in the list + Num_recent_missions = 0; + int count = cfread_int( cfp ); + if ((count < 0) || (count > MAX_RECENT_MISSIONS)) { + ReleaseWarning(LOCATION, + "Campaign file has invalid recent mission count %d, keeping at most %d.\n", + count, + MAX_RECENT_MISSIONS); + count = std::clamp(count, 0, MAX_RECENT_MISSIONS); + } + for (i = 0; i < count && !cfeof(cfp); i++) { char *cp; cfread_string_len( Recent_missions[i], MAX_FILENAME_LEN, cfp); @@ -1478,6 +1523,7 @@ void pilotfile::csg_read_lastmissions() cp = strchr(Recent_missions[i], '.'); if (cp) *cp = 0; + Num_recent_missions = i + 1; } } @@ -1504,7 +1550,7 @@ void pilotfile::csg_read_containers() { const int num_containers = cfread_int(cfp); - for (int idx = 0; idx < num_containers; idx++) { + for (int idx = 0; idx < num_containers && !cfeof(cfp); idx++) { Campaign.persistent_containers.emplace_back(); auto& container = Campaign.persistent_containers.back(); csg_read_container(container); @@ -1520,7 +1566,7 @@ void pilotfile::csg_read_containers() const int redalert_num_containers = cfread_int(cfp); - for (int idx = 0; idx < redalert_num_containers; idx++) { + for (int idx = 0; idx < redalert_num_containers && !cfeof(cfp); idx++) { Campaign.red_alert_containers.emplace_back(); auto& ra_container = Campaign.red_alert_containers.back(); csg_read_container(ra_container); @@ -1541,7 +1587,7 @@ void pilotfile::csg_read_container(sexp_container& container) const int size = cfread_int(cfp); if (container.is_list()) { - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size && !cfeof(cfp); ++i) { cfread_string_len(temp_buf, sizeof(temp_buf), cfp); container.list_data.emplace_back(temp_buf); } @@ -1549,7 +1595,7 @@ void pilotfile::csg_read_container(sexp_container& container) char temp_key[NAME_LENGTH]; memset(temp_key, 0, sizeof(temp_key)); - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size && !cfeof(cfp); ++i) { cfread_string_len(temp_key, sizeof(temp_key), cfp); cfread_string_len(temp_buf, sizeof(temp_buf), cfp); container.map_data.emplace(temp_key, temp_buf); @@ -1737,6 +1783,15 @@ bool pilotfile::load_savefile(player *_p, const char *campaign) size_t start_pos = cftell(cfp); + // a size of 0 would turn the read limit off, and only an empty section is written with it + if (section_size == 0) { + continue; + } + if (section_size > static_cast(cfilelength(cfp)) - start_pos) { + mprintf(("CSG => Warning: (0x%04x) Section runs past the end of the file.\n", (uint32_t)section_id)); + break; + } + // safety, to help protect against long reads cf_set_max_read_len(cfp, section_size); @@ -2007,6 +2062,15 @@ bool pilotfile::get_csg_rank(int *rank) size_t start_pos = cftell(cfp); size_t offset_pos; + // a size of 0 would turn the read limit off, and only an empty section is written with it + if (section_size == 0) { + continue; + } + if (section_size > static_cast(cfilelength(cfp)) - start_pos) { + mprintf(("CSG => Warning: (0x%04x) Section runs past the end of the file.\n", (uint32_t)section_id)); + break; + } + // safety, to help protect against long reads cf_set_max_read_len(cfp, section_size); diff --git a/code/pilotfile/csg_convert.cpp b/code/pilotfile/csg_convert.cpp index 58a2ae8003a..0d6d8323991 100644 --- a/code/pilotfile/csg_convert.cpp +++ b/code/pilotfile/csg_convert.cpp @@ -307,7 +307,7 @@ void pilotfile_convert::csg_import_missions(bool inferno) if (inferno) { cfread(&t_inf_score, sizeof(scoring_conv_INF_t), 1, cfp); - for (j = 0; j < ship_list_size; j++) { + for (j = 0; j < MIN(ship_list_size, (int)(sizeof(t_inf_score.kills) / sizeof(t_inf_score.kills[0]))); j++) { miss.stats.ship_kills[j].val = INTEL_INT(t_inf_score.kills[j]); } @@ -324,13 +324,13 @@ void pilotfile_convert::csg_import_missions(bool inferno) miss.stats.s_bonehead_hits = INTEL_INT(t_inf_score.s_bonehead_hits); miss.stats.bonehead_kills = INTEL_INT(t_inf_score.bonehead_kills); - for (j = 0; j < 18; j++) { + for (j = 0; j < MIN(18, (int)miss.stats.medals_earned.size()); j++) { miss.stats.medals_earned[j].val = INTEL_INT(t_inf_score.medals[j]); } } else { cfread(&t_score, sizeof(scoring_conv_t), 1, cfp); - for (j = 0; j < ship_list_size; j++) { + for (j = 0; j < MIN(ship_list_size, (int)(sizeof(t_score.kills) / sizeof(t_score.kills[0]))); j++) { miss.stats.ship_kills[j].val = INTEL_INT(t_score.kills[j]); } @@ -347,7 +347,7 @@ void pilotfile_convert::csg_import_missions(bool inferno) miss.stats.s_bonehead_hits = INTEL_INT(t_score.s_bonehead_hits); miss.stats.bonehead_kills = INTEL_INT(t_score.bonehead_kills); - for (j = 0; j < 18; j++) { + for (j = 0; j < MIN(18, (int)miss.stats.medals_earned.size()); j++) { miss.stats.medals_earned[j].val = INTEL_INT(t_score.medals[j]); } } diff --git a/code/pilotfile/plr.cpp b/code/pilotfile/plr.cpp index 59f05238c6b..145867c33d8 100644 --- a/code/pilotfile/plr.cpp +++ b/code/pilotfile/plr.cpp @@ -350,7 +350,7 @@ void pilotfile::plr_read_variables() auto list_size = handler->startArrayRead("variables"); p->variables.reserve(list_size); - for (size_t idx = 0; idx < list_size; idx++, handler->nextArraySection()) { + for (size_t idx = 0; idx < list_size && !handler->atEndOfFile(); idx++, handler->nextArraySection()) { sexp_variable n_var; n_var.type = handler->readInt("type"); handler->readString("text", n_var.text, TOKEN_LENGTH); @@ -388,7 +388,7 @@ void pilotfile::plr_read_containers() const size_t list_size = handler->startArrayRead("containers"); p->containers.reserve(list_size); - for (size_t idx = 0; idx < list_size; idx++, handler->nextArraySection()) { + for (size_t idx = 0; idx < list_size && !handler->atEndOfFile(); idx++, handler->nextArraySection()) { p->containers.emplace_back(); auto& container = p->containers.back(); @@ -401,12 +401,12 @@ void pilotfile::plr_read_containers() Assert(size >= 0); if (container.is_list()) { - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size && !handler->atEndOfFile(); ++i) { SCP_string data_idx_str = SCP_string("data_") + std::to_string(i); container.list_data.emplace_back(handler->readString(data_idx_str.c_str())); } } else if (container.is_map()) { - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size && !handler->atEndOfFile(); ++i) { SCP_string key_idx_str = SCP_string("key_") + std::to_string(i); SCP_string data_idx_str = SCP_string("data_") + std::to_string(i); SCP_string key = handler->readString(key_idx_str.c_str()); diff --git a/test/src/pilotfile/BinaryFileHandler.cpp b/test/src/pilotfile/BinaryFileHandler.cpp new file mode 100644 index 00000000000..aa44d8466f5 --- /dev/null +++ b/test/src/pilotfile/BinaryFileHandler.cpp @@ -0,0 +1,118 @@ +#include "pilotfile/BinaryFileHandler.h" + +#include "cfile/cfile.h" +#include "util/FSTestFixture.h" + +#include + +class BinaryFileHandlerTest : public test::FSTestFixture { + public: + BinaryFileHandlerTest() : test::FSTestFixture(INIT_CFILE) + { + pushModDir("pilotfile"); + } +}; + +namespace { +// Builds the bytes of a binary pilot file (little-endian, as the cfwrite functions store them) as an in-memory file. +// The file reads from this object's buffer, so the object has to outlive the handler, which closes the file. +class PilotFileBytes { + public: + PilotFileBytes& add_section(Section id, int size) + { + add(static_cast(id), 2); + return add_int(size); + } + + PilotFileBytes& add_int(int value) + { + add(static_cast(value), 4); + return *this; + } + + CFILE* open() const + { + CFileLocation res(true); + res.name_ext = "pilot.bin"; + res.full_name = "pilot.bin"; + res.data_ptr = _bytes.data(); + res.size = _bytes.size(); + return cfopen_special(res, "rb"); + } + + private: + void add(uint value, int count) + { + for (int i = 0; i < count; ++i) { + _bytes.push_back(static_cast((value >> (8 * i)) & 0xFF)); + } + } + + SCP_vector _bytes; +}; +} // namespace + +TEST_F(BinaryFileHandlerTest, next_section_zero_size_is_invalid) +{ + PilotFileBytes file; + file.add_section(Section::Flags, 0); + pilot::BinaryFileHandler handler(file.open()); + + EXPECT_EQ(handler.nextSection(), Section::Invalid); +} + +TEST_F(BinaryFileHandlerTest, next_section_past_end_is_invalid) +{ + PilotFileBytes file; + file.add_section(Section::Flags, 5).add_int(7); + pilot::BinaryFileHandler handler(file.open()); + + EXPECT_EQ(handler.nextSection(), Section::Invalid); +} + +TEST_F(BinaryFileHandlerTest, next_section_exact_fit_reads_then_zero) +{ + PilotFileBytes file; + file.add_section(Section::Flags, 4).add_int(7); + pilot::BinaryFileHandler handler(file.open()); + + EXPECT_EQ(handler.nextSection(), Section::Flags); + EXPECT_FALSE(handler.atEndOfFile()); + EXPECT_EQ(handler.readInt("value"), 7); + EXPECT_TRUE(handler.atEndOfFile()); + + int past_the_end = -1; + EXPECT_NO_THROW(past_the_end = handler.readInt("value")); + EXPECT_EQ(past_the_end, 0); + EXPECT_FALSE(handler.hasMoreSections()); +} + +TEST_F(BinaryFileHandlerTest, array_count_without_data_is_cut_to_the_bytes_left) +{ + PilotFileBytes file; + file.add_section(Section::Variables, 8).add_int(2000000000).add_int(7); + pilot::BinaryFileHandler handler(file.open()); + + ASSERT_EQ(handler.nextSection(), Section::Variables); + EXPECT_EQ(handler.startArrayRead("variables", false), static_cast(4)); +} + +TEST_F(BinaryFileHandlerTest, negative_array_count_is_cut_to_the_bytes_left) +{ + PilotFileBytes file; + file.add_section(Section::Variables, 8).add_int(-1).add_int(7); + pilot::BinaryFileHandler handler(file.open()); + + ASSERT_EQ(handler.nextSection(), Section::Variables); + EXPECT_EQ(handler.startArrayRead("variables", false), static_cast(4)); +} + +TEST_F(BinaryFileHandlerTest, array_count_up_to_the_bytes_left_is_kept) +{ + PilotFileBytes file; + file.add_section(Section::Variables, 8).add_int(4).add_int(7); + pilot::BinaryFileHandler handler(file.open()); + + ASSERT_EQ(handler.nextSection(), Section::Variables); + EXPECT_EQ(handler.startArrayRead("variables", false), static_cast(4)); +} diff --git a/test/src/pilotfile/csg.cpp b/test/src/pilotfile/csg.cpp new file mode 100644 index 00000000000..3a906f45a68 --- /dev/null +++ b/test/src/pilotfile/csg.cpp @@ -0,0 +1,138 @@ +#include "cfile/cfile.h" +#include "mission/missioncampaign.h" +#include "mission/missionload.h" +#include "pilotfile/pilotfile.h" +#include "playerman/player.h" +#include "util/FSTestFixture.h" + +#include + +class PilotCampaignFileTest : public test::FSTestFixture { + public: + PilotCampaignFileTest() : test::FSTestFixture(INIT_CFILE) + { + pushModDir("pilotfile"); + } + + protected: + void TearDown() override + { + cf_delete("short.stub.csg", + CF_TYPE_PLAYERS, + CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + Num_recent_missions = 0; + + FSTestFixture::TearDown(); + } + + static bool load_short_save(player* plr = nullptr) + { + player local; + if (plr == nullptr) { + plr = &local; + } + plr->reset(); + strcpy_s(plr->callsign, "short"); + + pilotfile loader; + return loader.load_savefile(plr, "stub"); + } +}; + +namespace { +CFILE* start_save() +{ + auto fp = cfopen("short.stub.csg", + "wb", + CF_TYPE_PLAYERS, + false, + CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + if (fp != nullptr) { + cfwrite_uint(CSG_FILE_ID, fp); + cfwrite_ubyte(CSG_VERSION, fp); + } + return fp; +} + +// Writes a save whose only section ends right after its count, with none of the data the count promises +void write_save(Section id, int count) +{ + auto fp = start_save(); + ASSERT_NE(fp, nullptr); + cfwrite_ushort(static_cast(id), fp); + cfwrite_uint(4, fp); + cfwrite_int(count, fp); + cfclose(fp); +} + +// Flags, then Info with empty lists +void write_flags_and_info(CFILE* fp, int last_ship, int missions_completed) +{ + cfwrite_ushort(static_cast(Section::Flags), fp); + cfwrite_uint(5, fp); + cfwrite_ubyte(0, fp); + cfwrite_int(0, fp); + + cfwrite_ushort(static_cast(Section::Info), fp); + cfwrite_uint(48, fp); + for (int i = 0; i < 4; ++i) { + cfwrite_int(0, fp); + } + for (int value : {last_ship, -1, 0, -1, 0, missions_completed}) { + cfwrite_int(value, fp); + } + cfwrite_string_len("", fp); + cfwrite_string_len("", fp); +} +} // namespace + +TEST_F(PilotCampaignFileTest, recent_missions_without_names_are_not_counted) +{ + write_save(Section::LastMissions, 10); + Num_recent_missions = 3; + + ASSERT_TRUE(load_short_save()); + + EXPECT_EQ(Num_recent_missions, 0); +} + +TEST_F(PilotCampaignFileTest, variables_without_data_stay_empty) +{ + write_save(Section::Variables, 1000); + + ASSERT_TRUE(load_short_save()); + + EXPECT_TRUE(Campaign.persistent_variables.empty()); +} + +TEST_F(PilotCampaignFileTest, missions_completed_counts_only_the_missions_read) +{ + auto fp = start_save(); + ASSERT_NE(fp, nullptr); + write_flags_and_info(fp, -1, 1000); + + // Missions as the last section, holding the record of mission 0 only + cfwrite_ushort(static_cast(Section::Missions), fp); + cfwrite_uint(68, fp); + for (int i = 0; i < 17; ++i) { + cfwrite_int(0, fp); + } + cfclose(fp); + + ASSERT_TRUE(load_short_save()); + + EXPECT_EQ(Campaign.num_missions_completed, 1); +} + +TEST_F(PilotCampaignFileTest, last_ship_outside_the_ship_list_is_cleared) +{ + auto fp = start_save(); + ASSERT_NE(fp, nullptr); + write_flags_and_info(fp, 0, 0); + cfclose(fp); + + player plr; + ASSERT_TRUE(load_short_save(&plr)); + + EXPECT_EQ(plr.last_ship_flown_si_index, -1); +} diff --git a/test/src/pilotfile/plr.cpp b/test/src/pilotfile/plr.cpp index b721e9e9f96..eead3a5389b 100644 --- a/test/src/pilotfile/plr.cpp +++ b/test/src/pilotfile/plr.cpp @@ -14,9 +14,19 @@ class PilotPlayerFileTest: public test::FSTestFixture { } protected: + void SetUp() override { + FSTestFixture::SetUp(); + + // a leftover from a crashed run would be picked up by binaryToJSONConversion + cf_delete("cut.plr", CF_TYPE_PLAYERS, CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + } + void TearDown() override { // Delete the converted files cf_delete("asdf.json", CF_TYPE_PLAYERS, CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + cf_delete("cut.plr", CF_TYPE_PLAYERS, CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + cf_delete("cut.json", CF_TYPE_PLAYERS, CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + cf_delete("cut.hdp", CF_TYPE_DATA); FSTestFixture::TearDown(); } @@ -282,3 +292,121 @@ TEST_F(PilotPlayerFileTest, binaryToJSONConversion) { // Close control_config stuff control_config_common_close(); } + +namespace { +CFILE* start_cut_player(Section id, uint size) +{ + auto fp = cfopen("cut.plr", + "wb", + CF_TYPE_PLAYERS, + false, + CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT); + if (fp != nullptr) { + cfwrite_uint(PLR_FILE_ID, fp); + cfwrite_ubyte(PLR_VERSION, fp); + cfwrite_ushort(static_cast(id), fp); + cfwrite_uint(size, fp); + } + return fp; +} + +void write_container(CFILE* fp, ContainerType type, int size) +{ + cfwrite_string_len("c", fp); + cfwrite_int(static_cast(type | ContainerType::STRING_DATA | ContainerType::SAVE_TO_PLAYER_FILE), fp); + cfwrite_int(0, fp); + cfwrite_int(size, fp); +} + +void write_variable(CFILE* fp) +{ + cfwrite_int(SEXP_VARIABLE_SAVE_TO_PLAYER_FILE, fp); + cfwrite_string_len("t", fp); + cfwrite_string_len("v", fp); +} + +// The last section claims two containers, the first of them 1000 entries, and holds only the first one's header +void write_player_with_cut_container(ContainerType type) +{ + auto fp = start_cut_player(Section::Containers, 21); + ASSERT_NE(fp, nullptr); + cfwrite_int(2, fp); + write_container(fp, type, 1000); + cfclose(fp); +} +} // namespace + +TEST_F(PilotPlayerFileTest, list_container_without_data_stays_empty) +{ + control_config_common_init(); + write_player_with_cut_container(ContainerType::LIST); + + player plr; + plr.reset(); + pilotfile loader; + ASSERT_TRUE(loader.load_player("cut", &plr, true)); + + ASSERT_EQ(plr.containers.size(), static_cast(1)); + EXPECT_TRUE(plr.containers[0].list_data.empty()); + + control_config_common_close(); +} + +TEST_F(PilotPlayerFileTest, map_container_without_data_stays_empty) +{ + control_config_common_init(); + write_player_with_cut_container(ContainerType::MAP | ContainerType::STRING_KEYS); + + player plr; + plr.reset(); + pilotfile loader; + ASSERT_TRUE(loader.load_player("cut", &plr, true)); + + ASSERT_EQ(plr.containers.size(), static_cast(1)); + EXPECT_TRUE(plr.containers[0].map_data.empty()); + + control_config_common_close(); +} + +TEST_F(PilotPlayerFileTest, variable_count_without_data_stops_at_the_end) +{ + control_config_common_init(); + auto fp = start_cut_player(Section::Variables, 18); + ASSERT_NE(fp, nullptr); + cfwrite_int(3, fp); + write_variable(fp); + cfclose(fp); + + player plr; + plr.reset(); + pilotfile loader; + ASSERT_TRUE(loader.load_player("cut", &plr, true)); + + EXPECT_EQ(plr.variables.size(), static_cast(1)); + + control_config_common_close(); +} + +TEST_F(PilotPlayerFileTest, json_variables_are_all_read) +{ + control_config_common_init(); + player saved; + saved.reset(); + strcpy_s(saved.callsign, "cut"); + sexp_variable var; + var.type = SEXP_VARIABLE_SAVE_TO_PLAYER_FILE; + strcpy_s(var.text, "t"); + strcpy_s(var.variable_name, "v"); + saved.variables.push_back(var); + pilotfile saver; + ASSERT_TRUE(saver.save_player(&saved)); + + player loaded; + loaded.reset(); + pilotfile loader; + ASSERT_TRUE(loader.load_player("cut", &loaded, false)); + + EXPECT_EQ(loaded.variables.size(), static_cast(1)); + + control_config_common_close(); +} diff --git a/test/src/source_groups.cmake b/test/src/source_groups.cmake index e07770a6367..482f384da36 100644 --- a/test/src/source_groups.cmake +++ b/test/src/source_groups.cmake @@ -65,6 +65,8 @@ add_file_folder("Parse" ) add_file_folder("Pilotfile" + pilotfile/BinaryFileHandler.cpp + pilotfile/csg.cpp pilotfile/plr.cpp ) diff --git a/test/test_data/pilotfile/data/missions/stub.fc2 b/test/test_data/pilotfile/data/missions/stub.fc2 new file mode 100644 index 00000000000..e69de29bb2d