180814287SRaphael Isemann //===-- PlatformPOSIX.cpp -------------------------------------------------===// 2e0f8f574SDaniel Malea // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e0f8f574SDaniel Malea // 7e0f8f574SDaniel Malea //===----------------------------------------------------------------------===// 8e0f8f574SDaniel Malea 9e0f8f574SDaniel Malea #include "PlatformPOSIX.h" 10e0f8f574SDaniel Malea 11*af921006SPavel Labath #include "Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h" 128be30215SAlex Langford #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 13348fb385STodd Fiala #include "lldb/Core/Debugger.h" 14348fb385STodd Fiala #include "lldb/Core/Module.h" 153cb132a0STamas Berghammer #include "lldb/Core/ValueObject.h" 161ecb34f4SJim Ingham #include "lldb/Expression/DiagnosticManager.h" 171ecb34f4SJim Ingham #include "lldb/Expression/FunctionCaller.h" 183cb132a0STamas Berghammer #include "lldb/Expression/UserExpression.h" 191ecb34f4SJim Ingham #include "lldb/Expression/UtilityFunction.h" 20e0f8f574SDaniel Malea #include "lldb/Host/File.h" 21c00cf4a0SZachary Turner #include "lldb/Host/FileCache.h" 22c00cf4a0SZachary Turner #include "lldb/Host/FileSystem.h" 23e0f8f574SDaniel Malea #include "lldb/Host/Host.h" 24fc89bbccSPavel Labath #include "lldb/Host/HostInfo.h" 25eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h" 263cb132a0STamas Berghammer #include "lldb/Target/DynamicLoader.h" 273cb132a0STamas Berghammer #include "lldb/Target/ExecutionContext.h" 28a78bd7ffSZachary Turner #include "lldb/Target/Process.h" 293cb132a0STamas Berghammer #include "lldb/Target/Thread.h" 30666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h" 315713a05bSZachary Turner #include "lldb/Utility/FileSpec.h" 32c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h" 336f9e6901SZachary Turner #include "lldb/Utility/Log.h" 34bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h" 35e0ea8d87SJonas Devlieghere #include "llvm/ADT/ScopeExit.h" 36e0f8f574SDaniel Malea 37e0f8f574SDaniel Malea using namespace lldb; 38e0f8f574SDaniel Malea using namespace lldb_private; 39e0f8f574SDaniel Malea 40e0f8f574SDaniel Malea /// Default Constructor 41b9c1b51eSKate Stone PlatformPOSIX::PlatformPOSIX(bool is_host) 4252d9c62aSPavel Labath : RemoteAwarePlatform(is_host), // This is the local host platform 430a66e2f1SEnrico Granata m_option_group_platform_rsync(new OptionGroupPlatformRSync()), 440a66e2f1SEnrico Granata m_option_group_platform_ssh(new OptionGroupPlatformSSH()), 4552d9c62aSPavel Labath m_option_group_platform_caching(new OptionGroupPlatformCaching()) {} 46e0f8f574SDaniel Malea 47e0f8f574SDaniel Malea /// Destructor. 48e0f8f574SDaniel Malea /// 49e0f8f574SDaniel Malea /// The destructor is virtual since this class is designed to be 50e0f8f574SDaniel Malea /// inherited from by the plug-in instance. 51fd2433e1SJonas Devlieghere PlatformPOSIX::~PlatformPOSIX() = default; 52e0f8f574SDaniel Malea 53b9c1b51eSKate Stone lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions( 54b9c1b51eSKate Stone lldb_private::CommandInterpreter &interpreter) { 550a66e2f1SEnrico Granata auto iter = m_options.find(&interpreter), end = m_options.end(); 56b9c1b51eSKate Stone if (iter == end) { 57b9c1b51eSKate Stone std::unique_ptr<lldb_private::OptionGroupOptions> options( 58b9c1b51eSKate Stone new OptionGroupOptions()); 590a66e2f1SEnrico Granata options->Append(m_option_group_platform_rsync.get()); 600a66e2f1SEnrico Granata options->Append(m_option_group_platform_ssh.get()); 610a66e2f1SEnrico Granata options->Append(m_option_group_platform_caching.get()); 620a66e2f1SEnrico Granata m_options[&interpreter] = std::move(options); 63e0f8f574SDaniel Malea } 640a66e2f1SEnrico Granata 650a66e2f1SEnrico Granata return m_options.at(&interpreter).get(); 66e0f8f574SDaniel Malea } 67e0f8f574SDaniel Malea 68b9c1b51eSKate Stone static uint32_t chown_file(Platform *platform, const char *path, 69e0f8f574SDaniel Malea uint32_t uid = UINT32_MAX, 70b9c1b51eSKate Stone uint32_t gid = UINT32_MAX) { 71e0f8f574SDaniel Malea if (!platform || !path || *path == 0) 72e0f8f574SDaniel Malea return UINT32_MAX; 73e0f8f574SDaniel Malea 74e0f8f574SDaniel Malea if (uid == UINT32_MAX && gid == UINT32_MAX) 75e0f8f574SDaniel Malea return 0; // pretend I did chown correctly - actually I just didn't care 76e0f8f574SDaniel Malea 77e0f8f574SDaniel Malea StreamString command; 78e0f8f574SDaniel Malea command.PutCString("chown "); 79e0f8f574SDaniel Malea if (uid != UINT32_MAX) 80e0f8f574SDaniel Malea command.Printf("%d", uid); 81e0f8f574SDaniel Malea if (gid != UINT32_MAX) 82e0f8f574SDaniel Malea command.Printf(":%d", gid); 83e0f8f574SDaniel Malea command.Printf("%s", path); 84e0f8f574SDaniel Malea int status; 8528e4942bSPavel Labath platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, 86248a1305SKonrad Kleine nullptr, std::chrono::seconds(10)); 87e0f8f574SDaniel Malea return status; 88e0f8f574SDaniel Malea } 89e0f8f574SDaniel Malea 9097206d57SZachary Turner lldb_private::Status 91e0f8f574SDaniel Malea PlatformPOSIX::PutFile(const lldb_private::FileSpec &source, 92b9c1b51eSKate Stone const lldb_private::FileSpec &destination, uint32_t uid, 93b9c1b51eSKate Stone uint32_t gid) { 94a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Platform); 95fbb76349SGreg Clayton 96b9c1b51eSKate Stone if (IsHost()) { 97532290e6SPavel Labath if (source == destination) 9897206d57SZachary Turner return Status(); 99e0f8f574SDaniel Malea // cp src dst 100e0f8f574SDaniel Malea // chown uid:gid dst 101e0f8f574SDaniel Malea std::string src_path(source.GetPath()); 102e0f8f574SDaniel Malea if (src_path.empty()) 10397206d57SZachary Turner return Status("unable to get file path for source"); 104e0f8f574SDaniel Malea std::string dst_path(destination.GetPath()); 105e0f8f574SDaniel Malea if (dst_path.empty()) 10697206d57SZachary Turner return Status("unable to get file path for destination"); 107e0f8f574SDaniel Malea StreamString command; 108e0f8f574SDaniel Malea command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); 109e0f8f574SDaniel Malea int status; 11028e4942bSPavel Labath RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr, 11119dd1a0eSPavel Labath std::chrono::seconds(10)); 112e0f8f574SDaniel Malea if (status != 0) 11397206d57SZachary Turner return Status("unable to perform copy"); 114e0f8f574SDaniel Malea if (uid == UINT32_MAX && gid == UINT32_MAX) 11597206d57SZachary Turner return Status(); 116e0f8f574SDaniel Malea if (chown_file(this, dst_path.c_str(), uid, gid) != 0) 11797206d57SZachary Turner return Status("unable to perform chown"); 11897206d57SZachary Turner return Status(); 119b9c1b51eSKate Stone } else if (m_remote_platform_sp) { 120b9c1b51eSKate Stone if (GetSupportsRSync()) { 121e0f8f574SDaniel Malea std::string src_path(source.GetPath()); 122e0f8f574SDaniel Malea if (src_path.empty()) 12397206d57SZachary Turner return Status("unable to get file path for source"); 124e0f8f574SDaniel Malea std::string dst_path(destination.GetPath()); 125e0f8f574SDaniel Malea if (dst_path.empty()) 12697206d57SZachary Turner return Status("unable to get file path for destination"); 127e0f8f574SDaniel Malea StreamString command; 128b9c1b51eSKate Stone if (GetIgnoresRemoteHostname()) { 129e0f8f574SDaniel Malea if (!GetRSyncPrefix()) 130b9c1b51eSKate Stone command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(), 131e0f8f574SDaniel Malea dst_path.c_str()); 132e0f8f574SDaniel Malea else 133b9c1b51eSKate Stone command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(), 134b9c1b51eSKate Stone GetRSyncPrefix(), dst_path.c_str()); 135b9c1b51eSKate Stone } else 136b9c1b51eSKate Stone command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(), 137b9c1b51eSKate Stone GetHostname(), dst_path.c_str()); 13863e5fb76SJonas Devlieghere LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData()); 139e0f8f574SDaniel Malea int retcode; 14028e4942bSPavel Labath Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr, 141248a1305SKonrad Kleine nullptr, std::chrono::minutes(1)); 142b9c1b51eSKate Stone if (retcode == 0) { 143e0f8f574SDaniel Malea // Don't chown a local file for a remote system 144e0f8f574SDaniel Malea // if (chown_file(this,dst_path.c_str(),uid,gid) != 0) 14597206d57SZachary Turner // return Status("unable to perform chown"); 14697206d57SZachary Turner return Status(); 147e0f8f574SDaniel Malea } 148b9c1b51eSKate Stone // if we are still here rsync has failed - let's try the slow way before 149b9c1b51eSKate Stone // giving up 150e0f8f574SDaniel Malea } 151e0f8f574SDaniel Malea } 152e0f8f574SDaniel Malea return Platform::PutFile(source, destination, uid, gid); 153e0f8f574SDaniel Malea } 154e0f8f574SDaniel Malea 15597206d57SZachary Turner lldb_private::Status PlatformPOSIX::GetFile( 156b9c1b51eSKate Stone const lldb_private::FileSpec &source, // remote file path 157d3173f34SChaoren Lin const lldb_private::FileSpec &destination) // local file path 158e0f8f574SDaniel Malea { 159a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Platform); 160fbb76349SGreg Clayton 161e0f8f574SDaniel Malea // Check the args, first. 162e0f8f574SDaniel Malea std::string src_path(source.GetPath()); 163e0f8f574SDaniel Malea if (src_path.empty()) 16497206d57SZachary Turner return Status("unable to get file path for source"); 165e0f8f574SDaniel Malea std::string dst_path(destination.GetPath()); 166e0f8f574SDaniel Malea if (dst_path.empty()) 16797206d57SZachary Turner return Status("unable to get file path for destination"); 168b9c1b51eSKate Stone if (IsHost()) { 169532290e6SPavel Labath if (source == destination) 17097206d57SZachary Turner return Status("local scenario->source and destination are the same file " 171b9c1b51eSKate Stone "path: no operation performed"); 172e0f8f574SDaniel Malea // cp src dst 173e0f8f574SDaniel Malea StreamString cp_command; 174e0f8f574SDaniel Malea cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); 175e0f8f574SDaniel Malea int status; 17628e4942bSPavel Labath RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr, 17719dd1a0eSPavel Labath std::chrono::seconds(10)); 178e0f8f574SDaniel Malea if (status != 0) 17997206d57SZachary Turner return Status("unable to perform copy"); 18097206d57SZachary Turner return Status(); 181b9c1b51eSKate Stone } else if (m_remote_platform_sp) { 182b9c1b51eSKate Stone if (GetSupportsRSync()) { 183e0f8f574SDaniel Malea StreamString command; 184b9c1b51eSKate Stone if (GetIgnoresRemoteHostname()) { 185e0f8f574SDaniel Malea if (!GetRSyncPrefix()) 186b9c1b51eSKate Stone command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(), 187e0f8f574SDaniel Malea dst_path.c_str()); 188e0f8f574SDaniel Malea else 189b9c1b51eSKate Stone command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(), 190b9c1b51eSKate Stone src_path.c_str(), dst_path.c_str()); 191b9c1b51eSKate Stone } else 192b9c1b51eSKate Stone command.Printf("rsync %s %s:%s %s", GetRSyncOpts(), 193b9c1b51eSKate Stone m_remote_platform_sp->GetHostname(), src_path.c_str(), 194e0f8f574SDaniel Malea dst_path.c_str()); 19563e5fb76SJonas Devlieghere LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData()); 196e0f8f574SDaniel Malea int retcode; 19728e4942bSPavel Labath Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr, 198248a1305SKonrad Kleine nullptr, std::chrono::minutes(1)); 199e0f8f574SDaniel Malea if (retcode == 0) 20097206d57SZachary Turner return Status(); 20105097246SAdrian Prantl // If we are here, rsync has failed - let's try the slow way before 20205097246SAdrian Prantl // giving up 203e0f8f574SDaniel Malea } 204e0f8f574SDaniel Malea // open src and dst 205e0f8f574SDaniel Malea // read/write, read/write, read/write, ... 206e0f8f574SDaniel Malea // close src 207e0f8f574SDaniel Malea // close dst 20863e5fb76SJonas Devlieghere LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n"); 20997206d57SZachary Turner Status error; 21014735cabSMichał Górny user_id_t fd_src = OpenFile(source, File::eOpenOptionReadOnly, 211b9c1b51eSKate Stone lldb::eFilePermissionsFileDefault, error); 212e0f8f574SDaniel Malea 213e0f8f574SDaniel Malea if (fd_src == UINT64_MAX) 21497206d57SZachary Turner return Status("unable to open source file"); 215e0f8f574SDaniel Malea 216fbb76349SGreg Clayton uint32_t permissions = 0; 217d3173f34SChaoren Lin error = GetFilePermissions(source, permissions); 218e0f8f574SDaniel Malea 219e0f8f574SDaniel Malea if (permissions == 0) 220fbb76349SGreg Clayton permissions = lldb::eFilePermissionsFileDefault; 221e0f8f574SDaniel Malea 222c00cf4a0SZachary Turner user_id_t fd_dst = FileCache::GetInstance().OpenFile( 22314735cabSMichał Górny destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly | 224b9c1b51eSKate Stone File::eOpenOptionTruncate, 225b9c1b51eSKate Stone permissions, error); 226e0f8f574SDaniel Malea 227b9c1b51eSKate Stone if (fd_dst == UINT64_MAX) { 228e0f8f574SDaniel Malea if (error.Success()) 229e0f8f574SDaniel Malea error.SetErrorString("unable to open destination file"); 230e0f8f574SDaniel Malea } 231e0f8f574SDaniel Malea 232b9c1b51eSKate Stone if (error.Success()) { 233fc54427eSJonas Devlieghere lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(1024, 0)); 234e0f8f574SDaniel Malea uint64_t offset = 0; 235e0f8f574SDaniel Malea error.Clear(); 236b9c1b51eSKate Stone while (error.Success()) { 237b9c1b51eSKate Stone const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(), 238b9c1b51eSKate Stone buffer_sp->GetByteSize(), error); 239e0f8f574SDaniel Malea if (error.Fail()) 240e0f8f574SDaniel Malea break; 241e0f8f574SDaniel Malea if (n_read == 0) 242e0f8f574SDaniel Malea break; 243b9c1b51eSKate Stone if (FileCache::GetInstance().WriteFile(fd_dst, offset, 244b9c1b51eSKate Stone buffer_sp->GetBytes(), n_read, 245b9c1b51eSKate Stone error) != n_read) { 246e0f8f574SDaniel Malea if (!error.Fail()) 247e0f8f574SDaniel Malea error.SetErrorString("unable to write to destination file"); 248e0f8f574SDaniel Malea break; 249e0f8f574SDaniel Malea } 250e0f8f574SDaniel Malea offset += n_read; 251e0f8f574SDaniel Malea } 252e0f8f574SDaniel Malea } 253e0f8f574SDaniel Malea // Ignore the close error of src. 254e0f8f574SDaniel Malea if (fd_src != UINT64_MAX) 255e0f8f574SDaniel Malea CloseFile(fd_src, error); 256e0f8f574SDaniel Malea // And close the dst file descriptot. 257b9c1b51eSKate Stone if (fd_dst != UINT64_MAX && 258b9c1b51eSKate Stone !FileCache::GetInstance().CloseFile(fd_dst, error)) { 259e0f8f574SDaniel Malea if (!error.Fail()) 260e0f8f574SDaniel Malea error.SetErrorString("unable to close destination file"); 261e0f8f574SDaniel Malea } 262e0f8f574SDaniel Malea return error; 263e0f8f574SDaniel Malea } 264e0f8f574SDaniel Malea return Platform::GetFile(source, destination); 265e0f8f574SDaniel Malea } 266e0f8f574SDaniel Malea 267b9c1b51eSKate Stone std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() { 268e0f8f574SDaniel Malea StreamString stream; 269b9c1b51eSKate Stone if (GetSupportsRSync()) { 270e0f8f574SDaniel Malea stream.PutCString("rsync"); 271e0f8f574SDaniel Malea if ((GetRSyncOpts() && *GetRSyncOpts()) || 272b9c1b51eSKate Stone (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) { 273e0f8f574SDaniel Malea stream.Printf(", options: "); 274e0f8f574SDaniel Malea if (GetRSyncOpts() && *GetRSyncOpts()) 275e0f8f574SDaniel Malea stream.Printf("'%s' ", GetRSyncOpts()); 276e0f8f574SDaniel Malea stream.Printf(", prefix: "); 277e0f8f574SDaniel Malea if (GetRSyncPrefix() && *GetRSyncPrefix()) 278e0f8f574SDaniel Malea stream.Printf("'%s' ", GetRSyncPrefix()); 279e0f8f574SDaniel Malea if (GetIgnoresRemoteHostname()) 280e0f8f574SDaniel Malea stream.Printf("ignore remote-hostname "); 281e0f8f574SDaniel Malea } 282e0f8f574SDaniel Malea } 283b9c1b51eSKate Stone if (GetSupportsSSH()) { 284e0f8f574SDaniel Malea stream.PutCString("ssh"); 285e0f8f574SDaniel Malea if (GetSSHOpts() && *GetSSHOpts()) 286e0f8f574SDaniel Malea stream.Printf(", options: '%s' ", GetSSHOpts()); 287e0f8f574SDaniel Malea } 288e0f8f574SDaniel Malea if (GetLocalCacheDirectory() && *GetLocalCacheDirectory()) 289e0f8f574SDaniel Malea stream.Printf("cache dir: %s", GetLocalCacheDirectory()); 290e0f8f574SDaniel Malea if (stream.GetSize()) 291adcd0268SBenjamin Kramer return std::string(stream.GetString()); 292e0f8f574SDaniel Malea else 293e0f8f574SDaniel Malea return ""; 294e0f8f574SDaniel Malea } 295e0f8f574SDaniel Malea 296b9c1b51eSKate Stone const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() { 29798d0a4b3SChaoren Lin if (IsRemote() && m_remote_platform_sp) 29898d0a4b3SChaoren Lin return m_remote_platform_sp->GetRemoteUnixSignals(); 29998d0a4b3SChaoren Lin return Platform::GetRemoteUnixSignals(); 30098d0a4b3SChaoren Lin } 30198d0a4b3SChaoren Lin 30297206d57SZachary Turner Status PlatformPOSIX::ConnectRemote(Args &args) { 30397206d57SZachary Turner Status error; 304b9c1b51eSKate Stone if (IsHost()) { 305a3939e15SPavel Labath error.SetErrorStringWithFormatv( 306a3939e15SPavel Labath "can't connect to the host platform '{0}', always connected", 307a3939e15SPavel Labath GetPluginName()); 308b9c1b51eSKate Stone } else { 309015d818bSTodd Fiala if (!m_remote_platform_sp) 310b9c1b51eSKate Stone m_remote_platform_sp = 311*af921006SPavel Labath platform_gdb_server::PlatformRemoteGDBServer::CreateInstance( 312*af921006SPavel Labath /*force=*/true, nullptr); 313015d818bSTodd Fiala 314015d818bSTodd Fiala if (m_remote_platform_sp && error.Success()) 315015d818bSTodd Fiala error = m_remote_platform_sp->ConnectRemote(args); 316015d818bSTodd Fiala else 317015d818bSTodd Fiala error.SetErrorString("failed to create a 'remote-gdb-server' platform"); 318015d818bSTodd Fiala 319015d818bSTodd Fiala if (error.Fail()) 320015d818bSTodd Fiala m_remote_platform_sp.reset(); 321015d818bSTodd Fiala } 322015d818bSTodd Fiala 323b9c1b51eSKate Stone if (error.Success() && m_remote_platform_sp) { 324b9c1b51eSKate Stone if (m_option_group_platform_rsync.get() && 325b9c1b51eSKate Stone m_option_group_platform_ssh.get() && 326b9c1b51eSKate Stone m_option_group_platform_caching.get()) { 327b9c1b51eSKate Stone if (m_option_group_platform_rsync->m_rsync) { 328015d818bSTodd Fiala SetSupportsRSync(true); 3290a66e2f1SEnrico Granata SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str()); 3300a66e2f1SEnrico Granata SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str()); 331b9c1b51eSKate Stone SetIgnoresRemoteHostname( 332b9c1b51eSKate Stone m_option_group_platform_rsync->m_ignores_remote_hostname); 333015d818bSTodd Fiala } 334b9c1b51eSKate Stone if (m_option_group_platform_ssh->m_ssh) { 335015d818bSTodd Fiala SetSupportsSSH(true); 3360a66e2f1SEnrico Granata SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str()); 337015d818bSTodd Fiala } 338b9c1b51eSKate Stone SetLocalCacheDirectory( 339b9c1b51eSKate Stone m_option_group_platform_caching->m_cache_dir.c_str()); 340015d818bSTodd Fiala } 341015d818bSTodd Fiala } 342015d818bSTodd Fiala 343015d818bSTodd Fiala return error; 344015d818bSTodd Fiala } 345015d818bSTodd Fiala 34697206d57SZachary Turner Status PlatformPOSIX::DisconnectRemote() { 34797206d57SZachary Turner Status error; 348015d818bSTodd Fiala 349b9c1b51eSKate Stone if (IsHost()) { 350a3939e15SPavel Labath error.SetErrorStringWithFormatv( 351a3939e15SPavel Labath "can't disconnect from the host platform '{0}', always connected", 352a3939e15SPavel Labath GetPluginName()); 353b9c1b51eSKate Stone } else { 354015d818bSTodd Fiala if (m_remote_platform_sp) 355015d818bSTodd Fiala error = m_remote_platform_sp->DisconnectRemote(); 356015d818bSTodd Fiala else 357015d818bSTodd Fiala error.SetErrorString("the platform is not currently connected"); 358015d818bSTodd Fiala } 359015d818bSTodd Fiala return error; 360015d818bSTodd Fiala } 361015d818bSTodd Fiala 362b9c1b51eSKate Stone lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info, 363b9c1b51eSKate Stone Debugger &debugger, Target *target, 36497206d57SZachary Turner Status &error) { 365348fb385STodd Fiala lldb::ProcessSP process_sp; 366a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Platform); 367348fb385STodd Fiala 368b9c1b51eSKate Stone if (IsHost()) { 369248a1305SKonrad Kleine if (target == nullptr) { 370348fb385STodd Fiala TargetSP new_target_sp; 371348fb385STodd Fiala 372f9a07e9fSJonas Devlieghere error = debugger.GetTargetList().CreateTarget( 373248a1305SKonrad Kleine debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp); 374348fb385STodd Fiala target = new_target_sp.get(); 37563e5fb76SJonas Devlieghere LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__); 376b9c1b51eSKate Stone } else { 377348fb385STodd Fiala error.Clear(); 37863e5fb76SJonas Devlieghere LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target", 379b9c1b51eSKate Stone __FUNCTION__); 380348fb385STodd Fiala } 381348fb385STodd Fiala 382b9c1b51eSKate Stone if (target && error.Success()) { 383b9c1b51eSKate Stone if (log) { 384348fb385STodd Fiala ModuleSP exe_module_sp = target->GetExecutableModule(); 38563e5fb76SJonas Devlieghere LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s", 386b9c1b51eSKate Stone __FUNCTION__, (void *)target, 38763e5fb76SJonas Devlieghere exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 388b9c1b51eSKate Stone : "<null>"); 389348fb385STodd Fiala } 390348fb385STodd Fiala 391b9c1b51eSKate Stone process_sp = 392b9c1b51eSKate Stone target->CreateProcess(attach_info.GetListenerForProcess(debugger), 3931a1cc0baSMichał Górny "gdb-remote", nullptr, true); 394348fb385STodd Fiala 395b9c1b51eSKate Stone if (process_sp) { 396583bbb1dSJim Ingham ListenerSP listener_sp = attach_info.GetHijackListener(); 397b9c1b51eSKate Stone if (listener_sp == nullptr) { 398b9c1b51eSKate Stone listener_sp = 399b9c1b51eSKate Stone Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack"); 400348fb385STodd Fiala attach_info.SetHijackListener(listener_sp); 401926af0cdSOleksiy Vyalov } 402583bbb1dSJim Ingham process_sp->HijackProcessEvents(listener_sp); 403348fb385STodd Fiala error = process_sp->Attach(attach_info); 404348fb385STodd Fiala } 405348fb385STodd Fiala } 406b9c1b51eSKate Stone } else { 407348fb385STodd Fiala if (m_remote_platform_sp) 408b9c1b51eSKate Stone process_sp = 409b9c1b51eSKate Stone m_remote_platform_sp->Attach(attach_info, debugger, target, error); 410348fb385STodd Fiala else 411348fb385STodd Fiala error.SetErrorString("the platform is not currently connected"); 412348fb385STodd Fiala } 413348fb385STodd Fiala return process_sp; 414348fb385STodd Fiala } 415348fb385STodd Fiala 416bd590a5fSPavel Labath lldb::ProcessSP PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, 417bd590a5fSPavel Labath Debugger &debugger, Target &target, 41897206d57SZachary Turner Status &error) { 419a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Platform); 420bd590a5fSPavel Labath LLDB_LOG(log, "target {0}", &target); 421a825eaa9SMichał Górny 422015d818bSTodd Fiala ProcessSP process_sp; 423015d818bSTodd Fiala 424a825eaa9SMichał Górny if (!IsHost()) { 425015d818bSTodd Fiala if (m_remote_platform_sp) 426b9c1b51eSKate Stone process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger, 427b9c1b51eSKate Stone target, error); 428015d818bSTodd Fiala else 429015d818bSTodd Fiala error.SetErrorString("the platform is not currently connected"); 430a825eaa9SMichał Górny return process_sp; 431015d818bSTodd Fiala } 432a825eaa9SMichał Górny 433a825eaa9SMichał Górny // 434a825eaa9SMichał Górny // For local debugging, we'll insist on having ProcessGDBRemote create the 435a825eaa9SMichał Górny // process. 436a825eaa9SMichał Górny // 437a825eaa9SMichał Górny 438a825eaa9SMichał Górny // Make sure we stop at the entry point 439a825eaa9SMichał Górny launch_info.GetFlags().Set(eLaunchFlagDebug); 440a825eaa9SMichał Górny 441a825eaa9SMichał Górny // We always launch the process we are going to debug in a separate process 442a825eaa9SMichał Górny // group, since then we can handle ^C interrupts ourselves w/o having to 443a825eaa9SMichał Górny // worry about the target getting them as well. 444a825eaa9SMichał Górny launch_info.SetLaunchInSeparateProcessGroup(true); 445a825eaa9SMichał Górny 446a825eaa9SMichał Górny // Now create the gdb-remote process. 447a825eaa9SMichał Górny LLDB_LOG(log, "having target create process with gdb-remote plugin"); 448a2c267e0SIlya Nozhkin process_sp = target.CreateProcess(launch_info.GetListener(), "gdb-remote", 449a2c267e0SIlya Nozhkin nullptr, true); 450a825eaa9SMichał Górny 451a825eaa9SMichał Górny if (!process_sp) { 452a825eaa9SMichał Górny error.SetErrorString("CreateProcess() failed for gdb-remote process"); 453a825eaa9SMichał Górny LLDB_LOG(log, "error: {0}", error); 454a825eaa9SMichał Górny return process_sp; 455a825eaa9SMichał Górny } 456a825eaa9SMichał Górny 457a825eaa9SMichał Górny LLDB_LOG(log, "successfully created process"); 458a2c267e0SIlya Nozhkin 459a2c267e0SIlya Nozhkin process_sp->HijackProcessEvents(launch_info.GetHijackListener()); 460a825eaa9SMichał Górny 461a825eaa9SMichał Górny // Log file actions. 462a825eaa9SMichał Górny if (log) { 463a825eaa9SMichał Górny LLDB_LOG(log, "launching process with the following file actions:"); 464a825eaa9SMichał Górny StreamString stream; 465a825eaa9SMichał Górny size_t i = 0; 466a825eaa9SMichał Górny const FileAction *file_action; 467a825eaa9SMichał Górny while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) { 468a825eaa9SMichał Górny file_action->Dump(stream); 469a825eaa9SMichał Górny LLDB_LOG(log, "{0}", stream.GetData()); 470a825eaa9SMichał Górny stream.Clear(); 471a825eaa9SMichał Górny } 472a825eaa9SMichał Górny } 473a825eaa9SMichał Górny 474a825eaa9SMichał Górny // Do the launch. 475a825eaa9SMichał Górny error = process_sp->Launch(launch_info); 476a825eaa9SMichał Górny if (error.Success()) { 477a825eaa9SMichał Górny // Hook up process PTY if we have one (which we should for local debugging 478a825eaa9SMichał Górny // with llgs). 479a825eaa9SMichał Górny int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor(); 480a825eaa9SMichał Górny if (pty_fd != PseudoTerminal::invalid_fd) { 481a825eaa9SMichał Górny process_sp->SetSTDIOFileDescriptor(pty_fd); 482a825eaa9SMichał Górny LLDB_LOG(log, "hooked up STDIO pty to process"); 483a825eaa9SMichał Górny } else 484a825eaa9SMichał Górny LLDB_LOG(log, "not using process STDIO pty"); 485a825eaa9SMichał Górny } else { 486a825eaa9SMichał Górny LLDB_LOG(log, "{0}", error); 487bd590a5fSPavel Labath // FIXME figure out appropriate cleanup here. Do we delete the process? 488bd590a5fSPavel Labath // Does our caller do that? 489a825eaa9SMichał Górny } 490a825eaa9SMichał Górny 491015d818bSTodd Fiala return process_sp; 492015d818bSTodd Fiala } 493015d818bSTodd Fiala 494b9c1b51eSKate Stone void PlatformPOSIX::CalculateTrapHandlerSymbolNames() { 4952094dbf4SJason Molenda m_trap_handlers.push_back(ConstString("_sigtramp")); 4962094dbf4SJason Molenda } 4973cb132a0STamas Berghammer 49897206d57SZachary Turner Status PlatformPOSIX::EvaluateLibdlExpression( 499b9c1b51eSKate Stone lldb_private::Process *process, const char *expr_cstr, 500d37c9469SPavel Labath llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) { 5013cb132a0STamas Berghammer DynamicLoader *loader = process->GetDynamicLoader(); 502b9c1b51eSKate Stone if (loader) { 50397206d57SZachary Turner Status error = loader->CanLoadImage(); 5043cb132a0STamas Berghammer if (error.Fail()) 5053cb132a0STamas Berghammer return error; 5063cb132a0STamas Berghammer } 5073cb132a0STamas Berghammer 5088d94ba0fSJim Ingham ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread()); 5093cb132a0STamas Berghammer if (!thread_sp) 51097206d57SZachary Turner return Status("Selected thread isn't valid"); 5113cb132a0STamas Berghammer 5123cb132a0STamas Berghammer StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0)); 5133cb132a0STamas Berghammer if (!frame_sp) 51497206d57SZachary Turner return Status("Frame 0 isn't valid"); 5153cb132a0STamas Berghammer 5163cb132a0STamas Berghammer ExecutionContext exe_ctx; 5173cb132a0STamas Berghammer frame_sp->CalculateExecutionContext(exe_ctx); 5183cb132a0STamas Berghammer EvaluateExpressionOptions expr_options; 5193cb132a0STamas Berghammer expr_options.SetUnwindOnError(true); 5203cb132a0STamas Berghammer expr_options.SetIgnoreBreakpoints(true); 5213cb132a0STamas Berghammer expr_options.SetExecutionPolicy(eExecutionPolicyAlways); 5223cb132a0STamas Berghammer expr_options.SetLanguage(eLanguageTypeC_plus_plus); 523b9c1b51eSKate Stone expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so 524b9c1b51eSKate Stone // don't do the work to trap them. 5254c03ea14SAdrian Prantl expr_options.SetTimeout(process->GetUtilityExpressionTimeout()); 5263cb132a0STamas Berghammer 52797206d57SZachary Turner Status expr_error; 52802980825SJim Ingham ExpressionResults result = 529b9c1b51eSKate Stone UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix, 530b9c1b51eSKate Stone result_valobj_sp, expr_error); 53102980825SJim Ingham if (result != eExpressionCompleted) 53202980825SJim Ingham return expr_error; 53302980825SJim Ingham 5343cb132a0STamas Berghammer if (result_valobj_sp->GetError().Fail()) 5353cb132a0STamas Berghammer return result_valobj_sp->GetError(); 53697206d57SZachary Turner return Status(); 5373cb132a0STamas Berghammer } 5383cb132a0STamas Berghammer 539d10d3795SFrederic Riss std::unique_ptr<UtilityFunction> 5401ecb34f4SJim Ingham PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx, 541d10d3795SFrederic Riss Status &error) { 54205097246SAdrian Prantl // Remember to prepend this with the prefix from 54305097246SAdrian Prantl // GetLibdlFunctionDeclarations. The returned values are all in 54405097246SAdrian Prantl // __lldb_dlopen_result for consistency. The wrapper returns a void * but 54505097246SAdrian Prantl // doesn't use it because UtilityFunctions don't work with void returns at 54605097246SAdrian Prantl // present. 5474bd2bfb6SVedant Kumar // 5484bd2bfb6SVedant Kumar // Use lazy binding so as to not make dlopen()'s success conditional on 5494bd2bfb6SVedant Kumar // forcing every symbol in the library. 5504bd2bfb6SVedant Kumar // 5514bd2bfb6SVedant Kumar // In general, the debugger should allow programs to load & run with 5524bd2bfb6SVedant Kumar // libraries as far as they can, instead of defaulting to being super-picky 5534bd2bfb6SVedant Kumar // about unavailable symbols. 5544bd2bfb6SVedant Kumar // 5554bd2bfb6SVedant Kumar // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin 5564bd2bfb6SVedant Kumar // and other POSIX OSes. 5571ecb34f4SJim Ingham static const char *dlopen_wrapper_code = R"( 5584bd2bfb6SVedant Kumar const int RTLD_LAZY = 1; 5594bd2bfb6SVedant Kumar 5601ecb34f4SJim Ingham struct __lldb_dlopen_result { 5611ecb34f4SJim Ingham void *image_ptr; 5621ecb34f4SJim Ingham const char *error_str; 5631ecb34f4SJim Ingham }; 5641ecb34f4SJim Ingham 56533d74170SShafik Yaghmour extern "C" void *memcpy(void *, const void *, size_t size); 56633d74170SShafik Yaghmour extern "C" size_t strlen(const char *); 5670d231f71SJim Ingham 5680d231f71SJim Ingham 5690d231f71SJim Ingham void * __lldb_dlopen_wrapper (const char *name, 5700d231f71SJim Ingham const char *path_strings, 5710d231f71SJim Ingham char *buffer, 5721ecb34f4SJim Ingham __lldb_dlopen_result *result_ptr) 5731ecb34f4SJim Ingham { 5740d231f71SJim Ingham // This is the case where the name is the full path: 57503856dd9SJim Ingham if (!path_strings) { 5764bd2bfb6SVedant Kumar result_ptr->image_ptr = dlopen(name, RTLD_LAZY); 57703856dd9SJim Ingham if (result_ptr->image_ptr) 5780d231f71SJim Ingham result_ptr->error_str = nullptr; 579f7588597SJim Ingham else 580f7588597SJim Ingham result_ptr->error_str = dlerror(); 5810d231f71SJim Ingham return nullptr; 5820d231f71SJim Ingham } 5830d231f71SJim Ingham 5840d231f71SJim Ingham // This is the case where we have a list of paths: 5850d231f71SJim Ingham size_t name_len = strlen(name); 58603856dd9SJim Ingham while (path_strings && path_strings[0] != '\0') { 5870d231f71SJim Ingham size_t path_len = strlen(path_strings); 5880d231f71SJim Ingham memcpy((void *) buffer, (void *) path_strings, path_len); 5890d231f71SJim Ingham buffer[path_len] = '/'; 5900d231f71SJim Ingham char *target_ptr = buffer+path_len+1; 5910d231f71SJim Ingham memcpy((void *) target_ptr, (void *) name, name_len + 1); 5924bd2bfb6SVedant Kumar result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY); 59303856dd9SJim Ingham if (result_ptr->image_ptr) { 5940d231f71SJim Ingham result_ptr->error_str = nullptr; 5950d231f71SJim Ingham break; 5960d231f71SJim Ingham } 5971ecb34f4SJim Ingham result_ptr->error_str = dlerror(); 5980d231f71SJim Ingham path_strings = path_strings + path_len + 1; 5990d231f71SJim Ingham } 6001ecb34f4SJim Ingham return nullptr; 6011ecb34f4SJim Ingham } 6021ecb34f4SJim Ingham )"; 6031ecb34f4SJim Ingham 6041ecb34f4SJim Ingham static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper"; 6051ecb34f4SJim Ingham Process *process = exe_ctx.GetProcessSP().get(); 6061ecb34f4SJim Ingham // Insert the dlopen shim defines into our generic expression: 607adcd0268SBenjamin Kramer std::string expr(std::string(GetLibdlFunctionDeclarations(process))); 6081ecb34f4SJim Ingham expr.append(dlopen_wrapper_code); 6091ecb34f4SJim Ingham Status utility_error; 6101ecb34f4SJim Ingham DiagnosticManager diagnostics; 6111ecb34f4SJim Ingham 612de346cf2SJonas Devlieghere auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction( 61333d74170SShafik Yaghmour std::move(expr), dlopen_wrapper_name, eLanguageTypeC_plus_plus, exe_ctx); 614de346cf2SJonas Devlieghere if (!utility_fn_or_error) { 615de346cf2SJonas Devlieghere std::string error_str = llvm::toString(utility_fn_or_error.takeError()); 616de346cf2SJonas Devlieghere error.SetErrorStringWithFormat("dlopen error: could not create utility" 6171ecb34f4SJim Ingham "function: %s", 618de346cf2SJonas Devlieghere error_str.c_str()); 6191ecb34f4SJim Ingham return nullptr; 6201ecb34f4SJim Ingham } 621de346cf2SJonas Devlieghere std::unique_ptr<UtilityFunction> dlopen_utility_func_up = 622de346cf2SJonas Devlieghere std::move(*utility_fn_or_error); 6231ecb34f4SJim Ingham 6241ecb34f4SJim Ingham Value value; 6251ecb34f4SJim Ingham ValueList arguments; 6261ecb34f4SJim Ingham FunctionCaller *do_dlopen_function = nullptr; 6271ecb34f4SJim Ingham 6281ecb34f4SJim Ingham // Fetch the clang types we will need: 629594308c7SRaphael Isemann TypeSystemClang *ast = 630594308c7SRaphael Isemann ScratchTypeSystemClang::GetForTarget(process->GetTarget()); 6313031818aSAlex Langford if (!ast) 6323031818aSAlex Langford return nullptr; 6331ecb34f4SJim Ingham 6341ecb34f4SJim Ingham CompilerType clang_void_pointer_type 6351ecb34f4SJim Ingham = ast->GetBasicType(eBasicTypeVoid).GetPointerType(); 6361ecb34f4SJim Ingham CompilerType clang_char_pointer_type 6371ecb34f4SJim Ingham = ast->GetBasicType(eBasicTypeChar).GetPointerType(); 6381ecb34f4SJim Ingham 6390d231f71SJim Ingham // We are passing four arguments, the basename, the list of places to look, 6400d231f71SJim Ingham // a buffer big enough for all the path + name combos, and 6410d231f71SJim Ingham // a pointer to the storage we've made for the result: 642057efa99SAdrian Prantl value.SetValueType(Value::ValueType::Scalar); 6431ecb34f4SJim Ingham value.SetCompilerType(clang_void_pointer_type); 6441ecb34f4SJim Ingham arguments.PushValue(value); 6451ecb34f4SJim Ingham value.SetCompilerType(clang_char_pointer_type); 6461ecb34f4SJim Ingham arguments.PushValue(value); 6470d231f71SJim Ingham arguments.PushValue(value); 6480d231f71SJim Ingham arguments.PushValue(value); 6491ecb34f4SJim Ingham 6501ecb34f4SJim Ingham do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller( 6511ecb34f4SJim Ingham clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error); 6521ecb34f4SJim Ingham if (utility_error.Fail()) { 6531ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not make function" 6541ecb34f4SJim Ingham "caller: %s", utility_error.AsCString()); 6551ecb34f4SJim Ingham return nullptr; 6561ecb34f4SJim Ingham } 6571ecb34f4SJim Ingham 6581ecb34f4SJim Ingham do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller(); 6591ecb34f4SJim Ingham if (!do_dlopen_function) { 6601ecb34f4SJim Ingham error.SetErrorString("dlopen error: could not get function caller."); 6611ecb34f4SJim Ingham return nullptr; 6621ecb34f4SJim Ingham } 6631ecb34f4SJim Ingham 6641ecb34f4SJim Ingham // We made a good utility function, so cache it in the process: 665d10d3795SFrederic Riss return dlopen_utility_func_up; 6661ecb34f4SJim Ingham } 6671ecb34f4SJim Ingham 668b9c1b51eSKate Stone uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process, 6694fbd67acSTamas Berghammer const lldb_private::FileSpec &remote_file, 6700d231f71SJim Ingham const std::vector<std::string> *paths, 6710d231f71SJim Ingham lldb_private::Status &error, 6720d231f71SJim Ingham lldb_private::FileSpec *loaded_image) { 6730d231f71SJim Ingham if (loaded_image) 6740d231f71SJim Ingham loaded_image->Clear(); 6750d231f71SJim Ingham 6761ecb34f4SJim Ingham std::string path; 6771ecb34f4SJim Ingham path = remote_file.GetPath(); 6783cb132a0STamas Berghammer 6791ecb34f4SJim Ingham ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread(); 6801ecb34f4SJim Ingham if (!thread_sp) { 6811ecb34f4SJim Ingham error.SetErrorString("dlopen error: no thread available to call dlopen."); 6823cb132a0STamas Berghammer return LLDB_INVALID_IMAGE_TOKEN; 6833cb132a0STamas Berghammer } 6843cb132a0STamas Berghammer 6851ecb34f4SJim Ingham DiagnosticManager diagnostics; 6863cb132a0STamas Berghammer 6871ecb34f4SJim Ingham ExecutionContext exe_ctx; 6881ecb34f4SJim Ingham thread_sp->CalculateExecutionContext(exe_ctx); 6891ecb34f4SJim Ingham 6901ecb34f4SJim Ingham Status utility_error; 691d10d3795SFrederic Riss UtilityFunction *dlopen_utility_func; 6921ecb34f4SJim Ingham ValueList arguments; 6931ecb34f4SJim Ingham FunctionCaller *do_dlopen_function = nullptr; 6941ecb34f4SJim Ingham 695d10d3795SFrederic Riss // The UtilityFunction is held in the Process. Platforms don't track the 696d10d3795SFrederic Riss // lifespan of the Targets that use them, we can't put this in the Platform. 697d10d3795SFrederic Riss dlopen_utility_func = process->GetLoadImageUtilityFunction( 698d10d3795SFrederic Riss this, [&]() -> std::unique_ptr<UtilityFunction> { 699d10d3795SFrederic Riss return MakeLoadImageUtilityFunction(exe_ctx, error); 700d10d3795SFrederic Riss }); 7011ecb34f4SJim Ingham // If we couldn't make it, the error will be in error, so we can exit here. 7021ecb34f4SJim Ingham if (!dlopen_utility_func) 7031ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7041ecb34f4SJim Ingham 7051ecb34f4SJim Ingham do_dlopen_function = dlopen_utility_func->GetFunctionCaller(); 7061ecb34f4SJim Ingham if (!do_dlopen_function) { 7071ecb34f4SJim Ingham error.SetErrorString("dlopen error: could not get function caller."); 7081ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7091ecb34f4SJim Ingham } 7101ecb34f4SJim Ingham arguments = do_dlopen_function->GetArgumentValues(); 7111ecb34f4SJim Ingham 71205097246SAdrian Prantl // Now insert the path we are searching for and the result structure into the 71305097246SAdrian Prantl // target. 7141ecb34f4SJim Ingham uint32_t permissions = ePermissionsReadable|ePermissionsWritable; 7151ecb34f4SJim Ingham size_t path_len = path.size() + 1; 7161ecb34f4SJim Ingham lldb::addr_t path_addr = process->AllocateMemory(path_len, 7171ecb34f4SJim Ingham permissions, 7181ecb34f4SJim Ingham utility_error); 7191ecb34f4SJim Ingham if (path_addr == LLDB_INVALID_ADDRESS) { 7201ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not allocate memory" 7211ecb34f4SJim Ingham "for path: %s", utility_error.AsCString()); 7221ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7231ecb34f4SJim Ingham } 7241ecb34f4SJim Ingham 7251ecb34f4SJim Ingham // Make sure we deallocate the input string memory: 726e0ea8d87SJonas Devlieghere auto path_cleanup = llvm::make_scope_exit([process, path_addr] { 727e0ea8d87SJonas Devlieghere // Deallocate the buffer. 7281ecb34f4SJim Ingham process->DeallocateMemory(path_addr); 7291ecb34f4SJim Ingham }); 7301ecb34f4SJim Ingham 7311ecb34f4SJim Ingham process->WriteMemory(path_addr, path.c_str(), path_len, utility_error); 7321ecb34f4SJim Ingham if (utility_error.Fail()) { 7331ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not write path string:" 7341ecb34f4SJim Ingham " %s", utility_error.AsCString()); 7351ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7361ecb34f4SJim Ingham } 7371ecb34f4SJim Ingham 73805097246SAdrian Prantl // Make space for our return structure. It is two pointers big: the token 73905097246SAdrian Prantl // and the error string. 7401ecb34f4SJim Ingham const uint32_t addr_size = process->GetAddressByteSize(); 7411ecb34f4SJim Ingham lldb::addr_t return_addr = process->CallocateMemory(2*addr_size, 7421ecb34f4SJim Ingham permissions, 7431ecb34f4SJim Ingham utility_error); 7441ecb34f4SJim Ingham if (utility_error.Fail()) { 7451ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not allocate memory" 7461ecb34f4SJim Ingham "for path: %s", utility_error.AsCString()); 7471ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7481ecb34f4SJim Ingham } 7491ecb34f4SJim Ingham 7501ecb34f4SJim Ingham // Make sure we deallocate the result structure memory 751e0ea8d87SJonas Devlieghere auto return_cleanup = llvm::make_scope_exit([process, return_addr] { 752e0ea8d87SJonas Devlieghere // Deallocate the buffer 7531ecb34f4SJim Ingham process->DeallocateMemory(return_addr); 7541ecb34f4SJim Ingham }); 7551ecb34f4SJim Ingham 7560d231f71SJim Ingham // This will be the address of the storage for paths, if we are using them, 7570d231f71SJim Ingham // or nullptr to signal we aren't. 7580d231f71SJim Ingham lldb::addr_t path_array_addr = 0x0; 759e0ea8d87SJonas Devlieghere llvm::Optional<llvm::detail::scope_exit<std::function<void()>>> 760e0ea8d87SJonas Devlieghere path_array_cleanup; 7610d231f71SJim Ingham 7620d231f71SJim Ingham // This is the address to a buffer large enough to hold the largest path 7630d231f71SJim Ingham // conjoined with the library name we're passing in. This is a convenience 7640d231f71SJim Ingham // to avoid having to call malloc in the dlopen function. 7650d231f71SJim Ingham lldb::addr_t buffer_addr = 0x0; 766e0ea8d87SJonas Devlieghere llvm::Optional<llvm::detail::scope_exit<std::function<void()>>> 767e0ea8d87SJonas Devlieghere buffer_cleanup; 7680d231f71SJim Ingham 7691ecb34f4SJim Ingham // Set the values into our args and write them to the target: 7700d231f71SJim Ingham if (paths != nullptr) { 7710d231f71SJim Ingham // First insert the paths into the target. This is expected to be a 7720d231f71SJim Ingham // continuous buffer with the strings laid out null terminated and 7730d231f71SJim Ingham // end to end with an empty string terminating the buffer. 7740d231f71SJim Ingham // We also compute the buffer's required size as we go. 7750d231f71SJim Ingham size_t buffer_size = 0; 7760d231f71SJim Ingham std::string path_array; 7770d231f71SJim Ingham for (auto path : *paths) { 77840fa4a1aSJim Ingham // Don't insert empty paths, they will make us abort the path 77940fa4a1aSJim Ingham // search prematurely. 78040fa4a1aSJim Ingham if (path.empty()) 78140fa4a1aSJim Ingham continue; 7820d231f71SJim Ingham size_t path_size = path.size(); 7830d231f71SJim Ingham path_array.append(path); 7840d231f71SJim Ingham path_array.push_back('\0'); 7850d231f71SJim Ingham if (path_size > buffer_size) 7860d231f71SJim Ingham buffer_size = path_size; 7870d231f71SJim Ingham } 7880d231f71SJim Ingham path_array.push_back('\0'); 7890d231f71SJim Ingham 7900d231f71SJim Ingham path_array_addr = process->AllocateMemory(path_array.size(), 7910d231f71SJim Ingham permissions, 7920d231f71SJim Ingham utility_error); 7930d231f71SJim Ingham if (path_array_addr == LLDB_INVALID_ADDRESS) { 7940d231f71SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not allocate memory" 7950d231f71SJim Ingham "for path array: %s", 7960d231f71SJim Ingham utility_error.AsCString()); 7970d231f71SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 7980d231f71SJim Ingham } 7990d231f71SJim Ingham 8000d231f71SJim Ingham // Make sure we deallocate the paths array. 801e0ea8d87SJonas Devlieghere path_array_cleanup.emplace([process, path_array_addr]() { 802e0ea8d87SJonas Devlieghere // Deallocate the path array. 8030d231f71SJim Ingham process->DeallocateMemory(path_array_addr); 8040d231f71SJim Ingham }); 8050d231f71SJim Ingham 8060d231f71SJim Ingham process->WriteMemory(path_array_addr, path_array.data(), 8070d231f71SJim Ingham path_array.size(), utility_error); 8080d231f71SJim Ingham 8090d231f71SJim Ingham if (utility_error.Fail()) { 8100d231f71SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not write path array:" 8110d231f71SJim Ingham " %s", utility_error.AsCString()); 8120d231f71SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 8130d231f71SJim Ingham } 8140d231f71SJim Ingham // Now make spaces in the target for the buffer. We need to add one for 8150d231f71SJim Ingham // the '/' that the utility function will insert and one for the '\0': 8160d231f71SJim Ingham buffer_size += path.size() + 2; 8170d231f71SJim Ingham 8180d231f71SJim Ingham buffer_addr = process->AllocateMemory(buffer_size, 8190d231f71SJim Ingham permissions, 8200d231f71SJim Ingham utility_error); 8210d231f71SJim Ingham if (buffer_addr == LLDB_INVALID_ADDRESS) { 8220d231f71SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not allocate memory" 8230d231f71SJim Ingham "for buffer: %s", 8240d231f71SJim Ingham utility_error.AsCString()); 8250d231f71SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 8260d231f71SJim Ingham } 8270d231f71SJim Ingham 8280d231f71SJim Ingham // Make sure we deallocate the buffer memory: 829e0ea8d87SJonas Devlieghere buffer_cleanup.emplace([process, buffer_addr]() { 830e0ea8d87SJonas Devlieghere // Deallocate the buffer. 8310d231f71SJim Ingham process->DeallocateMemory(buffer_addr); 8320d231f71SJim Ingham }); 8330d231f71SJim Ingham } 8340d231f71SJim Ingham 8351ecb34f4SJim Ingham arguments.GetValueAtIndex(0)->GetScalar() = path_addr; 8360d231f71SJim Ingham arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr; 8370d231f71SJim Ingham arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr; 8380d231f71SJim Ingham arguments.GetValueAtIndex(3)->GetScalar() = return_addr; 8391ecb34f4SJim Ingham 8401ecb34f4SJim Ingham lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS; 8411ecb34f4SJim Ingham 8421ecb34f4SJim Ingham diagnostics.Clear(); 8431ecb34f4SJim Ingham if (!do_dlopen_function->WriteFunctionArguments(exe_ctx, 8441ecb34f4SJim Ingham func_args_addr, 8451ecb34f4SJim Ingham arguments, 8461ecb34f4SJim Ingham diagnostics)) { 8471ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not write function " 8481ecb34f4SJim Ingham "arguments: %s", 8491ecb34f4SJim Ingham diagnostics.GetString().c_str()); 8501ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 8511ecb34f4SJim Ingham } 8521ecb34f4SJim Ingham 8531ecb34f4SJim Ingham // Make sure we clean up the args structure. We can't reuse it because the 8541ecb34f4SJim Ingham // Platform lives longer than the process and the Platforms don't get a 8551ecb34f4SJim Ingham // signal to clean up cached data when a process goes away. 856e0ea8d87SJonas Devlieghere auto args_cleanup = 857e0ea8d87SJonas Devlieghere llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] { 8581ecb34f4SJim Ingham do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr); 8591ecb34f4SJim Ingham }); 8601ecb34f4SJim Ingham 8611ecb34f4SJim Ingham // Now run the caller: 8621ecb34f4SJim Ingham EvaluateExpressionOptions options; 8631ecb34f4SJim Ingham options.SetExecutionPolicy(eExecutionPolicyAlways); 8641ecb34f4SJim Ingham options.SetLanguage(eLanguageTypeC_plus_plus); 8651ecb34f4SJim Ingham options.SetIgnoreBreakpoints(true); 8661ecb34f4SJim Ingham options.SetUnwindOnError(true); 8671ecb34f4SJim Ingham options.SetTrapExceptions(false); // dlopen can't throw exceptions, so 8681ecb34f4SJim Ingham // don't do the work to trap them. 8694c03ea14SAdrian Prantl options.SetTimeout(process->GetUtilityExpressionTimeout()); 870c01783a8SRaphael Isemann options.SetIsForUtilityExpr(true); 8711ecb34f4SJim Ingham 8721ecb34f4SJim Ingham Value return_value; 8731ecb34f4SJim Ingham // Fetch the clang types we will need: 874594308c7SRaphael Isemann TypeSystemClang *ast = 875594308c7SRaphael Isemann ScratchTypeSystemClang::GetForTarget(process->GetTarget()); 8763031818aSAlex Langford if (!ast) { 8776e3b0cc2SRaphael Isemann error.SetErrorString("dlopen error: Unable to get TypeSystemClang"); 8783031818aSAlex Langford return LLDB_INVALID_IMAGE_TOKEN; 8793031818aSAlex Langford } 8801ecb34f4SJim Ingham 8811ecb34f4SJim Ingham CompilerType clang_void_pointer_type 8821ecb34f4SJim Ingham = ast->GetBasicType(eBasicTypeVoid).GetPointerType(); 8831ecb34f4SJim Ingham 8841ecb34f4SJim Ingham return_value.SetCompilerType(clang_void_pointer_type); 8851ecb34f4SJim Ingham 8861ecb34f4SJim Ingham ExpressionResults results = do_dlopen_function->ExecuteFunction( 8871ecb34f4SJim Ingham exe_ctx, &func_args_addr, options, diagnostics, return_value); 8881ecb34f4SJim Ingham if (results != eExpressionCompleted) { 8890d231f71SJim Ingham error.SetErrorStringWithFormat("dlopen error: failed executing " 8901ecb34f4SJim Ingham "dlopen wrapper function: %s", 8911ecb34f4SJim Ingham diagnostics.GetString().c_str()); 8921ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 8931ecb34f4SJim Ingham } 8941ecb34f4SJim Ingham 8951ecb34f4SJim Ingham // Read the dlopen token from the return area: 8961ecb34f4SJim Ingham lldb::addr_t token = process->ReadPointerFromMemory(return_addr, 8971ecb34f4SJim Ingham utility_error); 8981ecb34f4SJim Ingham if (utility_error.Fail()) { 8991ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not read the return " 9001ecb34f4SJim Ingham "struct: %s", utility_error.AsCString()); 9011ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 9021ecb34f4SJim Ingham } 9031ecb34f4SJim Ingham 9041ecb34f4SJim Ingham // The dlopen succeeded! 9050d231f71SJim Ingham if (token != 0x0) { 9060d231f71SJim Ingham if (loaded_image && buffer_addr != 0x0) 9070d231f71SJim Ingham { 9080d231f71SJim Ingham // Capture the image which was loaded. We leave it in the buffer on 9090d231f71SJim Ingham // exit from the dlopen function, so we can just read it from there: 9100d231f71SJim Ingham std::string name_string; 9110d231f71SJim Ingham process->ReadCStringFromMemory(buffer_addr, name_string, utility_error); 9120d231f71SJim Ingham if (utility_error.Success()) 9138f3be7a3SJonas Devlieghere loaded_image->SetFile(name_string, llvm::sys::path::Style::posix); 9140d231f71SJim Ingham } 9151ecb34f4SJim Ingham return process->AddImageToken(token); 9160d231f71SJim Ingham } 9171ecb34f4SJim Ingham 9181ecb34f4SJim Ingham // We got an error, lets read in the error string: 9191ecb34f4SJim Ingham std::string dlopen_error_str; 9201ecb34f4SJim Ingham lldb::addr_t error_addr 9211ecb34f4SJim Ingham = process->ReadPointerFromMemory(return_addr + addr_size, utility_error); 9221ecb34f4SJim Ingham if (utility_error.Fail()) { 9231ecb34f4SJim Ingham error.SetErrorStringWithFormat("dlopen error: could not read error string: " 9241ecb34f4SJim Ingham "%s", utility_error.AsCString()); 9251ecb34f4SJim Ingham return LLDB_INVALID_IMAGE_TOKEN; 9261ecb34f4SJim Ingham } 9271ecb34f4SJim Ingham 9281ecb34f4SJim Ingham size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size, 9291ecb34f4SJim Ingham dlopen_error_str, 9301ecb34f4SJim Ingham utility_error); 9311ecb34f4SJim Ingham if (utility_error.Success() && num_chars > 0) 932b9c1b51eSKate Stone error.SetErrorStringWithFormat("dlopen error: %s", 9331ecb34f4SJim Ingham dlopen_error_str.c_str()); 9343cb132a0STamas Berghammer else 9353cb132a0STamas Berghammer error.SetErrorStringWithFormat("dlopen failed for unknown reasons."); 9361ecb34f4SJim Ingham 9373cb132a0STamas Berghammer return LLDB_INVALID_IMAGE_TOKEN; 9383cb132a0STamas Berghammer } 9393cb132a0STamas Berghammer 94097206d57SZachary Turner Status PlatformPOSIX::UnloadImage(lldb_private::Process *process, 941b9c1b51eSKate Stone uint32_t image_token) { 9423cb132a0STamas Berghammer const addr_t image_addr = process->GetImagePtrFromToken(image_token); 9433cb132a0STamas Berghammer if (image_addr == LLDB_INVALID_ADDRESS) 94497206d57SZachary Turner return Status("Invalid image token"); 9453cb132a0STamas Berghammer 9463cb132a0STamas Berghammer StreamString expr; 9473cb132a0STamas Berghammer expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr); 948f7a5851dSNitesh Jain llvm::StringRef prefix = GetLibdlFunctionDeclarations(process); 9493cb132a0STamas Berghammer lldb::ValueObjectSP result_valobj_sp; 95097206d57SZachary Turner Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix, 951b9c1b51eSKate Stone result_valobj_sp); 9523cb132a0STamas Berghammer if (error.Fail()) 9533cb132a0STamas Berghammer return error; 9543cb132a0STamas Berghammer 9553cb132a0STamas Berghammer if (result_valobj_sp->GetError().Fail()) 9563cb132a0STamas Berghammer return result_valobj_sp->GetError(); 9573cb132a0STamas Berghammer 9583cb132a0STamas Berghammer Scalar scalar; 959b9c1b51eSKate Stone if (result_valobj_sp->ResolveValue(scalar)) { 9603cb132a0STamas Berghammer if (scalar.UInt(1)) 96197206d57SZachary Turner return Status("expression failed: \"%s\"", expr.GetData()); 9623cb132a0STamas Berghammer process->ResetImageToken(image_token); 9633cb132a0STamas Berghammer } 96497206d57SZachary Turner return Status(); 9653cb132a0STamas Berghammer } 966fcdde63fSTamas Berghammer 967f7a5851dSNitesh Jain llvm::StringRef 968f7a5851dSNitesh Jain PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) { 969fcdde63fSTamas Berghammer return R"( 970fcdde63fSTamas Berghammer extern "C" void* dlopen(const char*, int); 971fcdde63fSTamas Berghammer extern "C" void* dlsym(void*, const char*); 972fcdde63fSTamas Berghammer extern "C" int dlclose(void*); 973fcdde63fSTamas Berghammer extern "C" char* dlerror(void); 974fcdde63fSTamas Berghammer )"; 975fcdde63fSTamas Berghammer } 976ccd6cffbSTamas Berghammer 977ec9bc8ccSPavel Labath ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) { 978ec9bc8ccSPavel Labath if (basename.IsEmpty()) 979ec9bc8ccSPavel Labath return basename; 980ec9bc8ccSPavel Labath 981ec9bc8ccSPavel Labath StreamString stream; 982ec9bc8ccSPavel Labath stream.Printf("lib%s.so", basename.GetCString()); 983ec9bc8ccSPavel Labath return ConstString(stream.GetString()); 984ec9bc8ccSPavel Labath } 985