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