[PATCH 1/2] scripts/sortextable: make close happens only if file is opened

From: Maninder Singh
Date: Thu Aug 11 2016 - 00:22:51 EST


1. Currently code is doing close even if it is failed to open,
which is wrong so fixing the same.
2. if file open is failed just return from there, no need of
next operations.
3. Use mmap address only after validation.

Issue is reported by static checker tool.

Reported-by: Ajeet Yadav <ajeet.y@xxxxxxxxxxx>
Signed-off-by: Maninder Singh <maninder1.s@xxxxxxxxxxx>
Signed-off-by: Vaneet Narang <v.narang@xxxxxxxxxxx>
---
scripts/sortextable.c | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/scripts/sortextable.c b/scripts/sortextable.c
index f453b7c..30b4e7c 100644
--- a/scripts/sortextable.c
+++ b/scripts/sortextable.c
@@ -70,7 +70,6 @@ cleanup(void)
{
if (!mmap_failed)
munmap(ehdr_curr, sb.st_size);
- close(fd_map);
}

static void __attribute__((noreturn))
@@ -91,7 +90,13 @@ static void *mmap_file(char const *fname)
void *addr;

fd_map = open(fname, O_RDWR);
- if (fd_map < 0 || fstat(fd_map, &sb) < 0) {
+
+ if (fd_map < 0) {
+ perror("open");
+ fail_file();
+ return MAP_FAILED;
+ }
+ if (fstat(fd_map, &sb) < 0) {
perror(fname);
fail_file();
}
@@ -106,6 +111,7 @@ static void *mmap_file(char const *fname)
fprintf(stderr, "Could not mmap file: %s\n", fname);
fail_file();
}
+ close(fd_map);
return addr;
}

@@ -270,6 +276,9 @@ do_file(char const *const fname)
table_sort_t custom_sort;
Elf32_Ehdr *ehdr = mmap_file(fname);

+ if (ehdr == MAP_FAILED)
+ return;
+
ehdr_curr = ehdr;
switch (ehdr->e_ident[EI_DATA]) {
default:
--
1.7.9.5