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 pipe_name_stream.flush();
78
79 return CreateNew(pipe_name.c_str(), child_process_inherit);
80}
81
82Status PipeWindows::CreateNew(llvm::StringRef name,
83 bool child_process_inherit) {
84 if (name.empty())
85 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
86
87 if (CanRead() || CanWrite())
88 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
89
90 std::string pipe_path = g_pipe_name_prefix.str();
91 pipe_path.append(name.str());
92
93 SECURITY_ATTRIBUTES sa{sizeof(SECURITY_ATTRIBUTES), 0,
94 child_process_inherit ? TRUE : FALSE};
95
96 // Always open for overlapped i/o. We implement blocking manually in Read
97 // and Write.
98 DWORD read_mode = FILE_FLAG_OVERLAPPED;
99 m_read =
100 ::CreateNamedPipeA(pipe_path.c_str(), PIPE_ACCESS_INBOUND | read_mode,
101 PIPE_TYPE_BYTE | PIPE_WAIT, /*nMaxInstances=*/1,
102 /*nOutBufferSize=*/1024,
103 /*nInBufferSize=*/1024,
104 /*nDefaultTimeOut=*/0, &sa);
105 if (INVALID_HANDLE_VALUE == m_read)
106 return Status(::GetLastError(), eErrorTypeWin32);
107 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
108 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
109 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
110
111 // Open the write end of the pipe. Note that closing either the read or
112 // write end of the pipe could directly close the pipe itself.
113 Status result = OpenNamedPipe(name, child_process_inherit, false);
114 if (!result.Success()) {
116 return result;
117 }
118
119 return result;
120}
121
123 bool child_process_inherit,
125 llvm::SmallString<128> pipe_name;
127 ::UUID unique_id;
128 RPC_CSTR unique_string;
129 RPC_STATUS status = ::UuidCreate(&unique_id);
130 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
131 status = ::UuidToStringA(&unique_id, &unique_string);
132 if (status == RPC_S_OK) {
133 pipe_name = prefix;
134 pipe_name += "-";
135 pipe_name += reinterpret_cast<char *>(unique_string);
136 ::RpcStringFreeA(&unique_string);
137 error = CreateNew(pipe_name, child_process_inherit);
138 } else {
139 error.SetError(status, eErrorTypeWin32);
140 }
141 if (error.Success())
142 name = pipe_name;
143 return error;
144}
145
147 bool child_process_inherit) {
148 if (CanRead())
149 return Status(); // Note the name is ignored.
150
151 return OpenNamedPipe(name, child_process_inherit, true);
152}
153
154Status
156 bool child_process_inherit,
157 const std::chrono::microseconds &timeout) {
158 if (CanWrite())
159 return Status(); // Note the name is ignored.
160
161 return OpenNamedPipe(name, child_process_inherit, false);
162}
163
165 bool child_process_inherit, bool is_read) {
166 if (name.empty())
167 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
168
169 assert(is_read ? !CanRead() : !CanWrite());
170
171 SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), 0,
172 child_process_inherit ? TRUE : FALSE};
173
174 std::string pipe_path = g_pipe_name_prefix.str();
175 pipe_path.append(name.str());
176
177 if (is_read) {
178 m_read = ::CreateFileA(pipe_path.c_str(), GENERIC_READ, 0, &attributes,
179 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
180 if (INVALID_HANDLE_VALUE == m_read)
181 return Status(::GetLastError(), eErrorTypeWin32);
182
183 m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
184
185 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
186 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
187 } else {
188 m_write = ::CreateFileA(pipe_path.c_str(), GENERIC_WRITE, 0, &attributes,
189 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
190 if (INVALID_HANDLE_VALUE == m_write)
191 return Status(::GetLastError(), eErrorTypeWin32);
192
193 m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
194
195 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
196 m_write_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
197 }
198
199 return Status();
200}
201
203
205
207 if (!CanRead())
209 int result = m_read_fd;
211 if (m_read_overlapped.hEvent)
212 ::CloseHandle(m_read_overlapped.hEvent);
213 m_read = INVALID_HANDLE_VALUE;
214 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
215 return result;
216}
217
219 if (!CanWrite())
221 int result = m_write_fd;
223 if (m_write_overlapped.hEvent)
224 ::CloseHandle(m_write_overlapped.hEvent);
225 m_write = INVALID_HANDLE_VALUE;
226 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
227 return result;
228}
229
231 if (!CanRead())
232 return;
233
234 if (m_read_overlapped.hEvent)
235 ::CloseHandle(m_read_overlapped.hEvent);
236
237 _close(m_read_fd);
238 m_read = INVALID_HANDLE_VALUE;
240 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
241}
242
244 if (!CanWrite())
245 return;
246
247 if (m_write_overlapped.hEvent)
248 ::CloseHandle(m_write_overlapped.hEvent);
249
250 _close(m_write_fd);
251 m_write = INVALID_HANDLE_VALUE;
253 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
254}
255
259}
260
261Status PipeWindows::Delete(llvm::StringRef name) { return Status(); }
262
263bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); }
264
265bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); }
266
267HANDLE
269
270HANDLE
272
274 const std::chrono::microseconds &duration,
275 size_t &bytes_read) {
276 if (!CanRead())
277 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
278
279 bytes_read = 0;
280 DWORD sys_bytes_read = 0;
281 BOOL result =
282 ::ReadFile(m_read, buf, size, &sys_bytes_read, &m_read_overlapped);
283 if (result) {
284 bytes_read = sys_bytes_read;
285 return Status();
286 }
287
288 DWORD failure_error = ::GetLastError();
289 if (failure_error != ERROR_IO_PENDING)
290 return Status(failure_error, eErrorTypeWin32);
291
292 DWORD timeout = (duration == std::chrono::microseconds::zero())
293 ? INFINITE
294 : duration.count() / 1000;
295 DWORD wait_result = ::WaitForSingleObject(m_read_overlapped.hEvent, timeout);
296 if (wait_result != WAIT_OBJECT_0) {
297 // The operation probably failed. However, if it timed out, we need to
298 // cancel the I/O. Between the time we returned from WaitForSingleObject
299 // and the time we call CancelIoEx, the operation may complete. If that
300 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
301 // happens, the original operation should be considered to have been
302 // successful.
303 bool failed = true;
304 failure_error = ::GetLastError();
305 if (wait_result == WAIT_TIMEOUT) {
306 BOOL cancel_result = ::CancelIoEx(m_read, &m_read_overlapped);
307 if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND)
308 failed = false;
309 }
310 if (failed)
311 return Status(failure_error, eErrorTypeWin32);
312 }
313
314 // Now we call GetOverlappedResult setting bWait to false, since we've
315 // already waited as long as we're willing to.
316 if (!::GetOverlappedResult(m_read, &m_read_overlapped, &sys_bytes_read,
317 FALSE))
318 return Status(::GetLastError(), eErrorTypeWin32);
319
320 bytes_read = sys_bytes_read;
321 return Status();
322}
323
324Status PipeWindows::WriteWithTimeout(const void *buf, size_t size,
325 const std::chrono::microseconds &duration,
326 size_t &bytes_written) {
327 if (!CanWrite())
328 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
329
330 bytes_written = 0;
331 DWORD sys_bytes_write = 0;
332 BOOL result =
333 ::WriteFile(m_write, buf, size, &sys_bytes_write, &m_write_overlapped);
334 if (result) {
335 bytes_written = sys_bytes_write;
336 return Status();
337 }
338
339 DWORD failure_error = ::GetLastError();
340 if (failure_error != ERROR_IO_PENDING)
341 return Status(failure_error, eErrorTypeWin32);
342
343 DWORD timeout = (duration == std::chrono::microseconds::zero())
344 ? INFINITE
345 : duration.count() / 1000;
346 DWORD wait_result = ::WaitForSingleObject(m_write_overlapped.hEvent, timeout);
347 if (wait_result != WAIT_OBJECT_0) {
348 // The operation probably failed. However, if it timed out, we need to
349 // cancel the I/O. Between the time we returned from WaitForSingleObject
350 // and the time we call CancelIoEx, the operation may complete. If that
351 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
352 // happens, the original operation should be considered to have been
353 // successful.
354 bool failed = true;
355 failure_error = ::GetLastError();
356 if (wait_result == WAIT_TIMEOUT) {
357 BOOL cancel_result = ::CancelIoEx(m_write, &m_write_overlapped);
358 if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND)
359 failed = false;
360 }
361 if (failed)
362 return Status(failure_error, eErrorTypeWin32);
363 }
364
365 // Now we call GetOverlappedResult setting bWait to false, since we've
366 // already waited as long as we're willing to.
367 if (!::GetOverlappedResult(m_write, &m_write_overlapped, &sys_bytes_write,
368 FALSE))
369 return Status(::GetLastError(), eErrorTypeWin32);
370
371 bytes_written = sys_bytes_write;
372 return Status();
373}
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:44
bool Success() const
Test for success condition.
Definition: Status.cpp:278
#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.