Create mock for malloc and calloc api-s

malloc and calloc mock functions are added to test if components
handle heap memory allocation errors properly.

Change-Id: I682ed0655abc5592726a49bcaacf05780c264b3a
Signed-off-by: Gabor Toth <gabor.toth2@arm.com>
diff --git a/components/common/libc/mock/mock_libc.cpp b/components/common/libc/mock/mock_libc.cpp
new file mode 100644
index 0000000..53c14f4
--- /dev/null
+++ b/components/common/libc/mock/mock_libc.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2024, Arm Limited. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ */
+
+#include "mock_libc.h"
+
+#include <CppUTestExt/MockSupport.h>
+
+/*
+ * Do not forget to redefine the mocked function with the test function on cmake level e.g:
+ *
+ * set_source_files_properties(<source.c> PROPERTIES
+ *	COMPILE_DEFINITIONS calloc=MOCK_CALLOC
+ * )
+ */
+
+static bool mock_libc_enabled = false;
+
+void mock_libc_enable(void)
+{
+	mock_libc_enabled = true;
+}
+
+void mock_libc_disable(void)
+{
+	mock_libc_enabled = false;
+}
+
+void expect_malloc(void *result)
+{
+	mock().expectOneCall("MOCK_MALLOC")
+		.andReturnValue(result);
+}
+
+void* MOCK_MALLOC(size_t size)
+{
+	if (!mock_libc_enabled)
+		return malloc(size);
+
+	void* result = mock().actualCall("MOCK_MALLOC")
+		.returnPointerValue();
+
+	if (result != NULL) {
+		result = malloc(size);
+	}
+
+	return result;
+}
+
+void expect_calloc(void *result)
+{
+	mock().expectOneCall("MOCK_CALLOC")
+		.andReturnValue(result);
+}
+
+void* MOCK_CALLOC(size_t nmemb, size_t size)
+{
+	if (!mock_libc_enabled)
+		return calloc(nmemb, size);
+
+	void* result = mock().actualCall("MOCK_CALLOC")
+		.returnPointerValue();
+
+	if (result != NULL) {
+		result = calloc(nmemb, size);
+	}
+
+	return result;
+}
diff --git a/components/common/libc/mock/mock_libc.h b/components/common/libc/mock/mock_libc.h
new file mode 100644
index 0000000..afd3652
--- /dev/null
+++ b/components/common/libc/mock/mock_libc.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2024, Arm Limited. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ */
+
+#ifndef MOCK_LIBC_H
+#define MOCK_LIBC_H
+
+#include "../include/malloc.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * libc is used everywhere in the sources so it useful to enable mocking
+ * only for the realted testcases to avoid the necessity of filling the
+ * tests with a huge amount of expect calls.
+ */
+void mock_libc_enable(void);
+void mock_libc_disable(void);
+
+void expect_malloc(void *result);
+void* MOCK_MALLOC(size_t size);
+
+void expect_calloc(void *result);
+void* MOCK_CALLOC(size_t nmemb, size_t size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MOCK_LIBC_H */
\ No newline at end of file