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/Debugger.h"
20 #include "lldb/Core/Error.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/ModuleList.h"
24 #include "lldb/Core/ModuleSpec.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Host/ConnectionFileDescriptor.h"
28 #include "lldb/Host/FileSpec.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/Target.h"
34 using namespace lldb_private;
36 static bool g_initialized = false;
39 PlatformRemoteGDBServer::Initialize ()
41 if (g_initialized == false)
44 PluginManager::RegisterPlugin (PlatformRemoteGDBServer::GetPluginNameStatic(),
45 PlatformRemoteGDBServer::GetDescriptionStatic(),
46 PlatformRemoteGDBServer::CreateInstance);
51 PlatformRemoteGDBServer::Terminate ()
55 g_initialized = false;
56 PluginManager::UnregisterPlugin (PlatformRemoteGDBServer::CreateInstance);
61 PlatformRemoteGDBServer::CreateInstance (bool force, const lldb_private::ArchSpec *arch)
66 create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
69 return PlatformSP(new PlatformRemoteGDBServer());
74 lldb_private::ConstString
75 PlatformRemoteGDBServer::GetPluginNameStatic()
77 static ConstString g_name("remote-gdb-server");
82 PlatformRemoteGDBServer::GetDescriptionStatic()
84 return "A platform that uses the GDB remote protocol as the communication transport.";
88 PlatformRemoteGDBServer::GetDescription ()
90 if (m_platform_description.empty())
94 // Send the get description packet
98 if (!m_platform_description.empty())
99 return m_platform_description.c_str();
100 return GetDescriptionStatic();
104 PlatformRemoteGDBServer::ResolveExecutable (const ModuleSpec &module_spec,
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(module_spec.GetFileSpec()))
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::Error &error)
426 lldb::ProcessSP process_sp;
431 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
432 ArchSpec remote_arch = GetRemoteSystemArchitecture();
433 llvm::Triple &remote_triple = remote_arch.GetTriple();
435 if (remote_triple.getVendor() == llvm::Triple::Apple && remote_triple.getOS() == llvm::Triple::IOS)
437 // When remote debugging to iOS, we use a USB mux that always talks
438 // to localhost, so we will need the remote debugserver to accept connections
439 // only from localhost, no matter what our current hostname is
440 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, "127.0.0.1");
444 // All other hosts should use their actual hostname
445 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, NULL);
450 error.SetErrorStringWithFormat ("unable to launch a GDB server on '%s'", GetHostname ());
456 TargetSP new_target_sp;
458 error = debugger.GetTargetList().CreateTarget (debugger,
464 target = new_target_sp.get();
469 if (target && error.Success())
471 debugger.GetTargetList().SetSelectedTarget(target);
473 // The darwin always currently uses the GDB remote debugger plug-in
474 // so even when debugging locally we are debugging remotely!
475 process_sp = target->CreateProcess (launch_info.GetListenerForProcess(debugger), "gdb-remote", NULL);
479 char connect_url[256];
480 const char *override_hostname = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
481 const char *port_offset_c_str = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
482 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
483 const int connect_url_len = ::snprintf (connect_url,
486 override_hostname ? override_hostname : GetHostname (),
488 assert (connect_url_len < (int)sizeof(connect_url));
489 error = process_sp->ConnectRemote (NULL, connect_url);
490 // Retry the connect remote one time...
492 error = process_sp->ConnectRemote (NULL, connect_url);
494 error = process_sp->Launch(launch_info);
495 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
497 printf ("error: connect remote failed (%s)\n", error.AsCString());
498 m_gdb_client.KillSpawnedProcess(debugserver_pid);
506 error.SetErrorString("not connected to remote gdb server");
514 PlatformRemoteGDBServer::Attach (lldb_private::ProcessAttachInfo &attach_info,
516 Target *target, // Can be NULL, if NULL create a new target, else use existing one
519 lldb::ProcessSP process_sp;
524 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
525 ArchSpec remote_arch = GetRemoteSystemArchitecture();
526 llvm::Triple &remote_triple = remote_arch.GetTriple();
528 if (remote_triple.getVendor() == llvm::Triple::Apple && remote_triple.getOS() == llvm::Triple::IOS)
530 // When remote debugging to iOS, we use a USB mux that always talks
531 // to localhost, so we will need the remote debugserver to accept connections
532 // only from localhost, no matter what our current hostname is
533 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, "127.0.0.1");
537 // All other hosts should use their actual hostname
538 port = m_gdb_client.LaunchGDBserverAndGetPort(debugserver_pid, NULL);
543 error.SetErrorStringWithFormat ("unable to launch a GDB server on '%s'", GetHostname ());
549 TargetSP new_target_sp;
551 error = debugger.GetTargetList().CreateTarget (debugger,
557 target = new_target_sp.get();
562 if (target && error.Success())
564 debugger.GetTargetList().SetSelectedTarget(target);
566 // The darwin always currently uses the GDB remote debugger plug-in
567 // so even when debugging locally we are debugging remotely!
568 process_sp = target->CreateProcess (attach_info.GetListenerForProcess(debugger), "gdb-remote", NULL);
572 char connect_url[256];
573 const char *override_hostname = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
574 const char *port_offset_c_str = getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
575 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
576 const int connect_url_len = ::snprintf (connect_url,
579 override_hostname ? override_hostname : GetHostname (),
581 assert (connect_url_len < (int)sizeof(connect_url));
582 error = process_sp->ConnectRemote (NULL, connect_url);
584 error = process_sp->Attach(attach_info);
585 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
587 m_gdb_client.KillSpawnedProcess(debugserver_pid);
595 error.SetErrorString("not connected to remote gdb server");
602 PlatformRemoteGDBServer::MakeDirectory (const char *path, uint32_t mode)
604 Error error = m_gdb_client.MakeDirectory(path,mode);
605 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
607 log->Printf ("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) error = %u (%s)", path, mode, error.GetError(), error.AsCString());
613 PlatformRemoteGDBServer::GetFilePermissions (const char *path, uint32_t &file_permissions)
615 Error error = m_gdb_client.GetFilePermissions(path, file_permissions);
616 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
618 log->Printf ("PlatformRemoteGDBServer::GetFilePermissions(path='%s', file_permissions=%o) error = %u (%s)", path, file_permissions, error.GetError(), error.AsCString());
623 PlatformRemoteGDBServer::SetFilePermissions (const char *path, uint32_t file_permissions)
625 Error error = m_gdb_client.SetFilePermissions(path, file_permissions);
626 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
628 log->Printf ("PlatformRemoteGDBServer::SetFilePermissions(path='%s', file_permissions=%o) error = %u (%s)", path, file_permissions, error.GetError(), error.AsCString());
634 PlatformRemoteGDBServer::OpenFile (const lldb_private::FileSpec& file_spec,
639 return m_gdb_client.OpenFile (file_spec, flags, mode, error);
643 PlatformRemoteGDBServer::CloseFile (lldb::user_id_t fd, Error &error)
645 return m_gdb_client.CloseFile (fd, error);
649 PlatformRemoteGDBServer::GetFileSize (const lldb_private::FileSpec& file_spec)
651 return m_gdb_client.GetFileSize(file_spec);
655 PlatformRemoteGDBServer::ReadFile (lldb::user_id_t fd,
661 return m_gdb_client.ReadFile (fd, offset, dst, dst_len, error);
665 PlatformRemoteGDBServer::WriteFile (lldb::user_id_t fd,
671 return m_gdb_client.WriteFile (fd, offset, src, src_len, error);
675 PlatformRemoteGDBServer::PutFile (const lldb_private::FileSpec& source,
676 const lldb_private::FileSpec& destination,
680 return Platform::PutFile(source,destination,uid,gid);
684 PlatformRemoteGDBServer::CreateSymlink (const char *src, // The name of the link is in src
685 const char *dst) // The symlink points to dst
687 Error error = m_gdb_client.CreateSymlink (src, dst);
688 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
690 log->Printf ("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') error = %u (%s)", src, dst, error.GetError(), error.AsCString());
695 PlatformRemoteGDBServer::Unlink (const char *path)
697 Error error = m_gdb_client.Unlink (path);
698 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
700 log->Printf ("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)", path, error.GetError(), error.AsCString());
705 PlatformRemoteGDBServer::GetFileExists (const lldb_private::FileSpec& file_spec)
707 return m_gdb_client.GetFileExists (file_spec);
711 PlatformRemoteGDBServer::RunShellCommand (const char *command, // Shouldn't be NULL
712 const char *working_dir, // Pass NULL to use the current working directory
713 int *status_ptr, // Pass NULL if you don't want the process exit status
714 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
715 std::string *command_output, // Pass NULL if you don't want the command output
716 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
718 return m_gdb_client.RunShellCommand (command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec);
722 PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames ()
724 m_trap_handlers.push_back (ConstString ("_sigtramp"));