blob: bcbcf441df46e88375aa3d0a76c0cb2429d3f029 [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/Host/ConnectionFileDescriptor.h"
19#include "lldb/Host/FileSpec.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000020#include "lldb/Host/FileSystem.h"
Zachary Turnerf343968f2016-08-09 23:06:08 +000021#include "lldb/Host/PosixApi.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000022#include "lldb/Utility/DataBuffer.h"
23#include "lldb/Utility/DataBufferHeap.h"
24#include "lldb/Utility/DataEncoder.h"
25#include "lldb/Utility/DataExtractor.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000026#include "lldb/Utility/StreamString.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) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 auto read_bytes =
78 conn.Read(read_buffer + total_read_bytes, size - total_read_bytes,
Pavel Labath2f159a52016-11-25 12:22:32 +000079 duration_cast<microseconds>(deadline - now), status, &error);
Chaoren Lin3ea689b2015-05-01 16:49:28 +000080 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 return error;
82 total_read_bytes += read_bytes;
83 if (status != eConnectionStatusSuccess)
84 break;
85 now = steady_clock::now();
86 }
87 if (total_read_bytes < size)
88 error = Error(
89 "Unable to read requested number of bytes. Connection status: %d.",
90 status);
91 return error;
92}
Oleksiy Vyalov6f001062015-03-25 17:58:13 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094} // namespace
Luke Drummond3db04912016-07-07 18:02:44 +000095
Kate Stoneb9c1b512016-09-06 20:57:50 +000096Error AdbClient::CreateByDeviceID(const std::string &device_id,
97 AdbClient &adb) {
98 DeviceIDList connect_devices;
99 auto error = adb.GetDevices(connect_devices);
100 if (error.Fail())
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000101 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102
103 std::string android_serial;
104 if (!device_id.empty())
105 android_serial = device_id;
106 else if (const char *env_serial = std::getenv("ANDROID_SERIAL"))
107 android_serial = env_serial;
108
109 if (android_serial.empty()) {
110 if (connect_devices.size() != 1)
111 return Error("Expected a single connected device, got instead %zu - try "
112 "setting 'ANDROID_SERIAL'",
113 connect_devices.size());
114 adb.SetDeviceID(connect_devices.front());
115 } else {
116 auto find_it = std::find(connect_devices.begin(), connect_devices.end(),
117 android_serial);
118 if (find_it == connect_devices.end())
119 return Error("Device \"%s\" not found", android_serial.c_str());
120
121 adb.SetDeviceID(*find_it);
122 }
123 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000124}
125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126AdbClient::AdbClient() {}
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128AdbClient::AdbClient(const std::string &device_id) : m_device_id(device_id) {}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000129
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000130AdbClient::~AdbClient() {}
131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132void AdbClient::SetDeviceID(const std::string &device_id) {
133 m_device_id = device_id;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000134}
135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136const std::string &AdbClient::GetDeviceID() const { return m_device_id; }
137
138Error AdbClient::Connect() {
139 Error error;
140 m_conn.reset(new ConnectionFileDescriptor);
141 m_conn->Connect("connect://localhost:5037", &error);
142
143 return error;
Oleksiy Vyalov6f001062015-03-25 17:58:13 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146Error AdbClient::GetDevices(DeviceIDList &device_list) {
147 device_list.clear();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 auto error = SendMessage("host:devices");
150 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000151 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 error = ReadResponseStatus();
154 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000155 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156
157 std::vector<char> in_buffer;
158 error = ReadMessage(in_buffer);
159
160 llvm::StringRef response(&in_buffer[0], in_buffer.size());
161 llvm::SmallVector<llvm::StringRef, 4> devices;
162 response.split(devices, "\n", -1, false);
163
164 for (const auto device : devices)
165 device_list.push_back(device.split('\t').first);
166
167 // Force disconnect since ADB closes connection after host:devices
168 // response is sent.
169 m_conn.reset();
170 return error;
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000171}
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173Error AdbClient::SetPortForwarding(const uint16_t local_port,
174 const uint16_t remote_port) {
175 char message[48];
176 snprintf(message, sizeof(message), "forward:tcp:%d;tcp:%d", local_port,
177 remote_port);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000178
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179 const auto error = SendDeviceMessage(message);
180 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000181 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182
183 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186Error AdbClient::SetPortForwarding(const uint16_t local_port,
Zachary Turner245f7fd2016-11-17 01:38:02 +0000187 llvm::StringRef remote_socket_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188 const UnixSocketNamespace socket_namespace) {
189 char message[PATH_MAX];
190 const char *sock_namespace_str =
191 (socket_namespace == UnixSocketNamespaceAbstract)
192 ? kSocketNamespaceAbstract
193 : kSocketNamespaceFileSystem;
194 snprintf(message, sizeof(message), "forward:tcp:%d;%s:%s", local_port,
Zachary Turner245f7fd2016-11-17 01:38:02 +0000195 sock_namespace_str, remote_socket_name.str().c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 const auto error = SendDeviceMessage(message);
198 if (error.Fail())
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000199 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200
201 return ReadResponseStatus();
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204Error AdbClient::DeletePortForwarding(const uint16_t local_port) {
205 char message[32];
206 snprintf(message, sizeof(message), "killforward:tcp:%d", local_port);
207
208 const auto error = SendDeviceMessage(message);
209 if (error.Fail())
210 return error;
211
212 return ReadResponseStatus();
213}
214
215Error AdbClient::SendMessage(const std::string &packet, const bool reconnect) {
216 Error error;
217 if (!m_conn || reconnect) {
218 error = Connect();
219 if (error.Fail())
220 return error;
221 }
222
223 char length_buffer[5];
224 snprintf(length_buffer, sizeof(length_buffer), "%04x",
225 static_cast<int>(packet.size()));
226
227 ConnectionStatus status;
228
229 m_conn->Write(length_buffer, 4, status, &error);
230 if (error.Fail())
231 return error;
232
233 m_conn->Write(packet.c_str(), packet.size(), status, &error);
234 return error;
235}
236
237Error AdbClient::SendDeviceMessage(const std::string &packet) {
238 std::ostringstream msg;
239 msg << "host-serial:" << m_device_id << ":" << packet;
240 return SendMessage(msg.str());
241}
242
243Error AdbClient::ReadMessage(std::vector<char> &message) {
244 message.clear();
245
246 char buffer[5];
247 buffer[4] = 0;
248
249 auto error = ReadAllBytes(buffer, 4);
250 if (error.Fail())
251 return error;
252
253 unsigned int packet_len = 0;
254 sscanf(buffer, "%x", &packet_len);
255
256 message.resize(packet_len, 0);
257 error = ReadAllBytes(&message[0], packet_len);
258 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000259 message.clear();
260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 return error;
262}
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264Error AdbClient::ReadMessageStream(std::vector<char> &message,
Pavel Labath818dd512016-11-24 14:03:57 +0000265 milliseconds timeout) {
266 auto start = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 message.clear();
268
269 Error error;
270 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
271 char buffer[1024];
272 while (error.Success() && status == lldb::eConnectionStatusSuccess) {
Pavel Labath818dd512016-11-24 14:03:57 +0000273 auto end = steady_clock::now();
274 auto elapsed = end - start;
275 if (elapsed >= timeout)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 return Error("Timed out");
277
Pavel Labath2f159a52016-11-25 12:22:32 +0000278 size_t n = m_conn->Read(buffer, sizeof(buffer),
279 duration_cast<microseconds>(timeout - elapsed),
280 status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 if (n > 0)
282 message.insert(message.end(), &buffer[0], &buffer[n]);
283 }
284 return error;
285}
286
287Error AdbClient::ReadResponseStatus() {
288 char response_id[5];
289
290 static const size_t packet_len = 4;
291 response_id[packet_len] = 0;
292
293 auto error = ReadAllBytes(response_id, packet_len);
294 if (error.Fail())
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000295 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296
297 if (strncmp(response_id, kOKAY, packet_len) != 0)
298 return GetResponseError(response_id);
299
300 return error;
Tamas Berghammer9d8dde82015-09-29 11:04:18 +0000301}
302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303Error AdbClient::GetResponseError(const char *response_id) {
304 if (strcmp(response_id, kFAIL) != 0)
305 return Error("Got unexpected response id from adb: \"%s\"", response_id);
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000306
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 std::vector<char> error_message;
308 auto error = ReadMessage(error_message);
309 if (error.Success())
310 error.SetErrorString(
311 std::string(&error_message[0], error_message.size()).c_str());
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 return error;
314}
Oleksiy Vyalov05a55de2015-03-23 21:03:02 +0000315
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316Error AdbClient::SwitchDeviceTransport() {
317 std::ostringstream msg;
318 msg << "host:transport:" << m_device_id;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000319
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 auto error = SendMessage(msg.str());
321 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000322 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323
324 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000325}
326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327Error AdbClient::StartSync() {
328 auto error = SwitchDeviceTransport();
329 if (error.Fail())
330 return Error("Failed to switch to device transport: %s", error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000331
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 error = Sync();
333 if (error.Fail())
334 return Error("Sync failed: %s", error.AsCString());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 return error;
337}
338
339Error AdbClient::Sync() {
340 auto error = SendMessage("sync:", false);
341 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000342 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343
344 return ReadResponseStatus();
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000345}
346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347Error AdbClient::ReadAllBytes(void *buffer, size_t size) {
348 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000349}
350
Pavel Labath818dd512016-11-24 14:03:57 +0000351Error AdbClient::internalShell(const char *command, milliseconds timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 std::vector<char> &output_buf) {
353 output_buf.clear();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 auto error = SwitchDeviceTransport();
356 if (error.Fail())
357 return Error("Failed to switch to device transport: %s", error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 StreamString adb_command;
360 adb_command.Printf("shell:%s", command);
Zachary Turnerc1564272016-11-16 21:15:24 +0000361 error = SendMessage(adb_command.GetString(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000363 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 error = ReadResponseStatus();
366 if (error.Fail())
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000367 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368
Pavel Labath818dd512016-11-24 14:03:57 +0000369 error = ReadMessageStream(output_buf, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 if (error.Fail())
371 return error;
372
373 // ADB doesn't propagate return code of shell execution - if
374 // output starts with /system/bin/sh: most likely command failed.
375 static const char *kShellPrefix = "/system/bin/sh:";
376 if (output_buf.size() > strlen(kShellPrefix)) {
377 if (!memcmp(&output_buf[0], kShellPrefix, strlen(kShellPrefix)))
378 return Error("Shell command %s failed: %s", command,
379 std::string(output_buf.begin(), output_buf.end()).c_str());
380 }
381
Mehdi Aminic1edf562016-11-11 04:29:25 +0000382 return Error();
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000383}
384
Pavel Labathce255ff2016-11-24 14:11:47 +0000385Error AdbClient::Shell(const char *command, milliseconds timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 std::string *output) {
387 std::vector<char> output_buffer;
Pavel Labathce255ff2016-11-24 14:11:47 +0000388 auto error = internalShell(command, timeout, output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 if (error.Fail())
390 return error;
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 if (output)
393 output->assign(output_buffer.begin(), output_buffer.end());
394 return error;
395}
Oleksiy Vyalovc6ac2e12016-07-08 17:45:37 +0000396
Pavel Labathce255ff2016-11-24 14:11:47 +0000397Error AdbClient::ShellToFile(const char *command, milliseconds timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 const FileSpec &output_file_spec) {
399 std::vector<char> output_buffer;
Pavel Labathce255ff2016-11-24 14:11:47 +0000400 auto error = internalShell(command, timeout, output_buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 if (error.Fail())
402 return error;
403
404 const auto output_filename = output_file_spec.GetPath();
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000405 std::error_code EC;
406 llvm::raw_fd_ostream dst(output_filename, EC, llvm::sys::fs::F_None);
407 if (EC)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 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();
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000412 if (dst.has_error())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 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
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000432 std::error_code EC;
433 llvm::raw_fd_ostream dst(local_file_path, EC, llvm::sys::fs::F_None);
434 if (EC)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 return Error("Unable to open local file %s", local_file_path.c_str());
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 const auto remote_file_path = remote_file.GetPath(false);
438 auto error = SendSyncRequest(kRECV, remote_file_path.length(),
439 remote_file_path.c_str());
440 if (error.Fail())
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000441 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442
443 std::vector<char> chunk;
444 bool eof = false;
445 while (!eof) {
446 error = PullFileChunk(chunk, eof);
447 if (error.Fail())
448 return error;
449 if (!eof)
450 dst.write(&chunk[0], chunk.size());
451 }
Pavel Labathe3ad2e22017-03-21 13:49:50 +0000452 dst.close();
453 if (dst.has_error())
454 return Error("Failed to write file %s", local_file_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455
456 local_file_remover.releaseFile();
457 return error;
Oleksiy Vyalov09e9079d2015-05-18 23:44:06 +0000458}
459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460Error AdbClient::SyncService::internalPushFile(const FileSpec &local_file,
461 const FileSpec &remote_file) {
462 const auto local_file_path(local_file.GetPath());
463 std::ifstream src(local_file_path.c_str(), std::ios::in | std::ios::binary);
464 if (!src.is_open())
465 return Error("Unable to open local file %s", local_file_path.c_str());
Robert Flack62efb1f2015-05-27 02:18:50 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 std::stringstream file_description;
468 file_description << remote_file.GetPath(false).c_str() << "," << kDefaultMode;
469 std::string file_description_str = file_description.str();
470 auto error = SendSyncRequest(kSEND, file_description_str.length(),
471 file_description_str.c_str());
472 if (error.Fail())
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000473 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474
475 char chunk[kMaxPushData];
476 while (!src.eof() && !src.read(chunk, kMaxPushData).bad()) {
477 size_t chunk_size = src.gcount();
478 error = SendSyncRequest(kDATA, chunk_size, chunk);
479 if (error.Fail())
480 return Error("Failed to send file chunk: %s", error.AsCString());
481 }
Pavel Labath1408bf72016-11-01 16:11:14 +0000482 error = SendSyncRequest(
Pavel Labath818dd512016-11-24 14:03:57 +0000483 kDONE, llvm::sys::toTimeT(FileSystem::GetModificationTime(local_file)),
Pavel Labath1408bf72016-11-01 16:11:14 +0000484 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 if (error.Fail())
486 return error;
487
488 std::string response_id;
489 uint32_t data_len;
490 error = ReadSyncHeader(response_id, data_len);
491 if (error.Fail())
492 return Error("Failed to read DONE response: %s", error.AsCString());
493 if (response_id == kFAIL) {
494 std::string error_message(data_len, 0);
495 error = ReadAllBytes(&error_message[0], data_len);
496 if (error.Fail())
497 return Error("Failed to read DONE error message: %s", error.AsCString());
498 return Error("Failed to push file: %s", error_message.c_str());
499 } else if (response_id != kOKAY)
500 return Error("Got unexpected DONE response: %s", response_id.c_str());
501
502 // If there was an error reading the source file, finish the adb file
503 // transfer first so that adb isn't expecting any more data.
504 if (src.bad())
505 return Error("Failed read on %s", local_file_path.c_str());
506 return error;
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000507}
508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509Error AdbClient::SyncService::internalStat(const FileSpec &remote_file,
510 uint32_t &mode, uint32_t &size,
511 uint32_t &mtime) {
512 const std::string remote_file_path(remote_file.GetPath(false));
513 auto error = SendSyncRequest(kSTAT, remote_file_path.length(),
514 remote_file_path.c_str());
515 if (error.Fail())
516 return Error("Failed to send request: %s", error.AsCString());
Oleksiy Vyalov0b5ebef2015-05-28 17:42:48 +0000517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 static const size_t stat_len = strlen(kSTAT);
519 static const size_t response_len = stat_len + (sizeof(uint32_t) * 3);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 std::vector<char> buffer(response_len);
522 error = ReadAllBytes(&buffer[0], buffer.size());
523 if (error.Fail())
524 return Error("Failed to read response: %s", error.AsCString());
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 DataExtractor extractor(&buffer[0], buffer.size(), eByteOrderLittle,
527 sizeof(void *));
528 offset_t offset = 0;
529
530 const void *command = extractor.GetData(&offset, stat_len);
531 if (!command)
532 return Error("Failed to get response command");
533 const char *command_str = static_cast<const char *>(command);
534 if (strncmp(command_str, kSTAT, stat_len))
535 return Error("Got invalid stat command: %s", command_str);
536
537 mode = extractor.GetU32(&offset);
538 size = extractor.GetU32(&offset);
539 mtime = extractor.GetU32(&offset);
Mehdi Aminic1edf562016-11-11 04:29:25 +0000540 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541}
542
543Error AdbClient::SyncService::PullFile(const FileSpec &remote_file,
544 const FileSpec &local_file) {
545 return executeCommand([this, &remote_file, &local_file]() {
546 return internalPullFile(remote_file, local_file);
547 });
548}
549
550Error AdbClient::SyncService::PushFile(const FileSpec &local_file,
551 const FileSpec &remote_file) {
552 return executeCommand([this, &local_file, &remote_file]() {
553 return internalPushFile(local_file, remote_file);
554 });
555}
556
557Error AdbClient::SyncService::Stat(const FileSpec &remote_file, uint32_t &mode,
558 uint32_t &size, uint32_t &mtime) {
559 return executeCommand([this, &remote_file, &mode, &size, &mtime]() {
560 return internalStat(remote_file, mode, size, mtime);
561 });
562}
563
564bool AdbClient::SyncService::IsConnected() const {
565 return m_conn && m_conn->IsConnected();
566}
567
568AdbClient::SyncService::SyncService(std::unique_ptr<Connection> &&conn)
569 : m_conn(std::move(conn)) {}
570
571Error AdbClient::SyncService::executeCommand(
572 const std::function<Error()> &cmd) {
573 if (!m_conn)
574 return Error("SyncService is disconnected");
575
576 const auto error = cmd();
577 if (error.Fail())
578 m_conn.reset();
579
580 return error;
581}
582
583AdbClient::SyncService::~SyncService() {}
584
585Error AdbClient::SyncService::SendSyncRequest(const char *request_id,
586 const uint32_t data_len,
587 const void *data) {
588 const DataBufferSP data_sp(new DataBufferHeap(kSyncPacketLen, 0));
589 DataEncoder encoder(data_sp, eByteOrderLittle, sizeof(void *));
590 auto offset = encoder.PutData(0, request_id, strlen(request_id));
591 encoder.PutU32(offset, data_len);
592
593 Error error;
594 ConnectionStatus status;
595 m_conn->Write(data_sp->GetBytes(), kSyncPacketLen, status, &error);
596 if (error.Fail())
597 return error;
598
599 if (data)
600 m_conn->Write(data, data_len, status, &error);
601 return error;
602}
603
604Error AdbClient::SyncService::ReadSyncHeader(std::string &response_id,
605 uint32_t &data_len) {
606 char buffer[kSyncPacketLen];
607
608 auto error = ReadAllBytes(buffer, kSyncPacketLen);
609 if (error.Success()) {
610 response_id.assign(&buffer[0], 4);
611 DataExtractor extractor(&buffer[4], 4, eByteOrderLittle, sizeof(void *));
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000612 offset_t offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 data_len = extractor.GetU32(&offset);
614 }
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000615
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 return error;
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000617}
618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619Error AdbClient::SyncService::PullFileChunk(std::vector<char> &buffer,
620 bool &eof) {
621 buffer.clear();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 std::string response_id;
624 uint32_t data_len;
625 auto error = ReadSyncHeader(response_id, data_len);
626 if (error.Fail())
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000627 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628
629 if (response_id == kDATA) {
630 buffer.resize(data_len, 0);
631 error = ReadAllBytes(&buffer[0], data_len);
632 if (error.Fail())
633 buffer.clear();
634 } else if (response_id == kDONE) {
635 eof = true;
636 } else if (response_id == kFAIL) {
637 std::string error_message(data_len, 0);
638 error = ReadAllBytes(&error_message[0], data_len);
639 if (error.Fail())
640 return Error("Failed to read pull error message: %s", error.AsCString());
641 return Error("Failed to pull file: %s", error_message.c_str());
642 } else
643 return Error("Pull failed with unknown response: %s", response_id.c_str());
644
Mehdi Aminic1edf562016-11-11 04:29:25 +0000645 return Error();
Oleksiy Vyalovd6a143f2016-07-06 17:02:42 +0000646}
647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648Error AdbClient::SyncService::ReadAllBytes(void *buffer, size_t size) {
649 return ::ReadAllBytes(*m_conn, buffer, size);
Oleksiy Vyalov6e181cf2016-06-30 18:10:27 +0000650}