blob: b434853120e3c73ba04c1a630a06a134fd018697 [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>
Chris Lattner24943d22010-06-08 16:52:24 +000016
17// C++ Includes
18#include <algorithm>
19#include <map>
20
21// Other libraries and framework includes
22
23#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000024#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/ArchSpec.h"
26#include "lldb/Core/Debugger.h"
27#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000028#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "lldb/Core/InputReader.h"
30#include "lldb/Core/Module.h"
31#include "lldb/Core/PluginManager.h"
32#include "lldb/Core/State.h"
33#include "lldb/Core/StreamString.h"
34#include "lldb/Core/Timer.h"
35#include "lldb/Host/TimeValue.h"
36#include "lldb/Symbol/ObjectFile.h"
37#include "lldb/Target/DynamicLoader.h"
38#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000040#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
42// Project includes
43#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000044#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045#include "GDBRemoteRegisterContext.h"
46#include "ProcessGDBRemote.h"
47#include "ProcessGDBRemoteLog.h"
48#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000049#include "StopInfoMachException.h"
50
Chris Lattner24943d22010-06-08 16:52:24 +000051
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#define DEBUGSERVER_BASENAME "debugserver"
54using namespace lldb;
55using namespace lldb_private;
56
Jim Inghamf9600482011-03-29 21:45:47 +000057static bool rand_initialized = false;
58
Chris Lattner24943d22010-06-08 16:52:24 +000059static inline uint16_t
60get_random_port ()
61{
Jim Inghamf9600482011-03-29 21:45:47 +000062 if (!rand_initialized)
63 {
64 rand_initialized = true;
65 sranddev();
66 }
Stephen Wilson50daf772011-03-25 18:16:28 +000067 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000068}
69
70
71const char *
72ProcessGDBRemote::GetPluginNameStatic()
73{
Greg Claytonb1888f22011-03-19 01:12:21 +000074 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77const char *
78ProcessGDBRemote::GetPluginDescriptionStatic()
79{
80 return "GDB Remote protocol based debugging plug-in.";
81}
82
83void
84ProcessGDBRemote::Terminate()
85{
86 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
87}
88
89
90Process*
91ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
92{
93 return new ProcessGDBRemote (target, listener);
94}
95
96bool
97ProcessGDBRemote::CanDebug(Target &target)
98{
99 // For now we are just making sure the file exists for a given module
100 ModuleSP exe_module_sp(target.GetExecutableModule());
101 if (exe_module_sp.get())
102 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000103 // However, if there is no executable module, we return true since we might be preparing to attach.
104 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000105}
106
107//----------------------------------------------------------------------
108// ProcessGDBRemote constructor
109//----------------------------------------------------------------------
110ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
111 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000113 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000114 m_gdb_comm(),
115 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000116 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000117 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
120 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000121 m_curr_tid (LLDB_INVALID_THREAD_ID),
122 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000123 m_z0_supported (1),
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{
134}
135
136//----------------------------------------------------------------------
137// Destructor
138//----------------------------------------------------------------------
139ProcessGDBRemote::~ProcessGDBRemote()
140{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000141 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000142 {
143 Host::ThreadCancel (m_debugserver_thread, NULL);
144 thread_result_t thread_result;
145 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
146 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
147 }
Chris Lattner24943d22010-06-08 16:52:24 +0000148 // m_mach_process.UnregisterNotificationCallbacks (this);
149 Clear();
150}
151
152//----------------------------------------------------------------------
153// PluginInterface
154//----------------------------------------------------------------------
155const char *
156ProcessGDBRemote::GetPluginName()
157{
158 return "Process debugging plug-in that uses the GDB remote protocol";
159}
160
161const char *
162ProcessGDBRemote::GetShortPluginName()
163{
164 return GetPluginNameStatic();
165}
166
167uint32_t
168ProcessGDBRemote::GetPluginVersion()
169{
170 return 1;
171}
172
173void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000174ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000175{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000176 if (!force && m_register_info.GetNumRegisters() > 0)
177 return;
178
179 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000180 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000181 uint32_t reg_offset = 0;
182 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000183 StringExtractorGDBRemote::ResponseType response_type;
184 for (response_type = StringExtractorGDBRemote::eResponse;
185 response_type == StringExtractorGDBRemote::eResponse;
186 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000187 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000188 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
189 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000190 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000191 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000193 response_type = response.GetResponseType();
194 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000195 {
196 std::string name;
197 std::string value;
198 ConstString reg_name;
199 ConstString alt_name;
200 ConstString set_name;
201 RegisterInfo reg_info = { NULL, // Name
202 NULL, // Alt name
203 0, // byte size
204 reg_offset, // offset
205 eEncodingUint, // encoding
206 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000207 {
208 LLDB_INVALID_REGNUM, // GCC reg num
209 LLDB_INVALID_REGNUM, // DWARF reg num
210 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000211 reg_num, // GDB reg num
212 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000213 }
214 };
215
216 while (response.GetNameColonValue(name, value))
217 {
218 if (name.compare("name") == 0)
219 {
220 reg_name.SetCString(value.c_str());
221 }
222 else if (name.compare("alt-name") == 0)
223 {
224 alt_name.SetCString(value.c_str());
225 }
226 else if (name.compare("bitsize") == 0)
227 {
228 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
229 }
230 else if (name.compare("offset") == 0)
231 {
232 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000233 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000234 {
235 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000236 }
237 }
238 else if (name.compare("encoding") == 0)
239 {
240 if (value.compare("uint") == 0)
241 reg_info.encoding = eEncodingUint;
242 else if (value.compare("sint") == 0)
243 reg_info.encoding = eEncodingSint;
244 else if (value.compare("ieee754") == 0)
245 reg_info.encoding = eEncodingIEEE754;
246 else if (value.compare("vector") == 0)
247 reg_info.encoding = eEncodingVector;
248 }
249 else if (name.compare("format") == 0)
250 {
251 if (value.compare("binary") == 0)
252 reg_info.format = eFormatBinary;
253 else if (value.compare("decimal") == 0)
254 reg_info.format = eFormatDecimal;
255 else if (value.compare("hex") == 0)
256 reg_info.format = eFormatHex;
257 else if (value.compare("float") == 0)
258 reg_info.format = eFormatFloat;
259 else if (value.compare("vector-sint8") == 0)
260 reg_info.format = eFormatVectorOfSInt8;
261 else if (value.compare("vector-uint8") == 0)
262 reg_info.format = eFormatVectorOfUInt8;
263 else if (value.compare("vector-sint16") == 0)
264 reg_info.format = eFormatVectorOfSInt16;
265 else if (value.compare("vector-uint16") == 0)
266 reg_info.format = eFormatVectorOfUInt16;
267 else if (value.compare("vector-sint32") == 0)
268 reg_info.format = eFormatVectorOfSInt32;
269 else if (value.compare("vector-uint32") == 0)
270 reg_info.format = eFormatVectorOfUInt32;
271 else if (value.compare("vector-float32") == 0)
272 reg_info.format = eFormatVectorOfFloat32;
273 else if (value.compare("vector-uint128") == 0)
274 reg_info.format = eFormatVectorOfUInt128;
275 }
276 else if (name.compare("set") == 0)
277 {
278 set_name.SetCString(value.c_str());
279 }
280 else if (name.compare("gcc") == 0)
281 {
282 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
283 }
284 else if (name.compare("dwarf") == 0)
285 {
286 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
287 }
288 else if (name.compare("generic") == 0)
289 {
290 if (value.compare("pc") == 0)
291 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
292 else if (value.compare("sp") == 0)
293 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
294 else if (value.compare("fp") == 0)
295 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
296 else if (value.compare("ra") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
298 else if (value.compare("flags") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
300 }
301 }
302
Jason Molenda53d96862010-06-11 23:44:18 +0000303 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000304 assert (reg_info.byte_size != 0);
305 reg_offset += reg_info.byte_size;
306 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
307 }
308 }
309 else
310 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000311 response_type = StringExtractorGDBRemote::eError;
Chris Lattner24943d22010-06-08 16:52:24 +0000312 }
313 }
314
315 if (reg_num == 0)
316 {
317 // We didn't get anything. See if we are debugging ARM and fill with
318 // a hard coded register set until we can get an updated debugserver
319 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000320 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000321 m_register_info.HardcodeARMRegisters();
322 }
323 m_register_info.Finalize ();
324}
325
326Error
327ProcessGDBRemote::WillLaunch (Module* module)
328{
329 return WillLaunchOrAttach ();
330}
331
332Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000333ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000334{
335 return WillLaunchOrAttach ();
336}
337
338Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000339ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Claytone71e2582011-02-04 01:58:07 +0000345ProcessGDBRemote::DoConnectRemote (const char *remote_url)
346{
347 Error error (WillLaunchOrAttach ());
348
349 if (error.Fail())
350 return error;
351
352 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
353 {
354 error = ConnectToDebugserver (remote_url);
355 }
356 else
357 {
358 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
359 }
360
361 if (error.Fail())
362 return error;
363 StartAsyncThread ();
364
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000365 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000366 if (pid == LLDB_INVALID_PROCESS_ID)
367 {
368 // We don't have a valid process ID, so note that we are connected
369 // and could now request to launch or attach, or get remote process
370 // listings...
371 SetPrivateState (eStateConnected);
372 }
373 else
374 {
375 // We have a valid process
376 SetID (pid);
377 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000378 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000379 {
380 const StateType state = SetThreadStopInfo (response);
381 if (state == eStateStopped)
382 {
383 SetPrivateState (state);
384 }
385 else
386 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
387 }
388 else
389 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
390 }
391 return error;
392}
393
394Error
Chris Lattner24943d22010-06-08 16:52:24 +0000395ProcessGDBRemote::WillLaunchOrAttach ()
396{
397 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000398 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000399 return error;
400}
401
402//----------------------------------------------------------------------
403// Process Control
404//----------------------------------------------------------------------
405Error
406ProcessGDBRemote::DoLaunch
407(
408 Module* module,
409 char const *argv[],
410 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000411 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000412 const char *stdin_path,
413 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000414 const char *stderr_path,
415 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000416)
417{
Greg Clayton4b407112010-09-30 21:49:03 +0000418 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000419 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
420 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
421 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000422
423 ObjectFile * object_file = module->GetObjectFile();
424 if (object_file)
425 {
426 ArchSpec inferior_arch(module->GetArchitecture());
427 char host_port[128];
428 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000429 char connect_url[128];
430 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000431
Greg Claytona2f74232011-02-24 22:24:29 +0000432 // Make sure we aren't already connected?
433 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000434 {
435 error = StartDebugserverProcess (host_port,
436 NULL,
437 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000438 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000439 NULL,
440 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000441 inferior_arch);
442 if (error.Fail())
443 return error;
444
Greg Claytone71e2582011-02-04 01:58:07 +0000445 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000446 }
447
448 if (error.Success())
449 {
450 lldb_utility::PseudoTerminal pty;
451 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000452
453 // If the debugserver is local and we aren't disabling STDIO, lets use
454 // a pseudo terminal to instead of relying on the 'O' packets for stdio
455 // since 'O' packets can really slow down debugging if the inferior
456 // does a lot of output.
457 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000458 {
459 const char *slave_name = NULL;
460 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000461 {
Greg Claytona2f74232011-02-24 22:24:29 +0000462 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
463 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000464 }
Greg Claytona2f74232011-02-24 22:24:29 +0000465 if (stdin_path == NULL)
466 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000467
Greg Claytona2f74232011-02-24 22:24:29 +0000468 if (stdout_path == NULL)
469 stdout_path = slave_name;
470
471 if (stderr_path == NULL)
472 stderr_path = slave_name;
473 }
474
Greg Claytonafb81862011-03-02 21:34:46 +0000475 // Set STDIN to /dev/null if we want STDIO disabled or if either
476 // STDOUT or STDERR have been set to something and STDIN hasn't
477 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000478 stdin_path = "/dev/null";
479
Greg Claytonafb81862011-03-02 21:34:46 +0000480 // Set STDOUT to /dev/null if we want STDIO disabled or if either
481 // STDIN or STDERR have been set to something and STDOUT hasn't
482 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000483 stdout_path = "/dev/null";
484
Greg Claytonafb81862011-03-02 21:34:46 +0000485 // Set STDERR to /dev/null if we want STDIO disabled or if either
486 // STDIN or STDOUT have been set to something and STDERR hasn't
487 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000488 stderr_path = "/dev/null";
489
490 if (stdin_path)
491 m_gdb_comm.SetSTDIN (stdin_path);
492 if (stdout_path)
493 m_gdb_comm.SetSTDOUT (stdout_path);
494 if (stderr_path)
495 m_gdb_comm.SetSTDERR (stderr_path);
496
497 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
498
499
500 if (working_dir && working_dir[0])
501 {
502 m_gdb_comm.SetWorkingDir (working_dir);
503 }
504
505 // Send the environment and the program + arguments after we connect
506 if (envp)
507 {
508 const char *env_entry;
509 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000510 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000511 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000512 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000513 }
Greg Claytona2f74232011-02-24 22:24:29 +0000514 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000515
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000516 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
517 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
518 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000519 if (arg_packet_err == 0)
520 {
521 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000522 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000523 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000524 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
526 else
527 {
Greg Claytona2f74232011-02-24 22:24:29 +0000528 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000529 }
Greg Claytona2f74232011-02-24 22:24:29 +0000530 }
531 else
532 {
533 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
534 }
Chris Lattner24943d22010-06-08 16:52:24 +0000535
Greg Claytona2f74232011-02-24 22:24:29 +0000536 if (GetID() == LLDB_INVALID_PROCESS_ID)
537 {
538 KillDebugserverProcess ();
539 return error;
540 }
541
542 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000543 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000544 {
545 SetPrivateState (SetThreadStopInfo (response));
546
547 if (!disable_stdio)
548 {
549 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
550 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
551 }
Chris Lattner24943d22010-06-08 16:52:24 +0000552 }
553 }
Chris Lattner24943d22010-06-08 16:52:24 +0000554 }
555 else
556 {
557 // Set our user ID to an invalid process ID.
558 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000559 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
560 module->GetFileSpec().GetFilename().AsCString(),
561 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
Chris Lattner24943d22010-06-08 16:52:24 +0000563 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000564
Chris Lattner24943d22010-06-08 16:52:24 +0000565}
566
567
568Error
Greg Claytone71e2582011-02-04 01:58:07 +0000569ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000570{
571 Error error;
572 // Sleep and wait a bit for debugserver to start to listen...
573 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
574 if (conn_ap.get())
575 {
Chris Lattner24943d22010-06-08 16:52:24 +0000576 const uint32_t max_retry_count = 50;
577 uint32_t retry_count = 0;
578 while (!m_gdb_comm.IsConnected())
579 {
Greg Claytone71e2582011-02-04 01:58:07 +0000580 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000581 {
582 m_gdb_comm.SetConnection (conn_ap.release());
583 break;
584 }
585 retry_count++;
586
587 if (retry_count >= max_retry_count)
588 break;
589
590 usleep (100000);
591 }
592 }
593
594 if (!m_gdb_comm.IsConnected())
595 {
596 if (error.Success())
597 error.SetErrorString("not connected to remote gdb server");
598 return error;
599 }
600
Chris Lattner24943d22010-06-08 16:52:24 +0000601 if (m_gdb_comm.StartReadThread(&error))
602 {
603 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000604 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000605
606 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000607 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
608 this,
609 m_debugserver_pid,
610 false);
611
Greg Claytonc1f45872011-02-12 06:28:37 +0000612 m_gdb_comm.ResetDiscoverableSettings();
613 m_gdb_comm.GetSendAcks ();
614 m_gdb_comm.GetThreadSuffixSupported ();
615 m_gdb_comm.GetHostInfo ();
616 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000617 }
618 return error;
619}
620
621void
622ProcessGDBRemote::DidLaunchOrAttach ()
623{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000624 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
625 if (log)
626 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000627 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000628 {
629 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
630
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000631 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000632
Greg Clayton20d338f2010-11-18 05:57:03 +0000633
Chris Lattner24943d22010-06-08 16:52:24 +0000634 StreamString strm;
635
Chris Lattner24943d22010-06-08 16:52:24 +0000636 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000637
Greg Claytoncb8977d2011-03-23 00:09:55 +0000638 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
639 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000640 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000641 ArchSpec &target_arch = GetTarget().GetArchitecture();
642
643 if (target_arch.IsValid())
644 {
645 // If the remote host is ARM and we have apple as the vendor, then
646 // ARM executables and shared libraries can have mixed ARM architectures.
647 // You can have an armv6 executable, and if the host is armv7, then the
648 // system will load the best possible architecture for all shared libraries
649 // it has, so we really need to take the remote host architecture as our
650 // defacto architecture in this case.
651
652 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
653 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
654 {
655 target_arch = gdb_remote_arch;
656 }
657 else
658 {
659 // Fill in what is missing in the triple
660 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
661 llvm::Triple &target_triple = target_arch.GetTriple();
662 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
663 target_triple.setVendor (remote_triple.getVendor());
664
665 if (target_triple.getOS() == llvm::Triple::UnknownOS)
666 target_triple.setOS (remote_triple.getOS());
667
668 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
669 target_triple.setEnvironment (remote_triple.getEnvironment());
670 }
671 }
672 else
673 {
674 // The target doesn't have a valid architecture yet, set it from
675 // the architecture we got from the remote GDB server
676 target_arch = gdb_remote_arch;
677 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000678 }
Chris Lattner24943d22010-06-08 16:52:24 +0000679 }
680}
681
682void
683ProcessGDBRemote::DidLaunch ()
684{
685 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000686}
687
688Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000689ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000690{
691 Error error;
692 // Clear out and clean up from any current state
693 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000694 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000695
Chris Lattner24943d22010-06-08 16:52:24 +0000696 if (attach_pid != LLDB_INVALID_PROCESS_ID)
697 {
Greg Claytona2f74232011-02-24 22:24:29 +0000698 // Make sure we aren't already connected?
699 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000700 {
Greg Claytona2f74232011-02-24 22:24:29 +0000701 char host_port[128];
702 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
703 char connect_url[128];
704 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000705
Greg Claytona2f74232011-02-24 22:24:29 +0000706 error = StartDebugserverProcess (host_port, // debugserver_url
707 NULL, // inferior_argv
708 NULL, // inferior_envp
709 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
710 NULL, // Don't send any attach by process name option to debugserver
711 false, // Don't send any attach wait_for_launch flag as an option to debugserver
712 arch_spec);
713
714 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000715 {
Greg Claytona2f74232011-02-24 22:24:29 +0000716 const char *error_string = error.AsCString();
717 if (error_string == NULL)
718 error_string = "unable to launch " DEBUGSERVER_BASENAME;
719
720 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000721 }
Greg Claytona2f74232011-02-24 22:24:29 +0000722 else
723 {
724 error = ConnectToDebugserver (connect_url);
725 }
726 }
727
728 if (error.Success())
729 {
730 char packet[64];
731 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
732
733 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000734 }
735 }
Chris Lattner24943d22010-06-08 16:52:24 +0000736 return error;
737}
738
739size_t
740ProcessGDBRemote::AttachInputReaderCallback
741(
742 void *baton,
743 InputReader *reader,
744 lldb::InputReaderAction notification,
745 const char *bytes,
746 size_t bytes_len
747)
748{
749 if (notification == eInputReaderGotToken)
750 {
751 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
752 if (gdb_process->m_waiting_for_attach)
753 gdb_process->m_waiting_for_attach = false;
754 reader->SetIsDone(true);
755 return 1;
756 }
757 return 0;
758}
759
760Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000761ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000762{
763 Error error;
764 // Clear out and clean up from any current state
765 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000766
Chris Lattner24943d22010-06-08 16:52:24 +0000767 if (process_name && process_name[0])
768 {
Greg Claytona2f74232011-02-24 22:24:29 +0000769 // Make sure we aren't already connected?
770 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000771 {
Chris Lattner24943d22010-06-08 16:52:24 +0000772
Greg Claytona2f74232011-02-24 22:24:29 +0000773 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
774
775 char host_port[128];
776 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
777 char connect_url[128];
778 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
779
780 error = StartDebugserverProcess (host_port, // debugserver_url
781 NULL, // inferior_argv
782 NULL, // inferior_envp
783 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
784 NULL, // Don't send any attach by process name option to debugserver
785 false, // Don't send any attach wait_for_launch flag as an option to debugserver
786 arch_spec);
787 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000788 {
Greg Claytona2f74232011-02-24 22:24:29 +0000789 const char *error_string = error.AsCString();
790 if (error_string == NULL)
791 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000792
Greg Claytona2f74232011-02-24 22:24:29 +0000793 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000794 }
Greg Claytona2f74232011-02-24 22:24:29 +0000795 else
796 {
797 error = ConnectToDebugserver (connect_url);
798 }
799 }
800
801 if (error.Success())
802 {
803 StreamString packet;
804
805 if (wait_for_launch)
806 packet.PutCString("vAttachWait");
807 else
808 packet.PutCString("vAttachName");
809 packet.PutChar(';');
810 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
811
812 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
813
Chris Lattner24943d22010-06-08 16:52:24 +0000814 }
815 }
Chris Lattner24943d22010-06-08 16:52:24 +0000816 return error;
817}
818
Chris Lattner24943d22010-06-08 16:52:24 +0000819
820void
821ProcessGDBRemote::DidAttach ()
822{
Greg Claytone71e2582011-02-04 01:58:07 +0000823 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000824}
825
826Error
827ProcessGDBRemote::WillResume ()
828{
Greg Claytonc1f45872011-02-12 06:28:37 +0000829 m_continue_c_tids.clear();
830 m_continue_C_tids.clear();
831 m_continue_s_tids.clear();
832 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000833 return Error();
834}
835
836Error
837ProcessGDBRemote::DoResume ()
838{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000839 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000840 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
841 if (log)
842 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000843
844 Listener listener ("gdb-remote.resume-packet-sent");
845 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
846 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000847 StreamString continue_packet;
848 bool continue_packet_error = false;
849 if (m_gdb_comm.HasAnyVContSupport ())
850 {
851 continue_packet.PutCString ("vCont");
852
853 if (!m_continue_c_tids.empty())
854 {
855 if (m_gdb_comm.GetVContSupported ('c'))
856 {
857 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)
858 continue_packet.Printf(";c:%4.4x", *t_pos);
859 }
860 else
861 continue_packet_error = true;
862 }
863
864 if (!continue_packet_error && !m_continue_C_tids.empty())
865 {
866 if (m_gdb_comm.GetVContSupported ('C'))
867 {
868 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)
869 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
870 }
871 else
872 continue_packet_error = true;
873 }
Greg Claytonb749a262010-12-03 06:02:24 +0000874
Greg Claytonc1f45872011-02-12 06:28:37 +0000875 if (!continue_packet_error && !m_continue_s_tids.empty())
876 {
877 if (m_gdb_comm.GetVContSupported ('s'))
878 {
879 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)
880 continue_packet.Printf(";s:%4.4x", *t_pos);
881 }
882 else
883 continue_packet_error = true;
884 }
885
886 if (!continue_packet_error && !m_continue_S_tids.empty())
887 {
888 if (m_gdb_comm.GetVContSupported ('S'))
889 {
890 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)
891 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
892 }
893 else
894 continue_packet_error = true;
895 }
896
897 if (continue_packet_error)
898 continue_packet.GetString().clear();
899 }
900 else
901 continue_packet_error = true;
902
903 if (continue_packet_error)
904 {
905 continue_packet_error = false;
906 // Either no vCont support, or we tried to use part of the vCont
907 // packet that wasn't supported by the remote GDB server.
908 // We need to try and make a simple packet that can do our continue
909 const size_t num_threads = GetThreadList().GetSize();
910 const size_t num_continue_c_tids = m_continue_c_tids.size();
911 const size_t num_continue_C_tids = m_continue_C_tids.size();
912 const size_t num_continue_s_tids = m_continue_s_tids.size();
913 const size_t num_continue_S_tids = m_continue_S_tids.size();
914 if (num_continue_c_tids > 0)
915 {
916 if (num_continue_c_tids == num_threads)
917 {
918 // All threads are resuming...
919 SetCurrentGDBRemoteThreadForRun (-1);
920 continue_packet.PutChar ('c');
921 }
922 else if (num_continue_c_tids == 1 &&
923 num_continue_C_tids == 0 &&
924 num_continue_s_tids == 0 &&
925 num_continue_S_tids == 0 )
926 {
927 // Only one thread is continuing
928 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
929 continue_packet.PutChar ('c');
930 }
931 else
932 {
933 // We can't represent this continue packet....
934 continue_packet_error = true;
935 }
936 }
937
938 if (!continue_packet_error && num_continue_C_tids > 0)
939 {
940 if (num_continue_C_tids == num_threads)
941 {
942 const int continue_signo = m_continue_C_tids.front().second;
943 if (num_continue_C_tids > 1)
944 {
945 for (size_t i=1; i<num_threads; ++i)
946 {
947 if (m_continue_C_tids[i].second != continue_signo)
948 continue_packet_error = true;
949 }
950 }
951 if (!continue_packet_error)
952 {
953 // Add threads continuing with the same signo...
954 SetCurrentGDBRemoteThreadForRun (-1);
955 continue_packet.Printf("C%2.2x", continue_signo);
956 }
957 }
958 else if (num_continue_c_tids == 0 &&
959 num_continue_C_tids == 1 &&
960 num_continue_s_tids == 0 &&
961 num_continue_S_tids == 0 )
962 {
963 // Only one thread is continuing with signal
964 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
965 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
966 }
967 else
968 {
969 // We can't represent this continue packet....
970 continue_packet_error = true;
971 }
972 }
973
974 if (!continue_packet_error && num_continue_s_tids > 0)
975 {
976 if (num_continue_s_tids == num_threads)
977 {
978 // All threads are resuming...
979 SetCurrentGDBRemoteThreadForRun (-1);
980 continue_packet.PutChar ('s');
981 }
982 else if (num_continue_c_tids == 0 &&
983 num_continue_C_tids == 0 &&
984 num_continue_s_tids == 1 &&
985 num_continue_S_tids == 0 )
986 {
987 // Only one thread is stepping
988 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
989 continue_packet.PutChar ('s');
990 }
991 else
992 {
993 // We can't represent this continue packet....
994 continue_packet_error = true;
995 }
996 }
997
998 if (!continue_packet_error && num_continue_S_tids > 0)
999 {
1000 if (num_continue_S_tids == num_threads)
1001 {
1002 const int step_signo = m_continue_S_tids.front().second;
1003 // Are all threads trying to step with the same signal?
1004 if (num_continue_S_tids > 1)
1005 {
1006 for (size_t i=1; i<num_threads; ++i)
1007 {
1008 if (m_continue_S_tids[i].second != step_signo)
1009 continue_packet_error = true;
1010 }
1011 }
1012 if (!continue_packet_error)
1013 {
1014 // Add threads stepping with the same signo...
1015 SetCurrentGDBRemoteThreadForRun (-1);
1016 continue_packet.Printf("S%2.2x", step_signo);
1017 }
1018 }
1019 else if (num_continue_c_tids == 0 &&
1020 num_continue_C_tids == 0 &&
1021 num_continue_s_tids == 0 &&
1022 num_continue_S_tids == 1 )
1023 {
1024 // Only one thread is stepping with signal
1025 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1026 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1027 }
1028 else
1029 {
1030 // We can't represent this continue packet....
1031 continue_packet_error = true;
1032 }
1033 }
1034 }
1035
1036 if (continue_packet_error)
1037 {
1038 error.SetErrorString ("can't make continue packet for this resume");
1039 }
1040 else
1041 {
1042 EventSP event_sp;
1043 TimeValue timeout;
1044 timeout = TimeValue::Now();
1045 timeout.OffsetWithSeconds (5);
1046 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1047
1048 if (listener.WaitForEvent (&timeout, event_sp) == false)
1049 error.SetErrorString("Resume timed out.");
1050 }
Greg Claytonb749a262010-12-03 06:02:24 +00001051 }
1052
Jim Ingham3ae449a2010-11-17 02:32:00 +00001053 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001054}
1055
Chris Lattner24943d22010-06-08 16:52:24 +00001056uint32_t
1057ProcessGDBRemote::UpdateThreadListIfNeeded ()
1058{
1059 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001060 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001061 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001062 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1063
Greg Clayton5205f0b2010-09-03 17:10:42 +00001064 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001065 const uint32_t stop_id = GetStopID();
1066 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1067 {
1068 // Update the thread list's stop id immediately so we don't recurse into this function.
1069 ThreadList curr_thread_list (this);
1070 curr_thread_list.SetStopID(stop_id);
1071
1072 Error err;
1073 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001074 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001075 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001076 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001077 {
1078 char ch = response.GetChar();
1079 if (ch == 'l')
1080 break;
1081 if (ch == 'm')
1082 {
1083 do
1084 {
1085 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1086
1087 if (tid != LLDB_INVALID_THREAD_ID)
1088 {
1089 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001090 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001091 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1092 curr_thread_list.AddThread(thread_sp);
1093 }
1094
1095 ch = response.GetChar();
1096 } while (ch == ',');
1097 }
1098 }
1099
1100 m_thread_list = curr_thread_list;
1101
1102 SetThreadStopInfo (m_last_stop_packet);
1103 }
1104 return GetThreadList().GetSize(false);
1105}
1106
1107
1108StateType
1109ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1110{
1111 const char stop_type = stop_packet.GetChar();
1112 switch (stop_type)
1113 {
1114 case 'T':
1115 case 'S':
1116 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001117 if (GetStopID() == 0)
1118 {
1119 // Our first stop, make sure we have a process ID, and also make
1120 // sure we know about our registers
1121 if (GetID() == LLDB_INVALID_PROCESS_ID)
1122 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001123 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001124 if (pid != LLDB_INVALID_PROCESS_ID)
1125 SetID (pid);
1126 }
1127 BuildDynamicRegisterInfo (true);
1128 }
Chris Lattner24943d22010-06-08 16:52:24 +00001129 // Stop with signal and thread info
1130 const uint8_t signo = stop_packet.GetHexU8();
1131 std::string name;
1132 std::string value;
1133 std::string thread_name;
1134 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001135 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001136 uint32_t tid = LLDB_INVALID_THREAD_ID;
1137 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1138 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001139 ThreadSP thread_sp;
1140
Chris Lattner24943d22010-06-08 16:52:24 +00001141 while (stop_packet.GetNameColonValue(name, value))
1142 {
1143 if (name.compare("metype") == 0)
1144 {
1145 // exception type in big endian hex
1146 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1147 }
1148 else if (name.compare("mecount") == 0)
1149 {
1150 // exception count in big endian hex
1151 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1152 }
1153 else if (name.compare("medata") == 0)
1154 {
1155 // exception data in big endian hex
1156 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1157 }
1158 else if (name.compare("thread") == 0)
1159 {
1160 // thread in big endian hex
1161 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001162 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001163 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001164 if (!thread_sp)
1165 {
1166 // Create the thread if we need to
1167 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1168 m_thread_list.AddThread(thread_sp);
1169 }
Chris Lattner24943d22010-06-08 16:52:24 +00001170 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001171 else if (name.compare("hexname") == 0)
1172 {
1173 StringExtractor name_extractor;
1174 // Swap "value" over into "name_extractor"
1175 name_extractor.GetStringRef().swap(value);
1176 // Now convert the HEX bytes into a string value
1177 name_extractor.GetHexByteString (value);
1178 thread_name.swap (value);
1179 }
Chris Lattner24943d22010-06-08 16:52:24 +00001180 else if (name.compare("name") == 0)
1181 {
1182 thread_name.swap (value);
1183 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001184 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001185 {
1186 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1187 }
Greg Claytona875b642011-01-09 21:07:35 +00001188 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1189 {
1190 // We have a register number that contains an expedited
1191 // register value. Lets supply this register to our thread
1192 // so it won't have to go and read it.
1193 if (thread_sp)
1194 {
1195 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1196
1197 if (reg != UINT32_MAX)
1198 {
1199 StringExtractor reg_value_extractor;
1200 // Swap "value" over into "reg_value_extractor"
1201 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001202 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1203 {
1204 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1205 name.c_str(),
1206 reg,
1207 reg,
1208 reg_value_extractor.GetStringRef().c_str(),
1209 stop_packet.GetStringRef().c_str());
1210 }
Greg Claytona875b642011-01-09 21:07:35 +00001211 }
1212 }
1213 }
Chris Lattner24943d22010-06-08 16:52:24 +00001214 }
Chris Lattner24943d22010-06-08 16:52:24 +00001215
1216 if (thread_sp)
1217 {
1218 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1219
1220 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001221 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001222 if (exc_type != 0)
1223 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001224 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001225
1226 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1227 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001228 exc_data_size,
1229 exc_data_size >= 1 ? exc_data[0] : 0,
1230 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001231 }
1232 else if (signo)
1233 {
Greg Clayton643ee732010-08-04 01:40:35 +00001234 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001235 }
1236 else
1237 {
Greg Clayton643ee732010-08-04 01:40:35 +00001238 StopInfoSP invalid_stop_info_sp;
1239 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001240 }
1241 }
1242 return eStateStopped;
1243 }
1244 break;
1245
1246 case 'W':
1247 // process exited
1248 return eStateExited;
1249
1250 default:
1251 break;
1252 }
1253 return eStateInvalid;
1254}
1255
1256void
1257ProcessGDBRemote::RefreshStateAfterStop ()
1258{
Jim Ingham7508e732010-08-09 23:31:02 +00001259 // FIXME - add a variable to tell that we're in the middle of attaching if we
1260 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001261 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001262// if (!GetTarget().GetArchitecture().IsValid())
1263// {
1264// Module *exe_module = GetTarget().GetExecutableModule().get();
1265// if (exe_module)
1266// m_arch_spec = exe_module->GetArchitecture();
1267// }
1268
Chris Lattner24943d22010-06-08 16:52:24 +00001269 // Let all threads recover from stopping and do any clean up based
1270 // on the previous thread state (if any).
1271 m_thread_list.RefreshStateAfterStop();
1272
1273 // Discover new threads:
1274 UpdateThreadListIfNeeded ();
1275}
1276
1277Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001278ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001279{
1280 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001281
Greg Claytona4881d02011-01-22 07:12:45 +00001282 bool timed_out = false;
1283 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001284
1285 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001286 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001287 // We are being asked to halt during an attach. We need to just close
1288 // our file handle and debugserver will go away, and we can be done...
1289 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001290 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001291 else
1292 {
1293 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1294 {
1295 if (timed_out)
1296 error.SetErrorString("timed out sending interrupt packet");
1297 else
1298 error.SetErrorString("unknown error sending interrupt packet");
1299 }
1300 }
Chris Lattner24943d22010-06-08 16:52:24 +00001301 return error;
1302}
1303
1304Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001305ProcessGDBRemote::InterruptIfRunning
1306(
1307 bool discard_thread_plans,
1308 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001309 EventSP &stop_event_sp
1310)
Chris Lattner24943d22010-06-08 16:52:24 +00001311{
1312 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001313
Greg Clayton2860ba92011-01-23 19:58:49 +00001314 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1315
Greg Clayton68ca8232011-01-25 02:58:48 +00001316 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001317 const bool is_running = m_gdb_comm.IsRunning();
1318 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001319 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001320 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001321 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001322 is_running);
1323
Greg Clayton2860ba92011-01-23 19:58:49 +00001324 if (discard_thread_plans)
1325 {
1326 if (log)
1327 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1328 m_thread_list.DiscardThreadPlans();
1329 }
1330 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001331 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001332 if (catch_stop_event)
1333 {
1334 if (log)
1335 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1336 PausePrivateStateThread();
1337 paused_private_state_thread = true;
1338 }
1339
Greg Clayton4fb400f2010-09-27 21:07:38 +00001340 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001341 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001342 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001343
Greg Clayton72e1c782011-01-22 23:43:18 +00001344 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001345 {
1346 if (timed_out)
1347 error.SetErrorString("timed out sending interrupt packet");
1348 else
1349 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001350 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001351 ResumePrivateStateThread();
1352 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001353 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001354
Greg Clayton72e1c782011-01-22 23:43:18 +00001355 if (catch_stop_event)
1356 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001357 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001358 TimeValue timeout_time;
1359 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001360 timeout_time.OffsetWithSeconds(5);
1361 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001362
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001363 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001364 if (log)
1365 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001366
Greg Clayton2860ba92011-01-23 19:58:49 +00001367 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001368 error.SetErrorString("unable to verify target stopped");
1369 }
1370
Greg Clayton68ca8232011-01-25 02:58:48 +00001371 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001372 {
1373 if (log)
1374 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001375 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001376 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001377 }
Chris Lattner24943d22010-06-08 16:52:24 +00001378 return error;
1379}
1380
Greg Clayton4fb400f2010-09-27 21:07:38 +00001381Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001382ProcessGDBRemote::WillDetach ()
1383{
Greg Clayton2860ba92011-01-23 19:58:49 +00001384 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1385 if (log)
1386 log->Printf ("ProcessGDBRemote::WillDetach()");
1387
Greg Clayton72e1c782011-01-22 23:43:18 +00001388 bool discard_thread_plans = true;
1389 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001390 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001391 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001392}
1393
1394Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001395ProcessGDBRemote::DoDetach()
1396{
1397 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001398 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001399 if (log)
1400 log->Printf ("ProcessGDBRemote::DoDetach()");
1401
1402 DisableAllBreakpointSites ();
1403
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001404 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001405
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001406 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1407 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001408 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001409 if (response_size)
1410 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1411 else
1412 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001413 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001414 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001415 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001416
Greg Clayton4fb400f2010-09-27 21:07:38 +00001417 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001418 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001419
1420 SetPrivateState (eStateDetached);
1421 ResumePrivateStateThread();
1422
1423 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424 return error;
1425}
Chris Lattner24943d22010-06-08 16:52:24 +00001426
1427Error
1428ProcessGDBRemote::DoDestroy ()
1429{
1430 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001431 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001432 if (log)
1433 log->Printf ("ProcessGDBRemote::DoDestroy()");
1434
1435 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001436 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001437 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001438 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001439 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001440 // We are being asked to halt during an attach. We need to just close
1441 // our file handle and debugserver will go away, and we can be done...
1442 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001443 }
1444 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001445 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001446
1447 StringExtractorGDBRemote response;
1448 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001449 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001450 {
1451 char packet_cmd = response.GetChar(0);
1452
1453 if (packet_cmd == 'W' || packet_cmd == 'X')
1454 {
1455 m_last_stop_packet = response;
1456 SetExitStatus(response.GetHexU8(), NULL);
1457 }
1458 }
1459 else
1460 {
1461 SetExitStatus(SIGABRT, NULL);
1462 //error.SetErrorString("kill packet failed");
1463 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001464 }
1465 }
Chris Lattner24943d22010-06-08 16:52:24 +00001466 StopAsyncThread ();
1467 m_gdb_comm.StopReadThread();
1468 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001469 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001470 return error;
1471}
1472
Chris Lattner24943d22010-06-08 16:52:24 +00001473//------------------------------------------------------------------
1474// Process Queries
1475//------------------------------------------------------------------
1476
1477bool
1478ProcessGDBRemote::IsAlive ()
1479{
Greg Clayton58e844b2010-12-08 05:08:21 +00001480 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001481}
1482
1483addr_t
1484ProcessGDBRemote::GetImageInfoAddress()
1485{
1486 if (!m_gdb_comm.IsRunning())
1487 {
1488 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001489 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001490 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001491 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001492 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1493 }
1494 }
1495 return LLDB_INVALID_ADDRESS;
1496}
1497
Chris Lattner24943d22010-06-08 16:52:24 +00001498//------------------------------------------------------------------
1499// Process Memory
1500//------------------------------------------------------------------
1501size_t
1502ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1503{
1504 if (size > m_max_memory_size)
1505 {
1506 // Keep memory read sizes down to a sane limit. This function will be
1507 // called multiple times in order to complete the task by
1508 // lldb_private::Process so it is ok to do this.
1509 size = m_max_memory_size;
1510 }
1511
1512 char packet[64];
1513 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1514 assert (packet_len + 1 < sizeof(packet));
1515 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001516 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001517 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001518 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001519 {
1520 error.Clear();
1521 return response.GetHexBytes(buf, size, '\xdd');
1522 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001523 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001524 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001525 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001526 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1527 else
1528 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1529 }
1530 else
1531 {
1532 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1533 }
1534 return 0;
1535}
1536
1537size_t
1538ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1539{
1540 StreamString packet;
1541 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001542 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001543 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001544 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001545 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001546 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001547 {
1548 error.Clear();
1549 return size;
1550 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001551 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001552 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001553 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001554 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1555 else
1556 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1557 }
1558 else
1559 {
1560 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1561 }
1562 return 0;
1563}
1564
1565lldb::addr_t
1566ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1567{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001568 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001569 if (allocated_addr == LLDB_INVALID_ADDRESS)
1570 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1571 else
1572 error.Clear();
1573 return allocated_addr;
1574}
1575
1576Error
1577ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1578{
1579 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001580 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001581 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1582 return error;
1583}
1584
1585
1586//------------------------------------------------------------------
1587// Process STDIO
1588//------------------------------------------------------------------
1589
1590size_t
1591ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1592{
1593 Mutex::Locker locker(m_stdio_mutex);
1594 size_t bytes_available = m_stdout_data.size();
1595 if (bytes_available > 0)
1596 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001597 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1598 if (log)
1599 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001600 if (bytes_available > buf_size)
1601 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001602 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001603 m_stdout_data.erase(0, buf_size);
1604 bytes_available = buf_size;
1605 }
1606 else
1607 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001608 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001609 m_stdout_data.clear();
1610
1611 //ResetEventBits(eBroadcastBitSTDOUT);
1612 }
1613 }
1614 return bytes_available;
1615}
1616
1617size_t
1618ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1619{
1620 // Can we get STDERR through the remote protocol?
1621 return 0;
1622}
1623
1624size_t
1625ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1626{
1627 if (m_stdio_communication.IsConnected())
1628 {
1629 ConnectionStatus status;
1630 m_stdio_communication.Write(src, src_len, status, NULL);
1631 }
1632 return 0;
1633}
1634
1635Error
1636ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1637{
1638 Error error;
1639 assert (bp_site != NULL);
1640
Greg Claytone005f2c2010-11-06 01:53:30 +00001641 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001642 user_id_t site_id = bp_site->GetID();
1643 const addr_t addr = bp_site->GetLoadAddress();
1644 if (log)
1645 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1646
1647 if (bp_site->IsEnabled())
1648 {
1649 if (log)
1650 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1651 return error;
1652 }
1653 else
1654 {
1655 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1656
1657 if (bp_site->HardwarePreferred())
1658 {
1659 // Try and set hardware breakpoint, and if that fails, fall through
1660 // and set a software breakpoint?
1661 }
1662
1663 if (m_z0_supported)
1664 {
1665 char packet[64];
1666 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1667 assert (packet_len + 1 < sizeof(packet));
1668 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001669 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001670 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001671 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001672 {
1673 // Disable z packet support and try again
1674 m_z0_supported = 0;
1675 return EnableBreakpoint (bp_site);
1676 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001677 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001678 {
1679 bp_site->SetEnabled(true);
1680 bp_site->SetType (BreakpointSite::eExternal);
1681 return error;
1682 }
1683 else
1684 {
1685 uint8_t error_byte = response.GetError();
1686 if (error_byte)
1687 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1688 }
1689 }
1690 }
1691 else
1692 {
1693 return EnableSoftwareBreakpoint (bp_site);
1694 }
1695 }
1696
1697 if (log)
1698 {
1699 const char *err_string = error.AsCString();
1700 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1701 bp_site->GetLoadAddress(),
1702 err_string ? err_string : "NULL");
1703 }
1704 // We shouldn't reach here on a successful breakpoint enable...
1705 if (error.Success())
1706 error.SetErrorToGenericError();
1707 return error;
1708}
1709
1710Error
1711ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1712{
1713 Error error;
1714 assert (bp_site != NULL);
1715 addr_t addr = bp_site->GetLoadAddress();
1716 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001717 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001718 if (log)
1719 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1720
1721 if (bp_site->IsEnabled())
1722 {
1723 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1724
1725 if (bp_site->IsHardware())
1726 {
1727 // TODO: disable hardware breakpoint...
1728 }
1729 else
1730 {
1731 if (m_z0_supported)
1732 {
1733 char packet[64];
1734 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1735 assert (packet_len + 1 < sizeof(packet));
1736 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001737 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001738 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001739 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001740 {
1741 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1742 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001743 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001744 {
1745 if (log)
1746 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1747 bp_site->SetEnabled(false);
1748 return error;
1749 }
1750 else
1751 {
1752 uint8_t error_byte = response.GetError();
1753 if (error_byte)
1754 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1755 }
1756 }
1757 }
1758 else
1759 {
1760 return DisableSoftwareBreakpoint (bp_site);
1761 }
1762 }
1763 }
1764 else
1765 {
1766 if (log)
1767 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1768 return error;
1769 }
1770
1771 if (error.Success())
1772 error.SetErrorToGenericError();
1773 return error;
1774}
1775
1776Error
1777ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1778{
1779 Error error;
1780 if (wp)
1781 {
1782 user_id_t watchID = wp->GetID();
1783 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001784 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001785 if (log)
1786 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1787 if (wp->IsEnabled())
1788 {
1789 if (log)
1790 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1791 return error;
1792 }
1793 else
1794 {
1795 // Pass down an appropriate z/Z packet...
1796 error.SetErrorString("watchpoints not supported");
1797 }
1798 }
1799 else
1800 {
1801 error.SetErrorString("Watchpoint location argument was NULL.");
1802 }
1803 if (error.Success())
1804 error.SetErrorToGenericError();
1805 return error;
1806}
1807
1808Error
1809ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1810{
1811 Error error;
1812 if (wp)
1813 {
1814 user_id_t watchID = wp->GetID();
1815
Greg Claytone005f2c2010-11-06 01:53:30 +00001816 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001817
1818 addr_t addr = wp->GetLoadAddress();
1819 if (log)
1820 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1821
1822 if (wp->IsHardware())
1823 {
1824 // Pass down an appropriate z/Z packet...
1825 error.SetErrorString("watchpoints not supported");
1826 }
1827 // TODO: clear software watchpoints if we implement them
1828 }
1829 else
1830 {
1831 error.SetErrorString("Watchpoint location argument was NULL.");
1832 }
1833 if (error.Success())
1834 error.SetErrorToGenericError();
1835 return error;
1836}
1837
1838void
1839ProcessGDBRemote::Clear()
1840{
1841 m_flags = 0;
1842 m_thread_list.Clear();
1843 {
1844 Mutex::Locker locker(m_stdio_mutex);
1845 m_stdout_data.clear();
1846 }
Chris Lattner24943d22010-06-08 16:52:24 +00001847}
1848
1849Error
1850ProcessGDBRemote::DoSignal (int signo)
1851{
1852 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001853 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001854 if (log)
1855 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1856
1857 if (!m_gdb_comm.SendAsyncSignal (signo))
1858 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1859 return error;
1860}
1861
Chris Lattner24943d22010-06-08 16:52:24 +00001862Error
1863ProcessGDBRemote::StartDebugserverProcess
1864(
1865 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1866 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1867 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001868 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID send this pid as an argument to debugserver
Chris Lattner24943d22010-06-08 16:52:24 +00001869 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1870 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001871 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001872)
1873{
1874 Error error;
1875 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1876 {
1877 // If we locate debugserver, keep that located version around
1878 static FileSpec g_debugserver_file_spec;
1879
1880 FileSpec debugserver_file_spec;
1881 char debugserver_path[PATH_MAX];
1882
1883 // Always check to see if we have an environment override for the path
1884 // to the debugserver to use and use it if we do.
1885 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1886 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001887 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001888 else
1889 debugserver_file_spec = g_debugserver_file_spec;
1890 bool debugserver_exists = debugserver_file_spec.Exists();
1891 if (!debugserver_exists)
1892 {
1893 // The debugserver binary is in the LLDB.framework/Resources
1894 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001895 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001896 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001897 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001898 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001899 if (debugserver_exists)
1900 {
1901 g_debugserver_file_spec = debugserver_file_spec;
1902 }
1903 else
1904 {
1905 g_debugserver_file_spec.Clear();
1906 debugserver_file_spec.Clear();
1907 }
Chris Lattner24943d22010-06-08 16:52:24 +00001908 }
1909 }
1910
1911 if (debugserver_exists)
1912 {
1913 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1914
1915 m_stdio_communication.Clear();
1916 posix_spawnattr_t attr;
1917
Greg Claytone005f2c2010-11-06 01:53:30 +00001918 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001919
1920 Error local_err; // Errors that don't affect the spawning.
1921 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001922 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1923 __FUNCTION__,
1924 debugserver_path,
1925 inferior_argv,
1926 inferior_envp,
1927 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001928 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1929 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001930 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001931 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001932 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001933
Chris Lattner24943d22010-06-08 16:52:24 +00001934 Args debugserver_args;
1935 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001936
Chris Lattner24943d22010-06-08 16:52:24 +00001937 // Start args with "debugserver /file/path -r --"
1938 debugserver_args.AppendArgument(debugserver_path);
1939 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001940 // use native registers, not the GDB registers
1941 debugserver_args.AppendArgument("--native-regs");
1942 // make debugserver run in its own session so signals generated by
1943 // special terminal key sequences (^C) don't affect debugserver
1944 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001945
Chris Lattner24943d22010-06-08 16:52:24 +00001946 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1947 if (env_debugserver_log_file)
1948 {
1949 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1950 debugserver_args.AppendArgument(arg_cstr);
1951 }
1952
1953 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1954 if (env_debugserver_log_flags)
1955 {
1956 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1957 debugserver_args.AppendArgument(arg_cstr);
1958 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001959// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001960// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001961
1962 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001963 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001964 {
Greg Claytona2f74232011-02-24 22:24:29 +00001965 // Terminate the debugserver args so we can now append the inferior args
1966 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001967
Greg Claytona2f74232011-02-24 22:24:29 +00001968 for (int i = 0; inferior_argv[i] != NULL; ++i)
1969 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001970 }
1971 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1972 {
1973 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1974 debugserver_args.AppendArgument (arg_cstr);
1975 }
1976 else if (attach_name && attach_name[0])
1977 {
1978 if (wait_for_launch)
1979 debugserver_args.AppendArgument ("--waitfor");
1980 else
1981 debugserver_args.AppendArgument ("--attach");
1982 debugserver_args.AppendArgument (attach_name);
1983 }
1984
1985 Error file_actions_err;
1986 posix_spawn_file_actions_t file_actions;
1987#if DONT_CLOSE_DEBUGSERVER_STDIO
1988 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1989#else
1990 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1991 if (file_actions_err.Success())
1992 {
1993 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1994 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1995 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1996 }
1997#endif
1998
1999 if (log)
2000 {
2001 StreamString strm;
2002 debugserver_args.Dump (&strm);
2003 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2004 }
2005
Greg Clayton72e1c782011-01-22 23:43:18 +00002006 error.SetError (::posix_spawnp (&m_debugserver_pid,
2007 debugserver_path,
2008 file_actions_err.Success() ? &file_actions : NULL,
2009 &attr,
2010 debugserver_args.GetArgumentVector(),
2011 (char * const*)inferior_envp),
2012 eErrorTypePOSIX);
2013
Greg Claytone9d0df42010-07-02 01:29:13 +00002014
2015 ::posix_spawnattr_destroy (&attr);
2016
Chris Lattner24943d22010-06-08 16:52:24 +00002017 if (file_actions_err.Success())
2018 ::posix_spawn_file_actions_destroy (&file_actions);
2019
2020 // We have seen some cases where posix_spawnp was returning a valid
2021 // looking pid even when an error was returned, so clear it out
2022 if (error.Fail())
2023 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2024
2025 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002026 error.PutToLog(log.get(), "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
Chris Lattner24943d22010-06-08 16:52:24 +00002027
Chris Lattner24943d22010-06-08 16:52:24 +00002028 }
2029 else
2030 {
2031 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2032 }
2033
2034 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2035 StartAsyncThread ();
2036 }
2037 return error;
2038}
2039
2040bool
2041ProcessGDBRemote::MonitorDebugserverProcess
2042(
2043 void *callback_baton,
2044 lldb::pid_t debugserver_pid,
2045 int signo, // Zero for no signal
2046 int exit_status // Exit value of process if signal is zero
2047)
2048{
2049 // We pass in the ProcessGDBRemote inferior process it and name it
2050 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2051 // pointer value itself, thus we need the double cast...
2052
2053 // "debugserver_pid" argument passed in is the process ID for
2054 // debugserver that we are tracking...
2055
Greg Clayton75ccf502010-08-21 02:22:51 +00002056 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002057
2058 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2059 if (log)
2060 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2061
Greg Clayton75ccf502010-08-21 02:22:51 +00002062 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002063 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002064 // Sleep for a half a second to make sure our inferior process has
2065 // time to set its exit status before we set it incorrectly when
2066 // both the debugserver and the inferior process shut down.
2067 usleep (500000);
2068 // If our process hasn't yet exited, debugserver might have died.
2069 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002070 const StateType state = process->GetState();
2071
2072 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2073 state != eStateInvalid &&
2074 state != eStateUnloaded &&
2075 state != eStateExited &&
2076 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002077 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002078 char error_str[1024];
2079 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002080 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002081 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2082 if (signal_cstr)
2083 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002084 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002085 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002086 }
2087 else
2088 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002089 ::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 +00002090 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002091
2092 process->SetExitStatus (-1, error_str);
2093 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002094 // Debugserver has exited we need to let our ProcessGDBRemote
2095 // know that it no longer has a debugserver instance
2096 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2097 // We are returning true to this function below, so we can
2098 // forget about the monitor handle.
2099 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002100 }
2101 return true;
2102}
2103
2104void
2105ProcessGDBRemote::KillDebugserverProcess ()
2106{
2107 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2108 {
2109 ::kill (m_debugserver_pid, SIGINT);
2110 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2111 }
2112}
2113
2114void
2115ProcessGDBRemote::Initialize()
2116{
2117 static bool g_initialized = false;
2118
2119 if (g_initialized == false)
2120 {
2121 g_initialized = true;
2122 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2123 GetPluginDescriptionStatic(),
2124 CreateInstance);
2125
2126 Log::Callbacks log_callbacks = {
2127 ProcessGDBRemoteLog::DisableLog,
2128 ProcessGDBRemoteLog::EnableLog,
2129 ProcessGDBRemoteLog::ListLogCategories
2130 };
2131
2132 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2133 }
2134}
2135
2136bool
2137ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2138{
2139 if (m_curr_tid == tid)
2140 return true;
2141
2142 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002143 int packet_len;
2144 if (tid <= 0)
2145 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2146 else
2147 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 assert (packet_len + 1 < sizeof(packet));
2149 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002150 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002151 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002152 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002153 {
2154 m_curr_tid = tid;
2155 return true;
2156 }
2157 }
2158 return false;
2159}
2160
2161bool
2162ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2163{
2164 if (m_curr_tid_run == tid)
2165 return true;
2166
2167 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002168 int packet_len;
2169 if (tid <= 0)
2170 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2171 else
2172 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2173
Chris Lattner24943d22010-06-08 16:52:24 +00002174 assert (packet_len + 1 < sizeof(packet));
2175 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002176 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002177 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002178 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002179 {
2180 m_curr_tid_run = tid;
2181 return true;
2182 }
2183 }
2184 return false;
2185}
2186
2187void
2188ProcessGDBRemote::ResetGDBRemoteState ()
2189{
2190 // Reset and GDB remote state
2191 m_curr_tid = LLDB_INVALID_THREAD_ID;
2192 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2193 m_z0_supported = 1;
2194}
2195
2196
2197bool
2198ProcessGDBRemote::StartAsyncThread ()
2199{
2200 ResetGDBRemoteState ();
2201
Greg Claytone005f2c2010-11-06 01:53:30 +00002202 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002203
2204 if (log)
2205 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2206
2207 // Create a thread that watches our internal state and controls which
2208 // events make it to clients (into the DCProcess event queue).
2209 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002210 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002211}
2212
2213void
2214ProcessGDBRemote::StopAsyncThread ()
2215{
Greg Claytone005f2c2010-11-06 01:53:30 +00002216 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002217
2218 if (log)
2219 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2220
2221 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2222
2223 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002224 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002225 {
2226 Host::ThreadJoin (m_async_thread, NULL, NULL);
2227 }
2228}
2229
2230
2231void *
2232ProcessGDBRemote::AsyncThread (void *arg)
2233{
2234 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2235
Greg Claytone005f2c2010-11-06 01:53:30 +00002236 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002237 if (log)
2238 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2239
2240 Listener listener ("ProcessGDBRemote::AsyncThread");
2241 EventSP event_sp;
2242 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2243 eBroadcastBitAsyncThreadShouldExit;
2244
2245 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2246 {
Greg Claytona2f74232011-02-24 22:24:29 +00002247 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2248
Chris Lattner24943d22010-06-08 16:52:24 +00002249 bool done = false;
2250 while (!done)
2251 {
2252 if (log)
2253 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2254 if (listener.WaitForEvent (NULL, event_sp))
2255 {
2256 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002257 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002258 {
Greg Claytona2f74232011-02-24 22:24:29 +00002259 if (log)
2260 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 +00002261
Greg Claytona2f74232011-02-24 22:24:29 +00002262 switch (event_type)
2263 {
2264 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002265 {
Greg Claytona2f74232011-02-24 22:24:29 +00002266 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002267
Greg Claytona2f74232011-02-24 22:24:29 +00002268 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002269 {
Greg Claytona2f74232011-02-24 22:24:29 +00002270 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2271 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2272 if (log)
2273 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002274
Greg Claytona2f74232011-02-24 22:24:29 +00002275 if (::strstr (continue_cstr, "vAttach") == NULL)
2276 process->SetPrivateState(eStateRunning);
2277 StringExtractorGDBRemote response;
2278 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002279
Greg Claytona2f74232011-02-24 22:24:29 +00002280 switch (stop_state)
2281 {
2282 case eStateStopped:
2283 case eStateCrashed:
2284 case eStateSuspended:
2285 process->m_last_stop_packet = response;
2286 process->m_last_stop_packet.SetFilePos (0);
2287 process->SetPrivateState (stop_state);
2288 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002289
Greg Claytona2f74232011-02-24 22:24:29 +00002290 case eStateExited:
2291 process->m_last_stop_packet = response;
2292 process->m_last_stop_packet.SetFilePos (0);
2293 response.SetFilePos(1);
2294 process->SetExitStatus(response.GetHexU8(), NULL);
2295 done = true;
2296 break;
2297
2298 case eStateInvalid:
2299 process->SetExitStatus(-1, "lost connection");
2300 break;
2301
2302 default:
2303 process->SetPrivateState (stop_state);
2304 break;
2305 }
Chris Lattner24943d22010-06-08 16:52:24 +00002306 }
2307 }
Greg Claytona2f74232011-02-24 22:24:29 +00002308 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002309
Greg Claytona2f74232011-02-24 22:24:29 +00002310 case eBroadcastBitAsyncThreadShouldExit:
2311 if (log)
2312 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2313 done = true;
2314 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002315
Greg Claytona2f74232011-02-24 22:24:29 +00002316 default:
2317 if (log)
2318 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2319 done = true;
2320 break;
2321 }
2322 }
2323 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2324 {
2325 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2326 {
2327 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002328 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002329 }
Chris Lattner24943d22010-06-08 16:52:24 +00002330 }
2331 }
2332 else
2333 {
2334 if (log)
2335 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2336 done = true;
2337 }
2338 }
2339 }
2340
2341 if (log)
2342 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2343
2344 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2345 return NULL;
2346}
2347
Chris Lattner24943d22010-06-08 16:52:24 +00002348const char *
2349ProcessGDBRemote::GetDispatchQueueNameForThread
2350(
2351 addr_t thread_dispatch_qaddr,
2352 std::string &dispatch_queue_name
2353)
2354{
2355 dispatch_queue_name.clear();
2356 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2357 {
2358 // Cache the dispatch_queue_offsets_addr value so we don't always have
2359 // to look it up
2360 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2361 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002362 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2363 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002364 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002365 if (module_sp)
2366 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2367
2368 if (dispatch_queue_offsets_symbol == NULL)
2369 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002370 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002371 if (module_sp)
2372 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2373 }
Chris Lattner24943d22010-06-08 16:52:24 +00002374 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002375 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002376
2377 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2378 return NULL;
2379 }
2380
2381 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002382 DataExtractor data (memory_buffer,
2383 sizeof(memory_buffer),
2384 m_target.GetArchitecture().GetByteOrder(),
2385 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002386
2387 // Excerpt from src/queue_private.h
2388 struct dispatch_queue_offsets_s
2389 {
2390 uint16_t dqo_version;
2391 uint16_t dqo_label;
2392 uint16_t dqo_label_size;
2393 } dispatch_queue_offsets;
2394
2395
2396 Error error;
2397 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2398 {
2399 uint32_t data_offset = 0;
2400 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2401 {
2402 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2403 {
2404 data_offset = 0;
2405 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2406 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2407 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2408 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2409 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2410 dispatch_queue_name.erase (bytes_read);
2411 }
2412 }
2413 }
2414 }
2415 if (dispatch_queue_name.empty())
2416 return NULL;
2417 return dispatch_queue_name.c_str();
2418}
2419
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002420//uint32_t
2421//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2422//{
2423// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2424// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2425// if (m_local_debugserver)
2426// {
2427// return Host::ListProcessesMatchingName (name, matches, pids);
2428// }
2429// else
2430// {
2431// // FIXME: Implement talking to the remote debugserver.
2432// return 0;
2433// }
2434//
2435//}
2436//
Jim Ingham55e01d82011-01-22 01:33:44 +00002437bool
2438ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2439 lldb_private::StoppointCallbackContext *context,
2440 lldb::user_id_t break_id,
2441 lldb::user_id_t break_loc_id)
2442{
2443 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2444 // run so I can stop it if that's what I want to do.
2445 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2446 if (log)
2447 log->Printf("Hit New Thread Notification breakpoint.");
2448 return false;
2449}
2450
2451
2452bool
2453ProcessGDBRemote::StartNoticingNewThreads()
2454{
2455 static const char *bp_names[] =
2456 {
2457 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002458 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002459 "_pthread_start",
2460 NULL
2461 };
2462
2463 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2464 size_t num_bps = m_thread_observation_bps.size();
2465 if (num_bps != 0)
2466 {
2467 for (int i = 0; i < num_bps; i++)
2468 {
2469 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2470 if (break_sp)
2471 {
2472 if (log)
2473 log->Printf("Enabled noticing new thread breakpoint.");
2474 break_sp->SetEnabled(true);
2475 }
2476 }
2477 }
2478 else
2479 {
2480 for (int i = 0; bp_names[i] != NULL; i++)
2481 {
2482 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2483 if (breakpoint)
2484 {
2485 if (log)
2486 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2487 m_thread_observation_bps.push_back(breakpoint->GetID());
2488 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2489 }
2490 else
2491 {
2492 if (log)
2493 log->Printf("Failed to create new thread notification breakpoint.");
2494 return false;
2495 }
2496 }
2497 }
2498
2499 return true;
2500}
2501
2502bool
2503ProcessGDBRemote::StopNoticingNewThreads()
2504{
Jim Inghamff276fe2011-02-08 05:19:01 +00002505 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2506 if (log)
2507 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002508 size_t num_bps = m_thread_observation_bps.size();
2509 if (num_bps != 0)
2510 {
2511 for (int i = 0; i < num_bps; i++)
2512 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002513
2514 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2515 if (break_sp)
2516 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002517 break_sp->SetEnabled(false);
2518 }
2519 }
2520 }
2521 return true;
2522}
2523
2524