blob: 04f88da7ac25b9e979a905dd708dd26d446a4cfe [file] [log] [blame]
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +00001//===-- AdbClient.cpp -------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +00006//
7//===----------------------------------------------------------------------===//
8
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +00009#include "AdbClient.h"
10
Kate Stoneb9c1b512016-09-06 20:57:50 +000011#include "llvm/ADT/STLExtras.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000012#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000014#include "llvm/Support/FileUtilities.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000015
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000016#include "lldb/Host/ConnectionFileDescriptor.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000017#include "lldb/Host/FileSystem.h"
Zachary Turnerf343968f2016-08-09 23:06:08 +000018#include "lldb/Host/PosixApi.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000019#include "lldb/Utility/DataBuffer.h"
20#include "lldb/Utility/DataBufferHeap.h"
21#include "lldb/Utility/DataEncoder.h"
22#include "lldb/Utility/DataExtractor.h"
Zachary Turner5713a052017-03-22 18:40:07 +000023#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000024#include "lldb/Utility/StreamString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000025#include "lldb/Utility/Timeout.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000026
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000027#include <limits.h>
28
Oleksiy Vyalov6f001062015-03-25 17:58:13 +000029#include <algorithm>
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +000030#include <cstdlib>
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000031#include <fstream>
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000032#include <sstream>
33
Adrian McCarthy1341d4c2016-06-30 20:55:50 +000034// On Windows, transitive dependencies pull in <Windows.h>, which defines a
35// macro that clashes with a method name.
36#ifdef SendMessage
37#undef SendMessage
38#endif
39
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000040using namespace lldb;
41using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000042using namespace lldb_private::platform_android;
Pavel Labath818dd512016-11-24 14:03:57 +000043using namespace std::chrono;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000044
45namespace {
46
Pavel Labathaee3e262017-10-31 12:27:46 +000047const seconds kReadTimeout(20);
Kate Stoneb9c1b512016-09-06 20:57:50 +000048const char *kOKAY = "OKAY";
49const char *kFAIL = "FAIL";
50const char *kDATA = "DATA";
51const char *kDONE = "DONE";
Oleksiy Vyalov6002a312015-06-05 01:32:45 +000052
Kate Stoneb9c1b512016-09-06 20:57:50 +000053const char *kSEND = "SEND";
54const char *kRECV = "RECV";
55const char *kSTAT = "STAT";
Oleksiy Vyalov6002a312015-06-05 01:32:45 +000056
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000057const size_t kSyncPacketLen = 8;
Robert Flack62efb1f2015-05-27 02:18:50 +000058// Maximum size of a filesync DATA packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +000059const size_t kMaxPushData = 2 * 1024;
Robert Flack62efb1f2015-05-27 02:18:50 +000060// Default mode for pushed files.
61const uint32_t kDefaultMode = 0100770; // S_IFREG | S_IRWXU | S_IRWXG
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000062
Kate Stoneb9c1b512016-09-06 20:57:50 +000063const char *kSocketNamespaceAbstract = "localabstract";
64const char *kSocketNamespaceFileSystem = "localfilesystem";
Oleksiy Vyalove7df5f52015-11-03 01:37:01 +000065
Zachary Turner97206d52017-05-12 04:51:55 +000066Status ReadAllBytes(Connection &conn, void *buffer, size_t size) {
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000067
Zachary Turner97206d52017-05-12 04:51:55 +000068 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 ConnectionStatus status;
70 char *read_buffer = static_cast<char *>(buffer);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000071
Kate Stoneb9c1b512016-09-06 20:57:50 +000072 auto now = steady_clock::now();
73 const auto deadline = now + kReadTimeout;
74 size_t total_read_bytes = 0;
75 while (total_read_bytes < size && now < deadline) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 auto read_bytes =
77 conn.Read(read_buffer + total_read_bytes, size - total_read_bytes,
Pavel Labath2f159a52016-11-25 12:22:32 +000078 duration_cast<microseconds>(deadline - now), status, &error);
Chaoren Lin3ea689b2015-05-01 16:49:28 +000079 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 return error;
81 total_read_bytes += read_bytes;
82 if (status != eConnectionStatusSuccess)
83 break;
84 now = steady_clock::now();
85 }
86 if (total_read_bytes < size)
Zachary Turner97206d52017-05-12 04:51:55 +000087 error = Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 "Unable to read requested number of bytes. Connection status: %d.",
89 status);
90 return error;
91}
Oleksiy Vyalov6f001062015-03-25 17:58:13 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093} // namespace
Luke Drummond3db04912016-07-07 18:02:44 +000094
Zachary Turner97206d52017-05-12 04:51:55 +000095Status AdbClient::CreateByDeviceID(const std::string &device_id,
96 AdbClient &adb) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 DeviceIDList connect_devices;
98 auto error = adb.GetDevices(connect_devices);
99 if (error.Fail())
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000100 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101
102 std::string android_serial;
103 if (!device_id.empty())
104 android_serial = device_id;
105 else if (const char *env_serial = std::getenv("ANDROID_SERIAL"))
106 android_serial = env_serial;
107
108 if (android_serial.empty()) {
109 if (connect_devices.size() != 1)
Zachary Turner97206d52017-05-12 04:51:55 +0000110 return Status("Expected a single connected device, got instead %zu - try "
111 "setting 'ANDROID_SERIAL'",
112 connect_devices.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 adb.SetDeviceID(connect_devices.front());
114 } else {
115 auto find_it = std::find(connect_devices.begin(), connect_devices.end(),
116 android_serial);
117 if (find_it == connect_devices.end())
Zachary Turner97206d52017-05-12 04:51:55 +0000118 return Status("Device \"%s\" not found", android_serial.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119
120 adb.SetDeviceID(*find_it);
121 }
122 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000123}
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125AdbClient::AdbClient() {}
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127AdbClient::AdbClient(const std::string &device_id) : m_device_id(device_id) {}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000128
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000129AdbClient::~AdbClient() {}
130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131void AdbClient::SetDeviceID(const std::string &device_id) {
132 m_device_id = device_id;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000133}
134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135const std::string &AdbClient::GetDeviceID() const { return m_device_id; }
136
Zachary Turner97206d52017-05-12 04:51:55 +0000137Status AdbClient::Connect() {
138 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 m_conn.reset(new ConnectionFileDescriptor);
Nathan Lanza0c01d922019-08-27 20:00:02 +0000140 std::string port = "5037";
141 if (const char *env_port = std::getenv("ANDROID_ADB_SERVER_PORT")) {
142 port = env_port;
143 }
144 std::string uri = "connect://localhost:" + port;
145 m_conn->Connect(uri.c_str(), &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146
147 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000148}
149
Zachary Turner97206d52017-05-12 04:51:55 +0000150Status AdbClient::GetDevices(DeviceIDList &device_list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 device_list.clear();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 auto error = SendMessage("host:devices");
154 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000155 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 error = ReadResponseStatus();
158 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000159 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160
161 std::vector<char> in_buffer;
162 error = ReadMessage(in_buffer);
163
164 llvm::StringRef response(&in_buffer[0], in_buffer.size());
165 llvm::SmallVector<llvm::StringRef, 4> devices;
166 response.split(devices, "\n", -1, false);
167
168 for (const auto device : devices)
169 device_list.push_back(device.split('\t').first);
170
Adrian Prantl05097242018-04-30 16:49:04 +0000171 // Force disconnect since ADB closes connection after host:devices response
172 // is sent.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 m_conn.reset();
174 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000175}
176
Zachary Turner97206d52017-05-12 04:51:55 +0000177Status AdbClient::SetPortForwarding(const uint16_t local_port,
178 const uint16_t remote_port) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179 char message[48];
180 snprintf(message, sizeof(message), "forward:tcp:%d;tcp:%d", local_port,
181 remote_port);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 const auto error = SendDeviceMessage(message);
184 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000185 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186
187 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000188}
189
Zachary Turner97206d52017-05-12 04:51:55 +0000190Status
191AdbClient::SetPortForwarding(const uint16_t local_port,
192 llvm::StringRef remote_socket_name,
193 const UnixSocketNamespace socket_namespace) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 char message[PATH_MAX];
195 const char *sock_namespace_str =
196 (socket_namespace == UnixSocketNamespaceAbstract)
197 ? kSocketNamespaceAbstract
198 : kSocketNamespaceFileSystem;
199 snprintf(message, sizeof(message), "forward:tcp:%d;%s:%s", local_port,
Zachary Turner245f7fd2016-11-17 01:38:02 +0000200 sock_namespace_str, remote_socket_name.str().c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 const auto error = SendDeviceMessage(message);
203 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000204 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205
206 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000207}
208
Zachary Turner97206d52017-05-12 04:51:55 +0000209Status AdbClient::DeletePortForwarding(const uint16_t local_port) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 char message[32];
211 snprintf(message, sizeof(message), "killforward:tcp:%d", local_port);
212
213 const auto error = SendDeviceMessage(message);
214 if (error.Fail())
215 return error;
216
217 return ReadResponseStatus();
218}
219
Zachary Turner97206d52017-05-12 04:51:55 +0000220Status AdbClient::SendMessage(const std::string &packet, const bool reconnect) {
221 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 if (!m_conn || reconnect) {
223 error = Connect();
224 if (error.Fail())
225 return error;
226 }
227
228 char length_buffer[5];
229 snprintf(length_buffer, sizeof(length_buffer), "%04x",
230 static_cast<int>(packet.size()));
231
232 ConnectionStatus status;
233
234 m_conn->Write(length_buffer, 4, status, &error);
235 if (error.Fail())
236 return error;
237
238 m_conn->Write(packet.c_str(), packet.size(), status, &error);
239 return error;
240}
241
Zachary Turner97206d52017-05-12 04:51:55 +0000242Status AdbClient::SendDeviceMessage(const std::string &packet) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 std::ostringstream msg;
244 msg << "host-serial:" << m_device_id << ":" << packet;
245 return SendMessage(msg.str());
246}
247
Zachary Turner97206d52017-05-12 04:51:55 +0000248Status AdbClient::ReadMessage(std::vector<char> &message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 message.clear();
250
251 char buffer[5];
252 buffer[4] = 0;
253
254 auto error = ReadAllBytes(buffer, 4);
255 if (error.Fail())
256 return error;
257
258 unsigned int packet_len = 0;
259 sscanf(buffer, "%x", &packet_len);
260
261 message.resize(packet_len, 0);
262 error = ReadAllBytes(&message[0], packet_len);
263 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000264 message.clear();
265
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 return error;
267}
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000268
Zachary Turner97206d52017-05-12 04:51:55 +0000269Status AdbClient::ReadMessageStream(std::vector<char> &message,
270 milliseconds timeout) {
Pavel Labath818dd512016-11-24 14:03:57 +0000271 auto start = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 message.clear();
273
Zachary Turner97206d52017-05-12 04:51:55 +0000274 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
276 char buffer[1024];
277 while (error.Success() && status == lldb::eConnectionStatusSuccess) {
Pavel Labath818dd512016-11-24 14:03:57 +0000278 auto end = steady_clock::now();
279 auto elapsed = end - start;
280 if (elapsed >= timeout)
Zachary Turner97206d52017-05-12 04:51:55 +0000281 return Status("Timed out");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282
Pavel Labath2f159a52016-11-25 12:22:32 +0000283 size_t n = m_conn->Read(buffer, sizeof(buffer),
284 duration_cast<microseconds>(timeout - elapsed),
285 status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 if (n > 0)
287 message.insert(message.end(), &buffer[0], &buffer[n]);
288 }
289 return error;
290}
291
Zachary Turner97206d52017-05-12 04:51:55 +0000292Status AdbClient::ReadResponseStatus() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 char response_id[5];
294
295 static const size_t packet_len = 4;
296 response_id[packet_len] = 0;
297
298 auto error = ReadAllBytes(response_id, packet_len);
299 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000300 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301
302 if (strncmp(response_id, kOKAY, packet_len) != 0)
303 return GetResponseError(response_id);
304
305 return error;
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000306}
307
Zachary Turner97206d52017-05-12 04:51:55 +0000308Status AdbClient::GetResponseError(const char *response_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309 if (strcmp(response_id, kFAIL) != 0)
Zachary Turner97206d52017-05-12 04:51:55 +0000310 return Status("Got unexpected response id from adb: \"%s\"", response_id);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 std::vector<char> error_message;
313 auto error = ReadMessage(error_message);
314 if (error.Success())
315 error.SetErrorString(
316 std::string(&error_message[0], error_message.size()).c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000317
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 return error;
319}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000320
Zachary Turner97206d52017-05-12 04:51:55 +0000321Status AdbClient::SwitchDeviceTransport() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 std::ostringstream msg;
323 msg << "host:transport:" << m_device_id;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000324
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 auto error = SendMessage(msg.str());
326 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000327 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328
329 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000330}
331
Zachary Turner97206d52017-05-12 04:51:55 +0000332Status AdbClient::StartSync() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 auto error = SwitchDeviceTransport();
334 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000335 return Status("Failed to switch to device transport: %s",
336 error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 error = Sync();
339 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000340 return Status("Sync failed: %s", error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000341
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 return error;
343}
344
Zachary Turner97206d52017-05-12 04:51:55 +0000345Status AdbClient::Sync() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 auto error = SendMessage("sync:", false);
347 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000348 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349
350 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000351}
352
Zachary Turner97206d52017-05-12 04:51:55 +0000353Status AdbClient::ReadAllBytes(void *buffer, size_t size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000355}
356
Zachary Turner97206d52017-05-12 04:51:55 +0000357Status AdbClient::internalShell(const char *command, milliseconds timeout,
358 std::vector<char> &output_buf) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 output_buf.clear();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 auto error = SwitchDeviceTransport();
362 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000363 return Status("Failed to switch to device transport: %s",
364 error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 StreamString adb_command;
367 adb_command.Printf("shell:%s", command);
Zachary Turnerc1564272016-11-16 21:15:24 +0000368 error = SendMessage(adb_command.GetString(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000370 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 error = ReadResponseStatus();
373 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000374 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375
Pavel Labath818dd512016-11-24 14:03:57 +0000376 error = ReadMessageStream(output_buf, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 if (error.Fail())
378 return error;
379
380 // ADB doesn't propagate return code of shell execution - if
381 // output starts with /system/bin/sh: most likely command failed.
382 static const char *kShellPrefix = "/system/bin/sh:";
383 if (output_buf.size() > strlen(kShellPrefix)) {
384 if (!memcmp(&output_buf[0], kShellPrefix, strlen(kShellPrefix)))
Zachary Turner97206d52017-05-12 04:51:55 +0000385 return Status("Shell command %s failed: %s", command,
386 std::string(output_buf.begin(), output_buf.end()).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 }
388
Zachary Turner97206d52017-05-12 04:51:55 +0000389 return Status();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000390}
391
Zachary Turner97206d52017-05-12 04:51:55 +0000392Status AdbClient::Shell(const char *command, milliseconds timeout,
393 std::string *output) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 std::vector<char> output_buffer;
Pavel Labathce255ff2016-11-24 14:11:47 +0000395 auto error = internalShell(command, timeout, output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 if (error.Fail())
397 return error;
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 if (output)
400 output->assign(output_buffer.begin(), output_buffer.end());
401 return error;
402}
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000403
Zachary Turner97206d52017-05-12 04:51:55 +0000404Status AdbClient::ShellToFile(const char *command, milliseconds timeout,
405 const FileSpec &output_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 std::vector<char> output_buffer;
Pavel Labathce255ff2016-11-24 14:11:47 +0000407 auto error = internalShell(command, timeout, output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 if (error.Fail())
409 return error;
410
411 const auto output_filename = output_file_spec.GetPath();
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000412 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000413 llvm::raw_fd_ostream dst(output_filename, EC, llvm::sys::fs::OF_None);
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000414 if (EC)
Zachary Turner97206d52017-05-12 04:51:55 +0000415 return Status("Unable to open local file %s", output_filename.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416
417 dst.write(&output_buffer[0], output_buffer.size());
418 dst.close();
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000419 if (dst.has_error())
Zachary Turner97206d52017-05-12 04:51:55 +0000420 return Status("Failed to write file %s", output_filename.c_str());
421 return Status();
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000422}
423
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000424std::unique_ptr<AdbClient::SyncService>
Zachary Turner97206d52017-05-12 04:51:55 +0000425AdbClient::GetSyncService(Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 std::unique_ptr<SyncService> sync_service;
427 error = StartSync();
428 if (error.Success())
429 sync_service.reset(new SyncService(std::move(m_conn)));
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000430
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 return sync_service;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000432}
433
Zachary Turner97206d52017-05-12 04:51:55 +0000434Status AdbClient::SyncService::internalPullFile(const FileSpec &remote_file,
435 const FileSpec &local_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 const auto local_file_path = local_file.GetPath();
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000437 llvm::FileRemover local_file_remover(local_file_path);
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000438
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000439 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000440 llvm::raw_fd_ostream dst(local_file_path, EC, llvm::sys::fs::OF_None);
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000441 if (EC)
Zachary Turner97206d52017-05-12 04:51:55 +0000442 return Status("Unable to open local file %s", local_file_path.c_str());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 const auto remote_file_path = remote_file.GetPath(false);
445 auto error = SendSyncRequest(kRECV, remote_file_path.length(),
446 remote_file_path.c_str());
447 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000448 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449
450 std::vector<char> chunk;
451 bool eof = false;
452 while (!eof) {
453 error = PullFileChunk(chunk, eof);
454 if (error.Fail())
455 return error;
456 if (!eof)
457 dst.write(&chunk[0], chunk.size());
458 }
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000459 dst.close();
460 if (dst.has_error())
Zachary Turner97206d52017-05-12 04:51:55 +0000461 return Status("Failed to write file %s", local_file_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462
463 local_file_remover.releaseFile();
464 return error;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000465}
466
Zachary Turner97206d52017-05-12 04:51:55 +0000467Status AdbClient::SyncService::internalPushFile(const FileSpec &local_file,
468 const FileSpec &remote_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 const auto local_file_path(local_file.GetPath());
470 std::ifstream src(local_file_path.c_str(), std::ios::in | std::ios::binary);
471 if (!src.is_open())
Zachary Turner97206d52017-05-12 04:51:55 +0000472 return Status("Unable to open local file %s", local_file_path.c_str());
Robert Flack62efb1f2015-05-27 02:18:50 +0000473
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 std::stringstream file_description;
475 file_description << remote_file.GetPath(false).c_str() << "," << kDefaultMode;
476 std::string file_description_str = file_description.str();
477 auto error = SendSyncRequest(kSEND, file_description_str.length(),
478 file_description_str.c_str());
479 if (error.Fail())
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000480 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481
482 char chunk[kMaxPushData];
483 while (!src.eof() && !src.read(chunk, kMaxPushData).bad()) {
484 size_t chunk_size = src.gcount();
485 error = SendSyncRequest(kDATA, chunk_size, chunk);
486 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000487 return Status("Failed to send file chunk: %s", error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 }
Pavel Labath1408bf72016-11-01 16:11:14 +0000489 error = SendSyncRequest(
Jonas Devlieghere46376962018-10-31 21:49:27 +0000490 kDONE, llvm::sys::toTimeT(FileSystem::Instance().GetModificationTime(local_file)),
Pavel Labath1408bf72016-11-01 16:11:14 +0000491 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 if (error.Fail())
493 return error;
494
495 std::string response_id;
496 uint32_t data_len;
497 error = ReadSyncHeader(response_id, data_len);
498 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000499 return Status("Failed to read DONE response: %s", error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 if (response_id == kFAIL) {
501 std::string error_message(data_len, 0);
502 error = ReadAllBytes(&error_message[0], data_len);
503 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000504 return Status("Failed to read DONE error message: %s", error.AsCString());
505 return Status("Failed to push file: %s", error_message.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 } else if (response_id != kOKAY)
Zachary Turner97206d52017-05-12 04:51:55 +0000507 return Status("Got unexpected DONE response: %s", response_id.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508
509 // If there was an error reading the source file, finish the adb file
510 // transfer first so that adb isn't expecting any more data.
511 if (src.bad())
Zachary Turner97206d52017-05-12 04:51:55 +0000512 return Status("Failed read on %s", local_file_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 return error;
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000514}
515
Zachary Turner97206d52017-05-12 04:51:55 +0000516Status AdbClient::SyncService::internalStat(const FileSpec &remote_file,
517 uint32_t &mode, uint32_t &size,
518 uint32_t &mtime) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 const std::string remote_file_path(remote_file.GetPath(false));
520 auto error = SendSyncRequest(kSTAT, remote_file_path.length(),
521 remote_file_path.c_str());
522 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000523 return Status("Failed to send request: %s", error.AsCString());
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 static const size_t stat_len = strlen(kSTAT);
526 static const size_t response_len = stat_len + (sizeof(uint32_t) * 3);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 std::vector<char> buffer(response_len);
529 error = ReadAllBytes(&buffer[0], buffer.size());
530 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000531 return Status("Failed to read response: %s", error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 DataExtractor extractor(&buffer[0], buffer.size(), eByteOrderLittle,
534 sizeof(void *));
535 offset_t offset = 0;
536
537 const void *command = extractor.GetData(&offset, stat_len);
538 if (!command)
Zachary Turner97206d52017-05-12 04:51:55 +0000539 return Status("Failed to get response command");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 const char *command_str = static_cast<const char *>(command);
541 if (strncmp(command_str, kSTAT, stat_len))
Zachary Turner97206d52017-05-12 04:51:55 +0000542 return Status("Got invalid stat command: %s", command_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543
544 mode = extractor.GetU32(&offset);
545 size = extractor.GetU32(&offset);
546 mtime = extractor.GetU32(&offset);
Zachary Turner97206d52017-05-12 04:51:55 +0000547 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548}
549
Zachary Turner97206d52017-05-12 04:51:55 +0000550Status AdbClient::SyncService::PullFile(const FileSpec &remote_file,
551 const FileSpec &local_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 return executeCommand([this, &remote_file, &local_file]() {
553 return internalPullFile(remote_file, local_file);
554 });
555}
556
Zachary Turner97206d52017-05-12 04:51:55 +0000557Status AdbClient::SyncService::PushFile(const FileSpec &local_file,
558 const FileSpec &remote_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 return executeCommand([this, &local_file, &remote_file]() {
560 return internalPushFile(local_file, remote_file);
561 });
562}
563
Zachary Turner97206d52017-05-12 04:51:55 +0000564Status AdbClient::SyncService::Stat(const FileSpec &remote_file, uint32_t &mode,
565 uint32_t &size, uint32_t &mtime) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 return executeCommand([this, &remote_file, &mode, &size, &mtime]() {
567 return internalStat(remote_file, mode, size, mtime);
568 });
569}
570
571bool AdbClient::SyncService::IsConnected() const {
572 return m_conn && m_conn->IsConnected();
573}
574
575AdbClient::SyncService::SyncService(std::unique_ptr<Connection> &&conn)
576 : m_conn(std::move(conn)) {}
577
Zachary Turner97206d52017-05-12 04:51:55 +0000578Status
579AdbClient::SyncService::executeCommand(const std::function<Status()> &cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 if (!m_conn)
Zachary Turner97206d52017-05-12 04:51:55 +0000581 return Status("SyncService is disconnected");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582
583 const auto error = cmd();
584 if (error.Fail())
585 m_conn.reset();
586
587 return error;
588}
589
590AdbClient::SyncService::~SyncService() {}
591
Zachary Turner97206d52017-05-12 04:51:55 +0000592Status AdbClient::SyncService::SendSyncRequest(const char *request_id,
593 const uint32_t data_len,
594 const void *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 const DataBufferSP data_sp(new DataBufferHeap(kSyncPacketLen, 0));
596 DataEncoder encoder(data_sp, eByteOrderLittle, sizeof(void *));
597 auto offset = encoder.PutData(0, request_id, strlen(request_id));
598 encoder.PutU32(offset, data_len);
599
Zachary Turner97206d52017-05-12 04:51:55 +0000600 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 ConnectionStatus status;
602 m_conn->Write(data_sp->GetBytes(), kSyncPacketLen, status, &error);
603 if (error.Fail())
604 return error;
605
606 if (data)
607 m_conn->Write(data, data_len, status, &error);
608 return error;
609}
610
Zachary Turner97206d52017-05-12 04:51:55 +0000611Status AdbClient::SyncService::ReadSyncHeader(std::string &response_id,
612 uint32_t &data_len) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 char buffer[kSyncPacketLen];
614
615 auto error = ReadAllBytes(buffer, kSyncPacketLen);
616 if (error.Success()) {
617 response_id.assign(&buffer[0], 4);
618 DataExtractor extractor(&buffer[4], 4, eByteOrderLittle, sizeof(void *));
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000619 offset_t offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 data_len = extractor.GetU32(&offset);
621 }
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000624}
625
Zachary Turner97206d52017-05-12 04:51:55 +0000626Status AdbClient::SyncService::PullFileChunk(std::vector<char> &buffer,
627 bool &eof) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 buffer.clear();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 std::string response_id;
631 uint32_t data_len;
632 auto error = ReadSyncHeader(response_id, data_len);
633 if (error.Fail())
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000634 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635
636 if (response_id == kDATA) {
637 buffer.resize(data_len, 0);
638 error = ReadAllBytes(&buffer[0], data_len);
639 if (error.Fail())
640 buffer.clear();
641 } else if (response_id == kDONE) {
642 eof = true;
643 } else if (response_id == kFAIL) {
644 std::string error_message(data_len, 0);
645 error = ReadAllBytes(&error_message[0], data_len);
646 if (error.Fail())
Zachary Turner97206d52017-05-12 04:51:55 +0000647 return Status("Failed to read pull error message: %s", error.AsCString());
648 return Status("Failed to pull file: %s", error_message.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 } else
Zachary Turner97206d52017-05-12 04:51:55 +0000650 return Status("Pull failed with unknown response: %s", response_id.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651
Zachary Turner97206d52017-05-12 04:51:55 +0000652 return Status();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000653}
654
Zachary Turner97206d52017-05-12 04:51:55 +0000655Status AdbClient::SyncService::ReadAllBytes(void *buffer, size_t size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000657}