1 //===-- PlatformAndroidRemoteGDBServer.cpp --------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/ConnectionFileDescriptor.h"
10 #include "lldb/Host/common/TCPSocket.h"
11 #include "lldb/Utility/Log.h"
12 #include "lldb/Utility/Status.h"
13 #include "lldb/Utility/UriParser.h"
14 
15 #include "PlatformAndroidRemoteGDBServer.h"
16 
17 #include <sstream>
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 using namespace platform_android;
22 
23 static const lldb::pid_t g_remote_platform_pid =
24     0; // Alias for the process id of lldb-platform
25 
26 static Status ForwardPortWithAdb(
27     const uint16_t local_port, const uint16_t remote_port,
28     llvm::StringRef remote_socket_name,
29     const llvm::Optional<AdbClient::UnixSocketNamespace> &socket_namespace,
30     std::string &device_id) {
31   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
32 
33   AdbClient adb;
34   auto error = AdbClient::CreateByDeviceID(device_id, adb);
35   if (error.Fail())
36     return error;
37 
38   device_id = adb.GetDeviceID();
39   LLDB_LOGF(log, "Connected to Android device \"%s\"", device_id.c_str());
40 
41   if (remote_port != 0) {
42     LLDB_LOGF(log, "Forwarding remote TCP port %d to local TCP port %d",
43               remote_port, local_port);
44     return adb.SetPortForwarding(local_port, remote_port);
45   }
46 
47   LLDB_LOGF(log, "Forwarding remote socket \"%s\" to local TCP port %d",
48             remote_socket_name.str().c_str(), local_port);
49 
50   if (!socket_namespace)
51     return Status("Invalid socket namespace");
52 
53   return adb.SetPortForwarding(local_port, remote_socket_name,
54                                *socket_namespace);
55 }
56 
57 static Status DeleteForwardPortWithAdb(uint16_t local_port,
58                                        const std::string &device_id) {
59   AdbClient adb(device_id);
60   return adb.DeletePortForwarding(local_port);
61 }
62 
63 static Status FindUnusedPort(uint16_t &port) {
64   Status error;
65   std::unique_ptr<TCPSocket> tcp_socket(new TCPSocket(true, false));
66   if (error.Fail())
67     return error;
68 
69   error = tcp_socket->Listen("127.0.0.1:0", 1);
70   if (error.Success())
71     port = tcp_socket->GetLocalPortNumber();
72 
73   return error;
74 }
75 
76 PlatformAndroidRemoteGDBServer::PlatformAndroidRemoteGDBServer() = default;
77 
78 PlatformAndroidRemoteGDBServer::~PlatformAndroidRemoteGDBServer() {
79   for (const auto &it : m_port_forwards)
80     DeleteForwardPortWithAdb(it.second, m_device_id);
81 }
82 
83 bool PlatformAndroidRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
84                                                      std::string &connect_url) {
85   uint16_t remote_port = 0;
86   std::string socket_name;
87   if (!m_gdb_client.LaunchGDBServer("127.0.0.1", pid, remote_port, socket_name))
88     return false;
89 
90   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
91 
92   auto error =
93       MakeConnectURL(pid, remote_port, socket_name.c_str(), connect_url);
94   if (error.Success() && log)
95     LLDB_LOGF(log, "gdbserver connect URL: %s", connect_url.c_str());
96 
97   return error.Success();
98 }
99 
100 bool PlatformAndroidRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
101   DeleteForwardPort(pid);
102   return m_gdb_client.KillSpawnedProcess(pid);
103 }
104 
105 Status PlatformAndroidRemoteGDBServer::ConnectRemote(Args &args) {
106   m_device_id.clear();
107 
108   if (args.GetArgumentCount() != 1)
109     return Status(
110         "\"platform connect\" takes a single argument: <connect-url>");
111 
112   const char *url = args.GetArgumentAtIndex(0);
113   if (!url)
114     return Status("URL is null.");
115   llvm::Optional<URI> parsed_url = URI::Parse(url);
116   if (!parsed_url)
117     return Status("Invalid URL: %s", url);
118   if (parsed_url->hostname != "localhost")
119     m_device_id = parsed_url->hostname.str();
120 
121   m_socket_namespace.reset();
122   if (parsed_url->scheme == "unix-connect")
123     m_socket_namespace = AdbClient::UnixSocketNamespaceFileSystem;
124   else if (parsed_url->scheme == "unix-abstract-connect")
125     m_socket_namespace = AdbClient::UnixSocketNamespaceAbstract;
126 
127   std::string connect_url;
128   auto error =
129       MakeConnectURL(g_remote_platform_pid, parsed_url->port.getValueOr(0),
130                      parsed_url->path, connect_url);
131 
132   if (error.Fail())
133     return error;
134 
135   args.ReplaceArgumentAtIndex(0, connect_url);
136 
137   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
138   LLDB_LOGF(log, "Rewritten platform connect URL: %s", connect_url.c_str());
139 
140   error = PlatformRemoteGDBServer::ConnectRemote(args);
141   if (error.Fail())
142     DeleteForwardPort(g_remote_platform_pid);
143 
144   return error;
145 }
146 
147 Status PlatformAndroidRemoteGDBServer::DisconnectRemote() {
148   DeleteForwardPort(g_remote_platform_pid);
149   return PlatformRemoteGDBServer::DisconnectRemote();
150 }
151 
152 void PlatformAndroidRemoteGDBServer::DeleteForwardPort(lldb::pid_t pid) {
153   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
154 
155   auto it = m_port_forwards.find(pid);
156   if (it == m_port_forwards.end())
157     return;
158 
159   const auto port = it->second;
160   const auto error = DeleteForwardPortWithAdb(port, m_device_id);
161   if (error.Fail()) {
162     LLDB_LOGF(log,
163               "Failed to delete port forwarding (pid=%" PRIu64
164               ", port=%d, device=%s): %s",
165               pid, port, m_device_id.c_str(), error.AsCString());
166   }
167   m_port_forwards.erase(it);
168 }
169 
170 Status PlatformAndroidRemoteGDBServer::MakeConnectURL(
171     const lldb::pid_t pid, const uint16_t remote_port,
172     llvm::StringRef remote_socket_name, std::string &connect_url) {
173   static const int kAttempsNum = 5;
174 
175   Status error;
176   // There is a race possibility that somebody will occupy a port while we're
177   // in between FindUnusedPort and ForwardPortWithAdb - adding the loop to
178   // mitigate such problem.
179   for (auto i = 0; i < kAttempsNum; ++i) {
180     uint16_t local_port = 0;
181     error = FindUnusedPort(local_port);
182     if (error.Fail())
183       return error;
184 
185     error = ForwardPortWithAdb(local_port, remote_port, remote_socket_name,
186                                m_socket_namespace, m_device_id);
187     if (error.Success()) {
188       m_port_forwards[pid] = local_port;
189       std::ostringstream url_str;
190       url_str << "connect://127.0.0.1:" << local_port;
191       connect_url = url_str.str();
192       break;
193     }
194   }
195 
196   return error;
197 }
198 
199 lldb::ProcessSP PlatformAndroidRemoteGDBServer::ConnectProcess(
200     llvm::StringRef connect_url, llvm::StringRef plugin_name,
201     lldb_private::Debugger &debugger, lldb_private::Target *target,
202     lldb_private::Status &error) {
203   // We don't have the pid of the remote gdbserver when it isn't started by us
204   // but we still want to store the list of port forwards we set up in our port
205   // forward map. Generate a fake pid for these cases what won't collide with
206   // any other valid pid on android.
207   static lldb::pid_t s_remote_gdbserver_fake_pid = 0xffffffffffffffffULL;
208 
209   llvm::Optional<URI> parsed_url = URI::Parse(connect_url);
210   if (!parsed_url) {
211     error.SetErrorStringWithFormat("Invalid URL: %s",
212                                    connect_url.str().c_str());
213     return nullptr;
214   }
215 
216   std::string new_connect_url;
217   error = MakeConnectURL(s_remote_gdbserver_fake_pid--,
218                          parsed_url->port.getValueOr(0), parsed_url->path,
219                          new_connect_url);
220   if (error.Fail())
221     return nullptr;
222 
223   return PlatformRemoteGDBServer::ConnectProcess(new_connect_url, plugin_name,
224                                                  debugger, target, error);
225 }
226