From 81ac92cb1bad4747b2e925a45ebd2a142d3e68e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fl=C3=A1vio=20J=2E=20Saraiva?= Date: Fri, 15 Mar 2024 20:02:13 +0000 Subject: [PATCH] Ensure mips64_load_elf_image reads everything. Handle fseek and fread errors. Fix resource leak that was missed in #151 --- stable/mips64.c | 17 ++++++++++++++--- unstable/mips64.c | 17 ++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/stable/mips64.c b/stable/mips64.c index 43bfde235..b84e874fd 100644 --- a/stable/mips64.c +++ b/stable/mips64.c @@ -978,7 +978,12 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, if (!(shdr->sh_flags & SHF_ALLOC) || !len) continue; - fseek(bfd,shdr->sh_offset,SEEK_SET); + if (fseek(bfd,shdr->sh_offset,SEEK_SET) != 0) { + perror("load_elf_image: fseek"); + elf_end(img_elf); + fclose(bfd); + return(-1); + } vaddr = sign_extend(shdr->sh_addr,32); if (cpu->vm->debug_level > 0) { @@ -993,6 +998,8 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, if (!haddr) { fprintf(stderr,"load_elf_image: invalid load address 0x%llx\n", vaddr); + elf_end(img_elf); + fclose(bfd); return(-1); } @@ -1006,8 +1013,12 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, clen = m_min(clen,remain); - if (fread((u_char *)haddr,clen,1,bfd) < 1) - break; + if (fread((u_char *)haddr,clen,1,bfd) != 1) { + perror("load_elf_image: fread"); + elf_end(img_elf); + fclose(bfd); + return(-1); + } vaddr += clen; len -= clen; diff --git a/unstable/mips64.c b/unstable/mips64.c index f3791b289..66a1174be 100644 --- a/unstable/mips64.c +++ b/unstable/mips64.c @@ -1061,7 +1061,12 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, if (!(shdr->sh_flags & SHF_ALLOC) || !len) continue; - fseek(bfd,shdr->sh_offset,SEEK_SET); + if (fseek(bfd,shdr->sh_offset,SEEK_SET) != 0) { + perror("load_elf_image: fseek"); + elf_end(img_elf); + fclose(bfd); + return(-1); + } vaddr = sign_extend(shdr->sh_addr,32); if (cpu->vm->debug_level > 0) { @@ -1076,6 +1081,8 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, if (!haddr) { fprintf(stderr,"load_elf_image: invalid load address 0x%llx\n", vaddr); + elf_end(img_elf); + fclose(bfd); return(-1); } @@ -1089,8 +1096,12 @@ int mips64_load_elf_image(cpu_mips_t *cpu,char *filename,int skip_load, clen = m_min(clen,remain); - if (fread((u_char *)haddr,clen,1,bfd) < 1) - break; + if (fread((u_char *)haddr,clen,1,bfd) != 1) { + perror("load_elf_image: fread"); + elf_end(img_elf); + fclose(bfd); + return(-1); + } vaddr += clen; len -= clen;