blob: d9e27d94f74e5a2dd82f98bb428f6108036cff35 [file] [log] [blame]
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +00001//===-- AdbClient.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// Other libraries and framework includes
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000011#include "AdbClient.h"
12
Kate Stoneb9c1b512016-09-06 20:57:50 +000013#include "llvm/ADT/STLExtras.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000014#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringRef.h"
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000016#include "llvm/Support/FileUtilities.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000017
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000018#include "lldb/Core/DataBuffer.h"
19#include "lldb/Core/DataBufferHeap.h"
20#include "lldb/Core/DataEncoder.h"
21#include "lldb/Core/DataExtractor.h"
22#include "lldb/Core/StreamString.h"
23#include "lldb/Host/ConnectionFileDescriptor.h"
24#include "lldb/Host/FileSpec.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000025#include "lldb/Host/FileSystem.h"
Zachary Turnerf343968f2016-08-09 23:06:08 +000026#include "lldb/Host/PosixApi.h"
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000027
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000028#include <limits.h>
29
Oleksiy Vyalov6f001062015-03-25 17:58:13 +000030#include <algorithm>
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +000031#include <cstdlib>
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000032#include <fstream>
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000033#include <sstream>
34
Adrian McCarthy1341d4c2016-06-30 20:55:50 +000035// On Windows, transitive dependencies pull in <Windows.h>, which defines a
36// macro that clashes with a method name.
37#ifdef SendMessage
38#undef SendMessage
39#endif
40
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000041using namespace lldb;
42using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000043using namespace lldb_private::platform_android;
Pavel Labath818dd512016-11-24 14:03:57 +000044using namespace std::chrono;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000045
46namespace {
47
Pavel Labath818dd512016-11-24 14:03:57 +000048const seconds kReadTimeout(8);
Kate Stoneb9c1b512016-09-06 20:57:50 +000049const char *kOKAY = "OKAY";
50const char *kFAIL = "FAIL";
51const char *kDATA = "DATA";
52const char *kDONE = "DONE";
Oleksiy Vyalov6002a312015-06-05 01:32:45 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054const char *kSEND = "SEND";
55const char *kRECV = "RECV";
56const char *kSTAT = "STAT";
Oleksiy Vyalov6002a312015-06-05 01:32:45 +000057
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +000058const size_t kSyncPacketLen = 8;
Robert Flack62efb1f2015-05-27 02:18:50 +000059// Maximum size of a filesync DATA packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +000060const size_t kMaxPushData = 2 * 1024;
Robert Flack62efb1f2015-05-27 02:18:50 +000061// Default mode for pushed files.
62const uint32_t kDefaultMode = 0100770; // S_IFREG | S_IRWXU | S_IRWXG
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +000063
Kate Stoneb9c1b512016-09-06 20:57:50 +000064const char *kSocketNamespaceAbstract = "localabstract";
65const char *kSocketNamespaceFileSystem = "localfilesystem";
Oleksiy Vyalove7df5f52015-11-03 01:37:01 +000066
Kate Stoneb9c1b512016-09-06 20:57:50 +000067Error ReadAllBytes(Connection &conn, void *buffer, size_t size) {
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 Error error;
70 ConnectionStatus status;
71 char *read_buffer = static_cast<char *>(buffer);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073 auto now = steady_clock::now();
74 const auto deadline = now + kReadTimeout;
75 size_t total_read_bytes = 0;
76 while (total_read_bytes < size && now < deadline) {
77 uint32_t timeout_usec = duration_cast<microseconds>(deadline - now).count();
78 auto read_bytes =
79 conn.Read(read_buffer + total_read_bytes, size - total_read_bytes,
80 timeout_usec, status, &error);
Chaoren Lin3ea689b2015-05-01 16:49:28 +000081 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 return error;
83 total_read_bytes += read_bytes;
84 if (status != eConnectionStatusSuccess)
85 break;
86 now = steady_clock::now();
87 }
88 if (total_read_bytes < size)
89 error = Error(
90 "Unable to read requested number of bytes. Connection status: %d.",
91 status);
92 return error;
93}
Oleksiy Vyalov6f001062015-03-25 17:58:13 +000094
Kate Stoneb9c1b512016-09-06 20:57:50 +000095} // namespace
Luke Drummond3db04912016-07-07 18:02:44 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097Error AdbClient::CreateByDeviceID(const std::string &device_id,
98 AdbClient &adb) {
99 DeviceIDList connect_devices;
100 auto error = adb.GetDevices(connect_devices);
101 if (error.Fail())
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000102 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103
104 std::string android_serial;
105 if (!device_id.empty())
106 android_serial = device_id;
107 else if (const char *env_serial = std::getenv("ANDROID_SERIAL"))
108 android_serial = env_serial;
109
110 if (android_serial.empty()) {
111 if (connect_devices.size() != 1)
112 return Error("Expected a single connected device, got instead %zu - try "
113 "setting 'ANDROID_SERIAL'",
114 connect_devices.size());
115 adb.SetDeviceID(connect_devices.front());
116 } else {
117 auto find_it = std::find(connect_devices.begin(), connect_devices.end(),
118 android_serial);
119 if (find_it == connect_devices.end())
120 return Error("Device \"%s\" not found", android_serial.c_str());
121
122 adb.SetDeviceID(*find_it);
123 }
124 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000125}
126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127AdbClient::AdbClient() {}
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129AdbClient::AdbClient(const std::string &device_id) : m_device_id(device_id) {}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000130
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000131AdbClient::~AdbClient() {}
132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133void AdbClient::SetDeviceID(const std::string &device_id) {
134 m_device_id = device_id;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000135}
136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137const std::string &AdbClient::GetDeviceID() const { return m_device_id; }
138
139Error AdbClient::Connect() {
140 Error error;
141 m_conn.reset(new ConnectionFileDescriptor);
142 m_conn->Connect("connect://localhost:5037", &error);
143
144 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000145}
146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147Error AdbClient::GetDevices(DeviceIDList &device_list) {
148 device_list.clear();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 auto error = SendMessage("host:devices");
151 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000152 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 error = ReadResponseStatus();
155 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000156 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157
158 std::vector<char> in_buffer;
159 error = ReadMessage(in_buffer);
160
161 llvm::StringRef response(&in_buffer[0], in_buffer.size());
162 llvm::SmallVector<llvm::StringRef, 4> devices;
163 response.split(devices, "\n", -1, false);
164
165 for (const auto device : devices)
166 device_list.push_back(device.split('\t').first);
167
168 // Force disconnect since ADB closes connection after host:devices
169 // response is sent.
170 m_conn.reset();
171 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174Error AdbClient::SetPortForwarding(const uint16_t local_port,
175 const uint16_t remote_port) {
176 char message[48];
177 snprintf(message, sizeof(message), "forward:tcp:%d;tcp:%d", local_port,
178 remote_port);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 const auto error = SendDeviceMessage(message);
181 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000182 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183
184 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187Error AdbClient::SetPortForwarding(const uint16_t local_port,
Zachary Turner245f7fd2016-11-17 01:38:02 +0000188 llvm::StringRef remote_socket_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189 const UnixSocketNamespace socket_namespace) {
190 char message[PATH_MAX];
191 const char *sock_namespace_str =
192 (socket_namespace == UnixSocketNamespaceAbstract)
193 ? kSocketNamespaceAbstract
194 : kSocketNamespaceFileSystem;
195 snprintf(message, sizeof(message), "forward:tcp:%d;%s:%s", local_port,
Zachary Turner245f7fd2016-11-17 01:38:02 +0000196 sock_namespace_str, remote_socket_name.str().c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 const auto error = SendDeviceMessage(message);
199 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000200 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201
202 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205Error AdbClient::DeletePortForwarding(const uint16_t local_port) {
206 char message[32];
207 snprintf(message, sizeof(message), "killforward:tcp:%d", local_port);
208
209 const auto error = SendDeviceMessage(message);
210 if (error.Fail())
211 return error;
212
213 return ReadResponseStatus();
214}
215
216Error AdbClient::SendMessage(const std::string &packet, const bool reconnect) {
217 Error error;
218 if (!m_conn || reconnect) {
219 error = Connect();
220 if (error.Fail())
221 return error;
222 }
223
224 char length_buffer[5];
225 snprintf(length_buffer, sizeof(length_buffer), "%04x",
226 static_cast<int>(packet.size()));
227
228 ConnectionStatus status;
229
230 m_conn->Write(length_buffer, 4, status, &error);
231 if (error.Fail())
232 return error;
233
234 m_conn->Write(packet.c_str(), packet.size(), status, &error);
235 return error;
236}
237
238Error AdbClient::SendDeviceMessage(const std::string &packet) {
239 std::ostringstream msg;
240 msg << "host-serial:" << m_device_id << ":" << packet;
241 return SendMessage(msg.str());
242}
243
244Error AdbClient::ReadMessage(std::vector<char> &message) {
245 message.clear();
246
247 char buffer[5];
248 buffer[4] = 0;
249
250 auto error = ReadAllBytes(buffer, 4);
251 if (error.Fail())
252 return error;
253
254 unsigned int packet_len = 0;
255 sscanf(buffer, "%x", &packet_len);
256
257 message.resize(packet_len, 0);
258 error = ReadAllBytes(&message[0], packet_len);
259 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000260 message.clear();
261
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 return error;
263}
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265Error AdbClient::ReadMessageStream(std::vector<char> &message,
Pavel Labath818dd512016-11-24 14:03:57 +0000266 milliseconds timeout) {
267 auto start = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 message.clear();
269
270 Error error;
271 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
272 char buffer[1024];
273 while (error.Success() && status == lldb::eConnectionStatusSuccess) {
Pavel Labath818dd512016-11-24 14:03:57 +0000274 auto end = steady_clock::now();
275 auto elapsed = end - start;
276 if (elapsed >= timeout)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 return Error("Timed out");
278
Pavel Labath818dd512016-11-24 14:03:57 +0000279 size_t n = m_conn->Read(
280 buffer, sizeof(buffer),
281 duration_cast<microseconds>(timeout - elapsed).count(), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 if (n > 0)
283 message.insert(message.end(), &buffer[0], &buffer[n]);
284 }
285 return error;
286}
287
288Error AdbClient::ReadResponseStatus() {
289 char response_id[5];
290
291 static const size_t packet_len = 4;
292 response_id[packet_len] = 0;
293
294 auto error = ReadAllBytes(response_id, packet_len);
295 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000296 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297
298 if (strncmp(response_id, kOKAY, packet_len) != 0)
299 return GetResponseError(response_id);
300
301 return error;
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000302}
303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304Error AdbClient::GetResponseError(const char *response_id) {
305 if (strcmp(response_id, kFAIL) != 0)
306 return Error("Got unexpected response id from adb: \"%s\"", response_id);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000307
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 std::vector<char> error_message;
309 auto error = ReadMessage(error_message);
310 if (error.Success())
311 error.SetErrorString(
312 std::string(&error_message[0], error_message.size()).c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000313
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 return error;
315}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000316
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317Error AdbClient::SwitchDeviceTransport() {
318 std::ostringstream msg;
319 msg << "host:transport:" << m_device_id;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 auto error = SendMessage(msg.str());
322 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000323 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324
325 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000326}
327
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328Error AdbClient::StartSync() {
329 auto error = SwitchDeviceTransport();
330 if (error.Fail())
331 return Error("Failed to switch to device transport: %s", error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 error = Sync();
334 if (error.Fail())
335 return Error("Sync failed: %s", error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 return error;
338}
339
340Error AdbClient::Sync() {
341 auto error = SendMessage("sync:", false);
342 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000343 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344
345 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000346}
347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348Error AdbClient::ReadAllBytes(void *buffer, size_t size) {
349 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000350}
351
Pavel Labath818dd512016-11-24 14:03:57 +0000352Error AdbClient::internalShell(const char *command, milliseconds timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 std::vector<char> &output_buf) {
354 output_buf.clear();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 auto error = SwitchDeviceTransport();
357 if (error.Fail())
358 return Error("Failed to switch to device transport: %s", error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000359
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 StreamString adb_command;
361 adb_command.Printf("shell:%s", command);
Zachary Turnerc1564272016-11-16 21:15:24 +0000362 error = SendMessage(adb_command.GetString(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000364 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 error = ReadResponseStatus();
367 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000368 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369
Pavel Labath818dd512016-11-24 14:03:57 +0000370 error = ReadMessageStream(output_buf, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 if (error.Fail())
372 return error;
373
374 // ADB doesn't propagate return code of shell execution - if
375 // output starts with /system/bin/sh: most likely command failed.
376 static const char *kShellPrefix = "/system/bin/sh:";
377 if (output_buf.size() > strlen(kShellPrefix)) {
378 if (!memcmp(&output_buf[0], kShellPrefix, strlen(kShellPrefix)))
379 return Error("Shell command %s failed: %s", command,
380 std::string(output_buf.begin(), output_buf.end()).c_str());
381 }
382
Mehdi Aminic1edf562016-11-11 04:29:25 +0000383 return Error();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000384}
385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386Error AdbClient::Shell(const char *command, uint32_t timeout_ms,
387 std::string *output) {
388 std::vector<char> output_buffer;
Pavel Labath818dd512016-11-24 14:03:57 +0000389 auto error = internalShell(command, milliseconds(timeout_ms), output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 if (error.Fail())
391 return error;
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 if (output)
394 output->assign(output_buffer.begin(), output_buffer.end());
395 return error;
396}
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398Error AdbClient::ShellToFile(const char *command, uint32_t timeout_ms,
399 const FileSpec &output_file_spec) {
400 std::vector<char> output_buffer;
Pavel Labath818dd512016-11-24 14:03:57 +0000401 auto error = internalShell(command, milliseconds(timeout_ms), output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 if (error.Fail())
403 return error;
404
405 const auto output_filename = output_file_spec.GetPath();
406 std::ofstream dst(output_filename, std::ios::out | std::ios::binary);
407 if (!dst.is_open())
408 return Error("Unable to open local file %s", output_filename.c_str());
409
410 dst.write(&output_buffer[0], output_buffer.size());
411 dst.close();
412 if (!dst)
413 return Error("Failed to write file %s", output_filename.c_str());
Mehdi Aminic1edf562016-11-11 04:29:25 +0000414 return Error();
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000415}
416
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000417std::unique_ptr<AdbClient::SyncService>
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418AdbClient::GetSyncService(Error &error) {
419 std::unique_ptr<SyncService> sync_service;
420 error = StartSync();
421 if (error.Success())
422 sync_service.reset(new SyncService(std::move(m_conn)));
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000423
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 return sync_service;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000425}
426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427Error AdbClient::SyncService::internalPullFile(const FileSpec &remote_file,
428 const FileSpec &local_file) {
429 const auto local_file_path = local_file.GetPath();
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000430 llvm::FileRemover local_file_remover(local_file_path);
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 std::ofstream dst(local_file_path, std::ios::out | std::ios::binary);
433 if (!dst.is_open())
434 return Error("Unable to open local file %s", local_file_path.c_str());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 const auto remote_file_path = remote_file.GetPath(false);
437 auto error = SendSyncRequest(kRECV, remote_file_path.length(),
438 remote_file_path.c_str());
439 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000440 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441
442 std::vector<char> chunk;
443 bool eof = false;
444 while (!eof) {
445 error = PullFileChunk(chunk, eof);
446 if (error.Fail())
447 return error;
448 if (!eof)
449 dst.write(&chunk[0], chunk.size());
450 }
451
452 local_file_remover.releaseFile();
453 return error;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000454}
455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456Error AdbClient::SyncService::internalPushFile(const FileSpec &local_file,
457 const FileSpec &remote_file) {
458 const auto local_file_path(local_file.GetPath());
459 std::ifstream src(local_file_path.c_str(), std::ios::in | std::ios::binary);
460 if (!src.is_open())
461 return Error("Unable to open local file %s", local_file_path.c_str());
Robert Flack62efb1f2015-05-27 02:18:50 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 std::stringstream file_description;
464 file_description << remote_file.GetPath(false).c_str() << "," << kDefaultMode;
465 std::string file_description_str = file_description.str();
466 auto error = SendSyncRequest(kSEND, file_description_str.length(),
467 file_description_str.c_str());
468 if (error.Fail())
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000469 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470
471 char chunk[kMaxPushData];
472 while (!src.eof() && !src.read(chunk, kMaxPushData).bad()) {
473 size_t chunk_size = src.gcount();
474 error = SendSyncRequest(kDATA, chunk_size, chunk);
475 if (error.Fail())
476 return Error("Failed to send file chunk: %s", error.AsCString());
477 }
Pavel Labath1408bf72016-11-01 16:11:14 +0000478 error = SendSyncRequest(
Pavel Labath818dd512016-11-24 14:03:57 +0000479 kDONE, llvm::sys::toTimeT(FileSystem::GetModificationTime(local_file)),
Pavel Labath1408bf72016-11-01 16:11:14 +0000480 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 if (error.Fail())
482 return error;
483
484 std::string response_id;
485 uint32_t data_len;
486 error = ReadSyncHeader(response_id, data_len);
487 if (error.Fail())
488 return Error("Failed to read DONE response: %s", error.AsCString());
489 if (response_id == kFAIL) {
490 std::string error_message(data_len, 0);
491 error = ReadAllBytes(&error_message[0], data_len);
492 if (error.Fail())
493 return Error("Failed to read DONE error message: %s", error.AsCString());
494 return Error("Failed to push file: %s", error_message.c_str());
495 } else if (response_id != kOKAY)
496 return Error("Got unexpected DONE response: %s", response_id.c_str());
497
498 // If there was an error reading the source file, finish the adb file
499 // transfer first so that adb isn't expecting any more data.
500 if (src.bad())
501 return Error("Failed read on %s", local_file_path.c_str());
502 return error;
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000503}
504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505Error AdbClient::SyncService::internalStat(const FileSpec &remote_file,
506 uint32_t &mode, uint32_t &size,
507 uint32_t &mtime) {
508 const std::string remote_file_path(remote_file.GetPath(false));
509 auto error = SendSyncRequest(kSTAT, remote_file_path.length(),
510 remote_file_path.c_str());
511 if (error.Fail())
512 return Error("Failed to send request: %s", error.AsCString());
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 static const size_t stat_len = strlen(kSTAT);
515 static const size_t response_len = stat_len + (sizeof(uint32_t) * 3);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 std::vector<char> buffer(response_len);
518 error = ReadAllBytes(&buffer[0], buffer.size());
519 if (error.Fail())
520 return Error("Failed to read response: %s", error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 DataExtractor extractor(&buffer[0], buffer.size(), eByteOrderLittle,
523 sizeof(void *));
524 offset_t offset = 0;
525
526 const void *command = extractor.GetData(&offset, stat_len);
527 if (!command)
528 return Error("Failed to get response command");
529 const char *command_str = static_cast<const char *>(command);
530 if (strncmp(command_str, kSTAT, stat_len))
531 return Error("Got invalid stat command: %s", command_str);
532
533 mode = extractor.GetU32(&offset);
534 size = extractor.GetU32(&offset);
535 mtime = extractor.GetU32(&offset);
Mehdi Aminic1edf562016-11-11 04:29:25 +0000536 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537}
538
539Error AdbClient::SyncService::PullFile(const FileSpec &remote_file,
540 const FileSpec &local_file) {
541 return executeCommand([this, &remote_file, &local_file]() {
542 return internalPullFile(remote_file, local_file);
543 });
544}
545
546Error AdbClient::SyncService::PushFile(const FileSpec &local_file,
547 const FileSpec &remote_file) {
548 return executeCommand([this, &local_file, &remote_file]() {
549 return internalPushFile(local_file, remote_file);
550 });
551}
552
553Error AdbClient::SyncService::Stat(const FileSpec &remote_file, uint32_t &mode,
554 uint32_t &size, uint32_t &mtime) {
555 return executeCommand([this, &remote_file, &mode, &size, &mtime]() {
556 return internalStat(remote_file, mode, size, mtime);
557 });
558}
559
560bool AdbClient::SyncService::IsConnected() const {
561 return m_conn && m_conn->IsConnected();
562}
563
564AdbClient::SyncService::SyncService(std::unique_ptr<Connection> &&conn)
565 : m_conn(std::move(conn)) {}
566
567Error AdbClient::SyncService::executeCommand(
568 const std::function<Error()> &cmd) {
569 if (!m_conn)
570 return Error("SyncService is disconnected");
571
572 const auto error = cmd();
573 if (error.Fail())
574 m_conn.reset();
575
576 return error;
577}
578
579AdbClient::SyncService::~SyncService() {}
580
581Error AdbClient::SyncService::SendSyncRequest(const char *request_id,
582 const uint32_t data_len,
583 const void *data) {
584 const DataBufferSP data_sp(new DataBufferHeap(kSyncPacketLen, 0));
585 DataEncoder encoder(data_sp, eByteOrderLittle, sizeof(void *));
586 auto offset = encoder.PutData(0, request_id, strlen(request_id));
587 encoder.PutU32(offset, data_len);
588
589 Error error;
590 ConnectionStatus status;
591 m_conn->Write(data_sp->GetBytes(), kSyncPacketLen, status, &error);
592 if (error.Fail())
593 return error;
594
595 if (data)
596 m_conn->Write(data, data_len, status, &error);
597 return error;
598}
599
600Error AdbClient::SyncService::ReadSyncHeader(std::string &response_id,
601 uint32_t &data_len) {
602 char buffer[kSyncPacketLen];
603
604 auto error = ReadAllBytes(buffer, kSyncPacketLen);
605 if (error.Success()) {
606 response_id.assign(&buffer[0], 4);
607 DataExtractor extractor(&buffer[4], 4, eByteOrderLittle, sizeof(void *));
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000608 offset_t offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 data_len = extractor.GetU32(&offset);
610 }
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000613}
614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615Error AdbClient::SyncService::PullFileChunk(std::vector<char> &buffer,
616 bool &eof) {
617 buffer.clear();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 std::string response_id;
620 uint32_t data_len;
621 auto error = ReadSyncHeader(response_id, data_len);
622 if (error.Fail())
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000623 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624
625 if (response_id == kDATA) {
626 buffer.resize(data_len, 0);
627 error = ReadAllBytes(&buffer[0], data_len);
628 if (error.Fail())
629 buffer.clear();
630 } else if (response_id == kDONE) {
631 eof = true;
632 } else if (response_id == kFAIL) {
633 std::string error_message(data_len, 0);
634 error = ReadAllBytes(&error_message[0], data_len);
635 if (error.Fail())
636 return Error("Failed to read pull error message: %s", error.AsCString());
637 return Error("Failed to pull file: %s", error_message.c_str());
638 } else
639 return Error("Pull failed with unknown response: %s", response_id.c_str());
640
Mehdi Aminic1edf562016-11-11 04:29:25 +0000641 return Error();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000642}
643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644Error AdbClient::SyncService::ReadAllBytes(void *buffer, size_t size) {
645 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000646}