blob: afd6af6a5c2b7b9f5f43036ebf8d5399472d032d [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000016#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000017
18// C++ Includes
19#include <algorithm>
20#include <map>
21
22// Other libraries and framework includes
23
24#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000025#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Core/ArchSpec.h"
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000029#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/InputReader.h"
31#include "lldb/Core/Module.h"
32#include "lldb/Core/PluginManager.h"
33#include "lldb/Core/State.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Timer.h"
36#include "lldb/Host/TimeValue.h"
37#include "lldb/Symbol/ObjectFile.h"
38#include "lldb/Target/DynamicLoader.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000041#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042
43// Project includes
44#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000045#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "GDBRemoteRegisterContext.h"
47#include "ProcessGDBRemote.h"
48#include "ProcessGDBRemoteLog.h"
49#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000050#include "StopInfoMachException.h"
51
Chris Lattner24943d22010-06-08 16:52:24 +000052
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#define DEBUGSERVER_BASENAME "debugserver"
55using namespace lldb;
56using namespace lldb_private;
57
Jim Inghamf9600482011-03-29 21:45:47 +000058static bool rand_initialized = false;
59
Chris Lattner24943d22010-06-08 16:52:24 +000060static inline uint16_t
61get_random_port ()
62{
Jim Inghamf9600482011-03-29 21:45:47 +000063 if (!rand_initialized)
64 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000065 time_t seed = time(NULL);
66
Jim Inghamf9600482011-03-29 21:45:47 +000067 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000068 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000069 }
Stephen Wilson50daf772011-03-25 18:16:28 +000070 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000071}
72
73
74const char *
75ProcessGDBRemote::GetPluginNameStatic()
76{
Greg Claytonb1888f22011-03-19 01:12:21 +000077 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000078}
79
80const char *
81ProcessGDBRemote::GetPluginDescriptionStatic()
82{
83 return "GDB Remote protocol based debugging plug-in.";
84}
85
86void
87ProcessGDBRemote::Terminate()
88{
89 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
90}
91
92
93Process*
94ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
95{
96 return new ProcessGDBRemote (target, listener);
97}
98
99bool
100ProcessGDBRemote::CanDebug(Target &target)
101{
102 // For now we are just making sure the file exists for a given module
103 ModuleSP exe_module_sp(target.GetExecutableModule());
104 if (exe_module_sp.get())
105 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000106 // However, if there is no executable module, we return true since we might be preparing to attach.
107 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000108}
109
110//----------------------------------------------------------------------
111// ProcessGDBRemote constructor
112//----------------------------------------------------------------------
113ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
114 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000117 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000119 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000120 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
123 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000124 m_continue_c_tids (),
125 m_continue_C_tids (),
126 m_continue_s_tids (),
127 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000128 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000129 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000130 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000131 m_local_debugserver (true),
132 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000133{
Greg Claytonff39f742011-04-01 00:29:43 +0000134 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
135 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000136}
137
138//----------------------------------------------------------------------
139// Destructor
140//----------------------------------------------------------------------
141ProcessGDBRemote::~ProcessGDBRemote()
142{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000143 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000144 {
145 Host::ThreadCancel (m_debugserver_thread, NULL);
146 thread_result_t thread_result;
147 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
148 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
149 }
Chris Lattner24943d22010-06-08 16:52:24 +0000150 // m_mach_process.UnregisterNotificationCallbacks (this);
151 Clear();
152}
153
154//----------------------------------------------------------------------
155// PluginInterface
156//----------------------------------------------------------------------
157const char *
158ProcessGDBRemote::GetPluginName()
159{
160 return "Process debugging plug-in that uses the GDB remote protocol";
161}
162
163const char *
164ProcessGDBRemote::GetShortPluginName()
165{
166 return GetPluginNameStatic();
167}
168
169uint32_t
170ProcessGDBRemote::GetPluginVersion()
171{
172 return 1;
173}
174
175void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000176ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000177{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000178 if (!force && m_register_info.GetNumRegisters() > 0)
179 return;
180
181 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000182 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000183 uint32_t reg_offset = 0;
184 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000185 StringExtractorGDBRemote::ResponseType response_type;
186 for (response_type = StringExtractorGDBRemote::eResponse;
187 response_type == StringExtractorGDBRemote::eResponse;
188 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000189 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000190 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
191 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000192 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000193 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000194 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000195 response_type = response.GetResponseType();
196 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
198 std::string name;
199 std::string value;
200 ConstString reg_name;
201 ConstString alt_name;
202 ConstString set_name;
203 RegisterInfo reg_info = { NULL, // Name
204 NULL, // Alt name
205 0, // byte size
206 reg_offset, // offset
207 eEncodingUint, // encoding
208 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000209 {
210 LLDB_INVALID_REGNUM, // GCC reg num
211 LLDB_INVALID_REGNUM, // DWARF reg num
212 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000213 reg_num, // GDB reg num
214 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000215 }
216 };
217
218 while (response.GetNameColonValue(name, value))
219 {
220 if (name.compare("name") == 0)
221 {
222 reg_name.SetCString(value.c_str());
223 }
224 else if (name.compare("alt-name") == 0)
225 {
226 alt_name.SetCString(value.c_str());
227 }
228 else if (name.compare("bitsize") == 0)
229 {
230 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
231 }
232 else if (name.compare("offset") == 0)
233 {
234 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000235 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000236 {
237 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000238 }
239 }
240 else if (name.compare("encoding") == 0)
241 {
242 if (value.compare("uint") == 0)
243 reg_info.encoding = eEncodingUint;
244 else if (value.compare("sint") == 0)
245 reg_info.encoding = eEncodingSint;
246 else if (value.compare("ieee754") == 0)
247 reg_info.encoding = eEncodingIEEE754;
248 else if (value.compare("vector") == 0)
249 reg_info.encoding = eEncodingVector;
250 }
251 else if (name.compare("format") == 0)
252 {
253 if (value.compare("binary") == 0)
254 reg_info.format = eFormatBinary;
255 else if (value.compare("decimal") == 0)
256 reg_info.format = eFormatDecimal;
257 else if (value.compare("hex") == 0)
258 reg_info.format = eFormatHex;
259 else if (value.compare("float") == 0)
260 reg_info.format = eFormatFloat;
261 else if (value.compare("vector-sint8") == 0)
262 reg_info.format = eFormatVectorOfSInt8;
263 else if (value.compare("vector-uint8") == 0)
264 reg_info.format = eFormatVectorOfUInt8;
265 else if (value.compare("vector-sint16") == 0)
266 reg_info.format = eFormatVectorOfSInt16;
267 else if (value.compare("vector-uint16") == 0)
268 reg_info.format = eFormatVectorOfUInt16;
269 else if (value.compare("vector-sint32") == 0)
270 reg_info.format = eFormatVectorOfSInt32;
271 else if (value.compare("vector-uint32") == 0)
272 reg_info.format = eFormatVectorOfUInt32;
273 else if (value.compare("vector-float32") == 0)
274 reg_info.format = eFormatVectorOfFloat32;
275 else if (value.compare("vector-uint128") == 0)
276 reg_info.format = eFormatVectorOfUInt128;
277 }
278 else if (name.compare("set") == 0)
279 {
280 set_name.SetCString(value.c_str());
281 }
282 else if (name.compare("gcc") == 0)
283 {
284 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
285 }
286 else if (name.compare("dwarf") == 0)
287 {
288 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
289 }
290 else if (name.compare("generic") == 0)
291 {
292 if (value.compare("pc") == 0)
293 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
294 else if (value.compare("sp") == 0)
295 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
296 else if (value.compare("fp") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
298 else if (value.compare("ra") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
300 else if (value.compare("flags") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
302 }
303 }
304
Jason Molenda53d96862010-06-11 23:44:18 +0000305 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000306 assert (reg_info.byte_size != 0);
307 reg_offset += reg_info.byte_size;
308 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
309 }
310 }
311 else
312 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000313 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000314 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 }
316 }
317
318 if (reg_num == 0)
319 {
320 // We didn't get anything. See if we are debugging ARM and fill with
321 // a hard coded register set until we can get an updated debugserver
322 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000323 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000324 m_register_info.HardcodeARMRegisters();
325 }
326 m_register_info.Finalize ();
327}
328
329Error
330ProcessGDBRemote::WillLaunch (Module* module)
331{
332 return WillLaunchOrAttach ();
333}
334
335Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000336ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000337{
338 return WillLaunchOrAttach ();
339}
340
341Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000342ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000343{
344 return WillLaunchOrAttach ();
345}
346
347Error
Greg Claytone71e2582011-02-04 01:58:07 +0000348ProcessGDBRemote::DoConnectRemote (const char *remote_url)
349{
350 Error error (WillLaunchOrAttach ());
351
352 if (error.Fail())
353 return error;
354
Greg Clayton180546b2011-04-30 01:09:13 +0000355 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000356
357 if (error.Fail())
358 return error;
359 StartAsyncThread ();
360
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000361 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000362 if (pid == LLDB_INVALID_PROCESS_ID)
363 {
364 // We don't have a valid process ID, so note that we are connected
365 // and could now request to launch or attach, or get remote process
366 // listings...
367 SetPrivateState (eStateConnected);
368 }
369 else
370 {
371 // We have a valid process
372 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000373 UpdateThreadListIfNeeded ();
Greg Claytone71e2582011-02-04 01:58:07 +0000374 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000375 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000376 {
377 const StateType state = SetThreadStopInfo (response);
378 if (state == eStateStopped)
379 {
380 SetPrivateState (state);
381 }
382 else
383 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
384 }
385 else
386 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
387 }
388 return error;
389}
390
391Error
Chris Lattner24943d22010-06-08 16:52:24 +0000392ProcessGDBRemote::WillLaunchOrAttach ()
393{
394 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000395 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000396 return error;
397}
398
399//----------------------------------------------------------------------
400// Process Control
401//----------------------------------------------------------------------
402Error
403ProcessGDBRemote::DoLaunch
404(
405 Module* module,
406 char const *argv[],
407 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000408 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000409 const char *stdin_path,
410 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000411 const char *stderr_path,
412 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000413)
414{
Greg Clayton4b407112010-09-30 21:49:03 +0000415 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000416 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
417 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
418 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000419
420 ObjectFile * object_file = module->GetObjectFile();
421 if (object_file)
422 {
Chris Lattner24943d22010-06-08 16:52:24 +0000423 char host_port[128];
424 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000425 char connect_url[128];
426 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000427
Greg Claytona2f74232011-02-24 22:24:29 +0000428 // Make sure we aren't already connected?
429 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000430 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000431 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000432 if (error.Fail())
433 return error;
434
Greg Claytone71e2582011-02-04 01:58:07 +0000435 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000436 }
437
438 if (error.Success())
439 {
440 lldb_utility::PseudoTerminal pty;
441 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000442
443 // If the debugserver is local and we aren't disabling STDIO, lets use
444 // a pseudo terminal to instead of relying on the 'O' packets for stdio
445 // since 'O' packets can really slow down debugging if the inferior
446 // does a lot of output.
447 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000448 {
449 const char *slave_name = NULL;
450 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000451 {
Greg Claytona2f74232011-02-24 22:24:29 +0000452 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
453 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000454 }
Greg Claytona2f74232011-02-24 22:24:29 +0000455 if (stdin_path == NULL)
456 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000457
Greg Claytona2f74232011-02-24 22:24:29 +0000458 if (stdout_path == NULL)
459 stdout_path = slave_name;
460
461 if (stderr_path == NULL)
462 stderr_path = slave_name;
463 }
464
Greg Claytonafb81862011-03-02 21:34:46 +0000465 // Set STDIN to /dev/null if we want STDIO disabled or if either
466 // STDOUT or STDERR have been set to something and STDIN hasn't
467 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000468 stdin_path = "/dev/null";
469
Greg Claytonafb81862011-03-02 21:34:46 +0000470 // Set STDOUT to /dev/null if we want STDIO disabled or if either
471 // STDIN or STDERR have been set to something and STDOUT hasn't
472 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000473 stdout_path = "/dev/null";
474
Greg Claytonafb81862011-03-02 21:34:46 +0000475 // Set STDERR to /dev/null if we want STDIO disabled or if either
476 // STDIN or STDOUT have been set to something and STDERR hasn't
477 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000478 stderr_path = "/dev/null";
479
480 if (stdin_path)
481 m_gdb_comm.SetSTDIN (stdin_path);
482 if (stdout_path)
483 m_gdb_comm.SetSTDOUT (stdout_path);
484 if (stderr_path)
485 m_gdb_comm.SetSTDERR (stderr_path);
486
487 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
488
489
490 if (working_dir && working_dir[0])
491 {
492 m_gdb_comm.SetWorkingDir (working_dir);
493 }
494
495 // Send the environment and the program + arguments after we connect
496 if (envp)
497 {
498 const char *env_entry;
499 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000500 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000501 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000502 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000503 }
Greg Claytona2f74232011-02-24 22:24:29 +0000504 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000505
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000506 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
507 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
508 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000509 if (arg_packet_err == 0)
510 {
511 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000512 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000513 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000514 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000515 }
516 else
517 {
Greg Claytona2f74232011-02-24 22:24:29 +0000518 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000519 }
Greg Claytona2f74232011-02-24 22:24:29 +0000520 }
521 else
522 {
523 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
524 }
Chris Lattner24943d22010-06-08 16:52:24 +0000525
Greg Claytona2f74232011-02-24 22:24:29 +0000526 if (GetID() == LLDB_INVALID_PROCESS_ID)
527 {
528 KillDebugserverProcess ();
529 return error;
530 }
531
532 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000533 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000534 {
535 SetPrivateState (SetThreadStopInfo (response));
536
537 if (!disable_stdio)
538 {
539 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
540 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
541 }
Chris Lattner24943d22010-06-08 16:52:24 +0000542 }
543 }
Chris Lattner24943d22010-06-08 16:52:24 +0000544 }
545 else
546 {
547 // Set our user ID to an invalid process ID.
548 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000549 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
550 module->GetFileSpec().GetFilename().AsCString(),
551 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000552 }
Chris Lattner24943d22010-06-08 16:52:24 +0000553 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000554
Chris Lattner24943d22010-06-08 16:52:24 +0000555}
556
557
558Error
Greg Claytone71e2582011-02-04 01:58:07 +0000559ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000560{
561 Error error;
562 // Sleep and wait a bit for debugserver to start to listen...
563 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
564 if (conn_ap.get())
565 {
Chris Lattner24943d22010-06-08 16:52:24 +0000566 const uint32_t max_retry_count = 50;
567 uint32_t retry_count = 0;
568 while (!m_gdb_comm.IsConnected())
569 {
Greg Claytone71e2582011-02-04 01:58:07 +0000570 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000571 {
572 m_gdb_comm.SetConnection (conn_ap.release());
573 break;
574 }
575 retry_count++;
576
577 if (retry_count >= max_retry_count)
578 break;
579
580 usleep (100000);
581 }
582 }
583
584 if (!m_gdb_comm.IsConnected())
585 {
586 if (error.Success())
587 error.SetErrorString("not connected to remote gdb server");
588 return error;
589 }
590
Greg Clayton24bc5d92011-03-30 18:16:51 +0000591 // We always seem to be able to open a connection to a local port
592 // so we need to make sure we can then send data to it. If we can't
593 // then we aren't actually connected to anything, so try and do the
594 // handshake with the remote GDB server and make sure that goes
595 // alright.
596 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000597 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000598 m_gdb_comm.Disconnect();
599 if (error.Success())
600 error.SetErrorString("not connected to remote gdb server");
601 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000602 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000603 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
604 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
605 this,
606 m_debugserver_pid,
607 false);
608 m_gdb_comm.ResetDiscoverableSettings();
609 m_gdb_comm.QueryNoAckModeSupported ();
610 m_gdb_comm.GetThreadSuffixSupported ();
611 m_gdb_comm.GetHostInfo ();
612 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000613 return error;
614}
615
616void
617ProcessGDBRemote::DidLaunchOrAttach ()
618{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000619 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
620 if (log)
621 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000622 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000623 {
624 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
625
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000626 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000627
Chris Lattner24943d22010-06-08 16:52:24 +0000628 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000629
Greg Claytoncb8977d2011-03-23 00:09:55 +0000630 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
631 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000632 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000633 ArchSpec &target_arch = GetTarget().GetArchitecture();
634
635 if (target_arch.IsValid())
636 {
637 // If the remote host is ARM and we have apple as the vendor, then
638 // ARM executables and shared libraries can have mixed ARM architectures.
639 // You can have an armv6 executable, and if the host is armv7, then the
640 // system will load the best possible architecture for all shared libraries
641 // it has, so we really need to take the remote host architecture as our
642 // defacto architecture in this case.
643
644 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
645 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
646 {
647 target_arch = gdb_remote_arch;
648 }
649 else
650 {
651 // Fill in what is missing in the triple
652 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
653 llvm::Triple &target_triple = target_arch.GetTriple();
654 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
655 target_triple.setVendor (remote_triple.getVendor());
656
657 if (target_triple.getOS() == llvm::Triple::UnknownOS)
658 target_triple.setOS (remote_triple.getOS());
659
660 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
661 target_triple.setEnvironment (remote_triple.getEnvironment());
662 }
663 }
664 else
665 {
666 // The target doesn't have a valid architecture yet, set it from
667 // the architecture we got from the remote GDB server
668 target_arch = gdb_remote_arch;
669 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000670 }
Chris Lattner24943d22010-06-08 16:52:24 +0000671 }
672}
673
674void
675ProcessGDBRemote::DidLaunch ()
676{
677 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000678}
679
680Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000681ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Error error;
684 // Clear out and clean up from any current state
685 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000686 if (attach_pid != LLDB_INVALID_PROCESS_ID)
687 {
Greg Claytona2f74232011-02-24 22:24:29 +0000688 // Make sure we aren't already connected?
689 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000690 {
Greg Claytona2f74232011-02-24 22:24:29 +0000691 char host_port[128];
692 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
693 char connect_url[128];
694 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000695
Greg Claytonb72d0f02011-04-12 05:54:46 +0000696 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000697
698 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000699 {
Greg Claytona2f74232011-02-24 22:24:29 +0000700 const char *error_string = error.AsCString();
701 if (error_string == NULL)
702 error_string = "unable to launch " DEBUGSERVER_BASENAME;
703
704 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000705 }
Greg Claytona2f74232011-02-24 22:24:29 +0000706 else
707 {
708 error = ConnectToDebugserver (connect_url);
709 }
710 }
711
712 if (error.Success())
713 {
714 char packet[64];
715 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
716
717 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000718 }
719 }
Chris Lattner24943d22010-06-08 16:52:24 +0000720 return error;
721}
722
723size_t
724ProcessGDBRemote::AttachInputReaderCallback
725(
726 void *baton,
727 InputReader *reader,
728 lldb::InputReaderAction notification,
729 const char *bytes,
730 size_t bytes_len
731)
732{
733 if (notification == eInputReaderGotToken)
734 {
735 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
736 if (gdb_process->m_waiting_for_attach)
737 gdb_process->m_waiting_for_attach = false;
738 reader->SetIsDone(true);
739 return 1;
740 }
741 return 0;
742}
743
744Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000745ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000746{
747 Error error;
748 // Clear out and clean up from any current state
749 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000750
Chris Lattner24943d22010-06-08 16:52:24 +0000751 if (process_name && process_name[0])
752 {
Greg Claytona2f74232011-02-24 22:24:29 +0000753 // Make sure we aren't already connected?
754 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000755 {
Greg Claytona2f74232011-02-24 22:24:29 +0000756 char host_port[128];
757 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
758 char connect_url[128];
759 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
760
Greg Claytonb72d0f02011-04-12 05:54:46 +0000761 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000762 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
Greg Claytona2f74232011-02-24 22:24:29 +0000764 const char *error_string = error.AsCString();
765 if (error_string == NULL)
766 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000767
Greg Claytona2f74232011-02-24 22:24:29 +0000768 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000769 }
Greg Claytona2f74232011-02-24 22:24:29 +0000770 else
771 {
772 error = ConnectToDebugserver (connect_url);
773 }
774 }
775
776 if (error.Success())
777 {
778 StreamString packet;
779
780 if (wait_for_launch)
781 packet.PutCString("vAttachWait");
782 else
783 packet.PutCString("vAttachName");
784 packet.PutChar(';');
785 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
786
787 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
788
Chris Lattner24943d22010-06-08 16:52:24 +0000789 }
790 }
Chris Lattner24943d22010-06-08 16:52:24 +0000791 return error;
792}
793
Chris Lattner24943d22010-06-08 16:52:24 +0000794
795void
796ProcessGDBRemote::DidAttach ()
797{
Greg Claytone71e2582011-02-04 01:58:07 +0000798 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000799}
800
801Error
802ProcessGDBRemote::WillResume ()
803{
Greg Claytonc1f45872011-02-12 06:28:37 +0000804 m_continue_c_tids.clear();
805 m_continue_C_tids.clear();
806 m_continue_s_tids.clear();
807 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000808 return Error();
809}
810
811Error
812ProcessGDBRemote::DoResume ()
813{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000814 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000815 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
816 if (log)
817 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000818
819 Listener listener ("gdb-remote.resume-packet-sent");
820 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
821 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000822 StreamString continue_packet;
823 bool continue_packet_error = false;
824 if (m_gdb_comm.HasAnyVContSupport ())
825 {
826 continue_packet.PutCString ("vCont");
827
828 if (!m_continue_c_tids.empty())
829 {
830 if (m_gdb_comm.GetVContSupported ('c'))
831 {
832 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
833 continue_packet.Printf(";c:%4.4x", *t_pos);
834 }
835 else
836 continue_packet_error = true;
837 }
838
839 if (!continue_packet_error && !m_continue_C_tids.empty())
840 {
841 if (m_gdb_comm.GetVContSupported ('C'))
842 {
843 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
844 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
845 }
846 else
847 continue_packet_error = true;
848 }
Greg Claytonb749a262010-12-03 06:02:24 +0000849
Greg Claytonc1f45872011-02-12 06:28:37 +0000850 if (!continue_packet_error && !m_continue_s_tids.empty())
851 {
852 if (m_gdb_comm.GetVContSupported ('s'))
853 {
854 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
855 continue_packet.Printf(";s:%4.4x", *t_pos);
856 }
857 else
858 continue_packet_error = true;
859 }
860
861 if (!continue_packet_error && !m_continue_S_tids.empty())
862 {
863 if (m_gdb_comm.GetVContSupported ('S'))
864 {
865 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
866 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
867 }
868 else
869 continue_packet_error = true;
870 }
871
872 if (continue_packet_error)
873 continue_packet.GetString().clear();
874 }
875 else
876 continue_packet_error = true;
877
878 if (continue_packet_error)
879 {
880 continue_packet_error = false;
881 // Either no vCont support, or we tried to use part of the vCont
882 // packet that wasn't supported by the remote GDB server.
883 // We need to try and make a simple packet that can do our continue
884 const size_t num_threads = GetThreadList().GetSize();
885 const size_t num_continue_c_tids = m_continue_c_tids.size();
886 const size_t num_continue_C_tids = m_continue_C_tids.size();
887 const size_t num_continue_s_tids = m_continue_s_tids.size();
888 const size_t num_continue_S_tids = m_continue_S_tids.size();
889 if (num_continue_c_tids > 0)
890 {
891 if (num_continue_c_tids == num_threads)
892 {
893 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000894 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000895 continue_packet.PutChar ('c');
896 }
897 else if (num_continue_c_tids == 1 &&
898 num_continue_C_tids == 0 &&
899 num_continue_s_tids == 0 &&
900 num_continue_S_tids == 0 )
901 {
902 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000903 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000904 continue_packet.PutChar ('c');
905 }
906 else
907 {
908 // We can't represent this continue packet....
909 continue_packet_error = true;
910 }
911 }
912
913 if (!continue_packet_error && num_continue_C_tids > 0)
914 {
915 if (num_continue_C_tids == num_threads)
916 {
917 const int continue_signo = m_continue_C_tids.front().second;
918 if (num_continue_C_tids > 1)
919 {
920 for (size_t i=1; i<num_threads; ++i)
921 {
922 if (m_continue_C_tids[i].second != continue_signo)
923 continue_packet_error = true;
924 }
925 }
926 if (!continue_packet_error)
927 {
928 // Add threads continuing with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000929 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000930 continue_packet.Printf("C%2.2x", continue_signo);
931 }
932 }
933 else if (num_continue_c_tids == 0 &&
934 num_continue_C_tids == 1 &&
935 num_continue_s_tids == 0 &&
936 num_continue_S_tids == 0 )
937 {
938 // Only one thread is continuing with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +0000939 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000940 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
941 }
942 else
943 {
944 // We can't represent this continue packet....
945 continue_packet_error = true;
946 }
947 }
948
949 if (!continue_packet_error && num_continue_s_tids > 0)
950 {
951 if (num_continue_s_tids == num_threads)
952 {
953 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000954 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000955 continue_packet.PutChar ('s');
956 }
957 else if (num_continue_c_tids == 0 &&
958 num_continue_C_tids == 0 &&
959 num_continue_s_tids == 1 &&
960 num_continue_S_tids == 0 )
961 {
962 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000963 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 continue_packet.PutChar ('s');
965 }
966 else
967 {
968 // We can't represent this continue packet....
969 continue_packet_error = true;
970 }
971 }
972
973 if (!continue_packet_error && num_continue_S_tids > 0)
974 {
975 if (num_continue_S_tids == num_threads)
976 {
977 const int step_signo = m_continue_S_tids.front().second;
978 // Are all threads trying to step with the same signal?
979 if (num_continue_S_tids > 1)
980 {
981 for (size_t i=1; i<num_threads; ++i)
982 {
983 if (m_continue_S_tids[i].second != step_signo)
984 continue_packet_error = true;
985 }
986 }
987 if (!continue_packet_error)
988 {
989 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000990 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000991 continue_packet.Printf("S%2.2x", step_signo);
992 }
993 }
994 else if (num_continue_c_tids == 0 &&
995 num_continue_C_tids == 0 &&
996 num_continue_s_tids == 0 &&
997 num_continue_S_tids == 1 )
998 {
999 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001000 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001001 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1002 }
1003 else
1004 {
1005 // We can't represent this continue packet....
1006 continue_packet_error = true;
1007 }
1008 }
1009 }
1010
1011 if (continue_packet_error)
1012 {
1013 error.SetErrorString ("can't make continue packet for this resume");
1014 }
1015 else
1016 {
1017 EventSP event_sp;
1018 TimeValue timeout;
1019 timeout = TimeValue::Now();
1020 timeout.OffsetWithSeconds (5);
1021 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1022
1023 if (listener.WaitForEvent (&timeout, event_sp) == false)
1024 error.SetErrorString("Resume timed out.");
1025 }
Greg Claytonb749a262010-12-03 06:02:24 +00001026 }
1027
Jim Ingham3ae449a2010-11-17 02:32:00 +00001028 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001029}
1030
Chris Lattner24943d22010-06-08 16:52:24 +00001031uint32_t
1032ProcessGDBRemote::UpdateThreadListIfNeeded ()
1033{
1034 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001035 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001036 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001037 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1038
Greg Clayton5205f0b2010-09-03 17:10:42 +00001039 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001040 const uint32_t stop_id = GetStopID();
1041 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1042 {
1043 // Update the thread list's stop id immediately so we don't recurse into this function.
1044 ThreadList curr_thread_list (this);
1045 curr_thread_list.SetStopID(stop_id);
1046
1047 Error err;
1048 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001049 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001050 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001051 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001052 {
1053 char ch = response.GetChar();
1054 if (ch == 'l')
1055 break;
1056 if (ch == 'm')
1057 {
1058 do
1059 {
1060 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1061
1062 if (tid != LLDB_INVALID_THREAD_ID)
1063 {
1064 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001065 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001066 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1067 curr_thread_list.AddThread(thread_sp);
1068 }
1069
1070 ch = response.GetChar();
1071 } while (ch == ',');
1072 }
1073 }
1074
1075 m_thread_list = curr_thread_list;
1076
1077 SetThreadStopInfo (m_last_stop_packet);
1078 }
1079 return GetThreadList().GetSize(false);
1080}
1081
1082
1083StateType
1084ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1085{
1086 const char stop_type = stop_packet.GetChar();
1087 switch (stop_type)
1088 {
1089 case 'T':
1090 case 'S':
1091 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001092 if (GetStopID() == 0)
1093 {
1094 // Our first stop, make sure we have a process ID, and also make
1095 // sure we know about our registers
1096 if (GetID() == LLDB_INVALID_PROCESS_ID)
1097 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001098 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001099 if (pid != LLDB_INVALID_PROCESS_ID)
1100 SetID (pid);
1101 }
1102 BuildDynamicRegisterInfo (true);
1103 }
Chris Lattner24943d22010-06-08 16:52:24 +00001104 // Stop with signal and thread info
1105 const uint8_t signo = stop_packet.GetHexU8();
1106 std::string name;
1107 std::string value;
1108 std::string thread_name;
1109 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001110 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001111 uint32_t tid = LLDB_INVALID_THREAD_ID;
1112 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1113 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001114 ThreadSP thread_sp;
1115
Chris Lattner24943d22010-06-08 16:52:24 +00001116 while (stop_packet.GetNameColonValue(name, value))
1117 {
1118 if (name.compare("metype") == 0)
1119 {
1120 // exception type in big endian hex
1121 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1122 }
1123 else if (name.compare("mecount") == 0)
1124 {
1125 // exception count in big endian hex
1126 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1127 }
1128 else if (name.compare("medata") == 0)
1129 {
1130 // exception data in big endian hex
1131 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1132 }
1133 else if (name.compare("thread") == 0)
1134 {
1135 // thread in big endian hex
1136 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001137 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001138 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001139 if (!thread_sp)
1140 {
1141 // Create the thread if we need to
1142 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1143 m_thread_list.AddThread(thread_sp);
1144 }
Chris Lattner24943d22010-06-08 16:52:24 +00001145 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001146 else if (name.compare("hexname") == 0)
1147 {
1148 StringExtractor name_extractor;
1149 // Swap "value" over into "name_extractor"
1150 name_extractor.GetStringRef().swap(value);
1151 // Now convert the HEX bytes into a string value
1152 name_extractor.GetHexByteString (value);
1153 thread_name.swap (value);
1154 }
Chris Lattner24943d22010-06-08 16:52:24 +00001155 else if (name.compare("name") == 0)
1156 {
1157 thread_name.swap (value);
1158 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001159 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001160 {
1161 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1162 }
Greg Claytona875b642011-01-09 21:07:35 +00001163 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1164 {
1165 // We have a register number that contains an expedited
1166 // register value. Lets supply this register to our thread
1167 // so it won't have to go and read it.
1168 if (thread_sp)
1169 {
1170 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1171
1172 if (reg != UINT32_MAX)
1173 {
1174 StringExtractor reg_value_extractor;
1175 // Swap "value" over into "reg_value_extractor"
1176 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001177 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1178 {
1179 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1180 name.c_str(),
1181 reg,
1182 reg,
1183 reg_value_extractor.GetStringRef().c_str(),
1184 stop_packet.GetStringRef().c_str());
1185 }
Greg Claytona875b642011-01-09 21:07:35 +00001186 }
1187 }
1188 }
Chris Lattner24943d22010-06-08 16:52:24 +00001189 }
Chris Lattner24943d22010-06-08 16:52:24 +00001190
1191 if (thread_sp)
1192 {
1193 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1194
1195 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001196 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001197 if (exc_type != 0)
1198 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001199 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001200
1201 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1202 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001203 exc_data_size,
1204 exc_data_size >= 1 ? exc_data[0] : 0,
1205 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001206 }
1207 else if (signo)
1208 {
Greg Clayton643ee732010-08-04 01:40:35 +00001209 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001210 }
1211 else
1212 {
Greg Clayton643ee732010-08-04 01:40:35 +00001213 StopInfoSP invalid_stop_info_sp;
1214 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001215 }
1216 }
1217 return eStateStopped;
1218 }
1219 break;
1220
1221 case 'W':
1222 // process exited
1223 return eStateExited;
1224
1225 default:
1226 break;
1227 }
1228 return eStateInvalid;
1229}
1230
1231void
1232ProcessGDBRemote::RefreshStateAfterStop ()
1233{
Jim Ingham7508e732010-08-09 23:31:02 +00001234 // FIXME - add a variable to tell that we're in the middle of attaching if we
1235 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001236 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001237// if (!GetTarget().GetArchitecture().IsValid())
1238// {
1239// Module *exe_module = GetTarget().GetExecutableModule().get();
1240// if (exe_module)
1241// m_arch_spec = exe_module->GetArchitecture();
1242// }
1243
Chris Lattner24943d22010-06-08 16:52:24 +00001244 // Let all threads recover from stopping and do any clean up based
1245 // on the previous thread state (if any).
1246 m_thread_list.RefreshStateAfterStop();
1247
1248 // Discover new threads:
1249 UpdateThreadListIfNeeded ();
1250}
1251
1252Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001253ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001254{
1255 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001256
Greg Claytona4881d02011-01-22 07:12:45 +00001257 bool timed_out = false;
1258 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001259
1260 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001261 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001262 // We are being asked to halt during an attach. We need to just close
1263 // our file handle and debugserver will go away, and we can be done...
1264 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001265 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001266 else
1267 {
1268 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1269 {
1270 if (timed_out)
1271 error.SetErrorString("timed out sending interrupt packet");
1272 else
1273 error.SetErrorString("unknown error sending interrupt packet");
1274 }
1275 }
Chris Lattner24943d22010-06-08 16:52:24 +00001276 return error;
1277}
1278
1279Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001280ProcessGDBRemote::InterruptIfRunning
1281(
1282 bool discard_thread_plans,
1283 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001284 EventSP &stop_event_sp
1285)
Chris Lattner24943d22010-06-08 16:52:24 +00001286{
1287 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001288
Greg Clayton2860ba92011-01-23 19:58:49 +00001289 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1290
Greg Clayton68ca8232011-01-25 02:58:48 +00001291 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001292 const bool is_running = m_gdb_comm.IsRunning();
1293 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001294 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001295 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001296 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001297 is_running);
1298
Greg Clayton2860ba92011-01-23 19:58:49 +00001299 if (discard_thread_plans)
1300 {
1301 if (log)
1302 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1303 m_thread_list.DiscardThreadPlans();
1304 }
1305 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001306 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001307 if (catch_stop_event)
1308 {
1309 if (log)
1310 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1311 PausePrivateStateThread();
1312 paused_private_state_thread = true;
1313 }
1314
Greg Clayton4fb400f2010-09-27 21:07:38 +00001315 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001316 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001317 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001318
Greg Clayton72e1c782011-01-22 23:43:18 +00001319 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001320 {
1321 if (timed_out)
1322 error.SetErrorString("timed out sending interrupt packet");
1323 else
1324 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001325 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001326 ResumePrivateStateThread();
1327 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001328 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001329
Greg Clayton72e1c782011-01-22 23:43:18 +00001330 if (catch_stop_event)
1331 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001332 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001333 TimeValue timeout_time;
1334 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001335 timeout_time.OffsetWithSeconds(5);
1336 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001337
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001338 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001339 if (log)
1340 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001341
Greg Clayton2860ba92011-01-23 19:58:49 +00001342 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001343 error.SetErrorString("unable to verify target stopped");
1344 }
1345
Greg Clayton68ca8232011-01-25 02:58:48 +00001346 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001347 {
1348 if (log)
1349 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001350 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001351 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001352 }
Chris Lattner24943d22010-06-08 16:52:24 +00001353 return error;
1354}
1355
Greg Clayton4fb400f2010-09-27 21:07:38 +00001356Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001357ProcessGDBRemote::WillDetach ()
1358{
Greg Clayton2860ba92011-01-23 19:58:49 +00001359 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1360 if (log)
1361 log->Printf ("ProcessGDBRemote::WillDetach()");
1362
Greg Clayton72e1c782011-01-22 23:43:18 +00001363 bool discard_thread_plans = true;
1364 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001365 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001366 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001367}
1368
1369Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001370ProcessGDBRemote::DoDetach()
1371{
1372 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001373 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001374 if (log)
1375 log->Printf ("ProcessGDBRemote::DoDetach()");
1376
1377 DisableAllBreakpointSites ();
1378
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001379 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001380
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001381 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1382 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001383 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001384 if (response_size)
1385 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1386 else
1387 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001388 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001389 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001390 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001391
Greg Clayton4fb400f2010-09-27 21:07:38 +00001392 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001393 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001394
1395 SetPrivateState (eStateDetached);
1396 ResumePrivateStateThread();
1397
1398 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001399 return error;
1400}
Chris Lattner24943d22010-06-08 16:52:24 +00001401
1402Error
1403ProcessGDBRemote::DoDestroy ()
1404{
1405 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001406 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001407 if (log)
1408 log->Printf ("ProcessGDBRemote::DoDestroy()");
1409
1410 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001411 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001412 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001413 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001414 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001415 // We are being asked to halt during an attach. We need to just close
1416 // our file handle and debugserver will go away, and we can be done...
1417 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001418 }
1419 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001420 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001421
1422 StringExtractorGDBRemote response;
1423 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001424 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001425 {
1426 char packet_cmd = response.GetChar(0);
1427
1428 if (packet_cmd == 'W' || packet_cmd == 'X')
1429 {
1430 m_last_stop_packet = response;
1431 SetExitStatus(response.GetHexU8(), NULL);
1432 }
1433 }
1434 else
1435 {
1436 SetExitStatus(SIGABRT, NULL);
1437 //error.SetErrorString("kill packet failed");
1438 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001439 }
1440 }
Chris Lattner24943d22010-06-08 16:52:24 +00001441 StopAsyncThread ();
1442 m_gdb_comm.StopReadThread();
1443 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001444 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001445 return error;
1446}
1447
Chris Lattner24943d22010-06-08 16:52:24 +00001448//------------------------------------------------------------------
1449// Process Queries
1450//------------------------------------------------------------------
1451
1452bool
1453ProcessGDBRemote::IsAlive ()
1454{
Greg Clayton58e844b2010-12-08 05:08:21 +00001455 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001456}
1457
1458addr_t
1459ProcessGDBRemote::GetImageInfoAddress()
1460{
1461 if (!m_gdb_comm.IsRunning())
1462 {
1463 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001464 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001465 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001466 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001467 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1468 }
1469 }
1470 return LLDB_INVALID_ADDRESS;
1471}
1472
Chris Lattner24943d22010-06-08 16:52:24 +00001473//------------------------------------------------------------------
1474// Process Memory
1475//------------------------------------------------------------------
1476size_t
1477ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1478{
1479 if (size > m_max_memory_size)
1480 {
1481 // Keep memory read sizes down to a sane limit. This function will be
1482 // called multiple times in order to complete the task by
1483 // lldb_private::Process so it is ok to do this.
1484 size = m_max_memory_size;
1485 }
1486
1487 char packet[64];
1488 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1489 assert (packet_len + 1 < sizeof(packet));
1490 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001491 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001492 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001493 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001494 {
1495 error.Clear();
1496 return response.GetHexBytes(buf, size, '\xdd');
1497 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001498 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001499 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001500 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001501 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1502 else
1503 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1504 }
1505 else
1506 {
1507 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1508 }
1509 return 0;
1510}
1511
1512size_t
1513ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1514{
1515 StreamString packet;
1516 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001517 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001518 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001519 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001520 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001521 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001522 {
1523 error.Clear();
1524 return size;
1525 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001526 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001527 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001528 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001529 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1530 else
1531 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1532 }
1533 else
1534 {
1535 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1536 }
1537 return 0;
1538}
1539
1540lldb::addr_t
1541ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1542{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001543 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001544 if (allocated_addr == LLDB_INVALID_ADDRESS)
1545 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1546 else
1547 error.Clear();
1548 return allocated_addr;
1549}
1550
1551Error
1552ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1553{
1554 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001555 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001556 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1557 return error;
1558}
1559
1560
1561//------------------------------------------------------------------
1562// Process STDIO
1563//------------------------------------------------------------------
1564
1565size_t
1566ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1567{
1568 Mutex::Locker locker(m_stdio_mutex);
1569 size_t bytes_available = m_stdout_data.size();
1570 if (bytes_available > 0)
1571 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001572 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1573 if (log)
1574 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001575 if (bytes_available > buf_size)
1576 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001577 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001578 m_stdout_data.erase(0, buf_size);
1579 bytes_available = buf_size;
1580 }
1581 else
1582 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001583 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001584 m_stdout_data.clear();
1585
1586 //ResetEventBits(eBroadcastBitSTDOUT);
1587 }
1588 }
1589 return bytes_available;
1590}
1591
1592size_t
1593ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1594{
1595 // Can we get STDERR through the remote protocol?
1596 return 0;
1597}
1598
1599size_t
1600ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1601{
1602 if (m_stdio_communication.IsConnected())
1603 {
1604 ConnectionStatus status;
1605 m_stdio_communication.Write(src, src_len, status, NULL);
1606 }
1607 return 0;
1608}
1609
1610Error
1611ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1612{
1613 Error error;
1614 assert (bp_site != NULL);
1615
Greg Claytone005f2c2010-11-06 01:53:30 +00001616 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001617 user_id_t site_id = bp_site->GetID();
1618 const addr_t addr = bp_site->GetLoadAddress();
1619 if (log)
1620 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1621
1622 if (bp_site->IsEnabled())
1623 {
1624 if (log)
1625 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1626 return error;
1627 }
1628 else
1629 {
1630 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1631
1632 if (bp_site->HardwarePreferred())
1633 {
1634 // Try and set hardware breakpoint, and if that fails, fall through
1635 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001636 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001637 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001638 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001639 {
1640 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001641 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001642 return error;
1643 }
Chris Lattner24943d22010-06-08 16:52:24 +00001644 }
1645 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001646
1647 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001648 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001649 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1650 {
1651 bp_site->SetEnabled(true);
1652 bp_site->SetType (BreakpointSite::eExternal);
1653 return error;
1654 }
Chris Lattner24943d22010-06-08 16:52:24 +00001655 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001656
1657 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001658 }
1659
1660 if (log)
1661 {
1662 const char *err_string = error.AsCString();
1663 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1664 bp_site->GetLoadAddress(),
1665 err_string ? err_string : "NULL");
1666 }
1667 // We shouldn't reach here on a successful breakpoint enable...
1668 if (error.Success())
1669 error.SetErrorToGenericError();
1670 return error;
1671}
1672
1673Error
1674ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1675{
1676 Error error;
1677 assert (bp_site != NULL);
1678 addr_t addr = bp_site->GetLoadAddress();
1679 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001680 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001681 if (log)
1682 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1683
1684 if (bp_site->IsEnabled())
1685 {
1686 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1687
Greg Claytonb72d0f02011-04-12 05:54:46 +00001688 BreakpointSite::Type bp_type = bp_site->GetType();
1689 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001690 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001691 case BreakpointSite::eSoftware:
1692 error = DisableSoftwareBreakpoint (bp_site);
1693 break;
1694
1695 case BreakpointSite::eHardware:
1696 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1697 error.SetErrorToGenericError();
1698 break;
1699
1700 case BreakpointSite::eExternal:
1701 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1702 error.SetErrorToGenericError();
1703 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001704 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001705 if (error.Success())
1706 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001707 }
1708 else
1709 {
1710 if (log)
1711 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1712 return error;
1713 }
1714
1715 if (error.Success())
1716 error.SetErrorToGenericError();
1717 return error;
1718}
1719
1720Error
1721ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1722{
1723 Error error;
1724 if (wp)
1725 {
1726 user_id_t watchID = wp->GetID();
1727 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001728 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001729 if (log)
1730 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1731 if (wp->IsEnabled())
1732 {
1733 if (log)
1734 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1735 return error;
1736 }
1737 else
1738 {
1739 // Pass down an appropriate z/Z packet...
1740 error.SetErrorString("watchpoints not supported");
1741 }
1742 }
1743 else
1744 {
1745 error.SetErrorString("Watchpoint location argument was NULL.");
1746 }
1747 if (error.Success())
1748 error.SetErrorToGenericError();
1749 return error;
1750}
1751
1752Error
1753ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1754{
1755 Error error;
1756 if (wp)
1757 {
1758 user_id_t watchID = wp->GetID();
1759
Greg Claytone005f2c2010-11-06 01:53:30 +00001760 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001761
1762 addr_t addr = wp->GetLoadAddress();
1763 if (log)
1764 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1765
1766 if (wp->IsHardware())
1767 {
1768 // Pass down an appropriate z/Z packet...
1769 error.SetErrorString("watchpoints not supported");
1770 }
1771 // TODO: clear software watchpoints if we implement them
1772 }
1773 else
1774 {
1775 error.SetErrorString("Watchpoint location argument was NULL.");
1776 }
1777 if (error.Success())
1778 error.SetErrorToGenericError();
1779 return error;
1780}
1781
1782void
1783ProcessGDBRemote::Clear()
1784{
1785 m_flags = 0;
1786 m_thread_list.Clear();
1787 {
1788 Mutex::Locker locker(m_stdio_mutex);
1789 m_stdout_data.clear();
1790 }
Chris Lattner24943d22010-06-08 16:52:24 +00001791}
1792
1793Error
1794ProcessGDBRemote::DoSignal (int signo)
1795{
1796 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001797 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001798 if (log)
1799 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1800
1801 if (!m_gdb_comm.SendAsyncSignal (signo))
1802 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1803 return error;
1804}
1805
Chris Lattner24943d22010-06-08 16:52:24 +00001806Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001807ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00001808{
1809 Error error;
1810 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1811 {
1812 // If we locate debugserver, keep that located version around
1813 static FileSpec g_debugserver_file_spec;
1814
Greg Claytonb72d0f02011-04-12 05:54:46 +00001815 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00001816 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00001817 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00001818
1819 // Always check to see if we have an environment override for the path
1820 // to the debugserver to use and use it if we do.
1821 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1822 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001823 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001824 else
1825 debugserver_file_spec = g_debugserver_file_spec;
1826 bool debugserver_exists = debugserver_file_spec.Exists();
1827 if (!debugserver_exists)
1828 {
1829 // The debugserver binary is in the LLDB.framework/Resources
1830 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001831 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001832 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001833 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001834 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001835 if (debugserver_exists)
1836 {
1837 g_debugserver_file_spec = debugserver_file_spec;
1838 }
1839 else
1840 {
1841 g_debugserver_file_spec.Clear();
1842 debugserver_file_spec.Clear();
1843 }
Chris Lattner24943d22010-06-08 16:52:24 +00001844 }
1845 }
1846
1847 if (debugserver_exists)
1848 {
1849 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1850
1851 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001852
Greg Claytone005f2c2010-11-06 01:53:30 +00001853 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001854
Greg Claytonb72d0f02011-04-12 05:54:46 +00001855 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00001856 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001857
Chris Lattner24943d22010-06-08 16:52:24 +00001858 // Start args with "debugserver /file/path -r --"
1859 debugserver_args.AppendArgument(debugserver_path);
1860 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001861 // use native registers, not the GDB registers
1862 debugserver_args.AppendArgument("--native-regs");
1863 // make debugserver run in its own session so signals generated by
1864 // special terminal key sequences (^C) don't affect debugserver
1865 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001866
Chris Lattner24943d22010-06-08 16:52:24 +00001867 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1868 if (env_debugserver_log_file)
1869 {
1870 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1871 debugserver_args.AppendArgument(arg_cstr);
1872 }
1873
1874 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1875 if (env_debugserver_log_flags)
1876 {
1877 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1878 debugserver_args.AppendArgument(arg_cstr);
1879 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001880// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001881// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001882
Greg Claytonb72d0f02011-04-12 05:54:46 +00001883 // We currently send down all arguments, attach pids, or attach
1884 // process names in dedicated GDB server packets, so we don't need
1885 // to pass them as arguments. This is currently because of all the
1886 // things we need to setup prior to launching: the environment,
1887 // current working dir, file actions, etc.
1888#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00001889 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001890 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001891 {
Greg Claytona2f74232011-02-24 22:24:29 +00001892 // Terminate the debugserver args so we can now append the inferior args
1893 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001894
Greg Claytona2f74232011-02-24 22:24:29 +00001895 for (int i = 0; inferior_argv[i] != NULL; ++i)
1896 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001897 }
1898 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1899 {
1900 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1901 debugserver_args.AppendArgument (arg_cstr);
1902 }
1903 else if (attach_name && attach_name[0])
1904 {
1905 if (wait_for_launch)
1906 debugserver_args.AppendArgument ("--waitfor");
1907 else
1908 debugserver_args.AppendArgument ("--attach");
1909 debugserver_args.AppendArgument (attach_name);
1910 }
Chris Lattner24943d22010-06-08 16:52:24 +00001911#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00001912
1913 ProcessLaunchInfo::FileAction file_action;
1914
1915 // Close STDIN, STDOUT and STDERR. We might need to redirect them
1916 // to "/dev/null" if we run into any problems.
1917 file_action.Close (STDIN_FILENO);
1918 launch_info.AppendFileAction (file_action);
1919 file_action.Close (STDOUT_FILENO);
1920 launch_info.AppendFileAction (file_action);
1921 file_action.Close (STDERR_FILENO);
1922 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00001923
1924 if (log)
1925 {
1926 StreamString strm;
1927 debugserver_args.Dump (&strm);
1928 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1929 }
1930
Greg Claytonb72d0f02011-04-12 05:54:46 +00001931 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00001932
Greg Claytonb72d0f02011-04-12 05:54:46 +00001933 if (error.Success ())
1934 m_debugserver_pid = launch_info.GetProcessID();
1935 else
Chris Lattner24943d22010-06-08 16:52:24 +00001936 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1937
1938 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001939 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001940 }
1941 else
1942 {
1943 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1944 }
1945
1946 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1947 StartAsyncThread ();
1948 }
1949 return error;
1950}
1951
1952bool
1953ProcessGDBRemote::MonitorDebugserverProcess
1954(
1955 void *callback_baton,
1956 lldb::pid_t debugserver_pid,
1957 int signo, // Zero for no signal
1958 int exit_status // Exit value of process if signal is zero
1959)
1960{
1961 // We pass in the ProcessGDBRemote inferior process it and name it
1962 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1963 // pointer value itself, thus we need the double cast...
1964
1965 // "debugserver_pid" argument passed in is the process ID for
1966 // debugserver that we are tracking...
1967
Greg Clayton75ccf502010-08-21 02:22:51 +00001968 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00001969
1970 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1971 if (log)
1972 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
1973
Greg Clayton75ccf502010-08-21 02:22:51 +00001974 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001975 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001976 // Sleep for a half a second to make sure our inferior process has
1977 // time to set its exit status before we set it incorrectly when
1978 // both the debugserver and the inferior process shut down.
1979 usleep (500000);
1980 // If our process hasn't yet exited, debugserver might have died.
1981 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001982 const StateType state = process->GetState();
1983
1984 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1985 state != eStateInvalid &&
1986 state != eStateUnloaded &&
1987 state != eStateExited &&
1988 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001989 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001990 char error_str[1024];
1991 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001992 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001993 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1994 if (signal_cstr)
1995 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001996 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001997 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001998 }
1999 else
2000 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002001 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002003
2004 process->SetExitStatus (-1, error_str);
2005 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002006 // Debugserver has exited we need to let our ProcessGDBRemote
2007 // know that it no longer has a debugserver instance
2008 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2009 // We are returning true to this function below, so we can
2010 // forget about the monitor handle.
2011 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002012 }
2013 return true;
2014}
2015
2016void
2017ProcessGDBRemote::KillDebugserverProcess ()
2018{
2019 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2020 {
2021 ::kill (m_debugserver_pid, SIGINT);
2022 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2023 }
2024}
2025
2026void
2027ProcessGDBRemote::Initialize()
2028{
2029 static bool g_initialized = false;
2030
2031 if (g_initialized == false)
2032 {
2033 g_initialized = true;
2034 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2035 GetPluginDescriptionStatic(),
2036 CreateInstance);
2037
2038 Log::Callbacks log_callbacks = {
2039 ProcessGDBRemoteLog::DisableLog,
2040 ProcessGDBRemoteLog::EnableLog,
2041 ProcessGDBRemoteLog::ListLogCategories
2042 };
2043
2044 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2045 }
2046}
2047
2048bool
Chris Lattner24943d22010-06-08 16:52:24 +00002049ProcessGDBRemote::StartAsyncThread ()
2050{
Greg Claytone005f2c2010-11-06 01:53:30 +00002051 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002052
2053 if (log)
2054 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2055
2056 // Create a thread that watches our internal state and controls which
2057 // events make it to clients (into the DCProcess event queue).
2058 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002059 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002060}
2061
2062void
2063ProcessGDBRemote::StopAsyncThread ()
2064{
Greg Claytone005f2c2010-11-06 01:53:30 +00002065 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002066
2067 if (log)
2068 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2069
2070 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2071
2072 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002073 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002074 {
2075 Host::ThreadJoin (m_async_thread, NULL, NULL);
2076 }
2077}
2078
2079
2080void *
2081ProcessGDBRemote::AsyncThread (void *arg)
2082{
2083 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2084
Greg Claytone005f2c2010-11-06 01:53:30 +00002085 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002086 if (log)
2087 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2088
2089 Listener listener ("ProcessGDBRemote::AsyncThread");
2090 EventSP event_sp;
2091 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2092 eBroadcastBitAsyncThreadShouldExit;
2093
2094 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2095 {
Greg Claytona2f74232011-02-24 22:24:29 +00002096 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2097
Chris Lattner24943d22010-06-08 16:52:24 +00002098 bool done = false;
2099 while (!done)
2100 {
2101 if (log)
2102 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2103 if (listener.WaitForEvent (NULL, event_sp))
2104 {
2105 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002106 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002107 {
Greg Claytona2f74232011-02-24 22:24:29 +00002108 if (log)
2109 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002110
Greg Claytona2f74232011-02-24 22:24:29 +00002111 switch (event_type)
2112 {
2113 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002114 {
Greg Claytona2f74232011-02-24 22:24:29 +00002115 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002116
Greg Claytona2f74232011-02-24 22:24:29 +00002117 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002118 {
Greg Claytona2f74232011-02-24 22:24:29 +00002119 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2120 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2121 if (log)
2122 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002123
Greg Claytona2f74232011-02-24 22:24:29 +00002124 if (::strstr (continue_cstr, "vAttach") == NULL)
2125 process->SetPrivateState(eStateRunning);
2126 StringExtractorGDBRemote response;
2127 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002128
Greg Claytona2f74232011-02-24 22:24:29 +00002129 switch (stop_state)
2130 {
2131 case eStateStopped:
2132 case eStateCrashed:
2133 case eStateSuspended:
2134 process->m_last_stop_packet = response;
2135 process->m_last_stop_packet.SetFilePos (0);
2136 process->SetPrivateState (stop_state);
2137 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002138
Greg Claytona2f74232011-02-24 22:24:29 +00002139 case eStateExited:
2140 process->m_last_stop_packet = response;
2141 process->m_last_stop_packet.SetFilePos (0);
2142 response.SetFilePos(1);
2143 process->SetExitStatus(response.GetHexU8(), NULL);
2144 done = true;
2145 break;
2146
2147 case eStateInvalid:
2148 process->SetExitStatus(-1, "lost connection");
2149 break;
2150
2151 default:
2152 process->SetPrivateState (stop_state);
2153 break;
2154 }
Chris Lattner24943d22010-06-08 16:52:24 +00002155 }
2156 }
Greg Claytona2f74232011-02-24 22:24:29 +00002157 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002158
Greg Claytona2f74232011-02-24 22:24:29 +00002159 case eBroadcastBitAsyncThreadShouldExit:
2160 if (log)
2161 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2162 done = true;
2163 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002164
Greg Claytona2f74232011-02-24 22:24:29 +00002165 default:
2166 if (log)
2167 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2168 done = true;
2169 break;
2170 }
2171 }
2172 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2173 {
2174 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2175 {
2176 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002177 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002178 }
Chris Lattner24943d22010-06-08 16:52:24 +00002179 }
2180 }
2181 else
2182 {
2183 if (log)
2184 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2185 done = true;
2186 }
2187 }
2188 }
2189
2190 if (log)
2191 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2192
2193 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2194 return NULL;
2195}
2196
Chris Lattner24943d22010-06-08 16:52:24 +00002197const char *
2198ProcessGDBRemote::GetDispatchQueueNameForThread
2199(
2200 addr_t thread_dispatch_qaddr,
2201 std::string &dispatch_queue_name
2202)
2203{
2204 dispatch_queue_name.clear();
2205 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2206 {
2207 // Cache the dispatch_queue_offsets_addr value so we don't always have
2208 // to look it up
2209 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2210 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002211 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2212 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002213 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002214 if (module_sp)
2215 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2216
2217 if (dispatch_queue_offsets_symbol == NULL)
2218 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002219 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002220 if (module_sp)
2221 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2222 }
Chris Lattner24943d22010-06-08 16:52:24 +00002223 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002224 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002225
2226 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2227 return NULL;
2228 }
2229
2230 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002231 DataExtractor data (memory_buffer,
2232 sizeof(memory_buffer),
2233 m_target.GetArchitecture().GetByteOrder(),
2234 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002235
2236 // Excerpt from src/queue_private.h
2237 struct dispatch_queue_offsets_s
2238 {
2239 uint16_t dqo_version;
2240 uint16_t dqo_label;
2241 uint16_t dqo_label_size;
2242 } dispatch_queue_offsets;
2243
2244
2245 Error error;
2246 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2247 {
2248 uint32_t data_offset = 0;
2249 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2250 {
2251 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2252 {
2253 data_offset = 0;
2254 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2255 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2256 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2257 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2258 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2259 dispatch_queue_name.erase (bytes_read);
2260 }
2261 }
2262 }
2263 }
2264 if (dispatch_queue_name.empty())
2265 return NULL;
2266 return dispatch_queue_name.c_str();
2267}
2268
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002269//uint32_t
2270//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2271//{
2272// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2273// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2274// if (m_local_debugserver)
2275// {
2276// return Host::ListProcessesMatchingName (name, matches, pids);
2277// }
2278// else
2279// {
2280// // FIXME: Implement talking to the remote debugserver.
2281// return 0;
2282// }
2283//
2284//}
2285//
Jim Ingham55e01d82011-01-22 01:33:44 +00002286bool
2287ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2288 lldb_private::StoppointCallbackContext *context,
2289 lldb::user_id_t break_id,
2290 lldb::user_id_t break_loc_id)
2291{
2292 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2293 // run so I can stop it if that's what I want to do.
2294 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2295 if (log)
2296 log->Printf("Hit New Thread Notification breakpoint.");
2297 return false;
2298}
2299
2300
2301bool
2302ProcessGDBRemote::StartNoticingNewThreads()
2303{
2304 static const char *bp_names[] =
2305 {
2306 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002307 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002308 "_pthread_start",
2309 NULL
2310 };
2311
2312 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2313 size_t num_bps = m_thread_observation_bps.size();
2314 if (num_bps != 0)
2315 {
2316 for (int i = 0; i < num_bps; i++)
2317 {
2318 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2319 if (break_sp)
2320 {
2321 if (log)
2322 log->Printf("Enabled noticing new thread breakpoint.");
2323 break_sp->SetEnabled(true);
2324 }
2325 }
2326 }
2327 else
2328 {
2329 for (int i = 0; bp_names[i] != NULL; i++)
2330 {
2331 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2332 if (breakpoint)
2333 {
2334 if (log)
2335 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2336 m_thread_observation_bps.push_back(breakpoint->GetID());
2337 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2338 }
2339 else
2340 {
2341 if (log)
2342 log->Printf("Failed to create new thread notification breakpoint.");
2343 return false;
2344 }
2345 }
2346 }
2347
2348 return true;
2349}
2350
2351bool
2352ProcessGDBRemote::StopNoticingNewThreads()
2353{
Jim Inghamff276fe2011-02-08 05:19:01 +00002354 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2355 if (log)
2356 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002357 size_t num_bps = m_thread_observation_bps.size();
2358 if (num_bps != 0)
2359 {
2360 for (int i = 0; i < num_bps; i++)
2361 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002362
2363 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2364 if (break_sp)
2365 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002366 break_sp->SetEnabled(false);
2367 }
2368 }
2369 }
2370 return true;
2371}
2372
2373