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), 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), false, 241 FileSpec::Style::posix); 242 if (destination_spec.IsRelative()) 243 destination_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent( 244 destination_spec.GetCString(false)); 245 246 // TODO: Set correct uid and gid on remote file. 247 Status error; 248 auto sync_service = GetSyncService(error); 249 if (error.Fail()) 250 return error; 251 return sync_service->PushFile(source, destination_spec); 252 } 253 254 const char *PlatformAndroid::GetCacheHostname() { return m_device_id.c_str(); } 255 256 Status PlatformAndroid::DownloadModuleSlice(const FileSpec &src_file_spec, 257 const uint64_t src_offset, 258 const uint64_t src_size, 259 const FileSpec &dst_file_spec) { 260 if (src_offset != 0) 261 return Status("Invalid offset - %" PRIu64, src_offset); 262 263 return GetFile(src_file_spec, dst_file_spec); 264 } 265 266 Status PlatformAndroid::DisconnectRemote() { 267 Status error = PlatformLinux::DisconnectRemote(); 268 if (error.Success()) { 269 m_device_id.clear(); 270 m_sdk_version = 0; 271 } 272 return error; 273 } 274 275 uint32_t PlatformAndroid::GetDefaultMemoryCacheLineSize() { 276 return g_android_default_cache_size; 277 } 278 279 uint32_t PlatformAndroid::GetSdkVersion() { 280 if (!IsConnected()) 281 return 0; 282 283 if (m_sdk_version != 0) 284 return m_sdk_version; 285 286 std::string version_string; 287 AdbClient adb(m_device_id); 288 Status error = 289 adb.Shell("getprop ro.build.version.sdk", seconds(5), &version_string); 290 version_string = llvm::StringRef(version_string).trim().str(); 291 292 if (error.Fail() || version_string.empty()) { 293 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM); 294 if (log) 295 log->Printf("Get SDK version failed. (error: %s, output: %s)", 296 error.AsCString(), version_string.c_str()); 297 return 0; 298 } 299 300 m_sdk_version = StringConvert::ToUInt32(version_string.c_str()); 301 return m_sdk_version; 302 } 303 304 Status PlatformAndroid::DownloadSymbolFile(const lldb::ModuleSP &module_sp, 305 const FileSpec &dst_file_spec) { 306 // For oat file we can try to fetch additional debug info from the device 307 ConstString extension = module_sp->GetFileSpec().GetFileNameExtension(); 308 if (extension != ConstString(".oat") && extension != ConstString(".odex")) 309 return Status( 310 "Symbol file downloading only supported for oat and odex files"); 311 312 // If we have no information about the platform file we can't execute oatdump 313 if (!module_sp->GetPlatformFileSpec()) 314 return Status("No platform file specified"); 315 316 // Symbolizer isn't available before SDK version 23 317 if (GetSdkVersion() < 23) 318 return Status("Symbol file generation only supported on SDK 23+"); 319 320 // If we already have symtab then we don't have to try and generate one 321 if (module_sp->GetSectionList()->FindSectionByName(ConstString(".symtab")) != 322 nullptr) 323 return Status("Symtab already available in the module"); 324 325 AdbClient adb(m_device_id); 326 std::string tmpdir; 327 Status error = adb.Shell("mktemp --directory --tmpdir /data/local/tmp", 328 seconds(5), &tmpdir); 329 if (error.Fail() || tmpdir.empty()) 330 return Status("Failed to generate temporary directory on the device (%s)", 331 error.AsCString()); 332 tmpdir = llvm::StringRef(tmpdir).trim().str(); 333 334 // Create file remover for the temporary directory created on the device 335 std::unique_ptr<std::string, std::function<void(std::string *)>> 336 tmpdir_remover(&tmpdir, [&adb](std::string *s) { 337 StreamString command; 338 command.Printf("rm -rf %s", s->c_str()); 339 Status error = adb.Shell(command.GetData(), seconds(5), nullptr); 340 341 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 342 if (log && error.Fail()) 343 log->Printf("Failed to remove temp directory: %s", error.AsCString()); 344 }); 345 346 FileSpec symfile_platform_filespec(tmpdir, false); 347 symfile_platform_filespec.AppendPathComponent("symbolized.oat"); 348 349 // Execute oatdump on the remote device to generate a file with symtab 350 StreamString command; 351 command.Printf("oatdump --symbolize=%s --output=%s", 352 module_sp->GetPlatformFileSpec().GetCString(false), 353 symfile_platform_filespec.GetCString(false)); 354 error = adb.Shell(command.GetData(), minutes(1), nullptr); 355 if (error.Fail()) 356 return Status("Oatdump failed: %s", error.AsCString()); 357 358 // Download the symbolfile from the remote device 359 return GetFile(symfile_platform_filespec, dst_file_spec); 360 } 361 362 bool PlatformAndroid::GetRemoteOSVersion() { 363 m_os_version = llvm::VersionTuple(GetSdkVersion()); 364 return !m_os_version.empty(); 365 } 366 367 llvm::StringRef 368 PlatformAndroid::GetLibdlFunctionDeclarations(lldb_private::Process *process) { 369 SymbolContextList matching_symbols; 370 std::vector<const char *> dl_open_names = { "__dl_dlopen", "dlopen" }; 371 const char *dl_open_name = nullptr; 372 Target &target = process->GetTarget(); 373 for (auto name: dl_open_names) { 374 if (target.GetImages().FindFunctionSymbols(ConstString(name), 375 eFunctionNameTypeFull, 376 matching_symbols)) { 377 dl_open_name = name; 378 break; 379 } 380 } 381 // Older platform versions have the dl function symbols mangled 382 if (dl_open_name == dl_open_names[0]) 383 return R"( 384 extern "C" void* dlopen(const char*, int) asm("__dl_dlopen"); 385 extern "C" void* dlsym(void*, const char*) asm("__dl_dlsym"); 386 extern "C" int dlclose(void*) asm("__dl_dlclose"); 387 extern "C" char* dlerror(void) asm("__dl_dlerror"); 388 )"; 389 390 return PlatformPOSIX::GetLibdlFunctionDeclarations(process); 391 } 392 393 AdbClient::SyncService *PlatformAndroid::GetSyncService(Status &error) { 394 if (m_adb_sync_svc && m_adb_sync_svc->IsConnected()) 395 return m_adb_sync_svc.get(); 396 397 AdbClient adb(m_device_id); 398 m_adb_sync_svc = adb.GetSyncService(error); 399 return (error.Success()) ? m_adb_sync_svc.get() : nullptr; 400 } 401