From 18f9b84af6d2cf33b97cd6262efed70d52f2f0cf Mon Sep 17 00:00:00 2001 From: Flyinghead Date: Thu, 5 Oct 2023 11:45:14 +0200 Subject: [PATCH] elf: memory corruption if .elf file is invalid --- core/reios/reios_elf.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/core/reios/reios_elf.cpp b/core/reios/reios_elf.cpp index 753a625ed4..30612b743e 100644 --- a/core/reios/reios_elf.cpp +++ b/core/reios/reios_elf.cpp @@ -15,28 +15,26 @@ bool reios_loadElf(const std::string& elf) { std::fseek(f, 0, SEEK_END); size_t size = std::ftell(f); - if (size > 16_MB) { + if (size == 0 || size > 16_MB) { std::fclose(f); return false; } void* elfF = malloc(size); - memset(elfF, 0, size); std::fseek(f, 0, SEEK_SET); size_t nread = std::fread(elfF, 1, size, f); std::fclose(f); elf_t elfFile; - - if (nread != size || elf_newFile(elfF, nread, &elfFile) != 0 || elf_checkFile(&elfFile) != 0) + if (nread != size || elf_newFile(elfF, nread, &elfFile) != 0) { - free((void*)elfFile.elfFile); + free(elfF); return false; } bool phys = false; - for (int i = 0; i < elf_getNumProgramHeaders(&elfFile); i++) + for (size_t i = 0; i < elf_getNumProgramHeaders(&elfFile); i++) { // Load that section uint64_t dest; @@ -57,7 +55,7 @@ bool reios_loadElf(const std::string& elf) { ptr += len; memset(ptr, 0, elf_getProgramHeaderMemorySize(&elfFile, i) - len); } - free((void*)elfFile.elfFile); + free(elfF); return true; }