From 522bd126bb247a51efb58ffc068efa4601ba887b Mon Sep 17 00:00:00 2001 From: Matthias Schwarzott Date: Sun, 25 Feb 2024 15:06:16 +0100 Subject: [PATCH] Pathfinder: only load and store good length values This avoids buffer overruns on load and save of games. This should fix some crashes. See https://github.com/Wargus/stratagus/issues/610 --- src/unit/script_unit.cpp | 12 +++++++++--- src/unit/unit_save.cpp | 6 ++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/unit/script_unit.cpp b/src/unit/script_unit.cpp index 75f1874a67..429538e119 100644 --- a/src/unit/script_unit.cpp +++ b/src/unit/script_unit.cpp @@ -257,10 +257,16 @@ void PathFinderOutput::Load(lua_State *l) LuaError(l, "incorrect argument _"); } const int subargs = lua_rawlen(l, -1); - for (int k = 0; k < subargs; ++k) { - this->Path[k] = LuaToNumber(l, -1, k + 1); + if (subargs <= PathFinderOutput::MAX_PATH_LENGTH) + { + for (int k = 0; k < subargs; ++k) { + this->Path[k] = LuaToNumber(l, -1, k + 1); + } + this->Length = subargs; + } else + { + this->Length = 0; } - this->Length = subargs; lua_pop(l, 1); } else { LuaError(l, "PathFinderOutput::Load: Unsupported tag: %s", tag.data()); diff --git a/src/unit/unit_save.cpp b/src/unit/unit_save.cpp index 4e74bfeadf..12b3bd5461 100644 --- a/src/unit/unit_save.cpp +++ b/src/unit/unit_save.cpp @@ -103,8 +103,10 @@ void PathFinderOutput::Save(CFile &file) const } if (this->Length > 0) { file.printf("\"path\", {"); - for (int i = 0; i < this->Length; ++i) { - file.printf("%d, ", this->Path[i]); + if (this->Length <= PathFinderOutput::MAX_PATH_LENGTH) { + for (int i = 0; i < this->Length; ++i) { + file.printf("%d, ", this->Path[i]); + } } file.printf("},"); }