180814287SRaphael Isemann //===-- AdbClient.cpp -----------------------------------------------------===//
205a55de3SOleksiy Vyalov //
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
605a55de3SOleksiy Vyalov //
705a55de3SOleksiy Vyalov //===----------------------------------------------------------------------===//
805a55de3SOleksiy Vyalov 
96e181cf3SOleksiy Vyalov #include "AdbClient.h"
106e181cf3SOleksiy Vyalov 
11b9c1b51eSKate Stone #include "llvm/ADT/STLExtras.h"
1205a55de3SOleksiy Vyalov #include "llvm/ADT/SmallVector.h"
1305a55de3SOleksiy Vyalov #include "llvm/ADT/StringRef.h"
1409e9079dSOleksiy Vyalov #include "llvm/Support/FileUtilities.h"
1505a55de3SOleksiy Vyalov 
166e181cf3SOleksiy Vyalov #include "lldb/Host/ConnectionFileDescriptor.h"
171408bf72SPavel Labath #include "lldb/Host/FileSystem.h"
18f343968fSZachary Turner #include "lldb/Host/PosixApi.h"
19666cc0b2SZachary Turner #include "lldb/Utility/DataBuffer.h"
20666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
21666cc0b2SZachary Turner #include "lldb/Utility/DataEncoder.h"
22666cc0b2SZachary Turner #include "lldb/Utility/DataExtractor.h"
235713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
24bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
252f3df613SZachary Turner #include "lldb/Utility/Timeout.h"
2605a55de3SOleksiy Vyalov 
2776e47d48SRaphael Isemann #include <climits>
2809e9079dSOleksiy Vyalov 
296f001068SOleksiy Vyalov #include <algorithm>
30c6ac2e1eSOleksiy Vyalov #include <cstdlib>
3109e9079dSOleksiy Vyalov #include <fstream>
3205a55de3SOleksiy Vyalov #include <sstream>
3305a55de3SOleksiy Vyalov 
341341d4cdSAdrian McCarthy // On Windows, transitive dependencies pull in <Windows.h>, which defines a
351341d4cdSAdrian McCarthy // macro that clashes with a method name.
361341d4cdSAdrian McCarthy #ifdef SendMessage
371341d4cdSAdrian McCarthy #undef SendMessage
381341d4cdSAdrian McCarthy #endif
391341d4cdSAdrian McCarthy 
4005a55de3SOleksiy Vyalov using namespace lldb;
4105a55de3SOleksiy Vyalov using namespace lldb_private;
42db264a6dSTamas Berghammer using namespace lldb_private::platform_android;
43818dd516SPavel Labath using namespace std::chrono;
4405a55de3SOleksiy Vyalov 
4593c1b3caSPavel Labath static const seconds kReadTimeout(20);
4693c1b3caSPavel Labath static const char *kOKAY = "OKAY";
4793c1b3caSPavel Labath static const char *kFAIL = "FAIL";
4893c1b3caSPavel Labath static const char *kDATA = "DATA";
4993c1b3caSPavel Labath static const char *kDONE = "DONE";
5005a55de3SOleksiy Vyalov 
5193c1b3caSPavel Labath static const char *kSEND = "SEND";
5293c1b3caSPavel Labath static const char *kRECV = "RECV";
5393c1b3caSPavel Labath static const char *kSTAT = "STAT";
546002a31bSOleksiy Vyalov 
5593c1b3caSPavel Labath static const size_t kSyncPacketLen = 8;
5662efb1f6SRobert Flack // Maximum size of a filesync DATA packet.
5793c1b3caSPavel Labath static const size_t kMaxPushData = 2 * 1024;
5862efb1f6SRobert Flack // Default mode for pushed files.
5993c1b3caSPavel Labath static const uint32_t kDefaultMode = 0100770; // S_IFREG | S_IRWXU | S_IRWXG
6005a55de3SOleksiy Vyalov 
6193c1b3caSPavel Labath static const char *kSocketNamespaceAbstract = "localabstract";
6293c1b3caSPavel Labath static const char *kSocketNamespaceFileSystem = "localfilesystem";
63e7df5f5dSOleksiy Vyalov 
ReadAllBytes(Connection & conn,void * buffer,size_t size)6493c1b3caSPavel Labath static Status ReadAllBytes(Connection &conn, void *buffer, size_t size) {
656e181cf3SOleksiy Vyalov 
6697206d57SZachary Turner   Status error;
676e181cf3SOleksiy Vyalov   ConnectionStatus status;
686e181cf3SOleksiy Vyalov   char *read_buffer = static_cast<char *>(buffer);
696e181cf3SOleksiy Vyalov 
706e181cf3SOleksiy Vyalov   auto now = steady_clock::now();
716e181cf3SOleksiy Vyalov   const auto deadline = now + kReadTimeout;
726e181cf3SOleksiy Vyalov   size_t total_read_bytes = 0;
73b9c1b51eSKate Stone   while (total_read_bytes < size && now < deadline) {
746e181cf3SOleksiy Vyalov     auto read_bytes =
75b9c1b51eSKate Stone         conn.Read(read_buffer + total_read_bytes, size - total_read_bytes,
762f159a5fSPavel Labath                   duration_cast<microseconds>(deadline - now), status, &error);
776e181cf3SOleksiy Vyalov     if (error.Fail())
786e181cf3SOleksiy Vyalov       return error;
796e181cf3SOleksiy Vyalov     total_read_bytes += read_bytes;
806e181cf3SOleksiy Vyalov     if (status != eConnectionStatusSuccess)
816e181cf3SOleksiy Vyalov       break;
826e181cf3SOleksiy Vyalov     now = steady_clock::now();
836e181cf3SOleksiy Vyalov   }
846e181cf3SOleksiy Vyalov   if (total_read_bytes < size)
8597206d57SZachary Turner     error = Status(
86b9c1b51eSKate Stone         "Unable to read requested number of bytes. Connection status: %d.",
87b9c1b51eSKate Stone         status);
886e181cf3SOleksiy Vyalov   return error;
896e181cf3SOleksiy Vyalov }
906e181cf3SOleksiy Vyalov 
CreateByDeviceID(const std::string & device_id,AdbClient & adb)9197206d57SZachary Turner Status AdbClient::CreateByDeviceID(const std::string &device_id,
92b9c1b51eSKate Stone                                    AdbClient &adb) {
937ff2de4fSEmre Kultursay   Status error;
943db04919SLuke Drummond   std::string android_serial;
953db04919SLuke Drummond   if (!device_id.empty())
963db04919SLuke Drummond     android_serial = device_id;
973db04919SLuke Drummond   else if (const char *env_serial = std::getenv("ANDROID_SERIAL"))
983db04919SLuke Drummond     android_serial = env_serial;
993db04919SLuke Drummond 
100b9c1b51eSKate Stone   if (android_serial.empty()) {
1017ff2de4fSEmre Kultursay     DeviceIDList connected_devices;
1027ff2de4fSEmre Kultursay     error = adb.GetDevices(connected_devices);
1037ff2de4fSEmre Kultursay     if (error.Fail())
1047ff2de4fSEmre Kultursay       return error;
1057ff2de4fSEmre Kultursay 
1067ff2de4fSEmre Kultursay     if (connected_devices.size() != 1)
10797206d57SZachary Turner       return Status("Expected a single connected device, got instead %zu - try "
108b9c1b51eSKate Stone                     "setting 'ANDROID_SERIAL'",
1097ff2de4fSEmre Kultursay                     connected_devices.size());
1107ff2de4fSEmre Kultursay     adb.SetDeviceID(connected_devices.front());
111b9c1b51eSKate Stone   } else {
1127ff2de4fSEmre Kultursay     adb.SetDeviceID(android_serial);
1136f001068SOleksiy Vyalov   }
1146f001068SOleksiy Vyalov   return error;
1156f001068SOleksiy Vyalov }
1166f001068SOleksiy Vyalov 
117fd2433e1SJonas Devlieghere AdbClient::AdbClient() = default;
1186e181cf3SOleksiy Vyalov 
AdbClient(const std::string & device_id)119b9c1b51eSKate Stone AdbClient::AdbClient(const std::string &device_id) : m_device_id(device_id) {}
12005a55de3SOleksiy Vyalov 
121fd2433e1SJonas Devlieghere AdbClient::~AdbClient() = default;
1226e181cf3SOleksiy Vyalov 
SetDeviceID(const std::string & device_id)123b9c1b51eSKate Stone void AdbClient::SetDeviceID(const std::string &device_id) {
12405a55de3SOleksiy Vyalov   m_device_id = device_id;
12505a55de3SOleksiy Vyalov }
12605a55de3SOleksiy Vyalov 
GetDeviceID() const127b9c1b51eSKate Stone const std::string &AdbClient::GetDeviceID() const { return m_device_id; }
1286f001068SOleksiy Vyalov 
Connect()12997206d57SZachary Turner Status AdbClient::Connect() {
13097206d57SZachary Turner   Status error;
13106412daeSJonas Devlieghere   m_conn = std::make_unique<ConnectionFileDescriptor>();
1320c01d920SNathan Lanza   std::string port = "5037";
1330c01d920SNathan Lanza   if (const char *env_port = std::getenv("ANDROID_ADB_SERVER_PORT")) {
1340c01d920SNathan Lanza     port = env_port;
1350c01d920SNathan Lanza   }
136a9d7b458SEmre Kultursay   std::string uri = "connect://127.0.0.1:" + port;
1370c01d920SNathan Lanza   m_conn->Connect(uri.c_str(), &error);
13805a55de3SOleksiy Vyalov 
13905a55de3SOleksiy Vyalov   return error;
14005a55de3SOleksiy Vyalov }
14105a55de3SOleksiy Vyalov 
GetDevices(DeviceIDList & device_list)14297206d57SZachary Turner Status AdbClient::GetDevices(DeviceIDList &device_list) {
14305a55de3SOleksiy Vyalov   device_list.clear();
14405a55de3SOleksiy Vyalov 
14505a55de3SOleksiy Vyalov   auto error = SendMessage("host:devices");
14605a55de3SOleksiy Vyalov   if (error.Fail())
14705a55de3SOleksiy Vyalov     return error;
14805a55de3SOleksiy Vyalov 
14905a55de3SOleksiy Vyalov   error = ReadResponseStatus();
15005a55de3SOleksiy Vyalov   if (error.Fail())
15105a55de3SOleksiy Vyalov     return error;
15205a55de3SOleksiy Vyalov 
15309e9079dSOleksiy Vyalov   std::vector<char> in_buffer;
15405a55de3SOleksiy Vyalov   error = ReadMessage(in_buffer);
15505a55de3SOleksiy Vyalov 
15609e9079dSOleksiy Vyalov   llvm::StringRef response(&in_buffer[0], in_buffer.size());
15705a55de3SOleksiy Vyalov   llvm::SmallVector<llvm::StringRef, 4> devices;
15805a55de3SOleksiy Vyalov   response.split(devices, "\n", -1, false);
15905a55de3SOleksiy Vyalov 
1608dc7b982SMark de Wever   for (const auto &device : devices)
161adcd0268SBenjamin Kramer     device_list.push_back(std::string(device.split('\t').first));
16205a55de3SOleksiy Vyalov 
16305097246SAdrian Prantl   // Force disconnect since ADB closes connection after host:devices response
16405097246SAdrian Prantl   // is sent.
1656e181cf3SOleksiy Vyalov   m_conn.reset();
16605a55de3SOleksiy Vyalov   return error;
16705a55de3SOleksiy Vyalov }
16805a55de3SOleksiy Vyalov 
SetPortForwarding(const uint16_t local_port,const uint16_t remote_port)16997206d57SZachary Turner Status AdbClient::SetPortForwarding(const uint16_t local_port,
170b9c1b51eSKate Stone                                     const uint16_t remote_port) {
17105a55de3SOleksiy Vyalov   char message[48];
172b9c1b51eSKate Stone   snprintf(message, sizeof(message), "forward:tcp:%d;tcp:%d", local_port,
173b9c1b51eSKate Stone            remote_port);
17405a55de3SOleksiy Vyalov 
17505a55de3SOleksiy Vyalov   const auto error = SendDeviceMessage(message);
17605a55de3SOleksiy Vyalov   if (error.Fail())
17705a55de3SOleksiy Vyalov     return error;
17805a55de3SOleksiy Vyalov 
17905a55de3SOleksiy Vyalov   return ReadResponseStatus();
18005a55de3SOleksiy Vyalov }
18105a55de3SOleksiy Vyalov 
18297206d57SZachary Turner Status
SetPortForwarding(const uint16_t local_port,llvm::StringRef remote_socket_name,const UnixSocketNamespace socket_namespace)18397206d57SZachary Turner AdbClient::SetPortForwarding(const uint16_t local_port,
184245f7fdcSZachary Turner                              llvm::StringRef remote_socket_name,
185b9c1b51eSKate Stone                              const UnixSocketNamespace socket_namespace) {
1869fe526c2SOleksiy Vyalov   char message[PATH_MAX];
187b9c1b51eSKate Stone   const char *sock_namespace_str =
188b9c1b51eSKate Stone       (socket_namespace == UnixSocketNamespaceAbstract)
189b9c1b51eSKate Stone           ? kSocketNamespaceAbstract
190b9c1b51eSKate Stone           : kSocketNamespaceFileSystem;
191b9c1b51eSKate Stone   snprintf(message, sizeof(message), "forward:tcp:%d;%s:%s", local_port,
192245f7fdcSZachary Turner            sock_namespace_str, remote_socket_name.str().c_str());
1939fe526c2SOleksiy Vyalov 
1949fe526c2SOleksiy Vyalov   const auto error = SendDeviceMessage(message);
1959fe526c2SOleksiy Vyalov   if (error.Fail())
1969fe526c2SOleksiy Vyalov     return error;
1979fe526c2SOleksiy Vyalov 
1989fe526c2SOleksiy Vyalov   return ReadResponseStatus();
1999fe526c2SOleksiy Vyalov }
2009fe526c2SOleksiy Vyalov 
DeletePortForwarding(const uint16_t local_port)20197206d57SZachary Turner Status AdbClient::DeletePortForwarding(const uint16_t local_port) {
20205a55de3SOleksiy Vyalov   char message[32];
203e7eabbb5SOleksiy Vyalov   snprintf(message, sizeof(message), "killforward:tcp:%d", local_port);
20405a55de3SOleksiy Vyalov 
20505a55de3SOleksiy Vyalov   const auto error = SendDeviceMessage(message);
20605a55de3SOleksiy Vyalov   if (error.Fail())
20705a55de3SOleksiy Vyalov     return error;
20805a55de3SOleksiy Vyalov 
20905a55de3SOleksiy Vyalov   return ReadResponseStatus();
21005a55de3SOleksiy Vyalov }
21105a55de3SOleksiy Vyalov 
SendMessage(const std::string & packet,const bool reconnect)21297206d57SZachary Turner Status AdbClient::SendMessage(const std::string &packet, const bool reconnect) {
21397206d57SZachary Turner   Status error;
214b9c1b51eSKate Stone   if (!m_conn || reconnect) {
21509e9079dSOleksiy Vyalov     error = Connect();
21605a55de3SOleksiy Vyalov     if (error.Fail())
21705a55de3SOleksiy Vyalov       return error;
21809e9079dSOleksiy Vyalov   }
21905a55de3SOleksiy Vyalov 
22005a55de3SOleksiy Vyalov   char length_buffer[5];
221b9c1b51eSKate Stone   snprintf(length_buffer, sizeof(length_buffer), "%04x",
222b9c1b51eSKate Stone            static_cast<int>(packet.size()));
22305a55de3SOleksiy Vyalov 
22405a55de3SOleksiy Vyalov   ConnectionStatus status;
22505a55de3SOleksiy Vyalov 
2266e181cf3SOleksiy Vyalov   m_conn->Write(length_buffer, 4, status, &error);
22705a55de3SOleksiy Vyalov   if (error.Fail())
22805a55de3SOleksiy Vyalov     return error;
22905a55de3SOleksiy Vyalov 
2306e181cf3SOleksiy Vyalov   m_conn->Write(packet.c_str(), packet.size(), status, &error);
23105a55de3SOleksiy Vyalov   return error;
23205a55de3SOleksiy Vyalov }
23305a55de3SOleksiy Vyalov 
SendDeviceMessage(const std::string & packet)23497206d57SZachary Turner Status AdbClient::SendDeviceMessage(const std::string &packet) {
23505a55de3SOleksiy Vyalov   std::ostringstream msg;
23605a55de3SOleksiy Vyalov   msg << "host-serial:" << m_device_id << ":" << packet;
23705a55de3SOleksiy Vyalov   return SendMessage(msg.str());
23805a55de3SOleksiy Vyalov }
23905a55de3SOleksiy Vyalov 
ReadMessage(std::vector<char> & message)24097206d57SZachary Turner Status AdbClient::ReadMessage(std::vector<char> &message) {
24105a55de3SOleksiy Vyalov   message.clear();
24205a55de3SOleksiy Vyalov 
24305a55de3SOleksiy Vyalov   char buffer[5];
24405a55de3SOleksiy Vyalov   buffer[4] = 0;
24505a55de3SOleksiy Vyalov 
24609e9079dSOleksiy Vyalov   auto error = ReadAllBytes(buffer, 4);
24705a55de3SOleksiy Vyalov   if (error.Fail())
24805a55de3SOleksiy Vyalov     return error;
24905a55de3SOleksiy Vyalov 
250d7e6a4f2SVince Harron   unsigned int packet_len = 0;
251e17800c5SOleksiy Vyalov   sscanf(buffer, "%x", &packet_len);
25209e9079dSOleksiy Vyalov 
25309e9079dSOleksiy Vyalov   message.resize(packet_len, 0);
25409e9079dSOleksiy Vyalov   error = ReadAllBytes(&message[0], packet_len);
25509e9079dSOleksiy Vyalov   if (error.Fail())
25609e9079dSOleksiy Vyalov     message.clear();
25705a55de3SOleksiy Vyalov 
25805a55de3SOleksiy Vyalov   return error;
25905a55de3SOleksiy Vyalov }
26005a55de3SOleksiy Vyalov 
ReadMessageStream(std::vector<char> & message,milliseconds timeout)26197206d57SZachary Turner Status AdbClient::ReadMessageStream(std::vector<char> &message,
262818dd516SPavel Labath                                     milliseconds timeout) {
263818dd516SPavel Labath   auto start = steady_clock::now();
2649d8dde8cSTamas Berghammer   message.clear();
2659d8dde8cSTamas Berghammer 
26697206d57SZachary Turner   Status error;
2679d8dde8cSTamas Berghammer   lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
2689d8dde8cSTamas Berghammer   char buffer[1024];
269b9c1b51eSKate Stone   while (error.Success() && status == lldb::eConnectionStatusSuccess) {
270818dd516SPavel Labath     auto end = steady_clock::now();
271818dd516SPavel Labath     auto elapsed = end - start;
272818dd516SPavel Labath     if (elapsed >= timeout)
27397206d57SZachary Turner       return Status("Timed out");
2749d8dde8cSTamas Berghammer 
2752f159a5fSPavel Labath     size_t n = m_conn->Read(buffer, sizeof(buffer),
2762f159a5fSPavel Labath                             duration_cast<microseconds>(timeout - elapsed),
2772f159a5fSPavel Labath                             status, &error);
2789d8dde8cSTamas Berghammer     if (n > 0)
2799d8dde8cSTamas Berghammer       message.insert(message.end(), &buffer[0], &buffer[n]);
2809d8dde8cSTamas Berghammer   }
2819d8dde8cSTamas Berghammer   return error;
2829d8dde8cSTamas Berghammer }
2839d8dde8cSTamas Berghammer 
ReadResponseStatus()28497206d57SZachary Turner Status AdbClient::ReadResponseStatus() {
28509e9079dSOleksiy Vyalov   char response_id[5];
28605a55de3SOleksiy Vyalov 
28705a55de3SOleksiy Vyalov   static const size_t packet_len = 4;
28809e9079dSOleksiy Vyalov   response_id[packet_len] = 0;
28909e9079dSOleksiy Vyalov 
29009e9079dSOleksiy Vyalov   auto error = ReadAllBytes(response_id, packet_len);
29109e9079dSOleksiy Vyalov   if (error.Fail())
29209e9079dSOleksiy Vyalov     return error;
29309e9079dSOleksiy Vyalov 
29409e9079dSOleksiy Vyalov   if (strncmp(response_id, kOKAY, packet_len) != 0)
29509e9079dSOleksiy Vyalov     return GetResponseError(response_id);
29609e9079dSOleksiy Vyalov 
29709e9079dSOleksiy Vyalov   return error;
29809e9079dSOleksiy Vyalov }
29909e9079dSOleksiy Vyalov 
GetResponseError(const char * response_id)30097206d57SZachary Turner Status AdbClient::GetResponseError(const char *response_id) {
30109e9079dSOleksiy Vyalov   if (strcmp(response_id, kFAIL) != 0)
30297206d57SZachary Turner     return Status("Got unexpected response id from adb: \"%s\"", response_id);
30309e9079dSOleksiy Vyalov 
30409e9079dSOleksiy Vyalov   std::vector<char> error_message;
30509e9079dSOleksiy Vyalov   auto error = ReadMessage(error_message);
30609e9079dSOleksiy Vyalov   if (error.Success())
307b9c1b51eSKate Stone     error.SetErrorString(
308b9c1b51eSKate Stone         std::string(&error_message[0], error_message.size()).c_str());
30909e9079dSOleksiy Vyalov 
31009e9079dSOleksiy Vyalov   return error;
31109e9079dSOleksiy Vyalov }
31209e9079dSOleksiy Vyalov 
SwitchDeviceTransport()31397206d57SZachary Turner Status AdbClient::SwitchDeviceTransport() {
31409e9079dSOleksiy Vyalov   std::ostringstream msg;
31509e9079dSOleksiy Vyalov   msg << "host:transport:" << m_device_id;
31609e9079dSOleksiy Vyalov 
31709e9079dSOleksiy Vyalov   auto error = SendMessage(msg.str());
31809e9079dSOleksiy Vyalov   if (error.Fail())
31909e9079dSOleksiy Vyalov     return error;
32009e9079dSOleksiy Vyalov 
32109e9079dSOleksiy Vyalov   return ReadResponseStatus();
32209e9079dSOleksiy Vyalov }
32309e9079dSOleksiy Vyalov 
StartSync()32497206d57SZachary Turner Status AdbClient::StartSync() {
3256e181cf3SOleksiy Vyalov   auto error = SwitchDeviceTransport();
3266e181cf3SOleksiy Vyalov   if (error.Fail())
32797206d57SZachary Turner     return Status("Failed to switch to device transport: %s",
32897206d57SZachary Turner                   error.AsCString());
3296e181cf3SOleksiy Vyalov 
3306e181cf3SOleksiy Vyalov   error = Sync();
3316e181cf3SOleksiy Vyalov   if (error.Fail())
33297206d57SZachary Turner     return Status("Sync failed: %s", error.AsCString());
3336e181cf3SOleksiy Vyalov 
3346e181cf3SOleksiy Vyalov   return error;
3356e181cf3SOleksiy Vyalov }
3366e181cf3SOleksiy Vyalov 
Sync()33797206d57SZachary Turner Status AdbClient::Sync() {
338d6a143fcSOleksiy Vyalov   auto error = SendMessage("sync:", false);
33909e9079dSOleksiy Vyalov   if (error.Fail())
3400b5ebef7SOleksiy Vyalov     return error;
34109e9079dSOleksiy Vyalov 
3426e181cf3SOleksiy Vyalov   return ReadResponseStatus();
3436e181cf3SOleksiy Vyalov }
3446e181cf3SOleksiy Vyalov 
ReadAllBytes(void * buffer,size_t size)34597206d57SZachary Turner Status AdbClient::ReadAllBytes(void *buffer, size_t size) {
3466e181cf3SOleksiy Vyalov   return ::ReadAllBytes(*m_conn, buffer, size);
3476e181cf3SOleksiy Vyalov }
3486e181cf3SOleksiy Vyalov 
internalShell(const char * command,milliseconds timeout,std::vector<char> & output_buf)34997206d57SZachary Turner Status AdbClient::internalShell(const char *command, milliseconds timeout,
350b9c1b51eSKate Stone                                 std::vector<char> &output_buf) {
351c6ac2e1eSOleksiy Vyalov   output_buf.clear();
352c6ac2e1eSOleksiy Vyalov 
353d6a143fcSOleksiy Vyalov   auto error = SwitchDeviceTransport();
354d6a143fcSOleksiy Vyalov   if (error.Fail())
35597206d57SZachary Turner     return Status("Failed to switch to device transport: %s",
35697206d57SZachary Turner                   error.AsCString());
357d6a143fcSOleksiy Vyalov 
3586e181cf3SOleksiy Vyalov   StreamString adb_command;
3596e181cf3SOleksiy Vyalov   adb_command.Printf("shell:%s", command);
360adcd0268SBenjamin Kramer   error = SendMessage(std::string(adb_command.GetString()), false);
3616e181cf3SOleksiy Vyalov   if (error.Fail())
3626e181cf3SOleksiy Vyalov     return error;
3636e181cf3SOleksiy Vyalov 
3646e181cf3SOleksiy Vyalov   error = ReadResponseStatus();
3656e181cf3SOleksiy Vyalov   if (error.Fail())
3666e181cf3SOleksiy Vyalov     return error;
3676e181cf3SOleksiy Vyalov 
368818dd516SPavel Labath   error = ReadMessageStream(output_buf, timeout);
369c6ac2e1eSOleksiy Vyalov   if (error.Fail())
370c6ac2e1eSOleksiy Vyalov     return error;
371c6ac2e1eSOleksiy Vyalov 
372c6ac2e1eSOleksiy Vyalov   // ADB doesn't propagate return code of shell execution - if
373c6ac2e1eSOleksiy Vyalov   // output starts with /system/bin/sh: most likely command failed.
374c6ac2e1eSOleksiy Vyalov   static const char *kShellPrefix = "/system/bin/sh:";
375b9c1b51eSKate Stone   if (output_buf.size() > strlen(kShellPrefix)) {
376c6ac2e1eSOleksiy Vyalov     if (!memcmp(&output_buf[0], kShellPrefix, strlen(kShellPrefix)))
37797206d57SZachary Turner       return Status("Shell command %s failed: %s", command,
378c6ac2e1eSOleksiy Vyalov                     std::string(output_buf.begin(), output_buf.end()).c_str());
379c6ac2e1eSOleksiy Vyalov   }
380c6ac2e1eSOleksiy Vyalov 
38197206d57SZachary Turner   return Status();
382c6ac2e1eSOleksiy Vyalov }
383c6ac2e1eSOleksiy Vyalov 
Shell(const char * command,milliseconds timeout,std::string * output)38497206d57SZachary Turner Status AdbClient::Shell(const char *command, milliseconds timeout,
385b9c1b51eSKate Stone                         std::string *output) {
386c6ac2e1eSOleksiy Vyalov   std::vector<char> output_buffer;
387ce255ff2SPavel Labath   auto error = internalShell(command, timeout, output_buffer);
3886e181cf3SOleksiy Vyalov   if (error.Fail())
3896e181cf3SOleksiy Vyalov     return error;
3906e181cf3SOleksiy Vyalov 
3916e181cf3SOleksiy Vyalov   if (output)
392c6ac2e1eSOleksiy Vyalov     output->assign(output_buffer.begin(), output_buffer.end());
3936e181cf3SOleksiy Vyalov   return error;
3946e181cf3SOleksiy Vyalov }
3956e181cf3SOleksiy Vyalov 
ShellToFile(const char * command,milliseconds timeout,const FileSpec & output_file_spec)39697206d57SZachary Turner Status AdbClient::ShellToFile(const char *command, milliseconds timeout,
397b9c1b51eSKate Stone                               const FileSpec &output_file_spec) {
398c6ac2e1eSOleksiy Vyalov   std::vector<char> output_buffer;
399ce255ff2SPavel Labath   auto error = internalShell(command, timeout, output_buffer);
400c6ac2e1eSOleksiy Vyalov   if (error.Fail())
401c6ac2e1eSOleksiy Vyalov     return error;
402c6ac2e1eSOleksiy Vyalov 
403c6ac2e1eSOleksiy Vyalov   const auto output_filename = output_file_spec.GetPath();
404e3ad2e2eSPavel Labath   std::error_code EC;
405d9b948b6SFangrui Song   llvm::raw_fd_ostream dst(output_filename, EC, llvm::sys::fs::OF_None);
406e3ad2e2eSPavel Labath   if (EC)
40797206d57SZachary Turner     return Status("Unable to open local file %s", output_filename.c_str());
408c6ac2e1eSOleksiy Vyalov 
409c6ac2e1eSOleksiy Vyalov   dst.write(&output_buffer[0], output_buffer.size());
410c6ac2e1eSOleksiy Vyalov   dst.close();
411e3ad2e2eSPavel Labath   if (dst.has_error())
41297206d57SZachary Turner     return Status("Failed to write file %s", output_filename.c_str());
41397206d57SZachary Turner   return Status();
414c6ac2e1eSOleksiy Vyalov }
415c6ac2e1eSOleksiy Vyalov 
4166e181cf3SOleksiy Vyalov std::unique_ptr<AdbClient::SyncService>
GetSyncService(Status & error)41797206d57SZachary Turner AdbClient::GetSyncService(Status &error) {
4186e181cf3SOleksiy Vyalov   std::unique_ptr<SyncService> sync_service;
4196e181cf3SOleksiy Vyalov   error = StartSync();
4206e181cf3SOleksiy Vyalov   if (error.Success())
4216e181cf3SOleksiy Vyalov     sync_service.reset(new SyncService(std::move(m_conn)));
4226e181cf3SOleksiy Vyalov 
4236e181cf3SOleksiy Vyalov   return sync_service;
4246e181cf3SOleksiy Vyalov }
4256e181cf3SOleksiy Vyalov 
internalPullFile(const FileSpec & remote_file,const FileSpec & local_file)42697206d57SZachary Turner Status AdbClient::SyncService::internalPullFile(const FileSpec &remote_file,
427b9c1b51eSKate Stone                                                 const FileSpec &local_file) {
4280b5ebef7SOleksiy Vyalov   const auto local_file_path = local_file.GetPath();
429771ef6d4SMalcolm Parsons   llvm::FileRemover local_file_remover(local_file_path);
43009e9079dSOleksiy Vyalov 
431e3ad2e2eSPavel Labath   std::error_code EC;
432d9b948b6SFangrui Song   llvm::raw_fd_ostream dst(local_file_path, EC, llvm::sys::fs::OF_None);
433e3ad2e2eSPavel Labath   if (EC)
43497206d57SZachary Turner     return Status("Unable to open local file %s", local_file_path.c_str());
43509e9079dSOleksiy Vyalov 
4360b5ebef7SOleksiy Vyalov   const auto remote_file_path = remote_file.GetPath(false);
437b9c1b51eSKate Stone   auto error = SendSyncRequest(kRECV, remote_file_path.length(),
438b9c1b51eSKate Stone                                remote_file_path.c_str());
43909e9079dSOleksiy Vyalov   if (error.Fail())
44009e9079dSOleksiy Vyalov     return error;
44109e9079dSOleksiy Vyalov 
44209e9079dSOleksiy Vyalov   std::vector<char> chunk;
44309e9079dSOleksiy Vyalov   bool eof = false;
444b9c1b51eSKate Stone   while (!eof) {
44509e9079dSOleksiy Vyalov     error = PullFileChunk(chunk, eof);
44609e9079dSOleksiy Vyalov     if (error.Fail())
4476002a31bSOleksiy Vyalov       return error;
44809e9079dSOleksiy Vyalov     if (!eof)
44909e9079dSOleksiy Vyalov       dst.write(&chunk[0], chunk.size());
45009e9079dSOleksiy Vyalov   }
451e3ad2e2eSPavel Labath   dst.close();
452e3ad2e2eSPavel Labath   if (dst.has_error())
45397206d57SZachary Turner     return Status("Failed to write file %s", local_file_path.c_str());
45409e9079dSOleksiy Vyalov 
45509e9079dSOleksiy Vyalov   local_file_remover.releaseFile();
45609e9079dSOleksiy Vyalov   return error;
45709e9079dSOleksiy Vyalov }
45809e9079dSOleksiy Vyalov 
internalPushFile(const FileSpec & local_file,const FileSpec & remote_file)45997206d57SZachary Turner Status AdbClient::SyncService::internalPushFile(const FileSpec &local_file,
460b9c1b51eSKate Stone                                                 const FileSpec &remote_file) {
4610b5ebef7SOleksiy Vyalov   const auto local_file_path(local_file.GetPath());
4620b5ebef7SOleksiy Vyalov   std::ifstream src(local_file_path.c_str(), std::ios::in | std::ios::binary);
46362efb1f6SRobert Flack   if (!src.is_open())
46497206d57SZachary Turner     return Status("Unable to open local file %s", local_file_path.c_str());
46562efb1f6SRobert Flack 
46662efb1f6SRobert Flack   std::stringstream file_description;
4670b5ebef7SOleksiy Vyalov   file_description << remote_file.GetPath(false).c_str() << "," << kDefaultMode;
46862efb1f6SRobert Flack   std::string file_description_str = file_description.str();
469b9c1b51eSKate Stone   auto error = SendSyncRequest(kSEND, file_description_str.length(),
470b9c1b51eSKate Stone                                file_description_str.c_str());
47162efb1f6SRobert Flack   if (error.Fail())
47262efb1f6SRobert Flack     return error;
47362efb1f6SRobert Flack 
47462efb1f6SRobert Flack   char chunk[kMaxPushData];
475b9c1b51eSKate Stone   while (!src.eof() && !src.read(chunk, kMaxPushData).bad()) {
47662efb1f6SRobert Flack     size_t chunk_size = src.gcount();
4776002a31bSOleksiy Vyalov     error = SendSyncRequest(kDATA, chunk_size, chunk);
47862efb1f6SRobert Flack     if (error.Fail())
47997206d57SZachary Turner       return Status("Failed to send file chunk: %s", error.AsCString());
48062efb1f6SRobert Flack   }
4811408bf72SPavel Labath   error = SendSyncRequest(
48246376966SJonas Devlieghere       kDONE, llvm::sys::toTimeT(FileSystem::Instance().GetModificationTime(local_file)),
483b9c1b51eSKate Stone       nullptr);
48462efb1f6SRobert Flack   if (error.Fail())
48562efb1f6SRobert Flack     return error;
4866002a31bSOleksiy Vyalov 
4876002a31bSOleksiy Vyalov   std::string response_id;
488d10f6aa4SJason Molenda   uint32_t data_len;
4896002a31bSOleksiy Vyalov   error = ReadSyncHeader(response_id, data_len);
4906002a31bSOleksiy Vyalov   if (error.Fail())
49197206d57SZachary Turner     return Status("Failed to read DONE response: %s", error.AsCString());
492b9c1b51eSKate Stone   if (response_id == kFAIL) {
4936002a31bSOleksiy Vyalov     std::string error_message(data_len, 0);
4946002a31bSOleksiy Vyalov     error = ReadAllBytes(&error_message[0], data_len);
4956002a31bSOleksiy Vyalov     if (error.Fail())
49697206d57SZachary Turner       return Status("Failed to read DONE error message: %s", error.AsCString());
49797206d57SZachary Turner     return Status("Failed to push file: %s", error_message.c_str());
498b9c1b51eSKate Stone   } else if (response_id != kOKAY)
49997206d57SZachary Turner     return Status("Got unexpected DONE response: %s", response_id.c_str());
5006002a31bSOleksiy Vyalov 
50162efb1f6SRobert Flack   // If there was an error reading the source file, finish the adb file
50262efb1f6SRobert Flack   // transfer first so that adb isn't expecting any more data.
50362efb1f6SRobert Flack   if (src.bad())
50497206d57SZachary Turner     return Status("Failed read on %s", local_file_path.c_str());
5050b5ebef7SOleksiy Vyalov   return error;
5060b5ebef7SOleksiy Vyalov }
5070b5ebef7SOleksiy Vyalov 
internalStat(const FileSpec & remote_file,uint32_t & mode,uint32_t & size,uint32_t & mtime)50897206d57SZachary Turner Status AdbClient::SyncService::internalStat(const FileSpec &remote_file,
509b9c1b51eSKate Stone                                             uint32_t &mode, uint32_t &size,
510b9c1b51eSKate Stone                                             uint32_t &mtime) {
5116e181cf3SOleksiy Vyalov   const std::string remote_file_path(remote_file.GetPath(false));
512b9c1b51eSKate Stone   auto error = SendSyncRequest(kSTAT, remote_file_path.length(),
513b9c1b51eSKate Stone                                remote_file_path.c_str());
5140b5ebef7SOleksiy Vyalov   if (error.Fail())
51597206d57SZachary Turner     return Status("Failed to send request: %s", error.AsCString());
5160b5ebef7SOleksiy Vyalov 
5176e181cf3SOleksiy Vyalov   static const size_t stat_len = strlen(kSTAT);
5186e181cf3SOleksiy Vyalov   static const size_t response_len = stat_len + (sizeof(uint32_t) * 3);
5196e181cf3SOleksiy Vyalov 
5206e181cf3SOleksiy Vyalov   std::vector<char> buffer(response_len);
5216e181cf3SOleksiy Vyalov   error = ReadAllBytes(&buffer[0], buffer.size());
5220b5ebef7SOleksiy Vyalov   if (error.Fail())
52397206d57SZachary Turner     return Status("Failed to read response: %s", error.AsCString());
5246e181cf3SOleksiy Vyalov 
525b9c1b51eSKate Stone   DataExtractor extractor(&buffer[0], buffer.size(), eByteOrderLittle,
526b9c1b51eSKate Stone                           sizeof(void *));
5276e181cf3SOleksiy Vyalov   offset_t offset = 0;
5286e181cf3SOleksiy Vyalov 
5296e181cf3SOleksiy Vyalov   const void *command = extractor.GetData(&offset, stat_len);
5306e181cf3SOleksiy Vyalov   if (!command)
53197206d57SZachary Turner     return Status("Failed to get response command");
5326e181cf3SOleksiy Vyalov   const char *command_str = static_cast<const char *>(command);
5336e181cf3SOleksiy Vyalov   if (strncmp(command_str, kSTAT, stat_len))
53497206d57SZachary Turner     return Status("Got invalid stat command: %s", command_str);
5356e181cf3SOleksiy Vyalov 
5366e181cf3SOleksiy Vyalov   mode = extractor.GetU32(&offset);
5376e181cf3SOleksiy Vyalov   size = extractor.GetU32(&offset);
5386e181cf3SOleksiy Vyalov   mtime = extractor.GetU32(&offset);
53997206d57SZachary Turner   return Status();
5406e181cf3SOleksiy Vyalov }
5416e181cf3SOleksiy Vyalov 
PullFile(const FileSpec & remote_file,const FileSpec & local_file)54297206d57SZachary Turner Status AdbClient::SyncService::PullFile(const FileSpec &remote_file,
543b9c1b51eSKate Stone                                         const FileSpec &local_file) {
544d6a143fcSOleksiy Vyalov   return executeCommand([this, &remote_file, &local_file]() {
545d6a143fcSOleksiy Vyalov     return internalPullFile(remote_file, local_file);
546d6a143fcSOleksiy Vyalov   });
547d6a143fcSOleksiy Vyalov }
548d6a143fcSOleksiy Vyalov 
PushFile(const FileSpec & local_file,const FileSpec & remote_file)54997206d57SZachary Turner Status AdbClient::SyncService::PushFile(const FileSpec &local_file,
550b9c1b51eSKate Stone                                         const FileSpec &remote_file) {
551d6a143fcSOleksiy Vyalov   return executeCommand([this, &local_file, &remote_file]() {
552d6a143fcSOleksiy Vyalov     return internalPushFile(local_file, remote_file);
553d6a143fcSOleksiy Vyalov   });
554d6a143fcSOleksiy Vyalov }
555d6a143fcSOleksiy Vyalov 
Stat(const FileSpec & remote_file,uint32_t & mode,uint32_t & size,uint32_t & mtime)55697206d57SZachary Turner Status AdbClient::SyncService::Stat(const FileSpec &remote_file, uint32_t &mode,
557b9c1b51eSKate Stone                                     uint32_t &size, uint32_t &mtime) {
558d6a143fcSOleksiy Vyalov   return executeCommand([this, &remote_file, &mode, &size, &mtime]() {
559d6a143fcSOleksiy Vyalov     return internalStat(remote_file, mode, size, mtime);
560d6a143fcSOleksiy Vyalov   });
561d6a143fcSOleksiy Vyalov }
562d6a143fcSOleksiy Vyalov 
IsConnected() const563b9c1b51eSKate Stone bool AdbClient::SyncService::IsConnected() const {
564d6a143fcSOleksiy Vyalov   return m_conn && m_conn->IsConnected();
565d6a143fcSOleksiy Vyalov }
566d6a143fcSOleksiy Vyalov 
SyncService(std::unique_ptr<Connection> && conn)567b9c1b51eSKate Stone AdbClient::SyncService::SyncService(std::unique_ptr<Connection> &&conn)
568b9c1b51eSKate Stone     : m_conn(std::move(conn)) {}
5696e181cf3SOleksiy Vyalov 
57097206d57SZachary Turner Status
executeCommand(const std::function<Status ()> & cmd)57197206d57SZachary Turner AdbClient::SyncService::executeCommand(const std::function<Status()> &cmd) {
572d6a143fcSOleksiy Vyalov   if (!m_conn)
57397206d57SZachary Turner     return Status("SyncService is disconnected");
574d6a143fcSOleksiy Vyalov 
575d6a143fcSOleksiy Vyalov   const auto error = cmd();
576d6a143fcSOleksiy Vyalov   if (error.Fail())
577d6a143fcSOleksiy Vyalov     m_conn.reset();
578d6a143fcSOleksiy Vyalov 
579d6a143fcSOleksiy Vyalov   return error;
580d6a143fcSOleksiy Vyalov }
581d6a143fcSOleksiy Vyalov 
582fd2433e1SJonas Devlieghere AdbClient::SyncService::~SyncService() = default;
5836e181cf3SOleksiy Vyalov 
SendSyncRequest(const char * request_id,const uint32_t data_len,const void * data)58497206d57SZachary Turner Status AdbClient::SyncService::SendSyncRequest(const char *request_id,
585b9c1b51eSKate Stone                                                const uint32_t data_len,
586b9c1b51eSKate Stone                                                const void *data) {
587*244258e3SGreg Clayton   DataEncoder encoder(eByteOrderLittle, sizeof(void *));
588*244258e3SGreg Clayton   encoder.AppendData(llvm::StringRef(request_id));
589*244258e3SGreg Clayton   encoder.AppendU32(data_len);
590*244258e3SGreg Clayton   llvm::ArrayRef<uint8_t> bytes = encoder.GetData();
59197206d57SZachary Turner   Status error;
5926e181cf3SOleksiy Vyalov   ConnectionStatus status;
593*244258e3SGreg Clayton   m_conn->Write(bytes.data(), kSyncPacketLen, status, &error);
5946e181cf3SOleksiy Vyalov   if (error.Fail())
5956e181cf3SOleksiy Vyalov     return error;
5966e181cf3SOleksiy Vyalov 
5976e181cf3SOleksiy Vyalov   if (data)
5986e181cf3SOleksiy Vyalov     m_conn->Write(data, data_len, status, &error);
5996e181cf3SOleksiy Vyalov   return error;
6006e181cf3SOleksiy Vyalov }
6016e181cf3SOleksiy Vyalov 
ReadSyncHeader(std::string & response_id,uint32_t & data_len)60297206d57SZachary Turner Status AdbClient::SyncService::ReadSyncHeader(std::string &response_id,
603b9c1b51eSKate Stone                                               uint32_t &data_len) {
6046e181cf3SOleksiy Vyalov   char buffer[kSyncPacketLen];
6056e181cf3SOleksiy Vyalov 
6066e181cf3SOleksiy Vyalov   auto error = ReadAllBytes(buffer, kSyncPacketLen);
607b9c1b51eSKate Stone   if (error.Success()) {
6086e181cf3SOleksiy Vyalov     response_id.assign(&buffer[0], 4);
6096e181cf3SOleksiy Vyalov     DataExtractor extractor(&buffer[4], 4, eByteOrderLittle, sizeof(void *));
6106e181cf3SOleksiy Vyalov     offset_t offset = 0;
6116e181cf3SOleksiy Vyalov     data_len = extractor.GetU32(&offset);
6126e181cf3SOleksiy Vyalov   }
6130b5ebef7SOleksiy Vyalov 
61462efb1f6SRobert Flack   return error;
61562efb1f6SRobert Flack }
61662efb1f6SRobert Flack 
PullFileChunk(std::vector<char> & buffer,bool & eof)61797206d57SZachary Turner Status AdbClient::SyncService::PullFileChunk(std::vector<char> &buffer,
618b9c1b51eSKate Stone                                              bool &eof) {
61909e9079dSOleksiy Vyalov   buffer.clear();
62009e9079dSOleksiy Vyalov 
62109e9079dSOleksiy Vyalov   std::string response_id;
62209e9079dSOleksiy Vyalov   uint32_t data_len;
62309e9079dSOleksiy Vyalov   auto error = ReadSyncHeader(response_id, data_len);
62409e9079dSOleksiy Vyalov   if (error.Fail())
62509e9079dSOleksiy Vyalov     return error;
62609e9079dSOleksiy Vyalov 
627b9c1b51eSKate Stone   if (response_id == kDATA) {
62809e9079dSOleksiy Vyalov     buffer.resize(data_len, 0);
62909e9079dSOleksiy Vyalov     error = ReadAllBytes(&buffer[0], data_len);
63009e9079dSOleksiy Vyalov     if (error.Fail())
63109e9079dSOleksiy Vyalov       buffer.clear();
632b9c1b51eSKate Stone   } else if (response_id == kDONE) {
63309e9079dSOleksiy Vyalov     eof = true;
634b9c1b51eSKate Stone   } else if (response_id == kFAIL) {
6356002a31bSOleksiy Vyalov     std::string error_message(data_len, 0);
6366002a31bSOleksiy Vyalov     error = ReadAllBytes(&error_message[0], data_len);
6376002a31bSOleksiy Vyalov     if (error.Fail())
63897206d57SZachary Turner       return Status("Failed to read pull error message: %s", error.AsCString());
63997206d57SZachary Turner     return Status("Failed to pull file: %s", error_message.c_str());
640b9c1b51eSKate Stone   } else
64197206d57SZachary Turner     return Status("Pull failed with unknown response: %s", response_id.c_str());
64209e9079dSOleksiy Vyalov 
64397206d57SZachary Turner   return Status();
64409e9079dSOleksiy Vyalov }
64509e9079dSOleksiy Vyalov 
ReadAllBytes(void * buffer,size_t size)64697206d57SZachary Turner Status AdbClient::SyncService::ReadAllBytes(void *buffer, size_t size) {
6476e181cf3SOleksiy Vyalov   return ::ReadAllBytes(*m_conn, buffer, size);
64805a55de3SOleksiy Vyalov }
649