blob: e5a1d7c0606b4e763e372cc54559f20b27ea71ed [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>
Chris Lattner24943d22010-06-08 16:52:24 +000013#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/stat.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015
16// C++ Includes
17#include <algorithm>
18#include <map>
19
20// Other libraries and framework includes
21
22#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/ArchSpec.h"
25#include "lldb/Core/Debugger.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000027#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Core/InputReader.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/StreamString.h"
33#include "lldb/Core/Timer.h"
34#include "lldb/Host/TimeValue.h"
35#include "lldb/Symbol/ObjectFile.h"
36#include "lldb/Target/DynamicLoader.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000039#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41// Project includes
42#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000043#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "GDBRemoteRegisterContext.h"
45#include "ProcessGDBRemote.h"
46#include "ProcessGDBRemoteLog.h"
47#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000048#include "StopInfoMachException.h"
49
Chris Lattner24943d22010-06-08 16:52:24 +000050
Chris Lattner24943d22010-06-08 16:52:24 +000051
52#define DEBUGSERVER_BASENAME "debugserver"
53using namespace lldb;
54using namespace lldb_private;
55
56static inline uint16_t
57get_random_port ()
58{
59 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
60}
61
62
63const char *
64ProcessGDBRemote::GetPluginNameStatic()
65{
Greg Claytonb1888f22011-03-19 01:12:21 +000066 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000067}
68
69const char *
70ProcessGDBRemote::GetPluginDescriptionStatic()
71{
72 return "GDB Remote protocol based debugging plug-in.";
73}
74
75void
76ProcessGDBRemote::Terminate()
77{
78 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
79}
80
81
82Process*
83ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
84{
85 return new ProcessGDBRemote (target, listener);
86}
87
88bool
89ProcessGDBRemote::CanDebug(Target &target)
90{
91 // For now we are just making sure the file exists for a given module
92 ModuleSP exe_module_sp(target.GetExecutableModule());
93 if (exe_module_sp.get())
94 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000095 // However, if there is no executable module, we return true since we might be preparing to attach.
96 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000097}
98
99//----------------------------------------------------------------------
100// ProcessGDBRemote constructor
101//----------------------------------------------------------------------
102ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
103 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000104 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000105 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_gdb_comm(),
107 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000108 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000109 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000110 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
112 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000113 m_curr_tid (LLDB_INVALID_THREAD_ID),
114 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_z0_supported (1),
Greg Claytonc1f45872011-02-12 06:28:37 +0000116 m_continue_c_tids (),
117 m_continue_C_tids (),
118 m_continue_s_tids (),
119 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000121 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000122 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000123 m_local_debugserver (true),
124 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000125{
126}
127
128//----------------------------------------------------------------------
129// Destructor
130//----------------------------------------------------------------------
131ProcessGDBRemote::~ProcessGDBRemote()
132{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000133 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000134 {
135 Host::ThreadCancel (m_debugserver_thread, NULL);
136 thread_result_t thread_result;
137 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
138 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
139 }
Chris Lattner24943d22010-06-08 16:52:24 +0000140 // m_mach_process.UnregisterNotificationCallbacks (this);
141 Clear();
142}
143
144//----------------------------------------------------------------------
145// PluginInterface
146//----------------------------------------------------------------------
147const char *
148ProcessGDBRemote::GetPluginName()
149{
150 return "Process debugging plug-in that uses the GDB remote protocol";
151}
152
153const char *
154ProcessGDBRemote::GetShortPluginName()
155{
156 return GetPluginNameStatic();
157}
158
159uint32_t
160ProcessGDBRemote::GetPluginVersion()
161{
162 return 1;
163}
164
165void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000166ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000167{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000168 if (!force && m_register_info.GetNumRegisters() > 0)
169 return;
170
171 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000172 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000173 uint32_t reg_offset = 0;
174 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000175 StringExtractorGDBRemote::ResponseType response_type;
176 for (response_type = StringExtractorGDBRemote::eResponse;
177 response_type == StringExtractorGDBRemote::eResponse;
178 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000179 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000180 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
181 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000182 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000183 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000184 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000185 response_type = response.GetResponseType();
186 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000187 {
188 std::string name;
189 std::string value;
190 ConstString reg_name;
191 ConstString alt_name;
192 ConstString set_name;
193 RegisterInfo reg_info = { NULL, // Name
194 NULL, // Alt name
195 0, // byte size
196 reg_offset, // offset
197 eEncodingUint, // encoding
198 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000199 {
200 LLDB_INVALID_REGNUM, // GCC reg num
201 LLDB_INVALID_REGNUM, // DWARF reg num
202 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000203 reg_num, // GDB reg num
204 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000205 }
206 };
207
208 while (response.GetNameColonValue(name, value))
209 {
210 if (name.compare("name") == 0)
211 {
212 reg_name.SetCString(value.c_str());
213 }
214 else if (name.compare("alt-name") == 0)
215 {
216 alt_name.SetCString(value.c_str());
217 }
218 else if (name.compare("bitsize") == 0)
219 {
220 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
221 }
222 else if (name.compare("offset") == 0)
223 {
224 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000225 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000226 {
227 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000228 }
229 }
230 else if (name.compare("encoding") == 0)
231 {
232 if (value.compare("uint") == 0)
233 reg_info.encoding = eEncodingUint;
234 else if (value.compare("sint") == 0)
235 reg_info.encoding = eEncodingSint;
236 else if (value.compare("ieee754") == 0)
237 reg_info.encoding = eEncodingIEEE754;
238 else if (value.compare("vector") == 0)
239 reg_info.encoding = eEncodingVector;
240 }
241 else if (name.compare("format") == 0)
242 {
243 if (value.compare("binary") == 0)
244 reg_info.format = eFormatBinary;
245 else if (value.compare("decimal") == 0)
246 reg_info.format = eFormatDecimal;
247 else if (value.compare("hex") == 0)
248 reg_info.format = eFormatHex;
249 else if (value.compare("float") == 0)
250 reg_info.format = eFormatFloat;
251 else if (value.compare("vector-sint8") == 0)
252 reg_info.format = eFormatVectorOfSInt8;
253 else if (value.compare("vector-uint8") == 0)
254 reg_info.format = eFormatVectorOfUInt8;
255 else if (value.compare("vector-sint16") == 0)
256 reg_info.format = eFormatVectorOfSInt16;
257 else if (value.compare("vector-uint16") == 0)
258 reg_info.format = eFormatVectorOfUInt16;
259 else if (value.compare("vector-sint32") == 0)
260 reg_info.format = eFormatVectorOfSInt32;
261 else if (value.compare("vector-uint32") == 0)
262 reg_info.format = eFormatVectorOfUInt32;
263 else if (value.compare("vector-float32") == 0)
264 reg_info.format = eFormatVectorOfFloat32;
265 else if (value.compare("vector-uint128") == 0)
266 reg_info.format = eFormatVectorOfUInt128;
267 }
268 else if (name.compare("set") == 0)
269 {
270 set_name.SetCString(value.c_str());
271 }
272 else if (name.compare("gcc") == 0)
273 {
274 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
275 }
276 else if (name.compare("dwarf") == 0)
277 {
278 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
279 }
280 else if (name.compare("generic") == 0)
281 {
282 if (value.compare("pc") == 0)
283 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
284 else if (value.compare("sp") == 0)
285 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
286 else if (value.compare("fp") == 0)
287 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
288 else if (value.compare("ra") == 0)
289 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
290 else if (value.compare("flags") == 0)
291 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
292 }
293 }
294
Jason Molenda53d96862010-06-11 23:44:18 +0000295 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000296 assert (reg_info.byte_size != 0);
297 reg_offset += reg_info.byte_size;
298 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
299 }
300 }
301 else
302 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000303 response_type = StringExtractorGDBRemote::eError;
Chris Lattner24943d22010-06-08 16:52:24 +0000304 }
305 }
306
307 if (reg_num == 0)
308 {
309 // We didn't get anything. See if we are debugging ARM and fill with
310 // a hard coded register set until we can get an updated debugserver
311 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000312 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000313 m_register_info.HardcodeARMRegisters();
314 }
315 m_register_info.Finalize ();
316}
317
318Error
319ProcessGDBRemote::WillLaunch (Module* module)
320{
321 return WillLaunchOrAttach ();
322}
323
324Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000325ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000326{
327 return WillLaunchOrAttach ();
328}
329
330Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000331ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000332{
333 return WillLaunchOrAttach ();
334}
335
336Error
Greg Claytone71e2582011-02-04 01:58:07 +0000337ProcessGDBRemote::DoConnectRemote (const char *remote_url)
338{
339 Error error (WillLaunchOrAttach ());
340
341 if (error.Fail())
342 return error;
343
344 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
345 {
346 error = ConnectToDebugserver (remote_url);
347 }
348 else
349 {
350 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
351 }
352
353 if (error.Fail())
354 return error;
355 StartAsyncThread ();
356
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000357 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000358 if (pid == LLDB_INVALID_PROCESS_ID)
359 {
360 // We don't have a valid process ID, so note that we are connected
361 // and could now request to launch or attach, or get remote process
362 // listings...
363 SetPrivateState (eStateConnected);
364 }
365 else
366 {
367 // We have a valid process
368 SetID (pid);
369 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000370 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000371 {
372 const StateType state = SetThreadStopInfo (response);
373 if (state == eStateStopped)
374 {
375 SetPrivateState (state);
376 }
377 else
378 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
379 }
380 else
381 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
382 }
383 return error;
384}
385
386Error
Chris Lattner24943d22010-06-08 16:52:24 +0000387ProcessGDBRemote::WillLaunchOrAttach ()
388{
389 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000390 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000391 return error;
392}
393
394//----------------------------------------------------------------------
395// Process Control
396//----------------------------------------------------------------------
397Error
398ProcessGDBRemote::DoLaunch
399(
400 Module* module,
401 char const *argv[],
402 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000403 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000404 const char *stdin_path,
405 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000406 const char *stderr_path,
407 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000408)
409{
Greg Clayton4b407112010-09-30 21:49:03 +0000410 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000411 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
412 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
413 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000414
415 ObjectFile * object_file = module->GetObjectFile();
416 if (object_file)
417 {
418 ArchSpec inferior_arch(module->GetArchitecture());
419 char host_port[128];
420 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000421 char connect_url[128];
422 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000423
Greg Claytona2f74232011-02-24 22:24:29 +0000424 // Make sure we aren't already connected?
425 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000426 {
427 error = StartDebugserverProcess (host_port,
428 NULL,
429 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000430 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000431 NULL,
432 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000433 inferior_arch);
434 if (error.Fail())
435 return error;
436
Greg Claytone71e2582011-02-04 01:58:07 +0000437 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000438 }
439
440 if (error.Success())
441 {
442 lldb_utility::PseudoTerminal pty;
443 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000444
445 // If the debugserver is local and we aren't disabling STDIO, lets use
446 // a pseudo terminal to instead of relying on the 'O' packets for stdio
447 // since 'O' packets can really slow down debugging if the inferior
448 // does a lot of output.
449 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000450 {
451 const char *slave_name = NULL;
452 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000453 {
Greg Claytona2f74232011-02-24 22:24:29 +0000454 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
455 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000456 }
Greg Claytona2f74232011-02-24 22:24:29 +0000457 if (stdin_path == NULL)
458 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000459
Greg Claytona2f74232011-02-24 22:24:29 +0000460 if (stdout_path == NULL)
461 stdout_path = slave_name;
462
463 if (stderr_path == NULL)
464 stderr_path = slave_name;
465 }
466
Greg Claytonafb81862011-03-02 21:34:46 +0000467 // Set STDIN to /dev/null if we want STDIO disabled or if either
468 // STDOUT or STDERR have been set to something and STDIN hasn't
469 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000470 stdin_path = "/dev/null";
471
Greg Claytonafb81862011-03-02 21:34:46 +0000472 // Set STDOUT to /dev/null if we want STDIO disabled or if either
473 // STDIN or STDERR have been set to something and STDOUT hasn't
474 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000475 stdout_path = "/dev/null";
476
Greg Claytonafb81862011-03-02 21:34:46 +0000477 // Set STDERR to /dev/null if we want STDIO disabled or if either
478 // STDIN or STDOUT have been set to something and STDERR hasn't
479 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000480 stderr_path = "/dev/null";
481
482 if (stdin_path)
483 m_gdb_comm.SetSTDIN (stdin_path);
484 if (stdout_path)
485 m_gdb_comm.SetSTDOUT (stdout_path);
486 if (stderr_path)
487 m_gdb_comm.SetSTDERR (stderr_path);
488
489 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
490
491
492 if (working_dir && working_dir[0])
493 {
494 m_gdb_comm.SetWorkingDir (working_dir);
495 }
496
497 // Send the environment and the program + arguments after we connect
498 if (envp)
499 {
500 const char *env_entry;
501 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000502 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000503 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000504 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000505 }
Greg Claytona2f74232011-02-24 22:24:29 +0000506 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000507
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000508 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
509 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
510 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000511 if (arg_packet_err == 0)
512 {
513 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000514 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000515 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000516 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000517 }
518 else
519 {
Greg Claytona2f74232011-02-24 22:24:29 +0000520 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000521 }
Greg Claytona2f74232011-02-24 22:24:29 +0000522 }
523 else
524 {
525 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
526 }
Chris Lattner24943d22010-06-08 16:52:24 +0000527
Greg Claytona2f74232011-02-24 22:24:29 +0000528 if (GetID() == LLDB_INVALID_PROCESS_ID)
529 {
530 KillDebugserverProcess ();
531 return error;
532 }
533
534 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000535 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000536 {
537 SetPrivateState (SetThreadStopInfo (response));
538
539 if (!disable_stdio)
540 {
541 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
542 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
543 }
Chris Lattner24943d22010-06-08 16:52:24 +0000544 }
545 }
Chris Lattner24943d22010-06-08 16:52:24 +0000546 }
547 else
548 {
549 // Set our user ID to an invalid process ID.
550 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000551 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
552 module->GetFileSpec().GetFilename().AsCString(),
553 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000554 }
Chris Lattner24943d22010-06-08 16:52:24 +0000555 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000556
Chris Lattner24943d22010-06-08 16:52:24 +0000557}
558
559
560Error
Greg Claytone71e2582011-02-04 01:58:07 +0000561ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000562{
563 Error error;
564 // Sleep and wait a bit for debugserver to start to listen...
565 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
566 if (conn_ap.get())
567 {
Chris Lattner24943d22010-06-08 16:52:24 +0000568 const uint32_t max_retry_count = 50;
569 uint32_t retry_count = 0;
570 while (!m_gdb_comm.IsConnected())
571 {
Greg Claytone71e2582011-02-04 01:58:07 +0000572 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000573 {
574 m_gdb_comm.SetConnection (conn_ap.release());
575 break;
576 }
577 retry_count++;
578
579 if (retry_count >= max_retry_count)
580 break;
581
582 usleep (100000);
583 }
584 }
585
586 if (!m_gdb_comm.IsConnected())
587 {
588 if (error.Success())
589 error.SetErrorString("not connected to remote gdb server");
590 return error;
591 }
592
Chris Lattner24943d22010-06-08 16:52:24 +0000593 if (m_gdb_comm.StartReadThread(&error))
594 {
595 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000596 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000597
598 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000599 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
600 this,
601 m_debugserver_pid,
602 false);
603
Greg Claytonc1f45872011-02-12 06:28:37 +0000604 m_gdb_comm.ResetDiscoverableSettings();
605 m_gdb_comm.GetSendAcks ();
606 m_gdb_comm.GetThreadSuffixSupported ();
607 m_gdb_comm.GetHostInfo ();
608 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000609 }
610 return error;
611}
612
613void
614ProcessGDBRemote::DidLaunchOrAttach ()
615{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000616 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
617 if (log)
618 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000619 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000620 {
621 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
622
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000623 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000624
Greg Clayton20d338f2010-11-18 05:57:03 +0000625
Chris Lattner24943d22010-06-08 16:52:24 +0000626 StreamString strm;
627
Chris Lattner24943d22010-06-08 16:52:24 +0000628 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000629
Greg Claytoncb8977d2011-03-23 00:09:55 +0000630 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
631 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000632 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000633 ArchSpec &target_arch = GetTarget().GetArchitecture();
634
635 if (target_arch.IsValid())
636 {
637 // If the remote host is ARM and we have apple as the vendor, then
638 // ARM executables and shared libraries can have mixed ARM architectures.
639 // You can have an armv6 executable, and if the host is armv7, then the
640 // system will load the best possible architecture for all shared libraries
641 // it has, so we really need to take the remote host architecture as our
642 // defacto architecture in this case.
643
644 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
645 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
646 {
647 target_arch = gdb_remote_arch;
648 }
649 else
650 {
651 // Fill in what is missing in the triple
652 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
653 llvm::Triple &target_triple = target_arch.GetTriple();
654 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
655 target_triple.setVendor (remote_triple.getVendor());
656
657 if (target_triple.getOS() == llvm::Triple::UnknownOS)
658 target_triple.setOS (remote_triple.getOS());
659
660 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
661 target_triple.setEnvironment (remote_triple.getEnvironment());
662 }
663 }
664 else
665 {
666 // The target doesn't have a valid architecture yet, set it from
667 // the architecture we got from the remote GDB server
668 target_arch = gdb_remote_arch;
669 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000670 }
Chris Lattner24943d22010-06-08 16:52:24 +0000671 }
672}
673
674void
675ProcessGDBRemote::DidLaunch ()
676{
677 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000678}
679
680Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000681ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Error error;
684 // Clear out and clean up from any current state
685 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000686 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000687
Chris Lattner24943d22010-06-08 16:52:24 +0000688 if (attach_pid != LLDB_INVALID_PROCESS_ID)
689 {
Greg Claytona2f74232011-02-24 22:24:29 +0000690 // Make sure we aren't already connected?
691 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000692 {
Greg Claytona2f74232011-02-24 22:24:29 +0000693 char host_port[128];
694 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
695 char connect_url[128];
696 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000697
Greg Claytona2f74232011-02-24 22:24:29 +0000698 error = StartDebugserverProcess (host_port, // debugserver_url
699 NULL, // inferior_argv
700 NULL, // inferior_envp
701 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
702 NULL, // Don't send any attach by process name option to debugserver
703 false, // Don't send any attach wait_for_launch flag as an option to debugserver
704 arch_spec);
705
706 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000707 {
Greg Claytona2f74232011-02-24 22:24:29 +0000708 const char *error_string = error.AsCString();
709 if (error_string == NULL)
710 error_string = "unable to launch " DEBUGSERVER_BASENAME;
711
712 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000713 }
Greg Claytona2f74232011-02-24 22:24:29 +0000714 else
715 {
716 error = ConnectToDebugserver (connect_url);
717 }
718 }
719
720 if (error.Success())
721 {
722 char packet[64];
723 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
724
725 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
727 }
Chris Lattner24943d22010-06-08 16:52:24 +0000728 return error;
729}
730
731size_t
732ProcessGDBRemote::AttachInputReaderCallback
733(
734 void *baton,
735 InputReader *reader,
736 lldb::InputReaderAction notification,
737 const char *bytes,
738 size_t bytes_len
739)
740{
741 if (notification == eInputReaderGotToken)
742 {
743 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
744 if (gdb_process->m_waiting_for_attach)
745 gdb_process->m_waiting_for_attach = false;
746 reader->SetIsDone(true);
747 return 1;
748 }
749 return 0;
750}
751
752Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000753ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000754{
755 Error error;
756 // Clear out and clean up from any current state
757 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000758
Chris Lattner24943d22010-06-08 16:52:24 +0000759 if (process_name && process_name[0])
760 {
Greg Claytona2f74232011-02-24 22:24:29 +0000761 // Make sure we aren't already connected?
762 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
Chris Lattner24943d22010-06-08 16:52:24 +0000764
Greg Claytona2f74232011-02-24 22:24:29 +0000765 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
766
767 char host_port[128];
768 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
769 char connect_url[128];
770 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
771
772 error = StartDebugserverProcess (host_port, // debugserver_url
773 NULL, // inferior_argv
774 NULL, // inferior_envp
775 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
776 NULL, // Don't send any attach by process name option to debugserver
777 false, // Don't send any attach wait_for_launch flag as an option to debugserver
778 arch_spec);
779 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000780 {
Greg Claytona2f74232011-02-24 22:24:29 +0000781 const char *error_string = error.AsCString();
782 if (error_string == NULL)
783 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000784
Greg Claytona2f74232011-02-24 22:24:29 +0000785 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000786 }
Greg Claytona2f74232011-02-24 22:24:29 +0000787 else
788 {
789 error = ConnectToDebugserver (connect_url);
790 }
791 }
792
793 if (error.Success())
794 {
795 StreamString packet;
796
797 if (wait_for_launch)
798 packet.PutCString("vAttachWait");
799 else
800 packet.PutCString("vAttachName");
801 packet.PutChar(';');
802 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
803
804 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
805
Chris Lattner24943d22010-06-08 16:52:24 +0000806 }
807 }
Chris Lattner24943d22010-06-08 16:52:24 +0000808 return error;
809}
810
Chris Lattner24943d22010-06-08 16:52:24 +0000811
812void
813ProcessGDBRemote::DidAttach ()
814{
Greg Claytone71e2582011-02-04 01:58:07 +0000815 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000816}
817
818Error
819ProcessGDBRemote::WillResume ()
820{
Greg Claytonc1f45872011-02-12 06:28:37 +0000821 m_continue_c_tids.clear();
822 m_continue_C_tids.clear();
823 m_continue_s_tids.clear();
824 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000825 return Error();
826}
827
828Error
829ProcessGDBRemote::DoResume ()
830{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000831 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000832 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
833 if (log)
834 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000835
836 Listener listener ("gdb-remote.resume-packet-sent");
837 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
838 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000839 StreamString continue_packet;
840 bool continue_packet_error = false;
841 if (m_gdb_comm.HasAnyVContSupport ())
842 {
843 continue_packet.PutCString ("vCont");
844
845 if (!m_continue_c_tids.empty())
846 {
847 if (m_gdb_comm.GetVContSupported ('c'))
848 {
849 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)
850 continue_packet.Printf(";c:%4.4x", *t_pos);
851 }
852 else
853 continue_packet_error = true;
854 }
855
856 if (!continue_packet_error && !m_continue_C_tids.empty())
857 {
858 if (m_gdb_comm.GetVContSupported ('C'))
859 {
860 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)
861 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
862 }
863 else
864 continue_packet_error = true;
865 }
Greg Claytonb749a262010-12-03 06:02:24 +0000866
Greg Claytonc1f45872011-02-12 06:28:37 +0000867 if (!continue_packet_error && !m_continue_s_tids.empty())
868 {
869 if (m_gdb_comm.GetVContSupported ('s'))
870 {
871 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)
872 continue_packet.Printf(";s:%4.4x", *t_pos);
873 }
874 else
875 continue_packet_error = true;
876 }
877
878 if (!continue_packet_error && !m_continue_S_tids.empty())
879 {
880 if (m_gdb_comm.GetVContSupported ('S'))
881 {
882 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)
883 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
884 }
885 else
886 continue_packet_error = true;
887 }
888
889 if (continue_packet_error)
890 continue_packet.GetString().clear();
891 }
892 else
893 continue_packet_error = true;
894
895 if (continue_packet_error)
896 {
897 continue_packet_error = false;
898 // Either no vCont support, or we tried to use part of the vCont
899 // packet that wasn't supported by the remote GDB server.
900 // We need to try and make a simple packet that can do our continue
901 const size_t num_threads = GetThreadList().GetSize();
902 const size_t num_continue_c_tids = m_continue_c_tids.size();
903 const size_t num_continue_C_tids = m_continue_C_tids.size();
904 const size_t num_continue_s_tids = m_continue_s_tids.size();
905 const size_t num_continue_S_tids = m_continue_S_tids.size();
906 if (num_continue_c_tids > 0)
907 {
908 if (num_continue_c_tids == num_threads)
909 {
910 // All threads are resuming...
911 SetCurrentGDBRemoteThreadForRun (-1);
912 continue_packet.PutChar ('c');
913 }
914 else if (num_continue_c_tids == 1 &&
915 num_continue_C_tids == 0 &&
916 num_continue_s_tids == 0 &&
917 num_continue_S_tids == 0 )
918 {
919 // Only one thread is continuing
920 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
921 continue_packet.PutChar ('c');
922 }
923 else
924 {
925 // We can't represent this continue packet....
926 continue_packet_error = true;
927 }
928 }
929
930 if (!continue_packet_error && num_continue_C_tids > 0)
931 {
932 if (num_continue_C_tids == num_threads)
933 {
934 const int continue_signo = m_continue_C_tids.front().second;
935 if (num_continue_C_tids > 1)
936 {
937 for (size_t i=1; i<num_threads; ++i)
938 {
939 if (m_continue_C_tids[i].second != continue_signo)
940 continue_packet_error = true;
941 }
942 }
943 if (!continue_packet_error)
944 {
945 // Add threads continuing with the same signo...
946 SetCurrentGDBRemoteThreadForRun (-1);
947 continue_packet.Printf("C%2.2x", continue_signo);
948 }
949 }
950 else if (num_continue_c_tids == 0 &&
951 num_continue_C_tids == 1 &&
952 num_continue_s_tids == 0 &&
953 num_continue_S_tids == 0 )
954 {
955 // Only one thread is continuing with signal
956 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
957 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
958 }
959 else
960 {
961 // We can't represent this continue packet....
962 continue_packet_error = true;
963 }
964 }
965
966 if (!continue_packet_error && num_continue_s_tids > 0)
967 {
968 if (num_continue_s_tids == num_threads)
969 {
970 // All threads are resuming...
971 SetCurrentGDBRemoteThreadForRun (-1);
972 continue_packet.PutChar ('s');
973 }
974 else if (num_continue_c_tids == 0 &&
975 num_continue_C_tids == 0 &&
976 num_continue_s_tids == 1 &&
977 num_continue_S_tids == 0 )
978 {
979 // Only one thread is stepping
980 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
981 continue_packet.PutChar ('s');
982 }
983 else
984 {
985 // We can't represent this continue packet....
986 continue_packet_error = true;
987 }
988 }
989
990 if (!continue_packet_error && num_continue_S_tids > 0)
991 {
992 if (num_continue_S_tids == num_threads)
993 {
994 const int step_signo = m_continue_S_tids.front().second;
995 // Are all threads trying to step with the same signal?
996 if (num_continue_S_tids > 1)
997 {
998 for (size_t i=1; i<num_threads; ++i)
999 {
1000 if (m_continue_S_tids[i].second != step_signo)
1001 continue_packet_error = true;
1002 }
1003 }
1004 if (!continue_packet_error)
1005 {
1006 // Add threads stepping with the same signo...
1007 SetCurrentGDBRemoteThreadForRun (-1);
1008 continue_packet.Printf("S%2.2x", step_signo);
1009 }
1010 }
1011 else if (num_continue_c_tids == 0 &&
1012 num_continue_C_tids == 0 &&
1013 num_continue_s_tids == 0 &&
1014 num_continue_S_tids == 1 )
1015 {
1016 // Only one thread is stepping with signal
1017 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1018 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1019 }
1020 else
1021 {
1022 // We can't represent this continue packet....
1023 continue_packet_error = true;
1024 }
1025 }
1026 }
1027
1028 if (continue_packet_error)
1029 {
1030 error.SetErrorString ("can't make continue packet for this resume");
1031 }
1032 else
1033 {
1034 EventSP event_sp;
1035 TimeValue timeout;
1036 timeout = TimeValue::Now();
1037 timeout.OffsetWithSeconds (5);
1038 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1039
1040 if (listener.WaitForEvent (&timeout, event_sp) == false)
1041 error.SetErrorString("Resume timed out.");
1042 }
Greg Claytonb749a262010-12-03 06:02:24 +00001043 }
1044
Jim Ingham3ae449a2010-11-17 02:32:00 +00001045 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001046}
1047
Chris Lattner24943d22010-06-08 16:52:24 +00001048uint32_t
1049ProcessGDBRemote::UpdateThreadListIfNeeded ()
1050{
1051 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001052 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001053 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001054 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1055
Greg Clayton5205f0b2010-09-03 17:10:42 +00001056 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001057 const uint32_t stop_id = GetStopID();
1058 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1059 {
1060 // Update the thread list's stop id immediately so we don't recurse into this function.
1061 ThreadList curr_thread_list (this);
1062 curr_thread_list.SetStopID(stop_id);
1063
1064 Error err;
1065 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001066 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001067 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001068 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001069 {
1070 char ch = response.GetChar();
1071 if (ch == 'l')
1072 break;
1073 if (ch == 'm')
1074 {
1075 do
1076 {
1077 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1078
1079 if (tid != LLDB_INVALID_THREAD_ID)
1080 {
1081 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001082 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001083 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1084 curr_thread_list.AddThread(thread_sp);
1085 }
1086
1087 ch = response.GetChar();
1088 } while (ch == ',');
1089 }
1090 }
1091
1092 m_thread_list = curr_thread_list;
1093
1094 SetThreadStopInfo (m_last_stop_packet);
1095 }
1096 return GetThreadList().GetSize(false);
1097}
1098
1099
1100StateType
1101ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1102{
1103 const char stop_type = stop_packet.GetChar();
1104 switch (stop_type)
1105 {
1106 case 'T':
1107 case 'S':
1108 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001109 if (GetStopID() == 0)
1110 {
1111 // Our first stop, make sure we have a process ID, and also make
1112 // sure we know about our registers
1113 if (GetID() == LLDB_INVALID_PROCESS_ID)
1114 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001115 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001116 if (pid != LLDB_INVALID_PROCESS_ID)
1117 SetID (pid);
1118 }
1119 BuildDynamicRegisterInfo (true);
1120 }
Chris Lattner24943d22010-06-08 16:52:24 +00001121 // Stop with signal and thread info
1122 const uint8_t signo = stop_packet.GetHexU8();
1123 std::string name;
1124 std::string value;
1125 std::string thread_name;
1126 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001127 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001128 uint32_t tid = LLDB_INVALID_THREAD_ID;
1129 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1130 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001131 ThreadSP thread_sp;
1132
Chris Lattner24943d22010-06-08 16:52:24 +00001133 while (stop_packet.GetNameColonValue(name, value))
1134 {
1135 if (name.compare("metype") == 0)
1136 {
1137 // exception type in big endian hex
1138 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1139 }
1140 else if (name.compare("mecount") == 0)
1141 {
1142 // exception count in big endian hex
1143 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1144 }
1145 else if (name.compare("medata") == 0)
1146 {
1147 // exception data in big endian hex
1148 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1149 }
1150 else if (name.compare("thread") == 0)
1151 {
1152 // thread in big endian hex
1153 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001154 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001155 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001156 if (!thread_sp)
1157 {
1158 // Create the thread if we need to
1159 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1160 m_thread_list.AddThread(thread_sp);
1161 }
Chris Lattner24943d22010-06-08 16:52:24 +00001162 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001163 else if (name.compare("hexname") == 0)
1164 {
1165 StringExtractor name_extractor;
1166 // Swap "value" over into "name_extractor"
1167 name_extractor.GetStringRef().swap(value);
1168 // Now convert the HEX bytes into a string value
1169 name_extractor.GetHexByteString (value);
1170 thread_name.swap (value);
1171 }
Chris Lattner24943d22010-06-08 16:52:24 +00001172 else if (name.compare("name") == 0)
1173 {
1174 thread_name.swap (value);
1175 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001176 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001177 {
1178 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1179 }
Greg Claytona875b642011-01-09 21:07:35 +00001180 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1181 {
1182 // We have a register number that contains an expedited
1183 // register value. Lets supply this register to our thread
1184 // so it won't have to go and read it.
1185 if (thread_sp)
1186 {
1187 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1188
1189 if (reg != UINT32_MAX)
1190 {
1191 StringExtractor reg_value_extractor;
1192 // Swap "value" over into "reg_value_extractor"
1193 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001194 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1195 {
1196 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1197 name.c_str(),
1198 reg,
1199 reg,
1200 reg_value_extractor.GetStringRef().c_str(),
1201 stop_packet.GetStringRef().c_str());
1202 }
Greg Claytona875b642011-01-09 21:07:35 +00001203 }
1204 }
1205 }
Chris Lattner24943d22010-06-08 16:52:24 +00001206 }
Chris Lattner24943d22010-06-08 16:52:24 +00001207
1208 if (thread_sp)
1209 {
1210 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1211
1212 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001213 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001214 if (exc_type != 0)
1215 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001216 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001217
1218 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1219 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001220 exc_data_size,
1221 exc_data_size >= 1 ? exc_data[0] : 0,
1222 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001223 }
1224 else if (signo)
1225 {
Greg Clayton643ee732010-08-04 01:40:35 +00001226 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001227 }
1228 else
1229 {
Greg Clayton643ee732010-08-04 01:40:35 +00001230 StopInfoSP invalid_stop_info_sp;
1231 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001232 }
1233 }
1234 return eStateStopped;
1235 }
1236 break;
1237
1238 case 'W':
1239 // process exited
1240 return eStateExited;
1241
1242 default:
1243 break;
1244 }
1245 return eStateInvalid;
1246}
1247
1248void
1249ProcessGDBRemote::RefreshStateAfterStop ()
1250{
Jim Ingham7508e732010-08-09 23:31:02 +00001251 // FIXME - add a variable to tell that we're in the middle of attaching if we
1252 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001253 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001254// if (!GetTarget().GetArchitecture().IsValid())
1255// {
1256// Module *exe_module = GetTarget().GetExecutableModule().get();
1257// if (exe_module)
1258// m_arch_spec = exe_module->GetArchitecture();
1259// }
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261 // Let all threads recover from stopping and do any clean up based
1262 // on the previous thread state (if any).
1263 m_thread_list.RefreshStateAfterStop();
1264
1265 // Discover new threads:
1266 UpdateThreadListIfNeeded ();
1267}
1268
1269Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001270ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001271{
1272 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001273
Greg Claytona4881d02011-01-22 07:12:45 +00001274 bool timed_out = false;
1275 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001276
1277 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001278 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001279 // We are being asked to halt during an attach. We need to just close
1280 // our file handle and debugserver will go away, and we can be done...
1281 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001282 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001283 else
1284 {
1285 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1286 {
1287 if (timed_out)
1288 error.SetErrorString("timed out sending interrupt packet");
1289 else
1290 error.SetErrorString("unknown error sending interrupt packet");
1291 }
1292 }
Chris Lattner24943d22010-06-08 16:52:24 +00001293 return error;
1294}
1295
1296Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001297ProcessGDBRemote::InterruptIfRunning
1298(
1299 bool discard_thread_plans,
1300 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001301 EventSP &stop_event_sp
1302)
Chris Lattner24943d22010-06-08 16:52:24 +00001303{
1304 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001305
Greg Clayton2860ba92011-01-23 19:58:49 +00001306 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1307
Greg Clayton68ca8232011-01-25 02:58:48 +00001308 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001309 const bool is_running = m_gdb_comm.IsRunning();
1310 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001311 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001312 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001313 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001314 is_running);
1315
Greg Clayton2860ba92011-01-23 19:58:49 +00001316 if (discard_thread_plans)
1317 {
1318 if (log)
1319 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1320 m_thread_list.DiscardThreadPlans();
1321 }
1322 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001323 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001324 if (catch_stop_event)
1325 {
1326 if (log)
1327 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1328 PausePrivateStateThread();
1329 paused_private_state_thread = true;
1330 }
1331
Greg Clayton4fb400f2010-09-27 21:07:38 +00001332 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001333 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001334 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001335
Greg Clayton72e1c782011-01-22 23:43:18 +00001336 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001337 {
1338 if (timed_out)
1339 error.SetErrorString("timed out sending interrupt packet");
1340 else
1341 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001342 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001343 ResumePrivateStateThread();
1344 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001345 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001346
Greg Clayton72e1c782011-01-22 23:43:18 +00001347 if (catch_stop_event)
1348 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001349 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001350 TimeValue timeout_time;
1351 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001352 timeout_time.OffsetWithSeconds(5);
1353 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001354
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001355 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001356 if (log)
1357 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001358
Greg Clayton2860ba92011-01-23 19:58:49 +00001359 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001360 error.SetErrorString("unable to verify target stopped");
1361 }
1362
Greg Clayton68ca8232011-01-25 02:58:48 +00001363 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001364 {
1365 if (log)
1366 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001367 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001368 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001369 }
Chris Lattner24943d22010-06-08 16:52:24 +00001370 return error;
1371}
1372
Greg Clayton4fb400f2010-09-27 21:07:38 +00001373Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001374ProcessGDBRemote::WillDetach ()
1375{
Greg Clayton2860ba92011-01-23 19:58:49 +00001376 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1377 if (log)
1378 log->Printf ("ProcessGDBRemote::WillDetach()");
1379
Greg Clayton72e1c782011-01-22 23:43:18 +00001380 bool discard_thread_plans = true;
1381 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001382 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001383 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001384}
1385
1386Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001387ProcessGDBRemote::DoDetach()
1388{
1389 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001390 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001391 if (log)
1392 log->Printf ("ProcessGDBRemote::DoDetach()");
1393
1394 DisableAllBreakpointSites ();
1395
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001396 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001397
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001398 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1399 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001400 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001401 if (response_size)
1402 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1403 else
1404 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001405 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001406 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001407 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001408
Greg Clayton4fb400f2010-09-27 21:07:38 +00001409 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001410 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001411
1412 SetPrivateState (eStateDetached);
1413 ResumePrivateStateThread();
1414
1415 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001416 return error;
1417}
Chris Lattner24943d22010-06-08 16:52:24 +00001418
1419Error
1420ProcessGDBRemote::DoDestroy ()
1421{
1422 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001423 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001424 if (log)
1425 log->Printf ("ProcessGDBRemote::DoDestroy()");
1426
1427 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001428 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001429 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001430 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001431 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001432 // We are being asked to halt during an attach. We need to just close
1433 // our file handle and debugserver will go away, and we can be done...
1434 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001435 }
1436 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001437 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001438
1439 StringExtractorGDBRemote response;
1440 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001441 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001442 {
1443 char packet_cmd = response.GetChar(0);
1444
1445 if (packet_cmd == 'W' || packet_cmd == 'X')
1446 {
1447 m_last_stop_packet = response;
1448 SetExitStatus(response.GetHexU8(), NULL);
1449 }
1450 }
1451 else
1452 {
1453 SetExitStatus(SIGABRT, NULL);
1454 //error.SetErrorString("kill packet failed");
1455 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001456 }
1457 }
Chris Lattner24943d22010-06-08 16:52:24 +00001458 StopAsyncThread ();
1459 m_gdb_comm.StopReadThread();
1460 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001461 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001462 return error;
1463}
1464
Chris Lattner24943d22010-06-08 16:52:24 +00001465//------------------------------------------------------------------
1466// Process Queries
1467//------------------------------------------------------------------
1468
1469bool
1470ProcessGDBRemote::IsAlive ()
1471{
Greg Clayton58e844b2010-12-08 05:08:21 +00001472 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001473}
1474
1475addr_t
1476ProcessGDBRemote::GetImageInfoAddress()
1477{
1478 if (!m_gdb_comm.IsRunning())
1479 {
1480 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001481 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001482 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001483 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001484 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1485 }
1486 }
1487 return LLDB_INVALID_ADDRESS;
1488}
1489
Chris Lattner24943d22010-06-08 16:52:24 +00001490//------------------------------------------------------------------
1491// Process Memory
1492//------------------------------------------------------------------
1493size_t
1494ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1495{
1496 if (size > m_max_memory_size)
1497 {
1498 // Keep memory read sizes down to a sane limit. This function will be
1499 // called multiple times in order to complete the task by
1500 // lldb_private::Process so it is ok to do this.
1501 size = m_max_memory_size;
1502 }
1503
1504 char packet[64];
1505 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1506 assert (packet_len + 1 < sizeof(packet));
1507 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001508 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001509 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001510 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001511 {
1512 error.Clear();
1513 return response.GetHexBytes(buf, size, '\xdd');
1514 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001515 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001516 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001517 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001518 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1519 else
1520 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1521 }
1522 else
1523 {
1524 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1525 }
1526 return 0;
1527}
1528
1529size_t
1530ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1531{
1532 StreamString packet;
1533 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001534 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001535 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001536 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001537 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001538 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001539 {
1540 error.Clear();
1541 return size;
1542 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001543 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001544 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001545 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001546 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1547 else
1548 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1549 }
1550 else
1551 {
1552 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1553 }
1554 return 0;
1555}
1556
1557lldb::addr_t
1558ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1559{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001560 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001561 if (allocated_addr == LLDB_INVALID_ADDRESS)
1562 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1563 else
1564 error.Clear();
1565 return allocated_addr;
1566}
1567
1568Error
1569ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1570{
1571 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001572 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001573 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1574 return error;
1575}
1576
1577
1578//------------------------------------------------------------------
1579// Process STDIO
1580//------------------------------------------------------------------
1581
1582size_t
1583ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1584{
1585 Mutex::Locker locker(m_stdio_mutex);
1586 size_t bytes_available = m_stdout_data.size();
1587 if (bytes_available > 0)
1588 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001589 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1590 if (log)
1591 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001592 if (bytes_available > buf_size)
1593 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001594 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001595 m_stdout_data.erase(0, buf_size);
1596 bytes_available = buf_size;
1597 }
1598 else
1599 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001600 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001601 m_stdout_data.clear();
1602
1603 //ResetEventBits(eBroadcastBitSTDOUT);
1604 }
1605 }
1606 return bytes_available;
1607}
1608
1609size_t
1610ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1611{
1612 // Can we get STDERR through the remote protocol?
1613 return 0;
1614}
1615
1616size_t
1617ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1618{
1619 if (m_stdio_communication.IsConnected())
1620 {
1621 ConnectionStatus status;
1622 m_stdio_communication.Write(src, src_len, status, NULL);
1623 }
1624 return 0;
1625}
1626
1627Error
1628ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1629{
1630 Error error;
1631 assert (bp_site != NULL);
1632
Greg Claytone005f2c2010-11-06 01:53:30 +00001633 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001634 user_id_t site_id = bp_site->GetID();
1635 const addr_t addr = bp_site->GetLoadAddress();
1636 if (log)
1637 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1638
1639 if (bp_site->IsEnabled())
1640 {
1641 if (log)
1642 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1643 return error;
1644 }
1645 else
1646 {
1647 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1648
1649 if (bp_site->HardwarePreferred())
1650 {
1651 // Try and set hardware breakpoint, and if that fails, fall through
1652 // and set a software breakpoint?
1653 }
1654
1655 if (m_z0_supported)
1656 {
1657 char packet[64];
1658 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1659 assert (packet_len + 1 < sizeof(packet));
1660 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001661 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001662 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001663 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001664 {
1665 // Disable z packet support and try again
1666 m_z0_supported = 0;
1667 return EnableBreakpoint (bp_site);
1668 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001669 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001670 {
1671 bp_site->SetEnabled(true);
1672 bp_site->SetType (BreakpointSite::eExternal);
1673 return error;
1674 }
1675 else
1676 {
1677 uint8_t error_byte = response.GetError();
1678 if (error_byte)
1679 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1680 }
1681 }
1682 }
1683 else
1684 {
1685 return EnableSoftwareBreakpoint (bp_site);
1686 }
1687 }
1688
1689 if (log)
1690 {
1691 const char *err_string = error.AsCString();
1692 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1693 bp_site->GetLoadAddress(),
1694 err_string ? err_string : "NULL");
1695 }
1696 // We shouldn't reach here on a successful breakpoint enable...
1697 if (error.Success())
1698 error.SetErrorToGenericError();
1699 return error;
1700}
1701
1702Error
1703ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1704{
1705 Error error;
1706 assert (bp_site != NULL);
1707 addr_t addr = bp_site->GetLoadAddress();
1708 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001709 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001710 if (log)
1711 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1712
1713 if (bp_site->IsEnabled())
1714 {
1715 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1716
1717 if (bp_site->IsHardware())
1718 {
1719 // TODO: disable hardware breakpoint...
1720 }
1721 else
1722 {
1723 if (m_z0_supported)
1724 {
1725 char packet[64];
1726 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1727 assert (packet_len + 1 < sizeof(packet));
1728 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001729 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001730 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001731 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001732 {
1733 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1734 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001735 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001736 {
1737 if (log)
1738 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1739 bp_site->SetEnabled(false);
1740 return error;
1741 }
1742 else
1743 {
1744 uint8_t error_byte = response.GetError();
1745 if (error_byte)
1746 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1747 }
1748 }
1749 }
1750 else
1751 {
1752 return DisableSoftwareBreakpoint (bp_site);
1753 }
1754 }
1755 }
1756 else
1757 {
1758 if (log)
1759 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1760 return error;
1761 }
1762
1763 if (error.Success())
1764 error.SetErrorToGenericError();
1765 return error;
1766}
1767
1768Error
1769ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1770{
1771 Error error;
1772 if (wp)
1773 {
1774 user_id_t watchID = wp->GetID();
1775 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001776 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001777 if (log)
1778 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1779 if (wp->IsEnabled())
1780 {
1781 if (log)
1782 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1783 return error;
1784 }
1785 else
1786 {
1787 // Pass down an appropriate z/Z packet...
1788 error.SetErrorString("watchpoints not supported");
1789 }
1790 }
1791 else
1792 {
1793 error.SetErrorString("Watchpoint location argument was NULL.");
1794 }
1795 if (error.Success())
1796 error.SetErrorToGenericError();
1797 return error;
1798}
1799
1800Error
1801ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1802{
1803 Error error;
1804 if (wp)
1805 {
1806 user_id_t watchID = wp->GetID();
1807
Greg Claytone005f2c2010-11-06 01:53:30 +00001808 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001809
1810 addr_t addr = wp->GetLoadAddress();
1811 if (log)
1812 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1813
1814 if (wp->IsHardware())
1815 {
1816 // Pass down an appropriate z/Z packet...
1817 error.SetErrorString("watchpoints not supported");
1818 }
1819 // TODO: clear software watchpoints if we implement them
1820 }
1821 else
1822 {
1823 error.SetErrorString("Watchpoint location argument was NULL.");
1824 }
1825 if (error.Success())
1826 error.SetErrorToGenericError();
1827 return error;
1828}
1829
1830void
1831ProcessGDBRemote::Clear()
1832{
1833 m_flags = 0;
1834 m_thread_list.Clear();
1835 {
1836 Mutex::Locker locker(m_stdio_mutex);
1837 m_stdout_data.clear();
1838 }
Chris Lattner24943d22010-06-08 16:52:24 +00001839}
1840
1841Error
1842ProcessGDBRemote::DoSignal (int signo)
1843{
1844 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001845 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001846 if (log)
1847 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1848
1849 if (!m_gdb_comm.SendAsyncSignal (signo))
1850 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1851 return error;
1852}
1853
Chris Lattner24943d22010-06-08 16:52:24 +00001854Error
1855ProcessGDBRemote::StartDebugserverProcess
1856(
1857 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1858 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1859 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001860 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 +00001861 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1862 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001863 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001864)
1865{
1866 Error error;
1867 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1868 {
1869 // If we locate debugserver, keep that located version around
1870 static FileSpec g_debugserver_file_spec;
1871
1872 FileSpec debugserver_file_spec;
1873 char debugserver_path[PATH_MAX];
1874
1875 // Always check to see if we have an environment override for the path
1876 // to the debugserver to use and use it if we do.
1877 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1878 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001879 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001880 else
1881 debugserver_file_spec = g_debugserver_file_spec;
1882 bool debugserver_exists = debugserver_file_spec.Exists();
1883 if (!debugserver_exists)
1884 {
1885 // The debugserver binary is in the LLDB.framework/Resources
1886 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001887 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001888 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001889 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001890 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001891 if (debugserver_exists)
1892 {
1893 g_debugserver_file_spec = debugserver_file_spec;
1894 }
1895 else
1896 {
1897 g_debugserver_file_spec.Clear();
1898 debugserver_file_spec.Clear();
1899 }
Chris Lattner24943d22010-06-08 16:52:24 +00001900 }
1901 }
1902
1903 if (debugserver_exists)
1904 {
1905 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1906
1907 m_stdio_communication.Clear();
1908 posix_spawnattr_t attr;
1909
Greg Claytone005f2c2010-11-06 01:53:30 +00001910 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001911
1912 Error local_err; // Errors that don't affect the spawning.
1913 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001914 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1915 __FUNCTION__,
1916 debugserver_path,
1917 inferior_argv,
1918 inferior_envp,
1919 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001920 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1921 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001922 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001923 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001924 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001925
Chris Lattner24943d22010-06-08 16:52:24 +00001926 Args debugserver_args;
1927 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001928
Chris Lattner24943d22010-06-08 16:52:24 +00001929 // Start args with "debugserver /file/path -r --"
1930 debugserver_args.AppendArgument(debugserver_path);
1931 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001932 // use native registers, not the GDB registers
1933 debugserver_args.AppendArgument("--native-regs");
1934 // make debugserver run in its own session so signals generated by
1935 // special terminal key sequences (^C) don't affect debugserver
1936 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001937
Chris Lattner24943d22010-06-08 16:52:24 +00001938 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1939 if (env_debugserver_log_file)
1940 {
1941 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1942 debugserver_args.AppendArgument(arg_cstr);
1943 }
1944
1945 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1946 if (env_debugserver_log_flags)
1947 {
1948 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1949 debugserver_args.AppendArgument(arg_cstr);
1950 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001951// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001952// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001953
1954 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001955 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001956 {
Greg Claytona2f74232011-02-24 22:24:29 +00001957 // Terminate the debugserver args so we can now append the inferior args
1958 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001959
Greg Claytona2f74232011-02-24 22:24:29 +00001960 for (int i = 0; inferior_argv[i] != NULL; ++i)
1961 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001962 }
1963 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1964 {
1965 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1966 debugserver_args.AppendArgument (arg_cstr);
1967 }
1968 else if (attach_name && attach_name[0])
1969 {
1970 if (wait_for_launch)
1971 debugserver_args.AppendArgument ("--waitfor");
1972 else
1973 debugserver_args.AppendArgument ("--attach");
1974 debugserver_args.AppendArgument (attach_name);
1975 }
1976
1977 Error file_actions_err;
1978 posix_spawn_file_actions_t file_actions;
1979#if DONT_CLOSE_DEBUGSERVER_STDIO
1980 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1981#else
1982 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1983 if (file_actions_err.Success())
1984 {
1985 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1986 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1987 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1988 }
1989#endif
1990
1991 if (log)
1992 {
1993 StreamString strm;
1994 debugserver_args.Dump (&strm);
1995 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1996 }
1997
Greg Clayton72e1c782011-01-22 23:43:18 +00001998 error.SetError (::posix_spawnp (&m_debugserver_pid,
1999 debugserver_path,
2000 file_actions_err.Success() ? &file_actions : NULL,
2001 &attr,
2002 debugserver_args.GetArgumentVector(),
2003 (char * const*)inferior_envp),
2004 eErrorTypePOSIX);
2005
Greg Claytone9d0df42010-07-02 01:29:13 +00002006
2007 ::posix_spawnattr_destroy (&attr);
2008
Chris Lattner24943d22010-06-08 16:52:24 +00002009 if (file_actions_err.Success())
2010 ::posix_spawn_file_actions_destroy (&file_actions);
2011
2012 // We have seen some cases where posix_spawnp was returning a valid
2013 // looking pid even when an error was returned, so clear it out
2014 if (error.Fail())
2015 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2016
2017 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002018 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 +00002019
Chris Lattner24943d22010-06-08 16:52:24 +00002020 }
2021 else
2022 {
2023 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2024 }
2025
2026 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2027 StartAsyncThread ();
2028 }
2029 return error;
2030}
2031
2032bool
2033ProcessGDBRemote::MonitorDebugserverProcess
2034(
2035 void *callback_baton,
2036 lldb::pid_t debugserver_pid,
2037 int signo, // Zero for no signal
2038 int exit_status // Exit value of process if signal is zero
2039)
2040{
2041 // We pass in the ProcessGDBRemote inferior process it and name it
2042 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2043 // pointer value itself, thus we need the double cast...
2044
2045 // "debugserver_pid" argument passed in is the process ID for
2046 // debugserver that we are tracking...
2047
Greg Clayton75ccf502010-08-21 02:22:51 +00002048 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002049
2050 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2051 if (log)
2052 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2053
Greg Clayton75ccf502010-08-21 02:22:51 +00002054 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002055 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002056 // Sleep for a half a second to make sure our inferior process has
2057 // time to set its exit status before we set it incorrectly when
2058 // both the debugserver and the inferior process shut down.
2059 usleep (500000);
2060 // If our process hasn't yet exited, debugserver might have died.
2061 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002062 const StateType state = process->GetState();
2063
2064 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2065 state != eStateInvalid &&
2066 state != eStateUnloaded &&
2067 state != eStateExited &&
2068 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002069 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002070 char error_str[1024];
2071 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002072 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002073 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2074 if (signal_cstr)
2075 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002076 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002077 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002078 }
2079 else
2080 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002081 ::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 +00002082 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002083
2084 process->SetExitStatus (-1, error_str);
2085 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002086 // Debugserver has exited we need to let our ProcessGDBRemote
2087 // know that it no longer has a debugserver instance
2088 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2089 // We are returning true to this function below, so we can
2090 // forget about the monitor handle.
2091 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002092 }
2093 return true;
2094}
2095
2096void
2097ProcessGDBRemote::KillDebugserverProcess ()
2098{
2099 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2100 {
2101 ::kill (m_debugserver_pid, SIGINT);
2102 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2103 }
2104}
2105
2106void
2107ProcessGDBRemote::Initialize()
2108{
2109 static bool g_initialized = false;
2110
2111 if (g_initialized == false)
2112 {
2113 g_initialized = true;
2114 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2115 GetPluginDescriptionStatic(),
2116 CreateInstance);
2117
2118 Log::Callbacks log_callbacks = {
2119 ProcessGDBRemoteLog::DisableLog,
2120 ProcessGDBRemoteLog::EnableLog,
2121 ProcessGDBRemoteLog::ListLogCategories
2122 };
2123
2124 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2125 }
2126}
2127
2128bool
2129ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2130{
2131 if (m_curr_tid == tid)
2132 return true;
2133
2134 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002135 int packet_len;
2136 if (tid <= 0)
2137 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2138 else
2139 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002140 assert (packet_len + 1 < sizeof(packet));
2141 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002142 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002143 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002144 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002145 {
2146 m_curr_tid = tid;
2147 return true;
2148 }
2149 }
2150 return false;
2151}
2152
2153bool
2154ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2155{
2156 if (m_curr_tid_run == tid)
2157 return true;
2158
2159 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002160 int packet_len;
2161 if (tid <= 0)
2162 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2163 else
2164 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2165
Chris Lattner24943d22010-06-08 16:52:24 +00002166 assert (packet_len + 1 < sizeof(packet));
2167 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002168 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002169 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002170 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002171 {
2172 m_curr_tid_run = tid;
2173 return true;
2174 }
2175 }
2176 return false;
2177}
2178
2179void
2180ProcessGDBRemote::ResetGDBRemoteState ()
2181{
2182 // Reset and GDB remote state
2183 m_curr_tid = LLDB_INVALID_THREAD_ID;
2184 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2185 m_z0_supported = 1;
2186}
2187
2188
2189bool
2190ProcessGDBRemote::StartAsyncThread ()
2191{
2192 ResetGDBRemoteState ();
2193
Greg Claytone005f2c2010-11-06 01:53:30 +00002194 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002195
2196 if (log)
2197 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2198
2199 // Create a thread that watches our internal state and controls which
2200 // events make it to clients (into the DCProcess event queue).
2201 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002202 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002203}
2204
2205void
2206ProcessGDBRemote::StopAsyncThread ()
2207{
Greg Claytone005f2c2010-11-06 01:53:30 +00002208 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002209
2210 if (log)
2211 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2212
2213 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2214
2215 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002216 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002217 {
2218 Host::ThreadJoin (m_async_thread, NULL, NULL);
2219 }
2220}
2221
2222
2223void *
2224ProcessGDBRemote::AsyncThread (void *arg)
2225{
2226 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2227
Greg Claytone005f2c2010-11-06 01:53:30 +00002228 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002229 if (log)
2230 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2231
2232 Listener listener ("ProcessGDBRemote::AsyncThread");
2233 EventSP event_sp;
2234 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2235 eBroadcastBitAsyncThreadShouldExit;
2236
2237 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2238 {
Greg Claytona2f74232011-02-24 22:24:29 +00002239 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2240
Chris Lattner24943d22010-06-08 16:52:24 +00002241 bool done = false;
2242 while (!done)
2243 {
2244 if (log)
2245 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2246 if (listener.WaitForEvent (NULL, event_sp))
2247 {
2248 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002249 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002250 {
Greg Claytona2f74232011-02-24 22:24:29 +00002251 if (log)
2252 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 +00002253
Greg Claytona2f74232011-02-24 22:24:29 +00002254 switch (event_type)
2255 {
2256 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002257 {
Greg Claytona2f74232011-02-24 22:24:29 +00002258 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002259
Greg Claytona2f74232011-02-24 22:24:29 +00002260 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002261 {
Greg Claytona2f74232011-02-24 22:24:29 +00002262 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2263 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2264 if (log)
2265 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002266
Greg Claytona2f74232011-02-24 22:24:29 +00002267 if (::strstr (continue_cstr, "vAttach") == NULL)
2268 process->SetPrivateState(eStateRunning);
2269 StringExtractorGDBRemote response;
2270 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002271
Greg Claytona2f74232011-02-24 22:24:29 +00002272 switch (stop_state)
2273 {
2274 case eStateStopped:
2275 case eStateCrashed:
2276 case eStateSuspended:
2277 process->m_last_stop_packet = response;
2278 process->m_last_stop_packet.SetFilePos (0);
2279 process->SetPrivateState (stop_state);
2280 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002281
Greg Claytona2f74232011-02-24 22:24:29 +00002282 case eStateExited:
2283 process->m_last_stop_packet = response;
2284 process->m_last_stop_packet.SetFilePos (0);
2285 response.SetFilePos(1);
2286 process->SetExitStatus(response.GetHexU8(), NULL);
2287 done = true;
2288 break;
2289
2290 case eStateInvalid:
2291 process->SetExitStatus(-1, "lost connection");
2292 break;
2293
2294 default:
2295 process->SetPrivateState (stop_state);
2296 break;
2297 }
Chris Lattner24943d22010-06-08 16:52:24 +00002298 }
2299 }
Greg Claytona2f74232011-02-24 22:24:29 +00002300 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002301
Greg Claytona2f74232011-02-24 22:24:29 +00002302 case eBroadcastBitAsyncThreadShouldExit:
2303 if (log)
2304 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2305 done = true;
2306 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002307
Greg Claytona2f74232011-02-24 22:24:29 +00002308 default:
2309 if (log)
2310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2311 done = true;
2312 break;
2313 }
2314 }
2315 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2316 {
2317 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2318 {
2319 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002320 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002321 }
Chris Lattner24943d22010-06-08 16:52:24 +00002322 }
2323 }
2324 else
2325 {
2326 if (log)
2327 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2328 done = true;
2329 }
2330 }
2331 }
2332
2333 if (log)
2334 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2335
2336 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2337 return NULL;
2338}
2339
Chris Lattner24943d22010-06-08 16:52:24 +00002340const char *
2341ProcessGDBRemote::GetDispatchQueueNameForThread
2342(
2343 addr_t thread_dispatch_qaddr,
2344 std::string &dispatch_queue_name
2345)
2346{
2347 dispatch_queue_name.clear();
2348 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2349 {
2350 // Cache the dispatch_queue_offsets_addr value so we don't always have
2351 // to look it up
2352 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2353 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002354 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2355 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002356 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002357 if (module_sp)
2358 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2359
2360 if (dispatch_queue_offsets_symbol == NULL)
2361 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002362 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002363 if (module_sp)
2364 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2365 }
Chris Lattner24943d22010-06-08 16:52:24 +00002366 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002367 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002368
2369 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2370 return NULL;
2371 }
2372
2373 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002374 DataExtractor data (memory_buffer,
2375 sizeof(memory_buffer),
2376 m_target.GetArchitecture().GetByteOrder(),
2377 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002378
2379 // Excerpt from src/queue_private.h
2380 struct dispatch_queue_offsets_s
2381 {
2382 uint16_t dqo_version;
2383 uint16_t dqo_label;
2384 uint16_t dqo_label_size;
2385 } dispatch_queue_offsets;
2386
2387
2388 Error error;
2389 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2390 {
2391 uint32_t data_offset = 0;
2392 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2393 {
2394 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2395 {
2396 data_offset = 0;
2397 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2398 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2399 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2400 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2401 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2402 dispatch_queue_name.erase (bytes_read);
2403 }
2404 }
2405 }
2406 }
2407 if (dispatch_queue_name.empty())
2408 return NULL;
2409 return dispatch_queue_name.c_str();
2410}
2411
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002412//uint32_t
2413//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2414//{
2415// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2416// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2417// if (m_local_debugserver)
2418// {
2419// return Host::ListProcessesMatchingName (name, matches, pids);
2420// }
2421// else
2422// {
2423// // FIXME: Implement talking to the remote debugserver.
2424// return 0;
2425// }
2426//
2427//}
2428//
Jim Ingham55e01d82011-01-22 01:33:44 +00002429bool
2430ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2431 lldb_private::StoppointCallbackContext *context,
2432 lldb::user_id_t break_id,
2433 lldb::user_id_t break_loc_id)
2434{
2435 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2436 // run so I can stop it if that's what I want to do.
2437 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2438 if (log)
2439 log->Printf("Hit New Thread Notification breakpoint.");
2440 return false;
2441}
2442
2443
2444bool
2445ProcessGDBRemote::StartNoticingNewThreads()
2446{
2447 static const char *bp_names[] =
2448 {
2449 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002450 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002451 "_pthread_start",
2452 NULL
2453 };
2454
2455 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2456 size_t num_bps = m_thread_observation_bps.size();
2457 if (num_bps != 0)
2458 {
2459 for (int i = 0; i < num_bps; i++)
2460 {
2461 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2462 if (break_sp)
2463 {
2464 if (log)
2465 log->Printf("Enabled noticing new thread breakpoint.");
2466 break_sp->SetEnabled(true);
2467 }
2468 }
2469 }
2470 else
2471 {
2472 for (int i = 0; bp_names[i] != NULL; i++)
2473 {
2474 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2475 if (breakpoint)
2476 {
2477 if (log)
2478 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2479 m_thread_observation_bps.push_back(breakpoint->GetID());
2480 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2481 }
2482 else
2483 {
2484 if (log)
2485 log->Printf("Failed to create new thread notification breakpoint.");
2486 return false;
2487 }
2488 }
2489 }
2490
2491 return true;
2492}
2493
2494bool
2495ProcessGDBRemote::StopNoticingNewThreads()
2496{
Jim Inghamff276fe2011-02-08 05:19:01 +00002497 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2498 if (log)
2499 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002500 size_t num_bps = m_thread_observation_bps.size();
2501 if (num_bps != 0)
2502 {
2503 for (int i = 0; i < num_bps; i++)
2504 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002505
2506 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2507 if (break_sp)
2508 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002509 break_sp->SetEnabled(false);
2510 }
2511 }
2512 }
2513 return true;
2514}
2515
2516