util/cbfstool: calculate cbfs file size for xip stages

The initial lookup for cbfs location for xip stages is implicitly
using the ELF size assuming it's relatively equivalent. However,
if the ELF that is being converted contains debug information or
other metadata then the location lookup can fail because the ELF is
considerably bigger than the real footprint.

BUG=b:70801221

Change-Id: I47024dcd8205a09885d3a3f76e255eb5e3c55d9e
Signed-off-by: Aaron Durbin <adurbin@chromium.org>
Reviewed-on: https://review.coreboot.org/22936
Reviewed-by: Furquan Shaikh <furquan@google.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
diff --git a/util/cbfstool/elfheaders.c b/util/cbfstool/elfheaders.c
index acb25a7..3622663 100644
--- a/util/cbfstool/elfheaders.c
+++ b/util/cbfstool/elfheaders.c
@@ -1440,3 +1440,26 @@
 
 	return add_rel(rel_sec, &rel);
 }
+
+int elf_program_file_size(const struct buffer *input, size_t *file_size)
+{
+	Elf64_Ehdr ehdr;
+	Elf64_Phdr *phdr;
+	int i;
+	size_t loadable_file_size = 0;
+
+	if (elf_headers(input, &ehdr, &phdr, NULL))
+		return -1;
+
+	for (i = 0; i < ehdr.e_phnum; i++) {
+		if (phdr[i].p_type != PT_LOAD)
+			continue;
+		loadable_file_size += phdr[i].p_filesz;
+	}
+
+	*file_size = loadable_file_size;
+
+	free(phdr);
+
+	return 0;
+}