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 | static std::atomic<uint32_t> g_pipe_serial(0); |
26 | static constexpr llvm::StringLiteral g_pipe_name_prefix = "\\\\.\\Pipe\\" ; |
27 | |
28 | PipeWindows::PipeWindows() |
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 | |
36 | PipeWindows::PipeWindows(pipe_t read, pipe_t write) |
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 | |
67 | PipeWindows::~PipeWindows() { Close(); } |
68 | |
69 | Status 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(i: 1); |
74 | std::string pipe_name = llvm::formatv( |
75 | "lldb.pipe.{0}.{1}.{2}" , GetCurrentProcessId(), &g_pipe_serial, serial); |
76 | |
77 | return CreateNew(name: pipe_name.c_str(), child_process_inherit); |
78 | } |
79 | |
80 | Status PipeWindows::CreateNew(llvm::StringRef name, |
81 | bool child_process_inherit) { |
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(str: 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 | 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, is_read: false); |
113 | if (!result.Success()) { |
114 | CloseReadFileDescriptor(); |
115 | return result; |
116 | } |
117 | |
118 | return result; |
119 | } |
120 | |
121 | Status PipeWindows::CreateWithUniqueName(llvm::StringRef prefix, |
122 | bool child_process_inherit, |
123 | llvm::SmallVectorImpl<char> &name) { |
124 | llvm::SmallString<128> pipe_name; |
125 | Status error; |
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(name: 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 | |
145 | Status PipeWindows::OpenAsReader(llvm::StringRef name, |
146 | bool child_process_inherit) { |
147 | if (CanRead()) |
148 | return Status(); // Note the name is ignored. |
149 | |
150 | return OpenNamedPipe(name, child_process_inherit, is_read: true); |
151 | } |
152 | |
153 | llvm::Error PipeWindows::OpenAsWriter(llvm::StringRef name, |
154 | bool child_process_inherit, |
155 | const Timeout<std::micro> &timeout) { |
156 | if (CanWrite()) |
157 | return llvm::Error::success(); // Note the name is ignored. |
158 | |
159 | return OpenNamedPipe(name, child_process_inherit, is_read: false).takeError(); |
160 | } |
161 | |
162 | Status PipeWindows::OpenNamedPipe(llvm::StringRef name, |
163 | bool child_process_inherit, bool is_read) { |
164 | if (name.empty()) |
165 | return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32); |
166 | |
167 | assert(is_read ? !CanRead() : !CanWrite()); |
168 | |
169 | // We always create inheritable handles, but we won't pass them to a child |
170 | // process unless explicitly requested (cf. ProcessLauncherWindows.cpp). |
171 | SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), 0, TRUE}; |
172 | |
173 | std::string pipe_path = g_pipe_name_prefix.str(); |
174 | pipe_path.append(str: 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 | |
201 | int PipeWindows::GetReadFileDescriptor() const { return m_read_fd; } |
202 | |
203 | int PipeWindows::GetWriteFileDescriptor() const { return m_write_fd; } |
204 | |
205 | int PipeWindows::ReleaseReadFileDescriptor() { |
206 | if (!CanRead()) |
207 | return PipeWindows::kInvalidDescriptor; |
208 | int result = m_read_fd; |
209 | m_read_fd = PipeWindows::kInvalidDescriptor; |
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 | |
217 | int PipeWindows::ReleaseWriteFileDescriptor() { |
218 | if (!CanWrite()) |
219 | return PipeWindows::kInvalidDescriptor; |
220 | int result = m_write_fd; |
221 | m_write_fd = PipeWindows::kInvalidDescriptor; |
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 | |
229 | void PipeWindows::CloseReadFileDescriptor() { |
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; |
238 | m_read_fd = PipeWindows::kInvalidDescriptor; |
239 | ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped)); |
240 | } |
241 | |
242 | void PipeWindows::CloseWriteFileDescriptor() { |
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; |
251 | m_write_fd = PipeWindows::kInvalidDescriptor; |
252 | ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped)); |
253 | } |
254 | |
255 | void PipeWindows::Close() { |
256 | CloseReadFileDescriptor(); |
257 | CloseWriteFileDescriptor(); |
258 | } |
259 | |
260 | Status PipeWindows::Delete(llvm::StringRef name) { return Status(); } |
261 | |
262 | bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); } |
263 | |
264 | bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); } |
265 | |
266 | HANDLE |
267 | PipeWindows::GetReadNativeHandle() { return m_read; } |
268 | |
269 | HANDLE |
270 | PipeWindows::GetWriteNativeHandle() { return m_write; } |
271 | |
272 | llvm::Expected<size_t> PipeWindows::Read(void *buf, size_t size, |
273 | const Timeout<std::micro> &timeout) { |
274 | if (!CanRead()) |
275 | return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32).takeError(); |
276 | |
277 | DWORD bytes_read = 0; |
278 | BOOL result = ::ReadFile(m_read, buf, size, &bytes_read, &m_read_overlapped); |
279 | if (result) |
280 | return bytes_read; |
281 | |
282 | DWORD failure_error = ::GetLastError(); |
283 | if (failure_error != ERROR_IO_PENDING) |
284 | return Status(failure_error, eErrorTypeWin32).takeError(); |
285 | |
286 | DWORD timeout_msec = |
287 | timeout ? ceil<std::chrono::milliseconds>(*timeout).count() : INFINITE; |
288 | DWORD wait_result = |
289 | ::WaitForSingleObject(m_read_overlapped.hEvent, timeout_msec); |
290 | if (wait_result != WAIT_OBJECT_0) { |
291 | // The operation probably failed. However, if it timed out, we need to |
292 | // cancel the I/O. Between the time we returned from WaitForSingleObject |
293 | // and the time we call CancelIoEx, the operation may complete. If that |
294 | // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that |
295 | // happens, the original operation should be considered to have been |
296 | // successful. |
297 | bool failed = true; |
298 | failure_error = ::GetLastError(); |
299 | if (wait_result == WAIT_TIMEOUT) { |
300 | BOOL cancel_result = ::CancelIoEx(m_read, &m_read_overlapped); |
301 | if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND) |
302 | failed = false; |
303 | } |
304 | if (failed) |
305 | return Status(failure_error, eErrorTypeWin32).takeError(); |
306 | } |
307 | |
308 | // Now we call GetOverlappedResult setting bWait to false, since we've |
309 | // already waited as long as we're willing to. |
310 | if (!::GetOverlappedResult(m_read, &m_read_overlapped, &bytes_read, FALSE)) |
311 | return Status(::GetLastError(), eErrorTypeWin32).takeError(); |
312 | |
313 | return bytes_read; |
314 | } |
315 | |
316 | llvm::Expected<size_t> PipeWindows::Write(const void *buf, size_t size, |
317 | const Timeout<std::micro> &timeout) { |
318 | if (!CanWrite()) |
319 | return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32).takeError(); |
320 | |
321 | DWORD bytes_written = 0; |
322 | BOOL result = |
323 | ::WriteFile(m_write, buf, size, &bytes_written, &m_write_overlapped); |
324 | if (result) |
325 | return bytes_written; |
326 | |
327 | DWORD failure_error = ::GetLastError(); |
328 | if (failure_error != ERROR_IO_PENDING) |
329 | return Status(failure_error, eErrorTypeWin32).takeError(); |
330 | |
331 | DWORD timeout_msec = |
332 | timeout ? ceil<std::chrono::milliseconds>(*timeout).count() : INFINITE; |
333 | DWORD wait_result = |
334 | ::WaitForSingleObject(m_write_overlapped.hEvent, timeout_msec); |
335 | if (wait_result != WAIT_OBJECT_0) { |
336 | // The operation probably failed. However, if it timed out, we need to |
337 | // cancel the I/O. Between the time we returned from WaitForSingleObject |
338 | // and the time we call CancelIoEx, the operation may complete. If that |
339 | // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that |
340 | // happens, the original operation should be considered to have been |
341 | // successful. |
342 | bool failed = true; |
343 | failure_error = ::GetLastError(); |
344 | if (wait_result == WAIT_TIMEOUT) { |
345 | BOOL cancel_result = ::CancelIoEx(m_write, &m_write_overlapped); |
346 | if (!cancel_result && ::GetLastError() == ERROR_NOT_FOUND) |
347 | failed = false; |
348 | } |
349 | if (failed) |
350 | return Status(failure_error, eErrorTypeWin32).takeError(); |
351 | } |
352 | |
353 | // Now we call GetOverlappedResult setting bWait to false, since we've |
354 | // already waited as long as we're willing to. |
355 | if (!::GetOverlappedResult(m_write, &m_write_overlapped, &bytes_written, |
356 | FALSE)) |
357 | return Status(::GetLastError(), eErrorTypeWin32).takeError(); |
358 | |
359 | return bytes_written; |
360 | } |
361 | |