blob: 987f24637d22a0919b1ee05535ba9aa654fa408a [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000016#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000017
18// C++ Includes
19#include <algorithm>
20#include <map>
21
22// Other libraries and framework includes
23
24#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000025#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Core/ArchSpec.h"
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000029#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/InputReader.h"
31#include "lldb/Core/Module.h"
32#include "lldb/Core/PluginManager.h"
33#include "lldb/Core/State.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Timer.h"
36#include "lldb/Host/TimeValue.h"
37#include "lldb/Symbol/ObjectFile.h"
38#include "lldb/Target/DynamicLoader.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000041#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042
43// Project includes
44#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000045#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "GDBRemoteRegisterContext.h"
47#include "ProcessGDBRemote.h"
48#include "ProcessGDBRemoteLog.h"
49#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000050#include "StopInfoMachException.h"
51
Chris Lattner24943d22010-06-08 16:52:24 +000052
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#define DEBUGSERVER_BASENAME "debugserver"
55using namespace lldb;
56using namespace lldb_private;
57
Jim Inghamf9600482011-03-29 21:45:47 +000058static bool rand_initialized = false;
59
Chris Lattner24943d22010-06-08 16:52:24 +000060static inline uint16_t
61get_random_port ()
62{
Jim Inghamf9600482011-03-29 21:45:47 +000063 if (!rand_initialized)
64 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000065 time_t seed = time(NULL);
66
Jim Inghamf9600482011-03-29 21:45:47 +000067 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000068 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000069 }
Stephen Wilson50daf772011-03-25 18:16:28 +000070 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000071}
72
73
74const char *
75ProcessGDBRemote::GetPluginNameStatic()
76{
Greg Claytonb1888f22011-03-19 01:12:21 +000077 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000078}
79
80const char *
81ProcessGDBRemote::GetPluginDescriptionStatic()
82{
83 return "GDB Remote protocol based debugging plug-in.";
84}
85
86void
87ProcessGDBRemote::Terminate()
88{
89 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
90}
91
92
93Process*
94ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
95{
96 return new ProcessGDBRemote (target, listener);
97}
98
99bool
100ProcessGDBRemote::CanDebug(Target &target)
101{
102 // For now we are just making sure the file exists for a given module
103 ModuleSP exe_module_sp(target.GetExecutableModule());
104 if (exe_module_sp.get())
105 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000106 // However, if there is no executable module, we return true since we might be preparing to attach.
107 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000108}
109
110//----------------------------------------------------------------------
111// ProcessGDBRemote constructor
112//----------------------------------------------------------------------
113ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
114 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000117 m_gdb_comm(),
118 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000119 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000120 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
123 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_curr_tid (LLDB_INVALID_THREAD_ID),
125 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_z0_supported (1),
Greg Claytonc1f45872011-02-12 06:28:37 +0000127 m_continue_c_tids (),
128 m_continue_C_tids (),
129 m_continue_s_tids (),
130 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000131 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000132 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000133 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000134 m_local_debugserver (true),
135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
137}
138
139//----------------------------------------------------------------------
140// Destructor
141//----------------------------------------------------------------------
142ProcessGDBRemote::~ProcessGDBRemote()
143{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000144 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000145 {
146 Host::ThreadCancel (m_debugserver_thread, NULL);
147 thread_result_t thread_result;
148 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
149 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
150 }
Chris Lattner24943d22010-06-08 16:52:24 +0000151 // m_mach_process.UnregisterNotificationCallbacks (this);
152 Clear();
153}
154
155//----------------------------------------------------------------------
156// PluginInterface
157//----------------------------------------------------------------------
158const char *
159ProcessGDBRemote::GetPluginName()
160{
161 return "Process debugging plug-in that uses the GDB remote protocol";
162}
163
164const char *
165ProcessGDBRemote::GetShortPluginName()
166{
167 return GetPluginNameStatic();
168}
169
170uint32_t
171ProcessGDBRemote::GetPluginVersion()
172{
173 return 1;
174}
175
176void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000177ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000178{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179 if (!force && m_register_info.GetNumRegisters() > 0)
180 return;
181
182 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000183 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000184 uint32_t reg_offset = 0;
185 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000186 StringExtractorGDBRemote::ResponseType response_type;
187 for (response_type = StringExtractorGDBRemote::eResponse;
188 response_type == StringExtractorGDBRemote::eResponse;
189 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000190 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000191 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
192 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000193 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000194 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000195 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000196 response_type = response.GetResponseType();
197 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000198 {
199 std::string name;
200 std::string value;
201 ConstString reg_name;
202 ConstString alt_name;
203 ConstString set_name;
204 RegisterInfo reg_info = { NULL, // Name
205 NULL, // Alt name
206 0, // byte size
207 reg_offset, // offset
208 eEncodingUint, // encoding
209 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000210 {
211 LLDB_INVALID_REGNUM, // GCC reg num
212 LLDB_INVALID_REGNUM, // DWARF reg num
213 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000214 reg_num, // GDB reg num
215 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000216 }
217 };
218
219 while (response.GetNameColonValue(name, value))
220 {
221 if (name.compare("name") == 0)
222 {
223 reg_name.SetCString(value.c_str());
224 }
225 else if (name.compare("alt-name") == 0)
226 {
227 alt_name.SetCString(value.c_str());
228 }
229 else if (name.compare("bitsize") == 0)
230 {
231 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
232 }
233 else if (name.compare("offset") == 0)
234 {
235 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000236 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000237 {
238 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000239 }
240 }
241 else if (name.compare("encoding") == 0)
242 {
243 if (value.compare("uint") == 0)
244 reg_info.encoding = eEncodingUint;
245 else if (value.compare("sint") == 0)
246 reg_info.encoding = eEncodingSint;
247 else if (value.compare("ieee754") == 0)
248 reg_info.encoding = eEncodingIEEE754;
249 else if (value.compare("vector") == 0)
250 reg_info.encoding = eEncodingVector;
251 }
252 else if (name.compare("format") == 0)
253 {
254 if (value.compare("binary") == 0)
255 reg_info.format = eFormatBinary;
256 else if (value.compare("decimal") == 0)
257 reg_info.format = eFormatDecimal;
258 else if (value.compare("hex") == 0)
259 reg_info.format = eFormatHex;
260 else if (value.compare("float") == 0)
261 reg_info.format = eFormatFloat;
262 else if (value.compare("vector-sint8") == 0)
263 reg_info.format = eFormatVectorOfSInt8;
264 else if (value.compare("vector-uint8") == 0)
265 reg_info.format = eFormatVectorOfUInt8;
266 else if (value.compare("vector-sint16") == 0)
267 reg_info.format = eFormatVectorOfSInt16;
268 else if (value.compare("vector-uint16") == 0)
269 reg_info.format = eFormatVectorOfUInt16;
270 else if (value.compare("vector-sint32") == 0)
271 reg_info.format = eFormatVectorOfSInt32;
272 else if (value.compare("vector-uint32") == 0)
273 reg_info.format = eFormatVectorOfUInt32;
274 else if (value.compare("vector-float32") == 0)
275 reg_info.format = eFormatVectorOfFloat32;
276 else if (value.compare("vector-uint128") == 0)
277 reg_info.format = eFormatVectorOfUInt128;
278 }
279 else if (name.compare("set") == 0)
280 {
281 set_name.SetCString(value.c_str());
282 }
283 else if (name.compare("gcc") == 0)
284 {
285 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
286 }
287 else if (name.compare("dwarf") == 0)
288 {
289 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("generic") == 0)
292 {
293 if (value.compare("pc") == 0)
294 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
295 else if (value.compare("sp") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
297 else if (value.compare("fp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
299 else if (value.compare("ra") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
301 else if (value.compare("flags") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
303 }
304 }
305
Jason Molenda53d96862010-06-11 23:44:18 +0000306 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000307 assert (reg_info.byte_size != 0);
308 reg_offset += reg_info.byte_size;
309 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
310 }
311 }
312 else
313 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000314 response_type = StringExtractorGDBRemote::eError;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 }
316 }
317
318 if (reg_num == 0)
319 {
320 // We didn't get anything. See if we are debugging ARM and fill with
321 // a hard coded register set until we can get an updated debugserver
322 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000323 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000324 m_register_info.HardcodeARMRegisters();
325 }
326 m_register_info.Finalize ();
327}
328
329Error
330ProcessGDBRemote::WillLaunch (Module* module)
331{
332 return WillLaunchOrAttach ();
333}
334
335Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000336ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000337{
338 return WillLaunchOrAttach ();
339}
340
341Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000342ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000343{
344 return WillLaunchOrAttach ();
345}
346
347Error
Greg Claytone71e2582011-02-04 01:58:07 +0000348ProcessGDBRemote::DoConnectRemote (const char *remote_url)
349{
350 Error error (WillLaunchOrAttach ());
351
352 if (error.Fail())
353 return error;
354
355 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
356 {
357 error = ConnectToDebugserver (remote_url);
358 }
359 else
360 {
361 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
362 }
363
364 if (error.Fail())
365 return error;
366 StartAsyncThread ();
367
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000368 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000369 if (pid == LLDB_INVALID_PROCESS_ID)
370 {
371 // We don't have a valid process ID, so note that we are connected
372 // and could now request to launch or attach, or get remote process
373 // listings...
374 SetPrivateState (eStateConnected);
375 }
376 else
377 {
378 // We have a valid process
379 SetID (pid);
380 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000381 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000382 {
383 const StateType state = SetThreadStopInfo (response);
384 if (state == eStateStopped)
385 {
386 SetPrivateState (state);
387 }
388 else
389 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
390 }
391 else
392 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
393 }
394 return error;
395}
396
397Error
Chris Lattner24943d22010-06-08 16:52:24 +0000398ProcessGDBRemote::WillLaunchOrAttach ()
399{
400 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000401 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000402 return error;
403}
404
405//----------------------------------------------------------------------
406// Process Control
407//----------------------------------------------------------------------
408Error
409ProcessGDBRemote::DoLaunch
410(
411 Module* module,
412 char const *argv[],
413 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000414 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000415 const char *stdin_path,
416 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000417 const char *stderr_path,
418 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000419)
420{
Greg Clayton4b407112010-09-30 21:49:03 +0000421 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000422 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
423 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
424 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000425
426 ObjectFile * object_file = module->GetObjectFile();
427 if (object_file)
428 {
429 ArchSpec inferior_arch(module->GetArchitecture());
430 char host_port[128];
431 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000432 char connect_url[128];
433 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000434
Greg Claytona2f74232011-02-24 22:24:29 +0000435 // Make sure we aren't already connected?
436 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000437 {
438 error = StartDebugserverProcess (host_port,
439 NULL,
440 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000441 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000442 NULL,
443 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000444 inferior_arch);
445 if (error.Fail())
446 return error;
447
Greg Claytone71e2582011-02-04 01:58:07 +0000448 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000449 }
450
451 if (error.Success())
452 {
453 lldb_utility::PseudoTerminal pty;
454 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000455
456 // If the debugserver is local and we aren't disabling STDIO, lets use
457 // a pseudo terminal to instead of relying on the 'O' packets for stdio
458 // since 'O' packets can really slow down debugging if the inferior
459 // does a lot of output.
460 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000461 {
462 const char *slave_name = NULL;
463 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000464 {
Greg Claytona2f74232011-02-24 22:24:29 +0000465 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
466 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000467 }
Greg Claytona2f74232011-02-24 22:24:29 +0000468 if (stdin_path == NULL)
469 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000470
Greg Claytona2f74232011-02-24 22:24:29 +0000471 if (stdout_path == NULL)
472 stdout_path = slave_name;
473
474 if (stderr_path == NULL)
475 stderr_path = slave_name;
476 }
477
Greg Claytonafb81862011-03-02 21:34:46 +0000478 // Set STDIN to /dev/null if we want STDIO disabled or if either
479 // STDOUT or STDERR have been set to something and STDIN hasn't
480 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000481 stdin_path = "/dev/null";
482
Greg Claytonafb81862011-03-02 21:34:46 +0000483 // Set STDOUT to /dev/null if we want STDIO disabled or if either
484 // STDIN or STDERR have been set to something and STDOUT hasn't
485 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000486 stdout_path = "/dev/null";
487
Greg Claytonafb81862011-03-02 21:34:46 +0000488 // Set STDERR to /dev/null if we want STDIO disabled or if either
489 // STDIN or STDOUT have been set to something and STDERR hasn't
490 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000491 stderr_path = "/dev/null";
492
493 if (stdin_path)
494 m_gdb_comm.SetSTDIN (stdin_path);
495 if (stdout_path)
496 m_gdb_comm.SetSTDOUT (stdout_path);
497 if (stderr_path)
498 m_gdb_comm.SetSTDERR (stderr_path);
499
500 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
501
502
503 if (working_dir && working_dir[0])
504 {
505 m_gdb_comm.SetWorkingDir (working_dir);
506 }
507
508 // Send the environment and the program + arguments after we connect
509 if (envp)
510 {
511 const char *env_entry;
512 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000513 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000514 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000515 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000516 }
Greg Claytona2f74232011-02-24 22:24:29 +0000517 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000518
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000519 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
520 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
521 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000522 if (arg_packet_err == 0)
523 {
524 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000525 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000526 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000527 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000528 }
529 else
530 {
Greg Claytona2f74232011-02-24 22:24:29 +0000531 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000532 }
Greg Claytona2f74232011-02-24 22:24:29 +0000533 }
534 else
535 {
536 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
537 }
Chris Lattner24943d22010-06-08 16:52:24 +0000538
Greg Claytona2f74232011-02-24 22:24:29 +0000539 if (GetID() == LLDB_INVALID_PROCESS_ID)
540 {
541 KillDebugserverProcess ();
542 return error;
543 }
544
545 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000546 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000547 {
548 SetPrivateState (SetThreadStopInfo (response));
549
550 if (!disable_stdio)
551 {
552 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
553 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
554 }
Chris Lattner24943d22010-06-08 16:52:24 +0000555 }
556 }
Chris Lattner24943d22010-06-08 16:52:24 +0000557 }
558 else
559 {
560 // Set our user ID to an invalid process ID.
561 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000562 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
563 module->GetFileSpec().GetFilename().AsCString(),
564 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000565 }
Chris Lattner24943d22010-06-08 16:52:24 +0000566 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000567
Chris Lattner24943d22010-06-08 16:52:24 +0000568}
569
570
571Error
Greg Claytone71e2582011-02-04 01:58:07 +0000572ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000573{
574 Error error;
575 // Sleep and wait a bit for debugserver to start to listen...
576 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
577 if (conn_ap.get())
578 {
Chris Lattner24943d22010-06-08 16:52:24 +0000579 const uint32_t max_retry_count = 50;
580 uint32_t retry_count = 0;
581 while (!m_gdb_comm.IsConnected())
582 {
Greg Claytone71e2582011-02-04 01:58:07 +0000583 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000584 {
585 m_gdb_comm.SetConnection (conn_ap.release());
586 break;
587 }
588 retry_count++;
589
590 if (retry_count >= max_retry_count)
591 break;
592
593 usleep (100000);
594 }
595 }
596
597 if (!m_gdb_comm.IsConnected())
598 {
599 if (error.Success())
600 error.SetErrorString("not connected to remote gdb server");
601 return error;
602 }
603
Chris Lattner24943d22010-06-08 16:52:24 +0000604 if (m_gdb_comm.StartReadThread(&error))
605 {
606 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000607 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000608
609 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000610 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
611 this,
612 m_debugserver_pid,
613 false);
614
Greg Claytonc1f45872011-02-12 06:28:37 +0000615 m_gdb_comm.ResetDiscoverableSettings();
616 m_gdb_comm.GetSendAcks ();
617 m_gdb_comm.GetThreadSuffixSupported ();
618 m_gdb_comm.GetHostInfo ();
619 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000620 }
621 return error;
622}
623
624void
625ProcessGDBRemote::DidLaunchOrAttach ()
626{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000627 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
628 if (log)
629 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000630 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000631 {
632 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
633
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000634 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000635
Greg Clayton20d338f2010-11-18 05:57:03 +0000636
Chris Lattner24943d22010-06-08 16:52:24 +0000637 StreamString strm;
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000640
Greg Claytoncb8977d2011-03-23 00:09:55 +0000641 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
642 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000643 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000644 ArchSpec &target_arch = GetTarget().GetArchitecture();
645
646 if (target_arch.IsValid())
647 {
648 // If the remote host is ARM and we have apple as the vendor, then
649 // ARM executables and shared libraries can have mixed ARM architectures.
650 // You can have an armv6 executable, and if the host is armv7, then the
651 // system will load the best possible architecture for all shared libraries
652 // it has, so we really need to take the remote host architecture as our
653 // defacto architecture in this case.
654
655 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
656 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
657 {
658 target_arch = gdb_remote_arch;
659 }
660 else
661 {
662 // Fill in what is missing in the triple
663 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
664 llvm::Triple &target_triple = target_arch.GetTriple();
665 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
666 target_triple.setVendor (remote_triple.getVendor());
667
668 if (target_triple.getOS() == llvm::Triple::UnknownOS)
669 target_triple.setOS (remote_triple.getOS());
670
671 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
672 target_triple.setEnvironment (remote_triple.getEnvironment());
673 }
674 }
675 else
676 {
677 // The target doesn't have a valid architecture yet, set it from
678 // the architecture we got from the remote GDB server
679 target_arch = gdb_remote_arch;
680 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000681 }
Chris Lattner24943d22010-06-08 16:52:24 +0000682 }
683}
684
685void
686ProcessGDBRemote::DidLaunch ()
687{
688 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000689}
690
691Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000692ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000693{
694 Error error;
695 // Clear out and clean up from any current state
696 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000697 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000698
Chris Lattner24943d22010-06-08 16:52:24 +0000699 if (attach_pid != LLDB_INVALID_PROCESS_ID)
700 {
Greg Claytona2f74232011-02-24 22:24:29 +0000701 // Make sure we aren't already connected?
702 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000703 {
Greg Claytona2f74232011-02-24 22:24:29 +0000704 char host_port[128];
705 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
706 char connect_url[128];
707 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000708
Greg Claytona2f74232011-02-24 22:24:29 +0000709 error = StartDebugserverProcess (host_port, // debugserver_url
710 NULL, // inferior_argv
711 NULL, // inferior_envp
712 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
713 NULL, // Don't send any attach by process name option to debugserver
714 false, // Don't send any attach wait_for_launch flag as an option to debugserver
715 arch_spec);
716
717 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000718 {
Greg Claytona2f74232011-02-24 22:24:29 +0000719 const char *error_string = error.AsCString();
720 if (error_string == NULL)
721 error_string = "unable to launch " DEBUGSERVER_BASENAME;
722
723 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000724 }
Greg Claytona2f74232011-02-24 22:24:29 +0000725 else
726 {
727 error = ConnectToDebugserver (connect_url);
728 }
729 }
730
731 if (error.Success())
732 {
733 char packet[64];
734 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
735
736 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000737 }
738 }
Chris Lattner24943d22010-06-08 16:52:24 +0000739 return error;
740}
741
742size_t
743ProcessGDBRemote::AttachInputReaderCallback
744(
745 void *baton,
746 InputReader *reader,
747 lldb::InputReaderAction notification,
748 const char *bytes,
749 size_t bytes_len
750)
751{
752 if (notification == eInputReaderGotToken)
753 {
754 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
755 if (gdb_process->m_waiting_for_attach)
756 gdb_process->m_waiting_for_attach = false;
757 reader->SetIsDone(true);
758 return 1;
759 }
760 return 0;
761}
762
763Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000764ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000765{
766 Error error;
767 // Clear out and clean up from any current state
768 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000769
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (process_name && process_name[0])
771 {
Greg Claytona2f74232011-02-24 22:24:29 +0000772 // Make sure we aren't already connected?
773 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000774 {
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Greg Claytona2f74232011-02-24 22:24:29 +0000776 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
777
778 char host_port[128];
779 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
780 char connect_url[128];
781 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
782
783 error = StartDebugserverProcess (host_port, // debugserver_url
784 NULL, // inferior_argv
785 NULL, // inferior_envp
786 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
787 NULL, // Don't send any attach by process name option to debugserver
788 false, // Don't send any attach wait_for_launch flag as an option to debugserver
789 arch_spec);
790 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000791 {
Greg Claytona2f74232011-02-24 22:24:29 +0000792 const char *error_string = error.AsCString();
793 if (error_string == NULL)
794 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000795
Greg Claytona2f74232011-02-24 22:24:29 +0000796 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000797 }
Greg Claytona2f74232011-02-24 22:24:29 +0000798 else
799 {
800 error = ConnectToDebugserver (connect_url);
801 }
802 }
803
804 if (error.Success())
805 {
806 StreamString packet;
807
808 if (wait_for_launch)
809 packet.PutCString("vAttachWait");
810 else
811 packet.PutCString("vAttachName");
812 packet.PutChar(';');
813 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
814
815 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
816
Chris Lattner24943d22010-06-08 16:52:24 +0000817 }
818 }
Chris Lattner24943d22010-06-08 16:52:24 +0000819 return error;
820}
821
Chris Lattner24943d22010-06-08 16:52:24 +0000822
823void
824ProcessGDBRemote::DidAttach ()
825{
Greg Claytone71e2582011-02-04 01:58:07 +0000826 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000827}
828
829Error
830ProcessGDBRemote::WillResume ()
831{
Greg Claytonc1f45872011-02-12 06:28:37 +0000832 m_continue_c_tids.clear();
833 m_continue_C_tids.clear();
834 m_continue_s_tids.clear();
835 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000836 return Error();
837}
838
839Error
840ProcessGDBRemote::DoResume ()
841{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000842 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000843 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
844 if (log)
845 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000846
847 Listener listener ("gdb-remote.resume-packet-sent");
848 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
849 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000850 StreamString continue_packet;
851 bool continue_packet_error = false;
852 if (m_gdb_comm.HasAnyVContSupport ())
853 {
854 continue_packet.PutCString ("vCont");
855
856 if (!m_continue_c_tids.empty())
857 {
858 if (m_gdb_comm.GetVContSupported ('c'))
859 {
860 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)
861 continue_packet.Printf(";c:%4.4x", *t_pos);
862 }
863 else
864 continue_packet_error = true;
865 }
866
867 if (!continue_packet_error && !m_continue_C_tids.empty())
868 {
869 if (m_gdb_comm.GetVContSupported ('C'))
870 {
871 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)
872 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
873 }
874 else
875 continue_packet_error = true;
876 }
Greg Claytonb749a262010-12-03 06:02:24 +0000877
Greg Claytonc1f45872011-02-12 06:28:37 +0000878 if (!continue_packet_error && !m_continue_s_tids.empty())
879 {
880 if (m_gdb_comm.GetVContSupported ('s'))
881 {
882 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)
883 continue_packet.Printf(";s:%4.4x", *t_pos);
884 }
885 else
886 continue_packet_error = true;
887 }
888
889 if (!continue_packet_error && !m_continue_S_tids.empty())
890 {
891 if (m_gdb_comm.GetVContSupported ('S'))
892 {
893 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)
894 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
895 }
896 else
897 continue_packet_error = true;
898 }
899
900 if (continue_packet_error)
901 continue_packet.GetString().clear();
902 }
903 else
904 continue_packet_error = true;
905
906 if (continue_packet_error)
907 {
908 continue_packet_error = false;
909 // Either no vCont support, or we tried to use part of the vCont
910 // packet that wasn't supported by the remote GDB server.
911 // We need to try and make a simple packet that can do our continue
912 const size_t num_threads = GetThreadList().GetSize();
913 const size_t num_continue_c_tids = m_continue_c_tids.size();
914 const size_t num_continue_C_tids = m_continue_C_tids.size();
915 const size_t num_continue_s_tids = m_continue_s_tids.size();
916 const size_t num_continue_S_tids = m_continue_S_tids.size();
917 if (num_continue_c_tids > 0)
918 {
919 if (num_continue_c_tids == num_threads)
920 {
921 // All threads are resuming...
922 SetCurrentGDBRemoteThreadForRun (-1);
923 continue_packet.PutChar ('c');
924 }
925 else if (num_continue_c_tids == 1 &&
926 num_continue_C_tids == 0 &&
927 num_continue_s_tids == 0 &&
928 num_continue_S_tids == 0 )
929 {
930 // Only one thread is continuing
931 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
932 continue_packet.PutChar ('c');
933 }
934 else
935 {
936 // We can't represent this continue packet....
937 continue_packet_error = true;
938 }
939 }
940
941 if (!continue_packet_error && num_continue_C_tids > 0)
942 {
943 if (num_continue_C_tids == num_threads)
944 {
945 const int continue_signo = m_continue_C_tids.front().second;
946 if (num_continue_C_tids > 1)
947 {
948 for (size_t i=1; i<num_threads; ++i)
949 {
950 if (m_continue_C_tids[i].second != continue_signo)
951 continue_packet_error = true;
952 }
953 }
954 if (!continue_packet_error)
955 {
956 // Add threads continuing with the same signo...
957 SetCurrentGDBRemoteThreadForRun (-1);
958 continue_packet.Printf("C%2.2x", continue_signo);
959 }
960 }
961 else if (num_continue_c_tids == 0 &&
962 num_continue_C_tids == 1 &&
963 num_continue_s_tids == 0 &&
964 num_continue_S_tids == 0 )
965 {
966 // Only one thread is continuing with signal
967 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
968 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
969 }
970 else
971 {
972 // We can't represent this continue packet....
973 continue_packet_error = true;
974 }
975 }
976
977 if (!continue_packet_error && num_continue_s_tids > 0)
978 {
979 if (num_continue_s_tids == num_threads)
980 {
981 // All threads are resuming...
982 SetCurrentGDBRemoteThreadForRun (-1);
983 continue_packet.PutChar ('s');
984 }
985 else if (num_continue_c_tids == 0 &&
986 num_continue_C_tids == 0 &&
987 num_continue_s_tids == 1 &&
988 num_continue_S_tids == 0 )
989 {
990 // Only one thread is stepping
991 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
992 continue_packet.PutChar ('s');
993 }
994 else
995 {
996 // We can't represent this continue packet....
997 continue_packet_error = true;
998 }
999 }
1000
1001 if (!continue_packet_error && num_continue_S_tids > 0)
1002 {
1003 if (num_continue_S_tids == num_threads)
1004 {
1005 const int step_signo = m_continue_S_tids.front().second;
1006 // Are all threads trying to step with the same signal?
1007 if (num_continue_S_tids > 1)
1008 {
1009 for (size_t i=1; i<num_threads; ++i)
1010 {
1011 if (m_continue_S_tids[i].second != step_signo)
1012 continue_packet_error = true;
1013 }
1014 }
1015 if (!continue_packet_error)
1016 {
1017 // Add threads stepping with the same signo...
1018 SetCurrentGDBRemoteThreadForRun (-1);
1019 continue_packet.Printf("S%2.2x", step_signo);
1020 }
1021 }
1022 else if (num_continue_c_tids == 0 &&
1023 num_continue_C_tids == 0 &&
1024 num_continue_s_tids == 0 &&
1025 num_continue_S_tids == 1 )
1026 {
1027 // Only one thread is stepping with signal
1028 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1029 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1030 }
1031 else
1032 {
1033 // We can't represent this continue packet....
1034 continue_packet_error = true;
1035 }
1036 }
1037 }
1038
1039 if (continue_packet_error)
1040 {
1041 error.SetErrorString ("can't make continue packet for this resume");
1042 }
1043 else
1044 {
1045 EventSP event_sp;
1046 TimeValue timeout;
1047 timeout = TimeValue::Now();
1048 timeout.OffsetWithSeconds (5);
1049 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1050
1051 if (listener.WaitForEvent (&timeout, event_sp) == false)
1052 error.SetErrorString("Resume timed out.");
1053 }
Greg Claytonb749a262010-12-03 06:02:24 +00001054 }
1055
Jim Ingham3ae449a2010-11-17 02:32:00 +00001056 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001057}
1058
Chris Lattner24943d22010-06-08 16:52:24 +00001059uint32_t
1060ProcessGDBRemote::UpdateThreadListIfNeeded ()
1061{
1062 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001063 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001064 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001065 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1066
Greg Clayton5205f0b2010-09-03 17:10:42 +00001067 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001068 const uint32_t stop_id = GetStopID();
1069 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1070 {
1071 // Update the thread list's stop id immediately so we don't recurse into this function.
1072 ThreadList curr_thread_list (this);
1073 curr_thread_list.SetStopID(stop_id);
1074
1075 Error err;
1076 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001077 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001078 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001079 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001080 {
1081 char ch = response.GetChar();
1082 if (ch == 'l')
1083 break;
1084 if (ch == 'm')
1085 {
1086 do
1087 {
1088 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1089
1090 if (tid != LLDB_INVALID_THREAD_ID)
1091 {
1092 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001093 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001094 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1095 curr_thread_list.AddThread(thread_sp);
1096 }
1097
1098 ch = response.GetChar();
1099 } while (ch == ',');
1100 }
1101 }
1102
1103 m_thread_list = curr_thread_list;
1104
1105 SetThreadStopInfo (m_last_stop_packet);
1106 }
1107 return GetThreadList().GetSize(false);
1108}
1109
1110
1111StateType
1112ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1113{
1114 const char stop_type = stop_packet.GetChar();
1115 switch (stop_type)
1116 {
1117 case 'T':
1118 case 'S':
1119 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001120 if (GetStopID() == 0)
1121 {
1122 // Our first stop, make sure we have a process ID, and also make
1123 // sure we know about our registers
1124 if (GetID() == LLDB_INVALID_PROCESS_ID)
1125 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001126 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001127 if (pid != LLDB_INVALID_PROCESS_ID)
1128 SetID (pid);
1129 }
1130 BuildDynamicRegisterInfo (true);
1131 }
Chris Lattner24943d22010-06-08 16:52:24 +00001132 // Stop with signal and thread info
1133 const uint8_t signo = stop_packet.GetHexU8();
1134 std::string name;
1135 std::string value;
1136 std::string thread_name;
1137 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001138 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001139 uint32_t tid = LLDB_INVALID_THREAD_ID;
1140 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1141 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001142 ThreadSP thread_sp;
1143
Chris Lattner24943d22010-06-08 16:52:24 +00001144 while (stop_packet.GetNameColonValue(name, value))
1145 {
1146 if (name.compare("metype") == 0)
1147 {
1148 // exception type in big endian hex
1149 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1150 }
1151 else if (name.compare("mecount") == 0)
1152 {
1153 // exception count in big endian hex
1154 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1155 }
1156 else if (name.compare("medata") == 0)
1157 {
1158 // exception data in big endian hex
1159 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1160 }
1161 else if (name.compare("thread") == 0)
1162 {
1163 // thread in big endian hex
1164 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001165 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001166 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001167 if (!thread_sp)
1168 {
1169 // Create the thread if we need to
1170 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1171 m_thread_list.AddThread(thread_sp);
1172 }
Chris Lattner24943d22010-06-08 16:52:24 +00001173 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001174 else if (name.compare("hexname") == 0)
1175 {
1176 StringExtractor name_extractor;
1177 // Swap "value" over into "name_extractor"
1178 name_extractor.GetStringRef().swap(value);
1179 // Now convert the HEX bytes into a string value
1180 name_extractor.GetHexByteString (value);
1181 thread_name.swap (value);
1182 }
Chris Lattner24943d22010-06-08 16:52:24 +00001183 else if (name.compare("name") == 0)
1184 {
1185 thread_name.swap (value);
1186 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001187 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001188 {
1189 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1190 }
Greg Claytona875b642011-01-09 21:07:35 +00001191 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1192 {
1193 // We have a register number that contains an expedited
1194 // register value. Lets supply this register to our thread
1195 // so it won't have to go and read it.
1196 if (thread_sp)
1197 {
1198 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1199
1200 if (reg != UINT32_MAX)
1201 {
1202 StringExtractor reg_value_extractor;
1203 // Swap "value" over into "reg_value_extractor"
1204 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001205 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1206 {
1207 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1208 name.c_str(),
1209 reg,
1210 reg,
1211 reg_value_extractor.GetStringRef().c_str(),
1212 stop_packet.GetStringRef().c_str());
1213 }
Greg Claytona875b642011-01-09 21:07:35 +00001214 }
1215 }
1216 }
Chris Lattner24943d22010-06-08 16:52:24 +00001217 }
Chris Lattner24943d22010-06-08 16:52:24 +00001218
1219 if (thread_sp)
1220 {
1221 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1222
1223 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001224 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001225 if (exc_type != 0)
1226 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001227 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001228
1229 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1230 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001231 exc_data_size,
1232 exc_data_size >= 1 ? exc_data[0] : 0,
1233 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001234 }
1235 else if (signo)
1236 {
Greg Clayton643ee732010-08-04 01:40:35 +00001237 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001238 }
1239 else
1240 {
Greg Clayton643ee732010-08-04 01:40:35 +00001241 StopInfoSP invalid_stop_info_sp;
1242 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001243 }
1244 }
1245 return eStateStopped;
1246 }
1247 break;
1248
1249 case 'W':
1250 // process exited
1251 return eStateExited;
1252
1253 default:
1254 break;
1255 }
1256 return eStateInvalid;
1257}
1258
1259void
1260ProcessGDBRemote::RefreshStateAfterStop ()
1261{
Jim Ingham7508e732010-08-09 23:31:02 +00001262 // FIXME - add a variable to tell that we're in the middle of attaching if we
1263 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001264 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001265// if (!GetTarget().GetArchitecture().IsValid())
1266// {
1267// Module *exe_module = GetTarget().GetExecutableModule().get();
1268// if (exe_module)
1269// m_arch_spec = exe_module->GetArchitecture();
1270// }
1271
Chris Lattner24943d22010-06-08 16:52:24 +00001272 // Let all threads recover from stopping and do any clean up based
1273 // on the previous thread state (if any).
1274 m_thread_list.RefreshStateAfterStop();
1275
1276 // Discover new threads:
1277 UpdateThreadListIfNeeded ();
1278}
1279
1280Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001281ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001282{
1283 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001284
Greg Claytona4881d02011-01-22 07:12:45 +00001285 bool timed_out = false;
1286 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001287
1288 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001289 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001290 // We are being asked to halt during an attach. We need to just close
1291 // our file handle and debugserver will go away, and we can be done...
1292 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001293 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001294 else
1295 {
1296 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1297 {
1298 if (timed_out)
1299 error.SetErrorString("timed out sending interrupt packet");
1300 else
1301 error.SetErrorString("unknown error sending interrupt packet");
1302 }
1303 }
Chris Lattner24943d22010-06-08 16:52:24 +00001304 return error;
1305}
1306
1307Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001308ProcessGDBRemote::InterruptIfRunning
1309(
1310 bool discard_thread_plans,
1311 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001312 EventSP &stop_event_sp
1313)
Chris Lattner24943d22010-06-08 16:52:24 +00001314{
1315 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001316
Greg Clayton2860ba92011-01-23 19:58:49 +00001317 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1318
Greg Clayton68ca8232011-01-25 02:58:48 +00001319 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001320 const bool is_running = m_gdb_comm.IsRunning();
1321 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001322 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001323 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001324 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001325 is_running);
1326
Greg Clayton2860ba92011-01-23 19:58:49 +00001327 if (discard_thread_plans)
1328 {
1329 if (log)
1330 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1331 m_thread_list.DiscardThreadPlans();
1332 }
1333 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001334 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001335 if (catch_stop_event)
1336 {
1337 if (log)
1338 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1339 PausePrivateStateThread();
1340 paused_private_state_thread = true;
1341 }
1342
Greg Clayton4fb400f2010-09-27 21:07:38 +00001343 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001344 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001345 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001346
Greg Clayton72e1c782011-01-22 23:43:18 +00001347 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001348 {
1349 if (timed_out)
1350 error.SetErrorString("timed out sending interrupt packet");
1351 else
1352 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001353 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001354 ResumePrivateStateThread();
1355 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001356 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001357
Greg Clayton72e1c782011-01-22 23:43:18 +00001358 if (catch_stop_event)
1359 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001360 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001361 TimeValue timeout_time;
1362 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001363 timeout_time.OffsetWithSeconds(5);
1364 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001365
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001366 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001367 if (log)
1368 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001369
Greg Clayton2860ba92011-01-23 19:58:49 +00001370 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001371 error.SetErrorString("unable to verify target stopped");
1372 }
1373
Greg Clayton68ca8232011-01-25 02:58:48 +00001374 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001375 {
1376 if (log)
1377 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001378 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001379 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381 return error;
1382}
1383
Greg Clayton4fb400f2010-09-27 21:07:38 +00001384Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001385ProcessGDBRemote::WillDetach ()
1386{
Greg Clayton2860ba92011-01-23 19:58:49 +00001387 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1388 if (log)
1389 log->Printf ("ProcessGDBRemote::WillDetach()");
1390
Greg Clayton72e1c782011-01-22 23:43:18 +00001391 bool discard_thread_plans = true;
1392 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001393 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001394 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001395}
1396
1397Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001398ProcessGDBRemote::DoDetach()
1399{
1400 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001401 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001402 if (log)
1403 log->Printf ("ProcessGDBRemote::DoDetach()");
1404
1405 DisableAllBreakpointSites ();
1406
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001407 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001408
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001409 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1410 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001411 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001412 if (response_size)
1413 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1414 else
1415 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001416 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001417 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001418 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001419
Greg Clayton4fb400f2010-09-27 21:07:38 +00001420 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001421 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001422
1423 SetPrivateState (eStateDetached);
1424 ResumePrivateStateThread();
1425
1426 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001427 return error;
1428}
Chris Lattner24943d22010-06-08 16:52:24 +00001429
1430Error
1431ProcessGDBRemote::DoDestroy ()
1432{
1433 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001434 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001435 if (log)
1436 log->Printf ("ProcessGDBRemote::DoDestroy()");
1437
1438 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001439 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001440 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001441 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001442 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001443 // We are being asked to halt during an attach. We need to just close
1444 // our file handle and debugserver will go away, and we can be done...
1445 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001446 }
1447 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001448 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001449
1450 StringExtractorGDBRemote response;
1451 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001452 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001453 {
1454 char packet_cmd = response.GetChar(0);
1455
1456 if (packet_cmd == 'W' || packet_cmd == 'X')
1457 {
1458 m_last_stop_packet = response;
1459 SetExitStatus(response.GetHexU8(), NULL);
1460 }
1461 }
1462 else
1463 {
1464 SetExitStatus(SIGABRT, NULL);
1465 //error.SetErrorString("kill packet failed");
1466 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001467 }
1468 }
Chris Lattner24943d22010-06-08 16:52:24 +00001469 StopAsyncThread ();
1470 m_gdb_comm.StopReadThread();
1471 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001472 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001473 return error;
1474}
1475
Chris Lattner24943d22010-06-08 16:52:24 +00001476//------------------------------------------------------------------
1477// Process Queries
1478//------------------------------------------------------------------
1479
1480bool
1481ProcessGDBRemote::IsAlive ()
1482{
Greg Clayton58e844b2010-12-08 05:08:21 +00001483 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001484}
1485
1486addr_t
1487ProcessGDBRemote::GetImageInfoAddress()
1488{
1489 if (!m_gdb_comm.IsRunning())
1490 {
1491 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001492 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001493 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001494 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001495 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1496 }
1497 }
1498 return LLDB_INVALID_ADDRESS;
1499}
1500
Chris Lattner24943d22010-06-08 16:52:24 +00001501//------------------------------------------------------------------
1502// Process Memory
1503//------------------------------------------------------------------
1504size_t
1505ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1506{
1507 if (size > m_max_memory_size)
1508 {
1509 // Keep memory read sizes down to a sane limit. This function will be
1510 // called multiple times in order to complete the task by
1511 // lldb_private::Process so it is ok to do this.
1512 size = m_max_memory_size;
1513 }
1514
1515 char packet[64];
1516 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1517 assert (packet_len + 1 < sizeof(packet));
1518 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001519 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001520 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001521 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001522 {
1523 error.Clear();
1524 return response.GetHexBytes(buf, size, '\xdd');
1525 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001526 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001527 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001528 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001529 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1530 else
1531 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1532 }
1533 else
1534 {
1535 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1536 }
1537 return 0;
1538}
1539
1540size_t
1541ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1542{
1543 StreamString packet;
1544 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001545 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001546 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001547 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001548 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001549 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001550 {
1551 error.Clear();
1552 return size;
1553 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001554 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001555 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001556 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001557 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1558 else
1559 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1560 }
1561 else
1562 {
1563 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1564 }
1565 return 0;
1566}
1567
1568lldb::addr_t
1569ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1570{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001571 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001572 if (allocated_addr == LLDB_INVALID_ADDRESS)
1573 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1574 else
1575 error.Clear();
1576 return allocated_addr;
1577}
1578
1579Error
1580ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1581{
1582 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001583 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001584 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1585 return error;
1586}
1587
1588
1589//------------------------------------------------------------------
1590// Process STDIO
1591//------------------------------------------------------------------
1592
1593size_t
1594ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1595{
1596 Mutex::Locker locker(m_stdio_mutex);
1597 size_t bytes_available = m_stdout_data.size();
1598 if (bytes_available > 0)
1599 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001600 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1601 if (log)
1602 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001603 if (bytes_available > buf_size)
1604 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001605 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001606 m_stdout_data.erase(0, buf_size);
1607 bytes_available = buf_size;
1608 }
1609 else
1610 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001611 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001612 m_stdout_data.clear();
1613
1614 //ResetEventBits(eBroadcastBitSTDOUT);
1615 }
1616 }
1617 return bytes_available;
1618}
1619
1620size_t
1621ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1622{
1623 // Can we get STDERR through the remote protocol?
1624 return 0;
1625}
1626
1627size_t
1628ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1629{
1630 if (m_stdio_communication.IsConnected())
1631 {
1632 ConnectionStatus status;
1633 m_stdio_communication.Write(src, src_len, status, NULL);
1634 }
1635 return 0;
1636}
1637
1638Error
1639ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1640{
1641 Error error;
1642 assert (bp_site != NULL);
1643
Greg Claytone005f2c2010-11-06 01:53:30 +00001644 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001645 user_id_t site_id = bp_site->GetID();
1646 const addr_t addr = bp_site->GetLoadAddress();
1647 if (log)
1648 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1649
1650 if (bp_site->IsEnabled())
1651 {
1652 if (log)
1653 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1654 return error;
1655 }
1656 else
1657 {
1658 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1659
1660 if (bp_site->HardwarePreferred())
1661 {
1662 // Try and set hardware breakpoint, and if that fails, fall through
1663 // and set a software breakpoint?
1664 }
1665
1666 if (m_z0_supported)
1667 {
1668 char packet[64];
1669 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1670 assert (packet_len + 1 < sizeof(packet));
1671 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001672 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001673 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001674 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001675 {
1676 // Disable z packet support and try again
1677 m_z0_supported = 0;
1678 return EnableBreakpoint (bp_site);
1679 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001680 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001681 {
1682 bp_site->SetEnabled(true);
1683 bp_site->SetType (BreakpointSite::eExternal);
1684 return error;
1685 }
1686 else
1687 {
1688 uint8_t error_byte = response.GetError();
1689 if (error_byte)
1690 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1691 }
1692 }
1693 }
1694 else
1695 {
1696 return EnableSoftwareBreakpoint (bp_site);
1697 }
1698 }
1699
1700 if (log)
1701 {
1702 const char *err_string = error.AsCString();
1703 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1704 bp_site->GetLoadAddress(),
1705 err_string ? err_string : "NULL");
1706 }
1707 // We shouldn't reach here on a successful breakpoint enable...
1708 if (error.Success())
1709 error.SetErrorToGenericError();
1710 return error;
1711}
1712
1713Error
1714ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1715{
1716 Error error;
1717 assert (bp_site != NULL);
1718 addr_t addr = bp_site->GetLoadAddress();
1719 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001720 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001721 if (log)
1722 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1723
1724 if (bp_site->IsEnabled())
1725 {
1726 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1727
1728 if (bp_site->IsHardware())
1729 {
1730 // TODO: disable hardware breakpoint...
1731 }
1732 else
1733 {
1734 if (m_z0_supported)
1735 {
1736 char packet[64];
1737 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1738 assert (packet_len + 1 < sizeof(packet));
1739 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001740 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001741 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001742 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001743 {
1744 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1745 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001746 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001747 {
1748 if (log)
1749 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1750 bp_site->SetEnabled(false);
1751 return error;
1752 }
1753 else
1754 {
1755 uint8_t error_byte = response.GetError();
1756 if (error_byte)
1757 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1758 }
1759 }
1760 }
1761 else
1762 {
1763 return DisableSoftwareBreakpoint (bp_site);
1764 }
1765 }
1766 }
1767 else
1768 {
1769 if (log)
1770 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1771 return error;
1772 }
1773
1774 if (error.Success())
1775 error.SetErrorToGenericError();
1776 return error;
1777}
1778
1779Error
1780ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1781{
1782 Error error;
1783 if (wp)
1784 {
1785 user_id_t watchID = wp->GetID();
1786 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001788 if (log)
1789 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1790 if (wp->IsEnabled())
1791 {
1792 if (log)
1793 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1794 return error;
1795 }
1796 else
1797 {
1798 // Pass down an appropriate z/Z packet...
1799 error.SetErrorString("watchpoints not supported");
1800 }
1801 }
1802 else
1803 {
1804 error.SetErrorString("Watchpoint location argument was NULL.");
1805 }
1806 if (error.Success())
1807 error.SetErrorToGenericError();
1808 return error;
1809}
1810
1811Error
1812ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1813{
1814 Error error;
1815 if (wp)
1816 {
1817 user_id_t watchID = wp->GetID();
1818
Greg Claytone005f2c2010-11-06 01:53:30 +00001819 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001820
1821 addr_t addr = wp->GetLoadAddress();
1822 if (log)
1823 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1824
1825 if (wp->IsHardware())
1826 {
1827 // Pass down an appropriate z/Z packet...
1828 error.SetErrorString("watchpoints not supported");
1829 }
1830 // TODO: clear software watchpoints if we implement them
1831 }
1832 else
1833 {
1834 error.SetErrorString("Watchpoint location argument was NULL.");
1835 }
1836 if (error.Success())
1837 error.SetErrorToGenericError();
1838 return error;
1839}
1840
1841void
1842ProcessGDBRemote::Clear()
1843{
1844 m_flags = 0;
1845 m_thread_list.Clear();
1846 {
1847 Mutex::Locker locker(m_stdio_mutex);
1848 m_stdout_data.clear();
1849 }
Chris Lattner24943d22010-06-08 16:52:24 +00001850}
1851
1852Error
1853ProcessGDBRemote::DoSignal (int signo)
1854{
1855 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001856 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001857 if (log)
1858 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1859
1860 if (!m_gdb_comm.SendAsyncSignal (signo))
1861 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1862 return error;
1863}
1864
Chris Lattner24943d22010-06-08 16:52:24 +00001865Error
1866ProcessGDBRemote::StartDebugserverProcess
1867(
1868 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1869 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1870 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001871 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 +00001872 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1873 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001874 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001875)
1876{
1877 Error error;
1878 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1879 {
1880 // If we locate debugserver, keep that located version around
1881 static FileSpec g_debugserver_file_spec;
1882
1883 FileSpec debugserver_file_spec;
1884 char debugserver_path[PATH_MAX];
1885
1886 // Always check to see if we have an environment override for the path
1887 // to the debugserver to use and use it if we do.
1888 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1889 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001890 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001891 else
1892 debugserver_file_spec = g_debugserver_file_spec;
1893 bool debugserver_exists = debugserver_file_spec.Exists();
1894 if (!debugserver_exists)
1895 {
1896 // The debugserver binary is in the LLDB.framework/Resources
1897 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001898 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001899 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001900 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001901 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001902 if (debugserver_exists)
1903 {
1904 g_debugserver_file_spec = debugserver_file_spec;
1905 }
1906 else
1907 {
1908 g_debugserver_file_spec.Clear();
1909 debugserver_file_spec.Clear();
1910 }
Chris Lattner24943d22010-06-08 16:52:24 +00001911 }
1912 }
1913
1914 if (debugserver_exists)
1915 {
1916 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1917
1918 m_stdio_communication.Clear();
1919 posix_spawnattr_t attr;
1920
Greg Claytone005f2c2010-11-06 01:53:30 +00001921 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001922
1923 Error local_err; // Errors that don't affect the spawning.
1924 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001925 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1926 __FUNCTION__,
1927 debugserver_path,
1928 inferior_argv,
1929 inferior_envp,
1930 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001931 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1932 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001933 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001934 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001935 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001936
Chris Lattner24943d22010-06-08 16:52:24 +00001937 Args debugserver_args;
1938 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001939
Chris Lattner24943d22010-06-08 16:52:24 +00001940 // Start args with "debugserver /file/path -r --"
1941 debugserver_args.AppendArgument(debugserver_path);
1942 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001943 // use native registers, not the GDB registers
1944 debugserver_args.AppendArgument("--native-regs");
1945 // make debugserver run in its own session so signals generated by
1946 // special terminal key sequences (^C) don't affect debugserver
1947 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001948
Chris Lattner24943d22010-06-08 16:52:24 +00001949 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1950 if (env_debugserver_log_file)
1951 {
1952 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1953 debugserver_args.AppendArgument(arg_cstr);
1954 }
1955
1956 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1957 if (env_debugserver_log_flags)
1958 {
1959 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1960 debugserver_args.AppendArgument(arg_cstr);
1961 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001962// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001963// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001964
1965 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001966 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001967 {
Greg Claytona2f74232011-02-24 22:24:29 +00001968 // Terminate the debugserver args so we can now append the inferior args
1969 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001970
Greg Claytona2f74232011-02-24 22:24:29 +00001971 for (int i = 0; inferior_argv[i] != NULL; ++i)
1972 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001973 }
1974 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1975 {
1976 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1977 debugserver_args.AppendArgument (arg_cstr);
1978 }
1979 else if (attach_name && attach_name[0])
1980 {
1981 if (wait_for_launch)
1982 debugserver_args.AppendArgument ("--waitfor");
1983 else
1984 debugserver_args.AppendArgument ("--attach");
1985 debugserver_args.AppendArgument (attach_name);
1986 }
1987
1988 Error file_actions_err;
1989 posix_spawn_file_actions_t file_actions;
1990#if DONT_CLOSE_DEBUGSERVER_STDIO
1991 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1992#else
1993 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1994 if (file_actions_err.Success())
1995 {
1996 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1997 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1998 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1999 }
2000#endif
2001
2002 if (log)
2003 {
2004 StreamString strm;
2005 debugserver_args.Dump (&strm);
2006 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2007 }
2008
Greg Clayton72e1c782011-01-22 23:43:18 +00002009 error.SetError (::posix_spawnp (&m_debugserver_pid,
2010 debugserver_path,
2011 file_actions_err.Success() ? &file_actions : NULL,
2012 &attr,
2013 debugserver_args.GetArgumentVector(),
2014 (char * const*)inferior_envp),
2015 eErrorTypePOSIX);
2016
Greg Claytone9d0df42010-07-02 01:29:13 +00002017
2018 ::posix_spawnattr_destroy (&attr);
2019
Chris Lattner24943d22010-06-08 16:52:24 +00002020 if (file_actions_err.Success())
2021 ::posix_spawn_file_actions_destroy (&file_actions);
2022
2023 // We have seen some cases where posix_spawnp was returning a valid
2024 // looking pid even when an error was returned, so clear it out
2025 if (error.Fail())
2026 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2027
2028 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002029 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 +00002030
Chris Lattner24943d22010-06-08 16:52:24 +00002031 }
2032 else
2033 {
2034 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2035 }
2036
2037 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2038 StartAsyncThread ();
2039 }
2040 return error;
2041}
2042
2043bool
2044ProcessGDBRemote::MonitorDebugserverProcess
2045(
2046 void *callback_baton,
2047 lldb::pid_t debugserver_pid,
2048 int signo, // Zero for no signal
2049 int exit_status // Exit value of process if signal is zero
2050)
2051{
2052 // We pass in the ProcessGDBRemote inferior process it and name it
2053 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2054 // pointer value itself, thus we need the double cast...
2055
2056 // "debugserver_pid" argument passed in is the process ID for
2057 // debugserver that we are tracking...
2058
Greg Clayton75ccf502010-08-21 02:22:51 +00002059 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002060
2061 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2062 if (log)
2063 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2064
Greg Clayton75ccf502010-08-21 02:22:51 +00002065 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002066 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002067 // Sleep for a half a second to make sure our inferior process has
2068 // time to set its exit status before we set it incorrectly when
2069 // both the debugserver and the inferior process shut down.
2070 usleep (500000);
2071 // If our process hasn't yet exited, debugserver might have died.
2072 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002073 const StateType state = process->GetState();
2074
2075 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2076 state != eStateInvalid &&
2077 state != eStateUnloaded &&
2078 state != eStateExited &&
2079 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002080 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002081 char error_str[1024];
2082 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002083 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002084 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2085 if (signal_cstr)
2086 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002087 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002088 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002089 }
2090 else
2091 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002092 ::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 +00002093 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002094
2095 process->SetExitStatus (-1, error_str);
2096 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002097 // Debugserver has exited we need to let our ProcessGDBRemote
2098 // know that it no longer has a debugserver instance
2099 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2100 // We are returning true to this function below, so we can
2101 // forget about the monitor handle.
2102 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002103 }
2104 return true;
2105}
2106
2107void
2108ProcessGDBRemote::KillDebugserverProcess ()
2109{
2110 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2111 {
2112 ::kill (m_debugserver_pid, SIGINT);
2113 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2114 }
2115}
2116
2117void
2118ProcessGDBRemote::Initialize()
2119{
2120 static bool g_initialized = false;
2121
2122 if (g_initialized == false)
2123 {
2124 g_initialized = true;
2125 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2126 GetPluginDescriptionStatic(),
2127 CreateInstance);
2128
2129 Log::Callbacks log_callbacks = {
2130 ProcessGDBRemoteLog::DisableLog,
2131 ProcessGDBRemoteLog::EnableLog,
2132 ProcessGDBRemoteLog::ListLogCategories
2133 };
2134
2135 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2136 }
2137}
2138
2139bool
2140ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2141{
2142 if (m_curr_tid == tid)
2143 return true;
2144
2145 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002146 int packet_len;
2147 if (tid <= 0)
2148 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2149 else
2150 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002151 assert (packet_len + 1 < sizeof(packet));
2152 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002153 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002154 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002155 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002156 {
2157 m_curr_tid = tid;
2158 return true;
2159 }
2160 }
2161 return false;
2162}
2163
2164bool
2165ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2166{
2167 if (m_curr_tid_run == tid)
2168 return true;
2169
2170 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002171 int packet_len;
2172 if (tid <= 0)
2173 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2174 else
2175 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2176
Chris Lattner24943d22010-06-08 16:52:24 +00002177 assert (packet_len + 1 < sizeof(packet));
2178 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002179 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002180 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002181 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002182 {
2183 m_curr_tid_run = tid;
2184 return true;
2185 }
2186 }
2187 return false;
2188}
2189
2190void
2191ProcessGDBRemote::ResetGDBRemoteState ()
2192{
2193 // Reset and GDB remote state
2194 m_curr_tid = LLDB_INVALID_THREAD_ID;
2195 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2196 m_z0_supported = 1;
2197}
2198
2199
2200bool
2201ProcessGDBRemote::StartAsyncThread ()
2202{
2203 ResetGDBRemoteState ();
2204
Greg Claytone005f2c2010-11-06 01:53:30 +00002205 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002206
2207 if (log)
2208 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2209
2210 // Create a thread that watches our internal state and controls which
2211 // events make it to clients (into the DCProcess event queue).
2212 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002213 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002214}
2215
2216void
2217ProcessGDBRemote::StopAsyncThread ()
2218{
Greg Claytone005f2c2010-11-06 01:53:30 +00002219 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002220
2221 if (log)
2222 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2223
2224 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2225
2226 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002227 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002228 {
2229 Host::ThreadJoin (m_async_thread, NULL, NULL);
2230 }
2231}
2232
2233
2234void *
2235ProcessGDBRemote::AsyncThread (void *arg)
2236{
2237 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2238
Greg Claytone005f2c2010-11-06 01:53:30 +00002239 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002240 if (log)
2241 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2242
2243 Listener listener ("ProcessGDBRemote::AsyncThread");
2244 EventSP event_sp;
2245 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2246 eBroadcastBitAsyncThreadShouldExit;
2247
2248 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2249 {
Greg Claytona2f74232011-02-24 22:24:29 +00002250 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2251
Chris Lattner24943d22010-06-08 16:52:24 +00002252 bool done = false;
2253 while (!done)
2254 {
2255 if (log)
2256 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2257 if (listener.WaitForEvent (NULL, event_sp))
2258 {
2259 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002260 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002261 {
Greg Claytona2f74232011-02-24 22:24:29 +00002262 if (log)
2263 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 +00002264
Greg Claytona2f74232011-02-24 22:24:29 +00002265 switch (event_type)
2266 {
2267 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002268 {
Greg Claytona2f74232011-02-24 22:24:29 +00002269 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002270
Greg Claytona2f74232011-02-24 22:24:29 +00002271 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002272 {
Greg Claytona2f74232011-02-24 22:24:29 +00002273 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2274 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2275 if (log)
2276 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002277
Greg Claytona2f74232011-02-24 22:24:29 +00002278 if (::strstr (continue_cstr, "vAttach") == NULL)
2279 process->SetPrivateState(eStateRunning);
2280 StringExtractorGDBRemote response;
2281 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002282
Greg Claytona2f74232011-02-24 22:24:29 +00002283 switch (stop_state)
2284 {
2285 case eStateStopped:
2286 case eStateCrashed:
2287 case eStateSuspended:
2288 process->m_last_stop_packet = response;
2289 process->m_last_stop_packet.SetFilePos (0);
2290 process->SetPrivateState (stop_state);
2291 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002292
Greg Claytona2f74232011-02-24 22:24:29 +00002293 case eStateExited:
2294 process->m_last_stop_packet = response;
2295 process->m_last_stop_packet.SetFilePos (0);
2296 response.SetFilePos(1);
2297 process->SetExitStatus(response.GetHexU8(), NULL);
2298 done = true;
2299 break;
2300
2301 case eStateInvalid:
2302 process->SetExitStatus(-1, "lost connection");
2303 break;
2304
2305 default:
2306 process->SetPrivateState (stop_state);
2307 break;
2308 }
Chris Lattner24943d22010-06-08 16:52:24 +00002309 }
2310 }
Greg Claytona2f74232011-02-24 22:24:29 +00002311 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002312
Greg Claytona2f74232011-02-24 22:24:29 +00002313 case eBroadcastBitAsyncThreadShouldExit:
2314 if (log)
2315 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2316 done = true;
2317 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Claytona2f74232011-02-24 22:24:29 +00002319 default:
2320 if (log)
2321 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2322 done = true;
2323 break;
2324 }
2325 }
2326 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2327 {
2328 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2329 {
2330 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002331 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002332 }
Chris Lattner24943d22010-06-08 16:52:24 +00002333 }
2334 }
2335 else
2336 {
2337 if (log)
2338 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2339 done = true;
2340 }
2341 }
2342 }
2343
2344 if (log)
2345 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2346
2347 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2348 return NULL;
2349}
2350
Chris Lattner24943d22010-06-08 16:52:24 +00002351const char *
2352ProcessGDBRemote::GetDispatchQueueNameForThread
2353(
2354 addr_t thread_dispatch_qaddr,
2355 std::string &dispatch_queue_name
2356)
2357{
2358 dispatch_queue_name.clear();
2359 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2360 {
2361 // Cache the dispatch_queue_offsets_addr value so we don't always have
2362 // to look it up
2363 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2364 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002365 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2366 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002367 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002368 if (module_sp)
2369 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2370
2371 if (dispatch_queue_offsets_symbol == NULL)
2372 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002373 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002374 if (module_sp)
2375 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2376 }
Chris Lattner24943d22010-06-08 16:52:24 +00002377 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002378 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002379
2380 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2381 return NULL;
2382 }
2383
2384 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002385 DataExtractor data (memory_buffer,
2386 sizeof(memory_buffer),
2387 m_target.GetArchitecture().GetByteOrder(),
2388 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002389
2390 // Excerpt from src/queue_private.h
2391 struct dispatch_queue_offsets_s
2392 {
2393 uint16_t dqo_version;
2394 uint16_t dqo_label;
2395 uint16_t dqo_label_size;
2396 } dispatch_queue_offsets;
2397
2398
2399 Error error;
2400 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2401 {
2402 uint32_t data_offset = 0;
2403 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2404 {
2405 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2406 {
2407 data_offset = 0;
2408 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2409 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2410 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2411 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2412 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2413 dispatch_queue_name.erase (bytes_read);
2414 }
2415 }
2416 }
2417 }
2418 if (dispatch_queue_name.empty())
2419 return NULL;
2420 return dispatch_queue_name.c_str();
2421}
2422
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002423//uint32_t
2424//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2425//{
2426// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2427// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2428// if (m_local_debugserver)
2429// {
2430// return Host::ListProcessesMatchingName (name, matches, pids);
2431// }
2432// else
2433// {
2434// // FIXME: Implement talking to the remote debugserver.
2435// return 0;
2436// }
2437//
2438//}
2439//
Jim Ingham55e01d82011-01-22 01:33:44 +00002440bool
2441ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2442 lldb_private::StoppointCallbackContext *context,
2443 lldb::user_id_t break_id,
2444 lldb::user_id_t break_loc_id)
2445{
2446 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2447 // run so I can stop it if that's what I want to do.
2448 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2449 if (log)
2450 log->Printf("Hit New Thread Notification breakpoint.");
2451 return false;
2452}
2453
2454
2455bool
2456ProcessGDBRemote::StartNoticingNewThreads()
2457{
2458 static const char *bp_names[] =
2459 {
2460 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002461 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002462 "_pthread_start",
2463 NULL
2464 };
2465
2466 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2467 size_t num_bps = m_thread_observation_bps.size();
2468 if (num_bps != 0)
2469 {
2470 for (int i = 0; i < num_bps; i++)
2471 {
2472 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2473 if (break_sp)
2474 {
2475 if (log)
2476 log->Printf("Enabled noticing new thread breakpoint.");
2477 break_sp->SetEnabled(true);
2478 }
2479 }
2480 }
2481 else
2482 {
2483 for (int i = 0; bp_names[i] != NULL; i++)
2484 {
2485 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2486 if (breakpoint)
2487 {
2488 if (log)
2489 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2490 m_thread_observation_bps.push_back(breakpoint->GetID());
2491 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2492 }
2493 else
2494 {
2495 if (log)
2496 log->Printf("Failed to create new thread notification breakpoint.");
2497 return false;
2498 }
2499 }
2500 }
2501
2502 return true;
2503}
2504
2505bool
2506ProcessGDBRemote::StopNoticingNewThreads()
2507{
Jim Inghamff276fe2011-02-08 05:19:01 +00002508 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2509 if (log)
2510 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002511 size_t num_bps = m_thread_observation_bps.size();
2512 if (num_bps != 0)
2513 {
2514 for (int i = 0; i < num_bps; i++)
2515 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002516
2517 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2518 if (break_sp)
2519 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002520 break_sp->SetEnabled(false);
2521 }
2522 }
2523 }
2524 return true;
2525}
2526
2527