Skip to content

Commit

Permalink
Merge pull request #228 from flaviojs/fix-resource-leaks-rom2c
Browse files Browse the repository at this point in the history
Fix resource leaks in rom2c.
  • Loading branch information
grossmj authored Apr 5, 2024
2 parents 5212749 + b44a439 commit 38de9d8
Showing 1 changed file with 38 additions and 17 deletions.
55 changes: 38 additions & 17 deletions common/rom2c.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,47 +35,49 @@ int main(int argc,char *argv[])

start = strtoul(argv[3],NULL,0);

if ((fd = open(argv[1],O_RDONLY)) == -1)
return(-1);
if ((fd = open(argv[1],O_RDONLY)) == -1) {
perror("open");
goto err_open;
}

if (elf_version(EV_CURRENT) == EV_NONE) {
fprintf(stderr,"load_elf_image: library out of date\n");
return(-1);
fprintf(stderr,"elf_version: library out of date\n");
goto err_elf_version;
}

if (!(img_elf = elf_begin(fd,ELF_C_READ,NULL))) {
fprintf(stderr,"load_elf_image: elf_begin: %s\n",
elf_errmsg(elf_errno()));
return(-1);
fprintf(stderr,"elf_begin: %s\n",elf_errmsg(elf_errno()));
goto err_elf_begin;
}

if (!(phdr = elf32_getphdr(img_elf))) {
fprintf(stderr,"load_elf_image: elf32_getphdr: %s\n",
elf_errmsg(elf_errno()));
return(-1);
fprintf(stderr,"elf32_getphdr: %s\n",elf_errmsg(elf_errno()));
goto err_elf32_getphdr;
}

if (!(ehdr = elf32_getehdr(img_elf))) {
fprintf(stderr,"elf32_getehdr: %s\n",elf_errmsg(elf_errno()));
goto err_elf32_getehdr;
}

if (!(fd_out = fopen(argv[2],"w"))) {
fprintf(stderr,"Unable to create file \"%s\"\n",argv[2]);
exit(EXIT_FAILURE);
goto err_fopen;
}

ehdr = elf32_getehdr(img_elf);
phdr = elf32_getphdr(img_elf);

printf("Extracting ROM from ELF file '%s'...\n",argv[1]);
bfd = fdopen(fd,"r");

if (!bfd) {
perror("load_elf_image: fdopen");
return(-1);
perror("fdopen");
goto err_fdopen;
}

for(i=0;i<ehdr->e_phnum;i++,phdr++)
{
if (fseek(bfd,phdr->p_offset,SEEK_SET) != 0) {
perror("fseek");
return(-1);
goto err_fseek;
}

vaddr = (m_uint64_t)phdr->p_vaddr;
Expand All @@ -101,6 +103,25 @@ int main(int argc,char *argv[])
}
}

fclose(bfd);
fclose(fd_out);
elf_end(img_elf);
return(0);

err_fseek:
fclose(bfd); // instead of close(fd)
fclose(fd_out);
elf_end(img_elf);
return(EXIT_FAILURE);
err_fdopen:
fclose(fd_out);
err_fopen:
err_elf32_getehdr:
err_elf32_getphdr:
elf_end(img_elf);
err_elf_begin:
err_elf_version:
close(fd);
err_open:
return(EXIT_FAILURE);
}

0 comments on commit 38de9d8

Please sign in to comment.