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