1 //===-- AdbClient.cpp -------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Other libraries and framework includes
11 #include "AdbClient.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Support/FileUtilities.h"
18 #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"
33 // On Windows, transitive dependencies pull in <Windows.h>, which defines a
34 // macro that clashes with a method name.
40 using namespace lldb_private;
41 using namespace lldb_private::platform_android;
45 const std::chrono::seconds kReadTimeout(8);
46 const char * kOKAY = "OKAY";
47 const char * kFAIL = "FAIL";
48 const char * kDATA = "DATA";
49 const char * kDONE = "DONE";
51 const char * kSEND = "SEND";
52 const char * kRECV = "RECV";
53 const char * kSTAT = "STAT";
55 const size_t kSyncPacketLen = 8;
56 // Maximum size of a filesync DATA packet.
57 const size_t kMaxPushData = 2*1024;
58 // Default mode for pushed files.
59 const uint32_t kDefaultMode = 0100770; // S_IFREG | S_IRWXU | S_IRWXG
61 const char * kSocketNamespaceAbstract = "localabstract";
62 const char * kSocketNamespaceFileSystem = "localfilesystem";
65 ReadAllBytes (Connection &conn, void *buffer, size_t size)
67 using namespace std::chrono;
70 ConnectionStatus status;
71 char *read_buffer = static_cast<char*>(buffer);
73 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)
78 uint32_t timeout_usec = duration_cast<microseconds>(deadline - now).count();
80 conn.Read(read_buffer + total_read_bytes, size - total_read_bytes, timeout_usec, status, &error);
83 total_read_bytes += read_bytes;
84 if (status != eConnectionStatusSuccess)
86 now = steady_clock::now();
88 if (total_read_bytes < size)
89 error = Error("Unable to read requested number of bytes. Connection status: %d.", status);
96 AdbClient::CreateByDeviceID(const std::string &device_id, AdbClient &adb)
98 DeviceIDList connect_devices;
99 auto error = adb.GetDevices(connect_devices);
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;
109 if (android_serial.empty())
111 if (connect_devices.size() != 1)
112 return Error("Expected a single connected device, got instead %zu - try setting 'ANDROID_SERIAL'",
113 connect_devices.size());
114 adb.SetDeviceID(connect_devices.front());
118 auto find_it = std::find(connect_devices.begin(), connect_devices.end(), android_serial);
119 if (find_it == connect_devices.end())
120 return Error("Device \"%s\" not found", android_serial.c_str());
122 adb.SetDeviceID(*find_it);
127 AdbClient::AdbClient () {}
129 AdbClient::AdbClient (const std::string &device_id)
130 : m_device_id (device_id)
134 AdbClient::~AdbClient() {}
137 AdbClient::SetDeviceID (const std::string &device_id)
139 m_device_id = device_id;
143 AdbClient::GetDeviceID() const
149 AdbClient::Connect ()
152 m_conn.reset (new ConnectionFileDescriptor);
153 m_conn->Connect ("connect://localhost:5037", &error);
159 AdbClient::GetDevices (DeviceIDList &device_list)
161 device_list.clear ();
163 auto error = SendMessage ("host:devices");
167 error = ReadResponseStatus ();
171 std::vector<char> in_buffer;
172 error = ReadMessage (in_buffer);
174 llvm::StringRef response (&in_buffer[0], in_buffer.size ());
175 llvm::SmallVector<llvm::StringRef, 4> devices;
176 response.split (devices, "\n", -1, false);
178 for (const auto device: devices)
179 device_list.push_back (device.split ('\t').first);
181 // Force disconnect since ADB closes connection after host:devices
188 AdbClient::SetPortForwarding (const uint16_t local_port, const uint16_t remote_port)
191 snprintf (message, sizeof (message), "forward:tcp:%d;tcp:%d", local_port, remote_port);
193 const auto error = SendDeviceMessage (message);
197 return ReadResponseStatus ();
201 AdbClient::SetPortForwarding (const uint16_t local_port,
202 const char* remote_socket_name,
203 const UnixSocketNamespace socket_namespace)
205 char message[PATH_MAX];
206 const char * sock_namespace_str = (socket_namespace == UnixSocketNamespaceAbstract) ?
207 kSocketNamespaceAbstract : kSocketNamespaceFileSystem;
208 snprintf (message, sizeof (message), "forward:tcp:%d;%s:%s",
213 const auto error = SendDeviceMessage (message);
217 return ReadResponseStatus ();
221 AdbClient::DeletePortForwarding (const uint16_t local_port)
224 snprintf (message, sizeof (message), "killforward:tcp:%d", local_port);
226 const auto error = SendDeviceMessage (message);
230 return ReadResponseStatus ();
234 AdbClient::SendMessage (const std::string &packet, const bool reconnect)
237 if (!m_conn || reconnect)
244 char length_buffer[5];
245 snprintf (length_buffer, sizeof (length_buffer), "%04x", static_cast<int>(packet.size ()));
247 ConnectionStatus status;
249 m_conn->Write (length_buffer, 4, status, &error);
253 m_conn->Write (packet.c_str (), packet.size (), status, &error);
258 AdbClient::SendDeviceMessage (const std::string &packet)
260 std::ostringstream msg;
261 msg << "host-serial:" << m_device_id << ":" << packet;
262 return SendMessage (msg.str ());
266 AdbClient::ReadMessage (std::vector<char> &message)
273 auto error = ReadAllBytes (buffer, 4);
277 unsigned int packet_len = 0;
278 sscanf (buffer, "%x", &packet_len);
280 message.resize (packet_len, 0);
281 error = ReadAllBytes (&message[0], packet_len);
289 AdbClient::ReadMessageStream (std::vector<char>& message, uint32_t timeout_ms)
291 auto start = std::chrono::steady_clock::now();
295 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
297 while (error.Success() && status == lldb::eConnectionStatusSuccess)
299 auto end = std::chrono::steady_clock::now();
300 uint32_t elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
301 if (elapsed_time >= timeout_ms)
302 return Error("Timed out");
304 size_t n = m_conn->Read(buffer, sizeof(buffer), 1000 * (timeout_ms - elapsed_time), status, &error);
306 message.insert(message.end(), &buffer[0], &buffer[n]);
312 AdbClient::ReadResponseStatus()
316 static const size_t packet_len = 4;
317 response_id[packet_len] = 0;
319 auto error = ReadAllBytes (response_id, packet_len);
323 if (strncmp (response_id, kOKAY, packet_len) != 0)
324 return GetResponseError (response_id);
330 AdbClient::GetResponseError (const char *response_id)
332 if (strcmp (response_id, kFAIL) != 0)
333 return Error ("Got unexpected response id from adb: \"%s\"", response_id);
335 std::vector<char> error_message;
336 auto error = ReadMessage (error_message);
337 if (error.Success ())
338 error.SetErrorString (std::string (&error_message[0], error_message.size ()).c_str ());
344 AdbClient::SwitchDeviceTransport ()
346 std::ostringstream msg;
347 msg << "host:transport:" << m_device_id;
349 auto error = SendMessage (msg.str ());
353 return ReadResponseStatus ();
357 AdbClient::StartSync ()
359 auto error = SwitchDeviceTransport ();
361 return Error ("Failed to switch to device transport: %s", error.AsCString ());
365 return Error ("Sync failed: %s", error.AsCString ());
373 auto error = SendMessage ("sync:", false);
377 return ReadResponseStatus ();
381 AdbClient::ReadAllBytes (void *buffer, size_t size)
383 return ::ReadAllBytes (*m_conn, buffer, size);
387 AdbClient::internalShell(const char *command, uint32_t timeout_ms, std::vector<char> &output_buf)
391 auto error = SwitchDeviceTransport();
393 return Error("Failed to switch to device transport: %s", error.AsCString());
395 StreamString adb_command;
396 adb_command.Printf("shell:%s", command);
397 error = SendMessage(adb_command.GetData(), false);
401 error = ReadResponseStatus();
405 error = ReadMessageStream(output_buf, timeout_ms);
409 // ADB doesn't propagate return code of shell execution - if
410 // output starts with /system/bin/sh: most likely command failed.
411 static const char *kShellPrefix = "/system/bin/sh:";
412 if (output_buf.size() > strlen(kShellPrefix))
414 if (!memcmp(&output_buf[0], kShellPrefix, strlen(kShellPrefix)))
415 return Error("Shell command %s failed: %s", command,
416 std::string(output_buf.begin(), output_buf.end()).c_str());
423 AdbClient::Shell(const char *command, uint32_t timeout_ms, std::string *output)
425 std::vector<char> output_buffer;
426 auto error = internalShell(command, timeout_ms, output_buffer);
431 output->assign(output_buffer.begin(), output_buffer.end());
436 AdbClient::ShellToFile(const char *command, uint32_t timeout_ms, const FileSpec &output_file_spec)
438 std::vector<char> output_buffer;
439 auto error = internalShell(command, timeout_ms, output_buffer);
443 const auto output_filename = output_file_spec.GetPath();
444 std::ofstream dst(output_filename, std::ios::out | std::ios::binary);
446 return Error("Unable to open local file %s", output_filename.c_str());
448 dst.write(&output_buffer[0], output_buffer.size());
451 return Error("Failed to write file %s", output_filename.c_str());
455 std::unique_ptr<AdbClient::SyncService>
456 AdbClient::GetSyncService (Error &error)
458 std::unique_ptr<SyncService> sync_service;
459 error = StartSync ();
460 if (error.Success ())
461 sync_service.reset (new SyncService(std::move(m_conn)));
467 AdbClient::SyncService::internalPullFile (const FileSpec &remote_file, const FileSpec &local_file)
469 const auto local_file_path = local_file.GetPath ();
470 llvm::FileRemover local_file_remover (local_file_path.c_str ());
472 std::ofstream dst (local_file_path, std::ios::out | std::ios::binary);
474 return Error ("Unable to open local file %s", local_file_path.c_str());
476 const auto remote_file_path = remote_file.GetPath (false);
477 auto error = SendSyncRequest (kRECV, remote_file_path.length (), remote_file_path.c_str ());
481 std::vector<char> chunk;
485 error = PullFileChunk (chunk, eof);
489 dst.write (&chunk[0], chunk.size ());
492 local_file_remover.releaseFile ();
497 AdbClient::SyncService::internalPushFile (const FileSpec &local_file, const FileSpec &remote_file)
499 const auto local_file_path (local_file.GetPath ());
500 std::ifstream src (local_file_path.c_str(), std::ios::in | std::ios::binary);
502 return Error ("Unable to open local file %s", local_file_path.c_str());
504 std::stringstream file_description;
505 file_description << remote_file.GetPath(false).c_str() << "," << kDefaultMode;
506 std::string file_description_str = file_description.str();
507 auto error = SendSyncRequest (kSEND, file_description_str.length(), file_description_str.c_str());
511 char chunk[kMaxPushData];
512 while (!src.eof() && !src.read(chunk, kMaxPushData).bad())
514 size_t chunk_size = src.gcount();
515 error = SendSyncRequest(kDATA, chunk_size, chunk);
517 return Error ("Failed to send file chunk: %s", error.AsCString ());
519 error = SendSyncRequest(kDONE, local_file.GetModificationTime().seconds(), nullptr);
523 std::string response_id;
525 error = ReadSyncHeader (response_id, data_len);
527 return Error ("Failed to read DONE response: %s", error.AsCString ());
528 if (response_id == kFAIL)
530 std::string error_message (data_len, 0);
531 error = ReadAllBytes (&error_message[0], data_len);
533 return Error ("Failed to read DONE error message: %s", error.AsCString ());
534 return Error ("Failed to push file: %s", error_message.c_str ());
536 else if (response_id != kOKAY)
537 return Error ("Got unexpected DONE response: %s", response_id.c_str ());
539 // If there was an error reading the source file, finish the adb file
540 // transfer first so that adb isn't expecting any more data.
542 return Error ("Failed read on %s", local_file_path.c_str());
547 AdbClient::SyncService::internalStat (const FileSpec &remote_file, uint32_t &mode, uint32_t &size, uint32_t &mtime)
549 const std::string remote_file_path (remote_file.GetPath (false));
550 auto error = SendSyncRequest (kSTAT, remote_file_path.length (), remote_file_path.c_str ());
552 return Error ("Failed to send request: %s", error.AsCString ());
554 static const size_t stat_len = strlen (kSTAT);
555 static const size_t response_len = stat_len + (sizeof (uint32_t) * 3);
557 std::vector<char> buffer (response_len);
558 error = ReadAllBytes (&buffer[0], buffer.size ());
560 return Error ("Failed to read response: %s", error.AsCString ());
562 DataExtractor extractor (&buffer[0], buffer.size (), eByteOrderLittle, sizeof (void*));
565 const void* command = extractor.GetData (&offset, stat_len);
567 return Error ("Failed to get response command");
568 const char* command_str = static_cast<const char*> (command);
569 if (strncmp (command_str, kSTAT, stat_len))
570 return Error ("Got invalid stat command: %s", command_str);
572 mode = extractor.GetU32 (&offset);
573 size = extractor.GetU32 (&offset);
574 mtime = extractor.GetU32 (&offset);
579 AdbClient::SyncService::PullFile (const FileSpec &remote_file, const FileSpec &local_file)
581 return executeCommand ([this, &remote_file, &local_file]() {
582 return internalPullFile (remote_file, local_file);
587 AdbClient::SyncService::PushFile (const FileSpec &local_file, const FileSpec &remote_file)
589 return executeCommand ([this, &local_file, &remote_file]() {
590 return internalPushFile (local_file, remote_file);
595 AdbClient::SyncService::Stat (const FileSpec &remote_file, uint32_t &mode, uint32_t &size, uint32_t &mtime)
597 return executeCommand ([this, &remote_file, &mode, &size, &mtime]() {
598 return internalStat (remote_file, mode, size, mtime);
603 AdbClient::SyncService::IsConnected () const
605 return m_conn && m_conn->IsConnected ();
608 AdbClient::SyncService::SyncService(std::unique_ptr<Connection> &&conn):
609 m_conn(std::move(conn))
614 AdbClient::SyncService::executeCommand (const std::function<Error()> &cmd)
617 return Error ("SyncService is disconnected");
619 const auto error = cmd ();
626 AdbClient::SyncService::~SyncService () {}
629 AdbClient::SyncService::SendSyncRequest (const char *request_id, const uint32_t data_len, const void *data)
631 const DataBufferSP data_sp (new DataBufferHeap (kSyncPacketLen, 0));
632 DataEncoder encoder (data_sp, eByteOrderLittle, sizeof (void*));
633 auto offset = encoder.PutData (0, request_id, strlen(request_id));
634 encoder.PutU32 (offset, data_len);
637 ConnectionStatus status;
638 m_conn->Write (data_sp->GetBytes (), kSyncPacketLen, status, &error);
643 m_conn->Write (data, data_len, status, &error);
648 AdbClient::SyncService::ReadSyncHeader (std::string &response_id, uint32_t &data_len)
650 char buffer[kSyncPacketLen];
652 auto error = ReadAllBytes (buffer, kSyncPacketLen);
653 if (error.Success ())
655 response_id.assign (&buffer[0], 4);
656 DataExtractor extractor (&buffer[4], 4, eByteOrderLittle, sizeof (void*));
658 data_len = extractor.GetU32 (&offset);
665 AdbClient::SyncService::PullFileChunk (std::vector<char> &buffer, bool &eof)
669 std::string response_id;
671 auto error = ReadSyncHeader (response_id, data_len);
675 if (response_id == kDATA)
677 buffer.resize (data_len, 0);
678 error = ReadAllBytes (&buffer[0], data_len);
682 else if (response_id == kDONE)
686 else if (response_id == kFAIL)
688 std::string error_message (data_len, 0);
689 error = ReadAllBytes (&error_message[0], data_len);
691 return Error ("Failed to read pull error message: %s", error.AsCString ());
692 return Error ("Failed to pull file: %s", error_message.c_str ());
695 return Error ("Pull failed with unknown response: %s", response_id.c_str ());
701 AdbClient::SyncService::ReadAllBytes (void *buffer, size_t size)
703 return ::ReadAllBytes (*m_conn, buffer, size);