1 //===-- PlatformAndroid.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/Core/Module.h"
10 #include "lldb/Core/PluginManager.h"
11 #include "lldb/Core/Section.h"
12 #include "lldb/Core/ValueObject.h"
13 #include "lldb/Host/HostInfo.h"
14 #include "lldb/Utility/Log.h"
15 #include "lldb/Utility/Scalar.h"
16 #include "lldb/Utility/UriParser.h"
17 
18 #include "AdbClient.h"
19 #include "PlatformAndroid.h"
20 #include "PlatformAndroidRemoteGDBServer.h"
21 #include "lldb/Target/Target.h"
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 using namespace lldb_private::platform_android;
26 using namespace std::chrono;
27 
28 LLDB_PLUGIN_DEFINE(PlatformAndroid)
29 
30 static uint32_t g_initialize_count = 0;
31 static const unsigned int g_android_default_cache_size =
32     2048; // Fits inside 4k adb packet.
33 
34 void PlatformAndroid::Initialize() {
35   PlatformLinux::Initialize();
36 
37   if (g_initialize_count++ == 0) {
38 #if defined(__ANDROID__)
39     PlatformSP default_platform_sp(new PlatformAndroid(true));
40     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
41     Platform::SetHostPlatform(default_platform_sp);
42 #endif
43     PluginManager::RegisterPlugin(
44         PlatformAndroid::GetPluginNameStatic(false),
45         PlatformAndroid::GetPluginDescriptionStatic(false),
46         PlatformAndroid::CreateInstance);
47   }
48 }
49 
50 void PlatformAndroid::Terminate() {
51   if (g_initialize_count > 0) {
52     if (--g_initialize_count == 0) {
53       PluginManager::UnregisterPlugin(PlatformAndroid::CreateInstance);
54     }
55   }
56 
57   PlatformLinux::Terminate();
58 }
59 
60 PlatformSP PlatformAndroid::CreateInstance(bool force, const ArchSpec *arch) {
61   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
62   if (log) {
63     const char *arch_name;
64     if (arch && arch->GetArchitectureName())
65       arch_name = arch->GetArchitectureName();
66     else
67       arch_name = "<null>";
68 
69     const char *triple_cstr =
70         arch ? arch->GetTriple().getTriple().c_str() : "<null>";
71 
72     LLDB_LOGF(log, "PlatformAndroid::%s(force=%s, arch={%s,%s})", __FUNCTION__,
73               force ? "true" : "false", arch_name, triple_cstr);
74   }
75 
76   bool create = force;
77   if (!create && arch && arch->IsValid()) {
78     const llvm::Triple &triple = arch->GetTriple();
79     switch (triple.getVendor()) {
80     case llvm::Triple::PC:
81       create = true;
82       break;
83 
84 #if defined(__ANDROID__)
85     // Only accept "unknown" for the vendor if the host is android and if
86     // "unknown" wasn't specified (it was just returned because it was NOT
87     // specified).
88     case llvm::Triple::VendorType::UnknownVendor:
89       create = !arch->TripleVendorWasSpecified();
90       break;
91 #endif
92     default:
93       break;
94     }
95 
96     if (create) {
97       switch (triple.getEnvironment()) {
98       case llvm::Triple::Android:
99         break;
100 
101 #if defined(__ANDROID__)
102       // Only accept "unknown" for the OS if the host is android and it
103       // "unknown" wasn't specified (it was just returned because it was NOT
104       // specified)
105       case llvm::Triple::EnvironmentType::UnknownEnvironment:
106         create = !arch->TripleEnvironmentWasSpecified();
107         break;
108 #endif
109       default:
110         create = false;
111         break;
112       }
113     }
114   }
115 
116   if (create) {
117     LLDB_LOGF(log, "PlatformAndroid::%s() creating remote-android platform",
118               __FUNCTION__);
119     return PlatformSP(new PlatformAndroid(false));
120   }
121 
122   LLDB_LOGF(
123       log, "PlatformAndroid::%s() aborting creation of remote-android platform",
124       __FUNCTION__);
125 
126   return PlatformSP();
127 }
128 
129 PlatformAndroid::PlatformAndroid(bool is_host)
130     : PlatformLinux(is_host), m_sdk_version(0) {}
131 
132 ConstString PlatformAndroid::GetPluginNameStatic(bool is_host) {
133   if (is_host) {
134     static ConstString g_host_name(Platform::GetHostPlatformName());
135     return g_host_name;
136   } else {
137     static ConstString g_remote_name("remote-android");
138     return g_remote_name;
139   }
140 }
141 
142 const char *PlatformAndroid::GetPluginDescriptionStatic(bool is_host) {
143   if (is_host)
144     return "Local Android user platform plug-in.";
145   else
146     return "Remote Android user platform plug-in.";
147 }
148 
149 ConstString PlatformAndroid::GetPluginName() {
150   return GetPluginNameStatic(IsHost());
151 }
152 
153 Status PlatformAndroid::ConnectRemote(Args &args) {
154   m_device_id.clear();
155 
156   if (IsHost()) {
157     return Status("can't connect to the host platform '%s', always connected",
158                   GetPluginName().GetCString());
159   }
160 
161   if (!m_remote_platform_sp)
162     m_remote_platform_sp = PlatformSP(new PlatformAndroidRemoteGDBServer());
163 
164   int port;
165   llvm::StringRef scheme, host, path;
166   const char *url = args.GetArgumentAtIndex(0);
167   if (!url)
168     return Status("URL is null.");
169   if (!UriParser::Parse(url, scheme, host, port, path))
170     return Status("Invalid URL: %s", url);
171   if (host != "localhost")
172     m_device_id = std::string(host);
173 
174   auto error = PlatformLinux::ConnectRemote(args);
175   if (error.Success()) {
176     AdbClient adb;
177     error = AdbClient::CreateByDeviceID(m_device_id, adb);
178     if (error.Fail())
179       return error;
180 
181     m_device_id = adb.GetDeviceID();
182   }
183   return error;
184 }
185 
186 Status PlatformAndroid::GetFile(const FileSpec &source,
187                                 const FileSpec &destination) {
188   if (IsHost() || !m_remote_platform_sp)
189     return PlatformLinux::GetFile(source, destination);
190 
191   FileSpec source_spec(source.GetPath(false), FileSpec::Style::posix);
192   if (source_spec.IsRelative())
193     source_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
194         source_spec.GetCString(false));
195 
196   Status error;
197   auto sync_service = GetSyncService(error);
198   if (error.Fail())
199     return error;
200 
201   uint32_t mode = 0, size = 0, mtime = 0;
202   error = sync_service->Stat(source_spec, mode, size, mtime);
203   if (error.Fail())
204     return error;
205 
206   if (mode != 0)
207     return sync_service->PullFile(source_spec, destination);
208 
209   auto source_file = source_spec.GetCString(false);
210 
211   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
212   LLDB_LOGF(log, "Got mode == 0 on '%s': try to get file via 'shell cat'",
213             source_file);
214 
215   if (strchr(source_file, '\'') != nullptr)
216     return Status("Doesn't support single-quotes in filenames");
217 
218   // mode == 0 can signify that adbd cannot access the file due security
219   // constraints - try "cat ..." as a fallback.
220   AdbClient adb(m_device_id);
221 
222   char cmd[PATH_MAX];
223   snprintf(cmd, sizeof(cmd), "cat '%s'", source_file);
224 
225   return adb.ShellToFile(cmd, minutes(1), destination);
226 }
227 
228 Status PlatformAndroid::PutFile(const FileSpec &source,
229                                 const FileSpec &destination, uint32_t uid,
230                                 uint32_t gid) {
231   if (IsHost() || !m_remote_platform_sp)
232     return PlatformLinux::PutFile(source, destination, uid, gid);
233 
234   FileSpec destination_spec(destination.GetPath(false), FileSpec::Style::posix);
235   if (destination_spec.IsRelative())
236     destination_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
237         destination_spec.GetCString(false));
238 
239   // TODO: Set correct uid and gid on remote file.
240   Status error;
241   auto sync_service = GetSyncService(error);
242   if (error.Fail())
243     return error;
244   return sync_service->PushFile(source, destination_spec);
245 }
246 
247 const char *PlatformAndroid::GetCacheHostname() { return m_device_id.c_str(); }
248 
249 Status PlatformAndroid::DownloadModuleSlice(const FileSpec &src_file_spec,
250                                             const uint64_t src_offset,
251                                             const uint64_t src_size,
252                                             const FileSpec &dst_file_spec) {
253   if (src_offset != 0)
254     return Status("Invalid offset - %" PRIu64, src_offset);
255 
256   return GetFile(src_file_spec, dst_file_spec);
257 }
258 
259 Status PlatformAndroid::DisconnectRemote() {
260   Status error = PlatformLinux::DisconnectRemote();
261   if (error.Success()) {
262     m_device_id.clear();
263     m_sdk_version = 0;
264   }
265   return error;
266 }
267 
268 uint32_t PlatformAndroid::GetDefaultMemoryCacheLineSize() {
269   return g_android_default_cache_size;
270 }
271 
272 uint32_t PlatformAndroid::GetSdkVersion() {
273   if (!IsConnected())
274     return 0;
275 
276   if (m_sdk_version != 0)
277     return m_sdk_version;
278 
279   std::string version_string;
280   AdbClient adb(m_device_id);
281   Status error =
282       adb.Shell("getprop ro.build.version.sdk", seconds(5), &version_string);
283   version_string = llvm::StringRef(version_string).trim().str();
284 
285   if (error.Fail() || version_string.empty()) {
286     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM);
287     LLDB_LOGF(log, "Get SDK version failed. (error: %s, output: %s)",
288               error.AsCString(), version_string.c_str());
289     return 0;
290   }
291 
292   // FIXME: improve error handling
293   llvm::to_integer(version_string, m_sdk_version);
294   return m_sdk_version;
295 }
296 
297 Status PlatformAndroid::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
298                                            const FileSpec &dst_file_spec) {
299   // For oat file we can try to fetch additional debug info from the device
300   ConstString extension = module_sp->GetFileSpec().GetFileNameExtension();
301   if (extension != ".oat" && extension != ".odex")
302     return Status(
303         "Symbol file downloading only supported for oat and odex files");
304 
305   // If we have no information about the platform file we can't execute oatdump
306   if (!module_sp->GetPlatformFileSpec())
307     return Status("No platform file specified");
308 
309   // Symbolizer isn't available before SDK version 23
310   if (GetSdkVersion() < 23)
311     return Status("Symbol file generation only supported on SDK 23+");
312 
313   // If we already have symtab then we don't have to try and generate one
314   if (module_sp->GetSectionList()->FindSectionByName(ConstString(".symtab")) !=
315       nullptr)
316     return Status("Symtab already available in the module");
317 
318   AdbClient adb(m_device_id);
319   std::string tmpdir;
320   Status error = adb.Shell("mktemp --directory --tmpdir /data/local/tmp",
321                            seconds(5), &tmpdir);
322   if (error.Fail() || tmpdir.empty())
323     return Status("Failed to generate temporary directory on the device (%s)",
324                   error.AsCString());
325   tmpdir = llvm::StringRef(tmpdir).trim().str();
326 
327   // Create file remover for the temporary directory created on the device
328   std::unique_ptr<std::string, std::function<void(std::string *)>>
329   tmpdir_remover(&tmpdir, [&adb](std::string *s) {
330     StreamString command;
331     command.Printf("rm -rf %s", s->c_str());
332     Status error = adb.Shell(command.GetData(), seconds(5), nullptr);
333 
334     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
335     if (log && error.Fail())
336       LLDB_LOGF(log, "Failed to remove temp directory: %s", error.AsCString());
337   });
338 
339   FileSpec symfile_platform_filespec(tmpdir);
340   symfile_platform_filespec.AppendPathComponent("symbolized.oat");
341 
342   // Execute oatdump on the remote device to generate a file with symtab
343   StreamString command;
344   command.Printf("oatdump --symbolize=%s --output=%s",
345                  module_sp->GetPlatformFileSpec().GetCString(false),
346                  symfile_platform_filespec.GetCString(false));
347   error = adb.Shell(command.GetData(), minutes(1), nullptr);
348   if (error.Fail())
349     return Status("Oatdump failed: %s", error.AsCString());
350 
351   // Download the symbolfile from the remote device
352   return GetFile(symfile_platform_filespec, dst_file_spec);
353 }
354 
355 bool PlatformAndroid::GetRemoteOSVersion() {
356   m_os_version = llvm::VersionTuple(GetSdkVersion());
357   return !m_os_version.empty();
358 }
359 
360 llvm::StringRef
361 PlatformAndroid::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
362   SymbolContextList matching_symbols;
363   std::vector<const char *> dl_open_names = { "__dl_dlopen", "dlopen" };
364   const char *dl_open_name = nullptr;
365   Target &target = process->GetTarget();
366   for (auto name: dl_open_names) {
367     target.GetImages().FindFunctionSymbols(
368         ConstString(name), eFunctionNameTypeFull, matching_symbols);
369     if (matching_symbols.GetSize()) {
370        dl_open_name = name;
371        break;
372     }
373   }
374   // Older platform versions have the dl function symbols mangled
375   if (dl_open_name == dl_open_names[0])
376     return R"(
377               extern "C" void* dlopen(const char*, int) asm("__dl_dlopen");
378               extern "C" void* dlsym(void*, const char*) asm("__dl_dlsym");
379               extern "C" int   dlclose(void*) asm("__dl_dlclose");
380               extern "C" char* dlerror(void) asm("__dl_dlerror");
381              )";
382 
383   return PlatformPOSIX::GetLibdlFunctionDeclarations(process);
384 }
385 
386 AdbClient::SyncService *PlatformAndroid::GetSyncService(Status &error) {
387   if (m_adb_sync_svc && m_adb_sync_svc->IsConnected())
388     return m_adb_sync_svc.get();
389 
390   AdbClient adb(m_device_id);
391   m_adb_sync_svc = adb.GetSyncService(error);
392   return (error.Success()) ? m_adb_sync_svc.get() : nullptr;
393 }
394