• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-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 #ifndef PANDA_RUNTIME_TOOLING_SAMPLER_THREAD_COMMUNICATOR_H
17 #define PANDA_RUNTIME_TOOLING_SAMPLER_THREAD_COMMUNICATOR_H
18 
19 #include <fcntl.h>
20 #include <poll.h>
21 #include <unistd.h>
22 
23 #include "libpandabase/macros.h"
24 #include "libpandabase/utils/logger.h"
25 #include "os/failure_retry.h"
26 
27 #include "runtime/tooling/sampler/sample_info.h"
28 
29 namespace ark::tooling::sampler {
30 
31 namespace test {
32 class SamplerTest;
33 }  // namespace test
34 
35 class ThreadCommunicator final {
36 public:
37     static constexpr uint8_t PIPE_READ_ID {0};
38     static constexpr uint8_t PIPE_WRITE_ID {1};
39 
40     ThreadCommunicator() = default;
41 
~ThreadCommunicator()42     ~ThreadCommunicator()
43     {
44         for (int fd : listenerPipe_) {
45             if (fd != -1) {
46                 if (PANDA_FAILURE_RETRY(::close(fd)) != 0) {
47                     LOG(ERROR, PROFILER) << "Cannot close fd: " << fd;
48                 }
49             }
50         }
51     }
52 
Init()53     bool Init()
54     {
55         if (listenerPipe_[PIPE_READ_ID] != -1) {
56             return true;
57         }
58         return pipe2(listenerPipe_.data(), O_CLOEXEC) != -1;
59     }
60 
61     bool IsPipeEmpty() const;
62     PANDA_PUBLIC_API bool SendSample(const SampleInfo &sample) const;
63     PANDA_PUBLIC_API bool ReadSample(SampleInfo *sample) const;
64 
65     NO_COPY_SEMANTIC(ThreadCommunicator);
66     NO_MOVE_SEMANTIC(ThreadCommunicator);
67 
68 private:
69     std::array<int, 2U> listenerPipe_ {-1, -1};
70 
71     friend class test::SamplerTest;
72 };
73 
74 }  // namespace ark::tooling::sampler
75 
76 #endif  // PANDA_RUNTIME_TOOLING_SAMPLER_THREAD_COMMUNICATOR_H
77