tests: Build Cmocka from source

Relying on Cmocka packages, which are provided with different OS
distributions, may introduce some problems with setup environments
across developers (e.g. library version mismatch). Instead, let's build
Cmocka from source code, which is now added to git submodules as
3rdparty/cmocka.

Please note, that cmake tool is required for building Cmocka (thus also
coreboot unit tests).

Signed-off-by: Jan Dabros <jsd@semihalf.com>
Change-Id: Ia947c5c60d5c58b76acebe4b614dd427ef995950
Reviewed-on: https://review.coreboot.org/c/coreboot/+/41653
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Paul Fagerburg <pfagerburg@chromium.org>
Reviewed-by: Patrick Georgi <pgeorgi@google.com>
diff --git a/tests/Makefile.inc b/tests/Makefile.inc
index be32434..a6689a2 100644
--- a/tests/Makefile.inc
+++ b/tests/Makefile.inc
@@ -2,6 +2,12 @@
 
 testsrc = $(top)/tests
 testobj = $(obj)/tests
+cmockasrc = 3rdparty/cmocka
+cmockaobj = $(cmockasrc)/build
+
+CMOCKA_LIB := $(cmockaobj)/src/libcmocka.so
+
+CMAKE:= cmake
 
 TEST_DEFAULT_CONFIG = $(top)/configs/config.emulation_qemu_x86_i440fx
 TEST_DOTCONFIG = $(testobj)/.config
@@ -26,8 +32,14 @@
 
 TEST_CFLAGS += -std=gnu11 -Os -ffunction-sections -fdata-sections -fno-builtin
 
+# Checkout Cmocka repository
+forgetthis:=$(shell git submodule update --init --checkout 3rdparty/cmocka)
+
+TEST_CFLAGS += -I$(cmockasrc)/include
+
 # Link against Cmocka
-TEST_LDFLAGS = -lcmocka -Wl,--gc-sections
+TEST_LDFLAGS = -L$(cmockaobj)/src -lcmocka -Wl,-rpath=$(cmockaobj)/src
+TEST_LDFLAGS += -Wl,--gc-sections
 
 # Extra attributes for unit tests, declared per test
 attributes:= srcs cflags mocks stage
@@ -69,7 +81,7 @@
 		-MT $$@ -c $$< -o $$@
 
 $($(1)-bin): TEST_LDFLAGS+= $$(foreach mock,$$($(1)-mocks),-Wl,--wrap=$$(mock))
-$($(1)-bin): $($(1)-objs)
+$($(1)-bin): $($(1)-objs) $(CMOCKA_LIB)
 	$(HOSTCC) $$^ $($(1)-cflags) $$(TEST_LDFLAGS) -o $$@
 
 endef
@@ -90,6 +102,13 @@
 DEPENDENCIES += $(addsuffix .d,$(basename $(all-test-objs)))
 -include $(DEPENDENCIES)
 
+# Build cmocka
+$(CMOCKA_LIB):
+	echo "*** Building CMOCKA ***"
+	mkdir -p $(cmockaobj)
+	cd $(cmockaobj) && $(CMAKE) $(abspath $(cmockasrc))
+	$(MAKE) -C $(cmockaobj)
+
 # Kconfig targets
 $(TEST_DOTCONFIG):
 	mkdir -p $(dir $@)