1 //===-- OutputRedirector.h -------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===/ 8 9 #ifndef LLDB_TOOLS_LLDB_DAP_OUTPUT_REDIRECTOR_H 10 #define LLDB_TOOLS_LLDB_DAP_OUTPUT_REDIRECTOR_H 11 12 #include "lldb/Host/Pipe.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/Support/Error.h" 15 #include <atomic> 16 #include <functional> 17 #include <thread> 18 19 namespace lldb_dap { 20 21 class OutputRedirector { 22 public: 23 /// Creates writable file descriptor that will invoke the given callback on 24 /// each write in a background thread. 25 /// 26 /// \return 27 /// \a Error::success if the redirection was set up correctly, or an error 28 /// otherwise. 29 llvm::Error RedirectTo(std::function<void(llvm::StringRef)> callback); 30 31 llvm::Expected<int> GetWriteFileDescriptor(); 32 void Stop(); 33 34 ~OutputRedirector() { Stop(); } 35 36 OutputRedirector() = default; 37 OutputRedirector(const OutputRedirector &) = delete; 38 OutputRedirector &operator=(const OutputRedirector &) = delete; 39 40 private: 41 std::atomic<bool> m_stopped = false; 42 lldb_private::Pipe m_pipe; 43 std::thread m_forwarder; 44 }; 45 46 } // namespace lldb_dap 47 48 #endif // LLDB_TOOLS_LLDB_DAP_OUTPUT_REDIRECTOR_H 49