cbfstool: allow user to explicitly specify header location

There potentially could be multiple CBFS instances present in the
firmware image. cbfstool should be able to operate on any of them, not
just the first one present.

To accomplish that, allow all CBFS commands to accept the -H parameter
(which specifies the exact CBFS header location in the image).

If this parameter is specified, the image is not searched for the CBFS
header, only the specified location is checked for validity, If the
location is valid, it is considered to be the CBFS header, if not -
the tool exits with an error status.

Note, that default behavior of the tool does not change.

BRANCH=storm
BUG=chrome-os-partner:34161, chromium:445938
TEST=run the following experiments:

  - examined an image with three CBFS instances, was able to print all
    of them.

  - built a rambi coreboot image and tried the following (cbfstool output abbreviated):

  $ ./util/cbfstool/cbfstool /build/rambi/firmware/coreboot.rom print
  coreboot.rom: 8192 kB, bootblocksize 2448, romsize 8388608, offset 0x700000
  alignment: 64 bytes, architecture: x86

  Name                           Offset     Type         Size
  cmos_layout.bin                0x700000   cmos_layout  1164
  ...
  (empty)                        0x7ec600   null         77848
  $ \od -tx4 -Ax /build/rambi/firmware/coreboot.rom | tail -2
  7ffff0 fff67de9 000000ff fff6dfe9 fffff650
  800000
  $ ./util/cbfstool/cbfstool /build/rambi/firmware/coreboot.rom print  -H 0x7ff650
  coreboot.rom: 8192 kB, bootblocksize 2448, romsize 8388608, offset 0x700000
  alignment: 64 bytes, architecture: x86

  Name                           Offset     Type         Size
  cmos_layout.bin                0x700000   cmos_layout  1164
  ...
  (empty)                        0x7ec600   null         77848
  $ ./util/cbfstool/cbfstool /build/rambi/firmware/coreboot.rom print  -H 0x7ff654
  E: /build/rambi/firmware/coreboot.rom does not have CBFS master header.
  E: Could not load ROM image '/build/rambi/firmware/coreboot.rom'.
  $

Change-Id: I486092e222c96c65868ae7d41a9e8976ffcc93c4
Signed-off-by: Vadim Bendebury <vbendeb@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/237485
Reviewed-by: David Hendricks <dhendrix@chromium.org>
Reviewed-by: Patrick Georgi <pgeorgi@chromium.org>
Reviewed-by: Stefan Reinauer <reinauer@google.com>
diff --git a/util/cbfstool/cbfs_image.c b/util/cbfstool/cbfs_image.c
index 7edf2b2..10661fd 100644
--- a/util/cbfstool/cbfs_image.c
+++ b/util/cbfstool/cbfs_image.c
@@ -245,14 +245,16 @@
 	return 0;
 }
 
-int cbfs_image_from_file(struct cbfs_image *image, const char *filename)
+int cbfs_image_from_file(struct cbfs_image *image,
+			 const char *filename, uint32_t offset)
 {
 	if (buffer_from_file(&image->buffer, filename) != 0)
 		return -1;
 	DEBUG("read_cbfs_image: %s (%zd bytes)\n", image->buffer.name,
 	      image->buffer.size);
 	image->header = cbfs_find_header(image->buffer.data,
-					 image->buffer.size);
+					 image->buffer.size,
+					 offset);
 	if (!image->header) {
 		ERROR("%s does not have CBFS master header.\n", filename);
 		cbfs_image_delete(image);
@@ -736,21 +738,41 @@
 	return count;
 }
 
-struct cbfs_header *cbfs_find_header(char *data, size_t size)
+static int cbfs_header_valid(struct cbfs_header *header, size_t size)
+{
+	if ((ntohl(header->magic) == CBFS_HEADER_MAGIC) &&
+	    ((ntohl(header->version) == CBFS_HEADER_VERSION1) ||
+	     (ntohl(header->version) == CBFS_HEADER_VERSION2)) &&
+	    (ntohl(header->romsize) <= size) &&
+	    (ntohl(header->offset) < ntohl(header->romsize)))
+		return 1;
+	return 0;
+}
+
+struct cbfs_header *cbfs_find_header(char *data, size_t size,
+				     uint32_t forced_offset)
 {
 	size_t offset;
 	int found = 0;
 	int32_t rel_offset;
 	struct cbfs_header *header, *result = NULL;
 
+	if (forced_offset < (size - sizeof(struct cbfs_header))) {
+		/* Check if the forced header is valid. */
+		header = (struct cbfs_header *)(data + forced_offset);
+		if (cbfs_header_valid(header, size))
+			return header;
+		return NULL;
+	}
+
 	// Try finding relative offset of master header at end of file first.
 	rel_offset = *(int32_t *)(data + size - sizeof(int32_t));
 	offset = size + rel_offset;
 	DEBUG("relative offset: %#zx(-%#zx), offset: %#zx\n",
 	      (size_t)rel_offset, (size_t)-rel_offset, offset);
+
 	if (offset >= size - sizeof(*header) ||
-	    ntohl(((struct cbfs_header *)(data + offset))->magic) !=
-	    CBFS_HEADER_MAGIC) {
+	    !cbfs_header_valid((struct cbfs_header *)(data + offset), size)) {
 		// Some use cases append non-CBFS data to the end of the ROM.
 		DEBUG("relative offset seems wrong, scanning whole image...\n");
 		offset = 0;
@@ -758,13 +780,8 @@
 
 	for (; offset + sizeof(*header) < size; offset++) {
 		header = (struct cbfs_header *)(data + offset);
-		if (ntohl(header->magic) !=(CBFS_HEADER_MAGIC))
-		    continue;
-		if (ntohl(header->version) != CBFS_HEADER_VERSION1 &&
-		    ntohl(header->version) != CBFS_HEADER_VERSION2) {
-			// Probably not a real CBFS header?
+		if (!cbfs_header_valid(header, size))
 			continue;
-		}
 		if (!found++)
 			result = header;
 	}
diff --git a/util/cbfstool/cbfs_image.h b/util/cbfstool/cbfs_image.h
index 3c4b708..229e1da 100644
--- a/util/cbfstool/cbfs_image.h
+++ b/util/cbfstool/cbfs_image.h
@@ -50,7 +50,8 @@
 		      int32_t entries_offset);
 
 /* Loads a CBFS image from file. Returns 0 on success, otherwise non-zero. */
-int cbfs_image_from_file(struct cbfs_image *image, const char *filename);
+int cbfs_image_from_file(struct cbfs_image *image,
+			 const char *filename, uint32_t offset);
 
 /* Writes a CBFS image into file. Returns 0 on success, otherwise non-zero. */
 int cbfs_image_write_file(struct cbfs_image *image, const char *filename);
@@ -104,7 +105,8 @@
  * NULL (including when multiple headers were found). If there is a X86 ROM
  * style signature (pointer at 0xfffffffc) found in ROM, it will be selected as
  * the only header.*/
-struct cbfs_header *cbfs_find_header(char *data, size_t size);
+struct cbfs_header *cbfs_find_header(char *data, size_t size,
+				     uint32_t forced_offset);
 
 /* Returns the first cbfs_file entry in CBFS image by CBFS header (no matter if
  * the entry has valid content or not), otherwise NULL. */
diff --git a/util/cbfstool/cbfstool.c b/util/cbfstool/cbfstool.c
index c54ec89..34987a7 100644
--- a/util/cbfstool/cbfstool.c
+++ b/util/cbfstool/cbfstool.c
@@ -63,6 +63,7 @@
 } param = {
 	/* All variables not listed are initialized as zero. */
 	.algo = CBFS_COMPRESS_NONE,
+	.headeroffset = ~0,
 };
 
 typedef int (*convert_buffer_t)(struct buffer *buffer, uint32_t *offset);
@@ -72,6 +73,7 @@
 			      const char *name,
 			      uint32_t type,
 			      uint32_t offset,
+			      uint32_t headeroffset,
 			      convert_buffer_t convert)
 {
 	struct cbfs_image image;
@@ -92,7 +94,7 @@
 		return 1;
 	}
 
-	if (cbfs_image_from_file(&image, cbfs_name))
+	if (cbfs_image_from_file(&image, cbfs_name, headeroffset))
 		return 1;
 
 	if (buffer_from_file(&buffer, filename) != 0) {
@@ -199,6 +201,7 @@
 				  param.name,
 				  param.type,
 				  param.baseaddress,
+				  param.headeroffset,
 				  NULL);
 }
 
@@ -209,6 +212,7 @@
 				  param.name,
 				  CBFS_COMPONENT_STAGE,
 				  param.baseaddress,
+				  param.headeroffset,
 				  cbfstool_convert_mkstage);
 }
 
@@ -219,6 +223,7 @@
 				  param.name,
 				  CBFS_COMPONENT_PAYLOAD,
 				  param.baseaddress,
+				  param.headeroffset,
 				  cbfstool_convert_mkpayload);
 }
 
@@ -239,6 +244,7 @@
 				  param.name,
 				  CBFS_COMPONENT_PAYLOAD,
 				  param.baseaddress,
+				  param.headeroffset,
 				  cbfstool_convert_mkflatpayload);
 }
 
@@ -251,7 +257,7 @@
 		return 1;
 	}
 
-	if (cbfs_image_from_file(&image, param.cbfs_name))
+	if (cbfs_image_from_file(&image, param.cbfs_name, param.headeroffset))
 		return 1;
 
 	if (cbfs_remove_entry(&image, param.name) != 0) {
@@ -373,7 +379,7 @@
 		return 1;
 	}
 
-	if (cbfs_image_from_file(&image, param.cbfs_name))
+	if (cbfs_image_from_file(&image, param.cbfs_name, param.headeroffset))
 		return 1;
 
 	if (cbfs_get_entry(&image, param.name))
@@ -408,7 +414,7 @@
 {
 	struct cbfs_image image;
 
-	if (cbfs_image_from_file(&image, param.cbfs_name))
+	if (cbfs_image_from_file(&image, param.cbfs_name, param.headeroffset))
 		return 1;
 
 	cbfs_print_directory(&image);
@@ -431,7 +437,7 @@
 		return 1;
 	}
 
-	if (cbfs_image_from_file(&image, param.cbfs_name))
+	if (cbfs_image_from_file(&image, param.cbfs_name, param.headeroffset))
 		result = 1;
 	else if (cbfs_export_entry(&image, param.name,
 				   param.filename))
@@ -457,7 +463,7 @@
 		return 1;
 	}
 
-	if (cbfs_image_from_file(&image, param.cbfs_name))
+	if (cbfs_image_from_file(&image, param.cbfs_name, param.headeroffset))
 		return 1;
 
 	ret = fit_update_table(&image, param.fit_empty_entries, param.name);
@@ -469,16 +475,16 @@
 }
 
 static const struct command commands[] = {
-	{"add", "f:n:t:b:vh?", cbfs_add},
-	{"add-flat-binary", "f:n:l:e:c:b:vh?", cbfs_add_flat_binary},
-	{"add-payload", "f:n:t:c:b:vh?C:I:", cbfs_add_payload},
-	{"add-stage", "f:n:t:c:b:S:vh?", cbfs_add_stage},
+	{"add", "H:f:n:t:b:vh?", cbfs_add},
+	{"add-flat-binary", "H:f:n:l:e:c:b:vh?", cbfs_add_flat_binary},
+	{"add-payload", "H:f:n:t:c:b:vh?C:I:", cbfs_add_payload},
+	{"add-stage", "H:f:n:t:c:b:S:vh?", cbfs_add_stage},
 	{"create", "s:B:b:H:a:o:m:vh?", cbfs_create},
-	{"extract", "n:f:vh?", cbfs_extract},
-	{"locate", "f:n:P:a:Tvh?", cbfs_locate},
-	{"print", "vh?", cbfs_print},
-	{"remove", "n:vh?", cbfs_remove},
-	{"update-fit", "n:x:vh?", cbfs_update_fit},
+	{"extract", "H:n:f:vh?", cbfs_extract},
+	{"locate", "H:f:n:P:a:Tvh?", cbfs_locate},
+	{"print", "H:vh?", cbfs_print},
+	{"remove", "H:n:vh?", cbfs_remove},
+	{"update-fit", "H:n:x:vh?", cbfs_update_fit},
 };
 
 static struct option long_options[] = {
@@ -512,9 +518,10 @@
 	    ("cbfstool: Management utility for CBFS formatted ROM images\n\n"
 	     "USAGE:\n" " %s [-h]\n"
 	     " %s FILE COMMAND [-v] [PARAMETERS]...\n\n" "OPTIONs:\n"
-	     "  -T              Output top-aligned memory address\n"
-	     "  -v              Provide verbose output\n"
-	     "  -h              Display this help message\n\n"
+	     "  -H header_offset  Do not search for header, use this offset\n"
+	     "  -T                Output top-aligned memory address\n"
+	     "  -v                Provide verbose output\n"
+	     "  -h                Display this help message\n\n"
 	     "COMMANDs:\n"
 	     " add -f FILE -n NAME -t TYPE [-b base-address]               "
 			"Add a component\n"