1 /*
2 * Copyright (C) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "eventfd_mock.h"
17
18 #include <dlfcn.h>
19
20 namespace OHOS {
21 namespace FileManagement {
22 namespace ModuleFileIO {
23 namespace Test {
24
25 thread_local std::shared_ptr<EventfdMock> EventfdMock::eventfdMock = nullptr;
26 thread_local bool EventfdMock::mockable = false;
27
GetMock()28 std::shared_ptr<EventfdMock> EventfdMock::GetMock()
29 {
30 if (eventfdMock == nullptr) {
31 eventfdMock = std::make_shared<EventfdMock>();
32 }
33
34 return eventfdMock;
35 }
36
EnableMock()37 void EventfdMock::EnableMock()
38 {
39 mockable = true;
40 }
41
DisableMock()42 void EventfdMock::DisableMock()
43 {
44 eventfdMock = nullptr;
45 mockable = false;
46 }
47
IsMockable()48 bool EventfdMock::IsMockable()
49 {
50 return mockable;
51 }
52
53 } // namespace Test
54 } // namespace ModuleFileIO
55 } // namespace FileManagement
56 } // namespace OHOS
57
58 #ifdef __cplusplus
59 extern "C" {
60 using namespace OHOS::FileManagement::ModuleFileIO::Test;
61
eventfd(unsigned int count,int flags)62 int eventfd(unsigned int count, int flags)
63 {
64 if (EventfdMock::IsMockable()) {
65 return EventfdMock::GetMock()->eventfd(count, flags);
66 }
67
68 static int (*realEventfd)(unsigned int, int) = []() {
69 auto func = (int (*)(unsigned int, int))dlsym(RTLD_NEXT, "eventfd");
70 if (!func) {
71 GTEST_LOG_(ERROR) << "Failed to resolve real eventfd: " << dlerror();
72 }
73 return func;
74 }();
75
76 if (!realEventfd) {
77 return -1;
78 }
79
80 return realEventfd(count, flags);
81 }
82
83 } // extern "C"
84 #endif