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