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 "llvm/ADT/StringRef.h" |
13 | #include "llvm/Support/Error.h" |
14 | #include <atomic> |
15 | #include <functional> |
16 | #include <thread> |
17 | |
18 | namespace lldb_dap { |
19 | |
20 | class OutputRedirector { |
21 | public: |
22 | static int kInvalidDescriptor; |
23 | |
24 | /// Creates writable file descriptor that will invoke the given callback on |
25 | /// each write in a background thread. |
26 | /// |
27 | /// \param[in] file_override |
28 | /// Updates the file descriptor to the redirection pipe, if not null. |
29 | /// |
30 | /// \param[in] callback |
31 | /// A callback invoked when any data is written to the file handle. |
32 | /// |
33 | /// \return |
34 | /// \a Error::success if the redirection was set up correctly, or an error |
35 | /// otherwise. |
36 | llvm::Error RedirectTo(std::FILE *file_override, |
37 | std::function<void(llvm::StringRef)> callback); |
38 | |
39 | llvm::Expected<int> GetWriteFileDescriptor(); |
40 | void Stop(); |
41 | |
42 | ~OutputRedirector() { Stop(); } |
43 | |
44 | OutputRedirector(); |
45 | OutputRedirector(const OutputRedirector &) = delete; |
46 | OutputRedirector &operator=(const OutputRedirector &) = delete; |
47 | |
48 | private: |
49 | std::atomic<bool> m_stopped = false; |
50 | int m_fd; |
51 | int m_original_fd; |
52 | int m_restore_fd; |
53 | std::thread m_forwarder; |
54 | }; |
55 | |
56 | } // namespace lldb_dap |
57 | |
58 | #endif // LLDB_TOOLS_LLDB_DAP_OUTPUT_REDIRECTOR_H |
59 |