boot: Check shared area more carefully before init

When the shared data area is not exclusively used by MCUboot, but also
by other boot stages it is inappropriate to initialize (erase) the
shared area based on a global variable. It must check the magic value
at the beginning of the area plus it should sanity-check other
available values for a case when memory garbage matches the magic
value.

Change-Id: I3a4552ad2863a61d81de9374ef6302ae0609f7bf
Signed-off-by: David Vincze <david.vincze@arm.com>
diff --git a/boot/bootutil/src/boot_record.c b/boot/bootutil/src/boot_record.c
index 3fb1fcc..281fe5d 100644
--- a/boot/bootutil/src/boot_record.c
+++ b/boot/bootutil/src/boot_record.c
@@ -62,13 +62,18 @@
 
     boot_data = (struct shared_boot_data *)MCUBOOT_SHARED_DATA_BASE;
 
-    /* Check whether first time to call this function. If does then initialise
-     * shared data area.
+    /* Check whether first time to call this function. If it is, then check
+     * whether the shared data area needs to be initialised.
      */
     if (!shared_memory_init_done) {
-        memset((void *)MCUBOOT_SHARED_DATA_BASE, 0, MCUBOOT_SHARED_DATA_SIZE);
-        boot_data->header.tlv_magic   = SHARED_DATA_TLV_INFO_MAGIC;
-        boot_data->header.tlv_tot_len = SHARED_DATA_HEADER_SIZE;
+        if ((boot_data->header.tlv_magic != SHARED_DATA_TLV_INFO_MAGIC) ||
+            (boot_data->header.tlv_tot_len > MCUBOOT_SHARED_DATA_SIZE)) {
+            memset((void *)MCUBOOT_SHARED_DATA_BASE, 0,
+                           MCUBOOT_SHARED_DATA_SIZE);
+            boot_data->header.tlv_magic   = SHARED_DATA_TLV_INFO_MAGIC;
+            boot_data->header.tlv_tot_len = SHARED_DATA_HEADER_SIZE;
+        }
+
         shared_memory_init_done = true;
     }