blob: 79949669e77c278bccc3e908233691e6aaba9238 [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 Clayton395fc332011-02-15 21:59:32 +0000625 m_target.GetArchitecture().SetByteOrder (m_gdb_comm.GetByteOrder());
Greg Clayton20d338f2010-11-18 05:57:03 +0000626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 StreamString strm;
628
Chris Lattner24943d22010-06-08 16:52:24 +0000629 // See if the GDB server supports the qHostInfo information
630 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
631 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytonfc7920f2011-02-09 03:09:55 +0000632 ArchSpec target_arch (GetTarget().GetArchitecture());
633 ArchSpec gdb_remote_arch (m_gdb_comm.GetHostArchitecture());
634
Greg Claytonc62176d2011-02-09 03:12:09 +0000635 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytonfc7920f2011-02-09 03:09:55 +0000636 // ARM executables and shared libraries can have mixed ARM architectures.
637 // You can have an armv6 executable, and if the host is armv7, then the
638 // system will load the best possible architecture for all shared libraries
639 // it has, so we really need to take the remote host architecture as our
640 // defacto architecture in this case.
641
Greg Clayton940b1032011-02-23 00:35:02 +0000642 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
643 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytonfc7920f2011-02-09 03:09:55 +0000644 {
645 GetTarget().SetArchitecture (gdb_remote_arch);
646 target_arch = gdb_remote_arch;
647 }
648
Greg Clayton395fc332011-02-15 21:59:32 +0000649 if (vendor)
650 m_target.GetArchitecture().GetTriple().setVendorName(vendor);
651 if (os_type)
652 m_target.GetArchitecture().GetTriple().setOSName(os_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000653 }
654}
655
656void
657ProcessGDBRemote::DidLaunch ()
658{
659 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000660}
661
662Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000663ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000664{
665 Error error;
666 // Clear out and clean up from any current state
667 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000668 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000669
Chris Lattner24943d22010-06-08 16:52:24 +0000670 if (attach_pid != LLDB_INVALID_PROCESS_ID)
671 {
Greg Claytona2f74232011-02-24 22:24:29 +0000672 // Make sure we aren't already connected?
673 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000674 {
Greg Claytona2f74232011-02-24 22:24:29 +0000675 char host_port[128];
676 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
677 char connect_url[128];
678 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000679
Greg Claytona2f74232011-02-24 22:24:29 +0000680 error = StartDebugserverProcess (host_port, // debugserver_url
681 NULL, // inferior_argv
682 NULL, // inferior_envp
683 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
684 NULL, // Don't send any attach by process name option to debugserver
685 false, // Don't send any attach wait_for_launch flag as an option to debugserver
686 arch_spec);
687
688 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000689 {
Greg Claytona2f74232011-02-24 22:24:29 +0000690 const char *error_string = error.AsCString();
691 if (error_string == NULL)
692 error_string = "unable to launch " DEBUGSERVER_BASENAME;
693
694 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000695 }
Greg Claytona2f74232011-02-24 22:24:29 +0000696 else
697 {
698 error = ConnectToDebugserver (connect_url);
699 }
700 }
701
702 if (error.Success())
703 {
704 char packet[64];
705 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
706
707 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000708 }
709 }
Chris Lattner24943d22010-06-08 16:52:24 +0000710 return error;
711}
712
713size_t
714ProcessGDBRemote::AttachInputReaderCallback
715(
716 void *baton,
717 InputReader *reader,
718 lldb::InputReaderAction notification,
719 const char *bytes,
720 size_t bytes_len
721)
722{
723 if (notification == eInputReaderGotToken)
724 {
725 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
726 if (gdb_process->m_waiting_for_attach)
727 gdb_process->m_waiting_for_attach = false;
728 reader->SetIsDone(true);
729 return 1;
730 }
731 return 0;
732}
733
734Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000735ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000736{
737 Error error;
738 // Clear out and clean up from any current state
739 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000740
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (process_name && process_name[0])
742 {
Greg Claytona2f74232011-02-24 22:24:29 +0000743 // Make sure we aren't already connected?
744 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000745 {
Chris Lattner24943d22010-06-08 16:52:24 +0000746
Greg Claytona2f74232011-02-24 22:24:29 +0000747 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
748
749 char host_port[128];
750 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
751 char connect_url[128];
752 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
753
754 error = StartDebugserverProcess (host_port, // debugserver_url
755 NULL, // inferior_argv
756 NULL, // inferior_envp
757 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
758 NULL, // Don't send any attach by process name option to debugserver
759 false, // Don't send any attach wait_for_launch flag as an option to debugserver
760 arch_spec);
761 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000762 {
Greg Claytona2f74232011-02-24 22:24:29 +0000763 const char *error_string = error.AsCString();
764 if (error_string == NULL)
765 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000766
Greg Claytona2f74232011-02-24 22:24:29 +0000767 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000768 }
Greg Claytona2f74232011-02-24 22:24:29 +0000769 else
770 {
771 error = ConnectToDebugserver (connect_url);
772 }
773 }
774
775 if (error.Success())
776 {
777 StreamString packet;
778
779 if (wait_for_launch)
780 packet.PutCString("vAttachWait");
781 else
782 packet.PutCString("vAttachName");
783 packet.PutChar(';');
784 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
785
786 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
787
Chris Lattner24943d22010-06-08 16:52:24 +0000788 }
789 }
Chris Lattner24943d22010-06-08 16:52:24 +0000790 return error;
791}
792
Chris Lattner24943d22010-06-08 16:52:24 +0000793
794void
795ProcessGDBRemote::DidAttach ()
796{
Greg Claytone71e2582011-02-04 01:58:07 +0000797 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000798}
799
800Error
801ProcessGDBRemote::WillResume ()
802{
Greg Claytonc1f45872011-02-12 06:28:37 +0000803 m_continue_c_tids.clear();
804 m_continue_C_tids.clear();
805 m_continue_s_tids.clear();
806 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000807 return Error();
808}
809
810Error
811ProcessGDBRemote::DoResume ()
812{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000813 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000814 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
815 if (log)
816 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000817
818 Listener listener ("gdb-remote.resume-packet-sent");
819 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
820 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000821 StreamString continue_packet;
822 bool continue_packet_error = false;
823 if (m_gdb_comm.HasAnyVContSupport ())
824 {
825 continue_packet.PutCString ("vCont");
826
827 if (!m_continue_c_tids.empty())
828 {
829 if (m_gdb_comm.GetVContSupported ('c'))
830 {
831 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)
832 continue_packet.Printf(";c:%4.4x", *t_pos);
833 }
834 else
835 continue_packet_error = true;
836 }
837
838 if (!continue_packet_error && !m_continue_C_tids.empty())
839 {
840 if (m_gdb_comm.GetVContSupported ('C'))
841 {
842 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)
843 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
844 }
845 else
846 continue_packet_error = true;
847 }
Greg Claytonb749a262010-12-03 06:02:24 +0000848
Greg Claytonc1f45872011-02-12 06:28:37 +0000849 if (!continue_packet_error && !m_continue_s_tids.empty())
850 {
851 if (m_gdb_comm.GetVContSupported ('s'))
852 {
853 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)
854 continue_packet.Printf(";s:%4.4x", *t_pos);
855 }
856 else
857 continue_packet_error = true;
858 }
859
860 if (!continue_packet_error && !m_continue_S_tids.empty())
861 {
862 if (m_gdb_comm.GetVContSupported ('S'))
863 {
864 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)
865 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
866 }
867 else
868 continue_packet_error = true;
869 }
870
871 if (continue_packet_error)
872 continue_packet.GetString().clear();
873 }
874 else
875 continue_packet_error = true;
876
877 if (continue_packet_error)
878 {
879 continue_packet_error = false;
880 // Either no vCont support, or we tried to use part of the vCont
881 // packet that wasn't supported by the remote GDB server.
882 // We need to try and make a simple packet that can do our continue
883 const size_t num_threads = GetThreadList().GetSize();
884 const size_t num_continue_c_tids = m_continue_c_tids.size();
885 const size_t num_continue_C_tids = m_continue_C_tids.size();
886 const size_t num_continue_s_tids = m_continue_s_tids.size();
887 const size_t num_continue_S_tids = m_continue_S_tids.size();
888 if (num_continue_c_tids > 0)
889 {
890 if (num_continue_c_tids == num_threads)
891 {
892 // All threads are resuming...
893 SetCurrentGDBRemoteThreadForRun (-1);
894 continue_packet.PutChar ('c');
895 }
896 else if (num_continue_c_tids == 1 &&
897 num_continue_C_tids == 0 &&
898 num_continue_s_tids == 0 &&
899 num_continue_S_tids == 0 )
900 {
901 // Only one thread is continuing
902 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
903 continue_packet.PutChar ('c');
904 }
905 else
906 {
907 // We can't represent this continue packet....
908 continue_packet_error = true;
909 }
910 }
911
912 if (!continue_packet_error && num_continue_C_tids > 0)
913 {
914 if (num_continue_C_tids == num_threads)
915 {
916 const int continue_signo = m_continue_C_tids.front().second;
917 if (num_continue_C_tids > 1)
918 {
919 for (size_t i=1; i<num_threads; ++i)
920 {
921 if (m_continue_C_tids[i].second != continue_signo)
922 continue_packet_error = true;
923 }
924 }
925 if (!continue_packet_error)
926 {
927 // Add threads continuing with the same signo...
928 SetCurrentGDBRemoteThreadForRun (-1);
929 continue_packet.Printf("C%2.2x", continue_signo);
930 }
931 }
932 else if (num_continue_c_tids == 0 &&
933 num_continue_C_tids == 1 &&
934 num_continue_s_tids == 0 &&
935 num_continue_S_tids == 0 )
936 {
937 // Only one thread is continuing with signal
938 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
939 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
940 }
941 else
942 {
943 // We can't represent this continue packet....
944 continue_packet_error = true;
945 }
946 }
947
948 if (!continue_packet_error && num_continue_s_tids > 0)
949 {
950 if (num_continue_s_tids == num_threads)
951 {
952 // All threads are resuming...
953 SetCurrentGDBRemoteThreadForRun (-1);
954 continue_packet.PutChar ('s');
955 }
956 else if (num_continue_c_tids == 0 &&
957 num_continue_C_tids == 0 &&
958 num_continue_s_tids == 1 &&
959 num_continue_S_tids == 0 )
960 {
961 // Only one thread is stepping
962 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
963 continue_packet.PutChar ('s');
964 }
965 else
966 {
967 // We can't represent this continue packet....
968 continue_packet_error = true;
969 }
970 }
971
972 if (!continue_packet_error && num_continue_S_tids > 0)
973 {
974 if (num_continue_S_tids == num_threads)
975 {
976 const int step_signo = m_continue_S_tids.front().second;
977 // Are all threads trying to step with the same signal?
978 if (num_continue_S_tids > 1)
979 {
980 for (size_t i=1; i<num_threads; ++i)
981 {
982 if (m_continue_S_tids[i].second != step_signo)
983 continue_packet_error = true;
984 }
985 }
986 if (!continue_packet_error)
987 {
988 // Add threads stepping with the same signo...
989 SetCurrentGDBRemoteThreadForRun (-1);
990 continue_packet.Printf("S%2.2x", step_signo);
991 }
992 }
993 else if (num_continue_c_tids == 0 &&
994 num_continue_C_tids == 0 &&
995 num_continue_s_tids == 0 &&
996 num_continue_S_tids == 1 )
997 {
998 // Only one thread is stepping with signal
999 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1000 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1001 }
1002 else
1003 {
1004 // We can't represent this continue packet....
1005 continue_packet_error = true;
1006 }
1007 }
1008 }
1009
1010 if (continue_packet_error)
1011 {
1012 error.SetErrorString ("can't make continue packet for this resume");
1013 }
1014 else
1015 {
1016 EventSP event_sp;
1017 TimeValue timeout;
1018 timeout = TimeValue::Now();
1019 timeout.OffsetWithSeconds (5);
1020 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1021
1022 if (listener.WaitForEvent (&timeout, event_sp) == false)
1023 error.SetErrorString("Resume timed out.");
1024 }
Greg Claytonb749a262010-12-03 06:02:24 +00001025 }
1026
Jim Ingham3ae449a2010-11-17 02:32:00 +00001027 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001028}
1029
Chris Lattner24943d22010-06-08 16:52:24 +00001030uint32_t
1031ProcessGDBRemote::UpdateThreadListIfNeeded ()
1032{
1033 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001034 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001035 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001036 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1037
Greg Clayton5205f0b2010-09-03 17:10:42 +00001038 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001039 const uint32_t stop_id = GetStopID();
1040 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1041 {
1042 // Update the thread list's stop id immediately so we don't recurse into this function.
1043 ThreadList curr_thread_list (this);
1044 curr_thread_list.SetStopID(stop_id);
1045
1046 Error err;
1047 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001048 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001049 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001050 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001051 {
1052 char ch = response.GetChar();
1053 if (ch == 'l')
1054 break;
1055 if (ch == 'm')
1056 {
1057 do
1058 {
1059 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1060
1061 if (tid != LLDB_INVALID_THREAD_ID)
1062 {
1063 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001064 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001065 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1066 curr_thread_list.AddThread(thread_sp);
1067 }
1068
1069 ch = response.GetChar();
1070 } while (ch == ',');
1071 }
1072 }
1073
1074 m_thread_list = curr_thread_list;
1075
1076 SetThreadStopInfo (m_last_stop_packet);
1077 }
1078 return GetThreadList().GetSize(false);
1079}
1080
1081
1082StateType
1083ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1084{
1085 const char stop_type = stop_packet.GetChar();
1086 switch (stop_type)
1087 {
1088 case 'T':
1089 case 'S':
1090 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001091 if (GetStopID() == 0)
1092 {
1093 // Our first stop, make sure we have a process ID, and also make
1094 // sure we know about our registers
1095 if (GetID() == LLDB_INVALID_PROCESS_ID)
1096 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001097 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001098 if (pid != LLDB_INVALID_PROCESS_ID)
1099 SetID (pid);
1100 }
1101 BuildDynamicRegisterInfo (true);
1102 }
Chris Lattner24943d22010-06-08 16:52:24 +00001103 // Stop with signal and thread info
1104 const uint8_t signo = stop_packet.GetHexU8();
1105 std::string name;
1106 std::string value;
1107 std::string thread_name;
1108 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001109 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001110 uint32_t tid = LLDB_INVALID_THREAD_ID;
1111 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1112 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001113 ThreadSP thread_sp;
1114
Chris Lattner24943d22010-06-08 16:52:24 +00001115 while (stop_packet.GetNameColonValue(name, value))
1116 {
1117 if (name.compare("metype") == 0)
1118 {
1119 // exception type in big endian hex
1120 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1121 }
1122 else if (name.compare("mecount") == 0)
1123 {
1124 // exception count in big endian hex
1125 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1126 }
1127 else if (name.compare("medata") == 0)
1128 {
1129 // exception data in big endian hex
1130 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1131 }
1132 else if (name.compare("thread") == 0)
1133 {
1134 // thread in big endian hex
1135 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001136 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001137 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001138 if (!thread_sp)
1139 {
1140 // Create the thread if we need to
1141 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1142 m_thread_list.AddThread(thread_sp);
1143 }
Chris Lattner24943d22010-06-08 16:52:24 +00001144 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001145 else if (name.compare("hexname") == 0)
1146 {
1147 StringExtractor name_extractor;
1148 // Swap "value" over into "name_extractor"
1149 name_extractor.GetStringRef().swap(value);
1150 // Now convert the HEX bytes into a string value
1151 name_extractor.GetHexByteString (value);
1152 thread_name.swap (value);
1153 }
Chris Lattner24943d22010-06-08 16:52:24 +00001154 else if (name.compare("name") == 0)
1155 {
1156 thread_name.swap (value);
1157 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001158 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001159 {
1160 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1161 }
Greg Claytona875b642011-01-09 21:07:35 +00001162 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1163 {
1164 // We have a register number that contains an expedited
1165 // register value. Lets supply this register to our thread
1166 // so it won't have to go and read it.
1167 if (thread_sp)
1168 {
1169 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1170
1171 if (reg != UINT32_MAX)
1172 {
1173 StringExtractor reg_value_extractor;
1174 // Swap "value" over into "reg_value_extractor"
1175 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001176 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1177 {
1178 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1179 name.c_str(),
1180 reg,
1181 reg,
1182 reg_value_extractor.GetStringRef().c_str(),
1183 stop_packet.GetStringRef().c_str());
1184 }
Greg Claytona875b642011-01-09 21:07:35 +00001185 }
1186 }
1187 }
Chris Lattner24943d22010-06-08 16:52:24 +00001188 }
Chris Lattner24943d22010-06-08 16:52:24 +00001189
1190 if (thread_sp)
1191 {
1192 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1193
1194 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001195 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001196 if (exc_type != 0)
1197 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001198 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001199
1200 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1201 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001202 exc_data_size,
1203 exc_data_size >= 1 ? exc_data[0] : 0,
1204 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001205 }
1206 else if (signo)
1207 {
Greg Clayton643ee732010-08-04 01:40:35 +00001208 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001209 }
1210 else
1211 {
Greg Clayton643ee732010-08-04 01:40:35 +00001212 StopInfoSP invalid_stop_info_sp;
1213 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001214 }
1215 }
1216 return eStateStopped;
1217 }
1218 break;
1219
1220 case 'W':
1221 // process exited
1222 return eStateExited;
1223
1224 default:
1225 break;
1226 }
1227 return eStateInvalid;
1228}
1229
1230void
1231ProcessGDBRemote::RefreshStateAfterStop ()
1232{
Jim Ingham7508e732010-08-09 23:31:02 +00001233 // FIXME - add a variable to tell that we're in the middle of attaching if we
1234 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001235 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001236// if (!GetTarget().GetArchitecture().IsValid())
1237// {
1238// Module *exe_module = GetTarget().GetExecutableModule().get();
1239// if (exe_module)
1240// m_arch_spec = exe_module->GetArchitecture();
1241// }
1242
Chris Lattner24943d22010-06-08 16:52:24 +00001243 // Let all threads recover from stopping and do any clean up based
1244 // on the previous thread state (if any).
1245 m_thread_list.RefreshStateAfterStop();
1246
1247 // Discover new threads:
1248 UpdateThreadListIfNeeded ();
1249}
1250
1251Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001252ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001253{
1254 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001255
Greg Claytona4881d02011-01-22 07:12:45 +00001256 bool timed_out = false;
1257 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001258
1259 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001260 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001261 // We are being asked to halt during an attach. We need to just close
1262 // our file handle and debugserver will go away, and we can be done...
1263 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001264 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001265 else
1266 {
1267 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1268 {
1269 if (timed_out)
1270 error.SetErrorString("timed out sending interrupt packet");
1271 else
1272 error.SetErrorString("unknown error sending interrupt packet");
1273 }
1274 }
Chris Lattner24943d22010-06-08 16:52:24 +00001275 return error;
1276}
1277
1278Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001279ProcessGDBRemote::InterruptIfRunning
1280(
1281 bool discard_thread_plans,
1282 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001283 EventSP &stop_event_sp
1284)
Chris Lattner24943d22010-06-08 16:52:24 +00001285{
1286 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001287
Greg Clayton2860ba92011-01-23 19:58:49 +00001288 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1289
Greg Clayton68ca8232011-01-25 02:58:48 +00001290 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001291 const bool is_running = m_gdb_comm.IsRunning();
1292 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001293 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001294 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001295 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001296 is_running);
1297
Greg Clayton2860ba92011-01-23 19:58:49 +00001298 if (discard_thread_plans)
1299 {
1300 if (log)
1301 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1302 m_thread_list.DiscardThreadPlans();
1303 }
1304 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001305 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001306 if (catch_stop_event)
1307 {
1308 if (log)
1309 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1310 PausePrivateStateThread();
1311 paused_private_state_thread = true;
1312 }
1313
Greg Clayton4fb400f2010-09-27 21:07:38 +00001314 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001315 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001316 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001317
Greg Clayton72e1c782011-01-22 23:43:18 +00001318 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001319 {
1320 if (timed_out)
1321 error.SetErrorString("timed out sending interrupt packet");
1322 else
1323 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001324 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001325 ResumePrivateStateThread();
1326 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001327 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001328
Greg Clayton72e1c782011-01-22 23:43:18 +00001329 if (catch_stop_event)
1330 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001331 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001332 TimeValue timeout_time;
1333 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001334 timeout_time.OffsetWithSeconds(5);
1335 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001336
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001337 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001338 if (log)
1339 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001340
Greg Clayton2860ba92011-01-23 19:58:49 +00001341 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001342 error.SetErrorString("unable to verify target stopped");
1343 }
1344
Greg Clayton68ca8232011-01-25 02:58:48 +00001345 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001346 {
1347 if (log)
1348 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001349 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001350 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001351 }
Chris Lattner24943d22010-06-08 16:52:24 +00001352 return error;
1353}
1354
Greg Clayton4fb400f2010-09-27 21:07:38 +00001355Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001356ProcessGDBRemote::WillDetach ()
1357{
Greg Clayton2860ba92011-01-23 19:58:49 +00001358 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1359 if (log)
1360 log->Printf ("ProcessGDBRemote::WillDetach()");
1361
Greg Clayton72e1c782011-01-22 23:43:18 +00001362 bool discard_thread_plans = true;
1363 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001364 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001365 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001366}
1367
1368Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001369ProcessGDBRemote::DoDetach()
1370{
1371 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001372 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001373 if (log)
1374 log->Printf ("ProcessGDBRemote::DoDetach()");
1375
1376 DisableAllBreakpointSites ();
1377
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001378 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001379
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001380 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1381 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001382 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001383 if (response_size)
1384 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1385 else
1386 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001387 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001388 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001389 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001390
Greg Clayton4fb400f2010-09-27 21:07:38 +00001391 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001392 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001393
1394 SetPrivateState (eStateDetached);
1395 ResumePrivateStateThread();
1396
1397 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001398 return error;
1399}
Chris Lattner24943d22010-06-08 16:52:24 +00001400
1401Error
1402ProcessGDBRemote::DoDestroy ()
1403{
1404 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001405 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001406 if (log)
1407 log->Printf ("ProcessGDBRemote::DoDestroy()");
1408
1409 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001410 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001411 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001412 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001413 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001414 // We are being asked to halt during an attach. We need to just close
1415 // our file handle and debugserver will go away, and we can be done...
1416 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001417 }
1418 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001419 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001420
1421 StringExtractorGDBRemote response;
1422 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001423 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001424 {
1425 char packet_cmd = response.GetChar(0);
1426
1427 if (packet_cmd == 'W' || packet_cmd == 'X')
1428 {
1429 m_last_stop_packet = response;
1430 SetExitStatus(response.GetHexU8(), NULL);
1431 }
1432 }
1433 else
1434 {
1435 SetExitStatus(SIGABRT, NULL);
1436 //error.SetErrorString("kill packet failed");
1437 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001438 }
1439 }
Chris Lattner24943d22010-06-08 16:52:24 +00001440 StopAsyncThread ();
1441 m_gdb_comm.StopReadThread();
1442 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001443 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001444 return error;
1445}
1446
Chris Lattner24943d22010-06-08 16:52:24 +00001447//------------------------------------------------------------------
1448// Process Queries
1449//------------------------------------------------------------------
1450
1451bool
1452ProcessGDBRemote::IsAlive ()
1453{
Greg Clayton58e844b2010-12-08 05:08:21 +00001454 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001455}
1456
1457addr_t
1458ProcessGDBRemote::GetImageInfoAddress()
1459{
1460 if (!m_gdb_comm.IsRunning())
1461 {
1462 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001463 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001464 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001465 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001466 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1467 }
1468 }
1469 return LLDB_INVALID_ADDRESS;
1470}
1471
Chris Lattner24943d22010-06-08 16:52:24 +00001472//------------------------------------------------------------------
1473// Process Memory
1474//------------------------------------------------------------------
1475size_t
1476ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1477{
1478 if (size > m_max_memory_size)
1479 {
1480 // Keep memory read sizes down to a sane limit. This function will be
1481 // called multiple times in order to complete the task by
1482 // lldb_private::Process so it is ok to do this.
1483 size = m_max_memory_size;
1484 }
1485
1486 char packet[64];
1487 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1488 assert (packet_len + 1 < sizeof(packet));
1489 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001490 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001491 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001492 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001493 {
1494 error.Clear();
1495 return response.GetHexBytes(buf, size, '\xdd');
1496 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001497 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001498 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001499 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001500 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1501 else
1502 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1503 }
1504 else
1505 {
1506 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1507 }
1508 return 0;
1509}
1510
1511size_t
1512ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1513{
1514 StreamString packet;
1515 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001516 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001517 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001518 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001519 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001520 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001521 {
1522 error.Clear();
1523 return size;
1524 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001525 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001526 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001527 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001528 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1529 else
1530 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1531 }
1532 else
1533 {
1534 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1535 }
1536 return 0;
1537}
1538
1539lldb::addr_t
1540ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1541{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001542 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001543 if (allocated_addr == LLDB_INVALID_ADDRESS)
1544 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1545 else
1546 error.Clear();
1547 return allocated_addr;
1548}
1549
1550Error
1551ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1552{
1553 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001554 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001555 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1556 return error;
1557}
1558
1559
1560//------------------------------------------------------------------
1561// Process STDIO
1562//------------------------------------------------------------------
1563
1564size_t
1565ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1566{
1567 Mutex::Locker locker(m_stdio_mutex);
1568 size_t bytes_available = m_stdout_data.size();
1569 if (bytes_available > 0)
1570 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001571 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1572 if (log)
1573 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001574 if (bytes_available > buf_size)
1575 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001576 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001577 m_stdout_data.erase(0, buf_size);
1578 bytes_available = buf_size;
1579 }
1580 else
1581 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001582 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001583 m_stdout_data.clear();
1584
1585 //ResetEventBits(eBroadcastBitSTDOUT);
1586 }
1587 }
1588 return bytes_available;
1589}
1590
1591size_t
1592ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1593{
1594 // Can we get STDERR through the remote protocol?
1595 return 0;
1596}
1597
1598size_t
1599ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1600{
1601 if (m_stdio_communication.IsConnected())
1602 {
1603 ConnectionStatus status;
1604 m_stdio_communication.Write(src, src_len, status, NULL);
1605 }
1606 return 0;
1607}
1608
1609Error
1610ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1611{
1612 Error error;
1613 assert (bp_site != NULL);
1614
Greg Claytone005f2c2010-11-06 01:53:30 +00001615 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001616 user_id_t site_id = bp_site->GetID();
1617 const addr_t addr = bp_site->GetLoadAddress();
1618 if (log)
1619 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1620
1621 if (bp_site->IsEnabled())
1622 {
1623 if (log)
1624 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1625 return error;
1626 }
1627 else
1628 {
1629 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1630
1631 if (bp_site->HardwarePreferred())
1632 {
1633 // Try and set hardware breakpoint, and if that fails, fall through
1634 // and set a software breakpoint?
1635 }
1636
1637 if (m_z0_supported)
1638 {
1639 char packet[64];
1640 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1641 assert (packet_len + 1 < sizeof(packet));
1642 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001643 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001644 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001645 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001646 {
1647 // Disable z packet support and try again
1648 m_z0_supported = 0;
1649 return EnableBreakpoint (bp_site);
1650 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001651 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001652 {
1653 bp_site->SetEnabled(true);
1654 bp_site->SetType (BreakpointSite::eExternal);
1655 return error;
1656 }
1657 else
1658 {
1659 uint8_t error_byte = response.GetError();
1660 if (error_byte)
1661 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1662 }
1663 }
1664 }
1665 else
1666 {
1667 return EnableSoftwareBreakpoint (bp_site);
1668 }
1669 }
1670
1671 if (log)
1672 {
1673 const char *err_string = error.AsCString();
1674 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1675 bp_site->GetLoadAddress(),
1676 err_string ? err_string : "NULL");
1677 }
1678 // We shouldn't reach here on a successful breakpoint enable...
1679 if (error.Success())
1680 error.SetErrorToGenericError();
1681 return error;
1682}
1683
1684Error
1685ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1686{
1687 Error error;
1688 assert (bp_site != NULL);
1689 addr_t addr = bp_site->GetLoadAddress();
1690 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001691 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001692 if (log)
1693 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1694
1695 if (bp_site->IsEnabled())
1696 {
1697 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1698
1699 if (bp_site->IsHardware())
1700 {
1701 // TODO: disable hardware breakpoint...
1702 }
1703 else
1704 {
1705 if (m_z0_supported)
1706 {
1707 char packet[64];
1708 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1709 assert (packet_len + 1 < sizeof(packet));
1710 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001711 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001712 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001713 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001714 {
1715 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1716 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001717 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001718 {
1719 if (log)
1720 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1721 bp_site->SetEnabled(false);
1722 return error;
1723 }
1724 else
1725 {
1726 uint8_t error_byte = response.GetError();
1727 if (error_byte)
1728 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1729 }
1730 }
1731 }
1732 else
1733 {
1734 return DisableSoftwareBreakpoint (bp_site);
1735 }
1736 }
1737 }
1738 else
1739 {
1740 if (log)
1741 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1742 return error;
1743 }
1744
1745 if (error.Success())
1746 error.SetErrorToGenericError();
1747 return error;
1748}
1749
1750Error
1751ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1752{
1753 Error error;
1754 if (wp)
1755 {
1756 user_id_t watchID = wp->GetID();
1757 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001758 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001759 if (log)
1760 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1761 if (wp->IsEnabled())
1762 {
1763 if (log)
1764 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1765 return error;
1766 }
1767 else
1768 {
1769 // Pass down an appropriate z/Z packet...
1770 error.SetErrorString("watchpoints not supported");
1771 }
1772 }
1773 else
1774 {
1775 error.SetErrorString("Watchpoint location argument was NULL.");
1776 }
1777 if (error.Success())
1778 error.SetErrorToGenericError();
1779 return error;
1780}
1781
1782Error
1783ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1784{
1785 Error error;
1786 if (wp)
1787 {
1788 user_id_t watchID = wp->GetID();
1789
Greg Claytone005f2c2010-11-06 01:53:30 +00001790 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001791
1792 addr_t addr = wp->GetLoadAddress();
1793 if (log)
1794 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1795
1796 if (wp->IsHardware())
1797 {
1798 // Pass down an appropriate z/Z packet...
1799 error.SetErrorString("watchpoints not supported");
1800 }
1801 // TODO: clear software watchpoints if we implement them
1802 }
1803 else
1804 {
1805 error.SetErrorString("Watchpoint location argument was NULL.");
1806 }
1807 if (error.Success())
1808 error.SetErrorToGenericError();
1809 return error;
1810}
1811
1812void
1813ProcessGDBRemote::Clear()
1814{
1815 m_flags = 0;
1816 m_thread_list.Clear();
1817 {
1818 Mutex::Locker locker(m_stdio_mutex);
1819 m_stdout_data.clear();
1820 }
Chris Lattner24943d22010-06-08 16:52:24 +00001821}
1822
1823Error
1824ProcessGDBRemote::DoSignal (int signo)
1825{
1826 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001827 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001828 if (log)
1829 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1830
1831 if (!m_gdb_comm.SendAsyncSignal (signo))
1832 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1833 return error;
1834}
1835
Chris Lattner24943d22010-06-08 16:52:24 +00001836Error
1837ProcessGDBRemote::StartDebugserverProcess
1838(
1839 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1840 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1841 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001842 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 +00001843 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1844 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001845 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001846)
1847{
1848 Error error;
1849 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1850 {
1851 // If we locate debugserver, keep that located version around
1852 static FileSpec g_debugserver_file_spec;
1853
1854 FileSpec debugserver_file_spec;
1855 char debugserver_path[PATH_MAX];
1856
1857 // Always check to see if we have an environment override for the path
1858 // to the debugserver to use and use it if we do.
1859 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1860 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001861 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001862 else
1863 debugserver_file_spec = g_debugserver_file_spec;
1864 bool debugserver_exists = debugserver_file_spec.Exists();
1865 if (!debugserver_exists)
1866 {
1867 // The debugserver binary is in the LLDB.framework/Resources
1868 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001869 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001870 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001871 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001872 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001873 if (debugserver_exists)
1874 {
1875 g_debugserver_file_spec = debugserver_file_spec;
1876 }
1877 else
1878 {
1879 g_debugserver_file_spec.Clear();
1880 debugserver_file_spec.Clear();
1881 }
Chris Lattner24943d22010-06-08 16:52:24 +00001882 }
1883 }
1884
1885 if (debugserver_exists)
1886 {
1887 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1888
1889 m_stdio_communication.Clear();
1890 posix_spawnattr_t attr;
1891
Greg Claytone005f2c2010-11-06 01:53:30 +00001892 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001893
1894 Error local_err; // Errors that don't affect the spawning.
1895 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001896 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1897 __FUNCTION__,
1898 debugserver_path,
1899 inferior_argv,
1900 inferior_envp,
1901 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001902 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1903 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001904 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001905 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001906 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001907
Chris Lattner24943d22010-06-08 16:52:24 +00001908 Args debugserver_args;
1909 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001910
Chris Lattner24943d22010-06-08 16:52:24 +00001911 // Start args with "debugserver /file/path -r --"
1912 debugserver_args.AppendArgument(debugserver_path);
1913 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001914 // use native registers, not the GDB registers
1915 debugserver_args.AppendArgument("--native-regs");
1916 // make debugserver run in its own session so signals generated by
1917 // special terminal key sequences (^C) don't affect debugserver
1918 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001919
Chris Lattner24943d22010-06-08 16:52:24 +00001920 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1921 if (env_debugserver_log_file)
1922 {
1923 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1924 debugserver_args.AppendArgument(arg_cstr);
1925 }
1926
1927 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1928 if (env_debugserver_log_flags)
1929 {
1930 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1931 debugserver_args.AppendArgument(arg_cstr);
1932 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001933// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001934// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001935
1936 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001937 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001938 {
Greg Claytona2f74232011-02-24 22:24:29 +00001939 // Terminate the debugserver args so we can now append the inferior args
1940 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001941
Greg Claytona2f74232011-02-24 22:24:29 +00001942 for (int i = 0; inferior_argv[i] != NULL; ++i)
1943 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001944 }
1945 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1946 {
1947 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1948 debugserver_args.AppendArgument (arg_cstr);
1949 }
1950 else if (attach_name && attach_name[0])
1951 {
1952 if (wait_for_launch)
1953 debugserver_args.AppendArgument ("--waitfor");
1954 else
1955 debugserver_args.AppendArgument ("--attach");
1956 debugserver_args.AppendArgument (attach_name);
1957 }
1958
1959 Error file_actions_err;
1960 posix_spawn_file_actions_t file_actions;
1961#if DONT_CLOSE_DEBUGSERVER_STDIO
1962 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1963#else
1964 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1965 if (file_actions_err.Success())
1966 {
1967 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1968 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1969 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1970 }
1971#endif
1972
1973 if (log)
1974 {
1975 StreamString strm;
1976 debugserver_args.Dump (&strm);
1977 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1978 }
1979
Greg Clayton72e1c782011-01-22 23:43:18 +00001980 error.SetError (::posix_spawnp (&m_debugserver_pid,
1981 debugserver_path,
1982 file_actions_err.Success() ? &file_actions : NULL,
1983 &attr,
1984 debugserver_args.GetArgumentVector(),
1985 (char * const*)inferior_envp),
1986 eErrorTypePOSIX);
1987
Greg Claytone9d0df42010-07-02 01:29:13 +00001988
1989 ::posix_spawnattr_destroy (&attr);
1990
Chris Lattner24943d22010-06-08 16:52:24 +00001991 if (file_actions_err.Success())
1992 ::posix_spawn_file_actions_destroy (&file_actions);
1993
1994 // We have seen some cases where posix_spawnp was returning a valid
1995 // looking pid even when an error was returned, so clear it out
1996 if (error.Fail())
1997 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1998
1999 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002000 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 +00002001
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
2003 else
2004 {
2005 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2006 }
2007
2008 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2009 StartAsyncThread ();
2010 }
2011 return error;
2012}
2013
2014bool
2015ProcessGDBRemote::MonitorDebugserverProcess
2016(
2017 void *callback_baton,
2018 lldb::pid_t debugserver_pid,
2019 int signo, // Zero for no signal
2020 int exit_status // Exit value of process if signal is zero
2021)
2022{
2023 // We pass in the ProcessGDBRemote inferior process it and name it
2024 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2025 // pointer value itself, thus we need the double cast...
2026
2027 // "debugserver_pid" argument passed in is the process ID for
2028 // debugserver that we are tracking...
2029
Greg Clayton75ccf502010-08-21 02:22:51 +00002030 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002031
2032 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2033 if (log)
2034 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2035
Greg Clayton75ccf502010-08-21 02:22:51 +00002036 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002037 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002038 // Sleep for a half a second to make sure our inferior process has
2039 // time to set its exit status before we set it incorrectly when
2040 // both the debugserver and the inferior process shut down.
2041 usleep (500000);
2042 // If our process hasn't yet exited, debugserver might have died.
2043 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002044 const StateType state = process->GetState();
2045
2046 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2047 state != eStateInvalid &&
2048 state != eStateUnloaded &&
2049 state != eStateExited &&
2050 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002051 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002052 char error_str[1024];
2053 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002054 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002055 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2056 if (signal_cstr)
2057 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002058 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002059 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002060 }
2061 else
2062 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002063 ::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 +00002064 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002065
2066 process->SetExitStatus (-1, error_str);
2067 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002068 // Debugserver has exited we need to let our ProcessGDBRemote
2069 // know that it no longer has a debugserver instance
2070 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2071 // We are returning true to this function below, so we can
2072 // forget about the monitor handle.
2073 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002074 }
2075 return true;
2076}
2077
2078void
2079ProcessGDBRemote::KillDebugserverProcess ()
2080{
2081 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2082 {
2083 ::kill (m_debugserver_pid, SIGINT);
2084 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2085 }
2086}
2087
2088void
2089ProcessGDBRemote::Initialize()
2090{
2091 static bool g_initialized = false;
2092
2093 if (g_initialized == false)
2094 {
2095 g_initialized = true;
2096 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2097 GetPluginDescriptionStatic(),
2098 CreateInstance);
2099
2100 Log::Callbacks log_callbacks = {
2101 ProcessGDBRemoteLog::DisableLog,
2102 ProcessGDBRemoteLog::EnableLog,
2103 ProcessGDBRemoteLog::ListLogCategories
2104 };
2105
2106 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2107 }
2108}
2109
2110bool
2111ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2112{
2113 if (m_curr_tid == tid)
2114 return true;
2115
2116 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002117 int packet_len;
2118 if (tid <= 0)
2119 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2120 else
2121 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002122 assert (packet_len + 1 < sizeof(packet));
2123 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002124 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002125 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002126 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002127 {
2128 m_curr_tid = tid;
2129 return true;
2130 }
2131 }
2132 return false;
2133}
2134
2135bool
2136ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2137{
2138 if (m_curr_tid_run == tid)
2139 return true;
2140
2141 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002142 int packet_len;
2143 if (tid <= 0)
2144 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2145 else
2146 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2147
Chris Lattner24943d22010-06-08 16:52:24 +00002148 assert (packet_len + 1 < sizeof(packet));
2149 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002150 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002151 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002152 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002153 {
2154 m_curr_tid_run = tid;
2155 return true;
2156 }
2157 }
2158 return false;
2159}
2160
2161void
2162ProcessGDBRemote::ResetGDBRemoteState ()
2163{
2164 // Reset and GDB remote state
2165 m_curr_tid = LLDB_INVALID_THREAD_ID;
2166 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2167 m_z0_supported = 1;
2168}
2169
2170
2171bool
2172ProcessGDBRemote::StartAsyncThread ()
2173{
2174 ResetGDBRemoteState ();
2175
Greg Claytone005f2c2010-11-06 01:53:30 +00002176 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002177
2178 if (log)
2179 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2180
2181 // Create a thread that watches our internal state and controls which
2182 // events make it to clients (into the DCProcess event queue).
2183 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002184 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002185}
2186
2187void
2188ProcessGDBRemote::StopAsyncThread ()
2189{
Greg Claytone005f2c2010-11-06 01:53:30 +00002190 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002191
2192 if (log)
2193 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2194
2195 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2196
2197 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002198 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002199 {
2200 Host::ThreadJoin (m_async_thread, NULL, NULL);
2201 }
2202}
2203
2204
2205void *
2206ProcessGDBRemote::AsyncThread (void *arg)
2207{
2208 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2209
Greg Claytone005f2c2010-11-06 01:53:30 +00002210 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002211 if (log)
2212 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2213
2214 Listener listener ("ProcessGDBRemote::AsyncThread");
2215 EventSP event_sp;
2216 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2217 eBroadcastBitAsyncThreadShouldExit;
2218
2219 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2220 {
Greg Claytona2f74232011-02-24 22:24:29 +00002221 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2222
Chris Lattner24943d22010-06-08 16:52:24 +00002223 bool done = false;
2224 while (!done)
2225 {
2226 if (log)
2227 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2228 if (listener.WaitForEvent (NULL, event_sp))
2229 {
2230 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002231 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002232 {
Greg Claytona2f74232011-02-24 22:24:29 +00002233 if (log)
2234 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 +00002235
Greg Claytona2f74232011-02-24 22:24:29 +00002236 switch (event_type)
2237 {
2238 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002239 {
Greg Claytona2f74232011-02-24 22:24:29 +00002240 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002241
Greg Claytona2f74232011-02-24 22:24:29 +00002242 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002243 {
Greg Claytona2f74232011-02-24 22:24:29 +00002244 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2245 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2246 if (log)
2247 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002248
Greg Claytona2f74232011-02-24 22:24:29 +00002249 if (::strstr (continue_cstr, "vAttach") == NULL)
2250 process->SetPrivateState(eStateRunning);
2251 StringExtractorGDBRemote response;
2252 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002253
Greg Claytona2f74232011-02-24 22:24:29 +00002254 switch (stop_state)
2255 {
2256 case eStateStopped:
2257 case eStateCrashed:
2258 case eStateSuspended:
2259 process->m_last_stop_packet = response;
2260 process->m_last_stop_packet.SetFilePos (0);
2261 process->SetPrivateState (stop_state);
2262 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002263
Greg Claytona2f74232011-02-24 22:24:29 +00002264 case eStateExited:
2265 process->m_last_stop_packet = response;
2266 process->m_last_stop_packet.SetFilePos (0);
2267 response.SetFilePos(1);
2268 process->SetExitStatus(response.GetHexU8(), NULL);
2269 done = true;
2270 break;
2271
2272 case eStateInvalid:
2273 process->SetExitStatus(-1, "lost connection");
2274 break;
2275
2276 default:
2277 process->SetPrivateState (stop_state);
2278 break;
2279 }
Chris Lattner24943d22010-06-08 16:52:24 +00002280 }
2281 }
Greg Claytona2f74232011-02-24 22:24:29 +00002282 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002283
Greg Claytona2f74232011-02-24 22:24:29 +00002284 case eBroadcastBitAsyncThreadShouldExit:
2285 if (log)
2286 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2287 done = true;
2288 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002289
Greg Claytona2f74232011-02-24 22:24:29 +00002290 default:
2291 if (log)
2292 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2293 done = true;
2294 break;
2295 }
2296 }
2297 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2298 {
2299 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2300 {
2301 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002302 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002303 }
Chris Lattner24943d22010-06-08 16:52:24 +00002304 }
2305 }
2306 else
2307 {
2308 if (log)
2309 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2310 done = true;
2311 }
2312 }
2313 }
2314
2315 if (log)
2316 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2317
2318 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2319 return NULL;
2320}
2321
Chris Lattner24943d22010-06-08 16:52:24 +00002322const char *
2323ProcessGDBRemote::GetDispatchQueueNameForThread
2324(
2325 addr_t thread_dispatch_qaddr,
2326 std::string &dispatch_queue_name
2327)
2328{
2329 dispatch_queue_name.clear();
2330 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2331 {
2332 // Cache the dispatch_queue_offsets_addr value so we don't always have
2333 // to look it up
2334 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2335 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002336 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2337 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002338 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002339 if (module_sp)
2340 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2341
2342 if (dispatch_queue_offsets_symbol == NULL)
2343 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002344 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002345 if (module_sp)
2346 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2347 }
Chris Lattner24943d22010-06-08 16:52:24 +00002348 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002349 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002350
2351 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2352 return NULL;
2353 }
2354
2355 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002356 DataExtractor data (memory_buffer,
2357 sizeof(memory_buffer),
2358 m_target.GetArchitecture().GetByteOrder(),
2359 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002360
2361 // Excerpt from src/queue_private.h
2362 struct dispatch_queue_offsets_s
2363 {
2364 uint16_t dqo_version;
2365 uint16_t dqo_label;
2366 uint16_t dqo_label_size;
2367 } dispatch_queue_offsets;
2368
2369
2370 Error error;
2371 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2372 {
2373 uint32_t data_offset = 0;
2374 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2375 {
2376 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2377 {
2378 data_offset = 0;
2379 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2380 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2381 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2382 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2383 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2384 dispatch_queue_name.erase (bytes_read);
2385 }
2386 }
2387 }
2388 }
2389 if (dispatch_queue_name.empty())
2390 return NULL;
2391 return dispatch_queue_name.c_str();
2392}
2393
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002394//uint32_t
2395//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2396//{
2397// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2398// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2399// if (m_local_debugserver)
2400// {
2401// return Host::ListProcessesMatchingName (name, matches, pids);
2402// }
2403// else
2404// {
2405// // FIXME: Implement talking to the remote debugserver.
2406// return 0;
2407// }
2408//
2409//}
2410//
Jim Ingham55e01d82011-01-22 01:33:44 +00002411bool
2412ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2413 lldb_private::StoppointCallbackContext *context,
2414 lldb::user_id_t break_id,
2415 lldb::user_id_t break_loc_id)
2416{
2417 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2418 // run so I can stop it if that's what I want to do.
2419 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2420 if (log)
2421 log->Printf("Hit New Thread Notification breakpoint.");
2422 return false;
2423}
2424
2425
2426bool
2427ProcessGDBRemote::StartNoticingNewThreads()
2428{
2429 static const char *bp_names[] =
2430 {
2431 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002432 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002433 "_pthread_start",
2434 NULL
2435 };
2436
2437 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2438 size_t num_bps = m_thread_observation_bps.size();
2439 if (num_bps != 0)
2440 {
2441 for (int i = 0; i < num_bps; i++)
2442 {
2443 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2444 if (break_sp)
2445 {
2446 if (log)
2447 log->Printf("Enabled noticing new thread breakpoint.");
2448 break_sp->SetEnabled(true);
2449 }
2450 }
2451 }
2452 else
2453 {
2454 for (int i = 0; bp_names[i] != NULL; i++)
2455 {
2456 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2457 if (breakpoint)
2458 {
2459 if (log)
2460 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2461 m_thread_observation_bps.push_back(breakpoint->GetID());
2462 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2463 }
2464 else
2465 {
2466 if (log)
2467 log->Printf("Failed to create new thread notification breakpoint.");
2468 return false;
2469 }
2470 }
2471 }
2472
2473 return true;
2474}
2475
2476bool
2477ProcessGDBRemote::StopNoticingNewThreads()
2478{
Jim Inghamff276fe2011-02-08 05:19:01 +00002479 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2480 if (log)
2481 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002482 size_t num_bps = m_thread_observation_bps.size();
2483 if (num_bps != 0)
2484 {
2485 for (int i = 0; i < num_bps; i++)
2486 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002487
2488 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2489 if (break_sp)
2490 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002491 break_sp->SetEnabled(false);
2492 }
2493 }
2494 }
2495 return true;
2496}
2497
2498