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),
32 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
33 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
34}
35
37 : m_read(reinterpret_cast<HANDLE>(read)),
38 m_write(reinterpret_cast<HANDLE>(write)),
41 assert(read != LLDB_INVALID_PIPE || write != LLDB_INVALID_PIPE);
42
43 // Don't risk in passing file descriptors and getting handles from them by
44 // _get_osfhandle since the retrieved handles are highly likely unrecognized
45 // in the current process and usually crashes the program. Pass handles
46 // instead since the handle can be inherited.
47
48 if (read != LLDB_INVALID_PIPE) {
49 m_read_fd = _open_osfhandle((intptr_t)read, _O_RDONLY);
50 // Make sure the fd and native handle are consistent.
51 if (m_read_fd < 0)
52 m_read = INVALID_HANDLE_VALUE;
53 }
54
55 if (write != LLDB_INVALID_PIPE) {
56 m_write_fd = _open_osfhandle((intptr_t)write, _O_WRONLY);
57 if (m_write_fd < 0)
58 m_write = INVALID_HANDLE_VALUE;
59 }
60
61 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
62 m_read_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
63
64 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
65 m_write_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
66}
67
69
71 // Even for anonymous pipes, we open a named pipe. This is because you
72 // cannot get overlapped i/o on Windows without using a named pipe. So we
73 // synthesize a unique name.
74 uint32_t serial = g_pipe_serial.fetch_add(1);
75 std::string pipe_name = llvm::formatv(
76 "lldb.pipe.{0}.{1}.{2}", GetCurrentProcessId(), &g_pipe_serial, serial);
77
78 return CreateNew(pipe_name.c_str());
79}
80
81Status PipeWindows::CreateNew(llvm::StringRef name) {
82 if (name.empty())
83 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
84
85 if (CanRead() || CanWrite())
86 return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
87
88 std::string pipe_path = g_pipe_name_prefix.str();
89 pipe_path.append(name.str());
90
91 // We always create inheritable handles, but we won't pass them to a child
92 // process unless explicitly requested (cf. ProcessLauncherWindows.cpp).
93 SECURITY_ATTRIBUTES sa{sizeof(SECURITY_ATTRIBUTES), 0, TRUE};
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 if (m_read_fd < 0) {
108 ::CloseHandle(m_read);
109 m_read = INVALID_HANDLE_VALUE;
110 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
111 }
112 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
113 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
114
115 // Open the write end of the pipe. Note that closing either the read or
116 // write end of the pipe could directly close the pipe itself.
117 Status result = OpenNamedPipe(name, false);
118 if (!result.Success()) {
120 return result;
121 }
122
123 return result;
124}
125
128 llvm::SmallString<128> pipe_name;
130 ::UUID unique_id;
131 RPC_CSTR unique_string;
132 RPC_STATUS status = ::UuidCreate(&unique_id);
133 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
134 status = ::UuidToStringA(&unique_id, &unique_string);
135 if (status == RPC_S_OK) {
136 pipe_name = prefix;
137 pipe_name += "-";
138 pipe_name += reinterpret_cast<char *>(unique_string);
139 ::RpcStringFreeA(&unique_string);
140 error = CreateNew(pipe_name);
141 } else {
142 error = Status(status, eErrorTypeWin32);
143 }
144 if (error.Success())
145 name = pipe_name;
146 return error;
147}
148
149Status PipeWindows::OpenAsReader(llvm::StringRef name) {
150 if (CanRead())
151 return Status(); // Note the name is ignored.
152
153 return OpenNamedPipe(name, true);
154}
155
156llvm::Error PipeWindows::OpenAsWriter(llvm::StringRef name,
157 const Timeout<std::micro> &timeout) {
158 if (CanWrite())
159 return llvm::Error::success(); // Note the name is ignored.
160
161 return OpenNamedPipe(name, false).takeError();
162}
163
164Status PipeWindows::OpenNamedPipe(llvm::StringRef name, bool is_read) {
165 if (name.empty())
166 return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
167
168 assert(is_read ? !CanRead() : !CanWrite());
169
170 // We always create inheritable handles, but we won't pass them to a child
171 // process unless explicitly requested (cf. ProcessLauncherWindows.cpp).
172 SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), 0, TRUE};
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, nullptr);
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 if (m_read_fd < 0) {
185 ::CloseHandle(m_read);
186 m_read = INVALID_HANDLE_VALUE;
187 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
188 }
189
190 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
191 m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
192 } else {
193 m_write = ::CreateFileA(pipe_path.c_str(), GENERIC_WRITE, 0, &attributes,
194 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
195 if (INVALID_HANDLE_VALUE == m_write)
196 return Status(::GetLastError(), eErrorTypeWin32);
197
198 m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
199 if (m_write_fd < 0) {
200 ::CloseHandle(m_write);
201 m_write = INVALID_HANDLE_VALUE;
202 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
203 }
204
205 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
206 m_write_overlapped.hEvent = ::CreateEventA(nullptr, TRUE, FALSE, nullptr);
207 }
208
209 return Status();
210}
211
213
215
217 if (!CanRead())
219 int result = m_read_fd;
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
229 if (!CanWrite())
231 int result = m_write_fd;
233 if (m_write_overlapped.hEvent)
234 ::CloseHandle(m_write_overlapped.hEvent);
235 m_write = INVALID_HANDLE_VALUE;
236 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
237 return result;
238}
239
241 if (!CanRead())
242 return;
243
244 if (m_read_overlapped.hEvent)
245 ::CloseHandle(m_read_overlapped.hEvent);
246
247 _close(m_read_fd);
248 m_read = INVALID_HANDLE_VALUE;
250 ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
251}
252
254 if (!CanWrite())
255 return;
256
257 if (m_write_overlapped.hEvent)
258 ::CloseHandle(m_write_overlapped.hEvent);
259
260 _close(m_write_fd);
261 m_write = INVALID_HANDLE_VALUE;
263 ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
264}
265
270
271Status PipeWindows::Delete(llvm::StringRef name) { return Status(); }
272
273bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); }
274
275bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); }
276
277HANDLE
279
280HANDLE
282
283llvm::Expected<size_t> PipeWindows::Read(void *buf, size_t size,
284 const Timeout<std::micro> &timeout) {
285 if (!CanRead())
286 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32).takeError();
287
288 DWORD bytes_read = 0;
289 BOOL result = ::ReadFile(m_read, buf, size, &bytes_read, &m_read_overlapped);
290 if (result)
291 return bytes_read;
292
293 DWORD failure_error = ::GetLastError();
294 if (failure_error != ERROR_IO_PENDING)
295 return Status(failure_error, eErrorTypeWin32).takeError();
296
297 DWORD timeout_msec =
298 timeout ? std::chrono::ceil<std::chrono::milliseconds>(*timeout).count()
299 : INFINITE;
300 DWORD wait_result =
301 ::WaitForSingleObject(m_read_overlapped.hEvent, timeout_msec);
302 if (wait_result != WAIT_OBJECT_0) {
303 // The operation probably failed. However, if it timed out, we need to
304 // cancel the I/O. Between the time we returned from WaitForSingleObject
305 // and the time we call CancelIoEx, the operation may complete. If that
306 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
307 // happens, the original operation should be considered to have been
308 // successful.
309 bool failed = true;
310 failure_error = ::GetLastError();
311 if (wait_result == WAIT_TIMEOUT) {
312 BOOL cancel_result = ::CancelIoEx(m_read, &m_read_overlapped);
313 if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND)
314 failed = false;
315 }
316 if (failed)
317 return Status(failure_error, eErrorTypeWin32).takeError();
318 }
319
320 // Now we call GetOverlappedResult setting bWait to false, since we've
321 // already waited as long as we're willing to.
322 if (!::GetOverlappedResult(m_read, &m_read_overlapped, &bytes_read, FALSE))
323 return Status(::GetLastError(), eErrorTypeWin32).takeError();
324
325 return bytes_read;
326}
327
328llvm::Expected<size_t> PipeWindows::Write(const void *buf, size_t size,
329 const Timeout<std::micro> &timeout) {
330 if (!CanWrite())
331 return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32).takeError();
332
333 DWORD bytes_written = 0;
334 BOOL result =
335 ::WriteFile(m_write, buf, size, &bytes_written, &m_write_overlapped);
336 if (result)
337 return bytes_written;
338
339 DWORD failure_error = ::GetLastError();
340 if (failure_error != ERROR_IO_PENDING)
341 return Status(failure_error, eErrorTypeWin32).takeError();
342
343 DWORD timeout_msec =
344 timeout ? std::chrono::ceil<std::chrono::milliseconds>(*timeout).count()
345 : INFINITE;
346 DWORD wait_result =
347 ::WaitForSingleObject(m_write_overlapped.hEvent, timeout_msec);
348 if (wait_result != WAIT_OBJECT_0) {
349 // The operation probably failed. However, if it timed out, we need to
350 // cancel the I/O. Between the time we returned from WaitForSingleObject
351 // and the time we call CancelIoEx, the operation may complete. If that
352 // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
353 // happens, the original operation should be considered to have been
354 // successful.
355 bool failed = true;
356 failure_error = ::GetLastError();
357 if (wait_result == WAIT_TIMEOUT) {
358 BOOL cancel_result = ::CancelIoEx(m_write, &m_write_overlapped);
359 if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND)
360 failed = false;
361 }
362 if (failed)
363 return Status(failure_error, eErrorTypeWin32).takeError();
364 }
365
366 // Now we call GetOverlappedResult setting bWait to false, since we've
367 // already waited as long as we're willing to.
368 if (!::GetOverlappedResult(m_write, &m_write_overlapped, &bytes_written,
369 FALSE))
370 return Status(::GetLastError(), eErrorTypeWin32).takeError();
371
372 return bytes_written;
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
void * HANDLE
bool CanWrite() const override
Status Delete(llvm::StringRef name) override
int ReleaseReadFileDescriptor() override
void CloseReadFileDescriptor() override
Status OpenNamedPipe(llvm::StringRef name, bool is_read)
void CloseWriteFileDescriptor() override
Status CreateNew() override
static const int kInvalidDescriptor
Definition PipeWindows.h:24
Status OpenAsReader(llvm::StringRef name) override
llvm::Expected< size_t > Read(void *buf, size_t size, const Timeout< std::micro > &timeout=std::nullopt) override
llvm::Expected< size_t > Write(const void *buf, size_t size, const Timeout< std::micro > &timeout=std::nullopt) override
int ReleaseWriteFileDescriptor() override
int GetWriteFileDescriptor() const override
llvm::Error OpenAsWriter(llvm::StringRef name, const Timeout< std::micro > &timeout) override
int GetReadFileDescriptor() const override
Status CreateWithUniqueName(llvm::StringRef prefix, llvm::SmallVectorImpl< char > &name) override
bool CanRead() const override
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
bool Success() const
Test for success condition.
Definition Status.cpp:303
Represents UUID's of various sizes.
Definition UUID.h:27
#define LLDB_INVALID_PIPE
Definition lldb-types.h:70
A class that represents a running process on the host machine.
int pipe_t
Definition lldb-types.h:64
@ eErrorTypeWin32
Standard Win32 error codes.