180814287SRaphael Isemann //===-- ConnectionGenericFileWindows.cpp ----------------------------------===//
212792af0SZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
612792af0SZachary Turner //
712792af0SZachary Turner //===----------------------------------------------------------------------===//
812792af0SZachary Turner 
9b9c1b51eSKate Stone #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
10*c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
116f9e6901SZachary Turner #include "lldb/Utility/Log.h"
1297206d57SZachary Turner #include "lldb/Utility/Status.h"
132f3df613SZachary Turner #include "lldb/Utility/Timeout.h"
1412792af0SZachary Turner 
1512792af0SZachary Turner #include "llvm/ADT/STLExtras.h"
1612792af0SZachary Turner #include "llvm/ADT/StringRef.h"
17190fadcdSZachary Turner #include "llvm/Support/ConvertUTF.h"
1812792af0SZachary Turner 
1912792af0SZachary Turner using namespace lldb;
2012792af0SZachary Turner using namespace lldb_private;
2112792af0SZachary Turner 
22b9c1b51eSKate Stone namespace {
23b9c1b51eSKate Stone // This is a simple helper class to package up the information needed to return
2405097246SAdrian Prantl // from a Read/Write operation function.  Since there is a lot of code to be
2505097246SAdrian Prantl // run before exit regardless of whether the operation succeeded or failed,
2605097246SAdrian Prantl // combined with many possible return paths, this is the cleanest way to
2705097246SAdrian Prantl // represent it.
28b9c1b51eSKate Stone class ReturnInfo {
2912792af0SZachary Turner public:
Set(size_t bytes,ConnectionStatus status,DWORD error_code)30b9c1b51eSKate Stone   void Set(size_t bytes, ConnectionStatus status, DWORD error_code) {
3112792af0SZachary Turner     m_error.SetError(error_code, eErrorTypeWin32);
3212792af0SZachary Turner     m_bytes = bytes;
3312792af0SZachary Turner     m_status = status;
3412792af0SZachary Turner   }
3512792af0SZachary Turner 
Set(size_t bytes,ConnectionStatus status,llvm::StringRef error_msg)36b9c1b51eSKate Stone   void Set(size_t bytes, ConnectionStatus status, llvm::StringRef error_msg) {
3712792af0SZachary Turner     m_error.SetErrorString(error_msg.data());
3812792af0SZachary Turner     m_bytes = bytes;
3912792af0SZachary Turner     m_status = status;
4012792af0SZachary Turner   }
4112792af0SZachary Turner 
GetBytes() const42b9c1b51eSKate Stone   size_t GetBytes() const { return m_bytes; }
GetStatus() const43b9c1b51eSKate Stone   ConnectionStatus GetStatus() const { return m_status; }
GetError() const4497206d57SZachary Turner   const Status &GetError() const { return m_error; }
4512792af0SZachary Turner 
4612792af0SZachary Turner private:
4797206d57SZachary Turner   Status m_error;
4812792af0SZachary Turner   size_t m_bytes;
4912792af0SZachary Turner   ConnectionStatus m_status;
5012792af0SZachary Turner };
5112792af0SZachary Turner }
5212792af0SZachary Turner 
ConnectionGenericFile()5312792af0SZachary Turner ConnectionGenericFile::ConnectionGenericFile()
54b9c1b51eSKate Stone     : m_file(INVALID_HANDLE_VALUE), m_owns_file(false) {
5512792af0SZachary Turner   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
5612792af0SZachary Turner   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
5712792af0SZachary Turner   InitializeEventHandles();
5812792af0SZachary Turner }
5912792af0SZachary Turner 
ConnectionGenericFile(lldb::file_t file,bool owns_file)6012792af0SZachary Turner ConnectionGenericFile::ConnectionGenericFile(lldb::file_t file, bool owns_file)
61b9c1b51eSKate Stone     : m_file(file), m_owns_file(owns_file) {
6212792af0SZachary Turner   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
6312792af0SZachary Turner   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
6412792af0SZachary Turner   InitializeEventHandles();
6512792af0SZachary Turner }
6612792af0SZachary Turner 
~ConnectionGenericFile()67b9c1b51eSKate Stone ConnectionGenericFile::~ConnectionGenericFile() {
6812792af0SZachary Turner   if (m_owns_file && IsConnected())
6912792af0SZachary Turner     ::CloseHandle(m_file);
7012792af0SZachary Turner 
7112792af0SZachary Turner   ::CloseHandle(m_event_handles[kBytesAvailableEvent]);
7212792af0SZachary Turner   ::CloseHandle(m_event_handles[kInterruptEvent]);
7312792af0SZachary Turner }
7412792af0SZachary Turner 
InitializeEventHandles()75b9c1b51eSKate Stone void ConnectionGenericFile::InitializeEventHandles() {
7612792af0SZachary Turner   m_event_handles[kInterruptEvent] = CreateEvent(NULL, FALSE, FALSE, NULL);
7712792af0SZachary Turner 
78b9c1b51eSKate Stone   // Note, we should use a manual reset event for the hEvent argument of the
7905097246SAdrian Prantl   // OVERLAPPED.  This is because both WaitForMultipleObjects and
8005097246SAdrian Prantl   // GetOverlappedResult (if you set the bWait argument to TRUE) will wait for
8105097246SAdrian Prantl   // the event to be signalled.  If we use an auto-reset event,
8212792af0SZachary Turner   // WaitForMultipleObjects will reset the event, return successfully, and then
8312792af0SZachary Turner   // GetOverlappedResult will block since the event is no longer signalled.
84b9c1b51eSKate Stone   m_event_handles[kBytesAvailableEvent] =
85b9c1b51eSKate Stone       ::CreateEvent(NULL, TRUE, FALSE, NULL);
8612792af0SZachary Turner }
8712792af0SZachary Turner 
IsConnected() const88b9c1b51eSKate Stone bool ConnectionGenericFile::IsConnected() const {
8912792af0SZachary Turner   return m_file && (m_file != INVALID_HANDLE_VALUE);
9012792af0SZachary Turner }
9112792af0SZachary Turner 
Connect(llvm::StringRef path,Status * error_ptr)923165945aSZachary Turner lldb::ConnectionStatus ConnectionGenericFile::Connect(llvm::StringRef path,
9397206d57SZachary Turner                                                       Status *error_ptr) {
94a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Connection);
9563e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%p ConnectionGenericFile::Connect (url = '%s')",
963165945aSZachary Turner             static_cast<void *>(this), path.str().c_str());
9712792af0SZachary Turner 
983165945aSZachary Turner   if (!path.consume_front("file://")) {
9912792af0SZachary Turner     if (error_ptr)
100b9c1b51eSKate Stone       error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
1013165945aSZachary Turner                                           path.str().c_str());
10212792af0SZachary Turner     return eConnectionStatusError;
10312792af0SZachary Turner   }
10412792af0SZachary Turner 
105b9c1b51eSKate Stone   if (IsConnected()) {
10612792af0SZachary Turner     ConnectionStatus status = Disconnect(error_ptr);
10712792af0SZachary Turner     if (status != eConnectionStatusSuccess)
10812792af0SZachary Turner       return status;
10912792af0SZachary Turner   }
11012792af0SZachary Turner 
111b9c1b51eSKate Stone   // Open the file for overlapped access.  If it does not exist, create it.  We
1123165945aSZachary Turner   // open it overlapped so that we can issue asynchronous reads and then use
1133165945aSZachary Turner   // WaitForMultipleObjects to allow the read to be interrupted by an event
1143165945aSZachary Turner   // object.
115190fadcdSZachary Turner   std::wstring wpath;
116b9c1b51eSKate Stone   if (!llvm::ConvertUTF8toWide(path, wpath)) {
117190fadcdSZachary Turner     if (error_ptr)
118190fadcdSZachary Turner       error_ptr->SetError(1, eErrorTypeGeneric);
119190fadcdSZachary Turner     return eConnectionStatusError;
120190fadcdSZachary Turner   }
121b9c1b51eSKate Stone   m_file = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
122b9c1b51eSKate Stone                          FILE_SHARE_READ, NULL, OPEN_ALWAYS,
123190fadcdSZachary Turner                          FILE_FLAG_OVERLAPPED, NULL);
124b9c1b51eSKate Stone   if (m_file == INVALID_HANDLE_VALUE) {
12512792af0SZachary Turner     if (error_ptr)
12612792af0SZachary Turner       error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
12712792af0SZachary Turner     return eConnectionStatusError;
12812792af0SZachary Turner   }
12912792af0SZachary Turner 
13012792af0SZachary Turner   m_owns_file = true;
1317a6ebb5bSPavel Labath   m_uri = path.str();
13212792af0SZachary Turner   return eConnectionStatusSuccess;
13312792af0SZachary Turner }
13412792af0SZachary Turner 
Disconnect(Status * error_ptr)13597206d57SZachary Turner lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Status *error_ptr) {
136a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Connection);
13763e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%p ConnectionGenericFile::Disconnect ()",
138b9c1b51eSKate Stone             static_cast<void *>(this));
13912792af0SZachary Turner 
14012792af0SZachary Turner   if (!IsConnected())
14112792af0SZachary Turner     return eConnectionStatusSuccess;
14212792af0SZachary Turner 
143b9c1b51eSKate Stone   // Reset the handle so that after we unblock any pending reads, subsequent
14405097246SAdrian Prantl   // calls to Read() will see a disconnected state.
14512792af0SZachary Turner   HANDLE old_file = m_file;
14612792af0SZachary Turner   m_file = INVALID_HANDLE_VALUE;
14712792af0SZachary Turner 
148b9c1b51eSKate Stone   // Set the disconnect event so that any blocking reads unblock, then cancel
149b9c1b51eSKate Stone   // any pending IO operations.
15012792af0SZachary Turner   ::CancelIoEx(old_file, &m_overlapped);
15112792af0SZachary Turner 
152b9c1b51eSKate Stone   // Close the file handle if we owned it, but don't close the event handles.
15305097246SAdrian Prantl   // We could always reconnect with the same Connection instance.
15412792af0SZachary Turner   if (m_owns_file)
15512792af0SZachary Turner     ::CloseHandle(old_file);
15612792af0SZachary Turner 
15712792af0SZachary Turner   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
15812792af0SZachary Turner   m_owns_file = false;
159eb303ee5SVince Harron   m_uri.clear();
16012792af0SZachary Turner   return eConnectionStatusSuccess;
16112792af0SZachary Turner }
16212792af0SZachary Turner 
Read(void * dst,size_t dst_len,const Timeout<std::micro> & timeout,lldb::ConnectionStatus & status,Status * error_ptr)163b9c1b51eSKate Stone size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
164ce8d6d9cSPavel Labath                                    const Timeout<std::micro> &timeout,
165b9c1b51eSKate Stone                                    lldb::ConnectionStatus &status,
16697206d57SZachary Turner                                    Status *error_ptr) {
16712792af0SZachary Turner   ReturnInfo return_info;
168ae944608SHafiz Abid Qadeer   BOOL result = 0;
169ae944608SHafiz Abid Qadeer   DWORD bytes_read = 0;
17012792af0SZachary Turner 
17112792af0SZachary Turner   if (error_ptr)
17212792af0SZachary Turner     error_ptr->Clear();
17312792af0SZachary Turner 
174b9c1b51eSKate Stone   if (!IsConnected()) {
17512792af0SZachary Turner     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
17612792af0SZachary Turner     goto finish;
17712792af0SZachary Turner   }
17812792af0SZachary Turner 
17912792af0SZachary Turner   m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
18012792af0SZachary Turner 
181ae944608SHafiz Abid Qadeer   result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
182b9c1b51eSKate Stone   if (result || ::GetLastError() == ERROR_IO_PENDING) {
183b9c1b51eSKate Stone     if (!result) {
184b9c1b51eSKate Stone       // The expected return path.  The operation is pending.  Wait for the
18505097246SAdrian Prantl       // operation to complete or be interrupted.
186ce8d6d9cSPavel Labath       DWORD milliseconds =
187ce8d6d9cSPavel Labath           timeout
188ce8d6d9cSPavel Labath               ? std::chrono::duration_cast<std::chrono::milliseconds>(*timeout)
189ce8d6d9cSPavel Labath                     .count()
190ce8d6d9cSPavel Labath               : INFINITE;
191b9c1b51eSKate Stone       DWORD wait_result =
192f15014ffSBenjamin Kramer           ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
193b9c1b51eSKate Stone                                    m_event_handles, FALSE, milliseconds);
194b9c1b51eSKate Stone       // All of the events are manual reset events, so make sure we reset them
195b9c1b51eSKate Stone       // to non-signalled.
196b9c1b51eSKate Stone       switch (wait_result) {
19712792af0SZachary Turner       case WAIT_OBJECT_0 + kBytesAvailableEvent:
19812792af0SZachary Turner         break;
19912792af0SZachary Turner       case WAIT_OBJECT_0 + kInterruptEvent:
20012792af0SZachary Turner         return_info.Set(0, eConnectionStatusInterrupted, 0);
20112792af0SZachary Turner         goto finish;
20212792af0SZachary Turner       case WAIT_TIMEOUT:
20312792af0SZachary Turner         return_info.Set(0, eConnectionStatusTimedOut, 0);
20412792af0SZachary Turner         goto finish;
20512792af0SZachary Turner       case WAIT_FAILED:
20612792af0SZachary Turner         return_info.Set(0, eConnectionStatusError, ::GetLastError());
20712792af0SZachary Turner         goto finish;
20812792af0SZachary Turner       }
20912792af0SZachary Turner     }
21012792af0SZachary Turner     // The data is ready.  Figure out how much was read and return;
211b9c1b51eSKate Stone     if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
21212792af0SZachary Turner       DWORD result_error = ::GetLastError();
21305097246SAdrian Prantl       // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during
21405097246SAdrian Prantl       // a blocking read. This triggers a call to CancelIoEx, which causes the
21505097246SAdrian Prantl       // operation to complete and the result to be ERROR_OPERATION_ABORTED.
216b9c1b51eSKate Stone       if (result_error == ERROR_HANDLE_EOF ||
217b9c1b51eSKate Stone           result_error == ERROR_OPERATION_ABORTED ||
218b9c1b51eSKate Stone           result_error == ERROR_BROKEN_PIPE)
21912792af0SZachary Turner         return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
22012792af0SZachary Turner       else
22112792af0SZachary Turner         return_info.Set(bytes_read, eConnectionStatusError, result_error);
222b9c1b51eSKate Stone     } else if (bytes_read == 0)
22312792af0SZachary Turner       return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
22412792af0SZachary Turner     else
22512792af0SZachary Turner       return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
22612792af0SZachary Turner 
22712792af0SZachary Turner     goto finish;
228b9c1b51eSKate Stone   } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
229b2df30d6SZachary Turner     // The write end of a pipe was closed.  This is equivalent to EOF.
230b2df30d6SZachary Turner     return_info.Set(0, eConnectionStatusEndOfFile, 0);
231b9c1b51eSKate Stone   } else {
232e171da5cSBruce Mitchener     // An unknown error occurred.  Fail out.
23312792af0SZachary Turner     return_info.Set(0, eConnectionStatusError, ::GetLastError());
234b2df30d6SZachary Turner   }
23512792af0SZachary Turner   goto finish;
23612792af0SZachary Turner 
23712792af0SZachary Turner finish:
23812792af0SZachary Turner   status = return_info.GetStatus();
23912792af0SZachary Turner   if (error_ptr)
24012792af0SZachary Turner     *error_ptr = return_info.GetError();
24112792af0SZachary Turner 
24205097246SAdrian Prantl   // kBytesAvailableEvent is a manual reset event.  Make sure it gets reset
24305097246SAdrian Prantl   // here so that any subsequent operations don't immediately see bytes
24405097246SAdrian Prantl   // available.
24512792af0SZachary Turner   ResetEvent(m_event_handles[kBytesAvailableEvent]);
24612792af0SZachary Turner 
24712792af0SZachary Turner   IncrementFilePointer(return_info.GetBytes());
248a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Connection);
24963e5fb76SJonas Devlieghere   LLDB_LOGF(log,
25063e5fb76SJonas Devlieghere             "%p ConnectionGenericFile::Read()  handle = %p, dst = %p, "
2515a8ad459SZachary Turner             "dst_len = %zu) => %zu, error = %s",
252d67b0997SMartin Storsjo             static_cast<void *>(this), m_file, dst, dst_len,
253d67b0997SMartin Storsjo             return_info.GetBytes(), return_info.GetError().AsCString());
25412792af0SZachary Turner 
25512792af0SZachary Turner   return return_info.GetBytes();
25612792af0SZachary Turner }
25712792af0SZachary Turner 
Write(const void * src,size_t src_len,lldb::ConnectionStatus & status,Status * error_ptr)258b9c1b51eSKate Stone size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
259b9c1b51eSKate Stone                                     lldb::ConnectionStatus &status,
26097206d57SZachary Turner                                     Status *error_ptr) {
26112792af0SZachary Turner   ReturnInfo return_info;
262ae944608SHafiz Abid Qadeer   DWORD bytes_written = 0;
263ae944608SHafiz Abid Qadeer   BOOL result = 0;
26412792af0SZachary Turner 
26512792af0SZachary Turner   if (error_ptr)
26612792af0SZachary Turner     error_ptr->Clear();
26712792af0SZachary Turner 
268b9c1b51eSKate Stone   if (!IsConnected()) {
26912792af0SZachary Turner     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
27012792af0SZachary Turner     goto finish;
27112792af0SZachary Turner   }
27212792af0SZachary Turner 
27312792af0SZachary Turner   m_overlapped.hEvent = NULL;
27412792af0SZachary Turner 
27505097246SAdrian Prantl   // Writes are not interruptible like reads are, so just block until it's
27605097246SAdrian Prantl   // done.
277ae944608SHafiz Abid Qadeer   result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
278b9c1b51eSKate Stone   if (!result && ::GetLastError() != ERROR_IO_PENDING) {
27912792af0SZachary Turner     return_info.Set(0, eConnectionStatusError, ::GetLastError());
28012792af0SZachary Turner     goto finish;
28112792af0SZachary Turner   }
28212792af0SZachary Turner 
283b9c1b51eSKate Stone   if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
28412792af0SZachary Turner     return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
28512792af0SZachary Turner     goto finish;
28612792af0SZachary Turner   }
28712792af0SZachary Turner 
28812792af0SZachary Turner   return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
28912792af0SZachary Turner   goto finish;
29012792af0SZachary Turner 
29112792af0SZachary Turner finish:
29212792af0SZachary Turner   status = return_info.GetStatus();
29312792af0SZachary Turner   if (error_ptr)
29412792af0SZachary Turner     *error_ptr = return_info.GetError();
29512792af0SZachary Turner 
29612792af0SZachary Turner   IncrementFilePointer(return_info.GetBytes());
297a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Connection);
29863e5fb76SJonas Devlieghere   LLDB_LOGF(log,
29963e5fb76SJonas Devlieghere             "%p ConnectionGenericFile::Write()  handle = %p, src = %p, "
3005a8ad459SZachary Turner             "src_len = %zu) => %zu, error = %s",
301d67b0997SMartin Storsjo             static_cast<void *>(this), m_file, src, src_len,
302d67b0997SMartin Storsjo             return_info.GetBytes(), return_info.GetError().AsCString());
30312792af0SZachary Turner   return return_info.GetBytes();
30412792af0SZachary Turner }
30512792af0SZachary Turner 
GetURI()306b9c1b51eSKate Stone std::string ConnectionGenericFile::GetURI() { return m_uri; }
307eb303ee5SVince Harron 
InterruptRead()308b9c1b51eSKate Stone bool ConnectionGenericFile::InterruptRead() {
30912792af0SZachary Turner   return ::SetEvent(m_event_handles[kInterruptEvent]);
31012792af0SZachary Turner }
31112792af0SZachary Turner 
IncrementFilePointer(DWORD amount)312b9c1b51eSKate Stone void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
31312792af0SZachary Turner   LARGE_INTEGER old_pos;
31412792af0SZachary Turner   old_pos.HighPart = m_overlapped.OffsetHigh;
31512792af0SZachary Turner   old_pos.LowPart = m_overlapped.Offset;
31612792af0SZachary Turner   old_pos.QuadPart += amount;
31712792af0SZachary Turner   m_overlapped.Offset = old_pos.LowPart;
31812792af0SZachary Turner   m_overlapped.OffsetHigh = old_pos.HighPart;
31912792af0SZachary Turner }
320