From ec3f937f93fcd55702a8902cb6711ac765b4a16c Mon Sep 17 00:00:00 2001 From: Misa Date: Fri, 17 Apr 2020 15:33:37 -0700 Subject: [PATCH] Handle errors from PHYSFS_readBytes() This fixes a bug where levels in the levels list duplicate if there's an invalid file (such as a folder) in the levels directory. It looks like it happens because we don't free the memory if PHYSFS_readBytes() encounters an error, even though we should. Then we get into Undefined Behavior territory and end up reusing memory, and here it just happens that previously, parsing the entire XML document for each level file was enough to make the loaded file pointer point to garbage that would fail the metadata check, but if we optimize it so we don't parse the entire XML document, it starts reusing memory instead. --- desktop_version/src/FileSystemUtils.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/desktop_version/src/FileSystemUtils.cpp b/desktop_version/src/FileSystemUtils.cpp index 307a4432..2569630f 100644 --- a/desktop_version/src/FileSystemUtils.cpp +++ b/desktop_version/src/FileSystemUtils.cpp @@ -189,7 +189,11 @@ void FILESYSTEM_loadFileToMemory(const char *name, unsigned char **mem, { *mem = (unsigned char*) malloc(length); } - PHYSFS_readBytes(handle, *mem, length); + int success = PHYSFS_readBytes(handle, *mem, length); + if (success == -1) + { + FILESYSTEM_freeMemory(mem); + } PHYSFS_close(handle); }