Initial import of flashmap
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..ce588f0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,33 @@
+2010, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+* Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Alternatively, this software may be distributed under the terms of the
+GNU General Public License ("GPL") version 2 as published by the Free
+Software Foundation.
+
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..a27acab
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,171 @@
+# 2010, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Alternatively, this software may be distributed under the terms of the
+# GNU General Public License ("GPL") version 2 as published by the Free
+# Software Foundation.
+
+PACKAGE_NAME = flashmap
+VERSION_MAJOR = 0
+VERSION_MINOR = 3
+
+AR = $(CROSS_COMPILE)ar
+CC = $(CROSS_COMPILE)gcc
+LD = $(CROSS_COMPILE)ld
+MAKE = make
+RM = rm -f
+
+INSTALL = install
+INSTALL_DATA := $(INSTALL) -m 644
+INSTALL_DIR := $(INSTALL) -m 755 -d
+INSTALL_PROGRAM := $(INSTALL) -m 755
+
+prefix = /usr/local
+sbindir = $(prefix)/sbin
+libdir = $(prefix)/lib
+includedir = $(prefix)/include
+
+DEFS = -DVERSION_MAJOR=$(VERSION_MAJOR)\
+ -DVERSION_MINOR=$(VERSION_MINOR)
+CFLAGS += -O2 -Wall -Werror -Wno-unused-parameter -Ilib/ $(DEFS)
+CFLAGS_GCOV := -fprofile-arcs -ftest-coverage -lgcov
+LINKOPTS =
+
+PROGRAMS = fmap_decode fmap_encode fmap_csum libfmap_example
+TEST_PROGRAM = fmap_test
+SHARED_OBJ = libfmap.so
+SHARED_OBJ_FILE = libfmap-$(VERSION_MAJOR).$(VERSION_MINOR).so
+LIB = lib
+GENHTML_OUTPUT ?= html
+
+SVNVERSION := $(shell LC_ALL=C svnversion -cn . 2>/dev/null | sed -e "s/.*://" -e "s/\([0-9]*\).*/\1/" | grep "[0-9]" || LC_ALL=C svn info . 2>/dev/null | awk '/^Revision:/ {print $$2 }' | grep "[0-9]" || LC_ALL=C git svn info . 2>/dev/null | awk '/^Revision:/ {print $$2 }' | grep "[0-9]" || echo unknown)
+
+RELEASENAME := $(PACKAGE_NAME)-$(VERSION_MAJOR).$(VERSION_MINOR)-r$(SVNVERSION)
+
+export CFLAGS
+
+all: $(PROGRAMS) $(SHARED_OBJ)
+
+help:
+ @echo "flashmap build targets:"
+ @echo "help - print this help screen"
+ @echo "all - build utilities and shared library"
+ @echo "test - build and run unit tests, generate coverage statistics"
+ @echo "install - install utilities, headers, and shared library"
+ @echo "uninstall - opposite of install"
+ @echo ""
+
+
+$(LIB)/libfmap.a:
+ @$(MAKE) -C $(LIB)
+ ar rcs $@ $(LIB)/*.o
+
+$(SHARED_OBJ): $(LIB)/libfmap.a
+ $(CC) -fpic -shared -Wl,-soname,$@ -o $(SHARED_OBJ_FILE) -Wl,-whole-archive $^ -Wl,-no-whole-archive
+
+$(PROGRAMS): $(LIB)/libfmap.a
+ $(CC) $(CFLAGS) $(LINKOPTS) -I. -o $@ $@.c $^
+
+# Add shared object filename to gcc command in case it's not installed already
+$(LIBFMAP_EXAMPLE): $(SHARED_OBJ)
+ $(CC) $(CFLAGS) $(LINKOPTS) -o $@ $@.c $(SHARED_OBJ_FILE)
+
+$(TEST_PROGRAM): $(LIB)/libfmap.a
+ $(CC) $(CFLAGS) $(LINKOPTS) -I. -o $@ $@.c $^
+
+test: CFLAGS += $(CFLAGS_GCOV)
+test: $(TEST_PROGRAM)
+ lcov --directory . --zerocounters
+ @echo "Running $(TEST_PROGRAM)"
+ ./$(TEST_PROGRAM)
+ lcov --directory . --capture \
+ --output-file $(TEST_PROGRAM).info --test-name $(TEST_PROGRAM)
+ genhtml -o $(GENHTML_OUTPUT)/ $(TEST_PROGRAM).info
+ @echo "Unit test coverage statistics are at $(GENHTML_OUTPUT)/index.html"
+
+test_only: $(TEST_PROGRAM)
+ @echo "Running $(TEST_PROGRAM)"
+ ./$(TEST_PROGRAM)
+
+PHONY += export
+export:
+ @rm -rf $(EXPORTDIR)/$(RELEASENAME)
+ @svn export -r BASE . $(EXPORTDIR)/$(RELEASENAME)
+ @sed "s/^SVNVERSION.*/SVNVERSION := $(SVNVERSION)/" Makefile >$(EXPORTDIR)/$(RELEASENAME)/Makefile
+ @LC_ALL=C svn log >$(EXPORTDIR)/$(RELEASENAME)/ChangeLog
+ @echo Exported $(EXPORTDIR)/$(RELEASENAME)/
+
+PHONY += tarball
+# TAROPTIONS reduces information leakage from the packager's system.
+# If other tar programs support command line arguments for setting uid/gid of
+# stored files, they can be handled here as well.
+TAROPTIONS = $(shell LC_ALL=C tar --version|grep -q GNU && echo "--owner=root --group=root")
+tarball: export
+ @tar cjf $(EXPORTDIR)/$(RELEASENAME).tar.bz2 -C $(EXPORTDIR)/ $(TAROPTIONS) $(RELEASENAME)/
+ @rm -rf $(EXPORTDIR)/$(RELEASENAME)
+ @echo Created $(EXPORTDIR)/$(RELEASENAME).tar.bz2
+
+install: all
+ $(INSTALL_DIR) $(DESTDIR)$(sbindir)
+ $(INSTALL_DIR) $(DESTDIR)$(libdir)
+ $(INSTALL_DIR) $(DESTDIR)$(includedir)
+ $(INSTALL_PROGRAM) fmap_decode $(DESTDIR)$(sbindir)
+ $(INSTALL_PROGRAM) fmap_encode $(DESTDIR)$(sbindir)
+ $(INSTALL_PROGRAM) fmap_csum $(DESTDIR)$(sbindir)
+ $(INSTALL_DATA) lib/fmap.h $(DESTDIR)$(includedir)
+ $(INSTALL_DATA) lib/valstr.h $(DESTDIR)$(includedir)
+ $(INSTALL_DATA) $(SHARED_OBJ_FILE) $(DESTDIR)$(libdir)
+ @echo Installed shared library, please run ldconfig to set up symlinks.
+
+uninstall:
+ $(RM) $(DESTDIR)$(sbindir)/fmap_decode
+ $(RM) $(DESTDIR)$(sbindir)/fmap_encode
+ $(RM) $(DESTDIR)$(sbindir)/fmap_csum
+ $(RM) $(DESTDIR)$(includedir)/fmap.h
+ $(RM) $(DESTDIR)$(includedir)/valstr.h
+ $(RM) $(DESTDIR)$(libdir)/$(SHARED_OBJ)
+ $(RM) $(DESTDIR)$(libdir)/$(SHARED_OBJ_FILE)
+
+.PHONY: clean
+RCS_FIND_IGNORE := \( -name SCCS -o -name BitKeeper -o -name .svn -o -name CVS -o -name .pc -o -name .hg -o -name .git \) -prune -o
+
+lcov-clean:
+ @find . $(RCS_FIND_IGNORE) \
+ \( -name '*.css' -o -name '*.gcda' -o -name '*.png' \
+ -o -name '*.css' -o -name '*.info' -o -name '*.html' \
+ -o -name '*.gcno' \) \
+ -type f -print | xargs rm -f
+ @rm -rf $(GENHTML_OUTPUT)/
+
+clean: lcov-clean
+ rm -f *.o *.a $(PROGRAMS) $(TEST_PROGRAM) $(LIBFMAP_EXAMPLE) $(SHARED_OBJ_FILE)
+ @$(MAKE) -C $(LIB) clean
+
+%.o: %.c
+ $(CC) $(CFLAGS) -c $^ -I. -o $@
diff --git a/bin/example.bin b/bin/example.bin
new file mode 100644
index 0000000..4f8a683
--- /dev/null
+++ b/bin/example.bin
Binary files differ
diff --git a/fmap.py b/fmap.py
new file mode 100644
index 0000000..3f26b54
--- /dev/null
+++ b/fmap.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python
+#
+# Copyright 2010, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Alternatively, this software may be distributed under the terms of the
+# GNU General Public License ("GPL") version 2 as published by the Free
+# Software Foundation.
+
+"""
+This module provides basic encode and decode functionality to the flashrom
+memory map (FMAP) structure.
+
+Usage:
+ (decode)
+ obj = fmap_decode(blob)
+ print obj
+
+ (encode)
+ blob = fmap_encode(obj)
+ open('output.bin', 'w').write(blob)
+
+ The object returned by fmap_decode is a dictionary with names defined in
+ fmap.h. A special property 'FLAGS' is provided as a readable and read-only
+ tuple of decoded area flags.
+"""
+
+import struct
+import sys
+
+# constants imported from lib/fmap.h
+FMAP_SIGNATURE = "__FMAP__"
+FMAP_VER_MAJOR = 1
+FMAP_VER_MINOR = 0
+FMAP_STRLEN = 32
+
+FMAP_FLAGS = {
+ 'FMAP_AREA_STATIC': 1 << 0,
+ 'FMAP_AREA_COMPRESSED': 1 << 1,
+}
+
+FMAP_HEADER_NAMES = (
+ 'signature',
+ 'ver_major',
+ 'ver_minor',
+ 'base',
+ 'size',
+ 'name',
+ 'nareas',
+)
+
+FMAP_AREA_NAMES = (
+ 'offset',
+ 'size',
+ 'name',
+ 'flags',
+)
+
+# format string
+FMAP_HEADER_FORMAT = "<8sBBQI%dsH" % (FMAP_STRLEN)
+FMAP_AREA_FORMAT = "<II%dsH" % (FMAP_STRLEN)
+
+
+def _fmap_decode_header(blob, offset):
+ """ (internal) Decodes a FMAP header from blob by offset"""
+ header = {}
+ for (name, value) in zip(FMAP_HEADER_NAMES,
+ struct.unpack_from(FMAP_HEADER_FORMAT,
+ blob,
+ offset)):
+ header[name] = value
+
+ if header['signature'] != FMAP_SIGNATURE:
+ raise struct.error('Invalid signature')
+ if header['ver_major'] != FMAP_VER_MAJOR or \
+ header['ver_minor'] != FMAP_VER_MINOR:
+ raise struct.error('Incompatible version')
+
+ # convert null-terminated names
+ header['name'] = header['name'].strip(chr(0))
+ return (header, struct.calcsize(FMAP_HEADER_FORMAT))
+
+
+def _fmap_decode_area(blob, offset):
+ """ (internal) Decodes a FMAP area record from blob by offset """
+ area = {}
+ for (name, value) in zip(FMAP_AREA_NAMES,
+ struct.unpack_from(FMAP_AREA_FORMAT, blob, offset)):
+ area[name] = value
+ # convert null-terminated names
+ area['name'] = area['name'].strip(chr(0))
+ # add a (readonly) readable FLAGS
+ area['FLAGS'] = _fmap_decode_area_flags(area['flags'])
+ return (area, struct.calcsize(FMAP_AREA_FORMAT))
+
+
+def _fmap_decode_area_flags(area_flags):
+ """ (internal) Decodes a FMAP flags property """
+ return tuple([name for name in FMAP_FLAGS if area_flags & FMAP_FLAGS[name]])
+
+
+def fmap_decode(blob, offset=None):
+ """ Decodes a blob to FMAP dictionary object.
+
+ Arguments:
+ blob: a binary data containing FMAP structure.
+ offset: starting offset of FMAP. When omitted, fmap_decode will search in
+ the blob.
+ """
+ fmap = {}
+ if offset == None:
+ # try search magic in fmap
+ offset = blob.find(FMAP_SIGNATURE)
+ (fmap, size) = _fmap_decode_header(blob, offset)
+ fmap['areas'] = []
+ offset = offset + size
+ for i in range(fmap['nareas']):
+ (area, size) = _fmap_decode_area(blob, offset)
+ offset = offset + size
+ fmap['areas'].append(area)
+ return fmap
+
+
+def _fmap_encode_header(obj):
+ """ (internal) Encodes a FMAP header """
+ values = [obj[name] for name in FMAP_HEADER_NAMES]
+ return struct.pack(FMAP_HEADER_FORMAT, *values)
+
+
+def _fmap_encode_area(obj):
+ """ (internal) Encodes a FMAP area entry """
+ values = [obj[name] for name in FMAP_AREA_NAMES]
+ return struct.pack(FMAP_AREA_FORMAT, *values)
+
+
+def fmap_encode(obj):
+ """ Encodes a FMAP dictionary object to blob.
+
+ Arguments
+ obj: a FMAP dictionary object.
+ """
+ # fix up values
+ obj['nareas'] = len(obj['areas'])
+ # TODO(hungte) re-assign signature / version?
+ blob = _fmap_encode_header(obj)
+ for area in obj['areas']:
+ blob = blob + _fmap_encode_area(area)
+ return blob
+
+
+if __name__ == '__main__':
+ # main entry, do a unit test
+ blob = open('bin/example.bin').read()
+ obj = fmap_decode(blob)
+ print obj
+ blob2 = fmap_encode(obj)
+ obj2 = fmap_decode(blob2)
+ print obj2
+ assert obj == obj2
+
diff --git a/fmap_csum.c b/fmap_csum.c
new file mode 100644
index 0000000..c443a62
--- /dev/null
+++ b/fmap_csum.c
@@ -0,0 +1,154 @@
+/* Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+
+#include "lib/fmap.h"
+
+static struct option const long_options[] =
+{
+ {"digest", required_argument, NULL, 'd'},
+ {"list", no_argument, NULL, 'l'},
+ {"version", no_argument, NULL, 'v'},
+ {NULL, 0, NULL, 0}
+};
+
+void print_csum(uint8_t *digest, size_t len)
+{
+ char *str;
+ char tmp[3];
+ unsigned int i;
+
+ str = malloc((len * 2) + 1);
+ memset(str, '\0', sizeof(str));
+ for (i = 0; i < len; i++) {
+ snprintf(tmp, 3, "%02x", digest[i]);
+ strncat(str, tmp, 3);
+ }
+
+ printf("%s\n", str);
+ free(str);
+}
+
+void print_help()
+{
+ printf("Usage: fmap_csum [OPTION]... [FILE]\n"
+ "Print sha1sum of static regions of FMAP-compliant binary\n"
+ "Arguments:\n"
+ "\t-h, --help\t\tprint this help menu\n"
+ "\t-v, --version\t\tdisplay version\n");
+}
+
+int main(int argc, char *argv[])
+{
+ int fd, len, rc = EXIT_SUCCESS;
+ struct stat s;
+ char *filename = NULL;
+ uint8_t *image;
+ int argflag;
+ uint8_t *digest = NULL;
+
+ while ((argflag = getopt_long(argc, argv, "d:hlv",
+ long_options, NULL)) > 0) {
+ switch (argflag) {
+ case 'v':
+ printf("fmap suite version: %d.%d\n",
+ VERSION_MAJOR, VERSION_MINOR);;
+ goto do_exit_1;
+ case 'h':
+ print_help();
+ goto do_exit_1;
+ default:
+ print_help();
+ rc = EXIT_FAILURE;
+ goto do_exit_1;
+ }
+ }
+
+ /* quit if filename not specified */
+ if (argv[optind]) {
+ filename = argv[optind];
+ } else {
+ print_help();
+ rc = EXIT_FAILURE;
+ goto do_exit_1;
+ }
+
+ fd = open(filename, O_RDONLY);
+ if (fd < 0) {
+ fprintf(stderr, "unable to open file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_1;
+ }
+ if (fstat(fd, &s) < 0) {
+ fprintf(stderr, "unable to stat file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_2;
+ }
+
+ image = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (image == MAP_FAILED) {
+ fprintf(stderr, "unable to map file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_2;
+ }
+
+ if ((len = fmap_get_csum(image, s.st_size, &digest)) < 0) {
+ fprintf(stderr, "unable to obtain checksum\n");
+ rc = EXIT_FAILURE;
+ goto do_exit_3;
+ }
+
+ print_csum(digest, len);
+
+do_exit_3:
+ munmap(image, s.st_size);
+ free(digest);
+do_exit_2:
+ close(fd);
+do_exit_1:
+ exit(rc);
+}
diff --git a/fmap_decode.c b/fmap_decode.c
new file mode 100644
index 0000000..98f8efa
--- /dev/null
+++ b/fmap_decode.c
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <string.h>
+
+#include "lib/fmap.h"
+
+int main(int argc, char *argv[])
+{
+ int fd;
+ int rc = EXIT_SUCCESS;
+ struct stat s;
+ char *filename;
+ uint8_t *blob;
+ off_t fmap_offset;
+
+ if (argc != 2) {
+ printf("usage: %s <filename>\n", argv[0]);
+ rc = EXIT_FAILURE;
+ goto do_exit_1;
+ }
+ filename = argv[1];
+
+ fd = open(filename, O_RDONLY);
+ if (fd < 0) {
+ printf("unable to open file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_2;
+ }
+ if (fstat(fd, &s) < 0) {
+ printf("unable to stat file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_2;
+ }
+
+ blob = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (blob == MAP_FAILED) {
+ printf("unable to mmap file %s: %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto do_exit_2;
+ }
+
+ fmap_offset = fmap_find(blob, s.st_size);
+ if (fmap_offset < 0) {
+ rc = EXIT_FAILURE;
+ goto do_exit_3;
+ } else {
+ fmap_print((struct fmap *)(blob + fmap_offset));
+ }
+
+do_exit_3:
+ munmap(blob, s.st_size);
+do_exit_2:
+ close(fd);
+do_exit_1:
+ return rc;
+}
diff --git a/fmap_encode.c b/fmap_encode.c
new file mode 100644
index 0000000..3b3efce
--- /dev/null
+++ b/fmap_encode.c
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <getopt.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "lib/fmap.h"
+#include "lib/input.h"
+
+static void print_usage()
+{
+ printf("Usage: fmap_encode [option] [arguments]\n"
+ "Options:\n"
+ "\t-h | --help print this help text\n"
+ "\t-i | --interactive <output> interactive setup\n"
+ "\t-k | --kv <input> <output> generate binary from kv-pairs\n"
+// "\t-x | --xml <input> <output> generate binary from xml\n"
+ "\n"
+ );
+}
+
+int main(int argc, char *argv[])
+{
+ int rc = EXIT_SUCCESS;
+ int opt, option_index = 0;
+ static const char optstring[] = "hi:k:";
+ static const struct option long_options[] = {
+ {"help", no_argument, NULL, 'h'},
+ {"interactive", required_argument, NULL, 'i'},
+ {"kv", required_argument, NULL, 'k'},
+ {NULL, 0, NULL, 0}
+ };
+ char *input = NULL, *output = NULL;
+
+ opt = getopt_long(argc, argv, optstring, long_options, &option_index);
+ switch(opt) {
+ case 'h':
+ print_usage();
+ break;
+ case 'i':
+ output = strdup(optarg);
+ rc = input_interactive(output);
+ break;
+ case 'k':
+ if (!optarg || !argv[optind]) {
+ printf("Error: missing argument\n");
+ print_usage();
+ rc = EXIT_FAILURE;
+ break;
+ }
+ input = strdup(optarg);
+ output = strdup(argv[optind]);
+ rc = input_kv_pair(input, output);
+ if (optind != (argc - 1))
+ optind++;
+ break;
+ default:
+ print_usage(); /* FIXME: implement this */
+ break;
+ }
+
+ if (input)
+ free(input);
+ if (output)
+ free(output);
+ return rc;
+}
diff --git a/fmap_test.c b/fmap_test.c
new file mode 100644
index 0000000..d9cccf7
--- /dev/null
+++ b/fmap_test.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "lib/fmap.h"
+#include "lib/input.h"
+
+int main()
+{
+ int rc = 0;
+
+ rc |= input_kv_pair_test();
+ rc |= fmap_test();
+
+ if (!rc) {
+ printf("Tests passed.\n");
+ rc = EXIT_SUCCESS;
+ } else {
+ printf("Tests failed.\n");
+ rc = EXIT_FAILURE;
+ }
+
+ return rc;
+}
diff --git a/lib/Makefile b/lib/Makefile
new file mode 100644
index 0000000..abd7ef8
--- /dev/null
+++ b/lib/Makefile
@@ -0,0 +1,59 @@
+# 2010, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Alternatively, this software may be distributed under the terms of the
+# GNU General Public License ("GPL") version 2 as published by the Free
+# Software Foundation.
+
+MINCRYPT = mincrypt
+INCLUDES = $(MINCRYPT)
+
+all: libfmap.a
+OBJS = fmap.o valstr.o kv_pair.o
+DEPS = $(MINCRYPT)/sha.o
+
+INPUT_OBJS = input_interactive.o input_kv_pair.o
+OBJS += $(INPUT_OBJS)
+
+CFLAGS += -fpic
+export CFLAGS
+
+.PHONY: clean
+clean:
+ rm -f *.o *.a
+ @$(MAKE) -C $(MINCRYPT) clean
+
+$(MINCRYPT)/sha.o:
+ @$(MAKE) -C $(MINCRYPT)
+
+libfmap.a: $(OBJS) $(DEPS)
+ ar rcs $@ $+
+
+%.o: %.c
+ $(CC) $(CFLAGS) -c $^ -I. -I$(INCLUDES) -o $@
diff --git a/lib/fmap.c b/lib/fmap.c
new file mode 100644
index 0000000..8850a92
--- /dev/null
+++ b/lib/fmap.c
@@ -0,0 +1,727 @@
+/* Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <assert.h>
+
+#include <fmap.h>
+#include <valstr.h>
+
+#include "kv_pair.h"
+#include "mincrypt/sha.h"
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
+
+const struct valstr flag_lut[] = {
+ { FMAP_AREA_STATIC, "static" },
+ { FMAP_AREA_COMPRESSED, "compressed" },
+ { FMAP_AREA_RO, "ro" },
+};
+
+/* returns size of fmap data structure if successful, <0 to indicate error */
+int fmap_size(struct fmap *fmap)
+{
+ if (!fmap)
+ return -1;
+
+ return sizeof(*fmap) + (fmap->nareas * sizeof(struct fmap_area));
+}
+
+/* brute force linear search */
+static long int fmap_lsearch(const uint8_t *image, size_t len)
+{
+ long int offset;
+ int fmap_found = 0;
+
+ for (offset = 0; offset < len - strlen(FMAP_SIGNATURE); offset++) {
+ if (!memcmp(&image[offset],
+ FMAP_SIGNATURE,
+ strlen(FMAP_SIGNATURE))) {
+ fmap_found = 1;
+ break;
+ }
+ }
+
+ if (!fmap_found)
+ return -1;
+
+ if (offset + fmap_size((struct fmap *)&image[offset]) > len)
+ return -1;
+
+ return offset;
+}
+
+/* if image length is a power of 2, use binary search */
+static long int fmap_bsearch(const uint8_t *image, size_t len)
+{
+ long int offset = -1;
+ int fmap_found = 0, stride;
+
+ /*
+ * For efficient operation, we start with the largest stride possible
+ * and then decrease the stride on each iteration. Also, check for a
+ * remainder when modding the offset with the previous stride. This
+ * makes it so that each offset is only checked once.
+ */
+ for (stride = len / 2; stride >= 1; stride /= 2) {
+ if (fmap_found)
+ break;
+
+ for (offset = 0;
+ offset < len - strlen(FMAP_SIGNATURE);
+ offset += stride) {
+ if ((offset % (stride * 2) == 0) && (offset != 0))
+ continue;
+ if (!memcmp(&image[offset],
+ FMAP_SIGNATURE,
+ strlen(FMAP_SIGNATURE))) {
+ fmap_found = 1;
+ break;
+ }
+ }
+ }
+
+ if (!fmap_found)
+ return -1;
+
+ if (offset + fmap_size((struct fmap *)&image[offset]) > len)
+ return -1;
+
+ return offset;
+}
+
+static int popcnt(unsigned int u)
+{
+ int count;
+
+ /* K&R method */
+ for (count = 0; u; count++)
+ u &= (u - 1);
+
+ return count;
+}
+
+long int fmap_find(const uint8_t *image, unsigned int image_len)
+{
+ long int ret = -1;
+
+ if ((image == NULL) || (image_len == 0))
+ return -1;
+
+ if (popcnt(image_len) == 1)
+ ret = fmap_bsearch(image, image_len);
+ else
+ ret = fmap_lsearch(image, image_len);
+
+ return ret;
+}
+
+int fmap_print(const struct fmap *fmap)
+{
+ int i;
+ struct kv_pair *kv = NULL;
+ const uint8_t *tmp;
+
+ kv = kv_pair_new();
+ if (!kv)
+ return -1;
+
+ tmp = fmap->signature;
+ kv_pair_fmt(kv, "fmap_signature",
+ "0x%02x%02x%02x%02x%02x%02x%02x%02x",
+ tmp[0], tmp[1], tmp[2], tmp[3],
+ tmp[4], tmp[5], tmp[6], tmp[7]);
+ kv_pair_fmt(kv, "fmap_ver_major", "%d", fmap->ver_major);
+ kv_pair_fmt(kv, "fmap_ver_minor","%d", fmap->ver_minor);
+ kv_pair_fmt(kv, "fmap_base", "0x%016llx",
+ (unsigned long long)fmap->base);
+ kv_pair_fmt(kv, "fmap_size", "0x%04x", fmap->size);
+ kv_pair_fmt(kv, "fmap_name", "%s", fmap->name);
+ kv_pair_fmt(kv, "fmap_nareas", "%d", fmap->nareas);
+ kv_pair_print(kv);
+ kv_pair_free(kv);
+
+ for (i = 0; i < fmap->nareas; i++) {
+ struct kv_pair *kv;
+ uint16_t flags;
+ char *str;
+
+ kv = kv_pair_new();
+ if (!kv)
+ return -1;
+
+ kv_pair_fmt(kv, "area_offset", "0x%08x",
+ fmap->areas[i].offset);
+ kv_pair_fmt(kv, "area_size", "0x%08x",
+ fmap->areas[i].size);
+ kv_pair_fmt(kv, "area_name", "%s",
+ fmap->areas[i].name);
+ kv_pair_fmt(kv, "area_flags_raw", "0x%02x",
+ fmap->areas[i].flags);
+
+ /* Print descriptive strings for flags rather than the field */
+ flags = fmap->areas[i].flags;
+ if ((str = fmap_flags_to_string(flags)) == NULL)
+ return -1;
+ kv_pair_fmt(kv, "area_flags", "%s", str );
+ free(str);
+
+ kv_pair_print(kv);
+ kv_pair_free(kv);
+ }
+
+ return 0;
+}
+
+/* get SHA1 sum of all static regions described by the flashmap and copy into
+ *digest (which will be allocated and must be freed by the caller), */
+int fmap_get_csum(const uint8_t *image, unsigned int image_len, uint8_t **digest)
+{
+ int i;
+ struct fmap *fmap;
+ int fmap_offset;
+ SHA_CTX ctx;
+
+ if ((image == NULL))
+ return -1;
+
+ if ((fmap_offset = fmap_find(image, image_len)) < 0)
+ return -1;
+ fmap = (struct fmap *)(image + fmap_offset);
+
+ SHA_init(&ctx);
+
+ /* Iterate through flash map and calculate the checksum piece-wise. */
+ for (i = 0; i < fmap->nareas; i++) {
+ /* skip non-static areas */
+ if (!(fmap->areas[i].flags & FMAP_AREA_STATIC))
+ continue;
+
+ /* sanity check the offset */
+ if (fmap->areas[i].size + fmap->areas[i].offset > image_len) {
+ fprintf(stderr,
+ "(%s) invalid parameter detected in area %d\n",
+ __func__, i);
+ return -1;
+ }
+
+ SHA_update(&ctx,
+ image + fmap->areas[i].offset,
+ fmap->areas[i].size);
+ }
+
+ SHA_final(&ctx);
+ *digest = malloc(SHA_DIGEST_SIZE);
+ memcpy(*digest, ctx.buf, SHA_DIGEST_SIZE);
+
+ return SHA_DIGEST_SIZE;
+}
+
+/* convert raw flags field to user-friendly string */
+char *fmap_flags_to_string(uint16_t flags)
+{
+ char *str = NULL;
+ int i, total_size;
+
+ str = malloc(1);
+ str[0] = '\0';
+ total_size = 1;
+
+ for (i = 0; i < sizeof(flags) * CHAR_BIT; i++) {
+ if (!flags)
+ break;
+
+ if (flags & (1 << i)) {
+ const char *tmp = val2str(1 << i, flag_lut);
+
+ total_size += strlen(tmp);
+ str = realloc(str, total_size);
+ strcat(str, tmp);
+
+ flags &= ~(1 << i);
+ if (flags) {
+ total_size++;
+ str = realloc(str, total_size);
+ strcat(str, ",");
+ }
+ }
+ }
+
+ return str;
+}
+
+/* allocate and initialize a new fmap structure */
+struct fmap *fmap_create(uint64_t base, uint32_t size, uint8_t *name)
+{
+ struct fmap *fmap;
+
+ fmap = malloc(sizeof(*fmap));
+ if (!fmap)
+ return NULL;
+
+ memset(fmap, 0, sizeof(*fmap));
+ memcpy(&fmap->signature, FMAP_SIGNATURE, strlen(FMAP_SIGNATURE));
+ fmap->ver_major = VERSION_MAJOR;
+ fmap->ver_minor = VERSION_MINOR;
+ fmap->base = base;
+ fmap->size = size;
+ memccpy(&fmap->name, name, '\0', FMAP_STRLEN);
+
+ return fmap;
+}
+
+/* free memory used by an fmap structure */
+void fmap_destroy(struct fmap *fmap) {
+ free(fmap);
+}
+
+/* append area to existing structure, return new total size if successful */
+int fmap_append_area(struct fmap **fmap,
+ uint32_t offset, uint32_t size,
+ const uint8_t *name, uint16_t flags)
+{
+ struct fmap_area *area;
+ int orig_size, new_size;
+
+ if ((fmap == NULL || *fmap == NULL) || (name == NULL))
+ return -1;
+
+ /* too many areas */
+ if ((*fmap)->nareas >= 0xffff)
+ return -1;
+
+ orig_size = fmap_size(*fmap);
+ new_size = orig_size + sizeof(*area);
+
+ *fmap = realloc(*fmap, new_size);
+ if (*fmap == NULL)
+ return -1;
+
+ area = (struct fmap_area *)((uint8_t *)*fmap + orig_size);
+ memset(area, 0, sizeof(*area));
+ memcpy(&area->offset, &offset, sizeof(area->offset));
+ memcpy(&area->size, &size, sizeof(area->size));
+ memccpy(&area->name, name, '\0', FMAP_STRLEN);
+ memcpy(&area->flags, &flags, sizeof(area->flags));
+
+ (*fmap)->nareas++;
+ return new_size;
+}
+
+struct fmap_area *fmap_find_area(struct fmap *fmap, const char *name)
+{
+ int i;
+ struct fmap_area *area = NULL;
+
+ if (!fmap || !name)
+ return NULL;
+
+ for (i = 0; i < fmap->nareas; i++) {
+ if (!strcmp((const char *)fmap->areas[i].name, name)) {
+ area = &fmap->areas[i];
+ break;
+ }
+ }
+
+ return area;
+}
+
+/*
+ * LCOV_EXCL_START
+ * Unit testing stuff done here so we do not need to expose static functions.
+ */
+static enum test_status { pass = EXIT_SUCCESS, fail = EXIT_FAILURE } status;
+static struct fmap *fmap_create_test(void)
+{
+ struct fmap *fmap;
+ uint64_t base = 0;
+ uint32_t size = 0x100000;
+ char name[] = "test_fmap";
+
+ status = fail;
+
+ fmap = fmap_create(base, size, (uint8_t *)name);
+ if (!fmap)
+ return NULL;
+
+ if (memcmp(&fmap->signature, FMAP_SIGNATURE, strlen(FMAP_SIGNATURE))) {
+ printf("FAILURE: signature is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ if ((fmap->ver_major != VERSION_MAJOR) ||
+ (fmap->ver_minor != VERSION_MINOR)) {
+ printf("FAILURE: version is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ if (fmap->base != base) {
+ printf("FAILURE: base is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ if (fmap->size != 0x100000) {
+ printf("FAILURE: size is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ if (strcmp((char *)fmap->name, "test_fmap")) {
+ printf("FAILURE: name is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ if (fmap->nareas != 0) {
+ printf("FAILURE: number of areas is incorrect\n");
+ goto fmap_create_test_exit;
+ }
+
+ status = pass;
+fmap_create_test_exit:
+ /* preserve fmap if all went well */
+ if (status == fail) {
+ fmap_destroy(fmap);
+ fmap = NULL;
+ }
+ return fmap;
+}
+
+static int fmap_print_test(struct fmap *fmap)
+{
+ return fmap_print(fmap);
+}
+
+static int fmap_get_csum_test(struct fmap *fmap)
+{
+ uint8_t *digest = NULL, *image = NULL;
+ /* assume 0x100-0x10100 is marked "static" and is filled with 0x00 */
+ int image_size = 0x20000;
+ uint8_t csum[SHA_DIGEST_SIZE] = {
+ 0x1a, 0xdc, 0x95, 0xbe, 0xbe, 0x9e, 0xea, 0x8c,
+ 0x11, 0x2d, 0x40, 0xcd, 0x04, 0xab, 0x7a, 0x8d,
+ 0x75, 0xc4, 0xf9, 0x61 };
+
+ status = fail;
+
+ if ((fmap_get_csum(NULL, image_size, &digest) >= 0) ||
+ (fmap_get_csum(image, image_size, NULL) >= 0)) {
+ printf("failed to abort on NULL pointer input\n");
+ goto fmap_get_csum_test_exit;
+ }
+
+ image = calloc(image_size, 1);
+ memcpy(image, fmap, fmap_size(fmap));
+
+ if (fmap_get_csum(image, image_size, &digest) != SHA_DIGEST_SIZE) {
+ printf("FAILURE: failed to calculate checksum\n");
+ goto fmap_get_csum_test_exit;
+ }
+ if (memcmp(digest, csum, SHA_DIGEST_SIZE)) {
+ printf("FAILURE: checksum is incorrect\n");
+ goto fmap_get_csum_test_exit;
+ }
+
+ status = pass;
+fmap_get_csum_test_exit:
+ free(image);
+ free(digest);
+ return status;
+}
+
+static int fmap_size_test(struct fmap *fmap)
+{
+ status = fail;
+
+ if (fmap_size(NULL) >= 0) {
+ printf("FAILURE: failed to abort on NULL pointer input\n");
+ goto fmap_size_test_exit;
+ }
+
+ status = pass;
+fmap_size_test_exit:
+ return status;
+}
+
+/* this test re-allocates the fmap, so it gets a double-pointer */
+static int fmap_append_area_test(struct fmap **fmap)
+{
+ int total_size;
+ uint16_t nareas_orig;
+ /* test_area will be used by fmap_csum_test and find_area_test */
+ struct fmap_area test_area = {
+ .offset = 0x400,
+ .size = 0x10000,
+ .name = "test_area_1",
+ .flags = FMAP_AREA_STATIC,
+ };
+
+ status = fail;
+
+ if ((fmap_append_area(NULL, 0, 0, test_area.name, 0) >= 0) ||
+ (fmap_append_area(fmap, 0, 0, NULL, 0) >= 0)) {
+ printf("FAILURE: failed to abort on NULL pointer input\n");
+ goto fmap_append_area_test_exit;
+ }
+
+ nareas_orig = (*fmap)->nareas;
+ (*fmap)->nareas = ~(0);
+ if (fmap_append_area(fmap, 0, 0, (const uint8_t *)"foo", 0) >= 0) {
+ printf("FAILURE: failed to abort with too many areas\n");
+ goto fmap_append_area_test_exit;
+ }
+ (*fmap)->nareas = nareas_orig;
+
+ total_size = sizeof(**fmap) + sizeof(test_area);
+ if (fmap_append_area(fmap,
+ test_area.offset,
+ test_area.size,
+ test_area.name,
+ test_area.flags
+ ) != total_size) {
+ printf("failed to append area\n");
+ goto fmap_append_area_test_exit;
+ }
+
+ if ((*fmap)->nareas != 1) {
+ printf("FAILURE: failed to increment number of areas\n");
+ goto fmap_append_area_test_exit;
+ }
+
+ status = pass;
+fmap_append_area_test_exit:
+ return status;
+}
+
+static int fmap_find_area_test(struct fmap *fmap)
+{
+ status = fail;
+ char area_name[] = "test_area_1";
+
+ if (fmap_find_area(NULL, area_name) ||
+ fmap_find_area(fmap, NULL)) {
+ printf("FAILURE: failed to abort on NULL pointer input\n");
+ goto fmap_find_area_test_exit;
+ }
+
+ if (fmap_find_area(fmap, area_name) == NULL) {
+ printf("FAILURE: failed to find \"%s\"\n", area_name);
+ goto fmap_find_area_test_exit;
+ }
+
+ status = pass;
+fmap_find_area_test_exit:
+ return status;
+}
+
+static int fmap_flags_to_string_test()
+{
+ char *str, *my_str;
+ int i;
+ uint16_t flags;
+
+ status = fail;
+
+ /* no area flag */
+ str = fmap_flags_to_string(0);
+ if (!str || strcmp(str, "")) {
+ printf("FAILURE: failed to return empty string when no flag"
+ "are set");
+ goto fmap_flags_to_string_test_exit;
+ }
+ free(str);
+
+ /* single area flags */
+ for (i = 0; i < ARRAY_SIZE(flag_lut); i++) {
+ if (!flag_lut[i].str)
+ continue;
+
+ if ((str = fmap_flags_to_string(flag_lut[i].val)) == NULL) {
+ printf("FAILURE: failed to translate flag to string");
+ goto fmap_flags_to_string_test_exit;
+ }
+ free(str);
+ }
+
+ /* construct our own flags field and string using all available flags
+ * and compare output with fmap_flags_to_string() */
+ my_str = calloc(256, 1);
+ flags = 0;
+ for (i = 0; i < ARRAY_SIZE(flag_lut); i++) {
+ if (!flag_lut[i].str)
+ continue;
+ else if (i > 0)
+ strcat(my_str, ",");
+
+ flags |= flag_lut[i].val;
+ strcat(my_str, flag_lut[i].str);
+ }
+
+ str = fmap_flags_to_string(flags);
+ if (strcmp(str, my_str)) {
+ printf("FAILURE: bad result from fmap_flags_to_string\n");
+ goto fmap_flags_to_string_test_exit;
+ }
+ free(my_str);
+ free(str);
+
+ status = pass;
+fmap_flags_to_string_test_exit:
+ return status;
+
+}
+
+static int fmap_find_test(struct fmap *fmap)
+{
+ uint8_t *buf;
+ size_t total_size, offset;
+
+ status = fail;
+
+ /*
+ * Note: In these tests, we'll use fmap_find() and control usage of
+ * lsearch and bsearch by using a power-of-2 total_size. For lsearch,
+ * use total_size - 1. For bsearch, use total_size.
+ */
+
+ total_size = 0x100000;
+ buf = calloc(total_size, 1);
+
+ /* test if image length is zero */
+ if (fmap_find(buf, 0) >= 0) {
+ printf("FAILURE: failed to abort on zero-length image\n");
+ goto fmap_find_test_exit;
+ }
+
+ /* test if no fmap exists */
+ if (fmap_find(buf, total_size - 1) >= 0) {
+ printf("FAILURE: lsearch returned false positive\n");
+ goto fmap_find_test_exit;
+ }
+ if (fmap_find(buf, total_size) >= 0) {
+ printf("FAILURE: bsearch returned false positive\n");
+ goto fmap_find_test_exit;
+ }
+
+ /* simple test case: fmap at (total_size / 2) + 1 */
+ offset = (total_size / 2) + 1;
+ memcpy(&buf[offset], fmap, fmap_size(fmap));
+
+ if (fmap_find(buf, total_size - 1) != offset) {
+ printf("FAILURE: lsearch failed to find fmap\n");
+ goto fmap_find_test_exit;
+ }
+ if (fmap_find(buf, total_size) != offset) {
+ printf("FAILURE: bsearch failed to find fmap\n");
+ goto fmap_find_test_exit;
+ }
+
+ /* test bsearch if offset is at 0 */
+ offset = 0;
+ memset(buf, 0, total_size);
+ memcpy(buf, fmap, fmap_size(fmap));
+ if (fmap_find(buf, total_size) != offset) {
+ printf("FAILURE: bsearch failed to find fmap at offset 0\n");
+ goto fmap_find_test_exit;
+ }
+
+ /* test overrun detection */
+ memset(buf, 0, total_size);
+ memcpy(&buf[total_size - fmap_size(fmap) + 1],
+ fmap,
+ fmap_size(fmap) + 1);
+ if (fmap_find(buf, total_size - 1) >= 0) {
+ printf("FAILURE: lsearch failed to catch overrun\n");
+ goto fmap_find_test_exit;
+ }
+ if (fmap_find(buf, total_size) >= 0) {
+ printf("FAILURE: bsearch failed to catch overrun\n");
+ goto fmap_find_test_exit;
+ }
+
+ status = pass;
+fmap_find_test_exit:
+ free(buf);
+ return status;
+}
+
+int fmap_test()
+{
+ int rc = EXIT_SUCCESS;
+ struct fmap *my_fmap;
+
+ /*
+ * This test has two parts: Creation of an fmap with one or more
+ * area(s), and other stuff. Since a valid fmap is required to run
+ * many tests, we abort if fmap creation fails in any way.
+ *
+ * Also, fmap_csum_test() makes some assumptions based on the areas
+ * appended. See fmap_append_area_test() for details.
+ */
+ if ((my_fmap = fmap_create_test()) == NULL) {
+ rc = EXIT_FAILURE;
+ goto fmap_test_exit;
+ }
+
+ if (fmap_find_test(my_fmap)) {
+ rc = EXIT_FAILURE;
+ goto fmap_test_exit;
+ }
+
+ if (fmap_append_area_test(&my_fmap)) {
+ rc = EXIT_FAILURE;
+ goto fmap_test_exit;
+ }
+
+ rc |= fmap_find_area_test(my_fmap);
+ rc |= fmap_get_csum_test(my_fmap);
+ rc |= fmap_size_test(my_fmap);
+ rc |= fmap_flags_to_string_test();
+ rc |= fmap_print_test(my_fmap);
+
+fmap_test_exit:
+ fmap_destroy(my_fmap);
+ if (rc)
+ printf("FAILED\n");
+ return rc;
+}
+/* LCOV_EXCL_STOP */
diff --git a/lib/fmap.h b/lib/fmap.h
new file mode 100644
index 0000000..9cea22d
--- /dev/null
+++ b/lib/fmap.h
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#ifndef FLASHMAP_LIB_FMAP_H__
+#define FLASHMAP_LIB_FMAP_H__
+
+#include <inttypes.h>
+
+#include <valstr.h>
+
+#define FMAP_SIGNATURE "__FMAP__"
+#define FMAP_VER_MAJOR 1 /* this header's FMAP minor version */
+#define FMAP_VER_MINOR 1 /* this header's FMAP minor version */
+#define FMAP_STRLEN 32 /* maximum length for strings, */
+ /* including null-terminator */
+extern const struct valstr flag_lut[16];
+enum fmap_flags {
+ FMAP_AREA_STATIC = 1 << 0,
+ FMAP_AREA_COMPRESSED = 1 << 1,
+ FMAP_AREA_RO = 1 << 2,
+};
+
+/* Mapping of volatile and static regions in firmware binary */
+struct fmap_area {
+ uint32_t offset; /* offset relative to base */
+ uint32_t size; /* size in bytes */
+ uint8_t name[FMAP_STRLEN]; /* descriptive name */
+ uint16_t flags; /* flags for this area */
+} __attribute__((packed));
+
+struct fmap {
+ uint8_t signature[8]; /* "__FMAP__" (0x5F5F464D41505F5F) */
+ uint8_t ver_major; /* major version */
+ uint8_t ver_minor; /* minor version */
+ uint64_t base; /* address of the firmware binary */
+ uint32_t size; /* size of firmware binary in bytes */
+ uint8_t name[FMAP_STRLEN]; /* name of this firmware binary */
+ uint16_t nareas; /* number of areas described by
+ fmap_areas[] below */
+ struct fmap_area areas[];
+} __attribute__((packed));
+
+/*
+ * fmap_find - find FMAP signature in a binary image
+ *
+ * @image: binary image
+ * @len: length of binary image
+ *
+ * This function does no error checking. The caller is responsible for
+ * verifying that the contents are sane.
+ *
+ * returns offset of FMAP signature to indicate success
+ * returns <0 to indicate failure
+ */
+extern long int fmap_find(const uint8_t *image, unsigned int len);
+
+/*
+ * fmap_print - Print contents of flash map data structure
+ *
+ * @map: raw map data
+ *
+ * returns 0 to indiciate success
+ * returns <0 to indicate failure
+ */
+extern int fmap_print(const struct fmap *map);
+
+/*
+ * fmap_get_csum - get the checksum of static regions of an image
+ *
+ * @image: image to checksum
+ * @len: length of image
+ * @digest: double-pointer to store location of first byte of digest
+ *
+ * fmap_get_csum() will reset, write, and finalize the digest.
+ * The location of the final digest will start at the location pointed to
+ * by digest, which will be allocated and must be freed by the caller.
+ *
+ * returns digest length if successful
+ * returns <0 to indicate error
+ */
+extern int fmap_get_csum(const uint8_t *image,
+ unsigned int image_len, uint8_t **digest);
+
+
+/*
+ * fmap_flags_to_string - convert raw flags field into user-friendly string
+ *
+ * @flags: raw flags
+ *
+ * This function returns a user-friendly comma-separated list of fmap area
+ * flags. If there are no flags (flags == 0), the string will contain only
+ * a terminating character ('\0')
+ *
+ * This function allocates memory which the caller must free.
+ *
+ * returns pointer to an allocated string if successful
+ * returns NULL to indicate failure
+ */
+char *fmap_flags_to_string(uint16_t flags);
+
+/*
+ * fmap_create - allocate and initialize a new fmap structure
+ *
+ * @base: base address of firmware within address space
+ * @size: size of the firmware (bytes)
+ * @name: name of firmware
+ *
+ * This function will allocate a flashmap header. Members of the structure
+ * which are not passed in are automatically initialized.
+ *
+ * returns pointer to newly allocated flashmap header if successful
+ * returns NULL to indicate failure
+ */
+extern struct fmap *fmap_create(uint64_t base,
+ uint32_t size, uint8_t *name);
+
+/* free memory used by an fmap structure */
+extern void fmap_destroy(struct fmap *fmap);
+
+/*
+ * fmap_size - returns size of fmap data structure (including areas)
+ *
+ * @fmap: fmap
+ *
+ * returns size of fmap structure if successful
+ * returns <0 to indicate failure
+ */
+extern int fmap_size(struct fmap *fmap);
+
+/*
+ * fmap_append_area - realloc an existing flashmap and append an area
+ *
+ * @fmap: double pointer to existing flashmap
+ * @offset: offset of area
+ * @size: size of area
+ * @name: name of area
+ * @flags: area flags
+ *
+ * returns total size of reallocated flashmap structure if successful
+ * returns <0 to indicate failure
+ */
+extern int fmap_append_area(struct fmap **fmap,
+ uint32_t offset, uint32_t size,
+ const uint8_t *name, uint16_t flags);
+
+/*
+ * fmap_find_area - find an fmap_area entry (by name) and return pointer to it
+ *
+ * @fmap: fmap structure to parse
+ * @name: name of area to find
+ *
+ * returns a pointer to the entry in the fmap structure if successful
+ * returns NULL to indicate failure or if no matching area entry is found
+ */
+extern struct fmap_area *fmap_find_area(struct fmap *fmap, const char *name);
+
+/* unit testing stuff */
+extern int fmap_test();
+
+#endif /* FLASHMAP_LIB_FMAP_H__*/
diff --git a/lib/input.h b/lib/input.h
new file mode 100644
index 0000000..7ef9e1d
--- /dev/null
+++ b/lib/input.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2011, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#ifndef FMAP_ENCODE_INPUT_H
+#define FMAP_ENCODE_INPUT_H
+
+#define MAXLEN 128 /* max length to process for input */
+enum input_types {
+ TYPE_STRING,
+ TYPE_ULL,
+};
+
+struct kv_attr {
+ char *key;
+ void *dest;
+ size_t len;
+ int (*handler)(void *dest, const char *src, size_t len);
+};
+
+/* main input API */
+extern int input_interactive(const char *outfile);
+extern int input_kv_pair(const char *infile, const char *outfile);
+
+/* unit testing stuff */
+extern int input_kv_pair_test();
+
+#endif /* FMAP_ENCODE_INPUT_H */
diff --git a/lib/input_interactive.c b/lib/input_interactive.c
new file mode 100644
index 0000000..877efe9
--- /dev/null
+++ b/lib/input_interactive.c
@@ -0,0 +1,203 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include <fmap.h>
+
+#include "input.h"
+
+/*
+ * do_prompt - Prompt a user for input, perform rudimentary sanity checking,
+ * convert to specified data type, and store up to "len" bytes in result.
+ * Conversions to unsigned types are done using strtoull() or similar.
+ *
+ * returns 0 to indicate success, <0 to indicate failure
+ */
+static int do_prompt(const char *prompt, enum input_types type,
+ void *result, size_t len)
+{
+ char buf[MAXLEN];
+ char *endptr;
+
+ printf("%s: ", prompt);
+ if (fgets(buf, sizeof(buf), stdin) == NULL) {
+ fprintf(stderr, "unable to obtain input\n");
+ return -1;
+ }
+
+ switch(type) {
+ case TYPE_ULL: {
+ unsigned long long int val;
+
+ val = strtoull(buf, &endptr, 0);
+ if ((buf == endptr) ||
+ ((unsigned int)(endptr - buf + 1) != strlen(buf))) {
+ fprintf(stderr, "invalid input detected\n");
+ return -1;
+ }
+
+ /* TODO: Add "out of range" warning? Current behavior
+ * is to silently truncate. */
+
+ memcpy(result, &val, len);
+ break;
+ }
+ case TYPE_STRING:
+ if (strlen(buf) > len) {
+ fprintf(stderr, "\"%s\" is too long\n", buf);
+ return -1;
+ }
+
+ /* replace any trailing whitespace character with terminator */
+ buf[strlen(buf) - 1] = '\0';
+ memcpy(result, buf, strlen(buf));
+ break;
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+int input_interactive(const char *filename)
+{
+ int fd, rc = EXIT_SUCCESS;
+ struct fmap *fmap = NULL;
+ int total_size, i;
+
+ fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+ if (fd < 0) {
+ fprintf(stderr, "unable to open file \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto exit_interactive_1;
+ }
+
+ if ((fmap = malloc(sizeof(*fmap))) == NULL) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_2;
+ }
+ memset(fmap, 0, sizeof(*fmap));
+
+ memcpy(&(fmap->signature), FMAP_SIGNATURE, strlen(FMAP_SIGNATURE));
+ fmap->ver_major = FMAP_VER_MAJOR;
+ fmap->ver_minor = FMAP_VER_MINOR;
+
+ if (do_prompt("binary base address", TYPE_ULL,
+ &(fmap->base), sizeof(fmap->base)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_2;
+ }
+
+ if (do_prompt("binary size", TYPE_ULL,
+ &(fmap->size), sizeof(fmap->size)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_2;
+ }
+
+ if (do_prompt("name of firmware image", TYPE_STRING,
+ &(fmap->name), FMAP_STRLEN) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_2;
+ }
+
+ if (do_prompt("number of areas", TYPE_ULL,
+ &(fmap->nareas), sizeof(fmap->nareas)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_2;
+ }
+
+ /* Add space for the FMAP areas */
+ total_size = sizeof(*fmap) + ((sizeof(fmap->areas[0])) * fmap->nareas);
+ fmap = realloc(fmap, total_size);
+
+ for (i = 0; i < fmap->nareas; i++) {
+ char prompt[32];
+
+ snprintf(prompt, sizeof(prompt), "area %d offset", i + 1);
+ if (do_prompt(prompt, TYPE_ULL,
+ &(fmap->areas[i].offset),
+ sizeof(fmap->areas[i].offset)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_3;
+ }
+
+ snprintf(prompt, sizeof(prompt), "area %d size", i + 1);
+ if (do_prompt(prompt, TYPE_ULL,
+ &(fmap->areas[i].size),
+ sizeof(fmap->areas[i].size)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_3;
+ }
+
+ snprintf(prompt, sizeof(prompt), "area %d name", i + 1);
+ if (do_prompt(prompt, TYPE_STRING,
+ &(fmap->areas[i].name),
+ sizeof(fmap->areas[i].name)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_3;
+ }
+
+ snprintf(prompt, sizeof(prompt), "area %d flags", i + 1);
+ if (do_prompt(prompt, TYPE_ULL,
+ &(fmap->areas[i].flags),
+ sizeof(fmap->areas[i].flags)) < 0) {
+ rc = EXIT_FAILURE;
+ goto exit_interactive_3;
+ }
+ }
+
+ fmap_print(fmap);
+ if (write(fd, fmap, total_size) != total_size) {
+ fprintf(stderr, "failed to write \"%s\": %s\n",
+ filename, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto exit_interactive_3;
+ }
+
+exit_interactive_3:
+ free(fmap);
+exit_interactive_2:
+ close(fd);
+exit_interactive_1:
+ return rc;
+}
diff --git a/lib/input_kv_pair.c b/lib/input_kv_pair.c
new file mode 100644
index 0000000..1e1f9ce
--- /dev/null
+++ b/lib/input_kv_pair.c
@@ -0,0 +1,643 @@
+/*
+ * Copyright 2011, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <fmap.h>
+
+#include "input.h"
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
+
+/*
+ * extract_value - Extract value from key="value" string
+ *
+ * line: string to extract value from
+ *
+ * returns allocated, NULL-terminated copy of value
+ * returns NULL to indicate failure
+ */
+static char *extract_value(const char *line, size_t len) {
+ char *val, *c;
+ int i = 0;
+
+ if (!line)
+ return NULL;
+
+ c = strchr(line, '"');
+ c++;
+
+ val = calloc(len, 1);
+ while (*c != '"') {
+ if (c == line + len) {
+ fprintf(stderr,
+ "overrun detected: missing end-quote?\n");
+ free(val);
+ val = NULL;
+ break;
+ }
+ val[i] = *c;
+ i++;
+ c++;
+ }
+
+ return val;
+}
+
+static int do_strcpy(void *dest, const char *src, size_t max_len)
+{
+ if (!dest || !src || (strlen(src) > max_len))
+ return -1;
+
+ strncpy(dest, src, strlen(src));
+ return 0;
+}
+
+static int do_memcpy(void *dest, const char *src, size_t len)
+{
+ if (!dest || !src)
+ return -1;
+
+ memcpy(dest, src, len);
+ return 0;
+}
+
+static int do_signature(void *dest, const char *src, size_t len)
+{
+ if (!dest || !src)
+ return -1;
+
+ memcpy(dest, FMAP_SIGNATURE, len);
+ return 0;
+}
+
+/*
+ * do_flags - translate strings into flag bitmap
+ *
+ * @dest: destination memory address
+ * @src: null-terminated string containing ASCII representation of flags
+ * @len: size of destination storage location
+ *
+ * returns 0 to indicate success
+ * returns <0 to indicate failure
+ */
+static int do_flags(void *dest, const char *src, size_t len)
+{
+ unsigned int i;
+ uint16_t flags = 0; /* TODO: can remove uint16_t assumption? */
+
+ if (!dest || !src)
+ return -1;
+
+ if (strlen(src) == 0) {
+ memset(dest, 0, len);
+ return 0;
+ }
+
+ for (i = 0; i < ARRAY_SIZE(flag_lut) && flag_lut[i].str; i++) {
+ if (strstr(src, flag_lut[i].str))
+ flags |= flag_lut[i].val;
+ }
+
+ memcpy(dest, &flags, len);
+ return 0;
+}
+
+/*
+ * do_strtoul - do ASCII to (unsigned) integer conversion
+ *
+ * @dest: destination memory address
+ * @src: null-terminated string containing ASCII representation of number
+ * @len: size of destination storage location
+ *
+ * returns 0 to indicate success
+ * returns <0 to indicate failure
+ */
+static int do_strtoul(void *dest, const char *src, size_t len)
+{
+ void *x;
+
+ if (!dest || !src)
+ return -1;
+
+ switch(len) {
+ case 1:
+ x = malloc(len);
+ *(uint8_t *)x = (uint8_t)strtoul(src, NULL, 0);
+ break;
+ case 2:
+ x = malloc(len);
+ *(uint16_t *)x = (uint16_t)strtoul(src, NULL, 0);
+ break;
+ case 4:
+ x = malloc(len);
+ *(uint32_t *)x = (uint32_t)strtoull(src, NULL, 0);
+ break;
+ case 8:
+ x = malloc(len);
+ *(uint64_t *)x = (uint64_t)strtoull(src, NULL, 0);
+ break;
+ default:
+ return -1;
+ }
+
+ memcpy(dest, x, len);
+ free(x);
+ return 0;
+}
+
+static int doit(const char *line,
+ struct kv_attr kv_attrs[], unsigned int num_entries)
+{
+ int rc = 0;
+ unsigned int i;
+
+ for (i = 0; i < num_entries; i++) {
+ const char *p = line;
+ char *value = NULL;
+
+ /* Ignore out partial key matches, e.g. foo= vs. foo_bar= */
+ while ((p = strstr(p, kv_attrs[i].key)) != NULL) {
+ if (*(p + strlen(kv_attrs[i].key)) == '=') {
+ break;
+ }
+ p++;
+ }
+
+ if (p == NULL) {
+ fprintf(stderr, "key \"%s\" not found, aborting\n",
+ kv_attrs[i].key);
+ rc = -1;
+ break;
+ }
+
+ /* found key, extract value from remainder of input string */
+ if (!(value = extract_value(p, strlen(p)))) {
+ fprintf(stderr,
+ "failed to extract value from \"%s\"\n", p);
+ rc = -1;
+ free(value);
+ break;
+ }
+
+ if (kv_attrs[i].handler(kv_attrs[i].dest, value, kv_attrs[i].len)) {
+ fprintf(stderr, "failed to process \"%s\"\n", value);
+ rc = -1;
+ free(value);
+ break;
+ }
+
+ free(value);
+ }
+
+ return rc;
+}
+
+static int parse_header(const char *line, struct fmap *fmap) {
+ struct kv_attr kv_attrs[] = {
+ { .key = "fmap_signature",
+ .dest = &fmap->signature,
+ .len = strlen(FMAP_SIGNATURE),
+ .handler = do_signature,
+ },
+ { .key = "fmap_ver_major",
+ .dest = &fmap->ver_major,
+ .len = sizeof(fmap->ver_major),
+ .handler = do_strtoul,
+ },
+ { .key = "fmap_ver_minor",
+ .dest = &fmap->ver_minor,
+ .len = sizeof(fmap->ver_minor),
+ .handler = do_strtoul,
+ },
+ { .key = "fmap_base",
+ .dest = &fmap->base,
+ .len = sizeof(fmap->base),
+ .handler = do_strtoul,
+ },
+ { .key = "fmap_size",
+ .dest = &fmap->size,
+ .len = sizeof(fmap->size),
+ .handler = do_strtoul,
+ },
+ { .key = "fmap_name",
+ .dest = &fmap->name,
+ .len = FMAP_STRLEN, /* treated as a maximum length */
+ .handler = do_strcpy,
+ },
+ { .key = "fmap_nareas",
+ .dest = &fmap->nareas,
+ .len = sizeof(fmap->nareas),
+ .handler = do_strtoul,
+ },
+ };
+
+ return doit(line, kv_attrs, ARRAY_SIZE(kv_attrs));
+}
+
+static int parse_area(const char *line, struct fmap_area *area) {
+ struct kv_attr kv_attrs[] = {
+ { .key = "area_offset",
+ .dest = &area->offset,
+ .len = sizeof(area->offset),
+ .handler = do_strtoul,
+ },
+ { .key = "area_size",
+ .dest = &area->size,
+ .len = sizeof(area->size),
+ .handler = do_strtoul,
+ },
+ { .key = "area_name",
+ .dest = &area->name,
+ .len = FMAP_STRLEN, /* treated as a maximum length */
+ .handler = do_strcpy,
+ },
+ { .key = "area_flags",
+ .dest = &area->flags,
+ .len = sizeof(area->flags),
+ .handler = do_flags,
+ },
+ };
+
+ return doit(line, kv_attrs, ARRAY_SIZE(kv_attrs));
+}
+
+int input_kv_pair(const char *infile, const char *outfile)
+{
+ char line[LINE_MAX];
+ FILE *fp_in, *fp_out;
+ struct fmap *fmap;
+ int area;
+ int rc = EXIT_SUCCESS;
+ size_t total_size = 0;
+
+ fp_in = fopen(infile, "r");
+ if (!fp_in) {
+ fprintf(stderr, "cannot open file \"%s\" (%s)\n",
+ infile, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto input_kv_pair_exit_1;
+ }
+
+ fp_out = fopen(outfile, "w");
+ if (!fp_out) {
+ fprintf(stderr, "cannot open file \"%s\" (%s)\n",
+ infile, strerror(errno));
+ rc = EXIT_FAILURE;
+ goto input_kv_pair_exit_1;
+ }
+
+ fmap = malloc(sizeof(*fmap));
+ if (!fmap)
+ goto input_kv_pair_exit_2;
+
+ /* assume first line contains fmap header */
+ memset(line, 0, sizeof(line));
+ if (!fgets(line, sizeof(line), fp_in) || parse_header(line, fmap)) {
+ fprintf(stderr, "failed to parse header\n");
+ rc = EXIT_FAILURE;
+ goto input_kv_pair_exit_2;
+ }
+
+ total_size = sizeof(*fmap) + (sizeof(fmap->areas[0]) * fmap->nareas);
+ fmap = realloc(fmap, total_size);
+ memset(line, 0, sizeof(line));
+ area = 0;
+ while (fgets(line, sizeof(line), fp_in)) {
+ if (parse_area(line, &fmap->areas[area])) {
+ rc = EXIT_FAILURE;
+ goto input_kv_pair_exit_2;
+ }
+ memset(line, 0, sizeof(line));
+ area++;
+ }
+
+ if (fwrite(fmap, 1, total_size, fp_out) != total_size) {
+ fprintf(stderr, "failed to write fmap binary\n");
+ rc = EXIT_FAILURE;
+ }
+
+input_kv_pair_exit_2:
+ free(fmap);
+ fclose(fp_in);
+ fclose(fp_out);
+input_kv_pair_exit_1:
+ return rc;
+}
+
+/*
+ * LCOV_EXCL_START
+ * Unit testing stuff done here so we do not need to expose static functions.
+ */
+
+static int extract_value_test() {
+ int rc = 0, len = 512;
+ char kv[len];
+ char *ret;
+
+ if (extract_value(NULL, 0)) {
+ printf("FAILURE: extract_value_test NULL case not "
+ "handled properly\n");
+ rc |= 1;
+ }
+
+ /* normal case */
+ sprintf(kv, "foo=\"bar\"");
+ ret = extract_value(kv, len);
+ if (strcmp(ret, "bar")) {
+ printf("FAILURE: \"%s\" != \"%s\"\n", ret, "bar");
+ rc |= 1;
+ }
+ free(ret);
+
+ /* missing end quote */
+ memset(kv, 0, sizeof(kv));
+ sprintf(kv, "foo=\"bar");
+ ret = extract_value(kv, len);
+ if (ret) {
+ printf("FAILURE: missing end-quote not caught\n");
+ rc |= 1;
+ }
+
+ return rc;
+}
+
+static int trivial_helper_function_tests() {
+ int rc = 0, len = 512;
+ int tmp;
+ char dest[len], src[len];
+
+ /*
+ * do_strcpy
+ */
+ sprintf(src, "hello world");
+ do_strcpy(dest, src, len);
+ if (strncmp(dest, src, strlen(src))) {
+ printf("FAILURE: do_strcpy failed\n");
+ rc |= 1;
+ }
+
+ if ((do_strcpy(NULL, src, strlen(src)) == 0) ||
+ (do_strcpy(dest, NULL, strlen(src)) == 0)) {
+ printf("FAILURE: do_strcpy NULL case not handled properly\n");
+ rc |= 1;
+ }
+
+ /* length of src exceeds max length */
+ tmp = do_strcpy(dest, src, strlen(src) - 1);
+ if (!tmp) {
+ printf("FAILURE: do_strcpy failed to catch overrun\n");
+ rc |= 1;
+ }
+
+ /*
+ * do_memcpy
+ */
+ if ((do_memcpy(NULL, src, strlen(src)) == 0) ||
+ (do_memcpy(dest, NULL, strlen(src)) == 0)) {
+ printf("FAILURE: do_memcpy NULL case not handled properly\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "hello world");
+ do_memcpy(dest, src, len);
+ if (memcmp(dest, src, strlen(src))) {
+ printf("FAILURE: do_memcpy failed\n");
+ rc |= 1;
+ }
+
+ /*
+ * do_signature
+ */
+ if ((do_signature(NULL, src, strlen(src)) == 0) ||
+ (do_signature(dest, NULL, strlen(src)) == 0)) {
+ printf("FAILURE: do_signature NULL case not handled properly\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "hello world");
+ do_signature(dest, src, strlen(FMAP_SIGNATURE));
+ if (strncmp(dest, FMAP_SIGNATURE, strlen(FMAP_SIGNATURE))) {
+ printf("FAILURE: do_signature failed\n");
+ rc |= 1;
+ }
+
+ return rc;
+}
+
+static int do_strtoul_test() {
+ int rc = 0;
+ uint8_t dest_8;
+ uint16_t dest_16;
+ uint32_t dest_32;
+ uint64_t dest_64;
+ char src[32];
+
+ sprintf(src, "0xff");
+ do_strtoul(&dest_8, src, 1);
+ if (dest_8 != 0xff) {
+ printf("FAILURE: do_strtoul failed to convert a uint8_t\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "0xffff");
+ do_strtoul(&dest_16, src, 2);
+ if (dest_16 != 0xffff) {
+ printf("FAILURE: do_strtoul failed to convert a uint16_t\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "0xffffffff");
+ do_strtoul(&dest_32, src, 4);
+ if (dest_32 != 0xffffffff) {
+ printf("FAILURE: do_strtoul failed to convert a uint32_t\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "0xffffffffffffffff");
+ do_strtoul(&dest_64, src, 8);
+ if (dest_64 != 0xffffffffffffffffULL) {
+ printf("FAILURE: do_strtoul failed to convert a uint64_t\n");
+ rc |= 1;
+ }
+
+ /* invalid length */
+ if (!do_strtoul(&dest_8, src, 3)) {
+ printf("FAILURE: do_strtoul returned 0 on bad length\n");
+ rc |= 1;
+ }
+
+ sprintf(src, "0xff");
+ if ((do_strtoul(NULL, src, 1) == 0) ||
+ (do_strtoul(&dest_8, NULL, strlen(src)) == 0)) {
+ printf("FAILURE: do_strtoul NULL case not handled properly\n");
+ rc |= 1;
+ }
+
+ return rc;
+}
+
+static int do_flags_test() {
+ int rc = 0;
+ unsigned int i;
+ uint16_t dest, tmp;
+ char src[512];
+
+ if ((do_flags(NULL, src, strlen(src)) == 0) ||
+ (do_flags(&dest, NULL, strlen(src)) == 0)) {
+ printf("FAILURE: do_flags NULL case not handled properly\n");
+ rc |= 1;
+ }
+
+ /* convert each flag individually */
+ for (i = 0; i < ARRAY_SIZE(flag_lut) && flag_lut[i].str; i++) {
+ do_flags(&dest, flag_lut[i].str, strlen(flag_lut[i].str));
+ if (dest != str2val(flag_lut[i].str, flag_lut)) {
+ printf("FAILURE: do_flags failed to convert %s\n",
+ flag_lut[i].str);
+ rc |= 1;
+ };
+ }
+
+ /* place all flags in a single string */
+ memset(src, 0, sizeof(src));
+ tmp = 0;
+ for (i = 0; i < ARRAY_SIZE(flag_lut) && flag_lut[i].str; i++) {
+ /* prepend a comma before adding this entry */
+ if (i != 0 && flag_lut[i - 1].str)
+ strcat(src, ",");
+
+ strcat(src, flag_lut[i].str);
+ tmp |= flag_lut[i].val;
+
+ }
+
+ do_flags(&dest, src, strlen(src));
+ if (dest != tmp) {
+ printf("FAILURE: do_flags %04x != %04x, src: %s\n",
+ dest, tmp, src);
+ rc |= 1;
+ }
+
+ if (do_flags(&dest, "", sizeof(dest))) {
+ printf("FAILURE: do_flags failed to catch zero-length src\n");
+ rc |= 1;
+ }
+
+ return rc;
+}
+
+static int dummy_handler(void *dest, const char *src, size_t max_len)
+{
+ return -1;
+}
+
+static int doit_test() {
+ int rc = 0;
+ char line[LINE_MAX], dest[LINE_MAX];
+ struct fmap fmap;
+ struct fmap_area fmap_area;
+ struct kv_attr attr[] = {
+ { .key = "foo",
+ .dest = &dest,
+ .len = LINE_MAX,
+ .handler = do_strcpy,
+ },
+ };
+
+ /* parse a valid header line */
+ sprintf(line, "fmap_signature=\"0x5f5f50414d465f5f\" "
+ "fmap_ver_major=\"1\" fmap_ver_minor=\"0\" "
+ "fmap_base=\"0x00000000ffe00000\" fmap_size=\"0x200000\" "
+ "fmap_name=\"System BIOS\" fmap_nareas=\"4\"");
+ rc |= parse_header(line, &fmap);
+
+ /* parse a valid fmap area line */
+ sprintf(line, "area_offset=\"0x00040000\" area_size=\"0x00180000\" "
+ "area_name=\"FV_MAIN\" area_flags=\"static,compressed\"");
+ rc |= parse_area(line, &fmap_area);
+
+ /* partially matched key should be ignored */
+ sprintf(line, "foo_bar=\"foobar\" foo=\"bar\"");
+ if (doit(line, attr, 1) || strcmp(attr[0].dest, "bar")) {
+ printf("FAILURE: doit failed to ignore partial key match "
+ "(expected \"bar\", got \"%s\")\n",(char *)attr[0].dest);
+ rc |= 1;
+ }
+
+ /* nonexitent key */
+ sprintf(line, "nonexistent=\"value\"");
+ if (doit(line, attr, 1) == 0) {
+ printf("FAILURE: doit returned false positive\n");
+ rc |= 1;
+ }
+
+ /* bad value (missing end quote) */
+ sprintf(line, "foo=\"bar");
+ if (doit(line, attr, 1) == 0) {
+ printf("FAILURE: doit did not catch bad key\n");
+ rc |= 1;
+ }
+
+ /* handler failure */
+ sprintf(line, "foo=\"bar\"");
+ attr[0].handler = dummy_handler;
+ if (doit(line, attr, 1) == 0) {
+ printf("FAILURE: handler should have failed\n");
+ rc |= 1;
+ }
+
+ return rc;
+}
+
+int input_kv_pair_test()
+{
+ int rc = EXIT_SUCCESS;
+
+ rc |= extract_value_test();
+ rc |= trivial_helper_function_tests();
+ rc |= do_strtoul_test();
+ rc |= do_flags_test();
+ rc |= doit_test();
+
+ if (rc)
+ printf("FAILED\n");
+ return rc;
+}
+/* LCOV_EXCL_STOP */
diff --git a/lib/kv_pair.c b/lib/kv_pair.c
new file mode 100644
index 0000000..2572c64
--- /dev/null
+++ b/lib/kv_pair.c
@@ -0,0 +1,242 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "kv_pair.h"
+
+/* Internal variable for output style. Use accessors to get/set style. */
+static enum kv_pair_style _style;
+
+void kv_pair_set_style(enum kv_pair_style style)
+{
+ _style = style;
+}
+
+enum kv_pair_style kv_pair_get_style()
+{
+ return _style;
+}
+
+struct kv_pair *kv_pair_new(void)
+{
+ struct kv_pair *kv;
+
+ kv = calloc(0, sizeof(*kv));
+ if (!kv)
+ return NULL;
+
+ return kv;
+}
+
+struct kv_pair **kv_pair_new_array(size_t size)
+{
+ struct kv_pair **kv;
+ size_t i;
+
+ kv = (struct kv_pair **) calloc(0, sizeof(kv) * size);
+ for (i = 0; i < size; ++i) {
+ kv[i] = kv_pair_new();
+ }
+ return kv;
+}
+
+struct kv_pair *kv_pair_add(struct kv_pair *kv_list,
+ const char *key, const char *value)
+{
+ struct kv_pair *kv_new;
+ struct kv_pair *kv_ptr;
+
+ kv_new = kv_pair_new();
+ if (!kv_new)
+ return NULL;
+
+ /* save key=value strings if provided */
+ if (key) {
+ kv_new->key = strdup(key);
+ if (!kv_new->key)
+ goto kv_pair_add_failed;
+ }
+ if (value) {
+ kv_new->value = strdup(value);
+ if (!kv_new->value)
+ goto kv_pair_add_failed;
+ }
+
+ /* first in the list if no list provided */
+ if (kv_list) {
+ /* find the end of list */
+ for (kv_ptr = kv_list; kv_ptr->next != NULL;
+ kv_ptr = kv_ptr->next)
+ ;
+
+ /* link in the new pair at the end */
+ kv_ptr->next = kv_new;
+ }
+
+ /* return pointer to the new pair */
+ return kv_new;
+
+kv_pair_add_failed:
+ kv_pair_free(kv_new);
+ return NULL;
+}
+
+struct kv_pair *kv_pair_add_bool(struct kv_pair *kv_list,
+ const char *key, int value)
+{
+ const char *str;
+
+ if (value) {
+ str = "yes";
+ } else {
+ str = "no";
+ }
+ return kv_pair_add(kv_list, key, str);
+}
+
+struct kv_pair *kv_pair_fmt(struct kv_pair *kv_list,
+ const char *kv_key, const char *format, ...)
+{
+ char kv_value[KV_PAIR_MAX_VALUE_LEN];
+ va_list vptr;
+
+ memset(kv_value, 0, sizeof(kv_value));
+
+ va_start(vptr, format);
+ vsnprintf(kv_value, sizeof(kv_value), format, vptr);
+ va_end(vptr);
+
+ return kv_pair_add(kv_list, kv_key, kv_value);
+}
+
+void kv_pair_free(struct kv_pair *kv_list)
+{
+ struct kv_pair *kv_ptr = kv_list;
+ struct kv_pair *kv_next;
+
+ while (kv_ptr != NULL) {
+ /* free key/value strings */
+ if (kv_ptr->key)
+ free(kv_ptr->key);
+ if (kv_ptr->value)
+ free(kv_ptr->value);
+
+ /* free current pair move to next */
+ kv_next = kv_ptr->next;
+ free(kv_ptr);
+ kv_ptr = kv_next;
+ }
+}
+
+void kv_pair_free_array(struct kv_pair **kv_array, size_t size)
+{
+ size_t i;
+ for (i = 0; i < size; ++i) {
+ kv_pair_free(kv_array[i]);
+ }
+ free(kv_array);
+}
+
+void kv_pair_print_to_file(FILE* fp, struct kv_pair *kv_list,
+ enum kv_pair_style style)
+{
+ struct kv_pair *kv_ptr;
+
+ switch (style) {
+ case KV_STYLE_PAIR:
+ for (kv_ptr = kv_list; kv_ptr != NULL; kv_ptr = kv_ptr->next) {
+ if (kv_ptr->key && kv_ptr->value) {
+ fprintf(fp, "%s=\"%s\" ",
+ kv_ptr->key, kv_ptr->value);
+ }
+ }
+ break;
+
+ case KV_STYLE_VALUE:
+ for (kv_ptr = kv_list; kv_ptr != NULL; kv_ptr = kv_ptr->next) {
+ if (kv_ptr->value) {
+ fprintf(fp, "%s", kv_ptr->value);
+ if (kv_ptr->next)
+ fprintf(fp, " | ");
+ }
+ }
+ break;
+
+ case KV_STYLE_LONG:
+ for (kv_ptr = kv_list; kv_ptr != NULL; kv_ptr = kv_ptr->next) {
+ if (kv_ptr->key && kv_ptr->value)
+ fprintf(fp, "%-20s | %s\n",
+ kv_ptr->key, kv_ptr->value);
+ }
+ break;
+ }
+
+ fprintf(fp, "\n");
+}
+
+void kv_pair_print(struct kv_pair *kv_list)
+{
+ kv_pair_print_to_file(stdout, kv_list, kv_pair_get_style());
+}
+
+const char *kv_pair_get_value(struct kv_pair *kv_list, const char *kv_key)
+{
+ const char *kv_value = NULL;
+ struct kv_pair *kv_ptr;
+
+ for (kv_ptr = kv_list; kv_ptr != NULL; kv_ptr = kv_ptr->next) {
+ if (kv_ptr->key && strcmp(kv_ptr->key, kv_key) == 0) {
+ kv_value = kv_ptr->value;
+ break;
+ }
+ }
+ return kv_value;
+}
+
+int kv_pair_size(struct kv_pair *kv_list) {
+ struct kv_pair *kv_ptr;
+ int count;
+
+ count = 0;
+ for (kv_ptr = kv_list; kv_ptr != NULL; kv_ptr = kv_ptr->next) {
+ if (kv_ptr->key) {
+ count++;
+ }
+ }
+ return count;
+}
diff --git a/lib/kv_pair.h b/lib/kv_pair.h
new file mode 100644
index 0000000..b573530
--- /dev/null
+++ b/lib/kv_pair.h
@@ -0,0 +1,153 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ */
+
+#ifndef FLASHMAP_LIB_KV_PAIR_H__
+#define FLASHMAP_LIB_KV_PAIR_H__
+
+#include <stdio.h>
+#include <inttypes.h>
+#include <string.h>
+
+/* key=value string pair list */
+#define KV_PAIR_MAX_VALUE_LEN 1024
+
+enum kv_pair_style {
+ KV_STYLE_PAIR, /* key1="value1" key2="value2" */
+ KV_STYLE_VALUE, /* | value1 | value2 | */
+ KV_STYLE_LONG, /* key1 | value1 */
+ /* key2 | value2 */
+};
+
+struct kv_pair {
+ char *key;
+ char *value;
+ struct kv_pair *next;
+};
+
+extern enum kv_pair_style kv_pair_get_style();
+
+extern void kv_pair_set_style(enum kv_pair_style style);
+
+/*
+ * kv_pair_new - create new key=value pair
+ *
+ * returns pointer to new key=value pair
+ * returns NULL to indicate error
+ */
+extern struct kv_pair *kv_pair_new(void);
+
+/*
+ * kv_pair_add - add new key=value pair to list
+ *
+ * @kv_list: key=value pair list
+ * @key: key string
+ * @value: value string
+ *
+ * returns pointer to new key=value pair
+ * returns NULL to indicate error
+ */
+extern struct kv_pair *kv_pair_add(struct kv_pair *kv_list,
+ const char *key, const char *value);
+
+/*
+ * kv_pair_add_bool - add new boolean kvpair to list
+ *
+ * @kv_list: key=value pair list
+ * @key: key string
+ * @value: value
+ *
+ * returns pointer to new key=value pair
+ * returns NULL to indicate error
+ */
+extern struct kv_pair *kv_pair_add_bool(struct kv_pair *kv_list,
+ const char *key, int value);
+
+/*
+ * kv_pair_fmt - add key=value pair based on printf format
+ * NOTE: uses variable argument list
+ *
+ * @kv_list: list of key=value pairs
+ * @kv_key: key string
+ * @format: printf-style format for value input
+ * @...: arguments to format
+ *
+ * returns pointer to new key=value pair
+ * returns NULL to indicate error
+ */
+extern struct kv_pair *kv_pair_fmt(struct kv_pair *kv_list,
+ const char *kv_key, const char *format, ...)
+ __attribute__((format(printf, 3, 4)));
+
+/*
+ * kv_pair_free - clean a key=value pair list
+ *
+ * @kv_list: pointer to key=value list
+ */
+extern void kv_pair_free(struct kv_pair *kv_list);
+
+/*
+ * kv_pair_print - print a key=value pair list
+ *
+ * @kv_list: pointer to key=value list
+ * @style: print style
+ */
+extern void kv_pair_print_to_file(FILE* fp, struct kv_pair *kv_list,
+ enum kv_pair_style style);
+
+/*
+ * kv_pair_print - print a key=value pair list to gsys output
+ *
+ * @kv_list: pointer to key=value list
+ */
+extern void kv_pair_print(struct kv_pair *kv_list);
+
+
+/*
+ * kv_pair_get_value - return first value with key match
+ *
+ * @kv_list: pointer to key=value list
+ * @kv_key: key string
+ */
+extern const char *kv_pair_get_value(struct kv_pair *kv_list,
+ const char *kv_key);
+
+/*
+ * kv_pair_size - return number of kv pairs in the chain
+ *
+ * @kv_list: pointer to key=value list
+ */
+extern int kv_pair_size(struct kv_pair *kv_list);
+
+#endif /* FLASHMAP_LIB_KV_PAIR_H__ */
diff --git a/lib/mincrypt/Makefile b/lib/mincrypt/Makefile
new file mode 100644
index 0000000..6229ec0
--- /dev/null
+++ b/lib/mincrypt/Makefile
@@ -0,0 +1,41 @@
+# 2010, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Alternatively, this software may be distributed under the terms of the
+# GNU General Public License ("GPL") version 2 as published by the Free
+# Software Foundation.
+
+all: sha.o
+
+.PHONY: clean
+clean:
+ rm -f *.o *.a
+
+%.o: %.c
+ $(CC) $(CFLAGS) -c $^ -I. -o $@
diff --git a/lib/mincrypt/sha.c b/lib/mincrypt/sha.c
new file mode 100644
index 0000000..a8beb00
--- /dev/null
+++ b/lib/mincrypt/sha.c
@@ -0,0 +1,307 @@
+/* sha.c
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in the
+** documentation and/or other materials provided with the distribution.
+** * Neither the name of Google Inc. nor the names of its contributors may
+** be used to endorse or promote products derived from this software
+** without specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
+** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "sha.h"
+
+// Some machines lack byteswap.h and endian.h. These have to use the
+// slower code, even if they're little-endian.
+
+#if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
+
+#include <byteswap.h>
+#include <memory.h>
+
+// This version is about 28% faster than the generic version below,
+// but assumes little-endianness.
+
+static inline uint32_t ror27(uint32_t val) {
+ return (val >> 27) | (val << 5);
+}
+static inline uint32_t ror2(uint32_t val) {
+ return (val >> 2) | (val << 30);
+}
+static inline uint32_t ror31(uint32_t val) {
+ return (val >> 31) | (val << 1);
+}
+
+static void SHA1_Transform(SHA_CTX* ctx) {
+ uint32_t W[80];
+ register uint32_t A, B, C, D, E;
+ int t;
+
+ A = ctx->state[0];
+ B = ctx->state[1];
+ C = ctx->state[2];
+ D = ctx->state[3];
+ E = ctx->state[4];
+
+#define SHA_F1(A,B,C,D,E,t) \
+ E += ror27(A) + \
+ (W[t] = bswap_32(ctx->buf.w[t])) + \
+ (D^(B&(C^D))) + 0x5A827999; \
+ B = ror2(B);
+
+ for (t = 0; t < 15; t += 5) {
+ SHA_F1(A,B,C,D,E,t + 0);
+ SHA_F1(E,A,B,C,D,t + 1);
+ SHA_F1(D,E,A,B,C,t + 2);
+ SHA_F1(C,D,E,A,B,t + 3);
+ SHA_F1(B,C,D,E,A,t + 4);
+ }
+ SHA_F1(A,B,C,D,E,t + 0); // 16th one, t == 15
+
+#undef SHA_F1
+
+#define SHA_F1(A,B,C,D,E,t) \
+ E += ror27(A) + \
+ (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) + \
+ (D^(B&(C^D))) + 0x5A827999; \
+ B = ror2(B);
+
+ SHA_F1(E,A,B,C,D,t + 1);
+ SHA_F1(D,E,A,B,C,t + 2);
+ SHA_F1(C,D,E,A,B,t + 3);
+ SHA_F1(B,C,D,E,A,t + 4);
+
+#undef SHA_F1
+
+#define SHA_F2(A,B,C,D,E,t) \
+ E += ror27(A) + \
+ (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) + \
+ (B^C^D) + 0x6ED9EBA1; \
+ B = ror2(B);
+
+ for (t = 20; t < 40; t += 5) {
+ SHA_F2(A,B,C,D,E,t + 0);
+ SHA_F2(E,A,B,C,D,t + 1);
+ SHA_F2(D,E,A,B,C,t + 2);
+ SHA_F2(C,D,E,A,B,t + 3);
+ SHA_F2(B,C,D,E,A,t + 4);
+ }
+
+#undef SHA_F2
+
+#define SHA_F3(A,B,C,D,E,t) \
+ E += ror27(A) + \
+ (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) + \
+ ((B&C)|(D&(B|C))) + 0x8F1BBCDC; \
+ B = ror2(B);
+
+ for (; t < 60; t += 5) {
+ SHA_F3(A,B,C,D,E,t + 0);
+ SHA_F3(E,A,B,C,D,t + 1);
+ SHA_F3(D,E,A,B,C,t + 2);
+ SHA_F3(C,D,E,A,B,t + 3);
+ SHA_F3(B,C,D,E,A,t + 4);
+ }
+
+#undef SHA_F3
+
+#define SHA_F4(A,B,C,D,E,t) \
+ E += ror27(A) + \
+ (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) + \
+ (B^C^D) + 0xCA62C1D6; \
+ B = ror2(B);
+
+ for (; t < 80; t += 5) {
+ SHA_F4(A,B,C,D,E,t + 0);
+ SHA_F4(E,A,B,C,D,t + 1);
+ SHA_F4(D,E,A,B,C,t + 2);
+ SHA_F4(C,D,E,A,B,t + 3);
+ SHA_F4(B,C,D,E,A,t + 4);
+ }
+
+#undef SHA_F4
+
+ ctx->state[0] += A;
+ ctx->state[1] += B;
+ ctx->state[2] += C;
+ ctx->state[3] += D;
+ ctx->state[4] += E;
+}
+
+void SHA_update(SHA_CTX* ctx, const void* data, int len) {
+ int i = ctx->count % sizeof(ctx->buf);
+ const uint8_t* p = (const uint8_t*)data;
+
+ ctx->count += len;
+
+ while (len > sizeof(ctx->buf) - i) {
+ memcpy(&ctx->buf.b[i], p, sizeof(ctx->buf) - i);
+ len -= sizeof(ctx->buf) - i;
+ p += sizeof(ctx->buf) - i;
+ SHA1_Transform(ctx);
+ i = 0;
+ }
+
+ while (len--) {
+ ctx->buf.b[i++] = *p++;
+ if (i == sizeof(ctx->buf)) {
+ SHA1_Transform(ctx);
+ i = 0;
+ }
+ }
+}
+
+
+const uint8_t* SHA_final(SHA_CTX* ctx) {
+ uint64_t cnt = ctx->count * 8;
+ int i;
+
+ SHA_update(ctx, (uint8_t*)"\x80", 1);
+ while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
+ SHA_update(ctx, (uint8_t*)"\0", 1);
+ }
+ for (i = 0; i < 8; ++i) {
+ uint8_t tmp = cnt >> ((7 - i) * 8);
+ SHA_update(ctx, &tmp, 1);
+ }
+
+ for (i = 0; i < 5; i++) {
+ ctx->buf.w[i] = bswap_32(ctx->state[i]);
+ }
+
+ return ctx->buf.b;
+}
+
+#else // #if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
+
+#define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits))))
+
+static void SHA1_transform(SHA_CTX *ctx) {
+ uint32_t W[80];
+ uint32_t A, B, C, D, E;
+ uint8_t *p = ctx->buf;
+ int t;
+
+ for(t = 0; t < 16; ++t) {
+ uint32_t tmp = *p++ << 24;
+ tmp |= *p++ << 16;
+ tmp |= *p++ << 8;
+ tmp |= *p++;
+ W[t] = tmp;
+ }
+
+ for(; t < 80; t++) {
+ W[t] = rol(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
+ }
+
+ A = ctx->state[0];
+ B = ctx->state[1];
+ C = ctx->state[2];
+ D = ctx->state[3];
+ E = ctx->state[4];
+
+ for(t = 0; t < 80; t++) {
+ uint32_t tmp = rol(5,A) + E + W[t];
+
+ if (t < 20)
+ tmp += (D^(B&(C^D))) + 0x5A827999;
+ else if ( t < 40)
+ tmp += (B^C^D) + 0x6ED9EBA1;
+ else if ( t < 60)
+ tmp += ((B&C)|(D&(B|C))) + 0x8F1BBCDC;
+ else
+ tmp += (B^C^D) + 0xCA62C1D6;
+
+ E = D;
+ D = C;
+ C = rol(30,B);
+ B = A;
+ A = tmp;
+ }
+
+ ctx->state[0] += A;
+ ctx->state[1] += B;
+ ctx->state[2] += C;
+ ctx->state[3] += D;
+ ctx->state[4] += E;
+}
+
+void SHA_update(SHA_CTX *ctx, const void *data, int len) {
+ int i = ctx->count % sizeof(ctx->buf);
+ const uint8_t* p = (const uint8_t*)data;
+
+ ctx->count += len;
+
+ while (len--) {
+ ctx->buf[i++] = *p++;
+ if (i == sizeof(ctx->buf)) {
+ SHA1_transform(ctx);
+ i = 0;
+ }
+ }
+}
+const uint8_t *SHA_final(SHA_CTX *ctx) {
+ uint8_t *p = ctx->buf;
+ uint64_t cnt = ctx->count * 8;
+ int i;
+
+ SHA_update(ctx, (uint8_t*)"\x80", 1);
+ while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
+ SHA_update(ctx, (uint8_t*)"\0", 1);
+ }
+ for (i = 0; i < 8; ++i) {
+ uint8_t tmp = cnt >> ((7 - i) * 8);
+ SHA_update(ctx, &tmp, 1);
+ }
+
+ for (i = 0; i < 5; i++) {
+ uint32_t tmp = ctx->state[i];
+ *p++ = tmp >> 24;
+ *p++ = tmp >> 16;
+ *p++ = tmp >> 8;
+ *p++ = tmp >> 0;
+ }
+
+ return ctx->buf;
+}
+
+#endif // endianness
+
+void SHA_init(SHA_CTX* ctx) {
+ ctx->state[0] = 0x67452301;
+ ctx->state[1] = 0xEFCDAB89;
+ ctx->state[2] = 0x98BADCFE;
+ ctx->state[3] = 0x10325476;
+ ctx->state[4] = 0xC3D2E1F0;
+ ctx->count = 0;
+}
+
+/* Convenience function */
+const uint8_t* SHA(const void *data, int len, uint8_t *digest) {
+ const uint8_t *p;
+ int i;
+ SHA_CTX ctx;
+ SHA_init(&ctx);
+ SHA_update(&ctx, data, len);
+ p = SHA_final(&ctx);
+ for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
+ digest[i] = *p++;
+ }
+ return digest;
+}
diff --git a/lib/mincrypt/sha.h b/lib/mincrypt/sha.h
new file mode 100644
index 0000000..af63e87
--- /dev/null
+++ b/lib/mincrypt/sha.h
@@ -0,0 +1,63 @@
+/* sha.h
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in the
+** documentation and/or other materials provided with the distribution.
+** * Neither the name of Google Inc. nor the names of its contributors may
+** be used to endorse or promote products derived from this software
+** without specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
+** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef _EMBEDDED_SHA_H_
+#define _EMBEDDED_SHA_H_
+
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct SHA_CTX {
+ uint64_t count;
+ uint32_t state[5];
+#if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
+ union {
+ uint8_t b[64];
+ uint32_t w[16];
+ } buf;
+#else
+ uint8_t buf[64];
+#endif
+} SHA_CTX;
+
+void SHA_init(SHA_CTX* ctx);
+void SHA_update(SHA_CTX* ctx, const void* data, int len);
+const uint8_t* SHA_final(SHA_CTX* ctx);
+
+/* Convenience method. Returns digest parameter value. */
+const uint8_t* SHA(const void* data, int len, uint8_t* digest);
+
+#define SHA_DIGEST_SIZE 20
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/lib/valstr.c b/lib/valstr.c
new file mode 100644
index 0000000..fa9ed82
--- /dev/null
+++ b/lib/valstr.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <valstr.h>
+
+const char *val2str_default(uint32_t val, const struct valstr *vs,
+ const char *def_str)
+{
+ int i;
+
+ for (i = 0; vs[i].str; i++) {
+ if (vs[i].val == val)
+ return vs[i].str;
+ }
+
+ return def_str;
+}
+
+const char *val2str(uint32_t val, const struct valstr *vs)
+{
+ return val2str_default(val, vs, "Unknown");
+}
+
+uint32_t str2val(const char *str, const struct valstr *vs)
+{
+ int i;
+
+ for (i = 0; vs[i].str; i++) {
+ if (strcasecmp(vs[i].str, str) == 0)
+ return vs[i].val;
+ }
+
+ return vs[i].val;
+}
diff --git a/lib/valstr.h b/lib/valstr.h
new file mode 100644
index 0000000..3885ef7
--- /dev/null
+++ b/lib/valstr.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2010, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef FLASHMAP_LIB_VALSTR_H__
+#define FLASHMAP_LIB_VALSTR_H__
+
+#include <inttypes.h>
+
+/* value + string structure for common conversions */
+struct valstr {
+ uint32_t val; /* field value */
+ const char *str; /* field description */
+};
+
+/*
+ * val2str_default - convert value to string
+ *
+ * @val: value to convert
+ * @vs: value-string data
+ * @def_str: default string to return if no matching value found
+ *
+ * returns pointer to string
+ * returns def_str if no matching value found
+ */
+const char *val2str_default(uint32_t val, const struct valstr *vs,
+ const char *def_str);
+
+/*
+ * val2str - convert value to string
+ *
+ * @val: value to convert
+ * @vs: value-string data
+ *
+ * returns pointer to string
+ * returns pointer to "unknown" static string if not found
+ */
+const char *val2str(uint32_t val, const struct valstr *vs);
+
+/*
+ * str2val - convert string to value
+ *
+ * @str: string to convert
+ * @vs: value-string data
+ *
+ * returns value for string
+ * returns value for last entry in value-string data if not found
+ */
+uint32_t str2val(const char *str, const struct valstr *vs);
+
+#endif /* FLASHMAP_LIB_VALSTR_H__ */
diff --git a/libfmap_example.c b/libfmap_example.c
new file mode 100644
index 0000000..422967b
--- /dev/null
+++ b/libfmap_example.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2011, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * libfmap_example: Simple example for creating a flashmap.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include <fmap.h>
+
+/* stuff that should be passed in by higher-level logic, ie firmware build
+ * system, parsed from a config file, etc. */
+#define FMAP_BASE 0xfc000000
+#define FMAP_NAME "x86_BIOS"
+#define FMAP_SIZE (4096 * 1024)
+
+int main(int argc, char *argv[])
+{
+ int fd, rc = EXIT_FAILURE;
+ struct fmap *fmap = NULL;
+ size_t total_size;
+ const char *filename;
+
+ if (argc != 2) {
+ printf("%s: Create fmap binary using example code\n", argv[0]);
+ printf("Usage: %s <filename>\n", argv[0]);
+ goto exit_1;
+ }
+
+ filename = argv[1];
+ fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+ if (fd < 0) {
+ fprintf(stderr, "unable to open file \"%s\": %s\n",
+ filename, strerror(errno));
+ goto exit_1;
+ }
+
+ fmap = fmap_create(FMAP_BASE, FMAP_SIZE, (uint8_t *)FMAP_NAME);
+ if (!fmap) {
+ fprintf(stderr, "unable to initialize fmap\n");
+ goto exit_2;
+ }
+
+ if (fmap_append_area(&fmap, FMAP_BASE, 0x100,
+ (const uint8_t *)"area_1",
+ FMAP_AREA_STATIC) < 0)
+ goto exit_3;
+ if (fmap_append_area(&fmap, FMAP_BASE + 0x100, 0x100,
+ (const uint8_t *)"area_2",
+ FMAP_AREA_COMPRESSED) < 0)
+ goto exit_3;
+ if (fmap_append_area(&fmap, FMAP_BASE + 0x200, 0x100,
+ (const uint8_t *)"area_3",
+ FMAP_AREA_RO) < 0)
+ goto exit_3;
+ if (fmap_append_area(&fmap, FMAP_BASE + 0x300, 0x100,
+ (const uint8_t *)"area_4",
+ FMAP_AREA_COMPRESSED | FMAP_AREA_RO) <0)
+ goto exit_3;
+
+ fmap_print(fmap);
+ total_size = fmap_size(fmap);
+ if (write(fd, fmap, total_size) != total_size) {
+ fprintf(stderr, "failed to write \"%s\": %s\n",
+ filename, strerror(errno));
+ goto exit_3;
+ }
+
+ rc = EXIT_SUCCESS;
+exit_3:
+ fmap_destroy(fmap);
+exit_2:
+ close(fd);
+exit_1:
+ return rc;
+}