1 /** 2 * Copyright (c) 2021-2024 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 LOG_IF(PANDA_FAILURE_RETRY(::close(fd)) != 0, FATAL, PROFILER) << "Cannot close fd: " << fd; 47 } 48 } 49 } 50 Init()51 bool Init() 52 { 53 if (listenerPipe_[PIPE_READ_ID] != -1) { 54 return true; 55 } 56 return pipe2(listenerPipe_.data(), O_CLOEXEC) != -1; 57 } 58 59 bool IsPipeEmpty() const; 60 PANDA_PUBLIC_API bool SendSample(const SampleInfo &sample) const; 61 PANDA_PUBLIC_API bool ReadSample(SampleInfo *sample) const; 62 63 NO_COPY_SEMANTIC(ThreadCommunicator); 64 NO_MOVE_SEMANTIC(ThreadCommunicator); 65 66 private: 67 std::array<int, 2U> listenerPipe_ {-1, -1}; 68 69 friend class test::SamplerTest; 70 }; 71 72 } // namespace ark::tooling::sampler 73 74 #endif // PANDA_RUNTIME_TOOLING_SAMPLER_THREAD_COMMUNICATOR_H 75