[coreboot] Patch set updated for coreboot: d40943e cbfstool: Improve and support platform without top-aligned mapping.

Hung-Te Lin (hungte@chromium.org) gerrit at coreboot.org
Mon Jan 28 13:19:48 CET 2013


Hung-Te Lin (hungte at chromium.org) just uploaded a new patch set to gerrit, which you can find at http://review.coreboot.org/2194

-gerrit

commit d40943ec67c84270bfec4a1e9a22a07d490c25cd
Author: Hung-Te Lin <hungte at chromium.org>
Date:   Sat Jan 26 02:03:28 2013 +0800

    cbfstool: Improve and support platform without top-aligned mapping.
    
    CBFS tool was written with lots of global variables and designed with assumption
    based on x86 architecture. To support other platforms better, we should rewrite
    using logical offset instead of top-aligned memory mapped address.
    
    Also fixed a calculation error in size of last entry (which will cause
    overwriting header data when you really used every bits in CBFS) in old CBFS
    tool.
    
    Usage changes:
    
     - "locate-stage" now outputs platform independent offset.  To retrieve x86
       top-aligned virtual address, add "-T".
    
     - "create" takes two extra optional params:
        "-b": base address (or offset) for bootblock. When omitted, put bootblock in
              end of ROM.
        "-H": header offset. When omitted, put header right before bootblock,
              and update a top-aligned virtual address reference in end of ROM.
    
     - All addresses (-b, -H, -l) can now be ROM offset (address < 0x8000000) or
       x86 top-aligned address (address > 0x80000000).
    
     - "-m" (architecture) is deprecated because we won't want to list hundreds of
       architecture variants (like ARM soc family).
    
    Verified to work on ARM (google/snow) and X86 (qemu/x86).
    
    Change-Id: I28c737c8f290e51332119188248ac9e28042024c
    Signed-off-by: Hung-Te Lin <hungte at chromium.org>
---
 src/arch/armv7/Makefile.inc    |    7 +-
 src/arch/x86/Makefile.inc      |    2 +-
 util/cbfstool/EXAMPLE          |   11 +-
 util/cbfstool/cbfs-mkpayload.c |   85 +--
 util/cbfstool/cbfs-mkstage.c   |   51 +-
 util/cbfstool/cbfs.h           |   10 +-
 util/cbfstool/cbfstool.c       |  569 ++++++++--------
 util/cbfstool/common.c         | 1423 ++++++++++++++++++++++------------------
 util/cbfstool/common.h         |  191 ++++--
 9 files changed, 1272 insertions(+), 1077 deletions(-)

diff --git a/src/arch/armv7/Makefile.inc b/src/arch/armv7/Makefile.inc
index 905fbf8..0adf13f 100644
--- a/src/arch/armv7/Makefile.inc
+++ b/src/arch/armv7/Makefile.inc
@@ -46,9 +46,12 @@ prebuild-files = \
 	$(if $(call extract_nth,4,$(file)),-b $(call extract_nth,4,$(file))) &&)
 prebuilt-files = $(foreach file,$(cbfs-files), $(call extract_nth,1,$(file)))
 
+# TODO(hungte) Change CBFS command to use per-board params. Also we don't need
+# to prefix 0x2000 bytes of zero in boot block anymore!
 $(obj)/coreboot.pre1: $(objcbfs)/bootblock.bin $$(prebuilt-files) $(CBFSTOOL)
-	$(CBFSTOOL) $@.tmp create -m armv7 -s $(CONFIG_COREBOOT_ROMSIZE_KB)K \
-		-B $(objcbfs)/bootblock.bin -a 64
+	$(CBFSTOOL) $@.tmp create -s $(CONFIG_COREBOOT_ROMSIZE_KB)K \
+		-B $(objcbfs)/bootblock.bin -a 64 -b 0x0000 -H 0x2040 \
+		-o 0x5000
 	$(prebuild-files) true
 	mv $@.tmp $@
 else
diff --git a/src/arch/x86/Makefile.inc b/src/arch/x86/Makefile.inc
index f79016e..230dc43 100644
--- a/src/arch/x86/Makefile.inc
+++ b/src/arch/x86/Makefile.inc
@@ -375,7 +375,7 @@ $(objgenerated)/romstage_xip.ld: $(objgenerated)/romstage_null.ld $(objcbfs)/bas
 
 $(objcbfs)/base_xip.txt: $(obj)/coreboot.pre1 $(objcbfs)/romstage_null.bin
 	rm -f $@
-	$(CBFSTOOL) $(obj)/coreboot.pre1 locate-stage \
+	$(CBFSTOOL) $(obj)/coreboot.pre1 locate-stage -T \
 		-f $(objcbfs)/romstage_null.bin \
 		-n $(CONFIG_CBFS_PREFIX)/romstage \
 		-a $(CONFIG_XIP_ROM_SIZE) > $@.tmp || \
diff --git a/util/cbfstool/EXAMPLE b/util/cbfstool/EXAMPLE
index 0f7aea6..3662acb 100644
--- a/util/cbfstool/EXAMPLE
+++ b/util/cbfstool/EXAMPLE
@@ -1,8 +1,5 @@
- rm coreboot.rom;
-./cbfstool coreboot.rom create 0x80000 0x10000 /tmp/coreboot.strip
-./cbfstool coreboot.rom add-payload /tmp/filo.elf normal/payload l
+./cbfstool coreboot.rom create -s 256k -B /tmp/coreboot.strip -o 0x10000
+./cbfstool coreboot.rom add-stage -f /tmp/romstage.bin -n fallback/romstage
+./cbfstool coreboot.rom add-payload -f /tmp/filo.elf -n normal/payload -c lzma
 ./cbfstool coreboot.rom print
-#./cbfstool coreboot.rom add-stage /tmp/filo.elf normal/payload
-
-./cbfstool coreboot.rom print
-cp coreboot.rom /home/rminnich/qemutest/
+qemu-system-i386 -bios coreboot.rom -nographic
diff --git a/util/cbfstool/cbfs-mkpayload.c b/util/cbfstool/cbfs-mkpayload.c
index 584ddb6..03280e3 100644
--- a/util/cbfstool/cbfs-mkpayload.c
+++ b/util/cbfstool/cbfs-mkpayload.c
@@ -25,17 +25,14 @@
 
 #include "common.h"
 #include "elf.h"
-#include "cbfs.h"
 
-int parse_elf_to_payload(unsigned char *input, unsigned char **output,
-			 comp_algo algo)
-{
+int parse_elf_to_payload(const struct buffer *input,
+			 struct buffer *output, comp_algo algo) {
 	Elf32_Phdr *phdr;
-	Elf32_Ehdr *ehdr = (Elf32_Ehdr *) input;
+	Elf32_Ehdr *ehdr = (Elf32_Ehdr *)input->data;
 	Elf32_Shdr *shdr;
 	char *header;
 	char *strtab;
-	unsigned char *sptr;
 	int headers;
 	int segments = 1;
 	int isize = 0, osize = 0;
@@ -43,21 +40,16 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 	struct cbfs_payload_segment *segs;
 	int i;
 
-	if(!iself(input)){
+	if(!is_elf_object(input->data)){
 		ERROR("The payload file is not in ELF format!\n");
 		return -1;
 	}
 
-	if (!((ehdr->e_machine == EM_ARM) && (arch == CBFS_ARCHITECTURE_ARMV7)) &&
-	    !((ehdr->e_machine == EM_386) && (arch == CBFS_ARCHITECTURE_X86))) {
-		ERROR("The payload file has the wrong architecture\n");
-		return -1;
-	}
-
 	comp_func_ptr compress = compression_function(algo);
 	if (!compress)
 		return -1;
 
+	DEBUG("start: parse_elf_to_payload\n");
 	headers = ehdr->e_phnum;
 	header = (char *)ehdr;
 
@@ -104,15 +96,14 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 	}
 
 	/* Allocate a block of memory to store the data in */
+	if (buffer_create(output, (segments * sizeof(*segs)) + isize,
+			  input->name) != 0)
+		return -1;
+	memset(output->data, 0, output->size);
 
-	sptr =
-	    calloc((segments * sizeof(struct cbfs_payload_segment)) + isize, 1);
 	doffset = (segments * sizeof(struct cbfs_payload_segment));
 
-	if (sptr == NULL)
-		goto err;
-
-	segs = (struct cbfs_payload_segment *)sptr;
+	segs = (struct cbfs_payload_segment *)output->data;
 	segments = 0;
 
 	for (i = 0; i < ehdr->e_shnum; i++) {
@@ -132,7 +123,7 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 			segs[segments].len = (unsigned int)shdr[i].sh_size;
 			segs[segments].offset = doffset;
 
-			memcpy((unsigned long *)(sptr + doffset),
+			memcpy((unsigned long *)(output->data + doffset),
 			       &header[shdr[i].sh_offset], shdr[i].sh_size);
 
 			doffset += segs[segments].len;
@@ -152,9 +143,9 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 		if (phdr[i].p_filesz == 0) {
 			segs[segments].type = PAYLOAD_SEGMENT_BSS;
 			segs[segments].load_addr =
-			    (uint64_t)htonll(phdr[i].p_paddr);
+			    htonll(phdr[i].p_paddr);
 			segs[segments].mem_len =
-			    (uint32_t)htonl(phdr[i].p_memsz);
+			    htonl(phdr[i].p_memsz);
 			segs[segments].offset = htonl(doffset);
 
 			segments++;
@@ -165,14 +156,14 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 			segs[segments].type = PAYLOAD_SEGMENT_CODE;
 		else
 			segs[segments].type = PAYLOAD_SEGMENT_DATA;
-		segs[segments].load_addr = (uint64_t)htonll(phdr[i].p_paddr);
-		segs[segments].mem_len = (uint32_t)htonl(phdr[i].p_memsz);
+		segs[segments].load_addr = htonll(phdr[i].p_paddr);
+		segs[segments].mem_len = htonl(phdr[i].p_memsz);
 		segs[segments].compression = htonl(algo);
 		segs[segments].offset = htonl(doffset);
 
 		int len;
 		compress((char *)&header[phdr[i].p_offset],
-			 phdr[i].p_filesz, (char *)(sptr + doffset), &len);
+			 phdr[i].p_filesz, output->data + doffset, &len);
 		segs[segments].len = htonl(len);
 
 		/* If the compressed section is larger, then use the
@@ -182,7 +173,7 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 			segs[segments].compression = 0;
 			segs[segments].len = htonl(phdr[i].p_filesz);
 
-			memcpy((char *)(sptr + doffset),
+			memcpy(output->data + doffset,
 			       &header[phdr[i].p_offset], phdr[i].p_filesz);
 		}
 
@@ -193,24 +184,19 @@ int parse_elf_to_payload(unsigned char *input, unsigned char **output,
 	}
 
 	segs[segments].type = PAYLOAD_SEGMENT_ENTRY;
-	segs[segments++].load_addr = (uint64_t)htonll(ehdr->e_entry);
-
-	*output = sptr;
-
-	return (segments * sizeof(struct cbfs_payload_segment)) + osize;
+	segs[segments++].load_addr = htonll(ehdr->e_entry);
 
-      err:
-	return -1;
+	output->size = (segments * sizeof(struct cbfs_payload_segment)) + osize;
+	return 0;
 }
 
-int parse_flat_binary_to_payload(unsigned char *input, unsigned char **output,
-				 int32_t input_size,
+int parse_flat_binary_to_payload(const struct buffer *input,
+				 struct buffer *output,
 				 uint32_t loadaddress,
 				 uint32_t entrypoint,
 				 comp_algo algo)
 {
 	comp_func_ptr compress;
-	unsigned char *payload;
 	struct cbfs_payload_segment *segs;
 	int doffset, len = 0;
 
@@ -219,38 +205,35 @@ int parse_flat_binary_to_payload(unsigned char *input, unsigned char **output,
 		return -1;
 
 	DEBUG("start: parse_flat_binary_to_payload\n");
-
-	/* FIXME compressed file size might be bigger than original file */
-	payload = calloc((2 * sizeof(struct cbfs_payload_segment)) + input_size, 1);
-	if (payload == NULL) {
-		ERROR("Could not allocate memory.\n");
+	if (buffer_create(output, (2 * sizeof(*segs) + input->size),
+			  input->name) != 0)
 		return -1;
-	}
+	memset(output->data, 0, output->size);
 
-	segs = (struct cbfs_payload_segment *)payload;
+	segs = (struct cbfs_payload_segment *)output->data;
 	doffset = (2 * sizeof(*segs));
 
 	/* Prepare code segment */
 	segs[0].type = PAYLOAD_SEGMENT_CODE;
 	segs[0].load_addr = htonll(loadaddress);
-	segs[0].mem_len = htonl(input_size);
+	segs[0].mem_len = htonl(input->size);
 	segs[0].offset = htonl(doffset);
 
-	/* TODO what if compressed file size is bigger than original? */
-	compress((char*)input, input_size, (char*)payload + doffset, &len);
+	/* TODO what if  compressed file size is bigger than original? */
+	compress(input->data, input->size, output->data + doffset, &len);
 	segs[0].compression = htonl(algo);
 	segs[0].len = htonl(len);
 
-	if ((unsigned int)len >= input_size) {
+	if ((unsigned int)len >= input->size) {
 		segs[0].compression = 0;
-		segs[0].len = htonl(input_size);
-		memcpy(payload + doffset, input, input_size);
+		segs[0].len = htonl(input->size);
+		memcpy(output->data + doffset, input->data, input->size);
 	}
 
 	/* prepare entry point segment */
 	segs[1].type = PAYLOAD_SEGMENT_ENTRY;
 	segs[1].load_addr = htonll(entrypoint);
-	*output = payload;
+	output->size = doffset + ntohl(segs[0].len);
 
-	return doffset + ntohl(segs[0].len);
+	return 0;
 }
diff --git a/util/cbfstool/cbfs-mkstage.c b/util/cbfstool/cbfs-mkstage.c
index 4374bda..aa13426 100644
--- a/util/cbfstool/cbfs-mkstage.c
+++ b/util/cbfstool/cbfs-mkstage.c
@@ -25,7 +25,6 @@
 #include <string.h>
 
 #include "common.h"
-#include "cbfs.h"
 #include "elf.h"
 
 static unsigned int idemp(unsigned int x)
@@ -44,13 +43,11 @@ static unsigned int swap32(unsigned int x)
 unsigned int (*elf32_to_native) (unsigned int) = idemp;
 
 /* returns size of result, or -1 if error */
-int parse_elf_to_stage(unsigned char *input, unsigned char **output,
-		       comp_algo algo, uint32_t * location)
-{
+int parse_elf_to_stage(const struct buffer *input, struct buffer *output,
+		       comp_algo algo, uint32_t location) {
 	Elf32_Phdr *phdr;
-	Elf32_Ehdr *ehdr = (Elf32_Ehdr *) input;
+	Elf32_Ehdr *ehdr = (Elf32_Ehdr *) input->data;
 	char *header, *buffer;
-	unsigned char *out;
 
 	int headers;
 	int i;
@@ -63,17 +60,12 @@ int parse_elf_to_stage(unsigned char *input, unsigned char **output,
 	if (!compress)
 		return -1;
 
-	if (!iself(input)) {
+	DEBUG("start: parse_elf_to_stage(location=0x%x)\n", location);
+	if (!is_elf_object(input->data)) {
 		ERROR("The stage file is not in ELF format!\n");
 		return -1;
 	}
 
-	if (!((ehdr->e_machine == EM_ARM) && (arch == CBFS_ARCHITECTURE_ARMV7)) &&
-	    !((ehdr->e_machine == EM_386) && (arch == CBFS_ARCHITECTURE_X86))) {
-		ERROR("The stage file has the wrong architecture\n");
-		return -1;
-	}
-
 	if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
 		elf_bigendian = 1;
 	}
@@ -121,8 +113,8 @@ int parse_elf_to_stage(unsigned char *input, unsigned char **output,
 			mem_end = mend;
 	}
 
-	if (data_start < *location) {
-		data_start = *location;
+	if (data_start < location) {
+		data_start = location;
 	}
 
 	if (data_end <= data_start) {
@@ -139,8 +131,7 @@ int parse_elf_to_stage(unsigned char *input, unsigned char **output,
 		return -1;
 	}
 
-	/* Copy the file data into the buffer */
-
+	/* Copy file data into buffer */
 	for (i = 0; i < headers; i++) {
 		unsigned int l_start, l_offset = 0;
 
@@ -151,9 +142,9 @@ int parse_elf_to_stage(unsigned char *input, unsigned char **output,
 			continue;
 
 		l_start = elf32_to_native(phdr[i].p_paddr);
-		if (l_start < *location) {
-			l_offset = *location - l_start;
-			l_start = *location;
+		if (l_start < location) {
+			l_offset = location - l_start;
+			l_start = location;
 		}
 
 		memcpy(buffer + (l_start - data_start),
@@ -162,28 +153,24 @@ int parse_elf_to_stage(unsigned char *input, unsigned char **output,
 	}
 
 	/* Now make the output buffer */
-	out = calloc(sizeof(struct cbfs_stage) + data_end - data_start, 1);
-
-	if (out == NULL) {
+	if (buffer_create(output, sizeof(*stage) + data_end - data_start,
+			  input->name) != 0) {
 		ERROR("Unable to allocate memory: %m\n");
 		return -1;
 	}
+	memset(output->data, 0, output->size);
 
-	stage = (struct cbfs_stage *)out;
+	stage = (struct cbfs_stage *)output->data;
 
 	stage->load = data_start; /* FIXME: htonll */
 	stage->memlen = mem_end - data_start;
 	stage->compression = algo;
 	stage->entry = ehdr->e_entry; /* FIXME: htonll */
 
-	compress(buffer, data_end - data_start,
-		 (char *)(out + sizeof(struct cbfs_stage)), (int *)&stage->len);
+	compress(buffer, data_end - data_start, (output->data + sizeof(*stage)),
+		 (int *)&stage->len);
 
 	free(buffer);
-
-	*output = out;
-
-	if (*location)
-		*location -= sizeof(struct cbfs_stage);
-	return sizeof(struct cbfs_stage) + stage->len;
+	output->size = sizeof(*stage) + stage->len;
+	return 0;
 }
diff --git a/util/cbfstool/cbfs.h b/util/cbfstool/cbfs.h
index 3dbeefd..5ebabb6 100644
--- a/util/cbfstool/cbfs.h
+++ b/util/cbfstool/cbfs.h
@@ -25,7 +25,9 @@
 #define CBFS_HEADPTR_ADDR_X86 0xFFFFFFFC
 #define CBFS_HEADER_VERSION1 0x31313131
 #define CBFS_HEADER_VERSION2 0x31313132
-#define CBFS_HEADER_VERSION  CBFS_HEADER_VERSION2
+// TODO(hungte) We probably don't need "architecture" anymore - remove in future
+// Right now, to make old cbfstool happy, declare version as 1.
+#define CBFS_HEADER_VERSION  CBFS_HEADER_VERSION1
 
 struct cbfs_header {
 	uint32_t magic;
@@ -42,6 +44,8 @@ struct cbfs_header {
 #define CBFS_ARCHITECTURE_X86      0x00000001
 #define CBFS_ARCHITECTURE_ARMV7    0x00000010
 
+#define CBFS_FILE_MAGIC "LARCHIVE"
+
 struct cbfs_file {
 	uint8_t magic[8];
 	uint32_t len;
@@ -105,9 +109,7 @@ struct cbfs_payload {
  */
 #define CBFS_COMPONENT_NULL 0xFFFFFFFF
 
-int cbfs_file_header(unsigned long physaddr);
+#define CBFS_NAME(_c) (((char *) (_c)) + sizeof(struct cbfs_file))
 #define CBFS_SUBHEADER(_p) ( (void *) ((((uint8_t *) (_p)) + ntohl((_p)->offset))) )
 
-struct cbfs_file *cbfs_create_empty_file(uint32_t physaddr, uint32_t size);
-
 #endif
diff --git a/util/cbfstool/cbfstool.c b/util/cbfstool/cbfstool.c
index b0e5148..59814c1 100644
--- a/util/cbfstool/cbfstool.c
+++ b/util/cbfstool/cbfstool.c
@@ -4,6 +4,7 @@
  * Copyright (C) 2009 coresystems GmbH
  *                 written by Patrick Georgi <patrick.georgi at coresystems.de>
  * Copyright (C) 2012 Google, Inc.
+ * Copyright (C) 2013 The ChromiumOS Authors.  All rights reserved.
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -20,12 +21,14 @@
  */
 
 #include <ctype.h>
+#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <getopt.h>
 #include "common.h"
-#include "cbfs.h"
+
+int verbose = 0;
 
 struct command {
 	const char *name;
@@ -33,376 +36,338 @@ struct command {
 	int (*function) (void);
 };
 
-int verbose = 0;
 struct param {
 	char *cbfs_name;
 	char *name;
 	char *filename;
-	char *bootblock;
+	char *bootblock_file;
 	uint32_t type;
-	uint32_t baseaddress;
-	uint32_t loadaddress;
+	uint32_t base_address;
+	uint32_t base_address_assigned;
+	uint32_t load_address;
+	uint32_t header_offset;
+	uint32_t header_offset_assigned;
 	uint32_t entrypoint;
 	uint32_t size;
 	uint32_t alignment;
 	uint32_t offset;
+	uint32_t top_aligned;
 	comp_algo algo;
 } param;
 
-static int cbfs_add(void)
-{
-	uint32_t filesize = 0;
-	void *rom, *filedata, *cbfsfile;
+typedef int (*convert_buffer_t)(struct buffer *buffer);
 
-	if (!param.filename) {
+static int cbfstool_add_file(const char *cbfs_name,
+			     const char *filename,
+			     const char *name,
+			     uint32_t type,
+			     uint32_t offset,
+			     convert_buffer_t convert) {
+	struct cbfs_image image;
+	struct buffer buffer;
+	int result = 1;
+
+	if (!filename) {
 		ERROR("You need to specify -f/--filename.\n");
 		return 1;
 	}
 
-	if (!param.name) {
+	if (!name) {
 		ERROR("You need to specify -n/--name.\n");
 		return 1;
 	}
 
-	if (param.type == 0) {
+	if (type == 0) {
 		ERROR("You need to specify a valid -t/--type.\n");
 		return 1;
 	}
 
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
+	if (cbfs_image_from_file(&image, cbfs_name) != 0) {
 		ERROR("Could not load ROM image '%s'.\n",
-			param.cbfs_name);
+			cbfs_name);
 		return 1;
 	}
 
-	filedata = loadfile(param.filename, &filesize, 0, SEEK_SET);
-	if (filedata == NULL) {
-		ERROR("Could not load file '%s'.\n",
-			param.filename);
-		free(rom);
+	if (cbfs_get_entry(&image, name)) {
+		ERROR("'%s' already in ROM image.\n", name);
 		return 1;
 	}
 
-	cbfsfile = create_cbfs_file(param.name, filedata, &filesize,
-					param.type, &param.baseaddress);
-	free(filedata);
-
-	if (add_file_to_cbfs(cbfsfile, filesize, param.baseaddress)) {
-		ERROR("Adding file '%s' failed.\n", param.filename);
-		free(cbfsfile);
-		free(rom);
-		return 1;
-	}
-	if (writerom(param.cbfs_name, rom, romsize)) {
-		free(cbfsfile);
-		free(rom);
+	if (buffer_from_file(&buffer, filename) != 0) {
+		ERROR("Could not load file '%s'.\n", filename);
+		cbfs_image_delete(&image);
 		return 1;
 	}
 
-	free(cbfsfile);
-	free(rom);
-	return 0;
-}
+	do {
+		if (convert && convert(&buffer) != 0) {
+			ERROR("Failed to parse file '%s'.\n",
+				filename);
+			break;
+		}
+		if (cbfs_add_entry(&image, &buffer, name, type, offset) != 0)
+			break;
+		if (cbfs_image_write_file(&image, cbfs_name) != 0)
+			break;
 
-static int cbfs_add_payload(void)
-{
-	uint32_t filesize = 0;
-	void *rom, *filedata, *cbfsfile;
-	unsigned char *payload;
+		result = 0;
+	} while (0);
 
-	if (!param.filename) {
-		ERROR("You need to specify -f/--filename.\n");
-		return 1;
-	}
+	buffer_delete(&buffer);
+	cbfs_image_delete(&image);
+	return result;
+}
 
-	if (!param.name) {
-		ERROR("You need to specify -n/--name.\n");
-		return 1;
-	}
+static int cbfstool_convert_mkstage(struct buffer *buffer) {
+	struct buffer output;
+	if (parse_elf_to_stage(buffer, &output, param.algo,
+			       param.base_address) != 0) 
+		return -1;
+	if (param.base_address)
+		param.base_address -= sizeof(struct cbfs_stage);
+	buffer_delete(buffer);
+	// direct assign, no dupe.
+	memcpy(buffer, &output, sizeof(*buffer));
+	return 0;
+}
 
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
-		ERROR("Could not load ROM image '%s'.\n",
-			param.cbfs_name);
-		return 1;
-	}
+static int cbfstool_convert_elf_mkpayload(struct buffer *buffer) {
+	struct buffer output;
+	if (parse_elf_to_payload(buffer, &output, param.algo) != 0)
+		return -1;
+	buffer_delete(buffer);
+	// direct assign, no dupe.
+	memcpy(buffer, &output, sizeof(*buffer));
+	return 0;
+}
 
-	filedata = loadfile(param.filename, &filesize, 0, SEEK_SET);
-	if (filedata == NULL) {
-		ERROR("Could not load file '%s'.\n",
-			param.filename);
-		free(rom);
-		return 1;
-	}
+static int cbfstool_convert_flat_mkpayload(struct buffer *buffer) {
+	struct buffer output;
+	if (parse_flat_binary_to_payload(buffer, &output,
+					 param.load_address,
+					 param.entrypoint,
+					 param.algo) != 0) {
+		return -1;
+	}
+	buffer_delete(buffer);
+	// direct assign, no dupe.
+	memcpy(buffer, &output, sizeof(*buffer));
+	return 0;
+}
 
-	filesize = parse_elf_to_payload(filedata, &payload, param.algo);
-	if ((int)filesize <= 0) {
-		ERROR("Adding payload '%s' failed.\n",
-			param.filename);
-		free(rom);
-		return 1;
-	}
+static int cbfstool_add(void)
+{
+	return cbfstool_add_file(param.cbfs_name,
+				 param.filename,
+				 param.name,
+				 param.type,
+				 param.base_address,
+				 NULL);
+}
 
-	cbfsfile = create_cbfs_file(param.name, payload, &filesize,
-				CBFS_COMPONENT_PAYLOAD, &param.baseaddress);
+static int cbfstool_add_payload(void)
+{
+	return cbfstool_add_file(param.cbfs_name,
+				 param.filename,
+				 param.name,
+				 CBFS_COMPONENT_PAYLOAD,
+				 param.base_address,
+				 cbfstool_convert_elf_mkpayload);
+}
 
-	free(filedata);
-	free(payload);
+static int cbfstool_add_stage(void)
+{
+	return cbfstool_add_file(param.cbfs_name,
+				 param.filename,
+				 param.name,
+				 CBFS_COMPONENT_STAGE,
+				 param.base_address,
+				 cbfstool_convert_mkstage);
+}
 
-	if (add_file_to_cbfs(cbfsfile, filesize, param.baseaddress)) {
-		ERROR("Adding payload '%s' failed.\n",
-			param.filename);
-		free(cbfsfile);
-		free(rom);
+static int cbfstool_add_flat_binary(void)
+{
+	if (param.load_address == 0) {
+		ERROR("You need to specify a valid "
+			"-l/--load-address.\n");
 		return 1;
 	}
-
-	if (writerom(param.cbfs_name, rom, romsize)) {
-		free(cbfsfile);
-		free(rom);
+	if (param.entrypoint == 0) {
+		ERROR("You need to specify a valid "
+			"-e/--entry-point.\n");
 		return 1;
 	}
-
-	free(cbfsfile);
-	free(rom);
-	return 0;
+	return cbfstool_add_file(param.cbfs_name,
+				 param.filename,
+				 param.name,
+				 CBFS_COMPONENT_PAYLOAD,
+				 param.base_address,
+				 cbfstool_convert_flat_mkpayload);
 }
 
-static int cbfs_add_stage(void)
+static int cbfstool_remove(void)
 {
-	uint32_t filesize = 0;
-	void *rom, *filedata, *cbfsfile;
-	unsigned char *stage;
-
-	if (!param.filename) {
-		ERROR("You need to specify -f/--filename.\n");
-		return 1;
-	}
+	int result = 1;
+	struct cbfs_image image;
 
 	if (!param.name) {
 		ERROR("You need to specify -n/--name.\n");
 		return 1;
 	}
 
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
+	if (cbfs_image_from_file(&image, param.cbfs_name) != 0) {
 		ERROR("Could not load ROM image '%s'.\n",
 			param.cbfs_name);
 		return 1;
 	}
 
-	filedata = loadfile(param.filename, &filesize, 0, SEEK_SET);
-	if (filedata == NULL) {
-		ERROR("Could not load file '%s'.\n",
-			param.filename);
-		free(rom);
-		return 1;
-	}
-
-	filesize = parse_elf_to_stage(filedata, &stage, param.algo, &param.baseaddress);
-
-	cbfsfile = create_cbfs_file(param.name, stage, &filesize,
-				CBFS_COMPONENT_STAGE, &param.baseaddress);
-
-	free(filedata);
-	free(stage);
-
-	if (add_file_to_cbfs(cbfsfile, filesize, param.baseaddress)) {
-		ERROR("Adding stage '%s' failed.\n",
-			param.filename);
-		free(cbfsfile);
-		free(rom);
-		return 1;
-	}
-
-	if (writerom(param.cbfs_name, rom, romsize)) {
-		free(cbfsfile);
-		free(rom);
-		return 1;
-	}
+	do {
+		if (cbfs_remove_entry(&image, param.name) != 0) {
+			ERROR("Removing file '%s' failed.\n",
+				param.name);
+			break;
+		}
+		if (cbfs_image_write_file(&image, param.cbfs_name) != 0)
+			break;
+		result = 0;
+	} while (0);
 
-	free(cbfsfile);
-	free(rom);
-	return 0;
+	cbfs_image_delete(&image);
+	return result;
 }
 
-static int cbfs_add_flat_binary(void)
+static int cbfstool_create(void)
 {
-	uint32_t filesize = 0;
-	void *rom, *filedata, *cbfsfile;
-	unsigned char *payload;
+	struct cbfs_image image;
+	struct buffer bootblock;
 
-	if (!param.filename) {
-		ERROR("You need to specify -f/--filename.\n");
-		return 1;
-	}
-
-	if (!param.name) {
-		ERROR("You need to specify -n/--name.\n");
+	if (param.size == 0) {
+		ERROR("You need to specify a valid -s/--size.\n");
 		return 1;
 	}
 
-	if (param.loadaddress == 0) {
-		ERROR("You need to specify a valid "
-			"-l/--load-address.\n");
+	if (!param.bootblock_file) {
+		ERROR("You need to specify -B/--bootblock.\n");
 		return 1;
 	}
 
-	if (param.entrypoint == 0) {
-		ERROR("You need to specify a valid "
-			"-e/--entry-point.\n");
+	if (buffer_from_file(&bootblock, param.bootblock_file) != 0) {
 		return 1;
 	}
 
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
-		ERROR("Could not load ROM image '%s'.\n",
-			param.cbfs_name);
-		return 1;
+	// Setup default boot offset and header offset.
+	if (!param.base_address_assigned) {
+		// put boot block before end of ROM.
+		param.base_address = param.size - bootblock.size;
+		DEBUG("bootblock in end of ROM.\n");
 	}
-
-	filedata = loadfile(param.filename, &filesize, 0, SEEK_SET);
-	if (filedata == NULL) {
-		ERROR("Could not load file '%s'.\n",
-			param.filename);
-		free(rom);
-		return 1;
+	if (!param.header_offset_assigned) {
+		// Put header before bootblock, and make a reference in end of
+		// bootblock.
+		param.header_offset = (
+				param.base_address -
+				sizeof(struct cbfs_header));
+		if (bootblock.size >= sizeof(uint32_t)) {
+			// TODO this only works for 32b top-aligned system now...
+			uint32_t ptr = param.header_offset - param.size;
+			uint32_t *sig = (uint32_t *)(bootblock.data +
+						     bootblock.size -
+						     sizeof(ptr));
+			*sig = ptr;
+			DEBUG("CBFS header reference in end of bootblock.\n");
+		}
 	}
 
-	filesize = parse_flat_binary_to_payload(filedata, &payload,
-						filesize,
-						param.loadaddress,
-						param.entrypoint,
-						param.algo);
-	if ((int)filesize <= 0) {
-		ERROR("Adding payload '%s' failed.\n",
-			param.filename);
-		free(rom);
+	if (cbfs_image_create(&image,
+			      param.size,
+			      param.alignment,
+			      &bootblock,
+			      param.base_address,
+			      param.header_offset,
+			      param.offset) != 0) {
+		ERROR("Failed to create %s.\n", param.cbfs_name);
 		return 1;
 	}
-
-	cbfsfile = create_cbfs_file(param.name, payload, &filesize,
-				    CBFS_COMPONENT_PAYLOAD, &param.baseaddress);
-
-	free(filedata);
-	free(payload);
-
-	if (add_file_to_cbfs(cbfsfile, filesize, param.baseaddress)) {
-		ERROR("Adding payload '%s' failed.\n",
-			param.filename);
-		free(cbfsfile);
-		free(rom);
+	if (cbfs_image_write_file(&image, param.cbfs_name) != 0) {
+		ERROR("Failed to write %s.\n", param.cbfs_name);
 		return 1;
 	}
-	if (writerom(param.cbfs_name, rom, romsize)) {
-		free(cbfsfile);
-		free(rom);
-		return 1;
-	}
-
-	free(cbfsfile);
-	free(rom);
+	cbfs_image_delete(&image);
 	return 0;
+
 }
 
-static int cbfs_remove(void)
+static int cbfstool_locate_stage(void)
 {
-	void *rom;
-
-	if (!param.name) {
-		ERROR("You need to specify -n/--name.\n");
-		return 1;
-	}
-
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
-		ERROR("Could not load ROM image '%s'.\n",
-			param.cbfs_name);
-		return 1;
-	}
+	struct cbfs_image image;
+	struct buffer buffer;
+	int32_t address;
 
-	if (remove_file_from_cbfs(param.name)) {
-		ERROR("Removing file '%s' failed.\n",
-			param.name);
-		free(rom);
+	if (!param.filename) {
+		ERROR("You need to specify -f/--filename.\n");
 		return 1;
 	}
 
-	if (writerom(param.cbfs_name, rom, romsize)) {
-		free(rom);
+	if (!param.name) {
+		ERROR("You need to specify -n/--name.\n");
 		return 1;
 	}
 
-	free(rom);
-	return 0;
-}
-
-static int cbfs_create(void)
-{
-	if (param.size == 0) {
-		ERROR("You need to specify a valid -s/--size.\n");
+	if (cbfs_image_from_file(&image, param.cbfs_name) != 0) {
+		ERROR("Failed to load %s.\n", param.cbfs_name);
 		return 1;
 	}
 
-	if (!param.bootblock) {
-		ERROR("You need to specify -b/--bootblock.\n");
+	if (buffer_from_file(&buffer, param.filename) != 0) {
+		ERROR("Cannot load %s.\n", param.filename);
+		cbfs_image_delete(&image);
 		return 1;
 	}
 
-	if (arch == CBFS_ARCHITECTURE_UNKNOWN) {
-		ERROR("You need to specify -m/--machine arch\n");
+	if (cbfs_get_entry(&image, param.name)) {
+		ERROR("'%s' already in CBFS.\n", param.name);
+		buffer_delete(&buffer);
+		cbfs_image_delete(&image);
 		return 1;
 	}
 
-	return create_cbfs_image(param.cbfs_name, param.size, param.bootblock,
-						param.alignment, param.offset);
-}
-
-static int cbfs_locate_stage(void)
-{
-	uint32_t filesize, location;
-
-	if (!param.filename) {
-		ERROR("You need to specify -f/--filename.\n");
+	address = cbfs_locate_stage(&image, param.name, buffer.size,
+				    param.alignment);
+	if (address == -1) {
+		ERROR("'%s' can't fit in CBFS for align 0x%x.\n",
+			param.name, param.alignment);
+		buffer_delete(&buffer);
+		cbfs_image_delete(&image);
 		return 1;
 	}
 
-	if (!param.name) {
-		ERROR("You need to specify -n/--name.\n");
-		return 1;
+	if (param.top_aligned) {
+		address = address - ntohl(image.header->romsize);
 	}
 
-	filesize = getfilesize(param.filename);
-
-	location = cbfs_find_stage_location(param.cbfs_name, filesize,
-					    param.name, param.alignment);
-
-	printf("0x%x\n", location);
-	return location == 0 ? 1 : 0;
+	buffer_delete(&buffer);
+	cbfs_image_delete(&image);
+	printf("0x%x\n", address);
+	return 0;
 }
 
-static int cbfs_print(void)
+static int cbfstool_print(void)
 {
-	void *rom;
-
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
+	struct cbfs_image image;
+	if (cbfs_image_from_file(&image, param.cbfs_name) != 0) {
 		ERROR("Could not load ROM image '%s'.\n",
 			param.cbfs_name);
 		return 1;
 	}
-
-	print_cbfs_directory(param.cbfs_name);
-
-	free(rom);
+	cbfs_print_directory(&image);
+	cbfs_image_delete(&image);
 	return 0;
 }
 
-static int cbfs_extract(void)
+static int cbfstool_extract(void)
 {
-	void *rom;
-	int ret;
+	int result = 0;
+	struct cbfs_image image;
 
 	if (!param.filename) {
 		ERROR("You need to specify -f/--filename.\n");
@@ -414,29 +379,29 @@ static int cbfs_extract(void)
 		return 1;
 	}
 
-	rom = loadrom(param.cbfs_name);
-	if (rom == NULL) {
+	if (cbfs_image_from_file(&image, param.cbfs_name) != 0) {
 		ERROR("Could not load ROM image '%s'.\n",
 			param.cbfs_name);
-		return 1;
+		result = 1;
+	} else if (cbfs_export_entry(&image, param.name,
+				     param.filename) != 0) {
+		result = 1;
 	}
 
-	ret = extract_file_from_cbfs(param.cbfs_name, param.name, param.filename);
-
-	free(rom);
-	return ret;
+	cbfs_image_delete(&image);
+	return result;
 }
 
 static const struct command commands[] = {
-	{"add", "f:n:t:b:vh?", cbfs_add},
-	{"add-payload", "f:n:t:c:b:vh?", cbfs_add_payload},
-	{"add-stage", "f:n:t:c:b:vh?", cbfs_add_stage},
-	{"add-flat-binary", "f:n:l:e:c:b:vh?", cbfs_add_flat_binary},
-	{"remove", "n:vh?", cbfs_remove},
-	{"create", "s:B:a:o:m:vh?", cbfs_create},
-	{"locate-stage", "f:n:a:vh?", cbfs_locate_stage},
-	{"print", "vh?", cbfs_print},
-	{"extract", "n:f:vh?", cbfs_extract},
+	{"add", "f:n:t:b:vh?", cbfstool_add},
+	{"add-payload", "f:n:t:c:b:vh?", cbfstool_add_payload},
+	{"add-stage", "f:n:t:c:b:vh?", cbfstool_add_stage},
+	{"add-flat-binary", "f:n:l:e:c:b:vh?", cbfstool_add_flat_binary},
+	{"remove", "n:vh?", cbfstool_remove},
+	{"create", "s:B:b:H:a:o:m:vh?", cbfstool_create},
+	{"locate-stage", "Tf:n:a:vh?", cbfstool_locate_stage},
+	{"print", "vh?", cbfstool_print},
+	{"extract", "n:f:vh?", cbfstool_extract},
 };
 
 static struct option long_options[] = {
@@ -448,10 +413,12 @@ static struct option long_options[] = {
 	{"entry-point",  required_argument, 0, 'e' },
 	{"size",         required_argument, 0, 's' },
 	{"bootblock",    required_argument, 0, 'B' },
+	{"header-offset",required_argument, 0, 'H' },
 	{"alignment",    required_argument, 0, 'a' },
 	{"offset",       required_argument, 0, 'o' },
 	{"file",         required_argument, 0, 'f' },
 	{"arch",         required_argument, 0, 'm' },
+	{"top-aligned",  no_argument,       0, 'T' },
 	{"verbose",      no_argument,       0, 'v' },
 	{"help",         no_argument,       0, 'h' },
 	{NULL,           0,                 0,  0  }
@@ -462,10 +429,11 @@ static void usage(char *name)
 	LOG("cbfstool: Management utility for CBFS formatted ROM images\n\n"
 	     "USAGE:\n" " %s [-h]\n"
 	     " %s FILE COMMAND [-v] [PARAMETERS]...\n\n" "OPTIONs:\n"
-	     "  -v              Provide verbose output\n"
-	     "  -h		Display this help message\n\n"
+	     "  -h             Display this help message\n\n"
+	     "  -T             Display top-aligned address instead of offset\n"
+	     "  -v             Verbose output\n"
 	     "COMMANDs:\n"
-	     " add -f FILE -n NAME -t TYPE [-b base-address]               "
+	     " add -f FILE -n NAME -t TYPE [-b base]                       "
 			"Add a component\n"
 	     " add-payload -f FILE -n NAME [-c compression] [-b base]      "
 			"Add a payload to the ROM\n"
@@ -476,9 +444,10 @@ static void usage(char *name)
 			"Add a 32bit flat mode binary\n"
 	     " remove -n NAME                                              "
 			"Remove a component\n"
-	     " create -s size -B bootblock -m ARCH [-a align] [-o offset]  "
+	     " create -s size -B bootblock [-b base] [-a align] \\\n"
+	     "         [-o offset] [-H header-offset]                      "
 			"Create a ROM file\n"
-	     " locate-stage -f FILE -n NAME [-a align]                     "
+	     " locate-stage -f FILE -n NAME [-a align] [-T]                "
 			"Find a space for stage to fit in one aligned page\n"
 	     " print                                                       "
 			"Show the contents of the ROM\n"
@@ -489,7 +458,7 @@ static void usage(char *name)
 	     "  armv7, x86\n"
 	     "TYPEs:\n", name, name
 	    );
-	print_supported_filetypes();
+	print_all_cbfs_entry_types();
 }
 
 int main(int argc, char **argv)
@@ -497,6 +466,14 @@ int main(int argc, char **argv)
 	size_t i;
 	int c;
 
+	/* Help tracing in debug builds. */
+	if (verbose > 1) {
+		LOG("[CBFS] ");
+		for (i = 0; i < argc; i++)
+			LOG("'%s' ", argv[i]);
+		LOG("\n");
+	}
+
 	if (argc < 3) {
 		usage(argv[0]);
 		return 1;
@@ -522,8 +499,8 @@ int main(int argc, char **argv)
 			/* filter out illegal long options */
 			if (strchr(commands[i].optstring, c) == NULL) {
 				/* TODO maybe print actual long option instead */
-				ERROR("%s: invalid option -- '%c'\n",
-				      argv[0], c);
+				ERROR("%s: invalid option -- '%c'\n", argv[0],
+				      c);
 				c = '?';
 			}
 
@@ -532,29 +509,31 @@ int main(int argc, char **argv)
 				param.name = optarg;
 				break;
 			case 't':
-				if (intfiletype(optarg) != ((uint64_t) - 1))
-					param.type = intfiletype(optarg);
-				else
-					param.type = strtoul(optarg, NULL, 0);
+				// zero should be reserved for types.
+				param.type = get_cbfs_entry_type(
+						optarg,
+						strtoul(optarg, NULL, 0));
 				if (param.type == 0)
 					WARN("Unknown type '%s' ignored\n",
-							optarg);
+					     optarg);
 				break;
 			case 'c':
-				if (!strncasecmp(optarg, "lzma", 5))
-					param.algo = CBFS_COMPRESS_LZMA;
-				else if (!strncasecmp(optarg, "none", 5))
-					param.algo = CBFS_COMPRESS_NONE;
-				else
+				param.algo = get_cbfs_compression(
+						optarg, -1);
+				if (param.algo == -1) {
 					WARN("Unknown compression '%s'"
 					     " ignored.\n", optarg);
+					param.algo = 0;
+				}
 				break;
 			case 'b':
-				param.baseaddress = strtoul(optarg, NULL, 0);
+				// base_address may be zero on non-x86, so we
+				// need an explicit "base_address_assigned".
+				param.base_address = strtoul(optarg, NULL, 0);
+				param.base_address_assigned = 1;
 				break;
 			case 'l':
-				param.loadaddress = strtoul(optarg, NULL, 0);
-
+				param.load_address = strtoul(optarg, NULL, 0);
 				break;
 			case 'e':
 				param.entrypoint = strtoul(optarg, NULL, 0);
@@ -568,7 +547,12 @@ int main(int argc, char **argv)
 					param.size *= 1024 * 1024;
 				}
 			case 'B':
-				param.bootblock = optarg;
+				param.bootblock_file = optarg;
+				break;
+			case 'H':
+				param.header_offset = strtoul(
+						optarg, NULL, 0);
+				param.header_offset_assigned = 1;
 				break;
 			case 'a':
 				param.alignment = strtoul(optarg, NULL, 0);
@@ -579,11 +563,14 @@ int main(int argc, char **argv)
 			case 'f':
 				param.filename = optarg;
 				break;
+			case 'T':
+				param.top_aligned = 1;
+				break;
 			case 'v':
 				verbose++;
 				break;
 			case 'm':
-				arch = string_to_arch(optarg);
+				INFO("Architecture (-m) is deprecated.\n");
 				break;
 			case 'h':
 			case '?':
diff --git a/util/cbfstool/common.c b/util/cbfstool/common.c
index a6cfa22..3fef412 100644
--- a/util/cbfstool/common.c
+++ b/util/cbfstool/common.c
@@ -4,6 +4,7 @@
  * Copyright (C) 2009 coresystems GmbH
  *                 written by Patrick Georgi <patrick.georgi at coresystems.de>
  * Copyright (C) 2012 Google, Inc.
+ * Copyright (C) 2013 The ChromiumOS Authors.  All rights reserved.
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -24,8 +25,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+
 #include "common.h"
-#include "cbfs.h"
 #include "elf.h"
 
 /* Utilities */
@@ -41,764 +42,902 @@ int is_big_endian(void)
 	return 0;
 }
 
-size_t getfilesize(const char *filename)
-{
-	size_t size;
-	FILE *file = fopen(filename, "rb");
-	if (file == NULL)
-		return -1;
+uint32_t align_up(uint32_t value, uint32_t align) {
+	if (value % align)
+		value += align - (value % align);
+	return value;
+}
+
+/* Buffer and file I/O */
 
-	fseek(file, 0, SEEK_END);
-	size = ftell(file);
-	fclose(file);
-	return size;
+int buffer_create(struct buffer *buffer, size_t size, const char *name) {
+	buffer->name = strdup(name);
+	buffer->size = size;
+	buffer->data = (char *)malloc(buffer->size);
+	if (!buffer->data) {
+		ERROR("buffer_create: Insufficient memory (0x%zx).\n", size);
+	}
+	return (buffer->data == NULL);
 }
 
-void *loadfile(const char *filename, uint32_t * romsize_p, void *content,
-	       int place)
-{
-	FILE *file = fopen(filename, "rb");
-	if (file == NULL)
-		return NULL;
-
-	fseek(file, 0, SEEK_END);
-	*romsize_p = ftell(file);
-	fseek(file, 0, SEEK_SET);
-	if (!content) {
-		content = malloc(*romsize_p);
-		if (!content) {
-			ERROR("Could not get %d bytes for file %s\n",
-			      *romsize_p, filename);
-			exit(1);
-		}
-	} else if (place == SEEK_END)
-		content -= *romsize_p;
+int buffer_from_file(struct buffer *buffer, const char *filename) {
+	FILE *fp = fopen(filename, "rb");
+	if (!fp) {
+		perror(filename);
+		return -1;
+	}
+	fseek(fp, 0, SEEK_END);
+	buffer->size = ftell(fp);
+	buffer->name = strdup(filename);
+	rewind(fp);
+	buffer->data = (char *)malloc(buffer->size);
+	assert(buffer->data);
+	if (fread(buffer->data, 1, buffer->size, fp) != buffer->size) {
+		ERROR("incomplete read: %s\n", filename);
+		fclose(fp);
+		return -1;
+	}
+	fclose(fp);
+	return 0;
+}
+
+int buffer_write_file(struct buffer *buffer, const char *filename) {
+	FILE *fp = fopen(filename, "wb");
+	if (!fp) {
+		perror(filename);
+		return -1;
+	}
+	assert(buffer && buffer->data);
+	if (fwrite(buffer->data, 1, buffer->size, fp) != buffer->size) {
+		ERROR("incomplete write: %s\n", filename);
+		fclose(fp);
+		return -1;
+	}
+	fclose(fp);
+	return 0;
+}
 
-	if (!fread(content, *romsize_p, 1, file)) {
-		ERROR("Failed to read %s\n", filename);
-		return NULL;
+int buffer_delete(struct buffer *buffer) {
+	assert(buffer);
+	if (buffer->name) {
+		free(buffer->name);
+		buffer->name = NULL;
+	}
+	if (buffer->data) {
+		free(buffer->data);
+		buffer->data = NULL;
 	}
-	fclose(file);
-	return content;
+	buffer->size = 0;
+	return 0;
 }
 
-static struct cbfs_header *master_header;
-static uint32_t phys_start, phys_end, align;
-uint32_t romsize;
-void *offset;
-uint32_t arch = CBFS_ARCHITECTURE_UNKNOWN;
+/* Type and format */
+
+int is_elf_object(const void *input) {
+	Elf32_Ehdr *ehdr = (Elf32_Ehdr *)input;
+	return !memcmp(ehdr->e_ident, ELFMAG, 4);
+}
 
-static struct {
-	uint32_t arch;
+struct typedesc_t {
+	uint32_t type;
 	const char *name;
-} arch_names[] = {
-	{ CBFS_ARCHITECTURE_ARMV7, "armv7" },
-	{ CBFS_ARCHITECTURE_X86, "x86" },
-	{ CBFS_ARCHITECTURE_UNKNOWN, "unknown" }
 };
 
-uint32_t string_to_arch(const char *arch_string)
-{
-	int i;
-	uint32_t ret = CBFS_ARCHITECTURE_UNKNOWN;
+static struct typedesc_t types_cbfs_entry[] = {
+	{CBFS_COMPONENT_STAGE, "stage"},
+	{CBFS_COMPONENT_PAYLOAD, "payload"},
+	{CBFS_COMPONENT_OPTIONROM, "optionrom"},
+	{CBFS_COMPONENT_BOOTSPLASH, "bootsplash"},
+	{CBFS_COMPONENT_RAW, "raw"},
+	{CBFS_COMPONENT_VSA, "vsa"},
+	{CBFS_COMPONENT_MBI, "mbi"},
+	{CBFS_COMPONENT_MICROCODE, "microcode"},
+	{CBFS_COMPONENT_CMOS_DEFAULT, "cmos_default"},
+	{CBFS_COMPONENT_CMOS_LAYOUT, "cmos_layout"},
+	{CBFS_COMPONENT_DELETED, "deleted"},
+	{CBFS_COMPONENT_NULL, "null"},
+	{0, NULL},
+};
 
-	for (i = 0; i < ARRAY_SIZE(arch_names); i++) {
-		if (!strcasecmp(arch_string, arch_names[i].name)) {
-			ret = arch_names[i].arch;
-			break;
-		}
-	}
+static struct typedesc_t types_cbfs_compression[] = {
+	{CBFS_COMPRESS_NONE, "none"},
+	{CBFS_COMPRESS_LZMA, "LZMA"},
+	{0, NULL},
+};
 
-	return ret;
+uint32_t lookup_type_by_name(struct typedesc_t *desc, const char *name,
+			     uint32_t default_value) {
+	int i;
+	for (i = 0; desc[i].name; i++)
+		if (strcmp(desc[i].name, name) == 0)
+			return desc[i].type;
+	return default_value;
 }
 
-const char *arch_to_string(uint32_t a)
-{
+const char *lookup_name_by_type(struct typedesc_t *desc, uint32_t type,
+				const char *default_value) {
 	int i;
-	const char *ret = NULL;
+	for (i = 0; desc[i].name; i++)
+		if (desc[i].type == type)
+			return desc[i].name;
+	return default_value;
+}
 
-	for (i = 0; i < ARRAY_SIZE(arch_names); i++) {
-		if (a == arch_names[i].arch) {
-			ret = arch_names[i].name;
-			break;
-		}
-	}
+uint32_t get_cbfs_entry_type(const char *name, uint32_t default_value) {
+	return lookup_type_by_name(types_cbfs_entry, name, default_value);
+}
 
-	return ret;
+const char *get_cbfs_entry_type_name(uint32_t type) {
+	return lookup_name_by_type(types_cbfs_entry, type, "(unknown)");
+}
 
+uint32_t get_cbfs_compression(const char *name, uint32_t unknown) {
+	return lookup_type_by_name(types_cbfs_compression, name, unknown);
 }
 
-int find_master_header(void *romarea, size_t size)
-{
-	size_t offset;
+void print_all_cbfs_entry_types(void) {
+	size_t i, total = ARRAY_SIZE(types_cbfs_entry);
 
-	if (master_header)
-		return 0;
+	for (i = 0; i < total; i++) {
+		printf(" %s%c", types_cbfs_entry[i].name,
+		       (i + 1 == total) ? '\n' : ',');
+		if ((i + 1) % 8 == 0)
+			printf("\n");
+	}
+}
 
-	for (offset = 0; offset < size - sizeof(struct cbfs_header); offset++) {
-		struct cbfs_header *tmp = romarea + offset;
+/* CBFS image processing */
 
-		if (tmp->magic == ntohl(CBFS_HEADER_MAGIC)) {
-			master_header = tmp;
-			break;
-		}
-	}
+/* The file name align is not defined in CBFS spec -- only a preference by
+ * (old) cbfstool. */
+#define CBFS_FILENAME_ALIGN	(16)
 
-	return master_header ? 0 : 1;
+/* To make CBFS more friendly to ROM, fill -1 (0xFF) instead of zero. */
+#define CBFS_CONTENT_DEFAULT_VALUE	(-1)
+
+static int cbfs_calculate_file_header_size(const char *name) {
+	return (sizeof(struct cbfs_file) +
+		align_up(strlen(name) + 1, CBFS_FILENAME_ALIGN));
 }
 
-void recalculate_rom_geometry(void *romarea)
+int cbfs_image_create(struct cbfs_image *image,
+		      size_t size,
+		      uint32_t align,
+		      struct buffer *bootblock,
+		      int32_t bootblock_offset,
+		      int32_t header_offset,
+		      int32_t entries_offset)
 {
-	if (find_master_header(romarea, romsize)) {
-		ERROR("Cannot find master header\n");
-		exit(1);
-	}
+	struct cbfs_header *header;
+	struct cbfs_file *entry;
+	uint32_t cbfs_len;
 
-	/* Update old headers */
-	if (master_header->version == CBFS_HEADER_VERSION1 &&
-	    ntohl(master_header->architecture) == CBFS_ARCHITECTURE_UNKNOWN) {
-		DEBUG("Updating CBFS master header to version 2\n");
-		master_header->architecture = htonl(CBFS_ARCHITECTURE_X86);
-	}
+	DEBUG("cbfs_create_image: bootblock=0x%x+0x%zx, "
+	      "header=0x%x+0x%zx, entries_offset=0x%x\n",
+	      bootblock_offset, bootblock->size,
+	      header_offset, sizeof(*header), entries_offset);
+
+	if (buffer_create(&image->buffer, size, "(new)") != 0)
+		return -1;
+	image->header = NULL;
+	memset(image->buffer.data, CBFS_CONTENT_DEFAULT_VALUE, size);
 
-	arch = ntohl(master_header->architecture);
+	// Adjust legcay top-aligned address to ROM offset.
+	if (IS_TOP_ALIGNED_ADDRESS(entries_offset))
+		entries_offset += (int32_t)size;
+	if (IS_TOP_ALIGNED_ADDRESS(bootblock_offset))
+		bootblock_offset += (int32_t)size;
+	if (IS_TOP_ALIGNED_ADDRESS(header_offset))
+		header_offset += (int32_t) size;
 
-	switch (arch) {
-	case CBFS_ARCHITECTURE_ARMV7:
-		offset = romarea;
-		phys_start = (0 + ntohl(master_header->offset)) & 0xffffffff;
-		phys_end = romsize & 0xffffffff;
-		break;
-	case CBFS_ARCHITECTURE_X86:
-		offset = romarea + romsize - 0x100000000ULL;
-		phys_start = (0 - romsize + ntohl(master_header->offset)) &
-				0xffffffff;
-		phys_end = (0 - ntohl(master_header->bootblocksize) -
-		     sizeof(struct cbfs_header)) & 0xffffffff;
-		break;
-	default:
-		ERROR("Unknown architecture\n");
-		exit(1);
+	DEBUG("cbfs_create_image: (real offset) bootblock=0x%x, "
+	      "header=0x%x, entries_offset=0x%x\n",
+	      bootblock_offset, header_offset, entries_offset);
+
+	if (align == 0)
+		align = 64;  // default align size.
+
+	// Prepare bootblock
+	if (bootblock_offset + bootblock->size > size) {
+		ERROR("Bootblock (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
+		      bootblock_offset, bootblock->size, size);
+		return -1;
 	}
+	memcpy(image->buffer.data + bootblock_offset, bootblock->data,
+	       bootblock->size);
 
-	align = ntohl(master_header->align);
+	// Prepare header
+	if (header_offset + sizeof(*header) > size) {
+		ERROR("Header (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
+		      header_offset, sizeof(*header), size);
+		return -1;
+	}
+	header = (struct cbfs_header *)(image->buffer.data + header_offset);
+	image->header = header;
+	header->magic = htonl(CBFS_HEADER_MAGIC);
+	header->version = htonl(CBFS_HEADER_VERSION);
+	header->romsize = htonl(size);
+	header->bootblocksize = htonl(bootblock->size);
+	header->align = htonl(align);
+	header->offset = htonl(entries_offset);
+
+	// Prepare entries
+	if (align_up(entries_offset, align) != entries_offset) {
+		ERROR("Offset (0x%x) must be aligned to 0x%x.\n",
+		      entries_offset, align);
+		return -1;
+	}
+	if (entries_offset + sizeof(*entry) > size) {
+		ERROR("Offset (0x%x+0x%zx) exceed ROM size(0x%zx)\n",
+		      entries_offset, sizeof(*entry), size);
+		return -1;
+	}
+	entry = (struct cbfs_file *)(image->buffer.data + entries_offset);
+	// To calculate available length, find
+	//   e = min(bootblock, header, size) where e > entries_offset.
+	cbfs_len = size;
+	if (bootblock_offset > entries_offset && bootblock_offset < cbfs_len)
+		cbfs_len = bootblock_offset;
+	if (header_offset > entries_offset && header_offset < cbfs_len)
+		cbfs_len = header_offset;
+	cbfs_len -= entries_offset + align;
+	cbfs_create_empty_entry(image, entry, cbfs_len, "");
+	LOG("Created CBFS image (capacity = %d bytes)\n", cbfs_len);
+	return 0;
 }
 
-void *loadrom(const char *filename)
-{
-	void *romarea = loadfile(filename, &romsize, 0, SEEK_SET);
-	if (romarea == NULL)
-		return NULL;
-	recalculate_rom_geometry(romarea);
-	return romarea;
-}
+static int cbfs_fix_legacy_size(struct cbfs_image *image) {
+	// A bug in old CBFStool may produce extra few bytes (by alignment) and
+	// cause cbfstool to overwrite things after free space -- which is
+	// usually CBFS header on x86. We need to workaround that.
 
-int writerom(const char *filename, void *start, uint32_t size)
-{
-	FILE *file = fopen(filename, "wb");
-	if (!file) {
-		ERROR("Could not open '%s' for writing: ", filename);
-		perror("");
-		return 1;
+	struct cbfs_file *entry, *first = NULL, *last = NULL;
+	for (first = entry = cbfs_find_first_entry(image);
+	     entry && cbfs_is_valid_entry(entry);
+	     entry = cbfs_find_next_entry(image, entry)) {
+		last = entry;
+	}
+	if ((char *)first < (char *)image->header &&
+	    (char *)entry > (char *)image->header) {
+		WARN("CBFS image was created with old cbfstool with size bug. "
+		     "Fixing size in last entry...\n");
+		last->len = htonl(ntohl(last->len) -
+				  ntohl(image->header->align));
+		DEBUG("Last entry has been changed from 0x%x to 0x%x.\n",
+		      cbfs_get_entry_addr(image, entry),
+		      cbfs_get_entry_addr(image,
+					  cbfs_find_next_entry(image, last)));
 	}
+	return 0;
+}
 
-	if (fwrite(start, size, 1, file) != 1) {
-		ERROR("Could not write to '%s': ", filename);
-		perror("");
-		return 1;
+int cbfs_image_from_file(struct cbfs_image *image, const char *filename) {
+	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);
+	if (!image->header) {
+		ERROR("%s does not have CBFS master header.\n", filename);
+		cbfs_image_delete(image);
+		return -1;
 	}
 
-	fclose(file);
+	cbfs_fix_legacy_size(image);
 	return 0;
 }
 
-int cbfs_file_header(unsigned long physaddr)
-{
-	/* maybe improve this test */
-	return (strncmp(phys_to_virt(physaddr), "LARCHIVE", 8) == 0);
+int cbfs_image_write_file(struct cbfs_image *image, const char *filename) {
+	assert(image && image->buffer.data);
+	return buffer_write_file(&image->buffer, filename);
 }
 
-struct cbfs_file *cbfs_create_empty_file(uint32_t physaddr, uint32_t size)
-{
-	struct cbfs_file *nextfile = (struct cbfs_file *)phys_to_virt(physaddr);
-	strncpy((char *)(nextfile->magic), "LARCHIVE", 8);
-	nextfile->len = htonl(size);
-	nextfile->type = htonl(0xffffffff);
-	nextfile->checksum = 0;	// FIXME?
-	nextfile->offset = htonl(sizeof(struct cbfs_file) + 16);
-	memset(((void *)nextfile) + sizeof(struct cbfs_file), 0, 16);
-	return nextfile;
+int cbfs_image_delete(struct cbfs_image *image) {
+	buffer_delete(&image->buffer);
+	image->header = NULL;
+	return 0;
 }
 
-int iself(unsigned char *input)
-{
-	Elf32_Ehdr *ehdr = (Elf32_Ehdr *) input;
-	return !memcmp(ehdr->e_ident, ELFMAG, 4);
-}
+/* Tries to add an entry with its data (CBFS_SUBHEADER) at given offset. */
+static int cbfs_add_entry_at(struct cbfs_image *image,
+			     struct cbfs_file *entry,
+			     uint32_t size,
+			     const char *name,
+			     uint32_t type,
+			     const void *data,
+			     uint32_t content_offset) {
+	struct cbfs_file *next = cbfs_find_next_entry(image, entry);
+	uint32_t addr = cbfs_get_entry_addr(image, entry),
+		 addr_next = cbfs_get_entry_addr(image, next);
+	uint32_t header_size = cbfs_calculate_file_header_size(name),
+		 min_entry_size = cbfs_calculate_file_header_size("");
+	uint32_t len, target;
+	uint32_t align = ntohl(image->header->align);
+
+	target = content_offset - header_size;
+	if (target % align)
+		target -= target % align;
+	if (target < addr) {
+		ERROR("No space to hold cbfs_file header.");
+		return -1;
+	}
 
-static struct filetypes_t {
-	uint32_t type;
-	const char *name;
-} filetypes[] = {
-	{CBFS_COMPONENT_STAGE, "stage"},
-	{CBFS_COMPONENT_PAYLOAD, "payload"},
-	{CBFS_COMPONENT_OPTIONROM, "optionrom"},
-	{CBFS_COMPONENT_BOOTSPLASH, "bootsplash"},
-	{CBFS_COMPONENT_RAW, "raw"},
-	{CBFS_COMPONENT_VSA, "vsa"},
-	{CBFS_COMPONENT_MBI, "mbi"},
-	{CBFS_COMPONENT_MICROCODE, "microcode"},
-	{CBFS_COMPONENT_CMOS_DEFAULT, "cmos default"},
-	{CBFS_COMPONENT_CMOS_LAYOUT, "cmos layout"},
-	{CBFS_COMPONENT_DELETED, "deleted"},
-	{CBFS_COMPONENT_NULL, "null"}
-};
+	// Process buffer BEFORE content_offset.
+	if (target - addr > min_entry_size) {
+		DEBUG("|min|...|header|content|... <create new entry>\n");
+		len = target - addr - min_entry_size;
+		cbfs_create_empty_entry(image, entry, len, "");
+		if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
+		entry = cbfs_find_next_entry(image, entry);
+		addr = cbfs_get_entry_addr(image, entry);
+	}
 
-void print_supported_filetypes(void)
-{
-	int i, number = ARRAY_SIZE(filetypes);
+	len = size + (content_offset - addr - header_size);
+	cbfs_create_empty_entry(image, entry, len, name);
+	if (len != size) {
+		DEBUG("|..|header|content|... <use offset to create entry>\n");
+		DEBUG("before: offset=0x%x, len=0x%x\n",
+		      ntohl(entry->offset), ntohl(entry->len));
+		// TODO reset expanded name buffer to 0xFF.
+		entry->offset = htonl(ntohl(entry->offset) + (len - size));
+		entry->len = htonl(size);
+		DEBUG("after: offset=0x%x, len=0x%x\n",
+		      ntohl(entry->offset), ntohl(entry->len));
+	}
 
-	for (i=0; i<number; i++) {
-		LOG(" %s%c", filetypes[i].name, (i==(number-1))?'\n':',');
-		if ((i%8) == 7)
-			LOG("\n");
+	// Ready to fill data into entry.
+	assert(ntohl(entry->len) == size);
+	entry->type = htonl(type);
+	DEBUG("content_offset: 0x%x, entry location: %x\n",
+	      content_offset, (int)((char*)CBFS_SUBHEADER(entry) -
+				    image->buffer.data));
+	assert((char*)CBFS_SUBHEADER(entry) - image->buffer.data ==
+	       content_offset);
+	memcpy(CBFS_SUBHEADER(entry), data, size);
+	if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
+
+	// Process buffer AFTER entry.
+	entry = cbfs_find_next_entry(image, entry);
+	addr = cbfs_get_entry_addr(image, entry);
+	assert(addr < addr_next);
+
+	if (addr_next - addr < min_entry_size) {
+		DEBUG("No space after content to keep CBFS structure.\n");
+		return -1;
 	}
-}
 
-const char *strfiletype(uint32_t number)
-{
-	size_t i;
-	for (i = 0; i < (sizeof(filetypes) / sizeof(struct filetypes_t)); i++)
-		if (filetypes[i].type == number)
-			return filetypes[i].name;
-	return "unknown";
+	len = addr_next - addr - min_entry_size;
+	cbfs_create_empty_entry(image, entry, len, "");
+	if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
+	return 0;
 }
 
-uint64_t intfiletype(const char *name)
-{
-	size_t i;
-	for (i = 0; i < (sizeof(filetypes) / sizeof(struct filetypes_t)); i++)
-		if (strcmp(filetypes[i].name, name) == 0)
-			return filetypes[i].type;
-	return -1;
-}
+int cbfs_add_entry(struct cbfs_image *image, struct buffer *buffer,
+		   const char *name, uint32_t type, uint32_t content_offset) {
+	uint32_t entry_type;
+	uint32_t addr, addr_next;
+	struct cbfs_file *entry, *next;
+	uint32_t header_size, need_size, new_size;
+
+	header_size = cbfs_calculate_file_header_size(name);
+
+	need_size = header_size + buffer->size;
+	DEBUG("cbfs_add_entry('%s'@0x%x) => need_size = %u+%zu=%u\n",
+	      name, content_offset, header_size, buffer->size, need_size);
+
+	if (IS_TOP_ALIGNED_ADDRESS(content_offset)) {
+		// legacy cbfstool takes top-aligned address.
+		uint32_t romsize = ntohl(image->header->romsize);
+		INFO("Converting top-aligned address 0x%x to offset: 0x%x\n",
+		     content_offset, content_offset + romsize);
+		content_offset += romsize;
+	}
 
-/* basename(3) may modify buffer, so we want a tiny alternative. */
-static const char *simple_basename(const char *name) {
-	const char *slash = strrchr(name, '/');
-	if (slash)
-		return slash + 1;
-	else
-		return name;
-}
+	// Merge empty entries.
+	DEBUG("(trying to merge empty entries...)\n");
+	cbfs_walk(image, cbfs_merge_empty_entry, NULL);
 
-void print_cbfs_directory(const char *filename)
-{
-	printf("%s: %d kB, bootblocksize %d, romsize %d, offset 0x%x\n"
-	       "alignment: %d bytes, architecture: %s\n\n",
-	       simple_basename((char *)filename), romsize / 1024,
-	       ntohl(master_header->bootblocksize),
-	       romsize, ntohl(master_header->offset), align,
-	       arch_to_string(arch));
-	printf("%-30s %-10s %-12s Size\n", "Name", "Offset", "Type");
-	uint32_t current = phys_start;
-	while (current < phys_end) {
-		if (!cbfs_file_header(current)) {
-			current += align;
+	for (entry = cbfs_find_first_entry(image);
+	     entry && cbfs_is_valid_entry(entry);
+	     entry = cbfs_find_next_entry(image, entry)) {
+
+		entry_type = ntohl(entry->type);
+		if (entry_type != CBFS_COMPONENT_NULL)
 			continue;
-		}
-		struct cbfs_file *thisfile =
-			(struct cbfs_file *)phys_to_virt(current);
-		uint32_t length = ntohl(thisfile->len);
-		char *fname = (char *)(phys_to_virt(current) + sizeof(struct cbfs_file));
-		if (strlen(fname) == 0)
-			fname = "(empty)";
-
-		printf("%-30s 0x%-8x %-12s %d\n", fname,
-		       current - phys_start + ntohl(master_header->offset),
-		       strfiletype(ntohl(thisfile->type)), length);
-
-		/* note the components of the subheader are in host order ... */
-		switch (ntohl(thisfile->type)) {
-		case CBFS_COMPONENT_STAGE:
-		{
-			struct cbfs_stage *stage = CBFS_SUBHEADER(thisfile);
-			INFO("    %s compression, entry: 0x%llx, load: 0x%llx, length: %d/%d\n",
-			       stage->compression == CBFS_COMPRESS_LZMA ? "LZMA" : "no",
-			       (unsigned long long)stage->entry,
-			       (unsigned long long)stage->load,
-			       stage->len,
-			       stage->memlen);
-			break;
-		}
-		case CBFS_COMPONENT_PAYLOAD:
-		{
-			struct cbfs_payload_segment *payload = CBFS_SUBHEADER(thisfile);
-			while(payload) {
-				switch(payload->type) {
-				case PAYLOAD_SEGMENT_CODE:
-				case PAYLOAD_SEGMENT_DATA:
-					INFO("    %s (%s compression, offset: 0x%x, load: 0x%llx, length: %d/%d)\n",
-						payload->type == PAYLOAD_SEGMENT_CODE ? "code " : "data" ,
-						payload->compression == CBFS_COMPRESS_LZMA ? "LZMA" : "no",
-						ntohl(payload->offset),
-						(unsigned long long)ntohll(payload->load_addr),
-						ntohl(payload->len), ntohl(payload->mem_len));
-					break;
-				case PAYLOAD_SEGMENT_ENTRY:
-					INFO("    entry (0x%llx)\n", (unsigned long long)ntohll(payload->load_addr));
-					break;
-				case PAYLOAD_SEGMENT_BSS:
-					INFO("    BSS (address 0x%016llx, length 0x%x)\n", (unsigned long long)ntohll(payload->load_addr), ntohl(payload->len));
-					break;
-				case PAYLOAD_SEGMENT_PARAMS:
-					INFO("    parameters\n");
-					break;
-				default:
-					INFO("    %x (%s compression, offset: 0x%x, load: 0x%llx, length: %d/%d\n",
-						payload->type,
-						payload->compression == CBFS_COMPRESS_LZMA ? "LZMA" : "no",
-						ntohl(payload->offset),
-						(unsigned long long)ntohll(payload->load_addr),
-						ntohl(payload->len),
-						ntohl(payload->mem_len));
-					break;
-				}
 
-				if(payload->type == PAYLOAD_SEGMENT_ENTRY)
-					payload=NULL;
-				else
-					payload++;
-			}
-			break;
-		}
-		default:
-			break;
-		}
-		current =
-		    ALIGN(current + ntohl(thisfile->len) +
-			  ntohl(thisfile->offset), align);
-	}
-}
+		addr = cbfs_get_entry_addr(image, entry);
+		next = cbfs_find_next_entry(image, entry);
+		addr_next = cbfs_get_entry_addr(image, next);
 
-int extract_file_from_cbfs(const char *filename, const char *payloadname, const char *outpath)
-{
-	FILE *outfile = NULL;
-	uint32_t current = phys_start;
-	while (current < phys_end) {
-		if (!cbfs_file_header(current)) {
-			current += align;
+		DEBUG("cbfs_add_entry: space at 0x%x+0x%x(%d) bytes\n",
+		      addr, addr_next - addr, addr_next - addr);
+		if (addr + need_size > addr_next)
 			continue;
+
+		// Can we simply put object here?
+		if (!content_offset || content_offset == addr + header_size) {
+			DEBUG("Filling new entry data (%zd bytes).\n",
+			      buffer->size);
+			cbfs_create_empty_entry(image, entry, buffer->size,
+						name);
+			entry->type = htonl(type);
+			memcpy(CBFS_SUBHEADER(entry), buffer->data, buffer->size);
+			if (verbose)
+				cbfs_print_entry_info(image, entry, stderr);
+
+			// setup new entry
+			DEBUG("Seting new empty entry.\n");
+			entry = cbfs_find_next_entry(image, entry);
+			new_size = (cbfs_get_entry_addr(image, next) -
+				    cbfs_get_entry_addr(image, entry));
+			new_size -= cbfs_calculate_file_header_size("");
+			DEBUG("new size: %d\n", new_size);
+			cbfs_create_empty_entry(image, entry, new_size, "");
+			if (verbose)
+				cbfs_print_entry_info(image, entry, stderr);
+			return 0;
 		}
 
-		// Locate the file start struct
-		struct cbfs_file *thisfile =
-		    (struct cbfs_file *)phys_to_virt(current);
-		// And its length
-		uint32_t length = ntohl(thisfile->len);
-		// Locate the file name
-		char *fname = (char *)(phys_to_virt(current) + sizeof(struct cbfs_file));
-
-		// It's not the file we are looking for..
-		if (strcmp(fname, payloadname) != 0)
-		{
-			current =
-			   ALIGN(current + ntohl(thisfile->len) +
-				  ntohl(thisfile->offset), align);
+		// We need to put content here, and the case is really
+		// complicated...
+		assert(content_offset);
+		if (addr_next < content_offset) {
+			DEBUG("Not for specified offset yet");
 			continue;
+		} else if (addr > content_offset) {
+			DEBUG("Exceed specified content_offset.");
+			break;
+		} else if (addr + header_size > content_offset) {
+			ERROR("Not enough space for header.\n");
+			break;
+		} else if (content_offset + buffer->size > addr_next) {
+			ERROR("Not enough space for content.\n");
+			break;
 		}
 
-		// Else, it's our file.
-		LOG("Found file %.30s at 0x%x, type %.12s, size %d\n", fname,
-		       current - phys_start, strfiletype(ntohl(thisfile->type)),
-		       length);
-
-		// If we are not dumping to stdout, open the out file.
-		outfile = fopen(outpath, "wb");
-		if (!outfile)
-		{
-			ERROR("Could not open the file %s for writing.\n", outpath);
-			return 1;
-		}
+		// TODO there are more few tricky cases that we may
+		// want to fit by altering offset.
+		DEBUG("section 0x%x+0x%x for content_offset 0x%x.\n",
+		      addr, addr_next - addr, content_offset);
 
-		if (ntohl(thisfile->type) != CBFS_COMPONENT_RAW)
-		{
-			WARN("Only 'raw' files are safe to extract.\n");
+		if (cbfs_add_entry_at(image, entry, buffer->size, name, type,
+				      buffer->data, content_offset) == 0) {
+			return 0;
 		}
+		break;
+	}
 
-		fwrite(((char *)thisfile)
-				+ ntohl(thisfile->offset), length, 1, outfile);
+	ERROR("Could not add [%s, %zd bytes (%zd KB)@0x%x]; too big?\n",
+	      buffer->name, buffer->size, buffer->size / 1024, content_offset);
+	return 0;
+}
 
-		fclose(outfile);
-		LOG("Successfully dumped the file.\n");
+int cbfs_remove_entry(struct cbfs_image *image, const char *name) {
+	struct cbfs_file *entry, *next;
+	size_t len;
+	entry = cbfs_get_entry(image, name);
+	if (!entry) {
+		ERROR("CBFS file %s not found.\n", name);
+		return -1;
+	}
+	next = cbfs_find_next_entry(image, entry);
+	assert(next);
+	DEBUG("cbfs_remove_entry: Removed %s @ 0x%x\n",
+	      CBFS_NAME(entry), cbfs_get_entry_addr(image, entry));
+	entry->type = htonl(CBFS_COMPONENT_DELETED);
+	len = (cbfs_get_entry_addr(image, next) -
+	       cbfs_get_entry_addr(image, entry));
+	entry->offset = htonl(cbfs_calculate_file_header_size(""));
+	entry->len = htonl(len - ntohl(entry->offset));
+	memset(CBFS_NAME(entry), 0, ntohl(entry->offset) - sizeof(*entry));
+	memset(CBFS_SUBHEADER(entry), CBFS_CONTENT_DEFAULT_VALUE,
+	       ntohl(entry->len));
+	return 0;
+}
 
-		// We'll only dump one file.
-		return 0;
+struct cbfs_file *cbfs_get_entry(struct cbfs_image *image, const char *name) {
+	struct cbfs_file *entry;
+	for (entry = cbfs_find_first_entry(image);
+	     entry && cbfs_is_valid_entry(entry);
+	     entry = cbfs_find_next_entry(image, entry)) {
+		if (strcasecmp(CBFS_NAME(entry), name) == 0) {
+			DEBUG("cbfs_get_entry: found %s\n", name);
+			return entry;
+		}
 	}
-	ERROR("File %s not found.\n", payloadname);
-	return 1;
+	return NULL;
 }
 
+int cbfs_export_entry(struct cbfs_image *image, const char *entry_name,
+		      const char *filename) {
+	struct cbfs_file *entry = cbfs_get_entry(image, entry_name);
+	struct buffer buffer;
+	if (!entry) {
+		ERROR("File not found: %s\n", entry_name);
+		return -1;
+	}
+	LOG("Found file %.30s at 0x%x, type %.12s, size %d\n",
+	    entry_name, cbfs_get_entry_addr(image, entry),
+	    get_cbfs_entry_type_name(ntohl(entry->type)), ntohl(entry->len));
 
-int add_file_to_cbfs(void *content, uint32_t contentsize, uint32_t location)
-{
-	uint32_t current = phys_start;
-	while (current < phys_end) {
-		if (!cbfs_file_header(current)) {
-			current += align;
-			continue;
-		}
-		struct cbfs_file *thisfile =
-		    (struct cbfs_file *)phys_to_virt(current);
-		uint32_t length = ntohl(thisfile->len);
-
-		DEBUG("at %x, %x bytes\n", current, length);
-		/* Is this a free chunk? */
-		if ((thisfile->type == CBFS_COMPONENT_DELETED)
-		    || (thisfile->type == CBFS_COMPONENT_NULL)) {
-			DEBUG("null||deleted at %x, %x bytes\n", current,
-				length);
-			/* if this is the right size, and if specified, the right location, use it */
-			if ((contentsize <= length)
-			    && ((location == 0) || (current == location))) {
-				if (contentsize < length) {
-					DEBUG("this chunk is %x bytes, we need %x. create a new chunk at %x with %x bytes\n",
-					     length, contentsize,
-					     ALIGN(current + contentsize,
-						   align),
-					     length - contentsize);
-					uint32_t start =
-					    ALIGN(current + contentsize, align);
-					uint32_t size =
-					    current + ntohl(thisfile->offset)
-					    + length - start - 16 -
-					    sizeof(struct cbfs_file);
-					cbfs_create_empty_file(start, size);
-				}
-				DEBUG("copying data\n");
-				memcpy(phys_to_virt(current), content,
-				       contentsize);
-				return 0;
-			}
-			if (location != 0) {
-				/* CBFS has the constraint that the chain always moves up in memory. so once
-				   we're past the place we seek, we don't need to look any further */
-				if (current > location) {
-					ERROR("The requested space is not available\n");
-					return 1;
-				}
-
-				/* Is the requested location inside the current chunk? */
-				if ((current < location)
-				    && ((location + contentsize) <=
-					(current + length))) {
-					/* Split it up. In the next iteration the code will be at the right place. */
-					DEBUG("split up. new length: %x\n",
-						location - current -
-						ntohl(thisfile->offset));
-					thisfile->len =
-					    htonl(location - current -
-						  ntohl(thisfile->offset));
-					cbfs_create_empty_file(location,
-								   length -
-								   (location -
-								    current));
-				}
-			}
-		}
-		current =
-		    ALIGN(current + ntohl(thisfile->len) +
-			  ntohl(thisfile->offset), align);
+	if (ntohl(entry->type) != CBFS_COMPONENT_RAW) {
+		WARN("Only 'raw' files are safe to extract.\n");
+	}
+
+	buffer.data = CBFS_SUBHEADER(entry);
+	buffer.size = ntohl(entry->len);
+	buffer.name = "(cbfs_export_entry)";
+	if (buffer_write_file(&buffer, filename) != 0) {
+		ERROR("Failed to write %s into %s.\n",
+		      entry_name, filename);
+		return -1;
 	}
-	ERROR("Could not add the file to CBFS, it's probably too big.\n");
-	ERROR("File size: %d bytes (%d KB).\n", contentsize, contentsize/1024);
-	return 1;
+	INFO("Successfully dumped the file to: %s\n", filename);
+	return 0;
 }
 
+/* basename(3) may modify buffer, so we want a tiny alternative. */
+static const char *simple_basename(const char *name) {
+	const char *slash = strrchr(name, '/');
+	if (slash)
+		return slash + 1;
+	else
+		return name;
+}
 
-static struct cbfs_file *merge_adjacent_files(struct cbfs_file *first,
-					      struct cbfs_file *second)
-{
-	uint32_t new_length =
-	    ntohl(first->len) + ntohl(second->len) + ntohl(second->offset);
-	first->len = htonl(new_length);
-	first->checksum = 0; // FIXME?
-	return first;
+int cbfs_print_header_info(struct cbfs_image *image) {
+	assert(image && image->header);
+	printf("%s: %zd kB, bootblocksize %d, romsize %d, offset 0x%x\n"
+	       "alignment: %d bytes\n\n",
+	       simple_basename(image->buffer.name),
+	       image->buffer.size / 1024,
+	       ntohl(image->header->bootblocksize),
+	       ntohl(image->header->romsize),
+	       ntohl(image->header->offset),
+	       ntohl(image->header->align));
+	return 0;
+}
+
+static int cbfs_print_stage_info(struct cbfs_stage *stage, FILE* fp) {
+	fprintf(fp,
+		"    %s compression, entry: 0x%" PRIx64 ", load: 0x%" PRIx64 ", "
+		"length: %d/%d\n",
+		lookup_name_by_type(types_cbfs_compression,
+				    stage->compression, "(unknown)"),
+		stage->entry,
+		stage->load,
+		stage->len,
+		stage->memlen);
+	return 0;
 }
 
-static struct cbfs_file *next_file(struct cbfs_file *prev)
+static int cbfs_print_payload_segment_info(struct cbfs_payload_segment *payload,
+					   FILE *fp)
 {
-	uint32_t pos = (prev == NULL) ? phys_start :
-	    ALIGN(virt_to_phys(prev) + ntohl(prev->len) + ntohl(prev->offset),
-		  align);
+	switch(payload->type) {
+		case PAYLOAD_SEGMENT_CODE:
+		case PAYLOAD_SEGMENT_DATA:
+			fprintf(fp, "    %s (%s compression, offset: 0x%x, "
+				"load: 0x%" PRIx64 ", length: %d/%d)\n",
+				(payload->type == PAYLOAD_SEGMENT_CODE ?
+				 "code " : "data"),
+				lookup_name_by_type(types_cbfs_compression,
+						    ntohl(payload->compression),
+						    "(unknown)"),
+				ntohl(payload->offset),
+				ntohll(payload->load_addr),
+				ntohl(payload->len), ntohl(payload->mem_len));
+			break;
+
+		case PAYLOAD_SEGMENT_ENTRY:
+			fprintf(fp, "    entry (0x%" PRIx64 ")\n",
+				ntohll(payload->load_addr));
+			break;
+
+		case PAYLOAD_SEGMENT_BSS:
+			fprintf(fp, "    BSS (address 0x%016" PRIx64 ", "
+				"length 0x%x)\n",
+				ntohll(payload->load_addr),
+				ntohl(payload->len));
+			break;
+
+		case PAYLOAD_SEGMENT_PARAMS:
+			fprintf(fp, "    parameters\n");
+			break;
 
-	for (; pos < phys_end; pos += align) {
-		if (cbfs_file_header(pos))
-			return (struct cbfs_file *)phys_to_virt(pos);
+		default:
+			fprintf(fp, "   0x%x (%s compression, offset: 0x%x, "
+				"load: 0x%" PRIx64 ", length: %d/%d\n",
+				payload->type,
+				lookup_name_by_type(types_cbfs_compression,
+						    payload->compression,
+						    "(unknown)"),
+				ntohl(payload->offset),
+				ntohll(payload->load_addr),
+				ntohl(payload->len),
+				ntohl(payload->mem_len));
+			break;
 	}
-	return NULL;
+	return 0;
 }
 
+int cbfs_print_entry_info(struct cbfs_image *image, struct cbfs_file *entry,
+			  void *arg) {
+	const char *name = CBFS_NAME(entry);
+	struct cbfs_payload_segment *payload;
+	FILE *fp = (FILE *)arg;
 
-int remove_file_from_cbfs(const char *filename)
-{
-	struct cbfs_file *prev = NULL;
-	struct cbfs_file *cur = next_file(prev);
-	struct cbfs_file *next = next_file(cur);
-	for (; cur; prev = cur, cur = next, next = next_file(next)) {
-
-		/* Check if this is the file to remove. */
-		char *name = (char *)cur + sizeof(*cur);
-		if (strcmp(name, filename))
-			continue;
+	if (!cbfs_is_valid_entry(entry)) {
+		ERROR("cbfs_print_entry_info: Invalid entry at 0x%x\n",
+		      cbfs_get_entry_addr(image, entry));
+		return -1;
+	}
+	if (!fp)
+		fp = stdout;
 
-		/* Mark the file as free space and erase its name. */
-		cur->type = CBFS_COMPONENT_NULL;
-		name[0] = '\0';
+	fprintf(fp, "%-30s 0x%-8x %-12s %d\n",
+		*name ? name : "(empty)",
+		cbfs_get_entry_addr(image, entry),
+		get_cbfs_entry_type_name(ntohl(entry->type)),
+		ntohl(entry->len));
 
-		/* Merge it with the previous file if possible. */
-		if (prev && prev->type == CBFS_COMPONENT_NULL)
-			cur = merge_adjacent_files(prev, cur);
+	if (!verbose)
+		return 0;
 
-		/* Merge it with the next file if possible. */
-		if (next && next->type == CBFS_COMPONENT_NULL)
-			merge_adjacent_files(cur, next);
+	DEBUG(" cbfs_file=0x%x, offset=0x%x, content_address=0x%x+0x%x\n",
+	      cbfs_get_entry_addr(image, entry), ntohl(entry->offset),
+	      cbfs_get_entry_addr(image, entry) + ntohl(entry->offset),
+	      ntohl(entry->len));
 
-		return 0;
+	/* note the components of the subheader may be in host order ... */
+	switch (ntohl(entry->type)) {
+		case CBFS_COMPONENT_STAGE:
+			cbfs_print_stage_info((struct cbfs_stage *)
+					      CBFS_SUBHEADER(entry), fp);
+			break;
+
+		case CBFS_COMPONENT_PAYLOAD:
+			payload  = (struct cbfs_payload_segment *)
+					CBFS_SUBHEADER(entry);
+			while (payload) {
+				cbfs_print_payload_segment_info(payload, fp);
+				if (payload->type == PAYLOAD_SEGMENT_ENTRY)
+					break;
+				else
+					payload ++;
+			}
+			break;
+		default:
+			break;
 	}
-	ERROR("CBFS file %s not found.\n", filename);
-	return 1;
+	return 0;
 }
 
+int cbfs_print_directory(struct cbfs_image *image) {
+	cbfs_print_header_info(image);
+	printf("%-30s %-10s %-12s Size\n", "Name", "Offset", "Type");
+	cbfs_walk(image, cbfs_print_entry_info, NULL);
+	return 0;
+}
 
-/* returns new data block with cbfs_file header, suitable to dump into the ROM. location returns
-   the new location that points to the cbfs_file header */
-void *create_cbfs_file(const char *filename, void *data, uint32_t * datasize,
-		       uint32_t type, uint32_t * location)
-{
-	uint32_t filename_len = ALIGN(strlen(filename) + 1, 16);
-	uint32_t headersize = sizeof(struct cbfs_file) + filename_len;
-	if ((location != 0) && (*location != 0)) {
-		uint32_t offset = *location % align;
-		/* If offset >= (headersize % align), we can stuff the header into the offset.
-		   Otherwise the header has to be aligned itself, and put before the offset data */
-		if (offset >= (headersize % align)) {
-			offset -= (headersize % align);
-		} else {
-			offset += align - (headersize % align);
-		}
-		headersize += offset;
-		*location -= headersize;
-	}
-	void *newdata = malloc(*datasize + headersize);
-	if (!newdata) {
-		ERROR("Could not get %d bytes for CBFS file.\n", *datasize +
-		       headersize);
-		exit(1);
-	}
-	memset(newdata, 0xff, *datasize + headersize);
-	struct cbfs_file *nextfile = (struct cbfs_file *)newdata;
-	strncpy((char *)(nextfile->magic), "LARCHIVE", 8);
-	nextfile->len = htonl(*datasize);
-	nextfile->type = htonl(type);
-	nextfile->checksum = 0;	// FIXME?
-	nextfile->offset = htonl(headersize);
-	strcpy(newdata + sizeof(struct cbfs_file), filename);
-	memcpy(newdata + headersize, data, *datasize);
-	*datasize += headersize;
-	return newdata;
-}
-
-int create_cbfs_image(const char *romfile, uint32_t _romsize,
-		const char *bootblock, uint32_t align, uint32_t offs)
-{
-	uint32_t bootblocksize = 0;
-	struct cbfs_header *master_header;
-	unsigned char *romarea, *bootblk;
+int cbfs_merge_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
+			   void *arg) {
+	struct cbfs_file *next;
+	uint32_t type, addr, last_addr;
 
-	romsize = _romsize;
-	romarea = malloc(romsize);
-	if (!romarea) {
-		ERROR("Could not get %d bytes of memory"
-			" for CBFS image.\n", romsize);
-		exit(1);
+	type = ntohl(entry->type);
+	if (type == CBFS_COMPONENT_DELETED) {
+		// Ready to be recycled.
+		type = CBFS_COMPONENT_NULL;
+		entry->type = htonl(type);
 	}
-	memset(romarea, 0xff, romsize);
+	if (type != CBFS_COMPONENT_NULL)
+		return 0;
 
-	if (align == 0)
-		align = 64;
-
-	bootblk = loadfile(bootblock, &bootblocksize,
-				romarea + romsize, SEEK_END);
-	if (!bootblk) {
-		ERROR("Could not load bootblock %s.\n",
-			bootblock);
-		free(romarea);
-		return 1;
-	}
+	next = cbfs_find_next_entry(image, entry);
 
-	// TODO(hungte) Replace magic numbers by named constants.
-	switch (arch) {
-	case CBFS_ARCHITECTURE_ARMV7:
-		/* Set up physical/virtual mapping */
-		offset = romarea;
-
-		/*
-		 * The initial jump instruction and bootblock will be placed
-		 * before and after the master header, respectively. The
-		 * bootblock image must contain a blank, aligned region large
-		 * enough for the master header to fit.
-		 *
-		 * An anchor string must be left such that when cbfstool is run
-		 * we can find it and insert the master header at the next
-		 * aligned boundary.
-		 */
-		loadfile(bootblock, &bootblocksize, romarea + offs, SEEK_SET);
-
-		unsigned char *p = romarea + offs;
-		while (1) {
-			/* FIXME: assumes little endian... */
-			if (*(uint32_t *)p == 0xdeadbeef)
-				break;
-			if (p >= (romarea + _romsize)) {
-				ERROR("Could not determine CBFS "
-				      "header location.\n");
-				return 1;
-			}
-			p += (sizeof(unsigned int));
+	while (next && cbfs_is_valid_entry(next)) {
+		type = ntohl(next->type);
+		if (type == CBFS_COMPONENT_DELETED) {
+			type = CBFS_COMPONENT_NULL;
+			next->type = htonl(type);
 		}
-		unsigned int u = ALIGN((unsigned int)(p - romarea), align);
-		master_header = (struct cbfs_header *)(romarea + u);
-
-		master_header->magic = ntohl(CBFS_HEADER_MAGIC);
-		master_header->version = ntohl(CBFS_HEADER_VERSION);
-		master_header->romsize = htonl(romsize);
-		master_header->bootblocksize = htonl(bootblocksize);
-		master_header->align = htonl(align);
-		master_header->offset = htonl(
-				ALIGN((0x40 + bootblocksize), align));
-		master_header->architecture = htonl(CBFS_ARCHITECTURE_ARMV7);
-
-		((uint32_t *) phys_to_virt(0x4 + offs))[0] =
-				virt_to_phys(master_header);
-
-		recalculate_rom_geometry(romarea);
-
-		cbfs_create_empty_file(
-				offs + ALIGN((0x40 + bootblocksize), align),
-				romsize - offs - sizeof(struct cbfs_file) -
-				ALIGN((bootblocksize + 0x40), align));
-		break;
-
-	case CBFS_ARCHITECTURE_X86:
-		// Set up physical/virtual mapping
-		offset = romarea + romsize - 0x100000000ULL;
+		if (type != CBFS_COMPONENT_NULL)
+			return 0;
+
+		addr = cbfs_get_entry_addr(image, entry);
+		last_addr = cbfs_get_entry_addr(
+				image, cbfs_find_next_entry(image, next));
+
+		// Now, we find two deleted/empty entries; try to merge now.
+		DEBUG("join_empty_entry: combine 0x%x+0x%x and 0x%x+0x%x.\n",
+		      cbfs_get_entry_addr(image, entry), ntohl(entry->len),
+		      cbfs_get_entry_addr(image, next), ntohl(next->len));
+		cbfs_create_empty_entry(image, entry,
+					(last_addr - addr -
+					 cbfs_calculate_file_header_size("")),
+					"");
+		DEBUG("new empty entry: length=0x%x\n", ntohl(entry->len));
+		next = cbfs_find_next_entry(image, entry);
+	}
+	return 0;
+}
 
-		loadfile(bootblock, &bootblocksize, romarea + romsize,
-			 SEEK_END);
-		master_header = (struct cbfs_header *)(romarea + romsize -
-				  bootblocksize - sizeof(struct cbfs_header));
+int cbfs_walk(struct cbfs_image *image, cbfs_entry_callback callback,
+	      void *arg) {
+	int count = 0;
+	struct cbfs_file *entry;
+	for (entry = cbfs_find_first_entry(image);
+	     entry && cbfs_is_valid_entry(entry);
+	     entry = cbfs_find_next_entry(image, entry)) {
+		count ++;
+		if (callback(image, entry, arg) != 0)
+			break;
+	}
+	return count;
+}
 
-		master_header->magic = ntohl(CBFS_HEADER_MAGIC);
-		master_header->version = ntohl(CBFS_HEADER_VERSION);
-		master_header->romsize = htonl(romsize);
-		master_header->bootblocksize = htonl(bootblocksize);
-		master_header->align = htonl(align);
-		master_header->offset = htonl(offs);
-		master_header->architecture = htonl(CBFS_ARCHITECTURE_X86);
+struct cbfs_header *cbfs_find_header(char *data, size_t size) {
+	size_t offset;
+	int found = 0;
+	uint32_t x86sig;
+	struct cbfs_header *header, *result = NULL;
+
+	// Try x86 style (check signature in bottom) header first.
+	x86sig = *(uint32_t *)(data + size - sizeof(uint32_t));
+	offset = (x86sig + (uint32_t)size);
+	DEBUG("x86sig: 0x%x, offset: 0x%zx\n", x86sig, offset);
+	if (offset >= size - sizeof(*header) ||
+	    ntohl(((struct cbfs_header *)(data + offset))->magic) !=
+	    CBFS_HEADER_MAGIC)
+		offset = 0;
+
+	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?
+			continue;
+		}
+		found++;
+		result = header;
+	}
+	if (found > 1) {
+		ERROR("multiple (%d) CBFS headers found!\n",
+		       found);
+		result = NULL;
+	}
+	return result;
+}
 
-		((uint32_t *) phys_to_virt(CBFS_HEADPTR_ADDR_X86))[0] =
-		    virt_to_phys(master_header);
+struct cbfs_file *cbfs_find_first_entry(struct cbfs_image *image) {
+	assert(image && image->header);
+	return (struct cbfs_file *)(image->buffer.data +
+				   ntohl(image->header->offset));
+}
 
-		recalculate_rom_geometry(romarea);
+struct cbfs_file *cbfs_find_next_entry(struct cbfs_image *image,
+				       struct cbfs_file *entry) {
+	uint32_t addr = cbfs_get_entry_addr(image, entry);
+	int align = ntohl(image->header->align);
+	assert(entry && cbfs_is_valid_entry(entry));
+	addr += ntohl(entry->offset) + ntohl(entry->len);
+	addr = align_up(addr, align);
+	return (struct cbfs_file *)(image->buffer.data + addr);
+}
 
-		cbfs_create_empty_file((0 - romsize + offs) & 0xffffffff,
-				       romsize - offs - bootblocksize -
-				       sizeof(struct cbfs_header) -
-				       sizeof(struct cbfs_file) - 16);
-		break;
+uint32_t cbfs_get_entry_addr(struct cbfs_image *image, struct cbfs_file *entry) {
+	assert(image && image->buffer.data && entry);
+	return (int32_t)((char *)entry - image->buffer.data);
+}
 
-	default:
-		// Should not happen.
-		ERROR("You found a bug in cbfstool.\n");
-		exit(1);
-	}
+int cbfs_is_valid_entry(struct cbfs_file *entry) {
+	return (entry &&memcmp(entry->magic, CBFS_FILE_MAGIC,
+			       sizeof(entry->magic)) == 0);
+}
 
-	writerom(romfile, romarea, romsize);
-	free(romarea);
+int cbfs_init_entry(struct cbfs_file *entry,
+		    struct buffer *buffer) {
+	memset(entry, 0, sizeof(*entry));
+	memcpy(entry->magic, CBFS_FILE_MAGIC, sizeof(entry->magic));
+	entry->len = htonl(buffer->size);
+	entry->offset = htonl(sizeof(*entry) + strlen(buffer->name) + 1);
 	return 0;
 }
 
-static int in_segment(int addr, int size, int gran)
-{
-	return ((addr & ~(gran - 1)) == ((addr + size) & ~(gran - 1)));
+int cbfs_create_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
+		      size_t len, const char *name) {
+	memset(entry, CBFS_CONTENT_DEFAULT_VALUE, sizeof(*entry));
+	memcpy(entry->magic, CBFS_FILE_MAGIC, sizeof(entry->magic));
+	entry->type = htonl(CBFS_COMPONENT_NULL);
+	entry->len = htonl(len);
+	entry->checksum = 0;  // TODO Build a checksum algorithm.
+	entry->offset = htonl(cbfs_calculate_file_header_size(name));
+	memset(CBFS_NAME(entry), 0, ntohl(entry->offset) - sizeof(*entry));
+	strcpy(CBFS_NAME(entry), name);
+	memset(CBFS_SUBHEADER(entry), CBFS_CONTENT_DEFAULT_VALUE, len);
+	return 0;
 }
 
-uint32_t cbfs_find_stage_location(const char *romfile, uint32_t filesize,
-				  const char *filename, uint32_t alignment)
-{
-	void *rom;
-	size_t filename_size, headersize, totalsize;
-	int ret = 0;
-	uint32_t current;
-
-	rom = loadrom(romfile);
-	if (rom == NULL) {
-		ERROR("Could not load ROM image '%s'.\n", romfile);
-		return 0;
-	}
-
-	filename_size = strlen(filename);
-	headersize = sizeof(struct cbfs_file) + ALIGN(filename_size + 1, 16) +
-			sizeof(struct cbfs_stage);
-	totalsize = headersize + filesize;
+/* Finds a place to hold whole stage data in same memory page.
+ */
+static int is_in_same_page(uint32_t start, uint32_t size, uint32_t page) {
+	if (!page)
+		return 1;
+	return (start / page) == (start + size - 1) / page;
+}
 
-	current = phys_start;
-	while (current < phys_end) {
-		uint32_t top;
-		struct cbfs_file *thisfile;
+int32_t cbfs_locate_stage(struct cbfs_image *image, const char *name,
+			  uint32_t size, uint32_t page_size) {
+	struct cbfs_file *entry;
+	size_t need_len;
+	uint32_t addr, addr_next, addr2, addr3, header_len;
+	assert(size < page_size);
+
+	if (page_size % ntohl(image->header->align))
+		WARN("locate_stage page does not align with CBFS image.\n");
+
+	header_len = (cbfs_calculate_file_header_size(name) +
+		      sizeof(struct cbfs_stage));
+	need_len = header_len + size;
+
+	// Merge empty entries to build get max available pages.
+	cbfs_walk(image, cbfs_merge_empty_entry, NULL);
+
+	/* Three cases of content location on memory page:
+	 * case 1.
+	 *          |  PAGE 1  |   PAGE 2  |
+	 *          |     <header><content>| Fit. Return start of content.
+	 *
+	 * case 2.
+	 *          |  PAGE 1  |   PAGE 2  |
+	 *          | <header><content>    | Fits when we shift content to align
+	 *  shift-> |  <header>|<content>  | at starting of PAGE 2.
+	 *
+	 * case 3. (large content filling whole page)
+	 *  |  PAGE 1  |   PAGE 2  | PAGE 3|
+	 *  | <header><  content > |       | Can't fit. If we shift content to
+	 *  |       {   free space .       } PAGE 2, header can't fit in free
+	 *  |  shift->     <header><content> space, so we must use PAGE 3.
+	 *
+	 * The returned address will be used to re-link stage file, and then
+	 * assigned to add-stage command (-b), which will be then re-calculated
+	 * by ELF loader and positioned by cbfs_add_entry.
+	 */
+	for (entry = cbfs_find_first_entry(image);
+	     entry && cbfs_is_valid_entry(entry);
+	     entry = cbfs_find_next_entry(image, entry)) {
+
+		uint32_t type = ntohl(entry->type);
+		if (type != CBFS_COMPONENT_NULL)
+			continue;
 
-		if (!cbfs_file_header(current)) {
-			current += align;
+		addr = cbfs_get_entry_addr(image, entry);
+		addr_next = cbfs_get_entry_addr(image, cbfs_find_next_entry(
+				image, entry));
+		if (addr_next - addr < need_len)
 			continue;
+		if (is_in_same_page(addr + header_len, size, page_size)) {
+			DEBUG("cbfs_locate_stage: FIT (PAGE1).");
+			return addr + header_len;
 		}
 
-		thisfile = (struct cbfs_file *)phys_to_virt(current);
-
-		top = current + ntohl(thisfile->len) + ntohl(thisfile->offset);
+		addr2 = align_up(addr, page_size);
+		if (addr2 < addr_next && addr_next - addr2 >= size &&
+		    addr2 - addr >= header_len) {
+			DEBUG("cbfs_locate_stage: OVERLAP (PAGE2).");
+			return addr2;
+		}
 
-		if (((ntohl(thisfile->type) == 0x0)
-		     || (ntohl(thisfile->type) == 0xffffffff))
-		    && (ntohl(thisfile->len) + ntohl(thisfile->offset) >=
-			totalsize)) {
-			if (in_segment
-			    (current + headersize, filesize, alignment)) {
-				ret = current + headersize;
-				break;
-			}
-			if ((ALIGN(current, alignment) + filesize < top)
-			    && (ALIGN(current, alignment) - headersize >
-				current)
-			    && in_segment(ALIGN(current, alignment), filesize,
-					  alignment)) {
-				ret = ALIGN(current, alignment);
-				break;
-			}
-			if ((ALIGN(current, alignment) + alignment + filesize <
-			     top)
-			    && (ALIGN(current, alignment) + alignment -
-				headersize > current)
-			    && in_segment(ALIGN(current, alignment) + alignment,
-					  filesize, alignment)) {
-				ret = ALIGN(current, alignment) + alignment;
-				break;
-			}
+		addr3 = addr2 + page_size;
+		if (addr3 < addr_next && addr_next - addr3 >= size &&
+		    addr3 - addr >= header_len) {
+			DEBUG("cbfs_locate_stage: OVERLAP+ (PAGE3).");
+			return addr3;
 		}
-		current =
-		    ALIGN(current + ntohl(thisfile->len) +
-			  ntohl(thisfile->offset), align);
 	}
-
-	free(rom);
-	return ret;
+	return -1;
 }
diff --git a/util/cbfstool/common.h b/util/cbfstool/common.h
index a196d45..2031e56 100644
--- a/util/cbfstool/common.h
+++ b/util/cbfstool/common.h
@@ -2,6 +2,7 @@
  * Copyright (C) 2009 coresystems GmbH
  *                 written by Patrick Georgi <patrick.georgi at coresystems.de>
  * Copyright (C) 2012 Google, Inc.
+ * Copyright (C) 2013 The ChromiumOS Authors.  All rights reserved.
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -30,75 +31,171 @@ extern int verbose;
 #define LOG(x...) { fprintf(stderr, x); }
 #define INFO(x...) { if (verbose > 0) fprintf(stderr, "INFO: " x); }
 #define DEBUG(x...) { if (verbose > 1) fprintf(stderr, "DEBUG: " x); }
-
 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+#define IS_TOP_ALIGNED_ADDRESS(x)	((uint32_t)(x) > 0x80000000)
 
 /* Endianess */
 #include <arpa/inet.h>	/* for ntohl, htonl */
 #include "swab.h"
-extern int is_big_endian(void);
+int is_big_endian(void);
 #define ntohll(x)	(is_big_endian() ? (x) : swab64(x))
 #define htonll(x)	(is_big_endian() ? (x) : swab64(x))
 
-extern void *offset;
-extern uint32_t romsize;
-extern int host_bigendian;
-extern uint32_t arch;
+/* Buffer and file I/O */
+struct buffer {
+	char *name;
+	char *data;
+	size_t size;
+};
 
-const char *arch_to_string(uint32_t a);
-uint32_t string_to_arch(const char *arch_string);
+/* Creates an empty memory buffer with given size.
+ * Returns 0 on success, otherwise non-zero. */
+int buffer_create(struct buffer *buffer, size_t size, const char *name);
 
-static inline void *phys_to_virt(uint32_t addr)
-{
-	return offset + addr;
-}
+/* Loads a file into memory buffer. Returns 0 on success, otherwise non-zero. */
+int buffer_from_file(struct buffer *buffer, const char *filename);
 
-static inline uint32_t virt_to_phys(void *addr)
-{
-	return (unsigned long)(addr - offset) & 0xffffffff;
-}
+/* Writes memory buffer content into file.
+ * Returns 0 on success, otherwise non-zero. */
+int buffer_write_file(struct buffer *buffer, const char *filename);
 
-#define ALIGN(val, by) (((val) + (by)-1)&~((by)-1))
+/* Destroys a memory buffer. Returns 0 on success, otherwise non-zero. */
+int buffer_delete(struct buffer *buffer);
 
-size_t getfilesize(const char *filename);
-void *loadfile(const char *filename, uint32_t * romsize_p, void *content,
-	       int place);
-void *loadrom(const char *filename);
-int writerom(const char *filename, void *start, uint32_t size);
 
-int iself(unsigned char *input);
+/* Type and format */
 
-typedef void (*comp_func_ptr) (char *, int, char *, int *);
-typedef enum { CBFS_COMPRESS_NONE = 0, CBFS_COMPRESS_LZMA = 1 } comp_algo;
+/* Returns 1 if input points to an ELF object, otherwise 0. */
+int is_elf_object(const void *input);
 
-comp_func_ptr compression_function(comp_algo algo);
+/* Returns the value from CBFS entry type name, or default_value if
+ * the name is not found. */
+uint32_t get_cbfs_entry_type(const char *name, uint32_t default_value);
+/* Returns the compression name, or default_value if not found. */
+uint32_t get_cbfs_compression(const char *name, uint32_t default_value);
 
-uint64_t intfiletype(const char *name);
+/* Prints all known CBFS entry types. */
+void print_all_cbfs_entry_types();
 
-void *create_cbfs_file(const char *filename, void *data, uint32_t * datasize,
-		       uint32_t type, uint32_t * location);
 
-int create_cbfs_image(const char *romfile, uint32_t romsize,
-		      const char *bootblock, uint32_t align, uint32_t offs);
+/* CBFS image processing */
 
-int add_file_to_cbfs(void *content, uint32_t contentsize, uint32_t location);
-int remove_file_from_cbfs(const char *filename);
-void print_cbfs_directory(const char *filename);
-int extract_file_from_cbfs(const char *filename, const char *payloadname, const char *outpath);
-int remove_file_from_cbfs(const char *filename);
+struct cbfs_image {
+	struct buffer buffer;
+	struct cbfs_header *header;
+};
 
-uint32_t cbfs_find_stage_location(const char *romfile, uint32_t filesize,
-				  const char *filename, uint32_t align);
+/* Creates an empty CBFS image by given size, and description to its content
+ * (bootblock, align, header location, starting offset of CBFS entries.
+ * The output image will contain a valid cbfs_header, with one cbfs_file
+ * entry with type CBFS_COMPONENT_NULL, with max available size.
+ * Returns 0 on success, otherwise none-zero. */
+int cbfs_image_create(struct cbfs_image *image,
+		      size_t size,
+		      uint32_t align,
+		      struct buffer *bootblock,
+		      int32_t bootblock_offset,
+		      int32_t header_offset,
+		      int32_t entries_offset);
 
-void print_supported_filetypes(void);
 
-/* cbfs-mkstage.c */
-int parse_elf_to_stage(unsigned char *input, unsigned char **output,
-		       comp_algo algo, uint32_t * location);
+/* 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);
+
+/* 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);
+
+/* Releases the CBFS image. Returns 0 on success, otherwise non-zero. */
+int cbfs_image_delete(struct cbfs_image *image);
+
+/* Adds an entry to CBFS image by given name and type. If content_offset is
+ * non-zero, try to align "content" (CBFS_SUBHEADER(p)) at content_offset.
+ * Returns 0 on success, otherwise non-zero. */
+int cbfs_add_entry(struct cbfs_image *image, struct buffer *buffer,
+		   const char *name, uint32_t type, uint32_t content_offset);
+
+/* Removes an entry from CBFS image. Returns 0 on success, otherwise non-zero. */
+int cbfs_remove_entry(struct cbfs_image *image, const char *name);
+
+/* Returns a pointer to entry by name, or NULL if name is not found. */
+struct cbfs_file *cbfs_get_entry(struct cbfs_image *image, const char *name);
+
+/* Exports an entry to external file.
+ * Returns 0 on success, otherwise (ex, not found) non-zero. */
+int cbfs_export_entry(struct cbfs_image *image, const char *entry_name,
+		      const char *filename);
+
+/* Initializes a new empty (type = NULL) entry with size and name in CBFS image.
+ * Returns 0 on success, otherwise (ex, not found) non-zero. */
+int cbfs_create_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
+			    size_t len, const char *name);
+
+/* Finds a location to put whole cbfs_stage content in same memory page.
+ * Returns a valid offset, or -1 on failure. */
+int32_t cbfs_locate_stage(struct cbfs_image *image, const char *name,
+			  uint32_t size, uint32_t page_size);
+
+/* Callback function used by cbfs_walk.
+ * Returns 0 on success, or non-zero to stop further iteration. */
+typedef int (*cbfs_entry_callback)(struct cbfs_image *image,
+				   struct cbfs_file *file,
+				   void *arg);
+
+/* Iterates through all entries in CBFS image, and invoke with callback.
+ * Stops if callback returns non-zero values.
+ * Returns number of entries invoked. */
+int cbfs_walk(struct cbfs_image *image, cbfs_entry_callback callback, void *arg);
+
+/* Primitive CBFS utilities */
+
+/* Returns a pointer to the only valid CBFS header in give buffer, otherwise
+ * 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);
+
+/* Returns the first cbfs_file entry in CBFS image by CBFS header (no matter if
+ * the entry has valid content or not), otherwise NULL. */
+struct cbfs_file *cbfs_find_first_entry(struct cbfs_image *image);
+
+/* Returns next cbfs_file entry (no matter if its content is valid or not), or
+ * NULL on failure. */
+struct cbfs_file *cbfs_find_next_entry(struct cbfs_image *image,
+				       struct cbfs_file *entry);
+
+/* Returns ROM address (offset) of entry.
+ * This is different from entry->offset (pointer to content). */
+uint32_t cbfs_get_entry_addr(struct cbfs_image *image, struct cbfs_file *entry);
+
+int cbfs_print_directory(struct cbfs_image *image);
+int cbfs_print_header_info(struct cbfs_image *image);
+int cbfs_print_entry_info(struct cbfs_image *image, struct cbfs_file *entry,
+			  void *arg);
+int cbfs_merge_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
+			   void *arg);
+
+/* Returns 1 if entry has valid data (by checking magic number), otherwise 0. */
+int cbfs_is_valid_entry(struct cbfs_file *entry);
+
+/* Utilities */
+
+/* compress.c */
+typedef void (*comp_func_ptr) (char *, int, char *, int *);
+typedef enum {
+	CBFS_COMPRESS_NONE = 0,
+	CBFS_COMPRESS_LZMA
+} comp_algo;
+comp_func_ptr compression_function(comp_algo algo);
+
 /* cbfs-mkpayload.c */
-int parse_elf_to_payload(unsigned char *input, unsigned char **output,
-			 comp_algo algo);
-int parse_flat_binary_to_payload(unsigned char *input, unsigned char **output,
-				 int32_t input_size, uint32_t loadaddress,
-				 uint32_t entrypoint, comp_algo algo);
+int parse_elf_to_payload(const struct buffer *input,
+			 struct buffer *output, comp_algo algo);
+int parse_flat_binary_to_payload(const struct buffer *input,
+				 struct buffer *output,
+				 uint32_t loadaddress,
+				 uint32_t entrypoint,
+				 comp_algo algo);
+/* cbfs-mkstage.c */
+int parse_elf_to_stage(const struct buffer *input, struct buffer *output,
+		       comp_algo algo, uint32_t location);
 #endif



More information about the coreboot mailing list