xref: /llvm-project/lldb/source/Host/windows/ConnectionGenericFileWindows.cpp (revision b9c1b51e45b845debb76d8658edabca70ca56079)
1 //===-- ConnectionGenericFileWindows.cpp ------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
11 #include "lldb/Core/Error.h"
12 #include "lldb/Core/Log.h"
13 #include "lldb/Host/TimeValue.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
25 // operation function.  Since there is a lot of code to be run before exit
26 // regardless of whether the
27 // operation succeeded or failed, combined with many possible return paths, this
28 // is the cleanest
29 // way to represent it.
30 class ReturnInfo {
31 public:
32   void Set(size_t bytes, ConnectionStatus status, DWORD error_code) {
33     m_error.SetError(error_code, eErrorTypeWin32);
34     m_bytes = bytes;
35     m_status = status;
36   }
37 
38   void Set(size_t bytes, ConnectionStatus status, llvm::StringRef error_msg) {
39     m_error.SetErrorString(error_msg.data());
40     m_bytes = bytes;
41     m_status = status;
42   }
43 
44   size_t GetBytes() const { return m_bytes; }
45   ConnectionStatus GetStatus() const { return m_status; }
46   const Error &GetError() const { return m_error; }
47 
48 private:
49   Error m_error;
50   size_t m_bytes;
51   ConnectionStatus m_status;
52 };
53 }
54 
55 ConnectionGenericFile::ConnectionGenericFile()
56     : m_file(INVALID_HANDLE_VALUE), m_owns_file(false) {
57   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
58   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
59   InitializeEventHandles();
60 }
61 
62 ConnectionGenericFile::ConnectionGenericFile(lldb::file_t file, bool owns_file)
63     : m_file(file), m_owns_file(owns_file) {
64   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
65   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
66   InitializeEventHandles();
67 }
68 
69 ConnectionGenericFile::~ConnectionGenericFile() {
70   if (m_owns_file && IsConnected())
71     ::CloseHandle(m_file);
72 
73   ::CloseHandle(m_event_handles[kBytesAvailableEvent]);
74   ::CloseHandle(m_event_handles[kInterruptEvent]);
75 }
76 
77 void ConnectionGenericFile::InitializeEventHandles() {
78   m_event_handles[kInterruptEvent] = CreateEvent(NULL, FALSE, FALSE, NULL);
79 
80   // Note, we should use a manual reset event for the hEvent argument of the
81   // OVERLAPPED.  This
82   // is because both WaitForMultipleObjects and GetOverlappedResult (if you set
83   // the bWait
84   // argument to TRUE) will wait for the event to be signalled.  If we use an
85   // auto-reset event,
86   // WaitForMultipleObjects will reset the event, return successfully, and then
87   // GetOverlappedResult will block since the event is no longer signalled.
88   m_event_handles[kBytesAvailableEvent] =
89       ::CreateEvent(NULL, TRUE, FALSE, NULL);
90 }
91 
92 bool ConnectionGenericFile::IsConnected() const {
93   return m_file && (m_file != INVALID_HANDLE_VALUE);
94 }
95 
96 lldb::ConnectionStatus ConnectionGenericFile::Connect(const char *s,
97                                                       Error *error_ptr) {
98   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
99   if (log)
100     log->Printf("%p ConnectionGenericFile::Connect (url = '%s')",
101                 static_cast<void *>(this), s);
102 
103   if (strstr(s, "file://") != s) {
104     if (error_ptr)
105       error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
106                                           s);
107     return eConnectionStatusError;
108   }
109 
110   if (IsConnected()) {
111     ConnectionStatus status = Disconnect(error_ptr);
112     if (status != eConnectionStatusSuccess)
113       return status;
114   }
115 
116   // file://PATH
117   const char *path = s + strlen("file://");
118   // Open the file for overlapped access.  If it does not exist, create it.  We
119   // open it overlapped
120   // so that we can issue asynchronous reads and then use WaitForMultipleObjects
121   // to allow the read
122   // to be interrupted by an event object.
123   std::wstring wpath;
124   if (!llvm::ConvertUTF8toWide(path, wpath)) {
125     if (error_ptr)
126       error_ptr->SetError(1, eErrorTypeGeneric);
127     return eConnectionStatusError;
128   }
129   m_file = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
130                          FILE_SHARE_READ, NULL, OPEN_ALWAYS,
131                          FILE_FLAG_OVERLAPPED, NULL);
132   if (m_file == INVALID_HANDLE_VALUE) {
133     if (error_ptr)
134       error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
135     return eConnectionStatusError;
136   }
137 
138   m_owns_file = true;
139   m_uri.assign(s);
140   return eConnectionStatusSuccess;
141 }
142 
143 lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Error *error_ptr) {
144   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
145   if (log)
146     log->Printf("%p ConnectionGenericFile::Disconnect ()",
147                 static_cast<void *>(this));
148 
149   if (!IsConnected())
150     return eConnectionStatusSuccess;
151 
152   // Reset the handle so that after we unblock any pending reads, subsequent
153   // calls to Read() will
154   // see a disconnected state.
155   HANDLE old_file = m_file;
156   m_file = INVALID_HANDLE_VALUE;
157 
158   // Set the disconnect event so that any blocking reads unblock, then cancel
159   // any pending IO operations.
160   ::CancelIoEx(old_file, &m_overlapped);
161 
162   // Close the file handle if we owned it, but don't close the event handles.
163   // We could always
164   // reconnect with the same Connection instance.
165   if (m_owns_file)
166     ::CloseHandle(old_file);
167 
168   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
169   m_owns_file = false;
170   m_uri.clear();
171   return eConnectionStatusSuccess;
172 }
173 
174 size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
175                                    uint32_t timeout_usec,
176                                    lldb::ConnectionStatus &status,
177                                    Error *error_ptr) {
178   ReturnInfo return_info;
179   BOOL result = 0;
180   DWORD bytes_read = 0;
181 
182   if (error_ptr)
183     error_ptr->Clear();
184 
185   if (!IsConnected()) {
186     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
187     goto finish;
188   }
189 
190   m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
191 
192   result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
193   if (result || ::GetLastError() == ERROR_IO_PENDING) {
194     if (!result) {
195       // The expected return path.  The operation is pending.  Wait for the
196       // operation to complete
197       // or be interrupted.
198       TimeValue time_value;
199       time_value.OffsetWithMicroSeconds(timeout_usec);
200       DWORD milliseconds = time_value.milliseconds();
201       DWORD wait_result =
202           ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
203                                    m_event_handles, FALSE, milliseconds);
204       // All of the events are manual reset events, so make sure we reset them
205       // to non-signalled.
206       switch (wait_result) {
207       case WAIT_OBJECT_0 + kBytesAvailableEvent:
208         break;
209       case WAIT_OBJECT_0 + kInterruptEvent:
210         return_info.Set(0, eConnectionStatusInterrupted, 0);
211         goto finish;
212       case WAIT_TIMEOUT:
213         return_info.Set(0, eConnectionStatusTimedOut, 0);
214         goto finish;
215       case WAIT_FAILED:
216         return_info.Set(0, eConnectionStatusError, ::GetLastError());
217         goto finish;
218       }
219     }
220     // The data is ready.  Figure out how much was read and return;
221     if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
222       DWORD result_error = ::GetLastError();
223       // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during a
224       // blocking read.
225       // This triggers a call to CancelIoEx, which causes the operation to
226       // complete and the
227       // result to be ERROR_OPERATION_ABORTED.
228       if (result_error == ERROR_HANDLE_EOF ||
229           result_error == ERROR_OPERATION_ABORTED ||
230           result_error == ERROR_BROKEN_PIPE)
231         return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
232       else
233         return_info.Set(bytes_read, eConnectionStatusError, result_error);
234     } else if (bytes_read == 0)
235       return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
236     else
237       return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
238 
239     goto finish;
240   } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
241     // The write end of a pipe was closed.  This is equivalent to EOF.
242     return_info.Set(0, eConnectionStatusEndOfFile, 0);
243   } else {
244     // An unknown error occurred.  Fail out.
245     return_info.Set(0, eConnectionStatusError, ::GetLastError());
246   }
247   goto finish;
248 
249 finish:
250   status = return_info.GetStatus();
251   if (error_ptr)
252     *error_ptr = return_info.GetError();
253 
254   // kBytesAvailableEvent is a manual reset event.  Make sure it gets reset here
255   // so that any
256   // subsequent operations don't immediately see bytes available.
257   ResetEvent(m_event_handles[kBytesAvailableEvent]);
258 
259   IncrementFilePointer(return_info.GetBytes());
260   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
261   if (log) {
262     log->Printf("%" PRIxPTR " ConnectionGenericFile::Read()  handle = %" PRIxPTR
263                 ", dst = %" PRIxPTR ", dst_len = %" PRIu64 ") => %" PRIu64
264                 ", error = %s",
265                 this, m_file, dst, static_cast<uint64_t>(dst_len),
266                 static_cast<uint64_t>(return_info.GetBytes()),
267                 return_info.GetError().AsCString());
268   }
269 
270   return return_info.GetBytes();
271 }
272 
273 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
274                                     lldb::ConnectionStatus &status,
275                                     Error *error_ptr) {
276   ReturnInfo return_info;
277   DWORD bytes_written = 0;
278   BOOL result = 0;
279 
280   if (error_ptr)
281     error_ptr->Clear();
282 
283   if (!IsConnected()) {
284     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
285     goto finish;
286   }
287 
288   m_overlapped.hEvent = NULL;
289 
290   // Writes are not interruptible like reads are, so just block until it's done.
291   result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
292   if (!result && ::GetLastError() != ERROR_IO_PENDING) {
293     return_info.Set(0, eConnectionStatusError, ::GetLastError());
294     goto finish;
295   }
296 
297   if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
298     return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
299     goto finish;
300   }
301 
302   return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
303   goto finish;
304 
305 finish:
306   status = return_info.GetStatus();
307   if (error_ptr)
308     *error_ptr = return_info.GetError();
309 
310   IncrementFilePointer(return_info.GetBytes());
311   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
312   if (log) {
313     log->Printf("%" PRIxPTR
314                 " ConnectionGenericFile::Write()  handle = %" PRIxPTR
315                 ", src = %" PRIxPTR ", src_len = %" PRIu64 ") => %" PRIu64
316                 ", error = %s",
317                 this, m_file, src, static_cast<uint64_t>(src_len),
318                 static_cast<uint64_t>(return_info.GetBytes()),
319                 return_info.GetError().AsCString());
320   }
321   return return_info.GetBytes();
322 }
323 
324 std::string ConnectionGenericFile::GetURI() { return m_uri; }
325 
326 bool ConnectionGenericFile::InterruptRead() {
327   return ::SetEvent(m_event_handles[kInterruptEvent]);
328 }
329 
330 void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
331   LARGE_INTEGER old_pos;
332   old_pos.HighPart = m_overlapped.OffsetHigh;
333   old_pos.LowPart = m_overlapped.Offset;
334   old_pos.QuadPart += amount;
335   m_overlapped.Offset = old_pos.LowPart;
336   m_overlapped.OffsetHigh = old_pos.HighPart;
337 }
338