• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "poll_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<PollMock> PollMock::pollMock = nullptr;
26 thread_local bool PollMock::mockable = false;
27 
GetMock()28 std::shared_ptr<PollMock> PollMock::GetMock()
29 {
30     if (pollMock == nullptr) {
31         pollMock = std::make_shared<PollMock>();
32     }
33     return pollMock;
34 }
35 
EnableMock()36 void PollMock::EnableMock()
37 {
38     mockable = true;
39 }
40 
DisableMock()41 void PollMock::DisableMock()
42 {
43     pollMock = nullptr;
44     mockable = false;
45 }
46 
IsMockable()47 bool PollMock::IsMockable()
48 {
49     return mockable;
50 }
51 
52 } // namespace Test
53 } // namespace ModuleFileIO
54 } // namespace FileManagement
55 } // namespace OHOS
56 
57 #ifdef __cplusplus
58 extern "C" {
59 using namespace OHOS::FileManagement::ModuleFileIO::Test;
60 
poll(struct pollfd * fds,nfds_t n,int timeout)61 int poll(struct pollfd *fds, nfds_t n, int timeout)
62 {
63     if (PollMock::IsMockable()) {
64         return PollMock::GetMock()->poll(fds, n, timeout);
65     }
66 
67     static int (*realPoll)(struct pollfd * fds, nfds_t n, int timeout) = []() {
68         auto func = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll");
69         if (!func) {
70             GTEST_LOG_(ERROR) << "Failed to resolve real poll: " << dlerror();
71         }
72         return func;
73     }();
74 
75     if (!realPoll) {
76         return -1;
77     }
78 
79     return realPoll(fds, n, timeout);
80 }
81 
82 } // extern "C"
83 #endif