blob: 53c14f4e36f84d9876981c3e83f7cc0a9340ce65 [file] [log] [blame]
Gabor Tothf4692ed2024-12-03 09:32:55 +01001/*
2 * Copyright (c) 2024, Arm Limited. All rights reserved.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8#include "mock_libc.h"
9
10#include <CppUTestExt/MockSupport.h>
11
12/*
13 * Do not forget to redefine the mocked function with the test function on cmake level e.g:
14 *
15 * set_source_files_properties(<source.c> PROPERTIES
16 * COMPILE_DEFINITIONS calloc=MOCK_CALLOC
17 * )
18 */
19
20static bool mock_libc_enabled = false;
21
22void mock_libc_enable(void)
23{
24 mock_libc_enabled = true;
25}
26
27void mock_libc_disable(void)
28{
29 mock_libc_enabled = false;
30}
31
32void expect_malloc(void *result)
33{
34 mock().expectOneCall("MOCK_MALLOC")
35 .andReturnValue(result);
36}
37
38void* MOCK_MALLOC(size_t size)
39{
40 if (!mock_libc_enabled)
41 return malloc(size);
42
43 void* result = mock().actualCall("MOCK_MALLOC")
44 .returnPointerValue();
45
46 if (result != NULL) {
47 result = malloc(size);
48 }
49
50 return result;
51}
52
53void expect_calloc(void *result)
54{
55 mock().expectOneCall("MOCK_CALLOC")
56 .andReturnValue(result);
57}
58
59void* MOCK_CALLOC(size_t nmemb, size_t size)
60{
61 if (!mock_libc_enabled)
62 return calloc(nmemb, size);
63
64 void* result = mock().actualCall("MOCK_CALLOC")
65 .returnPointerValue();
66
67 if (result != NULL) {
68 result = calloc(nmemb, size);
69 }
70
71 return result;
72}