/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/tools/lldb-vscode/OutputRedirector.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===-- OutputRedirector.cpp -----------------------------------*- 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 | | #if defined(_WIN32) |
10 | | #include <fcntl.h> |
11 | | #include <io.h> |
12 | | #else |
13 | | #include <unistd.h> |
14 | | #endif |
15 | | |
16 | | #include "OutputRedirector.h" |
17 | | #include "llvm/ADT/StringRef.h" |
18 | | |
19 | | using namespace llvm; |
20 | | |
21 | | namespace lldb_vscode { |
22 | | |
23 | 8 | Error RedirectFd(int fd, std::function<void(llvm::StringRef)> callback) { |
24 | 8 | int new_fd[2]; |
25 | | #if defined(_WIN32) |
26 | | if (_pipe(new_fd, 4096, O_TEXT) == -1) { |
27 | | #else |
28 | 8 | if (pipe(new_fd) == -1) { |
29 | 0 | #endif |
30 | 0 | int error = errno; |
31 | 0 | return createStringError(inconvertibleErrorCode(), |
32 | 0 | "Couldn't create new pipe for fd %d. %s", fd, |
33 | 0 | strerror(error)); |
34 | 0 | } |
35 | | |
36 | 8 | if (dup2(new_fd[1], fd) == -1) { |
37 | 0 | int error = errno; |
38 | 0 | return createStringError(inconvertibleErrorCode(), |
39 | 0 | "Couldn't override the fd %d. %s", fd, |
40 | 0 | strerror(error)); |
41 | 0 | } |
42 | | |
43 | 8 | int read_fd = new_fd[0]; |
44 | 8 | std::thread t([read_fd, callback]() { |
45 | 8 | char buffer[4096]; |
46 | 16 | while (true) { |
47 | 8 | ssize_t bytes_count = read(read_fd, &buffer, sizeof(buffer)); |
48 | 8 | if (bytes_count == 0) |
49 | 0 | return; |
50 | 8 | if (bytes_count == -1) { |
51 | 0 | if (errno == EAGAIN || errno == EINTR) |
52 | 0 | continue; |
53 | 0 | break; |
54 | 0 | } |
55 | 8 | callback(StringRef(buffer, bytes_count)); |
56 | 8 | } |
57 | 8 | }); |
58 | 8 | t.detach(); |
59 | 8 | return Error::success(); |
60 | 8 | } |
61 | | |
62 | | } // namespace lldb_vscode |