LLDB mainline
PipeWindows.cpp
Go to the documentation of this file.
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
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
22using namespace lldb;
23using namespace lldb_private;
24
25static std::atomic<uint32_t> g_pipe_serial(0);
26static constexpr llvm::StringLiteral g_pipe_name_prefix = "\\\\.\\Pipe\\";
27
29 : m_read(INVALID_HANDLE_VALUE), m_write(INVALID_HANDLE_VALUE),
30 m_read_fd(PipeWindows::kInvalidDescriptor),
31 m_write_fd(PipeWindows::kInvalidDescriptor) {
32 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
33 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
34}
35
37 : m_read((HANDLE)read), m_write((HANDLE)write),
38 m_read_fd(PipeWindows::kInvalidDescriptor),
39 m_write_fd(PipeWindows::kInvalidDescriptor) {
40 assert(read != LLDB_INVALID_PIPE || write != LLDB_INVALID_PIPE);
41
42 // Don't risk in passing file descriptors and getting handles from them by
43 // _get_osfhandle since the retrieved handles are highly likely unrecognized
44 // in the current process and usually crashes the program. Pass handles
45 // instead since the handle can be inherited.
46
47 if (read != LLDB_INVALID_PIPE) {
48 m_read_fd = _open_osfhandle((intptr_t)read, _O_RDONLY);
49 // Make sure the fd and native handle are consistent.
50 if (m_read_fd < 0)
51 m_read = INVALID_HANDLE_VALUE;
52 }
53
54 if (write != LLDB_INVALID_PIPE) {
55 m_write_fd = _open_osfhandle((intptr_t)write, _O_WRONLY);
56 if (m_write_fd < 0)
57 m_write = INVALID_HANDLE_VALUE;
58 }
59
60 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
61 m_read_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
62
63 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
64 m_write_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
65}
66
68
69Status PipeWindows::CreateNew(bool child_process_inherit) {
70 // Even for anonymous pipes, we open a named pipe. This is because you
71 // cannot get overlapped i/o on Windows without using a named pipe. So we
72 // synthesize a unique name.
73 uint32_t serial = g_pipe_serial.fetch_add(1);
74 std::string pipe_name;
75 llvm::raw_string_ostream pipe_name_stream(pipe_name);
76 pipe_name_stream << "lldb.pipe." << ::GetCurrentProcessId() << "." << serial;
77
78 return CreateNew(pipe_name.c_str(), child_process_inherit);
79}
80
81Status PipeWindows::CreateNew(llvm::StringRef name,
82 bool child_process_inherit) {
83 if (name.empty())
84 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
85
86 if (CanRead() || CanWrite())
87 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
88
89 std::string pipe_path = g_pipe_name_prefix.str();
90 pipe_path.append(name.str());
91
92 SECURITY_ATTRIBUTES sa{sizeof(SECURITY_ATTRIBUTES), 0,
93 child_process_inherit ? TRUE : FALSE};
94
95 // Always open for overlapped i/o. We implement blocking manually in Read
96 // and Write.
97 DWORD read_mode = FILE_FLAG_OVERLAPPED;
98 m_read =
99 ::CreateNamedPipeA(pipe_path.c_str(), PIPE_ACCESS_INBOUND | read_mode,
100 PIPE_TYPE_BYTE | PIPE_WAIT, /*nMaxInstances=*/1,
101 /*nOutBufferSize=*/1024,
102 /*nInBufferSize=*/1024,
103 /*nDefaultTimeOut=*/0, &sa);
104 if (INVALID_HANDLE_VALUE == m_read)
105 return Status(::GetLastError(), eErrorTypeWin32);
106 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
107 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
108 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
109
110 // Open the write end of the pipe. Note that closing either the read or
111 // write end of the pipe could directly close the pipe itself.
112 Status result = OpenNamedPipe(name, child_process_inherit, false);
113 if (!result.Success()) {
115 return result;
116 }
117
118 return result;
119}
120
122 bool child_process_inherit,
124 llvm::SmallString<128> pipe_name;
126 ::UUID unique_id;
127 RPC_CSTR unique_string;
128 RPC_STATUS status = ::UuidCreate(&unique_id);
129 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
130 status = ::UuidToStringA(&unique_id, &unique_string);
131 if (status == RPC_S_OK) {
132 pipe_name = prefix;
133 pipe_name += "-";
134 pipe_name += reinterpret_cast<char *>(unique_string);
135 ::RpcStringFreeA(&unique_string);
136 error = CreateNew(pipe_name, child_process_inherit);
137 } else {
138 error = Status(status, eErrorTypeWin32);
139 }
140 if (error.Success())
141 name = pipe_name;
142 return error;
143}
144
146 bool child_process_inherit) {
147 if (CanRead())
148 return Status(); // Note the name is ignored.
149
150 return OpenNamedPipe(name, child_process_inherit, true);
151}
152
153Status
155 bool child_process_inherit,
156 const std::chrono::microseconds &timeout) {
157 if (CanWrite())
158 return Status(); // Note the name is ignored.
159
160 return OpenNamedPipe(name, child_process_inherit, false);
161}
162
164 bool child_process_inherit, bool is_read) {
165 if (name.empty())
166 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
167
168 assert(is_read ? !CanRead() : !CanWrite());
169
170 SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), 0,
171 child_process_inherit ? TRUE : FALSE};
172
173 std::string pipe_path = g_pipe_name_prefix.str();
174 pipe_path.append(name.str());
175
176 if (is_read) {
177 m_read = ::CreateFileA(pipe_path.c_str(), GENERIC_READ, 0, &attributes,
178 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
179 if (INVALID_HANDLE_VALUE == m_read)
180 return Status(::GetLastError(), eErrorTypeWin32);
181
182 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
183
184 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
185 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
186 } else {
187 m_write = ::CreateFileA(pipe_path.c_str(), GENERIC_WRITE, 0, &attributes,
188 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
189 if (INVALID_HANDLE_VALUE == m_write)
190 return Status(::GetLastError(), eErrorTypeWin32);
191
192 m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
193
194 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
195 m_write_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
196 }
197
198 return Status();
199}
200
202
204
206 if (!CanRead())
208 int result = m_read_fd;
210 if (m_read_overlapped.hEvent)
211 ::CloseHandle(m_read_overlapped.hEvent);
212 m_read = INVALID_HANDLE_VALUE;
213 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
214 return result;
215}
216
218 if (!CanWrite())
220 int result = m_write_fd;
222 if (m_write_overlapped.hEvent)
223 ::CloseHandle(m_write_overlapped.hEvent);
224 m_write = INVALID_HANDLE_VALUE;
225 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
226 return result;
227}
228
230 if (!CanRead())
231 return;
232
233 if (m_read_overlapped.hEvent)
234 ::CloseHandle(m_read_overlapped.hEvent);
235
236 _close(m_read_fd);
237 m_read = INVALID_HANDLE_VALUE;
239 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
240}
241
243 if (!CanWrite())
244 return;
245
246 if (m_write_overlapped.hEvent)
247 ::CloseHandle(m_write_overlapped.hEvent);
248
249 _close(m_write_fd);
250 m_write = INVALID_HANDLE_VALUE;
252 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
253}
254
258}
259
260Status PipeWindows::Delete(llvm::StringRef name) { return Status(); }
261
262bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); }
263
264bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); }
265
266HANDLE
268
269HANDLE
271
273 const std::chrono::microseconds &duration,
274 size_t &bytes_read) {
275 if (!CanRead())
276 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
277
278 bytes_read = 0;
279 DWORD sys_bytes_read = 0;
280 BOOL result =
281 ::ReadFile(m_read, buf, size, &sys_bytes_read, &m_read_overlapped);
282 if (result) {
283 bytes_read = sys_bytes_read;
284 return Status();
285 }
286
287 DWORD failure_error = ::GetLastError();
288 if (failure_error != ERROR_IO_PENDING)
289 return Status(failure_error, 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 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,
316 FALSE))
317 return Status(::GetLastError(), eErrorTypeWin32);
318
319 bytes_read = sys_bytes_read;
320 return Status();
321}
322
323Status PipeWindows::WriteWithTimeout(const void *buf, size_t size,
324 const std::chrono::microseconds &duration,
325 size_t &bytes_written) {
326 if (!CanWrite())
327 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
328
329 bytes_written = 0;
330 DWORD sys_bytes_write = 0;
331 BOOL result =
332 ::WriteFile(m_write, buf, size, &sys_bytes_write, &m_write_overlapped);
333 if (result) {
334 bytes_written = sys_bytes_write;
335 return Status();
336 }
337
338 DWORD failure_error = ::GetLastError();
339 if (failure_error != ERROR_IO_PENDING)
340 return Status(failure_error, eErrorTypeWin32);
341
342 DWORD timeout = (duration == std::chrono::microseconds::zero())
343 ? INFINITE
344 : duration.count() / 1000;
345 DWORD wait_result = ::WaitForSingleObject(m_write_overlapped.hEvent, timeout);
346 if (wait_result != WAIT_OBJECT_0) {
347 // The operation probably failed. However, if it timed out, we need to
348 // cancel the I/O. Between the time we returned from WaitForSingleObject
349 // and the time we call CancelIoEx, the operation may complete. If that
350 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
351 // happens, the original operation should be considered to have been
352 // successful.
353 bool failed = true;
354 failure_error = ::GetLastError();
355 if (wait_result == WAIT_TIMEOUT) {
356 BOOL cancel_result = ::CancelIoEx(m_write, &m_write_overlapped);
357 if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND)
358 failed = false;
359 }
360 if (failed)
361 return Status(failure_error, eErrorTypeWin32);
362 }
363
364 // Now we call GetOverlappedResult setting bWait to false, since we've
365 // already waited as long as we're willing to.
366 if (!::GetOverlappedResult(m_write, &m_write_overlapped, &sys_bytes_write,
367 FALSE))
368 return Status(::GetLastError(), eErrorTypeWin32);
369
370 bytes_written = sys_bytes_write;
371 return Status();
372}
static llvm::raw_ostream & error(Stream &strm)
static std::atomic< uint32_t > g_pipe_serial(0)
static constexpr llvm::StringLiteral g_pipe_name_prefix
Definition: PipeWindows.cpp:26
bool CanWrite() const override
Status OpenAsReader(llvm::StringRef name, bool child_process_inherit) override
Status CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl< char > &name) override
Status Delete(llvm::StringRef name) override
int ReleaseReadFileDescriptor() override
void CloseReadFileDescriptor() override
OVERLAPPED m_write_overlapped
Definition: PipeWindows.h:85
Status ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) override
void CloseWriteFileDescriptor() override
OVERLAPPED m_read_overlapped
Definition: PipeWindows.h:84
static const int kInvalidDescriptor
Definition: PipeWindows.h:24
Status CreateNew(bool child_process_inherit) override
Definition: PipeWindows.cpp:69
Status WriteWithTimeout(const void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_written) override
Status OpenNamedPipe(llvm::StringRef name, bool child_process_inherit, bool is_read)
Status OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) override
int ReleaseWriteFileDescriptor() override
int GetWriteFileDescriptor() const override
int GetReadFileDescriptor() const override
bool CanRead() const override
An error handling class.
Definition: Status.h:118
bool Success() const
Test for success condition.
Definition: Status.cpp:304
#define LLDB_INVALID_PIPE
Definition: lldb-types.h:70
A class that represents a running process on the host machine.
Definition: SBAddress.h:15
int pipe_t
Definition: lldb-types.h:64
@ eErrorTypeWin32
Standard Win32 error codes.