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