Fix issues in FWU code

This patch fixes the following issues in Firmware Update (FWU) code:

1. The FWU layer maintains a list of loaded image ids and
   while checking for image overlaps, INVALID_IMAGE_IDs were not
   skipped. The patch now adds code to skip INVALID_IMAGE_IDs.

2. While resetting the state corresponding to an image, the code
   now resets the memory used by the image only if the image were
   copied previously via IMAGE_COPY smc. This prevents the invalid
   zeroing of image memory which are not copied but are directly
   authenticated via IMAGE_AUTH smc.

Change-Id: Idf18e69bcba7259411c88807bd0347d59d9afb8f
Signed-off-by: Soby Mathew <soby.mathew@arm.com>
diff --git a/bl1/bl1_fwu.c b/bl1/bl1_fwu.c
index 205ea92..85eee1a 100644
--- a/bl1/bl1_fwu.c
+++ b/bl1/bl1_fwu.c
@@ -176,18 +176,19 @@
 
 	checked_image_base = checked_info->image_base;
 	checked_image_end = checked_image_base + checked_info->image_size - 1;
-	/* No need to check for overlaps, it's done in bl1_fwu_image_copy(). */
+	/* No need to check for overflows, it's done in bl1_fwu_image_copy(). */
 
 	for (int i = 0; i < FWU_MAX_SIMULTANEOUS_IMAGES; i++) {
 
-		/* Don't check image against itself. */
-		if (bl1_fwu_loaded_ids[i] == image_id)
+		/* Skip INVALID_IMAGE_IDs and don't check image against itself */
+		if ((bl1_fwu_loaded_ids[i] == INVALID_IMAGE_ID) ||
+				(bl1_fwu_loaded_ids[i] == image_id))
 			continue;
 
 		image_desc = bl1_plat_get_image_desc(bl1_fwu_loaded_ids[i]);
 
 		/* Only check images that are loaded or being loaded. */
-		assert (image_desc->state != IMAGE_STATE_RESET);
+		assert (image_desc && image_desc->state != IMAGE_STATE_RESET);
 
 		info = &image_desc->image_info;
 
@@ -704,11 +705,15 @@
 			return -EPERM;
 		}
 
-		/* Clear the memory.*/
-		zero_normalmem((void *)image_desc->image_info.image_base,
-				image_desc->copied_size);
-		flush_dcache_range(image_desc->image_info.image_base,
-				image_desc->copied_size);
+		if (image_desc->copied_size) {
+			/* Clear the memory if the image is copied */
+			assert(GET_SECURITY_STATE(image_desc->ep_info.h.attr) == SECURE);
+
+			zero_normalmem((void *)image_desc->image_info.image_base,
+					image_desc->copied_size);
+			flush_dcache_range(image_desc->image_info.image_base,
+					image_desc->copied_size);
+		}
 
 		/* Reset status variables */
 		image_desc->copied_size = 0;