LLDB  mainline
ConnectionGenericFileWindows.cpp
Go to the documentation of this file.
1 //===-- ConnectionGenericFileWindows.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 #include "lldb/Utility/LLDBLog.h"
11 #include "lldb/Utility/Log.h"
12 #include "lldb/Utility/Status.h"
13 #include "lldb/Utility/Timeout.h"
14 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/ConvertUTF.h"
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 
22 namespace {
23 // This is a simple helper class to package up the information needed to return
24 // from a Read/Write operation function. Since there is a lot of code to be
25 // run before exit regardless of whether the operation succeeded or failed,
26 // combined with many possible return paths, this is the cleanest way to
27 // represent it.
28 class ReturnInfo {
29 public:
30  void Set(size_t bytes, ConnectionStatus status, DWORD error_code) {
31  m_error.SetError(error_code, eErrorTypeWin32);
32  m_bytes = bytes;
33  m_status = status;
34  }
35 
36  void Set(size_t bytes, ConnectionStatus status, llvm::StringRef error_msg) {
37  m_error.SetErrorString(error_msg.data());
38  m_bytes = bytes;
39  m_status = status;
40  }
41 
42  size_t GetBytes() const { return m_bytes; }
43  ConnectionStatus GetStatus() const { return m_status; }
44  const Status &GetError() const { return m_error; }
45 
46 private:
47  Status m_error;
48  size_t m_bytes;
49  ConnectionStatus m_status;
50 };
51 }
52 
53 ConnectionGenericFile::ConnectionGenericFile()
54  : m_file(INVALID_HANDLE_VALUE), m_owns_file(false) {
55  ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
56  ::ZeroMemory(&m_file_position, sizeof(m_file_position));
58 }
59 
61  : m_file(file), m_owns_file(owns_file) {
62  ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
63  ::ZeroMemory(&m_file_position, sizeof(m_file_position));
65 }
66 
68  if (m_owns_file && IsConnected())
69  ::CloseHandle(m_file);
70 
71  ::CloseHandle(m_event_handles[kBytesAvailableEvent]);
72  ::CloseHandle(m_event_handles[kInterruptEvent]);
73 }
74 
76  m_event_handles[kInterruptEvent] = CreateEvent(NULL, FALSE, FALSE, NULL);
77 
78  // Note, we should use a manual reset event for the hEvent argument of the
79  // OVERLAPPED. This is because both WaitForMultipleObjects and
80  // GetOverlappedResult (if you set the bWait argument to TRUE) will wait for
81  // the event to be signalled. If we use an auto-reset event,
82  // WaitForMultipleObjects will reset the event, return successfully, and then
83  // GetOverlappedResult will block since the event is no longer signalled.
85  ::CreateEvent(NULL, TRUE, FALSE, NULL);
86 }
87 
89  return m_file && (m_file != INVALID_HANDLE_VALUE);
90 }
91 
93  Status *error_ptr) {
95  LLDB_LOGF(log, "%p ConnectionGenericFile::Connect (url = '%s')",
96  static_cast<void *>(this), path.str().c_str());
97 
98  if (!path.consume_front("file://")) {
99  if (error_ptr)
100  error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
101  path.str().c_str());
102  return eConnectionStatusError;
103  }
104 
105  if (IsConnected()) {
106  ConnectionStatus status = Disconnect(error_ptr);
107  if (status != eConnectionStatusSuccess)
108  return status;
109  }
110 
111  // Open the file for overlapped access. If it does not exist, create it. We
112  // open it overlapped so that we can issue asynchronous reads and then use
113  // WaitForMultipleObjects to allow the read to be interrupted by an event
114  // object.
115  std::wstring wpath;
116  if (!llvm::ConvertUTF8toWide(path, wpath)) {
117  if (error_ptr)
118  error_ptr->SetError(1, eErrorTypeGeneric);
119  return eConnectionStatusError;
120  }
121  m_file = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
122  FILE_SHARE_READ, NULL, OPEN_ALWAYS,
123  FILE_FLAG_OVERLAPPED, NULL);
124  if (m_file == INVALID_HANDLE_VALUE) {
125  if (error_ptr)
126  error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
127  return eConnectionStatusError;
128  }
129 
130  m_owns_file = true;
131  m_uri = path.str();
133 }
134 
137  LLDB_LOGF(log, "%p ConnectionGenericFile::Disconnect ()",
138  static_cast<void *>(this));
139 
140  if (!IsConnected())
142 
143  // Reset the handle so that after we unblock any pending reads, subsequent
144  // calls to Read() will see a disconnected state.
145  HANDLE old_file = m_file;
146  m_file = INVALID_HANDLE_VALUE;
147 
148  // Set the disconnect event so that any blocking reads unblock, then cancel
149  // any pending IO operations.
150  ::CancelIoEx(old_file, &m_overlapped);
151 
152  // Close the file handle if we owned it, but don't close the event handles.
153  // We could always reconnect with the same Connection instance.
154  if (m_owns_file)
155  ::CloseHandle(old_file);
156 
157  ::ZeroMemory(&m_file_position, sizeof(m_file_position));
158  m_owns_file = false;
159  m_uri.clear();
161 }
162 
163 size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
164  const Timeout<std::micro> &timeout,
165  lldb::ConnectionStatus &status,
166  Status *error_ptr) {
167  ReturnInfo return_info;
168  BOOL result = 0;
169  DWORD bytes_read = 0;
170 
171  if (error_ptr)
172  error_ptr->Clear();
173 
174  if (!IsConnected()) {
175  return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
176  goto finish;
177  }
178 
180 
181  result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
182  if (result || ::GetLastError() == ERROR_IO_PENDING) {
183  if (!result) {
184  // The expected return path. The operation is pending. Wait for the
185  // operation to complete or be interrupted.
186  DWORD milliseconds =
187  timeout
188  ? std::chrono::duration_cast<std::chrono::milliseconds>(*timeout)
189  .count()
190  : INFINITE;
191  DWORD wait_result =
192  ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
193  m_event_handles, FALSE, milliseconds);
194  // All of the events are manual reset events, so make sure we reset them
195  // to non-signalled.
196  switch (wait_result) {
197  case WAIT_OBJECT_0 + kBytesAvailableEvent:
198  break;
199  case WAIT_OBJECT_0 + kInterruptEvent:
200  return_info.Set(0, eConnectionStatusInterrupted, 0);
201  goto finish;
202  case WAIT_TIMEOUT:
203  return_info.Set(0, eConnectionStatusTimedOut, 0);
204  goto finish;
205  case WAIT_FAILED:
206  return_info.Set(0, eConnectionStatusError, ::GetLastError());
207  goto finish;
208  }
209  }
210  // The data is ready. Figure out how much was read and return;
211  if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
212  DWORD result_error = ::GetLastError();
213  // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during
214  // a blocking read. This triggers a call to CancelIoEx, which causes the
215  // operation to complete and the result to be ERROR_OPERATION_ABORTED.
216  if (result_error == ERROR_HANDLE_EOF ||
217  result_error == ERROR_OPERATION_ABORTED ||
218  result_error == ERROR_BROKEN_PIPE)
219  return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
220  else
221  return_info.Set(bytes_read, eConnectionStatusError, result_error);
222  } else if (bytes_read == 0)
223  return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
224  else
225  return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
226 
227  goto finish;
228  } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
229  // The write end of a pipe was closed. This is equivalent to EOF.
230  return_info.Set(0, eConnectionStatusEndOfFile, 0);
231  } else {
232  // An unknown error occurred. Fail out.
233  return_info.Set(0, eConnectionStatusError, ::GetLastError());
234  }
235  goto finish;
236 
237 finish:
238  status = return_info.GetStatus();
239  if (error_ptr)
240  *error_ptr = return_info.GetError();
241 
242  // kBytesAvailableEvent is a manual reset event. Make sure it gets reset
243  // here so that any subsequent operations don't immediately see bytes
244  // available.
246 
247  IncrementFilePointer(return_info.GetBytes());
249  LLDB_LOGF(log,
250  "%p ConnectionGenericFile::Read() handle = %p, dst = %p, "
251  "dst_len = %zu) => %zu, error = %s",
252  static_cast<void *>(this), m_file, dst, dst_len,
253  return_info.GetBytes(), return_info.GetError().AsCString());
254 
255  return return_info.GetBytes();
256 }
257 
258 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
259  lldb::ConnectionStatus &status,
260  Status *error_ptr) {
261  ReturnInfo return_info;
262  DWORD bytes_written = 0;
263  BOOL result = 0;
264 
265  if (error_ptr)
266  error_ptr->Clear();
267 
268  if (!IsConnected()) {
269  return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
270  goto finish;
271  }
272 
273  m_overlapped.hEvent = NULL;
274 
275  // Writes are not interruptible like reads are, so just block until it's
276  // done.
277  result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
278  if (!result && ::GetLastError() != ERROR_IO_PENDING) {
279  return_info.Set(0, eConnectionStatusError, ::GetLastError());
280  goto finish;
281  }
282 
283  if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
284  return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
285  goto finish;
286  }
287 
288  return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
289  goto finish;
290 
291 finish:
292  status = return_info.GetStatus();
293  if (error_ptr)
294  *error_ptr = return_info.GetError();
295 
296  IncrementFilePointer(return_info.GetBytes());
298  LLDB_LOGF(log,
299  "%p ConnectionGenericFile::Write() handle = %p, src = %p, "
300  "src_len = %zu) => %zu, error = %s",
301  static_cast<void *>(this), m_file, src, src_len,
302  return_info.GetBytes(), return_info.GetError().AsCString());
303  return return_info.GetBytes();
304 }
305 
307 
309  return ::SetEvent(m_event_handles[kInterruptEvent]);
310 }
311 
313  LARGE_INTEGER old_pos;
314  old_pos.HighPart = m_overlapped.OffsetHigh;
315  old_pos.LowPart = m_overlapped.Offset;
316  old_pos.QuadPart += amount;
317  m_overlapped.Offset = old_pos.LowPart;
318  m_overlapped.OffsetHigh = old_pos.HighPart;
319 }
lldb_private::Status::SetError
int void SetError(ValueType err, lldb::ErrorType type)
Set accessor with an error value and type.
Definition: Status.cpp:216
lldb_private::ConnectionGenericFile::Disconnect
lldb::ConnectionStatus Disconnect(Status *error_ptr) override
Disconnect the communications connection if one is currently connected.
Definition: ConnectionGenericFileWindows.cpp:135
lldb_private::ConnectionGenericFile::m_event_handles
HANDLE m_event_handles[2]
Definition: ConnectionGenericFileWindows.h:47
lldb_private::ConnectionGenericFile::GetURI
std::string GetURI() override
Returns a URI that describes this connection object.
Definition: ConnectionGenericFileWindows.cpp:306
ConnectionGenericFileWindows.h
lldb_private::ConnectionGenericFile::m_file_position
LARGE_INTEGER m_file_position
Definition: ConnectionGenericFileWindows.h:49
LLDB_LOGF
#define LLDB_LOGF(log,...)
Definition: Log.h:343
lldb_private::ConnectionGenericFile::m_file
HANDLE m_file
Definition: ConnectionGenericFileWindows.h:46
lldb_private::ConnectionGenericFile::kInterruptEvent
@ kInterruptEvent
Definition: ConnectionGenericFileWindows.h:51
lldb::file_t
int file_t
Definition: lldb-types.h:59
lldb_private::ConnectionGenericFile::ConnectionGenericFile
ConnectionGenericFile()
Definition: ConnectionGenericFileWindows.cpp:53
lldb::eConnectionStatusNoConnection
@ eConnectionStatusNoConnection
No connection.
Definition: lldb-enumerations.h:300
lldb::eConnectionStatusEndOfFile
@ eConnectionStatusEndOfFile
End-of-file encountered.
Definition: lldb-enumerations.h:297
lldb::eErrorTypeWin32
@ eErrorTypeWin32
Standard Win32 error codes.
Definition: lldb-enumerations.h:312
lldb_private::LLDBLog::Connection
@ Connection
Log.h
lldb_private::ConnectionGenericFile::IsConnected
bool IsConnected() const override
Check if the connection is valid.
Definition: ConnectionGenericFileWindows.cpp:88
lldb_private::Status::SetErrorStringWithFormat
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
lldb_private::ConnectionGenericFile::IncrementFilePointer
void IncrementFilePointer(DWORD amount)
Definition: ConnectionGenericFileWindows.cpp:312
lldb_private::ConnectionGenericFile::Read
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr) override
The read function that attempts to read from the connection.
Definition: ConnectionGenericFileWindows.cpp:163
lldb::eConnectionStatusTimedOut
@ eConnectionStatusTimedOut
Request timed out.
Definition: lldb-enumerations.h:299
lldb::ConnectionStatus
ConnectionStatus
Connection Status Types.
Definition: lldb-enumerations.h:295
lldb::eConnectionStatusInterrupted
@ eConnectionStatusInterrupted
Interrupted read.
Definition: lldb-enumerations.h:303
lldb::eErrorTypeGeneric
@ eErrorTypeGeneric
Generic errors that can be any value.
Definition: lldb-enumerations.h:308
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:40
lldb_private::ConnectionGenericFile::m_owns_file
bool m_owns_file
Definition: ConnectionGenericFileWindows.h:48
lldb_private::ConnectionGenericFile::m_uri
std::string m_uri
Definition: ConnectionGenericFileWindows.h:57
lldb_private::ConnectionGenericFile::Connect
lldb::ConnectionStatus Connect(llvm::StringRef s, Status *error_ptr) override
Connect using the connect string url.
Definition: ConnectionGenericFileWindows.cpp:92
lldb_private::ConnectionGenericFile::InterruptRead
bool InterruptRead() override
Interrupts an ongoing Read() operation.
Definition: ConnectionGenericFileWindows.cpp:308
lldb_private::ConnectionGenericFile::kBytesAvailableEvent
@ kBytesAvailableEvent
Definition: ConnectionGenericFileWindows.h:51
lldb_private::Status
Definition: Status.h:44
lldb_private::Timeout< std::micro >
lldb::eConnectionStatusError
@ eConnectionStatusError
Check GetError() for details.
Definition: lldb-enumerations.h:298
lldb_private::ConnectionGenericFile::Write
size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr) override
The actual write function that attempts to write to the communications protocol.
Definition: ConnectionGenericFileWindows.cpp:258
Timeout.h
lldb::eConnectionStatusSuccess
@ eConnectionStatusSuccess
Success.
Definition: lldb-enumerations.h:296
Status.h
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::ConnectionGenericFile::m_overlapped
OVERLAPPED m_overlapped
Definition: ConnectionGenericFileWindows.h:45
lldb_private::ConnectionGenericFile::InitializeEventHandles
void InitializeEventHandles()
Definition: ConnectionGenericFileWindows.cpp:75
lldb_private::Status::Clear
void Clear()
Clear the object state.
Definition: Status.cpp:167
lldb_private::Log
Definition: Log.h:115
lldb_private::GetLog
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:308
lldb
Definition: SBAddress.h:15
LLDBLog.h
lldb_private::ConnectionGenericFile::~ConnectionGenericFile
~ConnectionGenericFile() override
Definition: ConnectionGenericFileWindows.cpp:67