Clean up building code coverage

Now 'COV=1 make' will make coverage automagically.

Coverage stats are reported separately for the firmware subdirectory,
for easier tracking.

BUG=chromium-os:38139
BRANCH=none
TEST='COV=1 make' then browse to build/coverage/index.html

Change-Id: Ie671a82b402beeb17882536f89b9230821fc4d13
Signed-off-by: Randall Spangler <rspangler@chromium.org>
Reviewed-on: https://gerrit.chromium.org/gerrit/41824
diff --git a/Makefile b/Makefile
index 8f4b9f8..bb5b91c 100644
--- a/Makefile
+++ b/Makefile
@@ -103,11 +103,12 @@
 # Create / use dependency files
 CFLAGS += -MMD -MF $@.d
 
-# Code coverage. Run like this:  COV=1 make runtests coverage
+# Code coverage
 ifneq (${COV},)
-COV_FLAGS = -O0 --coverage
-CFLAGS += ${COV_FLAGS}
-LDFLAGS += ${COV_FLAGS}
+  COV_FLAGS = -O0 --coverage
+  CFLAGS += ${COV_FLAGS}
+  LDFLAGS += ${COV_FLAGS}
+  COV_INFO = ${BUILD}/coverage.info
 endif
 
 # And a few more default utilities
@@ -505,7 +506,7 @@
 
 # Default target.
 .PHONY: all
-all: fwlib $(if ${FIRMWARE_ARCH},,host_stuff)
+all: fwlib $(if ${FIRMWARE_ARCH},,host_stuff) $(if ${COV},coverage)
 
 # Host targets
 .PHONY: host_stuff
@@ -522,17 +523,6 @@
 .PHONY: install
 install: cgpt_install utils_install futil_install
 
-# Coverage
-# TODO: only if COV=1
-# HEY - depend on runtests?
-COV_INFO = ${BUILD}/coverage.info
-.PHONY: coverage
-coverage:
-	rm -f ${COV_INFO}*
-	lcov --capture --directory . --base-directory . -o ${COV_INFO}.1
-	lcov --remove ${COV_INFO}.1 '/usr/*' -o ${COV_INFO}
-	genhtml ${COV_INFO} --output-directory ${BUILD}/coverage
-
 # Don't delete intermediate object files
 .SECONDARY:
 
@@ -978,3 +968,29 @@
 #	${BUILD}/tests/firmware_rollback_tests
 #	${BUILD}/tests/kernel_rollback_tests
 
+# Code coverage
+.PHONY: coverage_init
+coverage_init: test_setup
+	rm -f ${COV_INFO}*
+	lcov -c -i -d . -b . -o ${COV_INFO}.initial
+
+.PHONY: coverage_html
+coverage_html:
+	lcov -c -d . -b . -o ${COV_INFO}.tests
+	lcov -a ${COV_INFO}.initial -a ${COV_INFO}.tests -o ${COV_INFO}.total
+	lcov -r ${COV_INFO}.total '/usr/*' '*/linktest/*' -o ${COV_INFO}.local
+	genhtml ${COV_INFO}.local -o ${BUILD}/coverage
+
+# Generate addtional coverage stats just for firmware subdir, because the
+# per-directory stats for the whole project don't include their own subdirs.
+	lcov -e ${COV_INFO}.local '${SRCDIR}/firmware/*' \
+		-o ${COV_INFO}.firmware
+
+.PHONY: coverage
+ifeq (${COV},)
+coverage:
+	$(error Build coverage like this: make clean && COV=1 make)
+else
+coverage: coverage_init runtests coverage_html
+endif
+