EC-EFS: Fix in-place signature replacement

When futility replaces the old signature in the input file with a
new one, it assumes the signature is at the end of RW region. This
assumption is wrong for EC-EFS binaries because they place a
signature at each end of two EC_RW areas.

This patch fixes the issue by specifying the signature address via
'old_sig', which points to the (first) signature address regardless
of the input file format (EFS v.s. non-EFS, FMAP v.s. no FMAP).

BUG=b:66956286
BRANCH=none
TEST=Run
'futility sign --type rwsig --prikey key_ec_efs.vbprik2 ec.bin'.
Then run 'futility show --type rwsig ec.bin', which prints
'Signature verification succeeded.'
make runtests

Change-Id: I730fd31be640de3e9381f156d084162dd4093ba6
Signed-off-by: Daisuke Nojiri <dnojiri@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/767596
diff --git a/futility/file_type_rwsig.c b/futility/file_type_rwsig.c
index ebedf65..e2288f1 100644
--- a/futility/file_type_rwsig.c
+++ b/futility/file_type_rwsig.c
@@ -217,7 +217,7 @@
 	int retval = 1;
 	FmapHeader *fmap = NULL;
 	FmapAreaHeader *fmaparea;
-	const struct vb21_signature *old_sig = 0;
+	struct vb21_signature *old_sig = 0;
 
 	Debug("%s(): name %s\n", __func__, name);
 	Debug("%s(): len  0x%08x (%d)\n", __func__, len, len);
@@ -230,7 +230,7 @@
 			/* This looks like a full image. */
 			Debug("Found an FMAP!\n");
 
-			old_sig = (const struct vb21_signature *)
+			old_sig = (struct vb21_signature *)
 				fmap_find_by_name(buf, len, fmap, "SIG_RW",
 						  &fmaparea);
 			if (!old_sig) {
@@ -264,7 +264,7 @@
 			}
 
 			/* Take a look */
-			old_sig = (const struct vb21_signature *)
+			old_sig = (struct vb21_signature *)
 				(buf + len - sig_size);
 		}
 
@@ -314,8 +314,9 @@
 				tmp_sig->c.total_size, sig_size);
 			goto done;
 		}
-		memset(buf + len - sig_size, 0xff, sig_size);
-		memcpy(buf + len - sig_size, tmp_sig, tmp_sig->c.total_size);
+		Debug("Replacing old signature with new one\n");
+		memset(old_sig, 0xff, sig_size);
+		memcpy(old_sig, tmp_sig, tmp_sig->c.total_size);
 		if (fmap) {
 			Debug("Writing %s (size=%d)\n",
 			      EC_RW_FILENAME, fmaparea->area_size);