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/Scalar.h"
13 #include "lldb/Core/Section.h"
14 #include "lldb/Core/ValueObject.h"
15 #include "lldb/Host/HostInfo.h"
16 #include "lldb/Host/StringConvert.h"
17 #include "lldb/Utility/Log.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
87     // it "unknown" wasn't specified (it was just returned because it
88     // was NOT 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.getOS()) {
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
104       // it "unknown" wasn't specified (it was just returned because it
105       // was NOT specified)
106       case llvm::Triple::OSType::UnknownOS:
107         create = !arch->TripleOSWasSpecified();
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), false,
197                        FileSpec::ePathSyntaxPosix);
198   if (source_spec.IsRelative())
199     source_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
200         source_spec.GetCString(false));
201 
202   Status error;
203   auto sync_service = GetSyncService(error);
204   if (error.Fail())
205     return error;
206 
207   uint32_t mode = 0, size = 0, mtime = 0;
208   error = sync_service->Stat(source_spec, mode, size, mtime);
209   if (error.Fail())
210     return error;
211 
212   if (mode != 0)
213     return sync_service->PullFile(source_spec, destination);
214 
215   auto source_file = source_spec.GetCString(false);
216 
217   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
218   if (log)
219     log->Printf("Got mode == 0 on '%s': try to get file via 'shell cat'",
220                 source_file);
221 
222   if (strchr(source_file, '\'') != nullptr)
223     return Status("Doesn't support single-quotes in filenames");
224 
225   // mode == 0 can signify that adbd cannot access the file
226   // due security constraints - try "cat ..." as a fallback.
227   AdbClient adb(m_device_id);
228 
229   char cmd[PATH_MAX];
230   snprintf(cmd, sizeof(cmd), "cat '%s'", source_file);
231 
232   return adb.ShellToFile(cmd, minutes(1), destination);
233 }
234 
235 Status PlatformAndroid::PutFile(const FileSpec &source,
236                                 const FileSpec &destination, uint32_t uid,
237                                 uint32_t gid) {
238   if (IsHost() || !m_remote_platform_sp)
239     return PlatformLinux::PutFile(source, destination, uid, gid);
240 
241   FileSpec destination_spec(destination.GetPath(false), false,
242                             FileSpec::ePathSyntaxPosix);
243   if (destination_spec.IsRelative())
244     destination_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent(
245         destination_spec.GetCString(false));
246 
247   // TODO: Set correct uid and gid on remote file.
248   Status error;
249   auto sync_service = GetSyncService(error);
250   if (error.Fail())
251     return error;
252   return sync_service->PushFile(source, destination_spec);
253 }
254 
255 const char *PlatformAndroid::GetCacheHostname() { return m_device_id.c_str(); }
256 
257 Status PlatformAndroid::DownloadModuleSlice(const FileSpec &src_file_spec,
258                                             const uint64_t src_offset,
259                                             const uint64_t src_size,
260                                             const FileSpec &dst_file_spec) {
261   if (src_offset != 0)
262     return Status("Invalid offset - %" PRIu64, src_offset);
263 
264   return GetFile(src_file_spec, dst_file_spec);
265 }
266 
267 Status PlatformAndroid::DisconnectRemote() {
268   Status error = PlatformLinux::DisconnectRemote();
269   if (error.Success()) {
270     m_device_id.clear();
271     m_sdk_version = 0;
272   }
273   return error;
274 }
275 
276 uint32_t PlatformAndroid::GetDefaultMemoryCacheLineSize() {
277   return g_android_default_cache_size;
278 }
279 
280 uint32_t PlatformAndroid::GetSdkVersion() {
281   if (!IsConnected())
282     return 0;
283 
284   if (m_sdk_version != 0)
285     return m_sdk_version;
286 
287   std::string version_string;
288   AdbClient adb(m_device_id);
289   Status error =
290       adb.Shell("getprop ro.build.version.sdk", seconds(5), &version_string);
291   version_string = llvm::StringRef(version_string).trim().str();
292 
293   if (error.Fail() || version_string.empty()) {
294     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM);
295     if (log)
296       log->Printf("Get SDK version failed. (error: %s, output: %s)",
297                   error.AsCString(), version_string.c_str());
298     return 0;
299   }
300 
301   m_sdk_version = StringConvert::ToUInt32(version_string.c_str());
302   return m_sdk_version;
303 }
304 
305 Status PlatformAndroid::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
306                                            const FileSpec &dst_file_spec) {
307   // For oat file we can try to fetch additional debug info from the device
308   ConstString extension = module_sp->GetFileSpec().GetFileNameExtension();
309   if (extension != ConstString("oat") && extension != ConstString("odex"))
310     return Status(
311         "Symbol file downloading only supported for oat and odex files");
312 
313   // If we have no information about the platform file we can't execute oatdump
314   if (!module_sp->GetPlatformFileSpec())
315     return Status("No platform file specified");
316 
317   // Symbolizer isn't available before SDK version 23
318   if (GetSdkVersion() < 23)
319     return Status("Symbol file generation only supported on SDK 23+");
320 
321   // If we already have symtab then we don't have to try and generate one
322   if (module_sp->GetSectionList()->FindSectionByName(ConstString(".symtab")) !=
323       nullptr)
324     return Status("Symtab already available in the module");
325 
326   AdbClient adb(m_device_id);
327   std::string tmpdir;
328   Status error = adb.Shell("mktemp --directory --tmpdir /data/local/tmp",
329                            seconds(5), &tmpdir);
330   if (error.Fail() || tmpdir.empty())
331     return Status("Failed to generate temporary directory on the device (%s)",
332                   error.AsCString());
333   tmpdir = llvm::StringRef(tmpdir).trim().str();
334 
335   // Create file remover for the temporary directory created on the device
336   std::unique_ptr<std::string, std::function<void(std::string *)>>
337   tmpdir_remover(&tmpdir, [&adb](std::string *s) {
338     StreamString command;
339     command.Printf("rm -rf %s", s->c_str());
340     Status error = adb.Shell(command.GetData(), seconds(5), nullptr);
341 
342     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
343     if (log && error.Fail())
344       log->Printf("Failed to remove temp directory: %s", error.AsCString());
345   });
346 
347   FileSpec symfile_platform_filespec(tmpdir, false);
348   symfile_platform_filespec.AppendPathComponent("symbolized.oat");
349 
350   // Execute oatdump on the remote device to generate a file with symtab
351   StreamString command;
352   command.Printf("oatdump --symbolize=%s --output=%s",
353                  module_sp->GetPlatformFileSpec().GetCString(false),
354                  symfile_platform_filespec.GetCString(false));
355   error = adb.Shell(command.GetData(), minutes(1), nullptr);
356   if (error.Fail())
357     return Status("Oatdump failed: %s", error.AsCString());
358 
359   // Download the symbolfile from the remote device
360   return GetFile(symfile_platform_filespec, dst_file_spec);
361 }
362 
363 bool PlatformAndroid::GetRemoteOSVersion() {
364   m_major_os_version = GetSdkVersion();
365   m_minor_os_version = 0;
366   m_update_os_version = 0;
367   return m_major_os_version != 0;
368 }
369 
370 llvm::StringRef
371 PlatformAndroid::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
372   SymbolContextList matching_symbols;
373   std::vector<const char *> dl_open_names = { "__dl_dlopen", "dlopen" };
374   const char *dl_open_name = nullptr;
375   Target &target = process->GetTarget();
376   for (auto name: dl_open_names) {
377     if (target.GetImages().FindFunctionSymbols(ConstString(name),
378                                                eFunctionNameTypeFull,
379                                                matching_symbols)) {
380        dl_open_name = name;
381        break;
382     }
383   }
384   // Older platform versions have the dl function symbols mangled
385   if (dl_open_name == dl_open_names[0])
386     return R"(
387               extern "C" void* dlopen(const char*, int) asm("__dl_dlopen");
388               extern "C" void* dlsym(void*, const char*) asm("__dl_dlsym");
389               extern "C" int   dlclose(void*) asm("__dl_dlclose");
390               extern "C" char* dlerror(void) asm("__dl_dlerror");
391              )";
392 
393   return PlatformPOSIX::GetLibdlFunctionDeclarations(process);
394 }
395 
396 AdbClient::SyncService *PlatformAndroid::GetSyncService(Status &error) {
397   if (m_adb_sync_svc && m_adb_sync_svc->IsConnected())
398     return m_adb_sync_svc.get();
399 
400   AdbClient adb(m_device_id);
401   m_adb_sync_svc = adb.GetSyncService(error);
402   return (error.Success()) ? m_adb_sync_svc.get() : nullptr;
403 }
404