1 //===-- PlatformRemoteGDBServer.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
12 #include "PlatformRemoteGDBServer.h"
13 #include "lldb/Host/Config.h"
16 // Other libraries and framework includes
18 #include "lldb/Breakpoint/BreakpointLocation.h"
19 #include "lldb/Core/ConnectionFileDescriptor.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/Error.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/ModuleList.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Host/FileSpec.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/Target.h"
33 using namespace lldb_private;
35 static bool g_initialized = false;
38 PlatformRemoteGDBServer::Initialize ()
40 if (g_initialized == false)
43 PluginManager::RegisterPlugin (PlatformRemoteGDBServer::GetPluginNameStatic(),
44 PlatformRemoteGDBServer::GetDescriptionStatic(),
45 PlatformRemoteGDBServer::CreateInstance);
50 PlatformRemoteGDBServer::Terminate ()
54 g_initialized = false;
55 PluginManager::UnregisterPlugin (PlatformRemoteGDBServer::CreateInstance);
60 PlatformRemoteGDBServer::CreateInstance (bool force, const lldb_private::ArchSpec *arch)
65 create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
68 return new PlatformRemoteGDBServer ();
73 lldb_private::ConstString
74 PlatformRemoteGDBServer::GetPluginNameStatic()
76 static ConstString g_name("remote-gdb-server");
81 PlatformRemoteGDBServer::GetDescriptionStatic()
83 return "A platform that uses the GDB remote protocol as the communication transport.";
87 PlatformRemoteGDBServer::GetDescription ()
89 if (m_platform_description.empty())
93 // Send the get description packet
97 if (!m_platform_description.empty())
98 return m_platform_description.c_str();
99 return GetDescriptionStatic();
103 PlatformRemoteGDBServer::ResolveExecutable (const FileSpec &exe_file,
104 const ArchSpec &exe_arch,
105 lldb::ModuleSP &exe_module_sp,
106 const FileSpecList *module_search_paths_ptr)
109 //error.SetErrorString ("PlatformRemoteGDBServer::ResolveExecutable() is unimplemented");
110 if (m_gdb_client.GetFileExists(exe_file))
112 // TODO: get the remote end to somehow resolve this file
113 error.SetErrorString("file not found on remote end");
118 PlatformRemoteGDBServer::GetFileWithUUID (const FileSpec &platform_file,
119 const UUID *uuid_ptr,
120 FileSpec &local_file)
122 // Default to the local case
123 local_file = platform_file;
127 //------------------------------------------------------------------
128 /// Default Constructor
129 //------------------------------------------------------------------
130 PlatformRemoteGDBServer::PlatformRemoteGDBServer () :
131 Platform(false), // This is a remote platform
136 //------------------------------------------------------------------
139 /// The destructor is virtual since this class is designed to be
140 /// inherited from by the plug-in instance.
141 //------------------------------------------------------------------
142 PlatformRemoteGDBServer::~PlatformRemoteGDBServer()
147 PlatformRemoteGDBServer::GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch)
153 PlatformRemoteGDBServer::GetSoftwareBreakpointTrapOpcode (Target &target, BreakpointSite *bp_site)
155 // This isn't needed if the z/Z packets are supported in the GDB remote
156 // server. But we might need a packet to detect this.
161 PlatformRemoteGDBServer::GetRemoteOSVersion ()
163 uint32_t major, minor, update;
164 if (m_gdb_client.GetOSVersion (major, minor, update))
166 m_major_os_version = major;
167 m_minor_os_version = minor;
168 m_update_os_version = update;
175 PlatformRemoteGDBServer::GetRemoteOSBuildString (std::string &s)
177 return m_gdb_client.GetOSBuildString (s);
181 PlatformRemoteGDBServer::GetRemoteOSKernelDescription (std::string &s)
183 return m_gdb_client.GetOSKernelDescription (s);
186 // Remote Platform subclasses need to override this function
188 PlatformRemoteGDBServer::GetRemoteSystemArchitecture ()
190 return m_gdb_client.GetSystemArchitecture();
193 lldb_private::ConstString
194 PlatformRemoteGDBServer::GetRemoteWorkingDirectory()
198 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
200 if (m_gdb_client.GetWorkingDir(cwd))
202 ConstString working_dir(cwd.c_str());
204 log->Printf("PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'", working_dir.GetCString());
209 return ConstString();
214 return Platform::GetRemoteWorkingDirectory();
219 PlatformRemoteGDBServer::SetRemoteWorkingDirectory(const lldb_private::ConstString &path)
223 // Clear the working directory it case it doesn't get set correctly. This will
224 // for use to re-read it
225 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
227 log->Printf("PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')", path.GetCString());
228 return m_gdb_client.SetWorkingDir(path.GetCString()) == 0;
231 return Platform::SetRemoteWorkingDirectory(path);
235 PlatformRemoteGDBServer::IsConnected () const
237 return m_gdb_client.IsConnected();
241 PlatformRemoteGDBServer::ConnectRemote (Args& args)
246 error.SetErrorStringWithFormat ("the platform is already connected to '%s', execute 'platform disconnect' to close the current connection",
251 if (args.GetArgumentCount() == 1)
253 const char *url = args.GetArgumentAtIndex(0);
254 m_gdb_client.SetConnection (new ConnectionFileDescriptor());
255 const ConnectionStatus status = m_gdb_client.Connect(url, &error);
256 if (status == eConnectionStatusSuccess)
258 if (m_gdb_client.HandshakeWithServer(&error))
260 m_gdb_client.GetHostInfo();
261 // If a working directory was set prior to connecting, send it down now
263 m_gdb_client.SetWorkingDir(m_working_dir.GetCString());
267 m_gdb_client.Disconnect();
269 error.SetErrorString("handshake failed");
275 error.SetErrorString ("\"platform connect\" takes a single argument: <connect-url>");
283 PlatformRemoteGDBServer::DisconnectRemote ()
286 m_gdb_client.Disconnect(&error);
291 PlatformRemoteGDBServer::GetHostname ()
293 m_gdb_client.GetHostname (m_name);
296 return m_name.c_str();
300 PlatformRemoteGDBServer::GetUserName (uint32_t uid)
302 // Try and get a cache user name first
303 const char *cached_user_name = Platform::GetUserName(uid);
304 if (cached_user_name)
305 return cached_user_name;
307 if (m_gdb_client.GetUserName(uid, name))
308 return SetCachedUserName(uid, name.c_str(), name.size());
310 SetUserNameNotFound(uid); // Negative cache so we don't keep sending packets
315 PlatformRemoteGDBServer::GetGroupName (uint32_t gid)
317 const char *cached_group_name = Platform::GetGroupName(gid);
318 if (cached_group_name)
319 return cached_group_name;
321 if (m_gdb_client.GetGroupName(gid, name))
322 return SetCachedGroupName(gid, name.c_str(), name.size());
324 SetGroupNameNotFound(gid); // Negative cache so we don't keep sending packets
329 PlatformRemoteGDBServer::FindProcesses (const ProcessInstanceInfoMatch &match_info,
330 ProcessInstanceInfoList &process_infos)
332 return m_gdb_client.FindProcesses (match_info, process_infos);
336 PlatformRemoteGDBServer::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
338 return m_gdb_client.GetProcessInfo (pid, process_info);
343 PlatformRemoteGDBServer::LaunchProcess (ProcessLaunchInfo &launch_info)
345 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
347 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
350 log->Printf ("PlatformRemoteGDBServer::%s() called", __FUNCTION__);
352 m_gdb_client.SetSTDIN ("/dev/null");
353 m_gdb_client.SetSTDOUT ("/dev/null");
354 m_gdb_client.SetSTDERR ("/dev/null");
355 m_gdb_client.SetDisableASLR (launch_info.GetFlags().Test (eLaunchFlagDisableASLR));
356 m_gdb_client.SetDetachOnError (launch_info.GetFlags().Test (eLaunchFlagDetachOnError));
358 const char *working_dir = launch_info.GetWorkingDirectory();
359 if (working_dir && working_dir[0])
361 m_gdb_client.SetWorkingDir (working_dir);
364 // Send the environment and the program + arguments after we connect
365 const char **envp = launch_info.GetEnvironmentEntries().GetConstArgumentVector();
369 const char *env_entry;
370 for (int i=0; (env_entry = envp[i]); ++i)
372 if (m_gdb_client.SendEnvironmentPacket(env_entry) != 0)
377 ArchSpec arch_spec = launch_info.GetArchitecture();
378 const char *arch_triple = arch_spec.GetTriple().str().c_str();
380 m_gdb_client.SendLaunchArchPacket(arch_triple);
382 log->Printf ("PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'", __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
384 const uint32_t old_packet_timeout = m_gdb_client.SetPacketTimeout (5);
385 int arg_packet_err = m_gdb_client.SendArgumentsPacket (launch_info);
386 m_gdb_client.SetPacketTimeout (old_packet_timeout);
387 if (arg_packet_err == 0)
389 std::string error_str;
390 if (m_gdb_client.GetLaunchSuccess (error_str))
392 pid = m_gdb_client.GetCurrentProcessID ();
393 if (pid != LLDB_INVALID_PROCESS_ID)
395 launch_info.SetProcessID (pid);
397 log->Printf ("PlatformRemoteGDBServer::%s() pid %" PRIu64 " launched successfully", __FUNCTION__, pid);
402 log->Printf ("PlatformRemoteGDBServer::%s() launch succeeded but we didn't get a valid process id back!", __FUNCTION__);
403 // FIXME isn't this an error condition? Do we need to set an error here? Check with Greg.
408 error.SetErrorString (error_str.c_str());
410 log->Printf ("PlatformRemoteGDBServer::%s() launch failed: %s", __FUNCTION__, error.AsCString ());
415 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
421 PlatformRemoteGDBServer::DebugProcess (lldb_private::ProcessLaunchInfo &launch_info,
422 lldb_private::Debugger &debugger,
423 lldb_private::Target *target, // Can be NULL, if NULL create a new target, else use existing one
424 lldb_private::Listener &listener,
425 lldb_private::Error &error)
427 lldb::ProcessSP process_sp;
432 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
433 ArchSpec remote_arch = GetRemoteSystemArchitecture();
434 llvm::Triple &remote_triple = remote_arch.GetTriple();
436 if (remote_triple.getVendor() == llvm::Triple::Apple && remote_triple.getOS() == llvm::Triple::IOS)
438 // When remote debugging to iOS, we use a USB mux that always talks
439 // to localhost, so we will need the remote debugserver to accept connections
440 // only from localhost, no matter what our current hostname is
441 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, "127.0.0.1");
445 // All other hosts should use their actual hostname
446 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, NULL);
451 error.SetErrorStringWithFormat ("unable to launch a GDB server on '%s'", GetHostname ());
457 TargetSP new_target_sp;
459 error = debugger.GetTargetList().CreateTarget (debugger,
465 target = new_target_sp.get();
470 if (target && error.Success())
472 debugger.GetTargetList().SetSelectedTarget(target);
474 // The darwin always currently uses the GDB remote debugger plug-in
475 // so even when debugging locally we are debugging remotely!
476 process_sp = target->CreateProcess (listener, "gdb-remote", NULL);
480 char connect_url[256];
481 const char *override_hostname = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
482 const char *port_offset_c_str = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
483 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
484 const int connect_url_len = ::snprintf (connect_url,
487 override_hostname ? override_hostname : GetHostname (),
489 assert (connect_url_len < (int)sizeof(connect_url));
490 error = process_sp->ConnectRemote (NULL, connect_url);
492 error = process_sp->Launch(launch_info);
493 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
494 m_gdb_client.KillSpawnedProcess(debugserver_pid);
501 error.SetErrorString("not connected to remote gdb server");
509 PlatformRemoteGDBServer::Attach (lldb_private::ProcessAttachInfo &attach_info,
511 Target *target, // Can be NULL, if NULL create a new target, else use existing one
515 lldb::ProcessSP process_sp;
520 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
521 ArchSpec remote_arch = GetRemoteSystemArchitecture();
522 llvm::Triple &remote_triple = remote_arch.GetTriple();
524 if (remote_triple.getVendor() == llvm::Triple::Apple && remote_triple.getOS() == llvm::Triple::IOS)
526 // When remote debugging to iOS, we use a USB mux that always talks
527 // to localhost, so we will need the remote debugserver to accept connections
528 // only from localhost, no matter what our current hostname is
529 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, "127.0.0.1");
533 // All other hosts should use their actual hostname
534 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, NULL);
539 error.SetErrorStringWithFormat ("unable to launch a GDB server on '%s'", GetHostname ());
545 TargetSP new_target_sp;
547 error = debugger.GetTargetList().CreateTarget (debugger,
553 target = new_target_sp.get();
558 if (target && error.Success())
560 debugger.GetTargetList().SetSelectedTarget(target);
562 // The darwin always currently uses the GDB remote debugger plug-in
563 // so even when debugging locally we are debugging remotely!
564 process_sp = target->CreateProcess (listener, "gdb-remote", NULL);
568 char connect_url[256];
569 const char *override_hostname = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
570 const char *port_offset_c_str = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
571 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
572 const int connect_url_len = ::snprintf (connect_url,
575 override_hostname ? override_hostname : GetHostname (),
577 assert (connect_url_len < (int)sizeof(connect_url));
578 error = process_sp->ConnectRemote (NULL, connect_url);
580 error = process_sp->Attach(attach_info);
581 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
583 m_gdb_client.KillSpawnedProcess(debugserver_pid);
591 error.SetErrorString("not connected to remote gdb server");
598 PlatformRemoteGDBServer::MakeDirectory (const char *path, uint32_t mode)
600 Error error = m_gdb_client.MakeDirectory(path,mode);
601 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
603 log->Printf ("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) error = %u (%s)", path, mode, error.GetError(), error.AsCString());
609 PlatformRemoteGDBServer::GetFilePermissions (const char *path, uint32_t &file_permissions)
611 Error error = m_gdb_client.GetFilePermissions(path, file_permissions);
612 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
614 log->Printf ("PlatformRemoteGDBServer::GetFilePermissions(path='%s', file_permissions=%o) error = %u (%s)", path, file_permissions, error.GetError(), error.AsCString());
619 PlatformRemoteGDBServer::SetFilePermissions (const char *path, uint32_t file_permissions)
621 Error error = m_gdb_client.SetFilePermissions(path, file_permissions);
622 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
624 log->Printf ("PlatformRemoteGDBServer::SetFilePermissions(path='%s', file_permissions=%o) error = %u (%s)", path, file_permissions, error.GetError(), error.AsCString());
630 PlatformRemoteGDBServer::OpenFile (const lldb_private::FileSpec& file_spec,
635 return m_gdb_client.OpenFile (file_spec, flags, mode, error);
639 PlatformRemoteGDBServer::CloseFile (lldb::user_id_t fd, Error &error)
641 return m_gdb_client.CloseFile (fd, error);
645 PlatformRemoteGDBServer::GetFileSize (const lldb_private::FileSpec& file_spec)
647 return m_gdb_client.GetFileSize(file_spec);
651 PlatformRemoteGDBServer::ReadFile (lldb::user_id_t fd,
657 return m_gdb_client.ReadFile (fd, offset, dst, dst_len, error);
661 PlatformRemoteGDBServer::WriteFile (lldb::user_id_t fd,
667 return m_gdb_client.WriteFile (fd, offset, src, src_len, error);
671 PlatformRemoteGDBServer::PutFile (const lldb_private::FileSpec& source,
672 const lldb_private::FileSpec& destination,
676 return Platform::PutFile(source,destination,uid,gid);
680 PlatformRemoteGDBServer::CreateSymlink (const char *src, // The name of the link is in src
681 const char *dst) // The symlink points to dst
683 Error error = m_gdb_client.CreateSymlink (src, dst);
684 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
686 log->Printf ("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') error = %u (%s)", src, dst, error.GetError(), error.AsCString());
691 PlatformRemoteGDBServer::Unlink (const char *path)
693 Error error = m_gdb_client.Unlink (path);
694 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
696 log->Printf ("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)", path, error.GetError(), error.AsCString());
701 PlatformRemoteGDBServer::GetFileExists (const lldb_private::FileSpec& file_spec)
703 return m_gdb_client.GetFileExists (file_spec);
707 PlatformRemoteGDBServer::RunShellCommand (const char *command, // Shouldn't be NULL
708 const char *working_dir, // Pass NULL to use the current working directory
709 int *status_ptr, // Pass NULL if you don't want the process exit status
710 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
711 std::string *command_output, // Pass NULL if you don't want the command output
712 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
714 return m_gdb_client.RunShellCommand (command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec);
718 PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames ()
720 m_trap_handlers.push_back (ConstString ("_sigtramp"));