cbfstool: extract rmodules as ELFs properly

With the previous ELF stage extract support the resulting
ELF files wouldn't handle rmodules correctly in that the
rmodule header as well as the relocations were a part of
the program proper. Instead, try an initial pass at
converting the stage as if it was an rmodule first. If it
doesn't work fall back on the normal ELF extraction.

TEST=Pulled an rmodule out of Chrome OS shellball. Manually
     matched up the metadata and relocations.

Change-Id: Iaf222f92d145116ca4dfaa955fb7278e583161f2
Signed-off-by: Aaron Durbin <adurbin@chromium.org>
Reviewed-on: http://review.coreboot.org/12222
Tested-by: build bot (Jenkins)
Reviewed-by: Patrick Georgi <pgeorgi@google.com>
Reviewed-by: Paul Menzel <paulepanter@users.sourceforge.net>
diff --git a/util/cbfstool/cbfs_image.c b/util/cbfstool/cbfs_image.c
index bd432d4..c23a6e8 100644
--- a/util/cbfstool/cbfs_image.c
+++ b/util/cbfstool/cbfs_image.c
@@ -28,6 +28,7 @@
 #include "common.h"
 #include "cbfs_image.h"
 #include "elfparsing.h"
+#include "rmodule.h"
 
 /* Even though the file-adding functions---cbfs_add_entry() and
  * cbfs_add_entry_at()---perform their sizing checks against the beginning of
@@ -770,6 +771,7 @@
 	struct elf_writer *ew;
 	struct buffer elf_out;
 	size_t empty_sz;
+	int rmod_ret;
 
 	if (cbfs_stage_decompress(&stage, buff)) {
 		ERROR("Failed to decompress stage.\n");
@@ -781,6 +783,17 @@
 
 	ehdr.e_entry = stage.entry;
 
+	/* Attempt rmodule translation first. */
+	rmod_ret = rmodule_stage_to_elf(&ehdr, buff);
+
+	if (rmod_ret < 0) {
+		ERROR("rmodule parsing failed\n");
+		return -1;
+	} else if (rmod_ret == 0)
+		return 0;
+
+	/* Rmodule couldn't do anything with the data. Continue on with SELF. */
+
 	ew = elf_writer_init(&ehdr);
 	if (ew == NULL) {
 		ERROR("Unable to init ELF writer.\n");