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/Log.h" 11 #include "lldb/Core/Module.h" 12 #include "lldb/Core/PluginManager.h" 13 #include "lldb/Core/Scalar.h" 14 #include "lldb/Core/Section.h" 15 #include "lldb/Core/ValueObject.h" 16 #include "lldb/Host/HostInfo.h" 17 #include "lldb/Host/StringConvert.h" 18 #include "lldb/Utility/UriParser.h" 19 20 // Project includes 21 #include "AdbClient.h" 22 #include "PlatformAndroid.h" 23 #include "PlatformAndroidRemoteGDBServer.h" 24 25 using namespace lldb; 26 using namespace lldb_private; 27 using namespace lldb_private::platform_android; 28 using namespace std::chrono; 29 30 static uint32_t g_initialize_count = 0; 31 static const unsigned int g_android_default_cache_size = 32 2048; // Fits inside 4k adb packet. 33 34 void PlatformAndroid::Initialize() { 35 PlatformLinux::Initialize(); 36 37 if (g_initialize_count++ == 0) { 38 #if defined(__ANDROID__) 39 PlatformSP default_platform_sp(new PlatformAndroid(true)); 40 default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); 41 Platform::SetHostPlatform(default_platform_sp); 42 #endif 43 PluginManager::RegisterPlugin( 44 PlatformAndroid::GetPluginNameStatic(false), 45 PlatformAndroid::GetPluginDescriptionStatic(false), 46 PlatformAndroid::CreateInstance); 47 } 48 } 49 50 void PlatformAndroid::Terminate() { 51 if (g_initialize_count > 0) { 52 if (--g_initialize_count == 0) { 53 PluginManager::UnregisterPlugin(PlatformAndroid::CreateInstance); 54 } 55 } 56 57 PlatformLinux::Terminate(); 58 } 59 60 PlatformSP PlatformAndroid::CreateInstance(bool force, const ArchSpec *arch) { 61 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 62 if (log) { 63 const char *arch_name; 64 if (arch && arch->GetArchitectureName()) 65 arch_name = arch->GetArchitectureName(); 66 else 67 arch_name = "<null>"; 68 69 const char *triple_cstr = 70 arch ? arch->GetTriple().getTriple().c_str() : "<null>"; 71 72 log->Printf("PlatformAndroid::%s(force=%s, arch={%s,%s})", __FUNCTION__, 73 force ? "true" : "false", arch_name, triple_cstr); 74 } 75 76 bool create = force; 77 if (create == false && arch && arch->IsValid()) { 78 const llvm::Triple &triple = arch->GetTriple(); 79 switch (triple.getVendor()) { 80 case llvm::Triple::PC: 81 create = true; 82 break; 83 84 #if defined(__ANDROID__) 85 // Only accept "unknown" for the vendor if the host is android and 86 // it "unknown" wasn't specified (it was just returned because it 87 // was NOT specified_ 88 case llvm::Triple::VendorType::UnknownVendor: 89 create = !arch->TripleVendorWasSpecified(); 90 break; 91 #endif 92 default: 93 break; 94 } 95 96 if (create) { 97 switch (triple.getOS()) { 98 case llvm::Triple::Android: 99 break; 100 101 #if defined(__ANDROID__) 102 // Only accept "unknown" for the OS if the host is android and 103 // it "unknown" wasn't specified (it was just returned because it 104 // was NOT specified) 105 case llvm::Triple::OSType::UnknownOS: 106 create = !arch->TripleOSWasSpecified(); 107 break; 108 #endif 109 default: 110 create = false; 111 break; 112 } 113 } 114 } 115 116 if (create) { 117 if (log) 118 log->Printf("PlatformAndroid::%s() creating remote-android platform", 119 __FUNCTION__); 120 return PlatformSP(new PlatformAndroid(false)); 121 } 122 123 if (log) 124 log->Printf( 125 "PlatformAndroid::%s() aborting creation of remote-android platform", 126 __FUNCTION__); 127 128 return PlatformSP(); 129 } 130 131 PlatformAndroid::PlatformAndroid(bool is_host) 132 : PlatformLinux(is_host), m_sdk_version(0) {} 133 134 PlatformAndroid::~PlatformAndroid() {} 135 136 ConstString PlatformAndroid::GetPluginNameStatic(bool is_host) { 137 if (is_host) { 138 static ConstString g_host_name(Platform::GetHostPlatformName()); 139 return g_host_name; 140 } else { 141 static ConstString g_remote_name("remote-android"); 142 return g_remote_name; 143 } 144 } 145 146 const char *PlatformAndroid::GetPluginDescriptionStatic(bool is_host) { 147 if (is_host) 148 return "Local Android user platform plug-in."; 149 else 150 return "Remote Android user platform plug-in."; 151 } 152 153 ConstString PlatformAndroid::GetPluginName() { 154 return GetPluginNameStatic(IsHost()); 155 } 156 157 Error PlatformAndroid::ConnectRemote(Args &args) { 158 m_device_id.clear(); 159 160 if (IsHost()) { 161 return Error("can't connect to the host platform '%s', always connected", 162 GetPluginName().GetCString()); 163 } 164 165 if (!m_remote_platform_sp) 166 m_remote_platform_sp = PlatformSP(new PlatformAndroidRemoteGDBServer()); 167 168 int port; 169 llvm::StringRef scheme, host, path; 170 const char *url = args.GetArgumentAtIndex(0); 171 if (!url) 172 return Error("URL is null."); 173 if (!UriParser::Parse(url, scheme, host, port, path)) 174 return Error("Invalid URL: %s", url); 175 if (host != "localhost") 176 m_device_id = host; 177 178 auto error = PlatformLinux::ConnectRemote(args); 179 if (error.Success()) { 180 AdbClient adb; 181 error = AdbClient::CreateByDeviceID(m_device_id, adb); 182 if (error.Fail()) 183 return error; 184 185 m_device_id = adb.GetDeviceID(); 186 } 187 return error; 188 } 189 190 Error PlatformAndroid::GetFile(const FileSpec &source, 191 const FileSpec &destination) { 192 if (IsHost() || !m_remote_platform_sp) 193 return PlatformLinux::GetFile(source, destination); 194 195 FileSpec source_spec(source.GetPath(false), false, 196 FileSpec::ePathSyntaxPosix); 197 if (source_spec.IsRelative()) 198 source_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent( 199 source_spec.GetCString(false)); 200 201 Error 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 Error("Doesn't support single-quotes in filenames"); 223 224 // mode == 0 can signify that adbd cannot access the file 225 // due security 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 Error 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::ePathSyntaxPosix); 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 Error 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 Error 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 Error("Invalid offset - %" PRIu64, src_offset); 262 263 return GetFile(src_file_spec, dst_file_spec); 264 } 265 266 Error PlatformAndroid::DisconnectRemote() { 267 Error 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 Error 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 Error 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 Error( 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 Error("No platform file specified"); 315 316 // Symbolizer isn't available before SDK version 23 317 if (GetSdkVersion() < 23) 318 return Error("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 Error("Symtab already available in the module"); 324 325 AdbClient adb(m_device_id); 326 std::string tmpdir; 327 Error error = adb.Shell("mktemp --directory --tmpdir /data/local/tmp", 328 seconds(5), &tmpdir); 329 if (error.Fail() || tmpdir.empty()) 330 return Error("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 Error 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 Error("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_major_os_version = GetSdkVersion(); 364 m_minor_os_version = 0; 365 m_update_os_version = 0; 366 return m_major_os_version != 0; 367 } 368 369 const char *PlatformAndroid::GetLibdlFunctionDeclarations() const { 370 return R"( 371 extern "C" void* dlopen(const char*, int) asm("__dl_dlopen"); 372 extern "C" void* dlsym(void*, const char*) asm("__dl_dlsym"); 373 extern "C" int dlclose(void*) asm("__dl_dlclose"); 374 extern "C" char* dlerror(void) asm("__dl_dlerror"); 375 )"; 376 } 377 378 AdbClient::SyncService *PlatformAndroid::GetSyncService(Error &error) { 379 if (m_adb_sync_svc && m_adb_sync_svc->IsConnected()) 380 return m_adb_sync_svc.get(); 381 382 AdbClient adb(m_device_id); 383 m_adb_sync_svc = adb.GetSyncService(error); 384 return (error.Success()) ? m_adb_sync_svc.get() : nullptr; 385 } 386