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 
9 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
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:
Set(size_t bytes,ConnectionStatus status,DWORD error_code)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 
Set(size_t bytes,ConnectionStatus status,llvm::StringRef error_msg)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 
GetBytes() const42   size_t GetBytes() const { return m_bytes; }
GetStatus() const43   ConnectionStatus GetStatus() const { return m_status; }
GetError() const44   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 
ConnectionGenericFile()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));
57   InitializeEventHandles();
58 }
59 
ConnectionGenericFile(lldb::file_t file,bool owns_file)60 ConnectionGenericFile::ConnectionGenericFile(lldb::file_t file, bool owns_file)
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));
64   InitializeEventHandles();
65 }
66 
~ConnectionGenericFile()67 ConnectionGenericFile::~ConnectionGenericFile() {
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 
InitializeEventHandles()75 void ConnectionGenericFile::InitializeEventHandles() {
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.
84   m_event_handles[kBytesAvailableEvent] =
85       ::CreateEvent(NULL, TRUE, FALSE, NULL);
86 }
87 
IsConnected() const88 bool ConnectionGenericFile::IsConnected() const {
89   return m_file && (m_file != INVALID_HANDLE_VALUE);
90 }
91 
Connect(llvm::StringRef path,Status * error_ptr)92 lldb::ConnectionStatus ConnectionGenericFile::Connect(llvm::StringRef path,
93                                                       Status *error_ptr) {
94   Log *log = GetLog(LLDBLog::Connection);
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();
132   return eConnectionStatusSuccess;
133 }
134 
Disconnect(Status * error_ptr)135 lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Status *error_ptr) {
136   Log *log = GetLog(LLDBLog::Connection);
137   LLDB_LOGF(log, "%p ConnectionGenericFile::Disconnect ()",
138             static_cast<void *>(this));
139 
140   if (!IsConnected())
141     return eConnectionStatusSuccess;
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();
160   return eConnectionStatusSuccess;
161 }
162 
Read(void * dst,size_t dst_len,const Timeout<std::micro> & timeout,lldb::ConnectionStatus & status,Status * error_ptr)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 
179   m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
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 = ::WaitForMultipleObjects(
192           std::size(m_event_handles), m_event_handles, FALSE, milliseconds);
193       // All of the events are manual reset events, so make sure we reset them
194       // to non-signalled.
195       switch (wait_result) {
196       case WAIT_OBJECT_0 + kBytesAvailableEvent:
197         break;
198       case WAIT_OBJECT_0 + kInterruptEvent:
199         return_info.Set(0, eConnectionStatusInterrupted, 0);
200         goto finish;
201       case WAIT_TIMEOUT:
202         return_info.Set(0, eConnectionStatusTimedOut, 0);
203         goto finish;
204       case WAIT_FAILED:
205         return_info.Set(0, eConnectionStatusError, ::GetLastError());
206         goto finish;
207       }
208     }
209     // The data is ready.  Figure out how much was read and return;
210     if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
211       DWORD result_error = ::GetLastError();
212       // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during
213       // a blocking read. This triggers a call to CancelIoEx, which causes the
214       // operation to complete and the result to be ERROR_OPERATION_ABORTED.
215       if (result_error == ERROR_HANDLE_EOF ||
216           result_error == ERROR_OPERATION_ABORTED ||
217           result_error == ERROR_BROKEN_PIPE)
218         return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
219       else
220         return_info.Set(bytes_read, eConnectionStatusError, result_error);
221     } else if (bytes_read == 0)
222       return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
223     else
224       return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
225 
226     goto finish;
227   } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
228     // The write end of a pipe was closed.  This is equivalent to EOF.
229     return_info.Set(0, eConnectionStatusEndOfFile, 0);
230   } else {
231     // An unknown error occurred.  Fail out.
232     return_info.Set(0, eConnectionStatusError, ::GetLastError());
233   }
234   goto finish;
235 
236 finish:
237   status = return_info.GetStatus();
238   if (error_ptr)
239     *error_ptr = return_info.GetError();
240 
241   // kBytesAvailableEvent is a manual reset event.  Make sure it gets reset
242   // here so that any subsequent operations don't immediately see bytes
243   // available.
244   ResetEvent(m_event_handles[kBytesAvailableEvent]);
245 
246   IncrementFilePointer(return_info.GetBytes());
247   Log *log = GetLog(LLDBLog::Connection);
248   LLDB_LOGF(log,
249             "%p ConnectionGenericFile::Read()  handle = %p, dst = %p, "
250             "dst_len = %zu) => %zu, error = %s",
251             static_cast<void *>(this), m_file, dst, dst_len,
252             return_info.GetBytes(), return_info.GetError().AsCString());
253 
254   return return_info.GetBytes();
255 }
256 
Write(const void * src,size_t src_len,lldb::ConnectionStatus & status,Status * error_ptr)257 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
258                                     lldb::ConnectionStatus &status,
259                                     Status *error_ptr) {
260   ReturnInfo return_info;
261   DWORD bytes_written = 0;
262   BOOL result = 0;
263 
264   if (error_ptr)
265     error_ptr->Clear();
266 
267   if (!IsConnected()) {
268     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
269     goto finish;
270   }
271 
272   m_overlapped.hEvent = NULL;
273 
274   // Writes are not interruptible like reads are, so just block until it's
275   // done.
276   result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
277   if (!result && ::GetLastError() != ERROR_IO_PENDING) {
278     return_info.Set(0, eConnectionStatusError, ::GetLastError());
279     goto finish;
280   }
281 
282   if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
283     return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
284     goto finish;
285   }
286 
287   return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
288   goto finish;
289 
290 finish:
291   status = return_info.GetStatus();
292   if (error_ptr)
293     *error_ptr = return_info.GetError();
294 
295   IncrementFilePointer(return_info.GetBytes());
296   Log *log = GetLog(LLDBLog::Connection);
297   LLDB_LOGF(log,
298             "%p ConnectionGenericFile::Write()  handle = %p, src = %p, "
299             "src_len = %zu) => %zu, error = %s",
300             static_cast<void *>(this), m_file, src, src_len,
301             return_info.GetBytes(), return_info.GetError().AsCString());
302   return return_info.GetBytes();
303 }
304 
GetURI()305 std::string ConnectionGenericFile::GetURI() { return m_uri; }
306 
InterruptRead()307 bool ConnectionGenericFile::InterruptRead() {
308   return ::SetEvent(m_event_handles[kInterruptEvent]);
309 }
310 
IncrementFilePointer(DWORD amount)311 void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
312   LARGE_INTEGER old_pos;
313   old_pos.HighPart = m_overlapped.OffsetHigh;
314   old_pos.LowPart = m_overlapped.Offset;
315   old_pos.QuadPart += amount;
316   m_overlapped.Offset = old_pos.LowPart;
317   m_overlapped.OffsetHigh = old_pos.HighPart;
318 }
319