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