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 Status PlatformAndroid::ConnectRemote(Args &args) {
150   m_device_id.clear();
151 
152   if (IsHost())
153     return Status("can't connect to the host platform, always connected");
154 
155   if (!m_remote_platform_sp)
156     m_remote_platform_sp = PlatformSP(new PlatformAndroidRemoteGDBServer());
157 
158   const char *url = args.GetArgumentAtIndex(0);
159   if (!url)
160     return Status("URL is null.");
161   llvm::Optional<URI> parsed_url = URI::Parse(url);
162   if (!parsed_url)
163     return Status("Invalid URL: %s", url);
164   if (parsed_url->hostname != "localhost")
165     m_device_id = parsed_url->hostname.str();
166 
167   auto error = PlatformLinux::ConnectRemote(args);
168   if (error.Success()) {
169     AdbClient adb;
170     error = AdbClient::CreateByDeviceID(m_device_id, adb);
171     if (error.Fail())
172       return error;
173 
174     m_device_id = adb.GetDeviceID();
175   }
176   return error;
177 }
178 
179 Status PlatformAndroid::GetFile(const FileSpec &source,
180                                 const FileSpec &destination) {
181   if (IsHost() || !m_remote_platform_sp)
182     return PlatformLinux::GetFile(source, destination);
183 
184   FileSpec source_spec(source.GetPath(false), FileSpec::Style::posix);
185   if (source_spec.IsRelative())
186     source_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
187         source_spec.GetCString(false));
188 
189   Status error;
190   auto sync_service = GetSyncService(error);
191   if (error.Fail())
192     return error;
193 
194   uint32_t mode = 0, size = 0, mtime = 0;
195   error = sync_service->Stat(source_spec, mode, size, mtime);
196   if (error.Fail())
197     return error;
198 
199   if (mode != 0)
200     return sync_service->PullFile(source_spec, destination);
201 
202   auto source_file = source_spec.GetCString(false);
203 
204   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
205   LLDB_LOGF(log, "Got mode == 0 on '%s': try to get file via 'shell cat'",
206             source_file);
207 
208   if (strchr(source_file, '\'') != nullptr)
209     return Status("Doesn't support single-quotes in filenames");
210 
211   // mode == 0 can signify that adbd cannot access the file due security
212   // constraints - try "cat ..." as a fallback.
213   AdbClient adb(m_device_id);
214 
215   char cmd[PATH_MAX];
216   snprintf(cmd, sizeof(cmd), "cat '%s'", source_file);
217 
218   return adb.ShellToFile(cmd, minutes(1), destination);
219 }
220 
221 Status PlatformAndroid::PutFile(const FileSpec &source,
222                                 const FileSpec &destination, uint32_t uid,
223                                 uint32_t gid) {
224   if (IsHost() || !m_remote_platform_sp)
225     return PlatformLinux::PutFile(source, destination, uid, gid);
226 
227   FileSpec destination_spec(destination.GetPath(false), FileSpec::Style::posix);
228   if (destination_spec.IsRelative())
229     destination_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
230         destination_spec.GetCString(false));
231 
232   // TODO: Set correct uid and gid on remote file.
233   Status error;
234   auto sync_service = GetSyncService(error);
235   if (error.Fail())
236     return error;
237   return sync_service->PushFile(source, destination_spec);
238 }
239 
240 const char *PlatformAndroid::GetCacheHostname() { return m_device_id.c_str(); }
241 
242 Status PlatformAndroid::DownloadModuleSlice(const FileSpec &src_file_spec,
243                                             const uint64_t src_offset,
244                                             const uint64_t src_size,
245                                             const FileSpec &dst_file_spec) {
246   if (src_offset != 0)
247     return Status("Invalid offset - %" PRIu64, src_offset);
248 
249   return GetFile(src_file_spec, dst_file_spec);
250 }
251 
252 Status PlatformAndroid::DisconnectRemote() {
253   Status error = PlatformLinux::DisconnectRemote();
254   if (error.Success()) {
255     m_device_id.clear();
256     m_sdk_version = 0;
257   }
258   return error;
259 }
260 
261 uint32_t PlatformAndroid::GetDefaultMemoryCacheLineSize() {
262   return g_android_default_cache_size;
263 }
264 
265 uint32_t PlatformAndroid::GetSdkVersion() {
266   if (!IsConnected())
267     return 0;
268 
269   if (m_sdk_version != 0)
270     return m_sdk_version;
271 
272   std::string version_string;
273   AdbClient adb(m_device_id);
274   Status error =
275       adb.Shell("getprop ro.build.version.sdk", seconds(5), &version_string);
276   version_string = llvm::StringRef(version_string).trim().str();
277 
278   if (error.Fail() || version_string.empty()) {
279     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM);
280     LLDB_LOGF(log, "Get SDK version failed. (error: %s, output: %s)",
281               error.AsCString(), version_string.c_str());
282     return 0;
283   }
284 
285   // FIXME: improve error handling
286   llvm::to_integer(version_string, m_sdk_version);
287   return m_sdk_version;
288 }
289 
290 Status PlatformAndroid::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
291                                            const FileSpec &dst_file_spec) {
292   // For oat file we can try to fetch additional debug info from the device
293   ConstString extension = module_sp->GetFileSpec().GetFileNameExtension();
294   if (extension != ".oat" && extension != ".odex")
295     return Status(
296         "Symbol file downloading only supported for oat and odex files");
297 
298   // If we have no information about the platform file we can't execute oatdump
299   if (!module_sp->GetPlatformFileSpec())
300     return Status("No platform file specified");
301 
302   // Symbolizer isn't available before SDK version 23
303   if (GetSdkVersion() < 23)
304     return Status("Symbol file generation only supported on SDK 23+");
305 
306   // If we already have symtab then we don't have to try and generate one
307   if (module_sp->GetSectionList()->FindSectionByName(ConstString(".symtab")) !=
308       nullptr)
309     return Status("Symtab already available in the module");
310 
311   AdbClient adb(m_device_id);
312   std::string tmpdir;
313   Status error = adb.Shell("mktemp --directory --tmpdir /data/local/tmp",
314                            seconds(5), &tmpdir);
315   if (error.Fail() || tmpdir.empty())
316     return Status("Failed to generate temporary directory on the device (%s)",
317                   error.AsCString());
318   tmpdir = llvm::StringRef(tmpdir).trim().str();
319 
320   // Create file remover for the temporary directory created on the device
321   std::unique_ptr<std::string, std::function<void(std::string *)>>
322   tmpdir_remover(&tmpdir, [&adb](std::string *s) {
323     StreamString command;
324     command.Printf("rm -rf %s", s->c_str());
325     Status error = adb.Shell(command.GetData(), seconds(5), nullptr);
326 
327     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
328     if (log && error.Fail())
329       LLDB_LOGF(log, "Failed to remove temp directory: %s", error.AsCString());
330   });
331 
332   FileSpec symfile_platform_filespec(tmpdir);
333   symfile_platform_filespec.AppendPathComponent("symbolized.oat");
334 
335   // Execute oatdump on the remote device to generate a file with symtab
336   StreamString command;
337   command.Printf("oatdump --symbolize=%s --output=%s",
338                  module_sp->GetPlatformFileSpec().GetCString(false),
339                  symfile_platform_filespec.GetCString(false));
340   error = adb.Shell(command.GetData(), minutes(1), nullptr);
341   if (error.Fail())
342     return Status("Oatdump failed: %s", error.AsCString());
343 
344   // Download the symbolfile from the remote device
345   return GetFile(symfile_platform_filespec, dst_file_spec);
346 }
347 
348 bool PlatformAndroid::GetRemoteOSVersion() {
349   m_os_version = llvm::VersionTuple(GetSdkVersion());
350   return !m_os_version.empty();
351 }
352 
353 llvm::StringRef
354 PlatformAndroid::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
355   SymbolContextList matching_symbols;
356   std::vector<const char *> dl_open_names = { "__dl_dlopen", "dlopen" };
357   const char *dl_open_name = nullptr;
358   Target &target = process->GetTarget();
359   for (auto name: dl_open_names) {
360     target.GetImages().FindFunctionSymbols(
361         ConstString(name), eFunctionNameTypeFull, matching_symbols);
362     if (matching_symbols.GetSize()) {
363        dl_open_name = name;
364        break;
365     }
366   }
367   // Older platform versions have the dl function symbols mangled
368   if (dl_open_name == dl_open_names[0])
369     return R"(
370               extern "C" void* dlopen(const char*, int) asm("__dl_dlopen");
371               extern "C" void* dlsym(void*, const char*) asm("__dl_dlsym");
372               extern "C" int   dlclose(void*) asm("__dl_dlclose");
373               extern "C" char* dlerror(void) asm("__dl_dlerror");
374              )";
375 
376   return PlatformPOSIX::GetLibdlFunctionDeclarations(process);
377 }
378 
379 AdbClient::SyncService *PlatformAndroid::GetSyncService(Status &error) {
380   if (m_adb_sync_svc && m_adb_sync_svc->IsConnected())
381     return m_adb_sync_svc.get();
382 
383   AdbClient adb(m_device_id);
384   m_adb_sync_svc = adb.GetSyncService(error);
385   return (error.Success()) ? m_adb_sync_svc.get() : nullptr;
386 }
387