1 //===-- PipeWindows.cpp ---------------------------------------------------===//
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 #include "lldb/Host/windows/PipeWindows.h"
10
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/Support/Process.h"
13 #include "llvm/Support/raw_ostream.h"
14
15 #include <fcntl.h>
16 #include <io.h>
17 #include <rpc.h>
18
19 #include <atomic>
20 #include <string>
21
22 using namespace lldb;
23 using namespace lldb_private;
24
25 namespace {
26 std::atomic<uint32_t> g_pipe_serial(0);
27 constexpr llvm::StringLiteral g_pipe_name_prefix = "\\\\.\\Pipe\\";
28 } // namespace
29
PipeWindows()30 PipeWindows::PipeWindows()
31 : m_read(INVALID_HANDLE_VALUE), m_write(INVALID_HANDLE_VALUE),
32 m_read_fd(PipeWindows::kInvalidDescriptor),
33 m_write_fd(PipeWindows::kInvalidDescriptor) {
34 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
35 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
36 }
37
PipeWindows(pipe_t read,pipe_t write)38 PipeWindows::PipeWindows(pipe_t read, pipe_t write)
39 : m_read((HANDLE)read), m_write((HANDLE)write),
40 m_read_fd(PipeWindows::kInvalidDescriptor),
41 m_write_fd(PipeWindows::kInvalidDescriptor) {
42 assert(read != LLDB_INVALID_PIPE || write != LLDB_INVALID_PIPE);
43
44 // Don't risk in passing file descriptors and getting handles from them by
45 // _get_osfhandle since the retrieved handles are highly likely unrecognized
46 // in the current process and usually crashes the program. Pass handles
47 // instead since the handle can be inherited.
48
49 if (read != LLDB_INVALID_PIPE) {
50 m_read_fd = _open_osfhandle((intptr_t)read, _O_RDONLY);
51 // Make sure the fd and native handle are consistent.
52 if (m_read_fd < 0)
53 m_read = INVALID_HANDLE_VALUE;
54 }
55
56 if (write != LLDB_INVALID_PIPE) {
57 m_write_fd = _open_osfhandle((intptr_t)write, _O_WRONLY);
58 if (m_write_fd < 0)
59 m_write = INVALID_HANDLE_VALUE;
60 }
61
62 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
63 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
64 }
65
~PipeWindows()66 PipeWindows::~PipeWindows() { Close(); }
67
CreateNew(bool child_process_inherit)68 Status PipeWindows::CreateNew(bool child_process_inherit) {
69 // Create an anonymous pipe with the specified inheritance.
70 SECURITY_ATTRIBUTES sa{sizeof(SECURITY_ATTRIBUTES), 0,
71 child_process_inherit ? TRUE : FALSE};
72 BOOL result = ::CreatePipe(&m_read, &m_write, &sa, 1024);
73 if (result == FALSE)
74 return Status(::GetLastError(), eErrorTypeWin32);
75
76 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
77 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
78 m_read_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
79
80 m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
81 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
82
83 return Status();
84 }
85
CreateNewNamed(bool child_process_inherit)86 Status PipeWindows::CreateNewNamed(bool child_process_inherit) {
87 // Even for anonymous pipes, we open a named pipe. This is because you
88 // cannot get overlapped i/o on Windows without using a named pipe. So we
89 // synthesize a unique name.
90 uint32_t serial = g_pipe_serial.fetch_add(1);
91 std::string pipe_name;
92 llvm::raw_string_ostream pipe_name_stream(pipe_name);
93 pipe_name_stream << "lldb.pipe." << ::GetCurrentProcessId() << "." << serial;
94 pipe_name_stream.flush();
95
96 return CreateNew(pipe_name.c_str(), child_process_inherit);
97 }
98
CreateNew(llvm::StringRef name,bool child_process_inherit)99 Status PipeWindows::CreateNew(llvm::StringRef name,
100 bool child_process_inherit) {
101 if (name.empty())
102 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
103
104 if (CanRead() || CanWrite())
105 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
106
107 std::string pipe_path = g_pipe_name_prefix.str();
108 pipe_path.append(name.str());
109
110 // Always open for overlapped i/o. We implement blocking manually in Read
111 // and Write.
112 DWORD read_mode = FILE_FLAG_OVERLAPPED;
113 m_read = ::CreateNamedPipeA(
114 pipe_path.c_str(), PIPE_ACCESS_INBOUND | read_mode,
115 PIPE_TYPE_BYTE | PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
116 if (INVALID_HANDLE_VALUE == m_read)
117 return Status(::GetLastError(), eErrorTypeWin32);
118 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
119 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
120 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
121
122 // Open the write end of the pipe. Note that closing either the read or
123 // write end of the pipe could directly close the pipe itself.
124 Status result = OpenNamedPipe(name, child_process_inherit, false);
125 if (!result.Success()) {
126 CloseReadFileDescriptor();
127 return result;
128 }
129
130 return result;
131 }
132
CreateWithUniqueName(llvm::StringRef prefix,bool child_process_inherit,llvm::SmallVectorImpl<char> & name)133 Status PipeWindows::CreateWithUniqueName(llvm::StringRef prefix,
134 bool child_process_inherit,
135 llvm::SmallVectorImpl<char> &name) {
136 llvm::SmallString<128> pipe_name;
137 Status error;
138 ::UUID unique_id;
139 RPC_CSTR unique_string;
140 RPC_STATUS status = ::UuidCreate(&unique_id);
141 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
142 status = ::UuidToStringA(&unique_id, &unique_string);
143 if (status == RPC_S_OK) {
144 pipe_name = prefix;
145 pipe_name += "-";
146 pipe_name += reinterpret_cast<char *>(unique_string);
147 ::RpcStringFreeA(&unique_string);
148 error = CreateNew(pipe_name, child_process_inherit);
149 } else {
150 error.SetError(status, eErrorTypeWin32);
151 }
152 if (error.Success())
153 name = pipe_name;
154 return error;
155 }
156
OpenAsReader(llvm::StringRef name,bool child_process_inherit)157 Status PipeWindows::OpenAsReader(llvm::StringRef name,
158 bool child_process_inherit) {
159 if (CanRead())
160 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
161
162 return OpenNamedPipe(name, child_process_inherit, true);
163 }
164
165 Status
OpenAsWriterWithTimeout(llvm::StringRef name,bool child_process_inherit,const std::chrono::microseconds & timeout)166 PipeWindows::OpenAsWriterWithTimeout(llvm::StringRef name,
167 bool child_process_inherit,
168 const std::chrono::microseconds &timeout) {
169 if (CanWrite())
170 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
171
172 return OpenNamedPipe(name, child_process_inherit, false);
173 }
174
OpenNamedPipe(llvm::StringRef name,bool child_process_inherit,bool is_read)175 Status PipeWindows::OpenNamedPipe(llvm::StringRef name,
176 bool child_process_inherit, bool is_read) {
177 if (name.empty())
178 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
179
180 assert(is_read ? !CanRead() : !CanWrite());
181
182 SECURITY_ATTRIBUTES attributes = {};
183 attributes.bInheritHandle = child_process_inherit;
184
185 std::string pipe_path = g_pipe_name_prefix.str();
186 pipe_path.append(name.str());
187
188 if (is_read) {
189 m_read = ::CreateFileA(pipe_path.c_str(), GENERIC_READ, 0, &attributes,
190 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
191 if (INVALID_HANDLE_VALUE == m_read)
192 return Status(::GetLastError(), eErrorTypeWin32);
193
194 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
195
196 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
197 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
198 } else {
199 m_write = ::CreateFileA(pipe_path.c_str(), GENERIC_WRITE, 0, &attributes,
200 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
201 if (INVALID_HANDLE_VALUE == m_write)
202 return Status(::GetLastError(), eErrorTypeWin32);
203
204 m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
205
206 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
207 }
208
209 return Status();
210 }
211
GetReadFileDescriptor() const212 int PipeWindows::GetReadFileDescriptor() const { return m_read_fd; }
213
GetWriteFileDescriptor() const214 int PipeWindows::GetWriteFileDescriptor() const { return m_write_fd; }
215
ReleaseReadFileDescriptor()216 int PipeWindows::ReleaseReadFileDescriptor() {
217 if (!CanRead())
218 return PipeWindows::kInvalidDescriptor;
219 int result = m_read_fd;
220 m_read_fd = PipeWindows::kInvalidDescriptor;
221 if (m_read_overlapped.hEvent)
222 ::CloseHandle(m_read_overlapped.hEvent);
223 m_read = INVALID_HANDLE_VALUE;
224 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
225 return result;
226 }
227
ReleaseWriteFileDescriptor()228 int PipeWindows::ReleaseWriteFileDescriptor() {
229 if (!CanWrite())
230 return PipeWindows::kInvalidDescriptor;
231 int result = m_write_fd;
232 m_write_fd = PipeWindows::kInvalidDescriptor;
233 m_write = INVALID_HANDLE_VALUE;
234 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
235 return result;
236 }
237
CloseReadFileDescriptor()238 void PipeWindows::CloseReadFileDescriptor() {
239 if (!CanRead())
240 return;
241
242 if (m_read_overlapped.hEvent)
243 ::CloseHandle(m_read_overlapped.hEvent);
244
245 _close(m_read_fd);
246 m_read = INVALID_HANDLE_VALUE;
247 m_read_fd = PipeWindows::kInvalidDescriptor;
248 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
249 }
250
CloseWriteFileDescriptor()251 void PipeWindows::CloseWriteFileDescriptor() {
252 if (!CanWrite())
253 return;
254
255 _close(m_write_fd);
256 m_write = INVALID_HANDLE_VALUE;
257 m_write_fd = PipeWindows::kInvalidDescriptor;
258 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
259 }
260
Close()261 void PipeWindows::Close() {
262 CloseReadFileDescriptor();
263 CloseWriteFileDescriptor();
264 }
265
Delete(llvm::StringRef name)266 Status PipeWindows::Delete(llvm::StringRef name) { return Status(); }
267
CanRead() const268 bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); }
269
CanWrite() const270 bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); }
271
272 HANDLE
GetReadNativeHandle()273 PipeWindows::GetReadNativeHandle() { return m_read; }
274
275 HANDLE
GetWriteNativeHandle()276 PipeWindows::GetWriteNativeHandle() { return m_write; }
277
ReadWithTimeout(void * buf,size_t size,const std::chrono::microseconds & duration,size_t & bytes_read)278 Status PipeWindows::ReadWithTimeout(void *buf, size_t size,
279 const std::chrono::microseconds &duration,
280 size_t &bytes_read) {
281 if (!CanRead())
282 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
283
284 bytes_read = 0;
285 DWORD sys_bytes_read = size;
286 BOOL result = ::ReadFile(m_read, buf, sys_bytes_read, &sys_bytes_read,
287 &m_read_overlapped);
288 if (!result && GetLastError() != ERROR_IO_PENDING)
289 return Status(::GetLastError(), eErrorTypeWin32);
290
291 DWORD timeout = (duration == std::chrono::microseconds::zero())
292 ? INFINITE
293 : duration.count() * 1000;
294 DWORD wait_result = ::WaitForSingleObject(m_read_overlapped.hEvent, timeout);
295 if (wait_result != WAIT_OBJECT_0) {
296 // The operation probably failed. However, if it timed out, we need to
297 // cancel the I/O. Between the time we returned from WaitForSingleObject
298 // and the time we call CancelIoEx, the operation may complete. If that
299 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
300 // happens, the original operation should be considered to have been
301 // successful.
302 bool failed = true;
303 DWORD failure_error = ::GetLastError();
304 if (wait_result == WAIT_TIMEOUT) {
305 BOOL cancel_result = CancelIoEx(m_read, &m_read_overlapped);
306 if (!cancel_result && GetLastError() == ERROR_NOT_FOUND)
307 failed = false;
308 }
309 if (failed)
310 return Status(failure_error, eErrorTypeWin32);
311 }
312
313 // Now we call GetOverlappedResult setting bWait to false, since we've
314 // already waited as long as we're willing to.
315 if (!GetOverlappedResult(m_read, &m_read_overlapped, &sys_bytes_read, FALSE))
316 return Status(::GetLastError(), eErrorTypeWin32);
317
318 bytes_read = sys_bytes_read;
319 return Status();
320 }
321
Write(const void * buf,size_t num_bytes,size_t & bytes_written)322 Status PipeWindows::Write(const void *buf, size_t num_bytes,
323 size_t &bytes_written) {
324 if (!CanWrite())
325 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
326
327 DWORD sys_bytes_written = 0;
328 BOOL write_result = ::WriteFile(m_write, buf, num_bytes, &sys_bytes_written,
329 &m_write_overlapped);
330 if (!write_result && GetLastError() != ERROR_IO_PENDING)
331 return Status(::GetLastError(), eErrorTypeWin32);
332
333 BOOL result = GetOverlappedResult(m_write, &m_write_overlapped,
334 &sys_bytes_written, TRUE);
335 if (!result)
336 return Status(::GetLastError(), eErrorTypeWin32);
337 return Status();
338 }
339