tools: mkimage: Use fstat instead of stat to avoid malicious hacks

The patch is fixing:
"tools: mkimage: Check if file is regular file"
(sha1: 56c7e8015509312240b1ee15f2ff74510939a45d)
which contains two issues reported by Coverity
Unchecked return value from stat and incorrect calling sequence where
attack can happen between calling stat and fopen.
Using pair in opposite order (fopen and fstat) is fixing this issue
because fstat is using the same file descriptor (FILE *).

Also fixing issue with:
"tools: mkimage: Add support for initialization table for Zynq and
ZynqMP" (sha1: 3b6460809c2a28360029c1c48247648fac4455c9)
where file wasn't checked that it is regular file.

Reported-by: Coverity (CID: 154711, 154712)
Signed-off-by: Michal Simek <michal.simek@xilinx.com>
Reviewed-by: Tom Rini <trini@konsulko.com>
Series-to: trini
Series-cc: u-boot
diff --git a/tools/zynqimage.c b/tools/zynqimage.c
index 43876e7..b47132b 100644
--- a/tools/zynqimage.c
+++ b/tools/zynqimage.c
@@ -225,16 +225,26 @@
 static void zynqimage_parse_initparams(struct zynq_header *zynqhdr,
 	const char *filename)
 {
-	/* Expect a table of register-value pairs, e.g. "0x12345678 0x4321" */
-	FILE *fp = fopen(filename, "r");
+	FILE *fp;
 	struct zynq_reginit reginit;
 	unsigned int reg_count = 0;
-	int r;
+	int r, err;
+	struct stat path_stat;
 
+	/* Expect a table of register-value pairs, e.g. "0x12345678 0x4321" */
+	fp = fopen(filename, "r");
 	if (!fp) {
 		fprintf(stderr, "Cannot open initparams file: %s\n", filename);
 		exit(1);
 	}
+
+	err = fstat(fileno(fp), &path_stat);
+	if (err)
+		return;
+
+	if (!S_ISREG(path_stat.st_mode))
+		return;
+
 	do {
 		r = fscanf(fp, "%x %x", &reginit.address, &reginit.data);
 		if (r == 2) {
diff --git a/tools/zynqmpimage.c b/tools/zynqmpimage.c
index 202faea..60d8ed2 100644
--- a/tools/zynqmpimage.c
+++ b/tools/zynqmpimage.c
@@ -240,19 +240,23 @@
 	FILE *fp;
 	struct zynqmp_reginit reginit;
 	unsigned int reg_count = 0;
-	int r;
+	int r, err;
 	struct stat path_stat;
 
-	stat(filename, &path_stat);
-	if (!S_ISREG(path_stat.st_mode))
-		return;
-
 	/* Expect a table of register-value pairs, e.g. "0x12345678 0x4321" */
 	fp = fopen(filename, "r");
 	if (!fp) {
 		fprintf(stderr, "Cannot open initparams file: %s\n", filename);
 		exit(1);
 	}
+
+	err = fstat(fileno(fp), &path_stat);
+	if (err)
+		return;
+
+	if (!S_ISREG(path_stat.st_mode))
+		return;
+
 	do {
 		r = fscanf(fp, "%x %x", &reginit.address, &reginit.data);
 		if (r == 2) {