From 86e5e10daf54da7df358a06033f3a3bd8c852a08 Mon Sep 17 00:00:00 2001 From: Eric van Gyzen Date: Thu, 17 Feb 2022 09:53:48 -0600 Subject: [PATCH] elfdump: handle small files more gracefully elfdump -E on an empty file would complain "Invalid argument" because it tried to mmap zero bytes. With the -E flag, elfdump should simply exit non-zero. For tiny files, the code would reference off the end of the mapped region. Ensure the file is large enough to contain an ELF header before mapping it. MFC after: 1 week Sponsored by: Dell EMC Isilon --- usr.bin/elfdump/elfdump.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/usr.bin/elfdump/elfdump.c b/usr.bin/elfdump/elfdump.c index 2bdf98830088..28b42a55a508 100644 --- a/usr.bin/elfdump/elfdump.c +++ b/usr.bin/elfdump/elfdump.c @@ -585,6 +585,11 @@ main(int ac, char **av) if ((fd = open(*av, O_RDONLY)) < 0 || fstat(fd, &sb) < 0) err(1, "%s", *av); + if ((size_t)sb.st_size < sizeof(Elf32_Ehdr)) { + if (flags & ED_IS_ELF) + exit(1); + errx(1, "not an elf file"); + } cap_rights_init(&rights, CAP_MMAP_R); if (caph_rights_limit(fd, &rights) < 0) err(1, "unable to limit rights for %s", *av); @@ -598,7 +603,7 @@ main(int ac, char **av) e = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if (e == MAP_FAILED) err(1, NULL); - if (!IS_ELF(*(Elf32_Ehdr *)e)) { + if (!IS_ELF(*e)) { if (flags & ED_IS_ELF) exit(1); errx(1, "not an elf file");